Files
lucisv/crates/vlog_semantic/src/workspace/update.rs
T
lucioandClaude Fable 5 b57ae35be4 Decomposition, lane D: vlog_semantic's bind.rs and workspace.rs, vlog_refactor's ports.rs and rename.rs become modules, a pure move
TODO section 28, lane D (the file-size rule in CLAUDE.md).
bind.rs (1 718 production lines) becomes bind/{mod, item, decl, class,
cover, stmt, sva, expr}.rs; workspace.rs (1 111) becomes workspace/
{mod, index, update, record, external}.rs with facts.rs and
FACTS_FORMAT untouched; ports.rs (1 391) becomes ports/{mod, find, add,
remove, propagate, list}.rs, one file per refactoring; rename.rs (760)
becomes rename/{mod, scope, warnings, tests}.rs. No function split, no
file over 600 production lines (largest add.rs at 432), every public
path unchanged (crate-root doc pages identical; only private-module
pages relocated). Carved by a range manifest that had to tile the
original byte for byte. Proof: per-binary test counts identical
(vlog_semantic 345 / 17, vlog_refactor 206 / 5, workspace 3 215 / 48),
corpus --stdout byte-identical, and the lucisv check finding lists
byte-identical between this build and the base over the corpus and the
opentitan hw tree - done by the dev and redone from scratch by QA.

docs/features/decomposition-semantic/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 21:55:55 -07:00

398 lines
18 KiB
Rust

