Add vlog_semantic and parallel-files (jointly: shared root manifest)
vlog_semantic (new crate): single-file symbol tables and reference
resolution -- the layer that powers go-to-definition, references,
hover and document outline, and later the semantic lint rules.
Two-pass bind-then-resolve (Verilog forward references), 15 symbol
kinds, scope tree, and a three-state Resolution (Resolved /
ExternalCandidate carrying import paths for the future workspace
index / NotFound). scan.rs recovers name spans the AST lacks (95k
corpus spans verified; handshake filed and approved to move
name_span into the parser, which deletes the module). Corpus
baseline: 79.5% in-file resolution, 0.9% unresolved on clean files,
zero panics including tolerant-parse trees.
parallel-files (vfmt): rayon-parallel per-file formatting -- first
dependency, exact-pinned with written justification. 8 MiB worker
stacks discharge the recursion-limit handshake (sabotage-verified);
single-install panic hook discharges the cli-polish handshake;
deterministic input-order output (one stdout/stderr hash across 14
corpus runs at 4 thread counts); --threads flag; hand-rolled
.gitignore subset with 16/16 differential agreement against git
check-ignore. 3.6x wall-clock on the 860-file corpus.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{vlog-semantic,parallel-files}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
982e37063b
commit
7cf657a538
19 files changed
+3909
-65
No files matched your search
Generated
+59
@@ -2,10 +2,62 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"
|
||||
dependencies = [
|
||||
"crossbeam-epoch",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-epoch"
|
||||
version = "0.9.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"
|
||||
|
||||
[[package]]
|
||||
name = "rayon"
|
||||
version = "1.12.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
|
||||
dependencies = [
|
||||
"either",
|
||||
"rayon-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rayon-core"
|
||||
version = "1.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
|
||||
dependencies = [
|
||||
"crossbeam-deque",
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "vfmt"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"rayon",
|
||||
"vlog_formatter",
|
||||
"vlog_parser",
|
||||
]
|
||||
@@ -20,3 +72,10 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vlog_parser"
|
||||
version = "0.1.0"
|
||||
|
||||
[[package]]
|
||||
name = "vlog_semantic"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"vlog_parser",
|
||||
]
|
||||
+8
-1
@@ -1,11 +1,18 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/vlog_parser", "crates/vlog_formatter", "crates/vfmt"]
|
||||
members = ["crates/vlog_parser", "crates/vlog_semantic", "crates/vlog_formatter", "crates/vfmt"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
# `rayon` is sanctioned by TODO.md §3 (parallel file processing) and used by
|
||||
# `vfmt` only. Pinned exactly, because a work-stealing scheduler is exactly
|
||||
# the kind of dependency whose minor releases can change thread behavior;
|
||||
# justification in docs/features/parallel-files/README.md.
|
||||
[workspace.dependencies]
|
||||
rayon = "=1.12.0"
|
||||
|
||||
[profile.release]
|
||||
lto = true
|
||||
@@ -18,6 +18,12 @@ vfmt --diff rtl/
|
||||
# skip generated files while walking directories (repeatable)
|
||||
vfmt --exclude '*_gen.sv' --exclude build rtl/
|
||||
|
||||
# .gitignore is honored while walking; --no-gitignore turns that off
|
||||
vfmt --no-gitignore rtl/
|
||||
|
||||
# files are formatted on all cores; pin the worker count for reproducible CI
|
||||
vfmt --threads 1 rtl/
|
||||
|
||||
# ignore any vfmt.toml found next to the input
|
||||
vfmt --no-config rtl/
|
||||
|
||||
@@ -36,6 +42,31 @@ cat foo.sv | vfmt --stdin-filename rtl/foo.sv -
|
||||
|
||||
An error outranks "would reformat": a run with both exits 2.
|
||||
|
||||
### Parallelism
|
||||
|
||||
Files are formatted on a worker pool, one thread per logical CPU by default.
|
||||
`--threads N` pins the worker count (`--threads 1` is a single worker), which
|
||||
matters for reproducible CI timing and for bisecting; it never changes what is
|
||||
produced. **The thread count does not affect output**: results are collected
|
||||
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.
|
||||
|
||||
### Ignore files
|
||||
|
||||
While walking a directory, vfmt reads a `.gitignore` in every directory it
|
||||
enters and skips what those rules name. A deeper `.gitignore` is applied after
|
||||
(and so overrides) a shallower one, and within one file the last matching line
|
||||
wins — git's own precedence. `--no-gitignore` switches this off. A path named
|
||||
directly on the command line is never ignored, exactly as with `--exclude`.
|
||||
|
||||
Supported: `#` comments, blank lines, `*` inside one path component, a leading
|
||||
or embedded `/` (anchors the pattern to that `.gitignore`'s own directory), a
|
||||
trailing `/` (matches directories only), and `!` negation. **Not** supported:
|
||||
`**`, `?`, character classes, `\` escapes, the global/repo excludes files, and
|
||||
git's "already-tracked files are never ignored" rule. See
|
||||
`docs/features/parallel-files/README.md` for the exact subset.
|
||||
|
||||
## Configuration
|
||||
|
||||
Settings live in a `vfmt.toml` (or `.vfmt.toml`) file, ruff-style. For each
|
||||
|
||||
@@ -102,15 +102,25 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
clang-format-sized option surface.
|
||||
→ `crates/vfmt/src/config.rs`; discovery rule, TOML subset and
|
||||
precedence in `docs/features/config-discovery/README.md`.
|
||||
- [ ] **[R] Parallel file processing.** ruff's speed story is embarrassing
|
||||
- [x] **[R] Parallel file processing.** ruff's speed story is embarrassing
|
||||
parallelism over files. `main.rs` formats serially; use `rayon`
|
||||
par_iter over the collected file list (formatting is already pure).
|
||||
→ `crates/vfmt/src/main.rs`; pool sizing (8 MiB worker stacks, per the
|
||||
recursion-limit handshake), the reworked panic hook and the
|
||||
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
|
||||
hash, vfmt version) triple is unchanged, stored in `.vfmt_cache/`.
|
||||
Do this *after* parallelism; it matters for big monorepo RTL trees.
|
||||
- [ ] **[R] Respect `.gitignore`** and add `--exclude` globs when walking
|
||||
- [x] **[R] Respect `.gitignore`** and add `--exclude` globs when walking
|
||||
directories (`collect_files` in `main.rs` currently walks everything,
|
||||
including e.g. generated netlists).
|
||||
→ `--exclude` shipped with cli-polish; `.gitignore` is hand-rolled in
|
||||
`crates/vfmt/src/walk.rs` (anchoring, directory-only, `!` negation,
|
||||
nested files override) with a `--no-gitignore` escape hatch. The
|
||||
supported subset and everything git does that this does not are listed
|
||||
in `docs/features/parallel-files/README.md`.
|
||||
- [x] **[V+R] Exit-code contract doc.** Already ruff-like (0 clean /
|
||||
1 would-reformat / 2 error) — document it in README and freeze it; CI
|
||||
scripts will depend on it.
|
||||
@@ -248,12 +258,20 @@ later:
|
||||
serve formatter, linter, and highlighter. If gaps appear, consider a
|
||||
rowan-style green tree (rust-analyzer / ruff direction) rather than
|
||||
patching `Meta`.
|
||||
- [ ] **New crate `vlog_semantic`** (analog of `ruff_python_semantic`):
|
||||
- [x] **New crate `vlog_semantic`** (analog of `ruff_python_semantic`):
|
||||
symbol tables per scope (module/package/function/block/generate), binding
|
||||
→ references. Serves go-to-definition/hover first, then semantic lint
|
||||
rules (unused-signal, undriven-net) which are the lint rules people
|
||||
actually want and Verible *can't* do (it's syntax-only — this is the
|
||||
differentiation opportunity).
|
||||
→ `vlog_semantic::analyze(&SourceFile, src) -> Semantics`, never failing,
|
||||
with `symbol_at` / `definition_of` / `references_of` / `document_symbols`.
|
||||
Two-pass bind-then-resolve (so forward references work), imports of
|
||||
in-file packages resolved and all others kept as
|
||||
`Resolution::ExternalCandidate` for the workspace index below. Rules,
|
||||
simplifications and the corpus baseline (79.5% of uses resolved in-file on
|
||||
cleanly-parsed corpus files, 19.6% external, 0.9% unresolved) in
|
||||
`docs/features/vlog-semantic/README.md`.
|
||||
- [x] **`` `define`` table for hover expansion.** Record every
|
||||
`` `define`` (name, params, body text, source span) during lexing
|
||||
instead of treating it as fully opaque — no expansion during
|
||||
|
||||
@@ -12,3 +12,4 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
vlog_formatter = { path = "../vlog_formatter" }
|
||||
rayon = { workspace = true }
|
||||
@@ -13,6 +13,11 @@ pub struct Options {
|
||||
pub stdout: bool,
|
||||
/// Ignore `vfmt.toml` / `.vfmt.toml` files entirely.
|
||||
pub no_config: bool,
|
||||
/// Ignore `.gitignore` files while walking directories.
|
||||
pub no_gitignore: bool,
|
||||
/// `--threads`: worker count for the file pool. `None` or `Some(0)`
|
||||
/// means rayon's default, one per logical CPU.
|
||||
pub threads: Option<usize>,
|
||||
/// Path to report instead of `<stdin>` when input comes from stdin.
|
||||
/// Also the directory config discovery anchors on.
|
||||
pub stdin_filename: Option<String>,
|
||||
@@ -51,6 +56,11 @@ impl Options {
|
||||
exclude.extend(file.exclude.iter().flatten().cloned());
|
||||
exclude
|
||||
}
|
||||
|
||||
/// Worker threads to build the pool with; 0 lets rayon decide.
|
||||
pub fn thread_count(&self) -> usize {
|
||||
self.threads.unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Prints the `--help` text, including the frozen exit-code contract.
|
||||
@@ -72,12 +82,25 @@ OPTIONS:
|
||||
matches within one path component
|
||||
--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
|
||||
--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
|
||||
--line-length <N> maximum line length (default 100)
|
||||
--indent <N> indent width in spaces (default 2)
|
||||
--no-config ignore vfmt.toml / .vfmt.toml files
|
||||
-h, --help show this help
|
||||
-V, --version show version
|
||||
|
||||
IGNORE FILES:
|
||||
While walking a directory, vfmt reads a `.gitignore` in every directory it
|
||||
enters and skips what it names; a deeper file overrides a shallower one and
|
||||
the last matching line wins. Supported: `#` comments, `*` inside one path
|
||||
component, a leading or embedded `/` (anchors to that .gitignore's own
|
||||
directory), a trailing `/` (directories only) and `!` negation. Not
|
||||
supported: `**`, `?`, character classes, `\\` escapes and the global/repo
|
||||
excludes files. Paths named on the command line are never ignored.
|
||||
|
||||
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
|
||||
@@ -105,6 +128,8 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
diff: false,
|
||||
stdout: false,
|
||||
no_config: false,
|
||||
no_gitignore: false,
|
||||
threads: None,
|
||||
stdin_filename: None,
|
||||
exclude: Vec::new(),
|
||||
line_length: None,
|
||||
@@ -118,6 +143,11 @@ fn parse_from(args: impl Iterator<Item = String>) -> Result<Options, String> {
|
||||
"--diff" => opts.diff = true,
|
||||
"--stdout" => opts.stdout = true,
|
||||
"--no-config" => opts.no_config = true,
|
||||
"--no-gitignore" => opts.no_gitignore = true,
|
||||
"--threads" => {
|
||||
let v = args.next().ok_or("--threads requires a value")?;
|
||||
opts.threads = Some(v.parse().map_err(|_| format!("invalid thread count: {v}"))?);
|
||||
}
|
||||
"--exclude" => {
|
||||
let v = args.next().ok_or("--exclude requires a value")?;
|
||||
opts.exclude.push(v);
|
||||
@@ -216,5 +246,21 @@ mod tests {
|
||||
assert!(parse(&["--exclude"]).is_err());
|
||||
assert!(parse(&["--line-length"]).is_err());
|
||||
assert!(parse(&["--line-length", "wide", "rtl"]).is_err());
|
||||
assert!(parse(&["--threads"]).is_err());
|
||||
assert!(parse(&["--threads", "many", "rtl"]).is_err());
|
||||
assert!(parse(&["--threads", "-1", "rtl"]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_count_defaults_to_letting_rayon_decide() {
|
||||
assert_eq!(parse(&["rtl"]).unwrap().thread_count(), 0);
|
||||
assert_eq!(parse(&["--threads", "0", "rtl"]).unwrap().thread_count(), 0);
|
||||
assert_eq!(parse(&["--threads", "4", "rtl"]).unwrap().thread_count(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gitignore_is_honored_unless_switched_off() {
|
||||
assert!(!parse(&["rtl"]).unwrap().no_gitignore);
|
||||
assert!(parse(&["--no-gitignore", "rtl"]).unwrap().no_gitignore);
|
||||
}
|
||||
}
|
||||
+134
-44
@@ -14,16 +14,25 @@ mod config;
|
||||
mod diff;
|
||||
mod walk;
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::io::Read;
|
||||
use std::panic::AssertUnwindSafe;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::ExitCode;
|
||||
|
||||
use rayon::prelude::*;
|
||||
|
||||
use args::Options;
|
||||
use config::Discovery;
|
||||
use vlog_formatter::{format_source, Config};
|
||||
use walk::{collect_files, EXTENSIONS};
|
||||
|
||||
/// Worker stack size. `docs/features/recursion-limit/README.md` measured
|
||||
/// the full pipeline's worst-case peak at ~3.9 MiB in a debug build on
|
||||
/// input that trips the parser's nesting limit; rayon's own default is
|
||||
/// 2 MiB, which would put that crash back.
|
||||
const WORKER_STACK: usize = 8 * 1024 * 1024;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let opts = match args::parse() {
|
||||
Ok(o) => o,
|
||||
@@ -32,6 +41,8 @@ fn main() -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
}
|
||||
};
|
||||
// Once, before any worker thread exists, so nothing ever races on it.
|
||||
install_panic_hook();
|
||||
|
||||
if opts.inputs.len() == 1 && opts.inputs[0] == "-" {
|
||||
run_stdin(&opts)
|
||||
@@ -77,7 +88,7 @@ fn run_stdin(opts: &Options) -> ExitCode {
|
||||
}
|
||||
|
||||
fn run_files(opts: &Options) -> ExitCode {
|
||||
let jobs = match gather(opts) {
|
||||
let jobs = match gather(opts).and_then(|jobs| build_pool(opts).map(|()| jobs)) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
@@ -85,42 +96,26 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
}
|
||||
};
|
||||
|
||||
let mut changed = 0usize;
|
||||
let mut unchanged = 0usize;
|
||||
let mut errors = 0usize;
|
||||
for (file, config) in &jobs {
|
||||
let src = match std::fs::read_to_string(file) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
continue;
|
||||
// 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();
|
||||
|
||||
let (mut changed, mut unchanged, mut errors) = (0usize, 0usize, 0usize);
|
||||
for outcome in outcomes {
|
||||
match outcome {
|
||||
Outcome::Unchanged => unchanged += 1,
|
||||
Outcome::Printed(text) => print!("{text}"),
|
||||
Outcome::Changed(text) => {
|
||||
changed += 1;
|
||||
print!("{text}");
|
||||
}
|
||||
};
|
||||
let out = match format_contained(&src, config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
Outcome::Failed(message) => {
|
||||
errors += 1;
|
||||
continue;
|
||||
eprintln!("error: {message}");
|
||||
}
|
||||
};
|
||||
if opts.stdout {
|
||||
print!("{out}");
|
||||
continue;
|
||||
}
|
||||
if out == src {
|
||||
unchanged += 1;
|
||||
continue;
|
||||
}
|
||||
changed += 1;
|
||||
if opts.diff {
|
||||
print!("{}", diff::unified(&file.display().to_string(), &src, &out));
|
||||
} else if opts.check {
|
||||
println!("would reformat: {}", file.display());
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
eprintln!("error: {}: {e}", file.display());
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,6 +132,61 @@ fn run_files(opts: &Options) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
/// 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,
|
||||
/// `--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
|
||||
/// `--check` line, and is empty when the file was rewritten in place.
|
||||
Changed(String),
|
||||
/// `<path>: <what went wrong>`. The file was left untouched.
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let name = file.display();
|
||||
let src = match std::fs::read_to_string(file) {
|
||||
Ok(s) => s,
|
||||
Err(e) => return Outcome::Failed(format!("{name}: {e}")),
|
||||
};
|
||||
let out = match format_contained(&src, config) {
|
||||
Ok(o) => o,
|
||||
Err(e) => return Outcome::Failed(format!("{name}: {e}")),
|
||||
};
|
||||
if opts.stdout {
|
||||
return Outcome::Printed(out);
|
||||
}
|
||||
if out == src {
|
||||
return Outcome::Unchanged;
|
||||
}
|
||||
if opts.diff {
|
||||
Outcome::Changed(diff::unified(&name.to_string(), &src, &out))
|
||||
} else if opts.check {
|
||||
Outcome::Changed(format!("would reformat: {name}\n"))
|
||||
} else if let Err(e) = std::fs::write(file, &out) {
|
||||
Outcome::Failed(format!("{name}: {e}"))
|
||||
} else {
|
||||
Outcome::Changed(String::new())
|
||||
}
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
rayon::ThreadPoolBuilder::new()
|
||||
.num_threads(opts.thread_count())
|
||||
.stack_size(WORKER_STACK)
|
||||
.build_global()
|
||||
.map_err(|e| format!("could not start the worker pool: {e}"))
|
||||
}
|
||||
|
||||
/// Collects the files to format, each with the settings that govern it.
|
||||
/// Every config file is read here, before anything is written, so a broken
|
||||
/// one aborts the whole run instead of leaving it half applied.
|
||||
@@ -148,7 +198,7 @@ fn gather(opts: &Options) -> Result<Vec<(PathBuf, Config)>, String> {
|
||||
return Err("`-` cannot be combined with file arguments".to_string());
|
||||
}
|
||||
let exclude = opts.exclude_with(&discovery.for_input(Path::new(input))?);
|
||||
collect_files(input, &exclude, &mut files)?;
|
||||
collect_files(input, &exclude, !opts.no_gitignore, &mut files)?;
|
||||
}
|
||||
if files.is_empty() {
|
||||
return Err(format!("no Verilog files found (extensions: {})", EXTENSIONS.join(", ")));
|
||||
@@ -201,15 +251,38 @@ fn format_contained(src: &str, config: &Config) -> Result<String, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f`, turning a panic into `Err(message)`. The default panic hook
|
||||
/// is silenced for the duration so a contained panic prints no backtrace
|
||||
/// noise of its own. Sound only while vfmt formats on a single thread —
|
||||
/// see the feature README's handshake with the parallelism work.
|
||||
thread_local! {
|
||||
/// True while this thread is inside `catch_panic`, which is how the
|
||||
/// panic hook knows to keep quiet: vfmt reports contained panics
|
||||
/// itself, in its own error style.
|
||||
static CONTAINED: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Installs vfmt's panic hook. Called once at startup, before any worker
|
||||
/// thread exists, because swapping the process-global hook per call would
|
||||
/// race once files are formatted in parallel. A panic outside
|
||||
/// `catch_panic` — a real bug in the driver — still reaches the default
|
||||
/// hook and its backtrace.
|
||||
fn install_panic_hook() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| {
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
if !CONTAINED.with(Cell::get) {
|
||||
default(info);
|
||||
}
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/// Runs `f`, turning a panic into `Err(message)`. The thread-local flag
|
||||
/// silences the hook installed by `install_panic_hook` for the duration,
|
||||
/// on this thread only, so concurrent formatting of other files is
|
||||
/// unaffected.
|
||||
fn catch_panic<T>(f: impl FnOnce() -> T) -> Result<T, String> {
|
||||
let hook = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(|_| {}));
|
||||
CONTAINED.with(|flag| flag.set(true));
|
||||
let result = std::panic::catch_unwind(AssertUnwindSafe(f));
|
||||
std::panic::set_hook(hook);
|
||||
CONTAINED.with(|flag| flag.set(false));
|
||||
result.map_err(|payload| {
|
||||
if let Some(s) = payload.downcast_ref::<&str>() {
|
||||
(*s).to_string()
|
||||
@@ -235,11 +308,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn catch_panic_returns_values_unchanged() {
|
||||
install_panic_hook();
|
||||
assert_eq!(catch_panic(|| 1 + 1), Ok(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_panic_reports_the_payload() {
|
||||
install_panic_hook();
|
||||
assert_eq!(catch_panic(|| panic!("boom")), Err("boom".to_string()));
|
||||
let n = 7;
|
||||
assert_eq!(catch_panic(|| panic!("boom {n}")), Err("boom 7".to_string()));
|
||||
@@ -247,10 +322,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn catch_panic_is_reusable() {
|
||||
// The hook swap must be balanced, so a second contained panic
|
||||
// behaves exactly like the first.
|
||||
install_panic_hook();
|
||||
// The flag must be cleared on the way out, so a second contained
|
||||
// panic behaves exactly like the first.
|
||||
assert_eq!(catch_panic(|| panic!("first")), Err("first".to_string()));
|
||||
assert_eq!(catch_panic(|| panic!("second")), Err("second".to_string()));
|
||||
assert!(!CONTAINED.with(Cell::get), "the flag must not leak out of catch_panic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catch_panic_silences_only_its_own_thread() {
|
||||
// The hook is process-wide but the flag is not: a thread that is
|
||||
// not inside `catch_panic` must still get the default hook. Proven
|
||||
// by observing the flag from another thread while this one holds
|
||||
// it — if it were global state, the observation would be `true`.
|
||||
install_panic_hook();
|
||||
CONTAINED.with(|flag| flag.set(true));
|
||||
let elsewhere = std::thread::spawn(|| CONTAINED.with(Cell::get)).join().unwrap();
|
||||
CONTAINED.with(|flag| flag.set(false));
|
||||
assert!(!elsewhere);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+219
-16
@@ -1,21 +1,29 @@
|
||||
//! File discovery: directory walking and `--exclude` matching.
|
||||
//! File discovery: directory walking, `--exclude` matching and the
|
||||
//! `.gitignore` subset documented in
|
||||
//! `docs/features/parallel-files/README.md`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// File extensions vfmt formats when walking a directory.
|
||||
pub const EXTENSIONS: &[&str] = &["v", "sv", "vh", "svh"];
|
||||
|
||||
/// The name of the per-directory ignore file that is honoured by default.
|
||||
const GITIGNORE: &str = ".gitignore";
|
||||
|
||||
/// Adds `input` to `files`: the file itself, or every Verilog file under
|
||||
/// it if it is a directory. Exclude patterns apply to directory walks
|
||||
/// only — a path named on the command line is always formatted.
|
||||
/// it if it is a directory. Exclude patterns and `.gitignore` rules apply
|
||||
/// to directory walks only — a path named on the command line is always
|
||||
/// formatted.
|
||||
pub fn collect_files(
|
||||
input: &str,
|
||||
exclude: &[String],
|
||||
gitignore: bool,
|
||||
files: &mut Vec<PathBuf>,
|
||||
) -> Result<(), String> {
|
||||
let path = Path::new(input);
|
||||
if path.is_dir() {
|
||||
walk_dir(path, exclude, files).map_err(|e| format!("{input}: {e}"))?;
|
||||
let mut walk = Walk { exclude, gitignore, ignores: Vec::new(), rel: Vec::new(), files };
|
||||
walk.dir(path).map_err(|e| format!("{input}: {e}"))?;
|
||||
} else if path.is_file() {
|
||||
files.push(path.to_path_buf());
|
||||
} else {
|
||||
@@ -24,23 +32,139 @@ pub fn collect_files(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn walk_dir(dir: &Path, exclude: &[String], files: &mut Vec<PathBuf>) -> std::io::Result<()> {
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if is_excluded(&path, exclude) {
|
||||
/// One directory walk. `rel` is the path of the directory currently being
|
||||
/// read, in components relative to the walk root, which is what
|
||||
/// `.gitignore` rules are matched against; `ignores` is the stack of
|
||||
/// ignore files seen from the root down to it.
|
||||
struct Walk<'a> {
|
||||
exclude: &'a [String],
|
||||
gitignore: bool,
|
||||
ignores: Vec<Ignore>,
|
||||
rel: Vec<String>,
|
||||
files: &'a mut Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
fn dir(&mut self, dir: &Path) -> std::io::Result<()> {
|
||||
let pushed = self.push_ignore(dir)?;
|
||||
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<Result<_, _>>()?;
|
||||
entries.sort_by_key(|e| e.path());
|
||||
for entry in entries {
|
||||
let path = entry.path();
|
||||
if is_excluded(&path, self.exclude) {
|
||||
continue;
|
||||
}
|
||||
let is_dir = path.is_dir();
|
||||
self.rel.push(entry.file_name().to_string_lossy().into_owned());
|
||||
if !is_ignored(&self.ignores, &self.rel, is_dir) {
|
||||
if is_dir {
|
||||
self.dir(&path)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
self.files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.rel.pop();
|
||||
}
|
||||
if pushed {
|
||||
self.ignores.pop();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads `dir`'s `.gitignore`, if there is one, onto the rule stack.
|
||||
/// Returns whether anything was pushed, so `dir` can pop it again.
|
||||
fn push_ignore(&mut self, dir: &Path) -> std::io::Result<bool> {
|
||||
let path = dir.join(GITIGNORE);
|
||||
if !self.gitignore || !path.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
let rules = parse_gitignore(&std::fs::read_to_string(&path)?);
|
||||
self.ignores.push(Ignore { base: self.rel.len(), rules });
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// One `.gitignore` file's rules, plus how deep in the walk the directory
|
||||
/// holding it was, so its patterns can be matched relative to it.
|
||||
struct Ignore {
|
||||
base: usize,
|
||||
rules: Vec<Rule>,
|
||||
}
|
||||
|
||||
/// One `.gitignore` line, already stripped of its prefix and suffix
|
||||
/// markers. The remaining pattern uses the `--exclude` glob semantics.
|
||||
struct Rule {
|
||||
/// `!pattern`: a match re-includes instead of ignoring.
|
||||
negated: bool,
|
||||
/// `pattern/`: matches directories only.
|
||||
dir_only: bool,
|
||||
/// The pattern had a `/` at its start or in its middle, so it is
|
||||
/// matched from the `.gitignore`'s own directory instead of at any
|
||||
/// depth below it.
|
||||
anchored: bool,
|
||||
pattern: String,
|
||||
}
|
||||
|
||||
/// Parses the supported `.gitignore` subset; unsupported metacharacters
|
||||
/// are left to match literally rather than rejected. Grammar and the
|
||||
/// explicit list of what git does that this does not:
|
||||
/// `docs/features/parallel-files/README.md`.
|
||||
fn parse_gitignore(text: &str) -> Vec<Rule> {
|
||||
let mut rules = Vec::new();
|
||||
for raw in text.lines() {
|
||||
// Git strips trailing whitespace but not leading whitespace.
|
||||
let line = raw.trim_end();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
if path.is_dir() {
|
||||
walk_dir(&path, exclude, files)?;
|
||||
} else if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
if EXTENSIONS.contains(&ext) {
|
||||
files.push(path);
|
||||
let (negated, line) = match line.strip_prefix('!') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, line),
|
||||
};
|
||||
let (dir_only, line) = match line.strip_suffix('/') {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, line),
|
||||
};
|
||||
let anchored = line.contains('/');
|
||||
let pattern = line.strip_prefix('/').unwrap_or(line);
|
||||
if pattern.is_empty() {
|
||||
continue;
|
||||
}
|
||||
rules.push(Rule { negated, dir_only, anchored, pattern: pattern.to_string() });
|
||||
}
|
||||
rules
|
||||
}
|
||||
|
||||
/// True if the ignore stack ignores the entry at `rel` (components
|
||||
/// relative to the walk root). Later rules win, so a deeper `.gitignore`
|
||||
/// overrides a shallower one and a later line overrides an earlier one —
|
||||
/// git's own precedence, which is what makes `!` useful.
|
||||
fn is_ignored(ignores: &[Ignore], rel: &[String], is_dir: bool) -> bool {
|
||||
let mut ignored = false;
|
||||
for ignore in ignores {
|
||||
let Some(tail) = rel.get(ignore.base..) else { continue };
|
||||
for rule in &ignore.rules {
|
||||
if rule_matches(rule, tail, is_dir) {
|
||||
ignored = !rule.negated;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
ignored
|
||||
}
|
||||
|
||||
fn rule_matches(rule: &Rule, tail: &[String], is_dir: bool) -> bool {
|
||||
if rule.dir_only && !is_dir {
|
||||
return false;
|
||||
}
|
||||
if !rule.anchored {
|
||||
// No `/` in the pattern: it matches an entry's name at any depth.
|
||||
return tail.last().is_some_and(|name| glob_component(&rule.pattern, name));
|
||||
}
|
||||
let pattern: Vec<&str> = rule.pattern.split('/').collect();
|
||||
pattern.len() == tail.len()
|
||||
&& pattern.iter().zip(tail).all(|(p, c)| glob_component(p, c.as_str()))
|
||||
}
|
||||
|
||||
/// True if `path` matches any exclude pattern. A pattern containing `/`
|
||||
@@ -126,4 +250,83 @@ mod tests {
|
||||
assert!(excluded("a/ab", "a*b*"));
|
||||
assert!(!excluded("a/xxx", "*y"));
|
||||
}
|
||||
|
||||
/// Builds a one-level ignore stack rooted at the walk root and asks it
|
||||
/// about `rel` (a `/`-joined path, trailing `/` meaning a directory).
|
||||
fn ignored(text: &str, rel: &str) -> bool {
|
||||
ignored_at(&[(0, text)], rel)
|
||||
}
|
||||
|
||||
/// The same, with several `.gitignore` files at the given depths.
|
||||
fn ignored_at(files: &[(usize, &str)], rel: &str) -> bool {
|
||||
let ignores: Vec<Ignore> = files
|
||||
.iter()
|
||||
.map(|(base, text)| Ignore { base: *base, rules: parse_gitignore(text) })
|
||||
.collect();
|
||||
let is_dir = rel.ends_with('/');
|
||||
let parts: Vec<String> =
|
||||
rel.trim_end_matches('/').split('/').map(|s| s.to_string()).collect();
|
||||
is_ignored(&ignores, &parts, is_dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_and_blank_lines_are_skipped() {
|
||||
assert_eq!(parse_gitignore("\n# build\n\n \nbuild\n").len(), 1);
|
||||
assert!(!ignored("# build", "build"));
|
||||
assert!(ignored("build", "build"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_name_matches_at_any_depth() {
|
||||
assert!(ignored("build", "build"));
|
||||
assert!(ignored("build", "a/b/build"));
|
||||
assert!(ignored("*.log", "a/b/c.log"));
|
||||
assert!(!ignored("build", "a/building"));
|
||||
assert!(!ignored("build", "build/x.sv"), "the walk prunes the directory instead");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slash_anchors_the_pattern_to_the_ignore_files_directory() {
|
||||
assert!(ignored("/build", "build"));
|
||||
assert!(!ignored("/build", "a/build"), "a leading slash anchors");
|
||||
assert!(ignored("gen/rtl", "gen/rtl"));
|
||||
assert!(!ignored("gen/rtl", "a/gen/rtl"), "a slash in the middle anchors too");
|
||||
assert!(ignored("gen/*.sv", "gen/x.sv"));
|
||||
assert!(!ignored("gen/*.sv", "gen/a/x.sv"), "`*` never crosses a separator");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_slash_matches_directories_only() {
|
||||
assert!(ignored("build/", "build/"));
|
||||
assert!(!ignored("build/", "build"));
|
||||
assert!(ignored("build", "build/"), "without the slash both kinds match");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negation_re_includes_and_the_last_match_wins() {
|
||||
assert!(!ignored("*.sv\n!keep.sv", "keep.sv"));
|
||||
assert!(ignored("*.sv\n!keep.sv", "drop.sv"));
|
||||
assert!(ignored("!keep.sv\n*.sv", "keep.sv"), "order matters: the last match wins");
|
||||
// A deeper .gitignore is consulted after a shallower one, so it wins.
|
||||
assert!(!ignored_at(&[(0, "*.sv"), (1, "!keep.sv")], "sub/keep.sv"));
|
||||
assert!(ignored_at(&[(0, "!keep.sv"), (1, "*.sv")], "sub/keep.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_anchored_pattern_is_relative_to_its_own_gitignore() {
|
||||
// `/x.sv` in sub/.gitignore (base 1) means sub/x.sv, not x.sv.
|
||||
assert!(ignored_at(&[(1, "/x.sv")], "sub/x.sv"));
|
||||
assert!(!ignored_at(&[(1, "/x.sv")], "sub/deep/x.sv"));
|
||||
assert!(!ignored_at(&[(0, "/x.sv")], "sub/x.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_syntax_degrades_to_plain_globbing() {
|
||||
// `**` is just two stars inside one component; documented.
|
||||
assert!(ignored("a/**/z.sv", "a/b/z.sv"));
|
||||
assert!(!ignored("a/**/z.sv", "a/b/c/z.sv"));
|
||||
// `?` is a literal character, not a single-character wildcard.
|
||||
assert!(ignored("x?.sv", "x?.sv"));
|
||||
assert!(!ignored("x?.sv", "xa.sv"));
|
||||
}
|
||||
}
|
||||
+219
-1
@@ -283,6 +283,215 @@ fn deeply_nested_file_does_not_kill_the_batch() {
|
||||
assert!(err.contains("2 files failed to format"), "{err}");
|
||||
}
|
||||
|
||||
/// A tree wide enough that the pool actually splits it up, with a mix of
|
||||
/// formatted, unformatted and broken files so every counter is exercised.
|
||||
fn mixed_tree(dir: &TempDir) {
|
||||
for n in 0..24 {
|
||||
dir.write(&format!("wide/f{n:02}.sv"), UNFORMATTED);
|
||||
dir.write(&format!("deep/a/b/c/g{n:02}.v"), FORMATTED);
|
||||
}
|
||||
dir.write("bad/x.sv", UNPARSEABLE);
|
||||
dir.write("bad/y.sv", UNPARSEABLE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_count_changes_nothing_but_speed() {
|
||||
// The determinism bar: the same invocation must produce byte-identical
|
||||
// stdout, stderr and exit code however many workers ran it.
|
||||
for mode in [&["--check"][..], &["--diff"][..]] {
|
||||
let dir = TempDir::new("threads");
|
||||
mixed_tree(&dir);
|
||||
let root = dir.root();
|
||||
|
||||
let mut args = mode.to_vec();
|
||||
args.push(&root);
|
||||
let parallel = run(&args);
|
||||
let mut serial_args = vec!["--threads", "1"];
|
||||
serial_args.extend_from_slice(mode);
|
||||
serial_args.push(&root);
|
||||
let serial = run(&serial_args);
|
||||
|
||||
assert_eq!(code(¶llel), code(&serial), "{mode:?}");
|
||||
assert_eq!(parallel.stdout, serial.stdout, "{mode:?}: stdout must not depend on threads");
|
||||
assert_eq!(parallel.stderr, serial.stderr, "{mode:?}: stderr must not depend on threads");
|
||||
assert_eq!(code(¶llel), 2, "the broken files win over would-reformat");
|
||||
assert!(stderr(¶llel).contains("2 files failed to format"), "{}", stderr(¶llel));
|
||||
|
||||
// And a second parallel run of the same thing is byte-identical too.
|
||||
let again = run(&args);
|
||||
assert_eq!(parallel.stdout, again.stdout, "{mode:?}: two parallel runs must agree");
|
||||
assert_eq!(parallel.stderr, again.stderr, "{mode:?}: two parallel runs must agree");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writing_in_parallel_matches_writing_serially() {
|
||||
let parallel = TempDir::new("writepar");
|
||||
let serial = TempDir::new("writeser");
|
||||
mixed_tree(¶llel);
|
||||
mixed_tree(&serial);
|
||||
|
||||
let a = run(&[¶llel.root()]);
|
||||
let b = run(&["--threads", "1", &serial.root()]);
|
||||
assert_eq!(code(&a), 2);
|
||||
assert_eq!(code(&b), 2);
|
||||
// Only the summary line can be compared verbatim: the error lines name
|
||||
// the two (necessarily different) temporary directories.
|
||||
let summary = |out: &Output| stderr(out).lines().last().unwrap_or_default().to_string();
|
||||
assert_eq!(summary(&a), summary(&b), "the summary must not depend on the thread count");
|
||||
assert_eq!(
|
||||
summary(&a),
|
||||
"24 files reformatted, 24 files left unchanged, 2 files failed to format"
|
||||
);
|
||||
for n in 0..24 {
|
||||
let f = format!("wide/f{n:02}.sv");
|
||||
assert_eq!(parallel.read(&f), FORMATTED);
|
||||
assert_eq!(parallel.read(&f), serial.read(&f));
|
||||
}
|
||||
assert_eq!(parallel.read("bad/x.sv"), UNPARSEABLE, "a broken file is left untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diff_over_many_files_comes_out_in_input_order() {
|
||||
let dir = TempDir::new("difforder");
|
||||
let names = ["a.sv", "b.sv", "c.sv", "d/e.sv", "d/f.sv", "g.sv"];
|
||||
for name in names {
|
||||
dir.write(name, UNFORMATTED);
|
||||
}
|
||||
|
||||
let out = run(&["--diff", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let text = stdout(&out);
|
||||
let headers: Vec<&str> = text.lines().filter(|l| l.starts_with("--- ")).collect();
|
||||
let expected: Vec<String> =
|
||||
names.iter().map(|n| format!("--- {}/{n}", dir.root())).collect::<Vec<_>>();
|
||||
// `d/` sorts after `c.sv` and before `g.sv`, matching the walk order.
|
||||
let mut expected: Vec<&str> = expected.iter().map(String::as_str).collect();
|
||||
expected.sort();
|
||||
assert_eq!(headers, expected, "{text}");
|
||||
// Each file's hunks stay together: nothing interleaves.
|
||||
assert_eq!(text.matches("@@ ").count(), names.len(), "{text}");
|
||||
assert_eq!(stdout(&run(&["--threads", "1", "--diff", &dir.root()])), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deeply_nested_file_formats_on_a_worker_thread() {
|
||||
// Just under `vlog_parser::MAX_NESTING_DEPTH` (a nested `if … begin`
|
||||
// costs two levels), so it parses — and needs several MiB of stack to
|
||||
// do it in a debug build: without the depth limit this family died at
|
||||
// 15 levels on a 2 MiB thread, which is exactly rayon's default worker
|
||||
// stack. This test crashes the process if the pool's 8 MiB is dropped.
|
||||
let deep = format!(
|
||||
"module m;\nalways @(posedge clk) begin\n{}x <= 1;\n{}end\nendmodule\n",
|
||||
"if (clk) begin\n".repeat(28),
|
||||
"end\n".repeat(28)
|
||||
);
|
||||
let dir = TempDir::new("deeppool");
|
||||
dir.write("deep.sv", &deep);
|
||||
dir.write("plain.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--check", &dir.root()]);
|
||||
assert_eq!(code(&out), 1, "{}", stderr(&out));
|
||||
let err = stderr(&out);
|
||||
assert!(!err.contains("parse error"), "the input must be under the limit: {err}");
|
||||
assert!(!err.contains("panicked"), "{err}");
|
||||
assert!(stdout(&out).contains("deep.sv"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_file_keeps_its_own_config_when_formatted_in_parallel() {
|
||||
let dir = TempDir::new("configpar");
|
||||
dir.write("vfmt.toml", "indent = 4\n");
|
||||
dir.write("sub/vfmt.toml", "indent = 8\n");
|
||||
dir.write("sub/deeper/vfmt.toml", "indent = 2\n");
|
||||
for n in 0..12 {
|
||||
dir.write(&format!("root{n:02}.sv"), UNINDENTED);
|
||||
dir.write(&format!("sub/mid{n:02}.sv"), UNINDENTED);
|
||||
dir.write(&format!("sub/deeper/low{n:02}.sv"), UNINDENTED);
|
||||
}
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
for n in 0..12 {
|
||||
assert_eq!(dir.read(&format!("root{n:02}.sv")), INDENT_4);
|
||||
assert_eq!(
|
||||
dir.read(&format!("sub/mid{n:02}.sv")),
|
||||
"module m;\n wire x;\nendmodule\n"
|
||||
);
|
||||
assert_eq!(dir.read(&format!("sub/deeper/low{n:02}.sv")), INDENT_2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gitignore_is_honored_while_walking() {
|
||||
let dir = TempDir::new("gitignore");
|
||||
dir.write(".gitignore", "# generated\nbuild/\n*_gen.sv\n");
|
||||
dir.write("keep.sv", UNFORMATTED);
|
||||
dir.write("skip_gen.sv", UNFORMATTED);
|
||||
dir.write("build/inner.sv", UNFORMATTED);
|
||||
dir.write("sub/deep_gen.sv", UNFORMATTED);
|
||||
dir.write("sub/keep.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("keep.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("sub/keep.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("skip_gen.sv"), UNFORMATTED, "a name pattern ignores at any depth");
|
||||
assert_eq!(dir.read("sub/deep_gen.sv"), UNFORMATTED);
|
||||
assert_eq!(dir.read("build/inner.sv"), UNFORMATTED, "an ignored directory is not entered");
|
||||
assert!(stderr(&out).contains("2 files reformatted"), "{}", stderr(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nested_gitignore_overrides_the_one_above_it() {
|
||||
let dir = TempDir::new("gitignorenested");
|
||||
dir.write(".gitignore", "*_gen.sv\n/anchored.sv\n");
|
||||
dir.write("sub/.gitignore", "!keep_gen.sv\ndrop.sv\n");
|
||||
dir.write("anchored.sv", UNFORMATTED);
|
||||
dir.write("sub/anchored.sv", UNFORMATTED);
|
||||
dir.write("sub/keep_gen.sv", UNFORMATTED);
|
||||
dir.write("sub/other_gen.sv", UNFORMATTED);
|
||||
dir.write("sub/drop.sv", UNFORMATTED);
|
||||
dir.write("drop.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&[&dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("anchored.sv"), UNFORMATTED, "a leading slash anchors to the root");
|
||||
assert_eq!(dir.read("sub/anchored.sv"), FORMATTED, "…and does not reach into a subdirectory");
|
||||
assert_eq!(dir.read("sub/keep_gen.sv"), FORMATTED, "the deeper `!` rule wins");
|
||||
assert_eq!(dir.read("sub/other_gen.sv"), UNFORMATTED, "the outer rule still applies");
|
||||
assert_eq!(dir.read("sub/drop.sv"), UNFORMATTED, "the deeper file's own rule applies");
|
||||
assert_eq!(dir.read("drop.sv"), FORMATTED, "a deeper rule does not apply above itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_gitignore_switches_the_whole_thing_off() {
|
||||
let dir = TempDir::new("nogitignore");
|
||||
dir.write(".gitignore", "build/\n*_gen.sv\n");
|
||||
dir.write("keep.sv", UNFORMATTED);
|
||||
dir.write("skip_gen.sv", UNFORMATTED);
|
||||
dir.write("build/inner.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&["--no-gitignore", &dir.root()]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("keep.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("skip_gen.sv"), FORMATTED);
|
||||
assert_eq!(dir.read("build/inner.sv"), FORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gitignore_does_not_apply_to_explicitly_named_paths() {
|
||||
let dir = TempDir::new("gitignoreexplicit");
|
||||
dir.write(".gitignore", "*_gen.sv\nbuild/\n");
|
||||
let named = dir.write("skip_gen.sv", UNFORMATTED);
|
||||
let inside = dir.write("build/inner.sv", UNFORMATTED);
|
||||
|
||||
let out = run(&[&named, &inside]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("skip_gen.sv"), FORMATTED, "a path on the command line is never ignored");
|
||||
assert_eq!(dir.read("build/inner.sv"), FORMATTED);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn usage_errors_exit_2() {
|
||||
assert_eq!(code(&run(&[])), 2, "no inputs");
|
||||
@@ -298,7 +507,16 @@ fn help_documents_the_exit_codes() {
|
||||
let text = stdout(&out);
|
||||
assert!(text.contains("EXIT CODES:"), "{text}");
|
||||
assert!(text.contains("CONFIGURATION:"), "{text}");
|
||||
for flag in ["--check", "--diff", "--exclude", "--stdin-filename", "--no-config"] {
|
||||
assert!(text.contains("IGNORE FILES:"), "{text}");
|
||||
for flag in [
|
||||
"--check",
|
||||
"--diff",
|
||||
"--exclude",
|
||||
"--stdin-filename",
|
||||
"--no-config",
|
||||
"--no-gitignore",
|
||||
"--threads",
|
||||
] {
|
||||
assert!(text.contains(flag), "help is missing {flag}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "vlog_semantic"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Single-file symbol tables and reference resolution for vfmt's language server"
|
||||
|
||||
[dependencies]
|
||||
vlog_parser = { path = "../vlog_parser" }
|
||||
@@ -0,0 +1,828 @@
|
||||
//! Pass one: walk the tree, open scopes, bind declarations, and record every
|
||||
//! identifier *use* as a pending reference. Nothing is resolved here — that is
|
||||
//! `resolve.rs`, and the split is what makes forward references work.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use vlog_parser::ast::*;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::is_keyword;
|
||||
|
||||
use crate::model::{Import, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind};
|
||||
use crate::scan::{name_after_kw, name_span, NameScanner};
|
||||
|
||||
/// A recorded use, waiting for pass two to say what it names.
|
||||
pub(crate) struct Pending {
|
||||
pub name: String,
|
||||
pub name_span: TextRange,
|
||||
pub scope: ScopeId,
|
||||
pub target: Target,
|
||||
}
|
||||
|
||||
/// Where pass two must look for a pending use.
|
||||
pub(crate) enum Target {
|
||||
/// The lexical chain from `scope` outward, imports included.
|
||||
Lexical,
|
||||
/// A package name: the `p` of `p::x` or of `import p::x`.
|
||||
Package,
|
||||
/// A module name: the type of an instantiation.
|
||||
Module,
|
||||
/// The `x` of `p::x`: looked up in package `p`'s scope only.
|
||||
PackageMember(String),
|
||||
/// The `.port` of a connection to the named module.
|
||||
Port(String),
|
||||
}
|
||||
|
||||
pub(crate) struct Binder<'a> {
|
||||
src: &'a str,
|
||||
pub(crate) scopes: Vec<Scope>,
|
||||
pub(crate) symbols: Vec<Symbol>,
|
||||
pub(crate) pending: Vec<Pending>,
|
||||
}
|
||||
|
||||
impl<'a> Binder<'a> {
|
||||
pub(crate) fn new(src: &'a str, file_span: TextRange) -> Self {
|
||||
let file = Scope {
|
||||
kind: ScopeKind::File,
|
||||
parent: None,
|
||||
owner: None,
|
||||
span: file_span,
|
||||
symbols: Vec::new(),
|
||||
children: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
names: HashMap::new(),
|
||||
};
|
||||
Binder { src, scopes: vec![file], symbols: Vec::new(), pending: Vec::new() }
|
||||
}
|
||||
|
||||
pub(crate) fn file_scope(&self) -> ScopeId {
|
||||
ScopeId(0)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Tables
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn new_scope(&mut self, kind: ScopeKind, parent: ScopeId, span: TextRange) -> ScopeId {
|
||||
let id = ScopeId(self.scopes.len() as u32);
|
||||
self.scopes.push(Scope {
|
||||
kind,
|
||||
parent: Some(parent),
|
||||
owner: None,
|
||||
span,
|
||||
symbols: Vec::new(),
|
||||
children: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
names: HashMap::new(),
|
||||
});
|
||||
self.scopes[parent.0 as usize].children.push(id);
|
||||
id
|
||||
}
|
||||
|
||||
/// Bind `name` in `scope`. A name already bound there becomes a reference
|
||||
/// to the first declaration instead of a second symbol — which is how a
|
||||
/// non-ANSI port's body declaration attaches to its header port.
|
||||
fn declare(
|
||||
&mut self,
|
||||
scope: ScopeId,
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
name_span: TextRange,
|
||||
decl_span: TextRange,
|
||||
) -> Option<SymbolId> {
|
||||
if name.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if self.scopes[scope.0 as usize].names.contains_key(name) {
|
||||
self.use_name(scope, name, name_span, Target::Lexical);
|
||||
return None;
|
||||
}
|
||||
let id = SymbolId(self.symbols.len() as u32);
|
||||
self.symbols.push(Symbol {
|
||||
name: name.to_string(),
|
||||
kind,
|
||||
name_span,
|
||||
decl_span,
|
||||
scope,
|
||||
child_scope: None,
|
||||
});
|
||||
let s = &mut self.scopes[scope.0 as usize];
|
||||
s.symbols.push(id);
|
||||
s.names.insert(name.to_string(), id);
|
||||
Some(id)
|
||||
}
|
||||
|
||||
/// Declare `name` and open the scope it owns.
|
||||
fn declare_with_scope(
|
||||
&mut self,
|
||||
scope: ScopeId,
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
name_span: TextRange,
|
||||
decl_span: TextRange,
|
||||
child_kind: ScopeKind,
|
||||
) -> ScopeId {
|
||||
let sym = self.declare(scope, name, kind, name_span, decl_span);
|
||||
let child = self.new_scope(child_kind, scope, decl_span);
|
||||
if let Some(sym) = sym {
|
||||
self.symbols[sym.0 as usize].child_scope = Some(child);
|
||||
self.scopes[child.0 as usize].owner = Some(sym);
|
||||
}
|
||||
child
|
||||
}
|
||||
|
||||
/// Record a use — unless it is not a name this crate can say anything
|
||||
/// about: a system task (`$display`), a macro standing where a name
|
||||
/// belongs (`` `PICORV32_REGS regs (...) ``), or a keyword the parser kept
|
||||
/// in an identifier slot.
|
||||
fn use_name(&mut self, scope: ScopeId, name: &str, name_span: TextRange, target: Target) {
|
||||
if name.is_empty() || name.starts_with('$') || name.starts_with('`') || is_keyword(name) {
|
||||
return;
|
||||
}
|
||||
self.pending.push(Pending { name: name.to_string(), name_span, scope, target });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Items
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
pub(crate) fn bind_items(&mut self, items: &[Item], scope: ScopeId) {
|
||||
for item in items {
|
||||
self.bind_item(item, scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_item(&mut self, item: &Item, scope: ScopeId) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => self.bind_module(m, item.span, scope),
|
||||
ItemKind::Package { kw, name, items, .. } => {
|
||||
let ns = name_after_kw(self.src, item.span, kw, name);
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
name,
|
||||
SymbolKind::Package,
|
||||
ns,
|
||||
item.span,
|
||||
ScopeKind::Package,
|
||||
);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
ItemKind::Import(paths) => self.bind_imports(paths, item.span, scope),
|
||||
ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope),
|
||||
ItemKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, item.span, scope)
|
||||
}
|
||||
ItemKind::DataDecl(d) => self.bind_data_decl(d, item.span, scope),
|
||||
ItemKind::PortDecl(p) => self.bind_port_decl(p, item.span, scope),
|
||||
ItemKind::ContAssign(c) => {
|
||||
self.bind_opt_expr(c.delay.as_ref(), scope);
|
||||
for a in &c.assigns {
|
||||
self.bind_expr(&a.lhs, scope);
|
||||
self.bind_expr(&a.rhs, scope);
|
||||
}
|
||||
}
|
||||
ItemKind::Always { stmt, .. } => self.bind_stmt(stmt, scope),
|
||||
ItemKind::Initial(s) | ItemKind::Final(s) => self.bind_stmt(s, scope),
|
||||
ItemKind::Instantiation(i) => self.bind_instantiation(i, item.span, scope),
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
self.bind_opt_expr(g.delay.as_ref(), scope);
|
||||
for inst in &g.instances {
|
||||
if let Some(name) = &inst.name {
|
||||
let ns = name_span(self.src, inst.span, name);
|
||||
self.declare(scope, name, SymbolKind::Instance, ns, inst.span);
|
||||
}
|
||||
for a in &inst.args {
|
||||
self.bind_expr(&a.expr, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
ItemKind::Genvar(names) => {
|
||||
let mut scanner = NameScanner::new(self.src, item.span);
|
||||
for name in names {
|
||||
let ns = scanner.find(name).unwrap_or(TextRange::empty(item.span.start));
|
||||
self.declare(scope, name, SymbolKind::Genvar, ns, item.span);
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => {
|
||||
let inner = self.new_scope(ScopeKind::Generate, scope, item.span);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
ItemKind::GenIf(g) => self.bind_gen_if(g, scope),
|
||||
ItemKind::GenFor(g) => self.bind_gen_for(g, item.span, scope),
|
||||
ItemKind::GenCase(g) => {
|
||||
self.bind_expr(&g.expr, scope);
|
||||
for it in &g.items {
|
||||
for l in &it.labels {
|
||||
self.bind_expr(&l.expr, scope);
|
||||
}
|
||||
self.bind_gen_block(&it.body, scope);
|
||||
}
|
||||
}
|
||||
ItemKind::Function(f) => self.bind_function(f, item.span, scope),
|
||||
ItemKind::Task(t) => self.bind_task(t, item.span, scope),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
for (lhs, rhs) in pairs {
|
||||
self.bind_expr(lhs, scope);
|
||||
self.bind_expr(rhs, scope);
|
||||
}
|
||||
}
|
||||
// Opaque leaves: verbatim text this crate makes no claims about.
|
||||
ItemKind::Directive(_)
|
||||
| ItemKind::MacroItem(_)
|
||||
| ItemKind::Timeunit(_)
|
||||
| ItemKind::Error(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_module(&mut self, m: &Module, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_after_kw(self.src, span, &m.kw, &m.name);
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&m.name,
|
||||
SymbolKind::Module,
|
||||
ns,
|
||||
span,
|
||||
ScopeKind::Module,
|
||||
);
|
||||
// Header imports, then parameters, then ports: the order they are
|
||||
// written in, so one scanner walks the header left to right.
|
||||
let header = TextRange::new(ns.end, span.end);
|
||||
let mut scanner = NameScanner::new(self.src, header);
|
||||
for import in &m.imports {
|
||||
for path in &import.paths {
|
||||
self.bind_import_path(path, &mut scanner, inner);
|
||||
}
|
||||
}
|
||||
for p in m.param_ports.iter().flatten() {
|
||||
let name = self.decl_name(p.span, &p.ty, &p.unpacked, p.default.as_ref(), &p.name);
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, name.start), inner);
|
||||
self.declare(inner, &p.name, SymbolKind::Param, name, p.span);
|
||||
self.bind_dims(&p.unpacked, inner);
|
||||
self.bind_opt_expr(p.default.as_ref(), inner);
|
||||
}
|
||||
match &m.ports {
|
||||
PortList::Ansi(ports) => {
|
||||
for p in ports {
|
||||
let name =
|
||||
self.decl_name(p.span, &p.ty, &p.unpacked, p.default.as_ref(), &p.name);
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, name.start), inner);
|
||||
self.declare(inner, &p.name, SymbolKind::Port, name, p.span);
|
||||
self.bind_dims(&p.unpacked, inner);
|
||||
self.bind_opt_expr(p.default.as_ref(), inner);
|
||||
}
|
||||
}
|
||||
PortList::NonAnsi(ports) => {
|
||||
for p in ports {
|
||||
self.declare(inner, &p.name, SymbolKind::Port, p.span, p.span);
|
||||
}
|
||||
}
|
||||
PortList::None | PortList::Empty => {}
|
||||
}
|
||||
self.bind_items(&m.items, inner);
|
||||
}
|
||||
|
||||
fn bind_imports(&mut self, paths: &[String], span: TextRange, scope: ScopeId) {
|
||||
let mut scanner = NameScanner::new(self.src, span);
|
||||
for path in paths {
|
||||
self.bind_import_path(path, &mut scanner, scope);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record one `pkg::item` / `pkg::*` path as an import of `scope`.
|
||||
fn bind_import_path(&mut self, path: &str, scanner: &mut NameScanner, scope: ScopeId) {
|
||||
let (package, item) = match path.split_once("::") {
|
||||
Some((p, i)) => (p, i),
|
||||
None => (path, "*"),
|
||||
};
|
||||
let pkg_span = scanner.find(package).unwrap_or(TextRange::empty(0));
|
||||
let item = if item == "*" {
|
||||
None
|
||||
} else {
|
||||
// Consume the imported name so the next path starts after it.
|
||||
let item_span = scanner.find(item).unwrap_or(TextRange::empty(pkg_span.end));
|
||||
self.use_name(scope, item, item_span, Target::PackageMember(package.to_string()));
|
||||
Some(item.to_string())
|
||||
};
|
||||
self.use_name(scope, package, pkg_span, Target::Package);
|
||||
self.scopes[scope.0 as usize].imports.push(Import {
|
||||
package: package.to_string(),
|
||||
item,
|
||||
scope: None,
|
||||
name_span: pkg_span,
|
||||
});
|
||||
}
|
||||
|
||||
fn bind_typedef(&mut self, t: &Typedef, span: TextRange, scope: ScopeId) {
|
||||
// The typedef's own name is written last (`typedef enum {...} name;`),
|
||||
// so it is the last identifier of the construct, not the first.
|
||||
let ns = self.typedef_name_span(t, span);
|
||||
match &t.kind {
|
||||
TypedefKind::Alias(ty) => {
|
||||
self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope);
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
}
|
||||
TypedefKind::Enum(e) => {
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
if let Some(base) = &e.base {
|
||||
self.bind_data_type(base, TextRange::new(span.start, ns.start), scope);
|
||||
}
|
||||
// LRM: enum names belong to the scope holding the enum.
|
||||
for m in &e.members {
|
||||
let mns = name_span(self.src, m.span, &m.name);
|
||||
self.declare(scope, &m.name, SymbolKind::EnumVariant, mns, m.span);
|
||||
self.bind_opt_expr(m.value.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
TypedefKind::Struct(s) => {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&t.name,
|
||||
SymbolKind::Typedef,
|
||||
ns,
|
||||
span,
|
||||
ScopeKind::Struct,
|
||||
);
|
||||
for m in &s.members {
|
||||
let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end);
|
||||
self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope);
|
||||
for d in &m.declarators {
|
||||
let dns = name_span(self.src, d.span, &d.name);
|
||||
self.declare(inner, &d.name, SymbolKind::StructMember, dns, d.span);
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_dims(&t.unpacked, scope);
|
||||
}
|
||||
|
||||
/// The name of a `typedef` is the last identifier before its `;`.
|
||||
fn typedef_name_span(&self, t: &Typedef, span: TextRange) -> TextRange {
|
||||
let mut scanner = NameScanner::new(self.src, span);
|
||||
let mut last = TextRange::empty(span.start);
|
||||
while let Some(found) = scanner.find(&t.name) {
|
||||
last = found;
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) {
|
||||
let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var };
|
||||
self.bind_opt_expr(d.delay.as_ref(), scope);
|
||||
self.bind_declarators(&d.declarators, kind, &d.ty, span, scope);
|
||||
}
|
||||
|
||||
fn bind_port_decl(&mut self, p: &PortDecl, span: TextRange, scope: ScopeId) {
|
||||
let kind = match self.scopes[scope.0 as usize].kind {
|
||||
ScopeKind::Function | ScopeKind::Task => SymbolKind::TfArg,
|
||||
_ => SymbolKind::Port,
|
||||
};
|
||||
self.bind_declarators(&p.declarators, kind, &p.ty, span, scope);
|
||||
}
|
||||
|
||||
fn bind_declarators(
|
||||
&mut self,
|
||||
declarators: &[Declarator],
|
||||
kind: SymbolKind,
|
||||
ty: &DataType,
|
||||
span: TextRange,
|
||||
scope: ScopeId,
|
||||
) {
|
||||
let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end);
|
||||
self.bind_data_type(ty, TextRange::new(span.start, first), scope);
|
||||
for d in declarators {
|
||||
let ns = name_span(self.src, d.span, &d.name);
|
||||
self.declare(scope, &d.name, kind, ns, d.span);
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_instantiation(&mut self, i: &Instantiation, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_span(self.src, span, &i.module);
|
||||
self.use_name(scope, &i.module, ns, Target::Module);
|
||||
for c in i.params.iter().flatten() {
|
||||
self.bind_connection(c, &i.module, scope);
|
||||
}
|
||||
for inst in &i.instances {
|
||||
let ins = name_span(self.src, inst.span, &inst.name);
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, ins, inst.span);
|
||||
self.bind_dims(&inst.dims, scope);
|
||||
match &inst.conns {
|
||||
Connections::Named(conns) => {
|
||||
for c in conns {
|
||||
self.bind_connection(c, &i.module, scope);
|
||||
}
|
||||
}
|
||||
Connections::Ordered(conns) => {
|
||||
for c in conns {
|
||||
self.bind_opt_expr(c.expr.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_connection(&mut self, c: &Connection, module: &str, scope: ScopeId) {
|
||||
if c.name != "*" {
|
||||
let ns = name_span(self.src, c.span, &c.name);
|
||||
self.use_name(scope, &c.name, ns, Target::Port(module.to_string()));
|
||||
}
|
||||
self.bind_opt_expr(c.expr.as_ref(), scope);
|
||||
}
|
||||
|
||||
fn bind_gen_if(&mut self, g: &GenIf, scope: ScopeId) {
|
||||
self.bind_expr(&g.cond, scope);
|
||||
self.bind_gen_block(&g.then, scope);
|
||||
match g.els.as_deref() {
|
||||
Some(GenElse::If(_, inner)) => self.bind_gen_if(inner, scope),
|
||||
Some(GenElse::Block(b)) => self.bind_gen_block(b, scope),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_gen_for(&mut self, g: &GenFor, span: TextRange, scope: ScopeId) {
|
||||
// The loop header opens a scope of its own so that `for (genvar i...)`
|
||||
// does not leak `i` into the enclosing module.
|
||||
let header = self.new_scope(ScopeKind::Generate, scope, span);
|
||||
match (g.init_genvar, &g.init.lhs.kind) {
|
||||
// `for (genvar i = 0; ...)` declares; `for (i = 0; ...)` uses a
|
||||
// `genvar i;` written outside the loop.
|
||||
(true, ExprKind::Ident(name)) => {
|
||||
self.declare(header, name, SymbolKind::Genvar, g.init.lhs.span, g.init.lhs.span);
|
||||
}
|
||||
_ => self.bind_expr(&g.init.lhs, header),
|
||||
}
|
||||
self.bind_expr(&g.init.rhs, header);
|
||||
self.bind_expr(&g.cond, header);
|
||||
match &g.step {
|
||||
ForStep::Assign(a) => {
|
||||
self.bind_expr(&a.lhs, header);
|
||||
self.bind_expr(&a.rhs, header);
|
||||
}
|
||||
ForStep::Expr(e) => self.bind_expr(e, header),
|
||||
}
|
||||
self.bind_gen_block(&g.body, header);
|
||||
}
|
||||
|
||||
fn bind_gen_block(&mut self, b: &GenBlock, scope: ScopeId) {
|
||||
let inner = match &b.label {
|
||||
Some(label) => {
|
||||
let ns = name_span(self.src, b.span, label);
|
||||
self.declare_with_scope(
|
||||
scope,
|
||||
label,
|
||||
SymbolKind::Block,
|
||||
ns,
|
||||
b.span,
|
||||
ScopeKind::Generate,
|
||||
)
|
||||
}
|
||||
None => self.new_scope(ScopeKind::Generate, scope, b.span),
|
||||
};
|
||||
self.bind_items(&b.items, inner);
|
||||
}
|
||||
|
||||
fn bind_function(&mut self, f: &FunctionDecl, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_after_kw(self.src, span, "function", &f.name);
|
||||
if let Some(ret) = &f.ret {
|
||||
self.bind_data_type(ret, TextRange::new(span.start, ns.start), scope);
|
||||
}
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&f.name,
|
||||
SymbolKind::Function,
|
||||
ns,
|
||||
span,
|
||||
ScopeKind::Function,
|
||||
);
|
||||
self.bind_tf_args(&f.args, inner);
|
||||
self.bind_stmts(&f.stmts, inner);
|
||||
}
|
||||
|
||||
fn bind_task(&mut self, t: &TaskDecl, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_after_kw(self.src, span, "task", &t.name);
|
||||
let inner =
|
||||
self.declare_with_scope(scope, &t.name, SymbolKind::Task, ns, span, ScopeKind::Task);
|
||||
self.bind_tf_args(&t.args, inner);
|
||||
self.bind_stmts(&t.stmts, inner);
|
||||
}
|
||||
|
||||
fn bind_tf_args(&mut self, args: &[TfArg], scope: ScopeId) {
|
||||
for a in args {
|
||||
let name = self.decl_name(a.span, &a.ty, &a.unpacked, a.default.as_ref(), &a.name);
|
||||
self.bind_data_type(&a.ty, TextRange::new(a.span.start, name.start), scope);
|
||||
self.declare(scope, &a.name, SymbolKind::TfArg, name, a.span);
|
||||
self.bind_dims(&a.unpacked, scope);
|
||||
self.bind_opt_expr(a.default.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Statements
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn bind_stmts(&mut self, stmts: &[Stmt], scope: ScopeId) {
|
||||
for s in stmts {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_stmt(&mut self, stmt: &Stmt, scope: ScopeId) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { label, stmts, .. } | StmtKind::ForkJoin { label, stmts, .. } => {
|
||||
let inner = match label {
|
||||
Some(label) => {
|
||||
let ns = name_span(self.src, stmt.span, label);
|
||||
self.declare_with_scope(
|
||||
scope,
|
||||
label,
|
||||
SymbolKind::Block,
|
||||
ns,
|
||||
stmt.span,
|
||||
ScopeKind::Block,
|
||||
)
|
||||
}
|
||||
None => self.new_scope(ScopeKind::Block, scope, stmt.span),
|
||||
};
|
||||
self.bind_stmts(stmts, inner);
|
||||
}
|
||||
StmtKind::If { cond, then, els, .. } => {
|
||||
self.bind_expr(cond, scope);
|
||||
self.bind_stmt(then, scope);
|
||||
if let Some(e) = els {
|
||||
self.bind_stmt(e, scope);
|
||||
}
|
||||
}
|
||||
StmtKind::Case { expr, items, .. } => {
|
||||
self.bind_expr(expr, scope);
|
||||
for it in items {
|
||||
for l in &it.labels {
|
||||
self.bind_expr(&l.expr, scope);
|
||||
}
|
||||
self.bind_stmt(&it.stmt, scope);
|
||||
}
|
||||
}
|
||||
StmtKind::For { init, cond, step, body } => {
|
||||
let inner = self.new_scope(ScopeKind::Block, scope, stmt.span);
|
||||
for i in init {
|
||||
match &i.ty {
|
||||
Some(ty) => {
|
||||
if let ExprKind::Ident(name) = &i.assign.lhs.kind {
|
||||
self.bind_data_type(
|
||||
ty,
|
||||
TextRange::new(stmt.span.start, i.assign.lhs.span.start),
|
||||
scope,
|
||||
);
|
||||
self.declare(
|
||||
inner,
|
||||
name,
|
||||
SymbolKind::Var,
|
||||
i.assign.lhs.span,
|
||||
i.assign.lhs.span,
|
||||
);
|
||||
}
|
||||
}
|
||||
None => self.bind_expr(&i.assign.lhs, inner),
|
||||
}
|
||||
self.bind_expr(&i.assign.rhs, inner);
|
||||
}
|
||||
self.bind_opt_expr(cond.as_ref(), inner);
|
||||
for s in step {
|
||||
match s {
|
||||
ForStep::Assign(a) => {
|
||||
self.bind_expr(&a.lhs, inner);
|
||||
self.bind_expr(&a.rhs, inner);
|
||||
}
|
||||
ForStep::Expr(e) => self.bind_expr(e, inner),
|
||||
}
|
||||
}
|
||||
self.bind_stmt(body, inner);
|
||||
}
|
||||
StmtKind::While { cond, body } | StmtKind::DoWhile { body, cond } => {
|
||||
self.bind_expr(cond, scope);
|
||||
self.bind_stmt(body, scope);
|
||||
}
|
||||
StmtKind::Repeat { count, body } => {
|
||||
self.bind_expr(count, scope);
|
||||
self.bind_stmt(body, scope);
|
||||
}
|
||||
StmtKind::Forever { body } => self.bind_stmt(body, scope),
|
||||
StmtKind::Foreach { target, vars, body } => {
|
||||
let inner = self.new_scope(ScopeKind::Block, scope, stmt.span);
|
||||
self.bind_expr(target, scope);
|
||||
let mut scanner =
|
||||
NameScanner::new(self.src, TextRange::new(target.span.end, stmt.span.end));
|
||||
for v in vars {
|
||||
let ns = scanner.find(v).unwrap_or(TextRange::empty(target.span.end));
|
||||
self.declare(inner, v, SymbolKind::Var, ns, ns);
|
||||
}
|
||||
self.bind_stmt(body, inner);
|
||||
}
|
||||
StmtKind::Assign { lhs, timing, rhs, .. } => {
|
||||
self.bind_expr(lhs, scope);
|
||||
if let Some(t) = timing {
|
||||
self.bind_timing(t, scope);
|
||||
}
|
||||
self.bind_expr(rhs, scope);
|
||||
}
|
||||
StmtKind::ForceRelease { lhs, rhs, .. } => {
|
||||
self.bind_expr(lhs, scope);
|
||||
self.bind_opt_expr(rhs.as_ref(), scope);
|
||||
}
|
||||
StmtKind::Timing { control, stmt } => {
|
||||
self.bind_timing(control, scope);
|
||||
if let Some(s) = stmt {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
}
|
||||
StmtKind::Wait { cond, stmt } => {
|
||||
self.bind_expr(cond, scope);
|
||||
if let Some(s) = stmt {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
}
|
||||
StmtKind::ExprStmt(e) | StmtKind::EventTrigger(e) => self.bind_expr(e, scope),
|
||||
StmtKind::VarDecl(d) => self.bind_data_decl(d, stmt.span, scope),
|
||||
StmtKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, stmt.span, scope)
|
||||
}
|
||||
StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope),
|
||||
StmtKind::Return(e) => self.bind_opt_expr(e.as_ref(), scope),
|
||||
StmtKind::Disable(name) => {
|
||||
let ns = name_after_kw(self.src, stmt.span, "disable", name);
|
||||
self.use_name(scope, name, ns, Target::Lexical);
|
||||
}
|
||||
StmtKind::Assert { cond, then, els, .. } => {
|
||||
self.bind_expr(cond, scope);
|
||||
if let Some(s) = then {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
if let Some(s) = els {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
}
|
||||
StmtKind::Break
|
||||
| StmtKind::Continue
|
||||
| StmtKind::Directive(_)
|
||||
| StmtKind::MacroStmt(_)
|
||||
| StmtKind::Null
|
||||
| StmtKind::Error(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_timing(&mut self, t: &TimingControl, scope: ScopeId) {
|
||||
match t {
|
||||
TimingControl::Delay(e) => self.bind_expr(e, scope),
|
||||
TimingControl::Event(SensList::List(items)) => {
|
||||
for i in items {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
TimingControl::Event(SensList::Star { .. }) => {}
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Expressions
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn bind_opt_expr(&mut self, e: Option<&Expr>, scope: ScopeId) {
|
||||
if let Some(e) = e {
|
||||
self.bind_expr(e, scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_dims(&mut self, dims: &[Dim], scope: ScopeId) {
|
||||
for d in dims {
|
||||
self.bind_expr(&d.a, scope);
|
||||
self.bind_opt_expr(d.b.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_expr(&mut self, e: &Expr, scope: ScopeId) {
|
||||
match &e.kind {
|
||||
ExprKind::Ident(name) => self.use_name(scope, name, e.span, Target::Lexical),
|
||||
ExprKind::Number(_) | ExprKind::Str(_) | ExprKind::Empty(_) => {}
|
||||
ExprKind::Unary { expr, .. } | ExprKind::Postfix { expr, .. } => {
|
||||
self.bind_expr(expr, scope)
|
||||
}
|
||||
ExprKind::Binary { lhs, rhs, .. } => {
|
||||
self.bind_expr(lhs, scope);
|
||||
self.bind_expr(rhs, scope);
|
||||
}
|
||||
ExprKind::Ternary { cond, then, els, .. } => {
|
||||
self.bind_expr(cond, scope);
|
||||
self.bind_expr(then, scope);
|
||||
self.bind_expr(els, scope);
|
||||
}
|
||||
ExprKind::Call { callee, args } => {
|
||||
self.bind_expr(callee, scope);
|
||||
for a in args {
|
||||
self.bind_expr(&a.expr, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::Index { base, index } => {
|
||||
self.bind_expr(base, scope);
|
||||
self.bind_expr(index, scope);
|
||||
}
|
||||
ExprKind::Range { base, msb, lsb, .. } => {
|
||||
self.bind_expr(base, scope);
|
||||
self.bind_expr(msb, scope);
|
||||
self.bind_expr(lsb, scope);
|
||||
}
|
||||
// `a.b`: only the head is resolved — see the README.
|
||||
ExprKind::Member { base, .. } => self.bind_expr(base, scope),
|
||||
ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope),
|
||||
ExprKind::Concat(items) => {
|
||||
for i in items {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::Inside { lhs, ranges } => {
|
||||
self.bind_expr(lhs, scope);
|
||||
for i in ranges {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::Repl { count, inner } => {
|
||||
self.bind_expr(count, scope);
|
||||
for i in inner {
|
||||
self.bind_expr(&i.expr, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::Paren { inner, .. } => self.bind_expr(inner, scope),
|
||||
// The cast type is raw text with no span of its own.
|
||||
ExprKind::Cast { expr, .. } => self.bind_expr(expr, scope),
|
||||
ExprKind::AssignPattern(items) => {
|
||||
for i in items {
|
||||
self.bind_opt_expr(i.key.as_ref(), scope);
|
||||
self.bind_expr(&i.value, scope);
|
||||
}
|
||||
}
|
||||
ExprKind::ValueRange { lo, hi } => {
|
||||
self.bind_expr(lo, scope);
|
||||
self.bind_expr(hi, scope);
|
||||
}
|
||||
ExprKind::Type(ty) => self.bind_data_type(ty, e.span, scope),
|
||||
ExprKind::MinTypMax { min, typ, max } => {
|
||||
self.bind_expr(min, scope);
|
||||
self.bind_expr(typ, scope);
|
||||
self.bind_expr(max, scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `p::x`: the head names a package, the tail is looked up inside it.
|
||||
fn bind_scoped(&mut self, base: &Expr, name: &str, span: TextRange, scope: ScopeId) {
|
||||
let tail = TextRange::new(span.end.saturating_sub(name.len() as u32), span.end);
|
||||
match &base.kind {
|
||||
ExprKind::Ident(pkg) => {
|
||||
self.use_name(scope, pkg, base.span, Target::Package);
|
||||
self.use_name(scope, name, tail, Target::PackageMember(pkg.clone()));
|
||||
}
|
||||
_ => self.bind_expr(base, scope),
|
||||
}
|
||||
}
|
||||
|
||||
/// A user-defined type name is a use like any other. `window` is the
|
||||
/// source range the name was written in — everything before the declared
|
||||
/// name, which is where a data type always sits.
|
||||
fn bind_data_type(&mut self, ty: &DataType, window: TextRange, scope: ScopeId) {
|
||||
if !ty.name.is_empty() && !is_keyword(&ty.name) {
|
||||
match ty.name.split_once("::") {
|
||||
Some((pkg, item)) => {
|
||||
let mut scanner = NameScanner::new(self.src, window);
|
||||
let pkg_span = scanner.find(pkg).unwrap_or(TextRange::empty(window.start));
|
||||
let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start));
|
||||
self.use_name(scope, pkg, pkg_span, Target::Package);
|
||||
self.use_name(scope, item, item_span, Target::PackageMember(pkg.to_string()));
|
||||
}
|
||||
None => {
|
||||
let ns = name_span(self.src, window, &ty.name);
|
||||
self.use_name(scope, &ty.name, ns, Target::Lexical);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_dims(&ty.packed, scope);
|
||||
}
|
||||
|
||||
/// The range of a declared name that sits between its type and its
|
||||
/// dimensions/default (a port, a parameter port, a task/function argument).
|
||||
fn decl_name(
|
||||
&self,
|
||||
span: TextRange,
|
||||
ty: &DataType,
|
||||
unpacked: &[Dim],
|
||||
default: Option<&Expr>,
|
||||
name: &str,
|
||||
) -> TextRange {
|
||||
let start = ty.packed.last().map(|d| d.span.end).unwrap_or(span.start);
|
||||
let end = unpacked
|
||||
.first()
|
||||
.map(|d| d.span.start)
|
||||
.or_else(|| default.map(|e| e.span.start))
|
||||
.unwrap_or(span.end);
|
||||
name_span(self.src, TextRange::new(start, end), name)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Single-file symbol tables and reference resolution for Verilog/
|
||||
//! SystemVerilog.
|
||||
//!
|
||||
//! This crate plays the role of `ruff_python_semantic` in ruff's architecture:
|
||||
//! it takes the AST `vlog_parser` produced for **one** file and answers the
|
||||
//! questions a language server asks — what is declared here, what does this
|
||||
//! identifier name, where else is it used, what is the outline of this file.
|
||||
//! It resolves nothing across files; a name that only another file can supply
|
||||
//! is reported as [`Resolution::ExternalCandidate`] for the workspace index
|
||||
//! (TODO.md §6) to finish.
|
||||
//!
|
||||
//! [`analyze`] never fails and never panics: an error-tolerant parse's
|
||||
//! `Error` nodes are opaque leaves, exactly like macro invocations.
|
||||
//! See `docs/features/vlog-semantic/README.md` for the resolution rules and
|
||||
//! the simplifications taken.
|
||||
|
||||
mod bind;
|
||||
mod model;
|
||||
mod resolve;
|
||||
mod scan;
|
||||
|
||||
pub use model::{
|
||||
DocumentSymbol, Import, Reference, Resolution, Scope, ScopeId, ScopeKind, Symbol, SymbolId,
|
||||
SymbolKind,
|
||||
};
|
||||
|
||||
use std::collections::HashMap;
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// Everything known about one file: its scopes, its declarations and its uses.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Semantics {
|
||||
scopes: Vec<Scope>,
|
||||
symbols: Vec<Symbol>,
|
||||
references: Vec<Reference>,
|
||||
/// symbol → indices into `references`, in source order.
|
||||
uses: HashMap<SymbolId, Vec<usize>>,
|
||||
}
|
||||
|
||||
/// Build the symbol table for one parsed file. `src` must be the text the
|
||||
/// file was parsed from — spans index into it.
|
||||
pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
let mut binder = bind::Binder::new(src, file.span);
|
||||
let file_scope = binder.file_scope();
|
||||
binder.bind_items(&file.items, file_scope);
|
||||
|
||||
let bind::Binder { mut scopes, symbols, pending, .. } = binder;
|
||||
link_imports(&mut scopes, &symbols);
|
||||
|
||||
let mut references = Vec::with_capacity(pending.len());
|
||||
for p in &pending {
|
||||
references.push(Reference {
|
||||
name: p.name.clone(),
|
||||
name_span: p.name_span,
|
||||
scope: p.scope,
|
||||
resolution: resolve::resolve(&scopes, &symbols, p),
|
||||
});
|
||||
}
|
||||
|
||||
let mut uses: HashMap<SymbolId, Vec<usize>> = HashMap::new();
|
||||
for (i, r) in references.iter().enumerate() {
|
||||
if let Some(id) = r.resolved() {
|
||||
uses.entry(id).or_default().push(i);
|
||||
}
|
||||
}
|
||||
Semantics { scopes, symbols, references, uses }
|
||||
}
|
||||
|
||||
/// Point every import at the package it names, when this file declares it.
|
||||
fn link_imports(scopes: &mut [Scope], symbols: &[Symbol]) {
|
||||
let packages: HashMap<&str, ScopeId> = symbols
|
||||
.iter()
|
||||
.filter(|s| s.kind == SymbolKind::Package)
|
||||
.filter_map(|s| s.child_scope.map(|c| (s.name.as_str(), c)))
|
||||
.collect();
|
||||
for scope in scopes.iter_mut() {
|
||||
for import in &mut scope.imports {
|
||||
import.scope = packages.get(import.package.as_str()).copied();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Semantics {
|
||||
/// Every scope; index 0 is always the file scope.
|
||||
pub fn scopes(&self) -> &[Scope] {
|
||||
&self.scopes
|
||||
}
|
||||
|
||||
/// Every declaration, in the order they were bound.
|
||||
pub fn symbols(&self) -> &[Symbol] {
|
||||
&self.symbols
|
||||
}
|
||||
|
||||
/// Every use, in source order.
|
||||
pub fn references(&self) -> &[Reference] {
|
||||
&self.references
|
||||
}
|
||||
|
||||
/// The file scope.
|
||||
pub fn file_scope(&self) -> ScopeId {
|
||||
ScopeId(0)
|
||||
}
|
||||
|
||||
/// One scope by id.
|
||||
pub fn scope(&self, id: ScopeId) -> Option<&Scope> {
|
||||
self.scopes.get(id.0 as usize)
|
||||
}
|
||||
|
||||
/// One symbol by id.
|
||||
pub fn symbol(&self, id: SymbolId) -> Option<&Symbol> {
|
||||
self.symbols.get(id.0 as usize)
|
||||
}
|
||||
|
||||
/// The declaration whose *name* covers `offset` — a cursor sitting on a
|
||||
/// declared name, not anywhere in its declaration.
|
||||
pub fn symbol_at(&self, offset: u32) -> Option<SymbolId> {
|
||||
self.symbols.iter().position(|s| s.name_span.contains(offset)).map(|i| SymbolId(i as u32))
|
||||
}
|
||||
|
||||
/// The use whose name covers `offset`.
|
||||
pub fn reference_at(&self, offset: u32) -> Option<&Reference> {
|
||||
self.references.iter().find(|r| r.name_span.contains(offset))
|
||||
}
|
||||
|
||||
/// Go-to-definition: the declaration named at `offset`, whether the
|
||||
/// cursor sits on a use or on the declaration itself.
|
||||
pub fn definition_of(&self, offset: u32) -> Option<&Symbol> {
|
||||
if let Some(r) = self.reference_at(offset) {
|
||||
if let Some(id) = r.resolved() {
|
||||
return self.symbol(id);
|
||||
}
|
||||
}
|
||||
self.symbol_at(offset).and_then(|id| self.symbol(id))
|
||||
}
|
||||
|
||||
/// Find-all-references: every *use* of a symbol, in source order. The
|
||||
/// declaration itself is not one of them — it is `symbol.name_span`, and
|
||||
/// an LSP that wants `includeDeclaration` adds it.
|
||||
pub fn references_of(&self, id: SymbolId) -> Vec<&Reference> {
|
||||
match self.uses.get(&id) {
|
||||
Some(indices) => indices.iter().filter_map(|&i| self.references.get(i)).collect(),
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The outline of the file: file-scope declarations, each with the
|
||||
/// declarations it contains, in source order. Scopes no declaration owns
|
||||
/// (an unnamed `begin`) contribute their symbols to the enclosing level.
|
||||
pub fn document_symbols(&self) -> Vec<DocumentSymbol> {
|
||||
self.outline_of(ScopeId(0))
|
||||
}
|
||||
|
||||
fn outline_of(&self, scope: ScopeId) -> Vec<DocumentSymbol> {
|
||||
let Some(s) = self.scopes.get(scope.0 as usize) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut out: Vec<DocumentSymbol> = s
|
||||
.symbols
|
||||
.iter()
|
||||
.map(|&id| {
|
||||
let children = match self.symbol(id).and_then(|sym| sym.child_scope) {
|
||||
Some(child) => self.outline_of(child),
|
||||
None => Vec::new(),
|
||||
};
|
||||
DocumentSymbol { symbol: id, children }
|
||||
})
|
||||
.collect();
|
||||
for &child in &s.children {
|
||||
let owned = self.scopes.get(child.0 as usize).is_some_and(|c| c.owner.is_some());
|
||||
if !owned {
|
||||
out.extend(self.outline_of(child));
|
||||
}
|
||||
}
|
||||
out.sort_by_key(|d| self.symbol(d.symbol).map_or(0, |s| s.name_span.start));
|
||||
out
|
||||
}
|
||||
|
||||
/// How many uses resolved to a declaration in this file, out of how many
|
||||
/// were recorded. The corpus test reports the ratio as an honest baseline.
|
||||
pub fn resolution_counts(&self) -> (usize, usize) {
|
||||
(self.references.iter().filter(|r| r.resolved().is_some()).count(), self.references.len())
|
||||
}
|
||||
|
||||
/// The span the file covers, as the parser saw it.
|
||||
pub fn file_span(&self) -> TextRange {
|
||||
self.scopes.first().map_or(TextRange::empty(0), |s| s.span)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//! The tables `analyze` fills in: scopes, symbols and references.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// Index of a [`Scope`] in [`Semantics::scopes`](crate::Semantics::scopes).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct ScopeId(pub u32);
|
||||
|
||||
/// Index of a [`Symbol`] in [`Semantics::symbols`](crate::Semantics::symbols).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct SymbolId(pub u32);
|
||||
|
||||
/// What kind of declaration a [`Symbol`] came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SymbolKind {
|
||||
Module,
|
||||
Package,
|
||||
/// A module port, from either header style.
|
||||
Port,
|
||||
/// A net declaration (`wire`, `tri`, ...).
|
||||
Net,
|
||||
/// A variable declaration (`logic`, `reg`, `int`, ...).
|
||||
Var,
|
||||
Param,
|
||||
Genvar,
|
||||
Typedef,
|
||||
/// A name introduced by an `enum` body, visible in the enclosing scope.
|
||||
EnumVariant,
|
||||
Function,
|
||||
Task,
|
||||
/// A function or task argument.
|
||||
TfArg,
|
||||
/// A module or gate instance.
|
||||
Instance,
|
||||
/// A named `begin`/`fork`/generate block.
|
||||
Block,
|
||||
/// A member of a `struct`/`union` body.
|
||||
StructMember,
|
||||
}
|
||||
|
||||
/// A declaration: a name bound in one scope.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Symbol {
|
||||
pub name: String,
|
||||
pub kind: SymbolKind,
|
||||
/// Byte range of the declared name itself — what an editor highlights.
|
||||
pub name_span: TextRange,
|
||||
/// Byte range of the construct that owns the name (the whole `module`,
|
||||
/// the whole declarator, the whole port declaration).
|
||||
pub decl_span: TextRange,
|
||||
/// The scope the name is bound in.
|
||||
pub scope: ScopeId,
|
||||
/// The scope this declaration opens, for the kinds that open one
|
||||
/// (module, package, function, task, named block, struct body).
|
||||
pub child_scope: Option<ScopeId>,
|
||||
}
|
||||
|
||||
/// What a [`Reference`] turned out to name.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Resolution {
|
||||
/// Bound to a declaration in this file.
|
||||
Resolved(SymbolId),
|
||||
/// Nothing in this file binds it, but a named external unit could: a
|
||||
/// package imported with `import p::*` / `import p::x`, a package written
|
||||
/// as `p::x`, or a module instantiated but declared in another file.
|
||||
/// `paths` names those units — a path containing `::` is a package path,
|
||||
/// a bare name is a module or package name. The workspace index
|
||||
/// (TODO.md §6) is what finishes these.
|
||||
ExternalCandidate { paths: Vec<String> },
|
||||
/// Nothing in this file binds it and no external unit could.
|
||||
NotFound,
|
||||
}
|
||||
|
||||
/// A *use* of a name: an expression identifier, a type name, an instantiated
|
||||
/// module's name, a `.port` in a connection list, a package in an `import`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Reference {
|
||||
pub name: String,
|
||||
/// Byte range of the identifier as written.
|
||||
pub name_span: TextRange,
|
||||
/// The scope the use is written in.
|
||||
pub scope: ScopeId,
|
||||
pub resolution: Resolution,
|
||||
}
|
||||
|
||||
impl Reference {
|
||||
/// The symbol this use names, if it is declared in this file.
|
||||
pub fn resolved(&self) -> Option<SymbolId> {
|
||||
match self.resolution {
|
||||
Resolution::Resolved(id) => Some(id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// True when only a workspace-wide index can finish this reference.
|
||||
pub fn is_external_candidate(&self) -> bool {
|
||||
matches!(self.resolution, Resolution::ExternalCandidate { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// What construct a [`Scope`] came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ScopeKind {
|
||||
File,
|
||||
Module,
|
||||
Package,
|
||||
Function,
|
||||
Task,
|
||||
/// A `begin`/`end`, `fork`/`join`, `for` or `foreach` body.
|
||||
Block,
|
||||
/// A generate region, a generate block, or a `for` generate's header.
|
||||
Generate,
|
||||
/// A `struct`/`union` body. Never searched by name lookup — members are
|
||||
/// reached through `x.field`, which this crate does not resolve.
|
||||
Struct,
|
||||
}
|
||||
|
||||
/// One `import p::x;` / `import p::*;` recorded in the scope that wrote it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Import {
|
||||
/// The package name written before `::`.
|
||||
pub package: String,
|
||||
/// The imported name; `None` for a `::*` wildcard.
|
||||
pub item: Option<String>,
|
||||
/// The package's scope when the package is declared in this file.
|
||||
pub scope: Option<ScopeId>,
|
||||
/// Byte range of the package name as written.
|
||||
pub name_span: TextRange,
|
||||
}
|
||||
|
||||
impl Import {
|
||||
/// The import path as written, e.g. `pkg::*`.
|
||||
pub fn path(&self) -> String {
|
||||
match &self.item {
|
||||
Some(item) => format!("{}::{}", self.package, item),
|
||||
None => format!("{}::*", self.package),
|
||||
}
|
||||
}
|
||||
|
||||
/// True when this import could supply `name`.
|
||||
pub fn supplies(&self, name: &str) -> bool {
|
||||
match &self.item {
|
||||
Some(item) => item == name,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A lexical scope: a set of names plus a link to the scope enclosing it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Scope {
|
||||
pub kind: ScopeKind,
|
||||
pub parent: Option<ScopeId>,
|
||||
/// The symbol whose declaration opened this scope; `None` for the file
|
||||
/// scope and for unnamed blocks.
|
||||
pub owner: Option<SymbolId>,
|
||||
/// Byte range of the construct the scope covers.
|
||||
pub span: TextRange,
|
||||
/// Symbols bound here, in declaration order.
|
||||
pub symbols: Vec<SymbolId>,
|
||||
pub children: Vec<ScopeId>,
|
||||
pub imports: Vec<Import>,
|
||||
/// Name → symbol, first declaration wins (see the README's shadowing
|
||||
/// rules). Kept separate from `symbols` so a redeclaration is still
|
||||
/// visible in the outline.
|
||||
pub(crate) names: HashMap<String, SymbolId>,
|
||||
}
|
||||
|
||||
impl Scope {
|
||||
/// The symbol this scope binds `name` to, ignoring enclosing scopes.
|
||||
pub fn lookup_local(&self, name: &str) -> Option<SymbolId> {
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// One node of the outline tree returned by
|
||||
/// [`Semantics::document_symbols`](crate::Semantics::document_symbols).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DocumentSymbol {
|
||||
pub symbol: SymbolId,
|
||||
pub children: Vec<DocumentSymbol>,
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Pass two: turn every pending use into a [`Resolution`].
|
||||
//!
|
||||
//! Everything is bound before anything is resolved, so a name used before it
|
||||
//! is declared resolves exactly like one used after — which is what Verilog
|
||||
//! requires at module scope and what an editor needs mid-edit.
|
||||
|
||||
use crate::bind::{Pending, Target};
|
||||
use crate::model::{Resolution, Scope, ScopeId, SymbolId, SymbolKind};
|
||||
|
||||
/// Resolve one pending use against the finished scope tree.
|
||||
pub(crate) fn resolve(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
p: &Pending,
|
||||
) -> Resolution {
|
||||
match &p.target {
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Package),
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Module),
|
||||
Target::PackageMember(pkg) => {
|
||||
match owning_scope(scopes, symbols, pkg, SymbolKind::Package) {
|
||||
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::NotFound,
|
||||
},
|
||||
None => Resolution::ExternalCandidate { paths: vec![format!("{pkg}::{}", p.name)] },
|
||||
}
|
||||
}
|
||||
Target::Port(module) => match owning_scope(scopes, symbols, module, SymbolKind::Module) {
|
||||
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::NotFound,
|
||||
},
|
||||
// The port list lives in whatever file declares the module.
|
||||
None => Resolution::ExternalCandidate { paths: vec![module.clone()] },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the scope chain outward: names declared in a scope first, then the
|
||||
/// packages that scope imports, then the enclosing scope.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
let mut external = Vec::new();
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if let Some(sym) = scope.lookup_local(name) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
for import in &scope.imports {
|
||||
if !import.supplies(name) {
|
||||
continue;
|
||||
}
|
||||
match import.scope {
|
||||
Some(pkg) => {
|
||||
if let Some(sym) = scopes[pkg.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
}
|
||||
// A package this file does not declare: only the workspace
|
||||
// index can say whether it holds the name.
|
||||
None => {
|
||||
let path = import.path();
|
||||
if !external.contains(&path) {
|
||||
external.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
if external.is_empty() {
|
||||
Resolution::NotFound
|
||||
} else {
|
||||
Resolution::ExternalCandidate { paths: external }
|
||||
}
|
||||
}
|
||||
|
||||
fn named_at_file_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
) -> Resolution {
|
||||
match file_symbol(scopes, symbols, name, kind) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::ExternalCandidate { paths: vec![name.to_string()] },
|
||||
}
|
||||
}
|
||||
|
||||
fn owning_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
) -> Option<ScopeId> {
|
||||
let id = file_symbol(scopes, symbols, name, kind)?;
|
||||
symbols[id.0 as usize].child_scope
|
||||
}
|
||||
|
||||
/// Modules and packages are file-scope names, so one lookup finds them.
|
||||
fn file_symbol(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
) -> Option<SymbolId> {
|
||||
let id = scopes.first()?.lookup_local(name)?;
|
||||
if symbols.get(id.0 as usize)?.kind == kind {
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! Recovering the byte range of a name the AST kept only as a `String`.
|
||||
//!
|
||||
//! Most declarations in `vlog_parser`'s AST store their name as a plain
|
||||
//! `String` and give a span only for the whole construct (`module m ... `,
|
||||
//! `input logic [W-1:0] d`). A language server needs the range of the *name*,
|
||||
//! so this scans the construct's own source text for it. See the README's
|
||||
//! Handshakes section: once the parser carries `name_span` on those nodes,
|
||||
//! this module goes away.
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
/// A cursor over one source window that hands out the ranges of successive
|
||||
/// identifiers, skipping comments, strings and macro invocations.
|
||||
pub(crate) struct NameScanner<'a> {
|
||||
src: &'a [u8],
|
||||
pos: usize,
|
||||
end: usize,
|
||||
}
|
||||
|
||||
impl<'a> NameScanner<'a> {
|
||||
/// A scanner over `window` of `src`.
|
||||
pub(crate) fn new(src: &'a str, window: TextRange) -> Self {
|
||||
let end = (window.end as usize).min(src.len());
|
||||
let pos = (window.start as usize).min(end);
|
||||
NameScanner { src: src.as_bytes(), pos, end }
|
||||
}
|
||||
|
||||
/// The range of the next whole-word `name`, or `None` if the window holds
|
||||
/// no more. The cursor moves past what it returns, so repeated calls walk
|
||||
/// a list (`genvar i, j;`) left to right.
|
||||
pub(crate) fn find(&mut self, name: &str) -> Option<TextRange> {
|
||||
while let Some(word) = self.next_word() {
|
||||
if &self.src[word.as_range()] == name.as_bytes() {
|
||||
return Some(word);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The range of the next identifier of any spelling.
|
||||
fn next_word(&mut self) -> Option<TextRange> {
|
||||
while self.pos < self.end {
|
||||
let b = self.src[self.pos];
|
||||
match b {
|
||||
b'/' if self.peek(1) == Some(b'/') => self.skip_line(),
|
||||
b'/' if self.peek(1) == Some(b'*') => self.skip_block_comment(),
|
||||
b'"' => self.skip_string(),
|
||||
// A macro invocation is one opaque token: `` `WIDTH `` must
|
||||
// not answer a search for the identifier `WIDTH`.
|
||||
b'`' => {
|
||||
self.pos += 1;
|
||||
self.skip_word();
|
||||
}
|
||||
_ if is_ident_start(b) => {
|
||||
let start = self.pos;
|
||||
self.skip_word();
|
||||
return Some(TextRange::new(start as u32, self.pos as u32));
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn peek(&self, n: usize) -> Option<u8> {
|
||||
self.src.get(self.pos + n).copied()
|
||||
}
|
||||
|
||||
fn skip_word(&mut self) {
|
||||
// An escaped identifier (`\a+b `) runs to the next whitespace.
|
||||
if self.src.get(self.pos) == Some(&b'\\') {
|
||||
self.pos += 1;
|
||||
while self.pos < self.end && !self.src[self.pos].is_ascii_whitespace() {
|
||||
self.pos += 1;
|
||||
}
|
||||
return;
|
||||
}
|
||||
while self.pos < self.end && is_ident_continue(self.src[self.pos]) {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_line(&mut self) {
|
||||
while self.pos < self.end && self.src[self.pos] != b'\n' {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_block_comment(&mut self) {
|
||||
self.pos += 2;
|
||||
while self.pos < self.end {
|
||||
if self.src[self.pos] == b'*' && self.peek(1) == Some(b'/') {
|
||||
self.pos += 2;
|
||||
return;
|
||||
}
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn skip_string(&mut self) {
|
||||
self.pos += 1;
|
||||
while self.pos < self.end {
|
||||
match self.src[self.pos] {
|
||||
b'\\' => self.pos += 2,
|
||||
b'"' => {
|
||||
self.pos += 1;
|
||||
return;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_ident_start(b: u8) -> bool {
|
||||
b.is_ascii_alphabetic() || b == b'_' || b == b'$' || b == b'\\'
|
||||
}
|
||||
|
||||
fn is_ident_continue(b: u8) -> bool {
|
||||
b.is_ascii_alphanumeric() || b == b'_' || b == b'$'
|
||||
}
|
||||
|
||||
/// The range of `name` inside `window`, or an empty range at the window start
|
||||
/// when the scan comes up empty (a name the source spells differently — an
|
||||
/// escaped identifier, or text a macro produced).
|
||||
pub(crate) fn name_span(src: &str, window: TextRange, name: &str) -> TextRange {
|
||||
NameScanner::new(src, window).find(name).unwrap_or(TextRange::empty(window.start))
|
||||
}
|
||||
|
||||
/// The range of `name` written *after* the first `kw` in `window`. Used where
|
||||
/// the construct starts with a keyword and the name follows it, possibly
|
||||
/// past qualifiers (`function automatic int f`).
|
||||
pub(crate) fn name_after_kw(src: &str, window: TextRange, kw: &str, name: &str) -> TextRange {
|
||||
let mut scanner = NameScanner::new(src, window);
|
||||
if scanner.find(kw).is_none() {
|
||||
return TextRange::empty(window.start);
|
||||
}
|
||||
scanner.find(name).unwrap_or(TextRange::empty(window.start))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn whole(src: &str) -> TextRange {
|
||||
TextRange::new(0, src.len() as u32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_a_name_after_its_keyword() {
|
||||
let src = "module top (input a);";
|
||||
let span = name_after_kw(src, whole(src), "module", "top");
|
||||
assert_eq!(&src[span.as_range()], "top");
|
||||
assert_eq!(span.start, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_comments_and_strings() {
|
||||
let src = "/* d */ \"d\" // d\n d;";
|
||||
let span = name_span(src, whole(src), "d");
|
||||
assert_eq!(span.start, 18);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matches_whole_words_only() {
|
||||
let src = "input wire [W-1:0] w;";
|
||||
let span = name_span(src, whole(src), "w");
|
||||
assert_eq!(&src[span.as_range()], "w");
|
||||
assert_eq!(span.start, 19);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_invocation_is_one_opaque_token() {
|
||||
let src = "`WIDTH WIDTH";
|
||||
let span = name_span(src, whole(src), "WIDTH");
|
||||
assert_eq!(span.start, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_not_there_gives_an_empty_range() {
|
||||
let src = "module m;";
|
||||
let span = name_span(src, whole(src), "nope");
|
||||
assert!(span.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn successive_finds_walk_a_list() {
|
||||
let src = "genvar i, j;";
|
||||
let mut scanner = NameScanner::new(src, whole(src));
|
||||
assert_eq!(scanner.find("i").map(|s| s.start), Some(7));
|
||||
assert_eq!(scanner.find("j").map(|s| s.start), Some(10));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
//! Smoke test over the real-RTL corpus (`corpus/`, fetched by
|
||||
//! `tools/corpus_fetch.sh`): analyze every file, panic nowhere, check that
|
||||
//! every recorded span really covers the name it claims, and report an honest
|
||||
//! resolution rate. Skipped when the corpus is not checked out.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use vlog_parser::parse_source_tolerant;
|
||||
use vlog_semantic::{analyze, Semantics};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Totals {
|
||||
files: usize,
|
||||
symbols: usize,
|
||||
references: usize,
|
||||
resolved: usize,
|
||||
external: usize,
|
||||
/// Names the source scan could not place. Expected to stay at zero — a
|
||||
/// nonzero count means a construct whose name this crate cannot locate.
|
||||
unplaced: usize,
|
||||
}
|
||||
|
||||
impl Totals {
|
||||
fn add(&mut self, sem: &Semantics, src: &str, path: &Path) {
|
||||
self.files += 1;
|
||||
self.symbols += sem.symbols().len();
|
||||
for sym in sem.symbols() {
|
||||
self.unplaced +=
|
||||
usize::from(!covers(src, sym.name_span, &sym.name, path, "declaration"));
|
||||
}
|
||||
for r in sem.references() {
|
||||
self.unplaced += usize::from(!covers(src, r.name_span, &r.name, path, "use"));
|
||||
}
|
||||
let (resolved, total) = sem.resolution_counts();
|
||||
self.references += total;
|
||||
self.resolved += resolved;
|
||||
self.external += sem.references().iter().filter(|r| r.is_external_candidate()).count();
|
||||
}
|
||||
|
||||
fn unresolved(&self) -> usize {
|
||||
self.references - self.resolved - self.external
|
||||
}
|
||||
|
||||
fn report(&self, label: &str) {
|
||||
let pct = |n: usize| 100.0 * n as f64 / self.references.max(1) as f64;
|
||||
println!(
|
||||
"{label}: {} files, {} symbols, {} references — {:.1}% resolved in-file, \
|
||||
{:.1}% external candidates, {:.1}% unresolved, {} names unplaced",
|
||||
self.files,
|
||||
self.symbols,
|
||||
self.references,
|
||||
pct(self.resolved),
|
||||
pct(self.external),
|
||||
pct(self.unresolved()),
|
||||
self.unplaced,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `span` really is where `name` is written. An empty span is the
|
||||
/// scan's "not found" answer and is counted, not asserted away.
|
||||
fn covers(src: &str, span: vlog_parser::TextRange, name: &str, path: &Path, what: &str) -> bool {
|
||||
if span.is_empty() {
|
||||
return false;
|
||||
}
|
||||
assert_eq!(
|
||||
&src[span.as_range()],
|
||||
name,
|
||||
"{}: the {what} span of {name} covers other bytes",
|
||||
path.display()
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_corpus_file_analyzes_without_panicking() {
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !root.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut files = Vec::new();
|
||||
collect(&root, &mut files);
|
||||
files.sort();
|
||||
|
||||
let mut all = Totals::default();
|
||||
// The same numbers over the files that parse without a single error node,
|
||||
// which is the population the LSP's resolution quality is really about.
|
||||
let mut clean = Totals::default();
|
||||
for path in &files {
|
||||
let Ok(src) = fs::read_to_string(path) else {
|
||||
continue;
|
||||
};
|
||||
let (file, diags) = parse_source_tolerant(&src);
|
||||
let sem = analyze(&file, &src);
|
||||
all.add(&sem, &src, path);
|
||||
if diags.is_empty() {
|
||||
clean.add(&sem, &src, path);
|
||||
}
|
||||
}
|
||||
|
||||
all.report("corpus (every file)");
|
||||
clean.report("corpus (files that parse cleanly)");
|
||||
|
||||
assert!(all.files > 0, "corpus/ exists but holds no Verilog");
|
||||
assert_eq!(all.unplaced, 0, "every name must be locatable in the source");
|
||||
assert!(
|
||||
100 * clean.unresolved() < 3 * clean.references,
|
||||
"unresolved rate on cleanly-parsed files regressed: {} of {}",
|
||||
clean.unresolved(),
|
||||
clean.references
|
||||
);
|
||||
}
|
||||
|
||||
fn collect(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = fs::read_dir(dir) else {
|
||||
return;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
collect(&path, out);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh")) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,541 @@
|
||||
//! What `analyze` binds, what it resolves, and what it refuses to guess.
|
||||
|
||||
use vlog_parser::{parse_source, parse_source_tolerant};
|
||||
use vlog_semantic::{analyze, Resolution, Semantics, SymbolId, SymbolKind};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
/// Offset of the `n`th (0-based) occurrence of `needle`.
|
||||
fn nth(src: &str, needle: &str, n: usize) -> u32 {
|
||||
src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32
|
||||
}
|
||||
|
||||
fn symbol_named<'a>(s: &'a Semantics, name: &str) -> &'a vlog_semantic::Symbol {
|
||||
s.symbols().iter().find(|sym| sym.name == name).unwrap_or_else(|| panic!("no symbol {name}"))
|
||||
}
|
||||
|
||||
fn symbol_id(s: &Semantics, name: &str) -> SymbolId {
|
||||
let i = s.symbols().iter().position(|sym| sym.name == name).expect("symbol must exist");
|
||||
SymbolId(i as u32)
|
||||
}
|
||||
|
||||
fn kinds(s: &Semantics) -> Vec<(&str, SymbolKind)> {
|
||||
s.symbols().iter().map(|sym| (sym.name.as_str(), sym.kind)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_declaration_kind_is_bound() {
|
||||
let src = "\
|
||||
package pkg;
|
||||
typedef enum logic [1:0] { RED, GREEN } color_e;
|
||||
typedef struct packed { logic a; logic b; } pair_t;
|
||||
endpackage
|
||||
|
||||
module top #(parameter int W = 8) (input logic clk, output logic [W-1:0] q);
|
||||
wire net_w;
|
||||
logic var_l;
|
||||
localparam int LP = 3;
|
||||
genvar gi;
|
||||
typedef logic [1:0] two_t;
|
||||
function automatic int f(input int arg);
|
||||
return arg;
|
||||
endfunction
|
||||
task t(input int targ);
|
||||
endtask
|
||||
sub u_sub (.a(net_w));
|
||||
always_comb begin : blk
|
||||
var_l = net_w;
|
||||
end
|
||||
endmodule
|
||||
|
||||
module sub (input a);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let found = kinds(&s);
|
||||
let expect = [
|
||||
("pkg", SymbolKind::Package),
|
||||
("color_e", SymbolKind::Typedef),
|
||||
("RED", SymbolKind::EnumVariant),
|
||||
("GREEN", SymbolKind::EnumVariant),
|
||||
("pair_t", SymbolKind::Typedef),
|
||||
("a", SymbolKind::StructMember),
|
||||
("b", SymbolKind::StructMember),
|
||||
("top", SymbolKind::Module),
|
||||
("W", SymbolKind::Param),
|
||||
("clk", SymbolKind::Port),
|
||||
("q", SymbolKind::Port),
|
||||
("net_w", SymbolKind::Net),
|
||||
("var_l", SymbolKind::Var),
|
||||
("LP", SymbolKind::Param),
|
||||
("gi", SymbolKind::Genvar),
|
||||
("two_t", SymbolKind::Typedef),
|
||||
("f", SymbolKind::Function),
|
||||
("arg", SymbolKind::TfArg),
|
||||
("t", SymbolKind::Task),
|
||||
("targ", SymbolKind::TfArg),
|
||||
("u_sub", SymbolKind::Instance),
|
||||
("blk", SymbolKind::Block),
|
||||
("sub", SymbolKind::Module),
|
||||
];
|
||||
for (name, kind) in expect {
|
||||
assert!(found.contains(&(name, kind)), "missing {name} as {kind:?}; got {found:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_span_is_the_name_and_nothing_else() {
|
||||
let src =
|
||||
"module top #(parameter int W = 8) (input logic [W-1:0] d);\n wire [1:0] w;\nendmodule\n";
|
||||
let s = sem(src);
|
||||
for sym in s.symbols() {
|
||||
assert_eq!(&src[sym.name_span.as_range()], sym.name, "bad name span for {}", sym.name);
|
||||
}
|
||||
// The declaration span is the whole construct, the name span sits in it.
|
||||
let d = symbol_named(&s, "d");
|
||||
assert_eq!(&src[d.decl_span.as_range()], "input logic [W-1:0] d");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_variable_shadows_a_module_net() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire x;
|
||||
initial begin : blk
|
||||
integer x;
|
||||
x = 1;
|
||||
end
|
||||
assign x = 0;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let outer = symbol_id(&s, "x");
|
||||
let inner = s
|
||||
.symbols()
|
||||
.iter()
|
||||
.position(|sym| sym.name == "x" && sym.kind == SymbolKind::Var)
|
||||
.map(|i| SymbolId(i as u32))
|
||||
.expect("the block declares its own x");
|
||||
assert_ne!(outer, inner);
|
||||
|
||||
let use_in_block = s.reference_at(nth(src, "x = 1", 0)).expect("a use inside the block");
|
||||
assert_eq!(use_in_block.resolved(), Some(inner));
|
||||
|
||||
let use_outside = s.reference_at(nth(src, "x = 0", 0)).expect("a use outside the block");
|
||||
assert_eq!(use_outside.resolved(), Some(outer));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forward_reference_resolves() {
|
||||
let src = "\
|
||||
module m;
|
||||
assign y = w + P;
|
||||
wire w;
|
||||
localparam P = 1;
|
||||
wire y;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for name in ["y", "w", "P"] {
|
||||
let r = s.reference_at(nth(src, name, 0)).unwrap_or_else(|| panic!("a use of {name}"));
|
||||
assert_eq!(r.resolved(), Some(symbol_id(&s, name)), "{name} used before declaration");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_enum_variant_is_visible_in_the_enclosing_scope() {
|
||||
let src = "\
|
||||
module m;
|
||||
typedef enum logic { IDLE, BUSY } state_e;
|
||||
state_e st;
|
||||
always_comb st = IDLE;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let use_idle = s.reference_at(nth(src, "IDLE", 1)).expect("the use of IDLE");
|
||||
assert_eq!(use_idle.resolved(), Some(symbol_id(&s, "IDLE")));
|
||||
// The type name is a reference too, so hover/go-to-def works on it.
|
||||
let use_ty = s.reference_at(nth(src, "state_e st", 0)).expect("the use of state_e");
|
||||
assert_eq!(use_ty.resolved(), Some(symbol_id(&s, "state_e")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_argument_wins_over_a_module_net_of_the_same_name() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire a;
|
||||
function int f(input int a);
|
||||
f = a;
|
||||
endfunction
|
||||
assign b = a;
|
||||
wire b;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let arg = s
|
||||
.symbols()
|
||||
.iter()
|
||||
.position(|sym| sym.kind == SymbolKind::TfArg)
|
||||
.map(|i| SymbolId(i as u32))
|
||||
.expect("the argument is bound");
|
||||
let net = symbol_id(&s, "a");
|
||||
assert_ne!(arg, net);
|
||||
|
||||
let in_body = s.reference_at(nth(src, "f = a", 0) + 4).expect("the use inside the function");
|
||||
assert_eq!(in_body.resolved(), Some(arg));
|
||||
let outside = s.reference_at(nth(src, "assign b = a", 0) + 11).expect("the use outside");
|
||||
assert_eq!(outside.resolved(), Some(net));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_loop_genvar_is_scoped_to_its_loop() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire top_i;
|
||||
generate
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
wire w;
|
||||
assign w = i;
|
||||
end
|
||||
endgenerate
|
||||
assign top_i = i;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let genvar = symbol_id(&s, "i");
|
||||
assert_eq!(symbol_named(&s, "i").kind, SymbolKind::Genvar);
|
||||
|
||||
let in_loop = s.reference_at(nth(src, "assign w = i", 0) + 11).expect("the use in the body");
|
||||
assert_eq!(in_loop.resolved(), Some(genvar));
|
||||
|
||||
// Outside the loop the genvar is gone.
|
||||
let outside = s.reference_at(nth(src, "assign top_i = i", 0) + 15).expect("the use outside");
|
||||
assert_eq!(outside.resolution, Resolution::NotFound);
|
||||
|
||||
// The block label is a symbol, and the block's wire hangs under it.
|
||||
assert_eq!(symbol_named(&s, "g").kind, SymbolKind::Block);
|
||||
assert_eq!(symbol_named(&s, "w").kind, SymbolKind::Net);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn references_of_round_trips_with_every_resolved_reference() {
|
||||
let src = "\
|
||||
package p;
|
||||
localparam int K = 1;
|
||||
endpackage
|
||||
|
||||
module m #(parameter W = 4) (input clk, output q);
|
||||
import p::K;
|
||||
wire [W-1:0] d;
|
||||
logic r;
|
||||
always_ff @(posedge clk) r <= d[0] + K;
|
||||
assign q = r;
|
||||
sub u (.a(d), .b(r));
|
||||
endmodule
|
||||
|
||||
module sub (input a, input b);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert!(!s.references().is_empty());
|
||||
for r in s.references() {
|
||||
if let Some(id) = r.resolved() {
|
||||
let back = s.references_of(id);
|
||||
assert!(
|
||||
back.iter().any(|other| other.name_span == r.name_span),
|
||||
"{} at {:?} is missing from references_of",
|
||||
r.name,
|
||||
r.name_span
|
||||
);
|
||||
}
|
||||
}
|
||||
// A port name in a connection list resolves into the instantiated module.
|
||||
let port_a = s.reference_at(nth(src, ".a(d)", 0) + 1).expect("the .a connection");
|
||||
let decl = s.symbol(port_a.resolved().expect("resolved in-file")).expect("symbol");
|
||||
assert_eq!(decl.kind, SymbolKind::Port);
|
||||
assert_eq!(&src[decl.decl_span.as_range()], "input a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_of_answers_at_every_name_span() {
|
||||
let src = "\
|
||||
package p;
|
||||
localparam int K = 1;
|
||||
endpackage
|
||||
|
||||
module m (input clk);
|
||||
wire w;
|
||||
assign w = clk & p::K;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
for (i, sym) in s.symbols().iter().enumerate() {
|
||||
assert!(!sym.name_span.is_empty(), "{} has no name span", sym.name);
|
||||
let at = s.definition_of(sym.name_span.start).expect("a definition at its own name");
|
||||
assert_eq!(at.name, sym.name);
|
||||
assert_eq!(s.symbol_at(sym.name_span.start), Some(SymbolId(i as u32)));
|
||||
}
|
||||
// From a use, too — including a package-scoped one.
|
||||
let k = s.definition_of(nth(src, "p::K", 0) + 3).expect("go to definition of p::K");
|
||||
assert_eq!(k.name, "K");
|
||||
assert_eq!(k.kind, SymbolKind::Param);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_of_a_package_from_another_file_stays_an_external_candidate() {
|
||||
let src = "\
|
||||
module m;
|
||||
import other_pkg::*;
|
||||
import named_pkg::THING;
|
||||
wire w;
|
||||
assign w = SOMETHING;
|
||||
assign w = elsewhere_pkg::VALUE;
|
||||
missing_mod u (.p(w));
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
|
||||
// Only the wildcard could supply this name; the explicit import names
|
||||
// something else, so it is not offered to the workspace index.
|
||||
let some = s.reference_at(nth(src, "SOMETHING", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
some.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["other_pkg::*".into()] }
|
||||
);
|
||||
let thing = s.reference_at(nth(src, "named_pkg::THING", 0) + 11).expect("the imported name");
|
||||
assert_eq!(
|
||||
thing.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["named_pkg::THING".into()] }
|
||||
);
|
||||
|
||||
let scoped = s.reference_at(nth(src, "elsewhere_pkg::VALUE", 0) + 15).expect("the tail");
|
||||
assert_eq!(
|
||||
scoped.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["elsewhere_pkg::VALUE".into()] }
|
||||
);
|
||||
|
||||
// An instantiation of a module this file does not declare, and its ports.
|
||||
let module = s.reference_at(nth(src, "missing_mod", 0)).expect("the module name");
|
||||
assert_eq!(
|
||||
module.resolution,
|
||||
Resolution::ExternalCandidate { paths: vec!["missing_mod".into()] }
|
||||
);
|
||||
let port = s.reference_at(nth(src, ".p(w)", 0) + 1).expect("the port name");
|
||||
assert!(port.is_external_candidate());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_in_file_package_resolves_through_a_wildcard_import() {
|
||||
let src = "\
|
||||
package p;
|
||||
localparam int K = 1;
|
||||
typedef logic [1:0] t;
|
||||
endpackage
|
||||
|
||||
module m;
|
||||
import p::*;
|
||||
t v;
|
||||
assign v = K;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let k = s.reference_at(nth(src, "= K", 0) + 2).expect("the use of K");
|
||||
assert_eq!(k.resolved(), Some(symbol_id(&s, "K")));
|
||||
let t = s.reference_at(nth(src, "t v;", 0)).expect("the use of the type");
|
||||
assert_eq!(t.resolved(), Some(symbol_id(&s, "t")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_import_binds_to_the_module_scope() {
|
||||
let src = "\
|
||||
package p;
|
||||
localparam int K = 1;
|
||||
localparam int J = 2;
|
||||
endpackage
|
||||
|
||||
module m import p::*; import p::J; #(parameter W = K) (input logic [J-1:0] d);
|
||||
assign x = K;
|
||||
wire x;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
// Both the parameter default and the port width see the package.
|
||||
let w = s.reference_at(nth(src, "W = K", 0) + 4).expect("the parameter default");
|
||||
assert_eq!(w.resolved(), Some(symbol_id(&s, "K")));
|
||||
let d = s.reference_at(nth(src, "[J-1:0]", 0) + 1).expect("the port width");
|
||||
assert_eq!(d.resolved(), Some(symbol_id(&s, "J")));
|
||||
// And so does the body.
|
||||
let body = s.reference_at(nth(src, "assign x = K", 0) + 11).expect("the body use");
|
||||
assert_eq!(body.resolved(), Some(symbol_id(&s, "K")));
|
||||
// The import itself is a use of the package, and of the named item.
|
||||
let pkg = s.reference_at(nth(src, "import p::*", 0) + 7).expect("the package head");
|
||||
assert_eq!(pkg.resolved(), Some(symbol_id(&s, "p")));
|
||||
let named = s.reference_at(nth(src, "import p::J", 0) + 10).expect("the imported name");
|
||||
assert_eq!(named.resolved(), Some(symbol_id(&s, "J")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wildcard_connection_records_nothing_and_an_implicit_one_records_the_port() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire a;
|
||||
sub u0 (.*);
|
||||
sub u1 (.a);
|
||||
endmodule
|
||||
|
||||
module sub (input a);
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert!(s.references().iter().all(|r| r.name != "*"));
|
||||
let implicit = s.reference_at(nth(src, "(.a)", 0) + 2).expect("the .a port name");
|
||||
let port = s.symbol(implicit.resolved().expect("resolved")).expect("symbol");
|
||||
assert_eq!(port.kind, SymbolKind::Port);
|
||||
assert_eq!(port.name, "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tolerant_parse_with_error_nodes_is_analyzed_without_panicking() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire good;
|
||||
??? this is not verilog ???
|
||||
assign good = 1;
|
||||
initial begin
|
||||
@#$%^
|
||||
end
|
||||
endmodule
|
||||
|
||||
module still_here (input a);
|
||||
assign a = ;
|
||||
endmodule
|
||||
";
|
||||
let (file, diags) = parse_source_tolerant(src);
|
||||
assert!(!diags.is_empty(), "the fixture must actually break the parser");
|
||||
let s = analyze(&file, src);
|
||||
// The parts that did parse are still bound.
|
||||
assert_eq!(symbol_named(&s, "good").kind, SymbolKind::Net);
|
||||
assert_eq!(symbol_named(&s, "still_here").kind, SymbolKind::Module);
|
||||
// Nothing was bound inside the error text.
|
||||
assert!(s.symbols().iter().all(|sym| sym.name != "verilog"));
|
||||
assert!(s.references().iter().all(|r| r.name != "verilog"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyze_survives_an_empty_and_a_garbage_file() {
|
||||
for src in ["", "\n\n", "not verilog at all", "`define FOO 1\n"] {
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
let s = analyze(&file, src);
|
||||
assert!(s.document_symbols().is_empty() || !s.symbols().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_symbols_nest_declarations_under_what_declares_them() {
|
||||
let src = "\
|
||||
package p;
|
||||
localparam int K = 1;
|
||||
endpackage
|
||||
|
||||
module top (input clk);
|
||||
wire w;
|
||||
function int f(input int a);
|
||||
int local_v;
|
||||
return a;
|
||||
endfunction
|
||||
always_comb begin : named
|
||||
int in_block;
|
||||
in_block = 0;
|
||||
end
|
||||
initial begin
|
||||
int unnamed_block_var;
|
||||
unnamed_block_var = 1;
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let outline = s.document_symbols();
|
||||
let name = |d: &vlog_semantic::DocumentSymbol| s.symbol(d.symbol).expect("symbol").name.clone();
|
||||
|
||||
let top: Vec<String> = outline.iter().map(name).collect();
|
||||
assert_eq!(top, vec!["p", "top"]);
|
||||
|
||||
let pkg = &outline[0];
|
||||
assert_eq!(pkg.children.iter().map(name).collect::<Vec<_>>(), vec!["K"]);
|
||||
|
||||
let module = &outline[1];
|
||||
let children: Vec<String> = module.children.iter().map(name).collect();
|
||||
assert_eq!(
|
||||
children,
|
||||
vec![
|
||||
"clk",
|
||||
"w",
|
||||
"f",
|
||||
"named",
|
||||
// The unnamed `initial begin` has no symbol of its own, so what it
|
||||
// declares is listed at the module level.
|
||||
"unnamed_block_var",
|
||||
]
|
||||
);
|
||||
|
||||
let f = &module.children[2];
|
||||
assert_eq!(f.children.iter().map(name).collect::<Vec<_>>(), vec!["a", "local_v"]);
|
||||
let named = &module.children[3];
|
||||
assert_eq!(named.children.iter().map(name).collect::<Vec<_>>(), vec!["in_block"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_ansi_port_body_declaration_points_at_the_header_port() {
|
||||
let src = "\
|
||||
module m (a, b);
|
||||
input [7:0] a;
|
||||
output b;
|
||||
assign b = a[0];
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let a = symbol_id(&s, "a");
|
||||
assert_eq!(symbol_named(&s, "a").kind, SymbolKind::Port);
|
||||
// Exactly one symbol per port name, and the body declaration is a use.
|
||||
assert_eq!(s.symbols().iter().filter(|sym| sym.name == "a").count(), 1);
|
||||
let body = s.reference_at(nth(src, "input [7:0] a", 0) + 12).expect("the body declaration");
|
||||
assert_eq!(body.resolved(), Some(a));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hierarchical_name_resolves_only_its_head() {
|
||||
let src = "\
|
||||
module m;
|
||||
sub u ();
|
||||
assign x = u.inner_sig;
|
||||
wire x;
|
||||
endmodule
|
||||
|
||||
module sub;
|
||||
wire inner_sig;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let head = s.reference_at(nth(src, "u.inner_sig", 0)).expect("the head");
|
||||
assert_eq!(head.resolved(), Some(symbol_id(&s, "u")));
|
||||
// The tail is not recorded at all — see the README's non-goals.
|
||||
let tail = nth(src, "u.inner_sig", 0) + 2;
|
||||
assert!(s.reference_at(tail).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn macro_text_is_opaque() {
|
||||
let src = "\
|
||||
module m;
|
||||
`SOME_ASSERT(clk, rst)
|
||||
wire w;
|
||||
assign w = `WIDTH;
|
||||
endmodule
|
||||
";
|
||||
let (file, _) = parse_source_tolerant(src);
|
||||
let s = analyze(&file, src);
|
||||
assert!(s.references().iter().all(|r| r.name != "SOME_ASSERT" && r.name != "WIDTH"));
|
||||
}
|
||||
@@ -0,0 +1,487 @@
|
||||
# parallel-files
|
||||
|
||||
## Goal
|
||||
|
||||
Make `vfmt` format a whole RTL tree on all cores instead of one, and stop
|
||||
walking into directories the repository already declares generated. Two
|
||||
`TODO.md` §3 items in one change, because they touch the same loop:
|
||||
formatting is a pure function of `(source, config)`, so the per-file loop in
|
||||
`crates/vfmt/src/main.rs` parallelises with `rayon::par_iter` once panic
|
||||
containment and output ordering are reworked for concurrency; and
|
||||
`.gitignore` support is the other half of the file-discovery item whose
|
||||
`--exclude` half already shipped with cli-polish. The user-visible contract
|
||||
does not change: same stdout/stderr split, same exit codes, same per-file
|
||||
error messages, and — critically — the same *byte-identical* output for the
|
||||
same invocation, regardless of thread count.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Formatting one file has no cross-file state.** `format_source` reads a
|
||||
`&str` and a `Config` and returns a `String`; config discovery happens in
|
||||
full before any file is formatted (`gather`), and each file's write targets
|
||||
only itself. Nothing is shared between jobs but immutable data.
|
||||
- **Determinism comes from ordering the *reporting*, not the work.** Files are
|
||||
formatted in whatever order rayon's work-stealing picks. Every per-file
|
||||
outcome (stdout text, error line, counter bucket) is captured into a value
|
||||
and rendered afterwards in input order. Two runs of the same invocation
|
||||
therefore produce byte-identical stdout and stderr.
|
||||
- **Output is buffered until the run ends.** The price of ordered reporting is
|
||||
that `--diff` / `--stdout` text is held in memory until every file is done,
|
||||
rather than streaming. For the sizes vfmt targets (a large RTL tree is tens
|
||||
of MiB of source) this is acceptable; it is the reason `--stdout` over a
|
||||
huge tree is no longer incremental.
|
||||
- **8 MiB of worker stack is enough.** Taken from
|
||||
`docs/features/recursion-limit/README.md`, which measured the worst-case
|
||||
full-pipeline peak at ~3.9 MiB in a debug build and ~0.5 MiB in release.
|
||||
The pool is built with exactly that number; rayon's own default is 2 MiB,
|
||||
which would silently reintroduce the stack-overflow crash that feature
|
||||
fixed.
|
||||
- **The `.gitignore` support is a documented subset, not git.** It is the
|
||||
`--exclude` matcher plus anchoring, directory-only and negation. See
|
||||
"gitignore subset" below for exactly what is and is not honoured. It is
|
||||
not consulted for paths named directly on the command line, and it does
|
||||
not know whether the tree is a git repository at all.
|
||||
- **`.gitignore` files above the walk root are not read.** Only files at or
|
||||
below a directory named on the command line participate.
|
||||
- **stdin mode stays serial.** One buffer, one thread; nothing to parallelise.
|
||||
|
||||
## Behavior
|
||||
|
||||
### `--threads <N>`
|
||||
|
||||
- `--threads 0` or the flag absent: rayon's default, one worker per logical
|
||||
CPU.
|
||||
- `--threads 1`: a single worker. Useful for CI reproducibility, for
|
||||
profiling, and for bisecting a suspected concurrency bug.
|
||||
- Any `N`: that many workers. The value only changes *speed*: the bytes on
|
||||
stdout and stderr and the exit code are identical for every `N`.
|
||||
- Ignored in stdin mode.
|
||||
|
||||
### `.gitignore`
|
||||
|
||||
Honoured by default while walking directories; disabled with
|
||||
`--no-gitignore`. Each directory the walk enters is checked for a
|
||||
`.gitignore`, and its rules apply to that directory's subtree. Rules from a
|
||||
deeper `.gitignore` are considered after (and so override) shallower ones,
|
||||
and within one file the last matching line wins — git's own precedence.
|
||||
|
||||
Supported syntax:
|
||||
|
||||
| Form | Meaning |
|
||||
|---|---|
|
||||
| `# comment`, blank line | skipped |
|
||||
| `build` | a file *or* directory named `build`, at any depth below this `.gitignore` |
|
||||
| `*_gen.sv` | `*` matches any run of characters inside one path component; never crosses `/` |
|
||||
| `/build`, `gen/rtl` | a `/` at the start or in the middle anchors the pattern to this `.gitignore`'s own directory |
|
||||
| `build/` | trailing `/`: matches directories only |
|
||||
| `!keep.sv` | negation: re-includes a path an earlier rule ignored |
|
||||
|
||||
Not supported (deliberately, and silently — these forms are matched
|
||||
literally or as plain `*`, they are not errors):
|
||||
|
||||
- `**` has no special meaning; it is two `*`s inside one component, so
|
||||
`a/**/z.sv` matches only `a/<one component>/z.sv`.
|
||||
- `?` and character classes `[a-z]` are literal characters.
|
||||
- `\` escapes (so a pattern cannot contain a literal `!`, `#` or trailing
|
||||
space).
|
||||
- The global ignore file (`core.excludesFile`), `.git/info/exclude`, and
|
||||
`$GIT_DIR/info/exclude`.
|
||||
- Git's "already-tracked files are not ignored" rule: vfmt has no index, so
|
||||
a tracked file matching an ignore rule *is* skipped.
|
||||
- Re-including a path inside an ignored directory. An ignored directory is
|
||||
never descended into, so a `!` rule underneath it cannot bring anything
|
||||
back. (Git behaves the same way, for the same reason.)
|
||||
|
||||
A path named directly on the command line is never ignored, exactly as with
|
||||
`--exclude`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes `docs/features/recursion-limit/README.md`'s request:** that
|
||||
README asks whoever lands parallelism to build the rayon pool with
|
||||
`stack_size(8 * 1024 * 1024)` or larger, because a 2 MiB worker cannot
|
||||
reach `MAX_NESTING_DEPTH` in a debug build (~3.9 MiB measured). Done in
|
||||
`main.rs::build_pool`, with a test (`deep_file_formats_under_the_pool`)
|
||||
that fails if the stack size is ever removed.
|
||||
- **Discharges `docs/features/cli-polish/README.md`'s handshake:** that
|
||||
feature's `catch_panic` swapped the process-global panic hook with
|
||||
`take_hook`/`set_hook` around every call, and flagged it as sound only
|
||||
while single-threaded. It is replaced by a single hook installed at
|
||||
startup, before the pool exists, that consults a thread-local flag; the
|
||||
flag is set by `catch_panic` on the thread that is about to run contained
|
||||
work. No hook is ever swapped again, so nothing races. **Anyone editing
|
||||
`catch_panic` must keep it that way.**
|
||||
- **Consumes `vlog_formatter::{format_source, Config}`** unchanged. Both are
|
||||
`Send`/`Sync`-clean (`Config` is two `usize`s; `format_source` takes
|
||||
`&str`). Nothing in `vlog_parser` / `vlog_formatter` was touched.
|
||||
- **Promises to TODO.md §3's content-hash cache item:** the per-file unit of
|
||||
work is `process_file(&Path, &Config, &Options) -> Outcome` in `main.rs`,
|
||||
a pure-ish function whose only side effect is writing its own file. A cache
|
||||
lookup belongs at the top of it; the `Outcome` enum is where a "cached,
|
||||
unchanged" bucket would go.
|
||||
- **Promises to CI users:** the exit-code contract frozen by cli-polish is
|
||||
unchanged, and `--threads` does not affect it.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `rayon` as the workspace's first third-party dependency, pinned
|
||||
exactly, justified below.
|
||||
- [x] Global pool built once at startup with an 8 MiB worker stack.
|
||||
- [x] One panic hook installed at startup; `catch_panic` uses a thread-local
|
||||
flag instead of swapping hooks.
|
||||
- [x] Per-file loop parallelised; outcomes reported in input order.
|
||||
- [x] `--threads N`, documented in `--help` and `README.md`.
|
||||
- [x] `.gitignore` support in `walk.rs` with `--no-gitignore`.
|
||||
- [x] Tests: parallel-vs-`--threads 1` byte equality, contained panic under
|
||||
parallelism, deep-nesting file under the pool, `--diff` ordering,
|
||||
gitignore unit + CLI tests, per-file config under parallelism.
|
||||
- [x] `TODO.md` §3 parallel + `.gitignore` boxes.
|
||||
- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`.
|
||||
|
||||
## Dependency justification: `rayon = "=1.12.0"`
|
||||
|
||||
CLAUDE.md requires a written justification for every dependency; `TODO.md` §3
|
||||
pre-sanctions this one by name. It is the workspace's first third-party
|
||||
dependency, and `vfmt`'s only one.
|
||||
|
||||
**Why not hand-rolled threads.** The obvious alternative is *N* `std::thread`s
|
||||
each draining a shared `Mutex<vec::IntoIter>`, about 30 lines. Three things
|
||||
make that the worse choice here:
|
||||
|
||||
1. **Work stealing.** vfmt's per-file cost varies by two orders of magnitude
|
||||
(a 20-line header vs. a 10 000-line generated netlist). A static chunking
|
||||
leaves cores idle behind one slow file; a shared-queue design fixes that
|
||||
but then contends on the mutex for short files. rayon's per-worker deques
|
||||
with stealing get both, and this is the entire point of the feature.
|
||||
2. **Panic propagation.** A panic on a hand-rolled worker either poisons the
|
||||
shared mutex or is silently swallowed by a detached `JoinHandle`. rayon
|
||||
propagates a worker panic to the thread that called `par_iter` — which
|
||||
matters because vfmt's own containment (`catch_panic`) is the *inner*
|
||||
layer, and anything that escapes it must still surface as a crash rather
|
||||
than as a quietly missing file.
|
||||
3. **Maintenance.** Thread count, stack size, worker naming, and clean
|
||||
shutdown are all one builder call. The content-hash cache in TODO.md §3
|
||||
and any future `par_bridge` over a streaming walk get the same machinery
|
||||
for free.
|
||||
|
||||
**Cost.** Five transitive crates (`rayon-core`, `crossbeam-deque`,
|
||||
`crossbeam-epoch`, `crossbeam-utils`, `either`), all from the same
|
||||
well-maintained ecosystem, no build scripts, no `unsafe` in vfmt itself, and
|
||||
~9 s of cold release compile time. The version is pinned with `=` rather than
|
||||
a caret: a work-stealing scheduler is exactly the kind of dependency whose
|
||||
minor releases can change thread behavior, and vfmt's determinism claim is
|
||||
worth an explicit bump.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read CLAUDE.md, `TODO.md` §3, `docs/features/cli-polish/README.md`
|
||||
(the panic-hook handshake), `docs/features/recursion-limit/README.md`
|
||||
(Handshakes: the 8 MiB request) and all of `crates/vfmt/src` before
|
||||
writing anything.
|
||||
- **Blocked on the workspace for most of the run.** Another agent was
|
||||
mid-flight creating `crates/vlog_semantic`; its `Cargo.toml` was in the
|
||||
`[workspace] members` list before its `src/lib.rs` existed, so
|
||||
`cargo build` failed to load the workspace manifest. Iterated in a
|
||||
scratchpad copy of the workspace (that member removed) and re-ran
|
||||
everything against the real tree at the end. My edit to the root
|
||||
`Cargo.toml` is additive only (`[workspace.dependencies]`); the
|
||||
`members` line was left exactly as the other agent wrote it.
|
||||
|
||||
**Pool and stacks.** `build_pool` (`main.rs`) calls
|
||||
`ThreadPoolBuilder::new().num_threads(opts.thread_count()).stack_size(8 MiB)
|
||||
.build_global()` once, right after `gather` and before any file is touched.
|
||||
`--threads 0`/absent passes 0, which is rayon's "one per logical CPU".
|
||||
|
||||
The recursion-limit handshake asked for ≥ 8 MiB because a debug build needs
|
||||
~3.9 MiB to reach `MAX_NESTING_DEPTH`. That is honoured, and pinned by a
|
||||
test: `a_deeply_nested_file_formats_on_a_worker_thread` formats a 28-level
|
||||
`if … begin` nest (a nested `if … begin` costs two depth levels, so 28 sits
|
||||
just under the limit of 64). **Verified load-bearing**: with `WORKER_STACK`
|
||||
temporarily set back to rayon's 2 MiB default in the scratchpad copy, that
|
||||
test kills the process outright (no exit code at all — a stack overflow, not
|
||||
a panic), exactly the failure mode recursion-limit was built to remove.
|
||||
|
||||
**Correction to the brief, worth recording.** The task assumed rayon's
|
||||
`par_iter` also runs work on the calling thread, so the main thread's stack
|
||||
would matter too. That is not how rayon 1.12 behaves when `par_iter` is
|
||||
called from *outside* the pool: `Registry::in_worker` takes the cold path,
|
||||
injects the job, and **blocks** the caller. A probe binary (scratchpad,
|
||||
4 workers, 2000 jobs) saw work on exactly the four pool threads and never on
|
||||
`"main"`, and `rayon::current_thread_index()` on the main thread is `None`.
|
||||
The 2 MiB experiment above independently confirms it: if the main thread
|
||||
formatted anything, the deep file would sometimes have landed on its 8 MiB
|
||||
stack and the test would be flaky rather than deterministically fatal. So
|
||||
**every** file is formatted on a pool worker with the configured stack, and
|
||||
the main thread's own stack is irrelevant to this feature. That is the
|
||||
stronger guarantee, so nothing needed to change — only the reasoning.
|
||||
|
||||
**Determinism.** The parallel pass produces no output at all. Each job
|
||||
returns an `Outcome` (`Unchanged` / `Printed` / `Changed(text)` /
|
||||
`Failed(message)`) carrying the exact bytes it wants printed;
|
||||
`jobs.par_iter().map(process_file).collect::<Vec<_>>()` is an *indexed*
|
||||
parallel iterator, so the collect restores input order; `run_files` then
|
||||
walks that vector serially, printing and counting. Diff hunks and error
|
||||
lines therefore cannot interleave, and the summary counters are derived
|
||||
from the ordered vector rather than from shared counters. Verified at
|
||||
corpus scale: `vfmt --diff` over the 860-file corpus produces 2 424 208
|
||||
bytes of stdout and 66 019 bytes of stderr that are **byte-identical**
|
||||
across `--threads 1`, `2`, `8`, the default, and a repeat run.
|
||||
|
||||
The one real cost is that stdout is now buffered to the end of the run
|
||||
instead of streaming; recorded under Assumptions.
|
||||
|
||||
**Panic hook.** cli-polish's `catch_panic` took and re-set the process-global
|
||||
hook around every call and flagged the race. Replaced by:
|
||||
`install_panic_hook()` (a `std::sync::Once`, called from `main` before the
|
||||
pool is built) installs one hook that consults a `thread_local!`
|
||||
`CONTAINED: Cell<bool>`; `catch_panic` sets that flag on its own thread,
|
||||
runs `catch_unwind`, clears it. No hook is ever swapped again, so there is
|
||||
nothing to race on, and a panic *outside* `catch_panic` still gets the real
|
||||
default hook and its backtrace — which the old blanket silencing would have
|
||||
eaten if it were ever left installed. Verified both halves in the scratchpad:
|
||||
|
||||
- Sabotaged `format_source` (panic on a `SABOTAGE_<id>` marker), 44-file
|
||||
tree, 4 panicking files. Parallel run: all four reported as
|
||||
`error: …/boomNN.sv: panicked while formatting: sabotaged formatter: NN`
|
||||
in input order with their own distinct payloads, `40 files reformatted,
|
||||
4 files failed to format`, exit 2, the four files byte-identical
|
||||
afterwards, zero `thread '…' panicked` noise. stderr **byte-identical**
|
||||
to the same tree under `--threads 1`.
|
||||
- A deliberate `panic!` in the driver *outside* `catch_panic` still prints
|
||||
the full `thread 'main' panicked at … note: run with RUST_BACKTRACE=1`.
|
||||
|
||||
**`.gitignore`.** ~80 lines in `walk.rs`, no new dependency. The walk became
|
||||
a small `Walk` struct because it now carries three things down the
|
||||
recursion: the components of the current directory relative to the walk
|
||||
root, the stack of `.gitignore` rule sets seen so far, and the base depth of
|
||||
each of those sets. Rules reuse the existing `glob_component` matcher
|
||||
unchanged, so `--exclude` and `.gitignore` glob identically.
|
||||
|
||||
Anchoring follows git's actual rule rather than a leading-`/`-only rule,
|
||||
because git's rule *is* the `--exclude` split generalised: a `/` at the
|
||||
start **or in the middle** anchors to the `.gitignore`'s own directory; no
|
||||
`/` at all means "match this name at any depth below". Precedence is
|
||||
implemented by concatenating the stack root-to-leaf and letting the last
|
||||
matching rule win, which gives both "a deeper file overrides a shallower
|
||||
one" and "the last line in a file wins" from one loop.
|
||||
|
||||
**Differential-tested against real git**, not just against my own
|
||||
expectations: a scratchpad `git init` tree with a root `.gitignore`
|
||||
(`build/`, `*_gen.sv`, `/anchored.sv`, `gen/rtl`, `sub/*.sv`, a comment) and
|
||||
a nested `sub/.gitignore` (`!keep_gen.sv`, `drop.sv`) over 13 `.sv` files.
|
||||
`git check-ignore` and vfmt agree on **every** file.
|
||||
|
||||
On the real corpus (28 `.gitignore` files across ibex, OpenTitan, PULP
|
||||
common_cells and picorv32) the honoured rules change nothing: the same 860
|
||||
files are visited with and without `--no-gitignore`, because those files
|
||||
name build artifacts, not RTL. That is the right outcome and a useful
|
||||
negative result — the subset does not over-ignore real repositories.
|
||||
|
||||
**Speedup** (informational; release build, 10 logical cores, warm cache,
|
||||
best of 3, `--check` over the 860-file corpus):
|
||||
|
||||
| `--threads` | wall | speedup |
|
||||
|---|---|---|
|
||||
| 1 | 0.389 s | 1.00× |
|
||||
| 2 | 0.232 s | 1.68× |
|
||||
| 4 | 0.150 s | 2.60× |
|
||||
| 8 | 0.108 s | 3.60× |
|
||||
| default (10) | 0.107 s | 3.62× |
|
||||
|
||||
Below linear, and honestly so: 359 of the 860 corpus files fail to parse
|
||||
early (unsupported syntax, tracked in corpus-check), so a large fraction of
|
||||
the run is the serial directory walk plus 359 cheap early exits. The
|
||||
parallel fraction is the 501 files that actually format.
|
||||
|
||||
**Not done, deliberately.** `gather` (the walk plus config discovery) stays
|
||||
serial: it is I/O-bound, it owns a `&mut` discovery cache, and at corpus
|
||||
scale it is a small share of a run that is now 0.1 s. Parallelising it is
|
||||
the natural next step if profiling ever says so.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
Read CLAUDE.md, this README, the diff (`main.rs`/`args.rs`/`walk.rs`/`cli.rs`,
|
||||
root `Cargo.toml` + `Cargo.lock`, README.md, TODO.md §3), and the two
|
||||
handshake documents it cites (`docs/features/recursion-limit/README.md`,
|
||||
`docs/features/cli-polish/README.md`) — both handshakes are quoted
|
||||
accurately; nothing fabricated. Did not touch `crates/vlog_semantic`
|
||||
(another agent's work, now complete and compiling). No commits made.
|
||||
|
||||
**Verdict: pass on all seven claims, no blocking findings.**
|
||||
|
||||
1. **Pool.** `build_pool` (`main.rs:182`) is one `ThreadPoolBuilder` call,
|
||||
`stack_size(8 MiB)`, called once from `run_files` before any file is
|
||||
touched. Independently reproduced the "no work on the calling thread"
|
||||
claim with a standalone probe (rayon 1.12.0, 4 workers, 2000 jobs,
|
||||
`scratchpad/probe/main.rs`): `rayon::current_thread_index()` on `main` is
|
||||
`None`, and the set of thread names that actually ran `for_each` work
|
||||
never contains `"main"` — only unnamed pool workers. **Sabotage-checked**
|
||||
the 2 MiB claim myself: temporarily changed `WORKER_STACK` to
|
||||
`2 * 1024 * 1024`, rebuilt, ran
|
||||
`a_deeply_nested_file_formats_on_a_worker_thread` — it fails with the
|
||||
child process losing its exit code entirely (`panicked at
|
||||
cli.rs:81:23: exit code`), i.e. a hard crash, not a graceful error;
|
||||
restored the file and confirmed `git diff crates/vfmt/src/main.rs`
|
||||
byte-identical to before the experiment (`diff` of the two captured
|
||||
diffs was empty). **Pass.**
|
||||
2. **Hook.** Single `Once`-guarded `install_panic_hook` (`main.rs:266`);
|
||||
grepped the whole file for `take_hook`/`set_hook` — both appear exactly
|
||||
once, inside that function. Reproduced both halves live: (a) a
|
||||
sabotaged build (magic-marker panic injected into
|
||||
`vlog_formatter::format_source` in a scratchpad copy of the repo) run
|
||||
against a 44-file tree with 4 panicking files reports all four by name
|
||||
in input order, exit 2, zero `thread '…' panicked` noise, and is
|
||||
byte-identical between `--threads 1` and the default pool, both as a
|
||||
single comparison and across 20 repeated parallel runs (one stdout hash,
|
||||
one stderr hash, all 20). (b) Added a `panic!()` immediately after
|
||||
`install_panic_hook()` in `main()` (outside `catch_panic`) in the same
|
||||
scratchpad build: it still prints the full `thread 'main' panicked at
|
||||
… note: run with RUST_BACKTRACE=1`, exit 101 — the default hook is
|
||||
intact for real bugs. **Pass.**
|
||||
3. **Determinism.** Ran `vfmt --diff` over the full 860-file corpus (not
|
||||
just ~100) at `--threads` 1/2/8/default, 3 repeats each (12 runs) plus 2
|
||||
more default-thread repeats (5 total for that setting): stdout hashes to
|
||||
one value across all 12, stderr to one value across all 12 —
|
||||
2,424,208 bytes stdout / 66,019 bytes stderr, matching the work log's
|
||||
own numbers exactly once I used the same absolute-path invocation (my
|
||||
first pass used a relative `corpus` argument, which shortens every diff
|
||||
header and shrinks the totals — a harness artifact on my end, not a
|
||||
product issue, resolved and reconciled). Also re-ran the 20×
|
||||
panicking-scenario race hunt from claim 2 as the nondeterminism probe
|
||||
for this claim too. Zero variance anywhere. **Pass.**
|
||||
4. **`.gitignore`.** Built my own probe tree under a real `git init`
|
||||
(`scratchpad/gitprobe/`) covering all four requested tricky cases plus
|
||||
extras: a `!secret.sv` inside `build/` (ignored by the parent `build/`
|
||||
rule — git prunes the directory before reading its `.gitignore`, and so
|
||||
does vfmt); `/x.sv` anchored inside a *nested* `anchor_test/.gitignore`
|
||||
(correctly scoped to that directory only, not its `sub2/`); `!keepdir/`
|
||||
negating a directory while `*.sv` still catches the file inside it
|
||||
(git: ignored; vfmt: ignored — negating the directory doesn't negate the
|
||||
per-file pattern); and the `build/` vs. bare `build` directory-only
|
||||
distinction (already covered by the existing unit test
|
||||
`a_trailing_slash_matches_directories_only`, confirmed still green).
|
||||
Ran `git check-ignore -q` against every `.sv` file in the tree, compared
|
||||
to which files vfmt actually visited (16 files, 6 not ignored) —
|
||||
**exact agreement, 0 discrepancies.** Corpus visited-set check: `--diff`
|
||||
with and without `--no-gitignore` over the real 860-file corpus (28
|
||||
`.gitignore` files) produced byte-identical stdout and stderr, matching
|
||||
the "negative result" claim. `--threads 1000` (pool larger than the
|
||||
3-file tree it ran on, and separately against a single file) and
|
||||
`--threads 1000` against the full corpus all completed quickly and
|
||||
correctly (no hang, no resource exhaustion). A directory whose
|
||||
`.gitignore` contains only `*` yields `error: no Verilog files found
|
||||
(extensions: v, sv, vh, svh)`, exit 2 — sane, and `--no-gitignore`
|
||||
recovers the files as expected. `.gitignore` + `--exclude` together:
|
||||
both apply simultaneously (verified with one pattern from each). **Pass.**
|
||||
5. **Deps.** `cargo tree -p vfmt` shows exactly `rayon` → `either`,
|
||||
`rayon-core` → `crossbeam-deque` → `crossbeam-epoch`/`crossbeam-utils`
|
||||
(5 transitive crates as documented); `cargo metadata` confirms none of
|
||||
the six packages (rayon included) declare a build script. `rayon` is
|
||||
pinned `=1.12.0` in both `Cargo.toml` and `Cargo.lock`. Justification
|
||||
section present and specific. **Pass.**
|
||||
6. **Tools.** `cargo test -p vfmt`: 50 unit + 30 CLI, all green (0.01s +
|
||||
0.14–0.21s). `cargo clippy -p vfmt --all-targets` and
|
||||
`cargo fmt -p vfmt -- --check`: both silent/clean. Workspace-wide (now
|
||||
that `vlog_semantic` compiles): `cargo build --workspace`,
|
||||
`cargo clippy --workspace --all-targets` clean, `cargo test --workspace`
|
||||
green across all crates. Note: workspace-wide `cargo fmt --check` is
|
||||
*not* clean, but all 8 offending diffs are in
|
||||
`crates/vlog_semantic/tests/qa_attack.rs` — outside this feature's scope
|
||||
and outside the directive not to touch that crate; not a
|
||||
parallel-files finding, flagging for whoever owns that crate.
|
||||
Panic-under-parallelism scenario: see claim 2, reproduced with the exact
|
||||
shape asked for (4 of 44 files panicking) and race-hunted 20× with zero
|
||||
deviation. **Pass** (with the fmt note above filed separately, not
|
||||
against this feature).
|
||||
7. **Exit codes / stdin / per-file config.** Exit-code contract (0/1/2)
|
||||
unchanged, exercised throughout the CLI suite and my own ad hoc runs.
|
||||
`run_stdin` never calls `build_pool` — read from the source, confirmed:
|
||||
stdin mode never touches rayon at all, not just "runs on one thread of
|
||||
it". Per-file config under parallelism: exercised by
|
||||
`every_file_keeps_its_own_config_when_formatted_in_parallel` (12 files ×
|
||||
3 config layers) and `each_file_gets_the_config_of_its_own_directory`,
|
||||
both green; did not find it necessary to add a third manual
|
||||
two-dirs-two-configs run since these already cover more directories and
|
||||
more files than that would. **Pass.**
|
||||
|
||||
**Race-hunting, beyond re-verifying the claims:**
|
||||
- Panicking scenario (4/44) run 20× in parallel mode: one stdout hash, one
|
||||
stderr hash across all 20, both identical to the `--threads 1` baseline.
|
||||
- Corpus `--diff` run 5× at default threads plus 3× each at 1/2/8: 12 runs,
|
||||
one hash each for stdout/stderr.
|
||||
- `--threads 1000`: pool larger than the file count, both on a 3-file tree
|
||||
and a single file, and separately against the full 860-file corpus
|
||||
(0.2s wall, no anomalies).
|
||||
- `.gitignore` that ignores everything: sane error, not a crash or silent
|
||||
success.
|
||||
- `.gitignore` + `--exclude` together: both filters active simultaneously.
|
||||
- Deep-nesting file + panicking file + 10 good files in one parallel run
|
||||
(`scratchpad/combo_tree`): all three outcome kinds correct at once — the
|
||||
10 good files "would reformat" in input order, the deep file parses and
|
||||
"would reformat"s normally (proving the pool's stack size, not luck, is
|
||||
what saves it), the sabotaged file reports as a contained panic; exit 2
|
||||
(error outranks would-reformat), no interleaving.
|
||||
|
||||
**One methodology note, not a product finding:** immediately after the
|
||||
`WORKER_STACK` sabotage-and-restore in item 1, `cargo build -p vfmt`
|
||||
reported "Finished in 0.01s" and silently kept serving the *stale* 2 MiB
|
||||
binary — restoring the file with `mv` from a `sed -i.bak` backup left its
|
||||
mtime older than the already-rebuilt (sabotaged) target, so Cargo's
|
||||
mtime fast-path skipped recompilation despite the content being back to
|
||||
the original 8 MiB source. This briefly made `cargo test --workspace`
|
||||
report `a_deeply_nested_file_formats_on_a_worker_thread` and
|
||||
`deeply_nested_file_does_not_kill_the_batch` as crashing. `touch`ing
|
||||
`crates/vfmt/src/main.rs` and rebuilding made both pass again immediately,
|
||||
and `git diff` on the file was unaffected throughout (content never
|
||||
changed). Recorded here in case anyone else sees the same thing after a
|
||||
`sed -i.bak` / `mv` round-trip on this codebase — it is a Cargo caching
|
||||
quirk local to that workflow, not a vfmt bug.
|
||||
|
||||
**Severity summary:** no BLOCKING findings (zero nondeterminism observed
|
||||
across ~40 varied repeated runs), no should-fix gitignore/git
|
||||
disagreements (0 of many probe files disagreed). CLAUDE.md compliance:
|
||||
no `unwrap`/`expect`/`panic!` in library code paths in `main.rs`/`args.rs`/
|
||||
`walk.rs` outside `#[cfg(test)]` (grepped directly); all `pub` items carry
|
||||
a one-line doc comment; feature stayed inside `crates/vfmt` +
|
||||
`docs/features/parallel-files` as scoped, confirmed via `git status`/`git
|
||||
diff --stat` against `HEAD`. README.md and TODO.md claims read as
|
||||
accurate against what I independently measured.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits jointly with
|
||||
vlog-semantic (both touch the root manifest).**
|
||||
|
||||
The project's first dependency, taken the right way: pre-sanctioned in
|
||||
TODO §3, exact-pinned, five transitive crates audited for build
|
||||
scripts, written justification. Three things stood out:
|
||||
|
||||
1. **The dev corrected the brief with evidence.** My premise that
|
||||
rayon runs work on the calling thread is false for 1.12 — probed,
|
||||
documented, and the conclusion (every file formats on an 8 MiB
|
||||
worker) is *stronger* than the guarantee I asked for. Briefs are
|
||||
hypotheses; this is the correct way to falsify one. QA then
|
||||
independently re-proved it, and sabotage-verified that 2 MiB
|
||||
workers die exactly as the handshake predicted.
|
||||
2. **Both standing handshakes discharged on schedule**: the
|
||||
recursion-limit stack requirement (8 MiB workers) and cli-polish's
|
||||
single-install panic hook (Once + thread_local flag; uncontained
|
||||
panics still get the real hook — verified live both ways).
|
||||
3. **Determinism by construction** (collect indexed outcomes, print
|
||||
serially in input order) held under a real race hunt: one stdout
|
||||
hash and one stderr hash across 14 corpus-scale runs at four
|
||||
thread counts. The buffered-stdout trade-off is documented.
|
||||
|
||||
The gitignore subset earning a 16/16 differential agreement with real
|
||||
`git check-ignore` — including negation-inside-ignored-dir, the rule
|
||||
most hand-rolled implementations get wrong — is the acceptance
|
||||
evidence that matters. 3.6× wall-clock on the corpus is honest about
|
||||
its sub-linearity (early parse failures).
|
||||
|
||||
QA's methodology note (Cargo mtime fingerprinting silently serving a
|
||||
stale sabotaged build) is preserved in the QA log — future sabotage
|
||||
checks should `touch` after restore.
|
||||
@@ -0,0 +1,500 @@
|
||||
# vlog-semantic
|
||||
|
||||
## Goal
|
||||
|
||||
`crates/vlog_semantic` is the analog of ruff's `ruff_python_semantic`: it takes
|
||||
the AST `vlog_parser` produced for **one** file and builds the tables a
|
||||
language server needs — a tree of scopes, a symbol per declaration, and a
|
||||
reference per identifier *use*, each resolved to the declaration it names.
|
||||
That is what `textDocument/definition`, `references`, `hover` and
|
||||
`documentSymbol` are made of (TODO.md §6), and later what semantic lint rules
|
||||
(unused signal, undriven net) will read — the rules Verible structurally
|
||||
cannot write because it is syntax-only. This crate is deliberately
|
||||
**single-file**: a name only another file can supply is not an error, it is an
|
||||
`ExternalCandidate` carrying the import path, left for the workspace index
|
||||
(the next feature in §6) to finish.
|
||||
|
||||
`analyze` never fails and never panics. It is written against the
|
||||
error-tolerant tree, where `ItemKind::Error` / `StmtKind::Error` leaves are
|
||||
opaque — the same treatment macro invocations and directives already get.
|
||||
|
||||
## API as built
|
||||
|
||||
```rust
|
||||
pub fn analyze(file: &SourceFile, src: &str) -> Semantics;
|
||||
|
||||
impl Semantics {
|
||||
fn scopes(&self) -> &[Scope]; // index 0 is the file scope
|
||||
fn symbols(&self) -> &[Symbol];
|
||||
fn references(&self) -> &[Reference];
|
||||
fn scope(&self, ScopeId) -> Option<&Scope>;
|
||||
fn symbol(&self, SymbolId) -> Option<&Symbol>;
|
||||
|
||||
// the LSP queries
|
||||
fn symbol_at(&self, offset: u32) -> Option<SymbolId>;
|
||||
fn reference_at(&self, offset: u32) -> Option<&Reference>;
|
||||
fn definition_of(&self, offset: u32) -> Option<&Symbol>;
|
||||
fn references_of(&self, SymbolId) -> Vec<&Reference>;
|
||||
fn document_symbols(&self) -> Vec<DocumentSymbol>;
|
||||
fn resolution_counts(&self) -> (usize, usize); // (resolved, total)
|
||||
}
|
||||
|
||||
struct Symbol { name, kind: SymbolKind, name_span, decl_span, scope: ScopeId,
|
||||
child_scope: Option<ScopeId> }
|
||||
struct Reference{ name, name_span, scope: ScopeId, resolution: Resolution }
|
||||
struct Scope { kind: ScopeKind, parent, owner: Option<SymbolId>, span,
|
||||
symbols: Vec<SymbolId>, children, imports: Vec<Import> }
|
||||
|
||||
enum Resolution { Resolved(SymbolId), ExternalCandidate { paths: Vec<String> }, NotFound }
|
||||
```
|
||||
|
||||
`SymbolKind` is the list the task named: `Module`, `Package`, `Port`, `Net`,
|
||||
`Var`, `Param`, `Genvar`, `Typedef`, `EnumVariant`, `Function`, `Task`,
|
||||
`TfArg`, `Instance`, `Block`, `StructMember`. `ScopeKind` is `File`,
|
||||
`Module`, `Package`, `Function`, `Task`, `Block`, `Generate`, `Struct`.
|
||||
|
||||
### Deviations from the sketch in the task, and why
|
||||
|
||||
- **`analyze` takes `src` as well as the tree.** Most declarations in the AST
|
||||
keep their name as a plain `String` and carry a span only for the whole
|
||||
construct, so the *name's* range — the thing an editor highlights — is not
|
||||
recoverable from the tree alone. `scan.rs` finds it by scanning the
|
||||
construct's own source bytes (comments, strings and macro invocations
|
||||
skipped) inside a window narrowed by the sub-spans that *do* exist. The
|
||||
corpus test asserts `src[name_span] == name` for all 21 485 symbols and
|
||||
73 708 references it builds, so the scan is not a guess in practice. A
|
||||
Handshake request to put `name_span` on the AST is filed below; when it
|
||||
lands, `scan.rs` and this parameter go away.
|
||||
- **`Reference.resolution: Resolution` instead of `resolved:
|
||||
Option<SymbolId>`.** The task asked for both an `Option<SymbolId>` and an
|
||||
`ExternalCandidate` state carrying the import path; one enum says that once.
|
||||
`Reference::resolved() -> Option<SymbolId>` is kept as the accessor the
|
||||
sketch names, plus `is_external_candidate()`.
|
||||
- **`Symbol.child_scope`** was added: the outline needs "what does this
|
||||
declaration contain", and `p::x` resolution needs "which scope is package
|
||||
`p`".
|
||||
- **`references_of` does not include the declaration.** It returns *uses*
|
||||
only; the declaration is `symbol.name_span`, and an LSP honoring
|
||||
`includeDeclaration: true` appends it. Stated because the task asked for the
|
||||
choice to be documented.
|
||||
|
||||
## Resolution rules
|
||||
|
||||
Two passes. Pass one (`bind.rs`) walks the tree, opens scopes, binds every
|
||||
declaration and records every use as *pending*. Pass two (`resolve.rs`)
|
||||
resolves the pending uses against the finished tables. Nothing resolves during
|
||||
the walk, which is what makes **forward references** work: a net or parameter
|
||||
used above its declaration resolves exactly like one used below it, as
|
||||
Verilog requires at module scope — and as an editor needs mid-edit anywhere.
|
||||
|
||||
1. **Lexical chain.** From the scope the use is written in, outward through
|
||||
parents to the file scope. In each scope: names declared there first, then
|
||||
the packages that scope imports, then on to the parent.
|
||||
2. **Ports and parameters are module-scope names**, so a module body sees
|
||||
them; a `function`/`task`/block scope sees them through its parents.
|
||||
3. **Enum variants land in the scope holding the enum**, per the LRM — not
|
||||
inside the typedef. `typedef enum { IDLE } state_e;` in a module binds both
|
||||
`state_e` and `IDLE` in that module.
|
||||
4. **Struct members land in a `Struct` scope of their own**, hung under the
|
||||
typedef. Nothing ever *looks up* into it (member access `x.field` is not
|
||||
resolved, see below), so members cannot be reached as bare names — which is
|
||||
correct — but they are still symbols, so the outline can show them.
|
||||
5. **Imports.** `import p::*;` / `import p::x;` is recorded as an `Import` on
|
||||
the scope that wrote it (module header imports land on the module scope).
|
||||
Resolution consults it **only when `p` is a package declared in this
|
||||
file**; otherwise the use becomes
|
||||
`ExternalCandidate { paths: ["p::*"] }` — every import in the chain that
|
||||
could supply the name, in scope order, for the workspace index to try. An
|
||||
explicit `import p::x` is offered only for the name `x`.
|
||||
6. **Package-scoped names.** `p::x` records two references: the head `p`
|
||||
(target: a file-scope package) and the tail `x` (looked up in `p`'s scope
|
||||
only, never in the lexical chain). If `p` is not in this file, both become
|
||||
external candidates and the tail carries the full path `p::x`. If `p` *is*
|
||||
in this file but has no member `x`, the tail is `Resolution::NotFound` —
|
||||
not an external candidate, because the package is fully known locally and
|
||||
no workspace index could change the answer. (QA find, lead-documented.)
|
||||
7. **Instantiations.** The module name is a reference to a file-scope module,
|
||||
else an external candidate naming the module. A named connection's
|
||||
`.port` resolves **against that module's scope** — so `.data_i(x)` jumps to
|
||||
the port declaration when the module is in the same file, and is an
|
||||
external candidate when it is not. `.*` records nothing. Parameter
|
||||
overrides `#(.W(8))` resolve the same way.
|
||||
8. **Hierarchical names.** `a.b.c` resolves `a` and stops: no reference is
|
||||
recorded for `.b` or `.c`. Resolving a tail needs instance elaboration,
|
||||
which is a non-goal.
|
||||
9. **Type names are uses.** A declaration written with a user-defined type
|
||||
(`my_t x;`, `pkg::word_t y;`) records a reference for the type, so
|
||||
go-to-definition works on it. Built-in type keywords record nothing.
|
||||
10. **Redeclaration binds once.** A name already bound in a scope does not
|
||||
create a second symbol; the second occurrence becomes a *reference* to the
|
||||
first. This is what makes a non-ANSI port work — `module m(a); input a;`
|
||||
has one `a` symbol (the header port) and one use (the body declaration) —
|
||||
and it keeps `references_of` honest everywhere else.
|
||||
11. **Not recorded at all:** system tasks (`$display`), anything spelled with
|
||||
a leading backtick (a macro standing where a name belongs), and keywords
|
||||
the parser left in an identifier slot.
|
||||
|
||||
### Scope tree
|
||||
|
||||
`File > module | package > function | task | named or unnamed block | generate
|
||||
region | generate block | for-generate header | for/foreach statement`.
|
||||
|
||||
- A `for` generate opens a scope for its **header**, so `for (genvar i = 0;
|
||||
...)` does not leak `i` into the module; the body block nests inside it.
|
||||
`genvar i;` written at module scope binds there instead, as the LRM says.
|
||||
- A `for`/`foreach` *statement* opens a scope for the same reason
|
||||
(`for (int i = 0; ...)`).
|
||||
- A `struct`/`union` body opens a `Struct` scope that lookup never enters.
|
||||
|
||||
### Simplifications (deliberate, all of them LRM-inexact)
|
||||
|
||||
- **Every `begin`/`fork` opens a scope, named or not.** The LRM gives an
|
||||
unnamed block a scope only when it declares something; the difference is
|
||||
invisible unless a program declares a name in an unnamed block *and* relies
|
||||
on it leaking outward, which is illegal anyway.
|
||||
- **Forward references are accepted everywhere**, including inside functions
|
||||
and blocks where the LRM requires declaration-before-use. Being more
|
||||
permissive than the language costs an editor nothing and buys mid-edit
|
||||
robustness; a future lint rule can flag the strict violation.
|
||||
- **First declaration wins on a duplicate name** (rule 10). The LRM makes a
|
||||
true duplicate an error; reporting it belongs to the linter, not here.
|
||||
- **Explicit imports do not outrank wildcard imports.** Imports are consulted
|
||||
in the order written. The LRM prefers an explicit `import p::x` over a
|
||||
wildcard from another package; a file that needs that distinction is
|
||||
already ambiguous to a human reader.
|
||||
- **A function's name is not also a variable.** `f = expr;` inside `function
|
||||
f` resolves to the function symbol, which is where go-to-definition should
|
||||
land anyway.
|
||||
- **`endmodule : m` and other end labels record nothing.**
|
||||
- **`defparam` paths, `disable` targets and event names** are resolved with
|
||||
the ordinary lexical rule (`disable blk` finds the named block).
|
||||
- **Ordering inside a scope is not modeled**: `symbol_at` and lookup are
|
||||
position-independent. There is no "this name was not yet visible here".
|
||||
|
||||
## Non-goals
|
||||
|
||||
- **No type checking, no width inference, no elaboration.** Nothing here knows
|
||||
what a symbol's *type* is beyond the kind of declaration it came from.
|
||||
- **No cross-file anything.** No `` `include`` following, no workspace scan.
|
||||
External names are reported, never resolved.
|
||||
- **No macro expansion.** `` `NAME `` and `` `NAME(...) `` are opaque tokens;
|
||||
a name a macro would have produced is invisible to this crate, which is the
|
||||
same contract the formatter and the define table keep (TODO.md §7).
|
||||
- **No classes/constraints/UVM.** The parser does not accept them yet; when it
|
||||
does, they will need scope kinds of their own.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `src` passed to `analyze` is the exact text the tree was parsed from. Spans
|
||||
index into it; a mismatched string yields wrong name spans, not a panic
|
||||
(every slice is bounds-checked and clamped).
|
||||
- A construct's keyword is written before its name (`module m`, `function
|
||||
automatic int f`), and the name is a plain identifier. Where a type name and
|
||||
the declared name are the same token text (`function foo_t foo_t;`) the scan
|
||||
can pick the first of the two; nothing in the corpus does this.
|
||||
- The parser bounds nesting depth (`MAX_NESTING_DEPTH`, TODO.md §1), so the
|
||||
recursive walk here inherits a bounded stack and needs no depth counter of
|
||||
its own.
|
||||
- Identifiers are ASCII in practice; the scanner treats non-ASCII bytes as
|
||||
non-identifier bytes and never slices inside a multi-byte character.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`** (nothing here requires a change to work):
|
||||
|
||||
- `ast::SourceFile` and the whole node tree, including `ItemKind::Error` /
|
||||
`StmtKind::Error` from `parse_source_tolerant` — treated as opaque leaves.
|
||||
- `span::TextRange` on items, statements, expressions, declarators, ports,
|
||||
parameters, instances, enum members, struct members, dims and blocks.
|
||||
- `token::is_keyword` — to tell a built-in type keyword from a user type name,
|
||||
and to drop keywords the parser left in identifier slots.
|
||||
|
||||
**Promised to consumers** (`vfmt_server`, the workspace index, future lint
|
||||
rules):
|
||||
|
||||
- `analyze` never panics and never fails, on any input, tolerant tree or not.
|
||||
- `Symbol.name_span` / `Reference.name_span` are exact byte ranges of the name
|
||||
as written, or empty when the source does not spell the name literally.
|
||||
Empty ranges never match `contains`, so a query never returns one.
|
||||
- Every `Reference` whose `Resolution` is `ExternalCandidate` carries the
|
||||
workspace-level paths that could finish it; the workspace index may rewrite
|
||||
those references and nothing else.
|
||||
|
||||
**Requested of `vlog_parser`** (not done here — out of scope for this
|
||||
feature, and the crate works without it):
|
||||
|
||||
1. **`name_span: TextRange` on the nodes whose name is a bare `String`**:
|
||||
`Module`, `ItemKind::Package`, `FunctionDecl`, `TaskDecl`, `AnsiPort`,
|
||||
`ParamPort`, `TfArg`, `Typedef`, `Instantiation::module`,
|
||||
`Connection::name`, `ItemKind::Genvar`, `ItemKind::Import`,
|
||||
`GenBlock::label`, `StmtKind::Block::label`, `StmtKind::Foreach::vars`,
|
||||
`ExprKind::Member::name`, `ExprKind::Scope::name`. Every one of those is
|
||||
currently recovered by re-scanning source text in
|
||||
`crates/vlog_semantic/src/scan.rs`, which is ~150 lines this crate should
|
||||
not own and which cannot be right by construction — only right in
|
||||
practice, as the corpus test shows. This is the single change that would
|
||||
most simplify this crate.
|
||||
2. **A span for `DataType`** (and for `ExprKind::Cast::ty`), so a type
|
||||
reference does not need a window computed from its neighbours' spans.
|
||||
3. Nice to have, much smaller: the byte range of `Member`/`Scope` tails, which
|
||||
is today derived as `span.end - name.len()`.
|
||||
|
||||
## Corpus baseline
|
||||
|
||||
`cargo test -p vlog_semantic --test corpus -- --nocapture`, over the 860
|
||||
`.v`/`.sv`/`.svh` files in `corpus/` (Ibex, OpenTitan, PULP common_cells,
|
||||
picorv32), 2026-08-19:
|
||||
|
||||
| population | files | symbols | references | resolved in-file | external candidates | unresolved |
|
||||
|---|---:|---:|---:|---:|---:|---:|
|
||||
| every file | 860 | 21 485 | 73 708 | 73.4 % | 19.4 % | 7.2 % |
|
||||
| files that parse with zero errors | 502 | 12 900 | 46 408 | 79.5 % | 19.6 % | **0.9 %** |
|
||||
|
||||
No panics, and every one of the 95 193 name spans built across the corpus
|
||||
slices back to exactly the name it claims (0 unplaced).
|
||||
|
||||
Reading the numbers honestly:
|
||||
|
||||
- **~20 % external candidates is the expected steady state, not a defect.**
|
||||
RTL of this size lives on `import prim_pkg::*` and instantiates modules
|
||||
declared elsewhere; those references are *supposed* to leave this crate
|
||||
unfinished. The workspace index converts this bucket, and it is the single
|
||||
biggest lever on perceived LSP quality.
|
||||
- **0.9 % genuinely unresolved on clean files** is the interesting number. A
|
||||
sample of what is in it: names a `` `define`` would have produced (`XLEN`,
|
||||
`ENABLE_IRQ`), class/UVM constructs in files that parse only because their
|
||||
broken parts became error nodes (`this`, `super`, `null`, `new`), and
|
||||
hierarchical/member tails reached through a path this crate stops at.
|
||||
- **The 7.2 % over *all* files is dominated by the 42 % of corpus files that
|
||||
still hit a parse error** (classes, `bind`, queues — README's "not yet
|
||||
supported" list): a declaration swallowed by an error node cannot bind, so
|
||||
every use of it counts unresolved. That number will move when the parser
|
||||
moves, not when this crate does.
|
||||
|
||||
The test asserts the two properties, not the percentages: zero unplaced names
|
||||
anywhere, and under 3 % unresolved on cleanly-parsed files.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] New crate `crates/vlog_semantic`, workspace member, no dependency
|
||||
beyond `vlog_parser` + std
|
||||
- [x] Scope tree with parent links (file / module / package / function / task /
|
||||
block / generate / struct)
|
||||
- [x] Symbols for all 15 kinds, with `name_span`, `decl_span`, `scope`,
|
||||
`child_scope`
|
||||
- [x] References for expression identifiers, type names, hierarchical heads,
|
||||
instantiated module names, `.port` connections, package heads and tails,
|
||||
import paths
|
||||
- [x] Two-pass bind-then-resolve (forward references)
|
||||
- [x] Imports: in-file packages resolved, others kept as `ExternalCandidate`
|
||||
with their paths
|
||||
- [x] Queries: `symbol_at`, `reference_at`, `definition_of`, `references_of`,
|
||||
`document_symbols`
|
||||
- [x] `Error` nodes are opaque; tolerant trees analyze without panicking
|
||||
- [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
|
||||
- [x] TODO.md §6 `vlog_semantic` checkbox
|
||||
- [ ] Deferred to the workspace index: resolving `ExternalCandidate`s
|
||||
- [ ] Deferred: interfaces/modports, classes — the parser does not accept them
|
||||
- [ ] Deferred: `Symbol` type information (needed for hover text richer than
|
||||
"port, declared at line N")
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-19 — dev agent.** Built the crate: `model.rs` (tables), `bind.rs`
|
||||
(pass one), `resolve.rs` (pass two), `scan.rs` (name-span recovery),
|
||||
`lib.rs` (`analyze` + queries). Key decisions, all argued above:
|
||||
|
||||
- **`analyze(file, src)`**, not `analyze(file)`. Discovered while mapping the
|
||||
AST that only `Declarator`, `EnumMember`, `Instance`, `NonAnsiPort` and the
|
||||
expression nodes place their name at a span I can compute; everything else
|
||||
keeps the name as a `String` inside a construct-wide span. Rather than park
|
||||
go-to-definition for modules, ports, functions, tasks, parameters, block
|
||||
labels, genvars and connections — most of the feature — I took the source
|
||||
text and scan for the name inside a window narrowed by the spans that do
|
||||
exist. Handshake request #1 filed to make this unnecessary.
|
||||
- **One `Resolution` enum** instead of `Option<SymbolId>` plus a parallel
|
||||
external state; `resolved()` keeps the sketch's accessor.
|
||||
- **Redeclaration becomes a reference** (rule 10). Found while binding
|
||||
non-ANSI ports: `module m(a); input [7:0] a;` would otherwise produce two
|
||||
`a` symbols and split its references between them.
|
||||
- **Struct members get a scope lookup never enters.** The alternative — put
|
||||
them in the enclosing scope — would make a bare `field` resolve to a struct
|
||||
member, which is wrong.
|
||||
- The scanner skips a backtick plus its identifier as one token, so `` `WIDTH ``
|
||||
never answers a search for `WIDTH`; and `use_name` drops names that start
|
||||
with a backtick, which is how `` `PICORV32_REGS regs (...) `` (a macro used
|
||||
as a module name, twice in picorv32) stopped being an unplaceable reference.
|
||||
That took corpus unplaced names from 2 to 0.
|
||||
- Corpus numbers are reported for two populations because the all-files number
|
||||
is mostly a statement about parser coverage, not about resolution.
|
||||
|
||||
Checks at the end: `cargo test -p vlog_semantic` 26 tests green (19 + 6 + 1),
|
||||
`cargo clippy -p vlog_semantic --all-targets` silent, `cargo fmt` clean,
|
||||
`cargo test --workspace` green.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-19 — QA agent.** Verified against `crates/vlog_semantic/src/{lib,model,bind,resolve,scan}.rs`
|
||||
and this README. Scope: `-p vlog_semantic` only.
|
||||
|
||||
Gates:
|
||||
- `cargo test -p vlog_semantic`: **26 passed** (6 scan unit + 1 corpus + 19
|
||||
behavior), 0 failed, matching the claimed count exactly.
|
||||
- `cargo clippy -p vlog_semantic --all-targets`: silent. No `#[allow]`,
|
||||
`unwrap()`, `expect()` or `panic!` anywhere in `src/*.rs`.
|
||||
- `cargo fmt -p vlog_semantic -- --check`: clean.
|
||||
- `cargo tree -p vlog_semantic`: exactly `vlog_semantic -> vlog_parser`, no
|
||||
other dependency. Confirms "no deps beyond vlog_parser + std."
|
||||
- Root `Cargo.toml` diff: the `members` line gains `vlog_semantic`, as
|
||||
claimed. (The diff also carries an unrelated `[workspace.dependencies]
|
||||
rayon = "=1.12.0"` hunk — that belongs to the concurrently-worked
|
||||
`parallel-files`/`vfmt` feature, out of my scope, noted only so the
|
||||
"members-line-only" claim for *this* feature isn't misread against the
|
||||
whole file.)
|
||||
- `cargo test --workspace`: **2 failures**, both in `crates/vfmt`
|
||||
(`a_deeply_nested_file_formats_on_a_worker_thread`,
|
||||
`deeply_nested_file_does_not_kill_the_batch`) — outside my gate
|
||||
(`-p vlog_semantic` is green) and inside the area another QA agent owns
|
||||
concurrently. Flagging only so "workspace green" isn't taken at face
|
||||
value right now; not a `vlog_semantic` finding.
|
||||
- `SymbolKind` has exactly 15 variants, `ScopeKind` exactly 8, matching the
|
||||
claim (counted in `model.rs`).
|
||||
- TODO.md §6's `vlog_semantic` line is checked and its numbers (79.5% /
|
||||
19.6% / 0.9%) match the corpus re-run below verbatim.
|
||||
|
||||
Corpus re-run (`cargo test -p vlog_semantic --test corpus -- --nocapture`),
|
||||
reproduced **exactly**, not just within noise:
|
||||
```
|
||||
corpus (every file): 860 files, 21485 symbols, 73708 references — 73.4% resolved in-file, 19.4% external candidates, 7.2% unresolved, 0 names unplaced
|
||||
corpus (files that parse cleanly): 502 files, 12900 symbols, 46408 references — 79.5% resolved in-file, 19.6% external candidates, 0.9% unresolved, 0 names unplaced
|
||||
```
|
||||
Wall time 0.73s (well under the 2s claim). 0 panics, 0 unplaced names, both
|
||||
populations match the README table exactly.
|
||||
|
||||
**Attack suite.** Wrote a scratch integration test
|
||||
(`crates/vlog_semantic/tests/qa_attack.rs`, 20 `#[test]` fns, deleted after
|
||||
this pass — not part of the shipped suite) exercising the crate only
|
||||
through its public API. All 20 attacks passed; no BLOCKING findings. Cases
|
||||
covered:
|
||||
|
||||
- *scan.rs / name_span (claim 2):* module name shadowed by an identical
|
||||
string in a leading `//` comment (correctly skipped — lands on the real
|
||||
`module foo`, not the comment); a port name that is a whole-word prefix
|
||||
of a sibling port (`w` vs `ww` — `NameScanner` compares whole tokens, not
|
||||
substrings, so this class of bug is structurally excluded, not just
|
||||
untriggered here); a `genvar i` declared amid `ii`/`i_delay` lookalikes
|
||||
used throughout a generate-for body; a construct where the name sits at
|
||||
byte 0 of its window and another where it ends exactly at the window's
|
||||
last byte (`package p;endpackage`); a block comment full of multi-byte
|
||||
UTF-8 sitting between a module's keyword and its ports; an escaped
|
||||
identifier (`` \a+b ``) — the lexer passes these through, and both its
|
||||
declaration and its later use land on exactly `\a+b` (4 bytes), correctly
|
||||
resolved; a non-ANSI port used twice in the body, confirming exactly one
|
||||
symbol exists and both body occurrences are *uses* whose `name_span`
|
||||
sits at the body text, not the header; an instantiation where the
|
||||
instance name and the module type name are the same token
|
||||
(`dff dff (...)`) — the module-name reference and the instance symbol's
|
||||
`name_span` are distinct, non-overlapping ranges.
|
||||
- *resolution (claim 3):* three-deep shadowing (module net / function arg /
|
||||
block var all named `x`) — `references_of` on each binding contains only
|
||||
its own use, verified for all three; an enum variant used textually
|
||||
before its `typedef enum` — resolves (two-pass forward reference, as
|
||||
designed); `import p::*` where package `p` is declared *below* the
|
||||
import in the same file — resolves (two-pass); `import` of a package not
|
||||
in this file — `ExternalCandidate { paths: ["nowhere_pkg::*"] }`, exact
|
||||
path confirmed; two wildcard imports of different in-file packages that
|
||||
both define the same name — the first-written import wins (matches the
|
||||
README's documented "consulted in the order written" rule); `p::x`
|
||||
where `p` **is** an in-file package but `x` is not a member of it —
|
||||
resolves to `Resolution::NotFound`, *not* `ExternalCandidate`. This
|
||||
distinction is correct (the workspace index can't help — the package is
|
||||
fully known locally) but **is not stated in the README's rule 6**, which
|
||||
only describes the "`p` not in this file" case. Filed as a documentation
|
||||
gap, not a bug (see Findings below); a named connection `.clk(clk)` —
|
||||
confirmed the `.clk` token resolves into the instantiated module's port
|
||||
scope (`SymbolKind::Port`) while the `(clk)` argument resolves against
|
||||
the local net (`SymbolKind::Net`), two different symbols from one
|
||||
connection, as documented; an instance array (`sub u[3:0] (...)`) binds
|
||||
and resolves its connections without confusion; a recursive function
|
||||
(`fact`) — both the self-assignment (`fact = ...`) and the recursive
|
||||
call (`fact(n - 1)`) resolve to the function's own symbol; a reference to
|
||||
a generate-for's genvar from inside a nested `if`-generate two levels
|
||||
deep — resolves through the header scope as designed.
|
||||
- *tolerant-tree safety (claim 4):* 10 broken files, including the exact
|
||||
header-distortion repro from `docs/features/error-recovery/README.md`
|
||||
(`module m #(parameter W = , parameter X = 4) (input a); wire ok;
|
||||
endmodule` — module body re-parses as file-scope items) plus a broken
|
||||
port list, an orphaned `endmodule` with no matching `module`, an
|
||||
unterminated string, garbage tokens mid-body, mismatched `begin`/`end`,
|
||||
a broken for-generate header, an empty file, a dangling backtick macro
|
||||
with broken arguments, and two broken module headers back to back. No
|
||||
panics; every non-empty `name_span`/`Reference.name_span` produced still
|
||||
slices back to exactly the name it claims, even on these malformed
|
||||
trees.
|
||||
- *queries (claim 5):* `definition_of`/`symbol_at`/`reference_at` called at
|
||||
every byte offset (0..=len) of a small multi-construct file — no panic
|
||||
at any offset, including offsets that land on whitespace, punctuation,
|
||||
or mid-token.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- *Should-fix (documentation gap, not a bug), LOW.* README rule 6
|
||||
("Package-scoped names") describes only two outcomes for `p::x`: `p`
|
||||
external (both refs become `ExternalCandidate`), or implicitly `p`
|
||||
in-file and `x` found. It doesn't say what happens when `p` is in-file
|
||||
but `x` is not one of its members. Actual (and, on inspection, correct)
|
||||
behavior per `resolve.rs`'s `Target::PackageMember` arm: the tail
|
||||
resolves to `Resolution::NotFound`. Recommend adding one sentence to
|
||||
rule 6. Repro: `b6_package_member_missing_from_an_in_file_package` in the
|
||||
now-deleted scratch suite —
|
||||
```
|
||||
package p; localparam int K = 1; endpackage
|
||||
module m; assign w = p::MISSING; wire w; endmodule
|
||||
```
|
||||
`s.reference_at(<the "MISSING" span>).resolution == Resolution::NotFound`.
|
||||
- No BLOCKING findings. No wrong `name_span` (pointing at a comment, a use,
|
||||
or the wrong occurrence) and no panic were produced by any attack above,
|
||||
including the specific risky shapes named in the QA brief (comment
|
||||
shadowing, substring siblings, UTF-8 preceding a name, escaped
|
||||
identifiers, same-name instance/module, header-distortion trees).
|
||||
|
||||
Everything else (claims 1, 3's remaining rules, 4, 5) verified as
|
||||
documented: `analyze` never panicked across the full corpus or the 10
|
||||
broken-file probe; the 15 `SymbolKind`/8 `ScopeKind` counts are exact;
|
||||
`references_of` round-trips (pre-existing test plus the shadowing probe
|
||||
above); `document_symbols` nesting was not independently re-probed beyond
|
||||
the existing `document_symbols_nest_declarations_under_what_declares_them`
|
||||
test, which already covers module > function > block and passes.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits jointly with
|
||||
parallel-files (both touch the root manifest). The differentiation
|
||||
feature has arrived: this is the layer Verible doesn't have.**
|
||||
|
||||
What earned it:
|
||||
|
||||
1. **Two-pass bind-then-resolve** was the only correct answer to
|
||||
Verilog's forward references, and taking it from the start avoided
|
||||
the incremental-resolution trap. The redeclaration-becomes-reference
|
||||
rule for non-ANSI ports is the kind of language-specific judgment
|
||||
that makes references_of actually useful.
|
||||
2. **`Resolution` as a three-state enum** (Resolved / ExternalCandidate
|
||||
carrying paths / NotFound) is the right interface for the workspace
|
||||
index: the index gets exactly the worklist it needs, and QA's
|
||||
documentation find — in-file package misses are NotFound *because no
|
||||
index could change the answer* — shows the semantics were thought
|
||||
through, now stated in rule 6.
|
||||
3. **`scan.rs` is honest scaffolding**: 95k spans verified against
|
||||
source, every QA attack defeated (comments, substrings,
|
||||
decl-vs-use, escaped identifiers), and a filed handshake whose
|
||||
acceptance deletes the module. The `name_span`-in-parser handshake
|
||||
is hereby approved for the next parser-touching round.
|
||||
4. The corpus baseline (79.5% in-file resolution, 0.9% unresolved on
|
||||
clean files, 19.6% waiting on the index) is exactly the honest
|
||||
number the workspace-index feature will be measured against.
|
||||
|
||||
The workspace-green gate was transiently false during QA (two vfmt
|
||||
deep-nesting tests) — timing overlap with the parallel-files QA's
|
||||
deliberate stack-sabotage check, verified restored before the joint
|
||||
commit.
|
||||
Reference in new issue
Block a user