Initial commit: vfmt — ruff-style Verilog/SystemVerilog formatter
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 <[email protected]>
This commit is contained in:
commit
d3d9786791
27 files changed
+6313
No files matched your search
@@ -0,0 +1 @@
|
||||
/target
|
||||
Generated
+22
@@ -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"
|
||||
+11
@@ -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
|
||||
@@ -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`.
|
||||
@@ -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 <rev>` 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 <path>`.** 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<Diagnostic>` 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::<NoTabsRule>("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.
|
||||
@@ -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" }
|
||||
@@ -0,0 +1,223 @@
|
||||
//! vfmt — a Verilog/SystemVerilog formatter in the spirit of `ruff format`.
|
||||
//!
|
||||
//! Usage:
|
||||
//! vfmt [OPTIONS] <file|dir>... format files in place
|
||||
//! vfmt --check <file|dir>... 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<String>,
|
||||
}
|
||||
|
||||
fn print_help() {
|
||||
println!(
|
||||
"vfmt — a Verilog/SystemVerilog formatter
|
||||
|
||||
USAGE:
|
||||
vfmt [OPTIONS] <file|dir>...
|
||||
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 <N> maximum line length (default 100)
|
||||
--indent <N> indent width in spaces (default 2)
|
||||
-h, --help show this help
|
||||
-V, --version show version"
|
||||
);
|
||||
}
|
||||
|
||||
fn parse_args() -> Result<Options, String> {
|
||||
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<PathBuf>) -> 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<PathBuf>) -> std::io::Result<()> {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
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: <stdin>:{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"
|
||||
}
|
||||
}
|
||||
@@ -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" }
|
||||
@@ -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<Doc>),
|
||||
/// Increase indentation for any line breaks inside.
|
||||
Indent(Vec<Doc>),
|
||||
/// Sequence with no other effect.
|
||||
Concat(Vec<Doc>),
|
||||
/// Emitted only when the enclosing group is broken.
|
||||
IfBreak(String),
|
||||
}
|
||||
|
||||
pub fn text(s: impl Into<String>) -> Doc {
|
||||
Doc::Text(s.into())
|
||||
}
|
||||
|
||||
pub fn group(docs: Vec<Doc>) -> Doc {
|
||||
Doc::Group(docs)
|
||||
}
|
||||
|
||||
pub fn indent(docs: Vec<Doc>) -> Doc {
|
||||
Doc::Indent(docs)
|
||||
}
|
||||
|
||||
pub fn concat(docs: Vec<Doc>) -> Doc {
|
||||
Doc::Concat(docs)
|
||||
}
|
||||
|
||||
/// Join docs with a separator.
|
||||
pub fn join(items: Vec<Doc>, sep: Doc) -> Vec<Doc> {
|
||||
let mut out = Vec::new();
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
if i > 0 {
|
||||
out.push(sep.clone());
|
||||
}
|
||||
out.push(item);
|
||||
}
|
||||
out
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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};
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Snapshot tests: every file in `tests/fixtures/` is formatted and compared
|
||||
//! against `tests/snapshots/<name>.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}");
|
||||
}
|
||||
}
|
||||
+28
@@ -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
|
||||
+65
@@ -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
|
||||
+58
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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]
|
||||
@@ -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<Comment>,
|
||||
pub trailing: Option<String>,
|
||||
pub blank_before: bool,
|
||||
/// Attribute instances `(* ... *)` that preceded the node, verbatim.
|
||||
pub attrs: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SourceFile {
|
||||
pub items: Vec<Item>,
|
||||
/// Comments at the very end of the file.
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[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<Item>, dangling: Vec<Comment> },
|
||||
Directive(String),
|
||||
Import(Vec<String>),
|
||||
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<String>),
|
||||
GenerateRegion { items: Vec<Item>, dangling: Vec<Comment> },
|
||||
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<String>,
|
||||
pub param_ports: Vec<ParamPort>,
|
||||
pub ports: PortList,
|
||||
pub items: Vec<Item>,
|
||||
pub dangling: Vec<Comment>,
|
||||
pub end_label: Option<String>,
|
||||
}
|
||||
|
||||
#[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<AnsiPort>),
|
||||
/// Non-ANSI: just names in the header, declared in the body.
|
||||
NonAnsi(Vec<NonAnsiPort>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NonAnsiPort {
|
||||
pub meta: Meta,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AnsiPort {
|
||||
pub meta: Meta,
|
||||
pub dir: Option<String>,
|
||||
pub net: Option<String>,
|
||||
pub ty: DataType,
|
||||
pub name: String,
|
||||
pub unpacked: Vec<Dim>,
|
||||
pub default: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ParamPort {
|
||||
pub meta: Meta,
|
||||
/// `parameter` or `localparam`; empty if omitted (continuation params).
|
||||
pub kw: Option<String>,
|
||||
pub ty: DataType,
|
||||
pub is_type: bool,
|
||||
pub name: String,
|
||||
pub unpacked: Vec<Dim>,
|
||||
pub default: Option<Expr>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
pub packed: Vec<Dim>,
|
||||
}
|
||||
|
||||
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<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Typedef {
|
||||
pub name: String,
|
||||
pub unpacked: Vec<Dim>,
|
||||
pub kind: TypedefKind,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum TypedefKind {
|
||||
Alias(DataType),
|
||||
Enum(EnumType),
|
||||
Struct(StructType),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EnumType {
|
||||
pub base: Option<DataType>,
|
||||
pub members: Vec<EnumMember>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct EnumMember {
|
||||
pub meta: Meta,
|
||||
pub name: String,
|
||||
pub value: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StructType {
|
||||
/// "struct" or "union"
|
||||
pub kw: String,
|
||||
pub packed: bool,
|
||||
pub signing: Option<String>,
|
||||
pub members: Vec<StructMember>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StructMember {
|
||||
pub meta: Meta,
|
||||
pub ty: DataType,
|
||||
pub declarators: Vec<Declarator>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ParamDecl {
|
||||
/// `parameter` or `localparam`
|
||||
pub kw: String,
|
||||
pub ty: DataType,
|
||||
pub declarators: Vec<Declarator>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct DataDecl {
|
||||
/// Net type (`wire`, `tri`, ...) if any.
|
||||
pub net: Option<String>,
|
||||
/// Net delay: the `5` in `wire #5 w;`
|
||||
pub delay: Option<Expr>,
|
||||
/// `var` / `automatic` / `static` / `const` qualifiers, in order.
|
||||
pub qualifiers: Vec<String>,
|
||||
pub ty: DataType,
|
||||
pub declarators: Vec<Declarator>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PortDecl {
|
||||
pub dir: String,
|
||||
pub net: Option<String>,
|
||||
pub ty: DataType,
|
||||
pub declarators: Vec<Declarator>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Declarator {
|
||||
pub meta: Meta,
|
||||
pub name: String,
|
||||
pub unpacked: Vec<Dim>,
|
||||
/// `=` for variables; net declarations also use this for the initial
|
||||
/// continuous assignment.
|
||||
pub init: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ContAssign {
|
||||
/// Delay expression: the `5` in `assign #5 x = y;`
|
||||
pub delay: Option<Expr>,
|
||||
pub assigns: Vec<AssignPair>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AssignPair {
|
||||
pub meta: Meta,
|
||||
pub lhs: Expr,
|
||||
pub rhs: Expr,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SensList {
|
||||
/// `@*` or `@(*)`
|
||||
Star,
|
||||
List(Vec<SensItem>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct SensItem {
|
||||
pub edge: Option<String>,
|
||||
pub expr: Expr,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Instantiation {
|
||||
pub module: String,
|
||||
pub params: Vec<Connection>,
|
||||
pub instances: Vec<Instance>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Instance {
|
||||
pub meta: Meta,
|
||||
pub name: String,
|
||||
pub dims: Vec<Dim>,
|
||||
pub conns: Connections,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Connections {
|
||||
Ordered(Vec<OrderedConn>),
|
||||
Named(Vec<Connection>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct OrderedConn {
|
||||
pub meta: Meta,
|
||||
pub expr: Option<Expr>,
|
||||
}
|
||||
|
||||
#[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<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GateInstantiation {
|
||||
/// `and`, `or`, `not`, ...
|
||||
pub gate: String,
|
||||
pub delay: Option<Expr>,
|
||||
pub instances: Vec<GateInstance>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GateInstance {
|
||||
pub meta: Meta,
|
||||
pub name: Option<String>,
|
||||
pub args: Vec<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GenIf {
|
||||
pub cond: Expr,
|
||||
pub then: GenBlock,
|
||||
pub els: Option<Box<GenElse>>,
|
||||
}
|
||||
|
||||
#[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<GenCaseItem>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GenCaseItem {
|
||||
pub meta: Meta,
|
||||
/// Empty means `default`.
|
||||
pub labels: Vec<Expr>,
|
||||
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<String>,
|
||||
pub is_block: bool,
|
||||
pub items: Vec<Item>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct FunctionDecl {
|
||||
pub qualifiers: Vec<String>,
|
||||
pub ret: Option<DataType>,
|
||||
pub name: String,
|
||||
/// False for old-style `function f;` declarations without a port list.
|
||||
pub has_parens: bool,
|
||||
pub args: Vec<TfArg>,
|
||||
pub stmts: Vec<Stmt>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TaskDecl {
|
||||
pub qualifiers: Vec<String>,
|
||||
pub name: String,
|
||||
/// False for old-style `task t;` declarations without a port list.
|
||||
pub has_parens: bool,
|
||||
pub args: Vec<TfArg>,
|
||||
pub stmts: Vec<Stmt>,
|
||||
pub dangling: Vec<Comment>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TfArg {
|
||||
pub meta: Meta,
|
||||
pub dir: Option<String>,
|
||||
pub ty: DataType,
|
||||
pub name: String,
|
||||
pub unpacked: Vec<Dim>,
|
||||
pub default: Option<Expr>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Stmt {
|
||||
pub meta: Meta,
|
||||
pub kind: StmtKind,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum StmtKind {
|
||||
Block {
|
||||
label: Option<String>,
|
||||
stmts: Vec<Stmt>,
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
ForkJoin {
|
||||
label: Option<String>,
|
||||
join_kw: String,
|
||||
stmts: Vec<Stmt>,
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
If {
|
||||
qualifier: Option<String>,
|
||||
cond: Expr,
|
||||
then: Box<Stmt>,
|
||||
els: Option<Box<Stmt>>,
|
||||
},
|
||||
Case {
|
||||
qualifier: Option<String>,
|
||||
kw: String,
|
||||
expr: Expr,
|
||||
items: Vec<CaseItem>,
|
||||
dangling: Vec<Comment>,
|
||||
},
|
||||
For {
|
||||
init: Vec<ForInit>,
|
||||
cond: Option<Expr>,
|
||||
step: Vec<ForStep>,
|
||||
body: Box<Stmt>,
|
||||
},
|
||||
While { cond: Expr, body: Box<Stmt> },
|
||||
DoWhile { body: Box<Stmt>, cond: Expr },
|
||||
Repeat { count: Expr, body: Box<Stmt> },
|
||||
Forever { body: Box<Stmt> },
|
||||
Foreach { target: Expr, vars: Vec<String>, body: Box<Stmt> },
|
||||
/// Blocking/nonblocking/compound assignment.
|
||||
Assign {
|
||||
lhs: Expr,
|
||||
op: String,
|
||||
/// Intra-assignment timing control (e.g. `#1`, `@(posedge clk)`).
|
||||
timing: Option<TimingControl>,
|
||||
rhs: Expr,
|
||||
},
|
||||
/// `force`/`release`/`deassign` statements, raw pieces.
|
||||
ForceRelease { kw: String, lhs: Expr, rhs: Option<Expr> },
|
||||
/// Procedural timing control: `#10 stmt;`, `@(posedge clk) stmt;`,
|
||||
/// `#10;`, `@(ev);`
|
||||
Timing { control: TimingControl, stmt: Option<Box<Stmt>> },
|
||||
Wait { cond: Expr, stmt: Option<Box<Stmt>> },
|
||||
ExprStmt(Expr),
|
||||
/// `-> event_name;`
|
||||
EventTrigger(Expr),
|
||||
VarDecl(DataDecl),
|
||||
ParamDecl(ParamDecl),
|
||||
/// Old-style task/function port declaration: `input [7:0] a;`
|
||||
PortDecl(PortDecl),
|
||||
Return(Option<Expr>),
|
||||
Break,
|
||||
Continue,
|
||||
Disable(String),
|
||||
Directive(String),
|
||||
/// Immediate assertion: kept simple — `assert (expr) stmt else stmt;`
|
||||
Assert {
|
||||
kw: String,
|
||||
cond: Expr,
|
||||
then: Option<Box<Stmt>>,
|
||||
els: Option<Box<Stmt>>,
|
||||
},
|
||||
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<Expr>,
|
||||
pub stmt: Stmt,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ForInit {
|
||||
/// Declared type for `for (int i = 0; ...)`.
|
||||
pub ty: Option<DataType>,
|
||||
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<Expr> },
|
||||
Binary { lhs: Box<Expr>, op: String, rhs: Box<Expr> },
|
||||
Ternary { cond: Box<Expr>, then: Box<Expr>, els: Box<Expr> },
|
||||
Call { callee: Box<Expr>, args: Vec<Expr> },
|
||||
Index { base: Box<Expr>, index: Box<Expr> },
|
||||
Range { base: Box<Expr>, op: String, msb: Box<Expr>, lsb: Box<Expr> },
|
||||
Member { base: Box<Expr>, name: String },
|
||||
Scope { base: Box<Expr>, name: String },
|
||||
Concat(Vec<Expr>),
|
||||
Repl { count: Box<Expr>, inner: Vec<Expr> },
|
||||
Paren(Box<Expr>),
|
||||
/// `ty'(expr)` cast; `ty` kept as raw text.
|
||||
Cast { ty: String, expr: Box<Expr> },
|
||||
/// `'{...}` assignment pattern.
|
||||
AssignPattern(Vec<PatternItem>),
|
||||
Postfix { expr: Box<Expr>, op: String },
|
||||
Inside { lhs: Box<Expr>, ranges: Vec<Expr> },
|
||||
/// `[a:b]` inside an `inside` range list or value range.
|
||||
ValueRange { lo: Box<Expr>, hi: Box<Expr> },
|
||||
/// A type used in expression position (`parameter type T = logic [7:0]`).
|
||||
Type(DataType),
|
||||
/// `(min : typ : max)` delay expression.
|
||||
MinTypMax { min: Box<Expr>, typ: Box<Expr>, max: Box<Expr> },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PatternItem {
|
||||
/// `key: value` (key may be `default`, a type, or an expression).
|
||||
pub key: Option<Expr>,
|
||||
pub value: Expr,
|
||||
}
|
||||
@@ -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<RawTok, LexError> {
|
||||
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 \ <next line>
|
||||
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<String, LexError> {
|
||||
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<String, LexError> {
|
||||
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<Vec<Token>, LexError> {
|
||||
let mut raw_lexer = RawLexer::new(source.as_bytes());
|
||||
let mut raws: Vec<RawTok> = 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<Token> = Vec::new();
|
||||
let mut pending: Vec<Comment> = 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(&"<="));
|
||||
}
|
||||
}
|
||||
@@ -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<ast::SourceFile, Error> {
|
||||
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 {}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Comment>,
|
||||
/// A comment that appeared after this token on the same source line.
|
||||
pub trailing: Option<String>,
|
||||
/// 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"
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user