Release 0.65.6: saving a file no longer re-indexes the workspace
ci / checks (push) Successful in 59s
ci / corpus (push) Successful in 16s
release / build-and-publish (push) Failing after 4m55s

TODO §71.1. On OpenTitan hw (4 058 files) every save cost ~160 ms of
whole-index work, twice (the save and VS Code's watcher echo), and watcher
events for files the index could not hold started whole rescans.

- vlog_semantic: resolution records every table lookup per reading file,
  misses included (workspace/dependents.rs, references.rs, replace.rs); an
  update re-resolves the edited file and the readers of keys whose values
  changed in what resolution reads. An unchanged record merges nothing. When
  the readers hold more than an eighth of all references, old results are
  removed in one pass over the postings.
- lucisv_server: watcher events are classified per file (state/watched.rs);
  the include graph keeps every include line as written and re-resolves the
  lines a named path could satisfy, in one pass per event; an event naming
  more paths than half the index takes the single rescan; an open buffer the
  index does not hold joins on its first save; completion tables are rebuilt
  only for the names a file declares. Every save still republishes every open
  buffer. The line-length lint follows the formatting style's width.
- Fixed on the way: removing an included header left other files' include
  edges pointing at it.

Typical saves: comment or watcher echo <0.3 ms, local signal 4 ms, package
member 12 ms; warm startup +40..120 ms for the readers table.

QA failed the first cut on four stale answers found with an independent
fresh-server oracle; all four are fixed and are differential tests. Dev
(three rounds), QA (two rounds) and lead review:
docs/features/localized-reindex/README.md. TODO.md files lane 71.7 from
what the QA rounds and an investigation found in earlier releases too.

Version bump (Cargo.toml, Cargo.lock, editors/vscode/package.json and both
package-lock.json spots); notes in CHANGELOG.md (## 0.65.6) and
editors/vscode/CHANGELOG.md.

Gates: tools/gates.sh PASS on this tree; vlog_semantic 435/0,
lucisv_server 2011/0, lucisv_mcp 384/0.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
This commit is contained in:
Guoliang ChenandClaude Mythos 5.2 committed 2026-11-19 08:52:01 -08:00
1 parent 80017a59f2
commit 58d3db3e3c
36 files changed
+4536 -323

No files matched your search

+56
View File
@@ -4,6 +4,62 @@ All notable changes to lucisv are recorded here. Versions follow
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
(see `README.md`) are the only frozen contract.
## 0.65.6 — 2026-11-19
### Saving a file no longer re-indexes the workspace
(`docs/features/localized-reindex`; TODO §71.1. Measured on OpenTitan's `hw`
tree, 4 058 files, with the server driven the way VS Code drives it.)
- **What was happening.** Every save cost about 160 ms of whole-index work
whatever was edited — 117 ms of it re-resolving all 470 000 cross-file
references — and VS Code triggered it twice, once for the save and once for
its own file watcher. Watcher events for files the index could not hold (a
generated file in a gitignored directory, a file outside the filelist or
folder scope, a held file reported through a symlinked root or in another
letter case) started a whole rescan with the progress bar, 270–750 ms.
- **Now the index does only what the edit can reach.**
| edit, then save | before | now |
|---|---:|---:|
| a comment, or the watcher's echo of any save | ~160 ms | under 0.3 ms |
| a local signal in `uart_tx` or `prim_flop` | ~170 ms | 4 ms |
| a member added to `uart_reg_pkg` | ~167 ms | 12 ms |
| a line above a module 125 files instantiate | ~163 ms | 47 ms |
| a member added to a package 677 files import | ~162 ms | 92 ms |
| a watcher event for a file outside the scope | up to 746 ms, with the bar | 3.5 ms |
The index records which names each file looked up — including the ones it
did not find — and re-resolves only the readers of names whose meaning
changed. A save whose index record is unchanged merges nothing.
- **Still wide, on purpose.** Adding or deleting a file; a burst of more
files in one watcher event than half the index holds (a branch switch),
which takes the one rescan it always did; an edit above a declaration many
files use. Every save still re-checks every open file's diagnostics, so a
`lucisv.toml` or waiver edit takes effect at the next save as before — with
200 files open that is most of a save (53 ms, against ~205 ms before).
- **The price.** Every whole rescan costs a few per cent more for the table
that makes the rest cheap: warm OpenTitan startup is 40–120 ms slower,
depending on machine load.
- **How it is known to be right.** After any sequence of edits, everything
the server answers must equal what a freshly started server answers for the
same files. QA built that oracle independently and it failed the first cut
on four stale answers (include links to headers outside the scope, lint
configuration, a file-age check macOS defeats, excluded open buffers); all
four are fixed and are now tests. The final build: 312 hand-written
comparisons and twelve random 300–500-step runs over the corpus and
OpenTitan with no divergence it caused.
- **Also.** The language server's `line-length` lint now follows the chosen
formatting style's width (80 under `ansi` and `nxp`, 120 under
`microsoft`), closing the limit noted in 0.65.5. Removing an included
header no longer leaves other files' include links pointing at it.
- **Known, and next.** Found by this round's QA and present in earlier
releases too: an edit made while a whole rescan is running can be applied
out of order, leaving the server's copy of the buffer wrong until the file
is reopened; a watcher event that names only a directory leaves stale
state; an excluded file stays indexed after it is closed. These are the
next round's work.
## 0.65.5 — 2026-11-19
### Named formatting styles
Generated
+9 -9
View File
@@ -97,7 +97,7 @@ dependencies = [
[[package]]
name = "lucisv"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"lucisv_core",
"rayon",
@@ -108,11 +108,11 @@ dependencies = [
[[package]]
name = "lucisv_core"
version = "0.65.5"
version = "0.65.6"
[[package]]
name = "lucisv_mcp"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"lucisv_core",
"serde",
@@ -126,7 +126,7 @@ dependencies = [
[[package]]
name = "lucisv_server"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"lsp-server",
"lsp-types",
@@ -262,14 +262,14 @@ checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "vlog_formatter"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"vlog_parser",
]
[[package]]
name = "vlog_linter"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"lucisv_core",
"vlog_formatter",
@@ -279,11 +279,11 @@ dependencies = [
[[package]]
name = "vlog_parser"
version = "0.65.5"
version = "0.65.6"
[[package]]
name = "vlog_refactor"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"vlog_formatter",
"vlog_parser",
@@ -292,7 +292,7 @@ dependencies = [
[[package]]
name = "vlog_semantic"
version = "0.65.5"
version = "0.65.6"
dependencies = [
"vlog_parser",
]
+1 -1
View File
@@ -13,7 +13,7 @@ members = [
]
[workspace.package]
version = "0.65.5"
version = "0.65.6"
authors = ["Guoliang Chen"]
edition = "2021"
license = "MIT"
+24 -2
View File
@@ -7315,7 +7315,8 @@ the OpenTitan tree (not only on unit fixtures) before it is called done.
The items are the owner's words, lightly condensed; each gets its own
subsection, plan and `docs/features/<name>/README.md` when its turn comes.
- [ ] **71.1 An edit does not re-index the whole database.** Today every
- [x] **71.1 An edit does not re-index the whole database.** (0.65.6, `docs/features/localized-reindex`)
Today every
file edit re-indexes everything. A change to a `define` may have to;
a typical, localized edit must not.
- [ ] **71.2 Actions stay fast on a huge, heavily-dependent tree.** Do the
@@ -7399,8 +7400,29 @@ indexing, collide with each other and with §70's test files, and wait for
formatter should not need it.
- [ ] `` `ifdef `` between `end` and `else` is a parse error.
- [ ] An attribute on an ANSI port (`(* keep *) input a`) is a parse error.
- [ ] The server's `line-length` lint falls back to 100 columns under the
- [x] The server's `line-length` lint falls back to 100 columns under the
`ansi`/`microsoft`/`nxp` styles (`lucisv_server/src/lint.rs`); taken
when 71.1 merges.
- [ ] One-per-line styles give multi-instance declarations
(`p1 u8 (...), u9 (...)`) the hanging layout.
- Wave 5 (lead, 2026-11-19): 71.1 shipped as 0.65.6 after a QA FAIL (four
stale answers), a fix round, a QA pass and a last small round. What the
QA rounds and a read-only investigation turned up, all present before this
wave, becomes lane **71.7** (the owner's Find References item, widened):
- [ ] A caret just past an identifier's last letter asks about the next
character: references, definition, hover and highlight come back
empty (`server/dispatch.rs` `Server::offset`). This is the owner's
"not found, then works after clicking back".
- [ ] A `didChange` arriving during a whole rescan can overtake an older
one still queued (`server/mod.rs` `process_batch`): with incremental
sync the server's buffer is corrupted until the file is reopened.
- [ ] A burst `[request, didOpen]` during the startup scan is re-held at
every file (`server/index.rs` `answer_what_is_waiting`): the scan
takes ~300 s on OpenTitan instead of ~1.7 s.
- [ ] A watcher event naming only a directory leaves stale state; an
excluded buffer stays indexed after close; symlinked files are held
under one or both spellings depending on what was open.
71.3 (viewport highlighting) passed QA with a gap in the default folder
scope (colours wait out a widen, ~630 ms); it is rebased after 71.7 and
closes that in its fix round. Then 71.2.
+105 -9
View File
@@ -197,17 +197,86 @@ impl Candidates {
/// patched: this file's old words are given back and its new ones taken,
/// so nothing else is re-lexed. The result is what a whole
/// [`Candidates::build`] over the same files would have produced.
#[cfg(test)]
pub fn update_file(&mut self, index: &WorkspaceIndex, path: &Path, text: &str) {
self.update_words(index, path, words_in(text));
}
/// [`Candidates::update_file`] for a file whose words the caller already
/// has — an open buffer's, read off the tokens it was analyzed from.
#[cfg(test)]
pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec<String>) {
self.take_index_tables(index);
self.set_words(path, words);
}
/// [`Candidates::update_words`] in two halves, for a caller that knows
/// which it needs: the word table patched by this file alone…
pub fn set_file_words(&mut self, path: &Path, words: Vec<String>) {
self.set_words(path, words);
}
/// …and the two index-derived tables re-derived for the names one file declared
/// before or declares now — `symbols` its units and connection members,
/// `macros` its `` `define``s ([`FileFacts::declared_names`]) — which are
/// the only entries its update can move.
///
/// Exact because every table here is one block per exact name ([`word_cmp`]
/// is total, so equal keys are equal names) and each block is read off
/// the index for that name alone: the unit block from the symbol listing
/// restricted to the name, in the listing's order and deduplicated the
/// same way; a module name present exactly when some unit of it is
/// instantiable; a macro's entry from its first definition in file order.
/// So a block re-derived here is the block a whole re-derivation gives,
/// and every other block is untouched by an update that does not name it.
///
/// [`FileFacts::declared_names`]: vlog_semantic::FileFacts::declared_names
pub fn refresh_names(
&mut self,
index: &WorkspaceIndex,
symbols: &HashSet<&str>,
macros: &HashSet<&str>,
) {
let (fresh, _) = unit_tables(index, index.symbols_named(symbols));
let mut held = std::mem::take(&mut self.units);
held.retain(|unit| !symbols.contains(unit.name.as_str()));
self.units = merge_by_name(held, fresh, |unit| unit.name.as_str());
self.unit_masks = self.units.iter().map(|unit| char_mask(&unit.name)).collect();
for name in symbols {
let instantiable = index.units(name).iter().any(|def| def.kind.is_instantiable());
match (self.modules.binary_search_by(|held| held.as_str().cmp(name)), instantiable) {
(Ok(at), false) => {
self.modules.remove(at);
}
(Err(at), true) => self.modules.insert(at, name.to_string()),
_ => {}
}
}
let mut fresh: Vec<Macro> = macros
.iter()
.filter_map(|name| index.find_define(name).first().map(|(_, define)| macro_of(define)))
.collect();
sort_by_name(&mut fresh, |m| m.name.as_str());
let mut held = std::mem::take(&mut self.macros);
held.retain(|m| !macros.contains(m.name.as_str()));
self.macros = merge_by_name(held, fresh, |m| m.name.as_str());
}
/// Every table, rendered for comparison — the equivalence witness the
/// incremental tests hold an updated workspace to a rebuilt one with.
#[cfg(test)]
pub fn fingerprint(&self) -> String {
let mut word_files: Vec<(&String, &usize)> = self.word_files.iter().collect();
word_files.sort();
let mut per_file: Vec<(&PathBuf, &Vec<String>)> = self.per_file.iter().collect();
per_file.sort();
format!(
"units {:?}\nunit_masks {:?}\nmodules {:?}\nmacros {:?}\nwords {:?}\n\
word_masks {:?}\nword_files {word_files:?}\nper_file {per_file:?}\n",
self.units, self.unit_masks, self.modules, self.macros, self.words, self.word_masks
)
}
/// [`Candidates::update_words`] for a batch of files — the form a scan
/// publishing what it has indexed so far uses.
///
@@ -715,7 +784,15 @@ fn char_mask(text: &str) -> u32 {
/// tables want the same records. It is paid once per index build rather than
/// once per keystroke, which is the whole point of both.
fn index_tables(index: &WorkspaceIndex) -> (Vec<Candidate>, Vec<String>) {
let symbols = index.workspace_symbols("");
unit_tables(index, index.workspace_symbols(""))
}
/// [`index_tables`] over a given part of the symbol listing — all of it, or
/// the names one update touched — in the listing's own order.
fn unit_tables(
index: &WorkspaceIndex,
symbols: Vec<vlog_semantic::WorkspaceSymbol<'_>>,
) -> (Vec<Candidate>, Vec<String>) {
// `workspace_symbols` sorts by name first — with `str`'s own `Ord`, not a
// case-folded one — so same-named declarations are already adjacent and a
// plain `dedup` leaves one entry per module name, in `str` order. That is
@@ -757,14 +834,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
for id in 0..index.files().len() {
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
out.push(Macro {
name: define.name.clone(),
detail: format!("`define {}{args}", define.name),
});
out.push(macro_of(define));
}
}
sort_by_name(&mut out, |m| m.name.as_str());
@@ -772,6 +842,31 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
out
}
/// One `` `define``'s completion entry.
fn macro_of(define: &vlog_parser::defines::Define) -> Macro {
let args = match &define.params {
Some(params) => format!("({})", params.join(", ")),
None => String::new(),
};
Macro { name: define.name.clone(), detail: format!("`define {}{args}", define.name) }
}
/// Two lists sorted by [`word_cmp`] with no name in common, as one.
fn merge_by_name<T>(held: Vec<T>, fresh: Vec<T>, name: impl Fn(&T) -> &str) -> Vec<T> {
let mut out = Vec::with_capacity(held.len() + fresh.len());
let mut fresh = fresh.into_iter().peekable();
for item in held {
while let Some(next) =
fresh.next_if(|next| word_cmp(name(next), name(&item)) == Ordering::Less)
{
out.push(next);
}
out.push(item);
}
out.extend(fresh);
out
}
/// Every distinct identifier one file's token stream contains.
///
/// **`vlog_semantic::words::harvest_text`, under this crate's old name.** The
@@ -786,6 +881,7 @@ fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
/// one pass at the end: no part of a scan may be longer than one file, or the
/// message queue goes unanswered for the length of it
/// (`docs/features/scan-interleave/README.md`).
#[cfg(test)]
pub(crate) fn words_in(text: &str) -> Vec<String> {
words::harvest_text(text)
}
+102 -20
View File
@@ -86,7 +86,7 @@ fn include_on_line(line: &str, base: u32) -> Option<Include> {
///
/// Rebuilt whole on every index rebuild, from the same source list — and
/// patched one file at a time when only one file's text moved
/// ([`IncludeGraph::update_file`]).
/// ([`IncludeGraph::update_held`]).
#[derive(Debug, Default, Clone)]
pub struct IncludeGraph {
/// The `+incdir+` directories of the configured filelist, in filelist
@@ -107,6 +107,11 @@ pub struct IncludeGraph {
/// a single file — which is what makes an incrementally widened graph
/// byte-identical to a rebuilt one (`docs/features/index-scope/README.md`).
raw: HashMap<PathBuf, Vec<PathBuf>>,
/// Every held file's `` `include`` lines as written, resolved or not — so
/// a file appearing or vanishing anywhere on disk can be answered by
/// re-resolving just the lines that could name it
/// ([`IncludeGraph::refresh_naming`]), without reading a file.
lines: HashMap<PathBuf, Vec<Include>>,
/// Every in-scope file, exactly as the index spells it.
known: HashSet<PathBuf>,
/// Lower-cased spelling → the one in-scope file that has it, or `None`
@@ -154,29 +159,81 @@ impl IncludeGraph {
graph
}
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
/// Re-scan one file's `` `include``s, the rest of the graph left standing —
/// for a file whose text changed while the file set did not, a save of a
/// file the index already holds. The known-file and folded-spelling tables
/// are a function of the file set, and every other file's edges a function
/// of its own text and those tables, so only this file's edges are
/// re-scanned and re-spelled (`docs/features/localized-reindex/README.md`).
///
/// `known` is the index's file list as it stands *after* the update, which
/// is what the known-file and folded-spelling tables are: cheap to rebuild
/// from a list already in memory, and wrong to leave stale when a file has
/// come or gone.
///
/// One honest limit, and the reason the incremental path in `state.rs`
/// takes it only for a file that already existed: an edge of a *different*
/// file is not re-**resolved** against the disk. So a file appearing or
/// vanishing on disk does not change whether some other file's
/// `` `include "x.svh"`` finds anything until the next whole rebuild. Every
/// held edge *is* re-spelled against the new file list, because that half
/// costs no filesystem call — see [`IncludeGraph::respell`]. For the case
/// this is used in — one file's text changed, the file set did not — there
/// is nothing stale at all.
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
self.relearn(known);
/// Until 2026-11-19 this was `update_file`, which also re-learned both
/// tables and re-spelled every edge — O(files) for an answer that cannot
/// move. Its one honest limit is unchanged: an edge of a *different* file
/// is not re-**resolved** against the disk, which is why the incremental
/// path takes only a file the index already holds.
pub fn update_held(&mut self, path: &Path, text: &str) {
self.rescan_edges(path, text);
self.respell();
self.respell_one(path);
}
/// [`IncludeGraph::update_file`] for a batch of files whose `` `include``
/// Re-resolve the `` `include`` lines of every held file that writes one
/// whose last component could be `path`'s name — the only lines a file
/// appearing, vanishing or moving at `path` can change the answer of,
/// whether or not `path` is in scope: an include is resolved against the
/// disk, not against the scope (`docs/features/localized-reindex`, QA F1).
///
/// The name is compared case-insensitively, so a case-insensitive disk is
/// covered, and a target with no last component (`..`) counts as naming
/// everything. Reads no file: the lines are held.
pub fn refresh_naming(&mut self, path: &Path) {
self.refresh_naming_all(std::slice::from_ref(&path.to_path_buf()));
}
/// [`IncludeGraph::refresh_naming`] for every path of one watcher event
/// at once: one pass over the held lines for the whole set of names, so a
/// burst of ten thousand generated files costs one pass, not ten thousand
/// (QA R2-1). A line is re-resolved exactly when it would have been for
/// one of the paths alone, and re-resolving a file twice gives what once
/// does, so the batch is the same answer.
pub fn refresh_naming_all(&mut self, paths: &[PathBuf]) {
let folded = |name: &std::ffi::OsStr| name.to_string_lossy().to_lowercase();
let names: HashSet<String> =
paths.iter().filter_map(|path| path.file_name()).map(folded).collect();
if names.is_empty() {
return;
}
let could_name = |include: &Include| {
Path::new(&include.target).file_name().is_none_or(|last| names.contains(&folded(last)))
};
let mut naming: Vec<PathBuf> = self
.lines
.iter()
.filter(|(_, lines)| lines.iter().any(could_name))
.map(|(from, _)| from.clone())
.collect();
naming.sort();
for from in naming {
let lines = self.lines.get(&from).cloned().unwrap_or_default();
self.rescan_found(&from, &lines);
self.respell_one(&from);
}
}
/// Re-spell one file's edges from its raw ones.
fn respell_one(&mut self, path: &Path) {
match self.raw.get(path) {
Some(targets) => {
let spelled =
targets.iter().map(|to| self.as_the_index_spells_it(to.clone())).collect();
self.edges.insert(path.to_path_buf(), spelled);
}
None => {
self.edges.remove(path);
}
}
}
/// [`IncludeGraph::update_held`] for a batch of files whose `` `include``
/// lines have already been read, with the `+incdir+`s the scope resolves
/// to right now — the form a scan publishing what it has indexed so far
/// uses. The lines come from the step that indexed each file, for the
@@ -203,11 +260,29 @@ impl IncludeGraph {
self.respell();
}
/// Take `path` into the file set: known, folded, and every held edge
/// re-spelled against the new set — what [`IncludeGraph::from_includes`]
/// over the old set and `path` would have learned. Its own edges are
/// [`IncludeGraph::update_held`]'s business.
pub fn add_known(&mut self, path: &Path) {
if !self.known.insert(path.to_path_buf()) {
return;
}
if let Some(key) = path.to_str().map(str::to_lowercase) {
self.folded
.entry(key)
.and_modify(|found| *found = None)
.or_insert_with(|| Some(path.to_path_buf()));
}
self.respell();
}
/// Drop one file from the graph: its own edges, and its place among the
/// known files.
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
self.relearn(known);
self.raw.remove(path);
self.lines.remove(path);
self.respell();
}
@@ -223,6 +298,10 @@ impl IncludeGraph {
fn rescan_found(&mut self, path: &Path, found: &[Include]) {
let targets: Vec<PathBuf> =
found.iter().filter_map(|include| self.found(Some(path), include)).collect();
match found.is_empty() {
true => self.lines.remove(path),
false => self.lines.insert(path.to_path_buf(), found.to_vec()),
};
match targets.is_empty() {
true => self.raw.remove(path),
false => self.raw.insert(path.to_path_buf(), targets),
@@ -425,6 +504,9 @@ impl IncludeGraph {
let mut raw: Vec<(&PathBuf, &Vec<PathBuf>)> = self.raw.iter().collect();
raw.sort();
out.push_str(&format!("raw {raw:?}\n"));
let mut lines: Vec<(&PathBuf, &Vec<Include>)> = self.lines.iter().collect();
lines.sort_by_key(|(path, _)| *path);
out.push_str(&format!("lines {lines:?}\n"));
out
}
}
+86 -1
View File
@@ -304,7 +304,17 @@ fn configured(
}
}
options.overlay(&client.lint_options);
let width = file.line_length.or(client.line_length).unwrap_or(DEFAULT_LINE_LENGTH);
// The formatter's width ladder, so a line lucisv wrote is never a line
// lucisv calls too long: an explicit width (`lucisv.toml`, then the
// editor), else the chosen style's width (`lucisv.toml`'s `style`, then
// `lucisv.format.style`), else the default. `auto` names no preset and so
// no width — it falls through to the default, as it does in the
// formatter (`docs/features/format-styles/README.md`, Handshakes).
let styled = file.format_style.or(client.style).and_then(vlog_formatter::style::preset);
let width = file
.line_length
.or(client.line_length)
.unwrap_or_else(|| styled.map_or(DEFAULT_LINE_LENGTH, |style| style.line_length));
(options, width, file, problems)
}
@@ -731,6 +741,81 @@ mod tests {
assert_eq!(oracle.package_exports("nowhere_pkg"), Exports::Unknown);
}
/// Whether the server flags `line-length` on a line of `columns`
/// characters, in a scratch tree governed by `toml` (none for `None`),
/// with the editor's `lucisv.format.style` set to `editor_style`.
fn flags_a_line_of(
columns: usize,
toml: Option<&str>,
editor_style: Option<&'static str>,
) -> bool {
let dir = std::env::temp_dir().join(format!(
"lucisv_lint_width_{}_{columns}_{}",
std::process::id(),
toml.map_or(0, str::len) + editor_style.map_or(0, str::len) * 1000
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("scratch dir");
if let Some(toml) = toml {
std::fs::write(dir.join("lucisv.toml"), toml).expect("config");
}
let text = format!("module m;\n // {}\nendmodule\n", "x".repeat(columns - 5));
let path = dir.join("m.sv");
std::fs::write(&path, &text).expect("source");
let mut ws = Workspace::default();
ws.set_client_settings(ClientSettings { style: editor_style, ..ClientSettings::default() });
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri.clone(), text);
let doc = ws.document(&uri).expect("open");
let run = LintRun::for_document(&ws, doc);
let flagged = diagnostics_in(doc, &run)
.iter()
.any(|d| d.code == Some(NumberOrString::String("line-length".into())));
let _ = std::fs::remove_dir_all(&dir);
flagged
}
/// The width `lucisv check` holds the same file to: the CLI's own ladder,
/// an explicit width over the named style's over the default
/// (`lucisv`'s `Options::config_with`), with the editor's style standing
/// in for `--style`.
fn check_width(explicit: Option<usize>, style: Option<&str>) -> usize {
let config = style.and_then(vlog_formatter::Config::named).unwrap_or_default();
explicit.unwrap_or(config.max_width)
}
#[test]
fn line_length_holds_a_buffer_to_the_width_the_formatter_and_check_use() {
// One rung each, from the top: an explicit width beats a style; a
// project's style; the editor's style; the default; and `auto`, which
// names no width and so takes the default.
let rungs: [(&str, Option<&str>, Option<&'static str>, usize); 5] = [
(
"explicit",
Some("line-length = 120\n[format]\nstyle = \"ansi\"\n"),
None,
check_width(Some(120), Some("ansi")),
),
(
"project style",
Some("[format]\nstyle = \"ansi\"\n"),
None,
check_width(None, Some("ansi")),
),
("editor style", None, Some("microsoft"), check_width(None, Some("microsoft"))),
("default", None, None, check_width(None, None)),
("auto", Some("[format]\nstyle = \"auto\"\n"), None, check_width(None, Some("auto"))),
];
assert_eq!(rungs.map(|r| r.3), [120, 80, 120, 100, 100], "premise: the widths check uses");
for (rung, toml, editor, width) in rungs {
assert!(
!flags_a_line_of(width, toml, editor),
"{rung}: a line of exactly {width} is fine"
);
assert!(flags_a_line_of(width + 1, toml, editor), "{rung}: one column more is flagged");
}
}
#[test]
fn a_tab_becomes_one_warning_carrying_its_rule_name() {
let (ws, uri) = doc_of("module m;\n\twire a;\nendmodule\n");
@@ -92,7 +92,7 @@ impl Server {
/// Everything the server has to say about a buffer — the one computation
/// both diagnostic models answer from. A buffer that is not open has
/// nothing said about it.
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
pub(super) fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
// The lint pass is given the project: the rule selection
// `lucisv.lint.*` and the buffer's `[lint]` table resolved to, and the
+99 -15
View File
@@ -18,9 +18,21 @@ use super::batch::opened_in;
use super::client::{notify_on, plural};
use super::progress::IndexWatch;
use super::{Server, INTERLEAVE_ABOVE};
use crate::state::{IndexEvent, Scan, Workspace};
use crate::state::{IndexEvent, OneFile, Scan, Watched, Workspace};
use crate::{design_hierarchy, file_ops};
/// A watcher event naming more than one path per `BURST_DIVISOR` files the
/// index holds takes the whole rescan instead of being sorted path by path.
///
/// Measured on the full OpenTitan `hw` tree (4 058 files, release, one
/// notification of generated files under a gitignored directory, medians of
/// 3): sorting costs ~0.10 ms a path (1 000 paths 0.10 s, 5 000 paths 0.50 s),
/// a cached whole rescan ~0.16 ms an indexed file (0.63–0.65 s) — so the two
/// cross near 1.6 paths per file, and both scale with the tree. Dividing by 2
/// keeps the sorted path at or under ~0.3× the rescan it saves on any tree
/// (QA R2-1: never slower than 7408fac's one rescan per notification).
const BURST_DIVISOR: usize = 2;
impl Server {
/// Rescan the workspace and republish every open buffer against the new
/// index. Every caller changed what the index should contain — a save, a
@@ -59,15 +71,22 @@ impl Server {
/// that file is one the index already holds. Reports whether it ran; a
/// `false` means the caller owes a whole rebuild.
///
/// Everything a rebuild does *after* the scan happens here too, for the
/// same reasons: the code-lens refresh (the file that moved may have
/// changed an instantiation count in any buffer), the diagnostics
/// generation bump (every open buffer's diagnostics are computed against
/// the index), and a republish of every open buffer. The republish stays
/// wholesale rather than narrowing to the buffers that could have moved:
/// a lint reads the index, so any buffer's diagnostics may have changed,
/// and narrowing it correctly needs a dependency graph this server does not
/// have. Worth doing later; wrong to guess at now.
/// When the index moved, everything a rebuild does *after* the scan
/// happens here too, for the same reasons: the code-lens refresh (the file
/// that moved may have changed an instantiation count in any buffer), the
/// hierarchy view's invalidation, the diagnostics generation bump (every
/// open buffer's diagnostics are computed against the index), and a
/// republish of every open buffer. The republish stays wholesale: a lint
/// reads the index, so any buffer's diagnostics may have changed, and it
/// costs ~0.3 ms a buffer on OpenTitan — narrowing it would buy nothing
/// measurable for the one place a stale squiggle could hide
/// (`docs/features/localized-reindex/README.md`).
///
/// When the file's record did **not** move — the watcher's echo of the
/// save that just ran, a save of an unchanged buffer — every answer read
/// off the index alone is the answer it already was, so no lens refresh
/// and no hierarchy invalidation is sent. The republish still is: see
/// below.
///
/// Three things a whole rebuild does that this deliberately does not:
///
@@ -93,19 +112,84 @@ impl Server {
return true;
}
let started = self.timer();
if !self.workspace.update_one(path) {
let outcome = self.workspace.update_one_file(path);
if outcome == OneFile::NotHeld {
// No line: nothing was reindexed, and the caller is about to
// rebuild the whole index — which times itself.
return false;
}
self.refresh_code_lenses();
self.hierarchy_index_changed();
// Lenses and the hierarchy view are read off the index alone, so an
// unchanged record owes them nothing. Diagnostics are not: a lint
// also reads the buffer's `lucisv.toml` and waiver files from disk,
// which no notification reports, and a save has always been when an
// edit to them takes effect (QA F2). So every save republishes.
if outcome == OneFile::Changed {
self.refresh_code_lenses();
self.hierarchy_index_changed();
}
self.republish_all();
// The unchanged case says so inside the parentheses, so every reader
// of the old `reindex_one(<path>) took <ms>` shape still matches.
let unchanged = if outcome == OneFile::Unchanged { ", unchanged" } else { "" };
self.timed(started, |took| {
format!("reindex_one({}{unchanged}) took {took}", path.display())
});
true
}
/// The rescan a watcher event owes, decided file by file
/// ([`Workspace::watched`]): a file the scope provably cannot take — a
/// generated file under a gitignored directory, one outside the folder
/// scope or the filelist — owes nothing; a held file, by whatever
/// spelling the client used, is the one-file update; anything the scope
/// may take and the index does not hold is a whole rebuild, and so are
/// two or more held files, exactly as a checkout always was.
///
/// `named` is every path the event named, any extension: the include
/// lines that could name one are re-resolved first, unless the event takes
/// the whole rescan, which re-resolves all of them (QA F1). An event that owes the index
/// nothing still republishes every open buffer, for the reason
/// [`Server::reindex_one`] gives.
pub(super) fn reindex_watched(
&mut self,
paths: &[std::path::PathBuf],
named: &[std::path::PathBuf],
) {
// A burst — a branch switch, a generator run — is sorted file by file
// only while that is cheaper than the rescan it replaces.
if paths.len().saturating_mul(BURST_DIVISOR) > self.workspace.index().files().len() {
return self.reindex();
}
self.workspace.refresh_includes_naming(named);
let mut held: Vec<std::path::PathBuf> = Vec::new();
for path in paths {
match self.workspace.watched(path) {
Watched::Held(spelled) => held.push(spelled),
Watched::Outside => {}
Watched::Unknown => return self.reindex(),
}
}
held.sort();
held.dedup();
match held.as_slice() {
[] => self.republish_all(),
[one] => {
if !self.reindex_one(one) {
self.reindex();
}
}
_ => self.reindex(),
}
}
/// Every open buffer's diagnostics said again, under a new generation so
/// a pulling client asks again too — what a save owes even when the index
/// did not move. ~0.3 ms a buffer on OpenTitan.
pub(super) fn republish_all(&mut self) {
self.generation += 1;
for uri in self.workspace.open_uris() {
self.publish(&uri);
}
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
true
}
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
@@ -25,6 +25,7 @@ use serde::de::DeserializeOwned;
use super::batch::{widen_of, Widen};
use super::client::ms;
use super::Server;
use crate::uri::uri_to_path;
use crate::{file_ops, lint, settings, sync, watch};
impl Server {
@@ -136,8 +137,18 @@ impl Server {
}
DidSaveTextDocument::METHOD => {
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
// A save carrying the text the buffer already holds — the
// normal case, since every change was flushed above — has
// nothing to re-analyze. One carrying different text is a
// change the server missed: analyzed and published here,
// so the buffer's own answer is current whatever the
// reindex below finds moved.
if let Some(text) = p.text {
self.set_document(p.text_document.uri.clone(), text);
let uri = p.text_document.uri.clone();
if self.workspace.document(&uri).is_none_or(|doc| doc.text != text) {
self.set_document(uri.clone(), text);
self.publish(&uri);
}
}
// A save is one of the things that rebuild the index; the
// others are a change to `lucisv.exclude`/`lucisv.filelist`
@@ -160,15 +171,28 @@ impl Server {
// the params carry a list, and a checkout fills it.
DidChangeWatchedFiles::METHOD => {
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
// Whatever else the event owes, every path it names may
// be what an `include` line was looking for — in scope or
// not, of a source extension or not (QA F1). A rescan
// re-resolves every line anyway, so only the paths that
// do not take one are refreshed here.
let named: Vec<std::path::PathBuf> =
p.changes.iter().filter_map(|change| uri_to_path(&change.uri)).collect();
let filelist = self.workspace.filelist_path();
if watch::touches_scope(&p.changes, filelist.as_deref()) {
// One file named is the incremental case; a checkout
// filling the list, or the filelist itself moving, is
// the whole rebuild.
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
self.reindex();
if watch::names_a_config(&p.changes) {
// A `lucisv.toml` moves excludes, the filelist and
// the lint configuration at once — for the client
// that forwards it (ours registers sources only).
self.reindex();
} else if watch::touches_scope(&p.changes, filelist.as_deref()) {
// The filelist itself moving is the whole rebuild;
// anything else is sorted file by file.
match watch::scope_files(&p.changes, filelist.as_deref()) {
Some(paths) => self.reindex_watched(&paths, &named),
None => self.reindex(),
}
} else {
self.workspace.refresh_includes_naming(&named);
}
}
}
@@ -0,0 +1,754 @@
//! The localized reindex held to a whole rebuild through the real server
//! (`docs/features/localized-reindex/README.md`).
//!
//! Every step goes through the notifications an editor sends — a change, a
//! save and the watcher's echo of it for an open buffer; a watcher event alone
//! for a file rewritten, created or deleted on disk — and after every step the
//! server's state is compared with what a whole rebuild over the same disk and
//! the same buffers gives: the index (postings and readers table included),
//! the completion tables, the include graph, every open buffer's cross-file
//! answers, and **the diagnostics last published for every open buffer**. The
//! last is the one the narrowing could get wrong without any table showing it:
//! a buffer the server decided not to republish must still be showing what a
//! fresh analysis would say.
use std::collections::BTreeMap;
use super::*;
/// A session over a scratch tree, with what it last published per buffer.
struct Mirror {
tree: Tree,
session: Session,
open: BTreeMap<PathBuf, (Uri, i32)>,
shown: BTreeMap<String, Value>,
/// Whole rescans seen, so a sweep can say how much of it the narrowed
/// path carried.
rescans: usize,
}
impl Mirror {
fn new(name: &str, files: &[(&str, &str)], open: &[&str]) -> Mirror {
let tree = Tree::new(name);
for (rel, text) in files {
tree.write(rel, text);
}
Mirror::over(tree, open)
}
fn over(tree: Tree, open: &[&str]) -> Mirror {
let wide = ClientSettings {
index_scope: crate::settings::IndexScope::Workspace,
..Default::default()
};
Mirror::with(tree, open, wide)
}
fn with(tree: Tree, open: &[&str], settings: ClientSettings) -> Mirror {
// A client that shows a bar, so a whole rescan is visible as one.
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let session = Session::started(vec![tree.path.clone()], abilities, settings);
let mut mirror =
Mirror { tree, session, open: BTreeMap::new(), shown: BTreeMap::new(), rescans: 0 };
for rel in open {
let path = mirror.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("an open buffer's file is on disk");
let uri = mirror.session.open(&path, &text);
mirror.open.insert(path, (uri, 1));
}
mirror.absorb();
mirror
}
/// Remember the newest diagnostics the server pushed for each buffer, and
/// count the whole rescans (a progress bar begun) among the steps.
fn absorb(&mut self) {
for message in self.session.drain() {
let Message::Notification(n) = message else { continue };
if n.method == PublishDiagnostics::METHOD {
let published: PublishDiagnosticsParams =
serde_json::from_value(n.params).expect("publish params");
let shown = serde_json::to_value(&published.diagnostics).expect("diagnostics");
self.shown.insert(published.uri.as_str().to_string(), shown);
} else if n.method == Progress::METHOD && n.params.to_string().contains("\"begin\"") {
self.rescans += 1;
}
}
}
/// Write `rel` as an editor does: through its buffer when it is open (the
/// change, the save, the disk, the watcher's echo), else on disk alone
/// with the watcher's event.
fn write(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
let created = !path.exists();
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidChangeTextDocument::METHOD, change);
self.tree.write(rel, text);
self.session.notify(DidSaveTextDocument::METHOD, save);
} else {
self.tree.write(rel, text);
}
let kind = if created { FileChangeType::CREATED } else { FileChangeType::CHANGED };
self.event(&path, kind);
}
/// Delete a closed file on disk, as a checkout does.
fn delete(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
assert!(!self.open.contains_key(&path), "the sweep deletes closed files only");
std::fs::remove_file(&path).expect("delete");
self.event(&path, FileChangeType::DELETED);
}
/// Save an open buffer that has not changed, and the watcher's echo — a
/// save the index records nothing about.
fn save_only(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let (uri, _) = self.open.get(&path).cloned().expect("an open buffer");
let save = serde_json::json!({ "textDocument": { "uri": uri } });
self.session.notify(DidSaveTextDocument::METHOD, save);
self.event(&path, FileChangeType::CHANGED);
}
/// Rewrite an open buffer's file on disk behind the editor's back: the
/// editor reloads the clean buffer (a change carrying the disk's text),
/// and the watcher reports the file. No save.
fn disk_only(&mut self, rel: &str, text: &str) {
let path = self.tree.path.join(rel);
self.tree.write(rel, text);
if let Some((uri, version)) = self.open.get_mut(&path) {
*version += 1;
let change = serde_json::json!({
"textDocument": { "uri": uri, "version": *version },
"contentChanges": [{ "text": text }],
});
self.session.notify(DidChangeTextDocument::METHOD, change);
}
self.event(&path, FileChangeType::CHANGED);
}
/// Open a file that is on disk, after the startup scan.
fn open_file(&mut self, rel: &str) {
let path = self.tree.path.join(rel);
let text = std::fs::read_to_string(&path).expect("on disk");
let uri = self.session.open(&path, &text);
self.open.insert(path, (uri, 1));
}
fn event(&mut self, path: &Path, typ: FileChangeType) {
let changes = vec![FileEvent { uri: path_to_uri(path).expect("uri"), typ }];
self.session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
}
/// The whole claim: what the server holds and last showed is what a whole
/// rebuild over the same disk and buffers gives. The rebuild is done in
/// place, so a run that passes goes on from the state it already had.
fn holds(&mut self, step: &str) {
self.absorb();
let workspace = &mut self.session.server.workspace;
let incremental = workspace.derived_fingerprint();
workspace.rebuild_index();
let rebuilt = workspace.derived_fingerprint();
if incremental != rebuilt {
let first = incremental.lines().zip(rebuilt.lines()).find(|(a, b)| a != b);
panic!("{step}: the incremental state is not a rebuild's; first difference {first:?}");
}
for (uri, _) in self.open.values() {
let fresh = self.session.server.diagnostics_of(uri);
let fresh = serde_json::to_value(&fresh).expect("diagnostics");
let shown = self.shown.get(uri.as_str()).cloned().unwrap_or(Value::Null);
assert_eq!(shown, fresh, "{step}: {} shows stale diagnostics", uri.as_str());
}
}
/// Every step, each followed by the check.
fn steps(&mut self, steps: &[(&str, &str)]) {
self.holds("before any step");
for (at, (rel, text)) in steps.iter().enumerate() {
self.write(rel, text);
self.holds(&format!("step {at}, `{rel}`"));
}
}
}
const LEAF: &str =
"module leaf (input logic clk, output logic q);\n logic s;\n assign q = s;\nendmodule\n";
const TOP: &str = "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n";
const TB: &str = "module tb;\n top dut ();\n initial $display(dut.u_leaf.s);\nendmodule\n";
const PKG: &str =
"package cfg_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n";
const USER: &str = "module user import cfg_pkg::*; (input word_t a, output word_t b);\n assign b = a + W;\nendmodule\n";
const DEFS: &str = "`define WIDTH 8\n`define CLOG(x) $clog2(x)\n";
const INCLUDER: &str =
"`include \"defs.svh\"\nmodule includer;\n logic [`WIDTH-1:0] v;\nendmodule\n";
fn design() -> Vec<(&'static str, &'static str)> {
vec![
("rtl/leaf.sv", LEAF),
("rtl/top.sv", TOP),
("dv/tb.sv", TB),
("rtl/cfg_pkg.sv", PKG),
("rtl/user.sv", USER),
("rtl/defs.svh", DEFS),
("rtl/includer.sv", INCLUDER),
]
}
#[test]
fn every_kind_of_edit_to_an_open_module_leaves_the_rebuilt_state_and_every_squiggle() {
let mut mirror =
Mirror::new("lr_module", &design(), &["rtl/leaf.sv", "rtl/top.sv", "dv/tb.sv"]);
let open_leaf = |text: &str| ("rtl/leaf.sv", text.to_string());
let steps = [
// Nothing the index records: a comment after the last token.
open_leaf(&format!("{LEAF}// trailing\n")),
// A body edit, a local signal, a comment above everything.
open_leaf(&LEAF.replace("assign q = s;", "assign q = ~s;")),
open_leaf(&LEAF.replace(" logic s;\n", " logic s;\n logic t;\n")),
open_leaf(&format!("// above\n{LEAF}")),
// The port list: renamed, removed, added — `top` connects by name, so
// its unknown-port squiggles must follow without `top` being saved.
open_leaf(&LEAF.replace("input logic clk", "input logic clock")),
open_leaf(&LEAF.replace("input logic clk, ", "")),
open_leaf(&LEAF.replace("output logic q", "output logic q, input logic en")),
// The signal the testbench names hierarchically, gone and back.
open_leaf(&LEAF.replace("logic s;\n assign q = s;", "logic r;\n assign q = r;")),
// The module renamed away, so `top`'s instantiation resolves nowhere.
open_leaf(&LEAF.replace("module leaf", "module leaf2")),
open_leaf(LEAF),
];
let steps: Vec<(&str, &str)> = steps.iter().map(|(rel, text)| (*rel, text.as_str())).collect();
mirror.steps(&steps);
}
#[test]
fn edits_to_a_closed_package_a_define_header_and_an_include_line_all_hold() {
let mut mirror = Mirror::new("lr_package", &design(), &["rtl/user.sv", "rtl/includer.sv"]);
let user_text = USER.replace("+ W", "+ W + DEPTH");
let pkg_depth =
PKG.replace("localparam int W = 8;", "localparam int W = 8;\n localparam int DEPTH = 4;");
let defs_more = format!("{DEFS}`define DEPTH 4\n");
let includer_none = INCLUDER.replace("`include \"defs.svh\"\n", "");
let pkg_renamed = PKG.replace("package cfg_pkg", "package cfg2_pkg");
let defs_wider = DEFS.replace("8", "16");
let defs_params = DEFS.replace("CLOG(x)", "CLOG(x, y)");
let includer_nowhere = INCLUDER.replace("defs.svh", "nowhere.svh");
let steps: Vec<(&str, &str)> = vec![
// A package member the open user does not name yet, then does.
("rtl/cfg_pkg.sv", &pkg_depth),
("rtl/user.sv", &user_text),
// The package member it names, gone.
("rtl/cfg_pkg.sv", PKG),
// The package renamed.
("rtl/cfg_pkg.sv", &pkg_renamed),
("rtl/cfg_pkg.sv", PKG),
// A define header: a value, a new macro, a parameter list.
("rtl/defs.svh", &defs_wider),
("rtl/defs.svh", &defs_more),
("rtl/defs.svh", &defs_params),
// An include line removed and put back, and one that resolves nowhere.
("rtl/includer.sv", &includer_none),
("rtl/includer.sv", INCLUDER),
("rtl/includer.sv", &includer_nowhere),
("rtl/includer.sv", INCLUDER),
];
mirror.steps(&steps);
}
#[test]
fn a_signal_another_file_mentions_keeps_its_lint_answer_as_the_mention_comes_and_goes() {
// `unused-signal` consults the workspace census: `dbg` is unused in
// `probe.sv` but named by `peek.sv`, which is closed. The open buffer is
// never saved here, so only a republish the narrowing owed can move it.
let probe = "module probe;\n logic dbg;\nendmodule\n";
let peek = "module peek;\n initial $display(probe.dbg);\nendmodule\n";
let mut mirror =
Mirror::new("lr_census", &[("probe.sv", probe), ("peek.sv", peek)], &["probe.sv"]);
mirror.steps(&[
("peek.sv", "module peek;\n initial $display(1);\nendmodule\n"),
("peek.sv", peek),
("peek.sv", &format!("{peek}// a comment that moves nothing\n")),
]);
}
#[test]
fn files_created_and_deleted_beside_open_buffers_hold() {
let mut mirror = Mirror::new("lr_files", &design(), &["rtl/top.sv", "rtl/includer.sv"]);
mirror.holds("before any step");
// A second `leaf` makes the instantiation ambiguous; deleting it heals it.
mirror.write("rtl/zz_leaf.sv", LEAF);
mirror.holds("a duplicate module created");
mirror.delete("rtl/zz_leaf.sv");
mirror.holds("and deleted");
mirror.delete("rtl/defs.svh");
mirror.holds("an included header deleted");
mirror.write("rtl/defs.svh", DEFS);
mirror.holds("and recreated");
}
#[test]
fn a_watcher_event_for_a_file_the_scope_cannot_take_costs_no_rescan() {
// A generated file under a gitignored directory, and a file outside the
// workspace root: neither can change the index, so neither may cost the
// progress bar — and the state is still a rebuild's.
let mut mirror = Mirror::new("lr_outside", &design(), &["rtl/top.sv"]);
mirror.tree.write(".gitignore", "build/\n");
mirror.holds("before any step");
let _ = mirror.session.drain();
mirror.write("build/gen.sv", "module gen;\nendmodule\n");
assert!(mirror.session.progress().is_empty(), "no bar for a gitignored file");
mirror.holds("a generated file under build/");
let outside = Tree::new("lr_outside_elsewhere");
outside.write("far.sv", "module far;\nendmodule\n");
let _ = mirror.session.drain();
mirror.event(&outside.path.join("far.sv"), FileChangeType::CHANGED);
assert!(mirror.session.progress().is_empty(), "no bar for a file outside every root");
mirror.holds("a file outside the root");
// A file the scope does take, appearing, is still the whole rebuild —
// which is also what proves the two assertions above can fail.
mirror.rescans = 0;
mirror.write("rtl/new.sv", "module fresh;\nendmodule\n");
mirror.holds("a new file in scope");
assert_eq!(mirror.rescans, 1, "a file the scope takes appearing is a rescan");
assert!(
mirror.session.server.workspace.index().units("fresh").len() == 1,
"the new file is in the index"
);
}
#[test]
fn a_buffer_opened_from_outside_the_filelist_joins_the_index_on_its_first_save() {
// VS Code restores editors while the startup scan runs; one outside the
// filelist is open but not indexed until something rebuilds. Its first
// save used to be that rebuild, bar and all.
let mut files = design();
files.push(("rtl/waits.sv", "`include \"late.svh\"\nmodule waits;\nendmodule\n"));
files.push(("files.f", "rtl/leaf.sv\nrtl/top.sv\nrtl/cfg_pkg.sv\nrtl/waits.sv\n"));
let tree = Tree::new("lr_filelist");
for (rel, text) in &files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv", "dv/tb.sv"], listed);
mirror.rescans = 0;
mirror.write("dv/tb.sv", &TB.replace("$display", "$write"));
mirror.holds("the first save of the unlisted buffer");
assert_eq!(mirror.rescans, 0, "the buffer was on disk before the scan: no rescan");
assert!(mirror.session.server.workspace.index().units("tb").len() == 1, "and it is indexed");
// A file born after the scan may be what some `include` was waiting
// for — `waits.sv`'s is: its lines are re-resolved, still no rebuild.
mirror.write("rtl/late.svh", "`define LATE 1\n");
let path = mirror.tree.path.join("rtl/late.svh");
let uri = mirror.session.open(&path, "`define LATE 1\n");
mirror.open.insert(path, (uri, 1));
mirror.rescans = 0;
mirror.write("rtl/late.svh", "`define LATE 2\n");
mirror.holds("the first save of a buffer younger than the scan");
assert_eq!(mirror.rescans, 0, "the include waiting for it is re-resolved in place");
let graph = mirror.session.server.workspace.includes();
assert_eq!(graph.reachable(vec![mirror.tree.path.join("rtl/waits.sv")]).len(), 2, "and found");
}
/// QA F1: a header the scope cannot take, appearing and vanishing, moves an
/// in-scope includer's edge — an include is resolved against the disk.
#[test]
fn a_header_outside_the_scope_created_and_deleted_moves_the_includers_edges() {
let files = [
(".gitignore", "gen/\n"),
("rtl/a.sv", "`include \"../gen/h.svh\"\nmodule a;\nendmodule\n"),
("rtl/a_inc.svh", "`include \"../gen/h.svh\"\n`define AW 2\n"),
("rtl/b.sv", "`include \"a_inc.svh\"\nmodule b;\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f1_ignored", &files, &["rtl/b.sv"]);
mirror.steps(&[("gen/h.svh", "`define GEN_W 4\n")]);
mirror.rescans = 0;
mirror.delete("gen/h.svh");
mirror.holds("the ignored header deleted");
mirror.write("gen/h.svh", "`define GEN_W 5\n");
mirror.holds("and created again");
assert_eq!(mirror.rescans, 0, "the include graph alone, never a rescan");
}
/// QA R2-1: one event naming a burst of files is sorted path by path only
/// while that is cheaper than a rescan (`BURST_DIVISOR`); past it the event
/// takes the whole rescan. The state is a rebuild's on both sides.
#[test]
fn a_burst_of_created_files_is_sorted_below_the_threshold_and_rescanned_above() {
let mut files = design();
files.push((".gitignore", "gen/\n"));
files.push(("rtl/waits.sv", "`include \"../gen/h0.svh\"\nmodule waits;\nendmodule\n"));
let mut mirror = Mirror::new("lr_burst", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
let held = mirror.session.server.workspace.index().files().len();
let burst = |mirror: &mut Mirror, count: usize, tag: &str| {
let changes: Vec<FileEvent> = (0..count)
.map(|k| {
let rel = format!("gen/{tag}{k}.svh");
mirror.tree.write(&rel, &format!("`define {}{k} 1\n", tag.to_uppercase()));
let path = mirror.tree.path.join(rel);
FileEvent { uri: path_to_uri(&path).expect("uri"), typ: FileChangeType::CREATED }
})
.collect();
let params = DidChangeWatchedFilesParams { changes };
mirror.session.notify(DidChangeWatchedFiles::METHOD, params);
};
mirror.rescans = 0;
burst(&mut mirror, held / 2, "h");
mirror.holds("a burst at the threshold, `h0.svh` among it");
assert_eq!(mirror.rescans, 0, "sorted path by path: {held} held, {} named", held / 2);
burst(&mut mirror, held / 2 + 1, "k");
mirror.write("gen/h0.svh", "`define H0 2\n");
mirror.holds("a burst past the threshold");
assert_eq!(mirror.rescans, 1, "one path more is the whole rescan");
}
/// QA F1, filelist mode: an unlisted header under an `+incdir+`.
#[test]
fn an_unlisted_header_under_an_incdir_created_moves_the_includers_edge() {
let files = [
("files.f", "+incdir+inc\nrtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"h2.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let tree = Tree::new("lr_f1_incdir");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
mirror.write("inc/h2.svh", "`define H2 1\n");
mirror.holds("the unlisted header created");
mirror.delete("inc/h2.svh");
mirror.holds("and deleted");
}
/// QA F2: a `[lint]` edit in `lucisv.toml`, which no notification reports,
/// takes effect at the next save — even one the index records nothing about.
#[test]
fn a_lint_configuration_edit_takes_effect_at_a_save_that_moves_nothing() {
let lint_me = "module lint_me;\n\twire unused_w; \n reg r;\nendmodule\n";
let mut mirror = Mirror::new("lr_f2_toml", &[("rtl/lint_me.sv", lint_me)], &["rtl/lint_me.sv"]);
mirror.holds("before any step");
let uri = mirror.open.values().next().map(|(uri, _)| uri.as_str().to_string()).expect("open");
assert_ne!(mirror.shown.get(&uri), Some(&Value::Array(Vec::new())), "premise: findings");
mirror.tree.write(
"lucisv.toml",
"[lint]\nignore = [\"no-tabs\", \"no-trailing-whitespace\", \"unused-signal\"]\n",
);
mirror.save_only("rtl/lint_me.sv");
mirror.holds("the save after the lint configuration changed");
mirror.tree.write("lucisv.toml", "[lint]\n");
mirror.save_only("rtl/lint_me.sv");
mirror.holds("and after it changed back");
}
/// QA F3: a file moved in from elsewhere after the scan keeps its old times;
/// opened and saved, it joins the index and its waiting includer finds it.
/// No watcher event is sent for the move — a client that does not watch, or
/// an event coalesced away — so the save alone must re-resolve the includer
/// (the event's own re-resolution is F1's test).
#[test]
fn a_file_moved_in_after_the_scan_joins_and_is_found_by_its_includer() {
let files = [
("files.f", "rtl/a.sv\nrtl/top.sv\n"),
("rtl/a.sv", "`include \"late.svh\"\nmodule a;\nendmodule\n"),
("rtl/top.sv", "module top;\n a u_a ();\nendmodule\n"),
];
let elsewhere = Tree::new("lr_f3_elsewhere");
elsewhere.write("late.svh", "`define LATE 7\n");
let tree = Tree::new("lr_f3_moved");
for (rel, text) in files {
tree.write(rel, text);
}
let listed = ClientSettings { filelist: Some("files.f".to_string()), ..Default::default() };
let mut mirror = Mirror::with(tree, &["rtl/top.sv"], listed);
mirror.holds("before any step");
let moved = mirror.tree.path.join("rtl/late.svh");
std::fs::rename(elsewhere.path.join("late.svh"), &moved).expect("move in");
mirror.open_file("rtl/late.svh");
let (uri, _) = mirror.open[&moved].clone();
let save = serde_json::json!({ "textDocument": { "uri": uri } });
mirror.session.notify(DidSaveTextDocument::METHOD, save);
mirror.holds("opened and saved, with no watcher echo");
}
/// QA F4: an excluded buffer, open and changed on disk, is taken in, as a
/// fresh server takes every open buffer in.
#[test]
fn an_excluded_open_buffer_changed_on_disk_is_taken_in() {
let files = [
("lucisv.toml", "exclude = [\"rtl/b.sv\"]\n"),
("rtl/b.sv", "module b;\nendmodule\n"),
("rtl/top.sv", "module top;\n b u_b ();\nendmodule\n"),
];
let mut mirror = Mirror::new("lr_f4_excluded", &files, &["rtl/top.sv"]);
mirror.holds("before any step");
mirror.open_file("rtl/b.sv");
mirror.disk_only("rtl/b.sv", "module b;\n wire w2;\nendmodule\n");
mirror.holds("the excluded buffer changed on disk");
assert_eq!(mirror.session.server.workspace.index().units("b").len(), 1, "taken in");
}
#[cfg(unix)]
#[test]
fn a_held_file_reported_by_its_real_path_takes_the_one_file_update() {
// The workspace is opened through a symlink; the watcher reports the real
// path. Before this round that was a "file the index does not hold" and a
// whole rescan per save.
let real = Tree::new("lr_real");
for (rel, text) in design() {
real.write(rel, text);
}
let link = Tree::new("lr_link");
std::fs::remove_dir_all(&link.path).expect("make room for the link");
std::os::unix::fs::symlink(&real.path, &link.path).expect("symlink");
let abilities =
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
let mut session = Session::wide_with(vec![link.path.clone()], abilities);
let _ = session.drain();
real.write("rtl/leaf.sv", &LEAF.replace("input logic clk", "input logic clock"));
session.watched(&[real.path.join("rtl/leaf.sv")]);
assert!(session.progress().is_empty(), "the one-file path, not a rescan");
let index = session.server.workspace.index();
assert_eq!(index.member("leaf", "clock").len(), 1, "and the update landed");
assert!(
index.files().iter().all(|path| path.starts_with(&link.path)),
"under the link's spelling"
);
let _ = std::fs::remove_file(&link.path);
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit: a line inserted, deleted, duplicated or swapped with its
/// neighbour, or one identifier renamed to another the file already uses —
/// edits that move spans, names and whole declarations.
fn mutate(text: &str, rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(6) {
0 => lines.insert(at, " // lucisv sweep".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
4 => lines.insert(at, " logic lucisv_sweep_q;".to_string()),
_ => {
let words = vlog_semantic::words::harvest_text(text);
if words.len() >= 2 {
let from = words[rng.below(words.len())].clone();
let to = words[rng.below(words.len())].clone();
if let Some(line) = lines.iter_mut().find(|line| line.contains(from.as_str())) {
*line = line.replacen(from.as_str(), &to, 1);
}
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
/// `steps` seeded mutations over every source file under `tree`, with `open`
/// buffers open, each step checked; now and then a closed file is deleted or
/// a new one created.
fn sweep(tree: Tree, open: usize, seed: u64, steps: usize) {
// `opened` below is also what the lint-configuration step saves.
let mut files: Vec<String> = Vec::new();
collect(&tree.path, &tree.path, &mut files);
files.sort();
assert!(!files.is_empty(), "premise: a tree with sources in it");
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let opened: Vec<String> = (0..open).map(|_| files[rng.below(files.len())].clone()).collect();
let opened_refs: Vec<&str> = opened.iter().map(String::as_str).collect();
// The setting the event kinds QA found need: a gitignored `gen/` whose
// headers an in-scope file waits for, and excluded names to open.
tree.write(".gitignore", "gen/\n");
tree.write("lucisv.toml", "exclude = [\"sweep_excluded_*\"]\n");
let waits: String = (0..4).map(|k| format!("`include \"gen/h{k}.svh\"\n")).collect();
tree.write("sweep_waits.sv", &format!("{waits}module sweep_waits;\nendmodule\n"));
let elsewhere = Tree::new(&format!("lr_sweep_elsewhere_{seed}"));
let mut mirror = Mirror::over(tree, &opened_refs);
mirror.holds(&format!("seed {seed}: before any step"));
mirror.rescans = 0;
for step in 0..steps {
let rel = files[rng.below(files.len())].clone();
let path = mirror.tree.path.join(&rel);
let label = format!("seed {seed}, step {step}, `{rel}`");
match rng.below(24) {
0 if !mirror.open.contains_key(&path) && path.exists() => mirror.delete(&rel),
1 => mirror.write(&format!("sweep_new_{step}.sv"), "module sweep_new;\nendmodule\n"),
// A header outside the scope, waited for, toggled.
2 => {
let header = format!("gen/h{}.svh", rng.below(4));
match mirror.tree.path.join(&header).exists() {
true => mirror.delete(&header),
false => mirror.write(&header, &format!("`define SWEEP_{step} 1\n")),
}
}
// The lint configuration edited, then a save that moves nothing.
3 => {
let rules = ["no-tabs", "unused-signal", "line-length", "no-trailing-whitespace"];
let ignored: Vec<String> = rules
.iter()
.filter(|_| rng.below(2) == 0)
.map(|r| format!("\"{r}\""))
.collect();
let config = format!(
"exclude = [\"sweep_excluded_*\"]\n[lint]\nignore = [{}]\n",
ignored.join(", ")
);
mirror.tree.write("lucisv.toml", &config);
if let Some(open) = opened.get(rng.below(opened.len().max(1))) {
mirror.save_only(open);
}
}
// A file moved in from elsewhere, old times and all, then opened
// and saved.
4 => {
let name = format!("sweep_moved_{step}.svh");
elsewhere.write(&name, &format!("`define SWEEP_MOVED_{step} 1\n"));
let to = mirror.tree.path.join("gen").join(&name);
std::fs::create_dir_all(mirror.tree.path.join("gen")).expect("gen/");
std::fs::rename(elsewhere.path.join(&name), &to).expect("move in");
mirror.event(&to, FileChangeType::CREATED);
let rel = format!("gen/{name}");
mirror.open_file(&rel);
mirror.save_only(&rel);
}
// An excluded file, opened, then changed on disk.
5 => {
let rel = format!("sweep_excluded_{step}.sv");
mirror.write(&rel, &format!("module sweep_excluded_{step};\nendmodule\n"));
mirror.open_file(&rel);
let text = format!("module sweep_excluded_{step};\n wire w;\nendmodule\n");
mirror.disk_only(&rel, &text);
}
_ => {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let text = match mirror.open.contains_key(&path) {
true => mirror.session.server.workspace.text_of(&path).unwrap_or(text),
false => text,
};
mirror.write(&rel, &mutate(&text, &mut rng));
}
}
mirror.holds(&label);
}
eprintln!(
"seed {seed}: {steps} steps over {} files, {} of them whole rescans",
files.len(),
mirror.rescans
);
}
fn collect(root: &Path, dir: &Path, out: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
collect(root, &path, out);
} else if crate::watch::watched(&path, None) {
if let Ok(rel) = path.strip_prefix(root) {
out.push(rel.to_string_lossy().into_owned());
}
}
}
}
/// Copy every source file under `from` into `tree` under `prefix`, saying
/// how many — none when `from` is not on this machine.
fn copy_into(tree: &Tree, from: &Path, prefix: &str) -> usize {
let mut files: Vec<String> = Vec::new();
collect(from, from, &mut files);
for rel in &files {
let Ok(text) = std::fs::read_to_string(from.join(rel)) else { continue };
tree.write(&format!("{prefix}{rel}"), &text);
}
files.len()
}
fn home(rel: &str) -> PathBuf {
std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join(rel)
}
#[test]
fn a_seeded_sweep_over_the_hand_written_design_holds() {
for seed in 1..=3 {
let tree = Tree::new(&format!("lr_sweep_{seed}"));
for (rel, text) in design() {
tree.write(rel, text);
}
sweep(tree, 3, seed, 25);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_the_corpus -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over ~/.cache/lucisv-corpus, minutes in a debug build"]
fn a_seeded_sweep_over_the_corpus_holds() {
let from = std::env::var_os("LUCISV_CORPUS")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-corpus"));
for seed in [11, 12, 13] {
let tree = Tree::new(&format!("lr_corpus_{seed}"));
if copy_into(&tree, &from, "") == 0 {
eprintln!("{} not present — skipping", from.display());
return;
}
sweep(tree, 5, seed, 60);
}
}
/// `tools/guard.sh -- cargo test --release -p lucisv_server sweep_over_an_opentitan -- --ignored --nocapture`
#[test]
#[ignore = "a sweep over a sample of OpenTitan, minutes in a debug build"]
fn a_seeded_sweep_over_an_opentitan_sample_holds() {
let hw = std::env::var_os("LUCISV_OPENTITAN")
.map(PathBuf::from)
.unwrap_or_else(|| home(".cache/lucisv-opentitan-full/hw"));
for seed in [21, 22] {
let tree = Tree::new(&format!("lr_opentitan_{seed}"));
let mut copied = 0;
for sub in ["ip/uart/", "ip/gpio/", "ip/prim/rtl/", "ip/prim_generic/rtl/", "ip/tlul/rtl/"]
{
copied += copy_into(&tree, &hw.join(sub), sub);
}
if copied == 0 {
eprintln!("{} not present — skipping", hw.display());
return;
}
sweep(tree, 6, seed, 60);
}
}
@@ -56,6 +56,7 @@ mod hierarchy_reach;
mod index;
mod large_file;
mod lint_snapshot;
mod localized_reindex;
mod progress;
mod pull_diagnostics;
mod qa_generate_label;
@@ -81,17 +81,36 @@ fn an_index_rebuild_moves_the_result_id_too() {
// `inter_file_dependencies: true` is a promise: a save rebuilds the
// index, and what the index says can change what a *different* buffer
// reports. A stale "unchanged" there would be a wrong squiggle.
//
// Since localized-reindex (2026-11-19) the save whose record did not move
// still moves the stamp — a lint reads `lucisv.toml` from disk, and a
// save is when an edit to it takes effect (QA F2) — and so does the save
// of an edit the index has not seen.
let tree = Tree::new("pullreindex");
let mut session = Session::with(vec![tree.path.clone()], pulling());
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
let stamp = document_pull(&mut session, &uri, None)["resultId"]
.as_str()
.expect("a result id")
.to_string();
let stamp = |session: &mut Session, previous: Option<&str>| {
document_pull(session, &uri, previous)["resultId"]
.as_str()
.expect("a result id")
.to_string()
};
let first = stamp(&mut session, None);
let save = serde_json::json!({ "textDocument": { "uri": uri } });
session.notify(DidSaveTextDocument::METHOD, save.clone());
let after = document_pull(&mut session, &uri, Some(&first));
assert_eq!(after["kind"], "full", "a save that moved no record: {after:#?}");
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let after = document_pull(&mut session, &uri, Some(&stamp));
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module m;\n\twire ;\n wire extra;\nendmodule\n" }],
}),
);
let edited = stamp(&mut session, Some(&first));
session.notify(DidSaveTextDocument::METHOD, save);
let after = document_pull(&mut session, &uri, Some(&edited));
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
}
@@ -201,9 +201,22 @@ fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// Every rescan trigger, one refresh each.
// Every rescan trigger, one refresh each — a save of an edit the index
// has not seen, since a save that moved nothing refreshes nothing
// (localized-reindex, 2026-11-19).
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
assert!(session.requests().is_empty(), "a save that moved nothing asks for nothing");
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
session.notify(
DidChangeConfiguration::METHOD,
@@ -223,9 +236,22 @@ fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
let mut session = Session::new(vec![tree.path.clone()], false);
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
let _ = session.drain();
// A save of an edit the index has not seen, so the save path really
// moves the index (a save that moves nothing refreshes nothing anyway).
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
tree.write("top.sv", "module top;\n sub u_a ();\nendmodule\n");
session.watched(&[tree.path.join("top.sv")]);
let index = session.server.workspace.index();
let w = index.member_in("sub", "w", vlog_semantic::Surface::Hierarchical);
assert_eq!(w.len(), 1, "premise: the save moved the index");
assert!(session.requests().is_empty(), "silence, on every rescan path");
}
@@ -368,6 +394,14 @@ fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
let _ = session.drain();
// An edit the index has not seen, so the save moves it.
session.notify(
DidChangeTextDocument::METHOD,
serde_json::json!({
"textDocument": { "uri": uri, "version": 2 },
"contentChanges": [{ "text": "module sub;\n wire w;\nendmodule\n" }],
}),
);
session
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
+3 -11
View File
@@ -389,18 +389,10 @@ impl Workspace {
// The walk names its inputs as strings; every directory here came
// from a `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
// A broken `lucisv.toml` excludes nothing, and the client's
// `lucisv.exclude` is appended to it — see `walk_excludes`.
let configuring = trace.now();
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
let exclude = self.walk_excludes(&mut discovery, root);
ScanTrace::add(&mut trace.config_ms, configuring);
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable directory
+229 -75
View File
@@ -1,96 +1,231 @@
//! Re-indexing one saved file the index already holds, patching every
//! table rather than rebuilding it — the cheap path a `didSave` takes
//! before falling back to a whole rescan.
//! before falling back to a whole rescan — and doing only the work the
//! file's change can reach (`docs/features/localized-reindex/README.md`).
use std::path::Path;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use lucisv_core::walk::dir_id;
use vlog_semantic::FileFacts;
use super::Workspace;
use crate::scan_trace::ScanTrace;
/// What [`Workspace::update_one_file`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OneFile {
/// The index does not hold the file; the caller owes a whole rebuild.
NotHeld,
/// The file's record is the one the index already held — the watcher's
/// echo of a save, or a save that changed nothing the index records — so
/// nothing derived from the index moved and no other buffer's answer can
/// have either.
Unchanged,
/// The index moved, and every open buffer's overlay was refreshed.
Changed,
}
impl Workspace {
/// [`Workspace::update_one_file`], for a test that only asks whether the
/// cheap path was taken.
#[cfg(test)]
pub fn update_one(&mut self, path: &Path) -> bool {
self.update_one_file(path) != OneFile::NotHeld
}
/// Rebuild the index for **one** file, leaving every other file's
/// contribution exactly as it is. Reports whether it could.
/// contribution exactly as it is, and say what moved.
///
/// `false` means the caller must fall back to [`Workspace::rebuild_index`]:
/// the file is not one this index already holds, which is the one case the
/// cheap path cannot settle. A file appearing changes which *other* files
/// exist as far as the include graph is concerned (a `` `include`` that had
/// nothing to resolve to now has something), and answering that takes a
/// walk — so the rule is simply "a file the index already holds".
/// [`OneFile::NotHeld`] means the caller must fall back to
/// [`Workspace::rebuild_index`]: the file is not one this index already
/// holds, which the cheap path settles only for an open buffer older than
/// the last whole scan ([`Workspace::add_open_buffer`]). A file appearing
/// changes which *other* files exist as far as the include graph is
/// concerned (a `` `include`` that had nothing to resolve to now has
/// something), and answering that takes a walk.
///
/// The four pieces of state a rebuild produces, and what happens to each:
///
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
/// * **the workspace index** — [`WorkspaceIndex::update_facts`] /
/// [`WorkspaceIndex::remove_file`], which promise the index a whole
/// rebuild over the same file set would have produced;
/// * **the completion tables** — the two index-derived ones re-derived, the
/// word table patched by this file's words alone;
/// * **the include graph** — this file's edges re-scanned, the known-file
/// and folded-spelling tables re-learned from the index's list;
/// * **every open buffer's overlay** — refreshed, exactly as a rebuild
/// refreshes it, because any of them may resolve into the file that moved.
/// rebuild over the same file set would have produced, and say when the
/// record did not move at all;
/// * **the completion tables** — the word table patched by this file's
/// words, and the two index-derived ones re-derived for the names this
/// file declared or declares, only when it now declares something
/// different ([`FileFacts::declares_the_same`]);
/// * **the include graph** — this file's edges re-scanned and re-spelled;
/// nothing else in it depends on one file's text;
/// * **every open buffer's overlay** — refreshed when the index moved,
/// because any of them may resolve into the file that moved.
///
/// The text is chosen by `collect_sources`'s rules, for one path: an open
/// buffer beats disk and is never capped; a walked file over
/// `lucisv.index.maxFileSize`, one that has been deleted, and one that
/// cannot be read are all "this file is not in the index any more".
pub fn update_one(&mut self, path: &Path) -> bool {
if !self.index.files().iter().any(|held| held == path) {
return false;
///
/// [`WorkspaceIndex::update_facts`]: vlog_semantic::WorkspaceIndex::update_facts
/// [`WorkspaceIndex::remove_file`]: vlog_semantic::WorkspaceIndex::remove_file
pub fn update_one_file(&mut self, path: &Path) -> OneFile {
if self.index.file_id(path).is_none() {
return self.add_open_buffer(path);
}
// Re-indexing one file *is* the claim that its bytes moved.
self.forget_view(path);
match self.current_text(path) {
Some(text) => {
// The same rule a whole rebuild follows: when the text came
// from an open buffer, that buffer's finished analysis is the
// facts and the words, and neither is derived from the text a
// second time. `current_text` answers with a buffer's text only
// when that buffer is not on the large-file fast path, so the
// analysis found here is a real one.
match self.analysis_of(path) {
Some((facts, words)) => {
self.index.update_facts(facts);
self.candidates.update_words(&self.index, path, words);
}
None => {
self.index.update_file(path.to_path_buf(), &text);
// The words come back out of the record the update
// just wrote, so the file is lexed once rather than
// twice (`FACTS_FORMAT` 13). A path the index somehow
// does not hold falls back to lexing, which is what
// this line always did.
match self.index.facts_for(path).map(|facts| facts.words().to_vec()) {
Some(words) => self.candidates.update_words(&self.index, path, words),
None => self.candidates.update_file(&self.index, path, &text),
}
}
}
self.includes.update_file(path, &text, self.index.files());
// Written through here too, so an hour of saves is an hour of
// work the next session does not repeat. The record is the
// one the update just made — no second parse — and it is
// keyed by the text it was made from, which is the buffer's
// when a buffer beat disk. That record is simply never hit
// again if the file on disk says something else.
// A save is the other thing that asks the store something, so
// it opens a re-open a scan deferred rather than writing into
// the store the previous rescan left in hand ([`StoreOpen`]).
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, &text);
}
}
None => {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
}
let Some(text) = self.current_text(path) else {
self.remove_one(path);
return OneFile::Changed;
};
// The same rule a whole rebuild follows: when the text came from an
// open buffer, that buffer's finished analysis is the facts and the
// words, and neither is derived from the text a second time.
// `current_text` answers with a buffer's text only when that buffer is
// not on the large-file fast path, so the analysis found here is a
// real one. Otherwise the file is parsed once, and its words come back
// out of the record (`FACTS_FORMAT` 13).
let (facts, words) = self.analysis_of(path).unwrap_or_else(|| {
let facts = FileFacts::of(path.to_path_buf(), &text);
let words = facts.words().to_vec();
(facts, words)
});
let declared = self.declared_by_either(path, &facts);
let moved = self.index.update_facts(facts);
// The include lines are not in the record — `` `include "a.svh"`` and
// `` `include <a.svh>`` can read the same to it — so they are
// re-scanned whatever the record said.
self.includes.update_held(path, &text);
self.write_through(path, &text);
if !moved {
return OneFile::Unchanged;
}
self.candidates.set_file_words(path, words);
if let Some((symbols, macros)) = declared {
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
}
self.refresh_overlays();
OneFile::Changed
}
/// The half of [`Workspace::update_one_file`] for a file the index does
/// not hold, which it can settle only for an open buffer — one opened
/// after the last whole scan took its work list, from outside the
/// filelist or under an `exclude`, which a rebuild would take in because
/// every open buffer is taken in.
///
/// What a rebuild would re-read besides the buffer is every other file's
/// `` `include``s, and the only ones the file's arrival can answer
/// differently are those whose last component could be its name — so those
/// are re-resolved ([`IncludeGraph::refresh_naming`]), from the lines the
/// graph holds, against the disk as it is now. No witness of *when* the
/// file appeared is needed, and none is trusted: a birth time was, until
/// QA showed `mv`, `cp -p` and `tar x` set it back (F3).
///
/// The index is merged whole (every id after the new one moves), which
/// is in memory and reads nothing.
///
/// [`IncludeGraph::refresh_naming`]: crate::includes::IncludeGraph::refresh_naming
fn add_open_buffer(&mut self, path: &Path) -> OneFile {
let Some((facts, words)) = self.analysis_of(path) else { return OneFile::NotHeld };
let Some(text) = self.current_text(path) else { return OneFile::NotHeld };
if self.holds_another_spelling_of(path) {
// A rebuild would take the buffer's spelling *instead of* the
// held one (`discover.rs`'s `Aliased`), which is not an add.
return OneFile::NotHeld;
}
let (symbols, macros) = facts.declared_names();
let symbols: HashSet<String> = symbols.into_iter().map(str::to_string).collect();
let macros: HashSet<String> = macros.into_iter().map(str::to_string).collect();
self.index.update_facts(facts);
self.candidates.set_file_words(path, words);
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
self.candidates.refresh_names(&self.index, &symbols, &macros);
self.includes.add_known(path);
self.includes.update_held(path, &text);
self.includes.refresh_naming(path);
self.write_through(path, &text);
self.refresh_overlays();
OneFile::Changed
}
/// Whether the index holds the file at `path` under another name — a
/// directory alias — by the test the scan's own overlay applies: the same
/// file name, then the same `(dev, ino)`.
fn holds_another_spelling_of(&self, path: &Path) -> bool {
let Some(id) = dir_id(path) else { return false };
let named = |held: &&PathBuf| held.file_name() == path.file_name();
self.index.files().iter().filter(named).any(|held| dir_id(held) == Some(id))
}
/// The half of [`Workspace::update_one_file`] for a held file that is
/// gone, capped or unreadable. The files whose `` `include``s could name
/// it are re-resolved, because their lines resolve against the disk and a
/// deleted file is no longer there to find.
fn remove_one(&mut self, path: &Path) {
self.index.remove_file(path);
self.candidates.remove_file(&self.index, path);
self.includes.remove_file(path, self.index.files());
self.includes.refresh_naming(path);
self.refresh_overlays();
}
/// Files appeared, vanished or moved at `paths`, wherever they are: the
/// include lines that could name any of them are re-resolved, in one pass.
/// The whole of what such an event owes the graph for a file the index
/// does not hold.
pub fn refresh_includes_naming(&mut self, paths: &[PathBuf]) {
self.includes.refresh_naming_all(paths);
}
/// The names the held record and `facts` put in the completion tables'
/// listings, both records' together — or `None` when the two declare the
/// same things ([`FileFacts::declares_the_same`]) and no listing can move.
fn declared_by_either(
&self,
path: &Path,
facts: &FileFacts,
) -> Option<(HashSet<String>, HashSet<String>)> {
let held = self.index.facts_for(path)?;
if held.declares_the_same(facts) {
return None;
}
let mut symbols: HashSet<String> = HashSet::new();
let mut macros: HashSet<String> = HashSet::new();
for record in [held, facts] {
let (names, defines) = record.declared_names();
symbols.extend(names.into_iter().map(str::to_string));
macros.extend(defines.into_iter().map(str::to_string));
}
Some((symbols, macros))
}
/// Write the file's record through to the persistent store, so an hour of
/// saves is an hour of work the next session does not repeat. The record
/// is the one the update just made — no second parse — and it is keyed by
/// the text it was made from, which is the buffer's when a buffer beat
/// disk; that record is simply never hit again if the file on disk says
/// something else. A save is the other thing that asks the store
/// something, so it opens a re-open a scan deferred rather than writing
/// into the store the previous rescan left in hand ([`StoreOpen`]).
///
/// [`StoreOpen`]: super::StoreOpen
fn write_through(&mut self, path: &Path, text: &str) {
self.open_store(&mut ScanTrace::default());
if let Some(facts) = self.index.facts_for(path) {
self.cache.record(facts, text);
}
}
/// Re-resolve every open buffer's cross-file references against the index
/// as it now stands, exactly as a rebuild does.
fn refresh_overlays(&mut self) {
for doc in self.docs.values_mut() {
doc.refresh_overlay(&self.index);
}
true
}
/// [`Workspace::update_one`], then a whole rebuild over the same
@@ -99,20 +234,39 @@ impl Workspace {
///
/// It is the incremental path's whole claim, checked rather than argued:
/// the index's fingerprint (ids, disambiguation order, member tables,
/// edges, define counts) and the completion word table, which is the one
/// piece of derived state that is patched rather than re-derived. The
/// workspace is left holding the *rebuilt* index, which is the same index,
/// so a test may keep using it.
/// edges, define counts, postings and who read what), the completion
/// tables and the include graph. The workspace is left holding the
/// *rebuilt* index, which is the same index, so a test may keep using it.
#[cfg(test)]
pub fn update_one_checked(&mut self, path: &Path) -> bool {
if !self.update_one(path) {
return false;
}
let index = self.index.fingerprint();
let words = self.candidates.words("").to_vec();
let before = self.derived_fingerprint();
self.rebuild_index();
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
assert_eq!(before, self.derived_fingerprint(), "incremental state != rebuilt state");
true
}
/// Everything a rebuild derives from the sources, rendered for comparison:
/// the index, the completion tables, the include graph and every open
/// buffer's cross-file answers.
#[cfg(test)]
pub fn derived_fingerprint(&self) -> String {
let mut docs: Vec<(&lsp_types::Uri, &super::Document)> = self.docs.iter().collect();
docs.sort_by_key(|(uri, _)| uri.as_str());
let overlays: Vec<String> = docs
.iter()
.map(|(uri, doc)| {
format!("{} {:?}", uri.as_str(), doc.external.iter().collect::<Vec<_>>())
})
.collect();
format!(
"{}\n{}\n{}\n{}",
self.index.fingerprint(),
self.candidates.fingerprint(),
self.includes.fingerprint(),
overlays.join("\n")
)
}
}
+3
View File
@@ -36,13 +36,16 @@ mod scan;
mod scope;
mod sources;
mod views;
mod watched;
#[cfg(test)]
pub use document::mixed_buffer;
pub use document::{first_token_from, first_token_reaching, Document};
pub use incremental::OneFile;
pub use port_grace::PortGrace;
pub use scan::{IndexEvent, Scan};
pub use views::FileView;
pub use watched::Watched;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
/// to turn its byte span into a line, so an unbounded answer to the empty
@@ -25,6 +25,7 @@ mod large_file;
mod lazy_read;
mod open_buffers;
mod persistence;
mod reindex_perf;
mod settings;
mod size_cap;
mod views;
@@ -0,0 +1,206 @@
//! What a save and a keystroke cost the index at OpenTitan scale — the
//! measurements behind `docs/features/localized-reindex/README.md`.
//!
//! Every test here is `#[ignore]`d and asserts nothing but its premises; run
//! them in release, one at a time, through the guard:
//!
//! `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`
//!
//! The tree is `$LUCISV_OPENTITAN` or `~/.cache/lucisv-opentitan-full/hw`;
//! without it every probe says so and returns.
use std::time::{Duration, Instant};
use vlog_semantic::{FileId, SymbolKind};
use super::*;
/// The OpenTitan `hw` tree, when this machine has one.
pub(super) fn opentitan() -> Option<PathBuf> {
let root = std::env::var_os("LUCISV_OPENTITAN").map(PathBuf::from).or_else(|| {
std::env::var_os("HOME")
.map(|home| PathBuf::from(home).join(".cache/lucisv-opentitan-full/hw"))
})?;
root.is_dir().then_some(root)
}
/// A workspace over the whole OpenTitan tree, with `open` buffers open.
fn opentitan_workspace(root: &Path, open: &[&str]) -> Workspace {
let mut ws = Workspace::default();
ws.set_client_settings(wide(ClientSettings::default()));
ws.open_whole_workspace(vec![root.to_path_buf()]);
for rel in open {
let path = root.join(rel);
let text = fs::read_to_string(&path).expect("the probe's files are on disk");
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
}
ws
}
fn median(mut runs: Vec<Duration>) -> Duration {
runs.sort();
runs[runs.len() / 2]
}
/// The edits a save is measured after: each is applied to the buffer, then
/// `update_one` runs, then the buffer is put back and updated again.
fn edits(text: &str) -> Vec<(&'static str, String)> {
let body = text.rfind("endmodule").or_else(|| text.rfind("endpackage")).unwrap_or(text.len());
let first = text.find('\n').map_or(0, |at| at + 1);
vec![
("no change (the watcher's echo of a save)", text.to_string()),
("comment appended", format!("{text}\n// an edit\n")),
(
"local signal added",
format!("{} logic probe_local_q;\n{}", &text[..body], &text[body..]),
),
("comment above everything", format!("{}// an edit\n{}", &text[..first], &text[first..])),
]
}
const TARGETS: [&str; 5] = [
"ip/uart/rtl/uart_tx.sv",
"ip/prim_generic/rtl/prim_flop.sv",
"ip/uart/rtl/uart_reg_pkg.sv",
"ip/prim/rtl/prim_assert.sv",
"top_earlgrey/rtl/autogen/top_earlgrey.sv",
];
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_one_saved_file_costs_the_index_at_opentitan_scale() {
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let mut ws = opentitan_workspace(&root, &TARGETS);
assert!(ws.index().files().len() > 3_000, "premise: the whole tree is indexed");
for rel in TARGETS {
let path = root.join(rel);
let uri = crate::uri::path_to_uri(&path).expect("uri");
let text = fs::read_to_string(&path).expect("on disk");
for (what, edited) in edits(&text) {
let mut runs = Vec::new();
for _ in 0..5 {
ws.set_document(uri.clone(), edited.clone());
let started = Instant::now();
assert!(ws.update_one(&path), "premise: a held file");
runs.push(started.elapsed());
ws.set_document(uri.clone(), text.clone());
ws.update_one(&path);
}
eprintln!("update_one {rel}, {what}: median {:?}", median(runs));
}
}
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() {
// The three census rules ask `mentioned_outside` once per candidate
// declaration; every net and variable a file declares is the upper bound
// of what one lint pass over that file can ask.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let index = ws.index();
let (mut calls, mut total, mut worst) = (0usize, Duration::ZERO, (Duration::ZERO, 0, None));
for (id, path) in index.files().iter().enumerate() {
let Ok(text) = fs::read_to_string(path) else { continue };
let doc = Document::new(Some(path.clone()), text, index);
let names: Vec<&str> = doc
.semantics
.symbols()
.iter()
.filter(|s| matches!(s.kind, SymbolKind::Net | SymbolKind::Var))
.map(|s| s.name.as_str())
.collect();
let started = Instant::now();
for name in &names {
std::hint::black_box(index.mentioned_outside(name, Some(FileId(id as u32))));
}
let took = started.elapsed();
calls += names.len();
total += took;
if took > worst.0 {
worst = (took, names.len(), Some(path.clone()));
}
}
eprintln!(
"mention census over {} files: {calls} questions, {:?} each on average; \
worst file {:?} asks {} for {:?}",
index.files().len(),
total / calls.max(1) as u32,
worst.2,
worst.1,
worst.0
);
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_census_adds_to_a_real_lint_pass_at_opentitan_scale() {
// The bound above is every declaration; this is what the rules really
// ask: one buffer's whole lint pass against the indexed workspace, and the
// same pass with no workspace (no census at all), file by file.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let alone = Workspace::default();
let mut added: Vec<(Duration, Duration, PathBuf)> = Vec::new();
for path in ws.index().files() {
let Ok(text) = fs::read_to_string(path) else { continue };
// A fresh document per pass: a document remembers its last lint
// pass (`lint_snapshot`), and a remembered pass costs nothing.
let lint = |within: &Workspace| {
let doc = Document::new(Some(path.clone()), text.clone(), ws.index());
let started = Instant::now();
let run = crate::lint::LintRun::for_document(within, &doc);
std::hint::black_box(crate::diagnostics::all_in(&doc, &run));
started.elapsed()
};
let with = median((0..3).map(|_| lint(&ws)).collect());
let without = median((0..3).map(|_| lint(&alone)).collect());
added.push((with.saturating_sub(without), with, path.clone()));
}
added.sort();
let total: Duration = added.iter().map(|(d, _, _)| *d).sum();
eprintln!(
"census share of a lint pass over {} files: {:?} on average",
added.len(),
total / added.len().max(1) as u32
);
for (delta, with, path) in added.iter().rev().take(5) {
eprintln!(" {delta:?} of {with:?} in {}", path.display());
}
}
#[test]
#[ignore = "perf measurement over OpenTitan — see docs/features/localized-reindex/README.md"]
fn what_the_readers_table_holds_at_opentitan_scale() {
// The memory the narrowing costs: one key per table entry any file's
// resolution read, and one file id per reader of it — read back out of
// the fingerprint, which renders the table line by line.
let Some(root) = opentitan() else {
eprintln!("no OpenTitan tree — skipping");
return;
};
let ws = opentitan_workspace(&root, &[]);
let fingerprint = ws.index().fingerprint();
let lines: Vec<&str> = fingerprint.lines().filter(|line| line.starts_with("read ")).collect();
let readers: usize = lines.iter().map(|line| line.matches(',').count() + 1).sum();
let key_bytes: usize =
lines.iter().filter_map(|line| line.split(' ').nth(2)).map(str::len).sum();
eprintln!(
"readers table over {} files: {} keys ({} KiB of key text), {} reader entries ({} KiB of ids)",
ws.index().files().len(),
lines.len(),
key_bytes / 1024,
readers,
readers * 4 / 1024
);
}
+156
View File
@@ -0,0 +1,156 @@
//! What one path a file watcher named is to the index: a file it holds
//! (perhaps under another spelling), a file the scope provably cannot take,
//! or neither — which only a rescan can settle
//! (`docs/features/localized-reindex/README.md`).
//!
//! A watcher event for a `.sv` the index does not hold used to be a whole
//! rescan, progress bar and all, every time: a generated file under a
//! gitignored build directory, a file outside the folder scope or the
//! filelist, or a held file reported by its real path under a symlinked root.
//! Only the last kind of file can change what the index says, and none of
//! them needs the walk to find that out.
use std::fs;
use std::path::{Path, PathBuf};
use lucisv_core::config::Discovery;
use lucisv_core::walk::collect_files_below;
use super::discover::{oversize, Found};
use super::Workspace;
/// What a watched path is to the index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Watched {
/// A file the index holds, by the spelling it holds it under — or an
/// open buffer it does not hold yet, which a rebuild would take in and the
/// one-file path adds (QA F4).
Held(PathBuf),
/// A file no scan of the scope in force would index. Nothing to do for
/// the index.
Outside,
/// A file the scope may take and the index does not hold: a new file, or
/// one the cap kept out until now. Only a rescan can say.
Unknown,
}
impl Workspace {
/// What `path` is to the index. Errs towards [`Watched::Unknown`]: a
/// wasted rescan costs time, a skipped one would cost a stale index.
pub fn watched(&self, path: &Path) -> Watched {
if let Some(held) = self.held_spelling(path) {
return Watched::Held(held);
}
if self.docs.values().any(|doc| doc.path.as_deref() == Some(path)) {
return Watched::Held(path.to_path_buf());
}
match self.scope_could_take(path) {
true => Watched::Unknown,
false => Watched::Outside,
}
}
/// The spelling the index holds `path` under: `path` itself, or the same
/// file reached through a scope directory's other name — a symlinked root,
/// or a different case on a case-insensitive disk. Resolved through the
/// directories the scope is anchored at, so it costs a handful of
/// `canonicalize` calls rather than one per held file.
fn held_spelling(&self, path: &Path) -> Option<PathBuf> {
let holds = |path: &Path| self.index.file_id(path).is_some();
if holds(path) {
return Some(path.to_path_buf());
}
let real = canonical(path)?;
let mut anchors: Vec<PathBuf> = self.roots.clone();
anchors.extend(self.scope_dirs());
anchors.into_iter().find_map(|anchor| {
let rest = real.strip_prefix(fs::canonicalize(&anchor).ok()?).ok()?;
let spelled = anchor.join(rest);
holds(&spelled).then_some(spelled)
})
}
/// Whether a scan of the scope in force could index `path` — `false` only
/// when it provably could not: a filelist that does not list it, or a
/// walk of the scope's directories that does not find it or finds it over
/// `lucisv.index.maxFileSize`. The walk is `lucisv_core`'s own, rooted
/// where the scan's is, so `.gitignore`, `exclude` and the config's
/// excludes rule it out exactly as they rule it out of a scan.
fn scope_could_take(&self, path: &Path) -> bool {
if let Some(list) = self.filelist_path() {
// An unreadable filelist sends the scan to the rungs below, and
// so it sends this.
if let Ok(list) = lucisv_core::filelist::read(&list) {
return list.files.iter().any(|listed| same_file(listed, path));
}
}
let Some(dir) = path.parent() else { return true };
let dirs = match self.walks_the_workspace() {
true => self.roots.clone(),
false => self.scope_dirs(),
};
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
// The flat read of a rootless session: siblings only.
return dirs.iter().any(|scope| scope == dir);
}
dirs.iter()
.filter(|scope| path.starts_with(scope))
.any(|scope| self.walk_finds(scope, path))
}
/// Whether a walk of `scope` finds `path` under its cap.
fn walk_finds(&self, scope: &Path, path: &Path) -> bool {
let Some(dir) = path.parent() else { return true };
let excludes = self.walk_excludes(&mut Discovery::new(true), scope);
let mut found = None;
let take = &mut |file: PathBuf, len| {
if file == path {
found = Some(Found { path: file, len });
}
};
if collect_files_below(scope, dir, &excludes, true, take, &mut |_| {}).is_err() {
// The directory is gone or unreadable: nothing in it can be read
// either, and the scan would say the same.
return false;
}
found.is_some_and(|found| oversize(&found, self.client.max_file_size, &mut 0).is_none())
}
/// The exclude patterns a walk rooted at `dir` applies: the governing
/// config's, then the client's `lucisv.exclude`. *Appended*, never
/// substituted — the CLI appends a config's excludes to `--exclude` the
/// same way, and a setting that silently dropped a checked-in exclude
/// would put vendored code back in the index for one user only.
pub(super) fn walk_excludes(&self, discovery: &mut Discovery, dir: &Path) -> Vec<String> {
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a server
// that comes up empty. The error is reported when the user formats a
// file in this tree (`format::settings_for`).
let mut exclude = discovery.for_dir(dir).unwrap_or_default().exclude.unwrap_or_default();
exclude.extend(self.client.exclude.iter().cloned());
exclude
}
}
/// Whether two spellings name one file: equal, or equal once resolved. The
/// names are compared first, case-insensitively, so a filelist of thousands
/// costs a resolution only for the entries that could be the one.
fn same_file(listed: &Path, path: &Path) -> bool {
if listed == path {
return true;
}
let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().to_lowercase());
name(listed) == name(path)
&& canonical(listed).is_some()
&& canonical(listed) == canonical(path)
}
/// `path` with every symlink resolved and, on a case-insensitive disk, every
/// component in the case the disk holds it in. A file that is gone resolves
/// through its directory, so a deletion can still be matched.
fn canonical(path: &Path) -> Option<PathBuf> {
fs::canonicalize(path).ok().or_else(|| {
let real = fs::canonicalize(path.parent()?).ok()?;
Some(real.join(path.file_name()?))
})
}
+20 -13
View File
@@ -112,16 +112,16 @@ pub fn touches_scope(changes: &[FileEvent], filelist: Option<&Path>) -> bool {
.any(|path| watched(&path, filelist))
}
/// The one file an event named, when it named exactly one and that one is not
/// the filelist.
/// Every path an event named that the index reads, each once and in order —
/// or `None` when one of them is the filelist, whose change moves the whole
/// scope and is a rebuild by definition. A client is free to send `Changed`
/// and `Created` for one file, and that is still one file.
///
/// The gate on the incremental rescan path (`server.rs`'s `reindex_one`): a
/// checkout fills this list, and a list of one is the case a single file's
/// contribution can be replaced in place. The filelist is excluded because a
/// change to it moves the whole scope, which is a rebuild by definition. An
/// event naming the same path twice — a client is free to send `Changed` and
/// `Created` for one file — is still one file.
pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<PathBuf> {
/// What `server/index.rs`'s `reindex_watched` sorts into held, outside and
/// unknown files (`docs/features/localized-reindex/README.md`); until
/// 2026-11-19 this was `one_scope_file`, which gave up on any list longer
/// than one.
pub fn scope_files(changes: &[FileEvent], filelist: Option<&Path>) -> Option<Vec<PathBuf>> {
let mut named: Vec<PathBuf> = changes
.iter()
.filter_map(|change| uri_to_path(&change.uri))
@@ -129,10 +129,17 @@ pub fn one_scope_file(changes: &[FileEvent], filelist: Option<&Path>) -> Option<
.collect();
named.sort();
named.dedup();
match named.as_slice() {
[only] if Some(only.as_path()) != filelist => Some(only.clone()),
_ => None,
}
(!named.iter().any(|path| Some(path.as_path()) == filelist)).then_some(named)
}
/// Whether an event names a `lucisv.toml` (either spelling) — a change to
/// which moves the scope's excludes and filelist and the lint configuration
/// together. The names are `lucisv_core::config::NAMES`, the CLI's own.
pub fn names_a_config(changes: &[FileEvent]) -> bool {
changes.iter().filter_map(|change| uri_to_path(&change.uri)).any(|path| {
let name = path.file_name().and_then(|n| n.to_str());
name.is_some_and(|n| lucisv_core::config::NAMES.contains(&n))
})
}
/// Whether one path is something the index reads: a source file, or the
+6
View File
@@ -4873,6 +4873,12 @@ fn a_save_asks_a_capable_client_to_refresh_its_code_lenses_over_the_wire() {
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
serde_json::to_string(LENS_SUB).expect("json")
)),
// An edit before the save: a save that moved nothing the index
// records refreshes nothing (localized-reindex, 2026-11-19).
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
serde_json::to_string(&format!("{LENS_SUB}module lens_extra;\nendmodule\n")).expect("json")
)),
frame(&format!(
r#"{{"jsonrpc":"2.0","method":"textDocument/didSave","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
)),
@@ -0,0 +1,152 @@
//! Which files' references read which merged-table keys: recorded while a
//! file's references are resolved, and asked when an update moves a key, so
//! that only the files that read it are resolved again
//! (`docs/features/localized-reindex/README.md`).
//!
//! The recording is a thread-local switch rather than a parameter because the
//! resolution walk (`external.rs`, `reexport.rs`, `hierarchy.rs`) is shared
//! with every request-time caller through a dozen functions that take a
//! `&WorkspaceIndex`; threading a recorder through all of them would change
//! every signature for the one caller that wants it. The lookups note what
//! they read with [`note`], which costs one thread-local check when nothing is
//! recording — every request — and the index's own pass turns it on with
//! [`recording`]. `lint_trace` and `scan_trace` use the same shape.
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use super::FileId;
/// A merged table a resolution reads, named by what its key is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Table {
/// `units`, by file-scope name.
Unit = 0,
/// `members`, by the unit that exports the member.
Container = 1,
/// `hier_members`, by the unit that declares the member.
Hier = 2,
/// `bases`, by the class whose base it records.
Base = 3,
/// `reexports`, by the exporting package.
Exporter = 4,
}
const TABLES: [Table; 5] =
[Table::Unit, Table::Container, Table::Hier, Table::Base, Table::Exporter];
/// The keys one resolution pass read, table by table — misses included: a
/// lookup that found nothing is exactly the one a new declaration answers.
#[derive(Debug, Default)]
pub(super) struct Reads {
keys: [HashSet<String>; 5],
}
thread_local! {
static RECORDING: RefCell<Option<Reads>> = const { RefCell::new(None) };
}
/// Note that the resolution running on this thread read `table` under `key`.
pub(super) fn note(table: Table, key: &str) {
RECORDING.with(|cell| {
if let Some(reads) = cell.borrow_mut().as_mut() {
let keys = &mut reads.keys[table as usize];
if !keys.contains(key) {
keys.insert(key.to_string());
}
}
});
}
/// Run `body` and say every key it read. Nests: an outer recording is put
/// back afterwards, untouched by the inner one.
pub(super) fn recording<R>(body: impl FnOnce() -> R) -> (R, Reads) {
let outer = RECORDING.with(|cell| cell.replace(Some(Reads::default())));
let out = body();
let reads = RECORDING.with(|cell| cell.replace(outer)).unwrap_or_default();
(out, reads)
}
/// Key → the files whose last resolution read it, each list sorted and
/// without repeats.
///
/// It holds exactly what resolving every file against the tables as they
/// stand would record, which is what makes "the files that read a moved key"
/// a sound answer to "whose postings can have moved": a file that read no
/// moved key read only values that did not change, so its resolution — a pure
/// function of its own facts and those values — did not change either.
#[derive(Debug, Clone, Default)]
pub(super) struct Dependents {
readers: [HashMap<String, Vec<FileId>>; 5],
}
impl Dependents {
/// Forget every reader, for a rebuild from the records.
pub(super) fn clear(&mut self) {
self.readers.iter_mut().for_each(HashMap::clear);
}
/// Record that `file` read everything in `reads`.
pub(super) fn add(&mut self, file: FileId, reads: Reads) {
for (table, keys) in reads.keys.into_iter().enumerate() {
for key in keys {
let files = self.readers[table].entry(key).or_default();
// A whole rebuild adds files in id order, so the common case
// is a push; an update re-adds a few files in the middle.
match files.last() {
Some(last) if *last >= file => {
if let Err(at) = files.binary_search(&file) {
files.insert(at, file);
}
}
_ => files.push(file),
}
}
}
}
/// Take back what [`Dependents::add`] recorded for `file`.
pub(super) fn remove(&mut self, file: FileId, reads: &Reads) {
for (table, keys) in reads.keys.iter().enumerate() {
for key in keys {
let Some(files) = self.readers[table].get_mut(key) else { continue };
if let Ok(at) = files.binary_search(&file) {
files.remove(at);
}
if files.is_empty() {
self.readers[table].remove(key);
}
}
}
}
/// Take back everything recorded for every file `gone` says, by one pass
/// over the whole table.
pub(super) fn remove_all(&mut self, gone: &dyn Fn(FileId) -> bool) {
for readers in &mut self.readers {
readers.retain(|_, files| {
files.retain(|file| !gone(*file));
!files.is_empty()
});
}
}
/// The files that read `table` under `key`.
pub(super) fn readers(&self, table: Table, key: &str) -> &[FileId] {
self.readers[table as usize].get(key).map_or(&[], Vec::as_slice)
}
/// Every reader, one sorted line per key — for the index's fingerprint, so
/// the equivalence tests hold this table to a rebuild's as well.
pub(super) fn render(&self, out: &mut String) {
for table in TABLES {
let mut keys: Vec<(&String, &Vec<FileId>)> =
self.readers[table as usize].iter().collect();
keys.sort();
for (key, files) in keys {
let ids: Vec<u32> = files.iter().map(|file| file.0).collect();
out.push_str(&format!("read {table:?} {key} by {ids:?}\n"));
}
}
}
}
+23 -4
View File
@@ -13,6 +13,7 @@ use vlog_parser::defines::{Define, DefineTable};
use crate::model::{Surface, SymbolKind};
use super::dependents::{note, Table};
use super::external::{fold_path, last_segment, member_chain, own_members};
use super::hierarchy;
use super::record::{FileFacts, ReferenceFact};
@@ -67,6 +68,7 @@ impl WorkspaceIndex {
/// in disambiguation order (by file path, then by position in the file).
/// More than one means the workspace really does declare the name twice.
pub fn units(&self, name: &str) -> &[Def] {
note(Table::Unit, name);
self.units.get(name).map_or(&[], Vec::as_slice)
}
@@ -80,6 +82,7 @@ impl WorkspaceIndex {
/// hierarchical path may name besides is
/// [`WorkspaceIndex::member_in`]'s business ([`Surface`]).
pub fn member(&self, unit: &str, member: &str) -> &[Def] {
note(Table::Container, unit);
self.members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
@@ -95,6 +98,7 @@ impl WorkspaceIndex {
/// — the completion list behind `p::` and behind an instantiation's
/// connection list.
pub fn members_of(&self, unit: &str) -> impl Iterator<Item = (&str, &[Def])> {
note(Table::Container, unit);
self.members
.get(unit)
.into_iter()
@@ -108,6 +112,7 @@ impl WorkspaceIndex {
&self,
unit: &str,
) -> impl Iterator<Item = (&str, &[Def])> {
note(Table::Hier, unit);
self.hier_members
.get(unit)
.into_iter()
@@ -116,6 +121,7 @@ impl WorkspaceIndex {
/// [`WorkspaceIndex::member`] on the hierarchical-only half alone.
pub(super) fn hierarchical_member(&self, unit: &str, member: &str) -> &[Def] {
note(Table::Hier, unit);
self.hier_members.get(unit).and_then(|m| m.get(member)).map_or(&[], Vec::as_slice)
}
@@ -187,6 +193,7 @@ impl WorkspaceIndex {
/// edges `reexport`'s two walks follow. Empty for every unit that
/// re-exports nothing, which is all but a handful in any workspace.
pub(super) fn reexports(&self, unit: &str) -> &[Reexport] {
note(Table::Exporter, unit);
self.reexports.get(unit).map_or(&[], Vec::as_slice)
}
@@ -262,6 +269,7 @@ impl WorkspaceIndex {
/// declare — which is what ends the chase in
/// [`resolve_external`](super::resolve_external).
pub fn base_of(&self, name: &str) -> Option<&str> {
note(Table::Base, name);
self.bases.get(name).map(String::as_str)
}
@@ -315,7 +323,7 @@ impl WorkspaceIndex {
/// Whether at least one use could name `def` or another declaration equally.
pub fn references_are_ambiguous(&self, def: &Def) -> bool {
self.ambiguous_references.contains(&DefinitionKey::of(def))
self.ambiguous_references.contains_key(&DefinitionKey::of(def))
}
/// Every file holding a use spelled `name` that this index had to look
@@ -429,15 +437,26 @@ impl WorkspaceIndex {
/// sorted by name and is not truncated, so a caller with a result limit
/// applies its own.
pub fn workspace_symbols(&self, query: &str) -> Vec<WorkspaceSymbol<'_>> {
self.symbols_where(|name| contains_ignore_ascii_case(name, query))
}
/// [`WorkspaceIndex::workspace_symbols`] for exactly these names, in the
/// same order — what a table built from the whole listing re-derives for
/// the names one update touched (`docs/features/localized-reindex`).
pub fn symbols_named(&self, names: &HashSet<&str>) -> Vec<WorkspaceSymbol<'_>> {
self.symbols_where(|name| names.contains(name))
}
fn symbols_where(&self, keep: impl Fn(&str) -> bool) -> Vec<WorkspaceSymbol<'_>> {
let mut out = Vec::new();
for (name, defs) in &self.units {
if contains_ignore_ascii_case(name, query) {
if keep(name) {
out.extend(defs.iter().map(|def| WorkspaceSymbol { name, container: None, def }));
}
}
for (unit, members) in &self.members {
for (name, defs) in members {
if contains_ignore_ascii_case(name, query) {
if keep(name) {
out.extend(defs.iter().map(|def| WorkspaceSymbol {
name,
container: Some(unit),
@@ -626,7 +645,7 @@ impl IndexBuilder {
facts: self.files,
..WorkspaceIndex::default()
};
index.merge(None);
index.merge();
index
}
}
+16 -3
View File
@@ -24,21 +24,26 @@
//! two member surfaces holds what, and the reads that take a
//! [`crate::Surface`] instead of assuming one.
mod dependents;
mod external;
mod hierarchy;
mod index;
mod path_units;
mod record;
mod reexport;
mod references;
mod replace;
mod update;
pub use external::{resolve_external, Definition, ExternalResolutions, ExternalTarget};
pub use index::{index_order, IndexBuilder};
pub use record::FileFacts;
use dependents::Dependents;
pub(crate) use record::{Decl, ReferenceFact, SiteFact};
pub(crate) use reexport::Reexport;
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use vlog_parser::span::TextRange;
@@ -326,10 +331,18 @@ pub struct WorkspaceIndex {
macro_definitions: BTreeMap<String, Vec<(FileId, usize)>>,
/// Declaration → every unambiguous use, in file then source order.
reference_sites: BTreeMap<DefinitionKey, Vec<ReferenceSite>>,
/// Declarations touched by at least one ambiguous external reference.
/// Declarations touched by at least one ambiguous external reference,
/// each with how many such references touch it — counted so one file's
/// references can be taken back without re-resolving the rest.
/// Find-references refuses those rather than assigning the use to one of
/// several equally plausible declarations.
ambiguous_references: HashSet<DefinitionKey>,
ambiguous_references: HashMap<DefinitionKey, u32>,
/// The same, by the file whose references contributed them — so a sweep
/// can take a file's share back without re-resolving it.
ambiguous_by_file: HashMap<FileId, Vec<DefinitionKey>>,
/// Which files' references read which table keys — what lets an update
/// re-resolve only the files that read a key it moved.
dependents: Dependents,
}
/// The headline numbers of a built index.
+53 -1
View File
@@ -11,7 +11,7 @@ use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
use vlog_parser::span::TextRange;
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
@@ -271,6 +271,58 @@ impl FileFacts {
pub fn path(&self) -> &Path {
&self.path
}
/// Whether `other` declares what this record declares, as far as
/// [`WorkspaceIndex::workspace_symbols`](super::WorkspaceIndex::workspace_symbols)
/// and the `` `define`` table can see — the same units and
/// connection-surface members by name, kind and owning unit, in the order
/// that listing sorts them, and the same `` `define``s with the same
/// parameters in the same order — wherever in the file they now sit.
///
/// The completion tables are built from exactly those two views, so an
/// edit that moved no such declaration (a body change, a comment, a new
/// local signal) leaves them as they were and need not re-derive them
/// (`docs/features/localized-reindex/README.md`).
pub fn declares_the_same(&self, other: &FileFacts) -> bool {
let define = |define: &Define| (define.name.clone(), define.params.clone());
let defines = |facts: &FileFacts| -> Vec<(String, Option<Vec<String>>)> {
let entries = facts.defines.entries().iter();
entries.filter(|d| d.kind == DefineKind::Define).map(define).collect()
};
self.symbol_view() == other.symbol_view() && defines(self) == defines(other)
}
/// Every name this file puts in the workspace-symbol listing — its units
/// and its connection-surface members — and every macro it `` `define``s:
/// what a table built from those listings re-derives when the file moves.
pub fn declared_names(&self) -> (HashSet<&str>, HashSet<&str>) {
let units = self.units.iter().map(|decl| decl.name.as_str());
let members = self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection);
let symbols = units.chain(members.map(|(_, decl)| decl.name.as_str())).collect();
let entries = self.defines.entries().iter();
let macros =
entries.filter(|d| d.kind == DefineKind::Define).map(|d| d.name.as_str()).collect();
(symbols, macros)
}
/// This file's workspace symbols, spans aside: `(name, container, kind)`
/// in `workspace_symbols`' order, which within one file is by name, then
/// container, then position.
fn symbol_view(&self) -> Vec<(&str, Option<&str>, SymbolKind)> {
let units = self
.units
.iter()
.map(|decl| (decl.name.as_str(), None, decl.name_span.start, decl.kind));
let members =
self.members.iter().filter(|(_, decl)| decl.surface == Surface::Connection).map(
|(unit, decl)| {
(decl.name.as_str(), Some(unit.as_str()), decl.name_span.start, decl.kind)
},
);
let mut view: Vec<_> = units.chain(members).collect();
view.sort_by(|a, b| (a.0, a.1, a.2).cmp(&(b.0, b.1, b.2)));
view.into_iter().map(|(name, container, _, kind)| (name, container, kind)).collect()
}
}
/// One file's two identifier censuses, both read off the same token stream:
@@ -0,0 +1,176 @@
//! The declaration → use postings, built from every file's reference facts or
//! re-done for a few files: what an update calls once it knows which files
//! read a key it moved (`docs/features/localized-reindex/README.md`).
use std::collections::HashSet;
use super::dependents::{recording, Reads};
use super::external::{resolve_fact, ExternalTarget};
use super::record::ReferenceFact;
use super::{DefinitionKey, FileId, ReferenceSite, WorkspaceIndex};
/// What one reference puts into the postings.
enum Posting {
/// One use of one declaration.
Site(DefinitionKey, ReferenceSite),
/// A use that could name any of these declarations equally.
Ambiguous(Vec<DefinitionKey>),
}
impl WorkspaceIndex {
/// Rebuild every posting, the ambiguity counts and the readers table from
/// every file's facts.
pub(super) fn merge_references(&mut self) {
self.reference_sites.clear();
self.ambiguous_references.clear();
self.ambiguous_by_file.clear();
self.dependents.clear();
let every: Vec<FileId> = (0..self.facts.len()).map(|id| FileId(id as u32)).collect();
self.resolve_files(&every);
}
/// Put `files`' postings in, resolved against the tables as they stand.
///
/// `files` is in id order, and each file's postings go in after every
/// posting of a lower-numbered file and before every higher one — the
/// order [`WorkspaceIndex::merge_references`] produces by visiting the
/// files in that order, so a few files re-done in place give the lists a
/// whole rebuild gives.
pub(super) fn resolve_files(&mut self, files: &[FileId]) {
for &file in files {
let (postings, reads) = self.postings_of(file);
for posting in postings {
match posting {
Posting::Site(key, site) => {
let sites = self.reference_sites.entry(key).or_default();
let at = sites.partition_point(|held| held.file <= file);
sites.insert(at, site);
}
Posting::Ambiguous(keys) => {
for key in keys {
*self.ambiguous_references.entry(key).or_default() += 1;
self.ambiguous_by_file.entry(file).or_default().push(key);
}
}
}
}
self.dependents.add(file, reads);
}
}
/// Take `files`' postings out again.
///
/// Re-resolving them against the tables as they stand finds exactly what
/// [`WorkspaceIndex::resolve_files`] put in, because those are the tables
/// it was put in against — every update keeps the postings equal to a
/// resolution of every file over the current tables, and resolution is a
/// pure function of the two. So nothing per file has to be remembered to
/// undo it.
pub(super) fn unresolve_files(&mut self, files: &[FileId]) {
let leaving: HashSet<FileId> = files.iter().copied().collect();
let mut touched: HashSet<DefinitionKey> = HashSet::new();
for &file in files {
let (postings, reads) = self.postings_of(file);
for posting in postings {
match posting {
Posting::Site(key, _) => {
touched.insert(key);
}
Posting::Ambiguous(keys) => {
keys.iter().for_each(|key| self.forget_ambiguity(key))
}
}
}
self.dependents.remove(file, &reads);
self.ambiguous_by_file.remove(&file);
}
for key in touched {
let Some(sites) = self.reference_sites.get_mut(&key) else { continue };
sites.retain(|site| !leaving.contains(&site.file));
if sites.is_empty() {
self.reference_sites.remove(&key);
}
}
}
/// [`WorkspaceIndex::unresolve_files`] by one pass over the postings
/// rather than by re-resolving `files`: every site a file put in is
/// dropped wherever it is, its ambiguity taken back from what it is
/// recorded to have contributed, and its id struck from every reader
/// list. Linear in the postings, not in `files` — the cheaper way out when
/// `files` hold a large share of every reference (a package most of the
/// tree imports), where re-resolving them would be most of a whole merge.
pub(super) fn unresolve_by_sweep(&mut self, files: &[FileId]) {
let mut leaving = vec![false; self.facts.len()];
for file in files {
if let Some(slot) = leaving.get_mut(file.0 as usize) {
*slot = true;
}
}
let gone = |file: FileId| leaving.get(file.0 as usize).copied().unwrap_or(false);
self.reference_sites.retain(|_, sites| {
sites.retain(|site| !gone(site.file));
!sites.is_empty()
});
for file in files {
for key in self.ambiguous_by_file.remove(file).unwrap_or_default() {
self.forget_ambiguity(&key);
}
}
self.dependents.remove_all(&gone);
}
/// How many references `files` hold, against how many every file holds —
/// the two numbers that choose between the two ways out.
pub(super) fn reference_share(&self, files: &[FileId]) -> (usize, usize) {
let count =
|file: &FileId| self.facts.get(file.0 as usize).map_or(0, |f| f.references.len());
let total = self.facts.iter().map(|facts| facts.references.len()).sum();
(files.iter().map(count).sum(), total)
}
fn forget_ambiguity(&mut self, key: &DefinitionKey) {
let Some(count) = self.ambiguous_references.get_mut(key) else { return };
*count -= 1;
if *count == 0 {
self.ambiguous_references.remove(key);
}
}
/// One file's postings, and every table key resolving them read.
fn postings_of(&self, file: FileId) -> (Vec<Posting>, Reads) {
let Some(facts) = self.facts.get(file.0 as usize) else {
return (Vec::new(), Reads::default());
};
recording(|| {
let mut out = Vec::new();
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,
};
out.push(Posting::Site(key, site));
}
ReferenceFact::External { name, base, paths, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
ExternalTarget::Resolved(def) => {
out.push(Posting::Site(DefinitionKey::of(&def), site));
}
ExternalTarget::Ambiguous(defs) => {
out.push(Posting::Ambiguous(
defs.iter().map(DefinitionKey::of).collect(),
));
}
ExternalTarget::StillUnresolved => {}
}
}
}
}
out
})
}
}
@@ -0,0 +1,345 @@
//! Replacing one held file's record with a different one, doing only the
//! work the change can reach: the tables re-merged for the keys either record
//! names, from the files that contribute to them, and the postings re-done for
//! the files whose resolution read a key whose value really moved
//! (`docs/features/localized-reindex/README.md`).
use std::collections::{BTreeMap, BTreeSet, HashSet};
use crate::model::SymbolKind;
use super::dependents::Table;
use super::record::FileFacts;
use super::reexport::Reexport;
use super::update::Affected;
use super::{Def, FileId, WorkspaceIndex};
/// One unit's members: member name → every declaration of it.
type MemberTable = BTreeMap<String, Vec<Def>>;
/// The entries an update names in the four tables resolution reads, held
/// aside: the old tables' entries, swapped back in for as long as it takes to
/// take the readers' old postings out.
#[derive(Default)]
struct Entries {
units: Vec<(String, Option<Vec<Def>>)>,
members: Vec<(String, Option<MemberTable>)>,
hier_members: Vec<(String, Option<MemberTable>)>,
reexports: Vec<(String, Option<Vec<Reexport>>)>,
/// The whole class → base table, when either record has a class with a
/// base — the only way it can move, and it is rebuilt whole when it does.
bases: Option<BTreeMap<String, String>>,
}
/// The keys whose value, as resolution reads it, an update changed.
#[derive(Default)]
struct Moved {
keys: Vec<(Table, String)>,
}
/// One declaration as resolution reads it — see [`seen`].
type Seen<'a> = (FileId, u32, u32, SymbolKind, Option<&'a str>);
/// What resolution reads of one declaration: which declaration it is (the
/// posting key is its file and name span), what kind, and the type a member
/// hop continues through. A declaration whose body grew moved its
/// `decl_span` and its lines, and no posting can tell.
fn seen(defs: &[Def]) -> Vec<Seen<'_>> {
defs.iter()
.map(|d| (d.file, d.name_span.start, d.name_span.end, d.kind, d.type_name.as_deref()))
.collect()
}
fn seen_members(members: Option<&MemberTable>) -> Vec<(&str, Vec<Seen<'_>>)> {
members.into_iter().flatten().map(|(name, defs)| (name.as_str(), seen(defs))).collect()
}
impl WorkspaceIndex {
/// Replace the record at `at` with a different one.
///
/// * The **tables** are re-merged for the keys either record names
/// ([`Affected`]), from the records of the files that contribute to those
/// keys — the same loop a whole merge runs, over fewer files.
/// * The **postings** are re-done for this file and for every file whose
/// last resolution read a key whose value moved
/// ([`Dependents`](super::dependents::Dependents)): taken out against the
/// old tables, put back against the new ones.
///
/// A file that read no moved key read only values this replacement did not
/// change, so its postings are already what a rebuild would give. "Moved"
/// is judged as resolution sees a value ([`seen`]): an edit inside a
/// module's body moves the module's extent and the declarations after the
/// edit, but not the module's name, so the files that only instantiate it
/// are left alone.
///
/// Returns the files whose postings were re-done, for the tests that pin
/// the narrowing itself.
pub(super) fn replace_facts(&mut self, at: usize, facts: FileFacts) -> Vec<FileId> {
let file = FileId(at as u32);
let mut affected = Affected::of(&self.facts[at]);
affected.add(&facts);
let contributors = self.contributors(&affected, at);
let mut old = self.take_entries(&affected);
let mut old_facts = std::mem::replace(&mut self.facts[at], facts);
self.merge_tables(Some(&affected), contributors.as_deref());
if old.bases.is_some() {
self.merge_bases();
}
let readers = self.readers_of(&self.moved(&old, &affected), file);
// The readers' old postings out: re-resolved against the tables and
// the record they were made from, which costs what putting them back
// costs — or, when the readers hold more than an eighth of every
// reference, swept out in one pass over the postings, which is then
// the cheaper of the two (QA F5: every importer of a widely imported
// package re-resolved twice was slower than the old whole merge).
let (share, total) = self.reference_share(&readers);
if sweeps(share, total) {
self.unresolve_by_sweep(&readers);
} else {
self.swap_entries(&mut old);
std::mem::swap(&mut self.facts[at], &mut old_facts);
self.unresolve_files(&readers);
self.swap_entries(&mut old);
std::mem::swap(&mut self.facts[at], &mut old_facts);
}
self.resolve_files(&readers);
readers
}
/// Take the entries `affected` names out of the tables resolution reads.
fn take_entries(&mut self, affected: &Affected) -> Entries {
Entries {
units: take(&mut self.units, &affected.units),
members: take(&mut self.members, &affected.containers),
hier_members: take(&mut self.hier_members, &affected.containers),
reexports: take(&mut self.reexports, &affected.exporters),
bases: (!affected.classes.is_empty()).then(|| std::mem::take(&mut self.bases)),
}
}
/// Exchange the held entries with the tables' — twice is no change.
fn swap_entries(&mut self, held: &mut Entries) {
swap_in(&mut self.units, &mut held.units);
swap_in(&mut self.members, &mut held.members);
swap_in(&mut self.hier_members, &mut held.hier_members);
swap_in(&mut self.reexports, &mut held.reexports);
if let Some(bases) = held.bases.as_mut() {
std::mem::swap(&mut self.bases, bases);
}
}
/// Every key whose value, as resolution reads it, differs between the
/// held entries and the tables now.
fn moved(&self, old: &Entries, affected: &Affected) -> Moved {
let mut out = Moved::default();
for (name, defs) in &old.units {
let now = self.units.get(name).map_or(&[][..], Vec::as_slice);
if seen(defs.as_deref().unwrap_or_default()) != seen(now) {
out.keys.push((Table::Unit, name.clone()));
}
}
for (table, held, now) in [
(Table::Container, &old.members, &self.members),
(Table::Hier, &old.hier_members, &self.hier_members),
] {
for (unit, members) in held {
if seen_members(members.as_ref()) != seen_members(now.get(unit)) {
out.keys.push((table, unit.clone()));
}
}
}
for (exporter, entries) in &old.reexports {
if entries.as_ref() != self.reexports.get(exporter) {
out.keys.push((Table::Exporter, exporter.clone()));
}
}
if let Some(bases) = &old.bases {
for class in &affected.classes {
if bases.get(class) != self.bases.get(class) {
out.keys.push((Table::Base, class.clone()));
}
}
}
out
}
/// This file and every file whose postings read a moved key, in id order.
fn readers_of(&self, moved: &Moved, file: FileId) -> Vec<FileId> {
let mut out: BTreeSet<FileId> = BTreeSet::from([file]);
for (table, key) in &moved.keys {
out.extend(self.dependents.readers(*table, key));
}
out.into_iter().collect()
}
/// Every file holding a record under a key in `affected`, in id order —
/// read off the merged tables, whose entries say which file each came
/// from. `None` means every file: a re-export entry does not carry its
/// file, so a record that names an exporter takes the whole loop.
fn contributors(&self, affected: &Affected, at: usize) -> Option<Vec<usize>> {
if !affected.exporters.is_empty() {
return None;
}
let mut out: BTreeSet<usize> = BTreeSet::from([at]);
let id = |file: FileId| file.0 as usize;
for name in &affected.units {
out.extend(self.units.get(name).into_iter().flatten().map(|def| id(def.file)));
}
for unit in &affected.containers {
for table in [&self.members, &self.hier_members] {
let defs = table.get(unit).into_iter().flat_map(|m| m.values()).flatten();
out.extend(defs.map(|def| id(def.file)));
}
}
for module in &affected.modules {
let edges = self.instantiations.get(module).into_iter().flatten();
out.extend(edges.map(|edge| id(edge.file)));
}
for base in &affected.bases {
let edges = self.subclasses.get(base).into_iter().flatten();
out.extend(edges.map(|edge| id(edge.file)));
}
for name in &affected.macros {
let defines = self.macro_definitions.get(name).into_iter().flatten();
out.extend(defines.map(|(file, _)| id(*file)));
}
Some(out.into_iter().collect())
}
}
/// Below this many references in the whole index a sweep never pays: the
/// re-resolution of a few small files is already sub-millisecond.
const SWEEP_FLOOR: usize = 20_000;
/// Whether the readers' old postings go out by a sweep ([`sweeps`]'s rule:
/// they hold more than an eighth of every reference in an index big enough
/// for that to cost something) or by re-resolution.
fn sweeps(share: usize, total: usize) -> bool {
#[cfg(test)]
if let Some(forced) = tests::FORCE_SWEEP.with(std::cell::Cell::get) {
return forced;
}
total >= SWEEP_FLOOR && share * 8 > total
}
/// Remove the entries under `keys`, keeping each with its key — an absent
/// one as `None`, so swapping it back in removes what is there.
fn take<V>(table: &mut BTreeMap<String, V>, keys: &HashSet<String>) -> Vec<(String, Option<V>)> {
keys.iter().map(|key| (key.clone(), table.remove(key))).collect()
}
/// Exchange each held entry with the table's entry under the same key, an
/// absent entry on either side included.
fn swap_in<V>(table: &mut BTreeMap<String, V>, held: &mut [(String, Option<V>)]) {
for (key, value) in held {
let current = table.remove(key.as_str());
if let Some(value) = value.take() {
table.insert(key.clone(), value);
}
*value = current;
}
}
#[cfg(test)]
mod tests {
use std::cell::Cell;
use std::path::PathBuf;
use super::*;
thread_local! {
/// Which way out a test forces, whatever the sizes say.
pub(super) static FORCE_SWEEP: Cell<Option<bool>> = const { Cell::new(None) };
}
/// Every edit of a small chained design, each checked against a whole
/// build, with the readers' postings taken out each way in turn — the
/// sweep is otherwise taken only on trees of 20 000 references and up.
#[test]
fn both_ways_out_give_the_index_a_whole_build_gives() {
let base = [
("a.sv", "package a_pkg;\n localparam int W = 8;\nendpackage\nclass base_c;\n int m;\nendclass\n"),
("b.sv", "module leaf (input logic clk);\n logic s;\nendmodule\nclass mid_c extends base_c;\nendclass\n"),
("c.sv", "module top;\n import a_pkg::*;\n logic c;\n leaf u (.clk(c));\n initial $display(u.s, W);\nendmodule\nclass leaf_c extends mid_c;\n function void f(); m = 1; endfunction\nendclass\n"),
("d.sv", "module dup (input logic a);\nendmodule\nmodule user;\n dup i (.a(1'b0));\nendmodule\n"),
("e.sv", "module user2;\n dup j ();\nendmodule\n"),
];
let edits = [
("a.sv", "// top\npackage a_pkg;\n localparam int W = 8;\n localparam int V = 1;\nendpackage\nclass base_c;\n int n, m;\nendclass\n"),
("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nclass mid_c extends other_c;\nendclass\n"),
("b.sv", "module leaf (input logic clq);\n logic s;\nendmodule\nmodule dup;\nendmodule\n"),
("e.sv", "// a line\nmodule user2;\n dup j ();\nendmodule\n"),
("c.sv", "module top;\n logic c;\nendmodule\n"),
];
for forced in [true, false] {
FORCE_SWEEP.with(|cell| cell.set(Some(forced)));
let mut files: Vec<(String, String)> =
base.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
for round in 0..2 {
for (path, text) in edits.iter().chain(base.iter()) {
let slot = files.iter_mut().find(|(p, _)| p == path).expect("a held file");
slot.1 = text.to_string();
index.update_file(PathBuf::from(path), text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"sweep={forced}, round {round}: `{path}`"
);
}
}
FORCE_SWEEP.with(|cell| cell.set(None));
}
}
fn build(files: &[(String, String)]) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str())))
}
const LEAF: &str = "module leaf (input logic clk);\n logic s;\nendmodule\n";
const TOP: &str = "module top;\n logic c;\n leaf u (.clk(c));\nendmodule\n";
const TB: &str = "module tb;\n top t ();\n initial $display(t.u.s);\nendmodule\n";
/// The files an update of `leaf.sv` to `text` re-resolves, by path.
fn re_resolved(text: &str) -> Vec<String> {
let mut index = WorkspaceIndex::build([
(PathBuf::from("leaf.sv"), LEAF),
(PathBuf::from("tb.sv"), TB),
(PathBuf::from("top.sv"), TOP),
]);
let facts = FileFacts::of(PathBuf::from("leaf.sv"), text);
let files = index.replace_facts(0, facts);
files.iter().filter_map(|&file| index.path(file)).map(|p| p.display().to_string()).collect()
}
#[test]
fn a_body_edit_re_resolves_only_the_file_itself() {
// The module's name, its port and its signal keep their spans; only
// its extent and its body moved, and no posting can see either. A new
// declaration would be a new member, and the hierarchical reader
// re-resolved for it — a member table is judged whole.
let grown = "module leaf (input logic clk);\n logic s;\n assign s = clk;\nendmodule\n";
assert_eq!(re_resolved(grown), ["leaf.sv"]);
}
#[test]
fn a_port_edit_re_resolves_the_file_that_connects_to_it() {
// Same length, so the signal after it keeps its span — but the
// hierarchical path asks the connection surface before the
// hierarchical one, so it read the port table too.
let renamed = "module leaf (input logic clq);\n logic s;\nendmodule\n";
assert_eq!(re_resolved(renamed), ["leaf.sv", "tb.sv", "top.sv"]);
}
#[test]
fn a_moved_internal_signal_re_resolves_the_file_whose_path_reaches_it() {
let moved = "module leaf (input logic clk);\n logic pad;\n logic s;\nendmodule\n";
assert_eq!(re_resolved(moved), ["leaf.sv", "tb.sv"]);
}
#[test]
fn an_edit_above_everything_re_resolves_every_reader() {
let shifted = format!("// above\n{LEAF}");
assert_eq!(re_resolved(&shifted), ["leaf.sv", "tb.sv", "top.sv"]);
}
}
+135 -138
View File
@@ -4,18 +4,15 @@
//! makes that hold by construction, and the [`WorkspaceIndex::fingerprint`]
//! that proves it.
use std::collections::{BTreeMap, HashSet};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use vlog_parser::defines::DefineKind;
use crate::model::Surface;
use super::external::{resolve_fact, ExternalTarget};
use super::record::{facts_of, FileFacts, ReferenceFact};
use super::{
DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, ReferenceSite, WorkspaceIndex,
};
use super::record::{facts_of, FileFacts};
use super::{DefinitionKey, FileId, InheritanceEdge, InstantiationEdge, WorkspaceIndex};
impl WorkspaceIndex {
/// Replace one file's contribution to the index — or add the file, when
@@ -38,8 +35,13 @@ impl WorkspaceIndex {
/// 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));
///
/// Reports whether the index moved: `false` exactly when the file's new
/// record equals the one held, which is the watcher's echo of a save and a
/// save that changed nothing — the cheapest answer there is, and a sound
/// one, since an index is a function of its records.
pub fn update_file(&mut self, path: PathBuf, src: &str) -> bool {
self.update_facts(facts_of(path, src))
}
/// [`WorkspaceIndex::update_file`] for a file whose facts are already
@@ -51,26 +53,28 @@ impl WorkspaceIndex {
/// [`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) {
///
/// Reports whether the index moved, as [`WorkspaceIndex::update_file`]
/// does.
pub fn update_facts(&mut self, facts: FileFacts) -> bool {
let path = facts.path.clone();
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
Ok(at) if self.facts[at] == facts => return false,
// 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));
self.replace_facts(at, facts);
}
// 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);
self.merge();
}
}
true
}
/// [`WorkspaceIndex::update_facts`] and [`WorkspaceIndex::remove_file`] for
@@ -117,7 +121,7 @@ impl WorkspaceIndex {
}
}
}
self.merge(None);
self.merge();
}
/// Drop one file from the index, reporting whether it was there.
@@ -130,7 +134,7 @@ impl WorkspaceIndex {
};
self.files.remove(at);
self.facts.remove(at);
self.merge(None);
self.merge();
true
}
@@ -185,11 +189,11 @@ impl WorkspaceIndex {
));
}
}
let mut ambiguous: Vec<DefinitionKey> = self.ambiguous_references.iter().copied().collect();
let mut ambiguous: Vec<(&DefinitionKey, &u32)> = self.ambiguous_references.iter().collect();
ambiguous.sort();
for definition in ambiguous {
for (definition, count) in ambiguous {
out.push_str(&format!(
"ambiguous-ref {}:{}..{}\n",
"ambiguous-ref {}:{}..{} x{count}\n",
definition.file.0, definition.name_start, definition.name_end
));
}
@@ -238,17 +242,36 @@ impl WorkspaceIndex {
));
}
}
// Not an answer any caller reads, but the table that decides which
// files the *next* update re-resolves: one that drifted from a
// rebuild's would be a stale posting waiting to happen.
self.dependents.render(&mut out);
out
}
/// Rebuild the merged tables from the per-file records.
/// Rebuild every merged table, the postings and the readers table 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>) {
/// The tables are one loop over the path-sorted records pushing in the
/// order it meets them ([`WorkspaceIndex::merge_tables`]), which is the
/// *only* place any table's order is decided — so a restricted merge over
/// a few files and a whole one agree by construction, and both agree with
/// [`IndexBuilder::finish`](super::IndexBuilder::finish).
pub(super) fn merge(&mut self) {
self.merge_tables(None, None);
self.merge_bases();
// 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();
}
/// The table half of [`WorkspaceIndex::merge`]: clear the keys `affected`
/// names (all of them for `None`) and push back every record under them,
/// visiting `files` — the files that hold such records, in id order — or
/// every file for `None`. Visiting fewer files is the same loop, because a
/// file with no record under a cleared key pushes nothing.
pub(super) fn merge_tables(&mut self, affected: Option<&Affected>, files: Option<&[usize]>) {
match affected {
None => {
self.units.clear();
@@ -281,117 +304,87 @@ impl WorkspaceIndex {
}
}
}
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;
}
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.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 (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.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));
}
match files {
Some(files) => files.iter().for_each(|&id| self.push_records(id, affected)),
None => (0..self.facts.len()).for_each(|id| self.push_records(id, affected)),
}
// 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.
}
/// Push one file's records under the keys `affected` names (every key for
/// `None`), in the order the record holds them.
fn push_records(&mut self, id: usize, affected: Option<&Affected>) {
let file = FileId(id as u32);
let Some(facts) = self.facts.get(id) else { return };
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;
}
// The record's own tag picks the table; the two are keyed
// alike, are cleared together above, and a caller that names
// no surface reads the connection one.
let table = match decl.surface {
Surface::Connection => &mut self.members,
Surface::Hierarchical => &mut self.hier_members,
};
table
.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 (exporter, entry) in &facts.reexports {
if affected.is_some_and(|a| !a.exporters.contains(exporter)) {
continue;
}
self.reexports.entry(exporter.clone()).or_default().push(entry.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, rebuilt whole: one entry per `extends`
/// written anywhere (a few thousand on opentitan), first in file order
/// winning, which is `units`' rule.
pub(super) fn merge_bases(&mut self) {
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, surface, .. } => {
match resolve_fact(self, name, base.as_deref(), paths, *surface) {
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;
}
}
@@ -399,33 +392,37 @@ impl WorkspaceIndex {
/// file can leave every other key alone.
#[derive(Debug, Default)]
pub(super) struct Affected {
units: HashSet<String>,
pub(super) 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>,
pub(super) containers: HashSet<String>,
pub(super) modules: HashSet<String>,
pub(super) bases: HashSet<String>,
/// Keys of the `reexports` table — the package that writes the `export`,
/// never the package it takes the name from: a file changing what `a_pkg`
/// re-exports moves `a_pkg`'s edges and no one else's.
exporters: HashSet<String>,
macros: HashSet<String>,
pub(super) exporters: HashSet<String>,
pub(super) macros: HashSet<String>,
/// Keys of the `bases` table — the *extending* class, which is what a
/// member lookup up the `extends` chain asks it by.
pub(super) classes: HashSet<String>,
}
impl Affected {
fn of(facts: &FileFacts) -> Affected {
pub(super) fn of(facts: &FileFacts) -> Affected {
let mut out = Affected::default();
out.add(facts);
out
}
fn add(&mut self, facts: &FileFacts) {
pub(super) 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.classes.extend(facts.subclasses.iter().map(|(_, class)| class.name.clone()));
self.exporters.extend(facts.reexports.iter().map(|(exporter, _)| exporter.clone()));
self.macros.extend(facts.defines.entries().iter().map(|define| define.name.clone()));
}
@@ -0,0 +1,350 @@
//! The localized update's whole claim, attacked: after any sequence of
//! one-file updates, the index is the index a whole build over the same file
//! contents gives — postings, ambiguity, edges and the readers table that
//! decides which files the *next* update re-resolves included
//! (`docs/features/localized-reindex/README.md`).
//!
//! Each case is a design whose references reach across files through one of
//! the hops resolution takes — a port connection, a package import, a
//! re-export, an `extends` chain, a typedef alias, a hierarchical path through
//! instances, a qualified miss — and a sequence of edits to the file at the
//! far end of the hop, chosen so that a narrowing which forgot that hop would
//! leave a stale posting the fingerprint shows. The randomized sweep at the
//! bottom drives the same designs through seeded mutations.
use std::collections::BTreeMap;
use std::path::PathBuf;
use vlog_semantic::WorkspaceIndex;
fn build(files: &BTreeMap<String, String>) -> WorkspaceIndex {
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), s.as_str())))
}
/// Apply `steps` one update at a time, checking the index against a whole
/// build after every one of them.
fn holds(initial: &[(&str, &str)], steps: &[(&str, &str)]) {
let mut files: BTreeMap<String, String> =
initial.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
for (at, (path, text)) in steps.iter().enumerate() {
files.insert(path.to_string(), text.to_string());
index.update_file(PathBuf::from(path), text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"step {at}: updating `{path}` must give the index a whole build would have"
);
}
}
const PORTS: [(&str, &str); 2] = [
("leaf.sv", "module leaf (input logic clk, output logic q);\nendmodule\n"),
("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.clk(c), .q(d));\nendmodule\n"),
];
#[test]
fn a_port_connection_follows_every_edit_of_the_instantiated_module() {
holds(
&PORTS,
&[
// A body edit: the ports keep their spans, the module's extent grows.
("leaf.sv", "module leaf (input logic clk, output logic q);\n logic s;\nendmodule\n"),
// A comment above everything: every span moves.
("leaf.sv", "// moved\nmodule leaf (input logic clk, output logic q);\nendmodule\n"),
// A port renamed, then removed, then the module renamed away.
("leaf.sv", "module leaf (input logic clock, output logic q);\nendmodule\n"),
("leaf.sv", "module leaf (output logic q);\nendmodule\n"),
("leaf.sv", "module other (input logic clk, output logic q);\nendmodule\n"),
// And back, so a key that went missing comes home.
(PORTS[0].0, PORTS[0].1),
// The instantiating side moves too.
("top.sv", "module top;\n logic c, d;\n leaf u_leaf (.q(d), .clk(c));\nendmodule\n"),
],
);
}
const PACKAGES: [(&str, &str); 3] = [
("a_pkg.sv", "package a_pkg;\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"),
("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\n export a_pkg::*;\nendpackage\n"),
(
"user.sv",
"module user;\n import b_pkg::*;\n word_t w;\n localparam int X = W + a_pkg::W;\nendmodule\n",
),
];
#[test]
fn an_import_and_a_reexport_follow_every_edit_of_the_package_at_the_end() {
holds(
&PACKAGES,
&[
("a_pkg.sv", "package a_pkg;\n // shifted\n localparam int W = 8;\n typedef logic [W-1:0] word_t;\nendpackage\n"),
("a_pkg.sv", "package a_pkg;\n localparam int W2 = 8;\n typedef logic [7:0] word_t;\nendpackage\n"),
// The middle package stops re-exporting, then starts again.
("b_pkg.sv", "package b_pkg;\n import a_pkg::*;\nendpackage\n"),
(PACKAGES[1].0, PACKAGES[1].1),
// The package at the end renamed: every qualified use becomes a miss.
("a_pkg.sv", "package c_pkg;\n localparam int W = 8;\nendpackage\n"),
(PACKAGES[0].0, PACKAGES[0].1),
],
);
}
const CLASSES: [(&str, &str); 3] = [
("base.sv", "class base_c;\n int m;\n function void f(); endfunction\nendclass\n"),
("mid.sv", "class mid_c extends base_c;\nendclass\n"),
("leaf_c.sv", "class leaf_c extends mid_c;\n function void g();\n m = 1;\n f();\n this.m = 2;\n endfunction\nendclass\n"),
];
#[test]
fn an_inherited_member_follows_every_edit_along_the_extends_chain() {
holds(
&CLASSES,
&[
// The member two hops up moves, is renamed, comes back.
(
"base.sv",
"class base_c;\n int pad;\n int m;\n function void f(); endfunction\nendclass\n",
),
("base.sv", "class base_c;\n int n;\n function void f(); endfunction\nendclass\n"),
(CLASSES[0].0, CLASSES[0].1),
// The middle of the chain changes what it extends.
("mid.sv", "class mid_c extends other_c;\nendclass\n"),
("mid.sv", "class mid_c;\nendclass\n"),
(CLASSES[1].0, CLASSES[1].1),
// The middle class declares the member itself, shadowing the base.
("mid.sv", "class mid_c extends base_c;\n int m;\nendclass\n"),
],
);
}
const ALIASES: [(&str, &str); 3] = [
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; logic v; } hdr_t;\nendpackage\n"),
("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { hdr_t hdr; logic [31:0] data; } pkt_t;\nendpackage\n"),
("use.sv", "module use_it;\n import pkt_pkg::*;\n pkt_t p;\n assign p.hdr.addr = 8'h0;\nendmodule\n"),
];
#[test]
fn a_member_chain_through_struct_types_follows_every_edit_of_the_innermost_type() {
holds(
&ALIASES,
&[
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic v; logic [7:0] addr; } hdr_t;\nendpackage\n"),
("hdr.sv", "package hdr_pkg;\n typedef struct packed { logic [7:0] address; logic v; } hdr_t;\nendpackage\n"),
("pkt.sv", "package pkt_pkg;\n import hdr_pkg::*;\n typedef struct packed { logic [31:0] data; hdr_t hdr; } pkt_t;\nendpackage\n"),
(ALIASES[0].0, ALIASES[0].1),
],
);
}
#[test]
fn a_member_whose_type_alone_changes_moves_the_hop_through_it() {
// `hdr_t` and `oth_t` are the same length, so the member `hdr` keeps its
// span and only its declared type — the hop `p.hdr.addr` takes — moves.
let hdr = "package hdr_pkg;\n typedef struct packed { logic [7:0] addr; } hdr_t;\n \
typedef struct packed { logic v; logic [7:0] addr; } oth_t;\nendpackage\n";
holds(
&[("hdr.sv", hdr), ALIASES[1], ALIASES[2]],
&[
("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "oth_t hdr")),
("pkt.sv", &ALIASES[1].1.replace("hdr_t hdr", "nop_t hdr")),
ALIASES[1],
],
);
}
#[test]
fn a_unit_whose_kind_alone_changes_moves_a_path_rooted_at_it() {
// `module h_x` and `package h_x` put the name, and the member after it,
// at the same offsets: only the unit's kind moves, and a top-rooted
// hierarchical path roots only at a module.
holds(
&[
("h_x.sv", "module h_x;\n logic s;\nendmodule\n"),
("h_xtb.sv", "module h_xtb;\n initial $display(h_x.s);\nendmodule\n"),
],
&[
("h_x.sv", "package h_x;\n logic s;\nendpackage\n"),
("h_x.sv", "module h_x;\n logic s;\nendmodule\n"),
],
);
}
const HIERARCHY: [(&str, &str); 4] = [
("h_leaf.sv", "module h_leaf;\n logic sig;\nendmodule\n"),
("h_mid.sv", "module h_mid;\n h_leaf u_leaf ();\nendmodule\n"),
("h_top.sv", "module h_top;\n h_mid u_mid ();\nendmodule\n"),
(
"h_tb.sv",
"module h_tb;\n h_top dut ();\n initial $display(dut.u_mid.u_leaf.sig);\nendmodule\n",
),
];
#[test]
fn a_hierarchical_path_follows_every_edit_of_the_module_at_its_tail() {
holds(
&HIERARCHY,
&[
// The signal at the end moves, goes, comes back as another kind.
("h_leaf.sv", "module h_leaf;\n logic pad;\n logic sig;\nendmodule\n"),
("h_leaf.sv", "module h_leaf;\n logic other;\nendmodule\n"),
("h_leaf.sv", "module h_leaf;\n wire sig;\nendmodule\n"),
// An instance in the middle renamed, then its module swapped.
("h_mid.sv", "module h_mid;\n h_leaf u_leaf2 ();\nendmodule\n"),
("h_mid.sv", "module h_mid;\n h_top u_leaf ();\nendmodule\n"),
(HIERARCHY[1].0, HIERARCHY[1].1),
// The tail module turned into a port, which the connection
// surface answers first.
("h_leaf.sv", "module h_leaf (input logic sig);\nendmodule\n"),
],
);
}
const MISSES: [(&str, &str); 2] = [
("asker.sv", "module asker;\n localparam int K = later_pkg::K;\n later_m u ();\nendmodule\n"),
("other.sv", "module other;\nendmodule\n"),
];
#[test]
fn a_use_that_found_nothing_is_answered_the_moment_another_file_declares_it() {
holds(
&MISSES,
&[
// The other file starts declaring both names, then twice over,
// then stops — a miss, a hit, an ambiguity, a miss.
("other.sv", "package later_pkg;\n localparam int K = 1;\nendpackage\nmodule later_m;\nendmodule\n"),
("other.sv", "package later_pkg;\n localparam int K = 1;\n localparam int K = 2;\nendpackage\nmodule later_m;\nendmodule\nmodule later_m;\nendmodule\n"),
("other.sv", "module other;\nendmodule\n"),
],
);
}
#[test]
fn a_name_two_files_declare_stays_ambiguous_exactly_as_long_as_it_is() {
holds(
&[
("d1.sv", "module dup (input logic a);\nendmodule\n"),
("d2.sv", "module dup (input logic a);\nendmodule\n"),
("u.sv", "module u;\n logic x;\n dup i (.a(x));\nendmodule\n"),
],
&[
("d1.sv", "module dup_one (input logic a);\nendmodule\n"),
("d1.sv", "// back\nmodule dup (input logic a);\nendmodule\n"),
("d2.sv", "module dup (input logic b);\nendmodule\n"),
],
);
}
#[test]
fn a_define_a_broken_file_and_an_unchanged_save_all_hold() {
holds(
&[
("defs.svh", "`define W 8\n`define F(a) (a)\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
],
&[
("defs.svh", "`define W 16\n`define F(a, b) (a+b)\n"),
("defs.svh", "`undef W\n`define W 16\n"),
("m.sv", "module m;\n logic [`W-1:0] x\nendmodule\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
("m.sv", "module m;\n logic [`W-1:0] x;\nendmodule\n"),
],
);
}
#[test]
fn an_unchanged_record_reports_that_nothing_moved() {
let files: BTreeMap<String, String> =
PORTS.iter().map(|(p, s)| (p.to_string(), s.to_string())).collect();
let mut index = build(&files);
let before = index.fingerprint();
assert!(!index.update_file(PathBuf::from(PORTS[0].0), PORTS[0].1), "same text, same record");
assert_eq!(index.fingerprint(), before);
// A comment after the last token moves no span the record holds.
let trailing = format!("{}// trailing\n", PORTS[0].1);
assert!(!index.update_file(PathBuf::from(PORTS[0].0), &trailing), "{trailing:?}");
let renamed = PORTS[0].1.replace("clk", "clock");
assert!(index.update_file(PathBuf::from(PORTS[0].0), &renamed), "a port renamed moves it");
}
// ----------------------------------------------------------------------
// The seeded sweep
// ----------------------------------------------------------------------
/// xorshift64*: reproducible from a seed, no dependency.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
fn below(&mut self, n: usize) -> usize {
(self.next() % n.max(1) as u64) as usize
}
}
/// One random edit of `text`: a line inserted, deleted, duplicated or swapped
/// with its neighbour, or one identifier-ish word renamed to another from
/// the design — the kinds of edit that move spans, names and whole
/// declarations.
fn mutate(text: &str, words: &[&str], rng: &mut Rng) -> String {
let mut lines: Vec<String> = text.lines().map(str::to_string).collect();
let at = rng.below(lines.len() + 1);
match rng.below(5) {
0 => lines.insert(at, " // a comment".to_string()),
1 if at < lines.len() => {
lines.remove(at);
}
2 if at < lines.len() => {
let line = lines[at].clone();
lines.insert(at, line);
}
3 if at + 1 < lines.len() => lines.swap(at, at + 1),
_ => {
let from = words[rng.below(words.len())];
let to = words[rng.below(words.len())];
if let Some(line) = lines.iter_mut().find(|line| line.contains(from)) {
*line = line.replacen(from, to, 1);
}
}
}
let mut out = lines.join("\n");
out.push('\n');
out
}
#[test]
fn a_seeded_sweep_of_mutations_over_every_design_holds() {
let designs: [&[(&str, &str)]; 5] = [&PORTS, &PACKAGES, &CLASSES, &ALIASES, &HIERARCHY];
let words = [
"leaf", "clk", "q", "a_pkg", "b_pkg", "W", "word_t", "base_c", "mid_c", "m", "f", "hdr_t",
"addr", "pkt_t", "h_leaf", "u_leaf", "sig", "h_mid", "u_mid",
];
let mut checked = 0;
for seed in 1..=8u64 {
let mut rng = Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15));
let mut files: BTreeMap<String, String> = BTreeMap::new();
for design in designs {
files.extend(design.iter().map(|(p, s)| (p.to_string(), s.to_string())));
}
let mut index = build(&files);
let paths: Vec<String> = files.keys().cloned().collect();
for step in 0..40 {
let path = &paths[rng.below(paths.len())];
let text = mutate(&files[path], &words, &mut rng);
files.insert(path.clone(), text.clone());
index.update_file(PathBuf::from(path), &text);
assert_eq!(
index.fingerprint(),
build(&files).fingerprint(),
"seed {seed}, step {step}: `{path}` became {text:?}"
);
checked += 1;
}
}
assert_eq!(checked, 320);
}
File diff suppressed because it is too large. Load diff
+24
View File
@@ -1444,3 +1444,27 @@ A warm build is walk 210 ms + store read 87 ms + read/hash/decode 318 ms +
merge 204 ms; a cold one parses instead (1 387 ms). The rows are not
like-for-like with the server's (it scans in stages and answers during the
scan); they sit side by side so a regression in either shows.
### 2026-11-19 — localized reindex (TODO §71.1)
What one save costs the index on the full OpenTitan `hw` tree (4 058 files,
scope `workspace`, 10 buffers open), measured over LSP with the real release
server and in-process with `state::tests::reindex_perf` (release,
`--test-threads=1`); medians, the machine shared with another lane's builds.
Details and the method: `docs/features/localized-reindex/README.md`.
| | before (7408fac) | after |
|---|---:|---:|
| `reindex_one`, any edit, any file | 141–158 ms | — |
| …the watcher's echo of a save / an unchanged record | 153–176 ms, everything republished | 0.07–1.1 ms, nothing sent |
| …a local signal in a module (`uart_tx`, `prim_flop`) | 144–145 ms | 5.2 ms |
| …a package member added (`uart_reg_pkg`) | 148 ms | 11.7 ms |
| …a line above everything in `prim_flop.sv` (125 instantiating files) | 144 ms | 61 ms |
| watcher event for a `.sv` the scope cannot take | 746 ms whole rescan | 3.5 ms, nothing |
| whole merge (`absorb`, startup / cached rescan) | 135 / 165 ms | 158 / 189 ms |
| warm startup scan (fix round, QA's `perf.py`, two runs) | 1 113 / 1 124 ms | 1 171 / 1 148 ms |
| `prim_mubi_pkg` member added, 677 importers (fix round) | 162 ms | 92 ms |
| readers table | — | 13 806 keys, 69 222 entries |
| mention census, one lint pass (average / worst file) | 51 µs / 2.8 ms | unchanged |
Probes: `tools/guard.sh -- cargo test --release -p lucisv_server reindex_perf -- --ignored --nocapture --test-threads=1`.
+10
View File
@@ -5,6 +5,16 @@ for you. The extension and its bundled language server share one version
number; the full engineering notes live in the
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
## 0.65.6 — 2026-11-19
- **Saving no longer re-indexes the workspace.** On a large project a save
used to cost a whole-index pass, twice (once for the save, once for VS
Code's file watcher). A typical edit now costs a few milliseconds, and a
save that changes nothing the index records costs nothing.
- **No more surprise "indexing" bar** for generated files, files outside the
filelist or folder scope, or files reached through a symlink.
- **The line-length warning follows your formatting style's width.**
## 0.65.5 — 2026-11-19
- **Formatting styles, from a drop-down.** `lucisv.format.style` picks the
+8 -1
View File
@@ -30,7 +30,7 @@ Install **lucisv — Verilog/SystemVerilog** from the VS Code Extensions view,
then open a Verilog or SystemVerilog file. There is no separate server or CLI
setup.
The current release is **0.65.5**. Its platform packages include
The current release is **0.65.6**. Its platform packages include
`lucisv-server`, the `lucisv` command-line tool and `lucisv-mcp` (see
[Agents (MCP)](#agents-mcp)):
@@ -440,6 +440,13 @@ default):
}
```
## Release 0.65.6 highlights
Version 0.65.6 makes saving cheap on large projects: the language server
updates only what an edit can reach instead of re-resolving the whole index —
on OpenTitan a typical save drops from about 160 ms (twice) to a few
milliseconds.
## Release 0.65.5 highlights
Version 0.65.5 adds named formatting styles — `google`, `lowrisc`, `ansi`,
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "lucisv",
"version": "0.65.5",
"version": "0.65.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "lucisv",
"version": "0.65.5",
"version": "0.65.6",
"license": "MIT",
"dependencies": {
"vscode-languageclient": "9.0.1"
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "lucisv",
"displayName": "lucisv — Verilog/SystemVerilog",
"description": "Fast Verilog/SystemVerilog formatting, linting, navigation, refactoring, semantic highlighting and RTL design intelligence.",
"version": "0.65.5",
"version": "0.65.6",
"publisher": "guoliangchen",
"author": "Guoliang Chen",
"license": "MIT",