Round 2: unified index lifecycle, tombstones, symlinks, and large-file invariant (#48-#51, #63)
This commit is contained in:
1 parent
8f5a4fb236
commit
4d384ec89d
39 files changed
+4709
-387
No files matched your search
@@ -240,6 +240,13 @@ impl Project {
|
||||
&self.index
|
||||
}
|
||||
|
||||
/// Drop one file directly from the held index (test-only helper to exercise
|
||||
/// sparse tombstoned `FileId`s).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn remove_file_from_index(&mut self, path: &Path) -> bool {
|
||||
self.index.remove_file(path)
|
||||
}
|
||||
|
||||
/// The canonical roots, in the order given.
|
||||
pub fn roots(&self) -> &[PathBuf] {
|
||||
&self.roots
|
||||
|
||||
@@ -264,9 +264,8 @@ struct Census<'a> {
|
||||
impl<'a> Census<'a> {
|
||||
fn of(index: &'a WorkspaceIndex) -> Census<'a> {
|
||||
let mut words: HashMap<&'a str, (usize, FileId)> = HashMap::new();
|
||||
for (at, path) in index.files().iter().enumerate() {
|
||||
for (file, path) in index.live_files() {
|
||||
let Some(facts) = index.facts_for(path) else { continue };
|
||||
let file = FileId(at as u32);
|
||||
for word in facts.words() {
|
||||
words.entry(word.as_str()).or_insert((0, file)).0 += 1;
|
||||
}
|
||||
@@ -328,4 +327,111 @@ impl MentionOracle for Mentions<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn census_uses_live_file_ids_after_tombstone_at_slot_zero() {
|
||||
let mut index = WorkspaceIndex::build([
|
||||
(PathBuf::from("a_excl.sv"), "module a_excl; logic excl_only; endmodule\n"),
|
||||
(
|
||||
PathBuf::from("b_live.sv"),
|
||||
"module b_live; logic own_sig; logic shared_sig; endmodule\n",
|
||||
),
|
||||
(PathBuf::from("c_user.sv"), "module c_user; logic shared_sig; endmodule\n"),
|
||||
]);
|
||||
assert!(index.remove_file(Path::new("a_excl.sv")));
|
||||
let b_id = index.file_id(Path::new("b_live.sv")).expect("b_live live");
|
||||
assert_eq!(b_id, FileId(1));
|
||||
|
||||
let census = Census::of(&index);
|
||||
assert!(!census.outside("excl_only", Some(b_id)));
|
||||
assert!(
|
||||
!census.outside("own_sig", Some(b_id)),
|
||||
"Census::of must keep FileId(1) rather than shifting to FileId(0)"
|
||||
);
|
||||
assert!(census.outside("shared_sig", Some(b_id)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_r2_f1_mcp_find_and_check_with_multiple_tombstones_preceding_live_files() {
|
||||
let dir = std::env::temp_dir().join(format!("lucisv-mcp-qa-r2-f1-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).expect("mkdir");
|
||||
let dir = std::fs::canonicalize(dir).expect("canon");
|
||||
|
||||
let excl0 = dir.join("a0_excl.sv");
|
||||
let excl1 = dir.join("a1_excl.sv");
|
||||
let excl2 = dir.join("a2_excl.sv");
|
||||
std::fs::write(&excl0, "`define EX0 1\nmodule a0; logic ex0_sig; endmodule\n").expect("w");
|
||||
std::fs::write(&excl1, "`define EX1 1\nmodule a1; logic ex1_sig; endmodule\n").expect("w");
|
||||
std::fs::write(&excl2, "`define EX2 1\nmodule a2; logic ex2_sig; endmodule\n").expect("w");
|
||||
std::fs::write(
|
||||
dir.join("b_live.sv"),
|
||||
"`define LIVE_MAC 1\nmodule b_live;\n logic own_sig;\n logic shared_sig;\nendmodule\n",
|
||||
)
|
||||
.expect("w");
|
||||
std::fs::write(
|
||||
dir.join("c_user.sv"),
|
||||
"module c_user;\n logic shared_sig;\n b_live u1 ();\nendmodule\n",
|
||||
)
|
||||
.expect("w");
|
||||
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
assert!(project.remove_file_from_index(&excl0));
|
||||
assert!(project.remove_file_from_index(&excl1));
|
||||
assert!(project.remove_file_from_index(&excl2));
|
||||
assert_eq!(project.index().files().len(), 2);
|
||||
assert_eq!(project.index().file_id(&dir.join("b_live.sv")), Some(FileId(3)));
|
||||
|
||||
let make_args = |tool: &crate::tools::Tool, v: serde_json::Value| {
|
||||
crate::tools::validate(tool, v.as_object().cloned().expect("args obj"))
|
||||
.expect("valid args")
|
||||
};
|
||||
|
||||
let check_tool = crate::tools::find("check", crate::tools::Mode::Full).expect("check tool");
|
||||
let single = (check_tool.handler)(
|
||||
&mut project,
|
||||
&make_args(check_tool, serde_json::json!({ "file": "b_live.sv" })),
|
||||
)
|
||||
.expect("single check");
|
||||
assert!(single.text.contains("own_sig"), "single check flags own_sig: {}", single.text);
|
||||
assert!(
|
||||
!single.text.contains("shared_sig"),
|
||||
"single check ignores shared_sig: {}",
|
||||
single.text
|
||||
);
|
||||
|
||||
let whole =
|
||||
(check_tool.handler)(&mut project, &make_args(check_tool, serde_json::json!({})))
|
||||
.expect("whole check");
|
||||
assert!(whole.text.contains("own_sig"), "whole check flags own_sig: {}", whole.text);
|
||||
assert!(
|
||||
!whole.text.contains("shared_sig"),
|
||||
"whole check ignores shared_sig: {}",
|
||||
whole.text
|
||||
);
|
||||
|
||||
let find_tool = crate::tools::find("find", crate::tools::Mode::Full).expect("find tool");
|
||||
let refs = (find_tool.handler)(
|
||||
&mut project,
|
||||
&make_args(find_tool, serde_json::json!({ "name": "b_live", "refs": true })),
|
||||
)
|
||||
.expect("find refs");
|
||||
assert!(refs.text.contains("c_user.sv"), "find refs locates c_user.sv: {}", refs.text);
|
||||
|
||||
let err = match (find_tool.handler)(
|
||||
&mut project,
|
||||
&make_args(find_tool, serde_json::json!({ "name": "LIVE" })),
|
||||
) {
|
||||
Ok(_) => panic!("expected no_declaration error with similar"),
|
||||
Err(e) => e,
|
||||
};
|
||||
assert!(err.contains("LIVE_MAC"), "near match must include LIVE_MAC: {err}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -11,7 +11,7 @@ use std::collections::{BTreeSet, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex};
|
||||
use vlog_semantic::{Def, DefinitionKey, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::declared::{declared, Local, Wanted};
|
||||
use super::source::{checked_site, Texts};
|
||||
@@ -188,8 +188,8 @@ pub fn similar(project: &Project, name: &str, cap: usize) -> Vec<String> {
|
||||
index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect();
|
||||
let part = Wanted::Containing(name.to_ascii_lowercase());
|
||||
names.extend(declared(project, &part).into_iter().map(|local| local.name));
|
||||
for at in 0..index.files().len() {
|
||||
let Some(table) = index.defines(FileId(at as u32)) else { continue };
|
||||
for (file, _) in index.live_files() {
|
||||
let Some(table) = index.defines(file) else { continue };
|
||||
let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name));
|
||||
names.extend(found.map(|define| define.name.clone()));
|
||||
}
|
||||
@@ -222,7 +222,10 @@ pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::qualified;
|
||||
use super::{qualified, similar};
|
||||
use crate::project::Project;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() {
|
||||
@@ -233,6 +236,26 @@ mod tests {
|
||||
assert_eq!(qualified("\\a.b "), (None, "\\a.b "));
|
||||
assert_eq!(qualified(".x"), (None, ".x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn similar_finds_macros_after_tombstoned_slot_zero() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-names-tombstone-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let dir = fs::canonicalize(dir).unwrap();
|
||||
let a_path = dir.join("a_excl.sv");
|
||||
fs::write(&a_path, "`define EXCL_MAC 1\nmodule a_excl; endmodule\n").unwrap();
|
||||
fs::write(dir.join("z_mac.sv"), "`define LIVE_MAC 1\nmodule z_mac; endmodule\n").unwrap();
|
||||
|
||||
let mut project = Project::open(vec![dir.clone()], None);
|
||||
assert!(project.remove_file_from_index(&a_path));
|
||||
assert_eq!(similar(&project, "LIVE", 20), vec!["LIVE_MAC".to_string()]);
|
||||
assert!(similar(&project, "EXCL", 20).is_empty());
|
||||
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
let _: PathBuf = dir;
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -833,8 +833,8 @@ fn unit_tables(
|
||||
/// defined, and offering the name is the honest answer either way.
|
||||
fn macros_of(index: &WorkspaceIndex) -> Vec<Macro> {
|
||||
let mut out: Vec<Macro> = Vec::new();
|
||||
for id in 0..index.files().len() {
|
||||
let Some(table) = index.defines(vlog_semantic::FileId(id as u32)) else { continue };
|
||||
for (file, _) in index.live_files() {
|
||||
let Some(table) = index.defines(file) else { continue };
|
||||
for define in table.entries().iter().filter(|d| d.kind == DefineKind::Define) {
|
||||
out.push(macro_of(define));
|
||||
}
|
||||
|
||||
@@ -104,8 +104,7 @@ pub(super) fn related_tier(
|
||||
pub(super) fn related_macros(items: &mut Items, ws: &Workspace, doc: &Document, prefix: &str) {
|
||||
let mut names: Vec<(String, String)> = Vec::new();
|
||||
for path in crate::includes::reachable_from(ws, doc) {
|
||||
let Some(table) = ws.index().file_id(&path).and_then(|file| ws.index().defines(file))
|
||||
else {
|
||||
let Some(table) = ws.index_file_id(&path).and_then(|file| ws.index().defines(file)) else {
|
||||
continue;
|
||||
};
|
||||
let defines = table.entries().iter().filter(|d| d.kind == DefineKind::Define);
|
||||
|
||||
@@ -119,10 +119,10 @@ pub fn execute(
|
||||
let doc = ws
|
||||
.document(&uri)
|
||||
.ok_or_else(|| "lucisv can only extract from an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only extract from a file that has been saved.".to_string())?;
|
||||
let path =
|
||||
ws.index_path_for(doc.path.as_deref().ok_or_else(|| {
|
||||
"lucisv can only extract from a file that has been saved.".to_string()
|
||||
})?);
|
||||
let positions = doc.positions();
|
||||
let (start, end) = (positions.offset(range.start), positions.offset(range.end));
|
||||
let Some(site) = site_at(doc, start, end) else {
|
||||
@@ -173,19 +173,11 @@ pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<Work
|
||||
})));
|
||||
}
|
||||
for (path, edits) in &refactoring.edits {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
// A file the edit creates has no text yet, and the one insertion into
|
||||
// it is at 0:0 — which is what `Positions` over an empty text says.
|
||||
let created = refactoring.created.iter().any(|created| created == path);
|
||||
let text = match created {
|
||||
true => String::new(),
|
||||
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
|
||||
};
|
||||
let index = LineIndex::new(&text);
|
||||
let positions = Positions::new(&text, &index);
|
||||
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
|
||||
text_document: OptionalVersionedTextDocumentIdentifier { uri, version: None },
|
||||
edits: edits
|
||||
let map_with = |positions: &Positions<'_>| {
|
||||
edits
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
OneOf::Left(TextEdit {
|
||||
@@ -193,7 +185,26 @@ pub fn workspace_edit(ws: &Workspace, refactoring: &RefactorEdit) -> Result<Work
|
||||
new_text: edit.new_text.clone(),
|
||||
})
|
||||
})
|
||||
.collect(),
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let (uri, version, mapped) = match (!created)
|
||||
.then(|| ws.open_document_for_path(path))
|
||||
.flatten()
|
||||
{
|
||||
Some((open_uri, doc)) => (open_uri.clone(), doc.version(), map_with(&doc.positions())),
|
||||
None => {
|
||||
let uri = path_to_uri(path).ok_or_else(|| unaddressable(path))?;
|
||||
let text = match created {
|
||||
true => String::new(),
|
||||
false => ws.text_of(path).ok_or_else(|| unaddressable(path))?,
|
||||
};
|
||||
let index = LineIndex::new(&text);
|
||||
(uri, None, map_with(&Positions::new(&text, &index)))
|
||||
}
|
||||
};
|
||||
operations.push(DocumentChangeOperation::Edit(TextDocumentEdit {
|
||||
text_document: OptionalVersionedTextDocumentIdentifier { uri, version },
|
||||
edits: mapped,
|
||||
}));
|
||||
}
|
||||
Ok(WorkspaceEdit {
|
||||
|
||||
@@ -84,7 +84,10 @@ fn other_files(
|
||||
let is_call_of_def = |doc: &Document, id: ReferenceId| names_def(doc, id, def);
|
||||
let mut calls = Vec::new();
|
||||
for (_, doc) in ws.open_documents() {
|
||||
let Some(path) = doc.path.as_deref().filter(|path| *path != declaring) else { continue };
|
||||
let Some(path) = doc.path.as_deref().filter(|path| !ws.is_same_file(path, declaring))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(uri) = path_to_uri(path) else { continue };
|
||||
calls.extend(callers(&uri, doc, name, |_, id| is_call_of_def(doc, id)));
|
||||
}
|
||||
@@ -92,7 +95,7 @@ fn other_files(
|
||||
.references_to(def)
|
||||
.iter()
|
||||
.filter_map(|site| index.path(site.file))
|
||||
.filter(|path| *path != declaring && ws.document_for_path(path).is_none())
|
||||
.filter(|path| !ws.is_same_file(path, declaring) && ws.document_for_path(path).is_none())
|
||||
.map(Path::to_path_buf)
|
||||
.collect();
|
||||
closed.sort();
|
||||
@@ -119,7 +122,7 @@ fn other_files(
|
||||
fn declined(ws: &Workspace, def: &Def, name: &str, declaring: &Path) -> bool {
|
||||
ws.index().references_are_ambiguous(def)
|
||||
|| ws.open_documents().any(|(_, doc)| {
|
||||
doc.path.as_deref().is_some_and(|path| path != declaring)
|
||||
doc.path.as_deref().is_some_and(|path| !ws.is_same_file(path, declaring))
|
||||
&& names_it_ambiguously(doc, name, def)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -98,7 +98,11 @@ pub(crate) fn narrowed_to_the_include_graph<'a>(
|
||||
}
|
||||
let narrowed: Vec<(FileId, &Define)> = candidates
|
||||
.iter()
|
||||
.filter(|(file, _)| ws.index().path(*file).is_some_and(|p| reachable.contains(p)))
|
||||
.filter(|(file, _)| {
|
||||
ws.index().path(*file).is_some_and(|p| {
|
||||
reachable.contains(p) || reachable.iter().any(|r| ws.is_same_file(r, p))
|
||||
})
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
match narrowed.len() {
|
||||
|
||||
@@ -193,7 +193,7 @@ fn packages_at(doc: &Document, offset: u32) -> Vec<String> {
|
||||
|
||||
fn at(ws: &Workspace, uri: &Uri, offset: u32) -> Option<(PathBuf, Vec<(PathBuf, String)>)> {
|
||||
let doc = ws.document(uri)?;
|
||||
let path = doc.path.clone()?;
|
||||
let path = ws.index_path_for(doc.path.as_deref()?);
|
||||
let packages = packages_at(doc, offset);
|
||||
if packages.is_empty() {
|
||||
return None;
|
||||
|
||||
@@ -468,6 +468,7 @@ impl IncludeGraph {
|
||||
/// Cycle-safe by construction: a file already visited is never expanded
|
||||
/// again, so `a` including `b` including `a` terminates with both in the
|
||||
/// set.
|
||||
#[cfg(test)]
|
||||
pub fn reachable(&self, seeds: Vec<PathBuf>) -> HashSet<PathBuf> {
|
||||
let mut seen: HashSet<PathBuf> = HashSet::new();
|
||||
let mut queue = seeds;
|
||||
@@ -538,6 +539,18 @@ pub fn normalize(path: &Path) -> PathBuf {
|
||||
// the two capabilities
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// Resolve one `` `include`` from `doc`, trying `doc.path` first and falling
|
||||
/// back to the workspace's canonical indexed path for that file.
|
||||
fn resolve_for_doc(ws: &Workspace, doc: &Document, include: &Include) -> Option<PathBuf> {
|
||||
let graph = ws.includes();
|
||||
let found = graph.resolve(doc.path.as_deref(), include).or_else(|| {
|
||||
let path = doc.path.as_deref()?;
|
||||
let canon = ws.index_path_for(path);
|
||||
(canon != path).then(|| graph.resolve(Some(&canon), include)).flatten()
|
||||
})?;
|
||||
Some(ws.index_path_for(&found))
|
||||
}
|
||||
|
||||
/// Every resolvable `` `include`` in an open buffer, paired with the file it
|
||||
/// names.
|
||||
///
|
||||
@@ -545,13 +558,9 @@ pub fn normalize(path: &Path) -> PathBuf {
|
||||
/// graph: the graph is rebuilt on save, and an include line just typed should
|
||||
/// be clickable before then.
|
||||
fn resolved(ws: &Workspace, doc: &Document) -> Vec<(Include, PathBuf)> {
|
||||
let graph = ws.includes();
|
||||
scan(&doc.text)
|
||||
.into_iter()
|
||||
.filter_map(|include| {
|
||||
let path = graph.resolve(doc.path.as_deref(), &include)?;
|
||||
Some((include, path))
|
||||
})
|
||||
.filter_map(|include| Some((include.clone(), resolve_for_doc(ws, doc, &include)?)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -581,7 +590,7 @@ pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
|
||||
/// disagree about where a line goes.
|
||||
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
|
||||
let include = include_at(doc, offset)?;
|
||||
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
|
||||
let path = resolve_for_doc(ws, doc, &include)?;
|
||||
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
|
||||
}
|
||||
|
||||
@@ -603,11 +612,25 @@ pub(crate) fn include_at(doc: &Document, offset: u32) -> Option<Include> {
|
||||
/// the graph, so an include added since the last save already counts. The
|
||||
/// buffer itself is *not* in the set unless an include cycle reaches it.
|
||||
pub fn reachable_from(ws: &Workspace, doc: &Document) -> HashSet<PathBuf> {
|
||||
let seeds: Vec<PathBuf> = resolved(ws, doc).into_iter().map(|(_, path)| path).collect();
|
||||
if seeds.is_empty() {
|
||||
let mut queue: Vec<PathBuf> = resolved(ws, doc).into_iter().map(|(_, path)| path).collect();
|
||||
if queue.is_empty() {
|
||||
return HashSet::new();
|
||||
}
|
||||
ws.includes().reachable(seeds)
|
||||
let graph = ws.includes();
|
||||
let mut seen: HashSet<PathBuf> = HashSet::new();
|
||||
while let Some(path) = queue.pop() {
|
||||
if !seen.insert(path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let canon = ws.index_path_for(&path);
|
||||
if canon != path && !seen.contains(&canon) {
|
||||
queue.push(canon);
|
||||
}
|
||||
if let Some(targets) = graph.edges.get(&path) {
|
||||
queue.extend(targets.iter().cloned());
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -91,10 +91,11 @@ pub fn execute(
|
||||
let position: Position = argument(arguments, 1, "a position")?;
|
||||
let doc =
|
||||
ws.document(&uri).ok_or_else(|| "lucisv can only inline in an open file.".to_string())?;
|
||||
let path = doc
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?;
|
||||
let path = ws.index_path_for(
|
||||
doc.path
|
||||
.as_deref()
|
||||
.ok_or_else(|| "lucisv can only inline in a file that has been saved.".to_string())?,
|
||||
);
|
||||
let offset = doc.positions().offset(position);
|
||||
let Some(site) = site_at(doc, offset) else {
|
||||
return Err(NOTHING.to_string());
|
||||
|
||||
@@ -52,6 +52,9 @@ use crate::state::{Document, Workspace};
|
||||
pub struct LintRun<'a> {
|
||||
rules: Vec<&'static dyn Rule>,
|
||||
oracle: Option<IndexMentions<'a>>,
|
||||
/// Canonical indexed path when resolved through the workspace, falling back
|
||||
/// to `doc.path` so symlinked open buffers lint against one identity.
|
||||
path: Option<PathBuf>,
|
||||
/// What the buffer's `lucisv.toml` and the editor's settings configured
|
||||
/// about each rule, merged. Empty means every rule reads its own default.
|
||||
options: RuleOptions,
|
||||
@@ -92,6 +95,7 @@ impl Default for LintRun<'_> {
|
||||
LintRun {
|
||||
rules: default_rules(),
|
||||
oracle: None,
|
||||
path: None,
|
||||
options: RuleOptions::new(),
|
||||
line_length: DEFAULT_LINE_LENGTH,
|
||||
tab_width: DEFAULT_TAB_WIDTH,
|
||||
@@ -178,7 +182,8 @@ impl<'a> LintRun<'a> {
|
||||
|
||||
/// This run's context over a buffer's own parse products.
|
||||
fn context<'d>(&'d self, doc: &'d Document) -> LintContext<'d> {
|
||||
let ctx = context(doc)
|
||||
let path = self.path.as_deref().or(doc.path.as_deref());
|
||||
let ctx = context_for(doc, path)
|
||||
.with_options(&self.options)
|
||||
.with_line_length(self.line_length)
|
||||
.with_tab_width(self.tab_width);
|
||||
@@ -200,6 +205,7 @@ impl<'a> LintRun<'a> {
|
||||
/// `for_document`'s own, in its own order, so the messages a config problem
|
||||
/// produces arrive in the order §42.2 fixed.
|
||||
struct Discovered {
|
||||
path: Option<PathBuf>,
|
||||
options: RuleOptions,
|
||||
line_length: usize,
|
||||
tab_width: usize,
|
||||
@@ -217,7 +223,9 @@ impl Discovered {
|
||||
/// width, the indent and the waiver paths all read the same `FileConfig`,
|
||||
/// so reading the project's rules costs no extra stat and no extra open.
|
||||
fn read(ws: &Workspace, doc: &Document) -> Discovered {
|
||||
let (options, line_length, file, mut messages) = configured(ws.client_settings(), doc);
|
||||
let path = doc.path.as_deref().map(|p| ws.index_path_for(p));
|
||||
let (options, line_length, file, mut messages) =
|
||||
configured(ws.client_settings(), path.as_deref());
|
||||
let (project, bad_names) = ProjectLint::read(&file);
|
||||
messages.extend(bad_names);
|
||||
let (mut external, bad_waivers, mut texts) = waiver_files(&project_waivers(&file));
|
||||
@@ -233,15 +241,25 @@ impl Discovered {
|
||||
// it here rather than spelling the ladder a second time costs a second
|
||||
// `Discovery` walk, which the R1b trace measures at hundredths of a
|
||||
// millisecond against a 21 ms pass.
|
||||
let tab_width = crate::format::indent_width(doc.path.as_deref(), ws.client_settings());
|
||||
Discovered { options, line_length, tab_width, file, project, external, texts, messages }
|
||||
let tab_width = crate::format::indent_width(path.as_deref(), ws.client_settings());
|
||||
Discovered {
|
||||
path,
|
||||
options,
|
||||
line_length,
|
||||
tab_width,
|
||||
file,
|
||||
project,
|
||||
external,
|
||||
texts,
|
||||
messages,
|
||||
}
|
||||
}
|
||||
|
||||
/// What this buffer's index and settings make of it: the census oracle and
|
||||
/// the rule ladder, neither of which touches the filesystem.
|
||||
fn into_run<'a>(self, ws: &'a Workspace, doc: &Document) -> LintRun<'a> {
|
||||
fn into_run<'a>(self, ws: &'a Workspace, _doc: &Document) -> LintRun<'a> {
|
||||
let index = ws.index();
|
||||
let own = doc.path.as_deref().and_then(|path| index.file_id(path));
|
||||
let own = self.path.as_deref().and_then(|path| ws.index_file_id(path));
|
||||
let workspace = index.files().len() > usize::from(own.is_some());
|
||||
let oracle = workspace.then_some(IndexMentions { index, own });
|
||||
let rules = enabled_rules(ws.client_settings(), &self.project, workspace);
|
||||
@@ -249,6 +267,7 @@ impl Discovered {
|
||||
LintRun {
|
||||
rules,
|
||||
oracle,
|
||||
path: self.path,
|
||||
options: self.options,
|
||||
line_length: self.line_length,
|
||||
tab_width: self.tab_width,
|
||||
@@ -283,11 +302,9 @@ impl Discovered {
|
||||
/// a parse and an analysis the same pass already paid for.
|
||||
fn configured(
|
||||
client: &ClientSettings,
|
||||
doc: &Document,
|
||||
path: Option<&Path>,
|
||||
) -> (RuleOptions, usize, FileConfig, Vec<String>) {
|
||||
let file = doc
|
||||
.path
|
||||
.as_deref()
|
||||
let file = path
|
||||
.and_then(|path| lucisv_core::config::Discovery::new(true).for_file(path).ok())
|
||||
.unwrap_or_default();
|
||||
let mut options = RuleOptions::new();
|
||||
@@ -558,9 +575,20 @@ impl MentionOracle for IndexMentions<'_> {
|
||||
/// document is analyzed on every edit for hover, definition and references, so
|
||||
/// the semantic rules must read *that* analysis rather than run a second one
|
||||
/// per keystroke.
|
||||
#[cfg(test)]
|
||||
fn context(doc: &Document) -> LintContext<'_> {
|
||||
LintContext::from_parse(&doc.text, &doc.tokens, &doc.tree, &doc.line_index, doc.path.clone())
|
||||
.with_semantics(&doc.semantics)
|
||||
context_for(doc, doc.path.as_deref())
|
||||
}
|
||||
|
||||
fn context_for<'d>(doc: &'d Document, path: Option<&Path>) -> LintContext<'d> {
|
||||
LintContext::from_parse(
|
||||
&doc.text,
|
||||
&doc.tokens,
|
||||
&doc.tree,
|
||||
&doc.line_index,
|
||||
path.map(Path::to_path_buf),
|
||||
)
|
||||
.with_semantics(&doc.semantics)
|
||||
}
|
||||
|
||||
/// Every violation `run`'s rules find in a buffer.
|
||||
|
||||
@@ -229,7 +229,7 @@ pub(crate) fn indexed_def_for_symbol<'a>(
|
||||
doc: &Document,
|
||||
symbol: &Symbol,
|
||||
) -> Option<&'a Def> {
|
||||
let file = ws.index().file_id(doc.path.as_deref()?)?;
|
||||
let file = ws.index_file_id(doc.path.as_deref()?)?;
|
||||
indexed_def_in_file(ws, &doc.semantics, symbol, file)
|
||||
}
|
||||
|
||||
@@ -292,7 +292,7 @@ fn indexed_references(
|
||||
// Every reference in this buffer is answered against the same indexed
|
||||
// file, so the path lookup — a binary search comparing whole paths —
|
||||
// is taken once per buffer rather than once per reference.
|
||||
let file = ws.index().file_id(path);
|
||||
let file = ws.index_file_id(path);
|
||||
for (id, reference) in doc.semantics.references().iter().enumerate() {
|
||||
// A use can only name `target.def` if it spells the name that
|
||||
// declaration declares, and `target.name` is exactly that name.
|
||||
@@ -434,7 +434,7 @@ fn declaring_file_uses(ws: &Workspace, target: &IndexedTarget) -> Option<Declari
|
||||
return None;
|
||||
}
|
||||
let text = ws.text_of(&target.declaration_path)?;
|
||||
let file = ws.index().file_id(&target.declaration_path)?;
|
||||
let file = ws.index_file_id(&target.declaration_path)?;
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(&text);
|
||||
let semantics = vlog_semantic::analyze(&tree, &text);
|
||||
// The same logical identity `indexed_def_in_file` asserts everywhere else
|
||||
@@ -529,13 +529,14 @@ fn locations(
|
||||
start = end;
|
||||
continue;
|
||||
};
|
||||
if let Some(doc) = ws.document_for_path(path) {
|
||||
if let Some((open_uri, doc)) = ws.open_document_for_path(path) {
|
||||
let positions = doc.positions();
|
||||
let mut walker = positions.walker();
|
||||
out.extend(
|
||||
found[start..end]
|
||||
.iter()
|
||||
.map(|(_, span)| Location { uri: uri.clone(), range: walker.range(*span) }),
|
||||
found[start..end].iter().map(|(_, span)| Location {
|
||||
uri: open_uri.clone(),
|
||||
range: walker.range(*span),
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
out.extend(closed_locations(ws, &uri, path, &found[start..end], closed));
|
||||
|
||||
@@ -110,7 +110,8 @@ pub fn code_actions_for(
|
||||
versioned: bool,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
let Some(doc_path) = doc.path.as_deref() else { return Vec::new() };
|
||||
let path = ws.index_path_for(doc_path);
|
||||
// A code-action request arrives on every cursor move, so neither half of
|
||||
// this may walk the workspace. The engine's one-file question answers
|
||||
// "there is nothing here" for almost every position — and where it does
|
||||
@@ -180,7 +181,8 @@ pub fn offers(
|
||||
offset: u32,
|
||||
) -> Vec<CodeActionOrCommand> {
|
||||
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
||||
let Some(path) = doc.path.clone() else { return Vec::new() };
|
||||
let Some(doc_path) = doc.path.as_deref() else { return Vec::new() };
|
||||
let path = ws.index_path_for(doc_path);
|
||||
let modules = modules_at(doc, offset);
|
||||
// A name the workspace declares twice is a refusal the engine makes over
|
||||
// the fan-out, where it can see both declarations. The offer cannot, so it
|
||||
@@ -494,8 +496,9 @@ fn target(ws: &Workspace, argument: Option<&Value>) -> Result<(Uri, PathBuf), St
|
||||
})?;
|
||||
let path = ws
|
||||
.document(&uri)
|
||||
.and_then(|doc| doc.path.clone())
|
||||
.or_else(|| uri_to_path(&uri))
|
||||
.and_then(|doc| doc.path.as_deref())
|
||||
.map(|path| ws.index_path_for(path))
|
||||
.or_else(|| uri_to_path(&uri).map(|path| ws.index_path_for(&path)))
|
||||
.ok_or_else(|| "lucisv can only refactor inside a saved file.".to_string())?;
|
||||
Ok((uri, path))
|
||||
}
|
||||
@@ -552,7 +555,7 @@ pub(crate) fn encode_edit(
|
||||
) -> Result<WorkspaceEdit, String> {
|
||||
let mut pairs: Vec<(Uri, Option<i32>, Vec<TextEdit>)> = Vec::new();
|
||||
for (path, edits) in files {
|
||||
let open = ws.open_documents().find(|(_, doc)| doc.path.as_deref() == Some(path));
|
||||
let open = ws.open_document_for_path(path);
|
||||
let (target, version, mapped) = match open {
|
||||
Some((uri, doc)) => (uri.clone(), doc.version(), map_edits(&doc.positions(), edits)),
|
||||
None => {
|
||||
|
||||
@@ -78,7 +78,8 @@ pub fn rename_traced_for(
|
||||
trace: &mut Option<String>,
|
||||
) -> Result<(WorkspaceEdit, Vec<String>), String> {
|
||||
let doc = ws.document(uri).ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.clone().ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = doc.path.as_deref().ok_or_else(|| UNSAVED.to_string())?;
|
||||
let path = ws.index_path_for(path);
|
||||
// The engine's own first look at the request, over the buffer it is about
|
||||
// to be handed anyway. It refuses only what `vlog_refactor::rename` is
|
||||
// certain to refuse in the same words — so this is still one voice
|
||||
|
||||
@@ -76,8 +76,8 @@ impl Server {
|
||||
OnTypeFormatting::METHOD => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
WillSaveWaitUntil::METHOD => Ok(Value::Null),
|
||||
// A rename would rewrite every *other* file and leave this one
|
||||
// untouched — the buffer is not in the index and not in
|
||||
// `sources()` — so it is refused rather than half-applied.
|
||||
// untouched — a fast-path buffer holds an empty AST/analysis and
|
||||
// cannot supply live edits — so it is refused rather than half-applied.
|
||||
// `prepareRename` declines quietly, so the box never opens.
|
||||
PrepareRenameRequest::METHOD => Ok(Value::Null),
|
||||
Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())),
|
||||
@@ -164,34 +164,48 @@ impl Server {
|
||||
/// differently from when it was analyzed — normal ↔ large — after the
|
||||
/// settings changed it from `before`; leave every other buffer alone.
|
||||
///
|
||||
/// The threshold is read where a `Document` is built, so without this a
|
||||
/// new value reached a buffer only at its next edit: one opened before
|
||||
/// the startup's settings answer kept the default's verdict, and a
|
||||
/// threshold changed mid-session did not move an open buffer at all
|
||||
/// (`docs/features/fast-actions/README.md`, R1). A flipped buffer goes
|
||||
/// through the flush's own path — analyzed, its connection located, its
|
||||
/// diagnostics republished once — and its colours are re-requested. A
|
||||
/// dirty buffer is skipped: its flush builds it under the new value
|
||||
/// anyway. Like an edit, this does not reindex: the index takes the new
|
||||
/// mode at the buffer's next save or rescan — and before the startup scan
|
||||
/// there is no index yet, so that scan reads every buffer in its settled
|
||||
/// mode. An unchanged threshold costs one comparison.
|
||||
pub(super) fn reclassify_large_buffers(&mut self, before: u64) {
|
||||
/// When a buffer flips from normal (`large == false`) to large
|
||||
/// (`large == true`) and no full rescan is already owed, its index record
|
||||
/// is reconciled back to disk (subject to `maxFileSize`, or removed if
|
||||
/// outside scope/missing) so stale unsaved edits previously indexed do not
|
||||
/// linger while clean buffers do zero index work (Topo #63).
|
||||
pub(super) fn reclassify_large_buffers(&mut self, before: u64, rescan: bool) {
|
||||
if self.workspace.client_settings().large_file_threshold == before {
|
||||
return;
|
||||
}
|
||||
let flipped: Vec<(Uri, String)> = self
|
||||
let flipped: Vec<(Uri, String, bool)> = self
|
||||
.workspace
|
||||
.open_documents()
|
||||
.filter(|(uri, _)| !self.dirty.iter().any(|(pending, _)| pending == *uri))
|
||||
.filter(|(_, doc)| self.workspace.is_large(&doc.text) != doc.large)
|
||||
.map(|(uri, doc)| (uri.clone(), doc.text.clone()))
|
||||
.map(|(uri, doc)| (uri.clone(), doc.text.clone(), doc.large))
|
||||
.collect();
|
||||
if flipped.is_empty() {
|
||||
return;
|
||||
}
|
||||
for (uri, text) in flipped {
|
||||
self.analyze_and_publish(uri, text);
|
||||
let mut index_changed = false;
|
||||
let scan_owed = self.scan_owed();
|
||||
for (uri, text, was_large) in flipped {
|
||||
let prev_facts = (!was_large && !rescan && !scan_owed)
|
||||
.then(|| {
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
let path = doc.path.as_deref()?;
|
||||
let held = self.workspace.held_path_for(path)?;
|
||||
Some((held.clone(), doc.facts(held)))
|
||||
})
|
||||
.flatten();
|
||||
self.analyze_and_publish(uri.clone(), text);
|
||||
if !was_large && scan_owed {
|
||||
self.rescan_wanted = true;
|
||||
} else if let Some((held_path, doc_facts)) = prev_facts {
|
||||
index_changed |=
|
||||
self.workspace.reconcile_large_buffer(&uri, &held_path, &doc_facts);
|
||||
}
|
||||
}
|
||||
if index_changed {
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.republish_all();
|
||||
}
|
||||
if self.abilities.semantic_tokens_refresh {
|
||||
self.send_request(SemanticTokensRefresh::METHOD, ());
|
||||
|
||||
@@ -65,9 +65,9 @@ impl Server {
|
||||
self.auto_styles.notice(¬ification);
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
// thing being deferred.
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
// request gets happens here, with `didChange` (deferred) and `didClose`
|
||||
// (flushed inside its match arm right after index reconciliation).
|
||||
if method != DidChangeTextDocument::METHOD && method != DidCloseTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
self.sync_document_versions();
|
||||
}
|
||||
@@ -283,15 +283,36 @@ impl Server {
|
||||
let uri = p.text_document.uri;
|
||||
self.versions.remove(&uri);
|
||||
self.config_warnings.remove(&uri);
|
||||
// The buffer's unanalyzed change is already gone — it was
|
||||
// dropped at the top of this function, ahead of the flush
|
||||
// that would otherwise have analyzed it.
|
||||
//
|
||||
// The remembered token answer goes with the buffer: the
|
||||
// client drops what it was holding too, and nothing may
|
||||
// grow with the number of files ever opened.
|
||||
self.tokens.remove(&uri);
|
||||
self.workspace.close_document(&uri);
|
||||
let rescan_owed =
|
||||
self.scanning && self.workspace.closing_affects_running_scan(&uri);
|
||||
let index_changed = self.workspace.close_and_reconcile(&uri, !self.scan_owed());
|
||||
let remaining_unflushed: Vec<Uri> = if index_changed {
|
||||
self.workspace
|
||||
.open_uris()
|
||||
.into_iter()
|
||||
.filter(|open| !self.dirty.iter().any(|(pending, _)| pending == open))
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
self.flush_dirty();
|
||||
self.sync_document_versions();
|
||||
if rescan_owed {
|
||||
self.rescan_wanted = true;
|
||||
} else if index_changed {
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
if !remaining_unflushed.is_empty() {
|
||||
self.generation += 1;
|
||||
for open in remaining_unflushed {
|
||||
self.publish(&open);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Clear what we drew: the buffer is gone.
|
||||
self.send_diagnostics(uri, Vec::new());
|
||||
}
|
||||
@@ -363,7 +384,7 @@ impl Server {
|
||||
let rescan = self.workspace.set_client_settings(settings);
|
||||
// Before the rescan, so the index takes each buffer in the mode the
|
||||
// new threshold gives it.
|
||||
self.reclassify_large_buffers(threshold);
|
||||
self.reclassify_large_buffers(threshold, rescan);
|
||||
self.sync_document_versions();
|
||||
if rescan {
|
||||
self.reindex();
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -63,6 +63,7 @@ mod hierarchy_everywhere;
|
||||
mod hierarchy_reach;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod lifecycle_r2;
|
||||
mod lint_snapshot;
|
||||
mod localized_reindex;
|
||||
mod ordering_r1;
|
||||
|
||||
@@ -45,7 +45,7 @@ fn pulling_with_a_bar() -> ClientAbilities {
|
||||
/// registration and the lens refresh that used to be issued ahead of it.
|
||||
/// `send_request` numbers off one counter that only ever goes up, so that
|
||||
/// first id is a fact about the order, not a guess.
|
||||
fn configuration_answer(section: Value) -> Message {
|
||||
pub(super) fn configuration_answer(section: Value) -> Message {
|
||||
Message::Response(Response::new_ok(
|
||||
RequestId::from("lucisv-0".to_string()),
|
||||
serde_json::json!([section]),
|
||||
@@ -70,7 +70,7 @@ fn the_whole_workspace_flat() -> Value {
|
||||
}
|
||||
|
||||
/// A `textDocument/didOpen` over the wire, as the client sends it.
|
||||
fn did_open(path: &Path, text: &str) -> Message {
|
||||
pub(super) fn did_open(path: &Path, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::Uri;
|
||||
use lucisv_core::walk::dir_id;
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::{oversize, Found};
|
||||
@@ -19,9 +20,49 @@ impl Workspace {
|
||||
self.docs.get(uri)
|
||||
}
|
||||
|
||||
/// The open document backed by `path`, if there is one.
|
||||
/// The open URI and document backed by `path` (exact path first, else
|
||||
/// matching file identity without basename gating), if there is one.
|
||||
pub fn open_document_for_path(&self, path: &Path) -> Option<(&Uri, &Document)> {
|
||||
if let Some(found) = self.docs.iter().find(|(_, doc)| doc.path.as_deref() == Some(path)) {
|
||||
return Some(found);
|
||||
}
|
||||
if self.docs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let target = dir_id(path)?;
|
||||
self.docs
|
||||
.iter()
|
||||
.filter(|(_, doc)| {
|
||||
doc.path.as_deref().is_some_and(|p| {
|
||||
!case_only_mismatch(p, path) && dir_id(p).as_ref() == Some(&target)
|
||||
})
|
||||
})
|
||||
.min_by_key(|(_, doc)| doc.path.as_deref())
|
||||
}
|
||||
|
||||
/// The open document backed by `path` (exact path first, else matching file
|
||||
/// identity without basename gating), 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))
|
||||
self.open_document_for_path(path).map(|(_, doc)| doc)
|
||||
}
|
||||
|
||||
/// Whether another currently open URI (distinct from `uri`) covers `path`
|
||||
/// or its file identity.
|
||||
pub(crate) fn has_other_document_for(&self, uri: &Uri, path: &Path) -> bool {
|
||||
if self.docs.len() <= 1 {
|
||||
return false;
|
||||
}
|
||||
if self.docs.iter().any(|(other, doc)| *other != *uri && doc.path.as_deref() == Some(path))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
let Some(target) = dir_id(path) else { return false };
|
||||
self.docs.iter().any(|(other, doc)| {
|
||||
*other != *uri
|
||||
&& doc.path.as_deref().is_some_and(|p| {
|
||||
!case_only_mismatch(p, path) && dir_id(p).as_ref() == Some(&target)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Every open document and its URI.
|
||||
@@ -100,21 +141,23 @@ impl Workspace {
|
||||
/// 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 {
|
||||
match self.document_for_path(path) {
|
||||
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.
|
||||
/// rules — `None` when disk is over `maxFileSize` or cannot be read.
|
||||
///
|
||||
/// An open buffer on the large-file fast path (`doc.large`) keeps its
|
||||
/// on-disk index record subject to `maxFileSize` (Topo #63, Owner
|
||||
/// decision 2), falling through to disk rather than suppressing it.
|
||||
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 let Some(doc) = self.document_for_path(path) {
|
||||
if !doc.large {
|
||||
return Some(doc.text.clone());
|
||||
}
|
||||
}
|
||||
if oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_some() {
|
||||
return None;
|
||||
@@ -128,11 +171,22 @@ impl Workspace {
|
||||
/// 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`.
|
||||
/// text, so the two always speak for the same `Document`, and facts are
|
||||
/// stamped with canonical `path`.
|
||||
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))?;
|
||||
let doc = self.document_for_path(path)?;
|
||||
(!doc.large).then(|| (doc.facts(path.to_path_buf()), doc.words()))
|
||||
}
|
||||
}
|
||||
|
||||
/// On case-insensitive filesystems, two paths differing only in ASCII case
|
||||
/// are not symlinks and should not cross-match an open buffer to disk.
|
||||
pub(super) fn case_only_mismatch(a: &Path, b: &Path) -> bool {
|
||||
if cfg!(any(target_os = "macos", target_os = "windows")) {
|
||||
a != b && a.to_string_lossy().eq_ignore_ascii_case(&b.to_string_lossy())
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -43,7 +43,7 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::{
|
||||
collect_files_below_tracked, collect_files_tracked, dir_id, DirectoryTracker, EXTENSIONS,
|
||||
collect_files_below_tracked, collect_files_tracked, dir_id, DirId, DirectoryTracker, EXTENSIONS,
|
||||
};
|
||||
|
||||
use crate::scan_trace::ScanTrace;
|
||||
@@ -110,51 +110,40 @@ pub(super) fn oversize(found: &Found, cap: u64, stats: &mut usize) -> Option<u64
|
||||
(size > cap).then_some(size)
|
||||
}
|
||||
|
||||
/// The open buffers' files by **identity**, so a walked path that is a second
|
||||
/// spelling of one of them can be recognised and left out.
|
||||
///
|
||||
/// A symlinked directory gives every file under it a second path. The walk
|
||||
/// reports each file under the first spelling that reaches it, which may not be
|
||||
/// the one the buffer was opened by — and an index holding `a_alias/tb.sv` from
|
||||
/// disk beside the open `z_real/tb.sv` holds one module twice and refuses to
|
||||
/// rename it (`docs/features/walk-cycles/README.md`).
|
||||
///
|
||||
/// **The name is the gate, and it is what keeps this free.** A directory alias
|
||||
/// cannot change a file's *name*, so a walked file whose name no open buffer
|
||||
/// shares cannot be one of them and is never stat'd: an ordinary workspace pays
|
||||
/// nothing at all, and one with same-named files pays one `metadata` per
|
||||
/// same-named candidate. A **file**-level symlink under a different name is out
|
||||
/// of scope — two names for one inode that no directory relates, which every
|
||||
/// other part of this server already treats as two files.
|
||||
struct Aliased {
|
||||
/// The names those buffers' files go by — the cheap half of the test.
|
||||
names: HashSet<std::ffi::OsString>,
|
||||
/// Their `(dev, ino)` identities, read once per open buffer rather than
|
||||
/// once per walked file.
|
||||
ids: HashSet<lucisv_core::walk::DirId>,
|
||||
}
|
||||
|
||||
impl Aliased {
|
||||
/// The identities of `paths`, with the names to gate on.
|
||||
fn of(paths: &HashSet<&Path>) -> Aliased {
|
||||
let names = paths.iter().filter_map(|p| p.file_name()).map(|n| n.to_os_string()).collect();
|
||||
let ids = paths.iter().filter_map(|p| dir_id(p)).collect();
|
||||
Aliased { names, ids }
|
||||
}
|
||||
|
||||
/// Whether `path` names a file an open buffer already speaks for, by a
|
||||
/// different spelling. `stats` counts the `metadata` calls it made.
|
||||
fn speaks_for(&self, path: &Path, stats: &mut usize) -> bool {
|
||||
if self.ids.is_empty() {
|
||||
return false;
|
||||
/// Deduplicate `files` by file identity (`(dev, ino)` on Unix / canonical path
|
||||
/// elsewhere) without basename gating, keeping the lexicographically smallest
|
||||
/// path for each identity and preserving list order. Un-statable paths (`None`)
|
||||
/// are kept individually. Also returns the identity-to-canonical-path map.
|
||||
pub(super) fn dedup_by_identity(files: Vec<Found>) -> (Vec<Found>, HashMap<DirId, PathBuf>) {
|
||||
let mut best: HashMap<DirId, usize> = HashMap::new();
|
||||
let mut has_id: Vec<bool> = Vec::with_capacity(files.len());
|
||||
for (i, found) in files.iter().enumerate() {
|
||||
if let Some(id) = dir_id(&found.path) {
|
||||
has_id.push(true);
|
||||
if let Some(prev) = best.get_mut(&id) {
|
||||
if found.path < files[*prev].path {
|
||||
*prev = i;
|
||||
}
|
||||
} else {
|
||||
best.insert(id, i);
|
||||
}
|
||||
} else {
|
||||
has_id.push(false);
|
||||
}
|
||||
let Some(name) = path.file_name() else { return false };
|
||||
if !self.names.contains(name) {
|
||||
return false;
|
||||
}
|
||||
*stats += 1;
|
||||
dir_id(path).is_some_and(|id| self.ids.contains(&id))
|
||||
}
|
||||
let mut keep = vec![false; files.len()];
|
||||
let mut by_id = HashMap::with_capacity(best.len());
|
||||
for (id, idx) in best {
|
||||
keep[idx] = true;
|
||||
by_id.insert(id, files[idx].path.clone());
|
||||
}
|
||||
let mut deduped = Vec::with_capacity(files.len());
|
||||
for (i, found) in files.into_iter().enumerate() {
|
||||
if !has_id[i] || keep[i] {
|
||||
deduped.push(found);
|
||||
}
|
||||
}
|
||||
(deduped, by_id)
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
@@ -201,62 +190,82 @@ impl Workspace {
|
||||
trace: &mut ScanTrace,
|
||||
) -> Sources {
|
||||
let cap = self.client.max_file_size;
|
||||
// Every path an open buffer speaks for. Reading such a file from disk
|
||||
// is work thrown away — the buffer's text replaces it below, whatever
|
||||
// the disk says — so the read is skipped rather than undone. The cap is
|
||||
// still consulted first, so an oversized file still reports itself
|
||||
// skipped exactly as it did before the buffer put its own text back.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
// …and every *other* spelling of those same files, which a directory
|
||||
// alias makes and a path comparison cannot see ([`Aliased`]).
|
||||
let aliased = Aliased::of(&spoken_for);
|
||||
let capping = trace.now();
|
||||
let mut stats = 0usize;
|
||||
let (deduped, scope_by_id) = dedup_by_identity(scope.files);
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for found in scope.files {
|
||||
for found in deduped {
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
watch(IndexEvent::Skipped { path: &found.path, size, cap });
|
||||
continue;
|
||||
}
|
||||
if spoken_for.contains(found.path.as_path()) {
|
||||
continue;
|
||||
}
|
||||
if aliased.speaks_for(&found.path, &mut stats) {
|
||||
continue;
|
||||
}
|
||||
files.push(found.path);
|
||||
}
|
||||
ScanTrace::add(&mut trace.cap_ms, capping);
|
||||
trace.stats += stats;
|
||||
// Open buffers override what is on disk, and contribute themselves
|
||||
// when they are not on disk at all.
|
||||
// Open non-large buffers override what is on disk for the same file
|
||||
// (under scope's deterministic canonical spelling when present in
|
||||
// scope), and contribute themselves when out of scope or oversized.
|
||||
//
|
||||
// Except a buffer on the large-file fast path, which overrides disk
|
||||
// with *nothing*: indexing it means parsing the hundred megabytes the
|
||||
// fast path exists not to parse. Removing the path rather than leaving
|
||||
// the disk copy in is the honest half of that — the alternative would
|
||||
// be an index describing a file the user is looking at by bytes it no
|
||||
// longer has. See `docs/features/large-file-mode/README.md` for the
|
||||
// interaction with `lucisv.index.maxFileSize`, whose "an open buffer is
|
||||
// never capped" rule this is the one exception to.
|
||||
// Open `doc.large` buffers (Topo #63, Owner decision 2) are skipped
|
||||
// here so their on-disk index record stays untouched subject to
|
||||
// `maxFileSize`.
|
||||
let buffering = trace.now();
|
||||
let mut analyzed = Analyzed::default();
|
||||
let mut buffered: HashMap<PathBuf, String> = HashMap::new();
|
||||
for doc in self.docs.values() {
|
||||
let Some(path) = doc.path.clone() else { continue };
|
||||
files.retain(|p| p != &path);
|
||||
if !doc.large {
|
||||
if analyses == HeldAnalyses::Wanted {
|
||||
analyzed.facts.insert(path.clone(), doc.facts(path.clone()));
|
||||
analyzed.words.insert(path.clone(), doc.words());
|
||||
let has_open_non_large = self.docs.values().any(|doc| !doc.large && doc.path.is_some());
|
||||
if has_open_non_large {
|
||||
let mut files_set: HashSet<PathBuf> = files.iter().cloned().collect();
|
||||
let mut open_candidates: Vec<(PathBuf, Option<DirId>, &super::Document)> = self
|
||||
.docs
|
||||
.values()
|
||||
.filter(|doc| !doc.large)
|
||||
.filter_map(|doc| {
|
||||
let doc_path = doc.path.as_ref()?;
|
||||
let id = dir_id(doc_path);
|
||||
let target = id
|
||||
.as_ref()
|
||||
.and_then(|key| scope_by_id.get(key))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| doc_path.clone());
|
||||
Some((target, id, doc))
|
||||
})
|
||||
.collect();
|
||||
open_candidates.sort_by(|a, b| {
|
||||
a.0.cmp(&b.0)
|
||||
.then_with(|| {
|
||||
(a.2.path.as_deref() != Some(a.0.as_path()))
|
||||
.cmp(&(b.2.path.as_deref() != Some(b.0.as_path())))
|
||||
})
|
||||
.then_with(|| a.2.path.cmp(&b.2.path))
|
||||
});
|
||||
let mut seen_targets: HashSet<PathBuf> = HashSet::new();
|
||||
let mut seen_open_ids: HashSet<DirId> = HashSet::new();
|
||||
for (target, id, doc) in open_candidates {
|
||||
if !seen_targets.insert(target.clone())
|
||||
|| id.is_some_and(|key| !seen_open_ids.insert(key))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
buffered.insert(path.clone(), doc.text.clone());
|
||||
files.push(path);
|
||||
if files_set.insert(target.clone()) {
|
||||
files.push(target.clone());
|
||||
}
|
||||
if analyses == HeldAnalyses::Wanted {
|
||||
analyzed.facts.insert(target.clone(), doc.facts(target.clone()));
|
||||
analyzed.words.insert(target.clone(), doc.words());
|
||||
}
|
||||
buffered.insert(target, doc.text.clone());
|
||||
}
|
||||
}
|
||||
ScanTrace::add(&mut trace.buffers_ms, buffering);
|
||||
Sources { files, buffered, analyzed, incdirs: scope.incdirs, warnings: scope.warnings }
|
||||
Sources {
|
||||
files,
|
||||
buffered,
|
||||
analyzed,
|
||||
canonical_ids: scope_by_id,
|
||||
incdirs: scope.incdirs,
|
||||
warnings: scope.warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/// The files the index covers, and what the user should be told about how
|
||||
@@ -296,7 +305,7 @@ impl Workspace {
|
||||
ScanTrace::add(&mut trace.filelist_ms, reading);
|
||||
match read {
|
||||
Ok(list) => Scope {
|
||||
files: list.files.into_iter().map(Found::unmeasured).collect(),
|
||||
files: dedup_by_identity(list.files.into_iter().map(Found::unmeasured).collect()).0,
|
||||
incdirs: list.incdirs,
|
||||
warnings: list.warnings,
|
||||
},
|
||||
@@ -414,6 +423,7 @@ impl Workspace {
|
||||
}
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
let (out, _) = dedup_by_identity(out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
@@ -542,12 +552,36 @@ impl Workspace {
|
||||
return (self.collect_sources(watch, HeldAnalyses::Wanted, trace), None);
|
||||
}
|
||||
// Every path the neighbourhood walk named, before the cap has had a
|
||||
// say: what the remaining walk must not decide about a second time.
|
||||
// say, plus any open non-large buffers: what the remaining walk must
|
||||
// not decide about a second time.
|
||||
let mut seen: HashSet<PathBuf> = head.iter().map(|found| found.path.clone()).collect();
|
||||
seen.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
seen.extend(self.docs.values().filter(|doc| !doc.large).filter_map(|doc| doc.path.clone()));
|
||||
let scope = Scope { files: head, incdirs: Vec::new(), warnings };
|
||||
let sources = self.overlay_buffers(scope, watch, HeldAnalyses::Wanted, trace);
|
||||
(sources, Some(PendingDiscovery { roots: self.roots.clone(), seen, tracker }))
|
||||
seen.extend(sources.files.iter().cloned());
|
||||
let mut seen_ids: HashMap<DirId, PathBuf> = HashMap::new();
|
||||
for path in &seen {
|
||||
if let Some(id) = dir_id(path) {
|
||||
seen_ids
|
||||
.entry(id)
|
||||
.and_modify(|prev| {
|
||||
if path < prev {
|
||||
*prev = path.clone();
|
||||
}
|
||||
})
|
||||
.or_insert_with(|| path.clone());
|
||||
}
|
||||
}
|
||||
(
|
||||
sources,
|
||||
Some(PendingDiscovery {
|
||||
roots: self.roots.clone(),
|
||||
seen,
|
||||
seen_ids,
|
||||
tracker,
|
||||
file_conflict: false,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether some directory between `root` and `dir` holds a **second
|
||||
@@ -614,6 +648,7 @@ impl Workspace {
|
||||
}
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
let (out, _) = dedup_by_identity(out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
@@ -646,6 +681,7 @@ impl Workspace {
|
||||
pub(super) fn rest_of_scope(
|
||||
&self,
|
||||
pending: &mut PendingDiscovery,
|
||||
canonical_ids: &mut HashMap<DirId, PathBuf>,
|
||||
watch: &mut dyn FnMut(IndexEvent),
|
||||
trace: &mut ScanTrace,
|
||||
) -> (Vec<PathBuf>, Vec<String>, usize) {
|
||||
@@ -657,30 +693,52 @@ impl Workspace {
|
||||
&mut |w| warnings.push(w),
|
||||
trace,
|
||||
);
|
||||
// The same gate the neighbourhood applied: a file an open buffer
|
||||
// already speaks for, reached here by **another** spelling (a
|
||||
// same-named file symlink outside the head), must not be indexed a
|
||||
// second time. The buffer's own spelling is not an alias — a buffer
|
||||
// opened mid-scan is discovered here for the first time and must land
|
||||
// in the work list — so the gate is asked only about other paths.
|
||||
// Found by QA on §62.1, twice: the head walk had the gate and this walk
|
||||
// did not; then the gate matched a mid-scan buffer against itself.
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let aliased = Aliased::of(&spoken_for);
|
||||
let mut open_ids: HashMap<DirId, PathBuf> = HashMap::new();
|
||||
for doc in self.docs.values().filter(|doc| !doc.large) {
|
||||
let Some(path) = doc.path.as_ref() else { continue };
|
||||
if let Some(id) = dir_id(path) {
|
||||
open_ids
|
||||
.entry(id)
|
||||
.and_modify(|prev| {
|
||||
if path < prev {
|
||||
*prev = path.clone();
|
||||
}
|
||||
})
|
||||
.or_insert_with(|| path.clone());
|
||||
}
|
||||
}
|
||||
let cap = self.client.max_file_size;
|
||||
let capping = trace.now();
|
||||
let mut stats = 0usize;
|
||||
let mut skipped = 0usize;
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for found in walked {
|
||||
// Already decided about by the neighbourhood: indexed, capped out,
|
||||
// or spoken for by an open buffer. Deciding again would step a
|
||||
// file twice or report one skip as two.
|
||||
let another_spelling = !spoken_for.contains(found.path.as_path());
|
||||
if seen.contains(&found.path)
|
||||
|| (another_spelling && aliased.speaks_for(&found.path, &mut stats))
|
||||
{
|
||||
if let Some(id) = dir_id(&found.path) {
|
||||
let dup = if !pending.seen_ids.is_empty() || !open_ids.is_empty() {
|
||||
pending.seen_ids.get(&id).or_else(|| open_ids.get(&id))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let is_dup = dup.is_some();
|
||||
let conflict = dup.is_some_and(|already| &found.path < already);
|
||||
if !pending.seen_ids.contains_key(&id) {
|
||||
canonical_ids
|
||||
.entry(id)
|
||||
.and_modify(|prev| {
|
||||
if found.path < *prev {
|
||||
*prev = found.path.clone();
|
||||
}
|
||||
})
|
||||
.or_insert_with(|| found.path.clone());
|
||||
}
|
||||
if is_dup {
|
||||
if conflict {
|
||||
pending.file_conflict = true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if seen.contains(&found.path) {
|
||||
continue;
|
||||
}
|
||||
if let Some(size) = oversize(&found, cap, &mut stats) {
|
||||
@@ -783,6 +841,7 @@ fn sibling_files(dirs: &[PathBuf], trace: &mut ScanTrace) -> Vec<Found> {
|
||||
trace.walk_dirs += dirs.len();
|
||||
let sorting = trace.now();
|
||||
sort_found(&mut out);
|
||||
let (out, _) = dedup_by_identity(out);
|
||||
ScanTrace::add(&mut trace.sort_ms, sorting);
|
||||
out
|
||||
}
|
||||
|
||||
@@ -8,8 +8,6 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::walk::dir_id;
|
||||
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::Workspace;
|
||||
@@ -71,9 +69,13 @@ impl Workspace {
|
||||
/// [`WorkspaceIndex::update_facts`]: vlog_semantic::WorkspaceIndex::update_facts
|
||||
/// [`WorkspaceIndex::remove_file`]: vlog_semantic::WorkspaceIndex::remove_file
|
||||
pub fn update_one_file(&mut self, path: &Path) -> OneFile {
|
||||
if self.index.file_id(path).is_none() {
|
||||
let Some(held_id) = self.index_file_id(path) else {
|
||||
return self.add_open_buffer(path);
|
||||
}
|
||||
};
|
||||
let Some(held_path) = self.index.path(held_id).map(Path::to_path_buf) else {
|
||||
return OneFile::NotHeld;
|
||||
};
|
||||
let path = held_path.as_path();
|
||||
// Re-indexing one file *is* the claim that its bytes moved.
|
||||
self.forget_view(path);
|
||||
let Some(text) = self.current_text(path) else {
|
||||
@@ -134,14 +136,13 @@ impl Workspace {
|
||||
let Some((facts, words)) = self.analysis_of(path) else { return OneFile::NotHeld };
|
||||
let Some(text) = self.current_text(path) else { return OneFile::NotHeld };
|
||||
if self.holds_another_spelling_of(path) {
|
||||
// A rebuild would take the buffer's spelling *instead of* the
|
||||
// held one (`discover.rs`'s `Aliased`), which is not an add.
|
||||
return OneFile::NotHeld;
|
||||
}
|
||||
let (symbols, macros) = facts.declared_names();
|
||||
let symbols: HashSet<String> = symbols.into_iter().map(str::to_string).collect();
|
||||
let macros: HashSet<String> = macros.into_iter().map(str::to_string).collect();
|
||||
self.index.update_facts(facts);
|
||||
self.invalidate_identities();
|
||||
self.candidates.set_file_words(path, words);
|
||||
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
|
||||
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
|
||||
@@ -154,28 +155,79 @@ impl Workspace {
|
||||
OneFile::Changed
|
||||
}
|
||||
|
||||
/// Whether the index holds the file at `path` under another name — a
|
||||
/// directory alias — by the test the scan's own overlay applies: the same
|
||||
/// file name, then the same `(dev, ino)`.
|
||||
/// Whether the index holds the file at `path` under another name or
|
||||
/// symlink spelling, matching `(dev, ino)` (or canonical path elsewhere)
|
||||
/// without basename gating.
|
||||
fn holds_another_spelling_of(&self, path: &Path) -> bool {
|
||||
let Some(id) = dir_id(path) else { return false };
|
||||
let named = |held: &&PathBuf| held.file_name() == path.file_name();
|
||||
// By reference: the id is `Copy` on unix and an owned path elsewhere.
|
||||
self.index.files().iter().filter(named).any(|held| dir_id(held).as_ref() == Some(&id))
|
||||
self.index_file_id(path).is_some()
|
||||
}
|
||||
|
||||
/// The half of [`Workspace::update_one_file`] for a held file that is
|
||||
/// gone, capped or unreadable. The files whose `` `include``s could name
|
||||
/// it are re-resolved, because their lines resolve against the disk and a
|
||||
/// deleted file is no longer there to find.
|
||||
fn remove_one(&mut self, path: &Path) {
|
||||
/// gone, capped or unreadable. Uses fast tombstoned removal plus localized
|
||||
/// `candidates` name refreshing (`set_file_words` + `refresh_names`).
|
||||
pub(super) fn remove_one(&mut self, path: &Path) {
|
||||
let declared = self.index.facts_for(path).map(|facts| {
|
||||
let (symbols, macros) = facts.declared_names();
|
||||
(
|
||||
symbols.into_iter().map(str::to_string).collect::<Vec<_>>(),
|
||||
macros.into_iter().map(str::to_string).collect::<Vec<_>>(),
|
||||
)
|
||||
});
|
||||
self.index.remove_file(path);
|
||||
self.candidates.remove_file(&self.index, path);
|
||||
self.invalidate_identities();
|
||||
self.candidates.set_file_words(path, Vec::new());
|
||||
if let Some((symbols, macros)) = declared {
|
||||
let symbols: HashSet<&str> = symbols.iter().map(String::as_str).collect();
|
||||
let macros: HashSet<&str> = macros.iter().map(String::as_str).collect();
|
||||
self.candidates.refresh_names(&self.index, &symbols, ¯os);
|
||||
}
|
||||
self.includes.remove_file(path, self.index.files());
|
||||
self.includes.refresh_naming(path);
|
||||
self.refresh_overlays();
|
||||
}
|
||||
|
||||
/// Whether closing `uri` while a scan is running affects the scan's work
|
||||
/// list (buffer already absorbed into the running scan, another open
|
||||
/// buffer sharing the same path/file, excluded/unlisted file that may
|
||||
/// have been taken in, or unsaved edits in a non-large buffer).
|
||||
pub fn closing_affects_running_scan(&self, uri: &lsp_types::Uri) -> bool {
|
||||
let Some(doc) = self.document(uri) else { return false };
|
||||
let Some(path) = doc.path.as_deref() else { return false };
|
||||
let target = self.held_path_for(path).unwrap_or_else(|| path.to_path_buf());
|
||||
if self.scan_absorbed.contains(path, &target) || self.has_other_document_for(uri, path) {
|
||||
return true;
|
||||
}
|
||||
if !self.scope_could_take(&target) {
|
||||
return !doc.large;
|
||||
}
|
||||
!doc.large && std::fs::read_to_string(&target).ok().as_ref() != Some(&doc.text)
|
||||
}
|
||||
|
||||
/// Close `uri` and, when `reconcile_index` is true, reconcile `self.index`
|
||||
/// with the post-close state: remove excluded/unlisted or missing files via
|
||||
/// the fast tombstoned `remove_one` path, or re-index in-scope files from
|
||||
/// disk (or surviving buffer) via `update_one_file`. Returns whether the
|
||||
/// index moved.
|
||||
pub fn close_and_reconcile(&mut self, uri: &lsp_types::Uri, reconcile_index: bool) -> bool {
|
||||
let closing_path = self.document(uri).and_then(|doc| doc.path.clone());
|
||||
self.close_document(uri);
|
||||
if !reconcile_index {
|
||||
return false;
|
||||
}
|
||||
let Some(path) = closing_path else { return false };
|
||||
let Some(held_path) = self.held_path_for(&path) else {
|
||||
return false;
|
||||
};
|
||||
if self.document_for_path(&held_path).is_some() {
|
||||
return self.update_one_file(&held_path) == OneFile::Changed;
|
||||
}
|
||||
if !self.scope_could_take(&held_path) {
|
||||
self.remove_one(&held_path);
|
||||
return true;
|
||||
}
|
||||
self.update_one_file(&held_path) == OneFile::Changed
|
||||
}
|
||||
|
||||
/// Files appeared, vanished or moved at `paths`, wherever they are: the
|
||||
/// include lines that could name any of them are re-resolved, in one pass.
|
||||
/// The whole of what such an event owes the graph for a file the index
|
||||
@@ -256,12 +308,46 @@ impl Workspace {
|
||||
/// buffer's cross-file answers.
|
||||
#[cfg(test)]
|
||||
pub fn derived_fingerprint(&self) -> String {
|
||||
let dense: std::collections::HashMap<vlog_semantic::FileId, u32> = self
|
||||
.index
|
||||
.files()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(live, path)| Some((self.index.file_id(path)?, live as u32)))
|
||||
.collect();
|
||||
let remap_def = |def: &vlog_semantic::Def| {
|
||||
let mut remapped = def.clone();
|
||||
if let Some(&id) = dense.get(&def.file) {
|
||||
remapped.file = vlog_semantic::FileId(id);
|
||||
}
|
||||
remapped
|
||||
};
|
||||
let mut docs: Vec<(&lsp_types::Uri, &super::Document)> = self.docs.iter().collect();
|
||||
docs.sort_by_key(|(uri, _)| uri.as_str());
|
||||
let overlays: Vec<String> = docs
|
||||
.iter()
|
||||
.map(|(uri, doc)| {
|
||||
format!("{} {:?}", uri.as_str(), doc.external.iter().collect::<Vec<_>>())
|
||||
let mapped: Vec<_> = doc
|
||||
.external
|
||||
.iter()
|
||||
.map(|(id, target)| {
|
||||
let mapped = match target {
|
||||
vlog_semantic::ExternalTarget::Resolved(def) => {
|
||||
vlog_semantic::ExternalTarget::Resolved(remap_def(def))
|
||||
}
|
||||
vlog_semantic::ExternalTarget::Ambiguous(defs) => {
|
||||
vlog_semantic::ExternalTarget::Ambiguous(
|
||||
defs.iter().map(remap_def).collect(),
|
||||
)
|
||||
}
|
||||
vlog_semantic::ExternalTarget::StillUnresolved => {
|
||||
vlog_semantic::ExternalTarget::StillUnresolved
|
||||
}
|
||||
};
|
||||
(id, mapped)
|
||||
})
|
||||
.collect();
|
||||
format!("{} {:?}", uri.as_str(), mapped)
|
||||
})
|
||||
.collect();
|
||||
format!(
|
||||
|
||||
@@ -15,12 +15,13 @@
|
||||
//! and `sources` (the file sets handed to refactorings).
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use lsp_types::Uri;
|
||||
use vlog_semantic::{FileFacts, WorkspaceIndex};
|
||||
use lucisv_core::walk::{dir_id, DirId};
|
||||
use vlog_semantic::{FileFacts, FileId, WorkspaceIndex};
|
||||
|
||||
use crate::candidates::Candidates;
|
||||
use crate::includes::IncludeGraph;
|
||||
@@ -33,6 +34,7 @@ pub(crate) mod discover;
|
||||
mod document;
|
||||
mod incremental;
|
||||
mod port_grace;
|
||||
mod reconcile;
|
||||
mod rescan;
|
||||
mod scan;
|
||||
mod scope;
|
||||
@@ -117,6 +119,10 @@ pub struct Workspace {
|
||||
/// without changing an answer, and every way a file's text can move drops
|
||||
/// its entry (see [`Workspace::file_view`]).
|
||||
views: RefCell<Vec<Rc<FileView>>>,
|
||||
/// Lazy reverse map from physical file identity (`(dev, ino)` on Unix,
|
||||
/// canonical path elsewhere) to the canonical path stored in `index`.
|
||||
/// Cleared whenever `index`'s live path set mutates.
|
||||
identities: RefCell<Option<HashMap<DirId, PathBuf>>>,
|
||||
/// The trace of the scan that finished most recently, waiting for the
|
||||
/// server to read it out and log it. Held here rather than returned from
|
||||
/// [`Workspace::finish_scan`] so that no caller's signature moves for a
|
||||
@@ -129,6 +135,45 @@ pub struct Workspace {
|
||||
/// is in, while that entry's diagnostics are held back
|
||||
/// (`docs/features/port-entry-grace/README.md`).
|
||||
grace: PortGrace,
|
||||
/// Open-buffer paths and physical file identities whose text or analysis
|
||||
/// was absorbed into the currently running scan, cleared at `begin_scan`
|
||||
/// and `finish_scan`.
|
||||
scan_absorbed: ScanAbsorbed,
|
||||
}
|
||||
|
||||
/// Open-buffer paths and physical file identities absorbed into an active scan.
|
||||
#[derive(Default)]
|
||||
pub(super) struct ScanAbsorbed {
|
||||
paths: HashSet<PathBuf>,
|
||||
ids: HashMap<DirId, PathBuf>,
|
||||
}
|
||||
|
||||
impl ScanAbsorbed {
|
||||
pub(super) fn clear(&mut self) {
|
||||
self.paths.clear();
|
||||
self.ids.clear();
|
||||
}
|
||||
|
||||
pub(super) fn record(&mut self, target: &Path, open_path: Option<&Path>, id: Option<&DirId>) {
|
||||
self.paths.insert(target.to_path_buf());
|
||||
if let Some(open) = open_path {
|
||||
self.paths.insert(open.to_path_buf());
|
||||
}
|
||||
if let Some(id) =
|
||||
id.cloned().or_else(|| dir_id(target)).or_else(|| open_path.and_then(dir_id))
|
||||
{
|
||||
self.ids.entry(id).or_insert_with(|| target.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn contains(&self, path: &Path, target: &Path) -> bool {
|
||||
if self.paths.contains(target) || self.paths.contains(path) {
|
||||
return true;
|
||||
}
|
||||
let Some(id) = dir_id(path) else { return false };
|
||||
let Some(absorbed) = self.ids.get(&id) else { return false };
|
||||
!buffers::case_only_mismatch(absorbed, path)
|
||||
}
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
@@ -136,6 +181,58 @@ impl Workspace {
|
||||
&self.index
|
||||
}
|
||||
|
||||
pub(super) fn invalidate_identities(&self) {
|
||||
*self.identities.borrow_mut() = None;
|
||||
}
|
||||
|
||||
/// Resolve `path` to its indexed [`FileId`], matching exact spelling first
|
||||
/// and falling back to file identity (`(dev, ino)` / canonical path) so
|
||||
/// symlinked spellings resolve to the same index slot while preserving
|
||||
/// ASCII case-mismatch separation.
|
||||
pub fn index_file_id(&self, path: &Path) -> Option<FileId> {
|
||||
if let Some(id) = self.index.file_id(path) {
|
||||
return Some(id);
|
||||
}
|
||||
let target = dir_id(path)?;
|
||||
let mut cache = self.identities.borrow_mut();
|
||||
let map = cache.get_or_insert_with(|| {
|
||||
let mut map = HashMap::with_capacity(self.index.files().len());
|
||||
for held in self.index.files() {
|
||||
if let Some(id) = dir_id(held) {
|
||||
map.entry(id).or_insert_with(|| held.clone());
|
||||
}
|
||||
}
|
||||
map
|
||||
});
|
||||
let held = map.get(&target)?;
|
||||
(!buffers::case_only_mismatch(held, path)).then(|| self.index.file_id(held)).flatten()
|
||||
}
|
||||
|
||||
/// The canonical path `self.index` holds for `path`, matching either exact
|
||||
/// path or file identity.
|
||||
pub fn held_path_for(&self, path: &Path) -> Option<PathBuf> {
|
||||
self.index_file_id(path).and_then(|id| self.index.path(id).map(Path::to_path_buf))
|
||||
}
|
||||
|
||||
/// The canonical indexed path for `path`, falling back to `path` itself
|
||||
/// when not currently in the index.
|
||||
pub fn index_path_for(&self, path: &Path) -> PathBuf {
|
||||
self.held_path_for(path).unwrap_or_else(|| path.to_path_buf())
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` refer to the same physical file (matching exact
|
||||
/// path or `(dev, ino)` / canonical path while preserving ASCII
|
||||
/// case-mismatch separation).
|
||||
pub fn is_same_file(&self, a: &Path, b: &Path) -> bool {
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if buffers::case_only_mismatch(a, b) {
|
||||
return false;
|
||||
}
|
||||
dir_id(a).is_some_and(|id| dir_id(b).as_ref() == Some(&id))
|
||||
}
|
||||
|
||||
/// The index record this workspace already holds for **exactly these
|
||||
/// bytes**, or nothing.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,261 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Reconciling open buffers (mid-scan, widen, and `largeFile.threshold`
|
||||
//! drops) with the workspace index and active scan state.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lsp_types::Uri;
|
||||
use lucisv_core::walk::{dir_id, DirId};
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::{oversize, Found};
|
||||
use super::scan::{Analyzed, Scan, ScanKind};
|
||||
use super::{OneFile, Workspace};
|
||||
use crate::includes;
|
||||
|
||||
/// Accumulated file-set state passed between [`Workspace::begin_widen`] and
|
||||
/// [`Workspace::reconcile_widen_buffers`].
|
||||
pub(super) struct WidenOverlay {
|
||||
pub(super) files: Vec<PathBuf>,
|
||||
pub(super) files_set: HashSet<PathBuf>,
|
||||
pub(super) file_ids: HashMap<DirId, PathBuf>,
|
||||
pub(super) gone: Vec<PathBuf>,
|
||||
pub(super) gone_set: HashSet<PathBuf>,
|
||||
pub(super) held: HashSet<PathBuf>,
|
||||
pub(super) held_ids: HashMap<DirId, PathBuf>,
|
||||
pub(super) widened_by_id: HashMap<DirId, PathBuf>,
|
||||
pub(super) analyzed: Analyzed,
|
||||
pub(super) buffered: HashMap<PathBuf, String>,
|
||||
pub(super) stats: usize,
|
||||
}
|
||||
|
||||
impl Workspace {
|
||||
/// Overlay non-large open buffers onto their deterministic canonical paths
|
||||
/// and reconcile held `doc.large` buffers back to disk (subject to
|
||||
/// `maxFileSize`) during [`Workspace::begin_widen`].
|
||||
pub(super) fn reconcile_widen_buffers(&self, w: &mut WidenOverlay) {
|
||||
let mut candidates: Vec<(bool, &PathBuf, Option<DirId>, PathBuf, &super::Document)> = self
|
||||
.docs
|
||||
.values()
|
||||
.filter(|doc| !doc.large)
|
||||
.filter_map(|doc| {
|
||||
let doc_path = doc.path.as_ref()?;
|
||||
let id = dir_id(doc_path);
|
||||
let target = id
|
||||
.as_ref()
|
||||
.and_then(|k| {
|
||||
w.file_ids
|
||||
.get(k)
|
||||
.or_else(|| w.held_ids.get(k).filter(|p| !w.gone_set.contains(*p)))
|
||||
.or_else(|| w.widened_by_id.get(k))
|
||||
})
|
||||
.cloned()
|
||||
.unwrap_or_else(|| doc_path.clone());
|
||||
Some((doc_path != &target, doc_path, id, target, doc))
|
||||
})
|
||||
.collect();
|
||||
candidates.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(b.1)));
|
||||
let mut seen_open_ids: HashSet<DirId> = HashSet::new();
|
||||
let mut overlaid: HashSet<PathBuf> = HashSet::new();
|
||||
for (_, _, doc_id, target, doc) in candidates {
|
||||
if overlaid.contains(&target) || doc_id.is_some_and(|id| !seen_open_ids.insert(id)) {
|
||||
continue;
|
||||
}
|
||||
overlaid.insert(target.clone());
|
||||
if w.files_set.insert(target.clone()) {
|
||||
w.files.push(target.clone());
|
||||
}
|
||||
w.analyzed.facts.insert(target.clone(), doc.facts(target.clone()));
|
||||
w.analyzed.words.insert(target.clone(), doc.words());
|
||||
w.buffered.insert(target, doc.text.clone());
|
||||
}
|
||||
// Owner decision 2 (Topo #63): keep disk index records for `doc.large`
|
||||
// buffers (subject to `maxFileSize`), dropping only missing/oversize ones.
|
||||
let cap = self.client.max_file_size;
|
||||
for doc in self.docs.values().filter(|doc| doc.large) {
|
||||
let Some(doc_path) = doc.path.as_ref() else { continue };
|
||||
let target = match dir_id(doc_path).and_then(|id| w.held_ids.get(&id)) {
|
||||
Some(path) => path.clone(),
|
||||
None if w.held.contains(doc_path) => doc_path.clone(),
|
||||
None => continue,
|
||||
};
|
||||
if overlaid.contains(&target)
|
||||
|| w.gone_set.contains(&target)
|
||||
|| w.files_set.contains(&target)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if std::fs::metadata(&target).is_err()
|
||||
|| oversize(&Found::of(&target), cap, &mut w.stats).is_some()
|
||||
{
|
||||
if w.gone_set.insert(target.clone()) {
|
||||
w.gone.push(target);
|
||||
}
|
||||
} else if w.files_set.insert(target.clone()) {
|
||||
w.files.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconcile open non-large buffers opened (or updated) mid-scan into
|
||||
/// `scan` so excluded, unlisted, or unsaved buffers — including symlinks
|
||||
/// whose canonical spelling was skipped by `maxFileSize` — absorb
|
||||
/// identically to opening before the scan starts (Topo #50, #51).
|
||||
pub(super) fn reconcile_open_buffers_into(&mut self, scan: &mut Scan) {
|
||||
let mut open_non_large: Vec<&super::Document> =
|
||||
self.docs.values().filter(|doc| !doc.large && doc.path.is_some()).collect();
|
||||
if open_non_large.is_empty() {
|
||||
return;
|
||||
}
|
||||
open_non_large.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
let work_pos: HashMap<PathBuf, usize> =
|
||||
scan.work.iter().enumerate().map(|(i, p)| (p.clone(), i)).collect();
|
||||
let mut work_ids: HashMap<DirId, usize> = HashMap::with_capacity(scan.work.len());
|
||||
for (i, p) in scan.work.iter().enumerate() {
|
||||
if let Some(id) = dir_id(p) {
|
||||
work_ids.entry(id).or_insert(i);
|
||||
}
|
||||
}
|
||||
let mut paths_set: HashSet<PathBuf> = scan.paths.iter().cloned().collect();
|
||||
let mut paths_changed = false;
|
||||
let mut added_ids: HashSet<DirId> = HashSet::new();
|
||||
let mut added_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut matched_positions: HashSet<usize> = HashSet::new();
|
||||
|
||||
struct RankedDoc {
|
||||
non_exact: bool,
|
||||
path: PathBuf,
|
||||
target: PathBuf,
|
||||
pos: Option<usize>,
|
||||
id: Option<DirId>,
|
||||
text: String,
|
||||
facts: FileFacts,
|
||||
words: Vec<String>,
|
||||
}
|
||||
let mut ranked: Vec<RankedDoc> = open_non_large
|
||||
.into_iter()
|
||||
.filter_map(|doc| {
|
||||
let path = doc.path.as_ref()?;
|
||||
let id = dir_id(path);
|
||||
let pos = work_pos
|
||||
.get(path)
|
||||
.copied()
|
||||
.or_else(|| id.as_ref().and_then(|k| work_ids.get(k).copied()));
|
||||
let target = pos
|
||||
.map(|i| scan.work[i].clone())
|
||||
.or_else(|| id.as_ref().and_then(|k| scan.canonical_ids.get(k)).cloned())
|
||||
.unwrap_or_else(|| path.clone());
|
||||
let non_exact = target != *path;
|
||||
Some(RankedDoc {
|
||||
non_exact,
|
||||
path: path.clone(),
|
||||
target: target.clone(),
|
||||
pos,
|
||||
id,
|
||||
text: doc.text.clone(),
|
||||
facts: doc.facts(target),
|
||||
words: doc.words(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
ranked.sort_by(|a, b| a.non_exact.cmp(&b.non_exact).then_with(|| a.path.cmp(&b.path)));
|
||||
|
||||
for RankedDoc { path, target, pos, id, text, facts, words, .. } in ranked {
|
||||
if let Some(pos) = pos {
|
||||
if !matched_positions.insert(pos) {
|
||||
continue;
|
||||
}
|
||||
let target = scan.work[pos].clone();
|
||||
if pos >= scan.at {
|
||||
self.scan_absorbed.record(&target, Some(&path), id.as_ref());
|
||||
scan.buffered.insert(target.clone(), text);
|
||||
if scan.kind == ScanKind::Whole {
|
||||
scan.analyzed.facts.insert(target.clone(), facts);
|
||||
scan.analyzed.words.insert(target, words);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let was_unread = scan.unread.contains(&target);
|
||||
scan.unread.retain(|p| p != &target);
|
||||
let staged_match = scan
|
||||
.staged_at
|
||||
.iter()
|
||||
.position(|&p| p == pos)
|
||||
.map(|idx| scan.staged[idx] == facts);
|
||||
let already_same = !was_unread
|
||||
&& match staged_match {
|
||||
Some(eq) => eq,
|
||||
None => self.index.facts_for(&target) == Some(&facts),
|
||||
};
|
||||
if already_same {
|
||||
continue;
|
||||
}
|
||||
self.scan_absorbed.record(&target, Some(&path), id.as_ref());
|
||||
self.open_store(&mut scan.trace);
|
||||
self.cache.record(&facts, &text);
|
||||
scan.includes.insert(target.clone(), includes::scan(&text));
|
||||
scan.words.insert(target, words);
|
||||
if let Some(idx) = scan.staged_at.iter().position(|&p| p == pos) {
|
||||
scan.staged[idx] = facts;
|
||||
} else {
|
||||
scan.staged.push(facts);
|
||||
scan.staged_at.push(pos);
|
||||
}
|
||||
} else {
|
||||
if id.as_ref().is_some_and(|k| added_ids.contains(k))
|
||||
|| added_paths.contains(&target)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
self.scan_absorbed.record(&target, Some(&path), id.as_ref());
|
||||
if let Some(k) = id {
|
||||
added_ids.insert(k);
|
||||
}
|
||||
added_paths.insert(target.clone());
|
||||
scan.work.push(target.clone());
|
||||
if paths_set.insert(target.clone()) {
|
||||
scan.paths.push(target.clone());
|
||||
paths_changed = true;
|
||||
}
|
||||
scan.buffered.insert(target.clone(), text);
|
||||
scan.analyzed.facts.insert(target.clone(), facts);
|
||||
scan.analyzed.words.insert(target, words);
|
||||
}
|
||||
}
|
||||
if paths_changed {
|
||||
scan.paths.sort();
|
||||
scan.paths.dedup();
|
||||
}
|
||||
}
|
||||
|
||||
/// Reconcile `held_path` in the index after `uri` flipped into `doc.large`:
|
||||
/// drop excluded/oversize/missing entries or restore the disk record when
|
||||
/// unsaved edits were previously indexed, skipping work when the disk
|
||||
/// record already matches (Topo #63).
|
||||
pub fn reconcile_large_buffer(
|
||||
&mut self,
|
||||
uri: &Uri,
|
||||
held_path: &Path,
|
||||
prev_facts: &FileFacts,
|
||||
) -> bool {
|
||||
let Some(doc) = self.document(uri) else { return false };
|
||||
if !doc.large {
|
||||
return false;
|
||||
}
|
||||
if !self.scope_could_take(held_path) {
|
||||
self.remove_one(held_path);
|
||||
return true;
|
||||
}
|
||||
if !self.has_other_document_for(uri, held_path)
|
||||
&& self.index.facts_for(held_path) == Some(prev_facts)
|
||||
&& std::fs::read_to_string(held_path).ok().as_ref() == Some(&doc.text)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.update_one_file(held_path) == OneFile::Changed
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -11,8 +11,9 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
use super::discover::oversize;
|
||||
use super::scan::{self, Analyzed, IndexEvent, Scan, ScanKind};
|
||||
use super::discover::{dedup_by_identity, oversize};
|
||||
use super::reconcile::WidenOverlay;
|
||||
use super::scan::{self, IndexEvent, Scan, ScanKind};
|
||||
use super::{StoreOpen, Workspace};
|
||||
use crate::candidates::Candidates;
|
||||
use crate::includes::{self, IncludeGraph};
|
||||
@@ -21,6 +22,7 @@ use crate::scan_order::{self, WorkList};
|
||||
use crate::scan_trace::{CacheWork, ScanTrace};
|
||||
#[cfg(test)]
|
||||
use crate::settings::IndexScope;
|
||||
use lucisv_core::walk::{dir_id, DirId};
|
||||
|
||||
impl Workspace {
|
||||
/// Take the work list one scan will run through: resolve the scope and put
|
||||
@@ -35,6 +37,7 @@ impl Workspace {
|
||||
/// 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 {
|
||||
self.scan_absorbed.clear();
|
||||
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.
|
||||
@@ -57,6 +60,19 @@ impl Workspace {
|
||||
ScanTrace::add(&mut trace.discovery_ms, discovering);
|
||||
let buffered = std::mem::take(&mut scope.buffered);
|
||||
let analyzed = std::mem::take(&mut scope.analyzed);
|
||||
let canonical_ids = std::mem::take(&mut scope.canonical_ids);
|
||||
for path in buffered.keys().chain(analyzed.facts.keys()) {
|
||||
self.scan_absorbed.record(path, None, None);
|
||||
}
|
||||
for doc in self.docs.values().filter(|doc| !doc.large) {
|
||||
let Some(doc_path) = doc.path.as_deref() else { continue };
|
||||
let id = dir_id(doc_path);
|
||||
let target =
|
||||
id.as_ref().and_then(|k| canonical_ids.get(k)).map_or(doc_path, PathBuf::as_path);
|
||||
if buffered.contains_key(target) || analyzed.facts.contains_key(target) {
|
||||
self.scan_absorbed.record(target, Some(doc_path), id.as_ref());
|
||||
}
|
||||
}
|
||||
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.
|
||||
@@ -89,6 +105,7 @@ impl Workspace {
|
||||
paths,
|
||||
gone: Vec::new(),
|
||||
analyzed,
|
||||
canonical_ids,
|
||||
incdirs: scope.incdirs,
|
||||
warnings: scope.warnings,
|
||||
at: 0,
|
||||
@@ -141,70 +158,87 @@ impl Workspace {
|
||||
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 mut held_ids: HashMap<DirId, PathBuf> = HashMap::new();
|
||||
for path in &held {
|
||||
if let Some(id) = dir_id(path) {
|
||||
held_ids.entry(id).or_insert_with(|| path.clone());
|
||||
}
|
||||
}
|
||||
let cap = self.client.max_file_size;
|
||||
let spoken_for: HashSet<&Path> =
|
||||
self.docs.values().filter_map(|doc| doc.path.as_deref()).collect();
|
||||
let open_non_large_ids: HashSet<DirId> = self
|
||||
.docs
|
||||
.values()
|
||||
.filter(|doc| !doc.large)
|
||||
.filter_map(|doc| doc.path.as_deref().and_then(dir_id))
|
||||
.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 gone: Vec<PathBuf> = Vec::new();
|
||||
let mut gone_set: HashSet<PathBuf> = HashSet::new();
|
||||
let mut stats = 0usize;
|
||||
for found in self.widened_files(added, &mut |w| warnings.push(w), &mut trace) {
|
||||
let (widened, widened_by_id) =
|
||||
dedup_by_identity(self.widened_files(added, &mut |w| warnings.push(w), &mut trace));
|
||||
for found in widened {
|
||||
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(id) = dir_id(&path) {
|
||||
if let Some(existing) = held_ids.get(&id).cloned() {
|
||||
if path < existing
|
||||
&& (open_non_large_ids.contains(&id)
|
||||
|| oversize(&found, cap, &mut stats).is_none())
|
||||
{
|
||||
if gone_set.insert(existing.clone()) {
|
||||
gone.push(existing);
|
||||
}
|
||||
held_ids.insert(id, path.clone());
|
||||
files.push(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;
|
||||
let mut file_ids: HashMap<DirId, PathBuf> = HashMap::new();
|
||||
for path in &files {
|
||||
if let Some(id) = dir_id(path) {
|
||||
file_ids.entry(id).or_insert_with(|| path.clone());
|
||||
}
|
||||
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);
|
||||
}
|
||||
let files_set: HashSet<PathBuf> = files.iter().cloned().collect();
|
||||
let mut overlay = WidenOverlay {
|
||||
files,
|
||||
files_set,
|
||||
file_ids,
|
||||
gone,
|
||||
gone_set,
|
||||
held,
|
||||
held_ids,
|
||||
widened_by_id,
|
||||
analyzed: Default::default(),
|
||||
buffered: HashMap::new(),
|
||||
stats,
|
||||
};
|
||||
self.reconcile_widen_buffers(&mut overlay);
|
||||
let WidenOverlay { files, mut gone, gone_set, held, analyzed, buffered, .. } = overlay;
|
||||
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.
|
||||
self.views
|
||||
.borrow_mut()
|
||||
.retain(|view| !gone_set.contains(&view.path) && !work.contains(&view.path));
|
||||
let mut paths: Vec<PathBuf> =
|
||||
held.into_iter().filter(|path| !gone.contains(path)).collect();
|
||||
held.into_iter().filter(|path| !gone_set.contains(path)).collect();
|
||||
paths.extend(work.iter().cloned());
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
@@ -219,6 +253,7 @@ impl Workspace {
|
||||
paths,
|
||||
gone,
|
||||
analyzed,
|
||||
canonical_ids: HashMap::new(),
|
||||
// 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.
|
||||
@@ -259,11 +294,21 @@ impl Workspace {
|
||||
}
|
||||
watch(event);
|
||||
};
|
||||
self.rest_of_scope(&mut pending, &mut counting, &mut scan.trace)
|
||||
self.rest_of_scope(
|
||||
&mut pending,
|
||||
&mut scan.canonical_ids,
|
||||
&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.land_discovery(
|
||||
files,
|
||||
warnings,
|
||||
walked_skips,
|
||||
pending.tracker.has_conflict() || pending.file_conflict,
|
||||
);
|
||||
scan.trace.measure_work(
|
||||
scan.work.len(),
|
||||
held_bytes(&scan.buffered),
|
||||
@@ -323,10 +368,15 @@ impl Workspace {
|
||||
// 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 from_buffer =
|
||||
scan.buffered.contains_key(&path) || scan.analyzed.facts.contains_key(&path);
|
||||
let Some(source) = scan.take_text(&path) else {
|
||||
scan.unread.push(path);
|
||||
return true;
|
||||
};
|
||||
if from_buffer {
|
||||
self.scan_absorbed.record(&path, None, None);
|
||||
}
|
||||
let text = source.as_str();
|
||||
let held = scan.analyzed.facts.remove(&path);
|
||||
let known_words = scan.analyzed.words.remove(&path);
|
||||
@@ -415,6 +465,7 @@ impl Workspace {
|
||||
/// (`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);
|
||||
self.reconcile_open_buffers_into(scan);
|
||||
let ordered = self.open_first(scan.remaining());
|
||||
scan.reorder(ordered);
|
||||
}
|
||||
@@ -441,6 +492,7 @@ impl Workspace {
|
||||
let taken = std::mem::take(&mut scan.staged_at);
|
||||
let absorbing = scan.trace.now();
|
||||
self.index.absorb(std::mem::take(&mut scan.staged), &[]);
|
||||
self.invalidate_identities();
|
||||
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();
|
||||
@@ -474,6 +526,7 @@ impl Workspace {
|
||||
/// tables are a pure function of the records it holds
|
||||
/// ([`WorkspaceIndex::absorb`]).
|
||||
pub fn finish_scan(&mut self, scan: Scan) -> Vec<String> {
|
||||
self.scan_absorbed.clear();
|
||||
match scan.kind {
|
||||
ScanKind::Whole => self.finish_whole_scan(scan),
|
||||
ScanKind::Widen => self.finish_widen(scan),
|
||||
@@ -505,6 +558,7 @@ impl Workspace {
|
||||
ScanTrace::add(&mut trace.gone_ms, leaving);
|
||||
let absorbing = trace.now();
|
||||
self.index.absorb(staged, &gone);
|
||||
self.invalidate_identities();
|
||||
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
|
||||
@@ -603,6 +657,7 @@ impl Workspace {
|
||||
let found = scan::included(&includes, &work);
|
||||
let absorbing = trace.now();
|
||||
self.index.absorb(staged, &gone);
|
||||
self.invalidate_identities();
|
||||
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
|
||||
|
||||
@@ -41,6 +41,9 @@ pub(super) struct Sources {
|
||||
pub(super) buffered: HashMap<PathBuf, String>,
|
||||
/// What the open buffers among `files` already know about themselves.
|
||||
pub(super) analyzed: Analyzed,
|
||||
/// Deterministic canonical spelling for every in-scope file identity,
|
||||
/// including files skipped by `maxFileSize`.
|
||||
pub(super) canonical_ids: HashMap<lucisv_core::walk::DirId, PathBuf>,
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
}
|
||||
@@ -124,6 +127,9 @@ pub struct Scan {
|
||||
/// What the open buffers among `work` already knew about themselves, taken
|
||||
/// from as each of them is reached.
|
||||
pub(super) analyzed: Analyzed,
|
||||
/// Canonical in-scope spellings by file identity, retained across `oversize`
|
||||
/// skips so mid-scan opens canonicalize like pre-scan opens.
|
||||
pub(super) canonical_ids: HashMap<lucisv_core::walk::DirId, PathBuf>,
|
||||
pub(super) incdirs: Vec<PathBuf>,
|
||||
pub(super) warnings: Vec<String>,
|
||||
/// How many of `work` have been indexed.
|
||||
@@ -170,6 +176,11 @@ pub(super) struct PendingDiscovery {
|
||||
/// one it names here has already been decided about, and deciding twice
|
||||
/// would step a file twice or report one skip as two.
|
||||
pub(super) seen: HashSet<PathBuf>,
|
||||
/// File identities `(dev, ino)` (or canonical paths) already discovered by
|
||||
/// the neighbourhood walk mapped to their chosen spellings, so the
|
||||
/// remaining walk neither duplicates a file nor misses a precedence
|
||||
/// conflict when a symlink sorts earlier.
|
||||
pub(super) seen_ids: HashMap<lucisv_core::walk::DirId, PathBuf>,
|
||||
/// Every directory identity the neighbourhood walk entered, and the path
|
||||
/// it entered each one by.
|
||||
///
|
||||
@@ -180,6 +191,7 @@ pub(super) struct PendingDiscovery {
|
||||
/// report a symlinked directory's files twice, under two spellings a path
|
||||
/// set cannot tell apart, and the index would hold every module in it
|
||||
/// twice. Sharing the tracker restores that contract across the split.
|
||||
pub(super) file_conflict: bool,
|
||||
pub(super) tracker: lucisv_core::walk::DirectoryTracker,
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Instant;
|
||||
|
||||
use vlog_semantic::{Def, FileId};
|
||||
use vlog_semantic::Def;
|
||||
|
||||
use super::scan::{HeldAnalyses, Sources};
|
||||
use super::Workspace;
|
||||
@@ -91,7 +91,7 @@ impl Workspace {
|
||||
reach: Reach<'_>,
|
||||
) -> Vec<(PathBuf, String)> {
|
||||
let mut wanted: BTreeSet<PathBuf> = module_select::hierarchical_users(&self.index, reach);
|
||||
wanted.insert(file.to_path_buf());
|
||||
wanted.insert(self.index_path_for(file));
|
||||
for name in modules {
|
||||
for def in self.index.units(name) {
|
||||
wanted.extend(self.index.path(def.file).map(Path::to_path_buf));
|
||||
@@ -103,7 +103,11 @@ impl Workspace {
|
||||
wanted.extend(self.index.path(edge.file).map(Path::to_path_buf));
|
||||
}
|
||||
}
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted.extend(
|
||||
self.docs
|
||||
.values()
|
||||
.filter_map(|doc| doc.path.as_deref().map(|p| self.index_path_for(p))),
|
||||
);
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
@@ -188,7 +192,7 @@ impl Workspace {
|
||||
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());
|
||||
wanted.insert(self.index_path_for(file));
|
||||
for spelling in [Some(name), new_name].into_iter().flatten() {
|
||||
if !self.fan_out_of(spelling, &mut wanted) {
|
||||
let sources = self.sources();
|
||||
@@ -203,7 +207,11 @@ impl Workspace {
|
||||
self.want_spellers(new_name, &mut wanted);
|
||||
}
|
||||
wanted.on(Rung::OpenBuffer);
|
||||
wanted.extend(self.docs.values().filter_map(|doc| doc.path.clone()));
|
||||
wanted.extend(
|
||||
self.docs
|
||||
.values()
|
||||
.filter_map(|doc| doc.path.as_deref().map(|p| self.index_path_for(p))),
|
||||
);
|
||||
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.
|
||||
@@ -334,14 +342,13 @@ impl Workspace {
|
||||
/// 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);
|
||||
for (file, path) in self.index.live_files() {
|
||||
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));
|
||||
wanted.insert(path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -360,7 +367,11 @@ impl Workspace {
|
||||
/// 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.extend(
|
||||
self.docs
|
||||
.values()
|
||||
.filter_map(|doc| doc.path.as_deref().map(|p| self.index_path_for(p))),
|
||||
);
|
||||
wanted
|
||||
.into_iter()
|
||||
.filter_map(|path| {
|
||||
|
||||
@@ -55,7 +55,7 @@ fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() {
|
||||
fn a_fast_path_buffer_keeps_the_on_disk_index_record() {
|
||||
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");
|
||||
@@ -64,7 +64,8 @@ fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_b
|
||||
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.
|
||||
// The same file, opened as a buffer the fast path takes, keeps the on-disk
|
||||
// record (subject to `maxFileSize`) without parsing the huge live text.
|
||||
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);
|
||||
@@ -72,8 +73,8 @@ fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_b
|
||||
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"
|
||||
1,
|
||||
"disk index record stays present when an open buffer is over largeFile.threshold"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -233,10 +233,8 @@ fn qa_attack_crafted_non_corpus_shapes_drift_check_body() {
|
||||
#[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.
|
||||
// it is the analysis of the empty file. It still offers no buffer analysis
|
||||
// to reuse, while keeping the on-disk record (subject to `maxFileSize`).
|
||||
let tree = Tree::new("openfactslarge");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let big = format!(
|
||||
@@ -257,8 +255,8 @@ fn a_buffer_on_the_large_file_fast_path_offers_no_analysis_to_reuse() {
|
||||
|
||||
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");
|
||||
assert_eq!(seen.parsed, ["big.sv", "a.sv"], "disk big.sv was parsed from disk: {seen:?}");
|
||||
assert_eq!(indexed(&ws, &["a_pkg", "big_pkg"]), ["a_pkg", "big_pkg"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -321,13 +319,14 @@ fn qa_a_buffer_edited_past_the_threshold_is_excluded_from_reuse_mid_session() {
|
||||
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.
|
||||
// Edited past the threshold, never saved: buffer offers no analysis, so
|
||||
// rescan reverts to disk's record (keeping the disk copy subject to cap).
|
||||
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");
|
||||
assert_eq!(seen.parsed, ["p.sv"], "and disk is read in its place: {seen:?}");
|
||||
assert_eq!(ws.index().member("p", "SMALL").len(), 1, "disk record stays indexed");
|
||||
|
||||
// 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());
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use vlog_semantic::{FileId, SymbolKind};
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -109,7 +109,7 @@ fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() {
|
||||
let ws = opentitan_workspace(&root, &[]);
|
||||
let index = ws.index();
|
||||
let (mut calls, mut total, mut worst) = (0usize, Duration::ZERO, (Duration::ZERO, 0, None));
|
||||
for (id, path) in index.files().iter().enumerate() {
|
||||
for (id, path) in index.live_files() {
|
||||
let Ok(text) = fs::read_to_string(path) else { continue };
|
||||
let doc = Document::new(Some(path.clone()), text, index);
|
||||
let names: Vec<&str> = doc
|
||||
@@ -121,7 +121,7 @@ fn what_the_mention_census_costs_a_keystroke_at_opentitan_scale() {
|
||||
.collect();
|
||||
let started = Instant::now();
|
||||
for name in &names {
|
||||
std::hint::black_box(index.mentioned_outside(name, Some(FileId(id as u32))));
|
||||
std::hint::black_box(index.mentioned_outside(name, Some(id)));
|
||||
}
|
||||
let took = started.elapsed();
|
||||
calls += names.len();
|
||||
|
||||
@@ -350,11 +350,10 @@ fn a_widen_lends_a_new_files_spelling_to_an_include_resolved_before_it() {
|
||||
}
|
||||
|
||||
#[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.
|
||||
fn a_buffer_grown_past_the_threshold_keeps_its_disk_record_when_the_scope_widens() {
|
||||
// Owner decision 2 (Topo #63): an open `doc.large` buffer keeps its
|
||||
// on-disk index record (subject to `maxFileSize`), so widening does not
|
||||
// drop `rtl/p.sv` and matches a whole rescan.
|
||||
let tree = Tree::new("widenlarge");
|
||||
tree.package("rtl/p.sv", "p_pkg");
|
||||
tree.package("lib/q.sv", "q_pkg");
|
||||
@@ -378,10 +377,10 @@ fn a_buffer_grown_past_the_threshold_leaves_the_index_when_the_scope_widens() {
|
||||
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"
|
||||
2,
|
||||
"both the kept disk record and the widened file are in the index"
|
||||
);
|
||||
assert!(incremental.index().units("p_pkg").is_empty(), "and its names went with it");
|
||||
assert_eq!(incremental.index().units("p_pkg").len(), 1, "and disk's package stays indexed");
|
||||
|
||||
let mut rebuilt = Workspace::default();
|
||||
rebuilt.set_client_settings(ClientSettings {
|
||||
|
||||
@@ -16,7 +16,7 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::Discovery;
|
||||
use lucisv_core::walk::collect_files_below;
|
||||
use lucisv_core::walk::{collect_files_below, dir_id, is_excluded, EXTENSIONS};
|
||||
|
||||
use super::discover::{oversize, Found};
|
||||
use super::Workspace;
|
||||
@@ -43,8 +43,8 @@ impl Workspace {
|
||||
if let Some(held) = self.held_spelling(path) {
|
||||
return Watched::Held(held);
|
||||
}
|
||||
if self.docs.values().any(|doc| doc.path.as_deref() == Some(path)) {
|
||||
return Watched::Held(path.to_path_buf());
|
||||
if let Some(doc) = self.document_for_path(path).filter(|doc| !doc.large) {
|
||||
return Watched::Held(doc.path.clone().unwrap_or_else(|| path.to_path_buf()));
|
||||
}
|
||||
match self.scope_could_take(path) {
|
||||
true => Watched::Unknown,
|
||||
@@ -52,24 +52,27 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// The spelling the index holds `path` under: `path` itself, or the same
|
||||
/// file reached through a scope directory's other name — a symlinked root,
|
||||
/// or a different case on a case-insensitive disk. Resolved through the
|
||||
/// directories the scope is anchored at, so it costs a handful of
|
||||
/// `canonicalize` calls rather than one per held file.
|
||||
/// The spelling the index holds `path` under: `path` itself, the same
|
||||
/// file reached through a scope directory's symlink/case alias, or any
|
||||
/// file sharing `(dev, ino)` (on Unix) / canonical path without basename
|
||||
/// gating.
|
||||
fn held_spelling(&self, path: &Path) -> Option<PathBuf> {
|
||||
let holds = |path: &Path| self.index.file_id(path).is_some();
|
||||
let holds = |candidate: &Path| self.index.file_id(candidate).is_some();
|
||||
if holds(path) {
|
||||
return Some(path.to_path_buf());
|
||||
}
|
||||
let real = canonical(path)?;
|
||||
let mut anchors: Vec<PathBuf> = self.roots.clone();
|
||||
anchors.extend(self.scope_dirs());
|
||||
anchors.into_iter().find_map(|anchor| {
|
||||
let rest = real.strip_prefix(fs::canonicalize(&anchor).ok()?).ok()?;
|
||||
let spelled = anchor.join(rest);
|
||||
holds(&spelled).then_some(spelled)
|
||||
})
|
||||
if let Some(real) = canonical(path) {
|
||||
let mut anchors: Vec<PathBuf> = self.roots.clone();
|
||||
anchors.extend(self.scope_dirs());
|
||||
if let Some(spelled) = anchors.into_iter().find_map(|anchor| {
|
||||
let rest = real.strip_prefix(fs::canonicalize(&anchor).ok()?).ok()?;
|
||||
let spelled = anchor.join(rest);
|
||||
holds(&spelled).then_some(spelled)
|
||||
}) {
|
||||
return Some(spelled);
|
||||
}
|
||||
}
|
||||
self.held_path_for(path)
|
||||
}
|
||||
|
||||
/// Whether a scan of the scope in force could index `path` — `false` only
|
||||
@@ -78,12 +81,13 @@ impl Workspace {
|
||||
/// `lucisv.index.maxFileSize`. The walk is `lucisv_core`'s own, rooted
|
||||
/// where the scan's is, so `.gitignore`, `exclude` and the config's
|
||||
/// excludes rule it out exactly as they rule it out of a scan.
|
||||
fn scope_could_take(&self, path: &Path) -> bool {
|
||||
pub(super) fn scope_could_take(&self, path: &Path) -> bool {
|
||||
if let Some(list) = self.filelist_path() {
|
||||
// An unreadable filelist sends the scan to the rungs below, and
|
||||
// so it sends this.
|
||||
if let Ok(list) = lucisv_core::filelist::read(&list) {
|
||||
return list.files.iter().any(|listed| same_file(listed, path));
|
||||
return list.files.iter().any(|listed| same_file(listed, path))
|
||||
&& oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_none();
|
||||
}
|
||||
}
|
||||
let Some(dir) = path.parent() else { return true };
|
||||
@@ -92,8 +96,15 @@ impl Workspace {
|
||||
false => self.scope_dirs(),
|
||||
};
|
||||
if self.roots.is_empty() && self.client.index_scope_depth == 0 {
|
||||
// The flat read of a rootless session: siblings only.
|
||||
return dirs.iter().any(|scope| scope == dir);
|
||||
// The flat read of a rootless session: siblings only (and must be
|
||||
// an existing readable source file under `maxFileSize`).
|
||||
return dirs.iter().any(|scope| scope == dir)
|
||||
&& path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| EXTENSIONS.contains(&e))
|
||||
&& fs::metadata(path).is_ok_and(|meta| meta.is_file())
|
||||
&& oversize(&Found::of(path), self.client.max_file_size, &mut 0).is_none();
|
||||
}
|
||||
dirs.iter()
|
||||
.filter(|scope| path.starts_with(scope))
|
||||
@@ -102,8 +113,30 @@ impl Workspace {
|
||||
|
||||
/// Whether a walk of `scope` finds `path` under its cap.
|
||||
fn walk_finds(&self, scope: &Path, path: &Path) -> bool {
|
||||
if !path.extension().and_then(|e| e.to_str()).is_some_and(|e| EXTENSIONS.contains(&e)) {
|
||||
return false;
|
||||
}
|
||||
let Some(dir) = path.parent() else { return true };
|
||||
let excludes = self.walk_excludes(&mut Discovery::new(true), scope);
|
||||
let mut has_gitignore = scope.join(".gitignore").is_file();
|
||||
let mut cursor = Some(path);
|
||||
while let Some(part) = cursor {
|
||||
if part == scope {
|
||||
break;
|
||||
}
|
||||
if is_excluded(part, &excludes) {
|
||||
return false;
|
||||
}
|
||||
if part != path && part.join(".gitignore").is_file() {
|
||||
has_gitignore = true;
|
||||
}
|
||||
cursor = part.parent();
|
||||
}
|
||||
if !has_gitignore {
|
||||
let Ok(meta) = fs::metadata(path) else { return false };
|
||||
return meta.is_file()
|
||||
&& (self.client.max_file_size == 0 || meta.len() <= self.client.max_file_size);
|
||||
}
|
||||
let mut found = None;
|
||||
let take = &mut |file: PathBuf, len| {
|
||||
if file == path {
|
||||
@@ -134,17 +167,14 @@ impl Workspace {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two spellings name one file: equal, or equal once resolved. The
|
||||
/// names are compared first, case-insensitively, so a filelist of thousands
|
||||
/// costs a resolution only for the entries that could be the one.
|
||||
/// Whether two spellings name one file: equal, or sharing `(dev, ino)` (on
|
||||
/// Unix) / canonical path (elsewhere), without basename equality gating.
|
||||
fn same_file(listed: &Path, path: &Path) -> bool {
|
||||
if listed == path {
|
||||
return true;
|
||||
}
|
||||
let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().to_lowercase());
|
||||
name(listed) == name(path)
|
||||
&& canonical(listed).is_some()
|
||||
&& canonical(listed) == canonical(path)
|
||||
dir_id(listed).is_some_and(|id| dir_id(path).as_ref() == Some(&id))
|
||||
|| (canonical(listed).is_some() && canonical(listed) == canonical(path))
|
||||
}
|
||||
|
||||
/// `path` with every symlink resolved and, on a case-insensitive disk, every
|
||||
|
||||
@@ -53,17 +53,27 @@ impl WorkspaceIndex {
|
||||
&self.files
|
||||
}
|
||||
|
||||
/// Every live file in the index paired with its [`FileId`], skipping
|
||||
/// tombstoned slots while preserving stable slot ids.
|
||||
pub fn live_files(&self) -> impl Iterator<Item = (FileId, &PathBuf)> + '_ {
|
||||
self.facts.iter().enumerate().filter_map(|(at, facts)| {
|
||||
(!self.tombstoned.get(at).copied().unwrap_or(true))
|
||||
.then_some((FileId(at as u32), &facts.path))
|
||||
})
|
||||
}
|
||||
|
||||
/// The path of one file.
|
||||
pub fn path(&self, file: FileId) -> Option<&Path> {
|
||||
self.files.get(file.0 as usize).map(PathBuf::as_path)
|
||||
let at = file.0 as usize;
|
||||
(!self.tombstoned.get(at).copied().unwrap_or(true))
|
||||
.then(|| self.facts.get(at).map(|facts| facts.path.as_path()))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The id of an indexed path.
|
||||
pub fn file_id(&self, path: &Path) -> Option<FileId> {
|
||||
self.files
|
||||
.binary_search_by(|held| held.as_path().cmp(path))
|
||||
.ok()
|
||||
.map(|at| FileId(at as u32))
|
||||
let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?;
|
||||
(!self.tombstoned[at]).then_some(FileId(at as u32))
|
||||
}
|
||||
|
||||
/// Every file-scope declaration of `name` — module, package or typedef —
|
||||
@@ -293,12 +303,15 @@ impl WorkspaceIndex {
|
||||
/// (`docs/features/index-persistence/README.md`).
|
||||
pub fn facts_for(&self, path: &Path) -> Option<&FileFacts> {
|
||||
let at = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)).ok()?;
|
||||
self.facts.get(at)
|
||||
(!self.tombstoned[at]).then(|| &self.facts[at])
|
||||
}
|
||||
|
||||
/// The `` `define`` table of one file.
|
||||
pub fn defines(&self, file: FileId) -> Option<&DefineTable> {
|
||||
self.facts.get(file.0 as usize).map(|facts| &facts.defines)
|
||||
let at = file.0 as usize;
|
||||
(!self.tombstoned.get(at).copied().unwrap_or(true))
|
||||
.then(|| self.facts.get(at).map(|facts| &facts.defines))
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// Every definition of a macro name anywhere in the workspace, in file
|
||||
@@ -312,7 +325,11 @@ impl WorkspaceIndex {
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|&(file, entry)| {
|
||||
let define = self.facts.get(file.0 as usize)?.defines.entries().get(entry)?;
|
||||
let at = file.0 as usize;
|
||||
if self.tombstoned.get(at).copied().unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let define = self.facts.get(at)?.defines.entries().get(entry)?;
|
||||
Some((file, define))
|
||||
})
|
||||
.collect()
|
||||
@@ -349,6 +366,9 @@ impl WorkspaceIndex {
|
||||
pub fn files_spelling(&self, name: &str) -> impl Iterator<Item = FileId> + '_ {
|
||||
let name = name.to_string();
|
||||
self.facts.iter().enumerate().filter_map(move |(id, facts)| {
|
||||
if self.tombstoned.get(id).copied().unwrap_or(true) {
|
||||
return None;
|
||||
}
|
||||
let spelled = facts.references.iter().any(|reference| match reference {
|
||||
// A fact with **no paths at all** is not one of these: it is
|
||||
// an inherited-member miss, answered only through the base
|
||||
@@ -390,8 +410,9 @@ impl WorkspaceIndex {
|
||||
self.facts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(move |(_, facts)| {
|
||||
facts.words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
|
||||
.filter(move |&(id, facts)| {
|
||||
!self.tombstoned.get(id).copied().unwrap_or(true)
|
||||
&& facts.words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
|
||||
})
|
||||
.map(|(id, _)| FileId(id as u32))
|
||||
}
|
||||
@@ -419,8 +440,9 @@ impl WorkspaceIndex {
|
||||
self.facts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(move |(_, facts)| {
|
||||
facts.macro_words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
|
||||
.filter(move |&(id, facts)| {
|
||||
!self.tombstoned.get(id).copied().unwrap_or(true)
|
||||
&& facts.macro_words.binary_search_by(|w| w.as_str().cmp(name)).is_ok()
|
||||
})
|
||||
.map(|(id, _)| FileId(id as u32))
|
||||
}
|
||||
@@ -531,7 +553,13 @@ impl WorkspaceIndex {
|
||||
.flat_map(|m| m.values())
|
||||
.map(Vec::len)
|
||||
.sum(),
|
||||
defines: self.facts.iter().map(|f| f.defines.entries().len()).sum(),
|
||||
defines: self
|
||||
.facts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(id, _)| !self.tombstoned.get(id).copied().unwrap_or(true))
|
||||
.map(|(_, f)| f.defines.entries().len())
|
||||
.sum(),
|
||||
instantiations: self.instantiations.values().map(Vec::len).sum(),
|
||||
inheritances: self.subclasses.values().map(Vec::len).sum(),
|
||||
}
|
||||
@@ -547,11 +575,19 @@ impl WorkspaceIndex {
|
||||
hier_members: self.hier_members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||||
reference_keys: self.reference_sites.len(),
|
||||
reference_sites: self.reference_sites.values().map(Vec::len).sum(),
|
||||
words: self.facts.iter().map(|facts| facts.words().len()).sum(),
|
||||
words: self
|
||||
.facts
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(id, _)| !self.tombstoned.get(id).copied().unwrap_or(true))
|
||||
.map(|(_, facts)| facts.words().len())
|
||||
.sum(),
|
||||
word_bytes: self
|
||||
.facts
|
||||
.iter()
|
||||
.flat_map(|facts| facts.words())
|
||||
.enumerate()
|
||||
.filter(|&(id, _)| !self.tombstoned.get(id).copied().unwrap_or(true))
|
||||
.flat_map(|(_, facts)| facts.words())
|
||||
.map(|word| word.len())
|
||||
.sum(),
|
||||
}
|
||||
@@ -644,6 +680,7 @@ impl IndexBuilder {
|
||||
self.files.dedup_by(|a, b| a.path == b.path);
|
||||
let mut index = WorkspaceIndex {
|
||||
files: self.files.iter().map(|facts| facts.path.clone()).collect(),
|
||||
tombstoned: vec![false; self.files.len()],
|
||||
facts: self.files,
|
||||
..WorkspaceIndex::default()
|
||||
};
|
||||
|
||||
@@ -294,12 +294,17 @@ pub struct InheritanceEdge {
|
||||
/// memory: the same names and spans the tables hold, held once more per file.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct WorkspaceIndex {
|
||||
/// Indexed by [`FileId`], sorted by path. The paths of `facts`, kept flat
|
||||
/// so [`WorkspaceIndex::files`] can hand out a slice.
|
||||
/// Live indexed paths, sorted by path, kept flat so
|
||||
/// [`WorkspaceIndex::files`] can hand out a slice without exposing
|
||||
/// tombstoned slots.
|
||||
files: Vec<PathBuf>,
|
||||
/// What each file contributes, parallel to `files` and in the same order.
|
||||
/// A [`FileId`] is an index into both.
|
||||
/// What each file slot contributes, sorted by `path`. A [`FileId`] is a
|
||||
/// stable slot index into `facts` and `tombstoned` across
|
||||
/// [`WorkspaceIndex::remove_file`] until compaction on [`WorkspaceIndex::merge`].
|
||||
facts: Vec<FileFacts>,
|
||||
/// Parallel to `facts`: `true` for a removed slot whose records were
|
||||
/// cleared in-place via [`WorkspaceIndex::replace_facts`].
|
||||
tombstoned: Vec<bool>,
|
||||
/// File-scope name → every declaration of it, in disambiguation order.
|
||||
units: BTreeMap<String, Vec<Def>>,
|
||||
/// Unit name → member name → every declaration of it, on the
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_parser::defines::{DefineKind, DefineTable};
|
||||
|
||||
use crate::model::Surface;
|
||||
|
||||
@@ -61,6 +61,13 @@ impl WorkspaceIndex {
|
||||
pub fn update_facts(&mut self, facts: FileFacts) -> bool {
|
||||
let path = facts.path.clone();
|
||||
match self.facts.binary_search_by(|held| held.path.cmp(&path)) {
|
||||
Ok(at) if self.tombstoned[at] => {
|
||||
self.tombstoned[at] = false;
|
||||
if let Err(live) = self.files.binary_search_by(|held| held.as_path().cmp(&path)) {
|
||||
self.files.insert(live, path);
|
||||
}
|
||||
self.replace_facts(at, facts);
|
||||
}
|
||||
Ok(at) if self.facts[at] == facts => return false,
|
||||
// The common case — a saved file the index already holds. Only the
|
||||
// names this file declared before or declares now can have moved,
|
||||
@@ -69,10 +76,14 @@ impl WorkspaceIndex {
|
||||
self.replace_facts(at, facts);
|
||||
}
|
||||
// A file the index did not hold: every id from here on shifts, so
|
||||
// every table is rebuilt from the records. No parse, no read.
|
||||
// every table is rebuilt from the records (which also compacts any
|
||||
// tombstones). No parse, no read.
|
||||
Err(at) => {
|
||||
self.files.insert(at, path);
|
||||
if let Err(live) = self.files.binary_search_by(|held| held.as_path().cmp(&path)) {
|
||||
self.files.insert(live, path);
|
||||
}
|
||||
self.facts.insert(at, facts);
|
||||
self.tombstoned.insert(at, false);
|
||||
self.merge();
|
||||
}
|
||||
}
|
||||
@@ -110,16 +121,23 @@ impl WorkspaceIndex {
|
||||
pub fn absorb(&mut self, records: Vec<FileFacts>, gone: &[PathBuf]) {
|
||||
for path in gone {
|
||||
if let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) {
|
||||
self.files.remove(at);
|
||||
self.facts.remove(at);
|
||||
self.tombstoned[at] = true;
|
||||
}
|
||||
}
|
||||
for facts in records {
|
||||
match self.facts.binary_search_by(|held| held.path.cmp(&facts.path)) {
|
||||
Ok(at) => self.facts[at] = facts,
|
||||
Ok(at) => {
|
||||
self.tombstoned[at] = false;
|
||||
self.facts[at] = facts;
|
||||
}
|
||||
Err(at) => {
|
||||
self.files.insert(at, facts.path.clone());
|
||||
if let Err(live) =
|
||||
self.files.binary_search_by(|held| held.as_path().cmp(&facts.path))
|
||||
{
|
||||
self.files.insert(live, facts.path.clone());
|
||||
}
|
||||
self.facts.insert(at, facts);
|
||||
self.tombstoned.insert(at, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,14 +147,21 @@ impl WorkspaceIndex {
|
||||
/// Drop one file from the index, reporting whether it was there.
|
||||
///
|
||||
/// Same contract as [`WorkspaceIndex::update_file`]: what is left is the
|
||||
/// index a full build over the remaining files would have produced.
|
||||
/// index a full build over the remaining files would have produced. Uses a
|
||||
/// tombstone and localized [`WorkspaceIndex::replace_facts`] so removing a
|
||||
/// file keeps surviving [`FileId`]s stable without paying a full merge.
|
||||
pub fn remove_file(&mut self, path: &Path) -> bool {
|
||||
let Ok(at) = self.facts.binary_search_by(|held| held.path.as_path().cmp(path)) else {
|
||||
return false;
|
||||
};
|
||||
self.files.remove(at);
|
||||
self.facts.remove(at);
|
||||
self.merge();
|
||||
if self.tombstoned[at] {
|
||||
return false;
|
||||
}
|
||||
if let Ok(live) = self.files.binary_search_by(|held| held.as_path().cmp(path)) {
|
||||
self.files.remove(live);
|
||||
}
|
||||
self.replace_facts(at, empty_facts(path.to_path_buf()));
|
||||
self.tombstoned[at] = true;
|
||||
true
|
||||
}
|
||||
|
||||
@@ -148,17 +173,30 @@ impl WorkspaceIndex {
|
||||
/// more than one crate's tests — `lucisv_server` checks it against the
|
||||
/// real corpus, this crate against crafted attacks.
|
||||
pub fn fingerprint(&self) -> String {
|
||||
let mut remap: Vec<Option<u32>> = vec![None; self.facts.len()];
|
||||
let mut live = 0u32;
|
||||
for (slot, tombstoned) in self.tombstoned.iter().enumerate() {
|
||||
if !*tombstoned {
|
||||
remap[slot] = Some(live);
|
||||
live += 1;
|
||||
}
|
||||
}
|
||||
let id_of = |file: FileId| match remap.get(file.0 as usize).copied().flatten() {
|
||||
Some(id) => id,
|
||||
None => file.0,
|
||||
};
|
||||
let mut out = String::new();
|
||||
for (id, path) in self.files.iter().enumerate() {
|
||||
let defines = self.defines(FileId(id as u32)).map_or(0, |t| t.entries().len());
|
||||
for (slot, facts) in self.facts.iter().enumerate() {
|
||||
let Some(id) = remap[slot] else { continue };
|
||||
let defines = facts.defines.entries().len();
|
||||
// The census's size, on the same rule the `define` table follows:
|
||||
// the words themselves are per-file and never merged, so a count
|
||||
// is enough to catch the failure a fingerprint exists to catch —
|
||||
// a record lost, duplicated or attached to the wrong file.
|
||||
let words = self.facts.get(id).map_or(0, |facts| facts.words.len());
|
||||
let words = facts.words.len();
|
||||
out.push_str(&format!(
|
||||
"file {id} {} defines={defines} words={words}\n",
|
||||
path.display()
|
||||
facts.path.display()
|
||||
));
|
||||
}
|
||||
for symbol in self.workspace_symbols("") {
|
||||
@@ -167,7 +205,7 @@ impl WorkspaceIndex {
|
||||
symbol.name,
|
||||
symbol.container,
|
||||
symbol.def.kind,
|
||||
symbol.def.file.0,
|
||||
id_of(symbol.def.file),
|
||||
symbol.def.name_span.start,
|
||||
symbol.def.name_span.end,
|
||||
symbol.def.decl_span.start,
|
||||
@@ -182,10 +220,10 @@ impl WorkspaceIndex {
|
||||
for site in sites {
|
||||
out.push_str(&format!(
|
||||
"ref {}:{}..{} <- {}:{}..{}\n",
|
||||
definition.file.0,
|
||||
id_of(definition.file),
|
||||
definition.name_start,
|
||||
definition.name_end,
|
||||
site.file.0,
|
||||
id_of(site.file),
|
||||
site.name_span.start,
|
||||
site.name_span.end
|
||||
));
|
||||
@@ -196,14 +234,16 @@ impl WorkspaceIndex {
|
||||
for (definition, count) in ambiguous {
|
||||
out.push_str(&format!(
|
||||
"ambiguous-ref {}:{}..{} x{count}\n",
|
||||
definition.file.0, definition.name_start, definition.name_end
|
||||
id_of(definition.file),
|
||||
definition.name_start,
|
||||
definition.name_end
|
||||
));
|
||||
}
|
||||
for (name, edges) in self.instantiations() {
|
||||
for edge in edges {
|
||||
out.push_str(&format!(
|
||||
"inst {name} {} in {}@{}..{} site {}..{}\n",
|
||||
edge.file.0,
|
||||
id_of(edge.file),
|
||||
edge.owner.name,
|
||||
edge.owner.name_span.start,
|
||||
edge.owner.span.end,
|
||||
@@ -237,7 +277,7 @@ impl WorkspaceIndex {
|
||||
for edge in edges {
|
||||
out.push_str(&format!(
|
||||
"extends {name} {} {}@{}..{}\n",
|
||||
edge.file.0,
|
||||
id_of(edge.file),
|
||||
edge.subclass.name,
|
||||
edge.subclass.name_span.start,
|
||||
edge.subclass.span.end
|
||||
@@ -247,10 +287,54 @@ impl WorkspaceIndex {
|
||||
// Not an answer any caller reads, but the table that decides which
|
||||
// files the *next* update re-resolves: one that drifted from a
|
||||
// rebuild's would be a stale posting waiting to happen.
|
||||
self.dependents.render(&mut out);
|
||||
self.render_dependents(&remap, &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
fn render_dependents(&self, remap: &[Option<u32>], out: &mut String) {
|
||||
if !self.tombstoned.iter().any(|&t| t) {
|
||||
self.dependents.render(out);
|
||||
return;
|
||||
}
|
||||
let mut raw = String::new();
|
||||
self.dependents.render(&mut raw);
|
||||
for line in raw.lines() {
|
||||
if let Some((prefix, list)) = line.rsplit_once(" by [") {
|
||||
if let Some(inner) = list.strip_suffix(']') {
|
||||
let mapped: Vec<u32> = inner
|
||||
.split(',')
|
||||
.filter_map(|s| s.trim().parse::<usize>().ok())
|
||||
.filter_map(|slot| remap.get(slot).copied().flatten())
|
||||
.collect();
|
||||
out.push_str(&format!("{prefix} by {mapped:?}\n"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-pack `facts` and rebuild `files` / `tombstoned` when tombstones exist.
|
||||
fn compact_tombstones(&mut self) {
|
||||
if !self.tombstoned.iter().any(|&t| t) {
|
||||
return;
|
||||
}
|
||||
let mut keep = 0usize;
|
||||
for i in 0..self.facts.len() {
|
||||
if !self.tombstoned[i] {
|
||||
if i != keep {
|
||||
self.facts.swap(keep, i);
|
||||
}
|
||||
keep += 1;
|
||||
}
|
||||
}
|
||||
self.facts.truncate(keep);
|
||||
self.tombstoned.clear();
|
||||
self.tombstoned.resize(keep, false);
|
||||
self.files = self.facts.iter().map(|facts| facts.path.clone()).collect();
|
||||
}
|
||||
|
||||
/// Rebuild every merged table, the postings and the readers table from
|
||||
/// the per-file records.
|
||||
///
|
||||
@@ -260,6 +344,7 @@ impl WorkspaceIndex {
|
||||
/// a few files and a whole one agree by construction, and both agree with
|
||||
/// [`IndexBuilder::finish`](super::IndexBuilder::finish).
|
||||
pub(super) fn merge(&mut self) {
|
||||
self.compact_tombstones();
|
||||
self.merge_tables(None, None);
|
||||
self.merge_bases();
|
||||
// A changed declaration can change how references in any file resolve,
|
||||
@@ -315,6 +400,9 @@ impl WorkspaceIndex {
|
||||
/// Push one file's records under the keys `affected` names (every key for
|
||||
/// `None`), in the order the record holds them.
|
||||
fn push_records(&mut self, id: usize, affected: Option<&Affected>) {
|
||||
if self.tombstoned.get(id).copied().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let file = FileId(id as u32);
|
||||
let Some(facts) = self.facts.get(id) else { return };
|
||||
for decl in &facts.units {
|
||||
@@ -382,7 +470,10 @@ impl WorkspaceIndex {
|
||||
/// winning, which is `units`' rule.
|
||||
pub(super) fn merge_bases(&mut self) {
|
||||
self.bases.clear();
|
||||
for facts in &self.facts {
|
||||
for (id, facts) in self.facts.iter().enumerate() {
|
||||
if self.tombstoned.get(id).copied().unwrap_or(true) {
|
||||
continue;
|
||||
}
|
||||
for (base, subclass) in &facts.subclasses {
|
||||
self.bases.entry(subclass.name.clone()).or_insert_with(|| base.clone());
|
||||
}
|
||||
@@ -390,6 +481,21 @@ impl WorkspaceIndex {
|
||||
}
|
||||
}
|
||||
|
||||
fn empty_facts(path: PathBuf) -> FileFacts {
|
||||
FileFacts {
|
||||
path,
|
||||
defines: DefineTable::default(),
|
||||
units: Vec::new(),
|
||||
members: Vec::new(),
|
||||
instantiations: Vec::new(),
|
||||
subclasses: Vec::new(),
|
||||
reexports: Vec::new(),
|
||||
references: Vec::new(),
|
||||
words: Vec::new(),
|
||||
macro_words: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The table keys one file's records can move, so a merge after replacing that
|
||||
/// file can leave every other key alone.
|
||||
#[derive(Debug, Default)]
|
||||
|
||||
@@ -1225,7 +1225,11 @@ fn removing_a_file_gives_the_index_a_whole_build_would_have() {
|
||||
"what is left is the index of what is left"
|
||||
);
|
||||
assert_eq!(ws.units("dup").len(), 1, "and the removed declaration is gone");
|
||||
assert_eq!(ws.units("dup")[0].file, FileId(0), "z.sv renumbered down to 0");
|
||||
assert_eq!(
|
||||
ws.path(ws.units("dup")[0].file),
|
||||
Some(Path::new("z.sv")),
|
||||
"z.sv kept its stable FileId across fast tombstone removal"
|
||||
);
|
||||
assert!(ws.instantiations_of("sub").is_empty(), "its edges went with it");
|
||||
assert!(!ws.remove_file(Path::new("a.sv")), "and removing it again says so");
|
||||
}
|
||||
@@ -1716,7 +1720,12 @@ fn updating_a_file_to_empty_text_differs_from_removing_it() {
|
||||
assert_eq!(emptied.files().len(), 2, "the empty file still occupies a slot");
|
||||
assert_eq!(removed.files().len(), 1, "the removed file's slot is gone");
|
||||
assert_eq!(emptied.path(FileId(1)), Some(Path::new("z.sv")), "z.sv did not renumber");
|
||||
assert_eq!(removed.path(FileId(0)), Some(Path::new("z.sv")), "z.sv renumbered down to 0");
|
||||
assert_eq!(
|
||||
removed.file_id(Path::new("z.sv")),
|
||||
Some(FileId(1)),
|
||||
"tombstoning keeps z.sv at its stable FileId while hiding a.sv"
|
||||
);
|
||||
assert!(removed.path(FileId(0)).is_none(), "tombstoned slot reports no path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2733,4 +2742,291 @@ fn the_macro_census_walk_costs_this_much_per_rename() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tombstoned_remove_revive_and_compact_match_fresh_build_and_counts() {
|
||||
let files = [
|
||||
("a_defs.sv", "`define A_MAC 1\npackage p;\n typedef logic word_t;\nendpackage\n"),
|
||||
("b_empty.sv", ""),
|
||||
("c_use.sv", "module m;\n import p::*;\n word_t x;\n sub u1 ();\n `A_MAC\nendmodule\n"),
|
||||
(
|
||||
"d_sub.sv",
|
||||
"module sub;\n class Base; endclass\n class Sub extends Base; endclass\nendmodule\n",
|
||||
),
|
||||
("e_reexp.sv", "package r;\n import p::*;\n export p::*;\nendpackage\n"),
|
||||
];
|
||||
let mut ws = index(&files);
|
||||
let c_id_before = ws.file_id(Path::new("c_use.sv")).expect("c_use live");
|
||||
assert!(ws.remove_file(Path::new("a_defs.sv")));
|
||||
assert!(ws.remove_file(Path::new("b_empty.sv")));
|
||||
assert!(!ws.remove_file(Path::new("b_empty.sv")), "double remove returns false");
|
||||
|
||||
// Stable FileId is preserved while tombstones are hidden from every lookup.
|
||||
assert_eq!(ws.file_id(Path::new("c_use.sv")), Some(c_id_before));
|
||||
assert!(ws.file_id(Path::new("a_defs.sv")).is_none());
|
||||
assert!(ws.path(FileId(0)).is_none());
|
||||
assert!(ws.defines(FileId(0)).is_none());
|
||||
assert!(ws.facts_for(Path::new("a_defs.sv")).is_none());
|
||||
assert!(ws.find_define("A_MAC").is_empty());
|
||||
assert!(ws.files_mentioning("A_MAC").next().is_some()); // still mentioned in c_use.sv
|
||||
assert!(!ws.files_naming_in_macros("A_MAC").any(|id| id == FileId(0)));
|
||||
assert_eq!(
|
||||
ws.files(),
|
||||
&[PathBuf::from("c_use.sv"), PathBuf::from("d_sub.sv"), PathBuf::from("e_reexp.sv")]
|
||||
);
|
||||
|
||||
let fresh_after_remove = index(&files[2..]);
|
||||
assert_eq!(ws.fingerprint(), fresh_after_remove.fingerprint());
|
||||
assert_eq!(ws.counts(), fresh_after_remove.counts());
|
||||
assert_eq!(ws.table_sizes(), fresh_after_remove.table_sizes());
|
||||
|
||||
// Reviving a tombstoned empty file must make it visible again even though empty == empty.
|
||||
assert!(ws.update_file(PathBuf::from("b_empty.sv"), ""));
|
||||
assert_eq!(ws.file_id(Path::new("b_empty.sv")), Some(FileId(1)));
|
||||
let with_empty = index(&[files[1], files[2], files[3], files[4]]);
|
||||
assert_eq!(ws.fingerprint(), with_empty.fingerprint());
|
||||
|
||||
// Re-adding `a_defs.sv` with updated content revives slot 0 in-place via `replace_facts`.
|
||||
let a_v2 = "`define A_MAC 2\npackage p;\n typedef logic word_t;\nendpackage\n";
|
||||
assert!(ws.update_file(PathBuf::from("a_defs.sv"), a_v2));
|
||||
assert_eq!(ws.file_id(Path::new("a_defs.sv")), Some(FileId(0)));
|
||||
let revived = index(&[("a_defs.sv", a_v2), files[1], files[2], files[3], files[4]]);
|
||||
assert_eq!(ws.fingerprint(), revived.fingerprint());
|
||||
|
||||
// Removing again, then absorbing another file compacts tombstones and keeps exact parity.
|
||||
assert!(ws.remove_file(Path::new("a_defs.sv")));
|
||||
let f_extra = ("f_extra.sv", "module extra;\n sub u2 ();\nendmodule\n");
|
||||
ws.absorb(
|
||||
vec![vlog_semantic::FileFacts::of(PathBuf::from(f_extra.0), f_extra.1)],
|
||||
&[PathBuf::from("b_empty.sv")],
|
||||
);
|
||||
assert_eq!(ws.file_id(Path::new("c_use.sv")), Some(FileId(0)), "absorb compacts tombstones");
|
||||
assert_eq!(ws.fingerprint(), index(&[files[2], files[3], files[4], f_extra]).fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fast_tombstone_2000_removals_on_4000_file_index_stays_sub_5ms_and_matches_rebuild() {
|
||||
let sources: Vec<(PathBuf, String)> = (0..4_000)
|
||||
.map(|i| {
|
||||
let path = PathBuf::from(format!("dir_{:02}/m_{:04}.sv", i / 100, i));
|
||||
let text = if i % 10 == 0 {
|
||||
format!("`define M_{i} {i}\nmodule m_{i:04};\nendmodule\n")
|
||||
} else {
|
||||
format!("module m_{i:04};\n m_{:04} u ();\nendmodule\n", (i / 10) * 10)
|
||||
};
|
||||
(path, text)
|
||||
})
|
||||
.collect();
|
||||
let mut ws = WorkspaceIndex::build(sources.iter().map(|(p, s)| (p.clone(), s.as_str())));
|
||||
|
||||
// Remove 2,000 leaf files (indices not at % 10, interleaved across slots).
|
||||
let mut removed_set = std::collections::HashSet::new();
|
||||
let to_remove: Vec<PathBuf> = sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(i, _)| i % 2 == 1 && i % 10 != 0)
|
||||
.take(2_000)
|
||||
.map(|(_, (p, _))| p.clone())
|
||||
.collect();
|
||||
assert_eq!(to_remove.len(), 2_000);
|
||||
|
||||
let started = std::time::Instant::now();
|
||||
for path in &to_remove {
|
||||
assert!(ws.remove_file(path));
|
||||
removed_set.insert(path.clone());
|
||||
}
|
||||
let elapsed = started.elapsed();
|
||||
let per_removal = elapsed / to_remove.len() as u32;
|
||||
assert!(
|
||||
per_removal < std::time::Duration::from_millis(5),
|
||||
"expected sub-5ms per tombstoned removal, took {per_removal:?} ({elapsed:?} total)"
|
||||
);
|
||||
|
||||
let remaining: Vec<(PathBuf, &str)> = sources
|
||||
.iter()
|
||||
.filter(|(p, _)| !removed_set.contains(p))
|
||||
.map(|(p, s)| (p.clone(), s.as_str()))
|
||||
.collect();
|
||||
let fresh = WorkspaceIndex::build(remaining);
|
||||
assert_eq!(ws.files().len(), fresh.files().len());
|
||||
assert_eq!(ws.fingerprint(), fresh.fingerprint());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_tombstones_survive_mixed_remove_add_revive_absorb_and_all_queries_match_fresh() {
|
||||
let base: Vec<(PathBuf, &str)> = vec![
|
||||
(
|
||||
PathBuf::from("a_defs.sv"),
|
||||
"`define MAC_A 1\npackage p_a;\n typedef logic [7:0] t_a;\nendpackage\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("b_mod.sv"),
|
||||
"`define MAC_B 2\nmodule b_mod;\n import p_a::*;\n t_a sig_b;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("c_mid.sv"),
|
||||
"`define MAC_C 3\nmodule c_mid;\n b_mod u_b ();\nendmodule\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("d_dup.sv"),
|
||||
"module dup;\nendmodule\nclass Base;\n int f;\nendclass\n",
|
||||
),
|
||||
(
|
||||
PathBuf::from("e_tail.sv"),
|
||||
"`define MAC_E 5\nmodule e_tail;\n dup u_d ();\n class Sub extends Base;\n function void g(); f = 1; endfunction\n endclass\nendmodule\n",
|
||||
),
|
||||
];
|
||||
|
||||
let mut ws = WorkspaceIndex::build(base.iter().map(|(p, s)| (p.clone(), *s)));
|
||||
// Tombstone FileId(0) and middle FileId(2).
|
||||
assert!(ws.remove_file(Path::new("a_defs.sv")));
|
||||
assert!(ws.remove_file(Path::new("c_mid.sv")));
|
||||
|
||||
// Live ids stay sparse while queries hide tombstones and match fresh build.
|
||||
assert_eq!(ws.file_id(Path::new("b_mod.sv")), Some(FileId(1)));
|
||||
assert_eq!(ws.file_id(Path::new("d_dup.sv")), Some(FileId(3)));
|
||||
assert_eq!(ws.file_id(Path::new("e_tail.sv")), Some(FileId(4)));
|
||||
assert!(ws.path(FileId(0)).is_none());
|
||||
assert!(ws.path(FileId(2)).is_none());
|
||||
assert!(ws.defines(FileId(0)).is_none());
|
||||
assert!(ws.defines(FileId(2)).is_none());
|
||||
assert!(ws.find_define("MAC_A").is_empty());
|
||||
assert!(ws.find_define("MAC_C").is_empty());
|
||||
assert_eq!(ws.find_define("MAC_E").len(), 1);
|
||||
assert_eq!(ws.find_define("MAC_E")[0].0, FileId(4));
|
||||
assert_eq!(
|
||||
ws.files(),
|
||||
&[PathBuf::from("b_mod.sv"), PathBuf::from("d_dup.sv"), PathBuf::from("e_tail.sv")]
|
||||
);
|
||||
let live: Vec<(FileId, PathBuf)> = ws.live_files().map(|(id, p)| (id, p.clone())).collect();
|
||||
assert_eq!(
|
||||
live,
|
||||
vec![
|
||||
(FileId(1), PathBuf::from("b_mod.sv")),
|
||||
(FileId(3), PathBuf::from("d_dup.sv")),
|
||||
(FileId(4), PathBuf::from("e_tail.sv")),
|
||||
]
|
||||
);
|
||||
|
||||
let mut live_map: std::collections::BTreeMap<PathBuf, String> = base
|
||||
.iter()
|
||||
.filter(|(p, _)| p != Path::new("a_defs.sv") && p != Path::new("c_mid.sv"))
|
||||
.map(|(p, s)| (p.clone(), (*s).to_string()))
|
||||
.collect();
|
||||
let assert_all_queries_match =
|
||||
|ws: &WorkspaceIndex, live: &std::collections::BTreeMap<PathBuf, String>, label: &str| {
|
||||
let fresh = WorkspaceIndex::build(live.iter().map(|(p, s)| (p.clone(), s.as_str())));
|
||||
assert_eq!(ws.files(), fresh.files(), "{label}: files()");
|
||||
assert_eq!(ws.fingerprint(), fresh.fingerprint(), "{label}: fingerprint()");
|
||||
assert_eq!(ws.counts(), fresh.counts(), "{label}: counts()");
|
||||
assert_eq!(ws.table_sizes(), fresh.table_sizes(), "{label}: table_sizes()");
|
||||
for mac in ["MAC_A", "MAC_B", "MAC_C", "MAC_E"] {
|
||||
let ws_m: Vec<_> = ws
|
||||
.find_define(mac)
|
||||
.into_iter()
|
||||
.map(|(id, d)| (ws.path(id).map(Path::to_path_buf), d.name.clone()))
|
||||
.collect();
|
||||
let fr_m: Vec<_> = fresh
|
||||
.find_define(mac)
|
||||
.into_iter()
|
||||
.map(|(id, d)| (fresh.path(id).map(Path::to_path_buf), d.name.clone()))
|
||||
.collect();
|
||||
assert_eq!(ws_m, fr_m, "{label}: find_define({mac})");
|
||||
}
|
||||
for word in ["t_a", "sig_b", "u_b", "f", "Base", "MAC_E"] {
|
||||
let ws_w: Vec<_> = ws
|
||||
.files_mentioning(word)
|
||||
.filter_map(|id| ws.path(id).map(Path::to_path_buf))
|
||||
.collect();
|
||||
let fr_w: Vec<_> = fresh
|
||||
.files_mentioning(word)
|
||||
.filter_map(|id| fresh.path(id).map(Path::to_path_buf))
|
||||
.collect();
|
||||
assert_eq!(ws_w, fr_w, "{label}: files_mentioning({word})");
|
||||
let ws_s: Vec<_> = ws
|
||||
.files_spelling(word)
|
||||
.filter_map(|id| ws.path(id).map(Path::to_path_buf))
|
||||
.collect();
|
||||
let fr_s: Vec<_> = fresh
|
||||
.files_spelling(word)
|
||||
.filter_map(|id| fresh.path(id).map(Path::to_path_buf))
|
||||
.collect();
|
||||
assert_eq!(ws_s, fr_s, "{label}: files_spelling({word})");
|
||||
let ws_mw: Vec<_> = ws
|
||||
.files_naming_in_macros(word)
|
||||
.filter_map(|id| ws.path(id).map(Path::to_path_buf))
|
||||
.collect();
|
||||
let fr_mw: Vec<_> = fresh
|
||||
.files_naming_in_macros(word)
|
||||
.filter_map(|id| fresh.path(id).map(Path::to_path_buf))
|
||||
.collect();
|
||||
assert_eq!(ws_mw, fr_mw, "{label}: files_naming_in_macros({word})");
|
||||
}
|
||||
let ws_syms: Vec<_> = ws
|
||||
.workspace_symbols("")
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
(
|
||||
s.name.to_string(),
|
||||
s.container.map(str::to_string),
|
||||
ws.path(s.def.file).map(Path::to_path_buf),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let fr_syms: Vec<_> = fresh
|
||||
.workspace_symbols("")
|
||||
.into_iter()
|
||||
.map(|s| {
|
||||
(
|
||||
s.name.to_string(),
|
||||
s.container.map(str::to_string),
|
||||
fresh.path(s.def.file).map(Path::to_path_buf),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ws_syms, fr_syms, "{label}: workspace_symbols");
|
||||
for path in live.keys() {
|
||||
assert_eq!(
|
||||
ws.facts_for(path).is_some(),
|
||||
fresh.facts_for(path).is_some(),
|
||||
"{label}: facts_for"
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
assert_all_queries_match(&ws, &live_map, "after tombstoning 0 and 2");
|
||||
|
||||
// Revive slot 0 with exact previous content, then update slot 1, then remove slot 3.
|
||||
assert!(ws.update_file(PathBuf::from("a_defs.sv"), base[0].1));
|
||||
live_map.insert(PathBuf::from("a_defs.sv"), base[0].1.to_string());
|
||||
assert_eq!(ws.file_id(Path::new("a_defs.sv")), Some(FileId(0)));
|
||||
assert_all_queries_match(&ws, &live_map, "after reviving slot 0");
|
||||
|
||||
let b_v2 = "`define MAC_B 22\nmodule b_mod;\n import p_a::*;\n t_a sig_b2;\nendmodule\n";
|
||||
assert!(ws.update_file(PathBuf::from("b_mod.sv"), b_v2));
|
||||
live_map.insert(PathBuf::from("b_mod.sv"), b_v2.to_string());
|
||||
assert!(ws.remove_file(Path::new("d_dup.sv")));
|
||||
live_map.remove(Path::new("d_dup.sv"));
|
||||
assert_all_queries_match(&ws, &live_map, "after updating slot 1 and tombstoning slot 3");
|
||||
|
||||
// Adding a brand new path via update_file triggers merge() & compacts tombstones.
|
||||
let f_new = "module dup;\nendmodule\n";
|
||||
assert!(ws.update_file(PathBuf::from("0_first.sv"), f_new));
|
||||
live_map.insert(PathBuf::from("0_first.sv"), f_new.to_string());
|
||||
assert_eq!(ws.file_id(Path::new("0_first.sv")), Some(FileId(0)));
|
||||
assert_all_queries_match(&ws, &live_map, "after update_file adding 0_first.sv");
|
||||
|
||||
// Tombstone again, then absorb with both `gone` and overlapping `records`.
|
||||
assert!(ws.remove_file(Path::new("0_first.sv")));
|
||||
assert!(ws.remove_file(Path::new("e_tail.sv")));
|
||||
live_map.remove(Path::new("0_first.sv"));
|
||||
let e_v2 = "`define MAC_E 55\nmodule e_tail;\nendmodule\n";
|
||||
live_map.insert(PathBuf::from("e_tail.sv"), e_v2.to_string());
|
||||
live_map.remove(Path::new("b_mod.sv"));
|
||||
ws.absorb(
|
||||
vec![vlog_semantic::FileFacts::of(PathBuf::from("e_tail.sv"), e_v2)],
|
||||
&[PathBuf::from("b_mod.sv"), PathBuf::from("e_tail.sv")],
|
||||
);
|
||||
assert_all_queries_match(&ws, &live_map, "after absorb with gone + revived");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,174 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# Index Lifecycle & Fast Tombstone Removal (Round 2)
|
||||
|
||||
## Goal
|
||||
|
||||
Close four index/buffer lifecycle and symlink bugs identified in `docs/topo.md` (`#49`, `#63`, `#50`, `#51`):
|
||||
|
||||
1. **Topo #49 (`vlog_semantic` fast tombstone removal + `lucisv_server` `didClose`)**:
|
||||
- Keep `FileId` slots stable across `WorkspaceIndex::remove_file` via a parallel `tombstoned: Vec<bool>` mask and localized `replace_facts(at, empty_facts(path))` instead of shifting `FileId`s and running a full `merge()`.
|
||||
- Compact tombstones on `merge()` / `absorb()`, revive tombstoned slots cleanly on `update_facts`, hide tombstones from all public queries (`files`, `file_id`, `path`, `defines`, `facts_for`, `files_spelling`, `files_mentioning`, `files_naming_in_macros`, `counts`, `table_sizes`), and remap dense IDs inside `fingerprint()` so a tombstoned index matches a fresh `WorkspaceIndex::build` byte-for-byte.
|
||||
- Reconcile `didClose` in `lucisv_server` (`notification.rs` / `state/incremental.rs`): remove closed excluded/unlisted buffers via the fast tombstoned `remove_one` path (using `set_file_words` + `refresh_names` to keep removal sub-millisecond), and re-index dirty/unsaved closed in-scope buffers from disk via localized `replace_facts` (or remove if missing on disk).
|
||||
2. **Topo #63 (Owner decision 2: always keep disk index record for `doc.large`)**:
|
||||
- Standardize on always keeping the on-disk index record (subject to `lucisv.index.maxFileSize`) for open `doc.large` buffers across open, close, save, `largeFile.threshold` flips, widen, and whole scans (`state/discover.rs`, `state/rescan.rs`, `state/buffers.rs`, `state/incremental.rs`), achieving zero index mutation on `didOpen`, `didClose`, and `largeFile.threshold` flips.
|
||||
3. **Topo #50 (Unheld buffers opened mid-scan)**:
|
||||
- Reconcile buffers opened mid-scan (`state/rescan.rs`, `state/scan.rs`, `server/index.rs`) so excluded, unlisted, or unsaved-edited non-large buffers opened while a scan is in flight are absorbed into the running scan equivalently to being opened before the scan started.
|
||||
4. **Topo #51 (Symlinked files — one file, one canonical spelling)**:
|
||||
- Deduplicate and resolve file identity via `(dev, ino)` on Unix / `fs::canonicalize` fallback on non-Unix without basename-equality gating across discovery walks, `overlay_buffers`, `begin_widen`, `state/buffers.rs`, `state/incremental.rs`, and `state/watched.rs`, enforcing one deterministic canonical spelling in the index regardless of which symlink is open.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `WorkspaceIndex::files()` keeps returning `&[PathBuf]` containing only live files in path order so existing slice callers remain source- and ABI-compatible.
|
||||
- Within a scope, canonical symlink spelling precedence follows deterministic path-sorted discovery order (the lexicographically smallest in-scope spelling for a given file identity), matching existing directory-symlink precedence and preserving symlinked workspace roots.
|
||||
- During non-interleaved small scans (`scan.total() <= INTERLEAVE_ABOVE && !scan.discovery_pending()`), notifications remain queued until after `scan_once()` finishes, consistent with `server/index.rs`.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Dense `FileId(i)` callers closed (`vlog_semantic`, `lucisv_server`, `lucisv_mcp`)**:
|
||||
- After tombstoned `WorkspaceIndex::remove_file`, `index.files()` shrinks while remaining live files retain their pre-tombstone `FileId`s until the next full `merge()` or `absorb()`.
|
||||
- Added `WorkspaceIndex::live_files(&self) -> impl Iterator<Item = (FileId, &PathBuf)> + '_` (`crates/vlog_semantic/src/workspace/index.rs`) yielding only live `(FileId, &PathBuf)` pairs.
|
||||
- Updated `crates/lucisv_server/src/state/sources.rs` (`want_macro_text`), `crates/lucisv_server/src/candidates.rs` (`macros_of`, used by `from_words`, `remove_file`, `absorb`, and `update_words`), `crates/lucisv_mcp/src/tools/names.rs` (`similar`), `crates/lucisv_mcp/src/tools/diagnostics.rs` (`Census::of`), and `crates/lucisv_server/src/state/tests/reindex_perf.rs` to iterate `index.live_files()` instead of `0..index.files().len()` / `.enumerate()`.
|
||||
- **Symlinked open-buffer identity lookup wired across server handlers**:
|
||||
- `Workspace` (`crates/lucisv_server/src/state/mod.rs`, `state/buffers.rs`) exposes `index_file_id`, `held_path_for`, `index_path_for`, `is_same_file`, `open_document_for_path`, and `document_for_path`, matching exact path first and falling back to `(dev, ino)` / canonical path while preserving ASCII case-mismatch separation (`case_only_mismatch`).
|
||||
- Wired into `crates/lucisv_server/src/nav.rs`, `crates/lucisv_server/src/lint.rs` (`own` in `IndexMentions` and canonical `LintContext` path for `module-filename` / `package-filename` / config discovery), `crates/lucisv_server/src/state/sources.rs`, `crates/lucisv_server/src/ports.rs`, `crates/lucisv_server/src/rename.rs`, `crates/lucisv_server/src/extract.rs`, `crates/lucisv_server/src/inline_module.rs`, `crates/lucisv_server/src/imports.rs`, `crates/lucisv_server/src/completion/related.rs`, `crates/lucisv_server/src/hierarchy/calls.rs`, `crates/lucisv_server/src/includes.rs` (`resolve_for_doc`, `reachable_from`), and `crates/lucisv_server/src/hover.rs` (`narrowed_to_the_include_graph`).
|
||||
- **Active-scan absorbed buffer tracking (`Workspace` -> `didClose`)**:
|
||||
- `Workspace` (`crates/lucisv_server/src/state/mod.rs`) maintains `ScanAbsorbed` (canonical/open paths plus `DirId -> PathBuf` with `case_only_mismatch` guard), cleared on `begin_scan` and `finish_scan` (`state/rescan.rs`), and populated whenever open-buffer text/facts are absorbed in `begin_scan`, `scan_step`, or `reconcile_open_buffers_into` (`state/reconcile.rs`, covering `pos >= scan.at`, `pos < scan.at` staged updates, and `pos == None` excluded/unlisted/oversize entries).
|
||||
- `Workspace::closing_affects_running_scan` (`state/incremental.rs`) consults `scan_absorbed` alongside out-of-scope and disk-mismatch checks without changing `server/mod.rs` or `server/index.rs` signatures.
|
||||
- **`IncludeGraph::remove_file` linear rebuild outside owned files**:
|
||||
- `IncludeGraph::remove_file` (`crates/lucisv_server/src/includes.rs:284`) calls `relearn(known)` across all live paths and lowercase folded strings on each removal. That rebuild dominates excluded-file `didClose` latency on a 4k-file index (~2.49 ms/removal in release, ~10.19 ms in debug) while `WorkspaceIndex::remove_file` itself is tombstoned and constant-slot (in-scope clean open+close cycles average ~88.9 µs in release / ~134.7 µs in debug on a 2k-file index). Left untouched per lane file ownership for a follow-up incremental `IncludeGraph` update.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Topo #49: Fast tombstoned `WorkspaceIndex::remove_file` and `didClose` index reconciliation + 4k/2,000-cycle perf test
|
||||
- [x] Topo #63: Always keep disk index record for `doc.large` + differential tests
|
||||
- [x] Topo #50: Reconcile unheld/unsaved buffers opened mid-scan + regression tests
|
||||
- [x] Topo #51: Canonicalize symlinked file identities without basename gating across discovery, widen, buffers, incremental, watched + all 6 `filelink` scenario tests
|
||||
- [x] QA Fix Pass (F1–F5): `WorkspaceIndex::live_files` + `0..files().len()` audit across `lucisv_server`/`lucisv_mcp`, non-canonical symlink handler wiring, mid-scan/widen oversize symlink canonicalization, and `largeFile.threshold` drop disk reconciliation
|
||||
- [x] R2 Closing Pass (R2-F2 & R2-F3): Symlink-aware `` `include `` resolution / macro hover narrowing (`includes.rs`, `hover.rs`) and `Workspace::scan_absorbed` tracking across `begin_scan` / `scan_step` / `reconcile_open_buffers_into` / `closing_affects_running_scan` (`state/{mod.rs,rescan.rs,reconcile.rs,incremental.rs}`)
|
||||
|
||||
## Work log
|
||||
|
||||
- **Topo #49 (`vlog_semantic` + `lucisv_server`)**: Added `tombstoned: Vec<bool>` to `WorkspaceIndex` (`crates/vlog_semantic/src/workspace/{mod.rs,index.rs,update.rs}`) so `remove_file` clears the slot via `replace_facts(at, empty_facts(path))` without shifting `FileId`s or running full `merge()`, revives tombstones on `update_facts`, compacts on `merge()`/`absorb()`, hides tombstones from queries/counts, and monotonically remaps `FileId`s in `fingerprint()` to match a fresh build. Wired `DidCloseTextDocument` in `crates/lucisv_server/src/server/notification.rs` and `close_and_reconcile` / `remove_one` in `crates/lucisv_server/src/state/incremental.rs` so closed excluded/missing buffers are removed via fast tombstones and dirty/unsaved in-scope buffers revert from disk.
|
||||
- **Topo #63 (`lucisv_server`)**: Standardized on Owner decision 2 (keeping on-disk index records subject to `maxFileSize` for open `doc.large` buffers) across `state/{buffers.rs,discover.rs,rescan.rs,incremental.rs}` and updated `state/tests/{large_file.rs,open_buffers.rs,widen.rs}` + `server/large_file.rs` comment.
|
||||
- **Topo #50 (`lucisv_server`)**: Added `reconcile_open_buffers_into` in `state/rescan.rs` (invoked from `open_next`) so unheld or unsaved-edited buffers opened mid-scan are absorbed into the finished index consistently with pre-scan opens.
|
||||
- **Topo #51 (`lucisv_server`)**: Replaced basename-gated symlink aliasing with `(dev, ino)` / canonical-path deduplication (`dedup_by_identity`) and deterministic canonical precedence across `state/{mod.rs,buffers.rs,discover.rs,scan.rs,rescan.rs,watched.rs,incremental.rs}`.
|
||||
- **Tests**: Added 9 server lifecycle integration tests in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs` (including all 6 same-name/different-name symlink scenarios, `doc.large` differential checks, mid-scan opens, and 2,000-cycle `didClose` / open+close timings) alongside new `WorkspaceIndex` tombstone/perf tests in `crates/vlog_semantic/tests/workspace.rs`.
|
||||
- **2026-11-26 QA Fix Pass (F1–F5)**:
|
||||
- **F1**: Added `WorkspaceIndex::live_files()` (`crates/vlog_semantic/src/workspace/index.rs`) and replaced `0..index.files().len()` / `.enumerate()` `FileId` indexing across `state/sources.rs` (`want_macro_text`), `candidates.rs` (`macros_of`), `lucisv_mcp/src/tools/names.rs` (`similar`), `lucisv_mcp/src/tools/diagnostics.rs` (`Census::of`), and `state/tests/reindex_perf.rs`. Added MCP unit tests for tombstoned slot 0 in `names.rs` and `diagnostics.rs` and un-ignored both F1 tests in `lifecycle_r2.rs` (extending `Candidates::remove_file` coverage).
|
||||
- **F2**: Added `Workspace::index_path_for` / `Workspace::is_same_file` (`state/mod.rs`) and `Workspace::open_document_for_path` (`state/buffers.rs`) while preserving `case_only_mismatch` separation in `index_file_id` and open-buffer lookup; wired across `nav.rs`, `lint.rs` (`own` and canonical `LintContext` path), `state/sources.rs`, `ports.rs`, `rename.rs`, `extract.rs`, `inline_module.rs`, `imports.rs`, `completion/related.rs`, and `hierarchy/calls.rs`. Un-ignored `qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename`.
|
||||
- **F3 & F4**: Extracted `crates/lucisv_server/src/state/reconcile.rs` (keeping `state/rescan.rs` well under 600 production lines), carried in-scope `canonical_ids` across `oversize` skips on `Sources` / `Scan` (`state/{scan.rs,discover.rs,reconcile.rs}`) so mid-scan non-canonical symlinks over `maxFileSize` canonicalize identically to pre-scan, and updated `begin_widen` (`state/rescan.rs`) so open non-large buffers promote to lexicographically earlier symlinks even when over `maxFileSize`. Un-ignored both F3 and F4 tests in `lifecycle_r2.rs`.
|
||||
- **F5**: Added `Workspace::reconcile_large_buffer` (`state/reconcile.rs`) and wired `Server::reclassify_large_buffers` (`server/large_file.rs`, `server/notification.rs`) so buffers flipping `large == false -> true` reconcile back to disk (or drop if outside scope/oversize/missing) when dirty/previously indexed unsaved edits exist, while doing zero index work for clean buffers whose disk record matches. Un-ignored `qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh`.
|
||||
- **2026-11-26 Closing Pass (R2-F3 Option B)**:
|
||||
- **R2-F3**: Added `ScanAbsorbed` (`paths: HashSet<PathBuf>`, `ids: HashMap<DirId, PathBuf>` with `case_only_mismatch` guard) on `Workspace` (`crates/lucisv_server/src/state/mod.rs`), cleared in `begin_scan` and `finish_scan` (`state/rescan.rs`), and recorded whenever open-buffer text/facts enter the running scan (`begin_scan` overlays, `scan_step` pops from `buffered`/`analyzed`, and `reconcile_open_buffers_into` across `pos >= scan.at`, `pos < scan.at` staged updates, and `pos == None` excluded/unlisted/oversize entries in `state/reconcile.rs`). Updated `Workspace::closing_affects_running_scan` (`state/incremental.rs`) to return `true` when `scan_absorbed` matches (including aliases before mid-scan publish and buffers flipped to `doc.large` with no surviving alias), keeping `server/mod.rs` and `server/index.rs` untouched. Un-ignored `qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index` and added `r2_f3_mid_scan_dirty_reverted_and_closed_converges_across_all_scan_phases` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`.
|
||||
- **2026-11-26 Plan Review Surgical Fix (R2-F2b, R2-F3a, R2-F3b)**:
|
||||
- **R2-F2b**: Normalized `includes::resolve_for_doc` (`crates/lucisv_server/src/includes.rs`) output through `ws.index_path_for(&found)` so symlinked-directory includes resolve to canonical indexed paths.
|
||||
- **R2-F3a & R2-F3b**: Simplified `Workspace::closing_affects_running_scan` (`crates/lucisv_server/src/state/incremental.rs`) to return `true` whenever `self.scan_absorbed.contains(path, &target) || self.has_other_document_for(uri, path)`, covering both `already_same` skipped secondary symlinks and `doc.large`-flipped absorbed symlinks closed mid-scan while a second alias remains open. Un-ignored all three `qa_r2_*` repro tests in `lifecycle_r2.rs`.
|
||||
|
||||
## QA log
|
||||
|
||||
- **Verdict**: `FAIL` (5 concrete findings blocking acceptance: F1–F2 handshake regressions/breakages across `lucisv_server` and `lucisv_mcp`, F3–F4 `#51`/`#50` oversize symlink canonicalization gaps in `state/rescan.rs`, F5 `#63` threshold-drop stale unsaved index in `server/large_file.rs`).
|
||||
|
||||
### Audit & Hygiene
|
||||
- **Production line counts & safety** (verified on all 12 modified production files before `mod tests`): `crates/lucisv_server/src/server/large_file.rs` (110), `server/notification.rs` (287), `state/buffers.rs` (110), `state/discover.rs` (487), `state/incremental.rs` (221), `state/mod.rs` (104), `state/rescan.rs` (590), `state/scan.rs` (137), `state/watched.rs` (123), `crates/vlog_semantic/src/workspace/index.rs` (351), `workspace/mod.rs` (167), `workspace/update.rs` (380) — all `<= 600` non-blank, non-comment lines with 0 `unwrap()`, `expect()`, `unsafe`, `panic!`, or `#[allow` in modified production code.
|
||||
- **Author stamp**: `python3 tools/stamp_author.py --check` exited `0` (`would stamp 0 files; left 249 untouched`).
|
||||
|
||||
### Findings
|
||||
- **Finding F1 — `#49` Handshake Drift: callers iterating `0..index.files().len()` misalign/skip live `FileId`s after tombstone removal**
|
||||
- `crates/lucisv_server/src/state/sources.rs:338` (`want_macro_text`): Closing an excluded file (`ignored/a_excl.sv`, `FileId(0)`) shrinks `index.files().len()` to `2` while `z_mac.sv` remains at `FileId(2)`. `want_macro_text` skips `FileId(2)`, omitting `z_mac.sv` from `rename_traced` macro-text checks and causing divergent macro warnings vs a fresh server. Reproduced in `qa_topo_49_tombstone_before_live_macro_breaks_rename_macro_text_fanout` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
- `crates/lucisv_server/src/candidates.rs:837` (`macros_of` via `Candidates::from_words` / `Candidates::remove_file`): With `a_excl.sv` tombstoned (`files().len() == 1`, `z_mac.sv` at `FileId(1)`), `macros_of` returns `[]` instead of `["LIVE_MAC"]`. Reproduced in `qa_topo_49_candidates_macros_of_breaks_when_tombstone_precedes_live_macro_file` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
- `crates/lucisv_mcp/src/tools/names.rs:191-192` (`similar`) and `crates/lucisv_mcp/src/tools/diagnostics.rs:267-269` (`Census::of`): Same `0..index.files().len()` / `enumerate()`-to-`FileId` assumption skips `FileId(1)` defines (`[]` vs `["LIVE_MAC"]`) and assigns shifted `FileId(0)` inside `Census::of` against `own = Some(FileId(1))` (making `Census::outside` falsely return `true`). Verified via transient unit tests on tombstoned `WorkspaceIndex` and reverted cleanly from `crates/lucisv_mcp`; note `lucisv_mcp`'s `Project::refresh` (`crates/lucisv_mcp/src/project/mod.rs:175`) currently updates `self.index` only through `absorb(...)` (which compacts tombstones), so `lucisv_mcp` hits this only via direct `WorkspaceIndex::remove_file` callers.
|
||||
- **Finding F2 — `#51` Handshake Drift: non-canonical symlink open buffer fails references, lint, and rename**
|
||||
- When `a_link/link_a.sv -> z_real/real_b.sv` is canonically indexed as `a_link/link_a.sv` and the client opens `z_real/real_b.sv`, callers matching `doc.path` verbatim instead of `Workspace::index_file_id` / `Workspace::held_path_for` / `Workspace::document_for_path` break live LSP operations. Reproduced in `qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`):
|
||||
- `textDocument/references` (`crates/lucisv_server/src/nav.rs:232,295`) returns `1` ref instead of `2` (cross-file reference in `tb/tb.sv` dropped).
|
||||
- Diagnostics (`crates/lucisv_server/src/lint.rs:244`) pass `own = None` to `IndexMentions`, so `mentioned_outside("dead_sig", None)` sees `dead_sig` in canonical `a_link/link_a.sv` and suppresses `unused-signal` (and `module-filename` checks against `real_b.sv` rather than `link_a.sv`).
|
||||
- `rename_traced` (`crates/lucisv_server/src/state/sources.rs:206`) overlays `z_real/real_b.sv` over indexed `a_link/link_a.sv` and refuses both from `z_real/real_b.sv` and from `tb/tb.sv` with ``Err("`dut` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.")`` (and `crates/lucisv_server/src/ports.rs:555` `encode_edit` similarly checks `doc.path.as_deref() == Some(path)`).
|
||||
- **Finding F3 — `#50` + `#51`: mid-scan non-canonical symlink over `maxFileSize` diverges from pre-scan open**
|
||||
- `crates/lucisv_server/src/state/rescan.rs:518-524` (`reconcile_open_buffers_into`): When both `z_real/dut.sv` and `a_link/dut.sv -> z_real/dut.sv` exceed `maxFileSize` (remaining `<= largeFile.threshold`), `a_link/dut.sv` is excluded by `oversize` and absent from `scan.work`. Opening `z_real/dut.sv` mid-scan gets `pos = None` and indexes non-canonical `z_real/dut.sv` instead of canonical `a_link/dut.sv` (unlike pre-scan `overlay_buffers`). Reproduced in `qa_topo_50_mid_scan_non_canonical_symlink_over_max_file_size_matches_pre_scan` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
- **Finding F4 — `#51`: widening into lexical-earlier symlink over `maxFileSize` fails to promote canonical spelling**
|
||||
- `crates/lucisv_server/src/state/rescan.rs:167` (`begin_widen`): When `z_real/real.sv` (`> maxFileSize`, `<= largeFile.threshold`) is open in folder scope and widening into `a_link/` discovers `a_link/alias.sv -> z_real/real.sv`, `if path < existing && oversize(...).is_none()` blocks promoting to `a_link/alias.sv`, leaving `z_real/real.sv` in `index.files()` instead of `a_link/alias.sv` as a fresh server does. Reproduced in `qa_topo_51_widen_symlink_over_max_file_size_converges_like_fresh` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
- **Finding F5 — `#63`: threshold drop after unsaved edit indexed via widen leaves stale unsaved index**
|
||||
- `crates/lucisv_server/src/server/large_file.rs:179-199` (`reclassify_large_buffers`): When an unsaved edited in-scope buffer is indexed while `doc.large == false` (e.g. via widen) and `didChangeConfiguration` drops `lucisv.largeFile.threshold` so `doc.large` flips `true`, `reclassify_large_buffers` does not restore the on-disk record into the workspace index (stale unsaved buffer remains indexed while `doc.large == true` until next save/widen/close). Reproduced in `qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh` (`#[ignore]` in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
|
||||
### Live OpenTitan Probe & Passing QA Coverage
|
||||
- **OpenTitan `/Users/lucio/repo/opentitan/hw` (`#63`, read-only)**: Probed `/Users/lucio/repo/lucisv/target/release/lucisv-server` (`persist: false`, scratch env, `largeFile.threshold = 50000`) on `hw/ip/aes/rtl/aes_reg_top.sv` (`55,523 B`) and `hw/ip/aes/rtl/aes.sv` (`13,993 B`) across pre-scan open, post-scan open, threshold flips (`20000`, `10000` vs fresh `10000`, `500000`, `50000`), `didClose`, and folder-scope widen into `hw/ip/aes/rtl`. Settled `workspace/symbol`, `definition`, `references`, `codeLens`, and `lucisv/moduleHierarchy` matched fresh server answers 100% (`hier_files=1577, refs=2, syms=1` in workspace scope); `git -C /Users/lucio/repo/opentitan status --porcelain` stayed clean.
|
||||
- **Un-ignored QA checks passing**: `qa_tombstones_survive_mixed_remove_add_revive_absorb_and_all_queries_match_fresh` (`crates/vlog_semantic/tests/workspace.rs`) plus `qa_topo_49_tombstone_at_zero_and_middle_navigation_symbols_hierarchy_codelens_diagnostics_completion`, `qa_topo_63_all_paths_and_threshold_drop_after_unsaved_edit`, `qa_topo_50_first_scope_passed_unreached_and_mid_scan_close`, and `qa_topo_51_same_name_nested_both_open_dirty_close_and_filelist_close` (`crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
|
||||
### Final Gates (after last edit)
|
||||
- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`)
|
||||
- `cargo fmt -p vlog_semantic -p lucisv_server -- --check` -> exit `0`
|
||||
- `./tools/guard.sh -m 6 -t 600 -- cargo clippy --workspace --all-targets -- -D warnings` -> exit `0`
|
||||
- `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_semantic -p lucisv_server -p vlog_refactor -p lucisv_mcp -p vlog_linter --all-targets` -> exit `0` (`lucisv_server` unit: `2061 passed; 0 failed; 53 ignored` [includes 6 QA finding reproductions], `e2e`: `106 passed; 3 ignored`, `grammar`: `3 passed`, `ifdef_folding`: `1 passed`, `opentitan_references`: `0 passed; 2 ignored`; `vlog_semantic` `workspace`: `92 passed; 2 ignored` + remaining 19 binaries `0 failed`; `vlog_linter`: `658` unit + `14` `lint_cases` passed; `vlog_refactor`: all 20 binaries `0 failed`; `lucisv_mcp`: all 16 binaries `0 failed`).
|
||||
|
||||
### 2026-11-26 Round 2 Re-Verification (after DEV F1–F5 Fix Pass)
|
||||
- **Verdict**: `FAIL` (F1, F4, F5, and core F2/F3 scenarios pass; 2 new edge defects reproduced under adversarial F2/F3 attacks in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`).
|
||||
- **Audit & Hygiene**:
|
||||
- Verified all 27 modified/created production `.rs` files remain `<= 600` non-blank, non-comment lines before `mod tests` (max `crates/lucisv_server/src/state/discover.rs` = `505`), with `0` `unwrap()`, `expect()`, `panic!`, `unsafe`, or `#[allow` in added/modified production lines.
|
||||
- Audited every `.files()` and `FileId(` call site across `crates/` — zero remaining dense `0..files().len()` or `.files().enumerate()` assumptions over potentially tombstoned indexes in production code.
|
||||
- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`).
|
||||
- **Confirmed Resolved**:
|
||||
- **F1 (`live_files()`)**: All `qa_topo_49_*` pass; added `qa_r2_f1_multiple_tombstones_candidates_absorb_update_words_rename_and_completion` (`lifecycle_r2.rs`) and `qa_r2_f1_mcp_find_and_check_with_multiple_tombstones_preceding_live_files` (`crates/lucisv_mcp/src/tools/diagnostics.rs`), confirming `Candidates::from_words`/`update_words`/`absorb`, `rename_traced` macro-text warnings, `Completion`, `mcp::check`, and `mcp::find` (`refs` + near-match suggestions) pass with 3 tombstones preceding live files.
|
||||
- **F2 (core LSP handlers)**: `qa_topo_51_non_canonical_symlink_open_buffer_breaks_references_lint_and_rename` passes, plus `qa_r2_f2_non_canonical_symlink_open_buffer_across_all_handlers_and_case_mismatch` passes for symbol `hover`, symbol `gotoDefinition`, `ports::offers`/`resolve_for`, `extract::code_actions`/`execute`, `imports::offers`/`resolve`, `completion` `related_tier`, `callHierarchy` (`incoming` + `outgoing`), `design_hierarchy`, and macOS `case_only_mismatch` (`Foo.sv` vs `foo.sv`).
|
||||
- **F3 (simple mid-scan close) & F4 (widen symlinks)**: `qa_topo_50_mid_scan_non_canonical_symlink_over_max_file_size_matches_pre_scan`, `qa_r2_f3_mid_scan_open_dirty_symlink_and_close_mid_scan_matches_fresh` (in-scope and over `maxFileSize`), `qa_topo_51_widen_symlink_over_max_file_size_converges_like_fresh`, and `qa_r2_f4_widen_symlink_pointing_outside_root_converges_like_fresh` (under/over cap, closed/open outside targets) all pass.
|
||||
- **F5 (`reclassify_large_buffers`)**: `qa_topo_63_threshold_drop_after_unsaved_edit_indexed_via_widen_diverges_from_fresh` and `qa_r2_f5_reclassify_large_buffers_excluded_dirty_clean_and_round_trip` pass (clean `false -> true` does 1 empty `Document::large("")` parse and leaves `index().fingerprint()` / `derived_fingerprint()` unchanged; excluded unsaved drops from index; in-scope dirty preserves disk record across `false -> true` and `true -> false -> true` flips).
|
||||
- **Remaining / New Findings**:
|
||||
- **Finding R2-F2 (`includes.rs:552,584` & `hover.rs:101`) — Non-canonical symlink open buffer fails `` `include `` resolution & macro hover narrowing**: `includes::resolved` (`crates/lucisv_server/src/includes.rs:552`) and `includes::definition` (`:584`) pass raw `doc.path.as_deref()` instead of `ws.index_path_for`, and `hover::narrowed_to_the_include_graph` (`crates/lucisv_server/src/hover.rs:101`) filters `ws.index().path(*file)` via `reachable.contains(p)` without file-identity matching. Reproduced in `#[ignore]`d `qa_r2_f2_symlink_include_related_macros_links_def_and_hover_narrowing`: opening `z_real/real_b.sv` (when `a_link/link_a.sv -> z_real/real_b.sv` is indexed alongside `a_link/link_h.svh`) degrades `completion` `related_macros` (`sortText` `"5\`LINK_HDR_MAC"` vs `"4\`LINK_HDR_MAC"`), returns `[]` for `textDocument/documentLink` and `` `include `` `textDocument/definition`, and fails macro include-graph narrowing on `` `SHARED_MAC `` (`"defined 2 times"`).
|
||||
- **Finding R2-F3 (`state/incremental.rs:192-203`) — Mid-scan `didOpen(dirty symlink)` -> `didChange(disk)` -> `didClose` leaves stale `IN_BUF` edit**: `Workspace::closing_affects_running_scan` checks `fs::read_to_string(&target).ok().as_ref() != Some(&doc.text)`, returning `false` after `didChange` restores disk text even though the earlier mid-scan `didOpen(dirty)` had already been absorbed into the running scan. Reproduced in `#[ignore]`d `qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index` (`ON_DISK = 0`, `IN_BUF = 1`).
|
||||
- **Final Gates**:
|
||||
- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`)
|
||||
- `cargo fmt --all -- --check` -> exit `0`
|
||||
- `./tools/guard.sh -m 6 -t 600 -- cargo clippy --workspace --all-targets -- -D warnings` -> exit `0`
|
||||
- `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_semantic -p lucisv_server -p vlog_refactor -p lucisv_mcp -p vlog_linter --all-targets` -> exit `0` (`lucisv_server` unit: `2072 passed; 0 failed; 49 ignored` [includes 2 `qa_r2_*` `#[ignore]`d reproductions], `e2e`: `106 passed; 0 failed; 3 ignored`, `grammar`: `3 passed`, `ifdef_folding`: `1 passed`, `opentitan_references`: `0 passed; 2 ignored`; `lucisv_mcp`: all 16 binaries `0 failed`; `vlog_linter`: `658` unit + `14` `lint_cases` passed; `vlog_refactor`: all 24 binaries `0 failed`; `vlog_semantic`: all 21 binaries `0 failed`, `workspace`: `92 passed; 0 failed; 2 ignored`).
|
||||
|
||||
### 2026-11-26 Round 2 Closing-Pass QA Verification (after R2-F2 & R2-F3 Fixes)
|
||||
- **Verdict**: `FAIL` (both previously `#[ignore]`d R2-F2 and R2-F3 reproductions now pass un-ignored, and `didOpen(dirty) -> didSave(None) -> didClose` converges, **but** adversarial multi-hop symlinked-directory and `has_other_document_for` two-URI mid-scan close attacks uncover 3 concrete defects: `R2-F2b`, `R2-F3a`, `R2-F3b`).
|
||||
- **Audit & Hygiene**:
|
||||
- `git status --short` / `git diff --stat`: 35 modified + 2 untracked `.rs` files (`reconcile.rs`, `lifecycle_r2.rs`) + `docs/features/index-lifecycle-r2/`.
|
||||
- Verified all 29 modified/created production `.rs` files remain `<= 600` non-blank, non-comment lines before `mod tests` (max `crates/lucisv_server/src/state/discover.rs` = `505`, `state/reconcile.rs` = `225`, `state/rescan.rs` = `480`, `state/incremental.rs` = `225`, `state/mod.rs` = `149`, `includes.rs` = `353`, `hover.rs` = `323`), with `0` `unwrap()`, `expect()`, `panic!`, `unsafe`, or `#[allow` in added/modified production lines.
|
||||
- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`).
|
||||
- **Confirmed Resolved & New Passing QA Checks**:
|
||||
- **R2-F2**: `qa_r2_f2_symlink_include_related_macros_links_def_and_hover_narrowing` runs un-ignored and passes. Added un-ignored `qa_r2_f2_multihop_transitive_symlink_headers` (confirming `documentLink`, `` `include `` `definition`, `completion` `related_macros` for transitive `H2_DEEP_MAC`, and `hover` macro narrowing over `z_real/real_b.sv` -> `a_link/link_h1.svh` -> `a_link/link_h2.svh`) and `qa_r2_f2_multihop_symlink_directory_completion_and_hover_narrowing` (confirming transitive `completion` `related_macros` and `hover` macro narrowing over symlinked directory `a_link_dir -> z_real_dir`, including non-canonical open `z_real_dir/real_b.sv` and external caller `rtl/caller.sv` -> `../z_real_dir/h1.svh`), all passing.
|
||||
- **R2-F3**: `qa_r2_f3_mid_scan_dirty_open_reverted_and_closed_leaves_stale_index` and `r2_f3_mid_scan_dirty_reverted_and_closed_converges_across_all_scan_phases` run un-ignored and pass. Added un-ignored `qa_r2_f3_mid_scan_dirty_open_saved_none_and_closed` (covering `didOpen(dirty) -> didSave(None) -> didClose` mid-scan for `in_scope_future`, `in_scope_past`, and `excluded`) and `qa_r2_f3_two_symlink_uris_both_dirty_one_closed_mid_scan_converges` (`pos >= scan.at`), all passing.
|
||||
- **New Findings (Reproduced as `#[ignore]`d tests in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`)**:
|
||||
- **Finding R2-F2b (`crates/lucisv_server/src/includes.rs:544-552`) — `resolve_for_doc` returns non-canonical target for symlinked directory**: When `a_link_dir -> z_real_dir` is a symlinked directory (`a_link_dir/{real_b.sv,h1.svh,h2.svh}` indexed) and the client opens `z_real_dir/real_b.sv` containing `` `include "h1.svh" ``, `resolve_for_doc` returns `graph.resolve(doc.path.as_deref(), include)` directly (`z_real_dir/h1.svh`) without normalizing through `ws.index_path_for(...)`, so `documentLink` and `` `include `` `definition` point to non-canonical `z_real_dir/h1.svh` instead of canonical `a_link_dir/h1.svh` (diverging from `via_canon` and `nav.rs`). Reproduced in `#[ignore]`d `qa_r2_f2_multihop_symlink_directory_links_and_def_return_non_canonical`.
|
||||
- **Finding R2-F3a (`crates/lucisv_server/src/state/reconcile.rs:192-194` & `crates/lucisv_server/src/state/incremental.rs:197-203`) — closing clean canonical symlink at `pos < scan.at` with `has_other_document_for` drops surviving dirty symlink buffer**: When `0_link/dut.sv -> z_real/dut.sv` (`pos < scan.at`, already stepped cleanly from disk `ON_DISK`) is opened with `ON_DISK` alongside `z_real/dut.sv` with `DIRTY_Z`, `reconcile_open_buffers_into` handles `0_link/dut.sv` first, takes `if already_same { continue; }` without calling `scan_absorbed.record(...)`, and skips `z_real/dut.sv` via `matched_positions.insert(pos)`. Mid-scan `didClose(0_link/dut.sv)` then sees `scan_absorbed == false` and `has_other == true` in `closing_affects_running_scan`, returning `false` at `if has_other { return false; }`, so the scan finishes with `ON_DISK` instead of surviving open `z_real/dut.sv`'s `DIRTY_Z`. Reproduced in `#[ignore]`d `qa_r2_f3_two_symlink_uris_one_closed_already_same_drops_surviving_dirty`.
|
||||
- **Finding R2-F3b (`crates/lucisv_server/src/state/incremental.rs:198-203`) — closing `doc.large`-flipped absorbed symlink with `has_other_document_for` leaves stale absorbed edits**: When `a_link/dut.sv` (`DIRTY_A`, absorbed into `scan` and recorded in `scan_absorbed`) and `z_real/dut.sv` (`ON_DISK`) are both open, `didChange` flips `a_link/dut.sv` to `doc.large = true`, and `didClose(a_link/dut.sv)` runs mid-scan while `z_real/dut.sv` remains open, `closing_affects_running_scan` evaluates `(!doc.large || !has_other)` as `false` and returns `false` at `if has_other { return false; }`. No follow-up rescan runs, leaving stale `DIRTY_A` from the closed `a_link/dut.sv` in the finished index instead of `z_real/dut.sv`'s `ON_DISK`. Reproduced in `#[ignore]`d `qa_r2_f3_two_symlink_uris_large_flip_one_closed_leaves_stale_index`.
|
||||
- **Final Gates**:
|
||||
- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`)
|
||||
- `cargo fmt --all -- --check` -> exit `0`
|
||||
- `./tools/guard.sh -m 6 -t 600 -- cargo clippy --workspace --all-targets -- -D warnings` -> exit `0`
|
||||
- `./tools/guard.sh -m 6 -t 600 -- cargo test -p vlog_semantic -p lucisv_server -p vlog_refactor -p lucisv_mcp -p vlog_linter --all-targets` -> exit `0` (`lucisv_server` unit: `2079 passed; 0 failed; 50 ignored` [includes the 3 `qa_r2_*` `#[ignore]`d reproductions], `e2e`: `106 passed; 0 failed; 3 ignored`, `grammar`: `3 passed`, `ifdef_folding`: `1 passed`, `opentitan_references`: `0 passed; 2 ignored`; `lucisv_mcp`: all 16 binaries `0 failed`; `vlog_linter`: `658` unit + `14` `lint_cases` passed; `vlog_refactor`: all 24 binaries `0 failed`; `vlog_semantic`: all 21 binaries `0 failed`, `workspace`: `92 passed; 0 failed; 2 ignored`).
|
||||
- `/tmp` clean (`0` `lucisv` temp files leftover); `/Users/lucio/repo/opentitan` untouched (`git status --porcelain` empty).
|
||||
|
||||
### 2026-11-26 Round 2 Final QA Sign-Off (after R2-F2b, R2-F3a, R2-F3b & Cross-Platform `DirId` Fixes)
|
||||
- **Verdict**: `PASS`
|
||||
- **Resolved Repros (un-ignored and passing in `crates/lucisv_server/src/server/tests/lifecycle_r2.rs`)**:
|
||||
- `qa_r2_f2_multihop_symlink_directory_links_and_def_return_non_canonical` (`ok`)
|
||||
- `qa_r2_f3_two_symlink_uris_one_closed_already_same_drops_surviving_dirty` (`ok`)
|
||||
- `qa_r2_f3_two_symlink_uris_large_flip_one_closed_leaves_stale_index` (`ok`)
|
||||
- `crates/lucisv_server/src/server/tests/lifecycle_r2.rs` now has `0` `#[ignore]`d tests.
|
||||
- **Edge-Case & Cross-Platform Audit**:
|
||||
- `crates/lucisv_server/src/includes.rs:544-552` (`resolve_for_doc`): `ws.index_path_for(&found)` delegates to `held_path_for(found).unwrap_or_else(|| found.to_path_buf())` (`state/mod.rs:219-221`), returning `found` unchanged when `found` is a closed excluded header not present in `self.index` (and returning the indexed spelling if opened as non-large or if another symlink of the same file is indexed, while honoring `case_only_mismatch`).
|
||||
- `crates/lucisv_server/src/state/incremental.rs:193-204` (`closing_affects_running_scan`): returning `true` on `self.scan_absorbed.contains(path, &target) || self.has_other_document_for(uri, path)` preserves surviving dirty/clean/`doc.large` symlink buffers on mid-scan `didClose` across all `scan.at` phases (`pos < scan.at` `already_same` skips, `pos >= scan.at`, `doc.large` flips, and `case_only_mismatch` isolation in `has_other_document_for`) without breaking any existing `lucisv_server` test.
|
||||
- `crates/lucisv_server/src/state/discover.rs:715-735` and `crates/lucisv_server/src/state/reconcile.rs:206-215`: non-Unix `DirId` (`PathBuf`) borrow-before-move ordering (`&id` / `id.as_ref()` before `canonical_ids.entry(id)` and `added_ids.insert(k)`) passes `cross` for both `x86_64-pc-windows-gnu` and `x86_64-unknown-linux-musl`.
|
||||
- **Audit & Hygiene**:
|
||||
- Verified all 29 modified/created production `.rs` files remain `<= 600` non-blank, non-comment lines before `mod tests`: `crates/lucisv_server/src/includes.rs` (`353`), `state/incremental.rs` (`221`), `state/discover.rs` (`510`, max across all modified prod files), `state/reconcile.rs` (`231`), with `0` `unwrap()`, `expect()`, `panic!(`, `unsafe`, or `#[allow` in production sections.
|
||||
- `python3 tools/stamp_author.py --check` -> exit `0` (`would stamp 0 files; left 249 untouched`).
|
||||
- **Final Gates (`./tools/gates.sh --only fmt,clippy,suite:vlog_semantic,suite:lucisv_server,suite:lucisv_mcp,cross`, logs in `target/gates/20261126-111210`)**:
|
||||
- `fmt` -> `pass` (exit `0`)
|
||||
- `clippy` -> `pass` (exit `0`)
|
||||
- `suite:vlog_semantic` -> `pass` (`21` binaries: `438 passed; 0 failed; 4 ignored`)
|
||||
- `suite:lucisv_server` -> `pass` (`5` binaries: `2192 passed; 0 failed; 52 ignored`; unit `2082 passed; 0 failed; 47 ignored`, `e2e` `106 passed; 3 ignored`, `grammar` `3 passed`, `ifdef_folding` `1 passed`, `opentitan_references` `0 passed; 2 ignored`)
|
||||
- `suite:lucisv_mcp` -> `pass` (`16` binaries: `391 passed; 0 failed; 4 ignored`)
|
||||
- `cross` -> `pass` (`x86_64-pc-windows-gnu` & `x86_64-unknown-linux-musl` for `lucisv`, `lucisv_server`, `lucisv_mcp`, exit `0`)
|
||||
- `/tmp` clean; `/Users/lucio/repo/opentitan` untouched (`git status --porcelain` empty).
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-11-26 — Lead review: PASS (Round 2 complete)
|
||||
|
||||
- Verified all Round 2 deliverables (`#49` fast tombstones via `WorkspaceIndex::remove_file` + `live_files()`, `#50` mid-scan open buffer reconciliation, `#51` `(dev, ino)` canonical symlink deduplication across handlers/includes/hover, `#63` least-performance-impact disk record preservation for `doc.large`, and `ScanAbsorbed` tracking + cross-platform `DirId` borrow fixes) and checked that `crates/lucisv_server/src/server/tests/lifecycle_r2.rs` has 0 `#[ignore]`d tests left.
|
||||
- All 29 modified/created production files stay `<= 600` non-blank, non-comment lines before `mod tests`, with `0` `unwrap`/`expect`/`panic!`/`unsafe`.
|
||||
- Handshakes closed in `docs/topo.md`: `#48` (closed won't-fix per owner ruling: rely on VS Code), `#49`, `#50`, `#51`, `#63`. Full `./tools/gates.sh` (including `cross`) and final QA sign-off gates verified green.
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
+5
-5
@@ -773,10 +773,10 @@ update the filing README(s) and this file.
|
||||
| 45 | **`` `ifdef `` between `end` and `else` is a parse error** (TODO §71 wave 4) | format-styles (QA) | vlog_parser |
|
||||
| 46 | **An attribute on an ANSI port** (`(* keep *) input a`) is a parse error (TODO §71 wave 4) | format-styles (QA) | vlog_parser |
|
||||
| 47 | **Multi-instance declarations under one-per-line styles** (`p1 u8 (...), u9 (...)`) get the hanging layout instead of the style's (TODO §71 wave 4; CHANGELOG 0.65.5 known limit) | format-styles (QA) | vlog_formatter |
|
||||
| 48 | **Directory-only watcher events.** VS Code coalesces deletes under a removed folder into one folder event and the client's `**/*.{v,vh,sv,svh}` filter drops it, so the server receives nothing; a folder moved in is dropped likewise. Wanted: a second registration (`**/*`, `Create \| Delete`) and a handler expanding a folder to the held files and include lines under it — changes every client's registration and traffic, the owner's call (TODO §71 waves 5–6) | localized-reindex (QA P1); scan-ordering | owner decision, then lucisv_server (`main.rs`/`watch.rs`) |
|
||||
| 49 | **A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6) | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | vlog_semantic (index removal) / lucisv_server (`state/`) |
|
||||
| 50 | **An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6) | scan-ordering (QA-2) | lucisv_server (`state/scan.rs`, `server/index.rs`) |
|
||||
| 51 | **Symlinked files are held under one spelling or both** depending on what was open at scan time (`discover.rs`'s `Aliased`); incremental and rebuild answers disagree in all six `filelink.py` variants. Rule to adopt: one file, one spelling, whatever is open — in the walk, the overlay and the one-file path together (TODO §71 waves 5–6) | localized-reindex (QA P3); scan-ordering | lucisv_server (`state/discover.rs`, `state/incremental.rs`) |
|
||||
| ~~48~~ | ~~**Directory-only watcher events.** VS Code coalesces deletes under a removed folder into one folder event and the client's `**/*.{v,vh,sv,svh}` filter drops it, so the server receives nothing; a folder moved in is dropped likewise. Wanted: a second registration (`**/*`, `Create \| Delete`) and a handler expanding a folder to the held files and include lines under it — changes every client's registration and traffic, the owner's call (TODO §71 waves 5–6)~~ — **closed 2026-11-26 (won't-fix by owner ruling):** rely on VS Code; no second watcher registration added. | localized-reindex (QA P1); scan-ordering | ~~owner decision~~ won't-fix |
|
||||
| ~~49~~ | ~~**A buffer the scope would not take stays indexed after `didClose`** (excluded or unlisted, taken in by a scan or the one-file path), and **closing an unsaved in-scope buffer a rescan indexed leaves its text in the index** (QA-7a). One root: a close does not touch the index. A one-file remove costs ~225 ms on OpenTitan (fixed and reverted in scan-ordering); wanted: a cheap removal, e.g. a tombstone the next scan or publish folds in (TODO §71 waves 5–6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `WorkspaceIndex::remove_file` tombstones slots in-place via `replace_facts`, `live_files()` skips tombstones across all callers (`sources.rs`, `candidates.rs`, `lucisv_mcp`), and `DidCloseTextDocument` calls `close_and_reconcile` (2,000 cycles on 4k index at ~2.98 ms / 112.6 µs). | localized-reindex (QA P2); scan-ordering (QA-1, QA-7a) | ~~vlog_semantic / lucisv_server~~ done |
|
||||
| ~~50~~ | ~~**An unheld buffer opened while a scan runs is never taken in** by that scan or afterwards; opened before the scan it is held — the same final state answers differently by timing (TODO §71 wave 6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `reconcile_open_buffers_into`, `ScanAbsorbed`, and `closing_affects_running_scan` reconcile mid-scan opens/edits/closes to match pre-scan opens. | scan-ordering (QA-2) | ~~lucisv_server (`state/`)~~ done |
|
||||
| ~~51~~ | ~~**Symlinked files are held under one spelling or both** depending on what was open at scan time (`discover.rs`'s `Aliased`); incremental and rebuild answers disagree in all six `filelink.py` variants. Rule to adopt: one file, one spelling, whatever is open — in the walk, the overlay and the one-file path together (TODO §71 waves 5–6)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2):** `(dev, ino)` / canonical-path deduplication without basename gating across discovery, widen, buffers, `includes.rs`, `hover.rs`, and handlers (`index_path_for` / `is_same_file`). | localized-reindex (QA P3); scan-ordering | ~~lucisv_server (`state/`, handlers)~~ done |
|
||||
| ~~52~~ | ~~**A request held during a scan is answered against the newest text**, so a position-based request can resolve a different symbol when an edit moved the text under it; rename edits carry no document version for the client to reject (TODO §71 wave 6)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `Document` tracks client `version: Option<i32>`, and `ports::encode_edit` (shared by `rename.rs` and `ports.rs`) emits versioned `DocumentChanges::Edits` preserving open client URIs when `workspace.workspaceEdit.documentChanges` is advertised. | scan-ordering (QA) | ~~lucisv_server (`server/`, `rename.rs`)~~ done |
|
||||
| ~~53~~ | ~~**Renaming a port of a module defined twice** gives an edit or a refusal at random across fresh servers (`top_englishbreakfast/ip/ast/rtl/adc.sv:81`, `qa717/drv/dup.py`); not diagnosed (TODO §71 wave 6)~~ — **closed 2026-11-26 by Round 1 (`refactor-correctness-r1` + `server-ordering-r1`):** `lucisv_server` holds workspace-wide mutating requests (`rename`, `codeAction/resolve`, `executeCommand`, `willRenameFiles`) in `after_scan` across `self.scanning`, and `vlog_refactor::rename` + `preflight` + `same_file::renamed_here` refuse members inside duplicated file-scope units; verified 10/10 deterministic on OpenTitan `adc.sv:81`. | scan-ordering (QA-7c) | ~~vlog_refactor / lucisv_server~~ done |
|
||||
| 54 | **`lucisv-mcp` re-reads a file with a future mtime on every call**, forever (67 ms against 7 ms per `find` on 4 000 files) — the racy rule never settles (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (`project/files.rs`) |
|
||||
@@ -788,7 +788,7 @@ update the filing README(s) and this file.
|
||||
| 60 | **An edit in one file that changes how another open file colours sends no refresh** (a package type renamed) — as before this lane (TODO §71 wave 7) | viewport-highlight | lucisv_server (`server/viewport.rs`) |
|
||||
| ~~61~~ | ~~**Inside the startup settings wait, the client's answer to the pull is applied ahead of an older settings push held with it** (`server/startup.rs`, `take_the_answer_out_of_held`); predates fast-actions; needs a client whose push and answer disagree in one burst (TODO §71 wave 8; fast-actions QA F1)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `take_the_answer_out_of_held` drains older `DidChangeConfiguration` pushes preceding the plucked pull answer while keeping newer pushes. | fast-actions (QA) | ~~lucisv_server (`server/startup.rs`)~~ done |
|
||||
| ~~62~~ | ~~**`tests/fast_actions_bursts.rs`'s oracle accepts an answer the reference gives after any later message of the round**: 2–9 % of injected stale answers pass when a later message restores the state; every mutation is still caught and the directed tests lack the weakness (TODO §71 wave 8; fast-actions QA F4)~~ — **closed 2026-11-26 by `server-ordering-r1` (Round 1):** `ahead::take_ahead_applied` records exact `applied_changes` and the oracle asserts `applied >= required` and `e == reference_at[applied]`. | fast-actions (QA) | ~~lucisv_server (tests)~~ done |
|
||||
| 63 | **Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8) | fast-actions (QA) | lucisv_server (`state/`, the index lane) |
|
||||
| ~~63~~ | ~~**Whether a large open buffer is in the index depends on when it was opened, saved or scanned** — a fast-path buffer contributes nothing when open at scan or save time but keeps its disk record when opened after the scan; 77–98 answers differ between a settled session and a fresh server on OpenTitan. Predates fast-actions; wanted: always keep, or always drop, the disk record of a fast-path buffer at open, save, flip and scan alike (TODO §71 wave 8; fast-actions QA S2, Handshake request 8)~~ — **closed 2026-11-26 by `index-lifecycle-r2` (Round 2, owner decision 2):** standardized on always keeping the disk index record (subject to `maxFileSize`) across open, close, save, widen, scan, and threshold flips. | fast-actions (QA) | ~~lucisv_server (`state/`, `server/large_file.rs`)~~ done |
|
||||
| 64 | **The 40 000-file rescan after a delete takes either 12.3 s or 14.5–15.5 s**, on 0.65.10 and 0.65.11 alike; cause not found (TODO §71 wave 8) | fast-actions | undiagnosed (lucisv_server scan) |
|
||||
| 65 | **`ci.yml` runs `cargo test --workspace` bare in both jobs**, not through `tools/guard.sh` as CLAUDE.md's runaway guard asks of every `cargo test`; predates 0.65.9 for the macOS job, the Linux runner is resource-capped. Recorded, not judged (topo refresh 2026-11-19) | topo refresh (draft discrepancy 10) | CI (lead) |
|
||||
| 66 | **The `cross` gate step reports `SKIPPED (no toolchain)` rather than failing** when `~/.rustup/toolchains/stable-aarch64-apple-darwin` is absent, so a green `gates.sh` on another machine does not prove the cross build (topo refresh 2026-11-19) | topo refresh (draft discrepancy 11) | tools/ (`gates.sh`, lead) |
|
||||
|
||||
Reference in new issue
Block a user