//! AST for the supported Verilog/SystemVerilog subset. //! //! Nodes that begin a line carry a [`Meta`] with leading comments, an //! optional trailing comment, and a blank-line-before flag so the formatter //! can reproduce vertical structure the way ruff's formatter does. //! //! Spans: a node's `span` is its **code extent** — from the first to the last //! token of the construct itself. Attached comments are *not* part of it and //! carry their own spans on [`Comment`]; attribute instances `(* ... *)` are //! real tokens and *are* inside it. See `docs/features/spans/README.md` for //! which node types carry a span and why the rest do not. use crate::span::TextRange; use crate::token::Comment; #[derive(Debug, Clone, Default)] pub struct Meta { pub leading: Vec, /// The comment written *after* the node and the separator that closes it /// (`,` or `;`), on the same line. Several are merged into one, joined by /// a space; the merged value keeps the first one's position and spans /// from the first byte of the first to the last byte of the last. pub trailing: Option, /// Comments written *between* the node and the separator that follows it /// (`element /* c */,`). They print on the node's side of the separator, /// which is where the source put them — printing them after it moves a /// comment across a token and the safety net rejects the output. Empty /// for a node no separator follows. pub before_sep: Vec, pub blank_before: bool, /// Attribute instances `(* ... *)` that preceded the node, verbatim. pub attrs: Vec, } /// Source text passed through verbatim: a compiler directive or an attribute /// instance. `col` is the 1-based column it started in, which is what lets the /// formatter re-indent continuation lines of a multi-line one without drifting /// further right on every pass. #[derive(Debug, Clone)] pub struct RawText { pub text: String, pub col: u32, /// Byte extent of the passed-through token. pub span: TextRange, } /// A macro invocation standing where a module item or a statement belongs /// (`` `ASSERT_INIT(...) ``, `` `FFARNC(...) ``). Its arguments are token soup /// handed to a preprocessor we do not run, so the whole invocation is kept as /// verbatim source text — same treatment as a compiler directive. #[derive(Debug)] pub struct MacroCall { /// The invocation from the backtick through the closing `)`, verbatim. pub raw: RawText, /// True if a `;` followed it in the source. Both spellings occur in real /// RTL, so the formatter reproduces whichever one was written. pub semi: bool, } #[derive(Debug)] pub struct SourceFile { pub items: Vec, /// Comments at the very end of the file. pub dangling: Vec, /// The whole source text: `0..len`. pub span: TextRange, } #[derive(Debug)] pub struct Item { pub meta: Meta, pub kind: ItemKind, /// Code extent of the item, its `(* ... *)` attributes included. pub span: TextRange, } #[derive(Debug)] pub enum ItemKind { Module(Module), Package { kw: String, name: String, items: Vec, dangling: Vec, /// Label after `endpackage :`. end_label: Option, }, Directive(RawText), /// Macro invocation used as a module item. MacroItem(MacroCall), Import(Vec), Timeunit(String), Typedef(Typedef), ParamDecl(ParamDecl), DataDecl(DataDecl), /// Non-ANSI port declaration at module scope: `input [7:0] data;` PortDecl(PortDecl), ContAssign(ContAssign), /// The body statement carries any `@(...)`/`#delay` timing control. Always { kw: String, stmt: Stmt, }, Initial(Stmt), Final(Stmt), Instantiation(Instantiation), GateInstantiation(GateInstantiation), Genvar(Vec), GenerateRegion { items: Vec, dangling: Vec, }, GenIf(GenIf), GenFor(GenFor), GenCase(GenCase), Function(FunctionDecl), Task(TaskDecl), Defparam(Vec<(Expr, Expr)>), /// Source that could not be parsed as an item, kept verbatim. /// /// Only error-tolerant parsing /// (`vlog_parser::parse_source_tolerant`) ever produces this; the /// strict entry point fails on the first error instead, so the formatter /// never sees one. See `docs/features/error-recovery/README.md`. Error(RawText), } #[derive(Debug)] pub struct Module { pub kw: String, pub name: String, /// One entry per `import` statement written in the header. A header may /// write several (`module m import a::*; import b::t; (...)`), and merging /// them into one statement would replace a `;` with a `,`. pub imports: Vec, /// `None` when the header wrote no `#( ... )` at all; an empty `Some` is a /// written-but-empty `#()`, which must be printed back. pub param_ports: Option>, /// Comments written after the last parameter port and before the `)`. pub param_dangling: Vec, pub ports: PortList, /// Comments written after the last port and before the `)`. pub port_dangling: Vec, pub items: Vec, pub dangling: Vec, pub end_label: Option, } /// One `import` statement in a module header, with the comments written /// around it. A header import is not an [`Item`], so it needs its own place /// to keep them. #[derive(Debug)] pub struct HeaderImport { pub meta: Meta, /// The comma-separated paths of this one statement. pub paths: Vec, } #[derive(Debug)] pub enum PortList { /// No port list at all: `module m;` None, /// Empty parens: `module m();` Empty, /// ANSI-style declarations in the header. Ansi(Vec), /// Non-ANSI: just names in the header, declared in the body. NonAnsi(Vec), } #[derive(Debug)] pub struct NonAnsiPort { pub meta: Meta, pub name: String, /// Code extent of the port name. pub span: TextRange, } #[derive(Debug)] pub struct AnsiPort { pub meta: Meta, pub dir: Option, pub net: Option, pub ty: DataType, pub name: String, pub unpacked: Vec, pub default: Option, /// Code extent of the port declaration. pub span: TextRange, } #[derive(Debug)] pub struct ParamPort { pub meta: Meta, /// `parameter` or `localparam`; empty if omitted (continuation params). pub kw: Option, pub ty: DataType, pub is_type: bool, pub name: String, pub unpacked: Vec, pub default: Option, /// Code extent of the parameter port. pub span: TextRange, } /// A data type: keyword or user-defined name, plus signing and packed dims. /// `name` may be empty for implicit types (`input [7:0] x`). #[derive(Debug, Clone, Default)] pub struct DataType { pub name: String, pub signing: Option, pub packed: Vec, } impl DataType { pub fn is_implicit(&self) -> bool { self.name.is_empty() && self.signing.is_none() && self.packed.is_empty() } } /// A dimension: `[expr]` or `[a:b]`. #[derive(Debug, Clone)] pub struct Dim { pub a: Expr, pub b: Option, /// Code extent including the brackets. pub span: TextRange, } #[derive(Debug)] pub struct Typedef { pub name: String, pub unpacked: Vec, pub kind: TypedefKind, } #[derive(Debug)] pub enum TypedefKind { Alias(DataType), Enum(EnumType), Struct(StructType), } #[derive(Debug)] pub struct EnumType { pub base: Option, pub members: Vec, pub dangling: Vec, } #[derive(Debug)] pub struct EnumMember { pub meta: Meta, pub name: String, pub value: Option, /// Code extent of the member. pub span: TextRange, } #[derive(Debug)] pub struct StructType { /// "struct" or "union" pub kw: String, pub packed: bool, pub signing: Option, pub members: Vec, pub dangling: Vec, } #[derive(Debug)] pub struct StructMember { pub meta: Meta, pub ty: DataType, pub declarators: Vec, /// Code extent of the member, its `;` included. pub span: TextRange, } #[derive(Debug)] pub struct ParamDecl { /// `parameter` or `localparam` pub kw: String, pub ty: DataType, pub declarators: Vec, } #[derive(Debug)] pub struct DataDecl { /// Net type (`wire`, `tri`, ...) if any. pub net: Option, /// Net delay: the `5` in `wire #5 w;` pub delay: Option, /// `var` / `automatic` / `static` / `const` qualifiers, in order. pub qualifiers: Vec, pub ty: DataType, pub declarators: Vec, } #[derive(Debug)] pub struct PortDecl { pub dir: String, pub net: Option, pub ty: DataType, pub declarators: Vec, } #[derive(Debug)] pub struct Declarator { pub meta: Meta, pub name: String, pub unpacked: Vec, /// `=` for variables; net declarations also use this for the initial /// continuous assignment. pub init: Option, /// Code extent of the declarator. pub span: TextRange, } #[derive(Debug)] pub struct ContAssign { /// Delay expression: the `5` in `assign #5 x = y;` pub delay: Option, pub assigns: Vec, } #[derive(Debug)] pub struct AssignPair { pub meta: Meta, pub lhs: Expr, pub rhs: Expr, /// Comments written between the `=` and the right-hand side. Kept here so /// they print on the `=`'s side of the value instead of drifting into it. pub rhs_comments: Vec, /// Code extent of `lhs = rhs`. pub span: TextRange, } #[derive(Debug)] pub enum SensList { /// `@*` or `@(*)`, with any comments written next to the `*` so the /// formatter can print them back in the same place. Star { /// Comments between the `@`/`(` and the `*`. before: Vec, /// Comments between the `*` and the closing `)`. after: Vec, }, List(Vec), } #[derive(Debug)] pub struct SensItem { /// Comments written around this item: `leading` before it (after the `(` /// or the separator), `before_sep` between it and the separator that /// follows — or the closing `)` for the last item. pub meta: Meta, /// The separator written before this item; `None` on the first item. pub sep: Option, pub edge: Option, pub expr: Expr, } /// How two event-list items were separated in the source. Both spellings are /// legal and mean the same thing, but rewriting one as the other changes the /// token stream, so the formatter reproduces whichever was written. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SensSep { /// `@(posedge clk, negedge rst_n)` Comma, /// `@(posedge clk or negedge rst_n)` Or, } #[derive(Debug)] pub struct Instantiation { pub module: String, /// The parameter override list, `None` when the source wrote no `#(...)` /// at all. An empty `Some` is a written-but-empty `#()`, which must be /// printed back: dropping it would lose two tokens. pub params: Option>, pub instances: Vec, } #[derive(Debug)] pub struct Instance { pub meta: Meta, pub name: String, pub dims: Vec, pub conns: Connections, /// Code extent of the instance, its connection list included. pub span: TextRange, } #[derive(Debug)] pub enum Connections { Ordered(Vec), Named(Vec), } #[derive(Debug)] pub struct OrderedConn { pub meta: Meta, pub expr: Option, /// Code extent of the connection; empty for an omitted one. pub span: TextRange, } #[derive(Debug)] pub struct Connection { pub meta: Meta, /// Port/parameter name; `*` for the SystemVerilog `.*` wildcard. pub name: String, /// `None` for `.name` (implicit) and `.*`; `Some` for `.name(expr)`. /// An explicitly empty connection `.name()` is `Some(Expr::Empty)`. pub expr: Option, /// Comments written between the value and the connection's own `)` /// (`.data_i (x /* verilator lint_off */)`). Printed back inside the /// parens: after them they would sit in the enclosing list instead. pub close_comments: Vec, /// Code extent of the connection. pub span: TextRange, } #[derive(Debug)] pub struct GateInstantiation { /// `and`, `or`, `not`, ... pub gate: String, pub delay: Option, pub instances: Vec, } #[derive(Debug)] pub struct GateInstance { pub meta: Meta, pub name: Option, pub args: Vec, /// Code extent of the gate instance. pub span: TextRange, } #[derive(Debug)] pub struct GenIf { pub cond: Expr, pub then: GenBlock, pub els: Option>, /// Code extent of the whole `if`, its `else` branch included. pub span: TextRange, } #[derive(Debug)] pub enum GenElse { /// `else if`: boxed because a `Meta` plus a whole `GenIf` inline makes /// this variant several times the size of `Block`. If(Meta, Box), Block(GenBlock), } #[derive(Debug)] pub struct GenFor { pub init: SimpleAssign, pub init_genvar: bool, pub cond: Expr, pub step: ForStep, pub body: GenBlock, } #[derive(Debug)] pub struct GenCase { pub expr: Expr, pub items: Vec, pub dangling: Vec, } #[derive(Debug)] pub struct GenCaseItem { pub meta: Meta, /// Empty means `default`. Each label carries the comments written around /// it, so a comment between two labels stays between them. pub labels: Vec, pub body: GenBlock, /// Code extent of the case item, its body included. pub span: TextRange, } /// A single generate block: either a labeled/unlabeled begin..end with items, /// or a single item. #[derive(Debug)] pub struct GenBlock { pub label: Option, pub is_block: bool, pub items: Vec, pub dangling: Vec, /// Label after `end :`. pub end_label: Option, /// Code extent of the block or of the single item it holds. pub span: TextRange, } #[derive(Debug)] pub struct FunctionDecl { pub qualifiers: Vec, pub ret: Option, pub name: String, /// False for old-style `function f;` declarations without a port list. pub has_parens: bool, pub args: Vec, pub stmts: Vec, pub dangling: Vec, /// Label after `endfunction :`. pub end_label: Option, } #[derive(Debug)] pub struct TaskDecl { pub qualifiers: Vec, pub name: String, /// False for old-style `task t;` declarations without a port list. pub has_parens: bool, pub args: Vec, pub stmts: Vec, pub dangling: Vec, /// Label after `endtask :`. pub end_label: Option, } #[derive(Debug)] pub struct TfArg { pub meta: Meta, pub dir: Option, pub ty: DataType, pub name: String, pub unpacked: Vec, pub default: Option, /// Code extent of the argument declaration. pub span: TextRange, } #[derive(Debug)] pub struct Stmt { pub meta: Meta, pub kind: StmtKind, /// Code extent of the statement, its `(* ... *)` attributes included. pub span: TextRange, } #[derive(Debug)] pub enum StmtKind { Block { label: Option, stmts: Vec, dangling: Vec, /// Label after `end :`. end_label: Option, }, ForkJoin { label: Option, join_kw: String, stmts: Vec, dangling: Vec, /// Label after `join :` (any join kind). end_label: Option, }, If { qualifier: Option, cond: Expr, then: Box, els: Option>, }, Case { qualifier: Option, kw: String, expr: Expr, items: Vec, dangling: Vec, }, For { init: Vec, cond: Option, 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, }, /// Blocking/nonblocking/compound assignment. Assign { lhs: Expr, op: String, /// Intra-assignment timing control (e.g. `#1`, `@(posedge clk)`). timing: Option, rhs: Expr, }, /// `force`/`release`/`deassign` statements, raw pieces. 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>, }, ExprStmt(Expr), /// `-> event_name;` EventTrigger(Expr), VarDecl(DataDecl), ParamDecl(ParamDecl), /// Old-style task/function port declaration: `input [7:0] a;` PortDecl(PortDecl), Return(Option), Break, Continue, Disable(String), Directive(RawText), /// Macro invocation used as a statement. MacroStmt(MacroCall), /// Immediate assertion: kept simple — `assert (expr) stmt else stmt;` Assert { kw: String, cond: Expr, then: Option>, els: Option>, }, Null, /// Source that could not be parsed as a statement, kept verbatim. /// /// The statement-level twin of [`ItemKind::Error`]: produced only by /// error-tolerant parsing, never seen by the formatter. Error(RawText), } #[derive(Debug)] pub enum TimingControl { /// `#expr` Delay(Expr), /// `@(...)`, `@*` Event(SensList), } #[derive(Debug)] pub struct CaseItem { pub meta: Meta, /// Empty means `default`. Each label carries the comments written around /// it, so a comment between two labels stays between them. pub labels: Vec, pub stmt: Stmt, /// Code extent of the case item, its body included. pub span: TextRange, } #[derive(Debug)] pub struct ForInit { /// Declared type for `for (int i = 0; ...)`. pub ty: Option, pub assign: SimpleAssign, } #[derive(Debug)] pub struct SimpleAssign { pub lhs: Expr, pub op: String, pub rhs: Expr, } #[derive(Debug)] pub enum ForStep { Assign(SimpleAssign), Expr(Expr), } /// An expression: its code extent plus what it is. /// /// The span sits on this wrapper rather than on each [`ExprKind`] variant so /// that "the span of any expression" is one field access no matter which /// variant it is — the same shape [`Item`] and [`Stmt`] already have. #[derive(Debug, Clone)] pub struct Expr { pub kind: ExprKind, /// Code extent of the expression. pub span: TextRange, } #[derive(Debug, Clone)] pub enum ExprKind { Ident(String), Number(String), Str(String), /// Explicitly empty (used for `.port()` connections), carrying any /// comments written between the parens so they stay inside them. Empty(Vec), Unary { op: String, expr: Box, }, Binary { lhs: Box, op: String, rhs: Box, /// Boxed to keep `Expr` small, as for `TernaryComments`. comments: Box, }, Ternary { cond: Box, then: Box, els: Box, /// Boxed to keep `Expr` small: a ternary with comments in it is rare, /// but every `Expr` would otherwise carry four empty vectors. comments: 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, /// Elements carry their comments the way a concatenation's do, so a /// comment inside a replication stays inside it. inner: Vec, }, Paren { inner: Box, /// Comments written just inside the `(`. before: Vec, /// Comments left over just before the `)`. after: Vec, }, /// `ty'(expr)` cast; `ty` kept as raw text. Cast { ty: String, expr: Box, }, /// `'{...}` assignment pattern. AssignPattern(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, }, /// 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, }, } /// Comments written next to a binary operator. Kept per side so neither /// drifts across the operator: `a && // why` and `a // why` + `&& b` are /// different token streams. #[derive(Debug, Clone, Default)] pub struct BinaryComments { /// Between the left operand and the operator. These force the chain to /// break, with the operator starting the new line. pub before: Vec, /// Between the operator and the right operand. These force the chain to /// break, with the right operand starting the new line. pub after: Vec, } /// Comments written inside a `cond ? then : els`, kept per position so the /// formatter prints each back between the same two tokens it was written /// between. Anywhere else they would drift across `?` or `:`. #[derive(Debug, Clone, Default)] pub struct TernaryComments { /// Between the condition and `?`. pub before_question: Vec, /// Between `?` and the then-branch. pub after_question: Vec, /// Between the then-branch and `:`. pub before_colon: Vec, /// Between `:` and the else-branch. pub after_colon: Vec, } impl TernaryComments { /// True when nothing was written inside the `? :` — the common case, laid /// out without any comment handling. pub fn is_empty(&self) -> bool { self.before_question.is_empty() && self.after_question.is_empty() && self.before_colon.is_empty() && self.after_colon.is_empty() } } #[derive(Debug, Clone)] pub struct PatternItem { pub meta: Meta, /// `key: value` (key may be `default`, a type, or an expression). pub key: Option, pub value: Expr, /// Code extent of the pattern element. pub span: TextRange, } /// One element of a bracketed expression list (a concatenation, a call /// argument list, an `inside` set), with the comments written around it. A /// comment on an element is what forces its list to break one per line. #[derive(Debug, Clone)] pub struct ExprItem { pub meta: Meta, pub expr: Expr, /// Code extent of the element. pub span: TextRange, }