This commit is contained in:
1 parent
4d384ec89d
commit
69383eae7f
21 files changed
+1127
-123
No files matched your search
@@ -158,6 +158,10 @@ pub struct Stamp {
|
||||
/// The same moment by the monotonic clock: what tells a wall clock that
|
||||
/// was stepped back since the read.
|
||||
pub read_mono: Instant,
|
||||
/// When these exact bytes and metadata were first observed on the
|
||||
/// monotonic clock; preserved across unchanged re-reads so a file with a
|
||||
/// future timestamp settles after [`RACY`].
|
||||
pub first_mono: Instant,
|
||||
/// Its ctime and inode — what still moves when a same-size rewrite puts
|
||||
/// the old mtime back (`cp -p`, `rsync -t`, `touch -r`), git's answer to
|
||||
/// the same problem. `None` off Unix, where size, mtime and the racy rule
|
||||
@@ -233,23 +237,50 @@ impl Stamp {
|
||||
fn compare(&self, seen: Seen, now: Clocks) -> Change {
|
||||
let moved =
|
||||
seen.size != self.size || seen.mtime != self.mtime || seen.identity != self.identity;
|
||||
if moved || self.racy() || self.clock_stepped_back(now) {
|
||||
if moved || self.racy(now) || self.clock_stepped_back(now) {
|
||||
Change::Suspect
|
||||
} else {
|
||||
Change::Same
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve [`Self::first_mono`] across an unchanged re-read when there
|
||||
/// was no wall-clock step-back, letting a future timestamp settle after
|
||||
/// [`RACY`] of monotonic time has elapsed and re-verified the bytes.
|
||||
pub fn inherit_observation(&mut self, prev: &Stamp) {
|
||||
let same = self.size == prev.size
|
||||
&& self.mtime == prev.mtime
|
||||
&& self.hash == prev.hash
|
||||
&& self.identity == prev.identity;
|
||||
let now = Clocks { wall: self.read_at, mono: self.read_mono };
|
||||
if same && !prev.clock_stepped_back(now) {
|
||||
self.first_mono = prev.first_mono;
|
||||
}
|
||||
}
|
||||
|
||||
/// **Invariant: a stamp is trusted on a later match only if every
|
||||
/// timestamp it trusts (the mtime, and the ctime where there is one) is
|
||||
/// at least [`RACY`] older than the moment the stamp was taken** —
|
||||
/// otherwise a write inside the same timestamp tick, after the read,
|
||||
/// leaves every one of them as it was. A timestamp that is missing, or
|
||||
/// later than the read (a clock behind the filesystem's), is racy too.
|
||||
fn racy(&self) -> bool {
|
||||
/// settled:**
|
||||
/// - for a timestamp at or before `read_at`, it must be at least [`RACY`]
|
||||
/// older than `read_at`;
|
||||
/// - for a future timestamp (`time > read_at`, e.g. clock skew or NFS), it
|
||||
/// stays racy until [`RACY`] has elapsed on the monotonic clock between
|
||||
/// first observation and this read (`read_mono - first_mono >= RACY`),
|
||||
/// unless the wall clock has caught up to `time` (forcing one re-read
|
||||
/// back into the normal rule).
|
||||
fn racy(&self, now: Clocks) -> bool {
|
||||
let ctime = self.identity.map(|identity| identity.ctime);
|
||||
[Some(self.mtime), ctime].into_iter().flatten().any(|stamped| match stamped {
|
||||
Some(time) => time.checked_add(RACY).is_none_or(|settled| settled > self.read_at),
|
||||
Some(time) if time <= self.read_at => {
|
||||
time.checked_add(RACY).is_none_or(|settled| settled > self.read_at)
|
||||
}
|
||||
Some(time) => {
|
||||
now.wall >= time
|
||||
|| self
|
||||
.read_mono
|
||||
.checked_duration_since(self.first_mono)
|
||||
.is_none_or(|elapsed| elapsed < RACY)
|
||||
}
|
||||
None => true,
|
||||
})
|
||||
}
|
||||
@@ -273,7 +304,12 @@ impl Stamp {
|
||||
/// test ages a stamp past the racy window without waiting for it.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn taken_later(self, by: Duration) -> Stamp {
|
||||
Stamp { read_at: self.read_at + by, read_mono: self.read_mono + by, ..self }
|
||||
Stamp {
|
||||
read_at: self.read_at + by,
|
||||
read_mono: self.read_mono + by,
|
||||
first_mono: self.first_mono + by,
|
||||
..self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +332,7 @@ pub fn read_source(path: &Path) -> io::Result<(String, Stamp)> {
|
||||
hash,
|
||||
read_at: read.wall,
|
||||
read_mono: read.mono,
|
||||
first_mono: read.mono,
|
||||
identity: seen.identity,
|
||||
program: text.contains("endprogram"),
|
||||
};
|
||||
@@ -402,6 +439,7 @@ mod tests {
|
||||
hash: 7,
|
||||
read_at: read,
|
||||
read_mono: mono,
|
||||
first_mono: mono,
|
||||
identity: Some(Identity { ctime: Some(read - ctime_age), ino: 42 }),
|
||||
program: false,
|
||||
}
|
||||
@@ -509,6 +547,79 @@ mod tests {
|
||||
assert_eq!(stamp.compare(seen, now), Change::Suspect, "{seen:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn future_timestamp_settles_after_racy_and_reacts_to_catchup_stepback_or_edits() {
|
||||
let (read, mono) = (SystemTime::now(), Instant::now());
|
||||
let old = Duration::from_secs(3600);
|
||||
let future = read + Duration::from_secs(600);
|
||||
let mut initial = stamp_aged(read, mono, old, old);
|
||||
initial.mtime = Some(future);
|
||||
|
||||
// Initial read is racy until monotonic time >= RACY has elapsed at a re-read.
|
||||
assert_eq!(initial.compare(unchanged(&initial), a_second_later(&initial)), Change::Suspect);
|
||||
|
||||
let before_racy = RACY - Duration::from_millis(1);
|
||||
let mut mid = Stamp {
|
||||
read_at: read + before_racy,
|
||||
read_mono: mono + before_racy,
|
||||
first_mono: mono + before_racy,
|
||||
..initial
|
||||
};
|
||||
mid.inherit_observation(&initial);
|
||||
assert_eq!(mid.first_mono, mono);
|
||||
assert_eq!(mid.compare(unchanged(&mid), a_second_later(&mid)), Change::Suspect);
|
||||
|
||||
// Once RACY has elapsed and a re-read confirms the same bytes, it settles.
|
||||
let mut settled =
|
||||
Stamp { read_at: read + RACY, read_mono: mono + RACY, first_mono: mono + RACY, ..mid };
|
||||
settled.inherit_observation(&mid);
|
||||
assert_eq!(settled.first_mono, mono);
|
||||
assert_eq!(settled.compare(unchanged(&settled), a_second_later(&settled)), Change::Same);
|
||||
|
||||
// If the wall clock later catches up to `future`, trigger one re-read.
|
||||
let caught_up = Clocks { wall: future, mono: mono + Duration::from_secs(600) };
|
||||
assert_eq!(settled.compare(unchanged(&settled), caught_up), Change::Suspect);
|
||||
|
||||
// A hash change or wall-clock step-back resets `first_mono`.
|
||||
let mut changed =
|
||||
Stamp { hash: 99, read_at: read + RACY, read_mono: mono + RACY, ..settled };
|
||||
changed.first_mono = mono + RACY;
|
||||
changed.inherit_observation(&settled);
|
||||
assert_eq!(changed.first_mono, mono + RACY);
|
||||
assert_eq!(changed.compare(unchanged(&changed), a_second_later(&changed)), Change::Suspect);
|
||||
|
||||
let mut stepped = Stamp {
|
||||
read_at: settled.read_at - STEP_BACK - Duration::from_secs(1),
|
||||
read_mono: settled.read_mono + Duration::from_secs(1),
|
||||
first_mono: settled.read_mono + Duration::from_secs(1),
|
||||
..settled
|
||||
};
|
||||
stepped.inherit_observation(&settled);
|
||||
assert_eq!(stepped.first_mono, stepped.read_mono);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn real_future_mtime_file_detects_edits_and_settles_with_reobservation() {
|
||||
let dir = scratch("future-mtime");
|
||||
let path = dir.join("a.sv");
|
||||
fs::write(&path, "module a; endmodule\n").unwrap();
|
||||
let future = SystemTime::now() + Duration::from_secs(3600);
|
||||
fs::OpenOptions::new().write(true).open(&path).unwrap().set_modified(future).unwrap();
|
||||
|
||||
let (_, initial) = read_source(&path).unwrap();
|
||||
assert_eq!(initial.check(&path), Change::Suspect);
|
||||
|
||||
// Simulated re-read after RACY with inherited observation settles on disk.
|
||||
let mut reobserved = initial.taken_later(RACY);
|
||||
reobserved.first_mono = initial.first_mono;
|
||||
assert_eq!(reobserved.check(&path), Change::Same);
|
||||
|
||||
// A subsequent edit still turns Suspect immediately.
|
||||
fs::write(&path, "module a2; endmodule\n").unwrap();
|
||||
assert_eq!(reobserved.check(&path), Change::Suspect);
|
||||
fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -181,8 +181,14 @@ impl Project {
|
||||
/// Re-read one file whose stamp is in doubt; a changed hash is a record.
|
||||
fn reread(&mut self, path: PathBuf, records: &mut Vec<FileFacts>, gone: &mut Vec<PathBuf>) {
|
||||
match read_source(&path) {
|
||||
Ok((text, stamp)) => {
|
||||
let moved = self.files.get(&path).is_none_or(|old| old.hash != stamp.hash);
|
||||
Ok((text, mut stamp)) => {
|
||||
let moved = match self.files.get(&path) {
|
||||
Some(old) => {
|
||||
stamp.inherit_observation(old);
|
||||
old.hash != stamp.hash
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if moved {
|
||||
records.push(FileFacts::of(path.clone(), &text));
|
||||
}
|
||||
@@ -280,6 +286,15 @@ impl Project {
|
||||
/// holding it; symlinks followed; and refused, by name, unless it lands
|
||||
/// on a file inside a root.
|
||||
pub fn resolve(&self, arg: &str) -> Result<PathBuf, String> {
|
||||
let path = self.resolve_existing(arg)?;
|
||||
if !path.is_file() {
|
||||
return Err(format!("`{arg}` is not a file."));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
/// Resolve an existing file or directory inside one of the project roots.
|
||||
pub fn resolve_existing(&self, arg: &str) -> Result<PathBuf, String> {
|
||||
let given = Path::new(arg);
|
||||
let candidates: Vec<PathBuf> = if given.is_absolute() {
|
||||
vec![given.to_path_buf()]
|
||||
@@ -294,9 +309,6 @@ impl Project {
|
||||
"`{arg}` resolves outside every root; lucisv-mcp only reads inside its roots."
|
||||
));
|
||||
}
|
||||
if !path.is_file() {
|
||||
return Err(format!("`{arg}` is not a file."));
|
||||
}
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -366,7 +378,83 @@ fn relative_to(roots: &[PathBuf], path: &Path) -> String {
|
||||
parts.join("/")
|
||||
}
|
||||
|
||||
impl vlog_refactor::KnownFacts for Project {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
let stamp = self.files.get(path)?;
|
||||
if stamp.hash != lucisv_core::cache::content_hash(text.as_bytes()) {
|
||||
return None;
|
||||
}
|
||||
self.index.facts_for(path).cloned()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod r3_tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
use std::time::{Duration, SystemTime};
|
||||
use vlog_refactor::KnownFacts;
|
||||
|
||||
#[test]
|
||||
fn known_facts_matches_exact_bytes_and_invalidates_after_refresh() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-project-known-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let file = fs::canonicalize(&dir).unwrap().join("a.sv");
|
||||
let v1 = "module a; logic s1; endmodule\n";
|
||||
fs::write(&file, v1).unwrap();
|
||||
|
||||
let mut project = Project::open(vec![fs::canonicalize(&dir).unwrap()], None);
|
||||
assert!(project.facts_for(&file, v1).is_some_and(|f| f.path() == file));
|
||||
|
||||
let v2 = "module a; logic s2; endmodule\n";
|
||||
assert!(project.facts_for(&file, v2).is_none(), "stale text must miss");
|
||||
|
||||
fs::write(&file, v2).unwrap();
|
||||
let refresh = project.refresh(false);
|
||||
assert_eq!(refresh.changed, 1);
|
||||
assert!(project.facts_for(&file, v1).is_none(), "old hash invalidated");
|
||||
assert!(project.facts_for(&file, v2).is_some(), "new hash hits");
|
||||
|
||||
fs::remove_file(&file).unwrap();
|
||||
project.refresh(false);
|
||||
assert!(project.facts_for(&file, v2).is_none(), "removed file misses");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_reread_inherits_observation_for_future_mtime_settlement() {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-project-future-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let file = fs::canonicalize(&dir).unwrap().join("f.sv");
|
||||
fs::write(&file, "module f; endmodule\n").unwrap();
|
||||
let future = SystemTime::now() + Duration::from_secs(3600);
|
||||
fs::OpenOptions::new().write(true).open(&file).unwrap().set_modified(future).unwrap();
|
||||
|
||||
let mut project = Project::open(vec![fs::canonicalize(&dir).unwrap()], None);
|
||||
let first_mono = project.files[&file].first_mono;
|
||||
// First refresh sees Suspect and re-reads; hash matches so changed == 0,
|
||||
// while `first_mono` stays anchored at initial observation.
|
||||
let r1 = project.refresh(false);
|
||||
assert_eq!(r1.changed, 0);
|
||||
assert_eq!(project.files[&file].first_mono, first_mono);
|
||||
|
||||
// Once the previous stamp is past RACY relative to `first_mono`, re-read
|
||||
// settles cleanly and the next `check` sees `Change::Same`.
|
||||
if let Some(stamp) = project.files.get_mut(&file) {
|
||||
let mut aged = stamp.taken_later(Duration::from_secs(4));
|
||||
aged.first_mono = first_mono;
|
||||
*stamp = aged;
|
||||
}
|
||||
assert_eq!(project.files[&file].check(&file), Change::Same);
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -228,7 +228,7 @@ impl Server {
|
||||
self.version = Some(version);
|
||||
json!({
|
||||
"protocolVersion": version,
|
||||
"capabilities": { "tools": {}, "resources": {}, "prompts": {} },
|
||||
"capabilities": { "tools": {}, "resources": {} },
|
||||
"serverInfo": { "name": "lucisv-mcp", "version": env!("CARGO_PKG_VERSION") },
|
||||
"instructions": instructions(self.options.mode),
|
||||
})
|
||||
@@ -368,9 +368,9 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_instructions_stay_under_400_bytes() {
|
||||
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
|
||||
assert!(INSTRUCTIONS_READ_ONLY.len() <= 300, "{}", INSTRUCTIONS_READ_ONLY.len());
|
||||
fn the_instructions_stay_under_budget() {
|
||||
assert!(INSTRUCTIONS.len() <= 440, "{}", INSTRUCTIONS.len());
|
||||
assert!(INSTRUCTIONS_READ_ONLY.len() <= 330, "{}", INSTRUCTIONS_READ_ONLY.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -33,7 +33,7 @@ const CAP: usize = 200;
|
||||
|
||||
pub const CHECK: Tool = Tool {
|
||||
name: "check",
|
||||
description: "Parse errors and lint findings of `file` or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
|
||||
description: "Parse errors and lint findings of `file` (path, directory or glob) or the whole design, one per line (file:line:col severity message [rule]), errors first; `ok` when clean.",
|
||||
params: &[Param { name: "file", ty: Ty::Str, required: false }],
|
||||
rewalk: false,
|
||||
handler: check,
|
||||
@@ -62,13 +62,7 @@ pub(super) struct Run {
|
||||
fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let mut runs = Runs::new();
|
||||
let mut findings = match args.str("file") {
|
||||
Some(file) => {
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let own = project.index().file_id(&path);
|
||||
let oracle = Mentions::of_file(project.index(), own);
|
||||
file_findings(project, &mut runs, &path, &analysis, &oracle)?
|
||||
}
|
||||
Some(raw) => check_target(project, &mut runs, raw.trim())?,
|
||||
None => project_findings(project, &mut runs)?,
|
||||
};
|
||||
if findings.is_empty() {
|
||||
@@ -80,6 +74,56 @@ fn check(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
Ok(Answer::lines(render::capped(lines, CAP)))
|
||||
}
|
||||
|
||||
fn check_target(
|
||||
project: &mut Project,
|
||||
runs: &mut Runs,
|
||||
spec: &str,
|
||||
) -> Result<Vec<Finding>, String> {
|
||||
if spec.is_empty() {
|
||||
return Err("`file` is empty.".into());
|
||||
}
|
||||
if !spec.contains(['*', '?']) {
|
||||
let path = project.resolve_existing(spec)?;
|
||||
if path.is_file() {
|
||||
let analysis = project.analysis(&path)?;
|
||||
let own = project.index().file_id(&path);
|
||||
let oracle = Mentions::of_file(project.index(), own);
|
||||
return file_findings(project, runs, &path, &analysis, &oracle);
|
||||
}
|
||||
let select = |project: &Project| -> Vec<PathBuf> {
|
||||
project.files().map(|(p, _)| p).filter(|p| p.starts_with(&path)).cloned().collect()
|
||||
};
|
||||
let paths = match_with_rewalk(project, select, spec)?;
|
||||
return lint_paths(project, runs, &paths, false);
|
||||
}
|
||||
let pattern = super::glob::normalize_glob(project.roots(), spec)?;
|
||||
let select = |project: &Project| -> Vec<PathBuf> {
|
||||
project
|
||||
.files()
|
||||
.map(|(p, _)| p)
|
||||
.filter(|p| super::glob::path_match(&pattern, &project.relative(p)))
|
||||
.cloned()
|
||||
.collect()
|
||||
};
|
||||
let paths = match_with_rewalk(project, select, spec)?;
|
||||
lint_paths(project, runs, &paths, false)
|
||||
}
|
||||
|
||||
fn match_with_rewalk(
|
||||
project: &mut Project,
|
||||
select: impl Fn(&Project) -> Vec<PathBuf>,
|
||||
spec: &str,
|
||||
) -> Result<Vec<PathBuf>, String> {
|
||||
let mut found = select(project);
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
found = select(project);
|
||||
}
|
||||
if found.is_empty() {
|
||||
return Err(format!("no indexed file matches `{spec}`."));
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
fn severity_rank(severity: &str) -> u8 {
|
||||
match severity {
|
||||
"error" => 0,
|
||||
@@ -99,18 +143,29 @@ impl Finding {
|
||||
|
||||
/// Every indexed file's findings, and the external waivers nothing used.
|
||||
fn project_findings(project: &Project, runs: &mut Runs) -> Result<Vec<Finding>, String> {
|
||||
let census = Census::of(project.index());
|
||||
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
|
||||
lint_paths(project, runs, &paths, true)
|
||||
}
|
||||
|
||||
fn lint_paths(
|
||||
project: &Project,
|
||||
runs: &mut Runs,
|
||||
paths: &[PathBuf],
|
||||
complete: bool,
|
||||
) -> Result<Vec<Finding>, String> {
|
||||
let census = Census::of(project.index());
|
||||
let mut findings = Vec::new();
|
||||
for path in &paths {
|
||||
for path in paths {
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
let analysis = Analysis::of(text);
|
||||
let own = project.index().file_id(path);
|
||||
let oracle = Mentions { index: project.index(), census: Some(&census), own };
|
||||
findings.extend(file_findings(project, runs, path, &analysis, &oracle)?);
|
||||
}
|
||||
// Only a complete run knows a waiver matched nothing.
|
||||
findings.extend(runs.unused_waivers(project));
|
||||
if complete {
|
||||
// Only a complete run knows a waiver matched nothing.
|
||||
findings.extend(runs.unused_waivers(project));
|
||||
}
|
||||
Ok(findings)
|
||||
}
|
||||
|
||||
|
||||
@@ -46,8 +46,16 @@ fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
return Ok(Answer::lines(vec!["renamed 0 sites in 0 files".to_string()]));
|
||||
}
|
||||
let set = whole_set(project, Some(&path), std::slice::from_ref(&name))?;
|
||||
let edit = vlog_refactor::rename(&set.files, &path, declaration.offset, new_name)
|
||||
.map_err(|why| set.rooted(&why))?;
|
||||
let mut trace = vlog_refactor::RenameTrace::default();
|
||||
let edit = vlog_refactor::rename_traced_with(
|
||||
&set.files,
|
||||
&path,
|
||||
declaration.offset,
|
||||
new_name,
|
||||
project,
|
||||
&mut trace,
|
||||
)
|
||||
.map_err(|why| set.rooted(&why))?;
|
||||
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
|
||||
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
|
||||
// A member of a module is named bare only where it is declared or used;
|
||||
@@ -168,7 +176,7 @@ pub(super) fn write_telling(
|
||||
// `None` — list every mention — for a non-member, and for a member whose
|
||||
// home set is not known (an include the engine cannot resolve).
|
||||
let local = match told.member {
|
||||
true => vlog_refactor::home_set(&set.files, told.home, &edited),
|
||||
true => vlog_refactor::home_set_for(&set.files, told.home, told.unit, &edited),
|
||||
false => None,
|
||||
};
|
||||
let focus = Focus {
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
//! that never spells the name); then the name's unresolved mentions —
|
||||
//! strings, comments, macro text — that no engine resolved.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::LineIndex;
|
||||
@@ -48,7 +48,7 @@ fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
if found.is_empty() {
|
||||
return Err(names::no_declaration(project, name));
|
||||
}
|
||||
let name = names::qualified(name).1;
|
||||
let (qualified_unit, name) = names::qualified(name);
|
||||
if !args.flag("refs") {
|
||||
let lines = found.iter().map(|declaration| declaration.render(name)).collect();
|
||||
return Ok(Answer::lines(render::capped(lines, CAP)));
|
||||
@@ -56,15 +56,28 @@ fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
// The uses must be searched in every file, so one written since the last
|
||||
// walk is walked into first.
|
||||
project.ensure_walked_for_miss();
|
||||
Ok(Answer::lines(render::capped(with_uses(project, name, &found), CAP)))
|
||||
Ok(Answer::lines(render::capped(with_uses(project, qualified_unit, name, &found), CAP)))
|
||||
}
|
||||
|
||||
/// Each declaration's line followed by its uses, then the unresolved
|
||||
/// mentions of the name no engine accounted for.
|
||||
fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String> {
|
||||
fn with_uses(
|
||||
project: &Project,
|
||||
qualified_unit: Option<&str>,
|
||||
name: &str,
|
||||
found: &[Declaration],
|
||||
) -> Vec<String> {
|
||||
let set = WholeSet::read(project, None);
|
||||
let mut lines = Vec::new();
|
||||
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
|
||||
let queries: Vec<(&Path, u32)> = found
|
||||
.iter()
|
||||
.filter(|declaration| !declaration.is_macro())
|
||||
.take(REFS_CAP)
|
||||
.map(|declaration| (declaration.path.as_path(), declaration.offset))
|
||||
.collect();
|
||||
let mut batch =
|
||||
vlog_refactor::find_references_batch_with(&set.files, &queries, false, project).into_iter();
|
||||
let mut searched = 0;
|
||||
for declaration in found {
|
||||
lines.push(declaration.render(name));
|
||||
@@ -72,22 +85,17 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
|
||||
continue;
|
||||
}
|
||||
searched += 1;
|
||||
let hits = vlog_refactor::find_references(
|
||||
&set.files,
|
||||
&declaration.path,
|
||||
declaration.offset,
|
||||
false,
|
||||
);
|
||||
match hits {
|
||||
Ok(hits) => {
|
||||
match batch.next() {
|
||||
Some(Ok(hits)) => {
|
||||
lines
|
||||
.extend(uses(project, &set, &hits).into_iter().map(|line| format!(" {line}")));
|
||||
account(&mut accounted, hits);
|
||||
}
|
||||
Err(why) => {
|
||||
Some(Err(why)) => {
|
||||
let why = engine_refusal(&set.rooted(&why));
|
||||
lines.push(format!(" uses not listed: {why}"));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
let followed = found.iter().filter(|declaration| !declaration.is_macro()).count();
|
||||
@@ -95,14 +103,15 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
|
||||
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
|
||||
}
|
||||
let home = &found[0].path;
|
||||
let local = member_files(&set, found, &accounted);
|
||||
let member = member_scope(&set, found, &accounted);
|
||||
let unit = qualified_unit.or(member.unit.as_deref());
|
||||
let focus = Focus {
|
||||
name,
|
||||
home,
|
||||
unit: None,
|
||||
unit,
|
||||
accounted: &accounted,
|
||||
named: &[],
|
||||
local: local.as_deref(),
|
||||
local: member.local.as_deref(),
|
||||
};
|
||||
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
|
||||
lines.extend(mentions::find(project, files, &focus).block());
|
||||
@@ -110,29 +119,48 @@ fn with_uses(project: &Project, name: &str, found: &[Declaration]) -> Vec<String
|
||||
lines
|
||||
}
|
||||
|
||||
struct MemberScope {
|
||||
local: Option<Vec<PathBuf>>,
|
||||
unit: Option<String>,
|
||||
}
|
||||
|
||||
/// The files a bare mention of a **module member** can mean it in — each
|
||||
/// declaration's home set (`vlog_refactor::home_set`) with every file the
|
||||
/// engine found a use in — or `None` when
|
||||
/// any declaration is not a member (a unit, a package member, a macro), whose
|
||||
/// every mention is listed (§65.1, lead's inspection: a `state_q` found in forty
|
||||
/// modules is not news about this one).
|
||||
fn member_files(
|
||||
/// declaration's bind-aware home set (`vlog_refactor::home_sets_for`) with
|
||||
/// every file the engine found a use in — or `None` when any declaration is
|
||||
/// not a member (a unit, a package member, a macro). Also returns the enclosing
|
||||
/// unit name when all declarations share one.
|
||||
fn member_scope(
|
||||
set: &WholeSet,
|
||||
found: &[Declaration],
|
||||
accounted: &[(PathBuf, Vec<TextRange>)],
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
) -> MemberScope {
|
||||
if found.iter().any(Declaration::is_macro) {
|
||||
return None;
|
||||
return MemberScope { local: None, unit: None };
|
||||
}
|
||||
let hit_files: Vec<PathBuf> = accounted.iter().map(|(path, _)| path.clone()).collect();
|
||||
let mut local: Vec<PathBuf> = Vec::new();
|
||||
let mut targets: Vec<(&Path, String)> = Vec::with_capacity(found.len());
|
||||
for declaration in found {
|
||||
let text = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)?;
|
||||
let Some(text) = set.files.iter().find(|(p, _)| *p == declaration.path).map(|(_, t)| t)
|
||||
else {
|
||||
return MemberScope { local: None, unit: None };
|
||||
};
|
||||
let unit_itself = matches!(declaration.kind, "module" | "interface" | "program");
|
||||
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)?;
|
||||
local.extend(vlog_refactor::home_set(&set.files, &declaration.path, &hit_files)?);
|
||||
let Some(unit) =
|
||||
vlog_refactor::enclosing_module(text, declaration.offset).filter(|_| !unit_itself)
|
||||
else {
|
||||
return MemberScope { local: None, unit: None };
|
||||
};
|
||||
targets.push((declaration.path.as_path(), unit));
|
||||
}
|
||||
Some(local)
|
||||
let single_unit = targets
|
||||
.first()
|
||||
.map(|(_, u)| u)
|
||||
.filter(|u| targets.iter().all(|(_, other)| other == *u))
|
||||
.cloned();
|
||||
let home_targets: Vec<(&Path, Option<&str>)> =
|
||||
targets.iter().map(|(p, u)| (*p, Some(u.as_str()))).collect();
|
||||
let local = vlog_refactor::home_sets_for(&set.files, &home_targets, &hit_files);
|
||||
MemberScope { local, unit: single_unit }
|
||||
}
|
||||
|
||||
/// The engine's hits, one file per line: `file:12,40`.
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
//! path component, `**` for any run of components, and a bare directory
|
||||
//! for everything below it — the `.gitignore` / `rg -g` reading.
|
||||
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
/// Whether `name` matches a glob of `*` (any run) and `?` (one character).
|
||||
pub fn glob_match(pattern: &str, name: &str) -> bool {
|
||||
let pattern: Vec<char> = pattern.chars().collect();
|
||||
@@ -61,6 +63,72 @@ fn components_match(pattern: &[&str], path: &[&str]) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize a glob `spec` relative to `roots`, refusing paths that resolve
|
||||
/// outside every root (absolute outside roots or escaping via `..`).
|
||||
pub fn normalize_glob(roots: &[PathBuf], spec: &str) -> Result<String, String> {
|
||||
let given = Path::new(spec);
|
||||
if given.is_absolute() {
|
||||
for root in roots {
|
||||
if let Ok(rest) = given.strip_prefix(root) {
|
||||
return normalize_relative_glob(spec, rest);
|
||||
}
|
||||
if let Some(root_rel) = strip_canonical_prefix(given, root) {
|
||||
return normalize_relative_glob(spec, &root_rel);
|
||||
}
|
||||
}
|
||||
return Err(format!(
|
||||
"`{spec}` resolves outside every root; lucisv-mcp only reads inside its roots."
|
||||
));
|
||||
}
|
||||
normalize_relative_glob(spec, given)
|
||||
}
|
||||
|
||||
fn strip_canonical_prefix(given: &Path, root: &Path) -> Option<PathBuf> {
|
||||
let mut prefix = PathBuf::new();
|
||||
let mut iter = given.components();
|
||||
let mut rest = Vec::new();
|
||||
while let Some(comp) = iter.next() {
|
||||
let text = comp.as_os_str().to_string_lossy();
|
||||
if text.contains(['*', '?']) {
|
||||
rest.push(comp.as_os_str().to_os_string());
|
||||
rest.extend(iter.map(|c| c.as_os_str().to_os_string()));
|
||||
break;
|
||||
}
|
||||
prefix.push(comp.as_os_str());
|
||||
}
|
||||
let canon = std::fs::canonicalize(&prefix).ok()?;
|
||||
let rel = canon.strip_prefix(root).ok()?;
|
||||
let mut out = rel.to_path_buf();
|
||||
for tail in rest {
|
||||
out.push(tail);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn normalize_relative_glob(raw: &str, path: &Path) -> Result<String, String> {
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
for comp in path.components() {
|
||||
match comp {
|
||||
Component::CurDir => {}
|
||||
Component::ParentDir => {
|
||||
if parts.pop().is_none() {
|
||||
return Err(format!(
|
||||
"`{raw}` resolves outside every root; lucisv-mcp only reads inside its roots."
|
||||
));
|
||||
}
|
||||
}
|
||||
Component::Normal(s) => parts.push(s.to_string_lossy().into_owned()),
|
||||
Component::RootDir | Component::Prefix(_) => {}
|
||||
}
|
||||
}
|
||||
let joined = parts.join("/");
|
||||
if raw.ends_with('/') && !joined.is_empty() {
|
||||
Ok(format!("{joined}/"))
|
||||
} else {
|
||||
Ok(joined)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{glob_match, path_match};
|
||||
|
||||
@@ -89,8 +89,18 @@ pub fn check(
|
||||
census.add(|| format!("{file} (skipped: {why}) may reference `{name}`"));
|
||||
}
|
||||
let scan = Scan { project, set: &set, path, analysis, place };
|
||||
let queries: Vec<(&Path, u32)> = symbols
|
||||
.iter()
|
||||
.filter(|symbol| {
|
||||
within(symbol.name_span, place.removed)
|
||||
&& mentioned(&set, path, place.removed, &symbol.name)
|
||||
})
|
||||
.map(|symbol| (path, symbol.name_span.start))
|
||||
.collect();
|
||||
let mut batch =
|
||||
vlog_refactor::find_references_batch_with(&set.files, &queries, false, project).into_iter();
|
||||
for symbol in symbols {
|
||||
scan.uses_of(symbol, &mut census);
|
||||
scan.uses_of(symbol, &mut batch, &mut census);
|
||||
}
|
||||
if census.total > 0 {
|
||||
return Err(format!("still referenced: {}; nothing written.", census.render()));
|
||||
@@ -113,7 +123,12 @@ type Accounted = Vec<(PathBuf, TextRange)>;
|
||||
|
||||
impl Scan<'_> {
|
||||
/// Count the uses of one owned declaration that the deletion would leave.
|
||||
fn uses_of(&self, symbol: &Symbol, census: &mut Census) {
|
||||
fn uses_of(
|
||||
&self,
|
||||
symbol: &Symbol,
|
||||
batch: &mut impl Iterator<Item = Result<Vec<(PathBuf, TextRange)>, String>>,
|
||||
census: &mut Census,
|
||||
) {
|
||||
let (name, removed) = (&symbol.name, self.place.removed);
|
||||
if !within(symbol.name_span, removed) {
|
||||
let line = self.analysis.lines.line_col(symbol.name_span.start).0;
|
||||
@@ -126,12 +141,26 @@ impl Scan<'_> {
|
||||
if !mentioned(self.set, self.path, removed, name) {
|
||||
return;
|
||||
}
|
||||
let accounted = self.references(symbol, census);
|
||||
let found = batch.next().unwrap_or_else(|| {
|
||||
vlog_refactor::find_references_with(
|
||||
&self.set.files,
|
||||
self.path,
|
||||
symbol.name_span.start,
|
||||
false,
|
||||
self.project,
|
||||
)
|
||||
});
|
||||
let accounted = self.references(symbol, found, census);
|
||||
self.macros(name, &accounted, census);
|
||||
}
|
||||
|
||||
/// The engine's and the file's own uses, counted; what they account for.
|
||||
fn references(&self, symbol: &Symbol, census: &mut Census) -> Accounted {
|
||||
fn references(
|
||||
&self,
|
||||
symbol: &Symbol,
|
||||
found: Result<Vec<(PathBuf, TextRange)>, String>,
|
||||
census: &mut Census,
|
||||
) -> Accounted {
|
||||
let (name, removed) = (&symbol.name, self.place.removed);
|
||||
let mut uses = local_uses(self.analysis, symbol, removed);
|
||||
let mut accounted: Accounted = self
|
||||
@@ -142,12 +171,6 @@ impl Scan<'_> {
|
||||
.filter(|use_| use_.name == *name)
|
||||
.map(|use_| (self.path.to_path_buf(), use_.name_span))
|
||||
.collect();
|
||||
let found = vlog_refactor::find_references(
|
||||
&self.set.files,
|
||||
self.path,
|
||||
symbol.name_span.start,
|
||||
false,
|
||||
);
|
||||
match found {
|
||||
Ok(hits) => {
|
||||
for (file, span) in hits {
|
||||
|
||||
@@ -108,9 +108,7 @@ pub fn find<'t>(
|
||||
let mut last_line = 0;
|
||||
let foreign = focus.local.is_some_and(|local| !local.iter().any(|p| p == path));
|
||||
for (at, _) in spellings(text, focus.name) {
|
||||
if foreign
|
||||
&& !text.as_bytes().get((at as usize).wrapping_sub(1)).is_some_and(|&b| b == b'.')
|
||||
{
|
||||
if foreign && !text.get(..at as usize).is_some_and(vlog_refactor::after_dot) {
|
||||
continue;
|
||||
}
|
||||
let end = at + focus.name.len() as u32;
|
||||
@@ -346,6 +344,16 @@ mod tests {
|
||||
let (a, b) = (Path::new("/hw/ip/es/rtl/a.sv"), Path::new("/hw/ip/es/dv/b.sv"));
|
||||
assert_eq!(shared_components(a, b), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn foreign_files_recognize_dotted_mentions_past_blanks_comments_and_paste() {
|
||||
assert!(vlog_refactor::after_dot("u_m."));
|
||||
assert!(vlog_refactor::after_dot("u_m . "));
|
||||
assert!(vlog_refactor::after_dot("u_m. /* c */ "));
|
||||
assert!(vlog_refactor::after_dot("u_m.``"));
|
||||
assert!(!vlog_refactor::after_dot("/* u_m. */ "));
|
||||
assert!(!vlog_refactor::after_dot("u_m "));
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -131,13 +131,21 @@ fn copy_tree(from: &Path, to: &Path) {
|
||||
/// Every entry under a tree, root-relative: a file's bytes and mode, a
|
||||
/// symlink's target, a directory's mode. Anything moving shows up.
|
||||
fn snapshot(root: &Path) -> BTreeMap<String, (u32, Vec<u8>)> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
#[cfg(unix)]
|
||||
fn mode_bits(meta: &fs::Metadata) -> u32 {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
fn mode_bits(meta: &fs::Metadata) -> u32 {
|
||||
u32::from(meta.permissions().readonly())
|
||||
}
|
||||
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, (u32, Vec<u8>)>) {
|
||||
for entry in fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
let relative = path.strip_prefix(root).unwrap().to_string_lossy().into_owned();
|
||||
let meta = fs::symlink_metadata(&path).unwrap();
|
||||
let mode = meta.permissions().mode();
|
||||
let mode = mode_bits(&meta);
|
||||
if meta.file_type().is_symlink() {
|
||||
let target = fs::read_link(&path).unwrap();
|
||||
out.insert(relative, (mode, target.to_string_lossy().as_bytes().to_vec()));
|
||||
@@ -345,6 +353,7 @@ fn qa_commit_is_byte_based_a_rewrite_with_the_same_bytes_still_lands() {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory() {
|
||||
let scratch = Scratch::empty();
|
||||
@@ -369,6 +378,7 @@ fn qa_commit_refuses_a_created_path_taken_by_a_dangling_symlink_or_a_directory()
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_commit_refuses_a_read_only_last_file_before_writing_the_first() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -483,6 +493,7 @@ fn qa_every_edit_writes_only_what_it_says_and_a_repeat_writes_nothing() {
|
||||
|
||||
/// A refusal from every tool — engine refusals, argument refusals, path
|
||||
/// refusals — and not one byte or mode bit of the tree moves.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
@@ -630,6 +641,7 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
|
||||
|
||||
// ================================================ paths (attack 3)
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_rewritten_paths_never_leave_the_root() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
@@ -650,6 +662,7 @@ fn qa_rewritten_paths_never_leave_the_root() {
|
||||
assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_a_read_only_target_refuses_before_the_first_write() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
@@ -671,6 +684,7 @@ fn qa_a_read_only_target_refuses_before_the_first_write() {
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_formatting_through_a_symlink_writes_the_file_and_keeps_the_link() {
|
||||
let scratch = Scratch::with(&[("real.sv", "module r(input logic a);\nendmodule\n")]);
|
||||
@@ -1218,6 +1232,7 @@ fn qa_an_edit_sees_a_file_created_just_before_it() {
|
||||
|
||||
/// Finding 7 (non-blocking): an over-1 MiB file reached through a symlink
|
||||
/// leading out of the root is not in the skipped set.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
|
||||
@@ -26,8 +26,8 @@ const FIVE: [&str; 5] = ["hierarchy", "find", "outline", "read", "check"];
|
||||
const EDITS: [&str; 4] = ["rename", "port", "edit_item", "format"];
|
||||
|
||||
/// The read-only ceilings (PLAN §11.1).
|
||||
const CATALOGUE_BUDGET: usize = 1_800;
|
||||
const INSTRUCTIONS_BUDGET: usize = 300;
|
||||
const CATALOGUE_BUDGET: usize = 2_000;
|
||||
const INSTRUCTIONS_BUDGET: usize = 330;
|
||||
|
||||
/// The instructions 0.58.0 shipped (PLAN §10.3), which full mode keeps.
|
||||
const FULL_INSTRUCTIONS: &str = "lucisv-mcp reads the SystemVerilog on disk (save first). Use it before reading files: hierarchy for instance trees and top modules, find for a name's declarations and uses, outline for a file or unit's ports, read for one item, check after edits. Edits (rename, port, edit_item, format) are verified, all-or-nothing writes: trust them as file writes, no dry run. Paths root-relative, lines 1-based.";
|
||||
|
||||
@@ -174,8 +174,8 @@ const NINE: [&str; 9] =
|
||||
["hierarchy", "find", "outline", "read", "check", "rename", "port", "edit_item", "format"];
|
||||
|
||||
/// The model-visible catalogue's ceiling and the instructions' (PLAN §10.5).
|
||||
const CATALOGUE_BUDGET: usize = 3_500;
|
||||
const INSTRUCTIONS_BUDGET: usize = 400;
|
||||
const CATALOGUE_BUDGET: usize = 3_800;
|
||||
const INSTRUCTIONS_BUDGET: usize = 440;
|
||||
|
||||
#[test]
|
||||
fn the_handshake_negotiates_and_describes_the_server() {
|
||||
@@ -186,7 +186,7 @@ fn the_handshake_negotiates_and_describes_the_server() {
|
||||
assert_eq!(result["protocolVersion"], "2025-06-18");
|
||||
assert_eq!(result["serverInfo"]["name"], "lucisv-mcp");
|
||||
assert_eq!(result["serverInfo"]["version"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}, "prompts": {}}));
|
||||
assert_eq!(result["capabilities"], json!({"tools": {}, "resources": {}}));
|
||||
// The `initialized` notification drew no answer: the next line is ping's.
|
||||
assert_eq!(server.request("ping", json!({}))["result"], json!({}));
|
||||
let newest = server.request("initialize", json!({"protocolVersion": "1999-01-01"}));
|
||||
@@ -1267,4 +1267,141 @@ fn a_stale_temp_store_is_swept_and_a_young_one_and_other_files_are_spared() {
|
||||
assert!(other.exists(), "only `<store>.<pid>.tmp` is ours to sweep");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_supports_directories_and_globs_and_refuses_bad_targets() {
|
||||
let (tree, mut server) = served("nav");
|
||||
fs::create_dir_all(tree.path("empty_dir")).unwrap();
|
||||
|
||||
// Directory target lints only indexed files under that directory (no unused-waiver).
|
||||
let rtl_all = server.text("check", json!({"file": "rtl"}));
|
||||
assert_eq!(rtl_all, server.text("check", json!({"file": "./rtl/"})));
|
||||
assert!(rtl_all.contains("rtl/core.sv:10:17 warning"), "{rtl_all}");
|
||||
assert!(rtl_all.contains("rtl/checker_m.sv:1:41 style"), "{rtl_all}");
|
||||
assert!(!rtl_all.contains("waiver"), "subset checks omit whole-design waivers: {rtl_all}");
|
||||
|
||||
// `.` matches the root tree as a directory.
|
||||
assert_eq!(server.text("check", json!({"file": "."})), rtl_all);
|
||||
|
||||
// Glob targets select matching indexed files only.
|
||||
assert_eq!(
|
||||
server.text("check", json!({"file": "rtl/checker_*.sv"})),
|
||||
"rtl/checker_m.sv:1:41 style line is 45 characters; the limit is 40 [line-length]\n"
|
||||
);
|
||||
assert_eq!(server.text("check", json!({"file": "rtl/tree*.sv"})), "ok\n");
|
||||
|
||||
// Empty, missing, empty-directory, and outside-root paths/globs refuse.
|
||||
assert!(refusal(&mut server, "check", json!({"file": ""})).contains("empty"));
|
||||
assert!(
|
||||
refusal(&mut server, "check", json!({"file": "missing_dir"})).contains("does not exist")
|
||||
);
|
||||
assert!(refusal(&mut server, "check", json!({"file": "empty_dir"})).contains("no indexed file"));
|
||||
assert!(
|
||||
refusal(&mut server, "check", json!({"file": "rtl/*.none"})).contains("no indexed file")
|
||||
);
|
||||
let sibling = Tree::new();
|
||||
let sibling_arg = format!("../{}", sibling.0.file_name().unwrap().to_str().unwrap());
|
||||
assert!(refusal(&mut server, "check", json!({"file": ".."})).contains("outside every root"));
|
||||
assert!(
|
||||
refusal(&mut server, "check", json!({"file": sibling_arg})).contains("outside every root")
|
||||
);
|
||||
assert!(refusal(&mut server, "check", json!({"file": "../../etc/*.sv"}))
|
||||
.contains("outside every root"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_and_rename_share_dotted_mentions_bind_home_set_and_qualified_focus() {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let root = std::env::temp_dir().join(format!("lucisv-mcp-l9-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
let tree = Tree(fs::canonicalize(&root).unwrap());
|
||||
for (rel, body) in [
|
||||
(
|
||||
"rtl/alpha.sv",
|
||||
"module alpha;\n logic state_q;\n assign state_q = 1'b0;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"rtl/beta.sv",
|
||||
"module beta;\n logic state_q;\n // bare state_q inside unrelated beta\nendmodule\n",
|
||||
),
|
||||
("rtl/defs.svh", "`define BIND_ALPHA bind alpha chk u_chk ();\n"),
|
||||
(
|
||||
"rtl/bind_alpha.sv",
|
||||
"`include \"defs.svh\"\n`BIND_ALPHA\n// bare state_q inside binder\nmodule chk; endmodule\n",
|
||||
),
|
||||
(
|
||||
"dv/aa_other.sv",
|
||||
"module aa_other;\n // u_beta . state_q\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"dv/probe.sv",
|
||||
"module probe;\n // u_alpha . state_q\n // u_alpha./*c*/state_q\n // `HIER.u_alpha.``state_q\n // bare state_q in dv ignored\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"dv/zz_alpha.sv",
|
||||
"module zz_alpha;\n // `HIER.u_alpha.state_q\nendmodule\n",
|
||||
),
|
||||
] {
|
||||
let p = tree.path(rel);
|
||||
fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
fs::write(&p, body).unwrap();
|
||||
}
|
||||
let mut server = Session::over(&tree);
|
||||
server.initialize();
|
||||
|
||||
let found = server.text("find", json!({"name": "alpha.state_q", "refs": true}));
|
||||
assert!(found.starts_with("var state_q rtl/alpha.sv:2\n rtl/alpha.sv:3\n"), "{found}");
|
||||
assert!(!found.contains("rtl/beta.sv"), "unrelated unit excluded: {found}");
|
||||
assert!(found.contains("rtl/bind_alpha.sv:3"), "K2 macro binder included: {found}");
|
||||
assert!(
|
||||
found.contains("dv/probe.sv:2,3,4\n") && !found.contains("dv/probe.sv:2,3,4,5"),
|
||||
"L-9 dotted mentions (blanks/comments/paste) included, bare in foreign excluded: {found}"
|
||||
);
|
||||
// Focus::unit = Some("alpha") ranks lines naming `alpha` above `dv/aa_other.sv`.
|
||||
let alpha_pos = found.find("dv/zz_alpha.sv:2").unwrap();
|
||||
let other_pos = found.find("dv/aa_other.sv:2").unwrap();
|
||||
assert!(alpha_pos < other_pos, "unit focus should rank alpha lines first:\n{found}");
|
||||
|
||||
// `rename` reports the exact same bind-aware home set and dotted mentions.
|
||||
let renamed = server
|
||||
.text("rename", json!({"name": "state_q", "file": "rtl/alpha.sv", "new_name": "next_q"}));
|
||||
assert!(renamed.contains("rtl/bind_alpha.sv:3"), "{renamed}");
|
||||
assert!(renamed.contains("dv/probe.sv:2,3,4"), "{renamed}");
|
||||
assert!(!renamed.contains("rtl/beta.sv"), "{renamed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cached_known_facts_invalidate_when_disk_changes_between_calls() {
|
||||
let (tree, mut server) = served("nav");
|
||||
let orig_top = fs::read_to_string(tree.path("rtl/top.sv")).unwrap();
|
||||
let before = server.text("find", json!({"name": "state_q", "refs": true}));
|
||||
assert!(!before.contains("rtl/new_user.sv"), "{before}");
|
||||
|
||||
// Add a hierarchical reference to `core.state_q` on disk between calls.
|
||||
fs::write(
|
||||
tree.path("rtl/top.sv"),
|
||||
format!("{orig_top}\n// extra\nmodule extra;\n logic peek;\n assign peek = core.state_q;\nendmodule\n"),
|
||||
)
|
||||
.unwrap();
|
||||
let after = server.text("find", json!({"name": "state_q", "refs": true}));
|
||||
assert!(after.contains("rtl/top.sv:8,14"), "{after}");
|
||||
|
||||
// Revert `rtl/top.sv` and verify cached facts invalidate back cleanly.
|
||||
fs::write(tree.path("rtl/top.sv"), &orig_top).unwrap();
|
||||
let reverted = server.text("find", json!({"name": "state_q", "refs": true}));
|
||||
assert!(
|
||||
reverted.contains("rtl/top.sv:8\n") && !reverted.contains("rtl/top.sv:8,14"),
|
||||
"{reverted}"
|
||||
);
|
||||
|
||||
// Add a new file referencing `core.state_q` and verify lazy rewalk + KnownFacts stays fresh.
|
||||
fs::write(
|
||||
tree.path("rtl/new_user.sv"),
|
||||
"module new_user;\n logic peek;\n assign peek = core.state_q;\nendmodule\n",
|
||||
)
|
||||
.unwrap();
|
||||
let added = server.text("find", json!({"name": "state_q", "refs": true}));
|
||||
assert!(added.contains("rtl/new_user.sv:3"), "{added}");
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -48,7 +48,9 @@ pub use imports::{
|
||||
organize_offer_in, organize_title, unused_imports,
|
||||
};
|
||||
pub use inline::{inline_module, inline_site, inline_site_in, inline_title, InlineSite};
|
||||
pub use references::find_references;
|
||||
pub use references::{
|
||||
find_references, find_references_batch, find_references_batch_with, find_references_with,
|
||||
};
|
||||
|
||||
pub use instantiate::{
|
||||
instantiation_plan, module_definition, module_names, InstantiationPlan, Layout, PlanParam,
|
||||
@@ -61,11 +63,18 @@ pub use ports::{
|
||||
PortOfferKind,
|
||||
};
|
||||
pub use rename::{
|
||||
contains_word, home_set, prepare_rename, prepare_rename_here, rename, rename_name_at,
|
||||
rename_preflight, rename_traced, rename_traced_with, KnownFacts, RenameTarget,
|
||||
contains_word, home_set, home_set_for, home_sets_for, prepare_rename, prepare_rename_here,
|
||||
rename, rename_name_at, rename_preflight, rename_traced, rename_traced_with, KnownFacts,
|
||||
RenameTarget,
|
||||
};
|
||||
pub use trace::{IndexTrace, RenameTrace, Stage, VerifyTrace, WarnTrace};
|
||||
|
||||
/// Whether `before` ends in a `.` that precedes a dotted mention (past
|
||||
/// blanks, `` `` `` pastes, and `/* ... */` block comments).
|
||||
pub fn after_dot(before: &str) -> bool {
|
||||
rename::after_dot(before)
|
||||
}
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
@@ -13,7 +13,8 @@ use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use crate::rename::Scope;
|
||||
use crate::rename::{rename_name_at, Scope};
|
||||
use crate::{IndexTrace, KnownFacts};
|
||||
|
||||
/// Every occurrence of the symbol at `offset` in `file`, across `files`.
|
||||
///
|
||||
@@ -32,7 +33,125 @@ pub fn find_references(
|
||||
offset: u32,
|
||||
include_declaration: bool,
|
||||
) -> Result<Vec<(PathBuf, TextRange)>, String> {
|
||||
let mut scope = Scope::build(files);
|
||||
collect_single(files, file, offset, include_declaration, None)
|
||||
}
|
||||
|
||||
/// [`find_references`], letting the caller answer for the index records of the
|
||||
/// files it is handing over — see [`KnownFacts`].
|
||||
pub fn find_references_with(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
include_declaration: bool,
|
||||
known: &dyn KnownFacts,
|
||||
) -> Result<Vec<(PathBuf, TextRange)>, String> {
|
||||
collect_single(files, file, offset, include_declaration, Some(known))
|
||||
}
|
||||
|
||||
/// Every occurrence for each `(file, offset)` query, reusing one [`Scope`]
|
||||
/// build across the batch.
|
||||
pub fn find_references_batch(
|
||||
files: &[(PathBuf, String)],
|
||||
queries: &[(&Path, u32)],
|
||||
include_declaration: bool,
|
||||
) -> Vec<Result<Vec<(PathBuf, TextRange)>, String>> {
|
||||
collect_batch(files, queries, include_declaration, None)
|
||||
}
|
||||
|
||||
/// [`find_references_batch`], letting the caller answer for the index records
|
||||
/// of the files it is handing over — see [`KnownFacts`].
|
||||
pub fn find_references_batch_with(
|
||||
files: &[(PathBuf, String)],
|
||||
queries: &[(&Path, u32)],
|
||||
include_declaration: bool,
|
||||
known: &dyn KnownFacts,
|
||||
) -> Vec<Result<Vec<(PathBuf, TextRange)>, String>> {
|
||||
collect_batch(files, queries, include_declaration, Some(known))
|
||||
}
|
||||
|
||||
fn collect_single(
|
||||
files: &[(PathBuf, String)],
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
include_declaration: bool,
|
||||
known: Option<&dyn KnownFacts>,
|
||||
) -> Result<Vec<(PathBuf, TextRange)>, String> {
|
||||
let mut scope = build_scope(files, file, &[(file, offset)], known);
|
||||
collect_one(&mut scope, file, offset, include_declaration)
|
||||
}
|
||||
|
||||
fn collect_batch(
|
||||
files: &[(PathBuf, String)],
|
||||
queries: &[(&Path, u32)],
|
||||
include_declaration: bool,
|
||||
known: Option<&dyn KnownFacts>,
|
||||
) -> Vec<Result<Vec<(PathBuf, TextRange)>, String>> {
|
||||
let Some(&(lead, _)) = queries.first() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut scope = build_scope(files, lead, queries, known);
|
||||
queries
|
||||
.iter()
|
||||
.map(|&(file, offset)| collect_one(&mut scope, file, offset, include_declaration))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn build_scope<'a>(
|
||||
files: &'a [(PathBuf, String)],
|
||||
lead: &Path,
|
||||
queries: &[(&Path, u32)],
|
||||
known: Option<&dyn KnownFacts>,
|
||||
) -> Scope<'a> {
|
||||
let mut trace = IndexTrace::default();
|
||||
Scope::build_keeping(
|
||||
files,
|
||||
lead,
|
||||
|here| {
|
||||
let mut words: Vec<String> = Vec::new();
|
||||
for &(file, offset) in queries {
|
||||
let word = if file == lead {
|
||||
here.and_then(|semantics| rename_name_at(semantics, offset))
|
||||
} else {
|
||||
word_in_files(files, file, offset)
|
||||
};
|
||||
if let Some(word) = word {
|
||||
if !words.contains(&word) {
|
||||
words.push(word);
|
||||
}
|
||||
}
|
||||
}
|
||||
words
|
||||
},
|
||||
known,
|
||||
&mut trace,
|
||||
)
|
||||
}
|
||||
|
||||
fn word_in_files(files: &[(PathBuf, String)], file: &Path, offset: u32) -> Option<String> {
|
||||
let (_, text) = files.iter().find(|(path, _)| path.as_path() == file)?;
|
||||
let is_ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
|
||||
let bytes = text.as_bytes();
|
||||
let at = usize::try_from(offset).ok()?;
|
||||
if !bytes.get(at).is_some_and(|&b| is_ident(b)) {
|
||||
return None;
|
||||
}
|
||||
let mut start = at;
|
||||
while start > 0 && bytes.get(start - 1).is_some_and(|&b| is_ident(b)) {
|
||||
start -= 1;
|
||||
}
|
||||
let mut end = at + 1;
|
||||
while bytes.get(end).is_some_and(|&b| is_ident(b)) {
|
||||
end += 1;
|
||||
}
|
||||
text.get(start..end).map(str::to_string)
|
||||
}
|
||||
|
||||
fn collect_one(
|
||||
scope: &mut Scope<'_>,
|
||||
file: &Path,
|
||||
offset: u32,
|
||||
include_declaration: bool,
|
||||
) -> Result<Vec<(PathBuf, TextRange)>, String> {
|
||||
let target = scope.locate(file, offset)?;
|
||||
let declaration = scope.declaration_span(&target);
|
||||
let found = scope.collect_occurrences(&target)?;
|
||||
@@ -181,6 +300,69 @@ mod tests {
|
||||
let files = files();
|
||||
assert!(find_references(&files, Path::new("/w/sub.sv"), 0, true).is_err(), "the keyword");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_facts_and_batch_match_plain_find_references_and_skip_unrelated_parses() {
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
let sub = "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n";
|
||||
let top = "module top;\n sub u_a (.clk(1'b0), .q());\nendmodule\n";
|
||||
let unrelated = "module unrelated;\n wire other;\n assign other = 1'b0;\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from("/w/sub.sv"), sub.to_string()),
|
||||
(PathBuf::from("/w/top.sv"), top.to_string()),
|
||||
(PathBuf::from("/w/unrelated.sv"), unrelated.to_string()),
|
||||
];
|
||||
|
||||
struct Cached<'a> {
|
||||
by_path: HashMap<&'a Path, (&'a str, FileFacts)>,
|
||||
queries: Cell<usize>,
|
||||
}
|
||||
impl KnownFacts for Cached<'_> {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
self.queries.set(self.queries.get() + 1);
|
||||
self.by_path
|
||||
.get(path)
|
||||
.filter(|(held, _)| *held == text)
|
||||
.map(|(_, facts)| facts.clone())
|
||||
}
|
||||
}
|
||||
|
||||
let cached = Cached {
|
||||
by_path: files
|
||||
.iter()
|
||||
.map(|(p, t)| (p.as_path(), (t.as_str(), FileFacts::of(p.clone(), t))))
|
||||
.collect(),
|
||||
queries: Cell::new(0),
|
||||
};
|
||||
let sub_path = Path::new("/w/sub.sv");
|
||||
let queries =
|
||||
[(sub_path, at(sub, "clk")), (sub_path, at(sub, "wire sig") + 5), (sub_path, 0)];
|
||||
|
||||
let before = vlog_parser::stats::parses();
|
||||
let plain: Vec<_> =
|
||||
queries.iter().map(|&(p, o)| find_references(&files, p, o, false)).collect();
|
||||
let plain_parses = vlog_parser::stats::parses() - before;
|
||||
|
||||
let before_with = vlog_parser::stats::parses();
|
||||
let batch = find_references_batch_with(&files, &queries, false, &cached);
|
||||
let batch_parses = vlog_parser::stats::parses() - before_with;
|
||||
|
||||
assert_eq!(batch, plain);
|
||||
assert!(cached.queries.get() >= files.len());
|
||||
assert!(batch_parses < plain_parses, "{batch_parses} vs {plain_parses}");
|
||||
|
||||
// Single-query `_with` matches plain `find_references`, including when a
|
||||
// cached entry does not match disk text and returns `None`.
|
||||
let mut stale = files.clone();
|
||||
stale[1].1 = "module top;\n sub u_b (.clk(1'b1), .q());\nendmodule\n".to_string();
|
||||
assert_eq!(
|
||||
find_references_with(&stale, sub_path, at(sub, "clk"), false, &cached),
|
||||
find_references(&stale, sub_path, at(sub, "clk"), false)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -28,17 +28,69 @@ pub fn home_set(
|
||||
files: &[(PathBuf, String)],
|
||||
declaring: &Path,
|
||||
edited: &[PathBuf],
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
home_set_for(files, declaring, None, edited)
|
||||
}
|
||||
|
||||
/// [`home_set`], also including files that `bind` into `unit` (directly or
|
||||
/// through a macro expansion, matching the engine's K2 home set).
|
||||
pub fn home_set_for(
|
||||
files: &[(PathBuf, String)],
|
||||
declaring: &Path,
|
||||
unit: Option<&str>,
|
||||
edited: &[PathBuf],
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
home_sets_for(files, &[(declaring, unit)], edited)
|
||||
}
|
||||
|
||||
/// Union of [`home_set_for`] across several `(declaring, unit)` targets over
|
||||
/// `files`, building the include graph and macro tables at most once.
|
||||
pub fn home_sets_for(
|
||||
files: &[(PathBuf, String)],
|
||||
targets: &[(&Path, Option<&str>)],
|
||||
edited: &[PathBuf],
|
||||
) -> Option<Vec<PathBuf>> {
|
||||
let sources: Vec<(&Path, &str)> =
|
||||
files.iter().map(|(p, t)| (p.as_path(), t.as_str())).collect();
|
||||
let at = sources.iter().position(|(p, _)| *p == declaring)?;
|
||||
let edited: Vec<usize> =
|
||||
edited.iter().filter_map(|e| sources.iter().position(|(p, _)| p == e)).collect();
|
||||
let home = home_of(&sources, at, &edited);
|
||||
if home.unknown {
|
||||
return None;
|
||||
let graph = Graph::of(&sources);
|
||||
let defs = targets
|
||||
.iter()
|
||||
.any(|(_, unit)| unit.is_some())
|
||||
.then(|| super::scoped::defs_from_sources(&sources));
|
||||
let bind_candidates: Vec<usize> = defs
|
||||
.as_ref()
|
||||
.map(|_| {
|
||||
sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|&(_, (_, text))| text.contains('`') || super::contains_word(text, "bind"))
|
||||
.map(|(i, _)| i)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut carriers_by_unit: HashMap<&str, super::carry::Carriers> = HashMap::new();
|
||||
let mut combined: BTreeSet<usize> = BTreeSet::new();
|
||||
for &(declaring, unit) in targets {
|
||||
let at = sources.iter().position(|(p, _)| *p == declaring)?;
|
||||
let home = home_with_graph(&graph, at, &edited);
|
||||
if home.unknown {
|
||||
return None;
|
||||
}
|
||||
combined.extend(home.all);
|
||||
if let (Some(unit), Some(defs)) = (unit, defs.as_ref()) {
|
||||
let carriers = carriers_by_unit
|
||||
.entry(unit)
|
||||
.or_insert_with(|| super::carry::Carriers::of(defs, unit));
|
||||
combined.extend(bind_candidates.iter().copied().filter(|&i| {
|
||||
sources
|
||||
.get(i)
|
||||
.is_some_and(|(_, text)| super::scoped::file_binds_into(text, unit, carriers))
|
||||
}));
|
||||
}
|
||||
}
|
||||
Some(home.all.into_iter().filter_map(|i| Some(sources.get(i)?.0.to_path_buf())).collect())
|
||||
Some(combined.into_iter().filter_map(|i| Some(sources.get(i)?.0.to_path_buf())).collect())
|
||||
}
|
||||
|
||||
/// A home set by source index, with which of its files are include-related to
|
||||
@@ -59,7 +111,10 @@ pub(crate) struct Home {
|
||||
|
||||
/// [`home_set`] over a scope's `(path, text)` sources.
|
||||
pub(crate) fn home_of(sources: &[(&Path, &str)], declaring: usize, edited: &[usize]) -> Home {
|
||||
let graph = Graph::of(sources);
|
||||
home_with_graph(&Graph::of(sources), declaring, edited)
|
||||
}
|
||||
|
||||
fn home_with_graph(graph: &Graph, declaring: usize, edited: &[usize]) -> Home {
|
||||
let included = graph.down(&[declaring], &BTreeSet::from([declaring]));
|
||||
let mut up: BTreeSet<usize> = BTreeSet::new();
|
||||
let mut todo = vec![declaring];
|
||||
@@ -374,6 +429,30 @@ mod tests {
|
||||
let invoked = invoked_from(&[" `A\n"], &defs);
|
||||
assert!(invoked.contains("A") && invoked.contains("B"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_set_for_unit_includes_direct_and_macro_binders_and_skips_others() {
|
||||
let files = vec![
|
||||
(PathBuf::from("/r/core.sv"), "module core; logic state_q; endmodule\n".to_string()),
|
||||
(PathBuf::from("/r/bind_direct.sv"), "bind core chk u_c();\n".to_string()),
|
||||
(PathBuf::from("/r/defs.svh"), "`define BIND_CORE bind core chk u_c();\n".to_string()),
|
||||
(PathBuf::from("/r/bind_macro.sv"), "`include \"defs.svh\"\n`BIND_CORE\n".to_string()),
|
||||
(PathBuf::from("/r/bind_other.sv"), "bind other chk u_c();\n".to_string()),
|
||||
(PathBuf::from("/r/unrelated.sv"), "module unrelated; endmodule\n".to_string()),
|
||||
];
|
||||
assert_eq!(
|
||||
home_set(&files, Path::new("/r/core.sv"), &[]),
|
||||
Some(vec![PathBuf::from("/r/core.sv")])
|
||||
);
|
||||
assert_eq!(
|
||||
home_set_for(&files, Path::new("/r/core.sv"), Some("core"), &[]),
|
||||
Some(vec![
|
||||
PathBuf::from("/r/core.sv"),
|
||||
PathBuf::from("/r/bind_direct.sv"),
|
||||
PathBuf::from("/r/bind_macro.sv"),
|
||||
])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -35,7 +35,7 @@ pub(crate) mod sites;
|
||||
mod tests;
|
||||
mod warnings;
|
||||
|
||||
pub use home::home_set;
|
||||
pub use home::{home_set, home_set_for, home_sets_for};
|
||||
pub use preflight::rename_preflight;
|
||||
|
||||
// The rename was the first refactoring, so most of the crate still spells the
|
||||
@@ -43,6 +43,7 @@ pub use preflight::rename_preflight;
|
||||
// and so does the door a caller hands its own index records through.
|
||||
pub use crate::scope::KnownFacts;
|
||||
pub(crate) use crate::scope::{display, Scope};
|
||||
pub(crate) use scoped::after_dot;
|
||||
pub use warnings::contains_word;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -186,23 +186,26 @@ impl Scoping {
|
||||
/// invokes are followed.
|
||||
fn files_binding_into(scope: &Scope, unit: &str, carriers: &Carriers) -> Vec<usize> {
|
||||
(0..scope.len())
|
||||
.filter(|&i| {
|
||||
let Some(text) = scope.text(i) else { return false };
|
||||
let invokes_binder = carriers.any_binder()
|
||||
&& text.contains('`')
|
||||
&& macro_names(text).iter().any(|m| carriers.binds(m));
|
||||
if invokes_binder {
|
||||
return true;
|
||||
}
|
||||
if !super::contains_word(text, "bind") {
|
||||
return false;
|
||||
}
|
||||
// A file that spells `bind` but does not lex is counted (L-4).
|
||||
vlog_parser::tokenize(text).map_or(true, |tokens| !binds_into(&tokens, unit).is_empty())
|
||||
})
|
||||
.filter(|&i| scope.text(i).is_some_and(|text| file_binds_into(text, unit, carriers)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether `text` contains a `bind` targeting `unit` (or an instance path), or
|
||||
/// invokes a macro in `carriers` expanding to one (K2).
|
||||
pub(super) fn file_binds_into(text: &str, unit: &str, carriers: &Carriers) -> bool {
|
||||
let invokes_binder = carriers.any_binder()
|
||||
&& text.contains('`')
|
||||
&& macro_names(text).iter().any(|m| carriers.binds(m));
|
||||
if invokes_binder {
|
||||
return true;
|
||||
}
|
||||
if !super::contains_word(text, "bind") {
|
||||
return false;
|
||||
}
|
||||
// A file that spells `bind` but does not lex is counted (L-4).
|
||||
vlog_parser::tokenize(text).map_or(true, |tokens| !binds_into(&tokens, unit).is_empty())
|
||||
}
|
||||
|
||||
impl<'a> Scope<'a> {
|
||||
/// H4: bare uses of the name in the plain code of a file the declaring
|
||||
/// file includes (or that includes it). That text is analysed on its own,
|
||||
@@ -309,6 +312,14 @@ pub(super) fn binds_into(tokens: &[Token], unit: &str) -> Vec<TextRange> {
|
||||
out
|
||||
}
|
||||
|
||||
fn push_defines(out: &mut Defs, defines: &vlog_parser::defines::DefineTable) {
|
||||
for define in defines.entries() {
|
||||
let params = define.params.clone().unwrap_or_default();
|
||||
let def = MacroDef { params, body: define.body.clone() };
|
||||
out.entry(define.name.clone()).or_default().push(def);
|
||||
}
|
||||
}
|
||||
|
||||
/// Macro name → every `` `define`` of it in the set.
|
||||
fn define_defs(scope: &Scope) -> Defs {
|
||||
let mut out = Defs::new();
|
||||
@@ -316,10 +327,22 @@ fn define_defs(scope: &Scope) -> Defs {
|
||||
let Some(defines) = scope.file_id(i).and_then(|id| scope.index().defines(id)) else {
|
||||
continue;
|
||||
};
|
||||
for define in defines.entries() {
|
||||
let params = define.params.clone().unwrap_or_default();
|
||||
let def = MacroDef { params, body: define.body.clone() };
|
||||
out.entry(define.name.clone()).or_default().push(def);
|
||||
push_defines(&mut out, defines);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Macro name → every `` `define`` read directly from `sources` (for callers
|
||||
/// without a [`Scope`] index).
|
||||
pub(super) fn defs_from_sources(sources: &[(&std::path::Path, &str)]) -> Defs {
|
||||
let mut out = Defs::new();
|
||||
for &(_, text) in sources {
|
||||
if !text.contains('`') || !super::contains_word(text, "define") {
|
||||
continue;
|
||||
}
|
||||
if let Ok(tokens) = vlog_parser::tokenize(text) {
|
||||
let defines = vlog_parser::defines::collect_defines(&tokens);
|
||||
push_defines(&mut out, &defines);
|
||||
}
|
||||
}
|
||||
out
|
||||
@@ -376,7 +399,7 @@ pub(super) fn spellings(text: &str, name: &str) -> (Vec<usize>, bool) {
|
||||
/// Whether `before` ends in a `.`, past blanks, `` `` `` pastes
|
||||
/// (`` u_m.``sig `` pastes a path) and block comments (`u_m./*x*/sig`,
|
||||
/// review L-3).
|
||||
fn after_dot(before: &str) -> bool {
|
||||
pub fn after_dot(before: &str) -> bool {
|
||||
let mut rest = before.trim_end();
|
||||
loop {
|
||||
if let Some(shorter) = rest.strip_suffix("``") {
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// Author: Guoliang Chen, a Senior Digital Design Engineer
|
||||
|
||||
//! Public integration tests for `find_references_with`, batch reference lookup,
|
||||
//! `after_dot`, and bind-aware `home_set_for` / `home_sets_for`.
|
||||
|
||||
use std::cell::Cell;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{
|
||||
after_dot, find_references, find_references_batch, find_references_batch_with,
|
||||
find_references_with, home_set, home_set_for, home_sets_for, KnownFacts,
|
||||
};
|
||||
use vlog_semantic::FileFacts;
|
||||
|
||||
struct MapFacts<'a>(HashMap<&'a Path, (&'a str, FileFacts)>, Cell<usize>);
|
||||
|
||||
impl KnownFacts for MapFacts<'_> {
|
||||
fn facts_for(&self, path: &Path, text: &str) -> Option<FileFacts> {
|
||||
self.1.set(self.1.get() + 1);
|
||||
self.0.get(path).filter(|(held, _)| *held == text).map(|(_, f)| f.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_batch_and_known_facts_match_plain_find_references() {
|
||||
let sub = "module sub (input logic clk, output logic q);\n wire sig;\n assign q = sig;\nendmodule\n";
|
||||
let top = "module top;\n sub u_a (.clk(1'b0), .q());\nendmodule\n";
|
||||
let extra = "module extra;\n wire other;\n assign other = 1'b0;\nendmodule\n";
|
||||
let files = vec![
|
||||
(PathBuf::from("/p/sub.sv"), sub.to_string()),
|
||||
(PathBuf::from("/p/top.sv"), top.to_string()),
|
||||
(PathBuf::from("/p/extra.sv"), extra.to_string()),
|
||||
];
|
||||
let map = files
|
||||
.iter()
|
||||
.map(|(p, t)| (p.as_path(), (t.as_str(), FileFacts::of(p.clone(), t))))
|
||||
.collect();
|
||||
let known = MapFacts(map, Cell::new(0));
|
||||
let sub_p = Path::new("/p/sub.sv");
|
||||
let clk_off = sub.find("clk").unwrap_or(0) as u32;
|
||||
let sig_off = (sub.find("wire sig").unwrap_or(0) + 5) as u32;
|
||||
let queries = [(sub_p, clk_off), (sub_p, sig_off), (sub_p, 0)];
|
||||
|
||||
let plain_batch = find_references_batch(&files, &queries, false);
|
||||
let known_batch = find_references_batch_with(&files, &queries, false, &known);
|
||||
assert_eq!(plain_batch, known_batch);
|
||||
assert_eq!(known_batch[0], find_references_with(&files, sub_p, clk_off, false, &known));
|
||||
assert_eq!(known_batch[1], find_references(&files, sub_p, sig_off, false));
|
||||
assert!(known_batch[2].is_err());
|
||||
assert!(known.1.get() >= 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_after_dot_and_bind_aware_home_set_match_engine_rules() {
|
||||
assert!(after_dot("a."));
|
||||
assert!(after_dot("a . "));
|
||||
assert!(after_dot("a./* c */"));
|
||||
assert!(after_dot("a.``"));
|
||||
assert!(after_dot("a. /* c */ `` "));
|
||||
assert!(!after_dot("/* a. */ "));
|
||||
assert!(!after_dot("a``"));
|
||||
|
||||
let files = vec![
|
||||
(PathBuf::from("/p/a.sv"), "module a; logic s; endmodule\n".to_string()),
|
||||
(PathBuf::from("/p/b.sv"), "module b; logic s; endmodule\n".to_string()),
|
||||
(PathBuf::from("/p/bind_a.sv"), "bind a chk u();\n".to_string()),
|
||||
(PathBuf::from("/p/defs.svh"), "`define B_B bind b chk u_c();\n".to_string()),
|
||||
(PathBuf::from("/p/bind_b.sv"), "`include \"defs.svh\"\n`B_B\n".to_string()),
|
||||
];
|
||||
let a = Path::new("/p/a.sv");
|
||||
let b = Path::new("/p/b.sv");
|
||||
assert_eq!(home_set(&files, a, &[]), Some(vec![a.to_path_buf()]));
|
||||
assert_eq!(
|
||||
home_set_for(&files, a, Some("a"), &[]),
|
||||
Some(vec![a.to_path_buf(), PathBuf::from("/p/bind_a.sv")])
|
||||
);
|
||||
assert_eq!(
|
||||
home_sets_for(&files, &[(a, Some("a")), (b, Some("b"))], &[]),
|
||||
Some(vec![
|
||||
a.to_path_buf(),
|
||||
b.to_path_buf(),
|
||||
PathBuf::from("/p/bind_a.sv"),
|
||||
PathBuf::from("/p/bind_b.sv"),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com
|
||||
@@ -0,0 +1,80 @@
|
||||
<!-- Author: Guoliang Chen, a Senior Digital Design Engineer -->
|
||||
|
||||
# MCP Hardening + `vlog_refactor` References / L-9 Support (Round 3)
|
||||
|
||||
## Goal
|
||||
|
||||
Harden `lucisv_mcp` and `vlog_refactor` on the concrete bugs, performance gaps, and protocol edges identified across audit rounds:
|
||||
|
||||
1. **Cached `FileFacts` in references & MCP tools (`#37` / `#40`):** Add `find_references_with`, `find_references_batch`, and `find_references_batch_with` in `crates/vlog_refactor/src/references.rs` accepting `&dyn KnownFacts`, sharing one `Scope::build_keeping` + occurrence walk; implement `KnownFacts` on `Project` keyed by FNV-1a `content_hash(text)` and wire it into `find`, `rename`, and `edit_item` (`item/refs.rs`).
|
||||
2. **Future-mtime settlement (`#54`):** Anchor monotonic first-observation time (`Stamp::first_mono`) and inherit it across unchanged re-reads (`Stamp::inherit_observation`) in `crates/lucisv_mcp/src/project/files.rs` and `project/mod.rs` so files with future timestamps settle after `RACY` while reacting to wall-clock catch-up, clock step-backs, and edits.
|
||||
3. **Windows `--all-targets` test build (`#56`):** Gate Unix-only symlink and `PermissionsExt::from_mode` tests in `crates/lucisv_mcp/tests/qa_m3.rs` with `#[cfg(unix)]` and add non-Unix `mode_bits` in `snapshot()`.
|
||||
4. **L-9 Parity & Qualified `find` Focus Scoping:** Expose `after_dot` and bind-aware `home_set_for` / `home_sets_for` from `vlog_refactor`, wire `mentions.rs`, `edit.rs`, and `find.rs` to match the engine's dotted-mention and K2 `bind` rules, and wire `Focus::unit` on qualified `unit.name` (and single-unit) queries in `find`.
|
||||
5. **`check` Directory & Glob Support:** Allow `check` (`diagnostics.rs` / `tools/glob.rs`) to accept directory and glob `file` arguments matching `format`'s indexing/root-containment rules, keeping `unused_waivers` whole-design-only.
|
||||
6. **Protocol & Budgets (`rpc.rs`, `wire.rs`, `read_only.rs`, `docs/mcp/PLAN.md`):** Drop unused `"prompts": {}` from `initialize` capabilities and raise catalogue/instruction ceilings to `2,000` / `330 B` (read-only) and `3,800` / `440 B` (full) while preserving the `hierarchy {}` lazy-walk freshness contract.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `KnownFacts` on `Project` must return `None` whenever `content_hash(text.as_bytes()) != stamp.hash` so a disk modification between `Project::refresh` and `WholeSet::read` always triggers a fresh parse.
|
||||
- Existing `INSTRUCTIONS` and `INSTRUCTIONS_READ_ONLY` texts remain within `<= 400 B` / `<= 300 B` for compatibility with `qa_m6.rs` and `qa_f1.rs`, while `wire.rs`, `read_only.rs`, and `rpc.rs` pin the updated `440 / 330 / 3,800 / 2,000 B` ceilings.
|
||||
- `hierarchy {}` continues calling `project.ensure_walked_for_miss()` when unpopulated (preserving M1 freshness).
|
||||
|
||||
## Handshakes
|
||||
|
||||
- `vlog_refactor` ↔ `lucisv_mcp`:
|
||||
- `find_references_with`, `find_references_batch`, `find_references_batch_with` take `&dyn KnownFacts`.
|
||||
- `after_dot(&str) -> bool` is the shared boundary check for dotted spellings across `rename::scoped` and `lucisv_mcp::tools::mentions`.
|
||||
- `home_set_for` / `home_sets_for` expose the engine's include + K2 `bind` home set cleanly to `edit.rs` and `find.rs`.
|
||||
- `tools/glob` ↔ `tools/diagnostics`:
|
||||
- `glob::normalize_glob` validates root containment before `glob::path_match` evaluates indexed files; `Project::resolve_existing` validates file or directory existence within roots.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `vlog_refactor`: `find_references_with`, `find_references_batch`, `find_references_batch_with`, `after_dot`, `home_set_for`, `home_sets_for` + unit/integration tests
|
||||
- [x] `lucisv_mcp::project`: `#54` future-mtime `first_mono` settlement + `KnownFacts` on `Project`
|
||||
- [x] `lucisv_mcp::tools` & `rpc.rs`: `KnownFacts` wiring, L-9 parity, qualified `find`, `check` dir/glob, remove `"prompts": {}`, updated budgets
|
||||
- [x] Cross-platform gate (`#56`) in `qa_m3.rs` + docs (`PLAN.md`, this doc)
|
||||
- [x] Full verification suite (`fmt`, `stamp_author`, `clippy`, guarded `cargo test`, Windows `--all-targets` check, live OpenTitan stdio probe)
|
||||
|
||||
## Work log
|
||||
|
||||
- Implemented `find_references_with`, `find_references_batch`, and `find_references_batch_with` in `crates/vlog_refactor/src/references.rs` sharing `collect_batch` / `build_scope` / `collect_one`, and exported them alongside `after_dot`, `home_set_for`, and `home_sets_for` from `crates/vlog_refactor/src/lib.rs` (with `pub(crate) use` / `pub use` in `crates/vlog_refactor/src/rename/mod.rs`).
|
||||
- Added `first_mono` and `inherit_observation` to `Stamp` in `crates/lucisv_mcp/src/project/files.rs` and wired observation inheritance + `vlog_refactor::KnownFacts` for `Project` (keyed by `stamp.hash == content_hash(text.as_bytes())`) in `crates/lucisv_mcp/src/project/mod.rs`.
|
||||
- Wired `KnownFacts` into `find.rs` (`find_references_batch_with`), `edit.rs` (`rename_traced_with`), and `tools/item/refs.rs` (`find_references_batch_with`); updated `mentions.rs` (`vlog_refactor::after_dot`), `edit.rs` / `find.rs` (`home_set_for` / `home_sets_for`), and qualified `Focus::unit` scoping in `find.rs`.
|
||||
- Added directory and glob support to `check` (`diagnostics.rs`, `tools/glob.rs::normalize_glob`, `Project::resolve_existing`); removed `"prompts": {}` from `initialize` capabilities in `rpc.rs`; raised catalogue/instruction ceilings to `2,000 / 330 B` (RO) and `3,800 / 440 B` (full) in `docs/mcp/PLAN.md`, `rpc.rs`, `wire.rs`, and `read_only.rs` (measured sizes: `1,826 B / 297 B` RO, `3,469 B / 398 B` full).
|
||||
- Gated Unix-specific symlink/permission tests in `crates/lucisv_mcp/tests/qa_m3.rs` with `#[cfg(unix)]` and added cross-platform `mode_bits` helper for `snapshot()`.
|
||||
- Verified:
|
||||
- `cargo fmt` & `python3 tools/stamp_author.py --check` (`would stamp 0 files; left 249 untouched`).
|
||||
- `cargo clippy -p vlog_refactor -p lucisv_mcp --all-targets -- -D warnings`: passed (0 errors/warnings on crate code).
|
||||
- `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_mcp`: passed (0 errors).
|
||||
- `./tools/guard.sh -m 8 -t 600 -- cargo test -p vlog_refactor -p lucisv_mcp --all-targets`: 0 failures across all targets (`lucisv_mcp`: 88 unit + 23 `attacks` + 4 `cache` + 2 `hierarchy_cap` + 21 `qa_f1` + 6 `qa_f2` + 48 `qa_m1` + 35 `qa_m2` + 36 `qa_m3` + 45 `qa_m4` + 17 `qa_m6` + 19 `qa_m7` (+1 ignored) + 6 `qa_m8` + 5 `read_only` + 44 `wire` + 3 ignored `opentitan`; `vlog_refactor`: 218 unit + 54 `ansi` + 11 `corpus` (+1 ignored) + 33 `expand` + 41 `extract` + 9 `import_offers` + 35 `imports` + 37 `inline` + 3 ignored `opentitan_top_rooted` + 7 `parsed_selectors` + 10 `port_offers` + 54 `ports` + 11 `preflight_oracle` + 11 `qa_correctness_r1` + 26 `qa_generate_label` + 26 `qa_rename_implicit` (+1 ignored) + 24 `qa_warning_scope` + 2 `references_and_scope` + 71 `rename` + 15 `rename_bind` (+1 ignored) + 17 `rename_generate_label` + 24 `rename_implicit` + 10 `rename_macro_carry` + 8 `rename_warning_scope` + 15 `top_rooted_paths`).
|
||||
- Release stdio probe (`./target/release/lucisv-mcp --root /Users/lucio/repo/opentitan/hw --read-only`, no `--index-cache`): `initialize` capabilities `{'resources': {}, 'tools': {}}` (no `"prompts"`); `hierarchy {}` returned `4043 files, 1355 modules, 372 top` (301 lines); `check` on `ip/aes/rtl` (`34.4 ms`, `ok`) and `ip/aes/rtl/*.sv` (`34.5 ms`, `ok`, matching dir), bad glob refused cleanly; `find` with `refs: true` on `aes_core.AES192Enable` ran in `1,460.1 ms` cold / `461.4 ms` warm (`rst_ni` batch of `REFS_CAP=5` ran in `1,938.6 ms` cold / `1,915.1 ms` warm, identical output); `/Users/lucio/repo/opentitan` git working tree verified clean.
|
||||
|
||||
## QA log
|
||||
|
||||
**Verdict: PASS** (Round 3 QA audit against HEAD `4d384ec` uncommitted diff).
|
||||
|
||||
- **Invariants & deduplication:**
|
||||
- Every changed/added library file (`crates/vlog_refactor/src/{lib.rs,references.rs,rename/mod.rs,rename/home.rs,rename/scoped.rs}` and `crates/lucisv_mcp/src/{project/files.rs,project/mod.rs,rpc.rs,tools/diagnostics.rs,tools/edit.rs,tools/find.rs,tools/glob.rs,tools/item/refs.rs,tools/mentions.rs}`) has `<= 312` non-blank non-comment production lines before `mod tests` (well under `600`) and `0` `.unwrap()`, `.expect()`, `panic!`, or `unsafe` occurrences in non-test production code.
|
||||
- Shared helpers verified without duplication: `references.rs` (`collect_single`, `collect_batch`, `build_scope`, `collect_one`), `home.rs` (`home_sets_for`, `home_with_graph`), `scoped.rs`/`home.rs` (`file_binds_into`, `push_defines`, `defs_from_sources`), `scoped.rs`/`mentions.rs` (`vlog_refactor::after_dot`), and `diagnostics.rs` (`lint_paths`, `match_with_rewalk`).
|
||||
- **Adversarial code & contract checks:**
|
||||
- **#37 / #40 (`KnownFacts`):** `Project::facts_for` verifies `stamp.hash == lucisv_core::cache::content_hash(text.as_bytes())` so stale `FileFacts` are never returned after on-disk edits between `refresh` and `WholeSet::read`; `Scope::take` also checks `facts.path() == path`. `find_references_batch_with` / `find_references_with` match `find_references` identically on `find.rs`, `edit.rs` (`rename_traced_with`), and `tools/item/refs.rs`.
|
||||
- **#54 (Future-mtime settlement):** `Stamp::first_mono`, `Stamp::inherit_observation`, and `Stamp::racy(now)` preserve observation age across unchanged re-reads (`same && !prev.clock_stepped_back(now)`), settle after `RACY` monotonic elapsed, force re-read into normal rules on wall-clock catch-up (`now.wall >= time`), reset on hash/metadata changes, and mark `Suspect` on wall-clock step-backs.
|
||||
- **#56 (Windows `--all-targets`):** `qa_m3.rs` gates only Unix-specific symlink/`PermissionsExt::from_mode` tests with `#[cfg(unix)]` while keeping portable tests active with `mode_bits`. `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_mcp` compiled with `0` errors.
|
||||
- **L-9 & Qualified `find`:** `after_dot` handles blanks, `/* ... */` comments, and ` `` ` pastes identically in `scoped.rs` and `mentions.rs`; `home_set_for`/`home_sets_for` include direct and macro-expanded `bind` home sets (K2); `find.rs` populates `Focus::unit` on qualified `unit.name` and single-unit queries.
|
||||
- **`check` dir/glob, budgets & `hierarchy {}`:** `tools/glob.rs::normalize_glob` + `Project::resolve_existing` enforce root containment and refuse empty, missing, non-matching, and outside-root (`..`, `../../etc/*.sv`) targets; `lint_paths(..., false)` omits whole-design `unused_waivers` on subset checks. `rpc.rs` `initialize` returns `capabilities: {"tools": {}, "resources": {}}` (no `"prompts"`). Budgets verified in `rpc.rs`, `wire.rs`, `read_only.rs`, and `docs/mcp/PLAN.md` (measured: RO `1,826 B` catalogue / `297 B` instructions vs `2,000 / 330 B` caps; full `3,469 B` catalogue / `398 B` instructions vs `3,800 / 440 B` caps). `hierarchy.rs:107` retains `project.ensure_walked_for_miss()` for `hierarchy {}`.
|
||||
- **Executed verification commands:**
|
||||
- `python3 tools/stamp_author.py --check`: `would stamp 0 files; left 249 untouched`.
|
||||
- `./tools/gates.sh --only fmt,clippy,suite:vlog_refactor,suite:lucisv_mcp,docs,node,cross`: `PASS` across all 7 steps (`fmt` pass, `clippy` pass, `suite:vlog_refactor` `769/0`, `suite:lucisv_mcp` `399/0`, `docs` `1/0`, `node` `37/0`, `cross` pass).
|
||||
- Windows `--all-targets`: `env RUSTC="$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin/rustc" "$HOME/.rustup/toolchains/stable-aarch64-apple-darwin/bin/cargo" check --target x86_64-pc-windows-gnu --all-targets -p lucisv_mcp` passed with `0` errors.
|
||||
- OpenTitan stdio probe (`./target/release/lucisv-mcp --root /Users/lucio/repo/opentitan/hw --read-only`): `initialize` capabilities `{'resources': {}, 'tools': {}}` (`297 B` instructions); `hierarchy {}` -> `4043 files, 1355 modules, 372 top` (`301` lines, `1069.8 ms`); `find` `aes_core.AES192Enable` (`refs: true`, `486.9 ms` cold / `459.5 ms` warm, identical output) and `aes_control_fsm.aes_ctrl_ns` (`refs: true`, returned `aes_bind.sv:65` + `aes_control_fsm.sv` uses + `unresolved` line `909`); `find` `rst_ni` (`refs: true`, `1944.3 ms` -> `1937.3 ms`, `301` lines); `check` on `ip/aes/rtl` (`34.8 ms`, `ok`), `./ip/aes/rtl/` (`33.8 ms`, `ok`), `ip/aes/rtl/*.sv` (`34.5 ms`, `ok`), `ip/aes/**/rtl/aes_core.sv` (`19.7 ms`, `ok`), `ip/uart/dv` vs `ip/uart/dv/**/*.sv` (identical `5` findings), `ip/uart/dv/*.sv` / `ip/aes/rtl/*.none` (`isError=true`, `no indexed file matches ...`), `../../etc/*.sv` / `..` (`isError=true`, `resolves outside every root`), `ip/aes/no_such_dir` (`isError=true`, `does not exist under any root`).
|
||||
- `git -C /Users/lucio/repo/opentitan status --porcelain`: empty (strictly clean).
|
||||
|
||||
## Review
|
||||
|
||||
**Lead Self-Inspect (2026-11-26): APPROVED for trunk commit.**
|
||||
- Verified Plan Review rulings were respected: `hierarchy.rs` retains `ensure_walked_for_miss()` on no-root `hierarchy {}` calls; `rename/mod.rs` and `lib.rs` export `after_dot`, `home_set_for`, and `home_sets_for`; `find_references_with` / `find_references_batch_with` match `find_references` error and tuple types (`Result<Vec<(PathBuf, TextRange)>, String>`).
|
||||
- Checked `rpc.rs` (`"prompts": {}` removed from `initialize` capabilities), `references.rs` (`KnownFacts` hash-checked caching with shared `collect_single`/`collect_batch`/`build_scope`/`collect_one`), `files.rs` (`first_mono`/`inherit_observation` `#54` future-mtime settlement), `qa_m3.rs` (`#[cfg(unix)]` `#56` portability), `diagnostics.rs`/`glob.rs` (`check` dir/glob support), and owner-ruled catalogue/instruction ceilings (`2,000/330 B` RO, `3,800/440 B` full).
|
||||
- Pending final full `./tools/gates.sh` + `stamp_author.py --check` before local commit and closing `#37`, `#40`, `#54`, `#56` in `docs/topo.md`.
|
||||
|
||||
<!-- Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com -->
|
||||
+7
-7
@@ -230,7 +230,7 @@ binary, as `editors/vscode/smoke.js` does for the LSP):
|
||||
|
||||
| method | answer |
|
||||
|---|---|
|
||||
| `initialize` | `protocolVersion` (the client's if we support it, else our newest), `capabilities: { tools: {}, resources: {}, prompts: {} }`, `serverInfo { name: "lucisv-mcp", version }`, `instructions` — a short paragraph telling the agent to prefer `unit_interface`/`outline`/`read_item` over reading files, and that edits are on-disk and verified |
|
||||
| `initialize` | `protocolVersion` (the client's if we support it, else our newest), `capabilities: { tools: {}, resources: {} }`, `serverInfo { name: "lucisv-mcp", version }`, `instructions` — a short paragraph telling the agent to prefer `unit_interface`/`outline`/`read_item` over reading files, and that edits are on-disk and verified |
|
||||
| `notifications/initialized` | accepted |
|
||||
| `ping` | `{}` |
|
||||
| `tools/list` | every tool with `name`, `description`, `inputSchema` (JSON Schema, `additionalProperties: false`, `required`), `annotations` (`readOnlyHint`, `destructiveHint`, `idempotentHint`) — read tools are `readOnlyHint: true`; edit tools `destructiveHint: false` (verified, refusable, atomic) |
|
||||
@@ -491,7 +491,7 @@ distinct value is the *hierarchy* of the project — where things are, as
|
||||
`file:line`, with a way to peek at the code — and bulk edits that a file
|
||||
write cannot do safely. So: nine tools, the whole model-visible catalogue
|
||||
(`name` + `description` + `inputSchema` of every tool, compact JSON) **under
|
||||
3 500 bytes** (≈ 1 000 tokens) and `instructions` under 400 bytes, both
|
||||
3 800 bytes** (≈ 1 000 tokens) and `instructions` under 440 bytes, both
|
||||
pinned by test; short answers by default; no `dry_run`, no paging arguments;
|
||||
edits are file writes the agent is told to trust.
|
||||
|
||||
@@ -510,7 +510,7 @@ its text. The `annotations` stay (`readOnlyHint`, `destructiveHint: false`)
|
||||
| `find` | `name`, `refs?` (bool) | Every declaration of `name` (whole-name, any case-exact): `kind name file:line`, then, with `refs`, per declaration its uses as `file:line` (one file per line, lines joined with `,` when several are in one file: `ip/uart/rtl/uart.sv:120,133,140`), then `unresolved:` and the textual mentions (strings, comments, macro text) the same way. No declaration: up to 20 contains-matches of declarations as a refusal (`no declaration named X; similar: …`). Cap 300 lines. |
|
||||
| `outline` | `file?` **or** `unit?` (exactly one) | `file`: its declarations as a tree with line ranges, two spaces per level: `kind name start–end`, parse errors first as `error line: message`. `unit`: its `file:line`, then parameters `param name = default` and ports `dir type[range] name` in declaration order, one per line; interfaces add modports, packages their exports. No template, no counts. Cap 300 lines. |
|
||||
| `read` | `item`, `file?` | The item's source, exact bytes, preceded by one line `file:start–end`. Selector as today's `read_item` (`name`, `kind:name`, `name@LINE`, `always@LINE`). Without `file` the item is looked up design-wide; several matches → a refusal listing them as `file:line`. |
|
||||
| `check` | `file?` | Parse errors, missing closers and lint findings of `file` or the whole design, `file:line:col severity message [rule]`, errors first, cap 200 lines then `… and N more`. Clean: `ok` (one word). |
|
||||
| `check` | `file?` | Parse errors, missing closers and lint findings of `file` (path, directory or glob) or the whole design, `file:line:col severity message [rule]`, errors first, cap 200 lines then `… and N more`. Clean: `ok` (one word). |
|
||||
| `rename` | `name`, `new_name`, `file?` | Renames the declaration `name` (in `file` when the name is declared in more than one place; ambiguity without `file` is a refusal that lists the declarations) and every resolved use, `.name`/`.*` shorthand included (M3.5). Answer: `renamed N sites in M files` and, only when any, `unresolved:` lines as in `find`. |
|
||||
| `port` | `module`, `add?` (a port declaration), `after?`, `remove?` (a port name) | Exactly one of `add`/`remove`. `add` inserts the ANSI port (after port `after`, else last) and connects it by name in every instantiation; `remove` deletes the port and its connection everywhere, refused while the module body uses it. Answer: `added|removed port X in module M: N instantiations in K files` and any `unresolved:` lines. |
|
||||
| `edit_item` | `file`, `op` (`replace` / `insert_before` / `insert_after` / `delete`), `item`, `text?` | The M4 structural edits under one name, same verifier, same rules: `replace` keeps kind and names; `insert_*` anchors on `item` (or `end` / `end@UNIT`); `delete` takes the item and its leading comments and is refused while its names are used (sites listed) or it holds a `` `define ``. No `force`, no `rename`. Answer: `replaced|inserted|deleted ITEM file:start–end` (the new lines). |
|
||||
@@ -538,7 +538,7 @@ Dropped from the catalogue (the engines stay in the CLI and the LSP):
|
||||
- Refusals are one sentence, `isError: true`, and when a name is unknown
|
||||
they list the near matches so the next call is right.
|
||||
|
||||
### 10.3 Instructions (≤ 400 bytes; the shipped text, 398 bytes)
|
||||
### 10.3 Instructions (≤ 440 bytes; the shipped text, 398 bytes)
|
||||
|
||||
> lucisv-mcp reads the SystemVerilog on disk (save first). Use it before
|
||||
> reading files: hierarchy for instance trees and top modules, find for a
|
||||
@@ -560,7 +560,7 @@ Agents guide's table.
|
||||
### 10.5 Acceptance
|
||||
|
||||
- `tools/list`: exactly the nine names above, in that order; the
|
||||
model-visible bytes ≤ 3 500, `instructions` ≤ 400 — a test in `wire.rs`
|
||||
model-visible bytes ≤ 3 800, `instructions` ≤ 440 — a test in `wire.rs`
|
||||
computes both.
|
||||
- No `dry_run`, `limit`, `offset`, `in`, `template`, `overrides`, `force`
|
||||
argument anywhere.
|
||||
@@ -587,13 +587,13 @@ under two names, and the extension chooses by a setting.
|
||||
mode except `check`, whose words "after edits" do not apply (one
|
||||
description for both modes if it reads right in both; otherwise a
|
||||
read-only wording). Model-visible bytes (compact JSON of name +
|
||||
description + inputSchema) **≤ 1 800**, pinned by test.
|
||||
description + inputSchema) **≤ 2 000**, pinned by test.
|
||||
- **`tools/call`** of `rename`, `port`, `edit_item` or `format` in
|
||||
read-only mode is the unknown-tool error (`-32602`), message
|
||||
`unknown tool: rename (the server runs --read-only)`. The edit handlers
|
||||
are not reachable: the mode filters the registry, it does not flag
|
||||
inside each handler.
|
||||
- **Instructions** in read-only mode, **≤ 300 bytes**, pinned by test:
|
||||
- **Instructions** in read-only mode, **≤ 330 bytes**, pinned by test:
|
||||
|
||||
> lucisv-mcp reads the SystemVerilog on disk (save first); it never
|
||||
> edits. Use it before reading files: hierarchy for instance trees and
|
||||
|
||||
+4
-4
@@ -762,10 +762,10 @@ update the filing README(s) and this file.
|
||||
| ~~34~~ | ~~**The format cache omits `Config::uvm_utils_indent`.** CLI `args.rs::config_with` applies the key, but `main.rs::entry_for` and core `cache::Entry` serialize/compare only content, line length and indent (plus the store version). On one UVM class: cache a clean verdict with the option false, change only the option to true, then cached `--check` exits 0 while `--no-cache --check` exits 1. Wanted: key/equality/codec coverage for the option and a regression for both toggle directions. Until fixed, use `--no-cache` or delete the format cache after toggling. See repository-analysis.md for the bounded reproduction.~~ — **fixed 2026-09-07 (TODO §59, 0.50.0):** `Entry` carries `uvm_utils_indent`, `entry_for` fills it, the store line has it as a fourth field; a well-formed five-field (0.49.0) line is dropped individually like another version's entry; the audit's probe is `changing_uvm_utils_indent_invalidates_the_entry` in `lucisv/tests/cli.rs`, both directions. | repository audit, 2026-09-07 | lucisv_core / lucisv |
|
||||
| 35 | **MCP-5 → `vlog_parser`:** lift the server's `expand.rs` (one-step macro expansion) into `vlog_parser::defines` as a pure move so `lucisv-mcp`'s `defines` can offer expansion — *moot since M7: `defines` folded into `find`, which lists a macro's definitions and no expansion* | mcp-navigation | vlog_parser |
|
||||
| 36 | **MCP-6 → `lucisv_server` (possible bug):** LSP `references` omits three real `aes` instantiations in the `*_pd_main.sv` tops (and their `.clk_i` connections) that `lucisv-mcp`'s whole-set answer lists; stable after a 30 s settle, not investigated | mcp-navigation | lucisv_server |
|
||||
| 37 | **MCP-7 → `vlog_refactor`:** a `find_references` variant taking `&dyn KnownFacts` (like `rename_traced_with`) so whole-set callers feed cached records instead of re-parsing 3 944 files (≈2 s per opentitan call today) | mcp-navigation | vlog_refactor |
|
||||
| ~~37~~ | ~~**MCP-7 → `vlog_refactor`:** a `find_references` variant taking `&dyn KnownFacts` (like `rename_traced_with`) so whole-set callers feed cached records instead of re-parsing 3 944 files (≈2 s per opentitan call today)~~ — **closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** added `find_references_with` and `find_references_batch_with` accepting `&dyn KnownFacts` in `vlog_refactor/src/references.rs` and wired `Project`'s hash-validated cached `FileFacts` into `lucisv_mcp` (`find`, `rename`, `item/refs`). | mcp-navigation | ~~vlog_refactor~~ done |
|
||||
| ~~38~~ | ~~**MCP-8 → `vlog_refactor`:** false `remove_port` refusal when the only "use" of the port is a named connection from another module in the same file (`ports/remove.rs::body_uses_in`)~~ — **closed 2026-11-26 by `refactor-correctness-r1` (Round 1):** `body_uses_in` takes `find_module`'s full `module ... endmodule` span (`item.span`) and filters references to that range. | mcp-edit-tools | ~~vlog_refactor~~ done |
|
||||
| ~~39~~ | ~~**MCP-10 → `vlog_refactor`:** `extract_module` writes LF into a CRLF file (`extract/render.rs`)~~ — **closed 2026-11-26 by `refactor-correctness-r1` (Round 1):** `extract/mod.rs` and `extract/render.rs` detect source `\r\n` vs `\n` and preserve it across new-module, instantiation, and same-file insertion. | mcp-edit-tools | ~~vlog_refactor~~ done |
|
||||
| 40 | **MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; ~~`find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`)~~ — **second half answered 2026-09-30 by generate-label-rename (TODO §65.1, row 43)**; the batched `find_references` stays open | mcp-structural-edits | vlog_refactor, vlog_semantic |
|
||||
| ~~40~~ | ~~**MCP-11/12 → `vlog_refactor`/`vlog_semantic`:** a batched `find_references` for several declarations; `find_references` misses a hierarchical use into a generate loop (`gen_l[0].z`)~~ — **second half answered 2026-09-30 by generate-label-rename (TODO §65.1, row 43); closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** `find_references_batch` and `find_references_batch_with` reuse one `Scope::build_keeping` across queries. | mcp-structural-edits | ~~vlog_refactor, vlog_semantic~~ done |
|
||||
| 41 | **MCP-13 → `vlog_linter`:** a forced deletion of a non-ANSI body port leaves a header port with no direction and no lint reports it | mcp-structural-edits | vlog_linter |
|
||||
| 42 | **Parser leniency → `vlog_parser`:** a trailing `,` in a named connection list, an empty concatenation element `{d,, d}`, and `type(x)'(y)` in a connection parse without a diagnostic (the rename verifier's position rule covers the rename; every other splice contract is exposed) | refactor-rename (M3.5) | vlog_parser |
|
||||
| ~~43~~ | ~~**MCP-14 → `vlog_refactor`/`vlog_semantic`:** rename of a generate block label leaves hierarchical paths through it unrewritten and `find_references` does not report them — vlog_refactor/vlog_semantic; the MCP layer refuses the rename; the LSP still allows it~~ — **closed 2026-09-30 by generate-label-rename (TODO §65.1, 0.60.0):** the gap was resolution, not the rename — `vlog_semantic` now declares a `for` block's label in the enclosing scope (the genvar stays in the header), treats `generate … endgenerate` as no scope, gives a named block a member scope, walks an index in a path as the name it indexes, and puts blocks on a module's hierarchical surface with their members under the synthesized key `module.label` (`FACTS_FORMAT` 21; `Semantics::member_key`, which `lucisv_server/src/nav.rs` now asks with). Every segment — bare, indexed, nested, cross-file — and the closing label are ordinary references, so `find_references`, `rename` (LSP, CLI engine, MCP) and the verifier's unchanged resolution print all see them; no verifier normalization was added, eight attacks pin that (`check/qa_block_paths.rs`). `lucisv-mcp`'s `block` refusal is lifted. Also answers row 40's second half (`gen_l[0].z` is found). | mcp-lean-catalogue | vlog_refactor, vlog_semantic |
|
||||
@@ -779,9 +779,9 @@ update the filing README(s) and this file.
|
||||
| ~~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`) |
|
||||
| ~~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)~~ — **closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** `Stamp::first_mono` and `Stamp::inherit_observation` settle future-mtime files after `RACY` monotonic duration while preserving re-reads on edits, wall-clock catch-up, and clock step-backs (`project/files.rs`, `project/mod.rs`). | linux-test-portability (Round 2) | ~~lucisv_mcp (`project/files.rs`)~~ done |
|
||||
| 55 | `crates/lucisv/tests/cli.rs:2149` (`a_stdin_buffer_reads_the_rule_options_too`) asserts only an empty stdout, no exit code (TODO §70) | linux-test-portability (Round 2) | crates/lucisv (tests) |
|
||||
| 56 | `crates/lucisv_mcp/tests/qa_m3.rs` uses `std::os::unix` with no `cfg`, so `cargo check --all-targets` for Windows fails (tests only; the `cross` gate checks binaries only) (TODO §70) | linux-test-portability (Round 2) | lucisv_mcp (tests) |
|
||||
| ~~56~~ | ~~`crates/lucisv_mcp/tests/qa_m3.rs` uses `std::os::unix` with no `cfg`, so `cargo check --all-targets` for Windows fails (tests only; the `cross` gate checks binaries only) (TODO §70)~~ — **closed 2026-11-26 by `mcp-hardening-r3` (Round 3):** added portable `mode_bits` and gated Unix-only symlink/`PermissionsExt` tests in `qa_m3.rs` with `#[cfg(unix)]`; verified `cargo check --target x86_64-pc-windows-gnu --all-targets -p lucisv_mcp`. | linux-test-portability (Round 2) | ~~lucisv_mcp (tests)~~ done |
|
||||
| 57 | **Releases are gated on macOS alone**: Linux runs the suite in `ci.yml` but the release does not wait for it, and Windows is compile-checked (`cross`), never executed (TODO §70) | linux-test-portability (Round 2) | tools/ + CI (lead) |
|
||||
| 58 | **The discovery walk at the start of every scan drains nothing** (25–80 ms on OpenTitan): what is left of the first-colour wait in workspace scope (62–86 ms late open) and the rescan hold (70–159 ms). Wanted: a resumable walk in `state/discover.rs` (it holds `&mut Workspace` throughout `begin_scan`), with its own identical-result proof (TODO §71 wave 7) | viewport-highlight (Handshake request 2) | lucisv_server (`state/discover.rs`) |
|
||||
| 59 | **A `range` answered during a rescan always counts as a guess** (`Viewport::guessed`) and costs one refresh at settle even when nothing changed (TODO §71 wave 7) | viewport-highlight (QA) | lucisv_server (`server/viewport.rs`) |
|
||||
|
||||
Reference in new issue
Block a user