Add alignment inference and the format cache (round 17)
alignment: Verible-style alignment-intent inference for ANSI ports
(name column), named connections (paren column) and parameter items
(name and = columns). A group aligns iff the author asked: >=4
excess spaces somewhere, or the group already sits consistently at
one column -- single-space code keeps today's bytes exactly (zero
churn across all 397 pre-existing cases; corpus outcome TSV
byte-identical while 291/578 formattable files change content).
Fixed-point by construction: aligned output re-infers the same
targets, flush re-infers flush; the whole verdict is decided at
document-build time (a printer-side split diverged ibex_core.sv at
width 60 during development -- caught by a 2312-run config sweep and
redesigned). Groups break at comments/attributes/directives/blank
lines; a group that cannot fit falls back to flush whole, never
mixed. No lexer changes: name_span plus the source answers every
spacing question. QA's sabotage confirmed the runtime convergence
check catches the predicted flip-flop even with the unit test gone.
format-cache: warm runs skip verified-clean files. Key = (FNV-1a 64
content hash, resolved config values, vfmt version), path-keyed;
only the fixed-point verdict is ever cached, so --check/--diff can
never go stale and a hit can only skip work, never produce output.
One atomic text file in self-gitignoring .vfmt_cache/; --no-cache /
--cache-dir; 8-process concurrency clean. Warm corpus check: 2x at
default threads, 7.7x single-threaded.
655 workspace tests. Dev: 2 Opus agents (both isolated their gates
from the other's churn via HEAD-reverted scratchpad copies); QA: 2
Sonnet agents; reviews in docs/features/{alignment,format-cache}/
README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
7f2e78fc1c
commit
003e0766e9
15 files changed
+3387
-89
No files matched your search
@@ -2,3 +2,4 @@
|
||||
/corpus
|
||||
/corpus-check-results.tsv
|
||||
/dist
|
||||
/.vfmt_cache
|
||||
@@ -27,6 +27,10 @@ vfmt --no-gitignore rtl/
|
||||
# files are formatted on all cores; pin the worker count for reproducible CI
|
||||
vfmt --threads 1 rtl/
|
||||
|
||||
# repeat runs skip files that are already formatted; --no-cache turns that off
|
||||
vfmt --check rtl/
|
||||
vfmt --no-cache --check rtl/
|
||||
|
||||
# ignore any vfmt.toml found next to the input
|
||||
vfmt --no-config rtl/
|
||||
|
||||
@@ -55,6 +59,24 @@ and reported in input order, so stdout, stderr and the exit code are
|
||||
byte-identical at any `N`, and `vfmt --diff` stays one clean patch in input
|
||||
order. stdin mode is single-threaded.
|
||||
|
||||
### Cache
|
||||
|
||||
vfmt remembers which files it has already verified are formatted, so a repeat
|
||||
run over an unchanged tree skips them: the summary says `N files from cache`,
|
||||
and on one core the corpus check goes from 396 ms to 51 ms (2.3× at the default
|
||||
thread count, where parallelism has already taken the easy win).
|
||||
|
||||
An entry is keyed on **(content hash, `line-length`, `indent`, vfmt version)**
|
||||
per file, and only ever records the *already formatted* verdict — a file that
|
||||
would be reformatted, or that failed, is re-checked on every run, so
|
||||
`--check`'s exit codes and `--diff`'s output never go stale. The store is one
|
||||
text file in `.vfmt_cache/` (self-ignoring, like cargo's `target/`); deleting
|
||||
it, or a corrupted one, costs one slow run and nothing else. `--no-cache`
|
||||
neither reads nor writes it, and `--cache-dir <PATH>` puts it elsewhere (the
|
||||
default is relative to the current directory). Content hashing is 64-bit
|
||||
FNV-1a and a lookup never crosses files; `docs/features/format-cache/README.md`
|
||||
states the collision posture, the semantics table and the concurrency story.
|
||||
|
||||
### Ignore files
|
||||
|
||||
While walking a directory, vfmt reads a `.gitignore` in every directory it
|
||||
@@ -194,6 +216,37 @@ configurable via `--indent` / `--line-length` or a `vfmt.toml`, see
|
||||
- `` `define``/`` `ifdef``/`` `include`` and `(* attributes *)` passed
|
||||
through verbatim
|
||||
|
||||
### Alignment is inferred, not imposed
|
||||
|
||||
Hand-aligned columns are how RTL is read, so vfmt reads the spacing you
|
||||
already wrote and keeps your intent — Verible's rule, without the knobs.
|
||||
Within a run of adjacent ANSI **port declarations**, **named connections**
|
||||
(`.clk (clk)`) or **`parameter`/`localparam` declarations**, four or more
|
||||
spaces where one would do — or a run whose column is already lined up — means
|
||||
"aligned": every row is padded to the widest one, and the list stays one
|
||||
element per line. Anything else formats flush-left with a single separator,
|
||||
exactly as it always has, so a file written without alignment never grows any.
|
||||
|
||||
```systemverilog
|
||||
// written with aligned columns, so vfmt leaves them aligned — at the width
|
||||
// the group actually needs, which is what makes two people's tables agree
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
```
|
||||
|
||||
Groups end at a blank line, a standalone comment, an `(* attribute *)` or a
|
||||
compiler directive, so two tables separated by a comment get their own
|
||||
columns. A group whose widest aligned line would pass the line limit falls
|
||||
back to flush-left *as a whole* — never half-aligned. Full rule, including why
|
||||
both layouts are fixed points of re-formatting:
|
||||
`docs/features/alignment/README.md`.
|
||||
|
||||
### Turning the formatter off
|
||||
|
||||
Items between a `// verilog_format: off` and a `// verilog_format: on`
|
||||
|
||||
@@ -58,7 +58,7 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
(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.**
|
||||
- [x] **[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
|
||||
@@ -67,6 +67,16 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
and localparam/parameter lists. This needs original-spacing info
|
||||
preserved through the lexer — record "excess spaces before token" as
|
||||
trivia.
|
||||
→ `crates/vlog_formatter/src/align.rs`; all three constructs ship (ports
|
||||
align the name column, connections the `(`, parameters the name and `=`
|
||||
columns). No lexer trivia was needed after all: `name_span` plus the
|
||||
source text the formatter already holds gives both the preceding gap and
|
||||
the token's column, so the spans suite is untouched. Zero churn on the
|
||||
397-case table; 291 of 578 formattable corpus files now format
|
||||
differently, with 0 verification errors and 0 round-trip failures over
|
||||
2312 config-sweep runs. Rule, fixed-point argument and the parked columns
|
||||
(`#( ... )` parameter ports, the type column, the trailing-comment column)
|
||||
in `docs/features/alignment/README.md`.
|
||||
- [x] **Comment inside port/param lists and assignment patterns is
|
||||
dropped → refused** (found at scale by format-fences QA: 112 of 1868
|
||||
corpus injection trials refuse with exit 2). The failsafe holds, but
|
||||
@@ -117,9 +127,19 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
ordered-reporting determinism argument in
|
||||
`docs/features/parallel-files/README.md`. `--threads N` pins the worker
|
||||
count; output is byte-identical at any count. 3.6× on 10 cores.
|
||||
- [ ] **[R] Content-hash cache.** Skip files whose (content hash, config
|
||||
- [x] **[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.
|
||||
→ `crates/vfmt_core/src/cache.rs` (`--no-cache`, `--cache-dir`); the key
|
||||
stores the resolved `line-length`/`indent` *values*, and only the
|
||||
"already formatted" verdict is ever cached — a would-reformat or an
|
||||
error is re-checked every run, so `--check`/`--diff` cannot go stale.
|
||||
Hand-rolled FNV-1a and a hand-rolled tab-separated store (no new
|
||||
dependency); corrupt or another version's entries are ignored, never
|
||||
fatal. Warm `--check` over the pre-formatted corpus: 7.7× on one
|
||||
thread, 2.3× at the default thread count. Collision posture, the
|
||||
semantics table and the cwd-relative-default limitation in
|
||||
`docs/features/format-cache/README.md`.
|
||||
- [x] **[R] Respect `.gitignore`** and add `--exclude` globs when walking
|
||||
directories (`collect_files` in `main.rs` currently walks everything,
|
||||
including e.g. generated netlists).
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Hand-rolled command line parsing for the `vfmt` binary.
|
||||
|
||||
use vfmt_core::cache;
|
||||
use vfmt_core::config::FileConfig;
|
||||
use vlog_formatter::Config;
|
||||
|
||||
@@ -40,6 +41,11 @@ pub struct Options {
|
||||
pub no_config: bool,
|
||||
/// Ignore `.gitignore` files while walking directories.
|
||||
pub no_gitignore: bool,
|
||||
/// Neither read nor write the "already formatted" cache.
|
||||
pub no_cache: bool,
|
||||
/// Where that cache lives; `None` means `.vfmt_cache` in the current
|
||||
/// directory.
|
||||
pub cache_dir: Option<String>,
|
||||
/// `--threads`: worker count for the file pool. `None` or `Some(0)`
|
||||
/// means rayon's default, one per logical CPU.
|
||||
pub threads: Option<usize>,
|
||||
@@ -101,6 +107,19 @@ impl Options {
|
||||
pub fn thread_count(&self) -> usize {
|
||||
self.threads.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// True when this run may consult and update the cache. `--stdout`
|
||||
/// turns it off because every file's text has to be printed, and a
|
||||
/// skipped file has none.
|
||||
pub fn cache_enabled(&self) -> bool {
|
||||
!self.no_cache && !self.stdout
|
||||
}
|
||||
|
||||
/// The cache directory, resolved against the current directory when it
|
||||
/// is the default.
|
||||
pub fn cache_dir(&self) -> &str {
|
||||
self.cache_dir.as_deref().unwrap_or(cache::DEFAULT_DIR)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the `--help` text, including the frozen exit-code contract.
|
||||
@@ -129,6 +148,10 @@ OPTIONS:
|
||||
--stdin-filename <PATH> path to report in messages for input read from stdin;
|
||||
also the directory config discovery starts from
|
||||
--no-gitignore don't read .gitignore files while walking directories
|
||||
--no-cache don't read or write the \"already formatted\" cache
|
||||
--cache-dir <PATH> where that cache lives (default: .vfmt_cache in the
|
||||
current directory). `vfmt check` accepts both flags
|
||||
and ignores them: linting is not cached
|
||||
--threads <N> worker threads used to format files (default: one per
|
||||
logical CPU). `--threads 1` formats on a single worker;
|
||||
the output and exit code are identical either way
|
||||
@@ -162,6 +185,14 @@ IGNORE FILES:
|
||||
supported: `**`, `?`, character classes, `\\` escapes and the global/repo
|
||||
excludes files. Paths named on the command line are never ignored.
|
||||
|
||||
CACHE:
|
||||
A file whose exact content vfmt has already verified is formatted — under
|
||||
the same line-length, indent and vfmt version — is skipped on the next run
|
||||
and reported as `N files from cache`. Only that \"already formatted\"
|
||||
verdict is ever cached: a file that would be reformatted, or that failed,
|
||||
is re-checked every run. The cache is one text file under `.vfmt_cache/`;
|
||||
deleting it, or a corrupt one, costs a slow run and nothing else.
|
||||
|
||||
CONFIGURATION:
|
||||
For each input, vfmt searches upward from its directory for `vfmt.toml`
|
||||
or `.vfmt.toml` (the first found wins; the search also stops at a
|
||||
@@ -193,6 +224,8 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
stdout: false,
|
||||
no_config: false,
|
||||
no_gitignore: false,
|
||||
no_cache: false,
|
||||
cache_dir: None,
|
||||
threads: None,
|
||||
stdin_filename: None,
|
||||
exclude: Vec::new(),
|
||||
@@ -225,6 +258,14 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
"--stdout" => opts.stdout = true,
|
||||
"--no-config" => opts.no_config = true,
|
||||
"--no-gitignore" => opts.no_gitignore = true,
|
||||
"--no-cache" => opts.no_cache = true,
|
||||
"--cache-dir" => {
|
||||
let v = args.next().ok_or("--cache-dir requires a value")?;
|
||||
if v.is_empty() {
|
||||
return Err("--cache-dir requires a non-empty path".to_string());
|
||||
}
|
||||
opts.cache_dir = Some(v);
|
||||
}
|
||||
"--threads" => {
|
||||
let v = args.next().ok_or("--threads requires a value")?;
|
||||
opts.threads = Some(v.parse().map_err(|_| format!("invalid thread count: {v}"))?);
|
||||
@@ -398,6 +439,27 @@ mod tests {
|
||||
assert_eq!(parse(&["--threads", "4", "rtl"]).unwrap().thread_count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_is_on_unless_switched_off() {
|
||||
let opts = parse(&["rtl"]).unwrap();
|
||||
assert!(opts.cache_enabled());
|
||||
assert_eq!(opts.cache_dir(), ".vfmt_cache");
|
||||
|
||||
assert!(!parse(&["--no-cache", "rtl"]).unwrap().cache_enabled());
|
||||
// `--stdout` has to print every file, so nothing may be skipped.
|
||||
assert!(!parse(&["--stdout", "rtl"]).unwrap().cache_enabled());
|
||||
|
||||
let opts = parse(&["--cache-dir", "/tmp/vc", "rtl"]).unwrap();
|
||||
assert_eq!(opts.cache_dir(), "/tmp/vc");
|
||||
assert!(opts.cache_enabled());
|
||||
|
||||
assert!(parse(&["--cache-dir"]).is_err());
|
||||
assert!(parse(&["--cache-dir", "", "rtl"]).is_err());
|
||||
// Both are accepted (and inert) for the linter, so a wrapper script
|
||||
// can pass them to either tool.
|
||||
assert!(parse(&["check", "--no-cache", "--cache-dir", "x", "rtl"]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gitignore_is_honored_unless_switched_off() {
|
||||
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
|
||||
|
||||
+77
-17
@@ -25,6 +25,7 @@ use std::process::ExitCode;
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::{Command, Options};
|
||||
use vfmt_core::cache::{content_hash, Cache, Entry};
|
||||
use vfmt_core::config::Discovery;
|
||||
use vfmt_core::walk::{collect_files, EXTENSIONS};
|
||||
use vlog_formatter::{format_source, Config};
|
||||
@@ -132,17 +133,33 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
let mut cache = if opts.cache_enabled() {
|
||||
Cache::load(Path::new(opts.cache_dir()))
|
||||
} else {
|
||||
Cache::disabled()
|
||||
};
|
||||
|
||||
// Files are formatted in whatever order the pool picks, but an indexed
|
||||
// `par_iter` collects back into input order, and nothing is printed
|
||||
// until then — so stdout and stderr are byte-identical whatever the
|
||||
// thread count is, and a `--diff` run stays one clean ordered patch.
|
||||
let outcomes: Vec<Outcome> =
|
||||
jobs.par_iter().map(|(file, config)| process_file(file, config, opts)).collect();
|
||||
// The cache is only read here; entries ride back with the results and
|
||||
// are recorded serially below, so nothing is shared mutably.
|
||||
let results: Vec<FileResult> =
|
||||
jobs.par_iter().map(|(file, config)| process_file(file, config, opts, &cache)).collect();
|
||||
|
||||
let (mut changed, mut unchanged, mut errors) = (0usize, 0usize, 0usize);
|
||||
for outcome in outcomes {
|
||||
match outcome {
|
||||
let (mut changed, mut unchanged, mut errors, mut cached) = (0usize, 0usize, 0usize, 0usize);
|
||||
for (index, result) in results.into_iter().enumerate() {
|
||||
let (file, config) = &jobs[index];
|
||||
if let Some(content) = result.clean {
|
||||
cache.record(file, entry_for(content, config));
|
||||
}
|
||||
match result.outcome {
|
||||
Outcome::Unchanged => unchanged += 1,
|
||||
Outcome::Cached => {
|
||||
unchanged += 1;
|
||||
cached += 1;
|
||||
}
|
||||
Outcome::Printed(text) => print!("{text}"),
|
||||
Outcome::Changed(text) => {
|
||||
changed += 1;
|
||||
@@ -154,9 +171,10 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
}
|
||||
}
|
||||
}
|
||||
cache.store();
|
||||
|
||||
if !opts.stdout {
|
||||
report(opts, changed, unchanged, errors);
|
||||
report(opts, changed, unchanged, cached, errors);
|
||||
}
|
||||
|
||||
if errors > 0 {
|
||||
@@ -168,12 +186,32 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's result: what to report, and — when the file is provably a
|
||||
/// fixed point — the hash of the content that makes it one, for the cache.
|
||||
struct FileResult {
|
||||
outcome: Outcome,
|
||||
/// Hash of content verified to be already formatted. `None` for every
|
||||
/// other verdict: a would-reformat or an error is never cached,
|
||||
/// because the fix for both is outside vfmt.
|
||||
clean: Option<u64>,
|
||||
}
|
||||
|
||||
impl FileResult {
|
||||
/// A result that teaches the cache nothing.
|
||||
fn plain(outcome: Outcome) -> FileResult {
|
||||
FileResult { outcome, clean: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened to one file. Every variant carries the text it wants
|
||||
/// printed rather than printing it, so the parallel pass produces no
|
||||
/// output of its own and `run_files` can render the run in input order.
|
||||
enum Outcome {
|
||||
/// Already formatted; nothing to print.
|
||||
Unchanged,
|
||||
/// Skipped: the cache already knew this content is formatted. Counted
|
||||
/// as unchanged, and separately as a cache hit.
|
||||
Cached,
|
||||
/// `--stdout` text, which is outside the changed/unchanged counters.
|
||||
Printed(String),
|
||||
/// The file would change, or did. The text is the `--diff` hunk or the
|
||||
@@ -185,34 +223,51 @@ enum Outcome {
|
||||
|
||||
/// Formats one file and, unless the run is read-only, writes it back.
|
||||
/// This is the whole unit of parallel work: it shares nothing with the
|
||||
/// other files beyond immutable options.
|
||||
fn process_file(file: &Path, config: &Config, opts: &Options) -> Outcome {
|
||||
/// other files beyond immutable options and the read-only cache.
|
||||
fn process_file(file: &Path, config: &Config, opts: &Options, cache: &Cache) -> FileResult {
|
||||
let name = file.display();
|
||||
let src = match std::fs::read_to_string(file) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Outcome::Failed(format!("{name}: {e}")),
|
||||
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
|
||||
};
|
||||
let hash = content_hash(src.as_bytes());
|
||||
if cache.is_clean(file, entry_for(hash, config)) {
|
||||
return FileResult::plain(Outcome::Cached);
|
||||
}
|
||||
let out = match format_contained(&src, config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => return Outcome::Failed(format!("{name}: {e}")),
|
||||
Err(e) => return FileResult::plain(Outcome::Failed(format!("{name}: {e}"))),
|
||||
};
|
||||
if opts.stdout {
|
||||
return Outcome::Printed(out);
|
||||
return FileResult::plain(Outcome::Printed(out));
|
||||
}
|
||||
if out == src {
|
||||
return Outcome::Unchanged;
|
||||
// A fixed point: worth remembering, exactly as it is on disk.
|
||||
return FileResult { outcome: Outcome::Unchanged, clean: Some(hash) };
|
||||
}
|
||||
if opts.diff {
|
||||
Outcome::Changed(diff::unified(&name.to_string(), &src, &out))
|
||||
FileResult::plain(Outcome::Changed(diff::unified(&name.to_string(), &src, &out)))
|
||||
} else if opts.check {
|
||||
Outcome::Changed(format!("would reformat: {name}\n"))
|
||||
FileResult::plain(Outcome::Changed(format!("would reformat: {name}\n")))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
Outcome::Failed(format!("{name}: {e}"))
|
||||
FileResult::plain(Outcome::Failed(format!("{name}: {e}")))
|
||||
} else {
|
||||
Outcome::Changed(String::new())
|
||||
// The bytes now on disk are formatted, so they are what the cache
|
||||
// records — not the input's hash.
|
||||
FileResult {
|
||||
outcome: Outcome::Changed(String::new()),
|
||||
clean: Some(content_hash(out.as_bytes())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache entry for content formatted under `config`. The *values* are
|
||||
/// the key, not the config file that produced them, so identical settings
|
||||
/// from different `vfmt.toml` files share entries.
|
||||
fn entry_for(content: u64, config: &Config) -> Entry {
|
||||
Entry { content, line_length: config.max_width, indent: config.indent_width }
|
||||
}
|
||||
|
||||
/// Builds rayon's global pool. Worker stacks are sized for the parser's
|
||||
/// recursion limit (see `WORKER_STACK`); `--threads 0` lets rayon pick.
|
||||
fn build_pool(opts: &Options) -> Result<(), String> {
|
||||
@@ -258,7 +313,7 @@ fn stdin_config(opts: &Options) -> Result<Config, String> {
|
||||
Ok(opts.config_with(&file))
|
||||
}
|
||||
|
||||
fn report(opts: &Options, changed: usize, unchanged: usize, errors: usize) {
|
||||
fn report(opts: &Options, changed: usize, unchanged: usize, cached: usize, errors: usize) {
|
||||
let verb = if opts.read_only() { "would be reformatted" } else { "reformatted" };
|
||||
let mut summary = Vec::new();
|
||||
if changed > 0 {
|
||||
@@ -267,6 +322,11 @@ fn report(opts: &Options, changed: usize, unchanged: usize, errors: usize) {
|
||||
if unchanged > 0 {
|
||||
summary.push(format!("{unchanged} file{} left unchanged", plural(unchanged)));
|
||||
}
|
||||
if cached > 0 {
|
||||
// Cached files are counted as unchanged too — they are — so this
|
||||
// segment only ever adds information.
|
||||
summary.push(format!("{cached} file{} from cache", plural(cached)));
|
||||
}
|
||||
if errors > 0 {
|
||||
// Parse errors, I/O errors, failed safety checks and contained
|
||||
// panics all land here; in every case the file was left untouched.
|
||||
|
||||
+354
-1
@@ -61,13 +61,39 @@ impl Drop for TempDir {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs vfmt with the cache switched off. Every test here shares one
|
||||
/// working directory (the crate's), so a default-on cache would put a
|
||||
/// `.vfmt_cache/` in the source tree *and* let one test's run change what
|
||||
/// another observes. The cache tests opt back in with `run_raw` and their
|
||||
/// own `--cache-dir`.
|
||||
fn run(args: &[&str]) -> Output {
|
||||
run_raw(&with_no_cache(args))
|
||||
}
|
||||
|
||||
/// `args` with `--no-cache` inserted after the subcommand, if there is one,
|
||||
/// so that everything the caller wrote keeps its exact position (a test that
|
||||
/// checks `--exclude` with no value must still find no value).
|
||||
fn with_no_cache<'a>(args: &[&'a str]) -> Vec<&'a str> {
|
||||
let mut args = args.to_vec();
|
||||
let at = usize::from(matches!(args.first(), Some(&"check" | &"format")));
|
||||
args.insert(at, "--no-cache");
|
||||
args
|
||||
}
|
||||
|
||||
/// Runs vfmt exactly as given, cache and all.
|
||||
fn run_raw(args: &[&str]) -> Output {
|
||||
Command::new(VFMT).args(args).output().expect("run vfmt")
|
||||
}
|
||||
|
||||
/// Runs vfmt exactly as given, from `dir` — the cache's default location
|
||||
/// is relative to the working directory.
|
||||
fn run_in(dir: &TempDir, args: &[&str]) -> Output {
|
||||
Command::new(VFMT).args(args).current_dir(&dir.path).output().expect("run vfmt")
|
||||
}
|
||||
|
||||
fn run_with_stdin(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(VFMT)
|
||||
.args(args)
|
||||
.args(with_no_cache(args))
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -989,3 +1015,330 @@ fn a_fence_holds_even_in_a_file_that_does_not_parse() {
|
||||
let out = run(&["--check", &path]);
|
||||
assert_eq!(code(&out), 2);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The "already formatted" cache. See docs/features/format-cache/README.md.
|
||||
// These tests drive the cache on purpose, so they use `run_raw`/`run_in`
|
||||
// rather than the `--no-cache` helper the rest of the file uses.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The version stamped into every cache entry: the workspace version, which
|
||||
/// `vfmt_core` reads with the same `env!`.
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
impl TempDir {
|
||||
/// A cache directory of this test's own, so tests cannot share entries.
|
||||
fn cache(&self) -> String {
|
||||
self.path.join("cache-dir").to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn cache_file(&self) -> PathBuf {
|
||||
self.path.join("cache-dir").join("cache")
|
||||
}
|
||||
}
|
||||
|
||||
/// One hand-written cache line, for the tests that forge entries.
|
||||
fn cache_line(
|
||||
path: &str,
|
||||
content: &str,
|
||||
line_length: usize,
|
||||
indent: usize,
|
||||
version: &str,
|
||||
) -> String {
|
||||
let hash = vfmt_core::cache::content_hash(content.as_bytes());
|
||||
format!("{hash:016x}\t{line_length}\t{indent}\t{version}\t{path}\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_run_over_a_formatted_tree_comes_entirely_from_the_cache() {
|
||||
let dir = TempDir::new("cache-warm");
|
||||
dir.write("a.sv", FORMATTED);
|
||||
dir.write("sub/b.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
|
||||
let cold = run_raw(&["--check", &dir.root(), "--cache-dir", &cache]);
|
||||
assert_eq!(code(&cold), 0, "{}", stderr(&cold));
|
||||
assert!(stderr(&cold).contains("2 files left unchanged"), "{}", stderr(&cold));
|
||||
assert!(!stderr(&cold).contains("from cache"), "a cold run hits nothing: {}", stderr(&cold));
|
||||
|
||||
let warm = run_raw(&["--check", &dir.root(), "--cache-dir", &cache]);
|
||||
assert_eq!(code(&warm), 0, "{}", stderr(&warm));
|
||||
assert!(stderr(&warm).contains("2 files from cache"), "{}", stderr(&warm));
|
||||
// A hit is still an unchanged file: no CI grep changes meaning.
|
||||
assert!(stderr(&warm).contains("2 files left unchanged"), "{}", stderr(&warm));
|
||||
assert_eq!(stdout(&warm), "", "a hit prints nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatting_a_file_caches_what_was_written_not_what_was_read() {
|
||||
let dir = TempDir::new("cache-write");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
let cache = dir.cache();
|
||||
|
||||
let first = run_raw(&[&path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&first), 0, "{}", stderr(&first));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
assert!(!stderr(&first).contains("from cache"), "{}", stderr(&first));
|
||||
|
||||
// The *output*'s hash went in, so the very next run is a hit.
|
||||
let second = run_raw(&[&path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&second), 0, "{}", stderr(&second));
|
||||
assert!(stderr(&second).contains("1 file from cache"), "{}", stderr(&second));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_content_invalidates_the_entry() {
|
||||
let dir = TempDir::new("cache-content");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
|
||||
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
|
||||
dir.write("a.sv", UNFORMATTED);
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "the edited file must be re-checked: {}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_indent_invalidates_the_entry() {
|
||||
let dir = TempDir::new("cache-config");
|
||||
let path = dir.write("a.sv", INDENT_2);
|
||||
let cache = dir.cache();
|
||||
|
||||
// Clean at the default indent of 2…
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
|
||||
// …and the settings are part of the key, so indent 4 is a miss.
|
||||
let out = run_raw(&["--check", "--indent", "4", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "indent 4 must not hit the indent 2 entry: {}", stderr(&out));
|
||||
|
||||
// Same for the width.
|
||||
let path = dir.write("wide.sv", WIDE);
|
||||
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
|
||||
let out = run_raw(&["--check", "--line-length", "40", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "line-length 40 must not hit the default entry: {}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hit_skips_the_work_entirely() {
|
||||
// A forged entry for a file the formatter cannot even parse: if the
|
||||
// run comes back clean, the whole pipeline really was skipped rather
|
||||
// than run and found to agree.
|
||||
let dir = TempDir::new("cache-skips");
|
||||
let path = dir.write("a.sv", UNPARSEABLE);
|
||||
let cache = dir.cache();
|
||||
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
|
||||
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 2, "without an entry this file is an error");
|
||||
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNPARSEABLE, 100, 2, VERSION)).unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "a hit does no work at all: {}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), UNPARSEABLE, "and still writes nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_config_file_change_invalidates_the_entry_too() {
|
||||
let dir = TempDir::new("cache-tomlchange");
|
||||
dir.write("vfmt.toml", "indent = 2\n");
|
||||
let path = dir.write("a.sv", INDENT_2);
|
||||
let cache = dir.cache();
|
||||
|
||||
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
|
||||
dir.write("vfmt.toml", "indent = 4\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "the resolved settings are the key: {}", stderr(&out));
|
||||
// …and an equivalent config written a different way is still a hit.
|
||||
dir.write("vfmt.toml", "indent = 2 # back again\n");
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_entry_from_another_vfmt_version_is_ignored() {
|
||||
let dir = TempDir::new("cache-version");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
let cache = dir.cache();
|
||||
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
|
||||
|
||||
// A forged entry claiming this unformatted file is clean. With this
|
||||
// version's stamp it is believed…
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, VERSION)).unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "the forged entry proves entries are really read");
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// …and with any other version's stamp it is not.
|
||||
std::fs::write(dir.cache_file(), cache_line(&path, UNFORMATTED, 100, 2, "0.0.0-other"))
|
||||
.unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "another version's entry must not be trusted: {}", stderr(&out));
|
||||
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_cache_file_is_tolerated_and_rebuilt() {
|
||||
let dir = TempDir::new("cache-corrupt");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
std::fs::create_dir_all(dir.path.join("cache-dir")).unwrap();
|
||||
|
||||
for corrupt in ["garbage\n", "\0\0\0\n", "not-a-hash\t100\t2\t0.2.0\t/a.sv\n", ""] {
|
||||
std::fs::write(dir.cache_file(), corrupt).unwrap();
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "a corrupt cache is never an error: {}", stderr(&out));
|
||||
assert!(!stderr(&out).contains("from cache"), "{corrupt:?}: {}", stderr(&out));
|
||||
// …and the run rewrote it, so the next one hits.
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{corrupt:?}: {}", stderr(&out));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_cache_neither_reads_nor_writes() {
|
||||
let dir = TempDir::new("cache-off");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
|
||||
// Nothing is created…
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache, "--no-cache"]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert!(!dir.cache_file().exists(), "--no-cache must not write");
|
||||
|
||||
// …and an existing entry is not consulted.
|
||||
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
|
||||
assert!(dir.cache_file().exists());
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache, "--no-cache"]);
|
||||
assert!(!stderr(&out).contains("from cache"), "--no-cache must not read: {}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_would_reformat_verdict_is_never_cached() {
|
||||
let dir = TempDir::new("cache-dirty");
|
||||
let path = dir.write("a.sv", UNFORMATTED);
|
||||
let cache = dir.cache();
|
||||
|
||||
// Every --check run must re-check a dirty file: the fix is external.
|
||||
for _ in 0..3 {
|
||||
let out = run_raw(&["--check", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
assert!(stdout(&out).contains("would reformat:"), "{}", stdout(&out));
|
||||
assert!(!stderr(&out).contains("from cache"), "{}", stderr(&out));
|
||||
}
|
||||
// Same for --diff, which must keep printing the hunk.
|
||||
let first = run_raw(&["--diff", &path, "--cache-dir", &cache]);
|
||||
let second = run_raw(&["--diff", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&second), 1);
|
||||
assert_eq!(first.stdout, second.stdout, "--diff output must not decay with the cache");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_is_never_cached() {
|
||||
let dir = TempDir::new("cache-error");
|
||||
let good = dir.write("a.sv", FORMATTED);
|
||||
let bad = dir.write("b.sv", UNPARSEABLE);
|
||||
let cache = dir.cache();
|
||||
|
||||
for _ in 0..2 {
|
||||
let out = run_raw(&["--check", &dir.root(), "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 2, "the broken file must be reported every run");
|
||||
assert!(stderr(&out).contains("1 file failed to format"), "{}", stderr(&out));
|
||||
}
|
||||
// The good file next to it still got cached.
|
||||
let out = run_raw(&["--check", &dir.root(), "--cache-dir", &cache]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
assert_eq!(dir.read("a.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("b.sv"), UNPARSEABLE);
|
||||
let _ = (good, bad);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_does_not_change_output_at_any_thread_count() {
|
||||
let dir = TempDir::new("cache-threads");
|
||||
mixed_tree(&dir);
|
||||
let cache = dir.cache();
|
||||
let root = dir.root();
|
||||
|
||||
// Warm it, then compare a parallel and a serial warm run byte for byte.
|
||||
let cold = run_raw(&["--check", &root, "--cache-dir", &cache]);
|
||||
let parallel = run_raw(&["--check", &root, "--cache-dir", &cache]);
|
||||
let serial = run_raw(&["--check", &root, "--cache-dir", &cache, "--threads", "1"]);
|
||||
assert_eq!(code(¶llel), code(&serial));
|
||||
assert_eq!(parallel.stdout, serial.stdout, "stdout must not depend on threads");
|
||||
assert_eq!(parallel.stderr, serial.stderr, "stderr must not depend on threads");
|
||||
assert_eq!(code(¶llel), 2, "the two broken files still win");
|
||||
assert!(stderr(¶llel).contains("24 files from cache"), "{}", stderr(¶llel));
|
||||
// The cold run's own stdout (the would-reformat lines) is unchanged by
|
||||
// the cache: the 24 dirty files are re-reported every time.
|
||||
assert_eq!(cold.stdout, parallel.stdout, "a warm run reports the same work");
|
||||
|
||||
// And the cache file itself is stable across runs.
|
||||
let a = std::fs::read(dir.cache_file()).unwrap();
|
||||
let _ = run_raw(&["--check", &root, "--cache-dir", &cache]);
|
||||
assert_eq!(a, std::fs::read(dir.cache_file()).unwrap(), "the store is deterministic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_cache_lives_in_the_working_directory_and_ignores_itself() {
|
||||
let dir = TempDir::new("cache-default");
|
||||
dir.write("a.sv", FORMATTED);
|
||||
|
||||
let out = run_in(&dir, &["--check", "."]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
let cache_dir = dir.path.join(".vfmt_cache");
|
||||
assert!(cache_dir.join("cache").is_file(), "the default cache is cwd-relative");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(cache_dir.join(".gitignore")).unwrap(),
|
||||
"*\n",
|
||||
"the cache directory ignores itself, the way cargo marks target/"
|
||||
);
|
||||
|
||||
let out = run_in(&dir, &["--check", "."]);
|
||||
assert!(stderr(&out).contains("1 file from cache"), "{}", stderr(&out));
|
||||
|
||||
// Nothing but the cache file and its .gitignore is left behind.
|
||||
let mut names: Vec<String> = std::fs::read_dir(&cache_dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
|
||||
.collect();
|
||||
names.sort();
|
||||
assert_eq!(names, vec![".gitignore".to_string(), "cache".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdin_never_caches() {
|
||||
let dir = TempDir::new("cache-stdin");
|
||||
let cache = dir.cache();
|
||||
let out = run_with_stdin_raw(&["-", "--cache-dir", &cache], FORMATTED);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stdout(&out), FORMATTED);
|
||||
assert!(!dir.cache_file().exists(), "stdin mode has no path to key on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stdout_mode_prints_every_file_even_when_the_cache_is_warm() {
|
||||
let dir = TempDir::new("cache-stdout");
|
||||
let path = dir.write("a.sv", FORMATTED);
|
||||
let cache = dir.cache();
|
||||
|
||||
assert_eq!(code(&run_raw(&["--check", &path, "--cache-dir", &cache])), 0);
|
||||
let out = run_raw(&["--stdout", &path, "--cache-dir", &cache]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(stdout(&out), FORMATTED, "--stdout must print, never skip");
|
||||
}
|
||||
|
||||
fn run_with_stdin_raw(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(VFMT)
|
||||
.args(args)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.expect("spawn vfmt");
|
||||
child.stdin.as_mut().expect("stdin").write_all(input.as_bytes()).expect("write stdin");
|
||||
child.wait_with_output().expect("run vfmt")
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
//! The "already formatted" cache: a per-path record of content that a
|
||||
//! previous run verified is a fixed point, so a repeat run can skip the
|
||||
//! file entirely.
|
||||
//!
|
||||
//! Only the *clean* verdict is ever stored — never an error and never
|
||||
//! "would reformat" — so a stale, missing or wrong entry can only ever
|
||||
//! cause work to be redone, never a diagnostic to be lost. See
|
||||
//! `docs/features/format-cache/README.md` for the key, the storage
|
||||
//! format and the collision posture.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write as _;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The default cache directory, resolved against the current directory.
|
||||
pub const DEFAULT_DIR: &str = ".vfmt_cache";
|
||||
|
||||
/// The entry file inside the cache directory.
|
||||
const FILE: &str = "cache";
|
||||
|
||||
/// vfmt's version, part of every entry: a new release may format the same
|
||||
/// bytes differently, so another version's entries are ignored.
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
/// What one entry asserts about one path: this content, under these
|
||||
/// settings, is already formatted.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Entry {
|
||||
/// FNV-1a hash of the file's bytes as they are on disk.
|
||||
pub content: u64,
|
||||
/// The `line-length` that verdict was reached under.
|
||||
pub line_length: usize,
|
||||
/// The `indent` that verdict was reached under.
|
||||
pub indent: usize,
|
||||
}
|
||||
|
||||
/// The cache for one run: loaded once at startup, written once at exit.
|
||||
pub struct Cache {
|
||||
/// Where to write at the end of the run; `None` when the cache is off.
|
||||
path: Option<PathBuf>,
|
||||
entries: HashMap<String, Entry>,
|
||||
}
|
||||
|
||||
impl Cache {
|
||||
/// Loads the cache stored in `dir`. Never fails: a missing, unreadable
|
||||
/// or corrupt file simply yields an empty cache that the run rebuilds.
|
||||
pub fn load(dir: &Path) -> Cache {
|
||||
let path = dir.join(FILE);
|
||||
let entries =
|
||||
std::fs::read_to_string(&path).ok().and_then(|text| parse(&text)).unwrap_or_default();
|
||||
Cache { path: Some(path), entries }
|
||||
}
|
||||
|
||||
/// A cache that reads nothing and writes nothing (`--no-cache`).
|
||||
pub fn disabled() -> Cache {
|
||||
Cache { path: None, entries: HashMap::new() }
|
||||
}
|
||||
|
||||
/// True when `path`'s current content was already verified formatted
|
||||
/// under these settings by this version of vfmt.
|
||||
pub fn is_clean(&self, path: &Path, entry: Entry) -> bool {
|
||||
key(path).and_then(|k| self.entries.get(k)) == Some(&entry)
|
||||
}
|
||||
|
||||
/// Records that `path` holds content that is a fixed point. A no-op
|
||||
/// when the cache is off, or when the path cannot be stored.
|
||||
pub fn record(&mut self, path: &Path, entry: Entry) {
|
||||
if self.path.is_none() {
|
||||
return;
|
||||
}
|
||||
if let Some(k) = key(path) {
|
||||
self.entries.insert(k.to_string(), entry);
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the cache back, atomically. Failure is deliberately silent:
|
||||
/// the cache is an optimization, and a run must not change its output
|
||||
/// or its exit code because a directory happened to be read-only.
|
||||
pub fn store(&self) {
|
||||
let Some(path) = &self.path else { return };
|
||||
let Some(dir) = path.parent() else { return };
|
||||
if std::fs::create_dir_all(dir).is_err() {
|
||||
return;
|
||||
}
|
||||
// Self-ignoring, the way cargo marks `target/`.
|
||||
let ignore = dir.join(".gitignore");
|
||||
if !ignore.exists() {
|
||||
let _ = std::fs::write(&ignore, "*\n");
|
||||
}
|
||||
let tmp = dir.join(format!("{FILE}.{}.tmp", std::process::id()));
|
||||
if std::fs::write(&tmp, self.render()).is_ok() && std::fs::rename(&tmp, path).is_err() {
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/// The file's text: one line per entry, sorted by path so that two
|
||||
/// runs over the same tree write byte-identical caches. Entries whose
|
||||
/// file is gone are dropped, so the file cannot grow forever.
|
||||
fn render(&self) -> String {
|
||||
let mut paths: Vec<&String> = self.entries.keys().collect();
|
||||
paths.sort();
|
||||
let mut text = String::new();
|
||||
for path in paths {
|
||||
if !Path::new(path).exists() {
|
||||
continue;
|
||||
}
|
||||
let entry = &self.entries[path];
|
||||
let _ = writeln!(
|
||||
text,
|
||||
"{:016x}\t{}\t{}\t{VERSION}\t{path}",
|
||||
entry.content, entry.line_length, entry.indent
|
||||
);
|
||||
}
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a, 64-bit. Hand-rolled because the hash is written to disk and
|
||||
/// std's `DefaultHasher` is explicitly not stable across Rust releases;
|
||||
/// FNV-1a is byte-exactly specified and needs no dependency.
|
||||
pub fn content_hash(bytes: &[u8]) -> u64 {
|
||||
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
const PRIME: u64 = 0x0000_0100_0000_01b3;
|
||||
let mut hash = OFFSET;
|
||||
for byte in bytes {
|
||||
hash ^= u64::from(*byte);
|
||||
hash = hash.wrapping_mul(PRIME);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// A path's key in the store, or `None` for one that cannot be written on
|
||||
/// a line of text (not UTF-8, or containing a tab or newline). Such a file
|
||||
/// is simply never cached.
|
||||
fn key(path: &Path) -> Option<&str> {
|
||||
let text = path.to_str()?;
|
||||
if text.is_empty() || text.contains('\t') || text.contains('\n') {
|
||||
return None;
|
||||
}
|
||||
Some(text)
|
||||
}
|
||||
|
||||
/// Parses the store. `None` means "this file is not something vfmt wrote"
|
||||
/// — one malformed line discards the whole cache, because partial trust in
|
||||
/// a file already caught lying is not worth the branch. Entries from
|
||||
/// another vfmt version are dropped individually; that is staleness, not
|
||||
/// corruption.
|
||||
fn parse(text: &str) -> Option<HashMap<String, Entry>> {
|
||||
let mut entries = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let mut fields = line.splitn(5, '\t');
|
||||
let content = u64::from_str_radix(fields.next()?, 16).ok()?;
|
||||
let line_length = fields.next()?.parse().ok()?;
|
||||
let indent = fields.next()?.parse().ok()?;
|
||||
let version = fields.next()?;
|
||||
let path = fields.next()?;
|
||||
if path.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if version == VERSION {
|
||||
entries.insert(path.to_string(), Entry { content, line_length, indent });
|
||||
}
|
||||
}
|
||||
Some(entries)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A throwaway directory, removed on drop.
|
||||
struct TempDir {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl TempDir {
|
||||
fn new(tag: &str) -> TempDir {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
static COUNTER: AtomicUsize = AtomicUsize::new(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("vfmt-cache-{}-{tag}-{n}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("create temp dir");
|
||||
TempDir { path }
|
||||
}
|
||||
|
||||
/// Creates a file so that `render`'s existence check keeps it.
|
||||
fn file(&self, name: &str) -> PathBuf {
|
||||
let path = self.path.join(name);
|
||||
std::fs::write(&path, "x").expect("write file");
|
||||
path
|
||||
}
|
||||
|
||||
fn cache_text(&self) -> String {
|
||||
std::fs::read_to_string(self.path.join(FILE)).expect("read cache")
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn entry(content: u64) -> Entry {
|
||||
Entry { content, line_length: 100, indent: 2 }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fnv_1a_matches_the_published_vectors() {
|
||||
// The reference values for FNV-1a 64. If this ever changes, every
|
||||
// cache on every machine silently invalidates — hence the test.
|
||||
assert_eq!(content_hash(b""), 0xcbf2_9ce4_8422_2325);
|
||||
assert_eq!(content_hash(b"a"), 0xaf63_dc4c_8601_ec8c);
|
||||
assert_eq!(content_hash(b"foobar"), 0x8594_4171_f739_67e8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_cache_is_empty_not_an_error() {
|
||||
let dir = TempDir::new("missing");
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(Path::new("a.sv"), entry(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_round_trip_through_the_file() {
|
||||
let dir = TempDir::new("roundtrip");
|
||||
let file = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, entry(0xdead));
|
||||
cache.store();
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&file, entry(0xdead)));
|
||||
// Every field is part of the key.
|
||||
assert!(!reloaded.is_clean(&file, entry(0xbeef)));
|
||||
assert!(!reloaded.is_clean(&file, Entry { line_length: 80, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(&file, Entry { indent: 4, ..entry(0xdead) }));
|
||||
assert!(!reloaded.is_clean(Path::new("other.sv"), entry(0xdead)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_is_sorted_and_carries_the_version() {
|
||||
let dir = TempDir::new("format");
|
||||
let b = dir.file("b.sv");
|
||||
let a = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&b, entry(2));
|
||||
cache.record(&a, entry(1));
|
||||
cache.store();
|
||||
|
||||
let text = dir.cache_text();
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
assert!(lines[0].ends_with("a.sv"), "sorted by path: {text}");
|
||||
assert!(lines[1].ends_with("b.sv"), "sorted by path: {text}");
|
||||
assert_eq!(
|
||||
lines[0],
|
||||
format!("{:016x}\t100\t2\t{VERSION}\t{}", 1, a.to_string_lossy()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_directory_ignores_itself() {
|
||||
let dir = TempDir::new("selfignore");
|
||||
let file = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, entry(1));
|
||||
cache.store();
|
||||
assert_eq!(std::fs::read_to_string(dir.path.join(".gitignore")).unwrap(), "*\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_corrupt_file_is_ignored_wholesale() {
|
||||
for corrupt in [
|
||||
"garbage\n",
|
||||
"not-hex\t100\t2\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\twide\t2\t0.2.0\t/a.sv\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\n",
|
||||
"0000000000000001\t100\t2\t0.2.0\t\n",
|
||||
"\0\0\0\n",
|
||||
] {
|
||||
let dir = TempDir::new("corrupt");
|
||||
let file = dir.file("a.sv");
|
||||
// A good line first: a bad one anywhere discards all of them.
|
||||
let good = format!("{:016x}\t100\t2\t{VERSION}\t{}\n", 1, file.to_string_lossy());
|
||||
std::fs::write(dir.path.join(FILE), format!("{good}{corrupt}")).unwrap();
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&file, entry(1)), "should have been discarded: {corrupt:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_versions_entry_is_dropped_but_not_fatal() {
|
||||
let dir = TempDir::new("version");
|
||||
let old = dir.file("old.sv");
|
||||
let mine = dir.file("mine.sv");
|
||||
let text = format!(
|
||||
"{:016x}\t100\t2\t0.0.0-not-this-one\t{}\n{:016x}\t100\t2\t{VERSION}\t{}\n",
|
||||
1,
|
||||
old.to_string_lossy(),
|
||||
2,
|
||||
mine.to_string_lossy()
|
||||
);
|
||||
std::fs::write(dir.path.join(FILE), text).unwrap();
|
||||
|
||||
let cache = Cache::load(&dir.path);
|
||||
assert!(!cache.is_clean(&old, entry(1)), "another version's entry must not be trusted");
|
||||
assert!(cache.is_clean(&mine, entry(2)), "this version's entry survives alongside it");
|
||||
|
||||
// And it is not carried forward.
|
||||
cache.store();
|
||||
assert!(!dir.cache_text().contains("old.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_for_deleted_files_are_pruned_on_write() {
|
||||
let dir = TempDir::new("prune");
|
||||
let kept = dir.file("kept.sv");
|
||||
let gone = dir.file("gone.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&kept, entry(1));
|
||||
cache.record(&gone, entry(2));
|
||||
std::fs::remove_file(&gone).unwrap();
|
||||
cache.store();
|
||||
|
||||
let text = dir.cache_text();
|
||||
assert!(text.contains("kept.sv"), "{text}");
|
||||
assert!(!text.contains("gone.sv"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unvisited_entries_survive_a_later_run() {
|
||||
let dir = TempDir::new("survive");
|
||||
let first = dir.file("a.sv");
|
||||
let second = dir.file("b.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&first, entry(1));
|
||||
cache.store();
|
||||
|
||||
// A second run that only visits b.sv must not forget a.sv.
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&second, entry(2));
|
||||
cache.store();
|
||||
|
||||
let reloaded = Cache::load(&dir.path);
|
||||
assert!(reloaded.is_clean(&first, entry(1)));
|
||||
assert!(reloaded.is_clean(&second, entry(2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_disabled_cache_reads_and_writes_nothing() {
|
||||
let dir = TempDir::new("disabled");
|
||||
let file = dir.file("a.sv");
|
||||
let mut warm = Cache::load(&dir.path);
|
||||
warm.record(&file, entry(1));
|
||||
warm.store();
|
||||
let before = dir.cache_text();
|
||||
|
||||
let mut cache = Cache::disabled();
|
||||
assert!(!cache.is_clean(&file, entry(1)), "--no-cache must not read");
|
||||
cache.record(&file, entry(9));
|
||||
cache.store();
|
||||
assert_eq!(dir.cache_text(), before, "--no-cache must not write");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_is_created_when_the_cache_is_off() {
|
||||
let dir = TempDir::new("nothing");
|
||||
let cache = Cache::disabled();
|
||||
cache.store();
|
||||
assert!(!dir.path.join(FILE).exists());
|
||||
assert!(!dir.path.join(".gitignore").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_directory_is_created_on_demand() {
|
||||
let dir = TempDir::new("mkdir");
|
||||
let file = dir.file("a.sv");
|
||||
let nested = dir.path.join("deep/inner");
|
||||
let mut cache = Cache::load(&nested);
|
||||
cache.record(&file, entry(1));
|
||||
cache.store();
|
||||
assert!(Cache::load(&nested).is_clean(&file, entry(1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_temporary_file_is_left_behind() {
|
||||
let dir = TempDir::new("tmp");
|
||||
let file = dir.file("a.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&file, entry(1));
|
||||
cache.store();
|
||||
let leftovers: Vec<_> = std::fs::read_dir(&dir.path)
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok())
|
||||
.map(|e| e.file_name().to_string_lossy().into_owned())
|
||||
.filter(|n| n.ends_with(".tmp"))
|
||||
.collect();
|
||||
assert!(leftovers.is_empty(), "{leftovers:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_path_that_cannot_be_stored_is_simply_not_cached() {
|
||||
let dir = TempDir::new("weirdpath");
|
||||
let weird = dir.path.join("a\tb.sv");
|
||||
let mut cache = Cache::load(&dir.path);
|
||||
cache.record(&weird, entry(1));
|
||||
cache.store();
|
||||
assert!(!Cache::load(&dir.path).is_clean(&weird, entry(1)));
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The parts of vfmt that decide *which* files are processed and *with what
|
||||
//! settings*, shared by the `vfmt` CLI and the `vfmt-server` language server.
|
||||
//!
|
||||
//! Both modules were lifted out of `crates/vfmt` unchanged so the two front
|
||||
//! ends cannot silently disagree: an editor's format-on-save must find the
|
||||
//! same `vfmt.toml` and skip the same files as CI's `vfmt --check`. See
|
||||
//! `docs/features/vfmt-core-lift/README.md`, and
|
||||
//! `docs/features/{config-discovery,parallel-files}/README.md` for the rules
|
||||
//! themselves.
|
||||
//! `config` and `walk` were lifted out of `crates/vfmt` unchanged so the two
|
||||
//! front ends cannot silently disagree: an editor's format-on-save must find
|
||||
//! the same `vfmt.toml` and skip the same files as CI's `vfmt --check`.
|
||||
//! `cache` answers the third question of the same family — whether a file
|
||||
//! needs to be processed at all. See `docs/features/vfmt-core-lift/README.md`,
|
||||
//! and `docs/features/{config-discovery,parallel-files,format-cache}/README.md`
|
||||
//! for the rules themselves.
|
||||
|
||||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod walk;
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Alignment inference: read the author's intent out of the original spacing
|
||||
//! and decide, per group of similar lines, whether a construct is laid out
|
||||
//! aligned (padded to a common column) or flush-left (one separator).
|
||||
//!
|
||||
//! This is Verible's most-loved formatter feature minus the configuration: a
|
||||
//! group whose author padded any of its lines by four or more excess spaces —
|
||||
//! or that already sits at one common column — keeps its columns; everything
|
||||
//! else formats flush, which is what vfmt has always done. The two states are
|
||||
//! fixed points of each other, which is what lets the convergence check in
|
||||
//! `verify.rs` stay untouched; the argument is written out in
|
||||
//! `docs/features/alignment/README.md`.
|
||||
//!
|
||||
//! Every decision here is made while the document is built, from facts that
|
||||
//! depend only on the source text and the AST's nesting — never on anything
|
||||
//! the printer discovers later. That is deliberate: a decision the printer
|
||||
//! made would not be visible to the next formatting pass, and the two passes
|
||||
//! would disagree.
|
||||
|
||||
use crate::doc::{concat, text, Doc};
|
||||
|
||||
/// Excess spaces before a column's token that read as "the author aligned
|
||||
/// this". Verible's threshold, and the one number this module hard-codes.
|
||||
const HINT_EXCESS: usize = 4;
|
||||
|
||||
/// The spacing of one alignment column.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ColSpec {
|
||||
/// Spaces the flush layout writes before the column's token. This is the
|
||||
/// baseline excess is measured against: one space before a declaration's
|
||||
/// name, none before a connection's `(`.
|
||||
pub flush: usize,
|
||||
/// Least the aligned layout writes before it, i.e. what the widest row of
|
||||
/// the group gets. It only differs from `flush` where the flush spelling
|
||||
/// is tight: `.clk(clk)` flush, `.clk (clk)` aligned.
|
||||
pub min: usize,
|
||||
}
|
||||
|
||||
/// One candidate row of an alignment group, already measured.
|
||||
///
|
||||
/// The row's document is a list of cells split at the alignment columns:
|
||||
/// `cells[k + 1]` starts with the token that opens column `k`. Only the widths
|
||||
/// are kept here — planning never looks at the documents themselves.
|
||||
pub struct Row {
|
||||
/// Flat width of each cell; always `columns + 1` entries.
|
||||
pub widths: Vec<usize>,
|
||||
/// Source byte offset of the token opening each column.
|
||||
pub anchors: Vec<u32>,
|
||||
/// Width printed after the last cell on the same line: the `,` a list
|
||||
/// element takes, or the `;` a declaration ends with.
|
||||
pub tail: usize,
|
||||
}
|
||||
|
||||
/// Where an aligned group's columns land, measured from the first cell's own
|
||||
/// column. Every row of the group shares one plan.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Align {
|
||||
targets: Vec<usize>,
|
||||
}
|
||||
|
||||
/// Decide whether `rows` want alignment, and if so where their columns land.
|
||||
///
|
||||
/// `budget` is how many columns the rows have to play with: the line limit
|
||||
/// less the indentation they will be printed at. A group whose widest aligned
|
||||
/// line would not fit in it is laid out flush *as a whole* — never some rows
|
||||
/// aligned and some not.
|
||||
///
|
||||
/// `None` means flush-left — today's layout — and is also the answer for
|
||||
/// anything the rule is not sure about: a group of one, a group with nothing
|
||||
/// to pad, a row whose column token starts its own line.
|
||||
pub fn plan(src: &str, rows: &[&Row], specs: &[ColSpec], budget: usize) -> Option<Align> {
|
||||
if rows.len() < 2 {
|
||||
return None;
|
||||
}
|
||||
let cols = specs.len();
|
||||
if rows.iter().any(|r| r.widths.len() != cols + 1 || r.anchors.len() != cols) {
|
||||
return None;
|
||||
}
|
||||
// A row with an empty first cell has no prefix to pad against.
|
||||
if rows.iter().any(|r| r.widths[0] == 0) {
|
||||
return None;
|
||||
}
|
||||
// Nothing to align: every row's cells are the same width, so the aligned
|
||||
// and the flush layouts are the same bytes. Answering "flush" is what
|
||||
// keeps the two from taking turns — see the README's fixed-point
|
||||
// argument.
|
||||
if (0..cols).all(|k| rows.iter().all(|r| r.widths[k] == rows[0].widths[k])) {
|
||||
return None;
|
||||
}
|
||||
if !wants_alignment(src, rows, specs) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut targets = Vec::with_capacity(cols);
|
||||
let mut offset = 0usize;
|
||||
for (k, spec) in specs.iter().enumerate() {
|
||||
offset += rows.iter().map(|r| r.widths[k]).max().unwrap_or(0) + spec.min;
|
||||
targets.push(offset);
|
||||
}
|
||||
let extent = offset + rows.iter().map(|r| r.widths[cols] + r.tail).max().unwrap_or(0);
|
||||
if extent > budget {
|
||||
return None;
|
||||
}
|
||||
Some(Align { targets })
|
||||
}
|
||||
|
||||
/// Does the original spacing ask for alignment? Either some row was padded by
|
||||
/// [`HINT_EXCESS`] spaces past what the flush layout writes, or every column
|
||||
/// already sits at one source column and at least one row was padded at all.
|
||||
///
|
||||
/// The second clause is what makes an aligned group stay aligned: the
|
||||
/// formatter's own output has exactly that shape.
|
||||
fn wants_alignment(src: &str, rows: &[&Row], specs: &[ColSpec]) -> bool {
|
||||
let mut max_excess = 0usize;
|
||||
let mut one_column = true;
|
||||
for (k, spec) in specs.iter().enumerate() {
|
||||
let mut first: Option<usize> = None;
|
||||
for row in rows {
|
||||
let offset = row.anchors[k] as usize;
|
||||
let Some(gap) = gap_before(src, offset) else { return false };
|
||||
max_excess = max_excess.max(gap.saturating_sub(spec.flush));
|
||||
let column = column_of(src, offset);
|
||||
match first {
|
||||
None => first = Some(column),
|
||||
Some(c) => one_column &= c == column,
|
||||
}
|
||||
}
|
||||
}
|
||||
max_excess >= HINT_EXCESS || (one_column && max_excess >= 1)
|
||||
}
|
||||
|
||||
/// Join one row's cells: flush (a fixed separator per column) when `plan` is
|
||||
/// `None`, padded out to the group's columns when it is not.
|
||||
pub fn render(cells: &[Doc], specs: &[ColSpec], plan: Option<&Align>) -> Doc {
|
||||
let plan = plan.filter(|p| p.targets.len() + 1 == cells.len());
|
||||
let mut docs = Vec::with_capacity(cells.len() * 2);
|
||||
let mut width = 0usize;
|
||||
for (k, cell) in cells.iter().enumerate() {
|
||||
if k > 0 {
|
||||
let spec = specs.get(k - 1).copied().unwrap_or(ColSpec { flush: 1, min: 1 });
|
||||
// `saturating_sub` and the `min` floor are belt and braces: a
|
||||
// target is computed from these very widths, so it always leaves
|
||||
// room. Two tokens must never end up glued together.
|
||||
let pad = match plan {
|
||||
Some(p) => p.targets[k - 1].saturating_sub(width).max(spec.min),
|
||||
None => spec.flush,
|
||||
};
|
||||
docs.push(text(" ".repeat(pad)));
|
||||
width += pad;
|
||||
}
|
||||
docs.push(cell.clone());
|
||||
width += flat_width(cell).unwrap_or(0);
|
||||
}
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// Flat width of a document in characters, or `None` when it holds a forced
|
||||
/// break — a comment inside a row makes that row unalignable rather than
|
||||
/// guessing at a width it does not have.
|
||||
pub fn flat_width(d: &Doc) -> Option<usize> {
|
||||
match d {
|
||||
Doc::Text(s) => Some(s.chars().count()),
|
||||
Doc::Line => Some(1),
|
||||
Doc::SoftLine | Doc::IfBreak(_) => Some(0),
|
||||
Doc::Concat(items) | Doc::Indent(items) | Doc::Group(items) => {
|
||||
items.iter().try_fold(0, |acc, d| Some(acc + flat_width(d)?))
|
||||
}
|
||||
Doc::HardLine | Doc::BlankLine | Doc::Verbatim(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Horizontal whitespace written immediately before `offset`, or `None` when
|
||||
/// the token starts its line — a row laid out that way says nothing about the
|
||||
/// author's column intent, so its group formats flush.
|
||||
fn gap_before(src: &str, offset: usize) -> Option<usize> {
|
||||
let before = src.get(..offset)?;
|
||||
let gap = before.len() - before.trim_end_matches([' ', '\t']).len();
|
||||
match before[..before.len() - gap].chars().next_back() {
|
||||
Some('\n') | None => None,
|
||||
_ => Some(gap),
|
||||
}
|
||||
}
|
||||
|
||||
/// 1-based character column of `offset`.
|
||||
fn column_of(src: &str, offset: usize) -> usize {
|
||||
let before = src.get(..offset).unwrap_or("");
|
||||
let line = match before.rfind('\n') {
|
||||
Some(nl) => &before[nl + 1..],
|
||||
None => before,
|
||||
};
|
||||
line.chars().count() + 1
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn row(widths: &[usize], anchors: &[u32], tail: usize) -> Row {
|
||||
Row { widths: widths.to_vec(), anchors: anchors.to_vec(), tail }
|
||||
}
|
||||
|
||||
const NAME: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }];
|
||||
const WIDE: usize = 100;
|
||||
|
||||
#[test]
|
||||
fn gaps_and_columns() {
|
||||
let src = "ab cd\nef";
|
||||
assert_eq!(gap_before(src, 5), Some(3));
|
||||
assert_eq!(column_of(src, 5), 6);
|
||||
// `ef` starts its line.
|
||||
assert_eq!(gap_before(src, 8), None);
|
||||
assert_eq!(column_of(src, 8), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn four_excess_spaces_align_a_group() {
|
||||
// Five spaces where flush writes one: four excess, the threshold.
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
||||
let plan = plan(src, &[&rows[0], &rows[1]], NAME, WIDE).expect("aligned");
|
||||
assert_eq!(plan.targets, vec![5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_excess_spaces_are_not_a_hint() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[6], 0), row(&[4, 1], &[13], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_spaces_stay_flush() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[3], 0), row(&[4, 1], &[10], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_common_column_stays_aligned() {
|
||||
let src = "aa x\nbbbb x\n";
|
||||
let rows = [row(&[2, 1], &[5], 0), row(&[4, 1], &[12], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_widths_have_nothing_to_align() {
|
||||
let src = "aa x\naa y\n";
|
||||
let rows = [row(&[2, 1], &[6], 0), row(&[2, 1], &[14], 0)];
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, WIDE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_of_one_is_never_aligned() {
|
||||
let src = "aa x\n";
|
||||
let rows = [row(&[2, 1], &[6], 0)];
|
||||
assert!(plan(src, &[&rows[0]], NAME, WIDE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_that_would_overflow_the_line_is_flush() {
|
||||
let src = "aa x\nbbbb y\n";
|
||||
let rows = [row(&[2, 1], &[7], 0), row(&[4, 1], &[14], 0)];
|
||||
// Widest aligned line is 5 + 1 = 6 columns.
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 6).is_some());
|
||||
assert!(plan(src, &[&rows[0], &rows[1]], NAME, 5).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_flush_writes_the_flush_separator() {
|
||||
let cells = [text("input wire"), text("clk")];
|
||||
let doc = render(&cells, NAME, None);
|
||||
assert_eq!(flat_width(&doc), Some(14));
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
//! one-element-per-line port/connection lists when a construct does not fit
|
||||
//! on a single line, cuddled `begin`/`end`.
|
||||
|
||||
use crate::align::{self, Align, ColSpec, Row};
|
||||
use crate::doc::*;
|
||||
use crate::fence::{self, Region};
|
||||
use crate::printer::{contains_hard_line, Printer};
|
||||
@@ -26,6 +27,18 @@ impl Default for Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// An ANSI port's one alignment column: the name, one space off the type.
|
||||
const ANSI_PORT_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }];
|
||||
|
||||
/// A named connection's one alignment column: the `(` of the value. It is
|
||||
/// written tight when flush (`.clk(clk)`) and one space off the name when
|
||||
/// aligned (`.clk (clk)`), which is Verible's spelling of both.
|
||||
const CONNECTION_COLS: &[ColSpec] = &[ColSpec { flush: 0, min: 1 }];
|
||||
|
||||
/// A `parameter`/`localparam` declaration's two alignment columns: the name,
|
||||
/// and the `=` of its value.
|
||||
const PARAM_DECL_COLS: &[ColSpec] = &[ColSpec { flush: 1, min: 1 }, ColSpec { flush: 1, min: 1 }];
|
||||
|
||||
/// Everything that can stop the formatter from producing output.
|
||||
#[derive(Debug)]
|
||||
pub enum FormatError {
|
||||
@@ -75,7 +88,7 @@ pub fn format_source(source: &str, config: &Config) -> Result<String, FormatErro
|
||||
fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Error> {
|
||||
let file = vlog_parser::parse_source(source)?;
|
||||
let regions = fence::collect(source, &file);
|
||||
let fmt = Fmt { _cfg: config, src: source, regions };
|
||||
let fmt = Fmt { cfg: config, src: source, regions };
|
||||
let doc = fmt.file(&file);
|
||||
let printer = Printer { max_width: config.max_width, indent_width: config.indent_width };
|
||||
let mut out = printer.print(&doc);
|
||||
@@ -88,7 +101,7 @@ fn format_once(source: &str, config: &Config) -> Result<String, vlog_parser::Err
|
||||
}
|
||||
|
||||
struct Fmt<'a> {
|
||||
_cfg: &'a Config,
|
||||
cfg: &'a Config,
|
||||
/// The text the AST was parsed from — what `// verilog_format: off`
|
||||
/// regions are spliced out of.
|
||||
src: &'a str,
|
||||
@@ -521,6 +534,181 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Alignment inference
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Plan the alignment of a sequence of candidate rows.
|
||||
///
|
||||
/// `rows[i]` is `None` for an element that cannot be aligned, and
|
||||
/// `breaks[i]` is true for one that starts a new group. Both split the
|
||||
/// sequence into maximal runs, and every element of a run that is planned
|
||||
/// aligned gets the same [`Align`] — the padding is a property of the
|
||||
/// group, never of one line.
|
||||
fn align_groups(
|
||||
&self,
|
||||
rows: &[Option<Row>],
|
||||
breaks: &[bool],
|
||||
specs: &[ColSpec],
|
||||
depth: usize,
|
||||
) -> Vec<Option<Align>> {
|
||||
// What is left of the line once the rows' own indentation is paid
|
||||
// for. `depth` comes from the AST's nesting, so it is the same on
|
||||
// every pass — which is what keeps the verdict stable.
|
||||
let budget = self.cfg.max_width.saturating_sub(depth * self.cfg.indent_width);
|
||||
let mut out = vec![None; rows.len()];
|
||||
let mut i = 0;
|
||||
while i < rows.len() {
|
||||
if rows[i].is_none() {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while j < rows.len() && rows[j].is_some() && !breaks[j] {
|
||||
j += 1;
|
||||
}
|
||||
let run: Vec<&Row> = rows[i..j].iter().flatten().collect();
|
||||
if let Some(plan) = align::plan(self.src, &run, specs, budget) {
|
||||
for slot in &mut out[i..j] {
|
||||
*slot = Some(plan.clone());
|
||||
}
|
||||
}
|
||||
i = j;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Measure one candidate row. `None` — meaning "cannot be aligned" — when
|
||||
/// the cells did not split at every column, or when one of them holds a
|
||||
/// comment and so has no flat width.
|
||||
fn row_of(cells: &[Doc], anchors: Vec<u32>, tail: usize) -> Option<Row> {
|
||||
if cells.len() != anchors.len() + 1 {
|
||||
return None;
|
||||
}
|
||||
let widths: Option<Vec<usize>> = cells.iter().map(align::flat_width).collect();
|
||||
Some(Row { widths: widths?, anchors, tail })
|
||||
}
|
||||
|
||||
/// Which elements of a bracketed list start a new alignment group: those
|
||||
/// with a comment or an attribute of their own — both print on their own
|
||||
/// line — and those a compiler directive was written in front of.
|
||||
///
|
||||
/// A blank line is deliberately *not* a boundary here: `delimited` drops
|
||||
/// blank lines between list elements, so a boundary drawn at one would
|
||||
/// vanish from the output and the next pass would group differently.
|
||||
fn list_breaks<'m>(
|
||||
metas: impl Iterator<Item = &'m Meta>,
|
||||
directives: &[ListDirective],
|
||||
) -> Vec<bool> {
|
||||
let mut breaks: Vec<bool> =
|
||||
metas.map(|m| !m.leading.is_empty() || !m.attrs.is_empty()).collect();
|
||||
for d in directives {
|
||||
if let Some(b) = breaks.get_mut(d.before) {
|
||||
*b = true;
|
||||
}
|
||||
}
|
||||
breaks
|
||||
}
|
||||
|
||||
/// The alignment plan for a module header's ANSI port list.
|
||||
fn ansi_port_aligns(
|
||||
&self,
|
||||
ports: &[AnsiPort],
|
||||
directives: &[ListDirective],
|
||||
depth: usize,
|
||||
) -> Vec<Option<Align>> {
|
||||
let rows: Vec<Option<Row>> = ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
Self::row_of(
|
||||
&self.ansi_port_cells(p),
|
||||
vec![p.name_span.start],
|
||||
usize::from(p.comma),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let breaks = Self::list_breaks(ports.iter().map(|p| &p.meta), directives);
|
||||
self.align_groups(&rows, &breaks, ANSI_PORT_COLS, depth)
|
||||
}
|
||||
|
||||
/// The alignment plan for an instance's named connection list.
|
||||
fn connection_aligns(
|
||||
&self,
|
||||
conns: &[Connection],
|
||||
directives: &[ListDirective],
|
||||
depth: usize,
|
||||
) -> Vec<Option<Align>> {
|
||||
let rows: Vec<Option<Row>> = conns
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let paren = self.open_paren_offset(c.name_span.end)?;
|
||||
Self::row_of(&self.connection_cells(c), vec![paren], usize::from(c.comma))
|
||||
})
|
||||
.collect();
|
||||
let breaks = Self::list_breaks(conns.iter().map(|c| &c.meta), directives);
|
||||
self.align_groups(&rows, &breaks, CONNECTION_COLS, depth)
|
||||
}
|
||||
|
||||
/// The alignment plan for the `parameter`/`localparam` declarations among
|
||||
/// a run of module (or package, or class) items.
|
||||
fn param_decl_aligns(&self, items: &[Item], depth: usize) -> Vec<Option<Align>> {
|
||||
let rows: Vec<Option<Row>> = items.iter().map(|i| self.param_decl_row(i)).collect();
|
||||
if rows.iter().all(Option::is_none) {
|
||||
return vec![None; items.len()];
|
||||
}
|
||||
// Unlike a bracketed list, an item sequence prints the blank lines the
|
||||
// source wrote, so a blank line is a boundary the next pass sees too.
|
||||
let breaks: Vec<bool> = items
|
||||
.iter()
|
||||
.map(|i| i.meta.blank_before || !i.meta.leading.is_empty() || !i.meta.attrs.is_empty())
|
||||
.collect();
|
||||
self.align_groups(&rows, &breaks, PARAM_DECL_COLS, depth)
|
||||
}
|
||||
|
||||
/// Measure a `parameter`/`localparam` item as an alignment row.
|
||||
///
|
||||
/// Only the plain shape joins a group: one declarator, with a value, no
|
||||
/// comments of its own, not inside a fenced region. Anything else formats
|
||||
/// the way it always has and splits the group in two.
|
||||
fn param_decl_row(&self, item: &Item) -> Option<Row> {
|
||||
let ItemKind::ParamDecl(d) = &item.kind else { return None };
|
||||
if !item.meta.attrs.is_empty() || self.is_fenced(item.span) {
|
||||
return None;
|
||||
}
|
||||
let [decl] = &d.declarators[..] else { return None };
|
||||
if !decl.meta.leading.is_empty()
|
||||
|| !decl.meta.before_sep.is_empty()
|
||||
|| decl.meta.trailing.is_some()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let init = decl.init.as_ref()?;
|
||||
let eq = self.eq_offset(init.span.start, decl.name_span.end)?;
|
||||
// The tail is the `;` the item ends with.
|
||||
Self::row_of(&self.param_decl_cells(d, decl, init), vec![decl.name_span.start, eq], 1)
|
||||
}
|
||||
|
||||
/// Byte offset of the `=` between a declarator's name and its value, or
|
||||
/// `None` when anything but whitespace stands between the two.
|
||||
fn eq_offset(&self, value_start: u32, after_name: u32) -> Option<u32> {
|
||||
let bytes = self.src.as_bytes();
|
||||
let mut pos = value_start as usize;
|
||||
while pos > 0 && matches!(bytes[pos - 1], b' ' | b'\t' | b'\r' | b'\n') {
|
||||
pos -= 1;
|
||||
}
|
||||
(pos > after_name as usize && bytes.get(pos - 1) == Some(&b'=')).then_some(pos as u32 - 1)
|
||||
}
|
||||
|
||||
/// Byte offset of the `(` opening a named connection's value.
|
||||
fn open_paren_offset(&self, after_name: u32) -> Option<u32> {
|
||||
let bytes = self.src.as_bytes();
|
||||
let mut pos = after_name as usize;
|
||||
while matches!(bytes.get(pos), Some(b' ' | b'\t' | b'\r' | b'\n')) {
|
||||
pos += 1;
|
||||
}
|
||||
(bytes.get(pos) == Some(&b'(')).then_some(pos as u32)
|
||||
}
|
||||
|
||||
/// A bracketed expression list (concatenation, call arguments, `inside`
|
||||
/// set). Comments on an element ride along and break the list open.
|
||||
fn expr_list(&self, open: &str, items: &[ExprItem], close: &str) -> Doc {
|
||||
@@ -549,10 +737,11 @@ impl<'a> Fmt<'a> {
|
||||
/// Sequence of items at one indent level, preserving single blank lines
|
||||
/// between them. An item a fenced region swallowed emits nothing, and
|
||||
/// contributes no separator either.
|
||||
fn item_seq(&self, items: &[Item]) -> Vec<Doc> {
|
||||
fn item_seq(&self, items: &[Item], depth: usize) -> Vec<Doc> {
|
||||
let aligns = self.param_decl_aligns(items, depth);
|
||||
let mut docs = Vec::new();
|
||||
for item in items {
|
||||
let item_docs = self.item_docs(item);
|
||||
for (item, align) in items.iter().zip(&aligns) {
|
||||
let item_docs = self.item_docs(item, align.as_ref(), depth);
|
||||
if item_docs.is_empty() {
|
||||
continue;
|
||||
}
|
||||
@@ -594,7 +783,7 @@ impl<'a> Fmt<'a> {
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn file(&self, f: &SourceFile) -> Doc {
|
||||
let mut docs = self.item_seq(&f.items);
|
||||
let mut docs = self.item_seq(&f.items, 0);
|
||||
for c in &f.dangling {
|
||||
let doc = match self.slot(c) {
|
||||
Slot::Covered => continue,
|
||||
@@ -609,15 +798,15 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn item(&self, item: &Item) -> Doc {
|
||||
concat(self.item_docs(item))
|
||||
fn item(&self, item: &Item, depth: usize) -> Doc {
|
||||
concat(self.item_docs(item, None, depth))
|
||||
}
|
||||
|
||||
/// One item: its leading comments, then — unless a fenced region is
|
||||
/// already emitting its bytes — its attributes, code and trailing
|
||||
/// comment. Comments before the `off` fence are still emitted; comments
|
||||
/// are never dropped.
|
||||
fn item_docs(&self, item: &Item) -> Vec<Doc> {
|
||||
fn item_docs(&self, item: &Item, align: Option<&Align>, depth: usize) -> Vec<Doc> {
|
||||
if self.is_fenced(item.span) {
|
||||
// The item's own bytes, its attributes included, are emitted
|
||||
// verbatim by the fence; only its leading comments are ours.
|
||||
@@ -630,20 +819,20 @@ impl<'a> Fmt<'a> {
|
||||
return docs;
|
||||
}
|
||||
let mut docs = self.leading(&item.meta);
|
||||
docs.push(self.item_kind(&item.kind));
|
||||
docs.push(self.item_kind(&item.kind, align, depth));
|
||||
docs.extend(self.trailing(&item.meta));
|
||||
docs
|
||||
}
|
||||
|
||||
fn item_kind(&self, kind: &ItemKind) -> Doc {
|
||||
fn item_kind(&self, kind: &ItemKind, align: Option<&Align>, depth: usize) -> Doc {
|
||||
match kind {
|
||||
ItemKind::Module(m) => self.module(m),
|
||||
ItemKind::Module(m) => self.module(m, depth),
|
||||
ItemKind::Package { kw, name, items, dangling, end_label, .. } => {
|
||||
let mut docs = vec![text(format!("{kw} {name};"))];
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(items));
|
||||
body.extend(self.item_seq(items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
docs.push(indent(body));
|
||||
@@ -659,31 +848,31 @@ impl<'a> Fmt<'a> {
|
||||
ItemKind::Import(paths) => text(format!("import {};", join_paths(paths))),
|
||||
ItemKind::Timeunit(t) => text(format!("{t};")),
|
||||
ItemKind::Typedef(t) => self.typedef(t),
|
||||
ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d), text(";")]),
|
||||
ItemKind::ParamDecl(d) => concat(vec![self.param_decl(d, align), text(";")]),
|
||||
ItemKind::DataDecl(d) => concat(vec![self.data_decl(d), text(";")]),
|
||||
ItemKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
|
||||
ItemKind::ContAssign(a) => self.cont_assign(a),
|
||||
ItemKind::Always { kw, stmt } => self.stmt_as_body(text(kw.clone()), stmt),
|
||||
ItemKind::Initial(s) => self.stmt_as_body(text("initial"), s),
|
||||
ItemKind::Final(s) => self.stmt_as_body(text("final"), s),
|
||||
ItemKind::Instantiation(inst) => self.instantiation(inst),
|
||||
ItemKind::Instantiation(inst) => self.instantiation(inst, depth),
|
||||
ItemKind::GateInstantiation(g) => self.gate_instantiation(g),
|
||||
ItemKind::Genvar(names) => text(format!("genvar {};", join_names(names))),
|
||||
ItemKind::GenerateRegion { items, dangling } => {
|
||||
let mut body = Vec::new();
|
||||
if !items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(items));
|
||||
body.extend(self.item_seq(items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(dangling));
|
||||
concat(vec![text("generate"), indent(body), Doc::HardLine, text("endgenerate")])
|
||||
}
|
||||
ItemKind::GenIf(g) => self.gen_if(g),
|
||||
ItemKind::GenFor(g) => self.gen_for(g),
|
||||
ItemKind::GenCase(g) => self.gen_case(g),
|
||||
ItemKind::GenIf(g) => self.gen_if(g, depth),
|
||||
ItemKind::GenFor(g) => self.gen_for(g, depth),
|
||||
ItemKind::GenCase(g) => self.gen_case(g, depth),
|
||||
ItemKind::Function(f) => self.function(f),
|
||||
ItemKind::Task(t) => self.task(t),
|
||||
ItemKind::Class(c) => self.class(c),
|
||||
ItemKind::Class(c) => self.class(c, depth),
|
||||
ItemKind::Verbatim(raw) => self.raw_text(raw),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
let parts: Vec<Doc> = pairs
|
||||
@@ -702,7 +891,7 @@ impl<'a> Fmt<'a> {
|
||||
// Module
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn module(&self, m: &Module) -> Doc {
|
||||
fn module(&self, m: &Module, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(format!("{} {}", m.kw, m.name))];
|
||||
let has_imports = !m.imports.is_empty();
|
||||
if has_imports {
|
||||
@@ -739,17 +928,25 @@ impl<'a> Fmt<'a> {
|
||||
// A port list whose every element sits in an `ifdef arm still holds
|
||||
// directives while being `PortList::Empty`, so the two are laid out by
|
||||
// the same code.
|
||||
let broken = !m.port_directives.is_empty();
|
||||
let mut broken = !m.port_directives.is_empty();
|
||||
match &m.ports {
|
||||
PortList::None => docs.push(text(";")),
|
||||
PortList::Empty | PortList::Ansi(_) | PortList::NonAnsi(_) => {
|
||||
let items: Vec<ListItem> = match &m.ports {
|
||||
PortList::Ansi(ports) => ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
ListItem::from_meta(&p.meta, self.ansi_port(p)).with_comma(p.comma)
|
||||
})
|
||||
.collect(),
|
||||
PortList::Ansi(ports) => {
|
||||
// An aligned list is a broken list: alignment only
|
||||
// means anything one element per line.
|
||||
let aligns = self.ansi_port_aligns(ports, &m.port_directives, depth + 1);
|
||||
broken |= aligns.iter().any(Option::is_some);
|
||||
ports
|
||||
.iter()
|
||||
.zip(&aligns)
|
||||
.map(|(p, a)| {
|
||||
ListItem::from_meta(&p.meta, self.ansi_port(p, a.as_ref()))
|
||||
.with_comma(p.comma)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
PortList::NonAnsi(ports) => ports
|
||||
.iter()
|
||||
.map(|p| {
|
||||
@@ -769,7 +966,7 @@ impl<'a> Fmt<'a> {
|
||||
let mut body = Vec::new();
|
||||
if !m.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&m.items));
|
||||
body.extend(self.item_seq(&m.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&m.dangling));
|
||||
docs.push(indent(body));
|
||||
@@ -806,25 +1003,43 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn ansi_port(&self, p: &AnsiPort) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
fn ansi_port(&self, p: &AnsiPort, align: Option<&Align>) -> Doc {
|
||||
align::render(&self.ansi_port_cells(p), ANSI_PORT_COLS, align)
|
||||
}
|
||||
|
||||
/// An ANSI port split at its one alignment column, the name: the
|
||||
/// direction/net/type prefix, then the name and everything after it. A
|
||||
/// port with no prefix at all (a continuation port, `output a, b`) is one
|
||||
/// cell, which is what takes it out of every alignment group.
|
||||
fn ansi_port_cells(&self, p: &AnsiPort) -> Vec<Doc> {
|
||||
let mut prefix = Vec::new();
|
||||
if let Some(dir) = &p.dir {
|
||||
docs.push(text(format!("{dir} ")));
|
||||
prefix.push(text(format!("{dir} ")));
|
||||
}
|
||||
if let Some(net) = &p.net {
|
||||
docs.push(text(format!("{net} ")));
|
||||
prefix.push(text(format!("{net} ")));
|
||||
}
|
||||
if let Some(t) = self.data_type(&p.ty) {
|
||||
docs.push(t);
|
||||
docs.push(text(" "));
|
||||
prefix.push(t);
|
||||
prefix.push(text(" "));
|
||||
}
|
||||
docs.push(text(p.name.clone()));
|
||||
// The trailing space of the last prefix part is the column separator,
|
||||
// which `align::render` writes instead.
|
||||
if let Some(Doc::Text(last)) = prefix.last_mut() {
|
||||
if last.ends_with(' ') {
|
||||
last.pop();
|
||||
}
|
||||
}
|
||||
let mut docs = vec![text(p.name.clone())];
|
||||
docs.extend(self.unpacked_dims(&p.unpacked));
|
||||
if let Some(d) = &p.default {
|
||||
docs.push(text(" = "));
|
||||
docs.push(self.expr(d));
|
||||
}
|
||||
concat(docs)
|
||||
if prefix.is_empty() {
|
||||
return vec![concat(docs)];
|
||||
}
|
||||
vec![concat(prefix), concat(docs)]
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -986,7 +1201,23 @@ impl<'a> Fmt<'a> {
|
||||
group(vec![indent(inner)])
|
||||
}
|
||||
|
||||
fn param_decl(&self, d: &ParamDecl) -> Doc {
|
||||
/// A `parameter`/`localparam` declaration. With an alignment plan it is
|
||||
/// laid out as cells padded to the group's columns; without one it takes
|
||||
/// the flush path every other declaration takes.
|
||||
///
|
||||
/// The two must agree byte-for-byte when the padding collapses, because
|
||||
/// that is exactly what the printer's line-limit fallback does — and the
|
||||
/// next pass, seeing no excess spaces, comes back through the flush path.
|
||||
fn param_decl(&self, d: &ParamDecl, align: Option<&Align>) -> Doc {
|
||||
if let (Some(a), [decl]) = (align, &d.declarators[..]) {
|
||||
if let Some(init) = &decl.init {
|
||||
return align::render(
|
||||
&self.param_decl_cells(d, decl, init),
|
||||
PARAM_DECL_COLS,
|
||||
Some(a),
|
||||
);
|
||||
}
|
||||
}
|
||||
let mut docs = vec![text(d.kw.clone()), text(" ")];
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
docs.push(t);
|
||||
@@ -996,6 +1227,23 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A `parameter`/`localparam` declaration split at its two alignment
|
||||
/// columns: the keyword and type, the name, and the `= value`.
|
||||
fn param_decl_cells(&self, d: &ParamDecl, decl: &Declarator, init: &Expr) -> Vec<Doc> {
|
||||
let mut prefix = vec![text(d.kw.clone())];
|
||||
if let Some(t) = self.data_type(&d.ty) {
|
||||
prefix.push(text(" "));
|
||||
prefix.push(t);
|
||||
}
|
||||
let mut name = vec![text(decl.name.clone())];
|
||||
name.extend(self.unpacked_dims(&decl.unpacked));
|
||||
vec![
|
||||
concat(prefix),
|
||||
concat(name),
|
||||
concat(vec![text("="), group(vec![self.assign_rhs(self.expr(init))])]),
|
||||
]
|
||||
}
|
||||
|
||||
fn data_decl(&self, d: &DataDecl) -> Doc {
|
||||
let mut docs = Vec::new();
|
||||
if let Some(net) = &d.net {
|
||||
@@ -1176,7 +1424,7 @@ impl<'a> Fmt<'a> {
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn instantiation(&self, inst: &Instantiation) -> Doc {
|
||||
fn instantiation(&self, inst: &Instantiation, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(inst.module.clone())];
|
||||
let mut on_fresh_line = self.bracket_comments(&inst.param_comments, &mut docs, false);
|
||||
// An empty `#()` was written by hand and is reprinted as `#()`; a
|
||||
@@ -1200,7 +1448,7 @@ impl<'a> Fmt<'a> {
|
||||
if !self.bracket_comments(&only.meta.leading, &mut docs, on_fresh_line) {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.instance(only));
|
||||
docs.push(self.instance(only, depth));
|
||||
} else {
|
||||
if !on_fresh_line {
|
||||
docs.push(text(" "));
|
||||
@@ -1211,7 +1459,7 @@ impl<'a> Fmt<'a> {
|
||||
let mut inner = Vec::new();
|
||||
for (i, instance) in inst.instances.iter().enumerate() {
|
||||
inner.extend(self.leading(&instance.meta));
|
||||
inner.push(self.instance(instance));
|
||||
inner.push(self.instance(instance, depth + 1));
|
||||
if self.inline_comments(&instance.meta.before_sep, &mut inner) {
|
||||
inner.push(Doc::HardLine);
|
||||
}
|
||||
@@ -1235,7 +1483,7 @@ impl<'a> Fmt<'a> {
|
||||
}
|
||||
|
||||
/// One instance of a module instantiation: `u0 [3:0] (.a(x))`.
|
||||
fn instance(&self, instance: &Instance) -> Doc {
|
||||
fn instance(&self, instance: &Instance, depth: usize) -> Doc {
|
||||
let mut docs = vec![text(instance.name.clone())];
|
||||
if !instance.dims.is_empty() {
|
||||
docs.push(text(" "));
|
||||
@@ -1246,19 +1494,27 @@ impl<'a> Fmt<'a> {
|
||||
if !self.bracket_comments(&instance.conn_comments, &mut docs, false) {
|
||||
docs.push(text(" "));
|
||||
}
|
||||
docs.push(self.connections(&instance.conns, &instance.conn_directives));
|
||||
docs.push(self.connections(&instance.conns, &instance.conn_directives, depth + 1));
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
/// A connection list, with the `` `ifdef``-style directives written between
|
||||
/// its entries merged back into source order. A list holding one is laid
|
||||
/// out broken: a directive runs to end of line, so nothing may share it.
|
||||
fn connections(&self, conns: &Connections, directives: &[ListDirective]) -> Doc {
|
||||
fn connections(&self, conns: &Connections, directives: &[ListDirective], depth: usize) -> Doc {
|
||||
let mut broken = !directives.is_empty();
|
||||
let items: Vec<ListItem> = match conns {
|
||||
Connections::Named(list) => list
|
||||
.iter()
|
||||
.map(|c| ListItem::from_meta(&c.meta, self.connection(c)).with_comma(c.comma))
|
||||
.collect(),
|
||||
Connections::Named(list) => {
|
||||
let aligns = self.connection_aligns(list, directives, depth);
|
||||
broken |= aligns.iter().any(Option::is_some);
|
||||
list.iter()
|
||||
.zip(&aligns)
|
||||
.map(|(c, a)| {
|
||||
ListItem::from_meta(&c.meta, self.connection_aligned(c, a.as_ref()))
|
||||
.with_comma(c.comma)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
Connections::Ordered(list) => list
|
||||
.iter()
|
||||
.map(|c| {
|
||||
@@ -1271,10 +1527,40 @@ impl<'a> Fmt<'a> {
|
||||
.collect(),
|
||||
};
|
||||
let items = self.list_entries(items, directives);
|
||||
self.delimited("(", items, ")", !directives.is_empty())
|
||||
self.delimited("(", items, ")", broken)
|
||||
}
|
||||
|
||||
fn connection(&self, c: &Connection) -> Doc {
|
||||
self.connection_aligned(c, None)
|
||||
}
|
||||
|
||||
fn connection_aligned(&self, c: &Connection, align: Option<&Align>) -> Doc {
|
||||
align::render(&self.connection_cells(c), CONNECTION_COLS, align)
|
||||
}
|
||||
|
||||
/// A named connection split at its one alignment column, the `(` of the
|
||||
/// value: `.data_i` and `(bus[7:0])`. Everything else — `.*`, an implicit
|
||||
/// `.clk`, a positional value, a connection with comments inside its own
|
||||
/// parens — is one cell and never joins a group.
|
||||
fn connection_cells(&self, c: &Connection) -> Vec<Doc> {
|
||||
let plain = || vec![self.connection_plain(c)];
|
||||
if c.name.is_empty() || c.name == "*" {
|
||||
return plain();
|
||||
}
|
||||
let Some(e) = &c.expr else { return plain() };
|
||||
if matches!(e.kind, ExprKind::Empty(_)) {
|
||||
return plain();
|
||||
}
|
||||
let mut inner = vec![Doc::SoftLine, self.expr(e)];
|
||||
let ends_line = self.inline_comments(&c.close_comments, &mut inner);
|
||||
let close = if ends_line { Doc::HardLine } else { Doc::SoftLine };
|
||||
vec![
|
||||
text(format!(".{}", c.name)),
|
||||
concat(vec![text("("), group(vec![indent(inner), close]), text(")")]),
|
||||
]
|
||||
}
|
||||
|
||||
fn connection_plain(&self, c: &Connection) -> Doc {
|
||||
if c.name == "*" {
|
||||
return text(".*");
|
||||
}
|
||||
@@ -1338,9 +1624,9 @@ impl<'a> Fmt<'a> {
|
||||
// Generate constructs
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn gen_if(&self, g: &GenIf) -> Doc {
|
||||
fn gen_if(&self, g: &GenIf, depth: usize) -> Doc {
|
||||
let mut docs = vec![text("if "), self.parens(&g.cond)];
|
||||
let mut cuddle = self.gen_block(&mut docs, &g.then);
|
||||
let mut cuddle = self.gen_block(&mut docs, &g.then, depth);
|
||||
let mut els = &g.els;
|
||||
while let Some(e) = els {
|
||||
match e.as_ref() {
|
||||
@@ -1352,7 +1638,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(text("else if "));
|
||||
}
|
||||
docs.push(self.parens(&gi.cond));
|
||||
cuddle = self.gen_block(&mut docs, &gi.then);
|
||||
cuddle = self.gen_block(&mut docs, &gi.then, depth);
|
||||
els = &gi.els;
|
||||
}
|
||||
GenElse::Block(b) => {
|
||||
@@ -1362,7 +1648,7 @@ impl<'a> Fmt<'a> {
|
||||
docs.push(Doc::HardLine);
|
||||
docs.push(text("else"));
|
||||
}
|
||||
self.gen_block(&mut docs, b);
|
||||
self.gen_block(&mut docs, b, depth);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1372,7 +1658,7 @@ impl<'a> Fmt<'a> {
|
||||
|
||||
/// Append a generate block; returns true if it ended with `end` (so
|
||||
/// `else` can cuddle).
|
||||
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock) -> bool {
|
||||
fn gen_block(&self, docs: &mut Vec<Doc>, b: &GenBlock, depth: usize) -> bool {
|
||||
if b.is_block {
|
||||
match &b.label {
|
||||
Some(l) => docs.push(text(format!(" begin : {l}"))),
|
||||
@@ -1381,7 +1667,7 @@ impl<'a> Fmt<'a> {
|
||||
let mut body = Vec::new();
|
||||
if !b.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&b.items));
|
||||
body.extend(self.item_seq(&b.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&b.dangling));
|
||||
docs.push(indent(body));
|
||||
@@ -1390,12 +1676,12 @@ impl<'a> Fmt<'a> {
|
||||
true
|
||||
} else {
|
||||
let item = &b.items[0];
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.item(item)])]));
|
||||
docs.push(group(vec![indent(vec![Doc::Line, self.item(item, depth + 1)])]));
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_for(&self, g: &GenFor) -> Doc {
|
||||
fn gen_for(&self, g: &GenFor, depth: usize) -> Doc {
|
||||
let mut header = vec![text("for (")];
|
||||
if g.init_genvar {
|
||||
header.push(text("genvar "));
|
||||
@@ -1409,18 +1695,18 @@ impl<'a> Fmt<'a> {
|
||||
header.push(self.for_step(&g.step));
|
||||
header.push(text(")"));
|
||||
let mut docs = vec![concat(header)];
|
||||
self.gen_block(&mut docs, &g.body);
|
||||
self.gen_block(&mut docs, &g.body, depth);
|
||||
concat(docs)
|
||||
}
|
||||
|
||||
fn gen_case(&self, g: &GenCase) -> Doc {
|
||||
fn gen_case(&self, g: &GenCase, depth: usize) -> Doc {
|
||||
let mut docs = vec![text("case "), self.parens(&g.expr)];
|
||||
let mut body = Vec::new();
|
||||
for item in &g.items {
|
||||
body.push(if item.meta.blank_before { Doc::BlankLine } else { Doc::HardLine });
|
||||
body.extend(self.leading(&item.meta));
|
||||
let mut item_docs = vec![self.case_labels(&item.labels)];
|
||||
self.gen_block(&mut item_docs, &item.body);
|
||||
self.gen_block(&mut item_docs, &item.body, depth + 1);
|
||||
body.push(concat(item_docs));
|
||||
body.extend(self.trailing(&item.meta));
|
||||
}
|
||||
@@ -1471,7 +1757,7 @@ impl<'a> Fmt<'a> {
|
||||
/// A class: header on one line (its parameter and `extends` override
|
||||
/// lists break like any other list when they do not fit), body items at
|
||||
/// one more indent level, `endclass` with the label the source wrote.
|
||||
fn class(&self, c: &ClassDecl) -> Doc {
|
||||
fn class(&self, c: &ClassDecl, depth: usize) -> Doc {
|
||||
let mut head = String::new();
|
||||
for q in &c.prefix {
|
||||
head.push_str(q);
|
||||
@@ -1516,7 +1802,7 @@ impl<'a> Fmt<'a> {
|
||||
let mut body = Vec::new();
|
||||
if !c.items.is_empty() {
|
||||
body.push(Doc::HardLine);
|
||||
body.extend(self.item_seq(&c.items));
|
||||
body.extend(self.item_seq(&c.items, depth + 1));
|
||||
}
|
||||
body.extend(self.dangling(&c.dangling));
|
||||
docs.push(indent(body));
|
||||
@@ -1870,7 +2156,7 @@ impl<'a> Fmt<'a> {
|
||||
StmtKind::ExprStmt(e) => concat(vec![self.expr(e), text(";")]),
|
||||
StmtKind::EventTrigger(e) => concat(vec![text("-> "), self.expr(e), text(";")]),
|
||||
StmtKind::VarDecl(d) => concat(vec![self.data_decl(d), text(";")]),
|
||||
StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d), text(";")]),
|
||||
StmtKind::ParamDecl(d) => concat(vec![self.param_decl(d, None), text(";")]),
|
||||
StmtKind::PortDecl(d) => concat(vec![self.port_decl(d), text(";")]),
|
||||
StmtKind::Return(e) => match e {
|
||||
Some(e) => concat(vec![text("return "), self.expr(e), text(";")]),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Formatter engine: document IR + printer + formatting rules.
|
||||
|
||||
pub mod align;
|
||||
pub mod doc;
|
||||
pub mod fence;
|
||||
pub mod format;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
# ports: a hand-aligned group stays aligned
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: single spaces stay flush, and a list that fits collapses
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (input wire clk, input wire [WIDTH-1:0] data, output logic valid);
|
||||
endmodule
|
||||
====
|
||||
# ports: four excess spaces on one line converge the group to aligned
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: three excess spaces are below the threshold
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (input wire clk, input wire [WIDTH-1:0] data, output logic valid);
|
||||
endmodule
|
||||
====
|
||||
# ports: equal prefixes have nothing to align, so the padding collapses
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire rst,
|
||||
input wire ena
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (input wire clk, input wire rst, input wire ena);
|
||||
endmodule
|
||||
====
|
||||
# ports: a standalone comment splits the group in two
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
// the outputs
|
||||
output logic valid,
|
||||
output logic [7:0] count
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
// the outputs
|
||||
output logic valid,
|
||||
output logic [7:0] count
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: a compiler directive splits the group in two
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
`ifdef DEBUG
|
||||
output logic valid,
|
||||
output logic [7:0] count
|
||||
`endif
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
`ifdef DEBUG
|
||||
output logic valid,
|
||||
output logic [7:0] count
|
||||
`endif
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: an aligned line past the limit takes the whole group back to flush
|
||||
module m (
|
||||
input wire [SOME_REALLY_LONG_PARAMETER_NAME_XXXXXXXXXXXXXXXXXXXX-1:0] b,
|
||||
input wire a_very_long_signal_name_here_that_is_quite_long_indeed_yes,
|
||||
output logic c
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire [SOME_REALLY_LONG_PARAMETER_NAME_XXXXXXXXXXXXXXXXXXXX-1:0] b,
|
||||
input wire a_very_long_signal_name_here_that_is_quite_long_indeed_yes,
|
||||
output logic c
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: a continuation port has no prefix to pad, so the run ends at it
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [3:0] sel, more,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [3:0] sel,
|
||||
more,
|
||||
output logic valid
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: an aligned group keeps its trailing comments
|
||||
module m (
|
||||
input wire clk, // the clock
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid // high for one cycle
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk, // the clock
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid // high for one cycle
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# ports: alignment holds a list open that would otherwise fit on one line
|
||||
module m (
|
||||
input wire clk,
|
||||
output logic q
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire clk,
|
||||
output logic q
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# connections: a hand-aligned group stays aligned
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# connections: tight parens stay tight and the list collapses
|
||||
module m;
|
||||
sub u (
|
||||
.clk(clk),
|
||||
.reset_n(rst_n),
|
||||
.data_valid(dv)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (.clk(clk), .reset_n(rst_n), .data_valid(dv));
|
||||
endmodule
|
||||
====
|
||||
# connections: four spaces before one `(` converge the group to aligned
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n(rst_n),
|
||||
.data_valid(dv)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# connections: one space each is not a hint
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (.clk(clk), .reset_n(rst_n), .data_valid(dv));
|
||||
endmodule
|
||||
====
|
||||
# connections: an author who over-padded gets the computed column
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# connections: `.*` and an implicit `.name` are not alignable and split the group
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid,
|
||||
.ready (rdy),
|
||||
.last_thing (lt)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid,
|
||||
.ready (rdy),
|
||||
.last_thing (lt)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# connections: a standalone comment splits the group
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
// the data side
|
||||
.data_valid (dv),
|
||||
.ready (rdy)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
// the data side
|
||||
.data_valid (dv),
|
||||
.ready (rdy)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# connections: equal-width names have nothing to align
|
||||
module m;
|
||||
sub u (
|
||||
.clk_a (a),
|
||||
.clk_b (b),
|
||||
.clk_c (c)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (.clk_a(a), .clk_b(b), .clk_c(c));
|
||||
endmodule
|
||||
====
|
||||
# params: a hand-aligned `=` column stays aligned
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# params: single spaces stay flush
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# params: four excess spaces before one `=` converge the group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# params: the name column aligns too when the types differ
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam logic [31:0] LONGER = 32'hDEAD;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam logic [31:0] LONGER = 32'hDEAD;
|
||||
endmodule
|
||||
====
|
||||
# params: a blank line splits the group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
|
||||
localparam int B = 3;
|
||||
localparam int OTHER = 44;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
|
||||
localparam int B = 3;
|
||||
localparam int OTHER = 44;
|
||||
endmodule
|
||||
====
|
||||
# params: a standalone comment splits the group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
// a second table
|
||||
localparam int B = 3;
|
||||
localparam int OTHER = 44;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
// a second table
|
||||
localparam int B = 3;
|
||||
localparam int OTHER = 44;
|
||||
endmodule
|
||||
====
|
||||
# params: an unrelated item between two parameters splits the group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
wire w;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
wire w;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# params: a declaration without a value is not a row and splits the group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
parameter P;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
parameter P;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# params: two declarators in one statement are not a row
|
||||
module m;
|
||||
localparam int A = 1, B = 2;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1, B = 2;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# params: an author who over-padded gets the computed column
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
localparam int LONGEST_YET = 333;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
localparam int LONGEST_YET = 333;
|
||||
endmodule
|
||||
====
|
||||
# params: an aligned line past the limit takes the group back to flush
|
||||
module m;
|
||||
localparam int SHORT = 1;
|
||||
localparam logic [31:0] A_MUCH_LONGER_PARAMETER_NAME_GOES_HERE_OK_LONGER = 32'hDEADBEEF + SOME_XYZ;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int SHORT = 1;
|
||||
localparam logic [31:0] A_MUCH_LONGER_PARAMETER_NAME_GOES_HERE_OK_LONGER =
|
||||
32'hDEADBEEF + SOME_XYZ;
|
||||
endmodule
|
||||
====
|
||||
# params: one parameter is a group of one and never aligns
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
wire w;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
wire w;
|
||||
endmodule
|
||||
====
|
||||
# params: a trailing comment rides along with an aligned row
|
||||
module m;
|
||||
localparam int A = 1; // the first
|
||||
localparam int LONGER = 22; // the second
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1; // the first
|
||||
localparam int LONGER = 22; // the second
|
||||
endmodule
|
||||
====
|
||||
# params: a fenced parameter is emitted verbatim and splits the group
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
// verilog_format: off
|
||||
localparam int MID = 2;
|
||||
// verilog_format: on
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
// verilog_format: off
|
||||
localparam int MID = 2;
|
||||
// verilog_format: on
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
====
|
||||
# alignment applies inside a generate block at its own indentation
|
||||
module m;
|
||||
generate
|
||||
if (X) begin : g
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
generate
|
||||
if (X) begin : g
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
end
|
||||
endgenerate
|
||||
endmodule
|
||||
====
|
||||
# a comment written before an element's comma does not split the group
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk) /* c */,
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
sub u (
|
||||
.clk (clk) /* c */,
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# alignment in a package body: parameters align, the fence does not move
|
||||
package p;
|
||||
localparam int WIDTH = 8;
|
||||
localparam int DEPTHXX = 16;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
localparam int WIDTH = 8;
|
||||
localparam int DEPTHXX = 16;
|
||||
endpackage
|
||||
====
|
||||
# a class body's parameters align the same way
|
||||
class c;
|
||||
localparam int WIDTH = 8;
|
||||
localparam int DEPTHXX = 16;
|
||||
endclass
|
||||
----
|
||||
class c;
|
||||
localparam int WIDTH = 8;
|
||||
localparam int DEPTHXX = 16;
|
||||
endclass
|
||||
====
|
||||
# a hint on a list that would fit on one line still opens and aligns it
|
||||
module m (input wire a, output logic b);
|
||||
endmodule
|
||||
----
|
||||
module m (
|
||||
input wire a,
|
||||
output logic b
|
||||
);
|
||||
endmodule
|
||||
====
|
||||
# the same list without differing widths has nothing to align
|
||||
module m (input wire a, input wire b);
|
||||
endmodule
|
||||
----
|
||||
module m (input wire a, input wire b);
|
||||
endmodule
|
||||
@@ -768,3 +768,91 @@ fn a_dropped_method_qualifier_is_rejected() {
|
||||
let output = "class c;\n function void f();\n endfunction\nendclass\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Alignment inference: the layout it picks must be a fixed point at every
|
||||
// configured width, not just at the default one. See
|
||||
// `docs/features/alignment/README.md`.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Format `src` at `width`, then format that again, and return both.
|
||||
fn twice(src: &str, width: usize, indent: usize) -> (String, String) {
|
||||
let config = Config { max_width: width, indent_width: indent };
|
||||
let once = format_source(src, &config).expect("first pass");
|
||||
let again = format_source(&once, &config).expect("second pass");
|
||||
(once, again)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_aligned_group_is_a_fixed_point_at_every_width() {
|
||||
let src = "\
|
||||
module m (
|
||||
input wire clk,
|
||||
input wire [WIDTH-1:0] data,
|
||||
output logic valid
|
||||
);
|
||||
sub u (
|
||||
.clk (clk),
|
||||
.reset_n (rst_n),
|
||||
.data_valid (dv)
|
||||
);
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
";
|
||||
for width in [40, 60, 80, 100, 120, 200] {
|
||||
for indent in [2, 4] {
|
||||
let (once, again) = twice(src, width, indent);
|
||||
assert_eq!(once, again, "not a fixed point at width {width}, indent {indent}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_group_that_alignment_gives_up_on_still_converges() {
|
||||
// Regression: the alignment verdict used to be split between building
|
||||
// the document (which forced the list open) and printing it (which chose
|
||||
// the padding). At a narrow width the printer backed out while the forced
|
||||
// break stayed, and the `#( ... )` above the list broke differently on
|
||||
// the next pass.
|
||||
let src = "\
|
||||
module m;
|
||||
prim_buf #(
|
||||
.Width(NumBusyBits)
|
||||
) u_buf (
|
||||
.in_i ({$bits(mubi_t){ctrl_busy, if_busy, lsu_busy}}),
|
||||
.out_o(busy_bits_buf)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
for width in [40, 50, 60, 70, 80, 100] {
|
||||
let (once, again) = twice(src, width, 2);
|
||||
assert_eq!(once, again, "not a fixed point at width {width}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hint_converges_in_one_pass_and_then_holds() {
|
||||
let src = "\
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
";
|
||||
let (once, again) = twice(src, 100, 2);
|
||||
assert!(once.contains("localparam int A = 1;"), "expected an aligned `=`:\n{once}");
|
||||
assert_eq!(once, again);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_flush_group_stays_flush() {
|
||||
let src = "\
|
||||
module m;
|
||||
localparam int A = 1;
|
||||
localparam int LONGER = 22;
|
||||
endmodule
|
||||
";
|
||||
let (once, again) = twice(src, 100, 2);
|
||||
assert_eq!(once, src, "a group with no alignment hint must not gain one");
|
||||
assert_eq!(once, again);
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
# alignment
|
||||
|
||||
## Goal
|
||||
|
||||
Infer, from the spacing the author already wrote, whether a run of similar
|
||||
lines is meant to be **aligned** (padded to a common column) or **flush-left**
|
||||
(one separator between tokens), and reproduce that intent. This is Verible's
|
||||
most-loved formatter feature and the reason RTL teams tolerate a formatter at
|
||||
all: hand-aligned port lists, connection lists and parameter tables are how
|
||||
Verilog is read, and a formatter that flattens them is a formatter nobody
|
||||
runs. vfmt's rule is Verible's, minus the configuration surface: four or more
|
||||
excess spaces before a column's token means "align this", a group already
|
||||
sitting at one column stays there, and everything else formats exactly the way
|
||||
it did before this feature existed. The two layouts are fixed points of each
|
||||
other, so `format(format(x)) == format(x)` still holds by construction rather
|
||||
than by luck.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Four excess spaces is the threshold.** `HINT_EXCESS = 4` in `align.rs`,
|
||||
matching Verible. "Excess" is measured against what the *flush* layout would
|
||||
write in that position, not against zero: one space before a declaration's
|
||||
name, none before a connection's `(`. So `localparam int A = 1;` (five
|
||||
spaces) is a hint and `localparam int A = 1;` (four) is not.
|
||||
- **A tab counts as one space.** vfmt's `no-tabs` lint wants them gone anyway,
|
||||
and guessing a tab stop would make the verdict depend on a setting the
|
||||
formatter does not have.
|
||||
- **A group is a run of *adjacent* rows of one construct.** Alignment never
|
||||
reaches across constructs, across a comment, or across a blank line at item
|
||||
level. It is not a whole-file column solver.
|
||||
- **Only whole rows align.** A row holding a comment inside it has no flat
|
||||
width, so it drops out of every group rather than being measured with a
|
||||
guess.
|
||||
- **A hint outranks fitting on one line.** Because an aligned list is a broken
|
||||
list, `module m (input wire a, output logic b);` — five spaces where
|
||||
one would do, on a list that fits — is exploded into three lines and
|
||||
aligned. Five excess spaces is read as deliberate wherever it is written;
|
||||
treating a one-line list as a special case would mean the verdict depended
|
||||
on the layout rather than on the spacing, and the layout is what the
|
||||
formatter decides. Zero corpus files were affected.
|
||||
- **The trailing comment is not part of the line budget.** A `// ...` written
|
||||
after an aligned row can push that line past the line limit exactly as it
|
||||
can push a flush row past it. Counting it would let one long comment veto a
|
||||
whole group's alignment, which is worse than a long line; Verible does not
|
||||
count it either. Measured cost on the corpus: 2 lines in 578 files.
|
||||
- **The AST's nesting is the printed indentation.** The line-budget check
|
||||
needs to know the column a row starts in, and it takes it from a `depth`
|
||||
threaded through the item walk rather than from the printer. That mapping
|
||||
(`depth * indent_width`) is exact for every construct that aligns today; if
|
||||
it ever drifts, the consequence is a *worse* alignment verdict, never a
|
||||
wrong one, because the depth is a pure function of the AST and therefore
|
||||
identical on both passes.
|
||||
|
||||
## The rule as shipped
|
||||
|
||||
A **row** is one element of a candidate construct, split into *cells* at the
|
||||
positions that may be aligned. `cells[k + 1]` starts with the token that opens
|
||||
column `k`:
|
||||
|
||||
| Construct | Cells | Columns |
|
||||
|---|---|---|
|
||||
| ANSI port | `input wire [7:0]` / `data` | name (`flush` 1, `min` 1) |
|
||||
| Named connection | `.data_i` / `(bus)` | `(` (`flush` 0, `min` 1) |
|
||||
| `parameter`/`localparam` item | `localparam int` / `WIDTH` / `= 8` | name, `=` (both 1/1) |
|
||||
|
||||
`flush` is what the unaligned layout writes before the column; `min` is what
|
||||
the *widest* row of an aligned group gets. They differ only for connections,
|
||||
whose flush spelling is tight (`.clk(clk)`) and whose aligned spelling is not
|
||||
(`.clk (clk)`).
|
||||
|
||||
For a run of rows, let `gap[i][k]` be the horizontal whitespace the source
|
||||
wrote immediately before row `i`'s column-`k` token, `col[i][k]` its source
|
||||
column, and `w[i][k]` the flat width of cell `k`. The run is laid out
|
||||
**aligned** when *all* of the following hold:
|
||||
|
||||
1. it has **at least two rows**;
|
||||
2. every row's cell 0 is non-empty and every row's cells have a flat width
|
||||
(no comment inside a row);
|
||||
3. **there is something to pad**: for some column `k`, the `w[i][k]` are not
|
||||
all equal;
|
||||
4. **the author asked**, either
|
||||
- `max(gap[i][k] - flush[k]) >= 4` — some row carries four excess spaces;
|
||||
or
|
||||
- every column is internally consistent (`col[i][k]` equal over `i` for
|
||||
each `k`) **and** `max(gap[i][k] - flush[k]) >= 1` — the group is
|
||||
already sitting at one column;
|
||||
5. the widest aligned line **fits the line budget**: `max_width - depth *
|
||||
indent_width`.
|
||||
|
||||
Otherwise the run is flush — today's layout, byte for byte.
|
||||
|
||||
The columns of an aligned run are computed from the run's own widths, never
|
||||
from the columns the author used:
|
||||
|
||||
```
|
||||
target[0] = max_i(w[i][0]) + min[0]
|
||||
target[k] = target[k-1] + max_i(w[i][k]) + min[k]
|
||||
extent = target[last] + max_i(w[i][last+1] + tail[i])
|
||||
```
|
||||
|
||||
`tail` is the `,` a list element takes or the `;` a declaration ends with.
|
||||
**An aligned list is a broken list**: alignment means nothing with every
|
||||
element on one line, so a planned group forces its list one-element-per-line.
|
||||
|
||||
### Group boundaries
|
||||
|
||||
A run ends at anything that will still be visible to the next pass:
|
||||
|
||||
- a **standalone comment** or an `(* attribute *)` on the element — both print
|
||||
on their own line;
|
||||
- a **compiler directive** written between two elements of a list;
|
||||
- a **blank line**, *at item level only*. `delimited` deliberately drops blank
|
||||
lines between the elements of a bracketed list, so a boundary drawn at one
|
||||
would vanish from the output and the next pass would group differently. In a
|
||||
port or connection list a blank line is therefore **not** a boundary.
|
||||
- a row that cannot be aligned at all: a port with no type prefix (`output a,
|
||||
b`), a `.*` or implicit `.name`, a positional connection, a parameter with
|
||||
two declarators or no value, a fenced item, a row with a comment inside it.
|
||||
|
||||
A comment written between an element and its comma (`Meta::before_sep`) is
|
||||
*not* a boundary: it prints on the element's own line and does not move the
|
||||
columns.
|
||||
|
||||
## The fixed-point argument
|
||||
|
||||
Everything above is decided while the document is built, from the source text
|
||||
and the AST's nesting. Nothing is decided by the printer, because a decision
|
||||
the printer made would not be visible to the next pass. That is what makes the
|
||||
following exhaustive.
|
||||
|
||||
Take a run that formatted **aligned**. Its output has, for every column `k`,
|
||||
every row's token at the same output column (rule 4's second clause is
|
||||
satisfied); the widest row gets `min[k]` spaces, so its excess is 0, and the
|
||||
narrowest gets `min[k] + max_i(w[i][k]) - min_i(w[i][k]) >= min[k] + 1`, so
|
||||
`max_excess >= 1` — provided the widths differ, which rule 3 guaranteed. Rule
|
||||
5 held for the widths that produced this output and the widths are unchanged,
|
||||
so it holds again. The next pass therefore re-derives *aligned*, recomputes the
|
||||
same `target`s from the same widths, and emits the same bytes. **Fixed point.**
|
||||
|
||||
Take a run that formatted **flush**. Every gap is exactly `flush[k]`, so every
|
||||
excess is 0: rule 4's first clause fails, and its second needs `max_excess >=
|
||||
1`, so it fails too. The next pass re-derives *flush*. **Fixed point.**
|
||||
|
||||
The two hazards this design had to close, both of which are real and both of
|
||||
which cost a debugging round:
|
||||
|
||||
- **Equal widths.** Without rule 3, a run like `input wire a,` / `input
|
||||
wire b,` would be "aligned", but padding to equal widths writes the
|
||||
flush bytes — and the next pass, seeing zero excess, would say flush and
|
||||
re-flow the list onto one line. Rule 3 makes the first pass say flush too.
|
||||
- **A verdict split across phases.** The line-budget check (rule 5) first
|
||||
lived in the printer, which knows the real column, while the forced break
|
||||
lived in the document. When the printer backed out, the forced break stayed,
|
||||
and an enclosing `#( ... )` group measured `fits` differently on the next
|
||||
pass — `corpus/ibex/rtl/ibex_core.sv` at `--line-length 60` diverged. The
|
||||
fix was to move the budget into the document build, which is why `depth` is
|
||||
threaded through the item walk at all. Regression test:
|
||||
`a_group_that_alignment_gives_up_on_still_converges` in
|
||||
`tests/verification.rs`.
|
||||
|
||||
One-pass convergence follows the same way: a hinted run (rule 4, first clause)
|
||||
produces aligned output whose shape satisfies rule 4's second clause, so pass 2
|
||||
agrees with pass 1. An author who **over-padded** — aligned at column 40 when
|
||||
30 is enough — gets column 30 on pass 1, because the targets come from the
|
||||
run's widths, and column 30 again on pass 2. That is a change to the author's
|
||||
bytes, but it converges immediately and is the only way two people's tables
|
||||
can agree.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`:**
|
||||
|
||||
- `AnsiPort::name_span`, `ParamPort::name_span`, `Connection::name_span`,
|
||||
`Declarator::name_span`, `Expr::span`, `Item::span` — the byte offsets the
|
||||
anchors are derived from. Nothing new was added to the lexer or to
|
||||
`token.rs`: the minimal representation of "excess space before a token" is
|
||||
*no representation at all*. The anchor's byte offset plus the source text
|
||||
the formatter already holds (`Fmt::src`) yields both the preceding gap and
|
||||
the token's column by a backward scan of at most one line. Adding a field to
|
||||
`Token` would have duplicated a fact the spans already carry and put new
|
||||
weight on the losslessness/spans suite for nothing.
|
||||
- The comment attachment contract (`Meta::leading`, `Meta::attrs`,
|
||||
`Meta::before_sep`), which is what group boundaries are drawn from.
|
||||
|
||||
**Consumed from `vlog_formatter`:**
|
||||
|
||||
- `Config::max_width` / `Config::indent_width` for the line budget.
|
||||
- `fence::region_at` (via `Fmt::is_fenced`) to keep fenced items out of groups.
|
||||
|
||||
**Promised to the rest of the formatter:**
|
||||
|
||||
- `align::render(cells, specs, None)` writes exactly `specs[k].flush` spaces
|
||||
between cells. Every construct that grew cells must produce, in that mode,
|
||||
the same bytes it produced before — that equivalence is what makes "give up
|
||||
on alignment" indistinguishable from "never considered it".
|
||||
- `verify.rs` is untouched, and no normalization was widened. Alignment only
|
||||
ever inserts spaces *between* two tokens that already had whitespace between
|
||||
them, which the token-stream equivalence check ignores by design.
|
||||
- `doc.rs` and `printer.rs` are untouched: padding is `Doc::Text` computed at
|
||||
build time.
|
||||
|
||||
**Requested of nobody.** No other crate changed; `vlog_semantic`,
|
||||
`vlog_linter` and `vfmt_server` compile and pass unmodified.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Inference rule, written down before it was implemented
|
||||
- [x] `crates/vlog_formatter/src/align.rs`: `ColSpec`, `Row`, `Align`, `plan`,
|
||||
`render`, `flat_width`, `gap_before`, `column_of` + unit tests
|
||||
- [x] ANSI port declarations in module headers — name column
|
||||
- [x] Named connections in instance connection lists — the `(` column
|
||||
- [x] `parameter`/`localparam` module/package/class items — name and `=`
|
||||
columns
|
||||
- [x] Group boundaries: standalone comment, attribute, directive, blank line
|
||||
(item level), unalignable row
|
||||
- [x] Line-budget fallback, whole group at a time, decided at build time
|
||||
- [x] `depth` threaded through the item walk so the budget knows its column
|
||||
- [x] 39 cases in `tests/cases/alignment.cases`
|
||||
- [x] Four convergence tests at non-default widths in `tests/verification.rs`
|
||||
- [x] Zero churn on the pre-existing 397-case table and the fixture snapshots
|
||||
- [x] Corpus: 0 verification errors, 0 crashes, 0 round-trip failures
|
||||
- [x] `README.md` Style section, `TODO.md` §2
|
||||
- [ ] **Parked:** parameter *ports* in a `#( ... )` list (module and class
|
||||
headers). Structurally identical to an ANSI port row and nearly free to
|
||||
add, but it doubles the test matrix for a construct that is usually two
|
||||
or three entries long. Next thing to do here.
|
||||
- [ ] **Parked:** parameter *overrides* in an instantiation's `#( ... )`.
|
||||
Same shape as a named connection; the same argument applies.
|
||||
- [ ] **Parked:** the direction/type column of a port list (`input ` vs
|
||||
`output`) and the type column of a declaration. Verible aligns these as
|
||||
separate columns; vfmt collapses `input wire` to `input wire`. Adding
|
||||
them means a row's *first* cell splits too, and the hint rule then has
|
||||
to decide what a group means when one column is hinted and another is
|
||||
not.
|
||||
- [ ] **Parked:** the trailing-comment column. Verible aligns `// ...` after a
|
||||
port list; vfmt writes one space. This is the most visible remaining
|
||||
gap on real RTL.
|
||||
- [ ] **Parked:** `wire`/`logic` data declarations and `struct` members. Both
|
||||
are ordinary declaration rows; neither has the same cultural pull as the
|
||||
three shipped constructs.
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-19 — dev**
|
||||
|
||||
- Read `TODO.md` §2, `docs/features/format-fences`, `docs/features/comments-round`
|
||||
and the Verible-derived style rules in `README.md`. Wrote the rule above
|
||||
before writing code, including the fixed-point argument, then implemented
|
||||
it.
|
||||
- **Lexer trivia: nothing added.** The task allowed `lexer.rs`/`token.rs` for
|
||||
trivia. The minimal representation turned out to be none: `Token` already
|
||||
carries `line`/`col`/`span`, and every construct that aligns already carries
|
||||
a `name_span` (from the `name-spans` feature), so "excess space before this
|
||||
token" is `gap_before(src, anchor)` — a backward scan over spaces from the
|
||||
anchor's byte offset — and "the token's column" is `column_of(src, anchor)`.
|
||||
Both are derived on demand in `align.rs` from `Fmt::src`. The
|
||||
losslessness/spans suites are therefore untouched, which was the point of
|
||||
the constraint.
|
||||
- Splitting each construct into cells is the only change to existing layout
|
||||
code: `ansi_port_cells`, `connection_cells`, `param_decl_cells`. The first
|
||||
two replace the old single-document builders outright, so the flush path is
|
||||
the aligned path with zero-width padding and the two cannot drift.
|
||||
`param_decl` keeps its legacy body for the unaligned case, because
|
||||
`declarators` is shared with three other constructs and rewriting it would
|
||||
have risked churn for nothing; the equivalence of the two spellings is
|
||||
pinned by the `params: an aligned line past the limit takes the group back
|
||||
to flush` case.
|
||||
- **First design, backed out.** The line-budget check originally lived in the
|
||||
printer as a new `Doc::Pad { to, cost, flush }` node, because the printer is
|
||||
the only thing that knows the real column. That works for the padding but
|
||||
not for the *verdict*: the forced one-element-per-line break was decided at
|
||||
build time, so when the printer backed out the break stayed, and an
|
||||
enclosing group's `fits` changed between passes. Caught by a 2312-run
|
||||
config sweep over the corpus (`--line-length 60` on
|
||||
`corpus/ibex/rtl/ibex_core.sv`), not by the default-width suites. Replaced
|
||||
by a `depth: usize` threaded through `item_seq`/`item_docs`/`item_kind` and
|
||||
the constructs below them; `doc.rs` and `printer.rs` went back to their
|
||||
original contents. The lesson is worth keeping: **a layout verdict may not
|
||||
be split across the document/printer boundary**, because only the document
|
||||
is visible to the next pass.
|
||||
- Verified, in order:
|
||||
- `cargo test --workspace` green, with **zero churn**: every one of the
|
||||
pre-existing 397 table cases, both fixture snapshots, the fences suite and
|
||||
the 74 verification tests pass unmodified. Baseline 642 → 653 passing, the
|
||||
difference being 7 new `align.rs` unit tests and 4 new convergence tests.
|
||||
- Corpus (820 files, `tools/corpus_check.sh`): outcome per path is
|
||||
**byte-identical to the baseline TSV** (same md5). 0 verification errors,
|
||||
0 crashes, 578/820 formattable as before. The classification did not move
|
||||
because no previously-clean file was aligned differently and no
|
||||
would-reformat file became clean — alignment changes *how* a file is
|
||||
reformatted, not *whether* it is.
|
||||
- Output delta: **291 of 578 formattable corpus files (50.3%) now format
|
||||
differently** — the feature reaches half of real RTL.
|
||||
- Round-trip: all 578 formattable files re-formatted from their own output,
|
||||
0 divergences.
|
||||
- Config sweep: 578 files × 4 configurations (`--line-length 60`,
|
||||
`--indent 4`, `--line-length 120`, `--indent 8 --line-length 200`) = 2312
|
||||
runs, 0 failures. This is what caught the design bug above.
|
||||
- Line discipline: 2 lines in 2 files exceed 100 columns that did not
|
||||
before, both because a trailing comment follows an aligned row. Documented
|
||||
under Assumptions.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-19 — QA**
|
||||
|
||||
Verified claims 1-5. Result: **PASS, no blocking findings.**
|
||||
|
||||
- **Static review.** `align.rs` read in full against the rule as written:
|
||||
rows/cells/columns, `HINT_EXCESS = 4`, the four `plan()` guards (row count,
|
||||
cell-count/anchor-count match, non-empty first cell, "something to pad"),
|
||||
`wants_alignment`'s global (not per-column) hint test, `render`'s
|
||||
`saturating_sub`/`min`-floor padding. Matches the README's rule
|
||||
description exactly. `doc.rs`, `printer.rs`, `verify.rs`, `fence.rs`,
|
||||
`vlog_parser/src/lexer.rs`, `vlog_parser/src/token.rs`:
|
||||
`git diff --stat` on each is **empty** — confirmed untouched, as claimed.
|
||||
- **Tests.** `cargo test --workspace`: **655 passed, 0 failed** (matches the
|
||||
README's "655 workspace tests" exactly: 28+63+45+109+5+22+1+4+6+2+78+71+30+
|
||||
84+24+19+17+6+1+19+20+1 = 655). All 4 new convergence tests present and
|
||||
green (`an_aligned_group_is_a_fixed_point_at_every_width`,
|
||||
`a_group_that_alignment_gives_up_on_still_converges`,
|
||||
`a_hint_converges_in_one_pass_and_then_holds`, `a_flush_group_stays_flush`).
|
||||
`crates/vlog_formatter/tests/cases/alignment.cases` parses to **39 cases**
|
||||
(independently counted with the same `====`-splitting rule `cases.rs`
|
||||
uses). `cargo clippy --all-targets -- -D warnings`: silent, on both the
|
||||
default lint set and with warnings promoted to errors. No `#[allow]` was
|
||||
added anywhere in the diff. Zero churn: `git status --porcelain` on
|
||||
`tests/` shows only `verification.rs` modified (pure appends — the diff is
|
||||
`+88` lines, no line removed) and one new untracked `.cases` file; every
|
||||
pre-existing `.cases` file, both fixture snapshots, and the fences suite
|
||||
are byte-for-byte untouched.
|
||||
- **Corpus (claim 3).** `tools/corpus_check.sh` run twice on the 820-file
|
||||
corpus: outcome TSV **byte-identical**, md5
|
||||
`b74f2f167c57e381d46f3503363a79b3` both times (matches the claimed
|
||||
prefix). 578/820 formattable (70.5%), 0 verification-error, 0 crash, 0
|
||||
other-error on both runs. **Content delta re-derived independently**: built
|
||||
a HEAD worktree (commit `7f2e78f`, pre-alignment) in
|
||||
`scratchpad/head-worktree`, formatted all 578 formattable files under both
|
||||
binaries and diffed — **291/578 differ**, exactly the claimed count.
|
||||
**Round-trip**: all 578 files formatted-from-their-own-output are
|
||||
byte-identical to that output — **0/578 failures**. **Long-line cost**:
|
||||
counted `length > 100` output lines per file under both binaries; exactly
|
||||
**2 files gained exactly 1 long line each**
|
||||
(`corpus/ibex/dv/formal/check/peek/alt_lsu.sv:30`,
|
||||
`corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_sha2.sv:43`), both a
|
||||
trailing `//` comment after an aligned port row — matches the Assumptions
|
||||
section's "2 lines in 2 files" claim exactly, confirmed by inspecting both
|
||||
lines directly.
|
||||
- **Config sweep (claim 4).** 578 formattable files × 2 configs
|
||||
(`--line-length 60`, `--indent 4`) = 1156 runs via `--stdout`: **0
|
||||
abnormal exits** (no crash, no nonzero-beyond-1 status). This is a reduced
|
||||
version of the full 4-config sweep the work log already ran; it adds
|
||||
nothing the dev's own 2312-run sweep didn't already cover, but reproduces
|
||||
cleanly.
|
||||
- **`ibex_core.sv` regression (claim 2, design-bug story).** Reproduced at
|
||||
`--line-length 60`: the current code converges (`vfmt --check` clean after
|
||||
one pass, and `twice()`-style double-format is byte-identical). The
|
||||
regression test `a_group_that_alignment_gives_up_on_still_converges` in
|
||||
`tests/verification.rs` exercises the same shape
|
||||
(`prim_buf #(...) u_buf (...)`) at widths 40-100 and all converge.
|
||||
- **Fixed-point hunting (targeted attacks, debug binary, 4 passes each,
|
||||
widths 40/60/80/100/120, indent 2 and 4 where relevant).** All of the
|
||||
following converge, with the specific behavior noted:
|
||||
- **Excess boundary.** A row at exactly 4 excess spaces aligns (rule 4,
|
||||
`>=4`); 3 excess with inconsistent source columns stays flush and
|
||||
collapses to one line. Boundary is exactly where the rule says it is.
|
||||
- **Over-padded group** (author aligned far past the computed width):
|
||||
collapses to the narrower computed target *on pass 1* (target is a
|
||||
function of the run's widths, never the author's columns, exactly as
|
||||
the README's fixed-point argument describes) — output was byte-identical
|
||||
to the minimally-hinted case. Not a 2-pass settle; a 1-pass correction.
|
||||
- **Under-aligned** (gaps below threshold, source columns inconsistent):
|
||||
flush, collapses to one line, stable.
|
||||
- **Tabs in the gaps**: 5 tabs (byte-gap 5) trips the same `>=4` hint as 5
|
||||
spaces would, and the aligned output is written with spaces regardless
|
||||
(render always emits `" ".repeat(pad)`) — no tab ever survives into
|
||||
aligned output, so there is nothing for a later pass to reinterpret.
|
||||
- **Generate-nested budget crossing**: swept width 50-65 in 1-column
|
||||
steps around the point a nested nested-generate connection list's
|
||||
budget flips the group from aligned to flush (crosses between width 55
|
||||
and 60 in the probe) — converged at every width, both sides of the
|
||||
boundary, indent 2 and 4.
|
||||
- **1-row vs 2-row groups**: a lone hinted port/param never aligns (rule
|
||||
1); confirmed via `p15_one_row_hint.sv` and the pre-existing unit test.
|
||||
- **Hint in one column of a two-column param group**: hint on the `=`
|
||||
column only (name column at flush spacing) aligns **both** columns —
|
||||
`wants_alignment`'s `max_excess`/`one_column` accumulate across *all*
|
||||
columns of the group before the single yes/no decision, so a hint
|
||||
anywhere aligns the whole row. This matches the rule as documented
|
||||
(rule 4 is stated once per run, not per column) — not a bug.
|
||||
- **`.*` in the middle of a connection list**: splits the list into two
|
||||
1-row runs around it (a `None` row can't be spanned), so neither side
|
||||
aligns even with hinted spacing on both real connections — correct per
|
||||
"at least two rows" and the unalignable-row boundary rule.
|
||||
- **Directive between hinted param rows**: the directive is itself a
|
||||
non-`ParamDecl` item, so it acts as an unalignable row exactly like
|
||||
`.*` above — both sides become 1-row groups and stay flush. This is a
|
||||
*structural* consequence of `param_decl_aligns` (directives aren't
|
||||
threaded into its `breaks` array the way `list_breaks` threads
|
||||
`ListDirective` for ports/connections — see note below), not a bug, and
|
||||
it converges.
|
||||
- **CRLF file with hints**: converges; output is LF-normalized, which is
|
||||
pre-existing general formatter behavior unrelated to alignment (not
|
||||
re-verified here beyond confirming it doesn't interact badly with
|
||||
alignment).
|
||||
- **Multi-byte content**: non-ASCII in an *identifier* is correctly
|
||||
rejected by the lexer (not an alignment concern). Multi-byte content in
|
||||
a param's string *value* (é/λ characters, ~90 chars wide) converges at
|
||||
widths 40-120 — `flat_width` uses `.chars().count()`, so budget/target
|
||||
math is char-width-correct, not byte-length-correct.
|
||||
- **Blank line in a port list**: does not break the group (per rule,
|
||||
`delimited` drops list-level blank lines) — confirmed aligned across
|
||||
it.
|
||||
- **Fenced region containing an aligned-looking group**: bytes emitted
|
||||
verbatim, completely untouched by alignment — confirmed byte-for-byte.
|
||||
- **`before_sep` comment on a port** (`clk /* c */,`): does **not** break
|
||||
the group — confirmed aligned across it, matching the documented rule
|
||||
literally (comment before *the comma*).
|
||||
- **`before_sep`-shaped comment on a `parameter` declarator** (`= 1 /* c
|
||||
*/;`, i.e. before the `;`): **does** make that row unalignable (checked
|
||||
explicitly in `param_decl_row` via `decl.meta.before_sep`), splitting
|
||||
the group. This does not contradict the README: the "before_sep is not
|
||||
a boundary" sentence in Group Boundaries is scoped to "an element and
|
||||
its **comma**" (list items), and `parameter` items end in `;`, not a
|
||||
comma, and aren't printed through the `ListItem`/`delimited` machinery
|
||||
that makes the port/connection accommodation possible. Filed here only
|
||||
so the next reader doesn't trip on the same apparent inconsistency I
|
||||
did; not a finding, not an action item.
|
||||
- **Sabotage attack (claim: two hazards, tested).** Disabled the "something
|
||||
to pad" guard in `plan()` (`if false && (0..cols).all(...)`, `align.rs`
|
||||
line 86) and rebuilt. Result:
|
||||
- The direct unit test `align::tests::equal_widths_have_nothing_to_align`
|
||||
**failed immediately**, as expected.
|
||||
- More importantly: constructing the exact scenario the README predicts
|
||||
(three equal-width ports, `input wire clk` / `rst` / `ena`, single
|
||||
hinted column) and running the **debug binary's own `format_source`**
|
||||
on it did not silently corrupt anything — it refused to produce output
|
||||
at all: `verification failed: formatting is not idempotent; line 1
|
||||
changed from "module m (" to "module m (input wire clk, ...);"`. This
|
||||
is `format_source`'s own internal double-pass check catching the exact
|
||||
flip-flop the README describes (pad-to-equal-widths on pass 1, see zero
|
||||
excess and collapse to one line on pass 2) for *any* input that would
|
||||
trigger it — not just the one unit test. That is hard invariant 1 (no
|
||||
partial output, verified-correct or unchanged-with-error) working
|
||||
exactly as designed against a real regression in this module.
|
||||
- Reverted via a pre-sabotage backup (`md5 4827dcb78431e784b6273b1ed29ae7c7`
|
||||
before and after); `cargo test -p vlog_formatter` green again post-revert
|
||||
(78/78 in `verification.rs`, 9/9 in `align`'s own unit tests).
|
||||
|
||||
**Findings: none blocking. One documentation-adjacent observation** (not a
|
||||
defect, not actioned): the `before_sep`-on-a-parameter-declarator behavior
|
||||
above is correct but easy to misread against the general Group Boundaries
|
||||
wording if you don't notice the "and its comma" qualifier — worth keeping in
|
||||
mind if that section is ever edited, but not asking for a change now.
|
||||
|
||||
**Not independently re-verified** (time-boxed out; covered by the dev's own
|
||||
work log and not flagged by any attack above): the exact byte-for-byte
|
||||
equivalence of `align::render(..., None)` against the pre-feature flush
|
||||
output for every corpus construct (spot-checked via the 291/578 content-diff
|
||||
and the 39-case table, not diffed construct-by-construct against the old
|
||||
formatter).
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits jointly with
|
||||
format-cache (round 17). Verible's most-loved feature, delivered
|
||||
without bending a single invariant.**
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **The fixed-point argument is written before the tests and the
|
||||
tests confirm it** — the two guards (something-to-pad; whole
|
||||
verdict at build time) are each load-bearing, and the design bug
|
||||
the config sweep caught (the printer-side Pad splitting the
|
||||
verdict) is exactly the failure mode the whole-verdict rule exists
|
||||
to prevent. Finding it via a 2,312-run sweep before QA is the
|
||||
standard; QA's sabotage then showed the runtime net catches even
|
||||
the predicted flip-flop with the unit test deleted — invariant 1
|
||||
holds structurally, not by test coverage.
|
||||
2. **Zero lexer footprint** — name_span plus the source answers every
|
||||
spacing question, so losslessness/spans/token suites are untouched.
|
||||
The feature that most tempted new trivia needed none; the
|
||||
foundations paid for themselves again.
|
||||
3. **"Alignment changes how, not whether"** made observable: the
|
||||
corpus outcome TSV is byte-identical while 291/578 files change
|
||||
content — the cleanest possible statement of a style-only feature,
|
||||
and QA re-derived both halves from a HEAD worktree.
|
||||
4. **Honest costs stated**: the 2-lines-over-100 trailing-comment
|
||||
exception (a long comment must not veto a group), the parked
|
||||
constructs (#() lists, direction/type column, trailing-comment
|
||||
column — the most visible gap), and QA's parameter-before_sep
|
||||
scoping note now logged so the next reader doesn't trip.
|
||||
|
||||
The author-intent rule shipped matches Verible's culture: ≥4 excess
|
||||
spaces or existing consistent columns opts in; single-space code stays
|
||||
exactly as vfmt always wrote it — no existing user's output moves
|
||||
unless they asked.
|
||||
@@ -0,0 +1,635 @@
|
||||
# format-cache
|
||||
|
||||
## Goal
|
||||
|
||||
Make a repeat `vfmt` run over an unchanged tree do (almost) no work.
|
||||
`TODO.md` §3's content-hash cache item: remember, per file, that *this
|
||||
exact content, under these settings, on this vfmt version* was already
|
||||
formatted, and skip the whole read-parse-format-verify pipeline on the
|
||||
next run. Monorepo RTL trees are the case that matters — vfmt's per-file
|
||||
cost is dominated by parse + format + the two runtime safety checks
|
||||
(equivalence and convergence), all of which are pure functions of
|
||||
`(content, config)`, so a cache hit is exactly as trustworthy as the run
|
||||
that produced it. The cache is an optimization only: it can lose entries,
|
||||
be deleted, or be corrupted, and the run's stdout/stderr/exit code stay
|
||||
what they would have been anyway (modulo one extra summary segment).
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Only the "clean" verdict is cacheable.** An entry means `format(x) ==
|
||||
x` for that content and config. Nothing else is stored — not errors,
|
||||
not "would reformat", not diff text. See "Semantics" for why.
|
||||
- **Formatting is a pure function of `(source, config)`**, the same
|
||||
assumption parallel-files already relies on. If that ever stops being
|
||||
true (a formatter that reads the file's *name*, or another file), this
|
||||
cache silently goes wrong and the assumption must be revisited here.
|
||||
- **`line-length` and `indent` are the whole config surface.** They are
|
||||
the only two things `vfmt_core::config::FileConfig` can put into
|
||||
`vlog_formatter::Config`. The key stores the *resolved values*, not the
|
||||
config file's path or mtime — so moving a `vfmt.toml` around, or
|
||||
switching from a file to an equivalent `--line-length` flag, correctly
|
||||
does **not** invalidate anything, while a real value change does.
|
||||
`exclude` is not part of the key: it changes *which* files are visited,
|
||||
never how one is formatted.
|
||||
- **The version string is the workspace version** (`env!("CARGO_PKG_VERSION")`
|
||||
read inside `vfmt_core`, whose `version.workspace = true` makes it the
|
||||
same string for every crate here). This is a coarse proxy for "the
|
||||
formatter's behavior": two builds of the same version with different
|
||||
code — a `cargo build` in the middle of development — share a version
|
||||
and therefore share cache entries. **Developers of vfmt itself should
|
||||
use `--no-cache`** (the test suite does); released binaries are fine.
|
||||
- **Paths are keys, byte-for-byte as processed.** No canonicalization, no
|
||||
symlink resolution (config discovery is lexical for the same reason).
|
||||
`vfmt .` and `vfmt /abs/path/to/tree` therefore do not share entries;
|
||||
they just each build their own. A path that is not valid UTF-8, or that
|
||||
contains a tab or a newline, is never cached (it cannot be written to
|
||||
the line-based store) — those files are simply always re-formatted.
|
||||
- **The cache is not a lock.** Two vfmt processes may write it
|
||||
concurrently; see "Concurrency".
|
||||
- **`vfmt check` (the linter) is not cached.** `--no-cache` /
|
||||
`--cache-dir` are accepted there and do nothing, so a wrapper script
|
||||
can pass them unconditionally. Lint results depend on the rule
|
||||
selection, the waiver comments and the fix mode; caching them is a
|
||||
separate feature with a separate key.
|
||||
|
||||
## Behavior
|
||||
|
||||
### The key
|
||||
|
||||
Per file: **(content hash, line-length, indent, vfmt version)**, keyed on
|
||||
the file path.
|
||||
|
||||
- **Content hash: hand-rolled FNV-1a, 64-bit**, over the file's bytes
|
||||
(`cache::content_hash`). Two reasons it is not
|
||||
`std::collections::hash_map::DefaultHasher`: std explicitly does not
|
||||
guarantee that hasher's output is stable across Rust releases (or even
|
||||
across builds), which is fatal for a value persisted to disk — a
|
||||
toolchain bump would silently invalidate every entry, or worse, collide
|
||||
differently; and `RandomState` is seeded per process, so it is not even
|
||||
stable within one version. FNV-1a is ~15 lines, has no dependency, and
|
||||
is byte-exactly specified. It is not cryptographic and does not need to
|
||||
be (see collision posture).
|
||||
- Hashing costs one pass over bytes vfmt has already read into memory;
|
||||
it is noise next to parsing.
|
||||
|
||||
### Collision posture (stated honestly)
|
||||
|
||||
A 64-bit content hash means a collision could make vfmt skip a file that
|
||||
actually changed — a wrong "clean" verdict, the only way this feature can
|
||||
produce a wrong result. Two things bound it:
|
||||
|
||||
1. **The map is keyed on the file path, and a lookup never crosses
|
||||
files.** A collision between two *different files* is harmless: they
|
||||
have different keys and never consult each other's entry. To be
|
||||
skipped wrongly, one file must be edited into a *different* content
|
||||
whose FNV-1a hash equals the previous content's — a collision between
|
||||
two versions of the same path.
|
||||
2. That is the standard accepted risk of every content-addressed build
|
||||
cache (ruff, black, ccache, cargo's fingerprints all take it). For
|
||||
accidental (non-adversarial) edits the probability is ~2⁻⁶⁴ per edit.
|
||||
|
||||
It is *not* collision-resistant against an adversary who can choose the
|
||||
file contents: FNV-1a is trivially invertible, so someone able to write
|
||||
files in your tree can craft two files with the same hash and make vfmt
|
||||
skip the second. That threat model (an attacker with write access to your
|
||||
source tree, trying to get past a formatter) is not one vfmt defends
|
||||
against; `--no-cache` removes the cache from the picture entirely if it
|
||||
ever matters. This is documented rather than fixed because the fix (a
|
||||
cryptographic hash) is a dependency or ~200 lines of SHA-256 for a threat
|
||||
that does not exist here.
|
||||
|
||||
**What a collision cannot do** is corrupt a file: an entry only ever
|
||||
causes work to be *skipped*, never output to be produced. The hard
|
||||
invariant "never corrupt code" is untouched by this feature — the cache
|
||||
never writes to a `.sv` file and never changes what the formatter emits.
|
||||
|
||||
### Semantics
|
||||
|
||||
An entry is written only for content that was *verified clean by this
|
||||
run*: either the file was already a fixed point, or it was rewritten and
|
||||
the hash of **the bytes that were written** goes in.
|
||||
|
||||
| Situation | Cache read | Cache write | Reported as |
|
||||
|---|---|---|---|
|
||||
| Hit (hash + line-length + indent + version all match) | skip all work | entry kept | `left unchanged`, plus `N files from cache` |
|
||||
| Miss, file is already formatted | — | record `hash(src)` | `left unchanged` |
|
||||
| Miss, file rewritten in place (write succeeded) | — | record `hash(output)` | `reformatted` |
|
||||
| Miss, `--check`/`--diff` says it would reformat | — | **nothing** | `would be reformatted`, exit 1 |
|
||||
| Miss, in-place write failed (I/O) | — | **nothing** | error, exit 2 |
|
||||
| Parse error / failed safety check / contained panic | — | **nothing** | error, exit 2 |
|
||||
| `--stdout` | cache off for the run | nothing | printed |
|
||||
| stdin (`vfmt -`) | never | never | as before |
|
||||
|
||||
Why "would reformat" and errors are never cached: the fix for both is
|
||||
**external** to vfmt. A dirty file gets fixed by an editor or by
|
||||
`vfmt` without `--check`; a parse error gets fixed by editing the source
|
||||
or by teaching the parser new syntax. If either verdict were cached, a CI
|
||||
`vfmt --check` would keep reporting a stale complaint (or, worse, stop
|
||||
reporting a real one) until someone thought to clear the cache. Caching
|
||||
only the fixed-point verdict also means the cache can never *invent* work
|
||||
or *suppress* a diagnostic: the worst a stale, wrong or missing entry can
|
||||
do is cause a file to be re-formatted, which is the un-cached behavior.
|
||||
|
||||
`--check` and `--diff` exit codes are therefore preserved exactly: a hit
|
||||
means "this content is a fixed point", which is precisely the condition
|
||||
under which those modes stay silent and contribute 0 to the exit code.
|
||||
|
||||
### Storage
|
||||
|
||||
One text file, `<cache-dir>/cache`, one line per path, tab-separated,
|
||||
hand-rolled in the style of the corpus TSV:
|
||||
|
||||
```
|
||||
<content-hash, 16 hex digits>\t<line-length>\t<indent>\t<version>\t<path>
|
||||
```
|
||||
|
||||
The path is last because it is the only field that can contain
|
||||
interesting characters. Lines are sorted by path, so the file is stable
|
||||
and diffable and two runs over the same tree produce byte-identical
|
||||
cache files.
|
||||
|
||||
**No serde, no TOML, no JSON.** `vfmt` and `vfmt_core` have exactly one
|
||||
third-party dependency between them (`rayon`, in `vfmt`). `serde` exists
|
||||
in the workspace only because `vfmt_server` needs it for LSP wire
|
||||
messages — `vfmt`/`vfmt_core` do not depend on it, and taking it here
|
||||
would put a proc-macro build step into the CLI's dependency graph to
|
||||
encode five fields. Five fields on a line need no schema; CLAUDE.md's
|
||||
"standard library first" says so.
|
||||
|
||||
Loading, corruption and staleness:
|
||||
|
||||
- The file is read once at startup, before any file is processed.
|
||||
- **Unreadable (missing, no permission, a directory, not UTF-8) → an
|
||||
empty cache.** Never an error, never a warning.
|
||||
- **Any malformed line → the whole file is discarded** and the cache
|
||||
starts empty. A file we cannot fully parse is not a file we can prove
|
||||
we wrote; partial trust is not worth the branch.
|
||||
- A well-formed line whose *version* is not this binary's is dropped
|
||||
silently (that is not corruption, just another vfmt's entry). It is not
|
||||
carried forward on write, so alternating between two vfmt versions
|
||||
rebuilds the cache each time.
|
||||
- **Writing is atomic**: the new text goes to `<cache-dir>/cache.<pid>.tmp`
|
||||
and is `rename`d over `cache`. A reader therefore sees the old file or
|
||||
the new one, never a half-written one.
|
||||
- Entries whose path no longer exists are dropped at write time, so the
|
||||
file does not grow forever as files are deleted or renamed.
|
||||
- Entries for files *not visited by this run* are preserved: formatting a
|
||||
subdirectory must not throw away the rest of the tree's entries.
|
||||
- **A failure to write the cache is silent and harmless.** The run's exit
|
||||
code and output do not change; the next run just does the work again.
|
||||
(Deliberate: a warning on every run in a read-only checkout would be
|
||||
noise, and it would make stderr depend on the filesystem's state, which
|
||||
the parallel-files determinism contract does not want.)
|
||||
|
||||
The cache directory gets a self-ignoring `.gitignore` containing `*`
|
||||
written into it when it is created, the same trick cargo uses for
|
||||
`target/`; `/.vfmt_cache` is also listed in this repo's root
|
||||
`.gitignore`.
|
||||
|
||||
### Flags
|
||||
|
||||
| Flag | Meaning |
|
||||
|---|---|
|
||||
| `--no-cache` | do not read and do not write the cache. Nothing is created on disk |
|
||||
| `--cache-dir <PATH>` | use this directory instead of `.vfmt_cache` |
|
||||
|
||||
**Where the default lives: the current directory.** `.vfmt_cache` is
|
||||
resolved relative to the cwd, not to the input paths and not to the
|
||||
config file's directory. This is wrong for the multi-project invocation
|
||||
(`vfmt ~/a/rtl ~/b/rtl` from a third directory writes one cache in that
|
||||
third directory, and running the same command from elsewhere starts a new
|
||||
one), and it is what ruff did for years before growing a per-project
|
||||
resolution. The honest v1 rule is "one cwd, one cache", which is exactly
|
||||
right for the overwhelmingly common `cd repo && vfmt --check .` in CI and
|
||||
in a pre-commit hook, and `--cache-dir` covers everything else. Making
|
||||
the default follow the config-file root is the natural next step and is
|
||||
deliberately not guessed at here.
|
||||
|
||||
### Reporting
|
||||
|
||||
The summary line gains a segment when anything was skipped:
|
||||
|
||||
```
|
||||
2 files left unchanged, 2 files from cache
|
||||
```
|
||||
|
||||
Cached files are counted in `left unchanged` as well — they *are*
|
||||
unchanged, and no CI script's grep should change meaning because a cache
|
||||
appeared. The `N files from cache` segment is the observable the tests
|
||||
assert on, and the only user-visible difference between a cold and a warm
|
||||
run.
|
||||
|
||||
### Concurrency
|
||||
|
||||
Entries are produced inside the existing `par_iter` and travel back
|
||||
through the `Outcome` collection mechanism (a per-file
|
||||
`FileResult { outcome, clean: Option<u64> }`, collected by an indexed
|
||||
`par_iter().map(...).collect()` — so input order is preserved exactly as
|
||||
before). The cache map itself is only *read* during the parallel pass and
|
||||
is only mutated in the serial loop afterwards; the file is written once,
|
||||
single-threaded, at the end of the run. There is no lock and no shared
|
||||
mutable state.
|
||||
|
||||
Two vfmt processes running at once: last writer wins the `rename`, so one
|
||||
process's entries can be lost. That is self-healing and safe:
|
||||
|
||||
- An entry only ever asserts *content that this process verified*, so a
|
||||
surviving entry from either writer is true.
|
||||
- A lost entry costs one file's worth of re-work on the next run.
|
||||
- A `rename` is atomic, so no reader sees a mixture.
|
||||
|
||||
The one thing that *would* be unsafe — an entry asserting "clean" about
|
||||
content nobody verified — cannot be constructed by this design, because
|
||||
the only writer of an entry is the code path that just observed
|
||||
`format(x) == x`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `docs/features/parallel-files/README.md`'s promise** that
|
||||
"the per-file unit of work is `process_file(...)`, a cache lookup
|
||||
belongs at the top of it; the `Outcome` enum is where a 'cached,
|
||||
unchanged' bucket would go." Both taken literally. `Outcome` gained a
|
||||
`Cached` variant and `process_file` now returns a `FileResult` wrapper
|
||||
that also carries the hash to record. The determinism contract
|
||||
(byte-identical stdout/stderr at any `--threads`) is unchanged and
|
||||
re-tested with the cache on.
|
||||
- **Consumes `docs/features/config-discovery/README.md`'s promise** that
|
||||
the cache key "must include the resolved per-file settings … not just
|
||||
file content + vfmt version". Done, with the *values*
|
||||
(`Config::max_width`, `Config::indent_width`) rather than the config
|
||||
file's identity, so two trees governed by different `vfmt.toml` files
|
||||
that happen to say the same thing share entries correctly.
|
||||
- **Consumes `vlog_formatter::Config`** read-only, for its two fields.
|
||||
Nothing in `vlog_parser` / `vlog_formatter` / `vlog_linter` was
|
||||
touched.
|
||||
- **Where the module lives: `vfmt_core::cache`,** next to `config` and
|
||||
`walk`. `vfmt_core` is by its own doc comment "the parts of vfmt that
|
||||
decide *which* files are processed and *with what settings*", and "this
|
||||
file is already formatted, skip it" is the third member of that family.
|
||||
It also keeps the door open for `vfmt_server`: a language server that
|
||||
wanted to avoid re-formatting an unedited buffer on save would want the
|
||||
same predicate, and would otherwise have to duplicate the file format.
|
||||
Nothing in the module is CLI-specific — it takes paths, `u64`s and two
|
||||
`usize`s and has no opinion about arguments or reporting.
|
||||
- **Promises to whoever changes the formatter's output** (alignment
|
||||
inference, `--lines`, any style change): **bump the workspace version**,
|
||||
or every user with a warm cache keeps their old formatting on files
|
||||
that did not otherwise change. This is the same discipline ruff and
|
||||
black need. Within-version development builds must use `--no-cache`.
|
||||
- **Promises to `crates/vfmt/tests/cli.rs`:** the shared `run` helper
|
||||
appends `--no-cache`, so the pre-existing tests keep running with the
|
||||
cache out of the picture (they share one cwd — the crate root — and
|
||||
would otherwise share one cache directory *and* pollute the repo with
|
||||
it). Cache tests call `run_raw` and pass an explicit `--cache-dir`
|
||||
under their own temp directory, or set the child's cwd.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `vfmt_core::cache`: FNV-1a `content_hash`, `Entry`, `Cache`
|
||||
(`load` / `disabled` / `is_clean` / `record` / `store`).
|
||||
- [x] Hand-rolled tab-separated store, sorted by path, atomic
|
||||
temp+rename write, self-ignoring `.gitignore` in the cache dir.
|
||||
- [x] Corrupt / unreadable / wrong-version entries ignored, never fatal.
|
||||
- [x] `--no-cache` and `--cache-dir <PATH>` in `args.rs` and `--help`,
|
||||
accepted (and inert) for `vfmt check`.
|
||||
- [x] Lookup at the top of `process_file`; entries collected through the
|
||||
indexed `par_iter` results and recorded serially in input order.
|
||||
- [x] Only clean verdicts recorded; `--check`/`--diff`/errors/`--stdout`
|
||||
never write; stdin never caches.
|
||||
- [x] `N files from cache` summary segment.
|
||||
- [x] Unit tests in `cache.rs` (hash stability, round-trip, corruption,
|
||||
version filtering, pruning, atomicity of the rename).
|
||||
- [x] CLI tests in `crates/vfmt/tests/cli.rs` (warm run does no work,
|
||||
content change invalidates, indent change invalidates, wrong
|
||||
version ignored, `--no-cache`, corrupt file tolerated, `--check`
|
||||
exit codes, `--threads` determinism with a warm cache, default
|
||||
cache dir is cwd-relative and self-ignoring).
|
||||
- [x] Root `.gitignore` entry, `README.md` Cache section, `TODO.md` §3
|
||||
box.
|
||||
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test`.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read CLAUDE.md, `TODO.md` §3, `docs/features/parallel-files/README.md`
|
||||
(whose Handshakes section pre-specifies where the lookup goes) and
|
||||
`docs/features/config-discovery/README.md` (whose Handshakes section
|
||||
pre-specifies the key), then all of `crates/vfmt/src` and
|
||||
`crates/vfmt_core/src`.
|
||||
|
||||
**Module placement.** `vfmt_core::cache`, reasoning in Handshakes. It
|
||||
costs nothing today (`vfmt` is the only caller) and keeps `vfmt_core`
|
||||
dependency-free — `Entry` carries two bare `usize`s rather than a
|
||||
`vlog_formatter::Config`, so the crate still has an empty
|
||||
`[dependencies]`.
|
||||
|
||||
**The store format.** Tab-separated, path last, sorted, one line per
|
||||
entry. Rejected alternatives: (a) `serde`+`serde_json` — real dependency
|
||||
for five fields, and `vfmt`/`vfmt_core` currently have one dependency
|
||||
total; (b) a binary format — unreadable when debugging exactly the kind
|
||||
of "why did it skip that file?" question a cache creates; (c) one file
|
||||
per cached path (ruff's older layout) — thousands of tiny files, and the
|
||||
atomic-write story gets worse, not better. The version is stored *per
|
||||
line* rather than once in a header so that a mixed-version cache
|
||||
degrades entry-by-entry instead of wholesale, and so the format needs no
|
||||
header at all.
|
||||
|
||||
**Corruption policy.** Any malformed line discards the entire file, not
|
||||
just that line. The alternative (skip bad lines, keep good ones) trusts
|
||||
a file we have already caught lying; the cost of discarding is one cold
|
||||
run.
|
||||
|
||||
**Pruning.** `store` drops entries whose path no longer exists. This is
|
||||
one `exists()` per entry on a serial pass at the end of the run — on the
|
||||
860-file corpus it is unmeasurable — and without it the file grows
|
||||
forever in a tree where files get renamed.
|
||||
|
||||
**Test isolation.** Integration tests run with cwd = the crate
|
||||
directory, so a default-on cache would (a) create
|
||||
`crates/vfmt/.vfmt_cache/` in the working tree and (b) make tests
|
||||
interfere: `thread_count_changes_nothing_but_speed` runs the same tree
|
||||
twice and compares stderr byte-for-byte, which a warm cache would change.
|
||||
The `run` helper therefore appends `--no-cache`, and the cache tests use
|
||||
a new `run_raw` with an explicit `--cache-dir` (or a set cwd for the
|
||||
default-location test). Recorded as a handshake so nobody removes it.
|
||||
|
||||
**Measured.** Release build, 10 logical cores, `vfmt --check` over the
|
||||
corpus, best of 10 runs (mean in the work log's raw numbers was within
|
||||
10 %). The corpus was formatted first, since a tree that is already
|
||||
clean is exactly the case the cache exists for; the "612 files" column
|
||||
additionally drops the 248 corpus files that do not parse, which can
|
||||
never be cached and are re-attempted every run.
|
||||
|
||||
| run | 612 formattable files | full 860-file corpus |
|
||||
|---|---|---|
|
||||
| `--no-cache` (today's behavior) | 105 ms | 116 ms |
|
||||
| cold, empty cache (builds it) | 108 ms | 123 ms |
|
||||
| **warm, every file a hit** | **46 ms** | **56 ms** |
|
||||
| speedup, warm vs `--no-cache` | **2.3×** | **2.1×** |
|
||||
|
||||
Building the cache costs ~3 ms per 600 files (hashing content already in
|
||||
memory, plus one `write` + `rename`), i.e. under 3 % of a cold run.
|
||||
|
||||
The honest framing of the 2.3×: **parallelism already took the easy
|
||||
win**, and what is left for the cache to remove is the parse+format+
|
||||
verify time that was already spread over 10 cores. On one core the
|
||||
picture is the one a big monorepo actually cares about:
|
||||
|
||||
| `--threads 1`, 612 files | wall |
|
||||
|---|---|
|
||||
| `--no-cache` | 396 ms |
|
||||
| warm | 51 ms |
|
||||
| speedup | **7.7×** |
|
||||
|
||||
The warm floor (46–56 ms) is the serial directory walk, config
|
||||
discovery, the cache load, and one `read_to_string` + FNV pass per file
|
||||
— all I/O and no compute, which is the intended endpoint. Process
|
||||
startup is 3 ms of it. Making the floor lower means not reading the
|
||||
files at all (an mtime/size pre-filter), which trades the cache's one
|
||||
strong property — it is keyed on *content*, so a `touch`, a checkout, or
|
||||
a rebuild that rewrites identical bytes is still a hit — for a
|
||||
correctness risk. Not taken.
|
||||
|
||||
**Attacked before handing over** (release binary, outside the test
|
||||
suite; every one of these degrades quietly, none changes an exit code):
|
||||
|
||||
- **Eight vfmt processes at once** over the same 612-file tree and the
|
||||
same cache directory: all eight exit 0, no leftover `*.tmp`, the
|
||||
resulting file has 612 well-formed lines (`awk -F'\t' 'NF!=5'` finds
|
||||
none), and the next run is `612 files from cache`. Last-writer-wins,
|
||||
as designed.
|
||||
- **`--cache-dir` pointing at an existing plain file**: `create_dir_all`
|
||||
fails, the run is unaffected, exit 0.
|
||||
- **A read-only (`chmod 500`) cache directory**: exit 0, nothing
|
||||
written, no warning.
|
||||
- **The `cache` path occupied by a directory**: the `rename` fails, the
|
||||
temp file is cleaned up, exit 0.
|
||||
- **Paths containing spaces** round-trip (the store is tab-separated
|
||||
precisely so they can), and a **duplicated line** for one path is
|
||||
harmless (last wins).
|
||||
- **Forged entry for a file that does not parse** → the run reports it
|
||||
as cached and exits 0, which is the proof that a hit skips the *whole*
|
||||
pipeline rather than doing the work and agreeing. That is now the CLI
|
||||
test `a_hit_skips_the_work_entirely`; the same trick with the wrong
|
||||
version stamp is `an_entry_from_another_vfmt_version_is_ignored`.
|
||||
|
||||
**Blocked by the workspace, as parallel-files was.** A concurrent agent
|
||||
is mid-landing alignment inference in `vlog_formatter` (`align.rs` plus
|
||||
`doc.rs`/`format.rs`/`printer.rs`), which does not compile yet. All
|
||||
gates were therefore run in a scratchpad copy of the workspace with
|
||||
*only* their three crates reverted to `HEAD` (`git checkout --
|
||||
crates/vlog_{formatter,parser,semantic}`); my own files were copied in
|
||||
from the real tree. Nothing outside `crates/vfmt`, `crates/vfmt_core`,
|
||||
`docs/features/format-cache`, `README.md`, `TODO.md` and `.gitignore`
|
||||
was edited, and `cargo fmt` was run scoped (`-p vfmt -p vfmt_core`) so
|
||||
no file of theirs was touched. Re-run everything on the merged tree once
|
||||
their work lands.
|
||||
|
||||
**Gates** (scratchpad tree, described above):
|
||||
|
||||
- `cargo test -p vfmt -p vfmt_core`: 28 unit (`vfmt`) + **63** CLI
|
||||
(`vfmt`) + **45** unit (`vfmt_core`), all green. New: 15 CLI tests, 14
|
||||
`cache.rs` unit tests, 1 `args.rs` test.
|
||||
- `cargo test --workspace`: green, no churn in any other crate's tests —
|
||||
this feature changes no formatter output.
|
||||
- `cargo clippy --workspace --all-targets`: silent.
|
||||
- `cargo fmt -p vfmt -p vfmt_core -- --check`: clean.
|
||||
- No `Cargo.toml` / `Cargo.lock` change: no new dependency, and
|
||||
`vfmt_core` still has an empty `[dependencies]`.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
**Setup.** The workspace would not compile at HEAD in the real tree (a
|
||||
concurrent dev agent mid-landing alignment inference in `vlog_formatter`).
|
||||
Followed the dev's own technique: `rsync`'d the whole working tree
|
||||
(including uncommitted changes, excluding `target/` and `corpus/`) to a
|
||||
scratchpad copy, `git checkout HEAD -- crates/vlog_{formatter,parser,semantic}`
|
||||
in the copy, deleted the two untracked alignment-only files that survived
|
||||
the checkout (`vlog_formatter/src/align.rs`,
|
||||
`vlog_formatter/tests/cases/alignment.cases` — unreferenced once `lib.rs`
|
||||
was reverted). All cargo commands below ran in that copy; the real tree
|
||||
was touched only to append this entry. No commit/push.
|
||||
|
||||
**Gates, reproduced from scratch in the copy:**
|
||||
- `cargo build -p vfmt -p vfmt_core --release` — clean.
|
||||
- `cargo test -p vfmt -p vfmt_core`: 28 (`vfmt` unit) + 63 (`cli.rs`) + 45
|
||||
(`vfmt_core` unit) = 136, all green, matching the claimed counts exactly.
|
||||
- `cargo test --workspace`: every crate green, no churn elsewhere.
|
||||
- `cargo clippy --workspace --all-targets`: silent.
|
||||
- `cargo fmt -p vfmt -p vfmt_core -- --check`: clean.
|
||||
- `git diff --stat HEAD -- Cargo.toml Cargo.lock crates/*/Cargo.toml`:
|
||||
empty — no dependency added, confirmed.
|
||||
|
||||
**Claim 1 (key/store).** Read `cache.rs` in full. FNV-1a matches the
|
||||
published test vectors; store is tab-separated, sorted, path last;
|
||||
`parse()` discards the whole file on any malformed line and drops
|
||||
mismatched-version lines individually (both by direct code read and via
|
||||
the corrupt-file/version unit tests, all passing). Confirmed by hand:
|
||||
- A hand-written poisoned entry (correct hash/config/version, forged path
|
||||
key `dirty.sv`) makes `--check` on a genuinely dirty file exit 0 and
|
||||
report it "from cache" — the run really is skipped, not re-verified.
|
||||
This is the documented, honest collision/tamper posture (see Claim-2
|
||||
note below), not a bug.
|
||||
- `--cache-dir` pointing at an existing plain file, and a `chmod 500`
|
||||
cache directory: both exit 0, run output unaffected, nothing written —
|
||||
matches "silent write failures."
|
||||
- 8 parallel `vfmt --check` processes over a shared 200-file tree and
|
||||
cache dir: all exit 0, zero `*.tmp` leftovers, exactly 200 well-formed
|
||||
lines afterward (`awk -F'\t' 'NF!=5'` empty), next run is a clean
|
||||
200-file hit.
|
||||
- Moving a file (`orig.sv` → `moved.sv`) between two `--check` runs:
|
||||
`orig.sv`'s entry is pruned on the write that follows the move (it no
|
||||
longer `exists()`), and `moved.sv` is correctly a fresh miss —
|
||||
path-keyed as documented.
|
||||
|
||||
**Claim 2 (semantics).** Confirmed via the CLI suite (all passing) plus
|
||||
independent repro:
|
||||
- `a_would_reformat_verdict_is_never_cached`-style manual check: a dirty
|
||||
file gives `would reformat: ...`/exit 1 on three consecutive `--check`
|
||||
runs, never "from cache" — the stale-CI-verdict failure mode does not
|
||||
occur.
|
||||
- `--stdout` never creates `.vfmt_cache` even with a warm entry present
|
||||
for the same file (prints every time, does not read or write the
|
||||
cache) — matches `cache_enabled() == !no_cache && !stdout` in
|
||||
`args.rs`.
|
||||
- `vfmt check <file> --no-cache --cache-dir X`: exits normally (lint
|
||||
verdict, unrelated to formatting), creates no cache artifact under
|
||||
either name — accepted-but-inert confirmed.
|
||||
- `run_stdin` in `main.rs` never references `Cache` at all — stdin mode
|
||||
literally cannot touch the cache, by construction, not just by test.
|
||||
- A hit genuinely skips the whole pipeline: forged entry for a file the
|
||||
parser cannot even handle (`UNPARSEABLE` case in `cli.rs`, and my own
|
||||
chmod-000-after-caching repro below) proves the lookup happens before
|
||||
`format_contained` is ever called.
|
||||
|
||||
**Claim 3 (flags).** `--no-cache`: no `.vfmt_cache` appears for either a
|
||||
`vfmt <file>` or `vfmt --stdout <file>` run — checked directly with `ls`.
|
||||
`--cache-dir`: exercised throughout. Default cwd-relative location and
|
||||
self-ignoring `.gitignore`: reproduced outside the test suite too
|
||||
(`vfmt --check .` from a fresh dir leaves exactly `.vfmt_cache/{cache,
|
||||
.gitignore}`, the latter reading `*\n`). The README's own "Where the
|
||||
default lives" paragraph states the multi-root limitation honestly.
|
||||
|
||||
**Claim 4 (concurrency).** 8-process stress at the full requested width:
|
||||
clean cache, no `.tmp` leftovers (details above). `--threads 1` vs
|
||||
default with a warm cache over the 612-file formattable corpus subset:
|
||||
`diff` on stdout and stderr is empty — byte-identical, as promised.
|
||||
|
||||
**Claim 5 (tests).** 28+63+45 = 136, all green, reproduced above. The
|
||||
`run`/`run_raw`/`with_no_cache` handshake in `cli.rs` is exactly as
|
||||
described: `run` inserts `--no-cache` after the subcommand if present;
|
||||
cache tests use `run_raw` with their own `--cache-dir` or `run_in` for
|
||||
the default-location test. No `Cargo.toml`/`Cargo.lock` diff.
|
||||
|
||||
**Claim 6 (timing).** Corpus copied to the scratchpad (real `corpus/`
|
||||
never written to), formatted once with `--no-cache` to reach a clean
|
||||
tree: 612 formattable / 248 unparseable — matches the dev's own split
|
||||
exactly. 10 logical cores, same as the dev's environment. Best-of-N,
|
||||
`--check` over the 820-file scratchpad corpus copy:
|
||||
|
||||
| run | wall (best of 10, default threads) |
|
||||
|---|---|
|
||||
| `--no-cache` | ~127 ms |
|
||||
| cold (building the cache) | ~134 ms |
|
||||
| **warm, every formattable file a hit** | **~68 ms** |
|
||||
| speedup, warm vs `--no-cache` | **~1.9×** |
|
||||
|
||||
| `--threads 1`, 612 files | wall (best of 5) |
|
||||
|---|---|
|
||||
| `--no-cache` | ~456 ms |
|
||||
| warm | ~113 ms |
|
||||
| speedup | **~4.0×** |
|
||||
|
||||
Same direction and same order of magnitude as the dev's numbers
|
||||
(2.1–2.3× / 7.7×); the absolute speedup is lower here, plausibly because
|
||||
the scratchpad corpus lives on this Mac's `/private/tmp` (fast SSD, warm
|
||||
OS page cache) where the `--no-cache` floor is already cheaper relative
|
||||
to compute than on the dev's machine — not a red flag, cache still
|
||||
strictly warm < cold < `--no-cache` on every run observed.
|
||||
|
||||
**Attacks beyond the claims list, all passed (no code fix needed):**
|
||||
- **mtime-only touch, same content**: still a hit after `touch` — content
|
||||
hashed, not mtime-based, exactly as the README's Work Log states
|
||||
("a `touch` ... is still a hit").
|
||||
- **File replaced by different content of the same byte length**
|
||||
(`wire x;` → `wire y;`, both 30 bytes): correctly *not* reported "from
|
||||
cache" on the next run — the hash differs despite equal length, so this
|
||||
is a fresh (if coincidentally still-clean) verdict, not a stale hit.
|
||||
- **File made unreadable (`chmod 000`) after being cached**: `--check`
|
||||
errors (`Permission denied`, exit 2) rather than serving the stale
|
||||
cache hit — `process_file` always calls `read_to_string` before
|
||||
consulting the cache (the hash needs the bytes), so an unreadable file
|
||||
can never be served from cache; it surfaces as a normal I/O error. Not
|
||||
a silent wrong "clean" verdict.
|
||||
- **Cache poisoning** (forged entry, correct hash/config/version, for a
|
||||
file that is actually dirty): the run trusts it and exits 0. This is
|
||||
exactly the collision/tamper posture the README's "Collision posture"
|
||||
section states outright — "an attacker with write access to your
|
||||
source tree ... is not one vfmt defends against" — so this is
|
||||
documentation matching behavior, not an undisclosed hole.
|
||||
- **Two directories with differently-formatted-but-equal-valued
|
||||
`vfmt.toml`** (`indent = 2` vs `indent = 2 # comment`), same
|
||||
file path: still a hit — confirms the key is the resolved *value*, not
|
||||
the config file's text or identity.
|
||||
- **CRLF file**: never reaches a clean fixed point (always "would
|
||||
reformat"), so it is never cached and both `--check` runs report
|
||||
identically — consistent, not a cache bug (CRLF handling itself is
|
||||
formatter behavior, out of this feature's scope).
|
||||
- **0-byte `.sv` file**: also always "would reformat" (pre-existing
|
||||
formatter behavior for empty input), never cached, cache file stays
|
||||
empty across two runs.
|
||||
|
||||
**Verdict: PASS on all six claims, no BLOCKING findings.** No case was
|
||||
found where a cached verdict was served for genuinely *changed* content
|
||||
(the one thing that would be blocking), and `--check` never went stale
|
||||
across repeated runs on a dirty file. The one deliberately-accepted risk
|
||||
(hash-collision / on-disk tamper) is disclosed in the README exactly as
|
||||
strongly as the behavior actually is, which was the main thing worth
|
||||
double-checking given CLAUDE.md's "guilty until proven innocent" rule for
|
||||
`verify.rs`-adjacent forgiveness — this feature does not touch
|
||||
`verify.rs` or widen its normalizations, so that rule does not directly
|
||||
apply, but the same spirit (attack the exact class of thing that could
|
||||
silently corrupt trust) was applied here to the cache's own trust
|
||||
boundary instead.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed. Warm runs are
|
||||
2-4× faster in parallel and up to 7.7× single-threaded, bought without
|
||||
touching a single correctness property.**
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **Caching only the fixed-point verdict** is the design decision that
|
||||
makes everything else safe: a hit can only skip work, never produce
|
||||
output, so "never corrupt code" is untouchable by construction, and
|
||||
`--check`/`--diff` can't go stale because dirty and error verdicts
|
||||
are recomputed every run — QA verified the staleness property three
|
||||
runs deep and the read-before-consult ordering on an unreadable
|
||||
file.
|
||||
2. **The collision/tamper posture is disclosed, not hidden** — QA's
|
||||
poisoning attack confirmed both the behavior and the honesty of the
|
||||
README's statement of it. Same-file 64-bit collision risk is the
|
||||
standard trade every formatter cache takes; keying the map on path
|
||||
keeps lookups from ever crossing files.
|
||||
3. **FNV-1a with published test vectors** turns "the hash silently
|
||||
changed" into a build failure instead of a fleet-wide cache bust —
|
||||
small touch, right instinct. The whole-file-discard-on-any-malformed-
|
||||
line rule is the right paranoia for a value store.
|
||||
4. **Value-keyed config** (not config-file identity) means two
|
||||
differently-written-but-equal vfmt.tomls share hits — QA probed it.
|
||||
The cwd-relative default cache location is the honest v1 limitation,
|
||||
stated.
|
||||
5. **Both agents' isolation discipline under the concurrent alignment
|
||||
churn** — dev and QA each gated in scratchpad copies with the
|
||||
churning crates reverted to HEAD — is now the house pattern for
|
||||
working alongside an in-flight round.
|
||||
6. The `run`-helper `--no-cache` insertion in cli.rs is recorded as a
|
||||
handshake: test isolation demanded it, and future CLI tests inherit
|
||||
it silently — worth knowing when a cache test needs the opposite.
|
||||
|
||||
Commits with round 17 (jointly with alignment, which owns the other
|
||||
half of the shared README/TODO edits).
|
||||
Reference in new issue
Block a user