From d3d97867918c9b67e5bd1026dab0d758bdeaa5a3 Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Tue, 18 Aug 2026 23:12:01 -0700 Subject: [PATCH] =?UTF-8?q?Initial=20commit:=20vfmt=20=E2=80=94=20ruff-sty?= =?UTF-8?q?le=20Verilog/SystemVerilog=20formatter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workspace with comment-preserving parser (vlog_parser), prettier-style document IR + formatting rules (vlog_formatter), and CLI (vfmt). Includes snapshot/idempotency tests and a TODO backlog of practices adopted from ruff and Verible. Co-Authored-By: Claude Fable 5 --- .gitignore | 1 + Cargo.lock | 22 + Cargo.toml | 11 + README.md | 102 + TODO.md | 213 ++ crates/vfmt/Cargo.toml | 14 + crates/vfmt/src/main.rs | 223 ++ crates/vlog_formatter/Cargo.toml | 9 + crates/vlog_formatter/src/doc.rs | 56 + crates/vlog_formatter/src/format.rs | 1481 +++++++++++++ crates/vlog_formatter/src/lib.rs | 7 + crates/vlog_formatter/src/printer.rs | 202 ++ crates/vlog_formatter/tests/fixtures.rs | 102 + .../vlog_formatter/tests/fixtures/counter.sv | 28 + crates/vlog_formatter/tests/fixtures/fsm.sv | 65 + crates/vlog_formatter/tests/fixtures/legacy.v | 58 + .../tests/fixtures/sv_features.sv | 64 + .../tests/snapshots/counter.sv.formatted | 32 + .../tests/snapshots/fsm.sv.formatted | 63 + .../tests/snapshots/legacy.v.formatted | 60 + .../tests/snapshots/sv_features.sv.formatted | 84 + crates/vlog_parser/Cargo.toml | 8 + crates/vlog_parser/src/ast.rs | 529 +++++ crates/vlog_parser/src/lexer.rs | 659 ++++++ crates/vlog_parser/src/lib.rs | 36 + crates/vlog_parser/src/parser.rs | 1948 +++++++++++++++++ crates/vlog_parser/src/token.rs | 236 ++ 27 files changed, 6313 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.md create mode 100644 TODO.md create mode 100644 crates/vfmt/Cargo.toml create mode 100644 crates/vfmt/src/main.rs create mode 100644 crates/vlog_formatter/Cargo.toml create mode 100644 crates/vlog_formatter/src/doc.rs create mode 100644 crates/vlog_formatter/src/format.rs create mode 100644 crates/vlog_formatter/src/lib.rs create mode 100644 crates/vlog_formatter/src/printer.rs create mode 100644 crates/vlog_formatter/tests/fixtures.rs create mode 100644 crates/vlog_formatter/tests/fixtures/counter.sv create mode 100644 crates/vlog_formatter/tests/fixtures/fsm.sv create mode 100644 crates/vlog_formatter/tests/fixtures/legacy.v create mode 100644 crates/vlog_formatter/tests/fixtures/sv_features.sv create mode 100644 crates/vlog_formatter/tests/snapshots/counter.sv.formatted create mode 100644 crates/vlog_formatter/tests/snapshots/fsm.sv.formatted create mode 100644 crates/vlog_formatter/tests/snapshots/legacy.v.formatted create mode 100644 crates/vlog_formatter/tests/snapshots/sv_features.sv.formatted create mode 100644 crates/vlog_parser/Cargo.toml create mode 100644 crates/vlog_parser/src/ast.rs create mode 100644 crates/vlog_parser/src/lexer.rs create mode 100644 crates/vlog_parser/src/lib.rs create mode 100644 crates/vlog_parser/src/parser.rs create mode 100644 crates/vlog_parser/src/token.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..6e2d030 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,22 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "vfmt" +version = "0.1.0" +dependencies = [ + "vlog_formatter", + "vlog_parser", +] + +[[package]] +name = "vlog_formatter" +version = "0.1.0" +dependencies = [ + "vlog_parser", +] + +[[package]] +name = "vlog_parser" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..510ede5 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,11 @@ +[workspace] +resolver = "2" +members = ["crates/vlog_parser", "crates/vlog_formatter", "crates/vfmt"] + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "MIT" + +[profile.release] +lto = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..cb6fb32 --- /dev/null +++ b/README.md @@ -0,0 +1,102 @@ +# vfmt — a Verilog/SystemVerilog formatter in Rust + +An opinionated, fast formatter for Verilog-2001 and SystemVerilog RTL, built +in the image of [ruff](https://github.com/astral-sh/ruff)'s formatter, with +layout conventions borrowed from +[Verible](https://github.com/chipsalliance/verible)'s `verible-verilog-format`. + +```bash +# format files / directories in place (like `ruff format`) +vfmt rtl/ tb/top_tb.sv + +# check mode for CI (exit 1 if anything would change) +vfmt --check rtl/ + +# pipe through stdin/stdout +cat foo.sv | vfmt - +``` + +## Architecture (the ruff mapping) + +The workspace mirrors ruff's crate layout — a comment-preserving parser, a +generic pretty-printing IR, language formatting rules, and a thin CLI: + +| This repo | ruff equivalent | Role | +|---|---|---| +| `crates/vlog_parser` | `ruff_python_parser` + `ruff_python_ast` | Hand-written lexer and recursive-descent parser producing a comment-preserving AST | +| `crates/vlog_formatter/src/{doc,printer}.rs` | `ruff_formatter` | Wadler/prettier-style document IR (`Text`/`Line`/`Group`/`Indent`) + width-aware printer | +| `crates/vlog_formatter/src/format.rs` | `ruff_python_formatter` | Per-node formatting rules | +| `crates/vfmt` | the `ruff` CLI | File discovery, in-place rewriting, `--check`, stdin mode | + +Key ideas carried over from ruff/prettier: + +- **Trivia attachment.** The lexer runs a second phase that folds comments + into neighboring tokens as *leading*/*trailing* trivia and records blank + lines; the parser then harvests them onto AST nodes (`Meta`). Comments are + never dropped — anything not harvested at a precise location is folded into + the next node's leading comments. +- **Fit-based layout.** Every breakable construct (port lists, connection + lists, expressions, concatenations) is a `Group`: it renders on one line if + it fits within the line limit, otherwise it breaks one-element-per-line. + A comment inside a group forces it to break. +- **Idempotency as a hard invariant.** The test suite formats every fixture + twice and asserts a fixed point. + +## Style + +Defaults follow Verible: **2-space indent**, **100-column lines** (both +configurable via `--indent` / `--line-length`). + +- One port / parameter / connection per line once a header doesn't fit +- Cuddled `begin`/`end` (`end else begin`) +- Tight dimension expressions: `[WIDTH-1:0]`, `[base+:8]` +- Blank lines between items preserved (collapsed to at most one) +- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed + through verbatim + +## Supported syntax + +Basic Verilog-2001 and the common synthesizable SystemVerilog subset: + +- Modules (ANSI and non-ANSI headers), packages, parameter ports, + `import`, `timeunit` +- Net/variable declarations (`wire`/`reg`/`logic`/`int`/... , signing, + packed/unpacked dimensions, net delays), `parameter`/`localparam`, + `genvar`, `defparam` +- `assign` (with delays), `always`/`always_comb`/`always_ff`/`always_latch`, + `initial`/`final` +- Full statement set: `begin/end` (labeled), `if`/`else`, all `case` kinds + with `unique`/`priority`, `for`/`while`/`do`/`repeat`/`forever`/`foreach`, + `fork/join*`, timing controls (`#`, `@`), `wait`, `disable`, `force`/ + `release`, event triggers, immediate assertions, `break`/`continue`/ + `return` +- Module/gate instantiation: named and ordered connections, `.*`, + parameter overrides, instance arrays +- `generate` regions and module-level `if`/`for`/`case` +- Functions and tasks (ANSI and old-style port declarations) +- `typedef` (aliases, `enum`, packed `struct`/`union`) +- Expressions: the full operator precedence table, ternaries, + concatenation/replication, slices (`+:`/`-:`), casts (`int'(x)`), + assignment patterns (`'{...}`), `inside`, hierarchical and package-scoped + names, macro usages in expression position + +Not yet supported (parse errors, roadmap in order): +interfaces/modports, classes/constraints, concurrent assertions +(`assert property`), sequences, `case ... inside`, streaming operators, +DPI, specify blocks, `let`/`checker`. Like ruff, `vfmt` refuses to output +anything for a file it cannot fully parse, so it can never corrupt code. + +## Contributing / workflow + +This is a solo project — committing directly to `master` is allowed and +expected; no PRs or review required. + +## Building + +```bash +cargo build --release # binary at target/release/vfmt +cargo test # unit + snapshot + idempotency tests +``` + +Snapshot tests live in `crates/vlog_formatter/tests/fixtures/`; regenerate +expected outputs with `UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter`. diff --git a/TODO.md b/TODO.md new file mode 100644 index 0000000..04136ba --- /dev/null +++ b/TODO.md @@ -0,0 +1,213 @@ +# TODO — best practices adopted from ruff and Verible + +Curated backlog for vfmt, drawn from `astral-sh/ruff` (architecture, CLI/UX, +fix model) and `chipsalliance/verible` (formatter safety, alignment, +waivers, and especially test methodology). Items reference the current +draft's files. Roughly ordered by priority within each section. + +Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both. + +--- + +## 1. Correctness safety net (highest priority) + +- [ ] **[V] Token-stream equivalence verification.** Verible's formatter + re-lexes its output and asserts it is lexically equivalent to the input + (`verilog_equivalence.cc`); on mismatch it emits the *original* text. + Add `verify_equivalence(input, output)` to `vlog_formatter`: re-lex both + through `vlog_parser::lexer`, compare token kinds + text (whitespace + excluded, comments included). Run it inside `format_source()` on every + call — not just in tests. This turns "the formatter can never corrupt + code" from a test-suite property into a runtime guarantee. +- [ ] **[V] Convergence (idempotency) verification at runtime.** Verible + formats twice and checks a fixed point before writing. Do the same in + `format_source()` (optionally behind `--no-verify` for speed later). + Today idempotency is only asserted in `tests/fixtures.rs`. +- [ ] **[V] Failsafe fallback semantics.** On any internal verification + failure, return the input unchanged *with a diagnostic and nonzero exit*, + never partially formatted output. Parse errors already behave this way + (README notes it); extend the same contract to the two checks above. +- [ ] **[R] Panic containment.** ruff catches panics per-file and reports + them as errors instead of killing the whole run. Wrap per-file work in + `crates/vfmt/src/main.rs` with `std::panic::catch_unwind`. + +## 2. Formatter features + +- [ ] **[V] Format-off fences.** Support `// verilog_format: off` / + `// verilog_format: on` (accept a `vfmt: off/on` alias). Verible + implements this as "emit the original byte range verbatim" — the trivia + in `Meta` already carries comments, so detect fences during formatting in + `format.rs` and splice source text by span. Requires nodes to carry + byte spans (see §5, it's needed for LSP anyway). +- [ ] **[V] Range formatting: `--lines M-N[,M-N...]`.** Format only + constructs intersecting the given line ranges; emit everything else + verbatim. This is what makes adoption in dirty legacy codebases possible + (Verible ships `git-verible-verilog-format.sh` on top of it). Follow-up: + a `vfmt --diff-base ` or contrib script that derives ranges from + `git diff`. +- [ ] **[V] Alignment inference for declaration/port/connection groups.** + Verible's most-loved feature: infer align-vs-flush-left intent from the + original spacing (≥4 excess spaces = author wants alignment), and break + alignment groups at blank lines and standalone comments + (`--alignment_group_boundary`). Start with the three constructs where RTL + culture demands it: port declarations, named connections (`.clk (clk)`), + and localparam/parameter lists. This needs original-spacing info + preserved through the lexer — record "excess spaces before token" as + trivia. +- [ ] **[R] `--diff` mode.** Like `ruff format --diff` / Verible's autofix + `patch` mode: print a unified diff instead of rewriting, for CI logs and + code review. +- [ ] **[R] `--stdin-filename `.** Editors pipe buffer contents via + stdin; the filename is needed for good error messages and (later) + per-directory config resolution. + +## 3. CLI / UX (mostly ruff) + +- [ ] **[R] Config file discovery.** Search upward from each input file for + `vfmt.toml` / `.vfmt.toml` (analog of `ruff.toml` / `pyproject.toml`). + Keys: `line-length`, `indent`, `exclude` globs. CLI flags override file + config. Keep Verible's philosophy of *few* knobs — don't grow a + clang-format-sized option surface. +- [ ] **[R] Parallel file processing.** ruff's speed story is embarrassing + parallelism over files. `main.rs` formats serially; use `rayon` + par_iter over the collected file list (formatting is already pure). +- [ ] **[R] Content-hash cache.** Skip files whose (content hash, config + hash, vfmt version) triple is unchanged, stored in `.vfmt_cache/`. + Do this *after* parallelism; it matters for big monorepo RTL trees. +- [ ] **[R] Respect `.gitignore`** and add `--exclude` globs when walking + directories (`collect_files` in `main.rs` currently walks everything, + including e.g. generated netlists). +- [ ] **[V+R] Exit-code contract doc.** Already ruff-like (0 clean / + 1 would-reformat / 2 error) — document it in README and freeze it; CI + scripts will depend on it. + +## 4. Linter (`vfmt check`) — new crate `vlog_linter` + +Design it ruff-style from day one (shared parse, fix model), with +Verible's rule ergonomics (waivers, configurable rules). + +- [ ] **[R] One parse, two tools.** `vfmt check` and `vfmt format` must + share `vlog_parser` output in a single invocation (`vfmt check --fix + --format` style workflows come free later). +- [ ] **[V+R] Rule trait + registry.** Each rule: stable kebab-case name, + one-line summary, longer doc with style-guide rationale (Verible links + each rule to a style-guide section — do the same), and a + `check(node/token) -> Vec` over syntax tree or token stream. +- [ ] **[V] Diagnostic format `FILE:LINE:COL: message [rule-name]`** plus + **[R]** `--output-format json` for tooling from the start. +- [ ] **[R] Fix applicability model.** ruff distinguishes *safe* vs + *unsafe* fixes (`--fix` vs `--unsafe-fixes`). Adopt it now — retrofitting + safety classification is painful. +- [ ] **[V] Waiver mechanisms:** inline `// vfmt: waive rule-name` (accept + `verilog_lint: waive` for migration), `waive-start`/`waive-stop` ranges, + and external waiver files (`waive --rule=X --line=N --location=glob`) for + code you can't touch. ruff's lesson: also warn about *unused* waivers. +- [ ] **[V] Configurable naming rules via regex** (module/instance/ + parameter/enum naming), with named presets like Verible's + (snake_case, ALL_CAPS, etc.). +- [ ] **[V] `--generate_markdown`-style self-documentation** — generate the + rule reference from the registry so docs can't drift. ruff does the same + for its 900+ rules. +- [ ] Seed rules (all syntactic, all from Verible's default set): + no-tabs, no-trailing-spaces, explicit-parameter-storage-type, + case-missing-default, always-ff-non-blocking / always-comb-blocking, + forbid `wire`-reg mixups in SV files, module-filename match. + +## 5. Testing — adapt Verible's methodology + +Verible's formatter confidence comes from a few complementary layers +(`formatter_test.cc`, component tests, equivalence/convergence checks). +Adapt each: + +- [ ] **[V] Massive text-in/text-out table tests.** Verible's + `formatter_test.cc` is thousands of small `{input, expected}` pairs — the + backbone of the formatter. `small_cases` in + `crates/vlog_formatter/tests/fixtures.rs` is the seed; grow it into a + dedicated `tests/cases/` organized by construct (one file per area: + ports, expressions, case-statements, generate, comments, macros...). + Port cases directly from `formatter_test.cc` where our supported-syntax + overlaps — it encodes years of accumulated edge cases (translate expected + output to our style: 2-space indent matches, wrap style differs). +- [ ] **[V] Run equivalence + convergence on *every* test case**, not just + snapshots — once §1's `verify_equivalence` exists, assert it in the + fixture harness too, so every new case buys three checks for free. +- [ ] **[V] Component-level tests.** Verible tests the pipeline stages + separately (`token-annotator_test.cc`, `tree-unwrapper_test.cc`). Ours: + unit tests for `lexer.rs` trivia attachment (comment → leading/trailing + decisions, blank-line counting), `parser.rs` per-construct parse tests, + and `printer.rs` group-breaking behavior on synthetic docs. +- [ ] **[V] Lint test harness with inline violation markers.** Port the + `LintTestCase` / `RunLintTestCases` idea: test cases embed expected + findings positionally in the source (Verible splices `ExpectedTokenInfo` + fragments inline). A Rust adaptation: annotate with a marker comment or a + `^^^` caret line, e.g. + `assert_lint::("module m;\n\twire x;\n ^ no-tabs\nendmodule")`. + Exact-match: unexpected findings fail the test too. +- [ ] **[V] `RunApplyFixCases` equivalent:** every autofix rule gets + `(input, fixed_output)` pairs, and the fixed output must itself be + lint-clean and formatter-idempotent. +- [ ] **[V] Error-case tests.** Table of inputs that must *fail* to parse + with the expected error position — locks in the failsafe path. +- [ ] **[R] Real-world corpus check (ruff's "ecosystem check").** ruff + CI runs against big OSS codebases and diffs results between commits. Do + the same with permissively-licensed RTL: e.g. lowRISC Ibex, OpenTitan, + PULP cores, picorv32. Script: clone pinned revs, run vfmt over every + `.sv/.v`, report parse-success rate + equivalence/convergence failures; + fail CI on regression. Also the honest tracker for the "not yet + supported" list in README. +- [ ] **[R] Fuzzing.** ruff fuzzes its parser. `cargo-fuzz` targets: + (a) parser must never panic on arbitrary bytes, (b) for inputs that + parse, format must satisfy equivalence + convergence. +- [ ] **[R] Consider `insta`** for the snapshot harness (review workflow + `cargo insta review` beats `UPDATE_SNAPSHOTS=1`), keeping the + idempotency loop from `fixtures.rs`. + +## 6. Foundations for LSP / highlighting / navigation + +Goal: reuse the frontend as a language-server backend (semantic +highlighting, hover, go-to-definition) the way ruff grew `ruff_server` +(and `ty`) on shared crates. Decisions that are cheap now and expensive +later: + +- [ ] **Byte spans on every token and AST node.** Prerequisite for + everything in this section (and for §2 fences/range formatting). + `token.rs` / `ast.rs` should carry `TextRange { start, end }` offsets; + add a line-index utility (ruff's `ruff_source_file`) for offset↔line:col. +- [ ] **Error-tolerant parsing mode.** A formatter may refuse broken input; + an LSP cannot — code is mid-edit most of the time. Add recovery in + `parser.rs`: on statement-level error, record a diagnostic, skip to a + sync token (`;`, `end`, `endmodule`), continue. Formatter keeps requiring + zero errors; the LSP consumes the partial tree. +- [ ] **Keep the CST lossless.** Current design (trivia in `Meta`) is + format-oriented; verify every source byte is reachable from the tree + (tokens + trivia + spans). A `reconstruct(tree) == input` round-trip test + makes losslessness a tested invariant — this is what makes the same tree + serve formatter, linter, and highlighter. If gaps appear, consider a + rowan-style green tree (rust-analyzer / ruff direction) rather than + patching `Meta`. +- [ ] **New crate `vlog_semantic`** (analog of `ruff_python_semantic`): + symbol tables per scope (module/package/function/block/generate), binding + → references. Serves go-to-definition/hover first, then semantic lint + rules (unused-signal, undriven-net) which are the lint rules people + actually want and Verible *can't* do (it's syntax-only — this is the + differentiation opportunity). +- [ ] **New crate `vfmt_server`** (analog of `ruff_server`): LSP over + stdio via `tower-lsp` or `lsp-server`. Order of capabilities: + 1. `textDocument/formatting` + `rangeFormatting` (reuses §2 `--lines`), + 2. publish parse/lint diagnostics, + 3. `semanticTokens` for highlighting (needs only the lexer + spans), + 4. `hover` / `definition` (needs `vlog_semantic`). +- [ ] **Salsa-style incrementality — defer.** ruff's `ruff_db` uses salsa; + don't take that dependency until hover/definition across files exists. + Per-file recompute is fine at Verilog file sizes. + +## 7. Deliberate non-goals (also a best practice) + +- No preprocessor expansion: like Verible, operate on unpreprocessed + source, treat `` `define``/`` `ifdef`` bodies and macro calls as opaque + (current behavior — keep, and document the implications). +- No option explosion: Black/ruff's lesson — every knob halves the value + of a canonical style. Alignment inference (§2) is the culturally + necessary exception. +- No semantic claims in v1 lint rules: syntax-only rules first (Verible's + scope), semantic rules only after `vlog_semantic` exists. diff --git a/crates/vfmt/Cargo.toml b/crates/vfmt/Cargo.toml new file mode 100644 index 0000000..650afac --- /dev/null +++ b/crates/vfmt/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "vfmt" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "A Verilog/SystemVerilog formatter, in the spirit of ruff" + +[[bin]] +name = "vfmt" +path = "src/main.rs" + +[dependencies] +vlog_parser = { path = "../vlog_parser" } +vlog_formatter = { path = "../vlog_formatter" } diff --git a/crates/vfmt/src/main.rs b/crates/vfmt/src/main.rs new file mode 100644 index 0000000..3adaa82 --- /dev/null +++ b/crates/vfmt/src/main.rs @@ -0,0 +1,223 @@ +//! vfmt — a Verilog/SystemVerilog formatter in the spirit of `ruff format`. +//! +//! Usage: +//! vfmt [OPTIONS] ... format files in place +//! vfmt --check ... exit 1 if anything would change +//! vfmt - read stdin, write stdout + +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +use vlog_formatter::{format_source, Config}; + +const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"]; + +struct Options { + check: bool, + stdout: bool, + config: Config, + inputs: Vec, +} + +fn print_help() { + println!( + "vfmt — a Verilog/SystemVerilog formatter + +USAGE: + vfmt [OPTIONS] ... + vfmt - read from stdin, write to stdout + +OPTIONS: + --check don't write; exit 1 if any file would be reformatted + --stdout print formatted output instead of rewriting files + --line-length maximum line length (default 100) + --indent indent width in spaces (default 2) + -h, --help show this help + -V, --version show version" + ); +} + +fn parse_args() -> Result { + 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() { + "--check" => opts.check = true, + "--stdout" => opts.stdout = true, + "--line-length" => { + let v = args.next().ok_or("--line-length requires a value")?; + opts.config.max_width = + v.parse().map_err(|_| format!("invalid line length: {v}"))?; + } + "--indent" => { + let v = args.next().ok_or("--indent requires a value")?; + opts.config.indent_width = + v.parse().map_err(|_| format!("invalid indent: {v}"))?; + } + "-h" | "--help" => { + print_help(); + std::process::exit(0); + } + "-V" | "--version" => { + println!("vfmt {}", env!("CARGO_PKG_VERSION")); + std::process::exit(0); + } + "-" => opts.inputs.push("-".to_string()), + s if s.starts_with('-') => return Err(format!("unknown option: {s}")), + s => opts.inputs.push(s.to_string()), + } + } + if opts.inputs.is_empty() { + return Err("no input files (try `vfmt --help`)".to_string()); + } + Ok(opts) +} + +fn collect_files(input: &str, files: &mut Vec) -> Result<(), String> { + let path = Path::new(input); + if path.is_dir() { + walk_dir(path, files).map_err(|e| format!("{input}: {e}"))?; + } else if path.is_file() { + files.push(path.to_path_buf()); + } else { + return Err(format!("{input}: no such file or directory")); + } + Ok(()) +} + +fn walk_dir(dir: &Path, files: &mut Vec) -> std::io::Result<()> { + let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::>()?; + entries.sort_by_key(|e| e.path()); + for entry in entries { + let path = entry.path(); + if path.is_dir() { + walk_dir(&path, files)?; + } else if let Some(ext) = path.extension().and_then(|e| e.to_str()) { + if EXTENSIONS.contains(&ext) { + files.push(path); + } + } + } + Ok(()) +} + +fn main() -> ExitCode { + let opts = match parse_args() { + Ok(o) => o, + Err(e) => { + eprintln!("error: {e}"); + return ExitCode::from(2); + } + }; + + // stdin mode + if opts.inputs.len() == 1 && opts.inputs[0] == "-" { + let mut src = String::new(); + if let Err(e) = std::io::stdin().read_to_string(&mut src) { + eprintln!("error: reading stdin: {e}"); + return ExitCode::from(2); + } + match format_source(&src, &opts.config) { + Ok(out) => { + print!("{out}"); + ExitCode::SUCCESS + } + Err(e) => { + eprintln!("error: :{e}"); + ExitCode::from(2) + } + } + } else { + let mut files = Vec::new(); + for input in &opts.inputs { + if input == "-" { + eprintln!("error: `-` cannot be combined with file arguments"); + return ExitCode::from(2); + } + if let Err(e) = collect_files(input, &mut files) { + eprintln!("error: {e}"); + return ExitCode::from(2); + } + } + if files.is_empty() { + eprintln!("error: no Verilog files found (extensions: {})", EXTENSIONS.join(", ")); + return ExitCode::from(2); + } + + let mut changed = 0usize; + let mut unchanged = 0usize; + let mut errors = 0usize; + for file in &files { + let src = match std::fs::read_to_string(file) { + Ok(s) => s, + Err(e) => { + eprintln!("error: {}: {e}", file.display()); + errors += 1; + continue; + } + }; + let out = match format_source(&src, &opts.config) { + Ok(o) => o, + Err(e) => { + eprintln!("error: {}:{e}", file.display()); + errors += 1; + continue; + } + }; + if opts.stdout { + print!("{out}"); + continue; + } + if out == src { + unchanged += 1; + continue; + } + changed += 1; + if opts.check { + println!("would reformat: {}", file.display()); + } else if let Err(e) = std::fs::write(file, &out) { + eprintln!("error: {}: {e}", file.display()); + errors += 1; + } + } + + if !opts.stdout { + let verb = if opts.check { "would be reformatted" } else { "reformatted" }; + let mut summary = Vec::new(); + if changed > 0 { + summary.push(format!("{changed} file{} {verb}", plural(changed))); + } + if unchanged > 0 { + summary.push(format!("{unchanged} file{} left unchanged", plural(unchanged))); + } + if errors > 0 { + summary.push(format!("{errors} file{} failed to parse", plural(errors))); + } + if !summary.is_empty() { + eprintln!("{}", summary.join(", ")); + } + } + + if errors > 0 { + ExitCode::from(2) + } else if opts.check && changed > 0 { + ExitCode::from(1) + } else { + ExitCode::SUCCESS + } + } +} + +fn plural(n: usize) -> &'static str { + if n == 1 { + "" + } else { + "s" + } +} diff --git a/crates/vlog_formatter/Cargo.toml b/crates/vlog_formatter/Cargo.toml new file mode 100644 index 0000000..b76d7d8 --- /dev/null +++ b/crates/vlog_formatter/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "vlog_formatter" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Verilog/SystemVerilog formatter engine for vfmt" + +[dependencies] +vlog_parser = { path = "../vlog_parser" } diff --git a/crates/vlog_formatter/src/doc.rs b/crates/vlog_formatter/src/doc.rs new file mode 100644 index 0000000..10c9b80 --- /dev/null +++ b/crates/vlog_formatter/src/doc.rs @@ -0,0 +1,56 @@ +//! Wadler-style document IR, the same core idea as `ruff_formatter` (and +//! prettier): build a tree of texts, line-break opportunities, groups, and +//! indents; the printer then picks flat or broken layouts based on the +//! configured line width. + +#[derive(Debug, Clone)] +pub enum Doc { + /// Verbatim text. Must not contain newlines (use `HardLine`). + Text(String), + /// A space when flat, a newline when the enclosing group breaks. + Line, + /// Nothing when flat, a newline when the enclosing group breaks. + SoftLine, + /// Always a newline. Forces every enclosing group to break. + HardLine, + /// Two newlines (one blank line). + BlankLine, + /// Content that the printer tries to fit on one line; if it does not + /// fit (or contains a hard line), every `Line`/`SoftLine` directly + /// inside becomes a newline. + Group(Vec), + /// Increase indentation for any line breaks inside. + Indent(Vec), + /// Sequence with no other effect. + Concat(Vec), + /// Emitted only when the enclosing group is broken. + IfBreak(String), +} + +pub fn text(s: impl Into) -> Doc { + Doc::Text(s.into()) +} + +pub fn group(docs: Vec) -> Doc { + Doc::Group(docs) +} + +pub fn indent(docs: Vec) -> Doc { + Doc::Indent(docs) +} + +pub fn concat(docs: Vec) -> Doc { + Doc::Concat(docs) +} + +/// Join docs with a separator. +pub fn join(items: Vec, sep: Doc) -> Vec { + let mut out = Vec::new(); + for (i, item) in items.into_iter().enumerate() { + if i > 0 { + out.push(sep.clone()); + } + out.push(item); + } + out +} diff --git a/crates/vlog_formatter/src/format.rs b/crates/vlog_formatter/src/format.rs new file mode 100644 index 0000000..4d0077c --- /dev/null +++ b/crates/vlog_formatter/src/format.rs @@ -0,0 +1,1481 @@ +//! Formatting rules: AST → Doc. +//! +//! Style follows Verible's defaults: 2-space indent, 100-column lines, +//! one-element-per-line port/connection lists when a construct does not fit +//! on a single line, cuddled `begin`/`end`. + +use crate::doc::*; +use crate::printer::Printer; +use vlog_parser::ast::*; +use vlog_parser::token::Comment; + +#[derive(Debug, Clone)] +pub struct Config { + pub max_width: usize, + pub indent_width: usize, +} + +impl Default for Config { + fn default() -> Self { + Config { max_width: 100, indent_width: 2 } + } +} + +pub fn format_source(source: &str, config: &Config) -> Result { + let file = vlog_parser::parse_source(source)?; + let fmt = Fmt { _cfg: config }; + let doc = fmt.file(&file); + let printer = Printer { max_width: config.max_width, indent_width: config.indent_width }; + let mut out = printer.print(&doc); + // Normalize trailing whitespace: exactly one final newline. + while out.ends_with('\n') || out.ends_with(' ') { + out.pop(); + } + out.push('\n'); + Ok(out) +} + +struct Fmt<'a> { + _cfg: &'a Config, +} + +/// A list element ready for comma-list layout. +struct ListItem { + leading: Vec, + doc: Doc, + trailing: Option, + blank_before: bool, +} + +impl ListItem { + fn plain(doc: Doc) -> Self { + ListItem { leading: Vec::new(), doc, trailing: None, blank_before: false } + } + + fn from_meta(meta: &Meta, doc: Doc) -> Self { + ListItem { + leading: meta.leading.clone(), + doc, + trailing: meta.trailing.clone(), + blank_before: meta.blank_before, + } + } +} + +impl<'a> Fmt<'a> { + // ------------------------------------------------------------------ + // Shared helpers + // ------------------------------------------------------------------ + + /// Turn possibly-multi-line raw text (comments, directives) into a Doc. + fn raw_text(&self, s: &str) -> Doc { + let lines: Vec<&str> = s.split('\n').collect(); + if lines.len() == 1 { + return text(s); + } + let mut docs = Vec::new(); + for (i, line) in lines.iter().enumerate() { + if i > 0 { + docs.push(Doc::HardLine); + } + docs.push(text(line.trim_end())); + } + concat(docs) + } + + /// Leading comments (each on its own line) preceding a node. + fn leading(&self, meta: &Meta) -> Vec { + let mut docs = Vec::new(); + for (i, c) in meta.leading.iter().enumerate() { + if i > 0 && c.blank_before { + docs.push(Doc::BlankLine); + } + docs.push(self.raw_text(&c.text)); + docs.push(Doc::HardLine); + } + for attr in &meta.attrs { + docs.push(self.raw_text(attr)); + docs.push(Doc::HardLine); + } + docs + } + + fn trailing(&self, meta: &Meta) -> Vec { + match &meta.trailing { + Some(tr) => vec![text(format!(" {tr}"))], + None => Vec::new(), + } + } + + fn with_meta(&self, meta: &Meta, doc: Doc) -> Doc { + let mut docs = self.leading(meta); + docs.push(doc); + docs.extend(self.trailing(meta)); + concat(docs) + } + + /// Comma-separated list inside `open`/`close`, one per line when broken. + /// `force_break` lays every element on its own line regardless of width. + fn delimited(&self, open: &str, items: Vec, close: &str, force_break: bool) -> Doc { + if items.is_empty() { + return text(format!("{open}{close}")); + } + let mut inner: Vec = vec![if force_break { Doc::HardLine } else { Doc::SoftLine }]; + let last = items.len() - 1; + let mut close_needs_hardline = force_break; + for (i, item) in items.into_iter().enumerate() { + if i > 0 { + // separator emitted below along with the previous trailing + } + let meta = Meta { + leading: item.leading, + trailing: None, + blank_before: false, + attrs: Vec::new(), + }; + inner.extend(self.leading(&meta)); + inner.push(item.doc); + if i < last { + inner.push(text(",")); + } + if let Some(tr) = item.trailing { + inner.push(text(format!(" {tr}"))); + if i < last { + inner.push(Doc::HardLine); + } else { + close_needs_hardline = true; + } + } else if i < last { + inner.push(Doc::Line); + } + } + // Peek at blank_before flags is handled by leading comments already; + // blank lines inside bracketed lists are dropped deliberately. + let mut docs = vec![text(open), indent(inner)]; + docs.push(if close_needs_hardline { Doc::HardLine } else { Doc::SoftLine }); + docs.push(text(close)); + group(docs) + } + + /// `( expr )` with break opportunity inside. + fn parens(&self, e: &Expr) -> Doc { + group(vec![ + text("("), + indent(vec![Doc::SoftLine, self.expr(e)]), + Doc::SoftLine, + text(")"), + ]) + } + + /// Sequence of items/statements at one indent level, preserving single + /// blank lines between them. + fn item_seq(&self, items: &[Item]) -> Vec { + let mut docs = Vec::new(); + for (i, item) in items.iter().enumerate() { + if i > 0 { + docs.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.item(item)); + } + docs + } + + fn stmt_seq(&self, stmts: &[Stmt]) -> Vec { + let mut docs = Vec::new(); + for (i, s) in stmts.iter().enumerate() { + if i > 0 { + docs.push(if s.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.stmt(s)); + } + docs + } + + fn dangling(&self, comments: &[Comment]) -> Vec { + let mut docs = Vec::new(); + for c in comments { + if c.blank_before { + docs.push(Doc::BlankLine); + } else { + docs.push(Doc::HardLine); + } + docs.push(self.raw_text(&c.text)); + } + docs + } + + // ------------------------------------------------------------------ + // File / items + // ------------------------------------------------------------------ + + fn file(&self, f: &SourceFile) -> Doc { + let mut docs = self.item_seq(&f.items); + for (i, c) in f.dangling.iter().enumerate() { + if !docs.is_empty() || i > 0 { + docs.push(if c.blank_before { Doc::BlankLine } else { Doc::HardLine }); + } + docs.push(self.raw_text(&c.text)); + } + concat(docs) + } + + fn item(&self, item: &Item) -> Doc { + self.with_meta(&item.meta, self.item_kind(&item.kind)) + } + + fn item_kind(&self, kind: &ItemKind) -> Doc { + match kind { + ItemKind::Module(m) => self.module(m), + ItemKind::Package { kw, name, items, dangling } => { + let mut docs = vec![text(format!("{kw} {name};"))]; + let mut body = Vec::new(); + if !items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.item_seq(items)); + } + body.extend(self.dangling(dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("endpackage")); + concat(docs) + } + ItemKind::Directive(d) => self.raw_text(d), + ItemKind::Import(paths) => text(format!("import {};", paths.join(", "))), + ItemKind::Timeunit(t) => text(format!("{t};")), + ItemKind::Typedef(t) => self.typedef(t), + ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d), text(";")]), + ItemKind::DataDecl(d) => concat(vec![self.data_decl(d), text(";")]), + ItemKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]), + ItemKind::ContAssign(a) => self.cont_assign(a), + ItemKind::Always { kw, stmt } => self.stmt_as_body(text(kw.clone()), stmt), + ItemKind::Initial(s) => self.stmt_as_body(text("initial"), s), + ItemKind::Final(s) => self.stmt_as_body(text("final"), s), + ItemKind::Instantiation(inst) => self.instantiation(inst), + ItemKind::GateInstantiation(g) => self.gate_instantiation(g), + ItemKind::Genvar(names) => text(format!("genvar {};", names.join(", "))), + ItemKind::GenerateRegion { items, dangling } => { + let mut body = Vec::new(); + if !items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.item_seq(items)); + } + body.extend(self.dangling(dangling)); + concat(vec![ + text("generate"), + indent(body), + Doc::HardLine, + text("endgenerate"), + ]) + } + ItemKind::GenIf(g) => self.gen_if(g), + ItemKind::GenFor(g) => self.gen_for(g), + ItemKind::GenCase(g) => self.gen_case(g), + ItemKind::Function(f) => self.function(f), + ItemKind::Task(t) => self.task(t), + ItemKind::Defparam(pairs) => { + let parts: Vec = pairs + .iter() + .map(|(l, r)| { + concat(vec![self.expr(l), text(" = "), self.expr(r)]) + }) + .collect(); + let mut docs = vec![text("defparam ")]; + docs.extend(join(parts, text(", "))); + docs.push(text(";")); + concat(docs) + } + } + } + + // ------------------------------------------------------------------ + // Module + // ------------------------------------------------------------------ + + fn module(&self, m: &Module) -> Doc { + let mut docs = vec![text(format!("{} {}", m.kw, m.name))]; + let has_imports = !m.imports.is_empty(); + if has_imports { + docs.push(indent(vec![ + Doc::HardLine, + text(format!("import {};", m.imports.join(", "))), + ])); + docs.push(Doc::HardLine); + } + // After an import block the header continues at column 0, so the + // usual single space before `#(`/`(` is dropped. + let mut on_fresh_line = has_imports; + if !m.param_ports.is_empty() { + let items: Vec = m + .param_ports + .iter() + .map(|p| ListItem::from_meta(&p.meta, self.param_port(p))) + .collect(); + docs.push(text(if on_fresh_line { "#" } else { " #" })); + docs.push(self.delimited("(", items, ")", false)); + on_fresh_line = false; + } + match &m.ports { + PortList::None => docs.push(text(";")), + PortList::Empty => docs.push(text(if on_fresh_line { "();" } else { " ();" })), + PortList::Ansi(_) | PortList::NonAnsi(_) => { + let items: Vec = match &m.ports { + PortList::Ansi(ports) => ports + .iter() + .map(|p| ListItem::from_meta(&p.meta, self.ansi_port(p))) + .collect(), + PortList::NonAnsi(ports) => ports + .iter() + .map(|p| ListItem::from_meta(&p.meta, text(p.name.clone()))) + .collect(), + _ => unreachable!(), + }; + if !on_fresh_line { + docs.push(text(" ")); + } + docs.push(self.delimited("(", items, ")", false)); + docs.push(text(";")); + } + } + let mut body = Vec::new(); + if !m.items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.item_seq(&m.items)); + } + body.extend(self.dangling(&m.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(match &m.end_label { + Some(l) => text(format!("endmodule : {l}")), + None => text("endmodule"), + }); + concat(docs) + } + + fn param_port(&self, p: &ParamPort) -> Doc { + let mut parts: Vec = Vec::new(); + if let Some(kw) = &p.kw { + parts.push(kw.clone()); + } + if p.is_type { + parts.push("type".to_string()); + } + let mut docs = Vec::new(); + let ty = self.data_type(&p.ty); + let prefix = parts.join(" "); + if !prefix.is_empty() { + docs.push(text(prefix)); + docs.push(text(" ")); + } + if let Some(t) = ty { + docs.push(t); + docs.push(text(" ")); + } + docs.push(text(p.name.clone())); + docs.extend(self.unpacked_dims(&p.unpacked)); + if let Some(d) = &p.default { + docs.push(text(" = ")); + docs.push(group(vec![self.expr(d)])); + } + concat(docs) + } + + fn ansi_port(&self, p: &AnsiPort) -> Doc { + let mut docs = Vec::new(); + if let Some(dir) = &p.dir { + docs.push(text(format!("{dir} "))); + } + if let Some(net) = &p.net { + docs.push(text(format!("{net} "))); + } + if let Some(t) = self.data_type(&p.ty) { + docs.push(t); + docs.push(text(" ")); + } + docs.push(text(p.name.clone())); + docs.extend(self.unpacked_dims(&p.unpacked)); + if let Some(d) = &p.default { + docs.push(text(" = ")); + docs.push(self.expr(d)); + } + concat(docs) + } + + // ------------------------------------------------------------------ + // Types and declarations + // ------------------------------------------------------------------ + + /// Format a data type; `None` if fully implicit. + fn data_type(&self, ty: &DataType) -> Option { + if ty.is_implicit() { + return None; + } + let mut docs = Vec::new(); + let mut need_space = false; + if !ty.name.is_empty() { + docs.push(text(ty.name.clone())); + 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() { + if need_space { + docs.push(text(" ")); + } + for d in &ty.packed { + docs.push(self.dim(d)); + } + } + Some(concat(docs)) + } + + fn dim(&self, d: &Dim) -> Doc { + let mut docs = vec![text("["), self.expr_compact(&d.a)]; + if let Some(b) = &d.b { + docs.push(text(":")); + docs.push(self.expr_compact(b)); + } + docs.push(text("]")); + concat(docs) + } + + /// Compact rendering used inside `[...]` brackets: arithmetic and shift + /// operators lose their surrounding spaces (`[WIDTH-1:0]`), and no line + /// breaks are introduced. + fn expr_compact(&self, e: &Expr) -> Doc { + match e { + Expr::Binary { lhs, op, rhs } => { + let tight = Self::binary_prec(op) >= 8; + let sep = if tight { op.clone() } else { format!(" {op} ") }; + concat(vec![self.expr_compact(lhs), text(sep), self.expr_compact(rhs)]) + } + Expr::Ternary { cond, then, els } => concat(vec![ + self.expr_compact(cond), + text(" ? "), + self.expr_compact(then), + 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)]) + } + _ => self.expr(e), + } + } + + fn unpacked_dims(&self, dims: &[Dim]) -> Vec { + let mut docs = Vec::new(); + if !dims.is_empty() { + docs.push(text(" ")); + for d in dims { + docs.push(self.dim(d)); + } + } + docs + } + + fn declarators(&self, decls: &[Declarator]) -> Doc { + let items: Vec = decls + .iter() + .map(|d| { + let mut docs = vec![text(d.name.clone())]; + docs.extend(self.unpacked_dims(&d.unpacked)); + if let Some(init) = &d.init { + docs.push(text(" =")); + docs.push(group(vec![indent(vec![Doc::Line, 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, + trailing: None, + blank_before: false, + attrs: Vec::new(), + }); + docs.push(item.doc); + if let Some(tr) = item.trailing { + docs.push(text(format!(" {tr}"))); + } + 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, + trailing: None, + blank_before: false, + attrs: Vec::new(), + }; + inner.extend(self.leading(&meta)); + inner.push(item.doc); + if i < last { + inner.push(text(",")); + } + if let Some(tr) = item.trailing { + inner.push(text(format!(" {tr}"))); + if i < last { + inner.push(Doc::HardLine); + } + } else if i < last { + inner.push(Doc::Line); + } + } + group(vec![indent(inner)]) + } + + fn param_decl(&self, d: &ParamDecl) -> Doc { + let mut docs = vec![text(d.kw.clone()), text(" ")]; + if let Some(t) = self.data_type(&d.ty) { + docs.push(t); + docs.push(text(" ")); + } + docs.push(self.declarators(&d.declarators)); + concat(docs) + } + + fn data_decl(&self, d: &DataDecl) -> Doc { + let mut docs = Vec::new(); + if let Some(net) = &d.net { + docs.push(text(format!("{net} "))); + } + if let Some(delay) = &d.delay { + docs.push(text("#")); + docs.push(self.expr(delay)); + docs.push(text(" ")); + } + for q in &d.qualifiers { + docs.push(text(format!("{q} "))); + } + if let Some(t) = self.data_type(&d.ty) { + docs.push(t); + docs.push(text(" ")); + } + docs.push(self.declarators(&d.declarators)); + concat(docs) + } + + 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) + } + + fn typedef(&self, t: &Typedef) -> Doc { + match &t.kind { + TypedefKind::Alias(ty) => { + let mut docs = vec![text("typedef ")]; + if let Some(d) = self.data_type(ty) { + docs.push(d); + docs.push(text(" ")); + } + docs.push(text(t.name.clone())); + docs.extend(self.unpacked_dims(&t.unpacked)); + docs.push(text(";")); + concat(docs) + } + TypedefKind::Enum(e) => { + let mut docs = vec![text("typedef 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 = 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)) + }) + .collect(); + docs.push(self.delimited("{", items, "}", false)); + docs.push(text(format!(" {};", t.name))); + concat(docs) + } + TypedefKind::Struct(s) => { + let mut header = format!("typedef {}", s.kw); + 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)); + if let Some(tr) = &m.meta.trailing { + inner.push(text(format!(" {tr}"))); + } + } + inner.extend(self.dangling(&s.dangling)); + concat(vec![ + text(header), + indent(inner), + Doc::HardLine, + text(format!("}} {};", t.name)), + ]) + } + } + } + + // ------------------------------------------------------------------ + // Module items + // ------------------------------------------------------------------ + + fn cont_assign(&self, a: &ContAssign) -> Doc { + let mut docs = vec![text("assign ")]; + if let Some(delay) = &a.delay { + docs.push(text("#")); + docs.push(self.expr(delay)); + docs.push(text(" ")); + } + let items: Vec = a + .assigns + .iter() + .map(|p| { + let d = group(vec![ + self.expr(&p.lhs), + text(" ="), + indent(vec![Doc::Line, self.expr(&p.rhs)]), + ]); + ListItem::from_meta(&p.meta, d) + }) + .collect(); + if items.len() == 1 { + let item = items.into_iter().next().unwrap(); + docs.push(item.doc); + docs.push(text(";")); + if let Some(tr) = item.trailing { + docs.push(text(format!(" {tr}"))); + } + } else { + let last = items.len() - 1; + let mut inner = Vec::new(); + for (i, item) in items.into_iter().enumerate() { + inner.push(item.doc); + if i < last { + inner.push(text(",")); + } else { + inner.push(text(";")); + } + if let Some(tr) = item.trailing { + inner.push(text(format!(" {tr}"))); + if i < last { + inner.push(Doc::HardLine); + } + } else if i < last { + inner.push(Doc::Line); + } + } + docs.push(group(vec![indent(inner)])); + } + concat(docs) + } + + fn instantiation(&self, inst: &Instantiation) -> Doc { + let mut docs = vec![text(inst.module.clone())]; + if !inst.params.is_empty() { + let items: Vec = inst + .params + .iter() + .map(|c| ListItem::from_meta(&c.meta, self.connection(c))) + .collect(); + docs.push(text(" #")); + docs.push(self.delimited("(", items, ")", false)); + } + let single = inst.instances.len() == 1; + for (i, instance) in inst.instances.iter().enumerate() { + if i > 0 { + docs.push(text(",")); + docs.push(Doc::HardLine); + } else { + docs.push(text(" ")); + } + let _ = single; + docs.push(text(instance.name.clone())); + if !instance.dims.is_empty() { + docs.push(text(" ")); + for d in &instance.dims { + docs.push(self.dim(d)); + } + } + docs.push(text(" ")); + docs.push(self.connections(&instance.conns)); + } + docs.push(text(";")); + concat(docs) + } + + 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(); + self.delimited("(", items, ")", false) + } + Connections::Ordered(list) => { + let items: Vec = list + .iter() + .map(|c| { + let d = match &c.expr { + Some(e) => self.expr(e), + None => text(""), + }; + ListItem::from_meta(&c.meta, d) + }) + .collect(); + self.delimited("(", items, ")", false) + } + } + } + + fn connection(&self, c: &Connection) -> Doc { + if c.name == "*" { + return text(".*"); + } + if c.name.is_empty() { + // Positional parameter value. + return match &c.expr { + Some(e) => self.expr(e), + None => text(""), + }; + } + match &c.expr { + None => text(format!(".{}", c.name)), + Some(Expr::Empty) => text(format!(".{}()", c.name)), + Some(e) => concat(vec![ + text(format!(".{}(", c.name)), + group(vec![indent(vec![Doc::SoftLine, self.expr(e)]), Doc::SoftLine]), + text(")"), + ]), + } + } + + fn gate_instantiation(&self, g: &GateInstantiation) -> Doc { + let mut docs = vec![text(g.gate.clone())]; + if let Some(delay) = &g.delay { + docs.push(text(" #")); + docs.push(self.expr(delay)); + } + for (i, inst) in g.instances.iter().enumerate() { + docs.push(if i > 0 { text(", ") } else { text(" ") }); + if let Some(name) = &inst.name { + docs.push(text(name.clone())); + docs.push(text(" ")); + } + let items: Vec = + inst.args.iter().map(|a| ListItem::plain(self.expr(a))).collect(); + docs.push(self.delimited("(", items, ")", false)); + } + docs.push(text(";")); + concat(docs) + } + + // ------------------------------------------------------------------ + // Generate constructs + // ------------------------------------------------------------------ + + fn gen_if(&self, g: &GenIf) -> Doc { + let mut docs = vec![text("if "), self.parens(&g.cond)]; + let mut cuddle = self.gen_block(&mut docs, &g.then); + let mut els = &g.els; + while let Some(e) = els { + match e.as_ref() { + GenElse::If(_meta, gi) => { + if cuddle { + docs.push(text(" else if ")); + } else { + docs.push(Doc::HardLine); + docs.push(text("else if ")); + } + docs.push(self.parens(&gi.cond)); + cuddle = self.gen_block(&mut docs, &gi.then); + els = &gi.els; + } + GenElse::Block(b) => { + if cuddle { + docs.push(text(" else")); + } else { + docs.push(Doc::HardLine); + docs.push(text("else")); + } + self.gen_block(&mut docs, b); + break; + } + } + } + concat(docs) + } + + /// Append a generate block; returns true if it ended with `end` (so + /// `else` can cuddle). + fn gen_block(&self, docs: &mut Vec, b: &GenBlock) -> bool { + if b.is_block { + match &b.label { + Some(l) => docs.push(text(format!(" begin : {l}"))), + None => docs.push(text(" begin")), + } + let mut body = Vec::new(); + if !b.items.is_empty() { + body.push(Doc::HardLine); + body.extend(self.item_seq(&b.items)); + } + body.extend(self.dangling(&b.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("end")); + true + } else { + let item = &b.items[0]; + docs.push(group(vec![indent(vec![Doc::Line, self.item(item)])])); + false + } + } + + fn gen_for(&self, g: &GenFor) -> Doc { + let mut header = vec![text("for (")]; + if g.init_genvar { + header.push(text("genvar ")); + } + header.push(self.expr(&g.init.lhs)); + header.push(text(format!(" {} ", g.init.op))); + header.push(self.expr(&g.init.rhs)); + header.push(text("; ")); + header.push(self.expr(&g.cond)); + header.push(text("; ")); + header.push(self.for_step(&g.step)); + header.push(text(")")); + let mut docs = vec![concat(header)]; + self.gen_block(&mut docs, &g.body); + concat(docs) + } + + fn gen_case(&self, g: &GenCase) -> Doc { + let mut docs = vec![text("case "), self.parens(&g.expr)]; + let mut body = Vec::new(); + for item in &g.items { + body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine }); + body.extend(self.leading(&item.meta)); + let label = if item.labels.is_empty() { + text("default:") + } else { + let labels: Vec = item.labels.iter().map(|l| self.expr(l)).collect(); + concat(vec![concat(join(labels, text(", "))), text(":")]) + }; + let mut item_docs = vec![label]; + self.gen_block(&mut item_docs, &item.body); + body.push(concat(item_docs)); + if let Some(tr) = &item.meta.trailing { + body.push(text(format!(" {tr}"))); + } + } + body.extend(self.dangling(&g.dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("endcase")); + concat(docs) + } + + 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::Expr(e) => self.expr(e), + } + } + + // ------------------------------------------------------------------ + // Functions and tasks + // ------------------------------------------------------------------ + + fn tf_args(&self, args: &[TfArg]) -> Doc { + let items: Vec = args + .iter() + .map(|a| { + let mut docs = Vec::new(); + if let Some(dir) = &a.dir { + docs.push(text(format!("{dir} "))); + } + if let Some(t) = self.data_type(&a.ty) { + docs.push(t); + docs.push(text(" ")); + } + docs.push(text(a.name.clone())); + docs.extend(self.unpacked_dims(&a.unpacked)); + if let Some(d) = &a.default { + docs.push(text(" = ")); + docs.push(self.expr(d)); + } + ListItem::from_meta(&a.meta, concat(docs)) + }) + .collect(); + self.delimited("(", items, ")", false) + } + + fn function(&self, f: &FunctionDecl) -> Doc { + let mut header = vec![text("function ")]; + for q in &f.qualifiers { + header.push(text(format!("{q} "))); + } + if let Some(ret) = &f.ret { + if let Some(t) = self.data_type(ret) { + header.push(t); + header.push(text(" ")); + } + } + header.push(text(f.name.clone())); + if f.has_parens { + header.push(self.tf_args(&f.args)); + } + header.push(text(";")); + let mut body = Vec::new(); + if !f.stmts.is_empty() { + body.push(Doc::HardLine); + body.extend(self.stmt_seq(&f.stmts)); + } + body.extend(self.dangling(&f.dangling)); + concat(vec![ + concat(header), + indent(body), + Doc::HardLine, + text("endfunction"), + ]) + } + + fn task(&self, t: &TaskDecl) -> Doc { + let mut header = vec![text("task ")]; + for q in &t.qualifiers { + header.push(text(format!("{q} "))); + } + header.push(text(t.name.clone())); + if t.has_parens { + header.push(self.tf_args(&t.args)); + } + header.push(text(";")); + let mut body = Vec::new(); + if !t.stmts.is_empty() { + body.push(Doc::HardLine); + body.extend(self.stmt_seq(&t.stmts)); + } + body.extend(self.dangling(&t.dangling)); + concat(vec![concat(header), indent(body), Doc::HardLine, text("endtask")]) + } + + // ------------------------------------------------------------------ + // Statements + // ------------------------------------------------------------------ + + fn stmt(&self, s: &Stmt) -> Doc { + self.with_meta(&s.meta, self.stmt_kind(&s.kind)) + } + + /// Prefix (e.g. `always_ff`, `if (...)`) followed by a body statement: + /// blocks cuddle onto the prefix line, single statements go on the same + /// line if they fit, otherwise indented on the next line. + fn stmt_as_body(&self, prefix: Doc, s: &Stmt) -> Doc { + match &s.kind { + StmtKind::Block { label, stmts, dangling } => { + let mut docs = vec![prefix, text(" ")]; + docs.extend(self.leading(&s.meta)); + docs.push(self.block_doc(label, stmts, dangling)); + docs.extend(self.trailing(&s.meta)); + concat(docs) + } + StmtKind::Timing { control, stmt: Some(inner) } => { + // e.g. `always @(posedge clk) begin ... end` + let mut docs = vec![prefix, text(" ")]; + docs.extend(self.leading(&s.meta)); + let control_doc = self.timing_control(control); + docs.push(self.stmt_as_body(control_doc, inner)); + docs.extend(self.trailing(&s.meta)); + concat(docs) + } + _ => group(vec![prefix, indent(vec![Doc::Line, self.stmt(s)])]), + } + } + + fn block_doc(&self, label: &Option, stmts: &[Stmt], dangling: &[Comment]) -> Doc { + let mut docs = vec![match label { + Some(l) => text(format!("begin : {l}")), + None => text("begin"), + }]; + let mut body = Vec::new(); + if !stmts.is_empty() { + body.push(Doc::HardLine); + body.extend(self.stmt_seq(stmts)); + } + body.extend(self.dangling(dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("end")); + concat(docs) + } + + fn timing_control(&self, tc: &TimingControl) -> Doc { + match tc { + TimingControl::Delay(e) => concat(vec![text("#"), self.expr(e)]), + TimingControl::Event(sens) => self.sens_list(sens), + } + } + + fn sens_list(&self, sens: &SensList) -> Doc { + match sens { + SensList::Star => text("@(*)"), + SensList::List(items) => { + let any_edge = items.iter().any(|i| i.edge.is_some()); + let sep = if any_edge { text(" or ") } else { text(", ") }; + let parts: Vec = items + .iter() + .map(|i| { + let mut d = Vec::new(); + if let Some(e) = &i.edge { + d.push(text(format!("{e} "))); + } + d.push(self.expr(&i.expr)); + concat(d) + }) + .collect(); + let mut docs = vec![text("@(")]; + docs.push(group(vec![ + indent(vec![Doc::SoftLine, concat(join(parts, sep))]), + Doc::SoftLine, + ])); + docs.push(text(")")); + concat(docs) + } + } + } + + fn stmt_kind(&self, kind: &StmtKind) -> Doc { + match kind { + StmtKind::Block { label, stmts, dangling } => self.block_doc(label, stmts, dangling), + StmtKind::ForkJoin { label, join_kw, stmts, dangling } => { + let mut docs = vec![match label { + Some(l) => text(format!("fork : {l}")), + None => text("fork"), + }]; + let mut body = Vec::new(); + if !stmts.is_empty() { + body.push(Doc::HardLine); + body.extend(self.stmt_seq(stmts)); + } + body.extend(self.dangling(dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text(join_kw.clone())); + concat(docs) + } + 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 { + head.push_str(q); + head.push(' '); + } + head.push_str(kw); + head.push(' '); + 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.extend(self.leading(&item.meta)); + body.push(self.case_item(item)); + if let Some(tr) = &item.meta.trailing { + body.push(text(format!(" {tr}"))); + } + } + body.extend(self.dangling(dangling)); + docs.push(indent(body)); + docs.push(Doc::HardLine); + docs.push(text("endcase")); + concat(docs) + } + StmtKind::For { init, cond, step, body } => { + let mut header = vec![text("for (")]; + let init_parts: Vec = init + .iter() + .map(|fi| { + let mut d = Vec::new(); + if let Some(ty) = &fi.ty { + if let Some(t) = self.data_type(ty) { + d.push(t); + d.push(text(" ")); + } + } + d.push(self.expr(&fi.assign.lhs)); + d.push(text(format!(" {} ", fi.assign.op))); + d.push(self.expr(&fi.assign.rhs)); + concat(d) + }) + .collect(); + header.extend(join(init_parts, text(", "))); + header.push(text("; ")); + if let Some(c) = cond { + header.push(self.expr(c)); + } + header.push(text("; ")); + let step_parts: Vec = step.iter().map(|s| self.for_step(s)).collect(); + header.extend(join(step_parts, text(", "))); + header.push(text(")")); + self.stmt_as_body(concat(header), body) + } + StmtKind::While { cond, body } => { + self.stmt_as_body(concat(vec![text("while "), self.parens(cond)]), body) + } + StmtKind::DoWhile { body, cond } => { + let mut docs = vec![text("do")]; + match &body.kind { + StmtKind::Block { label, stmts, dangling } => { + docs.push(text(" ")); + docs.push(self.block_doc(label, stmts, dangling)); + docs.push(text(" while ")); + } + _ => { + docs.push(group(vec![indent(vec![Doc::Line, self.stmt(body)])])); + docs.push(Doc::HardLine); + docs.push(text("while ")); + } + } + docs.push(self.parens(cond)); + docs.push(text(";")); + concat(docs) + } + StmtKind::Repeat { count, body } => { + self.stmt_as_body(concat(vec![text("repeat "), self.parens(count)]), body) + } + StmtKind::Forever { body } => self.stmt_as_body(text("forever"), body), + StmtKind::Foreach { target, vars, body } => { + let head = concat(vec![ + text("foreach ("), + self.expr(target), + text(format!("[{}])", vars.join(", "))), + ]); + self.stmt_as_body(head, body) + } + StmtKind::Assign { lhs, op, timing, rhs } => { + let mut docs = vec![self.expr(lhs), text(format!(" {op}"))]; + let mut rhs_docs = Vec::new(); + if let Some(tc) = timing { + rhs_docs.push(self.timing_control(tc)); + rhs_docs.push(text(" ")); + } + rhs_docs.push(self.expr(rhs)); + docs.push(indent(vec![Doc::Line, concat(rhs_docs)])); + concat(vec![group(docs), text(";")]) + } + StmtKind::ForceRelease { kw, lhs, rhs } => { + let mut docs = vec![text(format!("{kw} ")), self.expr(lhs)]; + if let Some(r) = rhs { + docs.push(text(" = ")); + docs.push(self.expr(r)); + } + docs.push(text(";")); + concat(docs) + } + StmtKind::Timing { control, stmt } => { + let control_doc = self.timing_control(control); + match stmt { + Some(s) => self.stmt_as_body(control_doc, s), + None => concat(vec![control_doc, text(";")]), + } + } + StmtKind::Wait { cond, stmt } => { + let head = concat(vec![text("wait "), self.parens(cond)]); + match stmt { + Some(s) => self.stmt_as_body(head, s), + None => concat(vec![head, text(";")]), + } + } + StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]), + StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]), + StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]), + StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d), text(";")]), + StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]), + StmtKind::Return(e) => match e { + Some(e) => concat(vec![text("return "), self.expr(e), text(";")]), + None => text("return;"), + }, + StmtKind::Break => text("break;"), + StmtKind::Continue => text("continue;"), + StmtKind::Disable(name) => text(format!("disable {name};")), + StmtKind::Directive(d) => self.raw_text(d), + StmtKind::Assert { kw, cond, then, els } => { + let mut docs = vec![text(format!("{kw} ")), self.parens(cond)]; + match (then, els) { + (None, None) => docs.push(text(";")), + (Some(t), None) => { + docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])])); + } + (None, Some(e)) => { + docs.push(text(" else")); + docs.push(group(vec![indent(vec![Doc::Line, self.stmt(e)])])); + } + (Some(t), Some(e)) => { + docs.push(group(vec![indent(vec![Doc::Line, self.stmt(t)])])); + docs.push(Doc::HardLine); + docs.push(text("else")); + docs.push(group(vec![indent(vec![Doc::Line, self.stmt(e)])])); + } + } + concat(docs) + } + StmtKind::Null => text(";"), + } + } + + fn if_stmt( + &self, + qualifier: &Option, + cond: &Expr, + then: &Stmt, + els: &Option>, + ) -> Doc { + let mut head = String::new(); + if let Some(q) = qualifier { + head.push_str(q); + head.push(' '); + } + head.push_str("if "); + let prefix = concat(vec![text(head), self.parens(cond)]); + let then_is_block = matches!(then.kind, StmtKind::Block { .. }); + let mut docs = vec![self.stmt_as_body(prefix, then)]; + if let Some(els) = els { + if then_is_block { + docs.push(text(" else")); + } else { + docs.push(Doc::HardLine); + docs.push(text("else")); + } + // `else if` chains stay flat. + 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); + docs.push(self.if_stmt(eq, ec, et, ee)); + if let Some(tr) = &els.meta.trailing { + docs.push(text(format!(" {tr}"))); + } + } else { + docs.push(self.stmt_as_body(text(""), els)); + } + } + concat(docs) + } + + fn case_item(&self, item: &CaseItem) -> Doc { + let label = if item.labels.is_empty() { + text("default:") + } else { + let labels: Vec = item.labels.iter().map(|l| self.expr(l)).collect(); + concat(vec![concat(join(labels, text(", "))), text(":")]) + }; + self.stmt_as_body(label, &item.stmt) + } + + // ------------------------------------------------------------------ + // Expressions + // ------------------------------------------------------------------ + + fn binary_prec(op: &str) -> u8 { + match op { + "||" => 1, + "&&" => 2, + "|" => 3, + "^" | "^~" | "~^" => 4, + "&" => 5, + "==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6, + "<" | "<=" | ">" | ">=" => 7, + "<<" | ">>" | "<<<" | ">>>" => 8, + "+" | "-" => 9, + "*" | "/" | "%" => 10, + "**" => 11, + _ => 0, + } + } + + fn expr(&self, e: &Expr) -> Doc { + match e { + Expr::Ident(s) => text(s.clone()), + Expr::Number(s) => text(s.clone()), + Expr::Str(s) => text(s.clone()), + Expr::Empty => text(""), + Expr::Unary { op, expr } => concat(vec![text(op.clone()), self.expr(expr)]), + Expr::Binary { .. } => self.binary_chain(e), + Expr::Ternary { cond, then, els } => group(vec![ + self.expr(cond), + indent(vec![ + Doc::Line, + text("? "), + self.expr(then), + Doc::Line, + text(": "), + self.expr(els), + ]), + ]), + Expr::Call { callee, args } => { + let items: Vec = + args.iter().map(|a| ListItem::plain(self.expr(a))).collect(); + concat(vec![self.expr(callee), self.delimited("(", items, ")", false)]) + } + Expr::Index { base, index } => { + concat(vec![self.expr(base), text("["), self.expr_compact(index), text("]")]) + } + Expr::Range { base, op, msb, lsb } => concat(vec![ + self.expr(base), + text("["), + self.expr_compact(msb), + text(op.clone()), + 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::Concat(items) => { + let items: Vec = + items.iter().map(|i| ListItem::plain(self.expr(i))).collect(); + self.delimited("{", items, "}", false) + } + Expr::Repl { count, inner } => { + let inner_docs: Vec = inner.iter().map(|i| self.expr(i)).collect(); + concat(vec![ + text("{"), + self.expr(count), + text("{"), + concat(join(inner_docs, text(", "))), + text("}}"), + ]) + } + Expr::Paren(inner) => self.parens(inner), + Expr::Cast { ty, expr } => { + concat(vec![text(format!("{ty}'(")), self.expr(expr), text(")")]) + } + Expr::AssignPattern(items) => { + let items: Vec = items + .iter() + .map(|pi| { + let mut d = Vec::new(); + if let Some(k) = &pi.key { + d.push(self.expr(k)); + d.push(text(": ")); + } + d.push(self.expr(&pi.value)); + ListItem::plain(concat(d)) + }) + .collect(); + self.delimited("'{", items, "}", false) + } + Expr::Postfix { expr, op } => concat(vec![self.expr(expr), text(op.clone())]), + Expr::Inside { lhs, ranges } => { + let items: Vec = + ranges.iter().map(|r| ListItem::plain(self.expr(r))).collect(); + concat(vec![ + self.expr(lhs), + text(" inside "), + self.delimited("{", items, "}", false), + ]) + } + Expr::ValueRange { lo, hi } => { + 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), + ]), + } + } + + /// Flatten a left-nested chain of same-precedence binary operators so + /// `a + b + c` breaks as one unit instead of stair-stepping. + fn binary_chain(&self, e: &Expr) -> Doc { + let Expr::Binary { op, .. } = e else { unreachable!() }; + 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>, + ) { + match e { + Expr::Binary { lhs, op, rhs } if Fmt::binary_prec(op) == prec => { + walk(lhs, prec, operands, ops); + ops.push(op); + operands.push(rhs); + } + _ => operands.push(e), + } + } + walk(e, prec, &mut operands, &mut ops); + let mut docs = vec![self.expr(operands[0])]; + let mut cont = Vec::new(); + for (op, rhs) in ops.iter().zip(operands[1..].iter()) { + cont.push(text(format!(" {op}"))); + cont.push(Doc::Line); + cont.push(self.expr(rhs)); + } + docs.push(indent(cont)); + group(docs) + } +} diff --git a/crates/vlog_formatter/src/lib.rs b/crates/vlog_formatter/src/lib.rs new file mode 100644 index 0000000..dbcb10e --- /dev/null +++ b/crates/vlog_formatter/src/lib.rs @@ -0,0 +1,7 @@ +//! Formatter engine: document IR + printer + formatting rules. + +pub mod doc; +pub mod format; +pub mod printer; + +pub use format::{format_source, Config}; diff --git a/crates/vlog_formatter/src/printer.rs b/crates/vlog_formatter/src/printer.rs new file mode 100644 index 0000000..4d9a392 --- /dev/null +++ b/crates/vlog_formatter/src/printer.rs @@ -0,0 +1,202 @@ +//! The printer: renders a [`Doc`] tree to text within a target line width. +//! +//! This is the classic "strictly pretty" algorithm (also at the heart of +//! prettier and ruff_formatter): a work stack of (indent, mode, doc) triples +//! plus a lookahead `fits` check deciding whether each group prints flat. + +use crate::doc::Doc; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Flat, + Break, +} + +pub struct Printer { + pub max_width: usize, + pub indent_width: usize, +} + +impl Printer { + pub fn print(&self, doc: &Doc) -> String { + let mut out = String::new(); + let mut col = 0usize; + // Stack of (indent_level, mode, doc). + let mut stack: Vec<(usize, Mode, &Doc)> = vec![(0, Mode::Break, doc)]; + + while let Some((ind, mode, d)) = stack.pop() { + match d { + Doc::Text(s) => { + out.push_str(s); + col += s.chars().count(); + } + Doc::Concat(items) => { + for item in items.iter().rev() { + stack.push((ind, mode, item)); + } + } + Doc::Indent(items) => { + for item in items.iter().rev() { + stack.push((ind + 1, mode, item)); + } + } + Doc::Group(items) => { + 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)); + } + } + Doc::Line => { + if mode == Mode::Flat { + out.push(' '); + col += 1; + } else { + self.newline(&mut out, &mut col, ind); + } + } + Doc::SoftLine => { + if mode == Mode::Break { + self.newline(&mut out, &mut col, ind); + } + } + Doc::HardLine => { + self.newline(&mut out, &mut col, ind); + } + Doc::BlankLine => { + // Trim trailing spaces from the current line, add a blank. + while out.ends_with(' ') { + out.pop(); + } + out.push('\n'); + self.newline(&mut out, &mut col, ind); + } + Doc::IfBreak(s) => { + if mode == Mode::Break { + out.push_str(s); + col += s.chars().count(); + } + } + } + } + out + } + + fn newline(&self, out: &mut String, col: &mut usize, ind: usize) { + while out.ends_with(' ') { + out.pop(); + } + out.push('\n'); + let spaces = ind * self.indent_width; + out.extend(std::iter::repeat(' ').take(spaces)); + *col = spaces; + } + + /// Would `items` (flat) followed by the rest of the work stack fit on + /// the current line? + fn fits(&self, col: usize, items: &[Doc], rest: &[(usize, Mode, &Doc)]) -> bool { + let mut width = self.max_width as isize - col as isize; + if width < 0 { + return false; + } + // Local stack: the group's own content in flat mode, then the + // remainder of the outer stack (in its own modes) until a newline. + let mut stack: Vec<(Mode, &Doc)> = Vec::new(); + for (_, mode, d) in rest.iter() { + stack.push((*mode, d)); + } + // rest is a stack (top = last); keep order: we pushed bottom-first, + // so reverse to keep top of stack at the end. + // (rest's last element is the next to be processed.) + for item in items.iter().rev() { + stack.push((Mode::Flat, item)); + } + + while width >= 0 { + let Some((mode, d)) = stack.pop() else { return true }; + match d { + Doc::Text(s) => width -= s.chars().count() as isize, + Doc::Concat(items) | Doc::Indent(items) => { + for it in items.iter().rev() { + stack.push((mode, it)); + } + } + Doc::Group(items) => { + // Nested groups are measured flat unless they contain a + // hard line, which ends the line anyway. + if contains_hard_line(items) { + // Everything up to the hard line still has to fit. + for it in items.iter().rev() { + stack.push((Mode::Break, it)); + } + } else { + for it in items.iter().rev() { + stack.push((Mode::Flat, it)); + } + } + } + Doc::Line => { + if mode == Mode::Flat { + width -= 1; + } else { + return true; + } + } + Doc::SoftLine => { + if mode == Mode::Break { + return true; + } + } + Doc::HardLine | Doc::BlankLine => return true, + Doc::IfBreak(s) => { + if mode == Mode::Break { + width -= s.chars().count() as isize; + } + } + } + } + false + } +} + +fn contains_hard_line(items: &[Doc]) -> bool { + items.iter().any(|d| match d { + Doc::HardLine | Doc::BlankLine => true, + Doc::Concat(inner) | Doc::Indent(inner) | Doc::Group(inner) => contains_hard_line(inner), + _ => false, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::doc::*; + + fn p(width: usize, doc: Doc) -> String { + Printer { max_width: width, indent_width: 2 }.print(&doc) + } + + #[test] + fn flat_when_fits() { + let d = group(vec![text("foo("), Doc::SoftLine, text("bar"), Doc::SoftLine, text(")")]); + assert_eq!(p(80, d), "foo(bar)"); + } + + #[test] + fn breaks_when_too_wide() { + let d = group(vec![ + text("foo("), + indent(vec![Doc::SoftLine, text("barbarbar")]), + Doc::SoftLine, + text(")"), + ]); + assert_eq!(p(8, d), "foo(\n barbarbar\n)"); + } + + #[test] + fn hard_line_forces_break() { + let d = group(vec![text("a"), Doc::HardLine, text("b")]); + assert_eq!(p(80, d), "a\nb"); + } +} diff --git a/crates/vlog_formatter/tests/fixtures.rs b/crates/vlog_formatter/tests/fixtures.rs new file mode 100644 index 0000000..cef1bd6 --- /dev/null +++ b/crates/vlog_formatter/tests/fixtures.rs @@ -0,0 +1,102 @@ +//! Snapshot tests: every file in `tests/fixtures/` is formatted and compared +//! against `tests/snapshots/.formatted`; the result must also be +//! idempotent (formatting the output again changes nothing). +//! +//! Regenerate snapshots with: +//! UPDATE_SNAPSHOTS=1 cargo test -p vlog_formatter --test fixtures + +use std::path::PathBuf; + +use vlog_formatter::{format_source, Config}; + +fn fixture_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +fn snapshot_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots") +} + +#[test] +fn fixtures_match_snapshots_and_are_idempotent() { + let update = std::env::var("UPDATE_SNAPSHOTS").is_ok(); + let config = Config::default(); + 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")) + }) + .collect(); + entries.sort(); + assert!(!entries.is_empty(), "no fixtures found"); + + let mut failures = Vec::new(); + for path in entries { + let name = path.file_name().unwrap().to_str().unwrap().to_string(); + let src = std::fs::read_to_string(&path).expect("read fixture"); + let once = match format_source(&src, &config) { + Ok(o) => o, + Err(e) => { + failures.push(format!("{name}: failed to format: {e}")); + continue; + } + }; + // Idempotency. + match format_source(&once, &config) { + Ok(twice) => { + if twice != once { + failures.push(format!("{name}: formatting is not idempotent")); + } + } + Err(e) => { + failures.push(format!("{name}: reformatting own output failed: {e}")); + } + } + // Snapshot comparison. + let snap_path = snapshot_dir().join(format!("{name}.formatted")); + if update { + std::fs::write(&snap_path, &once).expect("write snapshot"); + } else { + match std::fs::read_to_string(&snap_path) { + Ok(expected) => { + if expected != once { + failures.push(format!( + "{name}: output differs from snapshot \ + (run with UPDATE_SNAPSHOTS=1 to update)" + )); + } + } + Err(_) => failures.push(format!( + "{name}: missing snapshot {} (run with UPDATE_SNAPSHOTS=1)", + snap_path.display() + )), + } + } + } + assert!(failures.is_empty(), "{}", failures.join("\n")); +} + +#[test] +fn small_cases() { + // (input, expected) pairs for focused behaviors. + let cases: &[(&str, &str)] = &[ + ( + "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", + ), + ( + "module m;wire [7:0] x = {a,b} ;endmodule", + "module m;\n wire [7:0] x = {a, b};\nendmodule\n", + ), + ]; + let config = Config::default(); + for (input, expected) in cases { + let got = format_source(input, &config).expect("format"); + assert_eq!(&got, expected, "input: {input}"); + } +} diff --git a/crates/vlog_formatter/tests/fixtures/counter.sv b/crates/vlog_formatter/tests/fixtures/counter.sv new file mode 100644 index 0000000..c08770a --- /dev/null +++ b/crates/vlog_formatter/tests/fixtures/counter.sv @@ -0,0 +1,28 @@ +// Simple counter module +`timescale 1ns/1ps +module counter #(parameter WIDTH=8,parameter int DEPTH = 16) (input wire clk,input wire rst_n, // async reset +output logic [WIDTH-1:0] count,output logic overflow); + +// internal signals +logic [WIDTH-1:0] next_count;wire enable; + +assign next_count=count+1'b1; +assign overflow = (count=={WIDTH{1'b1}}) && enable; + +always_ff @(posedge clk or negedge rst_n) begin +if(!rst_n) begin count<='0; end +else if(enable) count<=next_count; +else count<=count; +end + +always_comb begin +case(count[1:0]) +2'b00: dbg=4'd0; +2'b01,2'b10:dbg=4'd1; +default: dbg = 4'd2; +endcase +end + +submod #(.W(WIDTH),.D(DEPTH)) u_sub (.clk(clk),.rst_n(rst_n),.data_out(data),.unused()); + +endmodule : counter diff --git a/crates/vlog_formatter/tests/fixtures/fsm.sv b/crates/vlog_formatter/tests/fixtures/fsm.sv new file mode 100644 index 0000000..076ffda --- /dev/null +++ b/crates/vlog_formatter/tests/fixtures/fsm.sv @@ -0,0 +1,65 @@ +// Handshake FSM with a testbench-style checker task. +module fsm #( + parameter int TIMEOUT = 100 +) ( + input logic clk, + input logic rst_n, + input logic req_i, + input logic ack_i, + output logic grant_o, + output logic error_o +); + + typedef enum logic [1:0] { + IDLE, // waiting for request + GRANT, // request granted + WAIT, // waiting for ack + ERROR // timeout + } state_e; + + state_e state_q, state_d; + logic [$clog2(TIMEOUT)-1:0] timer_q, timer_d; + + always_comb begin + state_d = state_q; + timer_d = timer_q; + unique case (state_q) + IDLE: begin + timer_d = '0; + if (req_i) state_d = GRANT; + end + GRANT: state_d = WAIT; + WAIT: begin + timer_d = timer_q + 1'b1; + if (ack_i) state_d = IDLE; + else if (timer_q == TIMEOUT[$clog2(TIMEOUT)-1:0]) state_d = ERROR; + end + default: state_d = IDLE; + endcase + end + + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) begin + state_q <= IDLE; + timer_q <= '0; + end else begin + state_q <= state_d; + timer_q <= timer_d; + end + end + + assign grant_o = state_q == GRANT || state_q == WAIT; + assign error_o = state_q == ERROR; + + task automatic wait_for_grant(input int max_cycles, output bit ok); + ok = 1'b0; + for (int unsigned n = 0; n < max_cycles; n++) begin + @(posedge clk); + if (grant_o) begin + ok = 1'b1; + break; + end + end + endtask + +endmodule diff --git a/crates/vlog_formatter/tests/fixtures/legacy.v b/crates/vlog_formatter/tests/fixtures/legacy.v new file mode 100644 index 0000000..f64c420 --- /dev/null +++ b/crates/vlog_formatter/tests/fixtures/legacy.v @@ -0,0 +1,58 @@ +`include "defines.vh" +`define MAX_VAL 255 +`default_nettype none + +// Old-school Verilog-2001 module, non-ANSI ports +module legacy_dut (clk, rst, d, q, qb); +input clk; // clock +input rst; +input [7:0] d; +output reg [7:0] q; +output qb; + +wire #5 delayed_net; +reg [3:0] mem [0:15]; // small memory +integer i; + +assign #(2:3:4) qb = ~q[0]; +assign delayed_net = d[0] & d[1], other = d[2] | d[3]; + +and g1 (n1, d[0], d[1]); +or #2 g2 (n2, n1, d[2]), g3 (n3, n2, d[3]); + +defparam u_sub.WIDTH = 8, u_sub.DEPTH = 4; + +always @(posedge clk or posedge rst) +if (rst) q <= 8'h00; +else q <= d; + +initial begin : init_blk +for (i = 0; i < 16; i = i + 1) mem[i] = i[3:0]; +#100; +@(posedge clk); +wait (rst == 0); +-> done_event; +fork +#10 $display("a"); +#20 $display("b"); +join +repeat (3) @(posedge clk); +do begin i = i - 1; end while (i > 0); +forever begin +#5 clk_int = ~clk_int; +if (stop) disable init_blk; +end +end + +task automatic drive; +input [7:0] value; +output done; +begin +q = value; +done = 1'b1; +end +endtask + +specparam_unused u_x (.a(a), .b()); +endmodule +`default_nettype wire diff --git a/crates/vlog_formatter/tests/fixtures/sv_features.sv b/crates/vlog_formatter/tests/fixtures/sv_features.sv new file mode 100644 index 0000000..c7d1bfe --- /dev/null +++ b/crates/vlog_formatter/tests/fixtures/sv_features.sv @@ -0,0 +1,64 @@ +package my_pkg; +typedef enum logic [1:0] {ST_IDLE=2'b00,ST_RUN,ST_DONE} state_t; +typedef struct packed {logic [31:0] addr;logic [31:0] wdata;logic we;logic [3:0] be;} bus_req_t; +localparam int unsigned MAX_COUNT=1024; +endpackage + +module axi_widget + import my_pkg::*; +#( + parameter int unsigned DATA_WIDTH = 64, // data bus width + parameter int unsigned ADDR_WIDTH = 32, + localparam int unsigned STRB_WIDTH = DATA_WIDTH/8 +) ( + input logic clk_i, + input logic rst_ni, + input logic [ADDR_WIDTH-1:0] awaddr_i, + input logic [DATA_WIDTH-1:0] wdata_i, + output logic [DATA_WIDTH-1:0] rdata_o, + output logic really_long_output_signal_name_for_testing_line_breaks_o +); + +state_t state_q, state_d; +bus_req_t req; + +// a very long continuous assignment that will definitely need to be broken across multiple lines somehow +assign really_long_output_signal_name_for_testing_line_breaks_o = some_long_signal_name_a && another_long_signal_name_b || yet_another_signal_c && (a_final_signal_d != previous_value_q); + +assign rdata_o = state_q == ST_RUN ? {DATA_WIDTH{1'b1}} : '0; + +`ifdef SIMULATION +initial begin +$display("sim mode, DATA_WIDTH=%0d", DATA_WIDTH); +#10 $finish; +end +`endif + +function automatic logic [7:0] popcount(input logic [63:0] value_with_long_name, input int upper_bound_bits = 64); +logic [7:0] result; +result = '0; +for (int i = 0; i < upper_bound_bits; i++) begin +result = result + value_with_long_name[i]; +end +return result; +endfunction + +genvar g; +generate +for (g = 0; g < STRB_WIDTH; g = g + 1) begin : gen_strb +if (g == 0) begin : gen_first +assign strb[g] = 1'b1; +end else begin : gen_rest +assign strb[g] = wdata_i[g*8] ^ wdata_i[g*8+7]; +end +end +endgenerate + +wide_module #(.DATA_WIDTH(DATA_WIDTH),.ADDR_WIDTH(ADDR_WIDTH),.OUTSTANDING_TRANSACTIONS(8),.ENABLE_ECC(1'b1)) u_wide_module_instance_name (.clk_i(clk_i),.rst_ni(rst_ni),.awaddr_i(awaddr_i),.wdata_i(wdata_i),.rdata_o(rdata_o),.error_o()); + +always_ff @(posedge clk_i or negedge rst_ni) begin +if (!rst_ni) state_q <= ST_IDLE; +else state_q <= state_d; +end + +endmodule diff --git a/crates/vlog_formatter/tests/snapshots/counter.sv.formatted b/crates/vlog_formatter/tests/snapshots/counter.sv.formatted new file mode 100644 index 0000000..f28c058 --- /dev/null +++ b/crates/vlog_formatter/tests/snapshots/counter.sv.formatted @@ -0,0 +1,32 @@ +// Simple counter module +`timescale 1ns/1ps +module counter #(parameter WIDTH = 8, parameter int DEPTH = 16) ( + input wire clk, + input wire rst_n, // async reset + output logic [WIDTH-1:0] count, + output logic overflow +); + // internal signals + logic [WIDTH-1:0] next_count; + wire enable; + + assign next_count = count + 1'b1; + assign overflow = (count == {WIDTH{1'b1}}) && enable; + + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) begin + count <= '0; + end else if (enable) count <= next_count; + else count <= count; + end + + always_comb begin + case (count[1:0]) + 2'b00: dbg = 4'd0; + 2'b01, 2'b10: dbg = 4'd1; + default: dbg = 4'd2; + endcase + end + + submod #(.W(WIDTH), .D(DEPTH)) u_sub (.clk(clk), .rst_n(rst_n), .data_out(data), .unused()); +endmodule : counter diff --git a/crates/vlog_formatter/tests/snapshots/fsm.sv.formatted b/crates/vlog_formatter/tests/snapshots/fsm.sv.formatted new file mode 100644 index 0000000..ff868cf --- /dev/null +++ b/crates/vlog_formatter/tests/snapshots/fsm.sv.formatted @@ -0,0 +1,63 @@ +// Handshake FSM with a testbench-style checker task. +module fsm #( + parameter int TIMEOUT = 100 +) ( + input logic clk, + input logic rst_n, + input logic req_i, + input logic ack_i, + output logic grant_o, + output logic error_o +); + typedef enum logic [1:0] { + IDLE, // waiting for request + GRANT, // request granted + WAIT, // waiting for ack + ERROR // timeout + } state_e; + + state_e state_q, state_d; + logic [$clog2(TIMEOUT)-1:0] timer_q, timer_d; + + always_comb begin + state_d = state_q; + timer_d = timer_q; + unique case (state_q) + IDLE: begin + timer_d = '0; + if (req_i) state_d = GRANT; + end + GRANT: state_d = WAIT; + WAIT: begin + timer_d = timer_q + 1'b1; + if (ack_i) state_d = IDLE; + else if (timer_q == TIMEOUT[$clog2(TIMEOUT)-1:0]) state_d = ERROR; + end + default: state_d = IDLE; + endcase + end + + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) begin + state_q <= IDLE; + timer_q <= '0; + end else begin + state_q <= state_d; + timer_q <= timer_d; + end + end + + assign grant_o = state_q == GRANT || state_q == WAIT; + assign error_o = state_q == ERROR; + + task automatic wait_for_grant(input int max_cycles, output bit ok); + ok = 1'b0; + for (int unsigned n = 0; n < max_cycles; n++) begin + @(posedge clk); + if (grant_o) begin + ok = 1'b1; + break; + end + end + endtask +endmodule diff --git a/crates/vlog_formatter/tests/snapshots/legacy.v.formatted b/crates/vlog_formatter/tests/snapshots/legacy.v.formatted new file mode 100644 index 0000000..9d3b0b8 --- /dev/null +++ b/crates/vlog_formatter/tests/snapshots/legacy.v.formatted @@ -0,0 +1,60 @@ +`include "defines.vh" +`define MAX_VAL 255 +`default_nettype none + +// Old-school Verilog-2001 module, non-ANSI ports +module legacy_dut (clk, rst, d, q, qb); + input clk; // clock + input rst; + input [7:0] d; + output reg [7:0] q; + output qb; + + wire #5 delayed_net; + reg [3:0] mem [0:15]; // small memory + integer i; + + assign #(2:3:4) qb = ~q[0]; + assign delayed_net = d[0] & d[1], other = d[2] | d[3]; + + and g1 (n1, d[0], d[1]); + or #2 g2 (n2, n1, d[2]), g3 (n3, n2, d[3]); + + defparam u_sub.WIDTH = 8, u_sub.DEPTH = 4; + + always @(posedge clk or posedge rst) + if (rst) q <= 8'h00; + else q <= d; + + initial begin : init_blk + for (i = 0; i < 16; i = i + 1) mem[i] = i[3:0]; + #100; + @(posedge clk); + wait (rst == 0); + -> done_event; + fork + #10 $display("a"); + #20 $display("b"); + join + repeat (3) @(posedge clk); + do begin + i = i - 1; + end while (i > 0); + forever begin + #5 clk_int = ~clk_int; + if (stop) disable init_blk; + end + end + + task automatic drive; + input [7:0] value; + output done; + begin + q = value; + done = 1'b1; + end + endtask + + specparam_unused u_x (.a(a), .b()); +endmodule +`default_nettype wire diff --git a/crates/vlog_formatter/tests/snapshots/sv_features.sv.formatted b/crates/vlog_formatter/tests/snapshots/sv_features.sv.formatted new file mode 100644 index 0000000..9a14b86 --- /dev/null +++ b/crates/vlog_formatter/tests/snapshots/sv_features.sv.formatted @@ -0,0 +1,84 @@ +package my_pkg; + typedef enum logic [1:0] {ST_IDLE = 2'b00, ST_RUN, ST_DONE} state_t; + typedef struct packed { + logic [31:0] addr; + logic [31:0] wdata; + logic we; + logic [3:0] be; + } bus_req_t; + localparam int unsigned MAX_COUNT = 1024; +endpackage + +module axi_widget + import my_pkg::*; +#( + parameter int unsigned DATA_WIDTH = 64, // data bus width + parameter int unsigned ADDR_WIDTH = 32, + localparam int unsigned STRB_WIDTH = DATA_WIDTH / 8 +) ( + input logic clk_i, + input logic rst_ni, + input logic [ADDR_WIDTH-1:0] awaddr_i, + input logic [DATA_WIDTH-1:0] wdata_i, + output logic [DATA_WIDTH-1:0] rdata_o, + output logic really_long_output_signal_name_for_testing_line_breaks_o +); + state_t state_q, state_d; + bus_req_t req; + + // a very long continuous assignment that will definitely need to be broken across multiple lines somehow + assign really_long_output_signal_name_for_testing_line_breaks_o = + some_long_signal_name_a && another_long_signal_name_b || + yet_another_signal_c && (a_final_signal_d != previous_value_q); + + assign rdata_o = state_q == ST_RUN ? {DATA_WIDTH{1'b1}} : '0; + + `ifdef SIMULATION + initial begin + $display("sim mode, DATA_WIDTH=%0d", DATA_WIDTH); + #10 $finish; + end + `endif + + function automatic logic [7:0] popcount( + input logic [63:0] value_with_long_name, + input int upper_bound_bits = 64 + ); + logic [7:0] result; + result = '0; + for (int i = 0; i < upper_bound_bits; i++) begin + result = result + value_with_long_name[i]; + end + return result; + endfunction + + genvar g; + generate + for (g = 0; g < STRB_WIDTH; g = g + 1) begin : gen_strb + if (g == 0) begin : gen_first + assign strb[g] = 1'b1; + end else begin : gen_rest + assign strb[g] = wdata_i[g*8] ^ wdata_i[g*8+7]; + end + end + endgenerate + + wide_module #( + .DATA_WIDTH(DATA_WIDTH), + .ADDR_WIDTH(ADDR_WIDTH), + .OUTSTANDING_TRANSACTIONS(8), + .ENABLE_ECC(1'b1) + ) u_wide_module_instance_name ( + .clk_i(clk_i), + .rst_ni(rst_ni), + .awaddr_i(awaddr_i), + .wdata_i(wdata_i), + .rdata_o(rdata_o), + .error_o() + ); + + always_ff @(posedge clk_i or negedge rst_ni) begin + if (!rst_ni) state_q <= ST_IDLE; + else state_q <= state_d; + end +endmodule diff --git a/crates/vlog_parser/Cargo.toml b/crates/vlog_parser/Cargo.toml new file mode 100644 index 0000000..9107781 --- /dev/null +++ b/crates/vlog_parser/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "vlog_parser" +version.workspace = true +edition.workspace = true +license.workspace = true +description = "Verilog/SystemVerilog lexer and parser for vfmt" + +[dependencies] diff --git a/crates/vlog_parser/src/ast.rs b/crates/vlog_parser/src/ast.rs new file mode 100644 index 0000000..8595e3e --- /dev/null +++ b/crates/vlog_parser/src/ast.rs @@ -0,0 +1,529 @@ +//! 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. + +use crate::token::Comment; + +#[derive(Debug, Clone, Default)] +pub struct Meta { + pub leading: Vec, + pub trailing: Option, + pub blank_before: bool, + /// Attribute instances `(* ... *)` that preceded the node, verbatim. + pub attrs: Vec, +} + +#[derive(Debug)] +pub struct SourceFile { + pub items: Vec, + /// Comments at the very end of the file. + pub dangling: Vec, +} + +#[derive(Debug)] +pub struct Item { + pub meta: Meta, + pub kind: ItemKind, +} + +#[derive(Debug)] +pub enum ItemKind { + Module(Module), + Package { kw: String, name: String, items: Vec, dangling: Vec }, + Directive(String), + 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)>), +} + +#[derive(Debug)] +pub struct Module { + pub kw: String, + pub name: String, + pub imports: Vec, + pub param_ports: Vec, + pub ports: PortList, + pub items: Vec, + pub dangling: Vec, + pub end_label: Option, +} + +#[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, +} + +#[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, +} + +#[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, +} + +/// 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, +} + +#[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, +} + +#[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, +} + +#[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, +} + +#[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, +} + +#[derive(Debug)] +pub enum SensList { + /// `@*` or `@(*)` + Star, + List(Vec), +} + +#[derive(Debug)] +pub struct SensItem { + pub edge: Option, + pub expr: Expr, +} + +#[derive(Debug)] +pub struct Instantiation { + pub module: String, + pub params: Vec, + pub instances: Vec, +} + +#[derive(Debug)] +pub struct Instance { + pub meta: Meta, + pub name: String, + pub dims: Vec, + pub conns: Connections, +} + +#[derive(Debug)] +pub enum Connections { + Ordered(Vec), + Named(Vec), +} + +#[derive(Debug)] +pub struct OrderedConn { + pub meta: Meta, + pub expr: Option, +} + +#[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, +} + +#[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, +} + +#[derive(Debug)] +pub struct GenIf { + pub cond: Expr, + pub then: GenBlock, + pub els: Option>, +} + +#[derive(Debug)] +pub enum GenElse { + If(Meta, GenIf), + 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`. + pub labels: Vec, + pub body: GenBlock, +} + +/// 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, +} + +#[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, +} + +#[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, +} + +#[derive(Debug)] +pub struct TfArg { + pub meta: Meta, + pub dir: Option, + pub ty: DataType, + pub name: String, + pub unpacked: Vec, + pub default: Option, +} + +#[derive(Debug)] +pub struct Stmt { + pub meta: Meta, + pub kind: StmtKind, +} + +#[derive(Debug)] +pub enum StmtKind { + Block { + label: Option, + stmts: Vec, + dangling: Vec, + }, + ForkJoin { + label: Option, + join_kw: String, + stmts: Vec, + dangling: Vec, + }, + 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(String), + /// Immediate assertion: kept simple — `assert (expr) stmt else stmt;` + Assert { + kw: String, + cond: Expr, + then: Option>, + els: Option>, + }, + Null, +} + +#[derive(Debug)] +pub enum TimingControl { + /// `#expr` + Delay(Expr), + /// `@(...)`, `@*` + Event(SensList), +} + +#[derive(Debug)] +pub struct CaseItem { + pub meta: Meta, + /// Empty means `default`. + pub labels: Vec, + pub stmt: Stmt, +} + +#[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), +} + +#[derive(Debug, Clone)] +pub enum Expr { + Ident(String), + Number(String), + 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 }, + Concat(Vec), + Repl { count: Box, inner: Vec }, + Paren(Box), + /// `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 }, +} + +#[derive(Debug, Clone)] +pub struct PatternItem { + /// `key: value` (key may be `default`, a type, or an expression). + pub key: Option, + pub value: Expr, +} diff --git a/crates/vlog_parser/src/lexer.rs b/crates/vlog_parser/src/lexer.rs new file mode 100644 index 0000000..55f5804 --- /dev/null +++ b/crates/vlog_parser/src/lexer.rs @@ -0,0 +1,659 @@ +//! Hand-written lexer for Verilog/SystemVerilog. +//! +//! The lexer runs in two phases, mirroring how ruff's parser handles trivia: +//! a raw phase that produces every token including comments, and an +//! attachment phase that folds comments into the neighboring "real" tokens as +//! leading/trailing trivia and records blank-line information. The parser and +//! formatter then never have to think about interleaved comment tokens. + +use crate::token::{is_keyword, Comment, Token, TokenKind}; + +#[derive(Debug, Clone)] +pub struct LexError { + pub line: u32, + pub col: u32, + pub message: String, +} + +impl std::fmt::Display for LexError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}: {}", self.line, self.col, self.message) + } +} + +impl std::error::Error for LexError {} + +/// Raw token produced by phase one. Comments are still ordinary tokens here. +struct RawTok { + kind: RawKind, + text: String, + line: u32, + col: u32, + /// Number of newlines seen between the previous raw token and this one. + newlines_before: u32, +} + +#[derive(PartialEq, Eq, Clone, Copy)] +enum RawKind { + Real(TokenKind), + LineComment, + BlockComment, +} + +struct RawLexer<'a> { + src: &'a [u8], + pos: usize, + line: u32, + col: u32, +} + +/// Multi-character operators, longest first so greedy matching works. +const OPERATORS: &[&str] = &[ + "<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "**", "==", "!=", + "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=", "/=", + "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{", +]; + +const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$"; + +impl<'a> RawLexer<'a> { + fn new(src: &'a [u8]) -> Self { + RawLexer { src, pos: 0, line: 1, col: 1 } + } + + fn peek(&self) -> u8 { + *self.src.get(self.pos).unwrap_or(&0) + } + + fn peek_at(&self, offset: usize) -> u8 { + *self.src.get(self.pos + offset).unwrap_or(&0) + } + + fn bump(&mut self) -> u8 { + let c = self.peek(); + self.pos += 1; + if c == b'\n' { + self.line += 1; + self.col = 1; + } else { + self.col += 1; + } + c + } + + fn starts_with(&self, s: &str) -> bool { + self.src[self.pos..].starts_with(s.as_bytes()) + } + + fn text_from(&self, start: usize) -> String { + String::from_utf8_lossy(&self.src[start..self.pos]).into_owned() + } + + /// Skip spaces/tabs/newlines, returning how many newlines were skipped. + fn skip_whitespace(&mut self) -> u32 { + let mut newlines = 0; + while matches!(self.peek(), b' ' | b'\t' | b'\r' | b'\n') { + if self.bump() == b'\n' { + newlines += 1; + } + } + newlines + } + + fn error(&self, message: String) -> LexError { + LexError { line: self.line, col: self.col, message } + } + + fn next_raw(&mut self) -> Result { + let newlines_before = self.skip_whitespace(); + let (line, col) = (self.line, self.col); + let start = self.pos; + + if self.pos >= self.src.len() { + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Eof), + text: String::new(), + line, + col, + newlines_before, + }); + } + + let c = self.peek(); + + // Comments. + if c == b'/' && self.peek_at(1) == b'/' { + while self.pos < self.src.len() && self.peek() != b'\n' { + self.bump(); + } + let text = self.text_from(start).trim_end().to_string(); + return Ok(RawTok { kind: RawKind::LineComment, text, line, col, newlines_before }); + } + if c == b'/' && self.peek_at(1) == b'*' { + self.bump(); + self.bump(); + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated block comment".to_string())); + } + if self.peek() == b'*' && self.peek_at(1) == b'/' { + self.bump(); + self.bump(); + break; + } + self.bump(); + } + let text = self.text_from(start); + return Ok(RawTok { kind: RawKind::BlockComment, text, line, col, newlines_before }); + } + + // Compiler directives: capture through end of line, honoring `\` + // continuations (used by `define). + if c == b'`' { + while self.pos < self.src.len() && self.peek() != b'\n' { + // Stop before a trailing comment on the same line. + if self.peek() == b'/' && (self.peek_at(1) == b'/' || self.peek_at(1) == b'*') { + break; + } + self.bump(); + } + // Line continuation: `define FOO \ + while self.text_ends_with_continuation(start) && self.peek() == b'\n' { + self.bump(); + while self.pos < self.src.len() && self.peek() != b'\n' { + self.bump(); + } + } + let text = self.text_from(start).trim_end().to_string(); + // Short directives like `WIDTH used inside expressions (macro + // usage) should not swallow the rest of the line. Only treat + // known line-oriented directives as raw lines. + let first_word: String = text + .trim_start_matches('`') + .chars() + .take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_') + .collect(); + if is_line_directive(&first_word) { + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Directive), + text, + line, + col, + newlines_before, + }); + } + // Macro usage: rewind and lex just `NAME as an identifier-like + // token so it can appear inside expressions. + self.pos = start; + self.line = line; + self.col = col; + self.bump(); // backtick + while is_ident_char(self.peek()) { + self.bump(); + } + // Macro call with arguments: `NAME(...) — capture balanced parens. + if self.peek() == b'(' { + let mut depth = 0usize; + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated macro call".to_string())); + } + let ch = self.bump(); + if ch == b'(' { + depth += 1; + } else if ch == b')' { + depth -= 1; + if depth == 0 { + break; + } + } + } + } + let text = self.text_from(start); + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Ident), + text, + line, + col, + newlines_before, + }); + } + + // Attribute instance `(* ... *)`. + if c == b'(' && self.peek_at(1) == b'*' && self.peek_at(2) != b')' { + self.bump(); + self.bump(); + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated attribute (* ... *)".to_string())); + } + if self.peek() == b'*' && self.peek_at(1) == b')' { + self.bump(); + self.bump(); + break; + } + self.bump(); + } + let text = self.text_from(start); + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Attribute), + text, + line, + col, + newlines_before, + }); + } + + // String literal. + if c == b'"' { + self.bump(); + loop { + if self.pos >= self.src.len() { + return Err(self.error("unterminated string literal".to_string())); + } + match self.bump() { + b'\\' => { + self.bump(); + } + b'"' => break, + _ => {} + } + } + let text = self.text_from(start); + return Ok(RawTok { + kind: RawKind::Real(TokenKind::String), + text, + line, + col, + newlines_before, + }); + } + + // Escaped identifier: backslash to next whitespace. + if c == b'\\' { + self.bump(); + while self.pos < self.src.len() && !self.peek().is_ascii_whitespace() { + self.bump(); + } + let text = self.text_from(start); + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Ident), + text, + line, + col, + newlines_before, + }); + } + + // System identifier. + if c == b'$' && is_ident_char(self.peek_at(1)) { + self.bump(); + while is_ident_char(self.peek()) { + self.bump(); + } + let text = self.text_from(start); + return Ok(RawTok { + kind: RawKind::Real(TokenKind::SystemIdent), + text, + line, + col, + newlines_before, + }); + } + + // Number literals. + if c.is_ascii_digit() { + let text = self.lex_number()?; + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Number), + text, + line, + col, + newlines_before, + }); + } + + // Based literal without a size (`'hFF`, `'0`, `'x`), but not the + // assignment-pattern opener `'{` or a cast tick `'(`. + if c == b'\'' && is_base_intro(self.peek_at(1)) { + let text = self.lex_based_part()?; + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Number), + text, + line, + col, + newlines_before, + }); + } + + // Identifier or keyword. + if c == b'_' || c.is_ascii_alphabetic() { + while is_ident_char(self.peek()) { + self.bump(); + } + let text = self.text_from(start); + let kind = if is_keyword(&text) { TokenKind::Keyword } else { TokenKind::Ident }; + return Ok(RawTok { kind: RawKind::Real(kind), text, line, col, newlines_before }); + } + + // Operators, longest match first. + for op in OPERATORS { + if self.starts_with(op) { + for _ in 0..op.len() { + self.bump(); + } + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Symbol), + text: (*op).to_string(), + line, + col, + newlines_before, + }); + } + } + if SINGLE_OPS.contains(&c) { + self.bump(); + return Ok(RawTok { + kind: RawKind::Real(TokenKind::Symbol), + text: (c as char).to_string(), + line, + col, + newlines_before, + }); + } + + Err(self.error(format!("unexpected character {:?}", c as char))) + } + + fn text_ends_with_continuation(&self, start: usize) -> bool { + let text = &self.src[start..self.pos]; + let trimmed: &[u8] = { + let mut t = text; + while let Some((&last, rest)) = t.split_last() { + if last == b' ' || last == b'\t' || last == b'\r' { + t = rest; + } else { + break; + } + } + t + }; + trimmed.last() == Some(&b'\\') + } + + /// Lex a number starting at an ASCII digit. Handles plain decimal, real + /// numbers with exponents, sized based literals (`8'hFF`, `4'b10_10`, + /// with optional whitespace around the tick), and time-unit suffixes + /// (`10ns`). The returned text is normalized to contain no whitespace. + fn lex_number(&mut self) -> Result { + let start = self.pos; + while self.peek().is_ascii_digit() || self.peek() == b'_' { + self.bump(); + } + // Real number. + if self.peek() == b'.' && self.peek_at(1).is_ascii_digit() { + self.bump(); + while self.peek().is_ascii_digit() || self.peek() == b'_' { + self.bump(); + } + } + if matches!(self.peek(), b'e' | b'E') + && (self.peek_at(1).is_ascii_digit() + || (matches!(self.peek_at(1), b'+' | b'-') && self.peek_at(2).is_ascii_digit())) + { + self.bump(); + if matches!(self.peek(), b'+' | b'-') { + self.bump(); + } + while self.peek().is_ascii_digit() { + self.bump(); + } + } + let mut text = self.text_from(start); + + // Time unit suffix directly attached (1ns, 2.5us). + if self.peek().is_ascii_alphabetic() { + let unit_start = self.pos; + while self.peek().is_ascii_alphabetic() { + self.bump(); + } + text.push_str(&self.text_from(unit_start)); + return Ok(text); + } + + // Sized based literal: whitespace is allowed around the tick + // (`8 'hFF`); normalize it away. + let save = (self.pos, self.line, self.col); + let mut probe = self.pos; + while matches!(self.src.get(probe), Some(b' ') | Some(b'\t')) { + probe += 1; + } + if self.src.get(probe) == Some(&b'\'') + && probe + 1 < self.src.len() + && is_base_intro(self.src[probe + 1]) + && self.src.get(probe + 1) != Some(&b'{') + { + while self.pos < probe { + self.bump(); + } + match self.lex_based_part() { + Ok(based) => { + text.push_str(&based); + return Ok(text); + } + Err(_) => { + self.pos = save.0; + self.line = save.1; + self.col = save.2; + } + } + } + Ok(text) + } + + /// Lex the `'h FF` / `'b1010` / `'0` part, starting at the tick. + fn lex_based_part(&mut self) -> Result { + 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)) + { + // Unbased unsized literal: '0 '1 'x 'z + self.bump(); + return Ok(self.text_from(start)); + } + let mut text = String::from("'"); + if matches!(self.peek(), b's' | b'S') { + text.push(self.bump() as char); + } + if !matches!(self.peek(), b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H') { + return Err(self.error("expected number base after '".to_string())); + } + text.push(self.bump() as char); + // Whitespace is allowed between base and value. + while matches!(self.peek(), b' ' | b'\t') { + self.bump(); + } + let value_start = self.pos; + while self.peek().is_ascii_alphanumeric() || matches!(self.peek(), b'_' | b'?') { + self.bump(); + } + if self.pos == value_start { + return Err(self.error("expected digits after number base".to_string())); + } + text.push_str(&self.text_from(value_start)); + Ok(text) + } +} + +fn is_ident_char(c: u8) -> bool { + c == b'_' || c == b'$' || c.is_ascii_alphanumeric() +} + +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' + ) +} + +/// Directives that consume the rest of the source line. Anything else that +/// starts with a backtick is treated as a macro usage token. +fn is_line_directive(word: &str) -> bool { + matches!( + word, + "define" + | "undef" + | "undefineall" + | "ifdef" + | "ifndef" + | "elsif" + | "else" + | "endif" + | "include" + | "timescale" + | "default_nettype" + | "resetall" + | "celldefine" + | "endcelldefine" + | "line" + | "pragma" + | "unconnected_drive" + | "nounconnected_drive" + | "begin_keywords" + | "end_keywords" + ) +} + +/// Tokenize source text, attaching comments and blank-line info to tokens. +pub fn tokenize(source: &str) -> Result, LexError> { + let mut raw_lexer = RawLexer::new(source.as_bytes()); + let mut raws: Vec = Vec::new(); + loop { + let tok = raw_lexer.next_raw()?; + let is_eof = tok.kind == RawKind::Real(TokenKind::Eof); + raws.push(tok); + if is_eof { + break; + } + } + + // Attachment phase. + let mut tokens: Vec = Vec::new(); + let mut pending: Vec = Vec::new(); + let mut pending_blank = false; + + 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(); + if same_line_as_prev { + // Trailing comment for the previous real token. + let prev = tokens.last_mut().unwrap(); + match &mut prev.trailing { + Some(existing) => { + existing.push(' '); + existing.push_str(&raw.text); + } + None => prev.trailing = Some(raw.text), + } + } else { + pending.push(Comment { + text: raw.text, + blank_before: raw.newlines_before > 1 || pending_blank, + }); + pending_blank = false; + } + } + RawKind::Real(kind) => { + let blank_before = if pending.is_empty() { + raw.newlines_before > 1 + } else { + // Comments already carry their own blank flags; the token + // is blank-separated only if there was a blank line + // between the last comment and the token itself. + raw.newlines_before > 1 + }; + tokens.push(Token { + kind, + text: raw.text, + line: raw.line, + col: raw.col, + leading: std::mem::take(&mut pending), + trailing: None, + blank_before, + }); + } + } + } + Ok(tokens) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(src: &str) -> Vec<(TokenKind, String)> { + tokenize(src) + .unwrap() + .into_iter() + .map(|t| (t.kind, t.text)) + .collect() + } + + #[test] + fn basic_tokens() { + let toks = kinds("module foo; endmodule"); + assert_eq!(toks[0], (TokenKind::Keyword, "module".to_string())); + assert_eq!(toks[1], (TokenKind::Ident, "foo".to_string())); + assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string())); + assert_eq!(toks[3], (TokenKind::Keyword, "endmodule".to_string())); + } + + #[test] + fn based_literals() { + let toks = kinds("8'hFF 4'b10_10 'd10 32 'shA5 'x 1.5e-3 10ns"); + let texts: Vec<&str> = toks.iter().map(|(_, t)| t.as_str()).collect(); + assert_eq!(texts, ["8'hFF", "4'b10_10", "'d10", "32'shA5", "'x", "1.5e-3", "10ns", ""]); + assert!(toks[..7].iter().all(|(k, _)| *k == TokenKind::Number)); + } + + #[test] + fn trailing_comment_attaches() { + let toks = tokenize("assign x = y; // comment\nwire z;").unwrap(); + let semi = toks.iter().find(|t| t.is_sym(";")).unwrap(); + assert_eq!(semi.trailing.as_deref(), Some("// comment")); + } + + #[test] + fn leading_comment_attaches() { + let toks = tokenize("// header\n\n// second\nmodule m; endmodule").unwrap(); + assert_eq!(toks[0].leading.len(), 2); + assert!(toks[0].leading[1].blank_before); + } + + #[test] + fn directives_and_macros() { + let toks = kinds("`timescale 1ns / 1ps\nwire [`WIDTH-1:0] w;"); + assert_eq!(toks[0], (TokenKind::Directive, "`timescale 1ns / 1ps".to_string())); + assert!(toks.iter().any(|(k, t)| *k == TokenKind::Ident && t == "`WIDTH")); + } + + #[test] + fn attributes() { + let toks = kinds("(* keep = \"true\" *) wire w;"); + assert_eq!(toks[0].0, TokenKind::Attribute); + } + + #[test] + fn operators() { + let toks = kinds("a <<< b === c !== d <= e"); + let texts: Vec<&str> = toks.iter().map(|(_, t)| t.as_str()).collect(); + assert!(texts.contains(&"<<<")); + assert!(texts.contains(&"===")); + assert!(texts.contains(&"!==")); + assert!(texts.contains(&"<=")); + } +} diff --git a/crates/vlog_parser/src/lib.rs b/crates/vlog_parser/src/lib.rs new file mode 100644 index 0000000..92b4db9 --- /dev/null +++ b/crates/vlog_parser/src/lib.rs @@ -0,0 +1,36 @@ +//! Verilog/SystemVerilog lexer and parser. +//! +//! This crate plays the role of `ruff_python_parser` in ruff's architecture: +//! it turns source text into a comment-preserving AST that the formatter +//! crate consumes. + +pub mod ast; +pub mod lexer; +pub mod parser; +pub mod token; + +pub use lexer::{tokenize, LexError}; +pub use parser::{parse, ParseError}; + +/// Convenience: lex and parse in one step. +pub fn parse_source(source: &str) -> Result { + let tokens = tokenize(source).map_err(Error::Lex)?; + parse(tokens).map_err(Error::Parse) +} + +#[derive(Debug)] +pub enum Error { + Lex(LexError), + Parse(ParseError), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::Lex(e) => write!(f, "lex error: {e}"), + Error::Parse(e) => write!(f, "parse error: {e}"), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/vlog_parser/src/parser.rs b/crates/vlog_parser/src/parser.rs new file mode 100644 index 0000000..50b9ce1 --- /dev/null +++ b/crates/vlog_parser/src/parser.rs @@ -0,0 +1,1948 @@ +//! Recursive-descent parser producing the AST in [`crate::ast`]. +//! +//! Comment plumbing: [`Parser::bump`] moves any leading comments of a +//! consumed token into `pending_leading` and its trailing comment into +//! `pending_trailing`. Statements/items/list elements harvest those at +//! well-defined points; anything left over is folded into the next node's +//! leading comments so no comment is ever dropped. + +use crate::ast::*; +use crate::token::{Comment, Token, TokenKind}; + +#[derive(Debug, Clone)] +pub struct ParseError { + pub line: u32, + pub col: u32, + pub message: String, +} + +impl std::fmt::Display for ParseError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}: {}", self.line, self.col, self.message) + } +} + +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", +]; + +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", + "notif1", "pullup", "pulldown", "cmos", "rcmos", "nmos", "pmos", "rnmos", "rpmos", "tran", + "rtran", "tranif0", "tranif1", "rtranif0", "rtranif1", +]; + +const ASSIGN_OPS: &[&str] = &[ + "=", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "<<=", ">>=", "<<<=", ">>>=", +]; + +pub struct Parser { + tokens: Vec, + pos: usize, + pending_leading: Vec, + pending_trailing: Vec, +} + +pub fn parse(tokens: Vec) -> PResult { + let mut p = Parser { tokens, pos: 0, pending_leading: Vec::new(), pending_trailing: Vec::new() }; + p.parse_source_file() +} + +impl Parser { + fn cur(&self) -> &Token { + &self.tokens[self.pos] + } + + fn nth(&self, n: usize) -> &Token { + let i = (self.pos + n).min(self.tokens.len() - 1); + &self.tokens[i] + } + + fn at_eof(&self) -> bool { + self.cur().kind == TokenKind::Eof + } + + fn bump(&mut self) -> Token { + let mut t = self.tokens[self.pos].clone(); + if self.pos + 1 < self.tokens.len() { + self.pos += 1; + } + if !t.leading.is_empty() { + self.pending_leading.append(&mut t.leading); + } + if let Some(tr) = t.trailing.take() { + self.pending_trailing.push(tr); + } + t + } + + fn error(&self, message: impl Into) -> PResult { + let t = self.cur(); + let shown = if t.kind == TokenKind::Eof { "" } else { t.text.as_str() }; + Err(ParseError { + line: t.line, + col: t.col, + message: format!("{} (found {:?})", message.into(), shown), + }) + } + + fn expect_sym(&mut self, sym: &str) -> PResult { + if self.cur().is_sym(sym) { + Ok(self.bump()) + } else { + self.error(format!("expected `{sym}`")) + } + } + + fn expect_kw(&mut self, kw: &str) -> PResult { + if self.cur().is_kw(kw) { + Ok(self.bump()) + } else { + self.error(format!("expected `{kw}`")) + } + } + + fn expect_ident(&mut self) -> PResult { + if self.cur().kind == TokenKind::Ident { + Ok(self.bump().text) + } else { + self.error("expected identifier") + } + } + + fn eat_sym(&mut self, sym: &str) -> bool { + if self.cur().is_sym(sym) { + self.bump(); + true + } else { + false + } + } + + fn eat_kw(&mut self, kw: &str) -> bool { + if self.cur().is_kw(kw) { + self.bump(); + true + } else { + false + } + } + + /// Start a new node: gather pending + current-token leading comments. + fn take_meta(&mut self) -> Meta { + let mut leading: Vec = Vec::new(); + // Unharvested trailing comments from earlier tokens become leading + // comments here so they are never lost. + for tr in self.pending_trailing.drain(..) { + leading.push(Comment { text: tr, blank_before: false }); + } + leading.append(&mut self.pending_leading); + let tok = &mut self.tokens[self.pos]; + leading.append(&mut tok.leading); + let blank_before = + leading.first().map(|c| c.blank_before).unwrap_or(self.tokens[self.pos].blank_before); + Meta { leading, trailing: None, blank_before, attrs: Vec::new() } + } + + /// Harvest trailing comments accumulated since the last harvest. + fn take_trailing(&mut self) -> Option { + if self.pending_trailing.is_empty() { + None + } else { + Some(self.pending_trailing.drain(..).collect::>().join(" ")) + } + } + + /// Comments sitting right before a closing keyword (`end`, `endmodule`, + /// ...) — they belong inside the enclosing construct. + fn take_dangling(&mut self) -> Vec { + let mut out: Vec = Vec::new(); + for tr in self.pending_trailing.drain(..) { + out.push(Comment { text: tr, blank_before: false }); + } + out.append(&mut self.pending_leading); + let tok = &mut self.tokens[self.pos]; + out.append(&mut tok.leading); + out + } + + /// Given `self.tokens[i]` == an opening bracket, return the index just + /// past its matching close. Used for disambiguating lookahead only. + fn scan_matching(&self, mut i: usize, open: &str, close: &str) -> usize { + let mut depth = 0usize; + while i < self.tokens.len() { + let t = &self.tokens[i]; + if t.kind == TokenKind::Eof { + return i; + } + if t.is_sym(open) { + depth += 1; + } else if t.is_sym(close) { + depth -= 1; + if depth == 0 { + return i + 1; + } + } + i += 1; + } + i + } + + // ------------------------------------------------------------------ + // Top level + // ------------------------------------------------------------------ + + fn parse_source_file(&mut self) -> PResult { + let mut items = Vec::new(); + while !self.at_eof() { + items.push(self.parse_item()?); + } + let dangling = self.take_dangling(); + Ok(SourceFile { items, dangling }) + } + + fn parse_item(&mut self) -> PResult { + let mut meta = self.take_meta(); + while self.cur().kind == TokenKind::Attribute { + meta.attrs.push(self.bump().text); + let tok = &mut self.tokens[self.pos]; + meta.leading.append(&mut tok.leading); + } + let kind = self.parse_item_kind()?; + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(Item { meta, kind }) + } + + fn parse_item_kind(&mut self) -> PResult { + let t = self.cur(); + match t.kind { + TokenKind::Directive => Ok(ItemKind::Directive(self.bump().text)), + TokenKind::Keyword => self.parse_keyword_item(), + TokenKind::Ident => self.parse_ident_item(), + _ => self.error("expected item"), + } + } + + fn parse_keyword_item(&mut self) -> PResult { + let kw = self.cur().text.clone(); + match kw.as_str() { + "module" | "macromodule" => self.parse_module().map(ItemKind::Module), + "package" => self.parse_package(), + "import" => { + let paths = self.parse_import_list()?; + Ok(ItemKind::Import(paths)) + } + "timeunit" | "timeprecision" => { + let mut parts: Vec = Vec::new(); + while !self.cur().is_sym(";") && !self.at_eof() { + parts.push(self.bump().text); + } + self.expect_sym(";")?; + Ok(ItemKind::Timeunit(parts.join(" "))) + } + "typedef" => self.parse_typedef().map(ItemKind::Typedef), + "parameter" | "localparam" => { + let d = self.parse_param_decl()?; + self.expect_sym(";")?; + Ok(ItemKind::ParamDecl(d)) + } + "input" | "output" | "inout" => { + let d = self.parse_port_decl()?; + Ok(ItemKind::PortDecl(d)) + } + "genvar" => { + self.bump(); + let mut names = vec![self.expect_ident()?]; + while self.eat_sym(",") { + names.push(self.expect_ident()?); + } + self.expect_sym(";")?; + Ok(ItemKind::Genvar(names)) + } + "assign" => self.parse_cont_assign().map(ItemKind::ContAssign), + "always" | "always_comb" | "always_ff" | "always_latch" => { + let kw = self.bump().text; + let stmt = self.parse_stmt()?; + Ok(ItemKind::Always { kw, stmt }) + } + "initial" => { + self.bump(); + Ok(ItemKind::Initial(self.parse_stmt()?)) + } + "final" => { + self.bump(); + Ok(ItemKind::Final(self.parse_stmt()?)) + } + "generate" => { + self.bump(); + let mut items = Vec::new(); + while !self.cur().is_kw("endgenerate") && !self.at_eof() { + items.push(self.parse_item()?); + } + let dangling = self.take_dangling(); + self.expect_kw("endgenerate")?; + Ok(ItemKind::GenerateRegion { items, dangling }) + } + "if" => self.parse_gen_if().map(ItemKind::GenIf), + "for" => self.parse_gen_for().map(ItemKind::GenFor), + "case" => self.parse_gen_case().map(ItemKind::GenCase), + "function" => self.parse_function().map(ItemKind::Function), + "task" => self.parse_task().map(ItemKind::Task), + "defparam" => { + self.bump(); + let mut pairs = Vec::new(); + loop { + let lhs = self.parse_expr()?; + self.expect_sym("=")?; + let rhs = self.parse_expr()?; + pairs.push((lhs, rhs)); + if !self.eat_sym(",") { + break; + } + } + self.expect_sym(";")?; + Ok(ItemKind::Defparam(pairs)) + } + _ if GATE_KEYWORDS.contains(&kw.as_str()) => { + self.parse_gate_instantiation().map(ItemKind::GateInstantiation) + } + _ if NET_KEYWORDS.contains(&kw.as_str()) + || TYPE_KEYWORDS.contains(&kw.as_str()) + || matches!(kw.as_str(), "var" | "automatic" | "static" | "const" | "signed" + | "unsigned") => + { + let d = self.parse_data_decl()?; + Ok(ItemKind::DataDecl(d)) + } + _ => self.error(format!("unsupported construct starting with keyword `{kw}`")), + } + } + + /// Item starting with an identifier: either a module instantiation or a + /// declaration with a user-defined type. + fn parse_ident_item(&mut self) -> PResult { + // Skip over a package scope chain for lookahead purposes. + let mut p = self.pos; + while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) { + p += 2; + } + let t1 = self.nth(p + 1 - self.pos); + if t1.is_sym("#") { + return self.parse_instantiation().map(ItemKind::Instantiation); + } + if t1.kind == TokenKind::Ident { + let t2 = self.nth(p + 2 - self.pos); + if t2.is_sym("(") { + return self.parse_instantiation().map(ItemKind::Instantiation); + } + if t2.is_sym("[") { + let after = self.scan_matching(p + 2, "[", "]"); + if self.tokens.get(after).is_some_and(|t| t.is_sym("(")) { + return self.parse_instantiation().map(ItemKind::Instantiation); + } + } + return self.parse_data_decl().map(ItemKind::DataDecl); + } + if t1.is_sym("[") { + return self.parse_data_decl().map(ItemKind::DataDecl); + } + self.error("expected declaration or instantiation") + } + + fn parse_package(&mut self) -> PResult { + let kw = self.bump().text; + let name = self.expect_ident()?; + self.expect_sym(";")?; + let mut items = Vec::new(); + while !self.cur().is_kw("endpackage") && !self.at_eof() { + items.push(self.parse_item()?); + } + let dangling = self.take_dangling(); + self.expect_kw("endpackage")?; + if self.eat_sym(":") { + self.expect_ident()?; + } + Ok(ItemKind::Package { kw, name, items, dangling }) + } + + fn parse_import_list(&mut self) -> PResult> { + self.expect_kw("import")?; + let mut paths = Vec::new(); + loop { + let pkg = self.expect_ident()?; + self.expect_sym("::")?; + let sym = if self.eat_sym("*") { "*".to_string() } else { self.expect_ident()? }; + paths.push(format!("{pkg}::{sym}")); + if !self.eat_sym(",") { + break; + } + } + self.expect_sym(";")?; + Ok(paths) + } + + // ------------------------------------------------------------------ + // Module + // ------------------------------------------------------------------ + + fn parse_module(&mut self) -> PResult { + let kw = self.bump().text; + let name = self.expect_ident()?; + let mut imports = Vec::new(); + while self.cur().is_kw("import") { + imports.extend(self.parse_import_list()?); + } + let mut param_ports = Vec::new(); + if self.cur().is_sym("#") { + self.bump(); + self.expect_sym("(")?; + if !self.cur().is_sym(")") { + loop { + param_ports.push(self.parse_param_port()?); + if !self.eat_sym(",") { + break; + } + if let Some(last) = param_ports.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + } + } + self.expect_sym(")")?; + } + let ports = self.parse_port_list()?; + self.expect_sym(";")?; + let mut items = Vec::new(); + while !self.cur().is_kw("endmodule") && !self.at_eof() { + items.push(self.parse_item()?); + } + let dangling = self.take_dangling(); + self.expect_kw("endmodule")?; + let end_label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + Ok(Module { kw, name, imports, param_ports, ports, items, dangling, end_label }) + } + + fn parse_param_port(&mut self) -> PResult { + let mut meta = self.take_meta(); + let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") { + Some(self.bump().text) + } else { + None + }; + if self.eat_kw("type") { + let name = self.expect_ident()?; + let default = if self.eat_sym("=") { Some(self.parse_type_expr()?) } else { None }; + meta.trailing = self.take_trailing(); + return Ok(ParamPort { + meta, + kw, + ty: DataType::default(), + is_type: true, + name, + unpacked: Vec::new(), + default, + }); + } + let ty = self.parse_opt_data_type()?; + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + meta.trailing = self.take_trailing(); + Ok(ParamPort { meta, kw, ty, is_type: false, name, unpacked, default }) + } + + fn parse_port_list(&mut self) -> PResult { + if !self.cur().is_sym("(") { + return Ok(PortList::None); + } + self.bump(); + if self.cur().is_sym(")") { + self.bump(); + return Ok(PortList::Empty); + } + let ansi = { + let t = self.cur(); + t.is_kw("input") + || t.is_kw("output") + || t.is_kw("inout") + || t.is_kw("ref") + || TYPE_KEYWORDS.contains(&t.text.as_str()) + || NET_KEYWORDS.contains(&t.text.as_str()) + }; + if ansi { + let mut ports = Vec::new(); + loop { + ports.push(self.parse_ansi_port()?); + if !self.eat_sym(",") { + break; + } + if let Some(last) = ports.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + } + self.expect_sym(")")?; + // A trailing comment on the closing line belongs to the last port. + if let Some(last) = ports.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + Ok(PortList::Ansi(ports)) + } else { + let mut ports = Vec::new(); + loop { + let mut meta = self.take_meta(); + let name = self.expect_ident()?; + let more = self.eat_sym(","); + meta.trailing = self.take_trailing(); + ports.push(NonAnsiPort { meta, name }); + if !more { + break; + } + } + self.expect_sym(")")?; + Ok(PortList::NonAnsi(ports)) + } + } + + fn parse_ansi_port(&mut self) -> PResult { + let mut meta = self.take_meta(); + let dir = { + let t = self.cur(); + if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") { + Some(self.bump().text) + } else { + None + } + }; + let net = if NET_KEYWORDS.contains(&self.cur().text.as_str()) + && self.cur().kind == TokenKind::Keyword + { + Some(self.bump().text) + } else if self.cur().is_kw("var") { + Some(self.bump().text) + } else { + None + }; + let ty = self.parse_opt_data_type()?; + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + meta.trailing = self.take_trailing(); + Ok(AnsiPort { meta, dir, net, ty, name, unpacked, default }) + } + + /// Parse a possibly-implicit data type. Stops before the declarator name. + fn parse_opt_data_type(&mut self) -> PResult { + let mut ty = DataType::default(); + let t = self.cur(); + if t.kind == TokenKind::Keyword && TYPE_KEYWORDS.contains(&t.text.as_str()) { + ty.name = self.bump().text; + } else if t.kind == TokenKind::Ident { + // User-defined type only if what follows still leaves an + // identifier for the declarator name. + let mut p = self.pos; + while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) { + p += 2; + } + let next = p + 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()?; + while self.cur().is_sym("::") { + self.bump(); + name.push_str("::"); + name.push_str(&self.expect_ident()?); + } + ty.name = name; + } + } + if self.cur().is_kw("signed") || self.cur().is_kw("unsigned") { + ty.signing = Some(self.bump().text); + } + ty.packed = self.parse_dims()?; + Ok(ty) + } + + fn parse_dims(&mut self) -> PResult> { + let mut dims = Vec::new(); + while self.cur().is_sym("[") { + self.bump(); + let a = self.parse_expr()?; + let b = if self.eat_sym(":") { Some(self.parse_expr()?) } else { None }; + self.expect_sym("]")?; + dims.push(Dim { a, b }); + } + Ok(dims) + } + + fn parse_type_expr(&mut self) -> PResult { + let ty = self.parse_opt_data_type()?; + if ty.is_implicit() { + // Fall back: a plain identifier type (e.g. `= my_type_t`). + let name = self.expect_ident()?; + let mut t = DataType { name, ..DataType::default() }; + t.packed = self.parse_dims()?; + return Ok(Expr::Type(t)); + } + Ok(Expr::Type(ty)) + } + + // ------------------------------------------------------------------ + // Declarations + // ------------------------------------------------------------------ + + fn parse_param_decl(&mut self) -> PResult { + let kw = self.bump().text; + let ty = self.parse_opt_data_type()?; + let declarators = self.parse_declarators()?; + Ok(ParamDecl { kw, ty, declarators }) + } + + /// Parse declarators up to (but not consuming) the terminating `;`. + fn parse_declarators(&mut self) -> PResult> { + let mut out = Vec::new(); + loop { + let mut meta = self.take_meta(); + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + let init = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + out.push(Declarator { meta, name, unpacked, init }); + if !more { + break; + } + } + Ok(out) + } + + fn parse_data_decl(&mut self) -> PResult { + let mut net = None; + let mut qualifiers = Vec::new(); + loop { + 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") + || t.is_kw("const") + { + qualifiers.push(self.bump().text); + } else { + break; + } + } + let delay = if net.is_some() && self.cur().is_sym("#") { + self.bump(); + Some(self.parse_delay_value()?) + } else { + None + }; + let ty = self.parse_opt_data_type()?; + let declarators = self.parse_declarators()?; + self.expect_sym(";")?; + Ok(DataDecl { net, delay, qualifiers, ty, declarators }) + } + + fn parse_port_decl(&mut self) -> PResult { + let dir = self.bump().text; + let net = if NET_KEYWORDS.contains(&self.cur().text.as_str()) + && self.cur().kind == TokenKind::Keyword + { + Some(self.bump().text) + } else if self.cur().is_kw("var") { + Some(self.bump().text) + } else { + None + }; + let ty = self.parse_opt_data_type()?; + let declarators = self.parse_declarators()?; + self.expect_sym(";")?; + Ok(PortDecl { dir, net, ty, declarators }) + } + + fn parse_typedef(&mut self) -> PResult { + self.expect_kw("typedef")?; + if self.cur().is_kw("enum") { + self.bump(); + 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(); + loop { + let mut meta = self.take_meta(); + let name = self.expect_ident()?; + // Enum member ranges (`VAL[4]`) are rare; unsupported. + let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let more = self.eat_sym(","); + meta.trailing = self.take_trailing(); + members.push(EnumMember { meta, name, value }); + if !more { + break; + } + } + let dangling = self.take_dangling(); + self.expect_sym("}")?; + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + self.expect_sym(";")?; + return Ok(Typedef { + name, + unpacked, + kind: TypedefKind::Enum(EnumType { base, members, dangling }), + }); + } + if self.cur().is_kw("struct") || self.cur().is_kw("union") { + 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 mut meta = self.take_meta(); + let ty = self.parse_opt_data_type()?; + let declarators = self.parse_declarators()?; + self.expect_sym(";")?; + meta.trailing = self.take_trailing(); + members.push(StructMember { meta, ty, declarators }); + } + let dangling = self.take_dangling(); + self.expect_sym("}")?; + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + self.expect_sym(";")?; + return Ok(Typedef { + name, + unpacked, + kind: TypedefKind::Struct(StructType { kw, packed, signing, members, dangling }), + }); + } + let ty = self.parse_opt_data_type()?; + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + self.expect_sym(";")?; + Ok(Typedef { name, unpacked, kind: TypedefKind::Alias(ty) }) + } + + // ------------------------------------------------------------------ + // Module items + // ------------------------------------------------------------------ + + fn parse_cont_assign(&mut self) -> PResult { + self.expect_kw("assign")?; + let delay = if self.cur().is_sym("#") { + self.bump(); + Some(self.parse_delay_value()?) + } else { + None + }; + let mut assigns = Vec::new(); + loop { + let mut meta = self.take_meta(); + let lhs = self.parse_unary()?; + self.expect_sym("=")?; + let rhs = self.parse_expr()?; + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + assigns.push(AssignPair { meta, lhs, rhs }); + if !more { + break; + } + } + self.expect_sym(";")?; + Ok(ContAssign { delay, assigns }) + } + + fn parse_delay_value(&mut self) -> PResult { + if self.cur().is_sym("(") { + self.bump(); + let first = self.parse_expr()?; + let expr = if self.eat_sym(":") { + let typ = self.parse_expr()?; + self.expect_sym(":")?; + let max = self.parse_expr()?; + Expr::MinTypMax { min: Box::new(first), typ: Box::new(typ), max: Box::new(max) } + } else { + first + }; + self.expect_sym(")")?; + Ok(Expr::Paren(Box::new(expr))) + } else { + self.parse_primary() + } + } + + fn parse_instantiation(&mut self) -> PResult { + let mut module = self.expect_ident()?; + while self.cur().is_sym("::") { + self.bump(); + module.push_str("::"); + module.push_str(&self.expect_ident()?); + } + let mut params = Vec::new(); + if self.cur().is_sym("#") { + self.bump(); + self.expect_sym("(")?; + if !self.cur().is_sym(")") { + loop { + params.push(self.parse_connection()?); + if !self.eat_sym(",") { + break; + } + if let Some(last) = params.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + } + } + self.expect_sym(")")?; + } + let mut instances = Vec::new(); + loop { + let mut meta = self.take_meta(); + let name = self.expect_ident()?; + let dims = self.parse_dims()?; + self.expect_sym("(")?; + let conns = self.parse_connections()?; + self.expect_sym(")")?; + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + instances.push(Instance { meta, name, dims, conns }); + if !more { + break; + } + } + self.expect_sym(";")?; + Ok(Instantiation { module, params, instances }) + } + + fn parse_connections(&mut self) -> PResult { + if self.cur().is_sym(")") { + return Ok(Connections::Ordered(Vec::new())); + } + if self.cur().is_sym(".") { + let mut conns = Vec::new(); + loop { + conns.push(self.parse_connection()?); + if !self.eat_sym(",") { + break; + } + if let Some(last) = conns.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + } + // Comment on the closing-paren line belongs to the last conn. + if let Some(last) = conns.last_mut() { + if last.meta.trailing.is_none() { + last.meta.trailing = self.take_trailing(); + } + } + Ok(Connections::Named(conns)) + } else { + let mut conns = Vec::new(); + loop { + let meta = self.take_meta(); + let expr = if self.cur().is_sym(",") || self.cur().is_sym(")") { + None + } else { + Some(self.parse_expr()?) + }; + let more = self.eat_sym(","); + let mut meta = meta; + if more { + meta.trailing = self.take_trailing(); + } + conns.push(OrderedConn { meta, expr }); + if !more { + break; + } + } + Ok(Connections::Ordered(conns)) + } + } + + /// `.name(expr)`, `.name()`, `.name`, `.*`, or (for parameter lists and + /// ordered parameter overrides) a bare expression. + fn parse_connection(&mut self) -> PResult { + let mut meta = self.take_meta(); + if self.eat_sym(".") { + if self.eat_sym("*") { + return Ok(Connection { meta, name: "*".to_string(), expr: None }); + } + let name = self.expect_ident()?; + let expr = if self.eat_sym("(") { + if self.eat_sym(")") { + Some(Expr::Empty) + } else { + let e = self.parse_expr_or_type()?; + self.expect_sym(")")?; + Some(e) + } + } else { + None + }; + meta.trailing = self.take_trailing(); + Ok(Connection { meta, name, expr }) + } else { + let e = self.parse_expr_or_type()?; + meta.trailing = self.take_trailing(); + Ok(Connection { meta, name: String::new(), expr: Some(e) }) + } + } + + /// In parameter connections a value may be a type (`.T(logic [7:0])`). + fn parse_expr_or_type(&mut self) -> PResult { + let t = self.cur(); + if t.kind == TokenKind::Keyword + && TYPE_KEYWORDS.contains(&t.text.as_str()) + && !self.nth(1).is_sym("'") + { + return self.parse_type_expr(); + } + self.parse_expr() + } + + fn parse_gate_instantiation(&mut self) -> PResult { + let gate = self.bump().text; + let delay = if self.cur().is_sym("#") { + self.bump(); + Some(self.parse_delay_value()?) + } else { + None + }; + let mut instances = Vec::new(); + loop { + let mut meta = self.take_meta(); + let name = + if self.cur().kind == TokenKind::Ident { Some(self.bump().text) } else { None }; + self.expect_sym("(")?; + let mut args = Vec::new(); + if !self.cur().is_sym(")") { + loop { + args.push(self.parse_expr()?); + if !self.eat_sym(",") { + break; + } + } + } + self.expect_sym(")")?; + let more = self.eat_sym(","); + if more { + meta.trailing = self.take_trailing(); + } + instances.push(GateInstance { meta, name, args }); + if !more { + break; + } + } + self.expect_sym(";")?; + Ok(GateInstantiation { gate, delay, instances }) + } + + // ------------------------------------------------------------------ + // Generate constructs + // ------------------------------------------------------------------ + + fn parse_gen_if(&mut self) -> PResult { + self.expect_kw("if")?; + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + let then = self.parse_gen_block()?; + let els = if self.cur().is_kw("else") { + let meta = self.take_meta(); + self.bump(); + if self.cur().is_kw("if") { + Some(Box::new(GenElse::If(meta, self.parse_gen_if()?))) + } else { + let _ = meta; + Some(Box::new(GenElse::Block(self.parse_gen_block()?))) + } + } else { + None + }; + Ok(GenIf { cond, then, els }) + } + + fn parse_gen_for(&mut self) -> PResult { + self.expect_kw("for")?; + self.expect_sym("(")?; + let init_genvar = self.eat_kw("genvar"); + let lhs = self.parse_unary()?; + self.expect_sym("=")?; + let rhs = self.parse_expr()?; + let init = SimpleAssign { lhs, op: "=".to_string(), rhs }; + self.expect_sym(";")?; + let cond = self.parse_expr()?; + self.expect_sym(";")?; + let step = self.parse_for_step()?; + self.expect_sym(")")?; + let body = self.parse_gen_block()?; + Ok(GenFor { init, init_genvar, cond, step, body }) + } + + fn parse_gen_case(&mut self) -> PResult { + self.expect_kw("case")?; + self.expect_sym("(")?; + let expr = self.parse_expr()?; + self.expect_sym(")")?; + let mut items = Vec::new(); + while !self.cur().is_kw("endcase") && !self.at_eof() { + let mut meta = self.take_meta(); + let labels = if self.eat_kw("default") { + let _ = self.eat_sym(":"); + Vec::new() + } else { + let mut labels = vec![self.parse_expr()?]; + while self.eat_sym(",") { + labels.push(self.parse_expr()?); + } + self.expect_sym(":")?; + labels + }; + let body = self.parse_gen_block()?; + meta.trailing = self.take_trailing(); + items.push(GenCaseItem { meta, labels, body }); + } + let dangling = self.take_dangling(); + self.expect_kw("endcase")?; + Ok(GenCase { expr, items, dangling }) + } + + fn parse_gen_block(&mut self) -> PResult { + if self.cur().is_kw("begin") { + self.bump(); + let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + let mut items = Vec::new(); + while !self.cur().is_kw("end") && !self.at_eof() { + items.push(self.parse_item()?); + } + let dangling = self.take_dangling(); + self.expect_kw("end")?; + if self.eat_sym(":") { + self.expect_ident()?; + } + Ok(GenBlock { label, is_block: true, items, dangling }) + } else { + let item = self.parse_item()?; + Ok(GenBlock { label: None, is_block: false, items: vec![item], dangling: Vec::new() }) + } + } + + // ------------------------------------------------------------------ + // Functions and tasks + // ------------------------------------------------------------------ + + fn parse_function(&mut self) -> PResult { + self.expect_kw("function")?; + let mut qualifiers = Vec::new(); + while self.cur().is_kw("automatic") || self.cur().is_kw("static") { + qualifiers.push(self.bump().text); + } + // Return type: everything up to the identifier followed by `(` or `;`. + let ret = { + let t = self.cur(); + if t.kind == TokenKind::Ident && (self.nth(1).is_sym("(") || self.nth(1).is_sym(";")) { + None + } else { + let ty = self.parse_opt_data_type()?; + if ty.is_implicit() { + None + } else { + Some(ty) + } + } + }; + let name = self.expect_ident()?; + let has_parens = self.cur().is_sym("("); + let args = self.parse_tf_ports()?; + self.expect_sym(";")?; + let (stmts, dangling) = self.parse_tf_body("endfunction")?; + Ok(FunctionDecl { qualifiers, ret, name, has_parens, args, stmts, dangling }) + } + + fn parse_task(&mut self) -> PResult { + self.expect_kw("task")?; + let mut qualifiers = Vec::new(); + while self.cur().is_kw("automatic") || self.cur().is_kw("static") { + qualifiers.push(self.bump().text); + } + let name = self.expect_ident()?; + let has_parens = self.cur().is_sym("("); + let args = self.parse_tf_ports()?; + self.expect_sym(";")?; + let (stmts, dangling) = self.parse_tf_body("endtask")?; + Ok(TaskDecl { qualifiers, name, has_parens, args, stmts, dangling }) + } + + fn parse_tf_ports(&mut self) -> PResult> { + let mut args = Vec::new(); + if !self.cur().is_sym("(") { + return Ok(args); + } + self.bump(); + if self.eat_sym(")") { + return Ok(args); + } + loop { + let mut meta = self.take_meta(); + let dir = { + let t = self.cur(); + if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") { + Some(self.bump().text) + } else { + None + } + }; + let ty = self.parse_opt_data_type()?; + let name = self.expect_ident()?; + let unpacked = self.parse_dims()?; + let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; + let more = self.eat_sym(","); + meta.trailing = self.take_trailing(); + args.push(TfArg { meta, dir, ty, name, unpacked, default }); + if !more { + break; + } + } + self.expect_sym(")")?; + Ok(args) + } + + fn parse_tf_body(&mut self, end_kw: &str) -> PResult<(Vec, Vec)> { + let mut stmts = Vec::new(); + while !self.cur().is_kw(end_kw) && !self.at_eof() { + stmts.push(self.parse_stmt()?); + } + let dangling = self.take_dangling(); + self.expect_kw(end_kw)?; + if self.eat_sym(":") { + self.expect_ident()?; + } + Ok((stmts, dangling)) + } + + // ------------------------------------------------------------------ + // Statements + // ------------------------------------------------------------------ + + fn parse_stmt(&mut self) -> PResult { + let mut meta = self.take_meta(); + while self.cur().kind == TokenKind::Attribute { + meta.attrs.push(self.bump().text); + let tok = &mut self.tokens[self.pos]; + meta.leading.append(&mut tok.leading); + } + let kind = self.parse_stmt_kind()?; + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + Ok(Stmt { meta, kind }) + } + + fn parse_stmt_kind(&mut self) -> PResult { + let t = self.cur(); + if t.kind == TokenKind::Directive { + return Ok(StmtKind::Directive(self.bump().text)); + } + if t.is_sym(";") { + self.bump(); + return Ok(StmtKind::Null); + } + if t.is_sym("#") { + self.bump(); + let delay = self.parse_delay_value()?; + let stmt = if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) }; + return Ok(StmtKind::Timing { control: TimingControl::Delay(delay), stmt }); + } + if t.is_sym("@") { + self.bump(); + let sens = self.parse_sens_list()?; + let stmt = if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) }; + return Ok(StmtKind::Timing { control: TimingControl::Event(sens), stmt }); + } + if t.is_sym("->") { + self.bump(); + let e = self.parse_unary()?; + self.expect_sym(";")?; + return Ok(StmtKind::EventTrigger(e)); + } + if t.kind == TokenKind::Keyword { + return self.parse_keyword_stmt(); + } + // Fallback: assignment or expression statement. + self.parse_assign_or_expr_stmt() + } + + fn parse_keyword_stmt(&mut self) -> PResult { + let kw = self.cur().text.clone(); + match kw.as_str() { + "begin" => { + self.bump(); + let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + let mut stmts = Vec::new(); + while !self.cur().is_kw("end") && !self.at_eof() { + stmts.push(self.parse_stmt()?); + } + let dangling = self.take_dangling(); + self.expect_kw("end")?; + if self.eat_sym(":") { + self.expect_ident()?; + } + Ok(StmtKind::Block { label, stmts, dangling }) + } + "fork" => { + self.bump(); + let label = if self.eat_sym(":") { Some(self.expect_ident()?) } else { None }; + let mut stmts = Vec::new(); + while !self.at_eof() + && !(self.cur().is_kw("join") + || self.cur().is_kw("join_any") + || self.cur().is_kw("join_none")) + { + stmts.push(self.parse_stmt()?); + } + let dangling = self.take_dangling(); + let join_kw = self.bump().text; + if self.eat_sym(":") { + self.expect_ident()?; + } + Ok(StmtKind::ForkJoin { label, join_kw, stmts, dangling }) + } + "unique" | "unique0" | "priority" => { + let qualifier = Some(self.bump().text); + if self.cur().is_kw("if") { + self.parse_if_stmt(qualifier) + } else { + self.parse_case_stmt(qualifier) + } + } + "if" => self.parse_if_stmt(None), + "case" | "casex" | "casez" => self.parse_case_stmt(None), + "for" => { + self.bump(); + self.expect_sym("(")?; + let mut init = Vec::new(); + if !self.cur().is_sym(";") { + loop { + let ty = { + let t = self.cur(); + if t.kind == TokenKind::Keyword + && TYPE_KEYWORDS.contains(&t.text.as_str()) + { + Some(self.parse_opt_data_type()?) + } else { + None + } + }; + let lhs = self.parse_unary()?; + self.expect_sym("=")?; + let rhs = self.parse_expr()?; + init.push(ForInit { + ty, + assign: SimpleAssign { lhs, op: "=".to_string(), rhs }, + }); + if !self.eat_sym(",") { + break; + } + } + } + self.expect_sym(";")?; + let cond = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; + self.expect_sym(";")?; + let mut step = Vec::new(); + if !self.cur().is_sym(")") { + step.push(self.parse_for_step()?); + while self.eat_sym(",") { + step.push(self.parse_for_step()?); + } + } + self.expect_sym(")")?; + let body = Box::new(self.parse_stmt()?); + Ok(StmtKind::For { init, cond, step, body }) + } + "while" => { + self.bump(); + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + Ok(StmtKind::While { cond, body: Box::new(self.parse_stmt()?) }) + } + "do" => { + self.bump(); + let body = Box::new(self.parse_stmt()?); + self.expect_kw("while")?; + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + self.expect_sym(";")?; + Ok(StmtKind::DoWhile { body, cond }) + } + "repeat" => { + self.bump(); + self.expect_sym("(")?; + let count = self.parse_expr()?; + self.expect_sym(")")?; + Ok(StmtKind::Repeat { count, body: Box::new(self.parse_stmt()?) }) + } + "forever" => { + self.bump(); + Ok(StmtKind::Forever { body: Box::new(self.parse_stmt()?) }) + } + "foreach" => { + self.bump(); + self.expect_sym("(")?; + let mut name = self.expect_ident()?; + while self.cur().is_sym(".") { + self.bump(); + name.push('.'); + name.push_str(&self.expect_ident()?); + } + self.expect_sym("[")?; + let mut vars = Vec::new(); + if !self.cur().is_sym("]") { + vars.push(self.expect_ident()?); + while self.eat_sym(",") { + vars.push(self.expect_ident()?); + } + } + self.expect_sym("]")?; + self.expect_sym(")")?; + let body = Box::new(self.parse_stmt()?); + Ok(StmtKind::Foreach { target: Expr::Ident(name), vars, body }) + } + "return" => { + self.bump(); + let e = if self.cur().is_sym(";") { None } else { Some(self.parse_expr()?) }; + self.expect_sym(";")?; + Ok(StmtKind::Return(e)) + } + "break" => { + self.bump(); + self.expect_sym(";")?; + Ok(StmtKind::Break) + } + "continue" => { + self.bump(); + self.expect_sym(";")?; + Ok(StmtKind::Continue) + } + "disable" => { + self.bump(); + let mut name = self.expect_ident()?; + while self.cur().is_sym(".") { + self.bump(); + name.push('.'); + name.push_str(&self.expect_ident()?); + } + self.expect_sym(";")?; + Ok(StmtKind::Disable(name)) + } + "wait" => { + self.bump(); + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + let stmt = + if self.eat_sym(";") { None } else { Some(Box::new(self.parse_stmt()?)) }; + Ok(StmtKind::Wait { cond, stmt }) + } + "assert" | "assume" | "cover" => { + let kw = self.bump().text; + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + let (then, els) = if self.eat_sym(";") { + (None, None) + } else if self.eat_kw("else") { + (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 + }; + (Some(then), els) + }; + Ok(StmtKind::Assert { kw, cond, then, els }) + } + "force" => { + self.bump(); + let lhs = self.parse_unary()?; + self.expect_sym("=")?; + let rhs = self.parse_expr()?; + self.expect_sym(";")?; + Ok(StmtKind::ForceRelease { kw: "force".into(), lhs, rhs: Some(rhs) }) + } + "release" | "deassign" => { + let kw = self.bump().text; + let lhs = self.parse_unary()?; + self.expect_sym(";")?; + Ok(StmtKind::ForceRelease { kw, lhs, rhs: None }) + } + "parameter" | "localparam" => { + let d = self.parse_param_decl()?; + self.expect_sym(";")?; + Ok(StmtKind::ParamDecl(d)) + } + "input" | "output" | "inout" => { + let d = self.parse_port_decl()?; + Ok(StmtKind::PortDecl(d)) + } + _ if NET_KEYWORDS.contains(&kw.as_str()) + || TYPE_KEYWORDS.contains(&kw.as_str()) + || matches!(kw.as_str(), "var" | "automatic" | "static" | "const") => + { + // A type keyword followed by `'` is a cast expression, not a + // declaration. + if self.nth(1).is_sym("'") { + return self.parse_assign_or_expr_stmt(); + } + let d = self.parse_data_decl()?; + Ok(StmtKind::VarDecl(d)) + } + _ => self.error(format!("unsupported statement starting with keyword `{kw}`")), + } + } + + fn parse_if_stmt(&mut self, qualifier: Option) -> PResult { + self.expect_kw("if")?; + self.expect_sym("(")?; + let cond = self.parse_expr()?; + self.expect_sym(")")?; + let then = Box::new(self.parse_stmt()?); + let els = if self.cur().is_kw("else") { + self.bump(); + Some(Box::new(self.parse_stmt()?)) + } else { + None + }; + Ok(StmtKind::If { qualifier, cond, then, els }) + } + + fn parse_case_stmt(&mut self, qualifier: Option) -> PResult { + let kw = self.bump().text; + self.expect_sym("(")?; + let expr = self.parse_expr()?; + self.expect_sym(")")?; + // `case (x) inside` is not supported; plain case kinds only. + let mut items = Vec::new(); + while !self.cur().is_kw("endcase") && !self.at_eof() { + let mut meta = self.take_meta(); + let labels = if self.eat_kw("default") { + let _ = self.eat_sym(":"); + Vec::new() + } else { + let mut labels = vec![self.parse_expr()?]; + while self.eat_sym(",") { + labels.push(self.parse_expr()?); + } + self.expect_sym(":")?; + labels + }; + let stmt = self.parse_stmt()?; + if meta.trailing.is_none() { + meta.trailing = self.take_trailing(); + } + items.push(CaseItem { meta, labels, stmt }); + } + let dangling = self.take_dangling(); + self.expect_kw("endcase")?; + Ok(StmtKind::Case { qualifier, kw, expr, items, dangling }) + } + + 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 == "<=") + { + self.bump(); + let rhs = self.parse_expr()?; + Ok(ForStep::Assign(SimpleAssign { lhs, op, rhs })) + } else { + Ok(ForStep::Expr(lhs)) + } + } + + fn parse_assign_or_expr_stmt(&mut self) -> PResult { + // Declaration with a user-defined type: `my_t x;` / `my_t x = e;` + if self.cur().kind == TokenKind::Ident { + let mut p = self.pos; + while self.tokens.get(p + 1).is_some_and(|t| t.is_sym("::")) { + p += 2; + } + let next = &self.tokens[(p + 1).min(self.tokens.len() - 1)]; + if next.kind == TokenKind::Ident { + let d = self.parse_data_decl()?; + return Ok(StmtKind::VarDecl(d)); + } + } + let lhs = self.parse_unary()?; + let op = self.cur().text.clone(); + let is_assign = self.cur().kind == TokenKind::Symbol + && (ASSIGN_OPS.contains(&op.as_str()) || op == "<="); + if is_assign { + self.bump(); + let timing = if self.cur().is_sym("#") { + self.bump(); + Some(TimingControl::Delay(self.parse_delay_value()?)) + } else if self.cur().is_sym("@") { + self.bump(); + Some(TimingControl::Event(self.parse_sens_list()?)) + } else { + None + }; + let rhs = self.parse_expr()?; + self.expect_sym(";")?; + Ok(StmtKind::Assign { lhs, op, timing, rhs }) + } else { + self.expect_sym(";")?; + Ok(StmtKind::ExprStmt(lhs)) + } + } + + fn parse_sens_list(&mut self) -> PResult { + if self.eat_sym("*") { + return Ok(SensList::Star); + } + if self.cur().kind == TokenKind::Ident { + // `@ident` without parens. + let name = self.expect_ident()?; + return Ok(SensList::List(vec![SensItem { edge: None, expr: Expr::Ident(name) }])); + } + self.expect_sym("(")?; + if self.eat_sym("*") { + self.expect_sym(")")?; + return Ok(SensList::Star); + } + let mut items = Vec::new(); + loop { + let edge = { + let t = self.cur(); + if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { + Some(self.bump().text) + } else { + None + } + }; + let expr = self.parse_expr()?; + items.push(SensItem { edge, expr }); + if self.eat_sym(",") || self.eat_kw("or") { + continue; + } + break; + } + self.expect_sym(")")?; + Ok(SensList::List(items)) + } + + // ------------------------------------------------------------------ + // Expressions + // ------------------------------------------------------------------ + + pub fn parse_expr(&mut self) -> PResult { + self.parse_ternary() + } + + fn parse_ternary(&mut self) -> PResult { + let cond = self.parse_binary(1)?; + if self.cur().is_sym("?") { + self.bump(); + let then = self.parse_expr()?; + self.expect_sym(":")?; + let els = self.parse_ternary()?; + Ok(Expr::Ternary { cond: Box::new(cond), then: Box::new(then), els: Box::new(els) }) + } else { + Ok(cond) + } + } + + fn binary_prec(&self) -> Option { + let t = self.cur(); + if t.is_kw("inside") { + return Some(7); + } + if t.kind != TokenKind::Symbol { + return None; + } + let p = match t.text.as_str() { + "||" => 1, + "&&" => 2, + "|" => 3, + "^" | "^~" | "~^" => 4, + "&" => 5, + "==" | "!=" | "===" | "!==" | "==?" | "!=?" => 6, + "<" | "<=" | ">" | ">=" => 7, + "<<" | ">>" | "<<<" | ">>>" => 8, + "+" | "-" => 9, + "*" | "/" | "%" => 10, + "**" => 11, + _ => return None, + }; + Some(p) + } + + fn parse_binary(&mut self, min_prec: u8) -> PResult { + let mut lhs = self.parse_unary()?; + while let Some(prec) = self.binary_prec() { + if prec < min_prec { + break; + } + if self.cur().is_kw("inside") { + self.bump(); + self.expect_sym("{")?; + let mut ranges = Vec::new(); + loop { + if self.cur().is_sym("[") { + self.bump(); + let lo = self.parse_expr()?; + self.expect_sym(":")?; + let hi = self.parse_expr()?; + self.expect_sym("]")?; + ranges.push(Expr::ValueRange { lo: Box::new(lo), hi: Box::new(hi) }); + } else { + ranges.push(self.parse_expr()?); + } + if !self.eat_sym(",") { + break; + } + } + self.expect_sym("}")?; + lhs = Expr::Inside { lhs: Box::new(lhs), ranges }; + continue; + } + let op = self.bump().text; + let rhs = self.parse_binary(prec + 1)?; + lhs = Expr::Binary { lhs: Box::new(lhs), op, rhs: Box::new(rhs) }; + } + Ok(lhs) + } + + fn parse_unary(&mut self) -> PResult { + let t = self.cur(); + if t.kind == TokenKind::Symbol + && matches!( + t.text.as_str(), + "!" | "~" | "+" | "-" | "&" | "|" | "^" | "~&" | "~|" | "~^" | "^~" | "++" | "--" + ) + { + let op = self.bump().text; + let expr = self.parse_unary()?; + return Ok(Expr::Unary { op, expr: Box::new(expr) }); + } + self.parse_postfix() + } + + fn parse_postfix(&mut self) -> PResult { + let mut expr = self.parse_primary()?; + loop { + let t = self.cur(); + if t.is_sym(".") { + self.bump(); + let name = self.expect_ident()?; + expr = Expr::Member { base: Box::new(expr), name }; + } else if t.is_sym("::") { + self.bump(); + let name = self.expect_ident()?; + expr = Expr::Scope { base: Box::new(expr), name }; + } else if t.is_sym("[") { + self.bump(); + let a = self.parse_expr()?; + let t2 = self.cur(); + if t2.is_sym(":") || t2.is_sym("+:") || t2.is_sym("-:") { + let op = self.bump().text; + let b = self.parse_expr()?; + self.expect_sym("]")?; + expr = Expr::Range { + base: Box::new(expr), + op, + msb: Box::new(a), + lsb: Box::new(b), + }; + } else { + self.expect_sym("]")?; + expr = Expr::Index { base: Box::new(expr), index: Box::new(a) }; + } + } else if t.is_sym("(") { + self.bump(); + let mut args = Vec::new(); + if !self.cur().is_sym(")") { + loop { + args.push(self.parse_expr_or_type()?); + if !self.eat_sym(",") { + break; + } + } + } + self.expect_sym(")")?; + expr = Expr::Call { callee: Box::new(expr), args }; + } else if t.is_sym("'") && self.nth(1).is_sym("(") { + // Cast: `expr'(x)` where expr is a simple name or size. + let ty = match &expr { + Expr::Ident(n) => n.clone(), + Expr::Number(n) => n.clone(), + _ => return self.error("unsupported cast base expression"), + }; + self.bump(); // ' + self.bump(); // ( + let inner = self.parse_expr()?; + self.expect_sym(")")?; + expr = Expr::Cast { ty, expr: Box::new(inner) }; + } else if t.is_sym("++") || t.is_sym("--") { + let op = self.bump().text; + expr = Expr::Postfix { expr: Box::new(expr), op }; + } else { + break; + } + } + Ok(expr) + } + + fn parse_primary(&mut self) -> PResult { + let t = self.cur(); + match t.kind { + TokenKind::Number => Ok(Expr::Number(self.bump().text)), + TokenKind::String => Ok(Expr::Str(self.bump().text)), + TokenKind::Ident | TokenKind::SystemIdent => Ok(Expr::Ident(self.bump().text)), + TokenKind::Keyword => { + let kw = t.text.clone(); + // Type keyword casts: `int'(x)`, `signed'(y)`. + if (TYPE_KEYWORDS.contains(&kw.as_str()) + || kw == "signed" + || kw == "unsigned" + || kw == "const") + && self.nth(1).is_sym("'") + && self.nth(2).is_sym("(") + { + let ty = self.bump().text; + self.bump(); // ' + self.bump(); // ( + let inner = self.parse_expr()?; + self.expect_sym(")")?; + return Ok(Expr::Cast { ty, expr: Box::new(inner) }); + } + // Type keyword used as an argument (e.g. `$bits(int)`). + if TYPE_KEYWORDS.contains(&kw.as_str()) { + return self.parse_type_expr(); + } + self.error(format!("unexpected keyword `{kw}` in expression")) + } + TokenKind::Symbol => { + let sym = t.text.clone(); + match sym.as_str() { + "(" => { + self.bump(); + let inner = self.parse_expr()?; + if self.eat_sym(":") { + let typ = self.parse_expr()?; + self.expect_sym(":")?; + let max = self.parse_expr()?; + self.expect_sym(")")?; + return Ok(Expr::Paren(Box::new(Expr::MinTypMax { + min: Box::new(inner), + typ: Box::new(typ), + max: Box::new(max), + }))); + } + self.expect_sym(")")?; + Ok(Expr::Paren(Box::new(inner))) + } + "{" => { + self.bump(); + if self.cur().is_sym("}") { + return self.error("empty concatenation"); + } + let first = self.parse_expr()?; + if self.cur().is_sym("{") { + // Replication {N{a, b}} + self.bump(); + let mut inner = vec![self.parse_expr()?]; + while self.eat_sym(",") { + inner.push(self.parse_expr()?); + } + self.expect_sym("}")?; + self.expect_sym("}")?; + return Ok(Expr::Repl { count: Box::new(first), inner }); + } + let mut items = vec![first]; + while self.eat_sym(",") { + items.push(self.parse_expr()?); + } + self.expect_sym("}")?; + Ok(Expr::Concat(items)) + } + "'{" => { + self.bump(); + let mut items = Vec::new(); + if !self.cur().is_sym("}") { + loop { + let key_or_val = if self.cur().is_kw("default") { + self.bump(); + Expr::Ident("default".to_string()) + } else { + self.parse_expr_or_type()? + }; + if self.eat_sym(":") { + let value = self.parse_expr()?; + items.push(PatternItem { key: Some(key_or_val), value }); + } else { + items.push(PatternItem { key: None, value: key_or_val }); + } + if !self.eat_sym(",") { + break; + } + } + } + self.expect_sym("}")?; + Ok(Expr::AssignPattern(items)) + } + _ => self.error("expected expression"), + } + } + _ => self.error("expected expression"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::lexer::tokenize; + + fn parse_ok(src: &str) -> SourceFile { + let toks = tokenize(src).expect("lex error"); + match parse(toks) { + Ok(f) => f, + Err(e) => panic!("parse error in {src:?}: {e}"), + } + } + + #[test] + fn simple_module() { + let f = parse_ok("module m(input clk, output reg [7:0] q); endmodule"); + assert_eq!(f.items.len(), 1); + } + + #[test] + fn module_with_params_and_body() { + parse_ok( + "module counter #(parameter WIDTH = 8) ( + input wire clk, input wire rst_n, + output logic [WIDTH-1:0] count); + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) count <= '0; + else count <= count + 1'b1; + end + endmodule : counter", + ); + } + + #[test] + fn instantiation_forms() { + parse_ok( + "module top; + sub #(.W(8), .D(16)) u_sub (.clk(clk), .out(out), .unused()); + sub2 u2 (a, b, c); + and g1 (o, a, b); + mem #(8) banks [3:0] (.*); + endmodule", + ); + } + + #[test] + fn expressions() { + parse_ok( + "module e; + assign x = a ? {b, c[3:0], {4{d}}} : (e + f) * g; + assign y = data[base +: 8] | pkg::CONST; + assign z = int'(w) + 8'hFF + $clog2(DEPTH); + endmodule", + ); + } + + #[test] + fn generate_and_case() { + parse_ok( + "module g #(parameter N = 4)(); + genvar i; + generate + for (i = 0; i < N; i = i + 1) begin : lane + sub u (.x(x[i])); + end + endgenerate + always_comb begin + case (sel) + 2'b00: y = a; + 2'b01, 2'b10: y = b; + default: y = '0; + endcase + end + endmodule", + ); + } + + #[test] + fn typedefs() { + parse_ok( + "typedef enum logic [1:0] {IDLE, RUN = 2, DONE} state_t; + typedef struct packed { logic [7:0] addr; logic valid; } req_t; + typedef logic [31:0] word_t;", + ); + } + + #[test] + fn functions_tasks() { + parse_ok( + "module f; + function automatic logic [7:0] add1(input logic [7:0] x); + return x + 1; + endfunction + task do_thing(input int n); + repeat (n) @(posedge clk); + endtask + endmodule", + ); + } +} diff --git a/crates/vlog_parser/src/token.rs b/crates/vlog_parser/src/token.rs new file mode 100644 index 0000000..25efa29 --- /dev/null +++ b/crates/vlog_parser/src/token.rs @@ -0,0 +1,236 @@ +//! Token definitions for the Verilog/SystemVerilog lexer. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TokenKind { + /// Identifier, including escaped identifiers (`\foo`). + Ident, + /// System identifier such as `$display`. + SystemIdent, + /// Reserved keyword (the text field holds which one). + Keyword, + /// Any numeric literal, including sized/based literals (`8'hFF`) and time + /// literals (`10ns`). The text is normalized to contain no whitespace. + Number, + /// String literal, including the surrounding quotes. + String, + /// Compiler directive: from a backtick to the end of the (possibly + /// continued) line, e.g. `` `timescale 1ns / 1ps `` or `` `ifdef FOO ``. + Directive, + /// Attribute instance `(* ... *)`, stored verbatim. + Attribute, + /// Operator or punctuation. + Symbol, + /// End of file. + Eof, +} + +/// A comment that has been detached from the token stream. +#[derive(Debug, Clone)] +pub struct Comment { + /// Full text including the `//` or `/* */` markers. Never contains a + /// trailing newline. + pub text: String, + /// True if at least one blank line separated this comment from whatever + /// preceded it. + pub blank_before: bool, +} + +#[derive(Debug, Clone)] +pub struct Token { + pub kind: TokenKind, + pub text: String, + /// 1-based source line of the first character. + pub line: u32, + /// 1-based source column of the first character. + pub col: u32, + /// Comments that appeared before this token (on their own lines, or on + /// earlier lines). + pub leading: Vec, + /// A comment that appeared after this token on the same source line. + pub trailing: Option, + /// True if at least one blank line separated this token from the previous + /// token or comment. + pub blank_before: bool, +} + +impl Token { + pub fn is_kw(&self, kw: &str) -> bool { + self.kind == TokenKind::Keyword && self.text == kw + } + + pub fn is_sym(&self, sym: &str) -> bool { + self.kind == TokenKind::Symbol && self.text == sym + } +} + +/// Reserved words we treat as keywords. This covers Verilog-2001 plus the +/// SystemVerilog subset the parser understands. Words not listed here lex as +/// plain identifiers. +pub fn is_keyword(s: &str) -> bool { + matches!( + s, + "module" + | "macromodule" + | "endmodule" + | "interface" + | "endinterface" + | "package" + | "endpackage" + | "program" + | "endprogram" + | "modport" + | "input" + | "output" + | "inout" + | "ref" + | "wire" + | "tri" + | "tri0" + | "tri1" + | "wand" + | "wor" + | "trireg" + | "supply0" + | "supply1" + | "uwire" + | "reg" + | "logic" + | "bit" + | "byte" + | "shortint" + | "int" + | "longint" + | "integer" + | "time" + | "realtime" + | "real" + | "shortreal" + | "string" + | "chandle" + | "event" + | "var" + | "void" + | "signed" + | "unsigned" + | "packed" + | "parameter" + | "localparam" + | "defparam" + | "specparam" + | "type" + | "typedef" + | "enum" + | "struct" + | "union" + | "assign" + | "alias" + | "always" + | "always_comb" + | "always_ff" + | "always_latch" + | "initial" + | "final" + | "begin" + | "end" + | "if" + | "else" + | "case" + | "casex" + | "casez" + | "endcase" + | "default" + | "unique" + | "unique0" + | "priority" + | "for" + | "while" + | "repeat" + | "forever" + | "do" + | "foreach" + | "break" + | "continue" + | "return" + | "fork" + | "join" + | "join_any" + | "join_none" + | "disable" + | "wait" + | "posedge" + | "negedge" + | "edge" + | "or" + | "and" + | "nand" + | "nor" + | "xor" + | "xnor" + | "not" + | "buf" + | "bufif0" + | "bufif1" + | "notif0" + | "notif1" + | "pullup" + | "pulldown" + | "generate" + | "endgenerate" + | "genvar" + | "function" + | "endfunction" + | "task" + | "endtask" + | "automatic" + | "static" + | "const" + | "import" + | "export" + | "timeunit" + | "timeprecision" + | "assert" + | "assume" + | "cover" + | "property" + | "endproperty" + | "sequence" + | "endsequence" + | "inside" + | "with" + | "iff" + | "release" + | "force" + | "deassign" + | "primitive" + | "endprimitive" + | "specify" + | "endspecify" + | "table" + | "endtable" + | "small" + | "medium" + | "large" + | "scalared" + | "vectored" + | "highz0" + | "highz1" + | "strong0" + | "strong1" + | "pull0" + | "pull1" + | "weak0" + | "weak1" + | "cmos" + | "rcmos" + | "nmos" + | "pmos" + | "rnmos" + | "rpmos" + | "tran" + | "rtran" + | "tranif0" + | "tranif1" + | "rtranif0" + | "rtranif1" + ) +}