Files
lucisv/crates/vlog_refactor/src/scope.rs
T
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Release 0.66.2: every source file names its author
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00

613 lines
26 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! The in-scope files, the index built from them, and the analyses computed
//! so far — what every refactoring in this crate reads the workspace through.
//! Nothing here is specific to a rename: `ports`, `references` and
//! `instantiate` read the same workspace, which is why it sits at the crate
//! root rather than under one of them.
//!
//! **One parse per file** (take 5 §P2b). Building the index parses and
//! analyses every in-scope file already — `FileFacts::of` is a parse, an
//! `analyze` and a read-off — and used to throw that analysis away, so the
//! first thing every refactoring did was parse a third of those files a
//! second time. [`FileFacts::analyzed`] hands the analysis back instead, and
//! [`Scope::build_keeping`] retains the ones a caller says it will want. What
//! is retained is a *cache and nothing else*: a file whose analysis was not
//! kept is analysed on demand exactly as before, so a retention rule that
//! guesses wrong costs time and cannot change an answer.
//!
//! **And no parse at all, for a file the caller already has the record of**
//! (review round §R3b). Two thirds of that per-file cost is the lexer and the
//! parser, and a third of a rename's files are containers it indexes and never
//! reads again — so [`KnownFacts`] lets a caller hand back the [`FileFacts`]
//! it holds *for exactly the bytes it is handing over*, and those files are
//! never parsed. Unlike retention, this one is not merely a cache: a record
//! that does not describe the text it is filed against is a wrong index. The
//! contract, and the two halves of it this crate can check itself, are on
//! [`KnownFacts`]; `docs/features/perf5r-scope-reuse/README.md` has the rest.
use std::collections::HashMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use vlog_parser::parse_source_tolerant;
use vlog_semantic::{
analyze, resolve_external, ExternalResolutions, FileFacts, FileId, IndexBuilder, Semantics,
WorkspaceIndex,
};
use crate::trace::IndexTrace;
/// What the caller already knows about the files it is handing over.
///
/// A refactoring's scope is built by parsing and analysing every in-scope
/// file, and most of that work exists only to produce each file's
/// [`FileFacts`] — the record the workspace index is merged from. A caller
/// that has already read that record off *these very bytes* can hand it back
/// here, and the build skips the parse (review round §R3b, TODO §61.5).
///
/// **The whole contract is the one sentence in `facts_for`**, and it is the
/// caller's to keep: this crate cannot check a record against the text it
/// claims to describe without doing the parse the record exists to save. The
/// engine does the two checks it can — it asks with the exact text it is about
/// to index, and it refuses a record filed under another path — and nothing
/// else. So an implementation must key its answer on the *content* of the text
/// it is handed, from a record and a key it read out of one place; a modified
/// time, a size or a path alone is not that key, and neither is a record whose
/// hash was recorded by something other than the read that produced it.
///
/// A wrong answer here is a wrong index, which is a wrong refactoring: this is
/// the one thing in the door that is not merely a cache. `None` is always
/// safe — the file is analysed exactly as it always was.
pub trait KnownFacts {
/// The record [`FileFacts::of(path, text)`](FileFacts::of) would produce,
/// if the caller can promise it is exactly that; `None` otherwise.
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts>;
}
/// What the build does with one file, which is also what decides whether its
/// analysis is worth keeping.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Class {
/// The file the request was made in: analysed first, always kept.
Lead,
/// A file the retention rule asked for: analysed, and kept.
Kept,
/// Everything else: it contributes a record to the index and nothing
/// reads its analysis, so with a known record it is never analysed.
Other,
}
/// One scope build in progress: the records collected so far, the analyses
/// kept, and where the time went.
struct Building<'k, 't> {
builder: IndexBuilder,
kept: HashMap<usize, Semantics>,
known: Option<&'k dyn KnownFacts>,
trace: &'t mut IndexTrace,
}
impl Building<'_, '_> {
/// Take one file's contribution: its record, reused when the caller knows
/// it for exactly these bytes and read off a fresh analysis otherwise, and
/// its analysis when a later stage will read it.
///
/// The two halves of a reused file are computed apart — the record from
/// the caller, the [`Semantics`] from this text — where an analysed file's
/// come from one call. They agree because both are pure functions of the
/// same bytes, which is the same reason `Scope::analysis`'s on-demand path
/// has always been allowed to analyse a file the index build already read.
fn take(&mut self, i: usize, path: &Path, text: &str, class: Class) {
let known = self.known;
let record = self
.trace
.reused
.measure(|| known?.facts_for(path, text))
// A record filed under another path would be merged as that file.
// The caller cannot mean this, so it is a miss rather than a trust.
.filter(|facts| facts.path() == path);
self.count(class, text.len(), record.is_some());
let wanted = class != Class::Other;
let stage = match class {
Class::Lead => &mut self.trace.lead,
Class::Kept => &mut self.trace.kept,
Class::Other => &mut self.trace.other,
};
let (facts, semantics) = match record {
Some(facts) => {
let analysed = || stage.measure(|| analyze(&parse_source_tolerant(text).0, text));
(facts, wanted.then(analysed))
}
None => {
let (facts, semantics) =
stage.measure(|| FileFacts::analyzed(path.to_path_buf(), text));
(facts, wanted.then_some(semantics))
}
};
self.builder.add_facts(facts);
if let Some(semantics) = semantics {
self.kept.insert(i, semantics);
}
}
/// The file counted into its class, and into the reuse count when its
/// record came from the caller.
fn count(&mut self, class: Class, bytes: usize, reused: bool) {
match class {
Class::Lead => {}
Class::Kept => {
self.trace.kept_files += 1;
self.trace.kept_bytes += bytes;
}
Class::Other => {
self.trace.other_files += 1;
self.trace.other_bytes += bytes;
}
}
if reused {
self.trace.reused_files += 1;
self.trace.reused_bytes += bytes;
}
}
}
/// One file's two analysis layers, as `textDocument/definition` uses them.
pub(crate) struct Analysis {
pub(crate) semantics: Semantics,
pub(crate) external: ExternalResolutions,
}
/// The in-scope files, the index built from them, and the analyses computed so
/// far. Analyses are built on demand: a rename usually needs a handful of the
/// workspace's files, and analyzing the rest would be pure cost.
pub(crate) struct Scope<'a> {
/// Path and text, sorted by path and deduplicated the way
/// `WorkspaceIndex::build` does it, so index `i` and `FileId(i)`'s texts
/// agree.
sources: Vec<(&'a Path, &'a str)>,
pub(crate) index: WorkspaceIndex,
/// Source index → the index's own file id.
file_ids: Vec<Option<FileId>>,
cache: HashMap<usize, Analysis>,
/// The `Semantics` the index build kept, by source index — the half of an
/// [`Analysis`] that does not depend on the finished index. Moved into
/// `cache` the first time that file's analysis is asked for.
kept: HashMap<usize, Semantics>,
/// How many sources share each file name, for [`Scope::name_of`].
base_names: BaseNames,
}
impl<'a> Scope<'a> {
/// The in-scope files, indexed, keeping no analysis.
///
/// Each file is still parsed and analysed exactly once — that is what
/// building the index costs — and every later `analysis` call parses
/// again, which is the behaviour every caller but the rename has always
/// had. [`Scope::build_keeping`] is the one that keeps them.
pub(crate) fn build(files: &'a [(PathBuf, String)]) -> Scope<'a> {
Scope::assemble(files, None, |_| Vec::new(), None, &mut IndexTrace::default())
}
/// The in-scope files, indexed, **keeping** the analysis of `lead` and of
/// every file whose text mentions one of the words `keep` asks for.
///
/// `lead` — the file the request was made in — is analysed first, and
/// `keep` is then asked which words are worth retaining *given that
/// analysis*. That ordering is the whole trick: a rename cannot know the
/// name under the cursor until something has analysed the cursor's file,
/// and this way that analysis is the file's own one-and-only parse rather
/// than an extra one.
///
/// The rule is `text.contains(word)` — a substring test, deliberately the
/// same prefilter [`Scope::collect_occurrences`] uses, so every file the
/// occurrence walk will analyse and every file
/// [`crate::check`] will watch (a whole-word subset) is retained, and
/// nothing else is.
///
/// `known`, when the caller has one, is asked for each file's index record
/// before that file is analysed — see [`KnownFacts`]. It changes what the
/// build *costs* and nothing else: a record it does not answer for is read
/// off a fresh analysis exactly as it always was.
///
/// `trace` is filled in as the build runs — the per-file-class split the
/// review's §3 item 1 asked for. A caller with nothing to measure passes
/// `&mut IndexTrace::default()`; nothing in the build reads it back.
pub(crate) fn build_keeping(
files: &'a [(PathBuf, String)],
lead: &Path,
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
known: Option<&dyn KnownFacts>,
trace: &mut IndexTrace,
) -> Scope<'a> {
Scope::assemble(files, Some(lead), keep, known, trace)
}
fn assemble(
files: &'a [(PathBuf, String)],
lead: Option<&Path>,
keep: impl FnOnce(Option<&Semantics>) -> Vec<String>,
known: Option<&dyn KnownFacts>,
trace: &mut IndexTrace,
) -> Scope<'a> {
let mut sources: Vec<(&Path, &str)> =
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
// The same normalization `WorkspaceIndex::build` applies: a stable
// sort by path, then the first copy of a repeated path wins.
sources.sort_by(|a, b| a.0.cmp(b.0));
sources.dedup_by(|a, b| a.0 == b.0);
let mut building =
Building { builder: IndexBuilder::new(), kept: HashMap::new(), known, trace };
// The lead file first, so its analysis can be read before the rest are
// parsed. `IndexBuilder::finish` sorts by path, so feeding it out of
// order cannot reach the index.
let first = lead.and_then(|path| sources.iter().position(|(held, _)| *held == path));
if let Some(i) = first {
let (path, text) = sources[i];
building.take(i, path, text, Class::Lead);
}
let words = keep(first.and_then(|i| building.kept.get(&i)));
for (i, (path, text)) in sources.iter().enumerate() {
if Some(i) == first {
continue;
}
// Asked before the file is taken rather than after it — the same
// pure question of the same two values, moved so the class it
// answers decides what the build does with the file at all.
let wanted = words.iter().any(|word| text.contains(word.as_str()));
building.take(i, path, text, if wanted { Class::Kept } else { Class::Other });
}
let Building { builder, kept, trace, .. } = building;
let index = trace.merge.measure(|| builder.finish());
let ids: HashMap<&Path, FileId> = index
.files()
.iter()
.enumerate()
.map(|(i, path)| (path.as_path(), FileId(i as u32)))
.collect();
let file_ids = sources.iter().map(|(path, _)| ids.get(path).copied()).collect();
let base_names = BaseNames::of(sources.iter().map(|(p, _)| *p));
Scope { sources, index, file_ids, cache: HashMap::new(), kept, base_names }
}
pub(crate) fn len(&self) -> usize {
self.sources.len()
}
pub(crate) fn path(&self, i: usize) -> Option<&'a Path> {
self.sources.get(i).map(|(path, _)| *path)
}
pub(crate) fn text(&self, i: usize) -> Option<&'a str> {
self.sources.get(i).map(|(_, text)| *text)
}
pub(crate) fn file_id(&self, i: usize) -> Option<FileId> {
self.file_ids.get(i).copied().flatten()
}
pub(crate) fn index_of(&self, path: &Path) -> Option<usize> {
self.sources.iter().position(|(p, _)| *p == path)
}
/// The two analysis layers for one file, computed on first use.
///
/// The local half is the one the index build already made, when it was
/// kept; otherwise it is parsed here, exactly as it always was. The
/// external half is this scope's index resolved against it, and is
/// computed here either way — it cannot exist before the index does.
pub(crate) fn analysis(&mut self, i: usize) -> Option<&Analysis> {
let Scope { sources, index, cache, kept, .. } = self;
let text = sources.get(i).map(|(_, text)| *text)?;
Some(cache.entry(i).or_insert_with(|| {
let semantics =
kept.remove(&i).unwrap_or_else(|| analyze(&parse_source_tolerant(text).0, text));
let external = resolve_external(&semantics, index);
Analysis { semantics, external }
}))
}
/// One file's analysis, but only if it has already been computed — what
/// the verification pass reads while it also holds the index.
pub(crate) fn cached(&self, i: usize) -> Option<&Analysis> {
self.cache.get(&i)
}
/// One watched file's after-print inputs: the local analysis the
/// before-pass already computed, and its uses resolved against `index`.
///
/// A file the edits did not touch has the same declarations and the same
/// uses afterwards — its text did not change — so only what the workspace
/// answers *for* those uses can have moved, and re-resolving is the whole
/// of the difference. Re-parsing it to learn that is the work take 5 §P2c
/// removes.
///
/// `None` when that file's local analysis has not been computed. The
/// caller's own before-pass is what computes it, so that is a
/// contradiction rather than a fallback.
pub(crate) fn against(
&self,
i: usize,
index: &WorkspaceIndex,
) -> Option<(&Semantics, ExternalResolutions)> {
let semantics = &self.cached(i)?.semantics;
Some((semantics, resolve_external(semantics, index)))
}
/// The workspace index the edits were computed against.
pub(crate) fn index(&self) -> &WorkspaceIndex {
&self.index
}
/// How a file of this set is named in a message: its file name when no
/// other file in the set shares it, else the path the caller gave — two
/// `pwrmgr_if.sv` in one answer must name two findable files (§65.1
/// re-check R1). A front end makes the path relative as it does any other.
pub(crate) fn name_of(&self, path: &Path) -> String {
self.base_names.name(path)
}
/// [`Scope::name_of`] for the file at source index `i`.
pub(crate) fn name_at(&self, i: usize) -> String {
self.path(i).map_or_else(|| "?".to_string(), |path| self.name_of(path))
}
}
/// How a file is named in a message: its file name, because an absolute path
/// in a rename box is unreadable.
pub(crate) fn display(path: &Path) -> String {
path.file_name().and_then(|n| n.to_str()).unwrap_or("?").to_string()
}
/// How many files of a set share each file name, counted once so that
/// naming every file of a large set is linear, not quadratic (review M-2).
pub(crate) struct BaseNames(HashMap<OsString, usize>);
impl BaseNames {
/// The counts for the files at `all`.
pub(crate) fn of<'p>(all: impl IntoIterator<Item = &'p Path>) -> BaseNames {
let mut counts: HashMap<OsString, usize> = HashMap::new();
for path in all {
if let Some(base) = path.file_name() {
*counts.entry(base.to_os_string()).or_default() += 1;
}
}
BaseNames(counts)
}
/// [`display`] made unambiguous within the counted set: the file name
/// when no other path shares it, else the path as given. The one rule
/// [`Scope::name_of`] and a buffer-level planner (the port offers) both
/// name files by, so an offer and the refactoring it offers say the same
/// thing.
pub(crate) fn name(&self, path: &Path) -> String {
let shared = path.file_name().and_then(|b| self.0.get(b)).is_some_and(|&n| n > 1);
match shared {
true => path.display().to_string(),
false => display(path),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const FILES: [(&str, &str); 4] = [
("/w/sub.sv", "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n"),
("/w/top.sv", "module top;\n logic sig;\n sub u_sub (.clk(1'b0), .q(sig));\n assign u_sub.sig = 1'b0;\nendmodule\n"),
("/w/pkg.sv", "package pkg;\n localparam int SIG = 1;\nendpackage\n"),
("/w/user.sv", "import pkg::*;\nmodule user;\n localparam int X = SIG;\nendmodule\n"),
];
fn files() -> Vec<(PathBuf, String)> {
FILES.iter().map(|(p, t)| (PathBuf::from(*p), (*t).to_string())).collect()
}
/// Every declaration and use one analysis holds, as comparable text — the
/// whole observable of a `Semantics` plus its overlay.
fn print(analysis: &Analysis) -> String {
let mut out = String::new();
for symbol in analysis.semantics.symbols() {
out.push_str(&format!(
"sym {} {:?} {}..{}\n",
symbol.name, symbol.kind, symbol.name_span.start, symbol.name_span.end
));
}
for (id, reference) in analysis.semantics.references().iter().enumerate() {
out.push_str(&format!(
"ref {} {}..{} -> {:?} / {:?}\n",
reference.name,
reference.name_span.start,
reference.name_span.end,
reference.resolution,
analysis.external.get(vlog_semantic::ReferenceId(id as u32))
));
}
out
}
/// The scope's index is the index a plain `WorkspaceIndex::build` gives —
/// same fingerprint, same file ids — however the scope was assembled.
#[test]
fn assembling_the_scope_file_by_file_builds_the_same_index() {
let files = files();
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let plain = Scope::build(&files);
assert_eq!(plain.index().fingerprint(), built.fingerprint());
let keeping = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|_| vec!["sig".to_string()],
None,
&mut IndexTrace::default(),
);
assert_eq!(keeping.index().fingerprint(), built.fingerprint());
for i in 0..plain.len() {
assert_eq!(plain.file_id(i), keeping.file_id(i), "file ids move with retention");
assert_eq!(plain.path(i), keeping.path(i));
}
}
/// A retained analysis is the analysis the on-demand path would compute.
/// This is the whole of §P2b's correctness: what is kept is not a second
/// opinion, it is the same one, not thrown away.
#[test]
fn a_retained_analysis_is_the_one_the_on_demand_path_would_compute() {
let files = files();
let mut plain = Scope::build(&files);
let mut trace = IndexTrace::default();
let mut keeping = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|here| {
// Every word in play, so every file is retained.
assert!(here.is_some(), "the lead file's analysis is made first");
vec!["sig".to_string(), "pkg".to_string(), "u_sub".to_string()]
},
None,
&mut trace,
);
for i in 0..plain.len() {
let one = plain.analysis(i).map(print);
let two = keeping.analysis(i).map(print);
assert_eq!(one, two, "file {i} analyses differently when it is retained");
}
}
/// The lead file's analysis is made **before** the rest are parsed, which
/// is what lets a caller read the cursor's name off it and ask for that
/// name to be kept — without a second parse of anything.
#[test]
fn the_lead_files_analysis_is_available_to_the_retention_rule() {
let files = files();
let mut seen = None;
let mut trace = IndexTrace::default();
let scope = Scope::build_keeping(
&files,
Path::new("/w/user.sv"),
|here| {
seen = here.map(|semantics| semantics.symbols().len());
Vec::new()
},
None,
&mut trace,
);
assert_eq!(seen, Some(2), "`user` and `X` are what user.sv declares");
assert_eq!(scope.len(), 4);
}
/// **The R3b fingerprint proof.** An index part *reused* and part parsed is
/// the index every file's own text builds — same fingerprint, same file
/// ids — and the analyses it keeps are the same analyses either way.
///
/// This is the whole of the door's correctness at this level: a record
/// handed in by a caller who kept the promise is the record the parse
/// would have produced, so an index merged from a mixture of the two
/// cannot be told from one merged from either.
#[test]
fn an_index_part_reused_and_part_parsed_is_the_index_the_texts_build() {
/// A caller that knows `pkg.sv` and `user.sv`, read off their own text.
struct Two(Vec<(PathBuf, String, FileFacts)>);
impl KnownFacts for Two {
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
self.0
.iter()
.find(|(held, bytes, _)| held == path && bytes == text)
.map(|(_, _, facts)| facts.clone())
}
}
let files = files();
let known = Two(files
.iter()
.filter(|(path, _)| path.ends_with("pkg.sv") || path.ends_with("user.sv"))
.map(|(path, text)| (path.clone(), text.clone(), FileFacts::of(path.clone(), text)))
.collect());
assert_eq!(known.0.len(), 2, "premise: two of the four are known");
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut trace = IndexTrace::default();
let mut mixed = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|_| vec!["sig".to_string()],
Some(&known),
&mut trace,
);
assert_eq!(trace.reused_files, 2, "both known records were taken: {trace:?}");
assert_eq!(mixed.index().fingerprint(), built.fingerprint());
let mut plain = Scope::build(&files);
for i in 0..plain.len() {
assert_eq!(plain.file_id(i), mixed.file_id(i), "file ids move with reuse");
assert_eq!(plain.path(i), mixed.path(i));
assert_eq!(
plain.analysis(i).map(print),
mixed.analysis(i).map(print),
"file {i} analyses differently when its record is reused"
);
}
}
/// A caller that answers for nothing is the build as it always was — the
/// door is opt-in per file, not a mode.
#[test]
fn a_caller_that_knows_nothing_builds_exactly_what_it_always_did() {
struct Nothing;
impl KnownFacts for Nothing {
fn facts_for(&self, _path: &Path, _text: &str) -> Option<FileFacts> {
None
}
}
let files = files();
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut trace = IndexTrace::default();
let scope = Scope::build_keeping(
&files,
Path::new("/w/top.sv"),
|_| vec!["sig".to_string()],
Some(&Nothing),
&mut trace,
);
assert_eq!(trace.reused_files, 0);
assert_eq!(scope.index().fingerprint(), built.fingerprint());
}
/// A lead the scope does not hold is not an error: nothing is retained,
/// and the rest of the build is what it always was.
#[test]
fn a_lead_outside_the_scope_retains_nothing_and_still_builds() {
let files = files();
let built = WorkspaceIndex::build(files.iter().map(|(p, t)| (p.clone(), t.as_str())));
let mut asked = false;
let mut trace = IndexTrace::default();
let mut scope = Scope::build_keeping(
&files,
Path::new("/w/absent.sv"),
|here| {
asked = true;
assert!(here.is_none(), "there is no lead analysis to offer");
vec!["sig".to_string()]
},
None,
&mut trace,
);
assert!(asked, "the retention rule is asked either way");
assert_eq!(scope.index().fingerprint(), built.fingerprint());
assert!(scope.analysis(0).is_some(), "and every file still analyses on demand");
}
#[test]
fn a_file_name_another_file_shares_is_named_by_its_path() {
let paths = [Path::new("/a/x/if.sv"), Path::new("/a/y/if.sv"), Path::new("/a/top.sv")];
let names = BaseNames::of(paths);
assert_eq!(names.name(Path::new("/a/x/if.sv")), "/a/x/if.sv");
assert_eq!(names.name(Path::new("/a/y/if.sv")), "/a/y/if.sv");
assert_eq!(names.name(Path::new("/a/top.sv")), "top.sv");
assert_eq!(names.name(Path::new("/elsewhere/new.sv")), "new.sv", "outside the set");
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com