TODO §55: split lucisv_server state/mod.rs by responsibility (pure move)
state/mod.rs 986 -> 63 production lines: document.rs (one analyzed buffer), buffers.rs (open buffers), views.rs (closed-file view cache), scope.rs (roots, settings, scope ladder), rescan.rs (scan and widen protocol, 411), incremental.rs (one saved file re-indexed), sources.rs (file sets for refactorings, 170). The 3 944-line inline test module moved to state/tests/ (14 topic files). No function body changed; only forced pub(super) widenings. Lead's line-multiset check: no code line lost or added. CLAUDE.md measurement refreshed (2026-10-14); a stale test path in server/tests/folders.rs corrected. Gates on the merged tree: fmt and clippy -D warnings clean; lucisv_server 1 823 passed, 0 failed, 38 ignored (= before); the lane's workspace run 80 suites, 5 078 passed. Refactor dev Claude Fable 5.1. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
ca83f6f99f
commit
4fae8fb63a
27 files changed
+6131
-5814
No files matched your search
@@ -84,6 +84,11 @@ now): largest files `tools/read.rs` 405, `tools/item.rs` 379, `tools/item/verify
|
||||
`vlog_refactor/src/rename/connections.rs` at 477 and `check/mod.rs` at 426,
|
||||
and `lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55).
|
||||
|
||||
Re-measured 2026-10-14 after TODO §55 (pure move, `docs/features/decomposition-state`):
|
||||
`state/mod.rs` 63, the largest `state/` file `discover.rs` 412 (`rescan.rs` 411);
|
||||
files over 600 workspace-wide: `lucisv_server/src/perf.rs` 907 (reasoned),
|
||||
`vlog_parser/src/lexer.rs` 771, `vlog_formatter/src/format/stmt.rs` 604.
|
||||
|
||||
## Rust standards
|
||||
|
||||
- `cargo fmt` clean, `cargo clippy --all-targets` clean (no `#[allow]`
|
||||
|
||||
@@ -5084,11 +5084,14 @@ scope/widen logic, the document store, and the source selectors
|
||||
(`module_sources`, `rename_sources`) are three sentences. Not planned; the
|
||||
owner decides where it goes in loop 2.
|
||||
|
||||
- [ ] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
- [x] `state.rs` decomposition (pure move, byte-identical output, test
|
||||
count unchanged); CLAUDE.md's measurement line refreshed —
|
||||
**deferred to loop 3 by the lead, 2026-09-07** (958 lines at 0.49.0;
|
||||
the measurement line already says so); a Fable refactor lane when
|
||||
the owner schedules it
|
||||
the owner schedules it — **done 2026-10-14**
|
||||
(`docs/features/decomposition-state/README.md`: `state/` is ten
|
||||
modules, largest 412 production lines; the CLAUDE.md measurement
|
||||
line is the lead's, requested in that README's Handshakes)
|
||||
|
||||
## 50. `.*` expansion (planned 2026-09-05) — the first §8 refactoring
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
|
||||
// directory is raised on its own and none of them is ever dropped — so
|
||||
// this is an add like any other, and the widen's own file diff is what
|
||||
// stops the overlap being read twice
|
||||
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
||||
// (`state::tests::widen::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
||||
let ip = PathBuf::from("/w");
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
//! The open buffers: installing, closing and finding them, and which
|
||||
//! text — the buffer's or the disk's — speaks for a path when the index
|
||||
//! or a refactoring asks.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Uri;
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::{oversize, Found};
|
||||
use super::{Document, Workspace};
|
||||
use crate::uri::uri_to_path;
|
||||
|
||||
impl Workspace {
|
||||
pub fn document(&self, uri: &Uri) -> Option<&Document> {
|
||||
self.docs.get(uri)
|
||||
}
|
||||
|
||||
/// The open document backed by `path`, if there is one.
|
||||
pub fn document_for_path(&self, path: &Path) -> Option<&Document> {
|
||||
self.docs.values().find(|doc| doc.path.as_deref() == Some(path))
|
||||
}
|
||||
|
||||
/// Every open document and its URI.
|
||||
pub fn open_documents(&self) -> impl Iterator<Item = (&Uri, &Document)> {
|
||||
self.docs.iter()
|
||||
}
|
||||
|
||||
/// Replace a buffer's contents and re-analyze it.
|
||||
///
|
||||
/// Also the one place a directory enters the folder scope: a buffer with a
|
||||
/// path puts its own directory on the list `scope_dirs` raises. An
|
||||
/// `untitled:` buffer has no path and contributes none.
|
||||
///
|
||||
/// And the one place the **large-file fast path** is chosen: a text over
|
||||
/// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because
|
||||
/// the decision lives here it is re-taken on every `didOpen`, `didChange`
|
||||
/// and text-carrying `didSave`, which is what makes a buffer edited past
|
||||
/// the threshold — or back under it — change mode at that moment and not
|
||||
/// before (`docs/features/large-file-mode/README.md`).
|
||||
pub fn set_document(&mut self, uri: Uri, text: String) {
|
||||
let path = uri_to_path(&uri);
|
||||
if let Some(dir) = path.as_deref().and_then(Path::parent) {
|
||||
if !self.opened_dirs.iter().any(|seen| seen == dir) {
|
||||
self.opened_dirs.push(dir.to_path_buf());
|
||||
self.opened_dirs.sort();
|
||||
}
|
||||
}
|
||||
// This path now has a buffer speaking for it, so whatever the view
|
||||
// cache holds for it is both unwanted and possibly older than the
|
||||
// edits the buffer carries.
|
||||
if let Some(path) = path.as_deref() {
|
||||
self.forget_view(path);
|
||||
}
|
||||
let doc = match self.is_large(&text) {
|
||||
true => Document::large(path, text),
|
||||
false => Document::new(path, text, &self.index),
|
||||
};
|
||||
self.docs.insert(uri, doc);
|
||||
}
|
||||
|
||||
/// Whether a buffer of this text takes the fast path. `0` disables it, and
|
||||
/// the comparison is strict, so a buffer of exactly the threshold is still
|
||||
/// analyzed in full.
|
||||
fn is_large(&self, text: &str) -> bool {
|
||||
let threshold = self.client.large_file_threshold;
|
||||
threshold != 0 && text.len() as u64 > threshold
|
||||
}
|
||||
|
||||
/// Whether any open buffer is on the large-file fast path.
|
||||
///
|
||||
/// The gate in `server.rs` runs before every request, and this is what
|
||||
/// keeps that from costing a URI parse per request in the session where
|
||||
/// nothing is large — which is every session but one.
|
||||
pub fn has_large_documents(&self) -> bool {
|
||||
self.docs.values().any(|doc| doc.large)
|
||||
}
|
||||
|
||||
pub fn close_document(&mut self, uri: &Uri) {
|
||||
let closed = self.docs.remove(uri);
|
||||
// Disk is the authority again, and a view made before this buffer was
|
||||
// opened predates every save it made.
|
||||
if let Some(path) = closed.and_then(|doc| doc.path) {
|
||||
self.forget_view(&path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
|
||||
pub fn open_uris(&self) -> Vec<Uri> {
|
||||
self.docs.keys().cloned().collect()
|
||||
}
|
||||
|
||||
/// The text of a workspace file: the open buffer if there is one, else
|
||||
/// what is on disk. Same precedence the index rebuild uses, so a location
|
||||
/// is never computed against text the index did not see.
|
||||
pub fn text_of(&self, path: &Path) -> Option<String> {
|
||||
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
|
||||
match open {
|
||||
Some(doc) => Some(doc.text.clone()),
|
||||
None => fs::read_to_string(path).ok(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text one in-scope file contributes right now, by `collect_sources`'s
|
||||
/// rules — `None` when it contributes nothing at all.
|
||||
pub(super) fn current_text(&self, path: &Path) -> Option<String> {
|
||||
if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) {
|
||||
// A fast-path buffer contributes nothing, exactly as it does in
|
||||
// `collect_sources` — indexing it is the parse the fast path
|
||||
// exists to skip.
|
||||
return (!doc.large).then(|| doc.text.clone());
|
||||
}
|
||||
if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() {
|
||||
return None;
|
||||
}
|
||||
fs::read_to_string(path).ok()
|
||||
}
|
||||
|
||||
/// The index facts and the completion words of the open buffer backing
|
||||
/// `path`, read off the analysis it already holds — `None` when no buffer
|
||||
/// does, or when the one that does is on the large-file fast path and has
|
||||
/// no analysis of its own text to read.
|
||||
///
|
||||
/// The buffer is found the same way [`Workspace::current_text`] finds the
|
||||
/// text, so the two always speak for the same `Document`.
|
||||
pub(super) fn analysis_of(&self, path: &Path) -> Option<(FileFacts, Vec<String>)> {
|
||||
let doc = self.docs.values().find(|doc| doc.path.as_deref() == Some(path))?;
|
||||
(!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//! One open buffer, analyzed once from its text — [`Document`] and
|
||||
//! everything derived from it — and the two binary searches that find a
|
||||
//! token in it by offset without sweeping the buffer.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, ExternalResolutions, FileFacts, Semantics, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use crate::convert::Positions;
|
||||
|
||||
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
|
||||
/// change throws the whole thing away and builds a new one.
|
||||
pub struct Document {
|
||||
/// The buffer's path, absent for a `untitled:` document.
|
||||
pub path: Option<PathBuf>,
|
||||
pub text: String,
|
||||
pub line_index: LineIndex,
|
||||
/// Empty when the file does not lex — the lexer is all-or-nothing.
|
||||
pub tokens: Vec<Token>,
|
||||
/// The tolerant parse of `text` — the tree `semantics` was analyzed from,
|
||||
/// kept so the lint pass reads it instead of parsing the buffer again
|
||||
/// ("one parse, two tools", `docs/features/one-parse/README.md`).
|
||||
pub tree: SourceFile,
|
||||
pub diagnostics: Vec<ParseDiagnostic>,
|
||||
pub semantics: Semantics,
|
||||
pub defines: DefineTable,
|
||||
/// The workspace layer's answers for this file's external candidates.
|
||||
pub external: ExternalResolutions,
|
||||
/// Whether this buffer was opened on the **large-file fast path**: every
|
||||
/// field above except `text` and `line_index` is the empty analysis of an
|
||||
/// empty file, because nothing lexed it. Handlers that would scan the text
|
||||
/// itself check this flag; the ones that read the analysis need not, since
|
||||
/// there is nothing in it to find. See
|
||||
/// `docs/features/large-file-mode/README.md`.
|
||||
pub large: bool,
|
||||
/// The formatter's fence answer for exactly this `text`, computed on
|
||||
/// first use and never again — a whole tolerant parse the code-action
|
||||
/// path used to pay for on every request. Filled through
|
||||
/// [`crate::fences::of`], which is the only thing that may touch it; it
|
||||
/// is bound to this revision because a change builds a new `Document`.
|
||||
pub fences: std::sync::OnceLock<Vec<vlog_formatter::fence::Region>>,
|
||||
/// This buffer's lint findings, kept while every input that produced them
|
||||
/// is unchanged — read by the diagnostics pass and by quick-fix discovery
|
||||
/// alike, so one revision is linted once rather than twice (review round
|
||||
/// §R1a, `crate::lint_snapshot`). Bound to this revision for the same
|
||||
/// structural reason `fences` is; the inputs that can move *without* a new
|
||||
/// `Document` are the snapshot's own key, and the index moving is
|
||||
/// [`Document::refresh_overlay`], which clears it.
|
||||
pub lint: crate::lint_snapshot::Slot,
|
||||
}
|
||||
|
||||
impl Document {
|
||||
/// Analyze a buffer from scratch against the current workspace index.
|
||||
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
|
||||
// One lex: the tree is built from a clone of the token stream instead
|
||||
// of re-lexing the buffer (`parse_source_tolerant` is exactly
|
||||
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
|
||||
// that does not lex keeps the old path, so its all-error tree and its
|
||||
// lex diagnostic are byte-for-byte what they always were.
|
||||
use crate::lint_trace::{rebuild, Rebuild};
|
||||
crate::lint_trace::saw_document();
|
||||
let (tokens, (tree, diagnostics)) = match rebuild(Rebuild::Lex, || tokenize(&text)) {
|
||||
Ok(tokens) => {
|
||||
let parsed = rebuild(Rebuild::Parse, || parse_tolerant(tokens.clone(), &text));
|
||||
(tokens, parsed)
|
||||
}
|
||||
Err(_) => (Vec::new(), rebuild(Rebuild::Parse, || parse_source_tolerant(&text))),
|
||||
};
|
||||
let defines = rebuild(Rebuild::Defines, || collect_defines(&tokens));
|
||||
let semantics = rebuild(Rebuild::Analyze, || analyze(&tree, &text));
|
||||
let external = rebuild(Rebuild::External, || resolve_external(&semantics, index));
|
||||
let line_index = rebuild(Rebuild::Lines, || LineIndex::new(&text));
|
||||
let large = false;
|
||||
Document {
|
||||
path,
|
||||
text,
|
||||
line_index,
|
||||
tokens,
|
||||
tree,
|
||||
diagnostics,
|
||||
semantics,
|
||||
defines,
|
||||
external,
|
||||
large,
|
||||
fences: std::sync::OnceLock::new(),
|
||||
lint: crate::lint_snapshot::Slot::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Take a buffer on the **fast path**: index its lines and nothing else.
|
||||
///
|
||||
/// One newline scan is the whole cost of opening a 100 MB netlist. The
|
||||
/// derived fields are the analysis of the *empty* file rather than of this
|
||||
/// one — built by parsing `""`, which costs nothing and needs no new API
|
||||
/// from `vlog_parser` — so every handler that reads the analysis finds
|
||||
/// exactly nothing and answers empty without knowing this path exists.
|
||||
pub fn large(path: Option<PathBuf>, text: String) -> Document {
|
||||
let (tree, _) = parse_source_tolerant("");
|
||||
let semantics = analyze(&tree, "");
|
||||
let line_index = LineIndex::new(&text);
|
||||
Document {
|
||||
path,
|
||||
text,
|
||||
line_index,
|
||||
tokens: Vec::new(),
|
||||
tree,
|
||||
diagnostics: Vec::new(),
|
||||
semantics,
|
||||
defines: DefineTable::default(),
|
||||
external: ExternalResolutions::default(),
|
||||
large: true,
|
||||
fences: std::sync::OnceLock::new(),
|
||||
lint: crate::lint_snapshot::Slot::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// This document's position converter.
|
||||
pub fn positions(&self) -> Positions<'_> {
|
||||
Positions::new(&self.text, &self.line_index)
|
||||
}
|
||||
|
||||
/// The source token covering `offset`, found without sweeping the buffer.
|
||||
pub fn token_at(&self, offset: u32) -> Option<&Token> {
|
||||
let after = self.tokens.partition_point(|token| token.span.start <= offset);
|
||||
let token = self.tokens.get(after.checked_sub(1)?)?;
|
||||
token.span.contains(offset).then_some(token)
|
||||
}
|
||||
|
||||
/// Re-run only the workspace overlay, after the index was rebuilt. The
|
||||
/// single-file analysis is unaffected by other files, by construction.
|
||||
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
|
||||
self.external = resolve_external(&self.semantics, index);
|
||||
// The index is what the census oracle answers from, so a lint result
|
||||
// taken under the old one is no longer this buffer's answer. This is
|
||||
// the whole of the snapshot's index invalidation: every mutation of
|
||||
// `Workspace::index` ends in the loop that calls this, so there is no
|
||||
// generation counter to keep in step (review round §R1a).
|
||||
self.lint.clear();
|
||||
}
|
||||
|
||||
/// What this buffer contributes to the workspace index, read off the
|
||||
/// analysis it already holds instead of from its text.
|
||||
///
|
||||
/// [`FileFacts::of`] is `tokenize` + `parse_tolerant` + `analyze` followed
|
||||
/// by the fact walk, and the first three are exactly what [`Document::new`]
|
||||
/// already did to fill `tree`, `defines` and `semantics` — from the same
|
||||
/// text, with the same functions, down to the lex-failure branch. So this
|
||||
/// is `FileFacts::of(path, &self.text)` with the parse already paid for,
|
||||
/// not a second way of computing it
|
||||
/// (`an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus`).
|
||||
///
|
||||
/// Never called for a buffer on the large-file fast path: its analysis is
|
||||
/// the analysis of the empty file, and such a buffer contributes nothing to
|
||||
/// the index at all (see `collect_sources`).
|
||||
pub fn facts(&self, path: PathBuf) -> FileFacts {
|
||||
FileFacts::from_analysis(
|
||||
path,
|
||||
&self.tree,
|
||||
&self.defines,
|
||||
&self.semantics,
|
||||
&self.text,
|
||||
&self.line_index,
|
||||
&self.tokens,
|
||||
)
|
||||
}
|
||||
|
||||
/// The completion words this buffer contributes, read off the tokens it was
|
||||
/// analyzed from rather than by lexing its text a second time.
|
||||
pub fn words(&self) -> Vec<String> {
|
||||
crate::candidates::words_of_tokens(&self.tokens)
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Finding a token by offset without sweeping the buffer
|
||||
// ----------------------------------------------------------------------
|
||||
//
|
||||
// The lexer emits tokens in source order and they never overlap, so
|
||||
// `span.start` and `span.end` both rise across the vector: `end[i] <=
|
||||
// start[i+1] <= end[i+1]`. That makes both predicates below monotone, which
|
||||
// is the whole precondition `partition_point` needs. Every handler that used
|
||||
// to sweep the vector looking for a token at the cursor is one comparison
|
||||
// away from one of these two indices — see
|
||||
// `docs/features/interactive-latency/README.md` for the per-call-site
|
||||
// argument that each swap returns exactly what the sweep returned.
|
||||
|
||||
/// The index of the first token that **reaches** `offset` — the first with
|
||||
/// `span.end >= offset`. `tokens.len()` when none does.
|
||||
///
|
||||
/// Every token before it ends strictly before `offset`, so it cannot cover,
|
||||
/// end at, or contain `offset`. The token *at* this index is therefore the
|
||||
/// first candidate any such question has.
|
||||
pub fn first_token_reaching(tokens: &[Token], offset: u32) -> usize {
|
||||
tokens.partition_point(|token| token.span.end < offset)
|
||||
}
|
||||
|
||||
/// The index of the first token that **begins** at or after `offset` — the
|
||||
/// first with `span.start >= offset`. `tokens.len()` when none does.
|
||||
pub fn first_token_from(tokens: &[Token], offset: u32) -> usize {
|
||||
tokens.partition_point(|token| token.span.start < offset)
|
||||
}
|
||||
|
||||
/// A buffer of `blocks` repeated blocks, for the tests that check a binary
|
||||
/// search against the sweep it replaced.
|
||||
///
|
||||
/// Deliberately awkward: tokens written with no space between them (`a=b;`),
|
||||
/// line and block comments, a string, nested `begin`/`end` and several depths
|
||||
/// of parentheses. The offsets those tests walk are *every byte*, and the ones
|
||||
/// that could tell a binary search from a sweep are exactly the bytes two
|
||||
/// tokens share — which only adjacent punctuation produces.
|
||||
#[cfg(test)]
|
||||
pub fn mixed_buffer(blocks: usize) -> String {
|
||||
let mut src = String::from("module mixed (input logic clk, output logic [7:0] q);\n");
|
||||
for n in 0..blocks {
|
||||
src.push_str(&format!(
|
||||
" // block {n}\n \
|
||||
wire [7:0] w{n};assign w{n}=(q[0]?8'd1:8'd2)+{{4'h0,4'hF}};\n \
|
||||
/* {n} */ always @(posedge clk) begin\n \
|
||||
if (w{n}[0]) begin q<=w{n}; end else begin q<=8'd0; end\n \
|
||||
end\n \
|
||||
initial $display(\"block {n}\", w{n});\n"
|
||||
));
|
||||
}
|
||||
src.push_str("endmodule\n");
|
||||
src
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
//! 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.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use super::Workspace;
|
||||
use crate::scan_trace::ScanTrace;
|
||||
|
||||
impl Workspace {
|
||||
/// Rebuild the index for **one** file, leaving every other file's
|
||||
/// contribution exactly as it is. Reports whether it could.
|
||||
///
|
||||
/// `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".
|
||||
///
|
||||
/// The four pieces of state a rebuild produces, and what happens to each:
|
||||
///
|
||||
/// * **the workspace index** — [`WorkspaceIndex::update_file`] /
|
||||
/// [`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.
|
||||
///
|
||||
/// 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;
|
||||
}
|
||||
// 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());
|
||||
}
|
||||
}
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// [`Workspace::update_one`], then a whole rebuild over the same
|
||||
/// workspace, asserting the two produced the same thing — the paranoid
|
||||
/// form, for tests.
|
||||
///
|
||||
/// 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.
|
||||
#[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();
|
||||
self.rebuild_index();
|
||||
assert_eq!(index, self.index.fingerprint(), "incremental index != rebuilt index");
|
||||
assert_eq!(words, self.candidates.words(""), "incremental words != rebuilt words");
|
||||
true
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,758 @@
|
||||
//! Driving a scan, whole or widen, from its work list to the landed
|
||||
//! tables: `begin_scan`/`begin_widen` take the list, `scan_step` indexes
|
||||
//! one file, `publish_scan` makes the tables answer for what has been
|
||||
//! staged so far, and `finish_scan` lands them. The one-shot forms the
|
||||
//! tests use are at the end.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::oversize;
|
||||
use super::scan::{self, Analyzed, IndexEvent, Scan, ScanKind};
|
||||
use super::{StoreOpen, Workspace};
|
||||
use crate::candidates::Candidates;
|
||||
use crate::includes::{self, IncludeGraph};
|
||||
use crate::index_cache::IndexCache;
|
||||
use crate::scan_order::{self, WorkList};
|
||||
use crate::scan_trace::{CacheWork, ScanTrace};
|
||||
#[cfg(test)]
|
||||
use crate::settings::IndexScope;
|
||||
|
||||
impl Workspace {
|
||||
/// Take the work list one scan will run through: resolve the scope and put
|
||||
/// the user's own neighbourhood at the front of it.
|
||||
///
|
||||
/// **No file's text is read here** — only the open buffers', which are in
|
||||
/// memory already. Everything else is read at the step that indexes it
|
||||
/// ([`Workspace::scan_step`]), so the first file can be indexed as soon as
|
||||
/// the walk is done rather than after the whole scope has been read.
|
||||
///
|
||||
/// Nothing is indexed here and the live index is untouched, so a scan that
|
||||
/// is never stepped changes nothing but the view cache and the open cache
|
||||
/// handle.
|
||||
pub fn begin_scan(&mut self, watch: &mut dyn FnMut(IndexEvent), trace: bool) -> Scan {
|
||||
let mut trace = ScanTrace::opened(&mut self.scans, trace, "whole");
|
||||
// A rescan says nothing about *which* file moved, so nothing held from
|
||||
// before it can be trusted.
|
||||
self.views.borrow_mut().clear();
|
||||
let discovering = trace.now();
|
||||
let mut skipped = 0usize;
|
||||
// The cap's skips are reported by `collect_sources` and counted here,
|
||||
// because the end message names them and the scan is what owns that
|
||||
// number now.
|
||||
let mut counting = |event: IndexEvent<'_>, skipped: &mut usize| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
*skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
let (mut scope, pending) = {
|
||||
let mut count = |event: IndexEvent<'_>| counting(event, &mut skipped);
|
||||
self.first_scope(&mut count, &mut trace)
|
||||
};
|
||||
ScanTrace::add(&mut trace.discovery_ms, discovering);
|
||||
let buffered = std::mem::take(&mut scope.buffered);
|
||||
let analyzed = std::mem::take(&mut scope.analyzed);
|
||||
let ordering = trace.now();
|
||||
// The same list the index will be built from, with the user's own
|
||||
// neighbourhood moved to the front of it.
|
||||
let WorkList { files: work, head } = self.open_first(std::mem::take(&mut scope.files));
|
||||
// A scan that has not walked the whole workspace yet cannot ask
|
||||
// whether its head is a minority of it — the count that would answer
|
||||
// is the walk it is postponing. `splits_discovery` is what bounds the
|
||||
// head instead, and it refuses exactly the case `worth_waiting`
|
||||
// refuses: a buffer whose folder is the workspace.
|
||||
let head = match pending.is_some() {
|
||||
true => head,
|
||||
false => scan_order::worth_waiting(head, work.len()),
|
||||
};
|
||||
let paths = work.clone();
|
||||
ScanTrace::add(&mut trace.order_ms, ordering);
|
||||
// Re-opened rather than held across rescans: the directory it belongs
|
||||
// in depends on settings that arrive after startup, and a second
|
||||
// session over the same workspace may have written records this one
|
||||
// has not seen. **Deferred** to the first file that asks the store
|
||||
// anything ([`StoreOpen`]), so a scan with no files reads nothing.
|
||||
self.store = StoreOpen::Deferred(self.cache_dir());
|
||||
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
|
||||
Scan {
|
||||
kind: ScanKind::Whole,
|
||||
work,
|
||||
head,
|
||||
buffered,
|
||||
includes: HashMap::new(),
|
||||
unread: Vec::new(),
|
||||
paths,
|
||||
gone: Vec::new(),
|
||||
analyzed,
|
||||
incdirs: scope.incdirs,
|
||||
warnings: scope.warnings,
|
||||
at: 0,
|
||||
pending,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
words: HashMap::new(),
|
||||
skipped,
|
||||
cached: 0,
|
||||
trace,
|
||||
}
|
||||
}
|
||||
|
||||
/// Take the work list for a **scope widen**: the files `added` brings into
|
||||
/// scope that the index does not already hold, plus every open buffer's own
|
||||
/// analysis.
|
||||
///
|
||||
/// The cheap answer to a `didOpen` in a folder the scope had not reached.
|
||||
/// A whole rescan re-reads, re-hashes and re-merges every file already
|
||||
/// indexed to learn about a handful of new ones; this reads only the new
|
||||
/// ones, and [`Workspace::finish_scan`] folds them in beside what is
|
||||
/// already there. What comes out is the index, the completion tables and
|
||||
/// the include graph a whole rescan would have produced — **given that the
|
||||
/// disk files already indexed have not changed since they were indexed**,
|
||||
/// which is the file watcher's job and is written down in
|
||||
/// `docs/features/index-scope/README.md`.
|
||||
///
|
||||
/// Two halves make that equivalence hold, and both are why this is not
|
||||
/// simply "index the new files":
|
||||
///
|
||||
/// * **every open buffer is re-indexed from the analysis it holds**, so a
|
||||
/// buffer carrying unsaved edits contributes those edits exactly as a
|
||||
/// whole rescan's `collect_sources` overlay would. That costs a fact walk
|
||||
/// and a word set per open buffer (~5 ms for a 1.4 MB buffer, rescan-reuse
|
||||
/// round) and no parse at all.
|
||||
/// * **a buffer on the large-file fast path contributes nothing**, so a
|
||||
/// file the index holds whose buffer has grown past the threshold is
|
||||
/// taken back out — the one thing a widen removes, and the same rule
|
||||
/// `collect_sources` follows.
|
||||
///
|
||||
/// `added` is the directories that entered [`Workspace::scope_dirs`]; the
|
||||
/// caller decides that they really are an addition and nothing else
|
||||
/// (`server.rs`'s `widen_of`).
|
||||
pub fn begin_widen(
|
||||
&mut self,
|
||||
added: &[PathBuf],
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: bool,
|
||||
) -> Scan {
|
||||
let mut trace = ScanTrace::opened(&mut self.scans, trace, "widen");
|
||||
let discovering = trace.now();
|
||||
let held: HashSet<PathBuf> = self.index.files().iter().cloned().collect();
|
||||
let cap = self.client.max_file_size;
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let mut skipped = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
let mut warnings: Vec<String> = Vec::new();
|
||||
// The walk of the *added* directories alone, by the same rung-3 rules
|
||||
// `folder_files` follows — the whole scope is the union of these walks,
|
||||
// so the files this one finds beyond what is already indexed are
|
||||
// exactly the ones the widen owes.
|
||||
let mut stats = 0usize;
|
||||
for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) {
|
||||
let path = found.path.clone();
|
||||
// Already indexed: by another scope directory this walk overlaps,
|
||||
// or by an earlier scan. Re-reading it is the cost this path
|
||||
// exists to avoid.
|
||||
if held.contains(&path) {
|
||||
continue;
|
||||
}
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &path, size, cap });
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
if spoken_for.contains(path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
files.push(path);
|
||||
}
|
||||
let mut analyzed = Analyzed::default();
|
||||
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
|
||||
let mut gone: Vec<PathBuf> = Vec::new();
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
files.retain(|taken| taken != &path);
|
||||
if doc.large {
|
||||
if held.contains(&path) {
|
||||
gone.push(path);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
|
||||
analyzed.words.insert(path.clone(), doc.words());
|
||||
buffered.insert(path.clone(), doc.text.clone());
|
||||
files.push(path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.discovery_ms, discovering);
|
||||
let ordering = trace.now();
|
||||
let WorkList { files: work, head } = self.open_first(files);
|
||||
let head = scan_order::worth_waiting(head, work.len());
|
||||
ScanTrace::add(&mut trace.order_ms, ordering);
|
||||
trace.measure_work(work.len(), held_bytes(&buffered), skipped, self.cache.work());
|
||||
// A whole scan drops the view cache entire, because a rescan claims
|
||||
// nothing about *which* file moved. A widen names exactly the files it
|
||||
// is reading, so it drops exactly those — which keeps the cache's own
|
||||
// rule ("every way a file's text can move drops its entry",
|
||||
// [`Workspace::file_view`]) literally true rather than nearly so.
|
||||
for path in &work {
|
||||
self.views.borrow_mut().retain(|view| &view.path != path);
|
||||
}
|
||||
// Which files exist once this widen lands: what the index holds, less
|
||||
// what it is about to lose, plus what the widen brings in.
|
||||
let mut paths: Vec<PathBuf> =
|
||||
held.into_iter().filter(|path| !gone.contains(path)).collect();
|
||||
paths.extend(work.iter().cloned());
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
gone.sort();
|
||||
Scan {
|
||||
kind: ScanKind::Widen,
|
||||
work,
|
||||
head,
|
||||
buffered,
|
||||
includes: HashMap::new(),
|
||||
unread: Vec::new(),
|
||||
paths,
|
||||
gone,
|
||||
analyzed,
|
||||
// Rung 3 is the only rung an open buffer can widen, and it names no
|
||||
// `+incdir+`. Carried from the graph in hand rather than assumed
|
||||
// empty, so folding a widen in never *changes* the search path.
|
||||
incdirs: self.includes.incdirs().to_vec(),
|
||||
// A widen resolves no filelist — rung 1 is not a scope an open
|
||||
// buffer can widen — so the only warnings here are the walk's own.
|
||||
warnings,
|
||||
at: 0,
|
||||
// A widen names the directories it is about to walk, so there is
|
||||
// never anything left to discover.
|
||||
pending: None,
|
||||
staged: Vec::new(),
|
||||
staged_at: Vec::new(),
|
||||
words: HashMap::new(),
|
||||
skipped,
|
||||
cached: 0,
|
||||
trace,
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the rest of the workspace, once the user's own neighbourhood has
|
||||
/// been indexed and published — the second half of a split discovery
|
||||
/// ([`PendingDiscovery`]). Reports whether there was anything to walk.
|
||||
///
|
||||
/// **Its own step, indexing nothing.** The step it shares a call with
|
||||
/// would otherwise report a file against a denominator that grew inside
|
||||
/// the same call, and a bar whose percentage falls is worse than one that
|
||||
/// waits (`docs/features/indexing-ux/README.md`). So this discovers, says
|
||||
/// "there is more", and lets the next step be an ordinary one.
|
||||
fn discover_the_rest(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
|
||||
let Some(mut pending) = scan.take_pending() else { return false };
|
||||
let discovering = scan.trace.now();
|
||||
let mut skipped = 0usize;
|
||||
let (files, warnings, walked_skips) = {
|
||||
let mut counting = |event: IndexEvent<'_>| {
|
||||
if matches!(event, IndexEvent::Skipped { .. }) {
|
||||
skipped += 1;
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace)
|
||||
};
|
||||
debug_assert_eq!(skipped, walked_skips, "the cap reports every skip it counts");
|
||||
ScanTrace::add(&mut scan.trace.discovery_ms, discovering);
|
||||
scan.land_discovery(files, warnings, walked_skips, pending.tracker.has_conflict());
|
||||
scan.trace.measure_work(
|
||||
scan.work.len(),
|
||||
held_bytes(&scan.buffered),
|
||||
scan.skipped,
|
||||
scan.trace.cache,
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
/// Open the store a whole rescan asked for, if this is the first thing to
|
||||
/// need it ([`StoreOpen`]).
|
||||
///
|
||||
/// Called from the two places that ask the store anything — a scan's step
|
||||
/// and a save's write-through — so a rescan that reaches no file never
|
||||
/// reads it, and the widen behind that rescan still finds it open the
|
||||
/// moment it reaches one.
|
||||
pub(super) fn open_store(&mut self, trace: &mut ScanTrace) {
|
||||
let StoreOpen::Deferred(dir) = std::mem::replace(&mut self.store, StoreOpen::Done) else {
|
||||
return;
|
||||
};
|
||||
let opening = trace.now();
|
||||
self.cache = IndexCache::open(dir);
|
||||
ScanTrace::add(&mut trace.cache_open_ms, opening);
|
||||
// The counters this scan is charged for start where the store it has
|
||||
// just opened does. A scan that never opens one keeps the baseline
|
||||
// `measure_work` took, so its delta is the nothing it did.
|
||||
trace.cache = CacheWork::default();
|
||||
}
|
||||
|
||||
/// Index the next file of `scan`, reporting whether there was one.
|
||||
///
|
||||
/// One file is the whole step: **its text is read**, its record is taken —
|
||||
/// from the open buffer's own analysis, from the persistent cache, or from
|
||||
/// a parse — its `` `include``s are scanned off that text and its
|
||||
/// completion words are taken off the record. All three are *staged* on
|
||||
/// the scan rather than merged, because merging is a pass over the whole
|
||||
/// workspace and one per file would be quadratic
|
||||
/// ([`WorkspaceIndex::absorb`]).
|
||||
///
|
||||
/// **The text is read here and dropped here** (2026-09-08). Everything the
|
||||
/// scan will ever want from it — the content hash the store is keyed by,
|
||||
/// the parse, the include lines — is taken in this one step, so a whole
|
||||
/// scan reads each file's bytes exactly once and holds one file's text at
|
||||
/// a time rather than the whole scope's. An **open buffer's** text is not
|
||||
/// read: it was taken with the work list, beside the analysis that
|
||||
/// describes the same bytes, so a `didChange` mid-scan cannot make the two
|
||||
/// disagree. A file that cannot be read is remembered as `unread` and
|
||||
/// contributes nothing, which is what a file `collect_sources` could not
|
||||
/// read used to do before the work list existed.
|
||||
pub fn scan_step(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) -> bool {
|
||||
let (done, total) = (scan.at, scan.work.len());
|
||||
if done == total {
|
||||
return self.discover_the_rest(scan, watch);
|
||||
}
|
||||
scan.at += 1;
|
||||
// The first file of a scan is the first thing to ask the store
|
||||
// anything, so it is where the store this scan asked for is opened.
|
||||
self.open_store(&mut scan.trace);
|
||||
let path = scan.work[done].clone();
|
||||
let Some(source) = scan.take_text(&path) else {
|
||||
scan.unread.push(path);
|
||||
return true;
|
||||
};
|
||||
let text = source.as_str();
|
||||
let held = scan.analyzed.facts.remove(&path);
|
||||
let known_words = scan.analyzed.words.remove(&path);
|
||||
let facts = match held {
|
||||
// An open buffer's own finished analysis comes first. It is the
|
||||
// only source of facts that is right when the buffer has unsaved
|
||||
// edits, which is precisely when the content-keyed cache below has
|
||||
// nothing to offer. The record is written through all the same, so
|
||||
// the next session starts from it.
|
||||
Some(facts) => {
|
||||
watch(IndexEvent::Analyzed { done, total, path: &path });
|
||||
scan.trace.buffers += 1;
|
||||
self.cache.record(&facts, text);
|
||||
facts
|
||||
}
|
||||
// The cache answers for the exact bytes about to be indexed, so a
|
||||
// hit is the parse and not a guess at it. A miss — a new file, a
|
||||
// changed one, a record this version cannot read — parses, and
|
||||
// the result is written through immediately, which is what makes
|
||||
// an interrupted scan resumable.
|
||||
None => match self.cache.facts_for(&path, text) {
|
||||
Some(facts) => {
|
||||
scan.cached += 1;
|
||||
watch(IndexEvent::Cached { done, total, path: &path });
|
||||
facts
|
||||
}
|
||||
None => {
|
||||
watch(IndexEvent::Parsing { done, total, path: &path });
|
||||
let parsing = scan.trace.now();
|
||||
let facts = FileFacts::of(path.clone(), text);
|
||||
ScanTrace::add(&mut scan.trace.parse_ms, parsing);
|
||||
scan.trace.parse_bytes += text.len();
|
||||
self.cache.record(&facts, text);
|
||||
facts
|
||||
}
|
||||
},
|
||||
};
|
||||
// Read off the record rather than lexed here: since `FACTS_FORMAT` 13
|
||||
// a file's identifier census *is* one of its facts, so a cached hit
|
||||
// brings its words with it and a parse harvested them from the tokens
|
||||
// it already had. That retires the per-file re-lex a scan used to pay
|
||||
// for the completion word table (TODO §10's deferred item;
|
||||
// `docs/features/semantic-lints-on/README.md` has the measurement).
|
||||
// An open buffer's words are still the caller's, read off the tokens
|
||||
// it was analyzed from.
|
||||
let words = known_words.unwrap_or_else(|| facts.words().to_vec());
|
||||
// Scanned here, off the text this step read, because the include graph
|
||||
// is built when the scan ends and by then the text is gone. It is a
|
||||
// line scan over bytes already in cache, and it replaces the identical
|
||||
// scan `IncludeGraph::build` used to run over the same text later.
|
||||
scan.includes.insert(path.clone(), includes::scan(text));
|
||||
scan.words.insert(path, words);
|
||||
scan.staged.push(facts);
|
||||
scan.staged_at.push(done);
|
||||
true
|
||||
}
|
||||
|
||||
/// The work list in the order a scan walks it: the open buffers' own
|
||||
/// files, then the rest of the folders those buffers raise to, then
|
||||
/// everything else in path order ([`crate::scan_order`]).
|
||||
///
|
||||
/// **A reporting and latency decision and nothing else.**
|
||||
/// `vlog_semantic::IndexBuilder` sorts by path inside `finish` since
|
||||
/// 2026-08-27, so no insertion order can reach the index: this changes
|
||||
/// which file the progress bar names first — the user's own, and then
|
||||
/// what they are looking at across the folder — and changes nothing about
|
||||
/// the result. Pinned both ends: the builder's own
|
||||
/// `no_insertion_order_can_change_what_the_builder_produces`, and
|
||||
/// `the_open_files_are_indexed_first_and_the_index_cannot_tell` here.
|
||||
/// Re-order what is left of `scan` around the buffers open **now** — the
|
||||
/// same ranking [`Workspace::begin_scan`] applied, re-applied because a
|
||||
/// `didOpen` answered mid-scan changed the answer to "where is the user
|
||||
/// working?".
|
||||
///
|
||||
/// Called after the burst carrying that `didOpen` has been applied, so the
|
||||
/// buffer is installed and the folder it raises to is known. What was
|
||||
/// already indexed is untouched; only the tail moves, and the finished
|
||||
/// index cannot tell ([`Scan::reorder`]).
|
||||
/// **The rest of the workspace is walked first when it has not been.** A
|
||||
/// split startup is leading with the folder the user *was* in; a `didOpen`
|
||||
/// says they are somewhere else now, and re-ordering a work list that does
|
||||
/// not yet contain the new folder would answer the request behind that
|
||||
/// `didOpen` off a prefix that cannot hold what it is asking about. The
|
||||
/// walk this order postpones is exactly what makes the new folder
|
||||
/// nameable, so it happens here
|
||||
/// (`docs/features/perf5r-first-answer/README.md`).
|
||||
pub fn open_next(&mut self, scan: &mut Scan, watch: &mut dyn FnMut(IndexEvent)) {
|
||||
self.discover_the_rest(scan, watch);
|
||||
let ordered = self.open_first(scan.remaining());
|
||||
scan.reorder(ordered);
|
||||
}
|
||||
|
||||
fn open_first(&self, files: Vec<PathBuf>) -> WorkList {
|
||||
let open: Vec<PathBuf> = self.docs.values().filter_map(|doc| doc.path.clone()).collect();
|
||||
scan_order::work_list(files, &open, &self.raised_dirs())
|
||||
}
|
||||
|
||||
/// Make every table answer for the files `scan` has taken since the last
|
||||
/// publish — the moment a mid-scan answer is worth paying a merge for.
|
||||
///
|
||||
/// **All three tables together, never one of them.** The index, the
|
||||
/// completion tables and the include graph are what an answer reads, and a
|
||||
/// hover that saw a scanned file while a completion or an include link
|
||||
/// could not would make "the workspace as far as it has been scanned"
|
||||
/// three different things at once. Each is folded in with the batch form
|
||||
/// of the incremental update it already had, so one publish is one pass
|
||||
/// over the index and not one per file.
|
||||
pub fn publish_scan(&mut self, scan: &mut Scan) {
|
||||
if scan.staged.is_empty() {
|
||||
return;
|
||||
}
|
||||
let taken = std::mem::take(&mut scan.staged_at);
|
||||
let absorbing = scan.trace.now();
|
||||
self.index.absorb(std::mem::take(&mut scan.staged), &[]);
|
||||
ScanTrace::add(&mut scan.trace.publish_absorb_ms, absorbing);
|
||||
let completing = scan.trace.now();
|
||||
let published: Vec<PathBuf> = taken.iter().map(|&at| scan.work[at].clone()).collect();
|
||||
let words = published
|
||||
.iter()
|
||||
.map(|path| (path.clone(), scan.words.get(path).cloned().unwrap_or_default()))
|
||||
.collect();
|
||||
self.candidates.absorb(&self.index, words);
|
||||
ScanTrace::add(&mut scan.trace.publish_candidates_ms, completing);
|
||||
let including = scan.trace.now();
|
||||
let found = scan::included(&scan.includes, &published);
|
||||
self.includes.absorb_includes(&scan.incdirs, &scan.paths, &found);
|
||||
ScanTrace::add(&mut scan.trace.publish_includes_ms, including);
|
||||
let refreshing = scan.trace.now();
|
||||
// Every open buffer resolves against the index, so a buffer whose
|
||||
// cross-file names the scan has just reached must be able to see them.
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
ScanTrace::add(&mut scan.trace.publish_overlay_ms, refreshing);
|
||||
scan.trace.saw_publish(taken.len());
|
||||
}
|
||||
|
||||
/// Finish `scan`: the index, the completion tables, the include graph and
|
||||
/// every open buffer's overlay. Reports the warnings from resolving the
|
||||
/// scope.
|
||||
///
|
||||
/// **What comes out is the index a one-shot scan over the same work list
|
||||
/// would have produced**, however many times [`Workspace::publish_scan`]
|
||||
/// ran in between: a publish only ever folds records in, and the index's
|
||||
/// tables are a pure function of the records it holds
|
||||
/// ([`WorkspaceIndex::absorb`]).
|
||||
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String> {
|
||||
match scan.kind {
|
||||
ScanKind::Whole => self.finish_whole_scan(scan),
|
||||
ScanKind::Widen => self.finish_widen(scan),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Workspace::finish_scan`] for a whole scan.
|
||||
fn finish_whole_scan(&mut self, scan: Scan) -> Vec<String> {
|
||||
let Scan {
|
||||
mut work, unread, incdirs, warnings, staged, words, includes, mut trace, ..
|
||||
} = scan;
|
||||
// What the scan really indexed, which is its work list unless a file
|
||||
// left the disk between the walk and its own step. Such a file is not
|
||||
// in scope any more, so it must land in `gone` exactly as it would
|
||||
// have if the walk had missed it.
|
||||
work.retain(|path| !unread.contains(path));
|
||||
let found = scan::included(&includes, &work);
|
||||
let leaving = trace.now();
|
||||
// Whatever the last scan left in the index that this one's work list
|
||||
// does not name is a file that is no longer in scope.
|
||||
let held: HashSet<&Path> = work.iter().map(PathBuf::as_path).collect();
|
||||
let gone: Vec<PathBuf> = self
|
||||
.index
|
||||
.files()
|
||||
.iter()
|
||||
.filter(|path| !held.contains(path.as_path()))
|
||||
.cloned()
|
||||
.collect();
|
||||
ScanTrace::add(&mut trace.gone_ms, leaving);
|
||||
let absorbing = trace.now();
|
||||
self.index.absorb(staged, &gone);
|
||||
ScanTrace::add(&mut trace.absorb_ms, absorbing);
|
||||
// The one moment the live set of entries is known, so the one moment
|
||||
// the append log is worth rewriting — and only when this scan reached
|
||||
// a file at all. A scan with an empty work list asked the store
|
||||
// nothing and never opened it, so there is nothing of this session's
|
||||
// in it and nothing to rewrite it from (§P4b (b1)); the rewrite of a
|
||||
// store that *is* open is itself skipped when it would reproduce the
|
||||
// file byte for byte ([`IndexCache::compact`], §P4b (a)).
|
||||
if matches!(self.store, StoreOpen::Done) {
|
||||
self.cache.compact();
|
||||
}
|
||||
let completing = trace.now();
|
||||
// Built from the words every step took off its own record — the same
|
||||
// list, so a file the scope ladder excluded contributes no completion
|
||||
// candidates either, and nothing is lexed twice.
|
||||
self.candidates = Candidates::from_words(&self.index, words);
|
||||
ScanTrace::add(&mut trace.candidates_ms, completing);
|
||||
let including = trace.now();
|
||||
// Same list again: an `` `include`` in a file the scope excluded is
|
||||
// not an edge, and a file it excluded is not a hop away from anything.
|
||||
// The lines themselves were read at each file's own step.
|
||||
self.includes = IncludeGraph::from_includes(&found, incdirs);
|
||||
ScanTrace::add(&mut trace.includes_ms, including);
|
||||
let refreshing = trace.now();
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
ScanTrace::add(&mut trace.overlay_ms, refreshing);
|
||||
self.landed(trace);
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Close a scan's trace: the tables it left behind, measured, and the
|
||||
/// whole thing set aside for the server to log.
|
||||
///
|
||||
/// Every size it reads is a walk, so the trace itself decides whether to
|
||||
/// take them ([`ScanTrace::landed`]); a scan nobody traced sets nothing
|
||||
/// aside.
|
||||
fn landed(&mut self, mut trace: ScanTrace) {
|
||||
trace.landed(self.docs.len(), &self.cache, &self.index, &self.candidates, &self.includes);
|
||||
if trace.on() {
|
||||
self.last_trace = trace;
|
||||
}
|
||||
}
|
||||
|
||||
/// The trace of the scan that just finished, taken away — an inert one
|
||||
/// when the scan was not being traced.
|
||||
pub fn take_scan_trace(&mut self) -> ScanTrace {
|
||||
std::mem::take(&mut self.last_trace)
|
||||
}
|
||||
|
||||
/// [`Workspace::finish_scan`] for a widen: the same three tables, folded
|
||||
/// into rather than replaced.
|
||||
///
|
||||
/// Each table is landed with the batch form of the incremental update it
|
||||
/// already had, which is the same one [`Workspace::publish_scan`] uses —
|
||||
/// so what comes out is what a whole scan over the union of the old files
|
||||
/// and the new ones would have produced. The three claims that makes, one
|
||||
/// per table:
|
||||
///
|
||||
/// * **the index** — [`WorkspaceIndex::absorb`] keeps the records
|
||||
/// path-sorted and one to a path and merges them the way a whole build
|
||||
/// does;
|
||||
/// * **the completion tables** — the two index-derived ones are re-derived
|
||||
/// from the index, and the word table is patched per file into the same
|
||||
/// total order a whole build sorts into;
|
||||
/// * **the include graph** — the known-file and folded-spelling tables are
|
||||
/// relearned from the whole in-scope list and every held edge is
|
||||
/// re-spelled against it (the graph is rebuilt from every file's staged
|
||||
/// include list, [`IncludeGraph::from_includes`]), so a file that is in
|
||||
/// scope for the first time can lend its spelling to an edge that was
|
||||
/// resolved before it arrived.
|
||||
///
|
||||
/// One thing a whole scan does that this deliberately does not: the
|
||||
/// persistent store is **not compacted**. A widen does not know the live
|
||||
/// set of entries — it only added to it — and the next whole rescan
|
||||
/// rewrites the log anyway.
|
||||
fn finish_widen(&mut self, scan: Scan) -> Vec<String> {
|
||||
let Scan {
|
||||
mut work,
|
||||
mut paths,
|
||||
gone,
|
||||
incdirs,
|
||||
warnings,
|
||||
staged,
|
||||
words,
|
||||
includes,
|
||||
mut trace,
|
||||
unread,
|
||||
..
|
||||
} = scan;
|
||||
// A widen only ever adds, so a file whose text had gone by its own
|
||||
// step is simply not added — it is in neither list below.
|
||||
work.retain(|path| !unread.contains(path));
|
||||
paths.retain(|path| !unread.contains(path));
|
||||
let found = scan::included(&includes, &work);
|
||||
let absorbing = trace.now();
|
||||
self.index.absorb(staged, &gone);
|
||||
ScanTrace::add(&mut trace.absorb_ms, absorbing);
|
||||
// Before the additions, so the two never disagree about a path that is
|
||||
// in both lists — which cannot happen today (a large buffer is in
|
||||
// neither `work` nor `paths`) and would be a silent wrong answer if it
|
||||
// ever did.
|
||||
for path in &gone {
|
||||
self.candidates.remove_file(&self.index, path);
|
||||
self.includes.remove_file(path, &paths);
|
||||
}
|
||||
let batch: Vec<(PathBuf, Vec<String>)> = work
|
||||
.iter()
|
||||
.map(|path| (path.clone(), words.get(path).cloned().unwrap_or_default()))
|
||||
.collect();
|
||||
let completing = trace.now();
|
||||
self.candidates.absorb(&self.index, batch);
|
||||
ScanTrace::add(&mut trace.candidates_ms, completing);
|
||||
let including = trace.now();
|
||||
self.includes.absorb_includes(&incdirs, &paths, &found);
|
||||
ScanTrace::add(&mut trace.includes_ms, including);
|
||||
let refreshing = trace.now();
|
||||
for doc in self.docs.values_mut() {
|
||||
doc.refresh_overlay(&self.index);
|
||||
}
|
||||
ScanTrace::add(&mut trace.overlay_ms, refreshing);
|
||||
self.landed(trace);
|
||||
warnings
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The one-shot forms: the protocol above run to the end in one call.
|
||||
// Test-only, every one of them — the server drives the three calls
|
||||
// itself so that it can answer messages between two of them.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Adopt the workspace roots and build the index for the first time.
|
||||
/// Returns whatever the caller should tell the user about the scope.
|
||||
///
|
||||
/// The unwatched form. `server.rs` always watches (it has a progress bar
|
||||
/// to move), so this is reachable from tests alone — of which there are
|
||||
/// several dozen across this crate, and none of them has an opinion about
|
||||
/// progress reporting.
|
||||
#[cfg(test)]
|
||||
pub fn open_roots(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
|
||||
self.open_roots_with(roots, &mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::open_roots`] with `lucisv.index.scope` set to
|
||||
/// `"workspace"`: adopt the roots and index **all** of them, which is what
|
||||
/// every session did before 2026-08-27.
|
||||
///
|
||||
/// Test-only, and used by the dozens of tests across this crate that are
|
||||
/// about something other than scope — a hover, a rename, an inlay hint —
|
||||
/// and want the whole fixture tree in the index without opening a buffer
|
||||
/// in each of its directories first. Spelling it out at the call site is
|
||||
/// what keeps "this test wants the wide scope" a statement rather than an
|
||||
/// accident. The folder scope's own behaviour is tested by the tests named
|
||||
/// in `docs/features/index-scope/README.md`.
|
||||
#[cfg(test)]
|
||||
pub fn open_whole_workspace(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
|
||||
self.open_whole_workspace_with(roots, &mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::open_whole_workspace`], watched. Test-only, for the two
|
||||
/// tests that want the wide scope *and* the events.
|
||||
#[cfg(test)]
|
||||
pub fn open_whole_workspace_with(
|
||||
&mut self,
|
||||
roots: Vec<PathBuf>,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
) -> Vec<String> {
|
||||
self.client.index_scope = IndexScope::Workspace;
|
||||
self.open_roots_with(roots, watch)
|
||||
}
|
||||
|
||||
/// [`Workspace::open_roots`], watched — the unwatched form's sibling, and
|
||||
/// test-only for the same reason: the server drives the scan itself now,
|
||||
/// one file at a time, so it adopts the roots and steps the scan rather
|
||||
/// than calling this.
|
||||
#[cfg(test)]
|
||||
pub fn open_roots_with(
|
||||
&mut self,
|
||||
roots: Vec<PathBuf>,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
) -> Vec<String> {
|
||||
self.adopt_roots(roots);
|
||||
self.rebuild_index_with(watch)
|
||||
}
|
||||
|
||||
/// Re-scan the workspace and rebuild the index and the completion tables,
|
||||
/// then refresh every open buffer's overlay. Called on `initialize` and on
|
||||
/// every `didSave`.
|
||||
///
|
||||
/// Returns the warnings from resolving the scope — a filelist naming a
|
||||
/// file that is gone, say. Rendering them is `server.rs`'s job; this
|
||||
/// module speaks no protocol.
|
||||
///
|
||||
/// The unwatched form, reachable from tests alone for the same reason
|
||||
/// `open_roots` is.
|
||||
#[cfg(test)]
|
||||
pub fn rebuild_index(&mut self) -> Vec<String> {
|
||||
self.rebuild_index_with(&mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::rebuild_index`], watched: `watch` is called once for every
|
||||
/// file the size cap skipped and once for every file about to be parsed,
|
||||
/// in index order and before the parse, so a caller can report where the
|
||||
/// rescan has got to.
|
||||
///
|
||||
/// The events cover the index build alone. The completion tables and the
|
||||
/// include graph are built from the same list afterwards and are not
|
||||
/// reported: they cost a small fraction of the parse, and a bar that went
|
||||
/// to 100% and then sat there would be worse than one that ends.
|
||||
///
|
||||
/// A scan with nothing happening between its files, which is what every
|
||||
/// caller but the server's message loop wants. The loop drives the same
|
||||
/// three calls itself and answers messages between two of them
|
||||
/// (`docs/features/scan-interleave/README.md`) — so "one shot" and
|
||||
/// "interleaved" are not two scans that have to be kept in step, they are
|
||||
/// this loop with and without a drain in it.
|
||||
///
|
||||
/// Test-only for that reason: the server takes the three calls, and this
|
||||
/// is what every test that just wants an index calls instead.
|
||||
#[cfg(test)]
|
||||
pub fn rebuild_index_with(&mut self, watch: &mut dyn FnMut(IndexEvent)) -> Vec<String> {
|
||||
let mut scan = self.begin_scan(watch, false);
|
||||
while self.scan_step(&mut scan, watch) {}
|
||||
self.finish_scan(scan)
|
||||
}
|
||||
|
||||
/// [`Workspace::begin_widen`] run to the end in one shot, the way
|
||||
/// [`Workspace::rebuild_index_with`] runs a whole scan. Test-only for the
|
||||
/// same reason: the server drives the three calls itself.
|
||||
#[cfg(test)]
|
||||
pub fn widen_index(&mut self, added: &[PathBuf]) -> Vec<String> {
|
||||
self.widen_index_with(added, &mut |_| {})
|
||||
}
|
||||
|
||||
/// [`Workspace::widen_index`], watched.
|
||||
#[cfg(test)]
|
||||
pub fn widen_index_with(
|
||||
&mut self,
|
||||
added: &[PathBuf],
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
) -> Vec<String> {
|
||||
let mut scan = self.begin_widen(added, watch, false);
|
||||
while self.scan_step(&mut scan, watch) {}
|
||||
self.finish_scan(scan)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many bytes of buffer text a scan carries for its whole life — every
|
||||
/// other file's text lives from its own step to the end of that step.
|
||||
fn held_bytes(buffered: &HashMap<PathBuf, String>) -> usize {
|
||||
buffered.values().map(String::len).sum()
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! What decides the scope: the workspace roots, the `lucisv.*` settings a
|
||||
//! client pushed, and the ladder they select — which rung is in force and
|
||||
//! which directories it walks.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::{StoreOpen, Workspace};
|
||||
use crate::index_cache::IndexCache;
|
||||
use crate::settings::{ClientSettings, IndexScope};
|
||||
|
||||
impl Workspace {
|
||||
/// Take the workspace roots without indexing anything.
|
||||
///
|
||||
/// The half of [`Workspace::open_roots_with`] that is not a scan, for the
|
||||
/// caller that drives the scan itself — the server, which runs the startup
|
||||
/// scan through the same interleaved path every later rescan takes.
|
||||
pub fn adopt_roots(&mut self, roots: Vec<PathBuf>) {
|
||||
self.roots = roots;
|
||||
}
|
||||
|
||||
/// Add and remove workspace roots mid-session, reporting whether the set
|
||||
/// actually moved — which is whether the caller owes a rebuild.
|
||||
///
|
||||
/// Removals are applied before additions, so a folder named in both lists
|
||||
/// (which the protocol does not forbid, and which is how some clients
|
||||
/// spell "this folder moved") ends up present. Adding a root that is
|
||||
/// already held and removing one that was never held are both no-ops, and
|
||||
/// say so by leaving the set equal: `didChangeWorkspaceFolders` is a
|
||||
/// notification, so there is nowhere to report a disagreement to and
|
||||
/// nothing to gain from re-scanning for one.
|
||||
pub fn change_roots(&mut self, added: Vec<PathBuf>, removed: &[PathBuf]) -> bool {
|
||||
let before = self.roots.clone();
|
||||
self.roots.retain(|root| !removed.contains(root));
|
||||
for root in added {
|
||||
if !self.roots.contains(&root) {
|
||||
self.roots.push(root);
|
||||
}
|
||||
}
|
||||
self.roots != before
|
||||
}
|
||||
|
||||
/// Whether the client opened a workspace at all.
|
||||
///
|
||||
/// Without one there is nothing to walk but the open buffers' own
|
||||
/// directories, and nothing to clamp the folder scope's climb against.
|
||||
///
|
||||
/// Test-only since 2026-08-27: `didOpen` used to branch on it, and now
|
||||
/// branches on whether the file widened the scope, which is the same
|
||||
/// question asked of the rung that is actually in force.
|
||||
#[cfg(test)]
|
||||
pub fn has_roots(&self) -> bool {
|
||||
!self.roots.is_empty()
|
||||
}
|
||||
|
||||
/// The workspace folders, in the order the client named them.
|
||||
///
|
||||
/// The first one is what a relative path in a setting is resolved against,
|
||||
/// which is what [`Workspace::filelist_path`] does inline and what
|
||||
/// `lucisv.lint.waivers` needs too.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
}
|
||||
|
||||
/// The directories the folder scope walks: every directory a buffer has
|
||||
/// been opened from this session, each raised `lucisv.index.scopeDepth`
|
||||
/// levels. **Empty when the folder scope is not the active rung** — a
|
||||
/// filelist and the whole-workspace walk are scopes an open buffer cannot
|
||||
/// widen.
|
||||
///
|
||||
/// Public because `server.rs` compares it across a `didOpen` to decide
|
||||
/// whether the file just opened widened the scope, which is the one thing
|
||||
/// that makes a `didOpen` worth a rebuild.
|
||||
pub fn scope_dirs(&self) -> Vec<PathBuf> {
|
||||
if !self.folder_scoped() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
dirs
|
||||
}
|
||||
|
||||
/// Whether rung 3 — the folder scope — is the one in force.
|
||||
///
|
||||
/// A filelist outranks it, and so does an explicit
|
||||
/// `lucisv.index.scope: "workspace"` **when there is a workspace to
|
||||
/// walk**: with no roots there is nothing that setting could name, so a
|
||||
/// rootless session is folder-scoped whatever it says.
|
||||
fn folder_scoped(&self) -> bool {
|
||||
self.filelist_path().is_none() && !self.walks_the_workspace()
|
||||
}
|
||||
|
||||
/// Whether rung 2 — the walk of every workspace folder — is in force.
|
||||
pub(super) fn walks_the_workspace(&self) -> bool {
|
||||
self.client.index_scope == IndexScope::Workspace && !self.roots.is_empty()
|
||||
}
|
||||
|
||||
/// `dir` raised `lucisv.index.scopeDepth` ancestor levels, clamped twice:
|
||||
/// it never climbs above the workspace root that contains it — the deepest
|
||||
/// one, for nested roots — and never above the filesystem root, which is
|
||||
/// where a directory belonging to no root stops.
|
||||
///
|
||||
/// The root clamp is what keeps a `scopeDepth` of 5 in a two-deep project
|
||||
/// from indexing the user's home directory.
|
||||
///
|
||||
/// **A rootless session does not climb at all** (2026-08-28). The clamp is
|
||||
/// the whole reason a raise is safe, and with no workspace folder there is
|
||||
/// nothing to clamp against: a lone file opened from
|
||||
/// `~/work/chip/hw/ip/aes/rtl/` would otherwise raise the shipped
|
||||
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`] into `~/work/chip/hw/ip/` and
|
||||
/// walk a tree the user never named. The single-file case stays what it
|
||||
/// has always been — the buffer's own directory, read flat — and a user
|
||||
/// who wants more opens the folder, which is what gives the climb a floor.
|
||||
fn raised(&self, dir: &Path) -> PathBuf {
|
||||
if self.roots.is_empty() {
|
||||
return dir.to_path_buf();
|
||||
}
|
||||
let floor = self
|
||||
.roots
|
||||
.iter()
|
||||
.filter(|root| dir.starts_with(root))
|
||||
.max_by_key(|root| root.components().count());
|
||||
let mut out = dir;
|
||||
for _ in 0..self.client.index_scope_depth {
|
||||
if Some(out) == floor.map(PathBuf::as_path) {
|
||||
break;
|
||||
}
|
||||
let Some(parent) = out.parent() else { break };
|
||||
out = parent;
|
||||
}
|
||||
out.to_path_buf()
|
||||
}
|
||||
|
||||
/// The directories the open buffers' own folders raise to, whichever rung
|
||||
/// of the ladder is in force.
|
||||
///
|
||||
/// [`Workspace::scope_dirs`] answers the same question *as a scope* and is
|
||||
/// therefore empty unless rung 3 is in force. This one is an **ordering**
|
||||
/// question — where in the workspace the user is working — and it has the
|
||||
/// same answer under a filelist or an explicit `workspace` scope, where it
|
||||
/// is the only thing that says which part of a 4 000-file walk to index
|
||||
/// first.
|
||||
pub(super) fn raised_dirs(&self) -> Vec<PathBuf> {
|
||||
let mut dirs: Vec<PathBuf> = self.opened_dirs.iter().map(|dir| self.raised(dir)).collect();
|
||||
dirs.sort();
|
||||
dirs.dedup();
|
||||
dirs
|
||||
}
|
||||
|
||||
/// The `lucisv.*` settings in force, for the resolution points in
|
||||
/// `format.rs` to fold in.
|
||||
pub fn client_settings(&self) -> &ClientSettings {
|
||||
&self.client
|
||||
}
|
||||
|
||||
/// Adopt the settings a client pushed.
|
||||
///
|
||||
/// Returns `true` when the caller must rebuild the index: `exclude`,
|
||||
/// `filelist`, `index.maxFileSize`, `index.scope` and `index.scopeDepth`
|
||||
/// are the five that change *which files exist* as far as this server is
|
||||
/// concerned. `lineLength` and `indent` are read afresh by every
|
||||
/// formatting request, so they need no invalidation at all — and neither
|
||||
/// does `index.logFiles`, which changes only how loudly the *next* rescan
|
||||
/// narrates itself.
|
||||
///
|
||||
/// `largeFile.threshold` asks for no rescan either, and deliberately: it
|
||||
/// is consulted where a `Document` is *built*, so a change to it reaches
|
||||
/// each open buffer at that buffer's next `didOpen`/`didChange` and not
|
||||
/// before. A rescan now would index by the mode each buffer is still in,
|
||||
/// which is the mode the index already reflects
|
||||
/// (`docs/features/large-file-mode/README.md`).
|
||||
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
|
||||
let rescan = self.client.exclude != settings.exclude
|
||||
|| self.client.filelist != settings.filelist
|
||||
|| self.client.max_file_size != settings.max_file_size
|
||||
|| self.client.index_scope != settings.index_scope
|
||||
|| self.client.index_scope_depth != settings.index_scope_depth;
|
||||
// Neither cache setting changes *which files exist*, so neither asks
|
||||
// for a rescan — but both change where, or whether, the cache writes,
|
||||
// and the cache in hand was opened under the old ones. Dropping it
|
||||
// here is what makes `persist: false` take effect at once in both
|
||||
// directions: nothing more is written, and nothing held is read. The
|
||||
// next whole rescan opens the store the new settings name.
|
||||
if self.client.index_persist != settings.index_persist
|
||||
|| self.client.index_cache_path != settings.index_cache_path
|
||||
{
|
||||
self.cache = IndexCache::disabled();
|
||||
// And a deferred re-open goes with it, or the next file to want
|
||||
// the store would open the directory the old settings named.
|
||||
self.store = StoreOpen::Done;
|
||||
}
|
||||
self.client = settings;
|
||||
rescan
|
||||
}
|
||||
|
||||
/// Where the persistent index cache should live, by
|
||||
/// [`crate::index_cache::cache_dir`]'s ladder — the client's setting, the
|
||||
/// editor's storage folder, this platform's cache directory, or nowhere.
|
||||
pub(super) fn cache_dir(&self) -> Option<PathBuf> {
|
||||
// In this crate's own tests nothing falls through to the OS cache
|
||||
// directory: a unit test must not write into the developer's own
|
||||
// `~/Library/Caches`, and every test that is *about* the cache names
|
||||
// a directory of its own — a `cachePath` or a `storagePath` — which
|
||||
// the ladder below still answers with. The OS rung itself is tested
|
||||
// where it is written, against `index_cache::cache_dir` directly.
|
||||
#[cfg(test)]
|
||||
if self.client.index_cache_path.is_none() && self.storage.is_none() {
|
||||
return None;
|
||||
}
|
||||
crate::index_cache::cache_dir(
|
||||
&self.client,
|
||||
self.storage.as_deref(),
|
||||
&self.roots,
|
||||
self.filelist_path().as_deref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Adopt `initializationOptions.storagePath` — the folder the editor set
|
||||
/// aside for this workspace's server state.
|
||||
///
|
||||
/// Called once, before the first index build, because it is one rung of
|
||||
/// the ladder that decides where the cache is read from. A client that
|
||||
/// sends nothing leaves the OS cache directory to decide.
|
||||
pub fn set_storage_path(&mut self, storage: Option<PathBuf>) {
|
||||
self.storage = storage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! The file sets handed to the refactorings: the whole scope, or — for a
|
||||
//! port edit, a rename, a file rename — the fan-out the index already
|
||||
//! bounds, so a request reads a handful of files instead of the workspace.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_semantic::{Def, FileId};
|
||||
|
||||
use super::scan::{HeldAnalyses, Sources};
|
||||
use super::Workspace;
|
||||
use crate::module_select::{self, Reach};
|
||||
use crate::rename_trace::{self, Rung, SelectionTrace, Wanted};
|
||||
use crate::scan_trace::ScanTrace;
|
||||
|
||||
impl Workspace {
|
||||
/// The in-scope files and their current text — what a refactoring reads.
|
||||
///
|
||||
/// The same list `rebuild_index` feeds the index, recomputed rather than
|
||||
/// kept: a refactoring is a rare, user-initiated request, and a second
|
||||
/// copy of the workspace in memory is a high price for saving one walk.
|
||||
///
|
||||
/// This is the one caller that really does want every file's text at once,
|
||||
/// so it is where the read a scan no longer does in one pass still
|
||||
/// happens. A file that cannot be read contributes nothing, exactly as it
|
||||
/// did when `collect_sources` read them all.
|
||||
pub fn sources(&self) -> Vec<(PathBuf, String)> {
|
||||
let Sources { files, mut buffered, .. } =
|
||||
self.collect_sources(&mut |_| {}, HeldAnalyses::Unused, &mut ScanTrace::new(false));
|
||||
files
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = match buffered.remove(&path) {
|
||||
Some(text) => text,
|
||||
None => fs::read_to_string(&path).ok()?,
|
||||
};
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The in-scope files a port refactoring on `modules`, requested in `file`,
|
||||
/// can read or write — [`Workspace::sources`] narrowed to the fan-out the
|
||||
/// index already holds.
|
||||
///
|
||||
/// A `textDocument/codeAction` arrives on every cursor move and
|
||||
/// `sources()` reads the whole file set from disk, so a cursor resting on
|
||||
/// an instantiation used to cost one workspace read per keystroke (3.1 s
|
||||
/// on OpenTitan, and every queued request waited behind it). The index
|
||||
/// knows who declares a module and who instantiates it, so the engine can
|
||||
/// be handed those files and nothing else. Why the smaller set gives the
|
||||
/// same answer is argued in `docs/features/refactor-ports/README.md`; the
|
||||
/// four rungs are:
|
||||
///
|
||||
/// * **the file the request names**, whatever else it is;
|
||||
/// * **every file declaring one of `modules`** ([`WorkspaceIndex::units`])
|
||||
/// — all of them, so a name declared twice still refuses instead of
|
||||
/// quietly picking the one definer that made it into the set;
|
||||
/// * **every file that instantiates one** ([`WorkspaceIndex::instantiations_of`])
|
||||
/// or otherwise refers to one ([`WorkspaceIndex::references_to`]) —
|
||||
/// between them, every file the plan can edit and every file whose
|
||||
/// meaning the verifier could see move;
|
||||
/// * **every open buffer**, because its unsaved text may add or remove an
|
||||
/// instantiation the saved edges do not know about.
|
||||
///
|
||||
/// Each file's text comes from the same place `collect_sources` takes it:
|
||||
/// the open buffer when there is one, disk otherwise, and neither for a
|
||||
/// buffer on the large-file fast path or a file over the size cap.
|
||||
pub fn module_sources(&self, file: &Path, modules: &[String]) -> Vec<(PathBuf, String)> {
|
||||
self.module_sources_reaching(file, modules, Reach::none())
|
||||
}
|
||||
|
||||
/// [`Workspace::module_sources`] plus the **fifth rung**: every file whose
|
||||
/// tokens write one of `reach`'s scope names down
|
||||
/// ([`crate::module_select`], topology handshake 33).
|
||||
///
|
||||
/// Only inline-module asks for it, and only because its `no_hierarchy`
|
||||
/// refusal is about a path *through* the instance it dissolves rather
|
||||
/// than about either module's name: a testbench two wrapper levels above
|
||||
/// is in none of the four rungs. The rung can only add files, so every
|
||||
/// other caller's answer is untouched — and so is its cost, since
|
||||
/// [`Reach::none`] walks nothing.
|
||||
pub fn module_sources_reaching(
|
||||
&self,
|
||||
file: &Path,
|
||||
modules: &[String],
|
||||
reach: Reach<'_>,
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = module_select::hierarchical_users(&self.index, reach);
|
||||
wanted.insert(file.to_path_buf());
|
||||
for name in modules {
|
||||
for def in self.index.units(name) {
|
||||
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
|
||||
for site in self.index.references_to(def) {
|
||||
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
for edge in self.index.instantiations_of(name) {
|
||||
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The in-scope files a rename of `name` — to `new_name`, when the request
|
||||
/// carries one — can read, write or refuse over: [`Workspace::sources`]
|
||||
/// narrowed to what the index already knows about those two spellings.
|
||||
///
|
||||
/// A `textDocument/rename` cost 3.6–8.7 s on OpenTitan and a
|
||||
/// `prepareRename` 2.5–3.0 s, almost all of it re-reading, re-parsing and
|
||||
/// re-indexing 3 976 files to find the handful that spell one name. The
|
||||
/// index holds every declaration of a name and every use it resolved, so
|
||||
/// the engine can be handed those files and nothing else. **Why the
|
||||
/// smaller set gives the same answer is argued in full in
|
||||
/// `docs/features/refactor-rename/README.md`**; the rungs are:
|
||||
///
|
||||
/// * **the file the request names**, whatever else it is;
|
||||
/// * **every open buffer**, whose unsaved text the index has not seen —
|
||||
/// the one place this set deliberately does not trust the index;
|
||||
/// * per spelling `N` in `{name, new_name}`:
|
||||
/// * **every file declaring `N`** — as a unit or as a member of one
|
||||
/// ([`WorkspaceIndex::workspace_symbols`], filtered to the exact
|
||||
/// name). This is the rung the whole equality argument turns on:
|
||||
/// `follow_paths` only ever looks a reference's *own* name up, so a
|
||||
/// set holding every declarer of `N` resolves every reference spelling
|
||||
/// `N` exactly as the whole workspace does;
|
||||
/// * **every file declaring `N` on a module's hierarchical surface**
|
||||
/// ([`WorkspaceIndex::hierarchical_declarations`]) — an internal net
|
||||
/// is not a workspace symbol, and a hierarchical tail in another file
|
||||
/// resolves to one;
|
||||
/// * **every file with a use the index resolved to one of them**
|
||||
/// ([`WorkspaceIndex::references_to`]) — every file a rename can edit,
|
||||
/// and every file whose meaning the verifier could see move;
|
||||
/// * **every file instantiating `N`**
|
||||
/// ([`WorkspaceIndex::instantiations_of`]), which records a site whose
|
||||
/// reference resolved to nothing and therefore has no posting;
|
||||
/// * **every file whose `` `define`` table names `N` or spells it in a
|
||||
/// macro body**, walked over the tables the index already holds, for
|
||||
/// the two `` `define`` warnings;
|
||||
/// * **the units that export `N` as a member**, and every file
|
||||
/// declaring, referring to or instantiating one of those — how a third
|
||||
/// file's `.N(...)` connection or `u::N` is reached.
|
||||
/// * and, for the **new** name only, **every file that spells it in a use
|
||||
/// this workspace had to look outside that file to answer, including
|
||||
/// the uses it could not answer at all**
|
||||
/// ([`WorkspaceIndex::files_spelling`]).
|
||||
///
|
||||
/// **Why that last rung is the new name's alone.** It exists because a
|
||||
/// rename can give a name that meant *nothing* a meaning: `import
|
||||
/// taken_pkg::*` in a file with no other tie to the rename resolves to
|
||||
/// nothing today and to the renamed package tomorrow, which the
|
||||
/// whole-workspace verifier refuses over and the first five rungs cannot
|
||||
/// see. The old name has no such case, because a rename only ever
|
||||
/// **removes** declarations of it: a use of the old name that resolves is
|
||||
/// in that declaration's postings (rung 2, which walks *every* declaration
|
||||
/// of the name, not only the target's), and one that resolves to nothing
|
||||
/// still resolves to nothing afterwards — a lookup cannot start
|
||||
/// succeeding because a candidate was taken away. So the old name's uses
|
||||
/// are either already in the set or provably unmoved, and scanning for
|
||||
/// them would buy nothing.
|
||||
///
|
||||
/// One escape hatch, and it is the honest one: when the index says a
|
||||
/// declaration of `N` is named by an **ambiguous** use
|
||||
/// ([`WorkspaceIndex::references_are_ambiguous`]), the file holding that
|
||||
/// use is in no posting table, and the whole-workspace rename refuses
|
||||
/// because of it. Rather than lose that refusal, this hands back
|
||||
/// `sources()` and the slow path answers.
|
||||
/// It also says **which rung asked for each file**: [`Wanted`] is a path
|
||||
/// set that records the first rung to insert a path, so watching the
|
||||
/// selection cannot change it (take 5 §P2a).
|
||||
pub fn rename_sources_traced(
|
||||
&self,
|
||||
file: &Path,
|
||||
name: &str,
|
||||
new_name: Option<&str>,
|
||||
) -> (Vec<(PathBuf, String)>, SelectionTrace) {
|
||||
let started = Instant::now();
|
||||
let elapsed = |at: Instant| at.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut wanted = Wanted::new();
|
||||
wanted.insert(file.to_path_buf());
|
||||
for spelling in [Some(name), new_name].into_iter().flatten() {
|
||||
if !self.fan_out_of(spelling, &mut wanted) {
|
||||
let sources = self.sources();
|
||||
let trace = SelectionTrace::whole_scope(sources.len(), elapsed(started));
|
||||
return (sources, trace);
|
||||
}
|
||||
}
|
||||
// The sixth rung, and the **new** name's alone. See the doc comment
|
||||
// above for why the old name does not need it.
|
||||
if let Some(new_name) = new_name {
|
||||
wanted.on(Rung::Speller);
|
||||
self.want_spellers(new_name, &mut wanted);
|
||||
}
|
||||
wanted.on(Rung::OpenBuffer);
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
let (mut paths, mut trace) = wanted.finish();
|
||||
// One hop down: the modules those files instantiate, so a `.*` into
|
||||
// one is read rather than refused (M3.5). In `selected`, under no rung.
|
||||
let handed: Vec<&Path> = paths.keys().map(PathBuf::as_path).collect();
|
||||
for below in module_select::instantiated_by(&self.index, &handed) {
|
||||
paths.entry(below).or_insert(Rung::Instantiation);
|
||||
}
|
||||
// §P2d's census: which rungs asked for files that write neither name
|
||||
// down, and therefore contribute to this request only by shaping how
|
||||
// the others resolve. One record lookup per selected file, no read.
|
||||
trace.indirect =
|
||||
rename_trace::indirect_census(&self.index, &paths, [name, new_name.unwrap_or(name)]);
|
||||
let texts: Vec<(PathBuf, String)> = paths
|
||||
.into_keys()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect();
|
||||
// A file a rung wanted whose text this workspace no longer contributes
|
||||
// (deleted, oversize, a fast-path buffer) is counted by its rung and
|
||||
// is not in the input: the rungs total the *wanted* set, `selected`
|
||||
// the one the engine gets.
|
||||
trace.selected = texts.len();
|
||||
trace.ms = elapsed(started);
|
||||
(texts, trace)
|
||||
}
|
||||
|
||||
/// Add one spelling's fan-out to `wanted`. `false` means the index cannot
|
||||
/// bound it — see [`Workspace::rename_sources_traced`]'s escape hatch.
|
||||
fn fan_out_of(&self, name: &str, wanted: &mut Wanted) -> bool {
|
||||
// Every declaration of the name, wherever it is written. `units` alone
|
||||
// would miss a port, a parameter or a package member, and those are
|
||||
// exactly the declarations a `.port` connection or a `pkg::x` reaches
|
||||
// across files for.
|
||||
let mut containers: BTreeSet<&str> = BTreeSet::new();
|
||||
for symbol in self.index.workspace_symbols(name) {
|
||||
if symbol.name != name {
|
||||
continue;
|
||||
}
|
||||
if self.index.references_are_ambiguous(symbol.def) {
|
||||
return false;
|
||||
}
|
||||
containers.extend(symbol.container);
|
||||
self.want_declaration(symbol.def, wanted);
|
||||
}
|
||||
// And every declaration of it on a module's **hierarchical** surface,
|
||||
// which `workspace_symbols` deliberately does not list: an internal
|
||||
// net is not a workspace symbol, but `assign w = u_x.sig;` in another
|
||||
// file resolves to one and a rename must edit both ends. Without this
|
||||
// rung the fan-out would hold the file that *names* the net and not
|
||||
// the file that declares it (`docs/features/hierarchical-tail`).
|
||||
for (unit, def) in self.index.hierarchical_declarations(name) {
|
||||
if self.index.references_are_ambiguous(def) {
|
||||
return false;
|
||||
}
|
||||
containers.insert(unit);
|
||||
self.want_declaration(def, wanted);
|
||||
}
|
||||
self.want_sites(name, wanted);
|
||||
self.want_macro_text(name, wanted);
|
||||
for unit in containers {
|
||||
for def in self.index.units(unit) {
|
||||
self.want_declaration(def, wanted);
|
||||
}
|
||||
self.want_sites(unit, wanted);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// One declaration's own file, and every file the index recorded a use of
|
||||
/// it in.
|
||||
fn want_declaration(&self, def: &Def, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::Declaration);
|
||||
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
|
||||
wanted.on(Rung::Reference);
|
||||
for site in self.index.references_to(def) {
|
||||
wanted.extend(self.index.path(site.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file that instantiates a name — the census the reference postings
|
||||
/// cannot speak for, because an instantiation of something the workspace
|
||||
/// does not declare resolves to nothing and is posted nowhere.
|
||||
fn want_sites(&self, name: &str, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::Instantiation);
|
||||
for edge in self.index.instantiations_of(name) {
|
||||
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file that spells a name in a use the index had to look outside
|
||||
/// that file to answer, **including the uses it could not answer at all**
|
||||
/// ([`WorkspaceIndex::files_spelling`]).
|
||||
///
|
||||
/// The rung that closes the rename's one lost refusal (QA, 2026-08-28).
|
||||
/// A file whose only tie to the new name is `import new_name::*` of a
|
||||
/// package nothing declares yet holds no declaration, no posting, no
|
||||
/// instantiation edge and no macro entry — and the rename is exactly what
|
||||
/// gives that import a meaning, which the whole-workspace verifier refuses
|
||||
/// over. Only the postings' *keys* miss it; the per-file records keep every
|
||||
/// external use by the name it spells, so this reads it back.
|
||||
fn want_spellers(&self, name: &str, wanted: &mut Wanted) {
|
||||
for file in self.index.files_spelling(name) {
|
||||
wanted.extend(self.index.path(file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
|
||||
/// Every file whose `` `define`` table names the name or spells it in a
|
||||
/// macro **body** — the two warnings `Scope::define_sites` produces.
|
||||
///
|
||||
/// The index holds every file's `DefineTable` already, so this is a walk
|
||||
/// over tables in memory: no file is read and nothing is parsed. The
|
||||
/// question is asked with `vlog_refactor::contains_word`, which is the
|
||||
/// function `define_sites` itself decides with, so the fan-out and the
|
||||
/// warning cannot disagree about which files carry one.
|
||||
fn want_macro_text(&self, name: &str, wanted: &mut Wanted) {
|
||||
wanted.on(Rung::MacroText);
|
||||
for id in 0..self.index.files().len() {
|
||||
let file = FileId(id as u32);
|
||||
let Some(defines) = self.index.defines(file) else { continue };
|
||||
let touched = defines.entries().iter().any(|define| {
|
||||
define.name == name || vlog_refactor::contains_word(&define.body, name)
|
||||
});
|
||||
if touched {
|
||||
wanted.extend(self.index.path(file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The in-scope files a `workspace/willRenameFiles` can rewrite: the ones
|
||||
/// the include graph recorded a resolving `` `include`` in, plus every open
|
||||
/// buffer.
|
||||
///
|
||||
/// `will_rename` reads a file only to scan its `` `include``s and asks the
|
||||
/// graph where each one lands; a file whose includes all resolve to nothing
|
||||
/// — or that has none — contributes neither an edit nor a warning, and the
|
||||
/// graph's edge table is exactly the set of files that have at least one
|
||||
/// resolving include. So reading the rest was reading the whole workspace
|
||||
/// to answer "nothing" 3 900 times. Open buffers are added whatever the
|
||||
/// graph holds: the graph is rebuilt on save, so an `` `include`` typed and
|
||||
/// not yet saved is in the buffer and not in the edges.
|
||||
pub fn include_sources(&self) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = self.includes.includers().cloned().collect();
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
let text = self.current_text(&path)?;
|
||||
Some((path, text))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
//! A `Document`'s own analysis: the two token searches against the sweep
|
||||
//! they replaced, what a buffer holds once analyzed, and — TODO §63.2 QA —
|
||||
//! the trace's arithmetic, attacked with the three shapes TODO.md names: a
|
||||
//! buffer that fails to lex, a `define` edit that changes the macro table,
|
||||
//! and (via the server-level parity re-run) an edit that moves a fence.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The precondition both binary searches rest on. If the lexer ever emits
|
||||
/// a token out of order, or two tokens that overlap, `partition_point`'s
|
||||
/// predicates stop being monotone and every handler that calls
|
||||
/// [`first_token_reaching`] or [`first_token_from`] starts answering
|
||||
/// something else. This is the test that would fail first.
|
||||
#[test]
|
||||
fn the_token_stream_rises_and_never_overlaps() {
|
||||
let text = mixed_buffer(20);
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
assert!(doc.tokens.len() > 500, "premise: a stream worth searching");
|
||||
for pair in doc.tokens.windows(2) {
|
||||
assert!(pair[0].span.start <= pair[1].span.start, "{pair:?}");
|
||||
assert!(pair[0].span.end <= pair[1].span.start, "overlapping tokens: {pair:?}");
|
||||
assert!(pair[0].span.start <= pair[0].span.end, "an inverted span: {pair:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Both searches, against the sweep they stand in for, at every byte of a
|
||||
/// buffer full of tokens that touch.
|
||||
#[test]
|
||||
fn every_offset_finds_the_token_a_sweep_would_have_found() {
|
||||
let text = mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &WorkspaceIndex::default());
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = doc.tokens.iter().position(|t| t.span.end >= offset);
|
||||
assert_eq!(
|
||||
first_token_reaching(&doc.tokens, offset),
|
||||
swept.unwrap_or(doc.tokens.len()),
|
||||
"first token reaching {offset}"
|
||||
);
|
||||
let swept = doc.tokens.iter().position(|t| t.span.start >= offset);
|
||||
assert_eq!(
|
||||
first_token_from(&doc.tokens, offset),
|
||||
swept.unwrap_or(doc.tokens.len()),
|
||||
"first token from {offset}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_analyzes_a_clean_file() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(doc.diagnostics.is_empty());
|
||||
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
|
||||
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
|
||||
assert!(!doc.tokens.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_file_still_analyzes() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
|
||||
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
|
||||
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
|
||||
assert!(doc.tokens.is_empty());
|
||||
assert_eq!(doc.diagnostics.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_untitled_buffer_has_no_path() {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
|
||||
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
|
||||
assert_eq!(doc.path, None);
|
||||
}
|
||||
|
||||
/// A buffer that never lexes still reports a `Lex` stage (the failed
|
||||
/// attempt is real work and costs real time) and a `Parse` stage (the
|
||||
/// `parse_source_tolerant` fallback), and still counts as one document.
|
||||
/// `defines`/`analyze`/`external`/`lines` all still run over the empty
|
||||
/// token stream and empty-error tree exactly as the un-instrumented
|
||||
/// path always did — the wrapping must not skip a stage just because
|
||||
/// an earlier one errored.
|
||||
#[test]
|
||||
fn a_buffer_that_fails_to_lex_still_records_every_rebuild_stage() {
|
||||
crate::lint_trace::arm();
|
||||
// An unterminated string literal is an unambiguous lex error that
|
||||
// does not depend on lexer internals that could drift between
|
||||
// versions (`vlog_parser::tokenize` is documented all-or-nothing).
|
||||
let text = "module m;\n string s = \"unterminated\nendmodule\n".to_string();
|
||||
let doc = Document::new(None, text, &WorkspaceIndex::default());
|
||||
assert!(doc.tokens.is_empty(), "a lex failure leaves an empty token stream");
|
||||
assert!(!doc.diagnostics.is_empty(), "a lex failure is a diagnostic");
|
||||
let trace = crate::lint_trace::disarm().expect("armed");
|
||||
// Every stage's field is present on the line, whether or not it
|
||||
// took measurable time (`saw_document`, not a duration, is what
|
||||
// says a rebuild happened at all — see the flaky test this round
|
||||
// fixed in `lint_trace.rs`).
|
||||
let line = trace.line();
|
||||
assert!(line.contains("documents=1"), "{line}");
|
||||
for stage in ["lex=", "parse=", "defines=", "analyze=", "external=", "lines=", "publish="] {
|
||||
assert!(line.contains(stage), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A `` `define `` edit changes the macro table `collect_defines`
|
||||
/// produces, and nothing about wrapping that call in `rebuild` changes
|
||||
/// which tokens it sees or what it returns: the new revision's table
|
||||
/// reflects only the new text, never a stale value from the revision
|
||||
/// before it (`Document::new` builds a fresh `DefineTable` every time,
|
||||
/// same as before this round).
|
||||
#[test]
|
||||
fn a_define_edit_changes_the_macro_table_the_rebuild_reports_on() {
|
||||
crate::lint_trace::arm();
|
||||
let before = Document::new(
|
||||
None,
|
||||
"`define WIDTH 8\nmodule m;\n wire [`WIDTH-1:0] w;\nendmodule\n".to_string(),
|
||||
&WorkspaceIndex::default(),
|
||||
);
|
||||
assert_eq!(before.defines.latest("WIDTH").map(|d| d.body.trim()), Some("8"));
|
||||
assert!(before.defines.latest("DEPTH").is_none());
|
||||
|
||||
let after = Document::new(
|
||||
None,
|
||||
"`define DEPTH 16\nmodule m;\n wire [`DEPTH-1:0] w;\nendmodule\n".to_string(),
|
||||
&WorkspaceIndex::default(),
|
||||
);
|
||||
assert!(after.defines.latest("WIDTH").is_none(), "no macro survives across documents");
|
||||
assert_eq!(after.defines.latest("DEPTH").map(|d| d.body.trim()), Some("16"));
|
||||
|
||||
let trace = crate::lint_trace::disarm().expect("armed");
|
||||
let line = trace.line();
|
||||
assert!(line.contains("documents=2"), "two fresh Document::new calls, two rebuilds: {line}");
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
//! Rung 1 of the scope ladder: a filelist defines the index exactly, its
|
||||
//! warnings reach the caller, and its `+incdir+`s reach the include graph.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A tree with three packages, one of which a filelist deliberately omits.
|
||||
fn filelist_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
tree.package("rtl/unlisted.sv", "unlisted");
|
||||
tree.write("files.f", "// the project\nrtl/a.sv\nrtl/b.sv\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_filelist_defines_the_index_exactly() {
|
||||
// The point of a filelist: a file sitting in the tree that the project
|
||||
// does not build is not indexed, however much the walk would find it.
|
||||
let tree = filelist_tree("filelistkey");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
let warnings = ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
|
||||
let tree = filelist_tree("filelistsetting");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
tree.write("other.f", "rtl/unlisted.sv\n");
|
||||
|
||||
// Relative: against the workspace root, not the current directory.
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("other.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"], "the setting wins");
|
||||
|
||||
// Absolute: taken as written.
|
||||
let absolute = tree.path.join("other.f");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist(&absolute.display().to_string()));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
|
||||
// The failure that must never happen: an empty index and no
|
||||
// explanation because a path in a settings UI has a typo.
|
||||
let tree = filelist_tree("filelistgone");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("typo.f"));
|
||||
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"], "the walk ran");
|
||||
assert_eq!(warnings.len(), 1);
|
||||
assert!(warnings[0].contains("typo.f"), "{warnings:?}");
|
||||
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn an_unreadable_directory_is_said_once_per_scan_and_the_rest_is_indexed() {
|
||||
// TODO §45.2: the walk's warnings ride out on the scope's own
|
||||
// warnings, which the server logs once per scan. Before the channel
|
||||
// existed the walk returned an error the index simply dropped, so a
|
||||
// permission-denied directory cost every file after it silently.
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tree = Tree::new("walkwarn");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/z.sv", "z");
|
||||
tree.package("locked/hidden.sv", "hidden");
|
||||
std::os::unix::fs::symlink("nowhere.sv", tree.path.join("rtl/gone.sv")).expect("symlink");
|
||||
let locked = tree.path.join("locked");
|
||||
fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).expect("chmod");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
let warnings = ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let _ = fs::set_permissions(&locked, fs::Permissions::from_mode(0o755));
|
||||
|
||||
assert_eq!(indexed(&ws, &["a", "z", "hidden"]), ["a", "z"], "the scan finished");
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("locked")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("gone.sv: broken symbolic link")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelists_own_warnings_reach_the_caller() {
|
||||
let tree = filelist_tree("filelistwarn");
|
||||
tree.write("files.f", "rtl/a.sv\nrtl/moved.sv\n-nonsense\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
let warnings = ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a"], "the rest is still indexed");
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("moved.sv")), "{warnings:?}");
|
||||
assert!(warnings.iter().any(|w| w.contains("-nonsense")), "{warnings:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_is_indexed_even_when_the_filelist_omits_it() {
|
||||
// Open buffers overlay every rung of the ladder: a scratch file the
|
||||
// project does not build still gets its own symbols.
|
||||
let tree = filelist_tree("filelistbuffer");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
|
||||
let path = tree.path.join("rtl/unlisted.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package unlisted;\n localparam K = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_no_workspace_root_the_open_files_own_directory_is_indexed() {
|
||||
// The single-file case: no folder was opened, so the scope is what
|
||||
// sits beside the buffer — and nothing below it.
|
||||
let tree = Tree::new("noroot");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/sibling.sv", "sibling");
|
||||
tree.package("rtl/deeper/below.sv", "below");
|
||||
tree.package("elsewhere/far.sv", "far");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
assert!(!ws.has_roots(), "the premise: no workspace folder");
|
||||
let path = tree.path.join("rtl/open.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
|
||||
assert_eq!(
|
||||
indexed(&ws, &["open_pkg", "sibling", "below", "far"]),
|
||||
["open_pkg", "sibling"],
|
||||
"the buffer and its neighbours only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_still_wins_when_there_is_no_workspace_root() {
|
||||
let tree = filelist_tree("norootfilelist");
|
||||
let mut ws = Workspace::default();
|
||||
// With no root a relative setting cannot be anchored, so an absolute
|
||||
// path is the only sensible way to name one — and it works.
|
||||
ws.set_client_settings(using_filelist(&tree.path.join("files.f").display().to_string()));
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
|
||||
}
|
||||
|
||||
/// Where `ws` would look for `` `include "<name>" `` written in `from`.
|
||||
fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option<PathBuf> {
|
||||
let text = format!("`include \"{name}\"\n");
|
||||
let include = crate::includes::scan(&text).into_iter().next().expect("one include");
|
||||
ws.includes().resolve(Some(from), &include)
|
||||
}
|
||||
|
||||
/// A tree whose filelist names one `+incdir+` and nests a filelist naming
|
||||
/// another, with a header in each — plus one only the nested incdir holds.
|
||||
fn incdir_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("first/defs.svh", "`define W 1\n");
|
||||
tree.write("ip/include/defs.svh", "`define W 2\n");
|
||||
tree.write("ip/include/ip_only.svh", "`define X 1\n");
|
||||
tree.write("ip/ip.f", "+incdir+include\n");
|
||||
tree.write("files.f", "+incdir+first\n-f ip/ip.f\nrtl/a.sv\n");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelists_incdirs_reach_the_include_graph_in_filelist_order() {
|
||||
// M1 recorded `+incdir+` and used it for nothing; this is the wire
|
||||
// that spends it. A nested `-f`'s incdirs come through flattened,
|
||||
// *after* the ones named before the `-f` — which is the order an
|
||||
// include is searched in, so it is worth pinning here and not only in
|
||||
// the parser.
|
||||
let tree = incdir_tree("incdirs");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
let warnings = ws.open_roots(vec![tree.path.clone()]);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
|
||||
let from = tree.path.join("rtl/a.sv");
|
||||
assert_eq!(
|
||||
resolved_include(&ws, &from, "defs.svh"),
|
||||
Some(tree.path.join("first/defs.svh")),
|
||||
"the root filelist's incdir is searched before the nested one's"
|
||||
);
|
||||
assert_eq!(
|
||||
resolved_include(&ws, &from, "ip_only.svh"),
|
||||
Some(tree.path.join("ip/include/ip_only.svh")),
|
||||
"and the nested one is searched at all"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_filelist_there_are_no_incdirs_at_all() {
|
||||
// Rungs 2 and 3 of the ladder name no include path, so an `` `include``
|
||||
// there has only the including file's own directory to go on.
|
||||
let tree = incdir_tree("noincdirs");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_filelist_leaves_the_include_graph_without_incdirs() {
|
||||
let tree = incdir_tree("badfilelistincdirs");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("typo.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"),
|
||||
None,
|
||||
"the walk fallback names no include path"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
//! The folder scope (index-scope, 2026-08-27): rung 3's climb and the two
|
||||
//! clamps on it, what outranks it, and the inherited obligations from that
|
||||
//! round's review.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A project laid out the way the owner described it: the file being
|
||||
/// worked on in `rtl/`, a header folder beside it, and a third folder that
|
||||
/// has nothing to do with either.
|
||||
fn two_folder_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/beside.sv", "beside_pkg");
|
||||
tree.package("rtl/deeper/below.sv", "below_pkg");
|
||||
tree.package("include/defs.sv", "defs_pkg");
|
||||
tree.package("elsewhere/far.sv", "far_pkg");
|
||||
tree
|
||||
}
|
||||
|
||||
/// The four fixture packages, as the ones that are in the index.
|
||||
fn scoped(ws: &Workspace) -> Vec<String> {
|
||||
indexed(ws, &["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_folder_scope_at_depth_zero_is_the_open_files_own_folder_and_everything_under_it() {
|
||||
// The headline of the index-scope round: a workspace root is open, but
|
||||
// the index covers the folder the user is working in, not the project.
|
||||
// At depth 0 — the shipped default until 2026-08-28, and still exactly
|
||||
// what an explicit `scopeDepth: 0` asks for.
|
||||
let tree = two_folder_tree("scopedefault");
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert!(scoped(&ws).is_empty(), "premise: nothing is open, so nothing is in scope");
|
||||
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg"],
|
||||
"the buffer's own folder and its subtree — and no sibling folder"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_depth_of_one_reaches_the_folder_beside_it() {
|
||||
// `rtl/` plus `../include`: the layout the setting exists for.
|
||||
let tree = two_folder_tree("scopedepth");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
|
||||
"one level up is the whole tree here, sibling folders included"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_climb_stops_at_the_workspace_root() {
|
||||
// The clamp that keeps a depth of 99 in a two-deep project from
|
||||
// indexing the user's home directory. Asserted on the directories
|
||||
// themselves rather than on an index, because the failure this guards
|
||||
// against is a walk that should never be started.
|
||||
let tree = two_folder_tree("scopeclamp");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/deeper/below.sv");
|
||||
assert_eq!(ws.scope_dirs(), vec![tree.path.clone()], "clamped at the root, not above it");
|
||||
|
||||
// The deepest containing root wins, so a nested root clamps tighter.
|
||||
assert!(ws.change_roots(vec![tree.path.join("rtl")], &[]));
|
||||
assert_eq!(ws.scope_dirs(), vec![tree.path.join("rtl")], "the deepest root is the floor");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_session_does_not_climb_at_all() {
|
||||
// Changed 2026-08-28, with the shipped depth. The climb used to run
|
||||
// with `/` as its only floor, which was survivable while the shipped
|
||||
// depth was 0 and nobody climbed by accident. It is not survivable at
|
||||
// depth 2: a lone file opened from `~/work/chip/hw/ip/aes/rtl/` would
|
||||
// raise into `~/work/chip/hw/ip/` and walk a tree the user never
|
||||
// named. The clamp is what makes a raise safe, so with nothing to
|
||||
// clamp against there is no raise, whatever the depth says.
|
||||
let tree = two_folder_tree("scoperootless");
|
||||
for depth in [0, 1, 99] {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
assert!(!ws.has_roots(), "the premise: no workspace folder to clamp against");
|
||||
assert_eq!(
|
||||
ws.scope_dirs(),
|
||||
vec![tree.path.join("rtl")],
|
||||
"depth {depth}: the buffer's own directory, and nothing above it"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_session_reads_its_own_directory_flat_until_the_depth_is_raised() {
|
||||
// The `folder_files` exception, from the other side. The *directory*
|
||||
// is the buffer's own whatever the depth (no root, no climb — see
|
||||
// above), but the depth still chooses how it is read: 0 reads it flat,
|
||||
// one level, no `.gitignore`, and a raise means the user has asked for
|
||||
// a tree, so the tree below the buffer is walked.
|
||||
let tree = two_folder_tree("scoperootlesswalk");
|
||||
for (depth, expected) in
|
||||
[(0, vec!["open_pkg", "beside_pkg"]), (1, vec!["open_pkg", "beside_pkg", "below_pkg"])]
|
||||
{
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: depth, ..Default::default() });
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), expected, "depth {depth}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_scope_setting_restores_the_walk_of_every_root() {
|
||||
// The migration line in the README, pinned: with `scope: "workspace"`
|
||||
// the index is the whole tree with no buffer open at all — which is
|
||||
// exactly what this fixture gave before this round.
|
||||
let tree = two_folder_tree("scopewide");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
index_scope: IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg", "far_pkg"],
|
||||
"every file under the root, no buffer needed"
|
||||
);
|
||||
// And the depth is not consulted at all on that rung.
|
||||
let mut raised = Workspace::default();
|
||||
raised.set_client_settings(ClientSettings {
|
||||
index_scope: IndexScope::Workspace,
|
||||
index_scope_depth: 3,
|
||||
..Default::default()
|
||||
});
|
||||
raised.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(raised.index().files(), ws.index().files(), "the depth changes nothing here");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_still_defines_the_scope_exactly_whatever_the_folder_rung_would_say() {
|
||||
// Rung 1 outranks rung 3 as it always outranked rung 2: the filelist
|
||||
// is the project file, and it names files in folders no buffer has
|
||||
// been opened from.
|
||||
let tree = two_folder_tree("scopefilelist");
|
||||
tree.write("files.f", "include/defs.sv\nelsewhere/far.sv\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "defs_pkg", "far_pkg"],
|
||||
"the filelist, plus the open buffer that overlays every rung"
|
||||
);
|
||||
assert!(ws.scope_dirs().is_empty(), "and no `didOpen` can widen a filelist");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_file_never_narrows_the_scope() {
|
||||
// The decision, pinned: the scope only grows within a session. A
|
||||
// rebuild after a close must not take away answers the user had a
|
||||
// moment ago, and no `didClose` costs a rescan.
|
||||
let tree = two_folder_tree("scopeclose");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
open(&mut ws, &tree, "include/defs.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"]);
|
||||
|
||||
let closed = crate::uri::path_to_uri(&tree.path.join("include/defs.sv")).expect("uri");
|
||||
ws.close_document(&closed);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "beside_pkg", "below_pkg", "defs_pkg"],
|
||||
"the closed file's folder is still indexed"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_folder_scope_honours_every_exclude_and_the_gitignores_below_it() {
|
||||
// Rung 3 walks with the same function rung 2 walks with, so nothing a
|
||||
// user excluded comes back because the scope narrowed — with **one
|
||||
// honest exception**, pinned here rather than left to be discovered:
|
||||
// `lucisv_core`'s walk reads `.gitignore` files from its own starting
|
||||
// directory downwards, so a rule written at the workspace root does
|
||||
// not reach a walk that starts below it. The `exclude` patterns are
|
||||
// matched against whole paths and are unaffected either way. Stated in
|
||||
// `walked_files` and in `docs/features/index-scope/README.md`.
|
||||
let tree = Tree::new("scopefilters");
|
||||
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
|
||||
tree.write(".gitignore", "generated/\n");
|
||||
tree.write("rtl/.gitignore", "dumps/\n");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/vendor/ip.sv", "vendor_pkg");
|
||||
tree.package("rtl/dumps/net.sv", "dumps_pkg");
|
||||
tree.package("rtl/generated/net.sv", "generated_pkg");
|
||||
tree.package("rtl/scratch/wip.sv", "scratch_pkg");
|
||||
|
||||
let names = &["open_pkg", "vendor_pkg", "dumps_pkg", "generated_pkg", "scratch_pkg"];
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(excluding(&["scratch"]));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, names),
|
||||
["open_pkg", "generated_pkg"],
|
||||
"both excludes and the .gitignore inside the scope applied; the one at the \
|
||||
root, above where this walk starts, did not"
|
||||
);
|
||||
|
||||
// ...and the wide scope, whose walk starts at the root, does apply it.
|
||||
let mut wide = Workspace::default();
|
||||
wide.set_client_settings(ClientSettings {
|
||||
exclude: vec!["scratch".to_string()],
|
||||
index_scope: IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
wide.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&wide, names), ["open_pkg"], "everything filtered, from the root");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_added_mid_session_widens_nothing_until_a_file_in_it_is_opened() {
|
||||
// The interaction between the two ways a scope can move. Under the
|
||||
// folder rung a workspace folder is a *clamp*, not a work list, so
|
||||
// adding one changes which files exist only once a buffer in it makes
|
||||
// it a scope directory.
|
||||
let first = Tree::new("scopefolderfirst");
|
||||
first.package("a.sv", "a");
|
||||
let second = Tree::new("scopefoldersecond");
|
||||
second.package("b.sv", "b");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![first.path.clone()]);
|
||||
open(&mut ws, &first, "a.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: the first folder's file");
|
||||
|
||||
assert!(ws.change_roots(vec![second.path.clone()], &[]), "the root set moved");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "but no buffer lives there yet");
|
||||
|
||||
open(&mut ws, &second, "b.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "opening one widens the scope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scope_or_a_depth_change_asks_for_a_rescan() {
|
||||
// Both change which files exist, so both join `exclude`, `filelist`
|
||||
// and the size cap in the rescan test.
|
||||
let mut ws = Workspace::default();
|
||||
let wide = ClientSettings { index_scope: IndexScope::Workspace, ..Default::default() };
|
||||
assert!(ws.set_client_settings(wide.clone()), "a new scope rescans");
|
||||
assert!(!ws.set_client_settings(wide.clone()), "the same one does not");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
|
||||
|
||||
let deep = ClientSettings { index_scope_depth: 5, ..Default::default() };
|
||||
assert!(ws.set_client_settings(deep.clone()), "a new depth rescans");
|
||||
assert!(!ws.set_client_settings(deep), "the same one does not");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and going back does");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_open_files_are_indexed_first_and_the_index_cannot_tell() {
|
||||
// Two halves of one claim. First: the progress events name the open
|
||||
// buffers before anything else, which is what makes a big rescan feel
|
||||
// like it is working on the user's own files.
|
||||
let tree = Tree::new("scopeorder");
|
||||
tree.package("rtl/a_first.sv", "a_first");
|
||||
tree.package("rtl/m_open.sv", "m_open");
|
||||
tree.package("rtl/z_last.sv", "z_last");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/m_open.sv");
|
||||
// Every file of the work list, however it got into the index: since
|
||||
// 2026-08-28 the open buffer goes in from its own analysis and reports
|
||||
// `Analyzed` rather than `Parsing`, and the claim under test is about
|
||||
// the *order* the work list is walked in, not about who parses.
|
||||
let mut seen: Vec<PathBuf> = Vec::new();
|
||||
ws.rebuild_index_with(&mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. }
|
||||
| IndexEvent::Cached { path, .. }
|
||||
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
assert_eq!(
|
||||
seen,
|
||||
vec![
|
||||
tree.path.join("rtl/m_open.sv"),
|
||||
tree.path.join("rtl/a_first.sv"),
|
||||
tree.path.join("rtl/z_last.sv"),
|
||||
],
|
||||
"the open buffer first, then the rest in path order"
|
||||
);
|
||||
|
||||
// Second, and the reason the first is allowed to be true: the index
|
||||
// is byte-identical to the one the plain path order builds. The
|
||||
// builder sorts inside `finish`, so the order above is a reporting
|
||||
// decision and nothing more (`vlog_semantic`'s
|
||||
// `no_insertion_order_can_change_what_the_builder_produces` is the
|
||||
// other end of this).
|
||||
let mut plain = Workspace::default();
|
||||
plain.set_client_settings(ClientSettings {
|
||||
index_scope: IndexScope::Workspace,
|
||||
..Default::default()
|
||||
});
|
||||
plain.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().files(), plain.index().files(), "same files, same ids");
|
||||
assert_eq!(ws.index().counts(), plain.index().counts(), "and the same index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowering_the_scope_depth_narrows_the_index_on_the_next_rescan() {
|
||||
// The scope grows only along the *open* axis — a `didClose` never
|
||||
// narrows it. A settings change is the other axis and moves both ways,
|
||||
// because it is a deliberate statement about how much of this machine's
|
||||
// time to spend. Verified by hand by the previous round's QA; pinned
|
||||
// here.
|
||||
let tree = two_folder_tree("depthdown");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 1, ..Default::default() });
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert!(scoped(&ws).contains(&"defs_pkg".to_string()), "premise: depth 1 reaches beside");
|
||||
|
||||
assert!(
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() }),
|
||||
"lowering the depth asks for a rescan"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "narrowed, not kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_appearing_mid_session_flips_the_ladder_to_rung_one() {
|
||||
// Not just "asks for a rescan" — that the index really becomes the
|
||||
// filelist's files, from a folder scope that was covering something
|
||||
// else entirely.
|
||||
let tree = two_folder_tree("filelistmid");
|
||||
tree.write("files.f", "elsewhere/far.sv\n");
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "rtl/open.sv");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(scoped(&ws), ["open_pkg", "beside_pkg", "below_pkg"], "premise: the folder rung");
|
||||
|
||||
assert!(ws.set_client_settings(using_filelist("files.f")), "a rescan is owed");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
scoped(&ws),
|
||||
["open_pkg", "far_pkg"],
|
||||
"rung 1 defines the scope exactly — plus the open buffer, which overlays every rung"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_outside_every_root_rides_the_folder_rung_like_a_rootless_one() {
|
||||
// `raised()`'s floor is the deepest root *containing* the directory, and
|
||||
// there is none here — so the climb stops at `/`, exactly as it does
|
||||
// with no root at all. Verified by hand by the previous round's QA;
|
||||
// pinned here, on the directories rather than by walking one.
|
||||
let inside = Tree::new("outsideroot_in");
|
||||
inside.package("rtl/a.sv", "a_pkg");
|
||||
let outside = Tree::new("outsideroot_out");
|
||||
outside.package("other/b.sv", "b_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![inside.path.clone()]);
|
||||
open(&mut ws, &outside, "other/b.sv");
|
||||
assert_eq!(
|
||||
ws.scope_dirs(),
|
||||
vec![outside.path.join("other")],
|
||||
"at depth 0 it is the buffer's own directory and nothing else"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a_pkg", "b_pkg"]), ["b_pkg"], "the root's own tree is not in it");
|
||||
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 99, ..Default::default() });
|
||||
assert_eq!(
|
||||
ws.scope_dirs(),
|
||||
vec![PathBuf::from("/")],
|
||||
"and with nothing to clamp against the climb stops at the filesystem root"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! Workspace folders added and removed mid-session
|
||||
//! (`didChangeWorkspaceFolders`): what widens the scan, what narrows it,
|
||||
//! what changes nothing, and what is left when the last root goes.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_root_added_mid_session_widens_the_scan_and_a_removed_one_narrows_it() {
|
||||
let first = Tree::new("rootsfirst");
|
||||
first.package("a.sv", "a");
|
||||
let second = Tree::new("rootssecond");
|
||||
second.package("b.sv", "b");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![first.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a"], "premise: one folder");
|
||||
|
||||
assert!(ws.change_roots(vec![second.path.clone()], &[]), "a new folder moves the set");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"], "both folders are scanned");
|
||||
|
||||
assert!(ws.change_roots(Vec::new(), from_ref(&first.path)), "and so does dropping one");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["b"], "the dropped folder's files are gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subdirectory_of_an_existing_root_added_as_its_own_root_is_not_double_indexed() {
|
||||
// Overlap does not duplicate a file's registration: `walked_files`
|
||||
// walks each root independently and `dedup`s the combined, sorted
|
||||
// list by path, so a file both roots would reach lands in the index
|
||||
// once, not twice (a second identical registration would show up as
|
||||
// an *ambiguous* member — `indexed` below only counts a name found
|
||||
// exactly once).
|
||||
//
|
||||
// It is NOT exclude-proof, though, and that half is a genuine
|
||||
// consequence of "each root is governed by its own config"
|
||||
// (documented on `walked_files`): a directory the parent root's
|
||||
// `lucisv.toml` excludes is added *as a root in its own right* here,
|
||||
// and nothing excludes a root from itself. QA (2026-08-27): flagged
|
||||
// in the QA log as a finding, not a bug fix — this is consistent
|
||||
// with the per-root config model, but it was unreachable before this
|
||||
// round (roots used to be frozen at `initialize`), so it is worth a
|
||||
// pin and a name.
|
||||
let tree = Tree::new("subdirroot");
|
||||
tree.write("lucisv.toml", "exclude = [\"sub\"]\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("sub/hidden.sv", "hidden_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["kept", "hidden_pkg"]), ["kept"], "excluded, as configured");
|
||||
|
||||
assert!(ws.change_roots(vec![tree.path.join("sub")], &[]));
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, &["kept", "hidden_pkg"]),
|
||||
["kept", "hidden_pkg"],
|
||||
"reachable once through the added root, and only once — not ambiguous"
|
||||
);
|
||||
}
|
||||
|
||||
/// A workspace whose tree links back into itself. Before the walk kept a
|
||||
/// visited set (`docs/features/walk-cycles/README.md`) this scan never
|
||||
/// finished — the editor's index simply never came up. Each directory is
|
||||
/// entered once now, so each package is registered exactly once: a second
|
||||
/// registration would make the name *ambiguous*, and `indexed` only
|
||||
/// counts a name found exactly once.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_cyclic_workspace_is_scanned_once_and_finishes() {
|
||||
let tree = Tree::new("cycle");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/sub/b.sv", "b");
|
||||
// `rtl/self` is `rtl` itself; `rtl/sub/up` is `rtl` from one level
|
||||
// down. Either one alone runs until the OS refuses a path.
|
||||
std::os::unix::fs::symlink("../rtl", tree.path.join("rtl/self")).expect("symlink");
|
||||
std::os::unix::fs::symlink("..", tree.path.join("rtl/sub/up")).expect("symlink");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["a", "b"]), ["a", "b"]);
|
||||
assert_eq!(
|
||||
ws.walked_files(from_ref(&tree.path), &mut |_| {}, &mut ScanTrace::new(false)).len(),
|
||||
2,
|
||||
"two files, once each"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_change_that_changes_nothing_asks_for_no_rescan() {
|
||||
// Every no-op shape a client can send. Each must leave the root set
|
||||
// exactly as it was, and say so — a rescan here is pure cost.
|
||||
let tree = Tree::new("rootsnoop");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
|
||||
assert!(!ws.change_roots(Vec::new(), &[]), "an empty event");
|
||||
assert!(!ws.change_roots(vec![tree.path.clone()], &[]), "a folder already held");
|
||||
let never = tree.path.join("never-added");
|
||||
assert!(!ws.change_roots(Vec::new(), from_ref(&never)), "a folder never held");
|
||||
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&never)), "and both at once");
|
||||
assert!(ws.has_roots(), "the root survived every one of them");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_slash_in_the_removed_folder_still_matches_the_held_root() {
|
||||
// `uri_to_path` decodes a URI verbatim, trailing slash and all, and
|
||||
// `change_roots` compares by `PathBuf` equality — which compares
|
||||
// components, not raw strings, so `/a/b/` and `/a/b` are already the
|
||||
// same path as far as `retain`/`contains` are concerned. Pinned
|
||||
// because the doc README calls this out as a boundary worth
|
||||
// checking, not because the standard library needed help.
|
||||
let tree = Tree::new("trailingslash");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
|
||||
let mut with_slash = tree.path.clone().into_os_string();
|
||||
with_slash.push("/");
|
||||
assert!(
|
||||
ws.change_roots(Vec::new(), from_ref(&PathBuf::from(with_slash))),
|
||||
"the trailing slash must not hide the match"
|
||||
);
|
||||
assert!(!ws.has_roots());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_named_in_both_halves_of_one_event_stays() {
|
||||
// Removals run first, so "removed and added again" — which is how a
|
||||
// moved folder reaches some clients — is not a way to lose a root.
|
||||
let tree = Tree::new("rootsboth");
|
||||
tree.package("a.sv", "a");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(!ws.change_roots(vec![tree.path.clone()], from_ref(&tree.path)), "no net change");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["a"]), ["a"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_added_twice_across_two_events_is_absent_after_one_removal() {
|
||||
// The root set is a set, not a multiset: `change_roots` dedups on
|
||||
// push (`if !self.roots.contains(&root)`), so a second add of the
|
||||
// same path — even from a *later*, separate notification — never
|
||||
// grows a reference count for it. One removal is therefore always
|
||||
// enough, however many times a client (redundantly) added it.
|
||||
// QA (2026-08-27): pinned per the review checklist's multiset-vs-set
|
||||
// question.
|
||||
let tree = Tree::new("addedtwice");
|
||||
let extra = Tree::new("addedtwiceextra");
|
||||
extra.package("x.sv", "x");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
// Whole-workspace scope, so the indexed-content assertions below see
|
||||
// the roots at all — under the default folder scope nothing is
|
||||
// walked until a buffer opens, and the closing assertion was vacuous
|
||||
// (QA finding, 2026-08-27, lead-fixed).
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.change_roots(vec![extra.path.clone()], &[]), "the first add moves the set");
|
||||
assert!(
|
||||
!ws.change_roots(vec![extra.path.clone()], &[]),
|
||||
"a second, separate add of the same path is a no-op"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["x"]), vec!["x".to_string()], "present while added");
|
||||
assert!(
|
||||
ws.change_roots(Vec::new(), from_ref(&extra.path)),
|
||||
"one removal is enough to take it out"
|
||||
);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["x"]), Vec::<String>::new(), "gone, not merely decremented");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_root_falls_back_to_the_rootless_model() {
|
||||
// Rung 3 of the ladder is not a startup-only state: a session that
|
||||
// closes its last folder becomes the single-file case, and an open
|
||||
// buffer must still resolve against the files beside it.
|
||||
let tree = Tree::new("rootslast");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.package("rtl/sibling.sv", "sibling");
|
||||
tree.package("elsewhere/far.sv", "far");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["open_pkg", "sibling", "far"]), ["open_pkg", "sibling", "far"]);
|
||||
|
||||
let path = tree.path.join("rtl/open.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
|
||||
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
|
||||
assert!(!ws.has_roots(), "the workspace is rootless now");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, &["open_pkg", "sibling", "far"]),
|
||||
["open_pkg", "sibling"],
|
||||
"the buffer and its neighbours, as if the file had been opened on its own"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removing_the_last_root_leaves_a_relative_filelist_unanchored() {
|
||||
// `filelist_path` anchors a relative setting at `roots.first()`. With
|
||||
// no roots left there is nothing to anchor it to, and the path comes
|
||||
// back exactly as the client wrote it — not resolved against the
|
||||
// folder that is now gone, and not resolved against anything else
|
||||
// either. Nothing panics: `source_files` still falls back to the
|
||||
// rootless walk with a warning when that bare path cannot be read
|
||||
// (`a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so`
|
||||
// covers that fallback). QA (2026-08-27): pinned because this is new
|
||||
// reachable behaviour this round — losing the last root used to be
|
||||
// impossible.
|
||||
let tree = Tree::new("rootslastfilelist");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
tree.write("files.f", "rtl/open.sv\n");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(using_filelist("files.f"));
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
ws.filelist_path(),
|
||||
Some(tree.path.join("files.f")),
|
||||
"anchored at the root while it exists"
|
||||
);
|
||||
|
||||
assert!(ws.change_roots(Vec::new(), from_ref(&tree.path)));
|
||||
assert_eq!(
|
||||
ws.filelist_path(),
|
||||
Some(PathBuf::from("files.f")),
|
||||
"with no roots left, the same setting comes back bare — anchored at nothing"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! The incremental path (incremental-index, 2026-08-27): one saved file
|
||||
//! re-indexed in place, checked against the whole rebuild it stands in for.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_a_file_the_index_already_holds_takes_the_incremental_path() {
|
||||
// The whole gate, from both sides. A file the index holds is one the
|
||||
// update can replace; anything else is a rebuild's business, because a
|
||||
// file appearing changes what *other* files' includes resolve to.
|
||||
let tree = Tree::new("incrgate");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.update_one_checked(&tree.path.join("rtl/a.sv")), "a file the index holds");
|
||||
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "a file it does not");
|
||||
assert!(!ws.update_one(&tree.path.join("rtl/a.txt")), "and a path it never would");
|
||||
// A file that appears is exactly the "not held" case, and stays so
|
||||
// until something rebuilds.
|
||||
tree.package("rtl/new.sv", "new_pkg");
|
||||
assert!(!ws.update_one(&tree.path.join("rtl/new.sv")), "still not held");
|
||||
ws.rebuild_index();
|
||||
assert!(ws.update_one_checked(&tree.path.join("rtl/new.sv")), "held now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_files_edit_reaches_every_table_the_index_answers_from() {
|
||||
// The four pieces of derived state a rebuild produces, checked one by
|
||||
// one after an update that moves all four: a declaration, an
|
||||
// instantiation edge, an inheritance edge, a completion word and an
|
||||
// `` `include`` edge.
|
||||
let tree = Tree::new("incrtables");
|
||||
tree.write("rtl/defs.svh", "`define W 8\n");
|
||||
tree.write("rtl/sub.sv", "module sub;\nendmodule\nclass base;\nendclass\n");
|
||||
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n sub u1 ();\nendmodule\n");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let top = tree.path.join("rtl/top.sv");
|
||||
assert_eq!(ws.index().instantiations_of("sub").len(), 1, "premise: one site");
|
||||
assert_eq!(
|
||||
ws.includes().reachable(vec![top.clone()]).len(),
|
||||
2,
|
||||
"premise: top.sv reaches defs.svh"
|
||||
);
|
||||
assert_eq!(ws.candidates().words("u1").len(), 1, "premise: the instance name is a word");
|
||||
|
||||
fs::write(
|
||||
&top,
|
||||
"module top;\n logic renamed_wire;\nendmodule\nclass leaf extends base;\nendclass\n",
|
||||
)
|
||||
.expect("write");
|
||||
assert!(ws.update_one_checked(&top));
|
||||
assert!(ws.index().instantiations_of("sub").is_empty(), "the site went");
|
||||
assert_eq!(ws.index().subclasses_of("base").len(), 1, "and an inheritance edge came");
|
||||
assert!(ws.candidates().words("u1").is_empty(), "the old word was given back");
|
||||
assert_eq!(ws.candidates().words("renamed_wire").len(), 1, "the new one taken");
|
||||
assert_eq!(ws.includes().reachable(vec![top]).len(), 1, "the include edge went too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_the_cap_or_the_disk_takes_away_leaves_the_index() {
|
||||
let tree = Tree::new("incrremove");
|
||||
tree.package("rtl/keep.sv", "keep_pkg");
|
||||
tree.package("rtl/gone.sv", "gone_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]).len(), 2, "premise");
|
||||
|
||||
// Deleted on disk: the update is a removal.
|
||||
let gone = tree.path.join("rtl/gone.sv");
|
||||
fs::remove_file(&gone).expect("remove");
|
||||
assert!(ws.update_one_checked(&gone), "a held file, even a vanished one");
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "gone_pkg"]), ["keep_pkg"]);
|
||||
|
||||
// And a file that grew past the cap is the same answer for the same
|
||||
// reason: it is not a file this server reads any more.
|
||||
let mut ws = Workspace::default();
|
||||
let tree = Tree::new("incrcap");
|
||||
tree.package("rtl/keep.sv", "keep_pkg");
|
||||
fat_package(&tree, "rtl/netlist.sv", "netlist_pkg", 4096);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]).len(), 2, "premise: under no cap");
|
||||
ws.set_client_settings(wide(capping(1024)));
|
||||
assert!(ws.update_one_checked(&tree.path.join("rtl/netlist.sv")));
|
||||
assert_eq!(indexed(&ws, &["keep_pkg", "netlist_pkg"]), ["keep_pkg"], "the cap took it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_beats_disk_on_the_incremental_path_too() {
|
||||
let tree = Tree::new("incrbuffer");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join("rtl/a.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package buffered_pkg;\n localparam K = 1;\nendpackage\n".to_string());
|
||||
assert!(ws.update_one_checked(&path));
|
||||
assert_eq!(
|
||||
indexed(&ws, &["a_pkg", "buffered_pkg"]),
|
||||
["buffered_pkg"],
|
||||
"the buffer's text, not the file's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_incremental_update_agrees_with_a_whole_rebuild_over_the_real_corpus() {
|
||||
// The paranoid sweep: take real files out of a real workspace, put a
|
||||
// mutated version back through the incremental path, and check the
|
||||
// result against a whole rebuild every time. `update_one_checked` is
|
||||
// what does the checking; this test is the corpus it does it over.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
// Copied into a scratch tree, because the sweep rewrites files. Every
|
||||
// fifth file: `update_one_checked` rebuilds the whole workspace to
|
||||
// check itself, so the sweep costs a full rebuild per mutation and a
|
||||
// third of the corpus is still hundreds of real files.
|
||||
let tree = Tree::new("incrcorpus");
|
||||
let mut copied = 0;
|
||||
let mut sample: Vec<PathBuf> = Vec::new();
|
||||
for (n, source) in walk_sources(&corpus).into_iter().step_by(5).enumerate() {
|
||||
let Ok(text) = fs::read_to_string(&source) else { continue };
|
||||
let rel = format!("f{n:04}.sv");
|
||||
tree.write(&rel, &text);
|
||||
copied += 1;
|
||||
if n % 31 == 0 {
|
||||
sample.push(tree.path.join(&rel));
|
||||
}
|
||||
}
|
||||
assert!(copied > 100, "premise: the corpus was really copied ({copied} files)");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(sample.len() > 5, "a sample worth sweeping: {}", sample.len());
|
||||
|
||||
for path in &sample {
|
||||
let text = fs::read_to_string(path).expect("the copy is on disk");
|
||||
// Four shapes of edit, each checked against a whole rebuild.
|
||||
assert!(ws.update_one_checked(path), "unchanged");
|
||||
fs::write(
|
||||
path,
|
||||
format!("{text}\nmodule qa_added_module;\n qa_added_sub u1 ();\nendmodule\n"),
|
||||
)
|
||||
.expect("write");
|
||||
assert!(ws.update_one_checked(path), "a declaration and an edge added");
|
||||
fs::write(path, "class qa_leaf extends qa_base;\nendclass\n").expect("write");
|
||||
assert!(ws.update_one_checked(path), "replaced wholesale");
|
||||
fs::write(path, "").expect("write");
|
||||
assert!(ws.update_one_checked(path), "emptied");
|
||||
fs::remove_file(path).expect("remove");
|
||||
assert!(ws.update_one_checked(path), "removed");
|
||||
}
|
||||
eprintln!("paranoid sweep: {copied} files, {} of them mutated five ways", sample.len());
|
||||
}
|
||||
|
||||
/// What one file's rescan costs on the incremental path, against the whole
|
||||
/// rebuild it replaces, over the real corpus.
|
||||
///
|
||||
/// `#[ignore]`d like the crate's other measurement probes: it prints
|
||||
/// numbers rather than asserting one. The numbers themselves are in
|
||||
/// `docs/features/incremental-index/README.md`.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn qa_perf_one_file_against_the_whole_rebuild() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus]);
|
||||
let files = ws.index().files().len();
|
||||
let one = ws.index().files().last().cloned().expect("a file");
|
||||
|
||||
let mut whole = std::time::Duration::MAX;
|
||||
let mut single = std::time::Duration::MAX;
|
||||
for _ in 0..3 {
|
||||
let started = std::time::Instant::now();
|
||||
ws.rebuild_index();
|
||||
whole = whole.min(started.elapsed());
|
||||
let started = std::time::Instant::now();
|
||||
assert!(ws.update_one(&one));
|
||||
single = single.min(started.elapsed());
|
||||
}
|
||||
eprintln!(
|
||||
"reindex over {files} files: whole rebuild {whole:?}, one file {single:?} \
|
||||
({:.0}x)",
|
||||
whole.as_secs_f64() / single.as_secs_f64().max(f64::MIN_POSITIVE)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! An interleaved scan against the one-shot scan it must equal: the
|
||||
//! publication cadence, the tables however often they were published, a
|
||||
//! buffer opened mid-scan, and the events in the same order either way.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Run a scan the way `server.rs` does, publishing after **every** file —
|
||||
/// the worst case the interleaved path can produce, and the one a
|
||||
/// one-shot scan has to agree with.
|
||||
fn scan_publishing_every_file(ws: &mut Workspace) -> Vec<String> {
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
while ws.scan_step(&mut scan, &mut |_| {}) {
|
||||
ws.publish_scan(&mut scan);
|
||||
}
|
||||
ws.finish_scan(scan)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_publication_cadence_holds_a_publish_until_enough_has_been_staged() {
|
||||
// **The whole of the cadence, at its exact boundary.** A publish is a
|
||||
// pass over the whole index, and before §61.4 the drain paid one per
|
||||
// burst of requests — 13 to 18 in one warm opentitan scan, 46 % of it
|
||||
// (`docs/features/perf5r-publication/README.md`). `publish_is_due`
|
||||
// spaces them by work done rather than by how often a client asks: no
|
||||
// publish is due until `PUBLISH_EVERY` records are staged, one is due
|
||||
// the moment the 512th lands, and publishing clears the debt.
|
||||
let tree = Tree::new("publishcadence");
|
||||
for n in 0..scan::PUBLISH_EVERY + 2 {
|
||||
tree.package(&format!("p{n:04}.sv"), &format!("p{n:04}"));
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
for taken in 1..scan::PUBLISH_EVERY {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: file {taken} exists");
|
||||
assert!(!scan.publish_is_due(), "{taken} staged is not yet a publish");
|
||||
}
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "premise: the 512th file exists");
|
||||
assert!(scan.publish_is_due(), "{} staged is", scan::PUBLISH_EVERY);
|
||||
ws.publish_scan(&mut scan);
|
||||
assert!(!scan.publish_is_due(), "and publishing clears the debt");
|
||||
|
||||
// The cadence is a latency decision and nothing else: what this scan
|
||||
// lands is what a one-shot scan over the same tree lands.
|
||||
while ws.scan_step(&mut scan, &mut |_| {}) {}
|
||||
ws.finish_scan(scan);
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(everything(&one_shot), everything(&ws));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishing_between_every_file_leaves_what_a_one_shot_scan_leaves() {
|
||||
// The round's central invariant. The interleaved scan and the one-shot
|
||||
// scan are the same three calls with and without a drain between them,
|
||||
// so this pins the thing a drain could break: that folding records in
|
||||
// as they are taken lands the same index, the same completion tables
|
||||
// and the same include graph as folding them all in at the end.
|
||||
let tree = tangled("interleavesame");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
scan_publishing_every_file(&mut stepped);
|
||||
|
||||
assert_eq!(everything(&one_shot), everything(&stepped));
|
||||
assert!(one_shot.index().files().len() == 4, "premise: every file was scanned");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_that_publishes_as_it_goes_still_drops_what_left_the_scope() {
|
||||
// A publish only ever folds records *in*, so the removal a rescan owes
|
||||
// — files the last scan held that this one's work list does not name —
|
||||
// has to survive every publish that happened before it.
|
||||
let tree = tangled("interleavegone");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(!ws.index().units("c").is_empty(), "premise: c.sv is indexed");
|
||||
|
||||
std::fs::remove_file(tree.path.join("c.sv")).expect("remove");
|
||||
scan_publishing_every_file(&mut ws);
|
||||
|
||||
let mut fresh = Workspace::default();
|
||||
fresh.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(everything(&fresh), everything(&ws));
|
||||
assert!(ws.index().units("c").is_empty(), "the file that left the scope is gone");
|
||||
assert_eq!(ws.index().files().len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_or_changed_mid_scan_does_not_change_what_the_scan_indexes() {
|
||||
// The scan holds the text every file had when its work list was taken,
|
||||
// and indexes *that* — which is exactly what a `didOpen` or a
|
||||
// `didChange` landing a moment after the scan finished would leave in
|
||||
// the index too (neither touches it; a save is what does). So a
|
||||
// message answered in the middle of a scan cannot move the scan's
|
||||
// result, and the fingerprint is the witness.
|
||||
let tree = tangled("interleavemidchange");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = stepped.begin_scan(&mut |_| {}, false);
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: there is a first file");
|
||||
stepped.publish_scan(&mut scan);
|
||||
// The client opens `b.sv` and types in it, mid-scan.
|
||||
let opened = uri(&format!("file://{}", tree.path.join("b.sv").display()));
|
||||
stepped.set_document(opened.clone(), "module b;\n localparam MID = 1;\nendmodule\n".into());
|
||||
while stepped.scan_step(&mut scan, &mut |_| {}) {
|
||||
stepped.publish_scan(&mut scan);
|
||||
}
|
||||
stepped.finish_scan(scan);
|
||||
|
||||
assert_eq!(everything(&one_shot), everything(&stepped));
|
||||
assert_eq!(
|
||||
stepped.document(&opened).map(|doc| doc.text.as_str()),
|
||||
Some("module b;\n localparam MID = 1;\nendmodule\n"),
|
||||
"the buffer keeps the text it was given, index or no index"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_opened_mid_scan_is_indexed_next_and_the_index_cannot_tell() {
|
||||
// The open-first rule for a file opened *after* the work list was
|
||||
// taken. It moves to the front of what is left, everything it passed
|
||||
// keeps its place behind it, and the finished index is byte-identical
|
||||
// — records are merged in path order whatever order they arrived in.
|
||||
let tree = tangled("interleaveopenfirst");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut scan = stepped.begin_scan(&mut |_| {}, false);
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}), "premise: a.sv goes first");
|
||||
assert!(stepped.index().units("c").is_empty(), "premise: c.sv is not indexed yet");
|
||||
|
||||
// The client opens `c.sv`, and the work list is re-ordered around the
|
||||
// buffers open now — since 2026-09-08 that is one call rather than one
|
||||
// per opened path, because a buffer brings its folder with it
|
||||
// (`docs/features/perf5-p4/README.md` §P4b3).
|
||||
let jumped = uri(&format!("file://{}", tree.path.join("c.sv").display()));
|
||||
let jumped_text = fs::read_to_string(tree.path.join("c.sv")).expect("the fixture");
|
||||
stepped.set_document(jumped, jumped_text);
|
||||
stepped.open_next(&mut scan, &mut |_| {});
|
||||
assert!(stepped.scan_step(&mut scan, &mut |_| {}));
|
||||
stepped.publish_scan(&mut scan);
|
||||
assert!(!stepped.index().units("c").is_empty(), "c.sv was indexed next, not last");
|
||||
|
||||
while stepped.scan_step(&mut scan, &mut |_| {}) {}
|
||||
stepped.finish_scan(scan);
|
||||
assert_eq!(everything(&one_shot), everything(&stepped));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_reports_the_same_events_in_the_same_order_however_it_is_driven() {
|
||||
// The progress bar and the per-file log are the same two things a
|
||||
// one-shot scan reports, in the same order, against the same total:
|
||||
// interleaving adds drains between the events, never events.
|
||||
let tree = tangled("interleaveevents");
|
||||
let mut one_shot = Workspace::default();
|
||||
one_shot.client.index_scope = IndexScope::Workspace;
|
||||
one_shot.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut said = Vec::new();
|
||||
one_shot.rebuild_index_with(&mut |event| said.push(seen(&event)));
|
||||
|
||||
let mut stepped = Workspace::default();
|
||||
stepped.client.index_scope = IndexScope::Workspace;
|
||||
stepped.adopt_roots(vec![tree.path.clone()]);
|
||||
let mut also = Vec::new();
|
||||
let mut scan = stepped.begin_scan(&mut |event| also.push(seen(&event)), false);
|
||||
while stepped.scan_step(&mut scan, &mut |event| also.push(seen(&event))) {
|
||||
stepped.publish_scan(&mut scan);
|
||||
}
|
||||
assert_eq!(scan.skipped(), 0);
|
||||
assert_eq!(scan.cached(), 0);
|
||||
stepped.finish_scan(scan);
|
||||
|
||||
assert_eq!(said, also);
|
||||
assert_eq!(said.len(), 4, "one event per file, and nothing else: {said:?}");
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The large-file fast path: the threshold is strict and `0` turns it off,
|
||||
//! a fast-path buffer holds the analysis of an empty file and contributes
|
||||
//! nothing to the index, and a buffer changes mode as it crosses the line.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A workspace whose fast path starts at `threshold` bytes.
|
||||
fn thresholded(threshold: u64) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
large_file_threshold: threshold,
|
||||
..ClientSettings::default()
|
||||
});
|
||||
ws
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_is_strict_at_the_boundary() {
|
||||
let sizes = [99, 100, 101];
|
||||
let large: Vec<bool> = sizes
|
||||
.iter()
|
||||
.map(|&size| {
|
||||
let mut ws = thresholded(100);
|
||||
ws.set_document(uri("file:///rtl/big.v"), filler(size));
|
||||
ws.document(&uri("file:///rtl/big.v")).expect("open").large
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(large, [false, false, true], "under, at, over");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_threshold_of_zero_turns_the_fast_path_off_entirely() {
|
||||
let mut ws = thresholded(0);
|
||||
ws.set_document(uri("file:///rtl/big.v"), filler(200_000));
|
||||
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
|
||||
assert!(!doc.large);
|
||||
assert!(!doc.tokens.is_empty(), "it really was lexed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() {
|
||||
let mut ws = thresholded(100);
|
||||
ws.set_document(uri("file:///rtl/big.v"), filler(500));
|
||||
let doc = ws.document(&uri("file:///rtl/big.v")).expect("open");
|
||||
assert!(doc.large);
|
||||
assert!(doc.tokens.is_empty(), "nothing was lexed");
|
||||
assert!(doc.diagnostics.is_empty(), "nothing was parsed");
|
||||
assert!(doc.semantics.symbols().is_empty(), "nothing was analyzed");
|
||||
assert!(doc.defines.entries().is_empty(), "no defines were collected");
|
||||
// But the two things the fast path *does* build are real.
|
||||
assert_eq!(doc.text.len(), 500);
|
||||
assert!(doc.line_index.line_count() > 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() {
|
||||
let tree = Tree::new("largefile");
|
||||
tree.write("pkg.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
|
||||
let path = tree.path.join("pkg.sv");
|
||||
|
||||
let mut ws = thresholded(100);
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk was indexed");
|
||||
|
||||
// The same file, opened as a buffer the fast path takes.
|
||||
let mut text = String::from("package p;\n localparam IN_BUFFER = 1;\nendpackage\n");
|
||||
text.push_str(&" ".repeat(200));
|
||||
ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the buffer was not parsed");
|
||||
assert_eq!(
|
||||
ws.index().member("p", "ON_DISK").len(),
|
||||
0,
|
||||
"and the disk copy the buffer supersedes is not indexed in its place"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_edited_past_the_threshold_changes_mode_and_back() {
|
||||
let mut ws = thresholded(200);
|
||||
let file = uri("file:///rtl/grow.v");
|
||||
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
|
||||
assert!(!ws.document(&file).expect("open").large);
|
||||
ws.set_document(file.clone(), filler(1_000));
|
||||
assert!(ws.document(&file).expect("open").large, "grew past the threshold");
|
||||
ws.set_document(file.clone(), "module m;\nendmodule\n".into());
|
||||
let doc = ws.document(&file).expect("open");
|
||||
assert!(!doc.large, "and shrank back under it");
|
||||
assert!(!doc.tokens.is_empty(), "with a full analysis again");
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! The lazy read and the folder-first order (perf5-p4 §P4b3, 2026-09-08):
|
||||
//! each file's bytes read once, at its own step, with the open buffer's
|
||||
//! neighbourhood indexed before the rest of the workspace is even walked.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The paths a scan reported, whichever way each file got into the index.
|
||||
fn walked(ws: &mut Workspace) -> Vec<PathBuf> {
|
||||
let mut seen: Vec<PathBuf> = Vec::new();
|
||||
ws.rebuild_index_with(&mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. }
|
||||
| IndexEvent::Cached { path, .. }
|
||||
| IndexEvent::Analyzed { path, .. } => seen.push(path.to_path_buf()),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
seen
|
||||
}
|
||||
|
||||
/// A workspace whose buffer sits two folders below a root, so the folder
|
||||
/// the scope ladder raises it to is a real neighbourhood rather than the
|
||||
/// whole tree — opentitan's `hw/ip/aes/dv/tb/tb.sv` in miniature.
|
||||
fn neighbourhood_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("ip/aes/dv/tb/tb.sv", "tb_pkg");
|
||||
tree.package("ip/aes/rtl/aes.sv", "aes_pkg");
|
||||
tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg");
|
||||
tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg");
|
||||
tree.package("ip/uart/rtl/uart.sv", "uart_pkg");
|
||||
tree.package("dv/common/util.sv", "util_pkg");
|
||||
// The crowd the folder has to be a minority of — opentitan's `ip/aes`
|
||||
// is 124 files of 3 976 (`crate::scan_order::worth_waiting`).
|
||||
for n in 0..6 {
|
||||
tree.package(&format!("zz/z{n:03}.sv"), &format!("z{n:03}_pkg"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_scan_reads_each_files_bytes_exactly_once() {
|
||||
// The claim the lazy read makes. Everything the scan wants from a
|
||||
// file's text — the store's content hash, the parse, the `include`
|
||||
// lines — comes out of one read, and the open buffer's text is not
|
||||
// read from disk at all.
|
||||
let tree = neighbourhood_tree("readonce");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
|
||||
let before = crate::scan_trace::source_reads();
|
||||
assert_eq!(ws.rebuild_index().len(), 0, "premise: the walk is clean");
|
||||
assert_eq!(
|
||||
crate::scan_trace::source_reads() - before,
|
||||
12,
|
||||
"twelve files in the tree, twelve reads and not one more"
|
||||
);
|
||||
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
let before = crate::scan_trace::source_reads();
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
crate::scan_trace::source_reads() - before,
|
||||
11,
|
||||
"the open buffer's own text is in memory and is never read off disk"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_open_buffers_folder_is_indexed_before_the_rest_and_the_index_cannot_tell() {
|
||||
// The ordering §P4b2 asked for: the user's own file, then the folder
|
||||
// the scope ladder raises it to — `ip/aes`, two levels above
|
||||
// `ip/aes/dv` — and only then the workspace's alphabet.
|
||||
let tree = neighbourhood_tree("folderfirst");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
|
||||
assert_eq!(
|
||||
walked(&mut ws),
|
||||
[
|
||||
vec![
|
||||
tree.path.join("ip/aes/dv/tb/tb.sv"),
|
||||
tree.path.join("ip/aes/rtl/aes.sv"),
|
||||
tree.path.join("ip/aes/rtl/aes_core.sv"),
|
||||
tree.path.join("dv/common/util.sv"),
|
||||
tree.path.join("ip/kmac/rtl/kmac.sv"),
|
||||
tree.path.join("ip/uart/rtl/uart.sv"),
|
||||
],
|
||||
(0..6).map(|n| tree.path.join(format!("zz/z{n:03}.sv"))).collect(),
|
||||
]
|
||||
.concat(),
|
||||
"the buffer, then its folder in path order, then the rest in path order"
|
||||
);
|
||||
|
||||
// And the reason that is allowed to be true: the finished index does
|
||||
// not depend on it. `IndexBuilder::finish` sorts by path, so a scan
|
||||
// with nothing open builds the same thing.
|
||||
let mut plain = Workspace::default();
|
||||
plain.client.index_scope = IndexScope::Workspace;
|
||||
plain.adopt_roots(vec![tree.path.clone()]);
|
||||
plain.rebuild_index();
|
||||
assert_eq!(plain.index().fingerprint(), ws.index().fingerprint(), "same index");
|
||||
assert_eq!(everything(&plain), everything(&ws), "and the same tables around it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_neighbourhood_is_what_a_held_request_waits_for() {
|
||||
// The drain rule's own arithmetic, at the workspace level: `head`
|
||||
// counts the buffer and its folder and nothing beyond.
|
||||
let tree = neighbourhood_tree("headsegment");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert!(!scan.neighbourhood_indexed(), "nothing is indexed yet");
|
||||
// Three files are the neighbourhood — the buffer and `ip/aes` — and
|
||||
// the nine behind it are not.
|
||||
for expected in [false, false, true, true, true, true, true, true, true, true, true, true] {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}));
|
||||
assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at);
|
||||
}
|
||||
ws.finish_scan(scan);
|
||||
|
||||
// With nothing open there is no neighbourhood, and a held request is
|
||||
// answered at the first interleave point exactly as it always was.
|
||||
let mut bare = Workspace::default();
|
||||
bare.client.index_scope = IndexScope::Workspace;
|
||||
bare.adopt_roots(vec![tree.path.clone()]);
|
||||
let scan = bare.begin_scan(&mut |_| {}, false);
|
||||
assert!(scan.neighbourhood_indexed(), "no buffer, no wait");
|
||||
bare.finish_scan(scan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_opened_mid_scan_lengthens_the_neighbourhood_it_jumps_into() {
|
||||
// `index_next` moves a file to the front of what is left. When it
|
||||
// comes from beyond the head segment it pushes one of that segment's
|
||||
// files a place later, and a held request must not be answered one
|
||||
// file short of the folder it is waiting for.
|
||||
let tree = neighbourhood_tree("headjump");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
open(&mut ws, &tree, "ip/aes/dv/tb/tb.sv");
|
||||
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}), "the buffer's own file goes first");
|
||||
open(&mut ws, &tree, "ip/uart/rtl/uart.sv");
|
||||
ws.open_next(&mut scan, &mut |_| {});
|
||||
// `uart.sv` is now the head of what is left, and at the shipped
|
||||
// `scopeDepth: 2` its own folder raises to `ip` — which brings
|
||||
// `ip/kmac` in with it. Four files of waiting, one behind the file
|
||||
// already stepped, so the segment ends at five rather than three.
|
||||
for expected in [false, false, false, true, true] {
|
||||
assert!(ws.scan_step(&mut scan, &mut |_| {}));
|
||||
assert_eq!(scan.neighbourhood_indexed(), expected, "at {}", scan.at);
|
||||
}
|
||||
ws.finish_scan(scan);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_leaves_the_disk_between_the_walk_and_its_step_leaves_the_index() {
|
||||
// What `collect_sources` used to do by dropping an unreadable file
|
||||
// before the work list existed: the file contributes nothing, is not
|
||||
// counted among the cap's skips, and — for a whole scan — is taken
|
||||
// *out* of the index rather than left in it stale.
|
||||
let tree = Tree::new("vanished");
|
||||
tree.package("rtl/stays.sv", "stays_pkg");
|
||||
tree.package("rtl/goes.sv", "goes_pkg");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
ws.rebuild_index();
|
||||
assert!(!ws.index().units("goes_pkg").is_empty(), "premise: it was indexed once");
|
||||
|
||||
let mut scan = ws.begin_scan(&mut |_| {}, false);
|
||||
assert_eq!(scan.total(), 2, "the walk found both");
|
||||
fs::remove_file(tree.path.join("rtl/goes.sv")).expect("remove");
|
||||
let mut said: Vec<String> = Vec::new();
|
||||
while ws.scan_step(&mut scan, &mut |event| said.push(seen(&event))) {}
|
||||
assert_eq!(scan.skipped(), 0, "an unreadable file is not one the size cap skipped");
|
||||
assert_eq!(said.len(), 1, "and it reports no event of its own: {said:?}");
|
||||
ws.finish_scan(scan);
|
||||
|
||||
assert!(ws.index().units("goes_pkg").is_empty(), "it left the scope, so it left the index");
|
||||
assert!(!ws.index().units("stays_pkg").is_empty(), "and the file beside it did not");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tables_a_scan_lands_are_the_ones_the_texts_would_have_built() {
|
||||
// The lazy read's equivalence, table by table. The scan builds the
|
||||
// completion tables from the words it took off each record and the
|
||||
// include graph from the lines it scanned at each step; both must
|
||||
// equal what `Candidates::build` and `IncludeGraph::build` produce
|
||||
// from the same files' text.
|
||||
let tree = tangled("lazytables");
|
||||
let mut ws = Workspace::default();
|
||||
ws.client.index_scope = IndexScope::Workspace;
|
||||
ws.adopt_roots(vec![tree.path.clone()]);
|
||||
ws.rebuild_index();
|
||||
|
||||
let texts: Vec<(PathBuf, String)> = ws
|
||||
.index()
|
||||
.files()
|
||||
.iter()
|
||||
.map(|path| (path.clone(), fs::read_to_string(path).expect("fixture")))
|
||||
.collect();
|
||||
let eagerly = Candidates::build(ws.index(), &texts, HashMap::new());
|
||||
assert_eq!(eagerly.sizes(), ws.candidates().sizes(), "the same completion tables");
|
||||
assert_eq!(eagerly.words(""), ws.candidates().words(""), "word for word");
|
||||
|
||||
let rebuilt = IncludeGraph::build(&texts, Vec::new());
|
||||
assert_eq!(rebuilt.sizes(), ws.includes().sizes(), "the same include graph");
|
||||
for (path, _) in &texts {
|
||||
assert_eq!(
|
||||
rebuilt.reachable(vec![path.clone()]),
|
||||
ws.includes().reachable(vec![path.clone()]),
|
||||
"the same hops from {}",
|
||||
path.display()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! The `Workspace` tests: one file per topic, every one driven through the
|
||||
//! real `Workspace` against a scratch tree on disk.
|
||||
//!
|
||||
//! This file is the harness — `Tree`, a workspace root removed on drop —
|
||||
//! followed by the helpers more than one file uses: settings as a client
|
||||
//! would push them, a buffer opened from disk, and the ways a scan's
|
||||
//! outcome is read back. The sibling files are the sections the one big
|
||||
//! test module used to have, under the names they had; a helper used by
|
||||
//! one section only stayed with it.
|
||||
|
||||
use std::fs;
|
||||
use std::slice::from_ref;
|
||||
use std::str::FromStr;
|
||||
|
||||
use super::*;
|
||||
use crate::settings::IndexScope;
|
||||
|
||||
mod document;
|
||||
mod filelist;
|
||||
mod folder_scope;
|
||||
mod folders;
|
||||
mod incremental;
|
||||
mod interleave;
|
||||
mod large_file;
|
||||
mod lazy_read;
|
||||
mod open_buffers;
|
||||
mod persistence;
|
||||
mod settings;
|
||||
mod size_cap;
|
||||
mod views;
|
||||
mod widen;
|
||||
|
||||
fn uri(s: &str) -> Uri {
|
||||
Uri::from_str(s).expect("test uri parses")
|
||||
}
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv_server_scan_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
fs::write(&path, text).expect("write");
|
||||
}
|
||||
|
||||
/// A package declaring one localparam, so the index can be asked
|
||||
/// whether this file was scanned at all.
|
||||
fn package(&self, rel: &str, name: &str) {
|
||||
self.write(rel, &format!("package {name};\n localparam K = 1;\nendpackage\n"));
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open `rel` in `ws` as the buffer it is on disk.
|
||||
fn open(ws: &mut Workspace, tree: &Tree, rel: &str) {
|
||||
let path = tree.path.join(rel);
|
||||
let text = fs::read_to_string(&path).expect("the fixture is on disk");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, text);
|
||||
}
|
||||
|
||||
/// A buffer of exactly `bytes` bytes that is also real Verilog.
|
||||
fn filler(bytes: usize) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
while text.len() + 9 <= bytes {
|
||||
text.push_str(" wire a;\n");
|
||||
}
|
||||
while text.len() < bytes {
|
||||
text.push(' ');
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// A tree of three files that declare each other's names and include each
|
||||
/// other, so a half-published index has something to get wrong.
|
||||
fn tangled(tag: &str) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
tree.write("defs.svh", "`define WIDE 32\n");
|
||||
tree.write(
|
||||
"a.sv",
|
||||
"`include \"defs.svh\"\npackage a;\n localparam K = 1;\n \
|
||||
typedef logic [`WIDE-1:0] word_t;\nendpackage\n",
|
||||
);
|
||||
tree.write(
|
||||
"b.sv",
|
||||
"`include \"defs.svh\"\nmodule b;\n import a::*;\n word_t w;\n \
|
||||
localparam K2 = a::K;\nendmodule\n",
|
||||
);
|
||||
tree.write("c.sv", "module c;\n b inner ();\nendmodule\n");
|
||||
tree
|
||||
}
|
||||
|
||||
/// `settings` with the pre-2026-08-27 whole-workspace scope asked for —
|
||||
/// the push-door twin of [`Workspace::open_whole_workspace`], needed
|
||||
/// wherever a test pushes settings *after* opening its roots, since a push
|
||||
/// replaces every field including the scope.
|
||||
fn wide(settings: ClientSettings) -> ClientSettings {
|
||||
ClientSettings { index_scope: IndexScope::Workspace, ..settings }
|
||||
}
|
||||
|
||||
/// `lucisv.exclude` as a client would push it.
|
||||
fn excluding(patterns: &[&str]) -> ClientSettings {
|
||||
ClientSettings {
|
||||
exclude: patterns.iter().map(|p| p.to_string()).collect(),
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The folder rung at `scopeDepth: 0` — the open file's own folder and
|
||||
/// nothing above it.
|
||||
///
|
||||
/// Said out loud since 2026-08-28, when the shipped default became
|
||||
/// [`crate::settings::DEFAULT_SCOPE_DEPTH`]: a test about *this* rung
|
||||
/// names the depth it is about rather than riding whatever the default is
|
||||
/// this month. The behaviour it selects is unchanged.
|
||||
fn own_folder_only(ws: &mut Workspace) {
|
||||
ws.set_client_settings(ClientSettings { index_scope_depth: 0, ..Default::default() });
|
||||
}
|
||||
|
||||
/// `lucisv.filelist` as a client would push it.
|
||||
fn using_filelist(path: &str) -> ClientSettings {
|
||||
ClientSettings { filelist: Some(path.to_string()), ..Default::default() }
|
||||
}
|
||||
|
||||
/// A `ClientSettings` with the size cap set to `bytes`.
|
||||
fn capping(bytes: u64) -> ClientSettings {
|
||||
ClientSettings { max_file_size: bytes, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A file of `bytes` bytes that would declare `name` if anything read it.
|
||||
/// Padded with a trailing comment, so what makes it big is not what makes
|
||||
/// it a package.
|
||||
fn fat_package(tree: &Tree, rel: &str, name: &str, bytes: usize) {
|
||||
let head = format!("package {name};\n localparam K = 1;\nendpackage\n// ");
|
||||
let mut text = String::with_capacity(bytes + head.len());
|
||||
text.push_str(&head);
|
||||
while text.len() < bytes {
|
||||
text.push('x');
|
||||
}
|
||||
text.push('\n');
|
||||
tree.write(rel, &text);
|
||||
}
|
||||
|
||||
/// A client that keeps its index cache in `dir`.
|
||||
fn caching(dir: &Path) -> ClientSettings {
|
||||
ClientSettings {
|
||||
index_cache_path: Some(dir.to_string_lossy().into_owned()),
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the index holds, as the names of the packages it found.
|
||||
fn indexed(ws: &Workspace, names: &[&str]) -> Vec<String> {
|
||||
names.iter().filter(|n| ws.index().member(n, "K").len() == 1).map(|n| n.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Everything a scan produces, rendered as one comparable value: the
|
||||
/// index's own witness, the completion tables and the include graph.
|
||||
///
|
||||
/// The index's fingerprint alone would not do — this round publishes all
|
||||
/// three tables together, so all three have to be shown to come out the
|
||||
/// same however many publishes happened on the way.
|
||||
fn everything(ws: &Workspace) -> String {
|
||||
let mut out = ws.index().fingerprint();
|
||||
out.push_str(&format!("words {:?}\n", ws.candidates().words("")));
|
||||
out.push_str(&format!(
|
||||
"units {:?}\n",
|
||||
ws.candidates().units("").iter().map(|c| &c.name).collect::<Vec<_>>()
|
||||
));
|
||||
out.push_str(&format!(
|
||||
"macros {:?}\n",
|
||||
ws.candidates().macros("").iter().map(|m| &m.name).collect::<Vec<_>>()
|
||||
));
|
||||
let mut reachable: Vec<String> = ws
|
||||
.index()
|
||||
.files()
|
||||
.iter()
|
||||
.map(|path| {
|
||||
let mut hops: Vec<String> = ws
|
||||
.includes()
|
||||
.reachable(vec![path.clone()])
|
||||
.iter()
|
||||
.filter_map(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
hops.sort();
|
||||
format!("reaches {} {hops:?}", path.display())
|
||||
})
|
||||
.collect();
|
||||
reachable.sort();
|
||||
out.push_str(&reachable.join("\n"));
|
||||
out
|
||||
}
|
||||
|
||||
/// One [`IndexEvent`] as the word and the numbers a caller would report.
|
||||
fn seen(event: &IndexEvent) -> String {
|
||||
match event {
|
||||
IndexEvent::Parsing { done, total, path } => {
|
||||
format!("indexing {done}/{total} {}", path.display())
|
||||
}
|
||||
IndexEvent::Cached { done, total, path } => {
|
||||
format!("cached {done}/{total} {}", path.display())
|
||||
}
|
||||
IndexEvent::Analyzed { done, total, path } => {
|
||||
format!("analyzed {done}/{total} {}", path.display())
|
||||
}
|
||||
IndexEvent::Skipped { path, size, cap } => {
|
||||
format!("skipped {} {size} {cap}", path.display())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What one whole scan did, file by file: what it parsed, what it took
|
||||
/// from the cache instead, and what came from an open buffer's own
|
||||
/// analysis. The three together are the work list.
|
||||
#[derive(Debug, Default, PartialEq, Eq)]
|
||||
struct Scan {
|
||||
parsed: Vec<String>,
|
||||
cached: Vec<String>,
|
||||
analyzed: Vec<String>,
|
||||
}
|
||||
|
||||
/// Scan `roots` (or rescan what is already open, with `None`) and record
|
||||
/// which files were parsed and which came out of the cache.
|
||||
fn scan(ws: &mut Workspace, roots: Option<Vec<PathBuf>>) -> Scan {
|
||||
let mut out = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => out.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => out.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => out.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
match roots {
|
||||
Some(roots) => ws.open_whole_workspace_with(roots, &mut see),
|
||||
None => ws.rebuild_index_with(&mut see),
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().expect("a file").to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
/// Every source file under `dir`, for the corpus sweep above.
|
||||
fn walk_sources(dir: &Path) -> Vec<PathBuf> {
|
||||
let mut out = Vec::new();
|
||||
let mut stack = vec![dir.to_path_buf()];
|
||||
while let Some(next) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&next) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
stack.push(path);
|
||||
} else if matches!(path.extension().and_then(|e| e.to_str()), Some("sv" | "v" | "svh"))
|
||||
{
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
//! An open buffer's own analysis (index-scope, 2026-08-28) beats disk in
|
||||
//! the index and is what the index reuses — and the QA attacks on that:
|
||||
//! staleness across a close, and crossing the large-file threshold.
|
||||
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_overrides_disk_in_the_index() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv_server_state_{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).expect("temp dir");
|
||||
let path = dir.join("pkg.sv");
|
||||
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![dir.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1);
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0);
|
||||
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "buffer must win");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk must lose");
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffers_analysis_indexes_to_exactly_what_its_bytes_on_disk_would() {
|
||||
// The equivalence the reuse stands on. A rescan takes an open buffer's
|
||||
// facts and its words off the analysis that buffer already holds; the
|
||||
// claim is that the index and the completion tables are then byte for
|
||||
// byte the ones a *parse of those bytes* builds. The buffer carries
|
||||
// unsaved edits on purpose — bytes that are nowhere on disk, which is
|
||||
// exactly the case the content-keyed cache cannot help with and the
|
||||
// one the owner's report was about.
|
||||
let tree = Tree::new("openfacts");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("rtl/other.sv", "other_pkg");
|
||||
tree.write("rtl/top.sv", "module top;\n a_sub u ();\nendmodule\n");
|
||||
|
||||
let edited = "`define TAG 1\nimport a_pkg::*;\npackage edited_pkg;\n \
|
||||
localparam K = 1;\n class c extends a_base; int x; endclass\n\
|
||||
endpackage\nmodule top;\n logic [K-1:0] w;\n \
|
||||
a_sub u (.clk(w));\n a_sub v (.clk(w));\nendmodule\n";
|
||||
let path = tree.path.join("rtl/top.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
ws.set_document(uri, edited.to_string());
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(
|
||||
seen.analyzed,
|
||||
["top.sv"],
|
||||
"the open buffer went in from its own analysis: {seen:?}"
|
||||
);
|
||||
assert_eq!(seen.parsed, ["a.sv", "other.sv"], "and nothing else changed route: {seen:?}");
|
||||
let from_buffer = ws.index().fingerprint();
|
||||
let words_from_buffer = ws.candidates().words("").to_vec();
|
||||
let units_from_buffer: Vec<String> =
|
||||
ws.candidates().units("").iter().map(|c| c.name.clone()).collect();
|
||||
|
||||
// The same bytes on disk, nothing open: the parse route, end to end.
|
||||
tree.write("rtl/top.sv", edited);
|
||||
let mut plain = Workspace::default();
|
||||
plain.set_client_settings(wide(ClientSettings::default()));
|
||||
let mut route = Scan::default();
|
||||
plain.open_roots_with(vec![tree.path.clone()], &mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. } => route.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => route.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => route.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
assert_eq!(route.parsed, ["a.sv", "other.sv", "top.sv"], "premise: it really parsed");
|
||||
|
||||
assert_eq!(from_buffer, plain.index().fingerprint(), "the same index, byte for byte");
|
||||
assert_eq!(words_from_buffer, plain.candidates().words(""), "and the same words");
|
||||
let units_plain: Vec<String> =
|
||||
plain.candidates().units("").iter().map(|c| c.name.clone()).collect();
|
||||
assert_eq!(units_from_buffer, units_plain, "and the same index-derived candidates");
|
||||
|
||||
// And through the incremental door as well: `update_one` takes the same
|
||||
// shortcut, and `update_one_checked` holds it to a whole rebuild.
|
||||
assert!(ws.update_one_checked(&path), "the buffer's file is one the index holds");
|
||||
assert_eq!(ws.index().fingerprint(), from_buffer, "still the same index after an update");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_offers_the_facts_and_words_its_text_would_over_the_real_corpus() {
|
||||
// `Document::new` and `FileFacts::of` each lex, parse and analyze one
|
||||
// file, and the reuse is only sound while those two agree. Nothing
|
||||
// enforces it at compile time — they are separate call sites — so it is
|
||||
// swept over real files, in the encoded record form, which is every
|
||||
// field the index and the persistent store ever read.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let empty = WorkspaceIndex::default();
|
||||
let mut checked = 0usize;
|
||||
for path in walk_sources(&corpus).into_iter().step_by(3) {
|
||||
let Ok(text) = fs::read_to_string(&path) else { continue };
|
||||
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
|
||||
assert!(!doc.large, "premise: a full analysis, not the fast path");
|
||||
assert_eq!(
|
||||
doc.facts(path.clone()).encode(),
|
||||
FileFacts::of(path.clone(), &text).encode(),
|
||||
"the records differ for {}",
|
||||
path.display()
|
||||
);
|
||||
let mut from_buffer = doc.words();
|
||||
let mut from_text =
|
||||
crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
|
||||
from_buffer.sort();
|
||||
from_text.sort();
|
||||
assert_eq!(from_buffer, from_text, "the words differ for {}", path.display());
|
||||
checked += 1;
|
||||
}
|
||||
assert!(checked > 100, "premise: the corpus was really swept ({checked} files)");
|
||||
eprintln!("open-buffer equivalence: {checked} corpus files, facts and words identical");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_attack_crafted_non_corpus_shapes_drift_check() {
|
||||
// Run on a dedicated thread with a generous stack: `cargo test`'s
|
||||
// default per-test-thread stack (2 MiB) is smaller than a normal
|
||||
// process's main-thread stack, and a couple of the crafted shapes
|
||||
// below are deep enough to overflow the smaller one even though
|
||||
// `FileFacts::of` alone — no `Document`, no reuse — overflows it
|
||||
// identically on pristine, unmodified `master`. That is a real,
|
||||
// pre-existing recursion-depth ceiling in the parser/analyzer,
|
||||
// independent of this round; it is filed separately (QA log,
|
||||
// 2026-08-28) rather than blocking this round, since both routes
|
||||
// being compared here fail *identically*, which is the opposite of
|
||||
// the drift this test hunts for. Run at 64 MiB so the drift check
|
||||
// exercises real depth without tripping that unrelated ceiling.
|
||||
std::thread::Builder::new()
|
||||
.stack_size(64 * 1024 * 1024)
|
||||
.spawn(qa_attack_crafted_non_corpus_shapes_drift_check_body)
|
||||
.expect("spawn")
|
||||
.join()
|
||||
.expect("no panic");
|
||||
}
|
||||
|
||||
fn qa_attack_crafted_non_corpus_shapes_drift_check_body() {
|
||||
let empty = WorkspaceIndex::default();
|
||||
let cases: Vec<(&str, String)> = vec![
|
||||
("bom_plain", "\u{feff}module m;\nendmodule\n".to_string()),
|
||||
("crlf", "module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
|
||||
("bom_crlf", "\u{feff}module m;\r\n logic w;\r\nendmodule\r\n".to_string()),
|
||||
("unterminated_block_comment", "module m; /* never closed\nendmodule\n".to_string()),
|
||||
("unterminated_attribute", "(* foo module m; endmodule\n".to_string()),
|
||||
(
|
||||
"unterminated_macro_call",
|
||||
"`define M(a,b) a+b\nmodule m; logic w = `M(1,2\nendmodule\n".to_string(),
|
||||
),
|
||||
("unterminated_string", "module m; string s = \"never closed\nendmodule\n".to_string()),
|
||||
("unexpected_char", "module m; logic w = \u{1}; endmodule\n".to_string()),
|
||||
("deeply_nested_begin_end", {
|
||||
let mut s = String::from("module m;\ninitial begin\n");
|
||||
for _ in 0..500 {
|
||||
s.push_str("begin\n");
|
||||
}
|
||||
for _ in 0..500 {
|
||||
s.push_str("end\n");
|
||||
}
|
||||
s.push_str("end\nendmodule\n");
|
||||
s
|
||||
}),
|
||||
("deeply_nested_parens", {
|
||||
let mut s = String::from("module m;\n localparam int W = ");
|
||||
for _ in 0..2000 {
|
||||
s.push('(');
|
||||
}
|
||||
s.push('1');
|
||||
for _ in 0..2000 {
|
||||
s.push(')');
|
||||
}
|
||||
s.push_str(";\nendmodule\n");
|
||||
s
|
||||
}),
|
||||
("macro_heavy", {
|
||||
let mut s = String::new();
|
||||
for i in 0..500 {
|
||||
s.push_str(&format!("`define M{i} {i}\n"));
|
||||
}
|
||||
s.push_str("module m;\nendmodule\n");
|
||||
s
|
||||
}),
|
||||
(
|
||||
"include_bearing",
|
||||
"`include \"foo.svh\"\n`include \"bar/baz.vh\"\nmodule m;\nendmodule\n".to_string(),
|
||||
),
|
||||
(
|
||||
"parse_error_recovery",
|
||||
"module broken (input logic clk;\n wire w = ;\nendmodule\nmodule after; endmodule\n"
|
||||
.to_string(),
|
||||
),
|
||||
("mixed_line_endings", "module m;\n logic a;\r\n logic b;\nendmodule\n".to_string()),
|
||||
("null_byte", "module m;\n logic a; // \0 embedded\nendmodule\n".to_string()),
|
||||
("tab_and_form_feed", "module m;\n\t\u{c}logic a;\nendmodule\n".to_string()),
|
||||
];
|
||||
let total = cases.len();
|
||||
let mut failures = Vec::new();
|
||||
for (name, text) in cases {
|
||||
let path = PathBuf::from(format!("/w/{name}.sv"));
|
||||
let doc = Document::new(Some(path.clone()), text.clone(), &empty);
|
||||
let from_buffer = doc.facts(path.clone()).encode();
|
||||
let from_text = FileFacts::of(path.clone(), &text).encode();
|
||||
if from_buffer != from_text {
|
||||
failures
|
||||
.push(format!("FACTS DRIFT in {name}: buffer={from_buffer:?} text={from_text:?}"));
|
||||
}
|
||||
let mut wb = doc.words();
|
||||
let mut wt = crate::candidates::words_of_tokens(&tokenize(&text).unwrap_or_default());
|
||||
wb.sort();
|
||||
wt.sort();
|
||||
if wb != wt {
|
||||
failures.push(format!("WORDS DRIFT in {name}: buffer={wb:?} text={wt:?}"));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "drift found:\n{}", failures.join("\n"));
|
||||
eprintln!("qa attack: {total} crafted non-corpus shapes, no drift found");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() {
|
||||
// The one buffer whose held analysis is not an analysis of its text —
|
||||
// it is the analysis of the empty file. Such a buffer contributes
|
||||
// nothing to the index at all, which is what keeps the reuse from ever
|
||||
// meeting it: it is absent from the work list, so it is absent from
|
||||
// every list a rescan reports.
|
||||
let tree = Tree::new("openfactslarge");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let big = format!(
|
||||
"package big_pkg;\n localparam K = 1;\n{}endpackage\n",
|
||||
" // filler\n".repeat(200)
|
||||
);
|
||||
tree.write("rtl/big.sv", &big);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(ClientSettings {
|
||||
large_file_threshold: 100,
|
||||
..Default::default()
|
||||
}));
|
||||
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
let uri = crate::uri::path_to_uri(&tree.path.join("rtl/big.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), big);
|
||||
assert!(ws.document(&uri).expect("open").large, "premise: the fast path");
|
||||
|
||||
let seen = scan(&mut ws, None);
|
||||
assert!(seen.analyzed.is_empty(), "nothing came from an analysis: {seen:?}");
|
||||
assert_eq!(seen.parsed, ["a.sv"], "and the big buffer is on no list at all: {seen:?}");
|
||||
assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg"], "nor in the index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_unsaved_edits_win_then_close_reverts_to_disk_on_the_next_rescan() {
|
||||
// Charter attack 2 (staleness). An open buffer's *unsaved* edits must
|
||||
// win a rescan (the whole reason the reuse is sound even though the
|
||||
// content-keyed cache has nothing to key unsaved bytes by), and
|
||||
// closing the buffer without saving must let the next rescan see disk
|
||||
// again — nothing about the buffer's now-gone analysis may linger.
|
||||
let tree = Tree::new("qastaleness");
|
||||
tree.write("rtl/p.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n");
|
||||
let path = tree.path.join("rtl/p.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk's member");
|
||||
|
||||
// Open the buffer and edit it — never saved, so disk still says
|
||||
// `ON_DISK` — then rescan.
|
||||
ws.set_document(uri.clone(), "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "the live buffer's own analysis went in: {seen:?}");
|
||||
assert!(seen.parsed.is_empty() && seen.cached.is_empty(), "{seen:?}");
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "the live edit is indexed");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk's stale member is gone");
|
||||
|
||||
// Close without saving. Disk still says `ON_DISK`; the buffer's
|
||||
// analysis of `IN_BUFFER` no longer exists anywhere to be reused.
|
||||
ws.close_document(&uri);
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.parsed, ["p.sv"], "reparsed from disk, not reused: {seen:?}");
|
||||
assert!(seen.analyzed.is_empty(), "no buffer left to analyze from: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "back to disk's member");
|
||||
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the unsaved edit is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() {
|
||||
// Charter attack 3 (large-file path), the direction the dev's own
|
||||
// test does not cover: small **on disk**, edited **huge in the
|
||||
// buffer** without saving. `doc.large` is re-decided on every
|
||||
// `set_document`, so the very next rescan must drop the buffer from
|
||||
// the analyzed-reuse route (and from the index) the moment the edit
|
||||
// crosses the threshold — not one rescan later.
|
||||
let tree = Tree::new("qathreshgrow");
|
||||
tree.write("rtl/p.sv", "package p;\n localparam SMALL = 1;\nendpackage\n");
|
||||
let path = tree.path.join("rtl/p.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
..Default::default()
|
||||
}));
|
||||
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
|
||||
assert!(!ws.document(&uri).expect("open").large, "premise: a real analysis");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "small buffer reused: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
|
||||
|
||||
// Edited past the threshold, never saved.
|
||||
ws.set_document(uri.clone(), filler(1_000));
|
||||
assert!(ws.document(&uri).expect("open").large, "now on the fast path");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert!(seen.analyzed.is_empty(), "the now-huge buffer offers no analysis: {seen:?}");
|
||||
assert!(seen.parsed.is_empty(), "and disk is not read in its place either: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 0, "contributes nothing at all");
|
||||
|
||||
// And back under the threshold: a real analysis again, reused again.
|
||||
ws.set_document(uri.clone(), "package p;\n localparam SMALL = 1;\nendpackage\n".into());
|
||||
assert!(!ws.document(&uri).expect("open").large, "shrank back");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "reused again: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_buffer_huge_on_disk_shrunk_live_becomes_a_real_analysis_to_reuse() {
|
||||
// The other direction of charter attack 3: **huge on disk** (over the
|
||||
// fast-path threshold if it were read fresh — moot here, since a
|
||||
// buffer's `large` flag is decided from its own live text, never
|
||||
// disk), edited down **small in the buffer**. Included for the
|
||||
// opposite-direction symmetry the brief asks for; the on-disk size is
|
||||
// irrelevant to `doc.large` by construction (`is_large` reads
|
||||
// `text.len()`), so this is really the same claim from the other
|
||||
// starting point.
|
||||
let tree = Tree::new("qathreshshrink");
|
||||
let huge_on_disk = filler(1_000);
|
||||
tree.write("rtl/p.sv", &huge_on_disk);
|
||||
let path = tree.path.join("rtl/p.sv");
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
..Default::default()
|
||||
}));
|
||||
ws.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
// Disk alone: `filler` is real Verilog (`module m; wire a; ...`), well
|
||||
// under no cap, so it is walked and parsed whole — the large-file
|
||||
// threshold applies to *buffers*, not to the walk.
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.parsed, ["p.sv"], "disk copy parsed in full: {seen:?}");
|
||||
|
||||
// Opened as a buffer with that same huge text: the fast path, same as
|
||||
// any buffer over the threshold.
|
||||
ws.set_document(uri.clone(), huge_on_disk);
|
||||
assert!(ws.document(&uri).expect("open").large, "premise: fast path from the live text");
|
||||
|
||||
// Edited down to something small, never saved.
|
||||
ws.set_document(uri.clone(), "package p;\n localparam SHRUNK = 1;\nendpackage\n".into());
|
||||
assert!(!ws.document(&uri).expect("open").large, "back to a real analysis");
|
||||
let seen = scan(&mut ws, None);
|
||||
assert_eq!(seen.analyzed, ["p.sv"], "the shrunk buffer's own analysis is reused: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SHRUNK").len(), 1);
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
//! The persistent index cache (docs/features/index-persistence): what a
|
||||
//! warm scan parses, what the key is, where the store lives, and when it
|
||||
//! is read, written or left exactly as it was found.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A workspace that keeps its cache in `store` and indexes every root.
|
||||
fn cached_workspace(store: &Path) -> Workspace {
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(wide(caching(store)));
|
||||
ws
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_session_over_the_same_store_parses_nothing_it_parsed_before() {
|
||||
let tree = Tree::new("cachewarm");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
tree.package("b.sv", "b_pkg");
|
||||
let store = Tree::new("cachewarm_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
let first = scan(&mut cold, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(first.parsed, ["a.sv", "b.sv"], "a cold scan parses everything");
|
||||
assert!(first.cached.is_empty(), "{first:?}");
|
||||
let fingerprint = cold.index().fingerprint();
|
||||
|
||||
// A whole new server over the same tree and the same store — which is
|
||||
// what reopening the editor is.
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert!(second.parsed.is_empty(), "a warm scan parses nothing: {second:?}");
|
||||
assert_eq!(second.cached, ["a.sv", "b.sv"]);
|
||||
assert_eq!(
|
||||
warm.index().fingerprint(),
|
||||
fingerprint,
|
||||
"and the index it built is the index the parses built"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_half_warm_scan_parses_exactly_what_the_store_cannot_answer_for() {
|
||||
// The resume case, which is the whole feature: a store holding some
|
||||
// of the workspace — because the last session was killed halfway, or
|
||||
// because files have changed since — costs exactly the files it does
|
||||
// not answer for, and nothing else.
|
||||
let tree = Tree::new("cachehalf");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
tree.package("b.sv", "b_pkg");
|
||||
let store = Tree::new("cachehalf_store");
|
||||
|
||||
let mut first = cached_workspace(&store.path);
|
||||
scan(&mut first, Some(vec![tree.path.clone()]));
|
||||
|
||||
tree.package("b.sv", "b_renamed_pkg"); // changed since
|
||||
tree.package("c.sv", "c_pkg"); // never seen
|
||||
let mut second = cached_workspace(&store.path);
|
||||
let half = scan(&mut second, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(half.cached, ["a.sv"], "only the untouched file: {half:?}");
|
||||
assert_eq!(half.parsed, ["b.sv", "c.sv"]);
|
||||
|
||||
let mut fresh = Workspace::default();
|
||||
fresh.set_client_settings(wide(ClientSettings::default()));
|
||||
fresh.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
second.index().fingerprint(),
|
||||
fresh.index().fingerprint(),
|
||||
"a half-cached index is the index a cacheless scan would have built"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_is_the_content_and_only_the_content() {
|
||||
// Both directions of "no timestamp is trusted": a file rewritten with
|
||||
// the same bytes still hits (its modification time moved and nothing
|
||||
// else did), and a file rewritten with *different* bytes of the same
|
||||
// length misses. A cache keyed on size and mtime would get both of
|
||||
// these exactly the wrong way round.
|
||||
let tree = Tree::new("cachekey");
|
||||
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
|
||||
let store = Tree::new("cachekey_store");
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
|
||||
tree.write("a.sv", "package a_pkg;\n localparam K = 1;\nendpackage\n");
|
||||
let touched = scan(&mut ws, None);
|
||||
assert_eq!(touched.cached, ["a.sv"], "the same bytes are the same file: {touched:?}");
|
||||
|
||||
tree.write("a.sv", "package a_pkg;\n localparam K = 2;\nendpackage\n");
|
||||
let changed = scan(&mut ws, None);
|
||||
assert_eq!(changed.parsed, ["a.sv"], "one byte of difference is a miss: {changed:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cache_never_puts_back_a_file_the_scan_no_longer_visits() {
|
||||
// A record is not a file. The scope ladder decides what is walked;
|
||||
// the cache only ever answers *for* something already on the work
|
||||
// list, so a session whose scope has narrowed has an index that
|
||||
// narrowed with it, records or no records.
|
||||
let tree = Tree::new("cachescope");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("tb/b.sv", "b_pkg");
|
||||
let store = Tree::new("cachescope_store");
|
||||
|
||||
let mut wide_session = cached_workspace(&store.path);
|
||||
scan(&mut wide_session, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(indexed(&wide_session, &["a_pkg", "b_pkg"]), ["a_pkg", "b_pkg"]);
|
||||
|
||||
// The next session is folder-scoped and only ever opens a file in
|
||||
// `rtl/`, so `tb/` is not walked at all.
|
||||
let mut narrow = Workspace::default();
|
||||
narrow.set_client_settings(caching(&store.path));
|
||||
narrow.open_roots_with(vec![tree.path.clone()], &mut |_| {});
|
||||
open(&mut narrow, &tree, "rtl/a.sv");
|
||||
let narrowed = scan(&mut narrow, None);
|
||||
// `rtl/a.sv` is this session's open buffer, so it goes in from the
|
||||
// analysis that buffer already holds rather than from the store —
|
||||
// beside this test's point, and named so the point stays legible:
|
||||
// `tb/b.sv` appears on no list at all.
|
||||
assert_eq!(narrowed.analyzed, ["a.sv"], "{narrowed:?}");
|
||||
assert!(narrowed.parsed.is_empty() && narrowed.cached.is_empty(), "{narrowed:?}");
|
||||
assert_eq!(
|
||||
indexed(&narrow, &["a_pkg", "b_pkg"]),
|
||||
["a_pkg"],
|
||||
"the record for tb/b.sv exists and is still not an indexed file"
|
||||
);
|
||||
}
|
||||
|
||||
/// The store's bytes and its modification time — "not touched" as
|
||||
/// something a test can see rather than infer.
|
||||
fn store_stamp(store: &Path) -> (Vec<u8>, std::time::SystemTime) {
|
||||
let path = store.join("index-cache");
|
||||
let bytes = fs::read(&path).expect("read store");
|
||||
let stamp = fs::metadata(&path).expect("meta").modified().expect("mtime");
|
||||
(bytes, stamp)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_warm_rescan_that_appended_nothing_leaves_the_store_exactly_as_it_found_it() {
|
||||
// §P4b (a) through the workspace: every file hits the store, so the
|
||||
// session appends nothing, so the compaction at the end of the scan
|
||||
// would rewrite the file it read into itself. It does not run, and
|
||||
// the store on disk is not touched — not its bytes, not its mtime.
|
||||
let tree = Tree::new("compactskip");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
tree.package("b.sv", "b_pkg");
|
||||
let store = Tree::new("compactskip_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
scan(&mut cold, Some(vec![tree.path.clone()]));
|
||||
let before = store_stamp(&store.path);
|
||||
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(second.cached, ["a.sv", "b.sv"], "premise: a scan that appends nothing");
|
||||
assert_eq!(store_stamp(&store.path), before, "the store was not rewritten");
|
||||
|
||||
// A third session still reads it, and a file that *did* change still
|
||||
// costs the rewrite that folds its new record in.
|
||||
tree.package("b.sv", "b_renamed_pkg");
|
||||
let mut third = cached_workspace(&store.path);
|
||||
let changed = scan(&mut third, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(changed.parsed, ["b.sv"], "{changed:?}");
|
||||
let after = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert!(after.contains("b_renamed_pkg"), "the changed file's record landed");
|
||||
assert_eq!(after.lines().count(), 3, "and the store is one line per path: {after}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_with_no_files_neither_reads_the_store_nor_rewrites_it() {
|
||||
// §P4b (b1). `Server::started` builds the index at the **default**
|
||||
// settings, before `workspace/configuration` can even be asked — and
|
||||
// the folder scope is derived from the directories a buffer has been
|
||||
// opened from, of which there are none, so that scan's work list is
|
||||
// empty. Warm it still opened a 44 MiB store and rewrote it
|
||||
// byte-identically: 184 ms of a 1.33 s start, for a scan that indexes
|
||||
// nothing (`docs/features/perf5-p4/README.md`).
|
||||
let tree = Tree::new("emptyscan");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("rtl/b.sv", "b_pkg");
|
||||
let store = Tree::new("emptyscan_store");
|
||||
|
||||
let mut filling = cached_workspace(&store.path);
|
||||
scan(&mut filling, Some(vec![tree.path.clone()]));
|
||||
let before = store_stamp(&store.path);
|
||||
|
||||
// The startup shape: the folder scope, no buffer open.
|
||||
let mut empty = Workspace::default();
|
||||
empty.set_client_settings(caching(&store.path));
|
||||
empty.adopt_roots(vec![tree.path.clone()]);
|
||||
let nothing = scan(&mut empty, None);
|
||||
assert_eq!(nothing, Scan::default(), "premise: this scan indexes no file");
|
||||
assert_eq!(store_stamp(&store.path), before, "so the store is neither read nor written");
|
||||
|
||||
// And the widen the first `didOpen` triggers still hits every record
|
||||
// the store holds — the open was deferred to the first file that
|
||||
// wants it, not dropped.
|
||||
let opened = tree.path.join("rtl/a.sv");
|
||||
let uri = crate::uri::path_to_uri(&opened).expect("uri");
|
||||
empty.set_document(uri, fs::read_to_string(&opened).expect("read"));
|
||||
let added: Vec<PathBuf> = empty.scope_dirs();
|
||||
assert_eq!(added, vec![tree.path.join("rtl")], "premise: the open widened the scope");
|
||||
let mut widened = Scan::default();
|
||||
empty.widen_index_with(&added, &mut |event| match event {
|
||||
IndexEvent::Parsing { path, .. } => widened.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => widened.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => widened.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
});
|
||||
assert_eq!(widened.analyzed, ["a.sv"], "the open buffer indexes itself: {widened:?}");
|
||||
assert_eq!(widened.cached, ["b.sv"], "the widen reads the store the scan left: {widened:?}");
|
||||
assert!(widened.parsed.is_empty(), "not one file reparsed: {widened:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cold_session_that_indexes_nothing_creates_no_store_at_all() {
|
||||
// The same rule the other way up: with no store yet and no file to
|
||||
// index, nothing is created — no directory, no `.gitignore`, no
|
||||
// header-only store — and the session that *does* index a file makes
|
||||
// all three.
|
||||
let tree = Tree::new("emptycold");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let store = Tree::new("emptycold_store");
|
||||
let dir = store.path.join("inner");
|
||||
|
||||
let mut empty = Workspace::default();
|
||||
empty.set_client_settings(caching(&dir));
|
||||
empty.adopt_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(scan(&mut empty, None), Scan::default(), "premise");
|
||||
assert!(!dir.exists(), "a scan with no files creates no cache directory");
|
||||
|
||||
let mut indexing = cached_workspace(&dir);
|
||||
scan(&mut indexing, Some(vec![tree.path.clone()]));
|
||||
assert!(dir.join("index-cache").exists(), "and a scan with files still writes one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_off_reads_nothing_and_writes_nothing() {
|
||||
let tree = Tree::new("cacheoff");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let store = Tree::new("cacheoff_store");
|
||||
|
||||
// Nothing is written while it is off…
|
||||
let mut off = Workspace::default();
|
||||
off.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
scan(&mut off, Some(vec![tree.path.clone()]));
|
||||
assert!(!store.path.join("index-cache").exists(), "persist: false must not write");
|
||||
|
||||
// …and a store that already exists is not read when it goes off.
|
||||
let mut on = cached_workspace(&store.path);
|
||||
scan(&mut on, Some(vec![tree.path.clone()]));
|
||||
assert!(store.path.join("index-cache").exists(), "premise: a store to ignore");
|
||||
let mut ignoring = Workspace::default();
|
||||
ignoring
|
||||
.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
let scanned = scan(&mut ignoring, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(scanned.parsed, ["a.sv"], "persist: false must not read: {scanned:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_persistence_off_mid_session_stops_the_write_through_at_once() {
|
||||
// A save takes the incremental path, which writes its record through
|
||||
// without any rescan — so `persist: false` has to reach it the moment
|
||||
// it lands, not at the next scan.
|
||||
let tree = Tree::new("cachemidsession");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let store = Tree::new("cachemidsession_store");
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
tree.package("a.sv", "a_pkg_v2");
|
||||
assert!(ws.update_one(&tree.path.join("a.sv")), "premise: the fast path took it");
|
||||
let after_save = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert!(after_save.contains("a_pkg_v2"), "a save writes its record through");
|
||||
|
||||
ws.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
tree.package("a.sv", "a_pkg_v3");
|
||||
assert!(ws.update_one(&tree.path.join("a.sv")));
|
||||
let after_off = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert_eq!(after_off, after_save, "nothing more is written once it is off");
|
||||
}
|
||||
|
||||
/// QA (2026-08-27), the no-mtime deviation's save-path half: the
|
||||
/// write-through on `update_one` must key its record on the *buffer's*
|
||||
/// bytes, never on what happens to be on disk — that is the argument the
|
||||
/// README gives for why a stored `(size, mtime)` would have been unsound
|
||||
/// (a save's text can come from an unsaved buffer). Constructed
|
||||
/// directly: open a buffer whose text disagrees with the file on disk,
|
||||
/// let the incremental path write its record through, and check the
|
||||
/// store's record is keyed by the *buffer's* hash and holds the
|
||||
/// *buffer's* facts — and that disk's actual bytes, hashed, do not
|
||||
/// match what got written.
|
||||
#[test]
|
||||
fn a_saved_buffers_record_is_keyed_and_filled_from_the_buffer_not_stale_disk() {
|
||||
let tree = Tree::new("cachebuffer");
|
||||
tree.package("a.sv", "a_pkg_on_disk");
|
||||
let store = Tree::new("cachebuffer_store");
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
|
||||
// The buffer disagrees with disk — as it does the moment a user
|
||||
// types, before the editor's next `didSave` reaches disk at all.
|
||||
let path = tree.path.join("a.sv");
|
||||
let buffer_text = "package a_pkg_in_buffer;\n localparam K = 1;\nendpackage\n";
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri, buffer_text.to_string());
|
||||
assert!(ws.update_one(&path), "premise: the fast path took it");
|
||||
|
||||
// The append log still holds the earlier, disk-keyed line too — it is
|
||||
// not rewritten until the next whole-scan compaction — so the write
|
||||
// itself is checked by what it added, and the *effective* record
|
||||
// (what `open` resolves a repeated path to: the last line wins) is
|
||||
// checked separately below, which is the property that actually
|
||||
// matters for correctness.
|
||||
let store_text = fs::read_to_string(store.path.join("index-cache")).expect("a store");
|
||||
assert!(
|
||||
store_text.contains("a_pkg_in_buffer"),
|
||||
"the write-through must have appended the buffer's facts: {store_text}"
|
||||
);
|
||||
let buffer_hash = lucisv_core::cache::content_hash(buffer_text.as_bytes());
|
||||
assert!(
|
||||
store_text.contains(&format!("{buffer_hash:016x}")),
|
||||
"the appended record's key is the buffer's content hash: {store_text}"
|
||||
);
|
||||
|
||||
let disk_text = fs::read_to_string(&path).expect("disk");
|
||||
let disk_hash = lucisv_core::cache::content_hash(disk_text.as_bytes());
|
||||
assert_ne!(disk_hash, buffer_hash, "premise: disk and buffer really do disagree");
|
||||
|
||||
let reopened = IndexCache::open(Some(store.path.clone()));
|
||||
assert_eq!(
|
||||
reopened.facts_for(&path, buffer_text),
|
||||
Some(FileFacts::of(path.clone(), buffer_text)),
|
||||
"the record a fresh session resolves to is the buffer's, not disk's stale one"
|
||||
);
|
||||
assert!(
|
||||
reopened.facts_for(&path, &disk_text).is_none(),
|
||||
"disk's own current bytes must not hit — no record was ever keyed on them"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_cache_path_beats_the_editors_storage_folder() {
|
||||
// Rung 1 over rung 2 of `index_cache::cache_dir`'s ladder, through
|
||||
// the workspace rather than against the function: the store lands
|
||||
// where the *setting* says, and the editor's folder is left alone.
|
||||
let tree = Tree::new("cacheladder");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let storage = Tree::new("cacheladder_storage");
|
||||
let configured = Tree::new("cacheladder_configured");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_storage_path(Some(storage.path.clone()));
|
||||
ws.set_client_settings(wide(caching(&configured.path)));
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
assert!(configured.path.join("index-cache").exists(), "the setting won");
|
||||
assert!(!storage.path.join("index-cache").exists(), "the editor's folder is untouched");
|
||||
|
||||
// Unset it and the editor's folder is what is left standing — on the
|
||||
// next scan, which is when the store is re-opened.
|
||||
ws.set_client_settings(wide(ClientSettings::default()));
|
||||
ws.set_storage_path(Some(storage.path.clone()));
|
||||
scan(&mut ws, None);
|
||||
assert!(storage.path.join("index-cache").exists(), "and now the editor's folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_storage_folder_that_does_not_exist_yet_is_made_on_demand() {
|
||||
// What VS Code hands over: `context.storageUri` names a folder the
|
||||
// editor has not necessarily created.
|
||||
let tree = Tree::new("cachemkdir");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let storage = Tree::new("cachemkdir_storage");
|
||||
let nested = storage.path.join("deep/inner");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_storage_path(Some(nested.clone()));
|
||||
ws.set_client_settings(wide(ClientSettings::default()));
|
||||
scan(&mut ws, Some(vec![tree.path.clone()]));
|
||||
assert!(nested.join("index-cache").exists(), "made on demand");
|
||||
|
||||
let mut warm = Workspace::default();
|
||||
warm.set_storage_path(Some(nested));
|
||||
warm.set_client_settings(wide(ClientSettings::default()));
|
||||
let second = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(second.cached, ["a.sv"], "{second:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cached_index_is_the_index_a_fresh_scan_would_have_built_over_the_corpus() {
|
||||
// The paranoid sweep, against the real corpus: every file in, every
|
||||
// file out of the cache, and the two indexes compared observable by
|
||||
// observable through the fingerprint.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let store = Tree::new("cachecorpus_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
let first = scan(&mut cold, Some(vec![corpus.clone()]));
|
||||
assert!(first.parsed.len() > 500, "premise: the corpus was really scanned");
|
||||
assert!(first.cached.is_empty());
|
||||
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let second = scan(&mut warm, Some(vec![corpus]));
|
||||
assert_eq!(second.cached.len(), first.parsed.len(), "every file came back");
|
||||
assert!(second.parsed.is_empty(), "and none was parsed again");
|
||||
assert_eq!(
|
||||
warm.index().fingerprint(),
|
||||
cold.index().fingerprint(),
|
||||
"the cached index is the parsed index, file ids and all"
|
||||
);
|
||||
assert_eq!(warm.index().counts(), cold.index().counts());
|
||||
// The completion tables and the include graph are built from the
|
||||
// files' text either way, so they cannot drift — pinned rather than
|
||||
// assumed, since the cache is the one thing that skips a file's parse.
|
||||
assert_eq!(warm.candidates().words(""), cold.candidates().words(""));
|
||||
}
|
||||
|
||||
/// QA (2026-08-27), attack surface 1/4, fixed 2026-08-27: the negative
|
||||
/// control the equivalence sweep above cannot run on its own, through the
|
||||
/// whole workspace rather than the store. A record used to be verified
|
||||
/// only against the *file's* content hash, so a line whose hash matched
|
||||
/// `a.sv`'s real bytes but whose facts were altered was a hit and the
|
||||
/// index it produced silently diverged from what a fresh parse gives.
|
||||
/// Every record now carries a checksum of its own facts, so the damaged
|
||||
/// line is dropped: the file is parsed, the scan reports it as parsed
|
||||
/// rather than cached, and the fingerprint is exactly a fresh scan's.
|
||||
/// That is `docs/features/index-persistence`'s "a performance artifact
|
||||
/// and never a correctness input" holding against *accidental* damage of
|
||||
/// any shape; a store deliberately reforged is out of the threat model
|
||||
/// and pinned as such in `index_cache.rs`.
|
||||
#[test]
|
||||
fn a_poisoned_cache_record_is_dropped_and_the_index_is_a_fresh_scans() {
|
||||
let tree = Tree::new("poisonfingerprint");
|
||||
tree.package("a.sv", "a_pkg");
|
||||
let store = Tree::new("poisonfingerprint_store");
|
||||
|
||||
let mut cold = cached_workspace(&store.path);
|
||||
scan(&mut cold, Some(vec![tree.path.clone()]));
|
||||
let honest = cold.index().fingerprint();
|
||||
|
||||
// Hand-tamper the store on disk: keep the header, the hash of `a.sv`'s
|
||||
// *real* bytes and the checksum the genuine record was written with,
|
||||
// but swap in facts a parse of those bytes never produced (a different
|
||||
// package name entirely) — which is what every accidental way a
|
||||
// written record can change looks like from the reader's side.
|
||||
let store_file = store.path.join("index-cache");
|
||||
let text = fs::read_to_string(&store_file).expect("a store");
|
||||
let header_line = text.lines().next().expect("header").to_string();
|
||||
let record = text.lines().nth(1).expect("a record").to_string();
|
||||
let checksum = record.rsplit('\t').next().expect("a checksum field");
|
||||
let real_text = "package a_pkg;\n localparam K = 1;\nendpackage\n";
|
||||
let hash = lucisv_core::cache::content_hash(real_text.as_bytes());
|
||||
let evil = FileFacts::of(
|
||||
tree.path.join("a.sv"),
|
||||
"package poisoned_pkg;\n localparam K = 999;\nendpackage\n",
|
||||
);
|
||||
let poisoned =
|
||||
format!("{header_line}\n{hash:016x}\t{}\t{checksum}\n", evil.encode().expect("encodes"));
|
||||
fs::write(&store_file, poisoned).expect("write");
|
||||
|
||||
let mut warm = cached_workspace(&store.path);
|
||||
let scanned = scan(&mut warm, Some(vec![tree.path.clone()]));
|
||||
assert_eq!(scanned.parsed, ["a.sv"], "the tampered record is dropped: {scanned:?}");
|
||||
assert!(scanned.cached.is_empty(), "and it is not served: {scanned:?}");
|
||||
assert_eq!(
|
||||
warm.index().fingerprint(),
|
||||
honest,
|
||||
"a record whose facts no longer match their checksum cannot reach the index, so \
|
||||
the equivalence sweep's own claim holds against damage as well as staleness"
|
||||
);
|
||||
}
|
||||
|
||||
/// The measurement behind the README's numbers: a scan with no cache at
|
||||
/// all, a cold one that fills the store, a warm one that reads it, and a
|
||||
/// half-warm one with a single file changed.
|
||||
#[test]
|
||||
#[ignore = "measurement, not a test"]
|
||||
fn qa_perf_cold_warm_and_half_warm_scans() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let store = Tree::new("cacheperf_store");
|
||||
let timed = |ws: &mut Workspace| {
|
||||
let started = std::time::Instant::now();
|
||||
let scanned = scan(ws, None);
|
||||
(started.elapsed(), scanned)
|
||||
};
|
||||
|
||||
// The baseline: what a rescan cost before this feature existed.
|
||||
let mut off = Workspace::default();
|
||||
off.set_client_settings(wide(ClientSettings { index_persist: false, ..caching(&store.path) }));
|
||||
scan(&mut off, Some(vec![corpus.clone()]));
|
||||
let (cacheless, _) = timed(&mut off);
|
||||
|
||||
let mut ws = cached_workspace(&store.path);
|
||||
let started = std::time::Instant::now();
|
||||
let cold_scan = scan(&mut ws, Some(vec![corpus.clone()]));
|
||||
let cold = started.elapsed();
|
||||
let (warm, warm_scan) = timed(&mut ws);
|
||||
|
||||
// Half-warm: the store answers for every file but the one edited.
|
||||
let one = ws.index().files()[0].clone();
|
||||
let text = fs::read_to_string(&one).expect("read");
|
||||
fs::write(&one, format!("{text}\n// edited\n")).expect("write");
|
||||
let (half, half_scan) = timed(&mut ws);
|
||||
fs::write(&one, &text).expect("restore");
|
||||
|
||||
let files = ws.index().files().len();
|
||||
eprintln!(
|
||||
"{files} files: no cache {cacheless:?}; cold {cold:?} ({} parsed); \
|
||||
warm {warm:?} ({} cached); half-warm {half:?} ({} parsed, {} cached) — \
|
||||
warm is {:.2}x the cacheless scan",
|
||||
cold_scan.parsed.len(),
|
||||
warm_scan.cached.len(),
|
||||
half_scan.parsed.len(),
|
||||
half_scan.cached.len(),
|
||||
cacheless.as_secs_f64() / warm.as_secs_f64().max(f64::MIN_POSITIVE)
|
||||
);
|
||||
let store_size = fs::metadata(store.path.join("index-cache")).expect("a store").len();
|
||||
eprintln!("store: {store_size} bytes for {files} files");
|
||||
|
||||
// What the key costs, which is the whole argument for keying on
|
||||
// content rather than on a timestamp: the text is read on every scan
|
||||
// anyway (the completion tables and the include graph are built from
|
||||
// it), so the alternative would only ever have saved this.
|
||||
let texts: Vec<String> =
|
||||
ws.index().files().iter().filter_map(|path| fs::read_to_string(path).ok()).collect();
|
||||
let bytes: usize = texts.iter().map(String::len).sum();
|
||||
let started = std::time::Instant::now();
|
||||
let mut sink = 0u64;
|
||||
for text in &texts {
|
||||
sink ^= lucisv_core::cache::content_hash(text.as_bytes());
|
||||
}
|
||||
eprintln!("hashing {bytes} bytes of {files} files: {:?} ({sink:016x})", started.elapsed());
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
//! What the walk takes — source extensions, gitignores, the root config's
|
||||
//! excludes and the client's — and which pushed settings ask for a rescan.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_scan_skips_what_a_gitignore_skips() {
|
||||
let tree = Tree::new("gitignore");
|
||||
tree.write(".gitignore", "generated/\n*_gen.sv\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("generated/netlist.sv", "generated_pkg");
|
||||
tree.package("rtl/top_gen.sv", "gen_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1, "a plain file is indexed");
|
||||
assert_eq!(ws.index().member("generated_pkg", "K").len(), 0, "an ignored directory");
|
||||
assert_eq!(ws.index().member("gen_pkg", "K").len(), 0, "an ignored name, at depth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scan_honours_the_root_configs_excludes() {
|
||||
let tree = Tree::new("excludes");
|
||||
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("vendor/ip.sv", "vendor_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1);
|
||||
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "lucisv.toml excludes apply");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_root_config_does_not_stop_the_scan() {
|
||||
// Exit 2 is the CLI's answer to a broken config; a server that indexed
|
||||
// nothing because of a typo would look simply broken instead.
|
||||
let tree = Tree::new("brokencfg");
|
||||
tree.write("lucisv.toml", "bogus = 1\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_hides_files_from_the_index() {
|
||||
let tree = Tree::new("clientexclude");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("scratch/wip.sv", "scratch_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 1, "premise: indexed at first");
|
||||
|
||||
assert!(ws.set_client_settings(wide(excluding(&["scratch"]))), "an exclude change rescans");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
|
||||
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "the excluded one is gone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
|
||||
// The failure this guards: a user setting `lucisv.exclude` in their
|
||||
// editor and thereby putting the project's vendored code — which the
|
||||
// checked-in `lucisv.toml` excludes — back into the index for them only.
|
||||
let tree = Tree::new("bothexcludes");
|
||||
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
|
||||
tree.package("kept.sv", "kept");
|
||||
tree.package("vendor/ip.sv", "vendor_pkg");
|
||||
tree.package("scratch/wip.sv", "scratch_pkg");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(excluding(&["scratch"]));
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
|
||||
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "the config's exclude holds");
|
||||
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "and the pushed one applies");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_an_exclude_change_asks_for_a_rescan() {
|
||||
// `lineLength` and `indent` are read afresh by every formatting
|
||||
// request, so re-walking the workspace for them would be pure cost.
|
||||
let mut ws = Workspace::default();
|
||||
assert!(!ws.set_client_settings(ClientSettings::default()), "nothing changed");
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings {
|
||||
line_length: Some(120),
|
||||
indent: Some(4),
|
||||
..Default::default()
|
||||
}),
|
||||
"widths do not move files"
|
||||
);
|
||||
// QA (2026-08-26): `format_on_save` is read afresh by
|
||||
// `will_save_wait_until` exactly as `indent`/`lineLength` are by
|
||||
// `formatting` — it must not ask for a rescan either, or every
|
||||
// `lucisv.formatOnSave` toggle would pay for a full re-walk (and, on
|
||||
// a client that pulls, bump the diagnostics generation along with
|
||||
// it).
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings { format_on_save: true, ..Default::default() }),
|
||||
"turning the save hook on does not move files either"
|
||||
);
|
||||
// The file log changes how loudly a rescan narrates itself and nothing
|
||||
// about which files exist, so it must not buy one.
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings { log_files: false, ..Default::default() }),
|
||||
"turning the per-file log off does not move files either"
|
||||
);
|
||||
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
|
||||
// The cap does move files, so it does.
|
||||
assert!(
|
||||
ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["a".to_string()],
|
||||
max_file_size: 4096,
|
||||
..Default::default()
|
||||
}),
|
||||
"a new cap rescans"
|
||||
);
|
||||
assert!(
|
||||
!ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["a".to_string()],
|
||||
max_file_size: 4096,
|
||||
log_files: false,
|
||||
..Default::default()
|
||||
}),
|
||||
"the same cap with a different log setting does not"
|
||||
);
|
||||
assert!(
|
||||
ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["a".to_string()],
|
||||
log_files: false,
|
||||
..Default::default()
|
||||
}),
|
||||
"and going back to the default cap does"
|
||||
);
|
||||
ws.set_client_settings(excluding(&["a"]));
|
||||
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
|
||||
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_filelist_change_asks_for_a_rescan_too() {
|
||||
// It changes which files exist as far as this server is concerned,
|
||||
// which is the whole test for whether a rescan is owed.
|
||||
let mut ws = Workspace::default();
|
||||
assert!(ws.set_client_settings(using_filelist("files.f")), "a new filelist rescans");
|
||||
assert!(!ws.set_client_settings(using_filelist("files.f")), "the same one does not");
|
||||
assert!(ws.set_client_settings(using_filelist("other.f")), "a different one does");
|
||||
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_pushed_settings_are_readable_where_formatting_needs_them() {
|
||||
let mut ws = Workspace::default();
|
||||
assert_eq!(ws.client_settings(), &ClientSettings::default(), "default until pushed");
|
||||
ws.set_client_settings(ClientSettings {
|
||||
line_length: Some(120),
|
||||
indent: Some(4),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(ws.client_settings().indent, Some(4));
|
||||
assert_eq!(ws.client_settings().line_length, Some(120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scan_takes_only_source_extensions() {
|
||||
let tree = Tree::new("extensions");
|
||||
tree.package("a.sv", "a");
|
||||
tree.package("b.v", "b");
|
||||
tree.package("c.svh", "c");
|
||||
tree.package("d.vh", "d");
|
||||
tree.package("e.txt", "e");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
for name in ["a", "b", "c", "d"] {
|
||||
assert_eq!(ws.index().member(name, "K").len(), 1, "{name} is a source file");
|
||||
}
|
||||
assert_eq!(ws.index().member("e", "K").len(), 0, "a .txt is not");
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
//! `lucisv.index.maxFileSize`: a walked file over the cap is left out of
|
||||
//! the index, an open buffer never is, and every skip is reported with its
|
||||
//! size and the cap.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_walked_file_over_the_cap_is_left_out_of_the_index() {
|
||||
let tree = Tree::new("capskip");
|
||||
tree.package("small.sv", "small_pkg");
|
||||
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(
|
||||
indexed(&ws, &["small_pkg", "netlist_pkg"]),
|
||||
["small_pkg"],
|
||||
"the big file is not in the index, and was never read"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_cap_is_a_mebibyte_and_zero_turns_it_off() {
|
||||
// The shipped default, exercised against a file that really is over
|
||||
// 1 MiB — the only way to prove the constant is the one in force.
|
||||
let tree = Tree::new("capdefault");
|
||||
tree.package("small.sv", "small_pkg");
|
||||
fat_package(&tree, "huge.sv", "huge_pkg", 1024 * 1024 + 1);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["small_pkg", "huge_pkg"]), ["small_pkg"], "capped by default");
|
||||
|
||||
// `0` is the client asking for no cap, and must be exactly the
|
||||
// behaviour that existed before there was one.
|
||||
assert!(ws.set_client_settings(wide(capping(0))), "turning the cap off rescans");
|
||||
ws.rebuild_index();
|
||||
assert_eq!(
|
||||
indexed(&ws, &["small_pkg", "huge_pkg"]),
|
||||
["small_pkg", "huge_pkg"],
|
||||
"nothing capped"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_is_indexed_however_big_the_file_is() {
|
||||
// The documented exemption: the cap is about files nobody asked for.
|
||||
// A buffer the user opened is indexed and diagnosed whatever its size,
|
||||
// or the editor would refuse to understand the file on screen.
|
||||
let tree = Tree::new("capbuffer");
|
||||
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
// Whole-workspace scope so the walked file is genuinely capped by the
|
||||
// CAP, not merely unreachable by the folder scope (QA finding,
|
||||
// 2026-08-27, lead-fixed: the premise held for the wrong reason).
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
|
||||
|
||||
let uri = crate::uri::path_to_uri(&tree.path.join("huge.sv")).expect("uri");
|
||||
let text = fs::read_to_string(tree.path.join("huge.sv")).expect("read");
|
||||
ws.set_document(uri, text);
|
||||
ws.rebuild_index();
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "the open buffer is indexed in full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_open_buffer_over_the_cap_is_both_skipped_and_analyzed_unchanged_from_before() {
|
||||
// QA attack (index-scope, 2026-08-28, charter item 4: the cap
|
||||
// boundary). `collect_sources` walks the scope and reports
|
||||
// `Skipped` for every file over `maxFileSize` *before* it knows
|
||||
// whether an open buffer speaks for that path — that ordering is
|
||||
// pre-existing (the `spoken_for` short-circuit this round added only
|
||||
// skips the wasted disk *read*, not the cap check ahead of it). The
|
||||
// question this pins: did routing an open buffer's facts through its
|
||||
// own analysis change that reporting, or the fact that the buffer
|
||||
// still ends up indexed in full? It must not: the file is still
|
||||
// reported `Skipped` once (the disk phase honestly saying the walked
|
||||
// copy is over cap), and it still ends up indexed — now via
|
||||
// `Analyzed` rather than `Parsing`, since the round's whole point is
|
||||
// that an open buffer's own analysis is reused instead of reparsed.
|
||||
let tree = Tree::new("capbufferqa");
|
||||
fat_package(&tree, "huge.sv", "huge_pkg", 4096);
|
||||
let path = tree.path.join("huge.sv");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), Vec::<String>::new(), "premise: capped on disk");
|
||||
|
||||
let uri = crate::uri::path_to_uri(&path).expect("uri");
|
||||
let text = fs::read_to_string(&path).expect("read");
|
||||
ws.set_document(uri, text);
|
||||
|
||||
let mut skipped: Vec<PathBuf> = Vec::new();
|
||||
let mut analyzed: Vec<PathBuf> = Vec::new();
|
||||
let mut parsed: Vec<PathBuf> = Vec::new();
|
||||
ws.rebuild_index_with(&mut |event| match event {
|
||||
IndexEvent::Skipped { path, .. } => skipped.push(path.to_path_buf()),
|
||||
IndexEvent::Analyzed { path, .. } => analyzed.push(path.to_path_buf()),
|
||||
IndexEvent::Parsing { path, .. } => parsed.push(path.to_path_buf()),
|
||||
IndexEvent::Cached { .. } => {}
|
||||
});
|
||||
assert_eq!(skipped, vec![path.clone()], "still reported skipped once, from the disk phase");
|
||||
assert_eq!(analyzed, vec![path.clone()], "and indexed via its own analysis, not reparsed");
|
||||
assert!(parsed.is_empty(), "never re-parsed: {parsed:?}");
|
||||
assert_eq!(indexed(&ws, &["huge_pkg"]), ["huge_pkg"], "still indexed in full, unmoved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_skipped_file_is_reported_with_its_size_and_the_cap() {
|
||||
let tree = Tree::new("capevents");
|
||||
tree.package("small.sv", "small_pkg");
|
||||
fat_package(&tree, "netlist.sv", "netlist_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(capping(1024));
|
||||
let mut skipped: Vec<(PathBuf, u64, u64)> = Vec::new();
|
||||
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
|
||||
if let IndexEvent::Skipped { path, size, cap } = event {
|
||||
skipped.push((path.to_path_buf(), size, cap));
|
||||
}
|
||||
});
|
||||
assert_eq!(skipped.len(), 1, "{skipped:?}");
|
||||
assert_eq!(skipped[0].0, tree.path.join("netlist.sv"));
|
||||
assert!(skipped[0].1 >= 4096, "the file's real size: {skipped:?}");
|
||||
assert_eq!(skipped[0].2, 1024, "and the cap it was measured against");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_watcher_sees_every_file_in_index_order_against_a_total_it_knew_first() {
|
||||
// The denominator is the work list *after* the exclude and the cap:
|
||||
// a bar counting towards a number that included files nobody was
|
||||
// going to parse would stall short of the end every time.
|
||||
let tree = Tree::new("capwatch");
|
||||
tree.package("b.sv", "b");
|
||||
tree.package("a.sv", "a");
|
||||
tree.package("skipped/c.sv", "c");
|
||||
fat_package(&tree, "d.sv", "d_pkg", 4096);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
exclude: vec!["skipped".to_string()],
|
||||
max_file_size: 1024,
|
||||
..Default::default()
|
||||
});
|
||||
let mut seen: Vec<(usize, usize, PathBuf)> = Vec::new();
|
||||
ws.open_whole_workspace_with(vec![tree.path.clone()], &mut |event| {
|
||||
if let IndexEvent::Parsing { done, total, path } = event {
|
||||
seen.push((done, total, path.to_path_buf()));
|
||||
}
|
||||
});
|
||||
assert_eq!(
|
||||
seen,
|
||||
vec![(0, 2, tree.path.join("a.sv")), (1, 2, tree.path.join("b.sv")),],
|
||||
"sorted, excluded and capped files absent, total known from the first event"
|
||||
);
|
||||
assert_eq!(ws.index().files().len(), 2, "and the index holds exactly those");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_cap_changes_nothing_about_the_real_corpus() {
|
||||
// The cap ships on, so the burden is to show it costs an existing
|
||||
// project nothing: the index the default cap builds over `corpus/`
|
||||
// must be the one no cap at all builds. It is — the largest corpus
|
||||
// file is 94 KB, eleven times under the cap — and this test is what
|
||||
// notices if a future corpus, or a future default, changes that.
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
let mut capped = Workspace::default();
|
||||
capped.open_whole_workspace(vec![corpus.clone()]);
|
||||
let mut uncapped = Workspace::default();
|
||||
uncapped.set_client_settings(capping(0));
|
||||
uncapped.open_whole_workspace(vec![corpus]);
|
||||
|
||||
assert_eq!(capped.index().files(), uncapped.index().files(), "the same files, in order");
|
||||
assert_eq!(capped.index().counts(), uncapped.index().counts(), "and the same index");
|
||||
assert!(capped.index().files().len() > 500, "premise: the corpus was really scanned");
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! The closed-file view cache.
|
||||
//!
|
||||
//! Every test below observes the cache the only honest way there is: it
|
||||
//! changes a file on disk *without telling the server*, and asks whether
|
||||
//! the next view still shows the old text. A view that survives such an
|
||||
//! edit was cached; one that does not was re-read. That is a cache and not
|
||||
//! a correctness input, so "still shows the old text" is the expected
|
||||
//! answer everywhere the invalidation list does not name.
|
||||
|
||||
use super::*;
|
||||
use crate::state::views::{MAX_VIEWS, MAX_VIEW_BYTES};
|
||||
|
||||
/// A file with `n` declared modules, so its text is both readable and
|
||||
/// tellable apart.
|
||||
fn versioned(n: usize) -> String {
|
||||
(0..n).map(|k| format!("module m{k};\nendmodule\n")).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_files_text_is_read_once_and_then_reused() {
|
||||
let tree = Tree::new("viewreuse");
|
||||
tree.write("sub.sv", &versioned(1));
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let path = tree.path.join("sub.sv");
|
||||
|
||||
let first = ws.file_view(&path).expect("readable").text.clone();
|
||||
assert!(first.contains("m0"), "premise: the file was read");
|
||||
// Behind the server's back — no didSave, no watcher, no rescan.
|
||||
tree.write("sub.sv", &versioned(2));
|
||||
assert_eq!(
|
||||
ws.file_view(&path).expect("readable").text,
|
||||
first,
|
||||
"the second question about one file costs no second read"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_an_open_buffer_speaks_for_has_no_view_of_its_own() {
|
||||
// The buffer's own `Document` is the authority on its text; a second
|
||||
// copy here would be a second opinion, so there is deliberately none.
|
||||
let tree = Tree::new("viewopen");
|
||||
tree.write("sub.sv", &versioned(1));
|
||||
let path = tree.path.join("sub.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
assert!(ws.file_view(&path).is_some(), "premise: readable while closed");
|
||||
|
||||
ws.set_document(uri(&format!("file://{}", path.display())), versioned(3));
|
||||
assert!(ws.file_view(&path).is_none(), "an open buffer answers for itself");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_way_a_files_text_can_move_drops_its_view() {
|
||||
// The four invalidation points named in `Workspace::file_view`'s doc
|
||||
// comment, each proved by the same experiment: warm the view, change
|
||||
// the file on disk, run the event, and require the next view to be
|
||||
// the new text rather than the held one.
|
||||
let path_uri = |path: &Path| uri(&format!("file://{}", path.display()));
|
||||
|
||||
for event in ["didOpen", "didClose", "update_one", "rebuild"] {
|
||||
let tree = Tree::new(&format!("viewdrop_{event}"));
|
||||
tree.write("sub.sv", &versioned(1));
|
||||
let path = tree.path.join("sub.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let held = ws.file_view(&path).expect("readable").text.clone();
|
||||
tree.write("sub.sv", &versioned(2));
|
||||
assert_eq!(ws.file_view(&path).expect("readable").text, held, "premise: {event}");
|
||||
|
||||
match event {
|
||||
// Opening the file: the buffer takes over, and closing it
|
||||
// again must not hand back the view from before the buffer
|
||||
// existed — it predates every save that buffer made.
|
||||
"didOpen" | "didClose" => {
|
||||
ws.set_document(path_uri(&path), versioned(9));
|
||||
assert!(ws.file_view(&path).is_none(), "open: no view at all");
|
||||
ws.close_document(&path_uri(&path));
|
||||
}
|
||||
"update_one" => {
|
||||
assert!(ws.update_one(&path), "the index holds this file");
|
||||
}
|
||||
"rebuild" => {
|
||||
ws.rebuild_index();
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let after = ws.file_view(&path).expect("readable").text.clone();
|
||||
assert_ne!(after, held, "{event} must drop the held view");
|
||||
assert!(after.contains("m1"), "{event} must serve the file as it is now: {after}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_view_cache_holds_a_handful_of_files_and_a_bounded_amount_of_text() {
|
||||
let tree = Tree::new("viewbound");
|
||||
let paths: Vec<PathBuf> = (0..MAX_VIEWS + 2)
|
||||
.map(|n| {
|
||||
tree.write(&format!("f{n}.sv"), &versioned(n + 1));
|
||||
tree.path.join(format!("f{n}.sv"))
|
||||
})
|
||||
.collect();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
for path in &paths {
|
||||
let _ = ws.file_view(path).expect("readable");
|
||||
}
|
||||
assert_eq!(ws.views.borrow().len(), MAX_VIEWS, "the count bound holds");
|
||||
assert_eq!(
|
||||
ws.views.borrow()[0].path,
|
||||
paths[paths.len() - 1],
|
||||
"newest first, so the oldest is what falls off"
|
||||
);
|
||||
|
||||
// One file bigger than the whole byte budget: it is still cached —
|
||||
// it is exactly the file this cache exists for — and it evicts
|
||||
// everything else rather than being refused.
|
||||
tree.write("huge.sv", &"// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1));
|
||||
let huge = tree.path.join("huge.sv");
|
||||
let _ = ws.file_view(&huge).expect("readable");
|
||||
let views = ws.views.borrow();
|
||||
assert_eq!(views.len(), 1, "a file over the budget holds the cache alone");
|
||||
assert_eq!(views[0].path, huge);
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): the bound test above only ever caches *one* oversized
|
||||
/// file. The "newest is kept whatever it weighs" rule is only a bound —
|
||||
/// not a leak — if a *second* oversized file replaces the first rather
|
||||
/// than piling up beside it, which is the scenario the brief asks for by
|
||||
/// name.
|
||||
#[test]
|
||||
fn a_second_oversized_file_evicts_the_first_rather_than_growing_beside_it() {
|
||||
let tree = Tree::new("viewhugehuge");
|
||||
let filler = "// filler\n".repeat(MAX_VIEW_BYTES / 10 + 1);
|
||||
tree.write("huge_a.sv", &filler);
|
||||
tree.write("huge_b.sv", &filler);
|
||||
let a = tree.path.join("huge_a.sv");
|
||||
let b = tree.path.join("huge_b.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let _ = ws.file_view(&a).expect("readable");
|
||||
assert_eq!(ws.views.borrow().len(), 1, "the first huge file holds the cache alone");
|
||||
let _ = ws.file_view(&b).expect("readable");
|
||||
let views = ws.views.borrow();
|
||||
assert_eq!(views.len(), 1, "the second huge file replaces it rather than growing beside it");
|
||||
assert_eq!(views[0].path, b, "the newest is what survives");
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): `update_one`'s doc comment and the README both say it
|
||||
/// drops *that path's* view and nothing else — the selectivity half of
|
||||
/// the invalidation story, which `every_way_a_files_text_can_move_drops_
|
||||
/// its_view` never exercises because it only ever warms one file's view
|
||||
/// at a time. A regression that widened `update_one` to `views.clear()`
|
||||
/// would still pass every existing test in this file.
|
||||
#[test]
|
||||
fn updating_one_file_leaves_another_files_cached_view_alone() {
|
||||
let tree = Tree::new("viewupdateoneselective");
|
||||
tree.write("a.sv", &versioned(1));
|
||||
tree.write("b.sv", &versioned(1));
|
||||
let a = tree.path.join("a.sv");
|
||||
let b = tree.path.join("b.sv");
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
|
||||
let view_a = ws.file_view(&a).expect("readable").text.clone();
|
||||
let view_b = ws.file_view(&b).expect("readable").text.clone();
|
||||
|
||||
tree.write("a.sv", &versioned(2));
|
||||
tree.write("b.sv", &versioned(2));
|
||||
assert!(ws.update_one(&a), "the index holds a.sv");
|
||||
|
||||
assert_ne!(ws.file_view(&a).expect("readable").text, view_a, "a.sv's view was dropped");
|
||||
assert_eq!(
|
||||
ws.file_view(&b).expect("readable").text,
|
||||
view_b,
|
||||
"b.sv's view must survive a.sv's update — update_one names one path, not the cache"
|
||||
);
|
||||
}
|
||||
|
||||
/// QA (2026-08-28): `cached_view` moves a hit to the front so recency,
|
||||
/// not merely insertion order, decides what falls off — untested until
|
||||
/// now. Warm four files (the cap), touch the oldest again, then add a
|
||||
/// fifth: without the recency reorder the just-touched file would be the
|
||||
/// one to go (it was inserted first), and with it the file nobody has
|
||||
/// asked about since is what goes instead.
|
||||
#[test]
|
||||
fn re_hovering_the_oldest_cached_file_saves_it_from_eviction() {
|
||||
let tree = Tree::new("viewmru");
|
||||
let paths: Vec<PathBuf> = (0..MAX_VIEWS + 1)
|
||||
.map(|n| {
|
||||
tree.write(&format!("f{n}.sv"), &versioned(n + 1));
|
||||
tree.path.join(format!("f{n}.sv"))
|
||||
})
|
||||
.collect();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
// Fill the cache: f0 (oldest) through f3 (newest of the first batch).
|
||||
for path in &paths[..MAX_VIEWS] {
|
||||
let _ = ws.file_view(path).expect("readable");
|
||||
}
|
||||
// Touch the oldest again — it should now count as the most recent.
|
||||
let _ = ws.file_view(&paths[0]).expect("readable");
|
||||
// One more file arrives, forcing an eviction.
|
||||
let _ = ws.file_view(&paths[MAX_VIEWS]).expect("readable");
|
||||
|
||||
let paths_held: std::collections::HashSet<PathBuf> =
|
||||
ws.views.borrow().iter().map(|v| v.path.clone()).collect();
|
||||
assert!(
|
||||
paths_held.contains(&paths[0]),
|
||||
"the file re-hovered a moment ago must survive: {paths_held:?}"
|
||||
);
|
||||
assert!(
|
||||
!paths_held.contains(&paths[1]),
|
||||
"the file nobody has touched since must be what falls off instead: {paths_held:?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,459 @@
|
||||
//! The incremental scope widen (docs/features/index-scope): the tables a
|
||||
//! widen lands are the ones a whole rescan would have left, and it reads
|
||||
//! only the files the new folders brought in.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Everything a widen must leave equal to what a whole rescan leaves: the
|
||||
/// index, all three completion tables, and the include graph.
|
||||
///
|
||||
/// Rendered as strings so a failure names the table that moved rather than
|
||||
/// reporting that two opaque values differ.
|
||||
fn tables(ws: &Workspace) -> Vec<(&'static str, String)> {
|
||||
let units: Vec<String> = ws
|
||||
.candidates()
|
||||
.units("")
|
||||
.iter()
|
||||
.map(|c| format!("{} {:?} {}", c.name, c.kind, c.detail))
|
||||
.collect();
|
||||
let macros: Vec<String> =
|
||||
ws.candidates().macros("").iter().map(|m| format!("{} {}", m.name, m.detail)).collect();
|
||||
vec![
|
||||
("index", ws.index().fingerprint()),
|
||||
("words", format!("{:?}", ws.candidates().words(""))),
|
||||
("units", format!("{units:?}")),
|
||||
("macros", format!("{macros:?}")),
|
||||
("includes", ws.includes().fingerprint()),
|
||||
]
|
||||
}
|
||||
|
||||
fn same_tables(widened: &Workspace, rebuilt: &Workspace, what: &str) {
|
||||
for ((name, left), (_, right)) in tables(widened).into_iter().zip(tables(rebuilt)) {
|
||||
assert_eq!(left, right, "{what}: the {name} table a widen left is not a rebuild's");
|
||||
}
|
||||
}
|
||||
|
||||
/// The directories `open` added to the scope, and the widen that indexes
|
||||
/// them — the two-line spelling of what `server.rs`'s `didOpen` does.
|
||||
fn widen(ws: &mut Workspace, open: impl FnOnce(&mut Workspace)) -> Vec<PathBuf> {
|
||||
let before = ws.scope_dirs();
|
||||
open(ws);
|
||||
let after = ws.scope_dirs();
|
||||
let added: Vec<PathBuf> = after.iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
assert!(!added.is_empty(), "premise: this open widened the scope");
|
||||
ws.widen_index(&added);
|
||||
added
|
||||
}
|
||||
|
||||
/// A two-folder tree with an unsaved edit, a shared header included from
|
||||
/// both halves, and a name declared on each side.
|
||||
fn widen_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("rtl/top.sv", "`include \"defs.svh\"\nmodule top;\n wire a;\nendmodule\n");
|
||||
tree.write("rtl/defs.svh", "`define RTL_W 8\n");
|
||||
tree.package("rtl/rtl_pkg.sv", "rtl_pkg");
|
||||
tree.write("lib/sub.sv", "`include \"lib_defs.svh\"\nmodule sub;\nendmodule\n");
|
||||
tree.write("lib/lib_defs.svh", "`define LIB_W 16\n");
|
||||
tree.package("lib/lib_pkg.sv", "lib_pkg");
|
||||
tree
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_leaves_the_tables_a_whole_rescan_would_have_left() {
|
||||
let tree = widen_tree("widenequal");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let sub = crate::uri::path_to_uri(&tree.path.join("lib/sub.sv")).expect("uri");
|
||||
// The hostile half: the buffer that is already open carries an edit
|
||||
// that is on no disk anywhere when the widen runs. A widen that
|
||||
// indexed only the new folder's files would lose `NEVER_SAVED`, which
|
||||
// is the objection that stopped this shape being taken in round 19.
|
||||
let edited = "module top;\n wire never_saved;\n localparam NEVER_SAVED = 1;\nendmodule\n";
|
||||
let sub_text = fs::read_to_string(tree.path.join("lib/sub.sv")).expect("read");
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
own_folder_only(&mut incremental);
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(top.clone(), edited.to_string());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(incremental.index().files().len(), 3, "premise: the rtl folder alone");
|
||||
widen(&mut incremental, |ws| ws.set_document(sub.clone(), sub_text.clone()));
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
own_folder_only(&mut rebuilt);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(top.clone(), edited.to_string());
|
||||
rebuilt.set_document(sub.clone(), sub_text.clone());
|
||||
rebuilt.rebuild_index();
|
||||
|
||||
assert_eq!(rebuilt.index().files().len(), 6, "premise: both folders");
|
||||
assert_eq!(
|
||||
incremental.candidates().words("never_sav"),
|
||||
["NEVER_SAVED", "never_saved"],
|
||||
"the unsaved edit is in the widened tables"
|
||||
);
|
||||
same_tables(&incremental, &rebuilt, "an unsaved edit across a widen");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_reads_only_the_files_the_new_folders_brought_in() {
|
||||
let tree = widen_tree("widenwork");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let sub_path = tree.path.join("lib/sub.sv");
|
||||
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
|
||||
let sub_text = fs::read_to_string(&sub_path).expect("read");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.set_document(top.clone(), fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r"));
|
||||
ws.rebuild_index();
|
||||
|
||||
let mut seen = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = ws.scope_dirs();
|
||||
ws.set_document(sub.clone(), sub_text);
|
||||
let after = ws.scope_dirs();
|
||||
let added: Vec<PathBuf> =
|
||||
after.iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
ws.widen_index_with(&added, &mut see);
|
||||
}
|
||||
seen.parsed.sort();
|
||||
// The three `rtl/` files are already indexed and are not read again;
|
||||
// the open buffer is refreshed from the analysis it holds, which is
|
||||
// what makes an unsaved edit survive the widen.
|
||||
assert_eq!(seen.parsed, ["lib_defs.svh", "lib_pkg.sv"], "{seen:?}");
|
||||
seen.analyzed.sort();
|
||||
// Both open buffers, not only the newly opened one: every buffer's
|
||||
// held analysis is refreshed, which is what carries an unsaved edit
|
||||
// across a widen.
|
||||
assert_eq!(seen.analyzed, ["sub.sv", "top.sv"], "{seen:?}");
|
||||
assert!(seen.cached.is_empty(), "no cache in this test: {seen:?}");
|
||||
assert!(!seen.parsed.contains(&"top.sv".to_string()), "the old folder is untouched");
|
||||
assert_eq!(ws.index().files().len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_bar_counts_the_new_files_and_not_the_whole_scope() {
|
||||
let tree = widen_tree("widenbar");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let sub_path = tree.path.join("lib/sub.sv");
|
||||
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
|
||||
let sub_text = fs::read_to_string(&sub_path).expect("read");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
own_folder_only(&mut ws);
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.set_document(top, fs::read_to_string(tree.path.join("rtl/top.sv")).expect("r"));
|
||||
ws.rebuild_index();
|
||||
|
||||
let mut totals: Vec<usize> = Vec::new();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { total, .. }
|
||||
| IndexEvent::Cached { total, .. }
|
||||
| IndexEvent::Analyzed { total, .. } => totals.push(total),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = ws.scope_dirs();
|
||||
ws.set_document(sub, sub_text);
|
||||
let added: Vec<PathBuf> =
|
||||
ws.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
ws.widen_index_with(&added, &mut see);
|
||||
}
|
||||
// Two new files plus the two open buffers refreshed — never the six
|
||||
// the scope now holds. A bar that counted the whole scope would crawl.
|
||||
assert_eq!(totals, [4, 4, 4, 4], "the denominator is the widen's own work list");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_into_a_folder_that_contains_the_old_one_indexes_each_file_once() {
|
||||
// A file present in both the old scope portion and the new one: the
|
||||
// added directory is the *parent* of the directory already in scope,
|
||||
// so its walk finds everything the first scan already indexed.
|
||||
let tree = Tree::new("widennested");
|
||||
tree.package("rtl/deep/a.sv", "a_pkg");
|
||||
tree.package("rtl/b.sv", "b_pkg");
|
||||
let deep = crate::uri::path_to_uri(&tree.path.join("rtl/deep/a.sv")).expect("uri");
|
||||
let shallow = crate::uri::path_to_uri(&tree.path.join("rtl/b.sv")).expect("uri");
|
||||
let deep_text = fs::read_to_string(tree.path.join("rtl/deep/a.sv")).expect("read");
|
||||
let shallow_text = fs::read_to_string(tree.path.join("rtl/b.sv")).expect("read");
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
own_folder_only(&mut incremental);
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(deep.clone(), deep_text.clone());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(incremental.index().files().len(), 1, "premise: rtl/deep alone");
|
||||
|
||||
let mut seen = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = incremental.scope_dirs();
|
||||
incremental.set_document(shallow.clone(), shallow_text.clone());
|
||||
let added: Vec<PathBuf> =
|
||||
incremental.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
incremental.widen_index_with(&added, &mut see);
|
||||
}
|
||||
assert!(seen.parsed.is_empty(), "both files speak for themselves: {seen:?}");
|
||||
seen.analyzed.sort();
|
||||
assert_eq!(seen.analyzed, ["a.sv", "b.sv"], "{seen:?}");
|
||||
assert_eq!(incremental.index().files().len(), 2, "a.sv is indexed once, not twice");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
own_folder_only(&mut rebuilt);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(deep, deep_text);
|
||||
rebuilt.set_document(shallow, shallow_text);
|
||||
rebuilt.rebuild_index();
|
||||
same_tables(&incremental, &rebuilt, "a widen into a containing folder");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds() {
|
||||
// opentitan's own shape, and the jump `performance_take2.md` §5b
|
||||
// measured: at the shipped `scopeDepth: 2`, `ip/aes/dv/tb` raises to
|
||||
// `ip/aes`, and the very next file — `ip/aes/rtl/aes.sv` — raises to
|
||||
// `ip`, the *parent* of the directory already in scope. The new scope's
|
||||
// file set is a superset of the old one, so the widen owes the other
|
||||
// blocks and nothing else: `ip/aes`'s own already-indexed files are
|
||||
// never re-read, and the diff that says so is by **file against the
|
||||
// index**, not by folder against the old walk.
|
||||
let tree = Tree::new("widensubsume");
|
||||
tree.package("ip/aes/rtl/aes.sv", "aes_pkg");
|
||||
tree.package("ip/aes/rtl/aes_core.sv", "aes_core_pkg");
|
||||
tree.package("ip/aes/dv/tb/tb.sv", "aes_tb_pkg");
|
||||
tree.package("ip/aes/dv/env/aes_env.sv", "aes_env_pkg");
|
||||
tree.package("ip/kmac/rtl/kmac.sv", "kmac_pkg");
|
||||
tree.package("ip/hmac/rtl/hmac.sv", "hmac_pkg");
|
||||
// Over the cap: not indexed before the widen, so it must not count as
|
||||
// "already there" — it is walked again, skipped again, and reported.
|
||||
tree.write(
|
||||
"ip/kmac/rtl/huge.sv",
|
||||
&format!("package huge_pkg;\n{}endpackage\n", " // pad\n".repeat(200)),
|
||||
);
|
||||
|
||||
let aes = crate::uri::path_to_uri(&tree.path.join("ip/aes/rtl/aes.sv")).expect("uri");
|
||||
let tb = crate::uri::path_to_uri(&tree.path.join("ip/aes/dv/tb/tb.sv")).expect("uri");
|
||||
let aes_text = fs::read_to_string(tree.path.join("ip/aes/rtl/aes.sv")).expect("read");
|
||||
// An unsaved edit in a buffer that is *not* the one being opened: what
|
||||
// makes the equivalence below a real claim rather than a coincidence.
|
||||
let edited_tb =
|
||||
"package aes_tb_pkg;\n localparam K = 1;\n localparam UNSAVED = 2;\nendpackage\n";
|
||||
let settings =
|
||||
ClientSettings { index_scope_depth: 2, max_file_size: 512, ..Default::default() };
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
incremental.set_client_settings(settings.clone());
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(tb.clone(), edited_tb.into());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(
|
||||
incremental.scope_dirs(),
|
||||
[tree.path.join("ip/aes")],
|
||||
"premise: the testbench raises two levels to its own block"
|
||||
);
|
||||
assert_eq!(incremental.index().files().len(), 4, "premise: the block's four files");
|
||||
|
||||
let mut seen = Scan::default();
|
||||
let mut totals: Vec<usize> = Vec::new();
|
||||
let mut skipped: Vec<String> = Vec::new();
|
||||
let added = {
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, total, .. } => {
|
||||
seen.parsed.push(file_name(path));
|
||||
totals.push(total);
|
||||
}
|
||||
IndexEvent::Cached { path, total, .. } => {
|
||||
seen.cached.push(file_name(path));
|
||||
totals.push(total);
|
||||
}
|
||||
IndexEvent::Analyzed { path, total, .. } => {
|
||||
seen.analyzed.push(file_name(path));
|
||||
totals.push(total);
|
||||
}
|
||||
IndexEvent::Skipped { path, .. } => skipped.push(file_name(path)),
|
||||
};
|
||||
let before = incremental.scope_dirs();
|
||||
incremental.set_document(aes.clone(), aes_text.clone());
|
||||
let added: Vec<PathBuf> =
|
||||
incremental.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
incremental.widen_index_with(&added, &mut see);
|
||||
added
|
||||
};
|
||||
assert_eq!(added, [tree.path.join("ip")], "the added directory contains the old scope");
|
||||
seen.parsed.sort();
|
||||
// The two other blocks, and not one file of `ip/aes` — those the index
|
||||
// already holds, and holding them is what the file diff is for.
|
||||
assert_eq!(seen.parsed, ["hmac.sv", "kmac.sv"], "{seen:?}");
|
||||
seen.analyzed.sort();
|
||||
assert_eq!(seen.analyzed, ["aes.sv", "tb.sv"], "both buffers refresh: {seen:?}");
|
||||
assert_eq!(skipped, ["huge.sv"], "the capped file is walked and skipped again");
|
||||
assert_eq!(totals, [4, 4, 4, 4], "the bar counts the two new files and the two buffers");
|
||||
assert_eq!(incremental.index().files().len(), 6, "four held plus two new, never the cap's");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
rebuilt.set_client_settings(settings);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(tb, edited_tb.into());
|
||||
rebuilt.set_document(aes, aes_text);
|
||||
rebuilt.rebuild_index();
|
||||
assert_eq!(rebuilt.index().files().len(), 6, "premise: the same six files");
|
||||
same_tables(&incremental, &rebuilt, "a widen that subsumed the old scope");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it() {
|
||||
// The include graph's own hostile case, and the reason this round
|
||||
// holds each edge as the filesystem answered it: `rtl/top.sv` was
|
||||
// indexed while `lib/` was out of scope, so its `` `include`` into
|
||||
// `lib/` could not be spelled the way the index spells that file. The
|
||||
// widen must re-spell it without re-reading `rtl/top.sv`.
|
||||
let tree = Tree::new("widenspell");
|
||||
tree.write("lib/Shared.svh", "`define SHARED 1\n");
|
||||
// The include is written in the other case, which a case-insensitive
|
||||
// filesystem happily opens; on a case-sensitive one it does not
|
||||
// resolve at all, and both workspaces agree on that too.
|
||||
tree.write("rtl/top.sv", "`include \"../lib/shared.svh\"\nmodule top;\nendmodule\n");
|
||||
tree.package("lib/lib_pkg.sv", "lib_pkg");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let lib = crate::uri::path_to_uri(&tree.path.join("lib/lib_pkg.sv")).expect("uri");
|
||||
let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read");
|
||||
let lib_text = fs::read_to_string(tree.path.join("lib/lib_pkg.sv")).expect("read");
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
own_folder_only(&mut incremental);
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(top.clone(), top_text.clone());
|
||||
incremental.rebuild_index();
|
||||
widen(&mut incremental, |ws| ws.set_document(lib.clone(), lib_text.clone()));
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
own_folder_only(&mut rebuilt);
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(top, top_text);
|
||||
rebuilt.set_document(lib, lib_text);
|
||||
rebuilt.rebuild_index();
|
||||
same_tables(&incremental, &rebuilt, "an include spelled by a file the widen brought in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() {
|
||||
// The one thing a widen takes *out*: a buffer on the large-file fast
|
||||
// path contributes nothing, exactly as `collect_sources` says, so a
|
||||
// file the index holds whose buffer has grown past the threshold is
|
||||
// dropped — the same answer a whole rescan gives.
|
||||
let tree = Tree::new("widenlarge");
|
||||
tree.package("rtl/p.sv", "p_pkg");
|
||||
tree.package("lib/q.sv", "q_pkg");
|
||||
let small = crate::uri::path_to_uri(&tree.path.join("rtl/p.sv")).expect("uri");
|
||||
let other = crate::uri::path_to_uri(&tree.path.join("lib/q.sv")).expect("uri");
|
||||
let other_text = fs::read_to_string(tree.path.join("lib/q.sv")).expect("read");
|
||||
let huge = filler(1_000);
|
||||
|
||||
let mut incremental = Workspace::default();
|
||||
incremental.set_client_settings(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
});
|
||||
incremental.open_roots(vec![tree.path.clone()]);
|
||||
incremental.set_document(small.clone(), "package p_pkg;\nendpackage\n".into());
|
||||
incremental.rebuild_index();
|
||||
assert_eq!(incremental.index().files().len(), 1, "premise: rtl/p.sv is indexed");
|
||||
incremental.set_document(small.clone(), huge.clone());
|
||||
assert!(incremental.document(&small).expect("open").large, "premise: the fast path");
|
||||
widen(&mut incremental, |ws| ws.set_document(other.clone(), other_text.clone()));
|
||||
assert_eq!(
|
||||
incremental.index().files().len(),
|
||||
1,
|
||||
"the grown buffer left as the new folder arrived"
|
||||
);
|
||||
assert!(incremental.index().units("p_pkg").is_empty(), "and its names went with it");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
rebuilt.set_client_settings(ClientSettings {
|
||||
large_file_threshold: 200,
|
||||
index_scope_depth: 0,
|
||||
..Default::default()
|
||||
});
|
||||
rebuilt.open_roots(vec![tree.path.clone()]);
|
||||
rebuilt.set_document(small, huge);
|
||||
rebuilt.set_document(other, other_text);
|
||||
rebuilt.rebuild_index();
|
||||
same_tables(&incremental, &rebuilt, "a buffer over the threshold at widen time");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_persistent_cache_answers_for_the_files_a_widen_brings_in() {
|
||||
let tree = widen_tree("widencache");
|
||||
let store = Tree::new("widencache_store");
|
||||
let sub_path = tree.path.join("lib/sub.sv");
|
||||
let sub = crate::uri::path_to_uri(&sub_path).expect("uri");
|
||||
let sub_text = fs::read_to_string(&sub_path).expect("read");
|
||||
let top = crate::uri::path_to_uri(&tree.path.join("rtl/top.sv")).expect("uri");
|
||||
let top_text = fs::read_to_string(tree.path.join("rtl/top.sv")).expect("read");
|
||||
|
||||
// A first session fills the store with every file of both folders.
|
||||
let mut first = Workspace::default();
|
||||
first.set_client_settings(wide(caching(&store.path)));
|
||||
first.open_roots(vec![tree.path.clone()]);
|
||||
assert_eq!(first.index().files().len(), 6, "premise: the store is filled");
|
||||
|
||||
// A second session, folder-scoped, widens into `lib/`: the files it
|
||||
// brings in come from the store rather than from a parse.
|
||||
let mut second = Workspace::default();
|
||||
second.set_client_settings(caching(&store.path));
|
||||
second.open_roots(vec![tree.path.clone()]);
|
||||
second.set_document(top, top_text);
|
||||
second.rebuild_index();
|
||||
|
||||
let mut seen = Scan::default();
|
||||
{
|
||||
let mut see = |event: IndexEvent| match event {
|
||||
IndexEvent::Parsing { path, .. } => seen.parsed.push(file_name(path)),
|
||||
IndexEvent::Cached { path, .. } => seen.cached.push(file_name(path)),
|
||||
IndexEvent::Analyzed { path, .. } => seen.analyzed.push(file_name(path)),
|
||||
IndexEvent::Skipped { .. } => {}
|
||||
};
|
||||
let before = second.scope_dirs();
|
||||
second.set_document(sub, sub_text);
|
||||
let added: Vec<PathBuf> =
|
||||
second.scope_dirs().iter().filter(|dir| !before.contains(dir)).cloned().collect();
|
||||
second.widen_index_with(&added, &mut see);
|
||||
}
|
||||
seen.cached.sort();
|
||||
assert_eq!(seen.cached, ["lib_defs.svh", "lib_pkg.sv"], "from the store: {seen:?}");
|
||||
assert!(seen.parsed.is_empty(), "nothing was parsed twice: {seen:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_that_adds_nothing_new_still_refreshes_the_open_buffers() {
|
||||
// A widen whose added directory holds no file the index lacks — the
|
||||
// degenerate case, and the one where the open-buffer refresh is the
|
||||
// *whole* of the work. It must still land the buffers' current text.
|
||||
let tree = Tree::new("widenempty");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
fs::create_dir_all(tree.path.join("empty")).expect("dir");
|
||||
let a = crate::uri::path_to_uri(&tree.path.join("rtl/a.sv")).expect("uri");
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_roots(vec![tree.path.clone()]);
|
||||
ws.set_document(a.clone(), "package a_pkg;\n localparam K = 1;\nendpackage\n".into());
|
||||
ws.rebuild_index();
|
||||
ws.set_document(a, "package a_pkg;\n localparam EDITED = 1;\nendpackage\n".into());
|
||||
|
||||
ws.widen_index(from_ref(&tree.path.join("empty")));
|
||||
assert_eq!(ws.index().member("a_pkg", "EDITED").len(), 1, "the live edit is indexed");
|
||||
assert_eq!(ws.index().member("a_pkg", "K").len(), 0);
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The closed-file view cache: the last few files an answer needed the
|
||||
//! text of, held with their line index so that answering twice about one
|
||||
//! file reads it once — and every rule that drops an entry.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use super::Workspace;
|
||||
|
||||
/// One **closed** workspace file's text and the line index over it, held by
|
||||
/// [`Workspace`] just long enough that answering twice about the same file
|
||||
/// reads it once.
|
||||
///
|
||||
/// Only closed files: an open buffer's own `Document` is the authority on its
|
||||
/// text, and caching a second copy of it would be a way for the two to
|
||||
/// disagree.
|
||||
pub struct FileView {
|
||||
/// The file this view was read from.
|
||||
pub path: PathBuf,
|
||||
/// Its text, as it was on disk when the view was made.
|
||||
pub text: String,
|
||||
/// The line index over exactly that text.
|
||||
pub lines: LineIndex,
|
||||
}
|
||||
|
||||
/// How many closed files the view cache holds, and how much text they may add
|
||||
/// up to.
|
||||
///
|
||||
/// Two bounds, because they answer two different questions. `MAX_VIEWS` is how
|
||||
/// many files one answer can name — a hover card names one or two, a
|
||||
/// references list walks a handful before it moves on — and four is a handful.
|
||||
/// `MAX_VIEW_BYTES` is the memory question, and it exists because the file
|
||||
/// this cache is *for* can be tens of megabytes on its own: without it, four
|
||||
/// netlists would be half a gigabyte of server. The newest view is kept
|
||||
/// whatever it weighs, so a single huge file simply evicts everything else
|
||||
/// rather than refusing to be cached at all.
|
||||
pub(super) const MAX_VIEWS: usize = 4;
|
||||
pub(super) const MAX_VIEW_BYTES: usize = 8 * 1024 * 1024;
|
||||
|
||||
impl Workspace {
|
||||
/// One **closed** file's text and line index, read at most once per file
|
||||
/// per generation of that file.
|
||||
///
|
||||
/// `None` for a file that cannot be read, and — deliberately — for one an
|
||||
/// open buffer speaks for: that buffer's `Document` already holds both,
|
||||
/// and a second copy here would be a second opinion. Callers that want
|
||||
/// "whichever text is authoritative" ask `document_for_path` first, as
|
||||
/// `locate` does.
|
||||
///
|
||||
/// **A cache, never a correctness input.** Every entry is dropped the
|
||||
/// moment anything could have moved the file's text under it, and there
|
||||
/// are exactly four such moments:
|
||||
///
|
||||
/// * [`Workspace::set_document`] — a `didOpen`/`didChange`/`didSave` for
|
||||
/// that path; the buffer becomes the authority and the disk copy is no
|
||||
/// longer what a reader wants;
|
||||
/// * [`Workspace::close_document`] — the buffer stops being the authority,
|
||||
/// and whatever was cached for that path predates the edits it may have
|
||||
/// saved;
|
||||
/// * [`Workspace::update_one`] — one file re-indexed, which is exactly the
|
||||
/// claim that its bytes changed;
|
||||
/// * [`Workspace::rebuild_index_with`] — a whole rescan, which claims
|
||||
/// nothing about *which* file moved, so the whole cache goes;
|
||||
/// * [`Workspace::begin_widen`] — a scope widen, which *does* name the
|
||||
/// files it is about to read, so it drops those and leaves the rest.
|
||||
///
|
||||
/// What survives all four is a file changed on disk with nothing telling
|
||||
/// this server so — and there the index's own spans are stale by the same
|
||||
/// event, which is what `hover`'s `spells_exactly` guard exists for: a
|
||||
/// stale view can only ever *omit* a snippet, never show a wrong line.
|
||||
pub fn file_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
if self.document_for_path(path).is_some() {
|
||||
return None;
|
||||
}
|
||||
if let Some(hit) = self.cached_view(path) {
|
||||
return Some(hit);
|
||||
}
|
||||
let text = fs::read_to_string(path).ok()?;
|
||||
let view =
|
||||
Rc::new(FileView { path: path.to_path_buf(), lines: LineIndex::new(&text), text });
|
||||
let mut views = self.views.borrow_mut();
|
||||
views.insert(0, Rc::clone(&view));
|
||||
trim_views(&mut views);
|
||||
Some(view)
|
||||
}
|
||||
|
||||
/// The files the view cache is holding, newest first.
|
||||
///
|
||||
/// Test-only, and it exists for one question: whether an answer read a
|
||||
/// file at all. A `Location` computed from the index alone must leave this
|
||||
/// empty, which is the whole point of `locate::definition_location` — see
|
||||
/// `docs/features/lazy-code-action/README.md`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn held_views(&self) -> Vec<PathBuf> {
|
||||
self.views.borrow().iter().map(|view| view.path.clone()).collect()
|
||||
}
|
||||
|
||||
/// The held view for `path`, moved to the front so the bounds below drop
|
||||
/// whatever has gone longest unused.
|
||||
fn cached_view(&self, path: &Path) -> Option<Rc<FileView>> {
|
||||
let mut views = self.views.borrow_mut();
|
||||
let at = views.iter().position(|view| view.path == path)?;
|
||||
views[..=at].rotate_right(1);
|
||||
views.first().cloned()
|
||||
}
|
||||
|
||||
/// Drop whatever is held for one file. Called wherever that file's text
|
||||
/// may have moved; see [`Workspace::file_view`] for the list.
|
||||
pub(super) fn forget_view(&mut self, path: &Path) {
|
||||
self.views.borrow_mut().retain(|view| view.path != path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Cut the view cache back to its two bounds, newest first.
|
||||
///
|
||||
/// The newest view is kept whatever it weighs: one netlist-shaped file can
|
||||
/// exceed the whole byte budget on its own, and a cache that refused to hold
|
||||
/// it would be useless for exactly the file it exists for.
|
||||
fn trim_views(views: &mut Vec<Rc<FileView>>) {
|
||||
let mut bytes = 0usize;
|
||||
let mut kept = 0usize;
|
||||
for view in views.iter() {
|
||||
bytes += view.text.len();
|
||||
if kept == MAX_VIEWS || (kept > 0 && bytes > MAX_VIEW_BYTES) {
|
||||
break;
|
||||
}
|
||||
kept += 1;
|
||||
}
|
||||
views.truncate(kept);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
# decomposition-state — TODO §55: `lucisv_server/src/state/mod.rs`
|
||||
|
||||
## Goal
|
||||
|
||||
Split the one file every workspace-state lane collides in —
|
||||
`crates/lucisv_server/src/state/mod.rs`, 5 941 lines: 986 production
|
||||
(non-blank, non-comment) in one 1 600-line `impl Workspace`, plus a
|
||||
3 944-line inline `mod tests` — into sibling modules a reader can describe
|
||||
in one sentence each, with the tests in `state/tests/`, one file per topic,
|
||||
mirroring `server/tests/`. A **pure move**: no behaviour change, no renamed
|
||||
item, no function body touched, every path another module imports
|
||||
preserved by re-exports from `state/mod.rs`, the per-suite test counts
|
||||
identical to the baseline. `discover.rs` and `scan.rs`, already split out,
|
||||
are untouched.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `lucisv_server` is a binary crate; "public path" means what other
|
||||
modules of the crate import. Every one of them still resolves at
|
||||
`crate::state::…`: `Workspace`, `Document`, `FileView`,
|
||||
`WORKSPACE_SYMBOL_LIMIT`, `first_token_reaching`, `first_token_from`,
|
||||
`mixed_buffer` (`#[cfg(test)]`), `IndexEvent`, `Scan`,
|
||||
`discover::HEAD_WALK_MAX`. `Workspace`'s methods are methods whatever
|
||||
file their `impl` block is in, so no call site in the crate moved.
|
||||
- Sibling files are private modules; `Workspace`'s fields stay private
|
||||
(child modules see their ancestor's private items, as `discover.rs`
|
||||
already relied on), and so does `StoreOpen`. The only widenings are the
|
||||
private items a *sibling* now calls, all `pub(super)` and all taken from
|
||||
the compiler rather than guessed: `scope::{walks_the_workspace,
|
||||
raised_dirs, cache_dir}`, `buffers::{current_text, analysis_of}`,
|
||||
`views::forget_view`, `rescan::open_store`, and the two view-cache
|
||||
bounds `views::{MAX_VIEWS, MAX_VIEW_BYTES}` that one test file reads.
|
||||
- The tests are one `#[cfg(test)] mod tests;` in `state/mod.rs` →
|
||||
`state/tests/mod.rs`, whose sibling files are the sections the one big
|
||||
test module had, under the banner names it gave them. A helper more
|
||||
than one section used moved to `tests/mod.rs`; a helper one section
|
||||
used stayed with it. Each section's banner became the `//!` doc of its
|
||||
file, verbatim where the banner had a paragraph (the view cache,
|
||||
TODO §63.2). The test-local `struct Scan` (a scan's parsed/cached/
|
||||
analyzed census) shadows `state::Scan` inside `tests` exactly as it did
|
||||
inside the old inline module; the three files that drive a `state::Scan`
|
||||
by hand never name the type.
|
||||
- Moving the tests out of the inline module de-indents them by four
|
||||
spaces; `cargo fmt` then re-joined a dozen statements that fit in one
|
||||
line at the new indent. Whitespace only — every test name and body is
|
||||
the old one, and the 121 names are checked against the baseline log.
|
||||
- "Production lines" below are non-blank, non-comment lines outside
|
||||
`mod tests`, the CLAUDE.md metric.
|
||||
- The `lucisv` CLI does not depend on `lucisv_server`, so the formatter's
|
||||
output cannot move: the corpus/opentitan byte-identity sweep is vacuous
|
||||
for this lane and was not run. The gates are the test counts, the fmt
|
||||
and clippy runs, and the line-multiset check in the work log.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** (unchanged): everything `state/mod.rs` imported before —
|
||||
`vlog_parser`, `vlog_semantic`, `crate::{candidates, convert, includes,
|
||||
index_cache, module_select, rename_trace, scan_order, scan_trace,
|
||||
settings, uri}` — now imported by the file that uses each.
|
||||
- **Promises** (unchanged): the public surface listed under Assumptions,
|
||||
re-exported from `state/mod.rs`.
|
||||
- **Request to the lead — CLAUDE.md measurement line.** TODO §55's item
|
||||
reads "CLAUDE.md's measurement line refreshed"; CLAUDE.md is outside
|
||||
this lane's ownership. The 2026-09-23 line says
|
||||
`lucisv_server/src/state/mod.rs` at 985 (already over; TODO §55). After
|
||||
this lane: `state/mod.rs` 63, `discover.rs` 412, `rescan.rs` 411,
|
||||
`sources.rs` 170, `scan.rs` 135, `document.rs` 122, `scope.rs` 99,
|
||||
`buffers.rs` 71, `views.rs` 54, `incremental.rs` 54 — nothing in
|
||||
`state/` over 600.
|
||||
- **Note, no edit asked**: `server/tests/folders.rs:128` names
|
||||
`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`
|
||||
in a plain comment; that test is now
|
||||
`state::tests::widen::a_widen_that_subsumes_…`. The name still finds it
|
||||
by grep; the path prefix is one segment stale.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Baseline counts pinned (`cargo test -p lucisv_server` under guard).
|
||||
- [x] Production split: `document`, `buffers`, `views`, `scope`, `rescan`,
|
||||
`incremental`, `sources` beside `discover` and `scan`; `mod.rs` keeps
|
||||
the struct, `StoreOpen`, the table readers and the re-exports.
|
||||
- [x] Tests out to `state/tests/` (14 topic files + harness), every name
|
||||
and body kept.
|
||||
- [x] `cargo fmt -p lucisv_server`; `cargo fmt --all --check` clean.
|
||||
- [x] `cargo clippy --workspace --all-targets -- -D warnings` clean.
|
||||
- [x] `cargo test -p lucisv_server` after: counts equal the baseline.
|
||||
- [x] `cargo test --workspace --all-targets` once at the end.
|
||||
- [x] TODO §55 ticked.
|
||||
- [ ] CLAUDE.md measurement line — the lead's (Handshakes).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-10-14 — the move (refactor dev, Fable)
|
||||
|
||||
**Baseline** (`tools/guard.sh -t 1800 -- cargo test -p lucisv_server`,
|
||||
guard exit 0): unittests 1 721 passed / 36 ignored; `tests/e2e.rs` 99 / 2;
|
||||
`tests/grammar.rs` 3 / 0. 121 of the unit tests are `state::tests::*`.
|
||||
|
||||
**Module map** — old `state/mod.rs` line ranges → new file, one sentence
|
||||
each (production lines after the move in brackets):
|
||||
|
||||
| new file | old lines | holds |
|
||||
|---|---|---|
|
||||
| `mod.rs` [63] | 1–44, 317–388, 475–503 | `Workspace` itself, `StoreOpen`, `WORKSPACE_SYMBOL_LIMIT`, the readers of its tables (`index`, `known_facts`, `candidates`, `includes`), the module list and the re-exports. |
|
||||
| `document.rs` [122] | 76–291 | One open buffer analyzed once from its text — `Document` and everything derived from it — and the two binary token searches (`first_token_reaching`, `first_token_from`, `mixed_buffer`). |
|
||||
| `buffers.rs` [71] | 675–751, 1985–1994, 1502–1515, 1490–1500 | The open buffers: `document`, `document_for_path`, `open_documents`, `set_document`, `is_large`, `has_large_documents`, `close_document`, `open_uris`, and which text speaks for a path (`text_of`, `current_text`, `analysis_of`). |
|
||||
| `views.rs` [54] | 46–74, 1913–1983, 299–315 | The closed-file view cache: `FileView`, its two bounds, `file_view`, `held_views`, `cached_view`, `forget_view`, `trim_views`. |
|
||||
| `scope.rs` [99] | 445–473, 505–595, 1557–1571, 597–673 | Roots, client settings and the scope ladder: `adopt_roots`, `change_roots`, `has_roots`, `roots`, `scope_dirs`, `folder_scoped`, `walks_the_workspace`, `raised`, `raised_dirs`, `client_settings`, `set_client_settings`, `cache_dir`, `set_storage_path`. |
|
||||
| `rescan.rs` [411] | 814–891, 947–1082, 893–945, 1084–1173, 1517–1555, 1175–1380, 391–443, 753–812, 293–297 | Driving a scan, whole or widen, from work list to landed tables: `begin_scan`, `begin_widen`, `discover_the_rest`, `open_store`, `scan_step`, `open_next`/`open_first`, `publish_scan`, `finish_scan`/`finish_whole_scan`/`landed`/`take_scan_trace`, `finish_widen`; then the test-only one-shot forms (`open_roots*`, `open_whole_workspace*`, `rebuild_index*`, `widen_index*`) and `held_bytes`. |
|
||||
| `incremental.rs` [54] | 1382–1488 | One saved file re-indexed in place: `update_one`, `update_one_checked`. |
|
||||
| `sources.rs` [170] | 1573–1911 | The file sets handed to refactorings: `sources`, `module_sources`, `module_sources_reaching`, `rename_sources_traced`, `fan_out_of`, `want_*`, `include_sources`. |
|
||||
|
||||
Reading order inside `rescan.rs` is the protocol's: begin → step →
|
||||
publish → finish, with the one-shot wrappers after a separator comment
|
||||
(the one piece of new comment text in production code). Within every
|
||||
other file the original order is kept.
|
||||
|
||||
**Tests** — old `mod tests` (1 997–5 941) → `state/tests/`:
|
||||
|
||||
| file | tests | section it was |
|
||||
|---|---|---|
|
||||
| `mod.rs` | — | harness: `uri`, `Tree`, and the 17 helpers more than one section used (`open`, `filler`, `tangled`, `wide`, `excluding`, `own_folder_only`, `using_filelist`, `capping`, `fat_package`, `caching`, `indexed`, `everything`, `seen`, `Scan`/`scan`/`file_name`, `walk_sources`) |
|
||||
| `document.rs` | 8 | the token searches and `Document` tests at the top; TODO §63.2 QA (the trace's arithmetic) from the bottom |
|
||||
| `large_file.rs` | 5 | the large-file fast path |
|
||||
| `views.rs` | 7 | the closed-file view cache |
|
||||
| `interleave.rs` | 6 | an interleaved scan against the one-shot scan it must equal |
|
||||
| `folders.rs` | 9 | `didChangeWorkspaceFolders` (the second half of the interleave section) |
|
||||
| `settings.rs` | 9 | gitignore/config/pushed excludes, which settings ask for a rescan, source extensions |
|
||||
| `size_cap.rs` | 7 | `lucisv.index.maxFileSize` |
|
||||
| `filelist.rs` | 11 | rung 1 and its `+incdir+`s |
|
||||
| `folder_scope.rs` | 15 | the folder scope + inherited obligations (index-scope review) |
|
||||
| `lazy_read.rs` | 6 | the lazy read and the folder-first order (§P4b3) |
|
||||
| `incremental.rs` | 6 | the incremental path |
|
||||
| `persistence.rs` | 15 | the persistent index cache |
|
||||
| `open_buffers.rs` | 8 | an open buffer's own analysis + the QA attacks on it; `an_open_buffer_overrides_disk_in_the_index` from the top section |
|
||||
| `widen.rs` | 9 | the incremental scope widen |
|
||||
|
||||
121 tests, the same 121 names as the baseline log (diffed).
|
||||
|
||||
**How the move was made.** A script sliced the original by line range
|
||||
(production) and by brace-balanced item (tests, each with its doc comment
|
||||
and attributes) into the scratchpad, asserting that every one of the
|
||||
5 941 original lines landed exactly once, was blank, or was one of the
|
||||
five structural lines (`impl Workspace {`, its `}`, the `mod tests`
|
||||
wrapper) or a section banner; the new files were then copied into
|
||||
`state/` and `mod.rs` rewritten from the assembled text (diffed: equal).
|
||||
Imports per file and the eight `pub(super)` widenings were added by hand,
|
||||
taken from the compiler. A second script checks the multiset of
|
||||
production lines of the old file against the union of the new ones: the
|
||||
only differences are `use` continuation lines and the separator comment
|
||||
above the one-shot forms.
|
||||
|
||||
**Longest functions** (raw lines, before = after, since no body moved):
|
||||
`begin_widen` 106 (85 production — the one over 80, left as it is; a pure
|
||||
move does not split functions), `scan_step` 70, `begin_scan` 67,
|
||||
`update_one` 58, `finish_whole_scan` 55, `rename_sources_traced` 52,
|
||||
`finish_widen` 48, `fan_out_of` 39, `Document::new` 35, `publish_scan`
|
||||
29.
|
||||
|
||||
**Gates** (every suite through `tools/guard.sh`, logs kept in the
|
||||
session scratchpad):
|
||||
|
||||
- `cargo fmt -p lucisv_server`: reordered the `use` blocks in five new
|
||||
files and re-joined 12 statements in the de-indented tests; then
|
||||
`cargo fmt --all --check` exit 0.
|
||||
- `tools/guard.sh -t 1800 -- cargo clippy --workspace --all-targets --
|
||||
-D warnings`: guard exit 0, no warnings.
|
||||
- `tools/guard.sh -t 1800 -- cargo test -p lucisv_server` after the
|
||||
move: 1 721 passed / 36 ignored, 99 / 2, 3 / 0 — equal to the baseline,
|
||||
guard exit 0. Two earlier runs each failed **one** `large::tests`
|
||||
wall-clock budget test (`…locate_their_hits_in_linear_time`, 173 ms
|
||||
against a 150 ms budget; then `…colours_in_linear_time`) with the host
|
||||
at load average 12–21 (`mediaanalysisd`, `XProtectRemediator`,
|
||||
`syspolicyd` near 50 % CPU each, a foreign `rustc`) — the host
|
||||
condition the brief names; `large.rs` is not touched by this lane, both
|
||||
tests pass alone, and the third full run passed clean. Reported, not
|
||||
worked around.
|
||||
- `tools/guard.sh -t 1800 -- cargo test --workspace --all-targets`: 80
|
||||
suites, every one `ok`, 5 078 passed / 51 ignored, guard exit 0.
|
||||
|
||||
## QA log
|
||||
|
||||
## Review
|
||||
|
||||
**2026-10-14 — lead.** Accepted as a pure move. Independent check: the
|
||||
multiset of code lines in the old `state/mod.rs` against the union of the
|
||||
new `state/` files (excluding `discover.rs`/`scan.rs`) differs only in `use`
|
||||
lines, the `impl Workspace {` headers, the forced `pub(super)` widenings
|
||||
listed in the work log, and rustfmt re-wrapping the same tokens in the
|
||||
de-indented tests — no code line lost or added. The CLAUDE.md measurement
|
||||
line is refreshed (2026-10-14 paragraph); the stale test path in
|
||||
`server/tests/folders.rs:128` is corrected. Merged onto master after the
|
||||
review lows; gates re-run on the merged tree.
|
||||
Reference in new issue
Block a user