//! How an index changes after it is built: replace one file's record, add
//! or remove a file, absorb a batch — each producing exactly the index a full
//! build over the same records would — the [`WorkspaceIndex::merge`] that
//! makes that hold by construction, and the [`WorkspaceIndex::fingerprint`]
//! that proves it.
use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use super::external::{resolve_fact, ExternalTarget};
use super::record::{facts_of, FileFacts, ReferenceFact};
use super::{
DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex,
};
impl WorkspaceIndex {
/// Replace one file's contribution to the index — or add the file, when
/// the index does not hold it yet.
///
/// **The result is the index a full [`WorkspaceIndex::build`] over the same
/// file set would have produced, byte for byte**: same [`FileId`]s, same
/// disambiguation order, same member tables, same edges. That is the whole
/// contract, and it is what makes an incremental server safe. It holds by
/// construction rather than by care — the merge below is `finish`'s own
/// loop, over the same path-sorted records, restricted to the names this
/// file could have moved.
///
/// A [`FileId`] is a position in the path-sorted file list and nothing
/// else, so **adding a file renumbers the ones after it**. That is
/// deliberate: an id that meant a different thing depending on how the
/// index was arrived at would make "the same index" unprovable, and the
/// renumbering costs one merge pass over records already in memory — no
/// file is read and no file is re-parsed. Ids do not survive an add or a
/// remove; nothing in this workspace holds one across an update (the
/// server refreshes every overlay after it, exactly as it does after a
/// rebuild).
pub fn update_file(&mut self, path: PathBuf, src: &str) {
self.update_facts(facts_of(path, src));
}
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
/// known — read from a cache, or from an analysis the caller already holds
/// ([`FileFacts::from_analysis`]) — so the update costs no parse at all.
///
/// Exactly [`WorkspaceIndex::update_file`] with the parse already done, the
/// same way [`IndexBuilder::add_facts`](super::IndexBuilder::add_facts) is
/// [`IndexBuilder::add_file`](super::IndexBuilder::add_file) with
/// the parse already done: same contract, same result. Whether the record
/// really describes the file is the caller's business.
pub fn update_facts(&mut self, facts: FileFacts) {
let path = facts.path.clone();
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
// The common case — a saved file the index already holds. Only the
// names this file declared before or declares now can have moved,
// and the file list has not, so ids are untouched.
Ok(at) => {
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
self.facts[at] = facts;
self.merge(Some(&affected));
}
// A file the index did not hold: every id from here on shifts, so
// every table is rebuilt from the records. No parse, no read.
Err(at) => {
self.files.insert(at, path);
self.facts.insert(at, facts);
self.merge(None);
}
}
}
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
/// many files at once — and for **one** merge rather than one each.
///
/// Same contract as both — what comes out is the index a full
/// [`WorkspaceIndex::build`] over the records it now holds would have
/// produced — **provided each path appears once in `records`**. It holds
/// for the same reason theirs does: the records are kept path-sorted and
/// one file to a path, and [`WorkspaceIndex::merge`] is then the same loop
/// [`IndexBuilder::finish`](super::IndexBuilder::finish) runs over the
/// same list. A batch that names one path twice is an update applied
/// twice, so the **last** record wins,
/// where a `build` over the same duplicated input keeps the *first*
/// (`index_order` dedups) — the update semantic is the right one for an
/// "absorb what changed" API, and the one caller that feeds a scan
/// (`Scan::work`) is deduped before anything is staged. QA pinned the
/// divergence
/// (`absorbing_a_batch_with_a_duplicate_path_diverges_from_a_build_over_the_same_records`).
///
/// One merge, because a merge is a pass over **every** record the index
/// holds: a scan that merged after each of its files would be quadratic in
/// the size of the workspace, which is measured rather than argued in
/// `docs/features/scan-interleave/README.md`. A caller feeding a scan
/// therefore batches — it stages records as it takes them and folds a
/// batch in only when something is about to read the index.
///
/// `gone` is dropped first, so a path in both lists ends up held: a file
/// that moved out of one scan's scope and back into the next's is one
/// file, not a removal that happens to run second.
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
for path in gone {
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
self.files.remove(at);
self.facts.remove(at);
}
}
for facts in records {
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
Ok(at) => self.facts[at] = facts,
Err(at) => {
self.files.insert(at, facts.path.clone());
self.facts.insert(at, facts);
}
}
}
self.merge(None);
}
/// Drop one file from the index, reporting whether it was there.
///
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
/// index a full build over the remaining files would have produced.
pub fn remove_file(&mut self, path: &Path) -> bool {
let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) else {
return false;
};
self.files.remove(at);
self.facts.remove(at);
self.merge(None);
true
}
/// Every observable this index answers, rendered as one comparable value.
///
/// The witness for the equivalence [`WorkspaceIndex::update_file`]
/// promises: two indexes are the same index exactly when their
/// fingerprints are equal. Public because the proof is worth writing in
/// more than one crate's tests — `lucisv_server` checks it against the
/// real corpus, this crate against crafted attacks.
pub fn fingerprint(&self) -> String {
let mut out = String::new();
for (id, path) in self.files.iter().enumerate() {
let defines = self.defines(FileId(id as u32)).map_or(0, |t| t.entries().len());
// The census's size, on the same rule the `define` table follows:
// the words themselves are per-file and never merged, so a count
// is enough to catch the failure a fingerprint exists to catch —
// a record lost, duplicated or attached to the wrong file.
let words = self.facts.get(id).map_or(0, |facts| facts.words.len());
out.push_str(&format!(
"file {id} {} defines={defines} words={words}\n",
path.display()
));
}
for symbol in self.workspace_symbols("") {
out.push_str(&format!(
"sym {} in {:?} {:?} {}:{}..{} decl={}..{} line={} detail={:?} at={:?} type={:?}\n",
symbol.name,
symbol.container,
symbol.def.kind,
symbol.def.file.0,
symbol.def.name_span.start,
symbol.def.name_span.end,
symbol.def.decl_span.start,
symbol.def.decl_span.end,
symbol.def.lines.name,
symbol.def.lines.detail,
symbol.def.lines.positions,
symbol.def.type_name
));
}
for (definition, sites) in &self.reference_sites {
for site in sites {
out.push_str(&format!(
"ref {}:{}..{} <- {}:{}..{}\n",
definition.file.0,
definition.name_start,
definition.name_end,
site.file.0,
site.name_span.start,
site.name_span.end
));
}
}
let mut ambiguous: Vec<DefinitionKey> = self.ambiguous_references.iter().copied().collect();
ambiguous.sort();
for definition in ambiguous {
out.push_str(&format!(
"ambiguous-ref {}:{}..{}\n",
definition.file.0, definition.name_start, definition.name_end
));
}
for (name, edges) in self.instantiations() {
for edge in edges {
out.push_str(&format!(
"inst {name} {} in {}@{}..{} site {}..{}\n",
edge.file.0,
edge.owner.name,
edge.owner.name_span.start,
edge.owner.span.end,
edge.site_span.start,
edge.site_span.end
));
for instance in &edge.instances {
out.push_str(&format!(
" instance {} name {}..{} span {}..{} at {:?} {:?}\n",
instance.name,
instance.name_span.start,
instance.name_span.end,
instance.span.start,
instance.span.end,
instance.name_positions,
instance.positions
));
}
}
}
for (name, edges) in self.subclasses() {
for edge in edges {
out.push_str(&format!(
"extends {name} {} {}@{}..{}\n",
edge.file.0,
edge.subclass.name,
edge.subclass.name_span.start,
edge.subclass.span.end
));
}
}
out
}
/// Rebuild the merged tables from the per-file records.
///
/// `affected` names the keys that may have moved; `None` means all of
/// them. Either way this is one loop over the path-sorted records pushing
/// in the order it meets them, which is the *only* place any table's order
/// is decided — so a restricted merge and a whole one agree by
/// construction, and both agree with [`IndexBuilder::finish`](super::IndexBuilder::finish).
pub(super) fn merge(&mut self, affected: Option<&Affected>) {
match affected {
None => {
self.units.clear();
self.members.clear();
self.instantiations.clear();
self.subclasses.clear();
self.macro_definitions.clear();
}
Some(affected) => {
for name in &affected.units {
self.units.remove(name);
}
for name in &affected.containers {
self.members.remove(name);
}
for name in &affected.modules {
self.instantiations.remove(name);
}
for name in &affected.bases {
self.subclasses.remove(name);
}
for name in &affected.macros {
self.macro_definitions.remove(name);
}
}
}
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for decl in &facts.units {
if affected.is_some_and(|a| !a.units.contains(&decl.name)) {
continue;
}
self.units.entry(decl.name.clone()).or_default().push(decl.def(file));
}
for (unit, decl) in &facts.members {
if affected.is_some_and(|a| !a.containers.contains(unit)) {
continue;
}
self.members
.entry(unit.clone())
.or_default()
.entry(decl.name.clone())
.or_default()
.push(decl.def(file));
}
for (module, edge) in &facts.instantiations {
if affected.is_some_and(|a| !a.modules.contains(module)) {
continue;
}
self.instantiations.entry(module.clone()).or_default().push(InstantiationEdge {
file,
owner: edge.owner.clone(),
site_span: edge.site_span,
instances: edge.instances.clone(),
});
}
for (base, subclass) in &facts.subclasses {
if affected.is_some_and(|a| !a.bases.contains(base)) {
continue;
}
self.subclasses
.entry(base.clone())
.or_default()
.push(InheritanceEdge { file, subclass: subclass.clone() });
}
for (entry, define) in facts.defines.entries().iter().enumerate() {
if define.kind != DefineKind::Define
|| affected.is_some_and(|a| !a.macros.contains(&define.name))
{
continue;
}
self.macro_definitions.entry(define.name.clone()).or_default().push((file, entry));
}
}
// The reverse inheritance edge is rebuilt whole every time, whatever
// `affected` says: it is one entry per `extends` written anywhere (a
// few thousand on opentitan), and rebuilding it is both cheaper to
// reason about and the reason a restricted merge cannot leave it
// half-updated. First in file order wins, which is `units`' rule.
self.bases.clear();
for facts in &self.facts {
for (base, subclass) in &facts.subclasses {
self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone());
}
}
// A changed declaration can change how references in any file resolve,
// even when only one file's facts moved. Re-resolving compact facts is
// one in-memory pass; no source is read or parsed.
self.merge_references();
}
/// Rebuild declaration-to-occurrence postings from compact per-file facts.
fn merge_references(&mut self) {
let mut sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>> = BTreeMap::new();
let mut ambiguous: HashSet<DefinitionKey> = HashSet::new();
for (id, facts) in self.facts.iter().enumerate() {
let file = FileId(id as u32);
for reference in &facts.references {
let site = ReferenceSite { file, name_span: reference.occurrence() };
match reference {
ReferenceFact::Local { definition, .. } => {
let key = DefinitionKey {
file,
name_start: definition.start,
name_end: definition.end,
};
sites.entry(key).or_default().push(site);
}
ReferenceFact::External { name, base, paths, .. } => {
match resolve_fact(self, name, base.as_deref(), paths) {
ExternalTarget::Resolved(def) => {
sites.entry(DefinitionKey::of(&def)).or_default().push(site);
}
ExternalTarget::Ambiguous(defs) => {
ambiguous.extend(defs.iter().map(DefinitionKey::of));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
}
self.reference_sites = sites;
self.ambiguous_references = ambiguous;
}
}
/// The table keys one file's records can move, so a merge after replacing that
/// file can leave every other key alone.
#[derive(Debug, Default)]
pub(super) struct Affected {
units: HashSet<String>,
/// Keys of the `members` table — the *unit* a member is exported by, not
/// the member itself. A whole unit's sub-table is the smallest thing worth
/// rebuilding: one file adding a member to a package cannot move any other
/// package.
containers: HashSet<String>,
modules: HashSet<String>,
bases: HashSet<String>,
macros: HashSet<String>,
}
impl Affected {
fn of(facts: &FileFacts) -> Affected {
let mut out = Affected::default();
out.add(facts);
out
}
fn add(&mut self, facts: &FileFacts) {
self.units.extend(facts.units.iter().map(|decl| decl.name.clone()));
self.containers.extend(facts.members.iter().map(|(unit, _)| unit.clone()));
self.modules.extend(facts.instantiations.iter().map(|(module, _)| module.clone()));
self.bases.extend(facts.subclasses.iter().map(|(base, _)| base.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
}