MCP M7: the lean catalogue — nine tools, 3 440 model-visible bytes, no dry_run/paging, short answers
hierarchy (file:line per instance, peek), find (every declaration by name, refs + unresolved mentions), outline, read, check, rename, port, edit_item, format. Name lookup reaches every declaration the symbol tables hold (tools/declared.rs); rename of a generate-block label is refused (engine gap filed as topo §2.9 MCP-14). Text-only results, engine sentences made root-relative. Tests ported or deleted per the README; QA lane in tests/qa_m7.rs. Docs, smoke gate, release notes (0.58.0 unreleased) updated. Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
1 parent
edad66947f
commit
bfa8e98eb5
59 files changed
+4895
-7672
No files matched your search
@@ -4,6 +4,50 @@ All notable changes to lucisv are recorded here. Versions follow
|
||||
[semantic versioning](https://semver.org/); until 1.0 the CLI's exit codes
|
||||
(see `README.md`) are the only frozen contract.
|
||||
|
||||
## 0.58.0 — unreleased
|
||||
|
||||
### The lean MCP catalogue: nine tools, short answers, trusted writes
|
||||
|
||||
The census (`mcp_analysis.md`) found the server right on every run and
|
||||
dearer than plain file reads on every small task: a 5 400-token catalogue
|
||||
read each session, answers carrying more than the question, and agents
|
||||
dry-running what they were told to trust. PLAN §10 is the owner's ruling:
|
||||
accuracy over breadth. (`docs/features/mcp-lean-catalogue`.)
|
||||
|
||||
- **Nine tools, in this order: `hierarchy`, `find`, `outline`, `read`,
|
||||
`check`, `rename`, `port`, `edit_item`, `format`.** The model-visible
|
||||
catalogue (name, description, schema of every tool) is 3 440 bytes, was
|
||||
17.9 kB; the `initialize` instructions are 398 bytes. Both budgets
|
||||
(≤ 3 500 and ≤ 400) and the names and order are pinned by `tests/wire.rs`.
|
||||
No `title`, no `structuredContent` (a result is its text), no
|
||||
per-argument descriptions; the schemas are `type` (and `enum`) only.
|
||||
- **`hierarchy`** — without `root`: `N files, M modules, K top` and each
|
||||
top as `name file:line`; with `root`: the instance tree (`depth` 1–20,
|
||||
default 1), every instance at its **instantiation site**; `up`: every
|
||||
instantiation, all levels to `depth`; `peek`: each statement's source.
|
||||
Opentitan's `top_earlgrey` names 0.57.0's instance set, pinned.
|
||||
- **`find`** — every declaration of a name (or `unit.name`), macros
|
||||
included, as `kind name file:line`; `refs` adds each declaration's uses
|
||||
one file per line (`file:120,133`) and the unresolved mentions.
|
||||
- **`outline`** (`file` or `unit`), **`read`** (one item; design-wide
|
||||
without `file`), **`check`** (`file:line:col severity message [rule]`,
|
||||
errors first, `ok` when clean — the 0.57.0 `diagnostics` line set).
|
||||
- **`rename`** (by name; `file` and `name@LINE` pick a declaration),
|
||||
**`port`** (`add` after `after`, or `remove`, in every instantiation),
|
||||
**`edit_item`** (`replace`, `insert_before`, `insert_after`, `delete` —
|
||||
the M4 verifier unchanged; `delete` has no `force` any more), **`format`**
|
||||
(a path, directory or glob; `fix` applies the safe lint fixes first; a
|
||||
file the formatter refuses is named, the rest written).
|
||||
- **Gone from the wire:** `dry_run`, `limit`, `offset`, `in`, `template`,
|
||||
`overrides`, `force`, and the tools `project_overview`, `list_units`,
|
||||
`unit_interface`, `read_item`, `search_symbols`, `defines`, `definition`,
|
||||
`references`, `diagnostics`, `fix_lint`, `expand_wildcard`,
|
||||
`convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
|
||||
`remove_port`, `add_port`, `extract_module`, `replace_item`,
|
||||
`insert_item`, `delete_item`, `instantiate` (the engines stay in the CLI
|
||||
and the language server). Answers are capped (300 lines; `check` 200)
|
||||
with one `… and N more` line.
|
||||
|
||||
## 0.57.0 — 2026-09-23
|
||||
|
||||
### The MCP block complete: structural edits, the server in the extension, cache reuse, and three census rounds
|
||||
|
||||
+9
-9
@@ -404,37 +404,37 @@ under 400, short answers, no dry_run/paging, edits told to be trusted.
|
||||
Feature README `docs/features/mcp-lean-catalogue`. One dev (Opus), one QA
|
||||
(Opus), on trunk.
|
||||
|
||||
- [ ] registry: `TOOLS` holds exactly `hierarchy, find, outline, read,
|
||||
- [x] registry: `TOOLS` holds exactly `hierarchy, find, outline, read,
|
||||
check, rename, port, edit_item, format` in that order; `title` and
|
||||
`structuredContent` removed from the wire (`Answer` is text only);
|
||||
`Param.description` gone; `wire.rs` pins the names, the order, the
|
||||
byte budgets (≤ 3 500 model-visible, ≤ 400 instructions) and that no
|
||||
schema names `dry_run`, `limit`, `offset`, `in`, `template`,
|
||||
`overrides`, `force`
|
||||
- [ ] `hierarchy`: no root → counts line + top modules; down = instance
|
||||
- [x] `hierarchy`: no root → counts line + top modules; down = instance
|
||||
tree with instantiation `file:line`; `up`; `peek`; cap 300;
|
||||
unknown-root refusal with near matches; opentitan instance set
|
||||
identical to the old tool (test against `tests/opentitan.rs` truth)
|
||||
- [ ] `find`: declarations + `refs` uses grouped one file per line +
|
||||
- [x] `find`: declarations + `refs` uses grouped one file per line +
|
||||
`unresolved:`; macros found; near-match refusal
|
||||
- [ ] `outline` (`file` xor `unit`), `read` (design-wide lookup, ambiguity
|
||||
- [x] `outline` (`file` xor `unit`), `read` (design-wide lookup, ambiguity
|
||||
refusal), `check` (`ok` when clean; old `diagnostics` line set
|
||||
preserved on the fixtures)
|
||||
- [ ] `rename` (name-based, `file` disambiguates), `port` (add xor remove),
|
||||
- [x] `rename` (name-based, `file` disambiguates), `port` (add xor remove),
|
||||
`edit_item` (four ops, the M4 verifier unchanged, `attacks.rs` green
|
||||
unchanged), `format` (path or glob, `fix`)
|
||||
- [ ] instructions ≤ 400 bytes per PLAN §10.3; resources render through
|
||||
- [x] instructions ≤ 400 bytes per PLAN §10.3; resources render through
|
||||
the new renderers
|
||||
- [ ] tests: the old suites that exercise dropped tools are ported to the
|
||||
- [x] tests: the old suites that exercise dropped tools are ported to the
|
||||
surviving tool or deleted with a line in the README saying which;
|
||||
every kept invariant (verifier attacks, all-or-nothing writes, roots,
|
||||
freshness, cache read-only) keeps its test
|
||||
- [ ] docs: feature README; `docs/site/.../guides/agents.md` table
|
||||
- [x] docs: feature README; `docs/site/.../guides/agents.md` table
|
||||
regenerated by `mcp_smoke.js --tool-table` (+ the promises paragraph:
|
||||
no dry_run); extension README/CHANGELOG; `CHANGELOG.md` 0.58.0 notes
|
||||
(unreleased); `docs/topo.md` §2.8 rows; PLAN §4.3/§4.5 marked
|
||||
superseded by §10
|
||||
- [ ] QA: attack the byte budget (a description that grows), the caps, the
|
||||
- [x] QA: attack the byte budget (a description that grows), the caps, the
|
||||
ambiguity refusals, `peek` on a multi-line instantiation with
|
||||
comments, `port add` after a non-existent port, `edit_item delete`
|
||||
of a used item, `format` with a glob that matches nothing; differential
|
||||
|
||||
+28
-103
@@ -1,8 +1,9 @@
|
||||
//! The one write path every edit tool goes through.
|
||||
//!
|
||||
//! A tool hands over a [`Plan`] — per file, the text it computed against and
|
||||
//! the text it wants written — and gets back either the unified diff
|
||||
//! (`dry_run`) or a summary of what was written. The write is all-or-nothing
|
||||
//! the text it wants written — and gets back which files were written. There
|
||||
//! is no dry run (PLAN §10): an edit is a file write the agent is told to
|
||||
//! trust, so the verification happens here, before it. The write is all-or-nothing
|
||||
//! as far as a filesystem allows: every file's new text exists before the
|
||||
//! first write; every target is checked to lie inside a root; every file is
|
||||
//! re-read and compared with the text the plan was computed against, and a
|
||||
@@ -16,12 +17,9 @@ use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::atomic::write_atomic;
|
||||
use lucisv_core::diff::unified;
|
||||
use serde_json::{json, Value};
|
||||
use vlog_refactor::{RefactorEdit, TextEdit};
|
||||
|
||||
use crate::project::Project;
|
||||
use crate::tools::Answer;
|
||||
|
||||
/// One file an edit rewrites or creates.
|
||||
pub struct Change {
|
||||
@@ -40,12 +38,8 @@ pub struct Change {
|
||||
pub struct Plan {
|
||||
/// The files to write, in any order.
|
||||
pub changes: Vec<Change>,
|
||||
/// Files the tool looked at and left as they were (`format`, `fix_lint`).
|
||||
pub unchanged: Vec<PathBuf>,
|
||||
/// The engine's sentences about what it deliberately left alone.
|
||||
pub warnings: Vec<String>,
|
||||
/// One line the tool adds to the summary (`fix_lint`'s rules), if any.
|
||||
pub note: Option<String>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
@@ -96,27 +90,37 @@ fn apply_edits(text: &str, edits: &[TextEdit]) -> Result<String, String> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Check, then diff or write, then summarise. `dry_run` writes nothing.
|
||||
pub fn run(project: &Project, plan: Plan, dry_run: bool) -> Result<Answer, String> {
|
||||
/// What a plan came to on disk: the root-relative files rewritten and
|
||||
/// created, and those whose new text equals the old.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Written {
|
||||
pub changed: Vec<String>,
|
||||
pub created: Vec<String>,
|
||||
pub unchanged: Vec<String>,
|
||||
}
|
||||
|
||||
/// Check every target, then write every changed file, or nothing.
|
||||
pub fn run(project: &Project, plan: &Plan) -> Result<Written, String> {
|
||||
for change in &plan.changes {
|
||||
contained(project, change)?;
|
||||
}
|
||||
let mut moved: Vec<&Change> =
|
||||
plan.changes.iter().filter(|c| c.created || c.before != c.after).collect();
|
||||
moved.sort_by(|a, b| a.path.cmp(&b.path));
|
||||
let mut unchanged: Vec<String> = plan
|
||||
.changes
|
||||
.iter()
|
||||
.filter(|c| !c.created && c.before == c.after)
|
||||
.map(|c| project.relative(&c.path))
|
||||
.chain(plan.unchanged.iter().map(|path| project.relative(path)))
|
||||
.collect();
|
||||
unchanged.sort();
|
||||
let files: Vec<Written> = moved.iter().map(|change| Written::of(project, change)).collect();
|
||||
if !dry_run {
|
||||
commit(&moved, |path| project.relative(path))?;
|
||||
commit(&moved, |path| project.relative(path))?;
|
||||
let mut written = Written::default();
|
||||
for change in &plan.changes {
|
||||
let file = project.relative(&change.path);
|
||||
match (change.created, change.before == change.after) {
|
||||
(true, _) => written.created.push(file),
|
||||
(false, false) => written.changed.push(file),
|
||||
(false, true) => written.unchanged.push(file),
|
||||
}
|
||||
}
|
||||
Ok(summary(&files, &unchanged, &plan, dry_run))
|
||||
written.changed.sort();
|
||||
written.created.sort();
|
||||
written.unchanged.sort();
|
||||
Ok(written)
|
||||
}
|
||||
|
||||
/// A target must lie inside a root: an existing file resolves into one; a
|
||||
@@ -195,85 +199,6 @@ pub fn commit(changes: &[&Change], shown: impl Fn(&Path) -> String) -> Result<()
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One file of the summary: its name, its diff and the lines it moves.
|
||||
struct Written {
|
||||
file: String,
|
||||
created: bool,
|
||||
diff: String,
|
||||
added: usize,
|
||||
removed: usize,
|
||||
}
|
||||
|
||||
impl Written {
|
||||
fn of(project: &Project, change: &Change) -> Written {
|
||||
let file = project.relative(&change.path);
|
||||
let diff = unified(&file, &change.before, &change.after);
|
||||
// The two header lines are `---`/`+++`; every later line starting
|
||||
// with a sign is one line of the change.
|
||||
let body = diff.lines().skip(2);
|
||||
let added = body.clone().filter(|line| line.starts_with('+')).count();
|
||||
let removed = body.filter(|line| line.starts_with('-')).count();
|
||||
Written { file, created: change.created, diff, added, removed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The text and JSON an edit answers with.
|
||||
fn summary(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Answer {
|
||||
let created = files.iter().filter(|f| f.created).count();
|
||||
let mut text = if files.is_empty() {
|
||||
"unchanged\n".to_string()
|
||||
} else {
|
||||
let tail = if dry_run { " (dry run: nothing written)" } else { "" };
|
||||
format!("files: {} changed, {created} created{tail}\n", files.len() - created)
|
||||
};
|
||||
for file in files {
|
||||
let mark = if file.created { " (created)" } else { "" };
|
||||
text.push_str(&format!(" {} +{} -{}{mark}\n", file.file, file.added, file.removed));
|
||||
}
|
||||
if !unchanged.is_empty() && !files.is_empty() {
|
||||
text.push_str(&format!("unchanged: {}\n", unchanged.join(", ")));
|
||||
}
|
||||
if let Some(note) = &plan.note {
|
||||
text.push_str(note);
|
||||
text.push('\n');
|
||||
}
|
||||
push_warnings(&mut text, &plan.warnings);
|
||||
if dry_run {
|
||||
files.iter().for_each(|file| text.push_str(&file.diff));
|
||||
}
|
||||
Answer { text, structured: structured(files, unchanged, plan, dry_run) }
|
||||
}
|
||||
|
||||
fn push_warnings(text: &mut String, warnings: &[String]) {
|
||||
if warnings.is_empty() {
|
||||
return;
|
||||
}
|
||||
text.push_str("warnings:\n");
|
||||
for warning in warnings {
|
||||
text.push_str(&format!(" {warning}\n"));
|
||||
}
|
||||
}
|
||||
|
||||
fn structured(files: &[Written], unchanged: &[String], plan: &Plan, dry_run: bool) -> Value {
|
||||
let entry = |file: &Written| {
|
||||
let mut entry = json!({ "file": file.file, "added": file.added, "removed": file.removed });
|
||||
if dry_run {
|
||||
entry["diff"] = Value::from(file.diff.clone());
|
||||
}
|
||||
entry
|
||||
};
|
||||
let changed: Vec<Value> = files.iter().filter(|f| !f.created).map(entry).collect();
|
||||
let created: Vec<Value> = files.iter().filter(|f| f.created).map(entry).collect();
|
||||
json!({
|
||||
"changed": changed,
|
||||
"created": created,
|
||||
"unchanged": unchanged,
|
||||
"warnings": plan.warnings,
|
||||
"note": plan.note,
|
||||
"dry_run": dry_run,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -394,7 +319,7 @@ mod tests {
|
||||
};
|
||||
let refuse = |change: Change| {
|
||||
let plan = Plan { changes: vec![change], ..Plan::default() };
|
||||
run(&project, plan, false).err().unwrap()
|
||||
run(&project, &plan).err().unwrap()
|
||||
};
|
||||
let beside = refuse(create(outside.join("n.sv")));
|
||||
assert!(beside.contains("would be created outside every root"), "{beside}");
|
||||
|
||||
@@ -16,7 +16,7 @@ use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::defines::{collect_defines, DefineTable};
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
||||
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
|
||||
use vlog_semantic::{analyze, Semantics};
|
||||
|
||||
/// How many analyses are kept. An agent's calls cluster on a handful of
|
||||
/// files; a whole-design answer never needs a file's analysis at all.
|
||||
@@ -64,27 +64,6 @@ impl Analysis {
|
||||
Analysis { text, lines, tokens, defines, tree, diagnostics, semantics }
|
||||
}
|
||||
|
||||
/// The workspace overlay over this file's references, against `index` as
|
||||
/// it is now. Not cached: the index moves under an unchanged file.
|
||||
pub fn external(&self, index: &WorkspaceIndex) -> ExternalResolutions {
|
||||
resolve_external(&self.semantics, index)
|
||||
}
|
||||
|
||||
/// The token covering byte `offset`, if any.
|
||||
pub fn token_at(&self, offset: u32) -> Option<&Token> {
|
||||
let after = self.tokens.partition_point(|token| token.span.start <= offset);
|
||||
let token = self.tokens.get(after.checked_sub(1)?)?;
|
||||
token.span.contains(offset).then_some(token)
|
||||
}
|
||||
|
||||
/// The text of 1-based line `line`, without its line ending.
|
||||
pub fn line_text(&self, line: u32) -> &str {
|
||||
match self.lines.line_range(line) {
|
||||
Some(range) => self.slice(range.start, range.end).trim_end_matches('\r'),
|
||||
None => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// The 1-based first and last line a byte range covers. A range ending
|
||||
/// just after a newline ends on the line before it.
|
||||
pub fn line_span(&self, start: u32, end: u32) -> (u32, u32) {
|
||||
@@ -139,18 +118,13 @@ mod tests {
|
||||
assert_eq!(analysis.line_span(0, 10), (1, 1));
|
||||
assert_eq!(analysis.slice(0, 6), "module");
|
||||
assert!(analysis.diagnostics.is_empty());
|
||||
assert_eq!(analysis.line_text(2), "endmodule");
|
||||
assert_eq!(analysis.line_text(9), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_and_defines_are_kept_and_a_token_is_found_by_offset() {
|
||||
fn tokens_and_defines_are_kept() {
|
||||
let analysis = Analysis::of("`define W 8\r\nmodule a; endmodule\r\n".to_string());
|
||||
assert_eq!(analysis.defines.latest("W").map(|d| d.body.as_str()), Some("8"));
|
||||
assert_eq!(analysis.line_text(1), "`define W 8");
|
||||
let module = analysis.token_at(14).map(|t| t.text.as_str());
|
||||
assert_eq!(module, Some("module"));
|
||||
assert!(analysis.token_at(1000).is_none());
|
||||
assert!(analysis.tokens.iter().any(|t| t.text == "module"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -29,7 +29,7 @@ pub struct FileSet {
|
||||
pub files: Vec<PathBuf>,
|
||||
/// The filelist the set was read from, when it was.
|
||||
pub filelist: Option<PathBuf>,
|
||||
/// Problems worth one line each on stderr and in `project_overview`.
|
||||
/// Problems worth one line each (unreadable filelists, links leaving a root).
|
||||
pub warnings: Vec<String>,
|
||||
/// Walked files skipped for being over [`MAX_FILE_BYTES`].
|
||||
pub skipped_large: usize,
|
||||
|
||||
@@ -10,7 +10,6 @@ use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_semantic::{FileFacts, IndexBuilder, WorkspaceIndex};
|
||||
|
||||
use crate::cache::{self, Records, Reuse};
|
||||
@@ -41,8 +40,6 @@ pub struct Refresh {
|
||||
pub struct Project {
|
||||
roots: Vec<PathBuf>,
|
||||
filelist_arg: Option<PathBuf>,
|
||||
config: FileConfig,
|
||||
config_problem: Option<String>,
|
||||
files: BTreeMap<PathBuf, Stamp>,
|
||||
index: WorkspaceIndex,
|
||||
analyses: Analyses,
|
||||
@@ -99,12 +96,6 @@ impl Project {
|
||||
cache_dir: Option<PathBuf>,
|
||||
) -> Project {
|
||||
let started = Instant::now();
|
||||
let mut discovery = Discovery::new(true);
|
||||
let (config, config_problem) = match roots.first().map(|r| discovery.for_dir(r)) {
|
||||
Some(Ok(config)) => (config, None),
|
||||
Some(Err(problem)) => (FileConfig::default(), Some(problem)),
|
||||
None => (FileConfig::default(), None),
|
||||
};
|
||||
let walk = discover(&roots, filelist.as_deref());
|
||||
let mut records = cache_dir.as_deref().map(Records::load).unwrap_or_default();
|
||||
let loaded = load(&walk.files, &mut records);
|
||||
@@ -114,8 +105,6 @@ impl Project {
|
||||
Project {
|
||||
roots,
|
||||
filelist_arg: filelist,
|
||||
config,
|
||||
config_problem,
|
||||
files: loaded.files,
|
||||
index,
|
||||
analyses: Analyses::default(),
|
||||
@@ -264,22 +253,6 @@ impl Project {
|
||||
self.files.get(path)
|
||||
}
|
||||
|
||||
/// The config governing the first root, and the problem reading it.
|
||||
pub fn config(&self) -> (&FileConfig, Option<&str>) {
|
||||
(&self.config, self.config_problem.as_deref())
|
||||
}
|
||||
|
||||
/// The last discovery: its filelist, warnings and skipped files.
|
||||
pub fn discovery(&self) -> &FileSet {
|
||||
&self.walk
|
||||
}
|
||||
|
||||
/// Files discovery found but could not read as UTF-8 text.
|
||||
pub fn unreadable(&self) -> Vec<String> {
|
||||
let shown = |(path, why): &(PathBuf, String)| format!("{}: {why}", self.relative(path));
|
||||
self.unreadable.iter().map(shown).collect()
|
||||
}
|
||||
|
||||
/// Every discovered file the index does not hold, with why: over the
|
||||
/// size cap, or not UTF-8 text. An edit over the whole set must not
|
||||
/// pretend these were searched.
|
||||
|
||||
+61
-185
@@ -1,33 +1,14 @@
|
||||
//! The rendering rules every tool's text answer follows (PLAN §4.5): the
|
||||
//! The rendering rules every tool's text answer follows (PLAN §10.2): the
|
||||
//! token budget is the product.
|
||||
//!
|
||||
//! - paths are root-relative, and a file is named once per group of lines
|
||||
//! about it, never once per line;
|
||||
//! - lines and columns are 1-based, a position is `line:col`, a range is
|
||||
//! `first-last`;
|
||||
//! - lists are capped and open with their total — `N units`, or
|
||||
//! `N units (showing a–b)` when cut; a cut list also ends `… and N more`,
|
||||
//! and the caller can page with `offset`;
|
||||
//! - no prose and no markdown headings: a label is a bare word and a colon,
|
||||
//! a table only where the columns are fixed.
|
||||
//! - one line per fact, root-relative paths, `file:line`; a line range is
|
||||
//! `first–last`;
|
||||
//! - no headers, no blank lines, no trailing hints;
|
||||
//! - a fixed cap per tool, and one `… and N more` line when it cuts;
|
||||
//! - counts only where they are the answer.
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
/// How many entries a list answer holds unless the caller says otherwise.
|
||||
pub const DEFAULT_LIMIT: usize = 500;
|
||||
|
||||
/// What a list answer counts, singular then plural.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Noun(pub &'static str, pub &'static str);
|
||||
|
||||
impl Noun {
|
||||
/// `n` of this noun: `1 unit`, `3 units`.
|
||||
fn count(self, n: usize) -> String {
|
||||
format!("{n} {}", if n == 1 { self.0 } else { self.1 })
|
||||
}
|
||||
}
|
||||
|
||||
/// A declaration kind as one lower-case word — the keyword that declares it
|
||||
/// where there is one.
|
||||
pub fn kind(kind: SymbolKind) -> &'static str {
|
||||
@@ -61,7 +42,7 @@ pub fn kind(kind: SymbolKind) -> &'static str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every word [`kind`] can produce — what `read_item` accepts before a `:`.
|
||||
/// Every word [`kind`] can produce — what an item selector accepts before a `:`.
|
||||
const KIND_WORDS: &[&str] = &[
|
||||
"module",
|
||||
"interface",
|
||||
@@ -96,12 +77,12 @@ pub fn is_kind_word(word: &str) -> bool {
|
||||
KIND_WORDS.contains(&word)
|
||||
}
|
||||
|
||||
/// A line range as the answers print it: `12` or `12-40`.
|
||||
/// A line range as the answers print it: `12`, or `12–40`.
|
||||
pub fn lines(first: u32, last: u32) -> String {
|
||||
if first == last {
|
||||
first.to_string()
|
||||
} else {
|
||||
format!("{first}-{last}")
|
||||
format!("{first}–{last}")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -111,123 +92,53 @@ pub fn one_line(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
/// The window `offset..offset + limit` of a list, and how many entries
|
||||
/// follow it.
|
||||
pub fn page<T>(items: &[T], offset: usize, limit: usize) -> (&[T], usize) {
|
||||
let start = offset.min(items.len());
|
||||
let end = start.saturating_add(limit).min(items.len());
|
||||
(&items[start..end], items.len() - end)
|
||||
}
|
||||
|
||||
/// One page of a list: the entries shown, where they start, and how many
|
||||
/// the whole list holds.
|
||||
pub struct Page<'a, T> {
|
||||
pub shown: &'a [T],
|
||||
pub offset: usize,
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
impl<'a, T> Page<'a, T> {
|
||||
/// The window `offset..offset + limit` of `items`.
|
||||
pub fn of(items: &'a [T], offset: usize, limit: usize) -> Page<'a, T> {
|
||||
let (shown, _) = page(items, offset, limit);
|
||||
Page { shown, offset: offset.min(items.len()), total: items.len() }
|
||||
}
|
||||
|
||||
/// How many entries follow the page.
|
||||
pub fn rest(&self) -> usize {
|
||||
self.total - self.offset - self.shown.len()
|
||||
}
|
||||
|
||||
/// The line a list answer opens with: the total first, so an agent that
|
||||
/// stops reading when the list looks done still knows it was cut.
|
||||
pub fn header(&self, noun: Noun) -> String {
|
||||
let total = noun.count(self.total);
|
||||
if self.shown.len() == self.total {
|
||||
return format!("{total}\n");
|
||||
}
|
||||
match self.span() {
|
||||
Some((first, last)) if first == last => format!("{total} (showing {first})\n"),
|
||||
Some((first, last)) => format!("{total} (showing {first}–{last})\n"),
|
||||
None => format!("{total} (showing none: `offset` is past the end)\n"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The shown entries' 1-based positions, `[first, last]`; `[0, 0]` for
|
||||
/// an empty page.
|
||||
pub fn shown_json(&self) -> Value {
|
||||
let (first, last) = self.span().unwrap_or((0, 0));
|
||||
json!([first, last])
|
||||
}
|
||||
|
||||
fn span(&self) -> Option<(usize, usize)> {
|
||||
let first = self.offset + 1;
|
||||
(!self.shown.is_empty()).then(|| (first, self.offset + self.shown.len()))
|
||||
/// `n` of a noun whose plural adds `s`: `1 file`, `3 files`.
|
||||
pub fn count(n: usize, noun: &str) -> String {
|
||||
if n == 1 {
|
||||
format!("1 {noun}")
|
||||
} else {
|
||||
format!("{n} {noun}s")
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole text of a list the `in` path glob emptied.
|
||||
pub fn none_match(noun: Noun) -> String {
|
||||
format!("0 {} (none match `in`)\n", noun.1)
|
||||
/// `lines` cut at `cap`, ending with one `… and N more` line when cut.
|
||||
pub fn capped(mut lines: Vec<String>, cap: usize) -> Vec<String> {
|
||||
if lines.len() > cap {
|
||||
let rest = lines.len() - cap;
|
||||
lines.truncate(cap);
|
||||
lines.push(more(rest));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The line that says a list was cut, or nothing when it was not.
|
||||
pub fn more(out: &mut String, rest: usize) {
|
||||
if rest > 0 {
|
||||
out.push_str(&format!("… and {rest} more\n"));
|
||||
}
|
||||
/// The line that says how many entries a cut list left out.
|
||||
pub fn more(rest: usize) -> String {
|
||||
format!("… and {rest} more")
|
||||
}
|
||||
|
||||
/// Lines grouped under the file they are about: the file once, then each
|
||||
/// of its lines indented by two spaces. Entries arrive in any order; groups
|
||||
/// keep the order in which each file first appears.
|
||||
pub fn grouped(entries: &[(String, String)]) -> String {
|
||||
let mut order: Vec<&str> = Vec::new();
|
||||
for (file, _) in entries {
|
||||
if !order.contains(&file.as_str()) {
|
||||
order.push(file);
|
||||
/// Sites grouped one file per line, `file:12,40,41`: files in the order
|
||||
/// each first appears, each line once, in the order given.
|
||||
pub fn by_file(sites: &[(String, u32)]) -> Vec<String> {
|
||||
let mut grouped: Vec<(&str, Vec<u32>)> = Vec::new();
|
||||
for (file, line) in sites {
|
||||
match grouped.iter_mut().find(|(held, _)| held == file) {
|
||||
Some((_, lines)) if lines.contains(line) => {}
|
||||
Some((_, lines)) => lines.push(*line),
|
||||
None => grouped.push((file, vec![*line])),
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for file in order {
|
||||
out.push_str(file);
|
||||
out.push('\n');
|
||||
for (_, line) in entries.iter().filter(|(f, _)| f == file) {
|
||||
out.push_str(" ");
|
||||
out.push_str(line);
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
out
|
||||
grouped
|
||||
.into_iter()
|
||||
.map(|(file, lines)| {
|
||||
let lines: Vec<String> = lines.iter().map(u32::to_string).collect();
|
||||
format!("{file}:{}", lines.join(","))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rows whose columns are padded to line up, the last column left ragged.
|
||||
pub fn table(rows: &[Vec<String>]) -> String {
|
||||
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let mut widths = vec![0; columns];
|
||||
for row in rows {
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
widths[at] = widths[at].max(cell.chars().count());
|
||||
}
|
||||
}
|
||||
let mut out = String::new();
|
||||
for row in rows {
|
||||
let mut line = String::new();
|
||||
for (at, cell) in row.iter().enumerate() {
|
||||
if at + 1 < row.len() {
|
||||
// A column that is empty in every row takes no space at all.
|
||||
if widths[at] > 0 {
|
||||
line.push_str(&format!("{cell:<width$} ", width = widths[at]));
|
||||
}
|
||||
} else {
|
||||
line.push_str(cell);
|
||||
}
|
||||
}
|
||||
out.push_str(" ");
|
||||
out.push_str(line.trim_end());
|
||||
out.push('\n');
|
||||
}
|
||||
out
|
||||
/// One `warning: …` line per sentence an engine or the write path said.
|
||||
pub fn warnings(out: &mut Vec<String>, warnings: &[String]) {
|
||||
out.extend(warnings.iter().map(|warning| format!("warning: {}", one_line(warning))));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -275,57 +186,22 @@ mod tests {
|
||||
#[test]
|
||||
fn a_range_of_one_line_is_one_number() {
|
||||
assert_eq!(lines(3, 3), "3");
|
||||
assert_eq!(lines(3, 9), "3-9");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_says_how_many_entries_follow_it() {
|
||||
let items = [1, 2, 3, 4, 5];
|
||||
assert_eq!(page(&items, 1, 2), (&items[1..3], 2));
|
||||
assert_eq!(page(&items, 9, 2), (&items[5..5], 0));
|
||||
let mut out = String::new();
|
||||
more(&mut out, 2);
|
||||
more(&mut out, 0);
|
||||
assert_eq!(out, "… and 2 more\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_opens_with_its_total_and_the_window_it_shows() {
|
||||
const UNITS: Noun = Noun("unit", "units");
|
||||
let items: Vec<usize> = (0..77).collect();
|
||||
let cut = Page::of(&items, 0, 50);
|
||||
assert_eq!(cut.header(UNITS), "77 units (showing 1–50)\n");
|
||||
assert_eq!((cut.rest(), cut.shown_json()), (27, json!([1, 50])));
|
||||
let last = Page::of(&items, 50, 50);
|
||||
assert_eq!(last.header(UNITS), "77 units (showing 51–77)\n");
|
||||
assert_eq!(last.rest(), 0);
|
||||
assert_eq!(Page::of(&items, 76, 5).header(UNITS), "77 units (showing 77)\n");
|
||||
let whole = Page::of(&items[..1], 0, 50);
|
||||
assert_eq!(whole.header(UNITS), "1 unit\n");
|
||||
let past = Page::of(&items, 90, 5);
|
||||
assert_eq!(past.header(UNITS), "77 units (showing none: `offset` is past the end)\n");
|
||||
assert_eq!((past.rest(), past.shown_json()), (0, json!([0, 0])));
|
||||
assert_eq!(Page::of(&items[..0], 0, 5).header(UNITS), "0 units\n");
|
||||
assert_eq!(none_match(UNITS), "0 units (none match `in`)\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_is_named_once_per_group() {
|
||||
let entries = vec![
|
||||
("b.sv".to_string(), "module b 1".to_string()),
|
||||
("a.sv".to_string(), "module a 1".to_string()),
|
||||
("b.sv".to_string(), "module c 9".to_string()),
|
||||
];
|
||||
assert_eq!(grouped(&entries), "b.sv\n module b 1\n module c 9\na.sv\n module a 1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn table_columns_line_up_and_empty_columns_vanish() {
|
||||
let rows = vec![
|
||||
vec!["input".into(), "".into(), "logic".into(), "clk".into()],
|
||||
vec!["output".into(), "".into(), "logic [7:0]".into(), "q".into()],
|
||||
];
|
||||
assert_eq!(table(&rows), " input logic clk\n output logic [7:0] q\n");
|
||||
assert_eq!(lines(3, 9), "3–9");
|
||||
assert_eq!(one_line("a\n b\t c "), "a b c");
|
||||
assert_eq!((count(1, "file"), count(0, "site")), ("1 file".into(), "0 sites".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cut_list_ends_with_one_more_line() {
|
||||
let all: Vec<String> = (0..5).map(|n| n.to_string()).collect();
|
||||
assert_eq!(capped(all.clone(), 3), ["0", "1", "2", "… and 2 more"]);
|
||||
assert_eq!(capped(all.clone(), 5), all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sites_are_grouped_one_file_per_line() {
|
||||
let sites = [("b.sv", 3), ("a.sv", 1), ("b.sv", 9), ("b.sv", 3)];
|
||||
let sites: Vec<(String, u32)> = sites.iter().map(|(f, l)| (f.to_string(), *l)).collect();
|
||||
assert_eq!(by_file(&sites), ["b.sv:3,9", "a.sv:1"]);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The `lucisv://` resources: the project overview, the lint rule
|
||||
//! reference, one unit's interface and one file's outline — the same answers
|
||||
//! the read tools give, addressable by URI for a host that attaches context
|
||||
//! rather than calling tools.
|
||||
//! reference, one unit's outline and one file's outline — the same answers
|
||||
//! `hierarchy` and `outline` give, addressable by URI for a host that
|
||||
//! attaches context rather than calling tools.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
@@ -23,7 +23,7 @@ pub fn list() -> Value {
|
||||
"uri": "lucisv://overview",
|
||||
"name": "overview",
|
||||
"title": "Project overview",
|
||||
"description": "Files, units by kind, top-level modules and largest files of the indexed project.",
|
||||
"description": "File and module counts and the top-level modules, as hierarchy without a root answers.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
{
|
||||
@@ -42,8 +42,8 @@ pub fn templates() -> Value {
|
||||
{
|
||||
"uriTemplate": "lucisv://unit/{name}",
|
||||
"name": "unit",
|
||||
"title": "Unit interface",
|
||||
"description": "A module's or interface's parameters, ports and instantiation template; a package's or class's members.",
|
||||
"title": "Unit outline",
|
||||
"description": "A unit's file:line, parameters and ports (modports, package members), as outline unit answers.",
|
||||
"mimeType": "text/plain",
|
||||
},
|
||||
{
|
||||
@@ -78,7 +78,8 @@ impl Resource {
|
||||
!matches!(self, Resource::Rules)
|
||||
}
|
||||
|
||||
/// Whether answering walks the roots first, as `project_overview` does.
|
||||
/// Whether answering walks the roots first, as `hierarchy` without a
|
||||
/// root does.
|
||||
pub fn rewalk(&self) -> bool {
|
||||
matches!(self, Resource::Overview)
|
||||
}
|
||||
@@ -87,16 +88,11 @@ impl Resource {
|
||||
pub fn read(&self, uri: &str, project: Option<&mut Project>) -> Result<Value, String> {
|
||||
let (mime, text) = match (self, project) {
|
||||
(Resource::Rules, _) => ("text/markdown", vlog_linter::rules_markdown()),
|
||||
(Resource::Overview, Some(project)) => {
|
||||
("text/plain", run(project, "project_overview", None)?)
|
||||
}
|
||||
(Resource::Overview, Some(project)) => ("text/plain", run(project, "hierarchy", None)?),
|
||||
(Resource::Unit(name), Some(project)) => {
|
||||
// A URI has no `file` argument to pick among declarations.
|
||||
let text = run(project, "unit_interface", Some(("name", name))).map_err(|why| {
|
||||
why.replace(
|
||||
"pass `file` to pick one",
|
||||
"call the unit_interface tool with its file argument to pick one",
|
||||
)
|
||||
// A URI has no argument to pick among declarations.
|
||||
let text = run(project, "outline", Some(("unit", name))).map_err(|why| {
|
||||
why.replace("outline one `file` instead", "read one file's outline resource")
|
||||
})?;
|
||||
("text/plain", text)
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ const NOT_INITIALIZED: i64 = -32002;
|
||||
/// MCP's "resource not found".
|
||||
const RESOURCE_NOT_FOUND: i64 = -32002;
|
||||
|
||||
/// What the agent is told once, at `initialize`.
|
||||
const INSTRUCTIONS: &str = "lucisv-mcp reads and edits the SystemVerilog design under its roots, from disk, never unsaved buffers. Read less: unit_interface gives a module's ports, outline a file's declarations, read_item one item; list_units, search_symbols, definition, references and hierarchy find the rest; `in` filters by path glob. Who instantiates module X: hierarchy direction up (overrides: true adds #(…)), not references. Every edit is verified, all-or-nothing, straight to disk, and names files for diagnostics; dry_run: true shows the diff first. One item: replace_item, insert_item, delete_item. Design-wide: rename, add_port, remove_port and other refactorings; format, fix_lint. rename, references and the port edits list the name's unresolved mentions (strings, comments, macro text) to check. A position: file + line (+ col or name). Paths are relative to a root; lines are 1-based, columns 1-based bytes.";
|
||||
/// What the agent is told once, at `initialize` (PLAN §10.3, ≤ 400 bytes).
|
||||
const 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.";
|
||||
|
||||
/// A JSON-RPC error object.
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -324,7 +324,6 @@ fn tool_result(answer: Result<tools::Answer, String>) -> Value {
|
||||
match answer {
|
||||
Ok(answer) => json!({
|
||||
"content": [{ "type": "text", "text": answer.text }],
|
||||
"structuredContent": answer.structured,
|
||||
"isError": false,
|
||||
}),
|
||||
Err(refusal) => json!({
|
||||
@@ -346,6 +345,11 @@ mod tests {
|
||||
reply["error"]["code"].as_i64().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_instructions_stay_under_400_bytes() {
|
||||
assert!(INSTRUCTIONS.len() <= 400, "{}", INSTRUCTIONS.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handshake_echoes_a_known_revision_and_offers_the_newest_otherwise() {
|
||||
let mut s = server();
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! The declarations the files' own symbol tables hold — every one the
|
||||
//! semantic model knows and `outline` lists: typedefs, enum values,
|
||||
//! functions, tasks, genvars, generate blocks and what they declare,
|
||||
//! procedural locals, beside the ports, nets and variables the index also
|
||||
//! records. The index's word census narrows the files read: a file that
|
||||
//! declares a name writes it. One table for `find` (an exact name) and for
|
||||
//! its near matches (a part of a name), so both see the same set.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use super::read_item::child_items;
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
/// Which names the table is asked for.
|
||||
pub enum Wanted<'a> {
|
||||
/// Exactly this name.
|
||||
Exact(&'a str),
|
||||
/// Every name containing this part, any case (already lower-cased).
|
||||
Containing(String),
|
||||
}
|
||||
|
||||
impl Wanted<'_> {
|
||||
fn accepts(&self, name: &str) -> bool {
|
||||
match self {
|
||||
Wanted::Exact(wanted) => name == *wanted,
|
||||
Wanted::Containing(part) => name.to_ascii_lowercase().contains(part.as_str()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a file's sorted word census holds a wanted name.
|
||||
fn in_census(&self, words: &[String]) -> bool {
|
||||
match self {
|
||||
Wanted::Exact(wanted) => words.binary_search_by(|w| w.as_str().cmp(wanted)).is_ok(),
|
||||
Wanted::Containing(_) => words.iter().any(|word| self.accepts(word)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One declaration read off a file's own symbol table.
|
||||
pub struct Local {
|
||||
pub path: PathBuf,
|
||||
pub name: String,
|
||||
pub kind: &'static str,
|
||||
/// The byte offset of the name itself.
|
||||
pub offset: u32,
|
||||
/// The line shown: the completing declaration's for a non-ANSI port.
|
||||
pub line: u32,
|
||||
/// The module, interface, package or class the declaration is inside.
|
||||
pub unit: Option<String>,
|
||||
}
|
||||
|
||||
/// Every declaration whose name `wanted` accepts, in every indexed file
|
||||
/// whose words hold such a name, read from disk now.
|
||||
pub fn declared(project: &Project, wanted: &Wanted) -> Vec<Local> {
|
||||
let mut out = Vec::new();
|
||||
for (path, _) in project.files() {
|
||||
let census = project.index().facts_for(path).map(|facts| facts.words());
|
||||
if !census.is_some_and(|words| wanted.in_census(words)) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
let analysis = Analysis::of(text);
|
||||
for symbol in analysis.semantics.symbols().iter().filter(|s| wanted.accepts(&s.name)) {
|
||||
let shown = symbol.detail_span.unwrap_or(symbol.name_span);
|
||||
let offset = symbol.name_span.start;
|
||||
out.push(Local {
|
||||
path: path.clone(),
|
||||
name: symbol.name.clone(),
|
||||
kind: render::kind(symbol.kind),
|
||||
offset,
|
||||
line: analysis.lines.line_col(shown.start).0,
|
||||
unit: unit_at(&analysis.tree.items, symbol.name_span).map(str::to_string),
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The innermost module, interface, package or class whose item holds
|
||||
/// `span`, other than one `span` names.
|
||||
fn unit_at(items: &[Item], span: TextRange) -> Option<&str> {
|
||||
let item =
|
||||
items.iter().find(|item| item.span.start <= span.start && span.end <= item.span.end)?;
|
||||
let own = match &item.kind {
|
||||
ItemKind::Module(module) => Some((module.name.as_str(), module.name_span)),
|
||||
ItemKind::Package { name, name_span, .. } => Some((name.as_str(), *name_span)),
|
||||
ItemKind::Class(class) => Some((class.name.as_str(), class.name_span)),
|
||||
_ => None,
|
||||
};
|
||||
let inner = child_items(&item.kind).into_iter().find_map(|items| unit_at(items, span));
|
||||
inner.or(own.filter(|(_, name_span)| *name_span != span).map(|(name, _)| name))
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
//! `defines`: the `` `define`` table — one file's, one macro's every
|
||||
//! definition across the project, or the whole project's — without reading
|
||||
//! the files. Bookkeeping only, like `vlog_parser::defines`: nothing here
|
||||
//! expands a macro (the README says why the one-step expansion is not
|
||||
//! offered).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::defines::{Define, DefineKind};
|
||||
|
||||
use super::read::{only_in, IN};
|
||||
use super::source::{self, Texts};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
|
||||
|
||||
const DEFINES_NOUN: Noun = Noun("define", "defines");
|
||||
|
||||
/// A body longer than this many characters is cut, with `…`.
|
||||
const BODY_CAP: usize = 200;
|
||||
|
||||
pub const DEFINES: Tool = Tool {
|
||||
name: "defines",
|
||||
title: "Macro definitions",
|
||||
description:
|
||||
"The `define table (name, parameters, body, file:line) of a `file`, a macro `name`, or all.",
|
||||
params: &[
|
||||
Param { name: "file", ty: Ty::Str, required: false, description: "Only this file." },
|
||||
Param { name: "name", ty: Ty::Str, required: false, description: "Only this macro." },
|
||||
IN,
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Default 500.",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: defines,
|
||||
};
|
||||
|
||||
/// One table row, ready to render.
|
||||
struct Row {
|
||||
file: String,
|
||||
line: u32,
|
||||
define: Define,
|
||||
}
|
||||
|
||||
fn defines(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").map(|name| name.trim_start_matches('`')).filter(|n| !n.is_empty());
|
||||
let (rows, listing) = match args.str("file") {
|
||||
Some(file) => in_file(project, file, name, args)?,
|
||||
None => {
|
||||
let select = |project: &Project| {
|
||||
only_in(args, indexed(project, name), |(path, _)| project.relative(path))
|
||||
};
|
||||
let (mut all, mut emptied) = select(project);
|
||||
if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() {
|
||||
(all, emptied) = select(project);
|
||||
}
|
||||
let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
(rows_of(project, page.shown), Listing::of(&page, emptied))
|
||||
}
|
||||
};
|
||||
let entries: Vec<(String, String)> = rows
|
||||
.iter()
|
||||
.map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define))))
|
||||
.collect();
|
||||
let mut text = listing.header.clone();
|
||||
text.push_str(&render::grouped(&entries));
|
||||
render::more(&mut text, listing.rest);
|
||||
if listing.total == 0 {
|
||||
text =
|
||||
if listing.emptied { render::none_match(DEFINES_NOUN) } else { "no defines\n".into() };
|
||||
}
|
||||
let listed: Vec<Value> = rows.iter().map(row_json).collect();
|
||||
let structured = json!({ "defines": listed, "total": listing.total, "shown": listing.shown });
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// What an answer says about the page it shows, taken off a [`Page`] of
|
||||
/// either form's list.
|
||||
struct Listing {
|
||||
header: String,
|
||||
rest: usize,
|
||||
total: usize,
|
||||
shown: Value,
|
||||
emptied: bool,
|
||||
}
|
||||
|
||||
impl Listing {
|
||||
fn of<T>(page: &Page<T>, emptied: bool) -> Listing {
|
||||
Listing {
|
||||
header: page.header(DEFINES_NOUN),
|
||||
rest: page.rest(),
|
||||
total: page.total,
|
||||
shown: page.shown_json(),
|
||||
emptied,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One file's table as it is on disk now, filtered by `name`.
|
||||
fn in_file(
|
||||
project: &mut Project,
|
||||
file: &str,
|
||||
name: Option<&str>,
|
||||
args: &Args,
|
||||
) -> Result<(Vec<Row>, Listing), String> {
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let shown_file = project.relative(&path);
|
||||
let all: Vec<&Define> = analysis
|
||||
.defines
|
||||
.entries()
|
||||
.iter()
|
||||
.filter(|define| name.is_none_or(|name| define.name == name))
|
||||
.collect();
|
||||
let (all, emptied) = only_in(args, all, |_| shown_file.clone());
|
||||
let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let rows = page
|
||||
.shown
|
||||
.iter()
|
||||
.map(|define| Row {
|
||||
file: shown_file.clone(),
|
||||
line: analysis.lines.line_col(define.span.start).0,
|
||||
define: (*define).clone(),
|
||||
})
|
||||
.collect();
|
||||
Ok((rows, Listing::of(&page, emptied)))
|
||||
}
|
||||
|
||||
/// Every indexed definition (of `name`, when given), in file order.
|
||||
fn indexed(project: &Project, name: Option<&str>) -> Vec<(PathBuf, Define)> {
|
||||
let index = project.index();
|
||||
let of =
|
||||
|file, define: &Define| index.path(file).map(|path| (path.to_path_buf(), define.clone()));
|
||||
match name {
|
||||
Some(name) => index.find_define(name).into_iter().filter_map(|(f, d)| of(f, d)).collect(),
|
||||
None => (0..index.files().len() as u32)
|
||||
.map(vlog_semantic::FileId)
|
||||
.flat_map(|file| {
|
||||
let entries = index.defines(file).map(|table| table.entries()).unwrap_or(&[]);
|
||||
entries
|
||||
.iter()
|
||||
.filter(|d| d.kind == DefineKind::Define)
|
||||
.filter_map(move |d| of(file, d))
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows for indexed definitions, each line read off its file now; a
|
||||
/// definition whose file no longer spells its name there is omitted.
|
||||
fn rows_of(project: &Project, shown: &[(PathBuf, Define)]) -> Vec<Row> {
|
||||
let mut texts = Texts::default();
|
||||
shown
|
||||
.iter()
|
||||
.filter_map(|(path, define)| {
|
||||
let line = checked_line(&mut texts, path, define)?;
|
||||
Some(Row { file: project.relative(path), line, define: define.clone() })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn checked_line(texts: &mut Texts, path: &Path, define: &Define) -> Option<u32> {
|
||||
let (text, lines) = texts.get(path)?;
|
||||
let spelled = text.get(define.name_span.as_range())?;
|
||||
(spelled == define.name).then(|| lines.line_col(define.span.start).0)
|
||||
}
|
||||
|
||||
/// A definition as one line: `` `define NAME(a, b) body``, the body capped.
|
||||
fn spelled(define: &Define) -> String {
|
||||
if define.kind == DefineKind::Undef {
|
||||
return format!("`undef {}", define.name);
|
||||
}
|
||||
let mut out = format!("`define {}", define.name);
|
||||
if let Some(params) = &define.params {
|
||||
out.push_str(&format!("({})", params.join(", ")));
|
||||
}
|
||||
let body = source::capped(&define.body, BODY_CAP);
|
||||
if !body.is_empty() {
|
||||
out.push(' ');
|
||||
out.push_str(&body);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn row_json(row: &Row) -> Value {
|
||||
let define = &row.define;
|
||||
json!({
|
||||
"file": row.file,
|
||||
"line": row.line,
|
||||
"name": define.name,
|
||||
"kind": if define.kind == DefineKind::Undef { "undef" } else { "define" },
|
||||
"params": define.params,
|
||||
"body": source::capped(&define.body, BODY_CAP),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vlog_parser::defines::collect_defines;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
fn table(text: &str) -> Vec<Define> {
|
||||
collect_defines(&tokenize(text).unwrap()).entries().to_vec()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_definition_is_spelled_on_one_line_with_its_parameters() {
|
||||
let all = table("`define ADD(a, b = 1) \\\n ((a) + (b))\n`define W 8\n`undef W\n");
|
||||
assert_eq!(spelled(&all[0]), "`define ADD(a, b = 1) ((a) + (b))");
|
||||
assert_eq!(spelled(&all[1]), "`define W 8");
|
||||
assert_eq!(spelled(&all[2]), "`undef W");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_body_is_cut_at_the_cap() {
|
||||
let body = "x ".repeat(300);
|
||||
let cut = source::capped(&body, BODY_CAP);
|
||||
assert_eq!(cut.chars().count(), BODY_CAP + 1);
|
||||
assert!(cut.ends_with('…'));
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,13 @@
|
||||
//! `diagnostics`: what `lucisv check` would say about one file or the whole
|
||||
//! project — the tolerant parse's errors first, then the lint findings —
|
||||
//! with the CLI's JSON field names, so one contract serves CI and agents.
|
||||
//! `check`: what `lucisv check` would say about one file or the whole
|
||||
//! design — the tolerant parse's errors, then the lint findings — one line
|
||||
//! each, `file:line:col severity message [rule]`, errors first.
|
||||
//!
|
||||
//! The lint run is the CLI's, rung for rung: the `lucisv.toml` governing each
|
||||
//! file (`Discovery::for_file`) gives `[lint] select`/`ignore`, the
|
||||
//! `[lint.<rule>]` options, the external `waivers` and the formatter's line
|
||||
//! length; the `rules` argument replaces `select` as `--select` does; the
|
||||
//! workspace rules run, their questions answered by the project index
|
||||
//! ([`Mentions`]). Missing-closer warnings are the language server's own
|
||||
//! (`pairs.rs`, not a library) and are not offered.
|
||||
//! length; the workspace rules run, their questions answered by the project
|
||||
//! index ([`Mentions`]). Missing-closer warnings are the language server's
|
||||
//! own (`pairs.rs`, not a library) and are not offered.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
@@ -16,7 +15,6 @@ use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use serde_json::{json, Value};
|
||||
use vlog_linter::{
|
||||
lint_with, select_rules, Exports, ExternalWaivers, LintContext, MentionOracle, ModuleInterface,
|
||||
Rule, RuleOptions, Violation, WaiverUse,
|
||||
@@ -24,63 +22,28 @@ use vlog_linter::{
|
||||
use vlog_parser::LineIndex;
|
||||
use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::read::{in_glob, only_in, path_match, IN};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
|
||||
use crate::render;
|
||||
|
||||
pub const DIAGNOSTICS: Tool = Tool {
|
||||
name: "diagnostics",
|
||||
title: "Diagnostics",
|
||||
description:
|
||||
"Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "One file (default: all).",
|
||||
},
|
||||
Param {
|
||||
name: "rules",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Rules or severities to run.",
|
||||
},
|
||||
Param {
|
||||
name: "severity",
|
||||
ty: Ty::Enum(&["error", "warning", "style"]),
|
||||
required: false,
|
||||
description: "Only this severity.",
|
||||
},
|
||||
IN,
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Default 500.",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Findings to skip.",
|
||||
},
|
||||
],
|
||||
/// The most findings an answer lists before `… and N more`.
|
||||
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.",
|
||||
params: &[Param { name: "file", ty: Ty::Str, required: false }],
|
||||
rewalk: false,
|
||||
handler: diagnostics,
|
||||
handler: check,
|
||||
};
|
||||
|
||||
/// One finding, in the CLI's JSON shape.
|
||||
/// One finding: where, how bad, what, and which rule.
|
||||
struct Finding {
|
||||
file: String,
|
||||
rule: String,
|
||||
severity: &'static str,
|
||||
message: String,
|
||||
start: (u32, u32),
|
||||
end: (u32, u32),
|
||||
range: (u32, u32),
|
||||
fix: Value,
|
||||
}
|
||||
|
||||
/// What one config file makes of a lint run.
|
||||
@@ -94,39 +57,48 @@ pub(super) struct Run {
|
||||
used: RefCell<WaiverUse>,
|
||||
}
|
||||
|
||||
fn diagnostics(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
|
||||
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
|
||||
});
|
||||
let mut runs = Runs::new(selected);
|
||||
let (mut findings, no_file) = match args.str("file") {
|
||||
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)?, false)
|
||||
file_findings(project, &mut runs, &path, &analysis, &oracle)?
|
||||
}
|
||||
None => project_findings(project, &mut runs, in_glob(args))?,
|
||||
None => project_findings(project, &mut runs)?,
|
||||
};
|
||||
if let Some(severity) = args.str("severity") {
|
||||
findings.retain(|finding| finding.severity == severity);
|
||||
if findings.is_empty() {
|
||||
return Ok(Answer::lines(vec!["ok".to_string()]));
|
||||
}
|
||||
let (findings, emptied) = only_in(args, findings, |finding| finding.file.clone());
|
||||
Ok(render_findings(&findings, no_file || emptied, args))
|
||||
// Errors first, then warnings, then the rest; each file's order within.
|
||||
findings.sort_by_key(|finding| severity_rank(finding.severity));
|
||||
let lines = findings.iter().map(Finding::render).collect();
|
||||
Ok(Answer::lines(render::capped(lines, CAP)))
|
||||
}
|
||||
|
||||
/// Every indexed file's findings — only the files the `in` glob keeps, when
|
||||
/// one is given — and whether the glob kept no file at all.
|
||||
fn project_findings(
|
||||
project: &Project,
|
||||
runs: &mut Runs,
|
||||
glob: Option<&str>,
|
||||
) -> Result<(Vec<Finding>, bool), String> {
|
||||
fn severity_rank(severity: &str) -> u8 {
|
||||
match severity {
|
||||
"error" => 0,
|
||||
"warning" => 1,
|
||||
_ => 2,
|
||||
}
|
||||
}
|
||||
|
||||
impl Finding {
|
||||
/// `file:line:col severity message [rule]`.
|
||||
fn render(&self) -> String {
|
||||
let (line, col) = self.start;
|
||||
let message = render::one_line(&self.message);
|
||||
format!("{}:{line}:{col} {} {message} [{}]", self.file, self.severity, self.rule)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 all: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
|
||||
let kept = |path: &PathBuf| glob.is_none_or(|glob| path_match(glob, &project.relative(path)));
|
||||
let paths: Vec<PathBuf> = all.iter().filter(|path| kept(path)).cloned().collect();
|
||||
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
|
||||
let mut findings = Vec::new();
|
||||
for path in &paths {
|
||||
let Ok(text) = std::fs::read_to_string(path) else { continue };
|
||||
@@ -135,26 +107,23 @@ fn project_findings(
|
||||
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: a filtered run
|
||||
// does not say so.
|
||||
if glob.is_none() {
|
||||
findings.extend(runs.unused_waivers(project));
|
||||
}
|
||||
Ok((findings, paths.is_empty() && !all.is_empty()))
|
||||
// Only a complete run knows a waiver matched nothing.
|
||||
findings.extend(runs.unused_waivers(project));
|
||||
Ok(findings)
|
||||
}
|
||||
|
||||
/// The runs met so far in one call, one per governing config file — shared
|
||||
/// with `fix_lint`, so a fix runs under exactly the rules a finding came from.
|
||||
/// with `format`'s `fix`, so a fix runs under exactly the rules a finding
|
||||
/// came from.
|
||||
pub(super) struct Runs {
|
||||
discovery: Discovery,
|
||||
held: BTreeMap<Option<PathBuf>, Rc<Run>>,
|
||||
selected: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Runs {
|
||||
/// No run built yet; `selected` replaces each config's `[lint] select`.
|
||||
pub(super) fn new(selected: Option<Vec<String>>) -> Runs {
|
||||
Runs { discovery: Discovery::new(true), held: BTreeMap::new(), selected }
|
||||
/// No run built yet.
|
||||
pub(super) fn new() -> Runs {
|
||||
Runs { discovery: Discovery::new(true), held: BTreeMap::new() }
|
||||
}
|
||||
|
||||
/// The run for the config governing `path`, built on first use. A config
|
||||
@@ -171,10 +140,7 @@ impl Runs {
|
||||
}
|
||||
|
||||
fn build(&self, config: &FileConfig) -> Result<Run, String> {
|
||||
let select = match &self.selected {
|
||||
Some(selected) => selected.clone(),
|
||||
None => config.lint_select.clone().unwrap_or_default(),
|
||||
};
|
||||
let select = config.lint_select.clone().unwrap_or_default();
|
||||
let ignore = config.lint_ignore.clone().unwrap_or_default();
|
||||
let rules = select_rules(&select, &ignore, true)?;
|
||||
let mut options = RuleOptions::new();
|
||||
@@ -243,9 +209,6 @@ fn file_findings(
|
||||
severity: "error",
|
||||
message: error.message.clone(),
|
||||
start: (error.line, error.col),
|
||||
end: analysis.lines.line_col(error.span.end),
|
||||
range: (error.span.start, error.span.end),
|
||||
fix: Value::Null,
|
||||
})
|
||||
.collect();
|
||||
let violations = violations(&run, path, analysis, oracle);
|
||||
@@ -278,65 +241,15 @@ pub(super) fn violations(
|
||||
}
|
||||
|
||||
fn lint_finding(file: &str, lines: &LineIndex, violation: &Violation) -> Finding {
|
||||
let span = violation.span;
|
||||
let fix = violation.fix.as_ref().map_or(Value::Null, |fix| {
|
||||
let edits: Vec<Value> = fix
|
||||
.edits
|
||||
.iter()
|
||||
.map(|(range, content)| json!({"start": range.start, "end": range.end, "content": content}))
|
||||
.collect();
|
||||
json!({ "applicability": fix.applicability.as_str(), "edits": edits })
|
||||
});
|
||||
Finding {
|
||||
file: file.to_string(),
|
||||
rule: violation.rule.to_string(),
|
||||
severity: violation.severity.as_str(),
|
||||
message: violation.message.clone(),
|
||||
start: lines.line_col(span.start),
|
||||
end: lines.line_col(span.end),
|
||||
range: (span.start, span.end),
|
||||
fix,
|
||||
start: lines.line_col(violation.span.start),
|
||||
}
|
||||
}
|
||||
|
||||
const FINDINGS: Noun = Noun("finding", "findings");
|
||||
|
||||
/// Findings grouped by file, paged; the JSON is the CLI's array shape.
|
||||
/// `emptied` when the `in` glob removed everything there was.
|
||||
fn render_findings(findings: &[Finding], emptied: bool, args: &Args) -> Answer {
|
||||
let page = Page::of(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let shown = page.shown;
|
||||
let entries: Vec<(String, String)> = shown
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let line =
|
||||
format!("{}:{} {} {} [{}]", f.start.0, f.start.1, f.severity, f.message, f.rule);
|
||||
(f.file.clone(), line)
|
||||
})
|
||||
.collect();
|
||||
let mut text = page.header(FINDINGS);
|
||||
text.push_str(&render::grouped(&entries));
|
||||
render::more(&mut text, page.rest());
|
||||
if findings.is_empty() {
|
||||
text = if emptied { render::none_match(FINDINGS) } else { "no findings\n".to_string() };
|
||||
}
|
||||
let listed: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|f| {
|
||||
json!({
|
||||
"filename": f.file, "rule": f.rule, "severity": f.severity, "message": f.message,
|
||||
"location": {"line": f.start.0, "column": f.start.1},
|
||||
"end_location": {"line": f.end.0, "column": f.end.1},
|
||||
"range": {"start": f.range.0, "end": f.range.1},
|
||||
"fix": f.fix,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let total = findings.len();
|
||||
let structured = json!({ "diagnostics": listed, "total": total, "shown": page.shown_json() });
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
/// How many files write each word, and the first of them — the whole-project
|
||||
/// form's answer to "does another file mention this", built once per call
|
||||
/// instead of walking every record per question.
|
||||
|
||||
+105
-325
@@ -1,17 +1,14 @@
|
||||
//! The refactorings that act at one position — `rename`, and the six the
|
||||
//! editor offers as code actions at a cursor (`expand_wildcard`,
|
||||
//! `convert_ports`, `organize_imports`, `inline_module`, `propagate_ports`,
|
||||
//! `remove_port`) — plus what every edit tool shares: the `dry_run`
|
||||
//! argument, the whole-set read the engines are handed, and the step from a
|
||||
//! verified `RefactorEdit` to `apply::run`.
|
||||
//! `rename`, and what every design-wide edit shares: the whole-set read the
|
||||
//! engines are handed, and the step from a verified `RefactorEdit` to a
|
||||
//! written plan with the name's unresolved mentions listed.
|
||||
//!
|
||||
//! Each engine gets **every indexed file**, read from disk at call time
|
||||
//! (`source::WholeSet`, M2's ruling for `references`: a use can resolve
|
||||
//! through a file that never spells its name, so no narrowing is sound).
|
||||
//! The texts read are the texts the write-freshness rule compares against.
|
||||
//! A file the index skipped (over 1 MiB, not UTF-8) is never edited around:
|
||||
//! when its bytes spell a name the edit changes, the edit is refused;
|
||||
//! otherwise it is named under `warnings:` (QA finding 2).
|
||||
//! (`source::WholeSet`, M2's ruling: a use can resolve through a file that
|
||||
//! never spells its name, so no narrowing is sound). The texts read are the
|
||||
//! texts the write-freshness rule compares against. A file the index
|
||||
//! skipped (over 1 MiB, not UTF-8) is never edited around: when its bytes
|
||||
//! spell a name the edit changes, the edit is refused; otherwise it is named
|
||||
//! on a `warning:` line (QA finding 2 of M3).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
@@ -19,218 +16,96 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_refactor::{RefactorEdit, TextEdit};
|
||||
|
||||
use super::mentions::{self, Focus};
|
||||
use super::select::{target, Target};
|
||||
use super::names::{self, Declaration};
|
||||
use super::read_item::split_line;
|
||||
use super::source::WholeSet;
|
||||
use super::{nav, Answer, Args, Param, Tool, Ty};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Plan};
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// `dry_run`, which every edit tool takes.
|
||||
pub(super) const DRY_RUN: Param =
|
||||
Param { name: "dry_run", ty: Ty::Bool, required: false, description: "Diff only." };
|
||||
|
||||
const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." };
|
||||
const LINE: Param =
|
||||
Param { name: "line", ty: Ty::Int { min: 1 }, required: false, description: "Line." };
|
||||
const COL: Param =
|
||||
Param { name: "col", ty: Ty::Int { min: 1 }, required: false, description: "Byte column." };
|
||||
const NAME: Param =
|
||||
Param { name: "name", ty: Ty::Str, required: false, description: "The name on `line`." };
|
||||
|
||||
/// The position arguments of the six cursor refactorings, then `dry_run`.
|
||||
const AT: &[Param] = &[FILE, LINE, COL, NAME, DRY_RUN];
|
||||
|
||||
/// One engine that acts at a position.
|
||||
type Engine = fn(&[(PathBuf, String)], &Path, u32) -> Result<RefactorEdit, String>;
|
||||
|
||||
/// The names an engine acting at a position changes — what a skipped file
|
||||
/// must not spell.
|
||||
type Stake = fn(&Analysis, u32) -> Vec<String>;
|
||||
|
||||
pub const EXPAND_WILDCARD: Tool = Tool {
|
||||
name: "expand_wildcard",
|
||||
title: "Expand .* connections",
|
||||
description: "Replace one instance's `.*` with the named connections it binds.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: expand_wildcard,
|
||||
};
|
||||
|
||||
pub const CONVERT_PORTS: Tool = Tool {
|
||||
name: "convert_ports",
|
||||
title: "Convert ports to ANSI",
|
||||
description: "Rewrite a module's non-ANSI header as an ANSI port list.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: convert_ports,
|
||||
};
|
||||
|
||||
pub const ORGANIZE_IMPORTS: Tool = Tool {
|
||||
name: "organize_imports",
|
||||
title: "Organize imports",
|
||||
description: "Remove unused `import`s in the scope at a position; sort the rest.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: organize_imports,
|
||||
};
|
||||
|
||||
pub const INLINE_MODULE: Tool = Tool {
|
||||
name: "inline_module",
|
||||
title: "Inline an instance",
|
||||
description: "Replace one instance with its module's body, connections substituted.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: inline_module,
|
||||
};
|
||||
|
||||
pub const PROPAGATE_PORTS: Tool = Tool {
|
||||
name: "propagate_ports",
|
||||
title: "Connect missing ports",
|
||||
description: "Connect by name every port one instance leaves unconnected.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: propagate_ports,
|
||||
};
|
||||
|
||||
pub const REMOVE_PORT: Tool = Tool {
|
||||
name: "remove_port",
|
||||
title: "Remove a port",
|
||||
description:
|
||||
"Delete a port and its connection in every instantiation; refused while the body uses it.",
|
||||
params: AT,
|
||||
rewalk: true,
|
||||
handler: remove_port,
|
||||
};
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
pub const RENAME: Tool = Tool {
|
||||
name: "rename",
|
||||
title: "Rename",
|
||||
description: "Rename a declaration and its uses; select as `definition`. Writes out `.*`/`.name` bindings, lists unresolved mentions.",
|
||||
description: "Rename declaration `name` (or unit.name) to `new_name` with every resolved use (.name/.* written out); `file` and name@LINE pick among declarations. Lists unresolved mentions.",
|
||||
params: &[
|
||||
Param { required: false, ..FILE },
|
||||
Param {
|
||||
description: "Line.",
|
||||
..LINE
|
||||
},
|
||||
COL,
|
||||
Param {
|
||||
description: "Name; alone, looked up project-wide.",
|
||||
..NAME
|
||||
},
|
||||
Param {
|
||||
name: "unit",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Unit declaring a bare `name`.",
|
||||
},
|
||||
Param {
|
||||
name: "new_name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The new name.",
|
||||
},
|
||||
DRY_RUN,
|
||||
Param { name: "name", ty: Ty::Str, required: true },
|
||||
Param { name: "new_name", ty: Ty::Str, required: true },
|
||||
Param { name: "file", ty: Ty::Str, required: false },
|
||||
],
|
||||
rewalk: true,
|
||||
handler: rename,
|
||||
};
|
||||
|
||||
fn expand_wildcard(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
with_check(at_cursor(project, args, vlog_refactor::expand_wildcard, instantiated), args)
|
||||
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let new_name = args.str("new_name").unwrap_or_default().trim();
|
||||
let declaration = one_declaration(project, args)?;
|
||||
let (name, path) = (declaration.name, declaration.path);
|
||||
if name == new_name {
|
||||
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(project, &why))?;
|
||||
let sites: usize = edit.edits.iter().map(|(_, edits)| edits.len()).sum();
|
||||
let unit = vlog_refactor::enclosing_module(&project.analysis(&path)?.text, declaration.offset);
|
||||
let told = Told { name: &name, home: &path, unit: unit.as_deref() };
|
||||
let done = write_telling(project, edit, &set, &told)?;
|
||||
let (sites, files) = (render::count(sites, "site"), render::count(done.files, "file"));
|
||||
let mut lines = vec![format!("renamed {sites} in {files}")];
|
||||
lines.extend(done.tail);
|
||||
Ok(Answer::lines(lines))
|
||||
}
|
||||
|
||||
fn convert_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::convert_to_ansi, enclosing)
|
||||
/// The declaration a rename means: `name` (or `name@LINE`), in `file` when
|
||||
/// given — exactly one, else a refusal listing them.
|
||||
struct Picked {
|
||||
name: String,
|
||||
path: PathBuf,
|
||||
offset: u32,
|
||||
}
|
||||
|
||||
fn organize_imports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
// Only the file's own `import` items change; nothing another file spells.
|
||||
at_cursor(project, args, vlog_refactor::organize_imports, |_, _| Vec::new())
|
||||
}
|
||||
|
||||
fn inline_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
with_check(at_cursor(project, args, vlog_refactor::inline_module, instantiated), args)
|
||||
}
|
||||
|
||||
fn propagate_ports(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
at_cursor(project, args, vlog_refactor::propagate_ports, instantiated)
|
||||
}
|
||||
|
||||
fn remove_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
with_check(remove_port_at(project, args), args)
|
||||
}
|
||||
|
||||
fn remove_port_at(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let (path, offset) = cursor(project, args)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let port = name_at(&analysis, offset);
|
||||
let mut names = port.clone();
|
||||
names.extend(instantiated(&analysis, offset));
|
||||
let unit = enclosing(&analysis, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::remove_port(&set.files, &path, offset)?;
|
||||
let Some(port) = port.first() else { return finish(project, edit, &set, args) };
|
||||
let told = Told {
|
||||
name: port,
|
||||
lead: format!("the removed port `{port}` is still spelled"),
|
||||
home: &path,
|
||||
fn one_declaration(project: &mut Project, args: &Args) -> Result<Picked, String> {
|
||||
let given = args.str("name").unwrap_or_default().trim().trim_start_matches('`');
|
||||
let (name, line) = split_line(given)?;
|
||||
let file = match args.str("file") {
|
||||
Some(file) => Some(project.resolve(file)?),
|
||||
None => None,
|
||||
};
|
||||
finish_telling(project, edit, &set, args, told, unit.first().map(String::as_str))
|
||||
}
|
||||
|
||||
/// The declared name at a position.
|
||||
fn name_at(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::rename_name_at(&analysis.semantics, offset).into_iter().collect()
|
||||
}
|
||||
|
||||
/// The module an instantiation at a position names, or whose port it is on.
|
||||
fn instantiated(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::port_action_modules_in(&analysis.tree, offset)
|
||||
}
|
||||
|
||||
/// The module whose declaration covers a position.
|
||||
pub(super) fn enclosing(analysis: &Analysis, offset: u32) -> Vec<String> {
|
||||
vlog_refactor::enclosing_module(&analysis.text, offset).into_iter().collect()
|
||||
}
|
||||
|
||||
/// Run `engine` at the position the arguments name, over the whole set.
|
||||
fn at_cursor(
|
||||
project: &mut Project,
|
||||
args: &Args,
|
||||
engine: Engine,
|
||||
stake: Stake,
|
||||
) -> Result<Answer, String> {
|
||||
let (path, offset) = cursor(project, args)?;
|
||||
let names = stake(&*project.analysis(&path)?, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = engine(&set.files, &path, offset)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
|
||||
/// The position a cursor refactoring acts at: `file` + `line` alone is the
|
||||
/// line's first non-blank byte; anything else is `definition`'s selector,
|
||||
/// which must name a file.
|
||||
fn cursor(project: &mut Project, args: &Args) -> Result<(PathBuf, u32), String> {
|
||||
if let (Some(file), Some(line), None, None) =
|
||||
(args.str("file"), args.int("line"), args.int("col"), args.str("name"))
|
||||
{
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let line = u32::try_from(line).unwrap_or(u32::MAX);
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
let count = analysis.lines.line_count();
|
||||
return Err(format!("line {line} is past the end ({count} lines) (in `{file}`)"));
|
||||
};
|
||||
let text = analysis.line_text(line);
|
||||
let blank = text.len() - text.trim_start().len();
|
||||
return Ok((path, range.start + blank as u32));
|
||||
let found = names::declarations_walking(project, name);
|
||||
if found.is_empty() {
|
||||
return Err(names::no_declaration(project, name));
|
||||
}
|
||||
match target(project, args)? {
|
||||
Target::At { path, offset, .. } => Ok((path, offset)),
|
||||
Target::Named { .. } => Err("give the `file` the position is in.".into()),
|
||||
let wanted = |d: &&Declaration| {
|
||||
file.as_ref().is_none_or(|file| d.path == *file) && line.is_none_or(|line| d.line == line)
|
||||
};
|
||||
let picked: Vec<&Declaration> = found.iter().filter(wanted).collect();
|
||||
match picked.as_slice() {
|
||||
[] => Err(format!(
|
||||
"`{given}` is not declared there; its declarations: {}.",
|
||||
sites(&found.iter().collect::<Vec<_>>())
|
||||
)),
|
||||
[one] if one.is_macro() => {
|
||||
Err(format!("`{name}` is a macro; lucisv does not rename macros."))
|
||||
}
|
||||
// The engine rewrites no hierarchical path through a block and
|
||||
// reports none as a use, so the rename could not be complete
|
||||
// (topo §2.9 MCP-14).
|
||||
[one] if one.kind == "block" => Err(format!(
|
||||
"`rename` does not rename generate block labels: paths through the block (`{}[0].…`) would not be rewritten; edit the file.",
|
||||
names::qualified(name).1
|
||||
)),
|
||||
[one] => {
|
||||
let name = names::qualified(name).1.to_string();
|
||||
Ok(Picked { name, path: one.path.clone(), offset: one.offset })
|
||||
}
|
||||
many => Err(names::ambiguous(name, many, "pass `file`, and `name@LINE` within one file")),
|
||||
}
|
||||
}
|
||||
|
||||
fn sites(found: &[&Declaration]) -> String {
|
||||
found.iter().map(|d| format!("{}:{}", d.file, d.line)).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// The whole set an engine is handed — refused when a file the index
|
||||
/// skipped spells one of `names`, since the edit could not reach it.
|
||||
pub(super) fn whole_set(
|
||||
@@ -248,84 +123,47 @@ pub(super) fn whole_set(
|
||||
Ok(set)
|
||||
}
|
||||
|
||||
/// A verified edit over the set's texts, diffed or written; the files the
|
||||
/// set left out are named under `warnings:`.
|
||||
pub(super) fn finish(
|
||||
project: &Project,
|
||||
edit: RefactorEdit,
|
||||
set: &WholeSet,
|
||||
args: &Args,
|
||||
) -> Result<Answer, String> {
|
||||
let mut plan = Plan::from_refactor(edit, &set.files)?;
|
||||
plan.warnings.extend(set.warning(project));
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
/// The name an edit changes, for the unresolved-mentions warning: the name,
|
||||
/// how the warning begins, and the file declaring it.
|
||||
/// The name an edit changes, for the unresolved-mentions block: the name,
|
||||
/// the file declaring it, and the unit around it when known.
|
||||
pub(super) struct Told<'a> {
|
||||
pub name: &'a str,
|
||||
pub lead: String,
|
||||
pub home: &'a Path,
|
||||
pub unit: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// [`finish`], and the unresolved mentions of `told.name` the edit left
|
||||
/// alone named under `warnings:` (and as `unresolved_mentions`) — found in
|
||||
/// the texts as the edit writes them, so each `file:line` is right after
|
||||
/// the write (QA finding 4).
|
||||
pub(super) fn finish_telling(
|
||||
/// What a written edit says after its first line: how many files it wrote,
|
||||
/// and the warning and `unresolved:` lines.
|
||||
pub(super) struct Done {
|
||||
pub files: usize,
|
||||
pub tail: Vec<String>,
|
||||
}
|
||||
|
||||
/// Write a verified edit over the set's texts, then list the unresolved
|
||||
/// mentions of `told.name` the edit left alone — found in the texts as the
|
||||
/// edit writes them, so each `file:line` is right after the write (QA
|
||||
/// finding 4 of feedback-1).
|
||||
pub(super) fn write_telling(
|
||||
project: &Project,
|
||||
edit: RefactorEdit,
|
||||
set: &WholeSet,
|
||||
args: &Args,
|
||||
told: Told,
|
||||
unit: Option<&str>,
|
||||
) -> Result<Answer, String> {
|
||||
told: &Told,
|
||||
) -> Result<Done, String> {
|
||||
let accounted: Vec<(PathBuf, Vec<TextRange>)> =
|
||||
edit.edits.iter().map(|(path, edits)| (path.clone(), written_ranges(edits))).collect();
|
||||
let mut plan = Plan::from_refactor(edit, &set.files)?;
|
||||
let plan = Plan::from_refactor(edit, &set.files)?;
|
||||
let written = set.files.iter().map(|(path, text)| {
|
||||
let change = plan.changes.iter().find(|change| &change.path == path);
|
||||
(path.as_path(), change.map_or(text.as_str(), |change| change.after.as_str()))
|
||||
});
|
||||
let focus = Focus { name: told.name, home: told.home, unit, accounted: &accounted };
|
||||
let focus = Focus { name: told.name, home: told.home, unit: told.unit, accounted: &accounted };
|
||||
let mentions = mentions::find(project, written, &focus);
|
||||
plan.warnings.extend(set.warning(project));
|
||||
if !mentions.is_empty() {
|
||||
plan.warnings.push(mentions.warning(&told.lead));
|
||||
}
|
||||
let mut answer = apply::run(project, plan, args.flag("dry_run", false))?;
|
||||
answer.structured["unresolved_mentions"] = mentions.json();
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// How many changed files the check line names; the rest are counted.
|
||||
const CHECK_CAP: usize = 5;
|
||||
|
||||
/// An edit's answer, ending with the line that names the files to run
|
||||
/// `diagnostics` on — the agents ran it anyway; saying which saves a
|
||||
/// decision (feedback round 2). Nothing is added when nothing changed.
|
||||
pub(super) fn with_check(answer: Result<Answer, String>, args: &Args) -> Result<Answer, String> {
|
||||
let mut answer = answer?;
|
||||
let mut files: Vec<&str> = ["changed", "created"]
|
||||
.iter()
|
||||
.filter_map(|key| answer.structured[*key].as_array())
|
||||
.flatten()
|
||||
.filter_map(|entry| entry["file"].as_str())
|
||||
.collect();
|
||||
if files.is_empty() {
|
||||
return Ok(answer);
|
||||
}
|
||||
files.sort_unstable();
|
||||
let when = if args.flag("dry_run", false) { "check after writing" } else { "check" };
|
||||
let mut line =
|
||||
format!("{when}: diagnostics on {}", files[..files.len().min(CHECK_CAP)].join(", "));
|
||||
if files.len() > CHECK_CAP {
|
||||
line.push_str(&format!(" and {} more", files.len() - CHECK_CAP));
|
||||
}
|
||||
answer.text.push_str(&line);
|
||||
answer.text.push('\n');
|
||||
Ok(answer)
|
||||
let done = apply::run(project, &plan)?;
|
||||
let mut tail = Vec::new();
|
||||
let warnings: Vec<String> = plan.warnings.iter().map(|w| set.rooted(project, w)).collect();
|
||||
render::warnings(&mut tail, &warnings);
|
||||
tail.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
|
||||
tail.extend(mentions.block());
|
||||
Ok(Done { files: done.changed.len() + done.created.len(), tail })
|
||||
}
|
||||
|
||||
/// Where each of one file's edits lands in the text as written: its start
|
||||
@@ -343,61 +181,3 @@ fn written_ranges(edits: &[TextEdit]) -> Vec<TextRange> {
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn rename(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
with_check(rename_at(project, args), args)
|
||||
}
|
||||
|
||||
fn rename_at(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let new_name = args.str("new_name").unwrap_or_default();
|
||||
let (path, offset) = match target(project, args)? {
|
||||
Target::At { path, offset, .. } => (path, offset),
|
||||
Target::Named { name, unit } => nav::declaration_position(project, &name, unit.as_deref())?,
|
||||
};
|
||||
let names = name_at(&*project.analysis(&path)?, offset);
|
||||
// Already renamed: a second identical call is a no-op, not a refusal.
|
||||
if names.first().map(String::as_str) == Some(new_name) {
|
||||
return apply::run(project, Plan::default(), args.flag("dry_run", false));
|
||||
}
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::rename(&set.files, &path, offset, new_name)?;
|
||||
let Some(old) = names.first() else { return finish(project, edit, &set, args) };
|
||||
let unit = enclosing(&*project.analysis(&path)?, offset);
|
||||
let told =
|
||||
Told { name: old, lead: format!("the old name `{old}` is still spelled"), home: &path };
|
||||
finish_telling(project, edit, &set, args, told, unit.first().map(String::as_str))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use super::super::Args;
|
||||
use super::{with_check, Answer};
|
||||
|
||||
fn answer(changed: &[&str], created: &[&str]) -> Result<Answer, String> {
|
||||
let entries = |files: &[&str]| -> Vec<Value> {
|
||||
files.iter().map(|file| json!({ "file": file })).collect()
|
||||
};
|
||||
let structured = json!({ "changed": entries(changed), "created": entries(created) });
|
||||
Ok(Answer { text: "files: …\n".into(), structured })
|
||||
}
|
||||
|
||||
fn args(dry_run: bool) -> Args {
|
||||
Args(json!({ "dry_run": dry_run }).as_object().cloned().unwrap_or_default())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_check_line_names_five_files_in_path_order_and_counts_the_rest() {
|
||||
let changed = ["f.sv", "b.sv", "e.sv", "a.sv", "d.sv", "g.sv"];
|
||||
let said = with_check(answer(&changed, &["c.sv"]), &args(false)).unwrap();
|
||||
assert!(said
|
||||
.text
|
||||
.ends_with("\ncheck: diagnostics on a.sv, b.sv, c.sv, d.sv, e.sv and 2 more\n"));
|
||||
let dry = with_check(answer(&["a.sv"], &[]), &args(true)).unwrap();
|
||||
assert!(dry.text.ends_with("\ncheck after writing: diagnostics on a.sv\n"));
|
||||
let nothing = with_check(answer(&[], &[]), &args(false)).unwrap();
|
||||
assert_eq!(nothing.text, "files: …\n");
|
||||
assert!(with_check(Err("no".into()), &args(false)).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! `find`: where a name is declared and, on `refs`, where each declaration
|
||||
//! is used — the question an agent otherwise answers by grepping and
|
||||
//! reading. Declarations come from the index (`names.rs`); uses from
|
||||
//! `vlog_refactor::find_references` over every indexed file read from disk
|
||||
//! now (`source::WholeSet`, M2's ruling: a use can resolve through a file
|
||||
//! that never spells the name); then the name's unresolved mentions —
|
||||
//! strings, comments, macro text — that no engine resolved.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
use super::mentions::{self, Focus};
|
||||
use super::names::{self, Declaration};
|
||||
use super::source::WholeSet;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
/// The most lines an answer holds before `… and N more`.
|
||||
const CAP: usize = 300;
|
||||
|
||||
/// The most declarations whose uses one call lists: each is a whole-set
|
||||
/// engine run (≈ 2 s on opentitan), and a name declared more often than
|
||||
/// this is a question `read` or `outline` answers better.
|
||||
const REFS_CAP: usize = 5;
|
||||
|
||||
pub const FIND: Tool = Tool {
|
||||
name: "find",
|
||||
description: "Every declaration of `name` or unit.name (kind name file:line; macros too); `refs: true` adds each one's uses as file:line and the unresolved mentions (strings, comments, macro text).",
|
||||
params: &[
|
||||
Param { name: "name", ty: Ty::Str, required: true },
|
||||
Param { name: "refs", ty: Ty::Bool, required: false },
|
||||
],
|
||||
rewalk: false,
|
||||
handler: find,
|
||||
};
|
||||
|
||||
fn find(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or("").trim().trim_start_matches('`');
|
||||
if name.is_empty() {
|
||||
return Err("`name` is empty.".into());
|
||||
}
|
||||
let found = names::declarations_walking(project, name);
|
||||
if found.is_empty() {
|
||||
return Err(names::no_declaration(project, name));
|
||||
}
|
||||
let name = names::qualified(name).1;
|
||||
if !args.flag("refs") {
|
||||
let lines = found.iter().map(|declaration| declaration.render(name)).collect();
|
||||
return Ok(Answer::lines(render::capped(lines, CAP)));
|
||||
}
|
||||
// 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)))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let set = WholeSet::read(project, None);
|
||||
let mut lines = Vec::new();
|
||||
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
|
||||
let mut searched = 0;
|
||||
for declaration in found {
|
||||
lines.push(declaration.render(name));
|
||||
if declaration.is_macro() || searched == REFS_CAP {
|
||||
continue;
|
||||
}
|
||||
searched += 1;
|
||||
let hits = vlog_refactor::find_references(
|
||||
&set.files,
|
||||
&declaration.path,
|
||||
declaration.offset,
|
||||
false,
|
||||
);
|
||||
match hits {
|
||||
Ok(hits) => {
|
||||
lines
|
||||
.extend(uses(project, &set, &hits).into_iter().map(|line| format!(" {line}")));
|
||||
account(&mut accounted, hits);
|
||||
}
|
||||
Err(why) => {
|
||||
let why = engine_refusal(&set.rooted(project, &why));
|
||||
lines.push(format!(" uses not listed: {why}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let followed = found.iter().filter(|declaration| !declaration.is_macro()).count();
|
||||
if followed > REFS_CAP {
|
||||
lines.push(format!("uses listed for {REFS_CAP} of {followed} declarations"));
|
||||
}
|
||||
let home = &found[0].path;
|
||||
let focus = Focus { name, home, unit: None, accounted: &accounted };
|
||||
let files = set.files.iter().map(|(path, text)| (path.as_path(), text.as_str()));
|
||||
lines.extend(mentions::find(project, files, &focus).block());
|
||||
lines.extend(set.warning(project).map(|warning| format!("warning: {warning}")));
|
||||
lines
|
||||
}
|
||||
|
||||
/// The engine's hits, one file per line: `file:12,40`.
|
||||
fn uses(project: &Project, set: &WholeSet, hits: &[(PathBuf, TextRange)]) -> Vec<String> {
|
||||
let mut sites: Vec<(String, u32)> = Vec::new();
|
||||
let mut current: Option<(&PathBuf, LineIndex)> = None;
|
||||
for (path, span) in hits {
|
||||
if current.as_ref().is_none_or(|(held, _)| *held != path) {
|
||||
let text = set.files.iter().find(|(held, _)| held == path).map_or("", |(_, t)| t);
|
||||
current = Some((path, LineIndex::new(text)));
|
||||
}
|
||||
if let Some((_, lines)) = ¤t {
|
||||
sites.push((project.relative(path), lines.line_col(span.start).0));
|
||||
}
|
||||
}
|
||||
render::by_file(&sites)
|
||||
}
|
||||
|
||||
/// The hits recorded per file, so the mentions pass skips them.
|
||||
fn account(accounted: &mut Vec<(PathBuf, Vec<TextRange>)>, hits: Vec<(PathBuf, TextRange)>) {
|
||||
for (path, span) in hits {
|
||||
match accounted.iter_mut().find(|(held, _)| *held == path) {
|
||||
Some((_, spans)) => spans.push(span),
|
||||
None => accounted.push((path, vec![span])),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The engine's refusal, said as ours: `find_references` shares the
|
||||
/// rename's resolution, so its sentences speak of renaming; these do not.
|
||||
fn engine_refusal(sentence: &str) -> String {
|
||||
const REWORDED: &[(&str, &str)] = &[
|
||||
("there is no symbol to rename at this position", "there is no symbol at this position"),
|
||||
(
|
||||
"nothing outside the project scope can be renamed",
|
||||
"nothing outside the project scope is followed",
|
||||
),
|
||||
("lucisv found nothing to rename for", "lucisv found no occurrence of"),
|
||||
("the rename was abandoned", "the search was abandoned"),
|
||||
("which declaration this rename means", "which declaration this position means"),
|
||||
(", so a rename here would only be half a rename", ", so its uses cannot all be listed"),
|
||||
];
|
||||
let mut out = render::one_line(sentence);
|
||||
for (from, to) in REWORDED {
|
||||
out = out.replace(from, to);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::engine_refusal;
|
||||
|
||||
#[test]
|
||||
fn engine_refusals_never_speak_of_renaming() {
|
||||
for sentence in [
|
||||
"there is no symbol to rename at this position.",
|
||||
"`x` is declared outside the files lucisv indexes, so a rename here would only be half a rename.",
|
||||
"lucisv found nothing to rename for `x`.",
|
||||
"`x` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.",
|
||||
] {
|
||||
let said = engine_refusal(sentence);
|
||||
assert!(!said.contains("rename"), "{said}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,94 +1,98 @@
|
||||
//! `format` and `fix_lint`: the CLI's `lucisv format` and `lucisv check
|
||||
//! --fix`, per file, through the one write path (`apply.rs`).
|
||||
//! `format`: the CLI's `lucisv format` over a path or a glob, and with
|
||||
//! `fix` the CLI's `lucisv check --fix` first — each file through the one
|
||||
//! write path (`apply.rs`).
|
||||
//!
|
||||
//! `format` is `format_source` (or `format_range` for `lines`) under the
|
||||
//! `lucisv.toml` governing each file — the formatter's own safety net decides,
|
||||
//! and a refusal names the file and writes nothing anywhere. `fix_lint` runs
|
||||
//! the lint pass `diagnostics` runs (the same config ladder, waivers and
|
||||
//! cross-file oracle), applies the **safe** fixes whose edits stay out of
|
||||
//! every `// lucisv: off` fence — the CLI's `--fix` filter — until the file
|
||||
//! stops changing, and refuses a result that parses worse than the input.
|
||||
//! Formatting is `format_source` under the `lucisv.toml` governing each file;
|
||||
//! the formatter's own safety net decides, and a file it refuses is named
|
||||
//! and left alone while the rest are written (PLAN §10.1). `fix` runs the
|
||||
//! lint pass `check` runs (the same config ladder, waivers and cross-file
|
||||
//! oracle), applies the **safe** fixes whose edits stay out of every
|
||||
//! `// lucisv: off` fence — the CLI's `--fix` filter — until the file stops
|
||||
//! changing, and refuses a result that parses worse than the input.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::panic::{catch_unwind, AssertUnwindSafe};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use lucisv_core::config::{Discovery, FileConfig};
|
||||
use vlog_formatter::fence::{self, Region};
|
||||
use vlog_formatter::{format_range, format_source, Config, LineRanges};
|
||||
use vlog_formatter::{format_source, Config};
|
||||
use vlog_linter::{apply_fixes, Fix, Violation};
|
||||
|
||||
use super::diagnostics::{violations, Mentions, Runs};
|
||||
use super::edit::DRY_RUN;
|
||||
use super::glob::path_match;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Change, Plan};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
/// How many fix-then-relint rounds one file gets — the CLI's cap, for the
|
||||
/// CLI's reason: two overlapping fixes land in successive rounds.
|
||||
const MAX_FIX_ROUNDS: usize = 10;
|
||||
|
||||
const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." };
|
||||
const FILES: Param =
|
||||
Param { name: "files", ty: Ty::Str, required: false, description: "Comma-separated files." };
|
||||
|
||||
pub const FORMAT: Tool = Tool {
|
||||
name: "format",
|
||||
title: "Format files",
|
||||
description: "Format `file`/`files` as `lucisv format`; `lines` limits it.",
|
||||
description: "Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. A file the formatter refuses is named and left alone.",
|
||||
params: &[
|
||||
FILE,
|
||||
FILES,
|
||||
Param {
|
||||
name: "lines",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Line ranges such as `12-40,55` (one file only).",
|
||||
},
|
||||
DRY_RUN,
|
||||
Param { name: "files", ty: Ty::Str, required: true },
|
||||
Param { name: "fix", ty: Ty::Bool, required: false },
|
||||
],
|
||||
rewalk: false,
|
||||
handler: format,
|
||||
};
|
||||
|
||||
pub const FIX_LINT: Tool = Tool {
|
||||
name: "fix_lint",
|
||||
title: "Apply safe lint fixes",
|
||||
description: "Apply the safe lint fixes to `file`/`files`; says what remains.",
|
||||
params: &[
|
||||
FILE,
|
||||
FILES,
|
||||
Param {
|
||||
name: "rules",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Rules or severities to fix.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: fix_lint,
|
||||
};
|
||||
|
||||
/// The files a call names, resolved, each once, in the order given.
|
||||
fn named_files(project: &Project, args: &Args) -> Result<Vec<PathBuf>, String> {
|
||||
let given: Vec<&str> = match (args.str("file"), args.str("files")) {
|
||||
(Some(_), Some(_)) => return Err("give `file` or `files`, not both.".into()),
|
||||
(Some(file), None) => vec![file],
|
||||
(None, Some(files)) => files.split(',').map(str::trim).filter(|f| !f.is_empty()).collect(),
|
||||
(None, None) => return Err("give a `file`, or comma-separated `files`.".into()),
|
||||
};
|
||||
if given.is_empty() {
|
||||
return Err("`files` names no file.".into());
|
||||
}
|
||||
let mut out: Vec<PathBuf> = Vec::new();
|
||||
for file in given {
|
||||
let path = project.resolve(file)?;
|
||||
if !out.contains(&path) {
|
||||
out.push(path);
|
||||
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = matching_files(project, args.str("files").unwrap_or_default().trim())?;
|
||||
let fix = args.flag("fix");
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut runs = Runs::new();
|
||||
let mut plan = Plan::default();
|
||||
let mut refused: Vec<String> = Vec::new();
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
match fixed_and_formatted(project, &mut discovery, &mut runs, &path, &before, fix) {
|
||||
Ok(after) => plan.changes.push(Change { path, before, after, created: false }),
|
||||
Err(why) => refused.push(format!("not formatted: {} ({why})", project.relative(&path))),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
if plan.changes.is_empty() {
|
||||
return Err(refused.join("; "));
|
||||
}
|
||||
let written = apply::run(project, &plan)?;
|
||||
let formatted = written.changed.len() + written.unchanged.len();
|
||||
let unchanged = written.unchanged.len();
|
||||
let formatted = render::count(formatted, "file");
|
||||
let mut lines = vec![format!("formatted {formatted} ({unchanged} unchanged)")];
|
||||
lines.extend(refused);
|
||||
Ok(Answer::lines(render::capped(lines, 200)))
|
||||
}
|
||||
|
||||
/// The files `files` names: one path, every indexed file below a
|
||||
/// directory, or every indexed file a glob matches — refused when none.
|
||||
fn matching_files(project: &mut Project, files: &str) -> Result<Vec<PathBuf>, String> {
|
||||
if files.is_empty() {
|
||||
return Err("`files` is empty.".into());
|
||||
}
|
||||
let wildcard = files.contains(['*', '?']);
|
||||
if !wildcard {
|
||||
if let Ok(path) = project.resolve(files) {
|
||||
return Ok(vec![path]);
|
||||
}
|
||||
}
|
||||
let select = |project: &Project| -> Vec<PathBuf> {
|
||||
let kept = |path: &&PathBuf| path_match(files, &project.relative(path));
|
||||
project.files().map(|(path, _)| path).filter(kept).cloned().collect()
|
||||
};
|
||||
let mut found = select(project);
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
found = select(project);
|
||||
}
|
||||
if found.is_empty() {
|
||||
return Err(match wildcard {
|
||||
true => format!("no indexed file matches `{files}`; nothing written."),
|
||||
false => project.resolve(files).err().unwrap_or_default(),
|
||||
});
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
|
||||
/// A file's text as it is on disk now.
|
||||
@@ -97,24 +101,21 @@ fn read(project: &Project, path: &Path) -> Result<String, String> {
|
||||
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(path)))
|
||||
}
|
||||
|
||||
fn format(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = named_files(project, args)?;
|
||||
let lines = match args.str("lines") {
|
||||
None => None,
|
||||
Some(_) if paths.len() > 1 => return Err("`lines` needs a single file.".into()),
|
||||
Some(spec) => Some(LineRanges::parse(spec).map_err(|e| format!("`lines`: {e}"))?),
|
||||
/// One file's new text: its safe lint fixes (on `fix`), then formatted.
|
||||
fn fixed_and_formatted(
|
||||
project: &Project,
|
||||
discovery: &mut Discovery,
|
||||
runs: &mut Runs,
|
||||
path: &Path,
|
||||
before: &str,
|
||||
fix: bool,
|
||||
) -> Result<String, String> {
|
||||
let text = match fix {
|
||||
true => fix_file(project, runs, path, before)?,
|
||||
false => before.to_string(),
|
||||
};
|
||||
let mut discovery = Discovery::new(true);
|
||||
let mut plan = Plan::default();
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
let config = formatter_config(&discovery.for_file(&path)?);
|
||||
let after = formatted(&before, &config, lines.as_ref()).map_err(|why| {
|
||||
format!("`{}` was not formatted: {why}; nothing written.", project.relative(&path))
|
||||
})?;
|
||||
plan.changes.push(Change { path, before, after, created: false });
|
||||
}
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
let config = formatter_config(&discovery.for_file(path)?);
|
||||
formatted(&text, &config)
|
||||
}
|
||||
|
||||
/// The formatter settings a file's `lucisv.toml` resolves to — the CLI's
|
||||
@@ -135,11 +136,8 @@ fn formatter_config(file: &FileConfig) -> Config {
|
||||
|
||||
/// Format one text; a formatter panic is an error like any other, never the
|
||||
/// end of the server.
|
||||
fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result<String, String> {
|
||||
let run = catch_unwind(AssertUnwindSafe(|| match lines {
|
||||
Some(lines) => format_range(text, config, lines),
|
||||
None => format_source(text, config),
|
||||
}));
|
||||
fn formatted(text: &str, config: &Config) -> Result<String, String> {
|
||||
let run = catch_unwind(AssertUnwindSafe(|| format_source(text, config)));
|
||||
match run {
|
||||
Ok(Ok(out)) => Ok(out),
|
||||
Ok(Err(e)) => Err(e.to_string()),
|
||||
@@ -147,37 +145,6 @@ fn formatted(text: &str, config: &Config, lines: Option<&LineRanges>) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
fn fix_lint(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let paths = named_files(project, args)?;
|
||||
let selected: Option<Vec<String>> = args.str("rules").map(|rules| {
|
||||
rules.split(',').map(str::trim).filter(|r| !r.is_empty()).map(str::to_string).collect()
|
||||
});
|
||||
let mut runs = Runs::new(selected);
|
||||
let mut plan = Plan::default();
|
||||
let mut fixed: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
let mut left = 0;
|
||||
for path in paths {
|
||||
let before = read(project, &path)?;
|
||||
let outcome = fix_file(project, &mut runs, &path, &before)?;
|
||||
for (rule, count) in outcome.fixed {
|
||||
*fixed.entry(rule).or_default() += count;
|
||||
}
|
||||
left += outcome.left;
|
||||
plan.changes.push(Change { path, before, after: outcome.text, created: false });
|
||||
}
|
||||
plan.note = Some(fixed_note(&fixed, left));
|
||||
apply::run(project, plan, args.flag("dry_run", false))
|
||||
}
|
||||
|
||||
/// What fixing one file came to.
|
||||
struct Fixed {
|
||||
text: String,
|
||||
/// Per rule, how many of its findings the fixes removed.
|
||||
fixed: BTreeMap<&'static str, usize>,
|
||||
/// Findings still reported after the last round.
|
||||
left: usize,
|
||||
}
|
||||
|
||||
/// Fix, re-lint, repeat until nothing more applies; refuse a result whose
|
||||
/// tolerant parse reports more errors than the input's did.
|
||||
fn fix_file(
|
||||
@@ -185,13 +152,12 @@ fn fix_file(
|
||||
runs: &mut Runs,
|
||||
path: &Path,
|
||||
before: &str,
|
||||
) -> Result<Fixed, String> {
|
||||
) -> Result<String, String> {
|
||||
let run = runs.for_file(path)?;
|
||||
let oracle = Mentions::of_file(project.index(), project.index().file_id(path));
|
||||
let first = Analysis::of(before.to_string());
|
||||
let errors_before = first.diagnostics.len();
|
||||
let found = violations(&run, path, &first, &oracle);
|
||||
let mut remaining = found.clone();
|
||||
let mut remaining = violations(&run, path, &first, &oracle);
|
||||
let mut text = before.to_string();
|
||||
let mut errors_after = errors_before;
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
@@ -206,12 +172,10 @@ fn fix_file(
|
||||
}
|
||||
if errors_after > errors_before {
|
||||
return Err(format!(
|
||||
"fixing `{}` would leave it with {errors_after} parse errors where it had {errors_before}; nothing written.",
|
||||
project.relative(path)
|
||||
"its fixes would leave {errors_after} parse errors where it had {errors_before}"
|
||||
));
|
||||
}
|
||||
let fixed = removed_per_rule(&found, &remaining);
|
||||
Ok(Fixed { text, fixed, left: remaining.len() })
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
/// The findings whose fix may be applied: those whose every edit stays out
|
||||
@@ -231,28 +195,3 @@ fn touches_fence(fix: &Fix, regions: &[Region]) -> bool {
|
||||
.iter()
|
||||
.any(|(range, _)| fence::is_protected(regions, range.start as usize, range.end as usize))
|
||||
}
|
||||
|
||||
/// Per rule, how many fewer findings the fixed text has.
|
||||
fn removed_per_rule(before: &[Violation], after: &[Violation]) -> BTreeMap<&'static str, usize> {
|
||||
let count = |found: &[Violation]| {
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
found.iter().for_each(|v| *counts.entry(v.rule).or_default() += 1);
|
||||
counts
|
||||
};
|
||||
let after = count(after);
|
||||
count(before)
|
||||
.into_iter()
|
||||
.filter_map(|(rule, n)| {
|
||||
let gone = n.saturating_sub(after.get(rule).copied().unwrap_or(0));
|
||||
(gone > 0).then_some((rule, gone))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `fixed: rule ×2, rule ×1; 3 findings left`.
|
||||
fn fixed_note(fixed: &BTreeMap<&'static str, usize>, left: usize) -> String {
|
||||
let listed: Vec<String> = fixed.iter().map(|(rule, n)| format!("{rule} ×{n}")).collect();
|
||||
let fixed = if listed.is_empty() { "nothing".to_string() } else { listed.join(", ") };
|
||||
let plural = if left == 1 { "" } else { "s" };
|
||||
format!("fixed: {fixed}; {left} finding{plural} left")
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! Path globs, as `format`'s `files` takes them: `*` and `?` within one
|
||||
//! path component, `**` for any run of components, and a bare directory
|
||||
//! for everything below it — the `.gitignore` / `rg -g` reading.
|
||||
|
||||
/// 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();
|
||||
let name: Vec<char> = name.chars().collect();
|
||||
// Classic two-pointer match with one backtrack point per `*`.
|
||||
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
|
||||
while n < name.len() {
|
||||
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
|
||||
p += 1;
|
||||
n += 1;
|
||||
} else if p < pattern.len() && pattern[p] == '*' {
|
||||
star = Some(p);
|
||||
resume = n;
|
||||
p += 1;
|
||||
} else if let Some(at) = star {
|
||||
p = at + 1;
|
||||
resume += 1;
|
||||
n = resume;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
/// Whether a root-relative `path` matches a path glob: `*` and `?` within
|
||||
/// one component ([`glob_match`]), `**` as a whole component for any run of
|
||||
/// components (none included). A trailing `/` means everything below.
|
||||
pub fn path_match(pattern: &str, path: &str) -> bool {
|
||||
let pattern = pattern.strip_prefix("./").unwrap_or(pattern);
|
||||
// A bare directory (`ip/aes`, no wildcard) means everything below it, as
|
||||
// it does for `.gitignore` and `rg -g` (feedback-2 QA note 2).
|
||||
let literal = !pattern.contains(['*', '?']);
|
||||
if literal && path.strip_prefix(pattern).is_some_and(|rest| rest.starts_with('/')) {
|
||||
return true;
|
||||
}
|
||||
let mut parts: Vec<&str> = pattern.split('/').collect();
|
||||
if parts.last() == Some(&"") && parts.len() > 1 {
|
||||
parts.pop();
|
||||
parts.push("**");
|
||||
}
|
||||
// `**/**` means what `**` means; collapsing keeps the search linear-ish.
|
||||
parts.dedup_by(|a, b| *a == "**" && *b == "**");
|
||||
let components: Vec<&str> = path.split('/').collect();
|
||||
components_match(&parts, &components)
|
||||
}
|
||||
|
||||
fn components_match(pattern: &[&str], path: &[&str]) -> bool {
|
||||
match pattern.split_first() {
|
||||
None => path.is_empty(),
|
||||
Some((&"**", rest)) => (0..=path.len()).any(|skip| components_match(rest, &path[skip..])),
|
||||
Some((first, rest)) => path
|
||||
.split_first()
|
||||
.is_some_and(|(part, below)| glob_match(first, part) && components_match(rest, below)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{glob_match, path_match};
|
||||
|
||||
#[test]
|
||||
fn a_bare_directory_glob_means_everything_below_it() {
|
||||
assert!(super::path_match("ip/aes", "ip/aes/rtl/aes.sv"));
|
||||
assert!(super::path_match("ip/aes/", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!super::path_match("ip/aes", "ip/aes_x/rtl/aes.sv"));
|
||||
assert!(!super::path_match("ip/aes", "ip/ae"));
|
||||
assert!(super::path_match("ip/aes/rtl/aes.sv", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!super::path_match("ip/a?s", "ip/aes/rtl/aes.sv"), "a wildcard keeps glob rules");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn globs_match_runs_and_single_characters() {
|
||||
assert!(glob_match("prim_*", "prim_fifo_sync"));
|
||||
assert!(glob_match("*fifo*", "prim_fifo_sync"));
|
||||
assert!(glob_match("a?c", "abc"));
|
||||
assert!(glob_match("*", ""));
|
||||
assert!(!glob_match("a?c", "ac"));
|
||||
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
|
||||
assert!(glob_match("*_sync", "prim_fifo_sync"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_globs_keep_star_in_one_component_and_let_double_star_span_many() {
|
||||
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/rtl/aes.sv"));
|
||||
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/sub/rtl/aes.sv"));
|
||||
assert!(path_match("ip/**/rtl/*.sv", "ip/rtl/x.sv"));
|
||||
assert!(!path_match("ip/**/rtl/*.sv", "ip/aes/dv/aes.sv"));
|
||||
assert!(!path_match("ip/*/*.sv", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!path_match("*.sv", "ip/aes.sv"));
|
||||
assert!(path_match("**/*.sv", "ip/aes.sv") && path_match("**/*.sv", "top.sv"));
|
||||
assert!(path_match("ip/ae?/**", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!path_match("ip/ae?/**", "ip/aesx/rtl/aes.sv"));
|
||||
assert!(path_match("ip/", "ip/aes/rtl/aes.sv") && path_match("./ip/**", "ip/a.sv"));
|
||||
assert!(path_match("**/**/**/rtl/**", "a/b/rtl/c/d.sv"));
|
||||
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
|
||||
}
|
||||
}
|
||||
@@ -1,89 +1,51 @@
|
||||
//! `hierarchy`: the instance tree, down from a module (or from every
|
||||
//! top-level module) or up to the modules that instantiate it — read off the
|
||||
//! index's instantiation edges, textual rather than elaborated, exactly the
|
||||
//! census the editor's hierarchy view and call hierarchy draw from.
|
||||
//! `hierarchy`: the project's shape. Without a `root`, the counts and the
|
||||
//! top modules; with one, the instance tree down from it or every
|
||||
//! instantiation of it up to `depth` levels — read off the index's
|
||||
//! instantiation edges, textual rather than elaborated, exactly the census
|
||||
//! the editor's hierarchy view and call hierarchy draw from. Every instance
|
||||
//! line points at its **instantiation site**, and `peek` shows the
|
||||
//! statement written there.
|
||||
//!
|
||||
//! The walk is cut three ways: by `depth`, by a module already on the path
|
||||
//! (a module that instantiates itself, through `generate` or otherwise, ends
|
||||
//! its branch marked `recursive`), and by [`NODE_CAP`]. A module declared
|
||||
//! more than once is not expanded — which declaration an instance means is
|
||||
//! the elaborator's choice, not ours — and says how many there are.
|
||||
//!
|
||||
//! Each instance's `#(...)` overrides are always in the JSON; the text line
|
||||
//! shows them only on `overrides: true`, since a census rarely reads them.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::{
|
||||
Def, FileId, InstanceOccurrence, InstantiationEdge, SymbolKind, WorkspaceIndex,
|
||||
};
|
||||
|
||||
use super::read::{in_glob, path_match};
|
||||
use super::source::{self, Texts};
|
||||
use super::names;
|
||||
use super::source::Texts;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
|
||||
use crate::render;
|
||||
|
||||
/// The deepest a walk may go, whatever `depth` asks.
|
||||
const MAX_DEPTH: usize = 20;
|
||||
|
||||
/// The longest overrides text a line shows (on `overrides: true`); the JSON
|
||||
/// carries all of it.
|
||||
const OVERRIDES_CAP: usize = 200;
|
||||
const MAX_DEPTH: i64 = 20;
|
||||
|
||||
/// The most nodes one walk collects before it stops.
|
||||
const NODE_CAP: usize = 50_000;
|
||||
|
||||
/// The most lines an answer holds before `… and N more`.
|
||||
const CAP: usize = 300;
|
||||
|
||||
/// The most source lines `peek` shows of one statement before `…`.
|
||||
const PEEK_LINES: usize = 12;
|
||||
|
||||
pub const HIERARCHY: Tool = Tool {
|
||||
name: "hierarchy",
|
||||
title: "Instance hierarchy",
|
||||
description: "Who instantiates a module (`up`, with file:line) or what it instantiates (`down`, default). Textual.",
|
||||
description: "The instance tree of `root` to `depth` (1-20, default 1), each at its instantiation file:line; `up`: its instantiations; `peek`: each statement's source. No `root`: file/module counts and the top modules.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "root",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "The module; required for `up`.",
|
||||
},
|
||||
Param {
|
||||
name: "direction",
|
||||
ty: Ty::Enum(&["down", "up"]),
|
||||
required: false,
|
||||
description: "Default `down`.",
|
||||
},
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 },
|
||||
required: false,
|
||||
description: "Default 3.",
|
||||
},
|
||||
Param {
|
||||
name: "in",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Path glob on the instantiating file (`up`) or the module's (`down`), e.g. `ip/**/rtl/*.sv`.",
|
||||
},
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Default 500.",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Lines to skip.",
|
||||
},
|
||||
Param {
|
||||
name: "overrides",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Add each `#(…)` to the text lines.",
|
||||
},
|
||||
Param { name: "root", ty: Ty::Str, required: false },
|
||||
Param { name: "up", ty: Ty::Bool, required: false },
|
||||
Param { name: "depth", ty: Ty::Range { min: 1, max: MAX_DEPTH }, required: false },
|
||||
Param { name: "peek", ty: Ty::Bool, required: false },
|
||||
],
|
||||
rewalk: false,
|
||||
handler: hierarchy,
|
||||
@@ -99,87 +61,86 @@ struct Child {
|
||||
site: TextRange,
|
||||
/// The instance's own name.
|
||||
name: TextRange,
|
||||
/// Where the statement's first instance name starts: the `#(...)`
|
||||
/// belongs to the whole statement and ends before it.
|
||||
first: u32,
|
||||
/// Where the statement's last instance ends.
|
||||
end: u32,
|
||||
}
|
||||
|
||||
impl Child {
|
||||
/// One instance of an edge to `module`.
|
||||
fn of(module: &str, edge: &InstantiationEdge, occurrence: &InstanceOccurrence) -> Child {
|
||||
let first =
|
||||
edge.instances.first().map_or(occurrence.name_span.start, |i| i.name_span.start);
|
||||
let end = edge.instances.last().map_or(occurrence.span.end, |last| last.span.end);
|
||||
Child {
|
||||
instance: occurrence.name.clone(),
|
||||
module: module.to_string(),
|
||||
file: edge.file,
|
||||
site: edge.site_span,
|
||||
name: occurrence.name_span,
|
||||
first,
|
||||
end,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One line of the answer. A root line has no instance.
|
||||
/// One line of a tree. A root line (down only) has no instance.
|
||||
struct Node {
|
||||
depth: usize,
|
||||
/// Down: the instance; up: the instance of the line above it.
|
||||
/// Down: the instance; up: the instance of the module on the line above.
|
||||
instance: Option<Child>,
|
||||
/// Down: the instantiated module; up: the instantiating one; root: itself.
|
||||
module: String,
|
||||
root: Option<Def>,
|
||||
note: Option<String>,
|
||||
}
|
||||
|
||||
/// A walk in progress: the edges by owner, the `in` glob, what it
|
||||
/// collected, and the path of modules above the current node.
|
||||
struct Walk<'a> {
|
||||
project: &'a Project,
|
||||
index: &'a WorkspaceIndex,
|
||||
glob: Option<&'a str>,
|
||||
below: HashMap<(FileId, u32), Vec<Child>>,
|
||||
max_depth: usize,
|
||||
nodes: Vec<Node>,
|
||||
path: Vec<String>,
|
||||
note: Option<&'static str>,
|
||||
declared: usize,
|
||||
}
|
||||
|
||||
fn hierarchy(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let up = args.str("direction") == Some("up");
|
||||
let root = args.str("root").filter(|root| !root.is_empty());
|
||||
if up && root.is_none() {
|
||||
return Err("`direction: up` needs a `root`.".into());
|
||||
}
|
||||
if let Some(root) = root {
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
return Err(format!("no module or interface `{root}` is indexed."));
|
||||
}
|
||||
}
|
||||
let max_depth = args.count("depth", 3);
|
||||
let index = project.index();
|
||||
let mut walk = Walk::new(project, in_glob(args), max_depth, !up);
|
||||
let roots: Vec<(String, Def)> = match root {
|
||||
Some(root) => {
|
||||
modules_named(index, root).into_iter().map(|d| (root.to_string(), d)).collect()
|
||||
}
|
||||
None => top_modules(index).into_iter().filter(|(_, def)| walk.keeps(def.file)).collect(),
|
||||
let Some(root) = args.str("root").map(str::trim).filter(|root| !root.is_empty()) else {
|
||||
// Files written since the last walk are counted.
|
||||
project.ensure_walked_for_miss();
|
||||
return Ok(Answer::lines(overview(project)));
|
||||
};
|
||||
let single_up = up && roots.len() == 1;
|
||||
for (name, def) in roots {
|
||||
walk.root(name, def, up);
|
||||
if modules_named(project.index(), root).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
}
|
||||
let emptied = walk.glob.is_some()
|
||||
&& match root {
|
||||
Some(root) if single_up => {
|
||||
walk.nodes.len() == 1 && !index.instantiations_of(root).is_empty()
|
||||
let index = project.index();
|
||||
let declared = modules_named(index, root);
|
||||
if declared.is_empty() {
|
||||
let similar = names::similar_units(index, root, 10);
|
||||
return Err(match similar.is_empty() {
|
||||
true => format!("no module or interface named `{root}`."),
|
||||
false => {
|
||||
format!("no module or interface named `{root}`; similar: {}.", similar.join(", "))
|
||||
}
|
||||
None => walk.nodes.is_empty() && !top_modules(index).is_empty(),
|
||||
Some(_) => false,
|
||||
};
|
||||
let shape = Shape { up, single_up, emptied };
|
||||
Ok(render(project, walk.nodes, shape, args))
|
||||
});
|
||||
}
|
||||
let (up, depth) = (args.flag("up"), args.count("depth", 1));
|
||||
let mut walk = Walk::new(index, depth, !up);
|
||||
if up {
|
||||
walk.path = vec![root.to_string()];
|
||||
walk.up(root, 1);
|
||||
} else {
|
||||
for def in declared {
|
||||
walk.root(root, def);
|
||||
}
|
||||
}
|
||||
if up && walk.nodes.is_empty() {
|
||||
return Ok(Answer::lines(vec![format!("nothing instantiates {root}")]));
|
||||
}
|
||||
Ok(Answer::lines(render_nodes(project, &walk.nodes, up, args.flag("peek"))))
|
||||
}
|
||||
|
||||
/// `N files, M modules, K top`, then each top module as `name file:line`.
|
||||
fn overview(project: &Project) -> Vec<String> {
|
||||
let index = project.index();
|
||||
let modules = index.units_of(SymbolKind::Module).count();
|
||||
let tops = top_modules(index);
|
||||
let files = project.files().count();
|
||||
let (files, modules) = (render::count(files, "file"), render::count(modules, "module"));
|
||||
let mut lines = vec![format!("{files}, {modules}, {} top", tops.len())];
|
||||
for (name, def) in &tops {
|
||||
let path = index.path(def.file).unwrap_or(Path::new(""));
|
||||
lines.push(format!("{name} {}:{}", project.relative(path), def.lines.name));
|
||||
}
|
||||
render::capped(lines, CAP)
|
||||
}
|
||||
|
||||
/// Every instantiable declaration of `name`.
|
||||
@@ -197,11 +158,19 @@ fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A walk in progress: the edges by owner, what it collected, and the path
|
||||
/// of modules above the current node.
|
||||
struct Walk<'a> {
|
||||
index: &'a WorkspaceIndex,
|
||||
below: HashMap<(FileId, u32), Vec<Child>>,
|
||||
max_depth: usize,
|
||||
nodes: Vec<Node>,
|
||||
path: Vec<String>,
|
||||
}
|
||||
|
||||
impl<'a> Walk<'a> {
|
||||
/// A walk over `project`'s index; the owner table is built only for
|
||||
/// `down`.
|
||||
fn new(project: &'a Project, glob: Option<&'a str>, max_depth: usize, down: bool) -> Walk<'a> {
|
||||
let index = project.index();
|
||||
/// A walk over the index; the owner table is built only for `down`.
|
||||
fn new(index: &'a WorkspaceIndex, max_depth: usize, down: bool) -> Walk<'a> {
|
||||
let mut below: HashMap<(FileId, u32), Vec<Child>> = HashMap::new();
|
||||
for (module, edges) in index.instantiations().filter(|_| down) {
|
||||
for edge in edges {
|
||||
@@ -214,14 +183,7 @@ impl<'a> Walk<'a> {
|
||||
for children in below.values_mut() {
|
||||
children.sort_by_key(|child| child.name.start);
|
||||
}
|
||||
Walk { project, index, glob, below, max_depth, nodes: Vec::new(), path: Vec::new() }
|
||||
}
|
||||
|
||||
/// Whether the `in` glob (if any) keeps an entry in `file`.
|
||||
fn keeps(&self, file: FileId) -> bool {
|
||||
let Some(glob) = self.glob else { return true };
|
||||
let path = self.index.path(file);
|
||||
path.is_some_and(|path| path_match(glob, &self.project.relative(path)))
|
||||
Walk { index, below, max_depth, nodes: Vec::new(), path: Vec::new() }
|
||||
}
|
||||
|
||||
fn full(&self) -> bool {
|
||||
@@ -229,24 +191,21 @@ impl<'a> Walk<'a> {
|
||||
}
|
||||
|
||||
/// One root line and its tree.
|
||||
fn root(&mut self, name: String, def: Def, up: bool) {
|
||||
fn root(&mut self, name: &str, def: Def) {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
self.path = vec![name.clone()];
|
||||
self.path = vec![name.to_string()];
|
||||
let line = Node {
|
||||
depth: 0,
|
||||
instance: None,
|
||||
module: name.clone(),
|
||||
module: name.to_string(),
|
||||
root: Some(def.clone()),
|
||||
note: None,
|
||||
declared: 1,
|
||||
};
|
||||
self.nodes.push(line);
|
||||
if up {
|
||||
self.up(&name, 1);
|
||||
} else {
|
||||
self.down(&def, 1);
|
||||
}
|
||||
self.down(&def, 1);
|
||||
}
|
||||
|
||||
/// The instances `def` declares, and theirs, to `max_depth`.
|
||||
@@ -258,16 +217,12 @@ impl<'a> Walk<'a> {
|
||||
return;
|
||||
}
|
||||
let declared = modules_named(self.index, &child.module);
|
||||
// `in` asks for the module's own file; one not indexed has none.
|
||||
if self.glob.is_some() && !declared.iter().any(|def| self.keeps(def.file)) {
|
||||
continue;
|
||||
}
|
||||
let recursive = self.path.contains(&child.module);
|
||||
let note = match declared.len() {
|
||||
_ if recursive => Some("recursive".to_string()),
|
||||
0 => Some("not indexed".to_string()),
|
||||
_ if recursive => Some("recursive"),
|
||||
0 => Some("not indexed"),
|
||||
1 => None,
|
||||
n => Some(format!("declared {n} times")),
|
||||
_ => Some("declared"),
|
||||
};
|
||||
let expand = note.is_none() && depth < self.max_depth;
|
||||
let module = child.module.clone();
|
||||
@@ -277,6 +232,7 @@ impl<'a> Walk<'a> {
|
||||
module: module.clone(),
|
||||
root: None,
|
||||
note,
|
||||
declared: declared.len(),
|
||||
});
|
||||
if let (true, [only]) = (expand, declared.as_slice()) {
|
||||
self.path.push(module);
|
||||
@@ -290,23 +246,19 @@ impl<'a> Walk<'a> {
|
||||
fn up(&mut self, module: &str, depth: usize) {
|
||||
let index = self.index;
|
||||
for edge in index.instantiations_of(module) {
|
||||
if !self.keeps(edge.file) {
|
||||
continue;
|
||||
}
|
||||
for occurrence in &edge.instances {
|
||||
if self.full() {
|
||||
return;
|
||||
}
|
||||
let parent = edge.owner.name.clone();
|
||||
let recursive = self.path.contains(&parent);
|
||||
let child = Child::of(module, edge, occurrence);
|
||||
let note = recursive.then(|| "recursive".to_string());
|
||||
self.nodes.push(Node {
|
||||
depth,
|
||||
instance: Some(child),
|
||||
instance: Some(Child::of(module, edge, occurrence)),
|
||||
module: parent.clone(),
|
||||
root: None,
|
||||
note,
|
||||
note: recursive.then_some("recursive"),
|
||||
declared: 1,
|
||||
});
|
||||
if !recursive && depth < self.max_depth {
|
||||
self.path.push(parent.clone());
|
||||
@@ -318,154 +270,93 @@ impl<'a> Walk<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
const NODES: Noun = Noun("node", "nodes");
|
||||
const INSTANTIATIONS: Noun = Noun("instantiation", "instantiations");
|
||||
|
||||
/// How an answer is counted: `up` from one root counts the instantiations
|
||||
/// under its root line, which every page repeats; any other walk counts
|
||||
/// every line. `emptied` when the `in` glob removed every entry there was.
|
||||
struct Shape {
|
||||
up: bool,
|
||||
single_up: bool,
|
||||
emptied: bool,
|
||||
}
|
||||
|
||||
/// The collected nodes, paged, as indented lines and as a flat JSON list.
|
||||
fn render(project: &Project, nodes: Vec<Node>, shape: Shape, args: &Args) -> Answer {
|
||||
let (lead, counted, noun) = match nodes.split_first() {
|
||||
Some((root, rest)) if shape.single_up => (Some(root), rest, INSTANTIATIONS),
|
||||
_ => (None, nodes.as_slice(), NODES),
|
||||
};
|
||||
let page = Page::of(counted, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut text = if shape.emptied { render::none_match(noun) } else { page.header(noun) };
|
||||
let show_overrides = args.flag("overrides", false);
|
||||
/// The nodes as lines, two spaces per level (`up` starts at no indent),
|
||||
/// each followed by its statement on `peek`; cut whole nodes at [`CAP`].
|
||||
fn render_nodes(project: &Project, nodes: &[Node], up: bool, peek: bool) -> Vec<String> {
|
||||
let mut texts = Texts::default();
|
||||
let mut listed: Vec<Value> = Vec::new();
|
||||
for node in lead.into_iter().chain(page.shown) {
|
||||
let line = Line::of(project, &mut texts, node);
|
||||
text.push_str(&" ".repeat(node.depth));
|
||||
text.push_str(&line.text(node, shape.up, show_overrides));
|
||||
text.push('\n');
|
||||
listed.push(line.json(node, shape.up));
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for (at, node) in nodes.iter().enumerate() {
|
||||
let level = if up { node.depth - 1 } else { node.depth };
|
||||
let indent = " ".repeat(level);
|
||||
let mut block = vec![format!("{indent}{}", node_line(project, &mut texts, node, up))];
|
||||
if let (true, Some(child)) = (peek, &node.instance) {
|
||||
let source = statement(project, &mut texts, child);
|
||||
// A blank line of the statement stays blank: no indent of ours.
|
||||
let shown = |line: String| match line.is_empty() {
|
||||
true => line,
|
||||
false => format!("{indent} {line}"),
|
||||
};
|
||||
block.extend(source.into_iter().map(shown));
|
||||
}
|
||||
if lines.len() + block.len() > CAP {
|
||||
lines.push(render::more(nodes.len() - at));
|
||||
return lines;
|
||||
}
|
||||
lines.extend(block);
|
||||
}
|
||||
render::more(&mut text, page.rest());
|
||||
if nodes.len() >= NODE_CAP {
|
||||
text.push_str(&format!("tree cut at {NODE_CAP} nodes; lower `depth` or pick a `root`\n"));
|
||||
}
|
||||
if nodes.is_empty() && !shape.emptied {
|
||||
text = "no modules\n".to_string();
|
||||
}
|
||||
let direction = if shape.up { "up" } else { "down" };
|
||||
let structured = json!({
|
||||
"direction": direction, "nodes": listed, "total": counted.len(),
|
||||
"shown": page.shown_json(), "cut": nodes.len() >= NODE_CAP,
|
||||
});
|
||||
Answer { text, structured }
|
||||
lines
|
||||
}
|
||||
|
||||
/// What one node's line needs from its file: where it is and the overrides.
|
||||
struct Line {
|
||||
file: String,
|
||||
line: u32,
|
||||
overrides: Option<String>,
|
||||
}
|
||||
|
||||
impl Line {
|
||||
fn of(project: &Project, texts: &mut Texts, node: &Node) -> Line {
|
||||
let index = project.index();
|
||||
if let Some(def) = &node.root {
|
||||
/// One node: `instance: module file:line` down, `parent.instance file:line`
|
||||
/// up, `module file:line` for a root — the instance's line is where it is
|
||||
/// instantiated, the root's where it is declared.
|
||||
fn node_line(project: &Project, texts: &mut Texts, node: &Node, up: bool) -> String {
|
||||
let index = project.index();
|
||||
let mut out = match (&node.instance, &node.root) {
|
||||
(Some(child), _) => {
|
||||
let path = index.path(child.file).unwrap_or(Path::new(""));
|
||||
let line = texts.get(path).map_or(0, |(_, lines)| lines.line_col(child.name.start).0);
|
||||
let at = format!("{}:{line}", project.relative(path));
|
||||
match up {
|
||||
false => format!("{}: {} {at}", child.instance, child.module),
|
||||
true => format!("{}.{} {at}", node.module, child.instance),
|
||||
}
|
||||
}
|
||||
(None, Some(def)) => {
|
||||
let path = index.path(def.file).unwrap_or(Path::new(""));
|
||||
return Line { file: project.relative(path), line: def.lines.name, overrides: None };
|
||||
format!("{} {}:{}", node.module, project.relative(path), def.lines.name)
|
||||
}
|
||||
let Some(child) = &node.instance else {
|
||||
return Line { file: String::new(), line: 0, overrides: None };
|
||||
};
|
||||
let path = index.path(child.file).unwrap_or(Path::new(""));
|
||||
let file = project.relative(path);
|
||||
let Some((text, lines)) = texts.get(path) else {
|
||||
return Line { file, line: 0, overrides: None };
|
||||
};
|
||||
let line = lines.line_col(child.name.start).0;
|
||||
Line { file, line, overrides: overrides(text, child) }
|
||||
}
|
||||
|
||||
/// The line as the text answer shows it; the overrides only when
|
||||
/// `show_overrides`.
|
||||
fn text(&self, node: &Node, up: bool, show_overrides: bool) -> String {
|
||||
let mut out = match (&node.instance, up) {
|
||||
(None, _) => format!("{} {}:{}", node.module, self.file, self.line),
|
||||
(Some(child), false) => format!("{} : {}", child.instance, child.module),
|
||||
(Some(child), true) => format!("{}.{}", node.module, child.instance),
|
||||
};
|
||||
if let Some(overrides) = self.overrides.as_ref().filter(|_| show_overrides) {
|
||||
out.push(' ');
|
||||
out.push_str(&source::capped(overrides, OVERRIDES_CAP));
|
||||
}
|
||||
if up && node.instance.is_some() {
|
||||
out.push_str(&format!(" {}:{}", self.file, self.line));
|
||||
}
|
||||
if let Some(note) = &node.note {
|
||||
out.push_str(&format!(" ({note})"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn json(&self, node: &Node, up: bool) -> Value {
|
||||
let child = node.instance.as_ref();
|
||||
json!({
|
||||
"depth": node.depth,
|
||||
"instance": child.map(|child| child.instance.clone()),
|
||||
"module": child.map_or(node.module.clone(), |child| child.module.clone()),
|
||||
"parent": child.filter(|_| up).map(|_| node.module.clone()),
|
||||
"file": self.file,
|
||||
"line": self.line,
|
||||
"overrides": self.overrides,
|
||||
"note": node.note,
|
||||
})
|
||||
(None, None) => node.module.clone(),
|
||||
};
|
||||
match node.note {
|
||||
Some("declared") => out.push_str(&format!(" (declared {} times)", node.declared)),
|
||||
Some(note) => out.push_str(&format!(" ({note})")),
|
||||
None => {}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `#(...)` written between the module name and the instance name,
|
||||
/// comments dropped, on one line — when the file still spells the module
|
||||
/// name at the site.
|
||||
fn overrides(text: &str, child: &Child) -> Option<String> {
|
||||
/// The instantiation statement around `child`, as written: from the start
|
||||
/// of the line naming the module to the end of the line holding its `;`,
|
||||
/// its common indentation removed, cut at [`PEEK_LINES`] lines. Nothing
|
||||
/// when the file no longer spells the module there.
|
||||
fn statement(project: &Project, texts: &mut Texts, child: &Child) -> Vec<String> {
|
||||
let index = project.index();
|
||||
let Some((text, _)) = index.path(child.file).and_then(|path| texts.get(path)) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if text.get(child.site.as_range()) != Some(child.module.as_str()) {
|
||||
return None;
|
||||
}
|
||||
let between = text.get(child.site.end as usize..child.first as usize)?;
|
||||
let written = source::without_comments(between);
|
||||
let written = written.trim();
|
||||
written.starts_with('#').then(|| render::one_line(written))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn child(text: &str, module: &str, instance: &str) -> Child {
|
||||
let site = text.find(module).unwrap() as u32;
|
||||
let name = text.find(instance).unwrap() as u32;
|
||||
Child {
|
||||
instance: instance.to_string(),
|
||||
module: module.to_string(),
|
||||
file: FileId(0),
|
||||
site: TextRange::new(site, site + module.len() as u32),
|
||||
name: TextRange::new(name, name + instance.len() as u32),
|
||||
first: text.find(" u_").unwrap() as u32 + 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overrides_are_sliced_between_the_module_and_the_instance_name() {
|
||||
let text = " fifo #( // sizes\n .Width (8),\n .Depth(2)\n ) u_fifo (.*);";
|
||||
let fifo = child(text, "fifo", "u_fifo");
|
||||
assert_eq!(overrides(text, &fifo).as_deref(), Some("#( .Width (8), .Depth(2) )"));
|
||||
let plain = " fifo u_plain (.*);";
|
||||
assert_eq!(overrides(plain, &child(plain, "fifo", "u_plain")), None);
|
||||
let two = " fifo #(.W(2)) u_a (), u_b ();";
|
||||
assert_eq!(overrides(two, &child(two, "fifo", "u_b")).as_deref(), Some("#(.W(2))"));
|
||||
let mut stale = fifo.clone();
|
||||
stale.module = "other".into();
|
||||
assert_eq!(overrides(text, &stale), None);
|
||||
return Vec::new();
|
||||
}
|
||||
let site = child.site.start as usize;
|
||||
let end = (child.end as usize).min(text.len());
|
||||
let start = text[..site].rfind('\n').map_or(0, |at| at + 1);
|
||||
let semi = text[end..].find(';').map_or(end, |at| end + at + 1);
|
||||
let stop = text[semi..].find('\n').map_or(text.len(), |at| semi + at);
|
||||
let written: Vec<&str> = text[start..stop].lines().map(str::trim_end).collect();
|
||||
let margin = written
|
||||
.iter()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.map(|line| line.len() - line.trim_start().len())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let mut out: Vec<String> = written
|
||||
.iter()
|
||||
.take(PEEK_LINES)
|
||||
.map(|line| line.get(margin..).unwrap_or("").to_string())
|
||||
.collect();
|
||||
if written.len() > PEEK_LINES {
|
||||
out.push("…".to_string());
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1,82 +1,43 @@
|
||||
//! `unit_interface`: what a unit offers the code that uses it — a module's
|
||||
//! or interface's parameters and ports (plus an interface's modports, and
|
||||
//! the instantiation template on request), a package's or class's exported
|
||||
//! members — without the agent reading the file that declares it.
|
||||
//! `outline unit:` — what a unit offers the code that uses it: a module's
|
||||
//! or interface's parameters and ports in declaration order (plus an
|
||||
//! interface's modports), a package's or class's members — without the
|
||||
//! agent reading the file that declares it.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_refactor::{instantiation_plan, InstantiationPlan, Layout};
|
||||
use vlog_refactor::{instantiation_plan, InstantiationPlan};
|
||||
use vlog_semantic::{Def, ScopeId, Semantics, Symbol, SymbolKind};
|
||||
|
||||
use super::read_item::child_items;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
pub const UNIT_INTERFACE: Tool = Tool {
|
||||
name: "unit_interface",
|
||||
title: "Unit interface",
|
||||
description: "A unit's parameters, ports (direction, type, range), modports or members; `template: true` adds an instantiation.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The unit (`pkg::cls` for a class).",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Its file, if declared twice.",
|
||||
},
|
||||
Param {
|
||||
name: "template",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Add the instantiation.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: unit_interface,
|
||||
};
|
||||
|
||||
/// A unit found in the index: where it is, and what it is.
|
||||
struct Found {
|
||||
path: PathBuf,
|
||||
def: Def,
|
||||
}
|
||||
|
||||
fn unit_interface(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or("");
|
||||
let mut found = candidates(project, name, args.str("file"))?;
|
||||
/// The unit's `file:line`, then its interface, one fact per line.
|
||||
pub fn unit_outline(project: &mut Project, name: &str) -> Result<Vec<String>, String> {
|
||||
let mut found = candidates(project, name);
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
found = candidates(project, name, args.str("file"))?;
|
||||
found = candidates(project, name);
|
||||
}
|
||||
let found = pick(project, found, name, args.str("file"))?;
|
||||
let found = pick(project, found, name)?;
|
||||
let analysis = project.analysis(&found.path)?;
|
||||
let file = project.relative(&found.path);
|
||||
let kind = super::read::unit_kind(project, &found.path, &found.def);
|
||||
let head = format!("{kind} {name} {file}:{}\n", found.def.lines.name);
|
||||
let head = format!("{}:{}", project.relative(&found.path), found.def.lines.name);
|
||||
let short = name.rsplit("::").next().unwrap_or(name);
|
||||
match found.def.kind {
|
||||
SymbolKind::Module | SymbolKind::Interface => {
|
||||
let template = args.flag("template", false);
|
||||
instantiable(&analysis, &found, short, head, &file, template).map(|mut answer| {
|
||||
answer.structured["kind"] = Value::from(kind);
|
||||
answer
|
||||
})
|
||||
}
|
||||
_ => Ok(members(project, &analysis, &found, short, head, &file)),
|
||||
SymbolKind::Module | SymbolKind::Interface => instantiable(&analysis, &found, short, head),
|
||||
_ => Ok(members(project, &analysis, &found, short, head)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `file`, when given). `Err` only
|
||||
/// when `file` itself is refused.
|
||||
fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<Found>, String> {
|
||||
/// Every indexed unit declaration of `name` (`pkg::cls` for a class).
|
||||
fn candidates(project: &Project, name: &str) -> Vec<Found> {
|
||||
let index = project.index();
|
||||
let unit_kinds =
|
||||
[SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class];
|
||||
@@ -85,30 +46,23 @@ fn candidates(project: &Project, name: &str, file: Option<&str>) -> Result<Vec<F
|
||||
None => index.units(name).to_vec(),
|
||||
};
|
||||
defs.retain(|def| unit_kinds.contains(&def.kind));
|
||||
let mut found: Vec<Found> = defs
|
||||
.into_iter()
|
||||
defs.into_iter()
|
||||
.filter_map(|def| Some(Found { path: index.path(def.file)?.to_path_buf(), def }))
|
||||
.collect();
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
found.retain(|f| f.path == path);
|
||||
}
|
||||
Ok(found)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one declaration among `found`, or a refusal that says why there is
|
||||
/// not exactly one.
|
||||
fn pick(
|
||||
project: &Project,
|
||||
mut found: Vec<Found>,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<Found, String> {
|
||||
fn pick(project: &Project, mut found: Vec<Found>, name: &str) -> Result<Found, String> {
|
||||
match found.len() {
|
||||
0 => Err(format!(
|
||||
"no module, interface, package or class named `{name}` is indexed{}; search_symbols finds near names.",
|
||||
file.map_or(String::new(), |f| format!(" in `{f}`"))
|
||||
)),
|
||||
0 => {
|
||||
let similar = super::names::similar_units(project.index(), name, 10);
|
||||
let near = match similar.is_empty() {
|
||||
true => String::new(),
|
||||
false => format!("; similar: {}", similar.join(", ")),
|
||||
};
|
||||
Err(format!("no module, interface, package or class named `{name}`{near}."))
|
||||
}
|
||||
1 => Ok(found.remove(0)),
|
||||
_ => {
|
||||
let sites: Vec<String> = found
|
||||
@@ -116,7 +70,7 @@ fn pick(
|
||||
.map(|f| format!("{}:{}", project.relative(&f.path), f.def.lines.name))
|
||||
.collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pass `file` to pick one.",
|
||||
"`{name}` is declared {} times ({}); outline one `file` instead.",
|
||||
sites.len(),
|
||||
sites.join(", ")
|
||||
))
|
||||
@@ -124,42 +78,30 @@ fn pick(
|
||||
}
|
||||
}
|
||||
|
||||
/// A module's or interface's parameters, ports and modports, and its
|
||||
/// template when `with_template` asks for it.
|
||||
/// A module's or interface's parameters, ports and modports.
|
||||
fn instantiable(
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
head: String,
|
||||
file: &str,
|
||||
with_template: bool,
|
||||
) -> Result<Answer, String> {
|
||||
) -> Result<Vec<String>, String> {
|
||||
let plan = instantiation_plan(name, &analysis.text, None)?;
|
||||
let scope = unit_symbol(&analysis.semantics, found, name).and_then(|s| s.child_scope);
|
||||
let ports = port_rows(&plan, analysis, scope);
|
||||
let modports = match (found.def.kind, scope) {
|
||||
(SymbolKind::Interface, Some(scope)) => modports_of(analysis, scope),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let template = with_template.then(|| plan.render(&Layout::default()));
|
||||
let text = interface_text(head, &plan, &ports, &modports, template.as_deref());
|
||||
let mut structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"parameters": plan.params.iter().map(|p| json!({ "name": p.name, "default": p.default })).collect::<Vec<_>>(),
|
||||
"ports": ports.iter().map(PortRow::to_json).collect::<Vec<_>>(),
|
||||
"modports": modports,
|
||||
"warnings": plan.warnings,
|
||||
});
|
||||
if let Some(template) = template {
|
||||
structured["template"] = Value::from(template);
|
||||
let mut lines = vec![head];
|
||||
lines.extend(plan.params.iter().map(|p| match p.default.trim() {
|
||||
"" => format!("param {}", p.name),
|
||||
default => format!("param {} = {}", p.name, render::one_line(default)),
|
||||
}));
|
||||
lines.extend(port_lines(&plan, analysis, scope));
|
||||
if let (SymbolKind::Interface, Some(scope)) = (found.def.kind, scope) {
|
||||
lines.extend(modports_of(analysis, scope));
|
||||
}
|
||||
Ok(Answer { text, structured })
|
||||
render::warnings(&mut lines, &plan.warnings);
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
/// An interface's modports, each as its declaration reads on one line.
|
||||
/// An interface's modports, each as its declaration reads on one line,
|
||||
/// led by the keyword.
|
||||
fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
|
||||
analysis
|
||||
.semantics
|
||||
@@ -167,59 +109,13 @@ fn modports_of(analysis: &Analysis, scope: ScopeId) -> Vec<String> {
|
||||
.iter()
|
||||
.filter(|s| s.scope == scope && s.kind == SymbolKind::Modport)
|
||||
.map(|s| render::one_line(analysis.slice(s.decl_span.start, s.decl_span.end)))
|
||||
.map(|written| match written.starts_with("modport") {
|
||||
true => written,
|
||||
false => format!("modport {written}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The text answer: the head line, then each non-empty section; the
|
||||
/// template last, when asked for.
|
||||
fn interface_text(
|
||||
mut text: String,
|
||||
plan: &InstantiationPlan,
|
||||
ports: &[PortRow],
|
||||
modports: &[String],
|
||||
template: Option<&str>,
|
||||
) -> String {
|
||||
if !plan.params.is_empty() {
|
||||
text.push_str(&format!("parameters ({}):\n", plan.params.len()));
|
||||
let rows: Vec<Vec<String>> =
|
||||
plan.params.iter().map(|p| vec![p.name.clone(), default_cell(&p.default)]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !ports.is_empty() {
|
||||
text.push_str(&format!("ports ({}):\n", ports.len()));
|
||||
let rows: Vec<Vec<String>> = ports
|
||||
.iter()
|
||||
.map(|p| vec![p.dir.clone(), p.written_type(), p.name_with_unpacked()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
}
|
||||
if !modports.is_empty() {
|
||||
text.push_str("modports:\n");
|
||||
for modport in modports {
|
||||
text.push_str(&format!(" {modport}\n"));
|
||||
}
|
||||
}
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
if let Some(template) = template {
|
||||
text.push_str("template:\n");
|
||||
text.push_str(template);
|
||||
if !template.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
fn default_cell(default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
"(no default)".to_string()
|
||||
} else {
|
||||
format!("= {}", render::one_line(default))
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit's own symbol in the file's analysis: the declaration at the
|
||||
/// indexed name, else the first of its kind spelling the name.
|
||||
fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Option<&'s Symbol> {
|
||||
@@ -236,59 +132,21 @@ fn unit_symbol<'s>(semantics: &'s Semantics, found: &Found, name: &str) -> Optio
|
||||
)
|
||||
}
|
||||
|
||||
/// One port as the answer shows it.
|
||||
struct PortRow {
|
||||
dir: String,
|
||||
ty: String,
|
||||
range: String,
|
||||
name: String,
|
||||
unpacked: String,
|
||||
}
|
||||
|
||||
impl PortRow {
|
||||
/// The type as the declaration writes it, packed range included — one
|
||||
/// column, so a long type name widens one column rather than two.
|
||||
fn written_type(&self) -> String {
|
||||
match (self.ty.is_empty(), self.range.is_empty()) {
|
||||
(_, true) => self.ty.clone(),
|
||||
(true, false) => self.range.clone(),
|
||||
(false, false) => format!("{} {}", self.ty, self.range),
|
||||
}
|
||||
}
|
||||
|
||||
fn name_with_unpacked(&self) -> String {
|
||||
if self.unpacked.is_empty() {
|
||||
self.name.clone()
|
||||
} else {
|
||||
format!("{} {}", self.name, self.unpacked)
|
||||
}
|
||||
}
|
||||
|
||||
fn to_json(&self) -> Value {
|
||||
json!({
|
||||
"direction": self.dir, "type": self.ty, "range": self.range,
|
||||
"name": self.name, "unpacked": self.unpacked,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan's ports with the packed range split off the type, and the
|
||||
/// unpacked dimensions an ANSI port writes after its name.
|
||||
fn port_rows(
|
||||
/// Each port as `dir type [range] name [unpacked]`, the empty parts left
|
||||
/// out.
|
||||
fn port_lines(
|
||||
plan: &InstantiationPlan,
|
||||
analysis: &Analysis,
|
||||
scope: Option<ScopeId>,
|
||||
) -> Vec<PortRow> {
|
||||
) -> Vec<String> {
|
||||
plan.ports
|
||||
.iter()
|
||||
.map(|port| {
|
||||
let (ty, range) = match port.ty.find('[') {
|
||||
Some(at) => (port.ty[..at].trim().to_string(), port.ty[at..].trim().to_string()),
|
||||
None => (port.ty.clone(), String::new()),
|
||||
};
|
||||
let unpacked =
|
||||
scope.map_or(String::new(), |scope| unpacked(analysis, scope, &port.name));
|
||||
PortRow { dir: port.dir.clone(), ty, range, name: port.name.clone(), unpacked }
|
||||
let parts = [port.dir.as_str(), port.ty.trim(), port.name.as_str(), unpacked.as_str()];
|
||||
let parts: Vec<&str> = parts.into_iter().filter(|part| !part.is_empty()).collect();
|
||||
render::one_line(&parts.join(" "))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -322,20 +180,19 @@ fn unpacked(analysis: &Analysis, scope: ScopeId, name: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// A package's or class's members, in declaration order, and a class's
|
||||
/// base. `name` is the unit's own name, without a package prefix — which
|
||||
/// two classes in two packages may share, so both answers are read off this
|
||||
/// declaration: a member counts only when it is declared inside
|
||||
/// `found.def.decl_span`, and the base is what this declaration's own
|
||||
/// `extends` writes.
|
||||
/// A package's or class's members, in declaration order, as `kind name
|
||||
/// LINE`, and a class's base. `name` is the unit's own name, without a
|
||||
/// package prefix — which two classes in two packages may share, so both
|
||||
/// answers are read off this declaration: a member counts only when it is
|
||||
/// declared inside `found.def.decl_span`, and the base is what this
|
||||
/// declaration's own `extends` writes.
|
||||
fn members(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
found: &Found,
|
||||
name: &str,
|
||||
mut text: String,
|
||||
file: &str,
|
||||
) -> Answer {
|
||||
head: String,
|
||||
) -> Vec<String> {
|
||||
let index = project.index();
|
||||
let within = found.def.decl_span;
|
||||
let mut rows: Vec<(u32, &'static str, String)> = index
|
||||
@@ -350,25 +207,12 @@ fn members(
|
||||
})
|
||||
.collect();
|
||||
rows.sort();
|
||||
let base = class_base(&analysis.tree.items, found.def.name_span);
|
||||
if let Some(base) = &base {
|
||||
text.push_str(&format!("extends {base}\n"));
|
||||
let mut lines = vec![head];
|
||||
if let Some(base) = class_base(&analysis.tree.items, found.def.name_span) {
|
||||
lines.push(format!("extends {base}"));
|
||||
}
|
||||
text.push_str("members:\n");
|
||||
let table: Vec<Vec<String>> = rows
|
||||
.iter()
|
||||
.map(|(line, kind, member)| vec![kind.to_string(), member.clone(), line.to_string()])
|
||||
.collect();
|
||||
text.push_str(&render::table(&table));
|
||||
let structured = json!({
|
||||
"name": name,
|
||||
"kind": render::kind(found.def.kind),
|
||||
"file": file,
|
||||
"line": found.def.lines.name,
|
||||
"extends": base,
|
||||
"members": rows.iter().map(|(line, kind, member)| json!({ "name": member, "kind": kind, "line": line })).collect::<Vec<_>>(),
|
||||
});
|
||||
Answer { text, structured }
|
||||
lines.extend(rows.iter().map(|(line, kind, member)| format!("{kind} {member} {line}")));
|
||||
lines
|
||||
}
|
||||
|
||||
/// The base the class declared at `name_span` names in its `extends`, read
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
//! The structural edits — `replace_item`, `insert_item`, `delete_item` — the
|
||||
//! general token saver: an agent sends one item's text, never the file.
|
||||
//! `edit_item` — the structural edits under one name (`replace`,
|
||||
//! `insert_before`, `insert_after`, `delete`), the general token saver: an
|
||||
//! agent sends one item's text, never the file.
|
||||
//!
|
||||
//! Each tool finds its place with `read_item`'s own slicer
|
||||
//! Each op finds its place with the slicer `read` uses
|
||||
//! ([`read_item::select`]), so the bytes it replaces are exactly the bytes
|
||||
//! `read_item` showed; builds a [`Splice`]; hands it to [`verify::check`]
|
||||
//! (the rules are there); and writes through `apply::run`, the one write
|
||||
//! path (dry run, freshness, atomic write). Contract and rules:
|
||||
//! `docs/features/mcp-structural-edits/README.md`.
|
||||
//! `read` showed; builds a [`Splice`]; hands it to [`verify::check`] (the
|
||||
//! rules are there); and writes through `apply::run`, the one write path
|
||||
//! (freshness, atomic write). Contract and rules:
|
||||
//! `docs/features/mcp-structural-edits/README.md`; the lean surface:
|
||||
//! `docs/features/mcp-lean-catalogue/README.md`.
|
||||
|
||||
mod lexical;
|
||||
mod macros;
|
||||
@@ -18,12 +20,10 @@ mod verify;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::json;
|
||||
use vlog_formatter::fence;
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
|
||||
use super::edit::DRY_RUN;
|
||||
use super::read_item::{child_items, select};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::apply::{self, Change, Plan};
|
||||
@@ -35,76 +35,35 @@ use span::{
|
||||
};
|
||||
use verify::{Expect, Splice};
|
||||
|
||||
const FILE: Param = Param { name: "file", ty: Ty::Str, required: true, description: "The file." };
|
||||
const ITEM: Param =
|
||||
Param { name: "item", ty: Ty::Str, required: true, description: "`read_item`'s selector." };
|
||||
const TEXT: Param =
|
||||
Param { name: "text", ty: Ty::Str, required: true, description: "The source text." };
|
||||
|
||||
pub const REPLACE_ITEM: Tool = Tool {
|
||||
name: "replace_item",
|
||||
title: "Replace one item",
|
||||
description: "Replace one item with `text`: one item, same kind and names (unless `rename`; references untouched). Comments around `text` replace the item's own.",
|
||||
pub const EDIT_ITEM: Tool = Tool {
|
||||
name: "edit_item",
|
||||
description: "One item of `file` (selector as read): `op` replace it by `text` (same kind and names), insert `text` before/after it (item `end`/`end@UNIT`: a unit's end), or delete it if unused.",
|
||||
params: &[
|
||||
FILE,
|
||||
ITEM,
|
||||
TEXT,
|
||||
Param { name: "file", ty: Ty::Str, required: true },
|
||||
Param {
|
||||
name: "rename",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Allow other declared names.",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: replace_item,
|
||||
};
|
||||
|
||||
pub const INSERT_ITEM: Tool = Tool {
|
||||
name: "insert_item",
|
||||
title: "Insert items",
|
||||
description: "Insert items `text` before or after item `anchor`, or at `end` (`end@NAME`) of the last unit (unit NAME).",
|
||||
params: &[
|
||||
FILE,
|
||||
Param {
|
||||
name: "anchor",
|
||||
ty: Ty::Str,
|
||||
name: "op",
|
||||
ty: Ty::Enum(&["replace", "insert_before", "insert_after", "delete"]),
|
||||
required: true,
|
||||
description: "An item selector, `end`, or `end@NAME`.",
|
||||
},
|
||||
Param {
|
||||
name: "position",
|
||||
ty: Ty::Enum(&["before", "after"]),
|
||||
required: false,
|
||||
description: "`before` or `after` (default).",
|
||||
},
|
||||
TEXT,
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: insert_item,
|
||||
};
|
||||
|
||||
pub const DELETE_ITEM: Tool = Tool {
|
||||
name: "delete_item",
|
||||
title: "Delete one item",
|
||||
description: "Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a `define, unless `force`.",
|
||||
params: &[
|
||||
FILE,
|
||||
ITEM,
|
||||
Param {
|
||||
name: "force",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Delete anyway.",
|
||||
},
|
||||
DRY_RUN,
|
||||
Param { name: "item", ty: Ty::Str, required: true },
|
||||
Param { name: "text", ty: Ty::Str, required: false },
|
||||
],
|
||||
rewalk: true,
|
||||
handler: delete_item,
|
||||
handler: edit_item,
|
||||
};
|
||||
|
||||
fn edit_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let op = args.str("op").unwrap_or_default();
|
||||
let text = args.str("text");
|
||||
match (op, text) {
|
||||
("delete", None) => delete_item(project, args),
|
||||
("delete", Some(_)) => Err("`delete` takes no `text`; nothing written.".into()),
|
||||
(_, None) => Err(format!("`{op}` needs `text`; nothing written.")),
|
||||
("replace", Some(text)) => replace_item(project, args, text),
|
||||
(_, Some(text)) => insert_item(project, args, text, op == "insert_before"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file a call names: its path, its root-relative name and analysis.
|
||||
/// A file that does not lex is refused here: no span in it can be trusted.
|
||||
fn open(project: &mut Project, args: &Args) -> Result<(PathBuf, String, Rc<Analysis>), String> {
|
||||
@@ -134,7 +93,7 @@ fn target<'a>(analysis: &'a Analysis, selector: &str, file: &str) -> Result<Loca
|
||||
select(analysis, selector).map_err(|why| format!("{why} in `{file}`; nothing written."))?;
|
||||
locate(&analysis.tree.items, span).ok_or_else(|| {
|
||||
format!(
|
||||
"`{selector}` is part of a larger item (a port in a module header, an argument, a generate branch), not an item of its own; edit the enclosing item (`add_port`/`remove_port` for ports); nothing written."
|
||||
"`{selector}` is part of a larger item (a port in a module header, an argument, a generate branch), not an item of its own; edit the enclosing item (`port` for ports); nothing written."
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -165,58 +124,56 @@ fn fenced(text: &str, start: u32, end: u32) -> bool {
|
||||
|
||||
const FENCED: &str = "lies inside a `// lucisv: off` fence, which no lucisv tool edits";
|
||||
|
||||
fn replace_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
fn replace_item(project: &mut Project, args: &Args, text: &str) -> Result<Answer, String> {
|
||||
let (path, file, analysis) = open(project, args)?;
|
||||
let selector = args.str("item").unwrap_or("").trim();
|
||||
let located = target(&analysis, selector, &file)?;
|
||||
let span = located.item.span;
|
||||
let text = normalise(args.str("text").unwrap_or(""), &analysis.text, false)?;
|
||||
let dry_run = args.flag("dry_run", false);
|
||||
let text = normalise(text, &analysis.text, false)?;
|
||||
let (start, end) = replace_region(&analysis.text, located.item, &text);
|
||||
let class = verify::class_of(&located.item.kind);
|
||||
// The item as it already is: a no-op, not a refusal (even in a fence).
|
||||
if text == analysis.slice(start, end) {
|
||||
return apply::run(project, Plan::default(), dry_run);
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
let names = verify::owned_names(&analysis, span);
|
||||
return Ok(said("unchanged", class, &names, &file, (first, last), Vec::new()));
|
||||
}
|
||||
if fenced(&analysis.text, start, end) {
|
||||
return Err(format!("`{selector}` {FENCED}; nothing written."));
|
||||
}
|
||||
let class = verify::class_of(&located.item.kind);
|
||||
let splice = Splice { start, old_end: end, text };
|
||||
let outcome = verify::check(&analysis, &splice, Expect::One(class)).map_err(refused(&file))?;
|
||||
let new_span = outcome.items.first().map_or(span, |(_, span)| *span);
|
||||
let was = verify::owned_names(&analysis, span);
|
||||
let now = verify::owned_names(&outcome.analysis, new_span);
|
||||
let warnings = name_rule(&was, &now, args.flag("rename", false))?;
|
||||
name_rule(&was, &now)?;
|
||||
let lines = outcome.analysis.line_span(new_span.start, new_span.end);
|
||||
let note = format!("replaced {class}{}", named(&now));
|
||||
finish(project, (path, &analysis, outcome.text), note, lines, warnings, dry_run)
|
||||
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
|
||||
Ok(said("replaced", class, &now, &file, lines, Vec::new()))
|
||||
}
|
||||
|
||||
/// The text declares the names the item did, unless `rename` allows others
|
||||
/// — and then the answer warns that no reference followed.
|
||||
fn name_rule(was: &[String], now: &[String], rename: bool) -> Result<Vec<String>, String> {
|
||||
/// The text declares the names the item did: a replacement that renames
|
||||
/// would leave every reference behind (`rename` renames with references).
|
||||
fn name_rule(was: &[String], now: &[String]) -> Result<(), String> {
|
||||
if was == now {
|
||||
return Ok(Vec::new());
|
||||
return Ok(());
|
||||
}
|
||||
if !rename {
|
||||
return Err(format!(
|
||||
"the text declares {} where the item declared {}; pass `rename: true` to allow it (references are not updated; `rename` does that); nothing written.",
|
||||
listed(now),
|
||||
listed(was)
|
||||
));
|
||||
}
|
||||
Ok(vec![format!(
|
||||
"{} replaced by {}: references are NOT updated (the `rename` tool renames with references)",
|
||||
listed(was),
|
||||
listed(now)
|
||||
)])
|
||||
Err(format!(
|
||||
"the text declares {} where the item declared {}; `rename` renames a declaration with its references; nothing written.",
|
||||
listed(now),
|
||||
listed(was)
|
||||
))
|
||||
}
|
||||
|
||||
fn insert_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
fn insert_item(
|
||||
project: &mut Project,
|
||||
args: &Args,
|
||||
text: &str,
|
||||
before: bool,
|
||||
) -> Result<Answer, String> {
|
||||
let (path, file, analysis) = open(project, args)?;
|
||||
let anchor = args.str("anchor").unwrap_or("").trim();
|
||||
let before = args.str("position") == Some("before");
|
||||
let text = normalise(args.str("text").unwrap_or(""), &analysis.text, true)?;
|
||||
let anchor = args.str("item").unwrap_or("").trim();
|
||||
let text = normalise(text, &analysis.text, true)?;
|
||||
let spot = match anchor.strip_prefix("end") {
|
||||
Some(rest) if rest.is_empty() || rest.starts_with('@') => {
|
||||
end_spot(&analysis, rest.trim_start_matches('@'), &file)?
|
||||
@@ -242,9 +199,8 @@ fn insert_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
.iter()
|
||||
.flat_map(|(_, span)| verify::owned_names(&outcome.analysis, *span))
|
||||
.collect();
|
||||
let note = format!("inserted {}{}", classes.join(", "), named(&names));
|
||||
let dry_run = args.flag("dry_run", false);
|
||||
finish(project, (path, &analysis, outcome.text), note, lines, Vec::new(), dry_run)
|
||||
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
|
||||
Ok(said("inserted", &classes.join(", "), &names, &file, lines, Vec::new()))
|
||||
}
|
||||
|
||||
fn delete_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
@@ -258,32 +214,30 @@ fn delete_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
return Err(format!("`{selector}` {FENCED}; nothing written."));
|
||||
}
|
||||
let removed = TextRange::new(start, end);
|
||||
let force = args.flag("force", false);
|
||||
let place = refs::Place { item: located.item.span, removed, scope: located.siblings };
|
||||
let mut warnings = refs::check(project, &path, &analysis, &place, force)?;
|
||||
let warnings = refs::check(project, &path, &analysis, &place)?;
|
||||
let class = verify::class_of(&located.item.kind);
|
||||
let splice = Splice { start, old_end: end, text: String::new() };
|
||||
let outcome =
|
||||
verify::check(&analysis, &splice, Expect::Nothing { force }).map_err(refused(&file))?;
|
||||
warnings.extend(dropped_macros_warning(&outcome.dropped_macros));
|
||||
let outcome = verify::check(&analysis, &splice, Expect::Nothing).map_err(refused(&file))?;
|
||||
let names = verify::owned_names(&analysis, located.item.span);
|
||||
let lines = analysis.line_span(start, end);
|
||||
let note =
|
||||
format!("deleted {class}{} (old lines {})", named(&names), render::lines(lines.0, lines.1));
|
||||
let dry_run = args.flag("dry_run", false);
|
||||
let plan = plan(path, &analysis, outcome.text, note, warnings);
|
||||
apply::run(project, plan, dry_run)
|
||||
apply::run(project, &plan(path, &analysis, outcome.text, Vec::new()))?;
|
||||
Ok(said("deleted", class, &names, &file, lines, warnings))
|
||||
}
|
||||
|
||||
/// What a forced deletion says about the macro definitions it removed
|
||||
/// (the M4 review's ruling on rule 6): nothing when it removed none.
|
||||
fn dropped_macros_warning(names: &[String]) -> Option<String> {
|
||||
(!names.is_empty()).then(|| {
|
||||
format!(
|
||||
"deleted macro definitions: {} — code after the item that used them will change meaning",
|
||||
names.join(", ")
|
||||
)
|
||||
})
|
||||
/// `replaced function f file:12–20`, then any warning lines.
|
||||
fn said(
|
||||
verb: &str,
|
||||
class: &str,
|
||||
names: &[String],
|
||||
file: &str,
|
||||
(first, last): (u32, u32),
|
||||
warnings: Vec<String>,
|
||||
) -> Answer {
|
||||
let named = if names.is_empty() { String::new() } else { format!(" {}", names.join(", ")) };
|
||||
let mut lines = vec![format!("{verb} {class}{named} {file}:{}", render::lines(first, last))];
|
||||
render::warnings(&mut lines, &warnings);
|
||||
Answer::lines(lines)
|
||||
}
|
||||
|
||||
/// Whether the item's own leading comments hold a fence line: deleting one
|
||||
@@ -293,34 +247,9 @@ fn fence_comment(item: &Item) -> bool {
|
||||
}
|
||||
|
||||
/// The one-file plan: the analysed text before, the verified text after.
|
||||
fn plan(
|
||||
path: PathBuf,
|
||||
analysis: &Analysis,
|
||||
after: String,
|
||||
note: String,
|
||||
warnings: Vec<String>,
|
||||
) -> Plan {
|
||||
fn plan(path: PathBuf, analysis: &Analysis, after: String, warnings: Vec<String>) -> Plan {
|
||||
let change = Change { path, before: analysis.text.clone(), after, created: false };
|
||||
Plan { changes: vec![change], note: Some(note), warnings, ..Plan::default() }
|
||||
}
|
||||
|
||||
/// Write (or diff) a replace or insert, its note carrying the new item's
|
||||
/// lines and the hint; the lines are in `structuredContent.item` too.
|
||||
fn finish(
|
||||
project: &Project,
|
||||
(path, analysis, after): (PathBuf, &Analysis, String),
|
||||
note: String,
|
||||
(first, last): (u32, u32),
|
||||
warnings: Vec<String>,
|
||||
dry_run: bool,
|
||||
) -> Result<Answer, String> {
|
||||
let lines = render::lines(first, last);
|
||||
let note = format!(
|
||||
"{note} (lines {lines})\nhint: run `format` with `lines: \"{lines}\"` to reflow; `diagnostics` to check"
|
||||
);
|
||||
let mut answer = apply::run(project, plan(path, analysis, after, note, warnings), dry_run)?;
|
||||
answer.structured["item"] = json!({ "lines": [first, last] });
|
||||
Ok(answer)
|
||||
Plan { changes: vec![change], warnings }
|
||||
}
|
||||
|
||||
/// `` `a`, `b` `` for a list of names; `nothing` when empty.
|
||||
@@ -331,18 +260,9 @@ fn listed(names: &[String]) -> String {
|
||||
names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// ` `a`, `b`` after a kind word, or nothing.
|
||||
fn named(names: &[String]) -> String {
|
||||
if names.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(" {}", listed(names))
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` made ready to splice: surrounding blank space dropped (for an
|
||||
/// insertion, the first line's indentation is kept), line endings made the
|
||||
/// file's. Empty text is refused: deleting is `delete_item`'s.
|
||||
/// file's. Empty text is refused: deleting is `op: delete`'s.
|
||||
fn normalise(text: &str, file_text: &str, keep_indent: bool) -> Result<String, String> {
|
||||
let trimmed = text.trim_end_matches(|c: char| c.is_ascii_whitespace());
|
||||
let trimmed = if keep_indent {
|
||||
@@ -352,7 +272,7 @@ fn normalise(text: &str, file_text: &str, keep_indent: bool) -> Result<String, S
|
||||
trimmed.trim_start_matches(|c: char| c.is_ascii_whitespace())
|
||||
};
|
||||
if trimmed.is_empty() {
|
||||
return Err("`text` is empty; `delete_item` removes an item; nothing written.".into());
|
||||
return Err("`text` is empty; `op: delete` removes an item; nothing written.".into());
|
||||
}
|
||||
let lf = trimmed.replace("\r\n", "\n");
|
||||
Ok(if line_ending(file_text) == "\r\n" { lf.replace('\n', "\r\n") } else { lf })
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `delete_item`'s macro rule: a name spelled inside a macro call's
|
||||
//! `op: delete`'s macro rule: a name spelled inside a macro call's
|
||||
//! arguments (`` `ASSERT_KNOWN(k, sig) ``) or a `` `define`` body is a use
|
||||
//! no lucisv engine resolves — the lexer keeps a macro call as one token and
|
||||
//! a `` `define`` as one directive. Each such spelling the engine and the
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! `delete_item`'s reference rule: an item is not deleted while a name it
|
||||
//! owns (`verify::owned`) is still used anywhere in the project, unless the
|
||||
//! agent says `force`.
|
||||
//! `edit_item op: delete`'s reference rule: an item is not deleted while a
|
||||
//! name it owns (`verify::owned`) is still used anywhere in the project.
|
||||
//!
|
||||
//! Uses are `vlog_refactor::find_references` over the whole indexed set,
|
||||
//! read from disk now (`WholeSet`, M2's ruling) — the census `references`
|
||||
@@ -70,7 +69,6 @@ pub fn check(
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
place: &Place,
|
||||
force: bool,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let symbols = verify::owned(analysis, place.item);
|
||||
if symbols.is_empty() {
|
||||
@@ -92,18 +90,10 @@ pub fn check(
|
||||
for symbol in symbols {
|
||||
scan.uses_of(symbol, &mut census);
|
||||
}
|
||||
let mut warnings: Vec<String> = set.warning(project).into_iter().collect();
|
||||
if census.total == 0 {
|
||||
return Ok(warnings);
|
||||
if census.total > 0 {
|
||||
return Err(format!("still referenced: {}; nothing written.", census.render()));
|
||||
}
|
||||
if !force {
|
||||
return Err(format!(
|
||||
"still referenced: {}; nothing written (`force: true` deletes anyway).",
|
||||
census.render()
|
||||
));
|
||||
}
|
||||
warnings.push(format!("deleted with references left: {}", census.render()));
|
||||
Ok(warnings)
|
||||
Ok(set.warning(project).into_iter().collect())
|
||||
}
|
||||
|
||||
/// What one deletion's reference scan reads.
|
||||
@@ -234,7 +224,7 @@ fn within(inner: TextRange, outer: TextRange) -> bool {
|
||||
/// bytes: resolved to it, or to nothing at all. The second kind is what the
|
||||
/// cross-file engine does not follow (a hierarchical path into a generate
|
||||
/// loop, `gen_l[0].z`); counting it may refuse a deletion that was safe,
|
||||
/// never allow one that was not — `force` is the way past.
|
||||
/// never allow one that was not.
|
||||
fn local_uses(analysis: &Analysis, symbol: &Symbol, removed: TextRange) -> Vec<TextRange> {
|
||||
let semantics = &analysis.semantics;
|
||||
let id = semantics.symbol_at(symbol.name_span.start);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Which bytes an item owns: the lines `insert_item` and `delete_item` work
|
||||
//! on, and the span `replace_item` replaces when its text brings comments.
|
||||
//! Which bytes an item owns: the lines `edit_item`'s inserts and deletes
|
||||
//! work on, and the span its `replace` replaces when its text brings comments.
|
||||
//!
|
||||
//! Two rules, stated once here and in the README:
|
||||
//!
|
||||
@@ -14,7 +14,7 @@ use vlog_parser::ast::Item;
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
/// Why an item that does not own its lines is refused by insert and delete.
|
||||
pub const SHARED_LINE: &str = "shares a line with other code; insert_item and delete_item work on items on lines of their own (run `format` first)";
|
||||
pub const SHARED_LINE: &str = "shares a line with other code; edit_item inserts and deletes work on items on lines of their own (run `format` first)";
|
||||
|
||||
/// The start of the item's own leading comments (the item's own start when
|
||||
/// it has none): walking back over `Meta::leading`, up to the first gap
|
||||
@@ -44,7 +44,7 @@ pub fn own_lines(text: &str, item: &Item) -> Result<(u32, u32), String> {
|
||||
Ok((line_start(text, first), last))
|
||||
}
|
||||
|
||||
/// The bytes `replace_item` replaces with `text`: the item's span, widened
|
||||
/// The bytes `op: replace` replaces with `text`: the item's span, widened
|
||||
/// back over its own leading comments when `text` begins with a comment,
|
||||
/// and forward over its trailing comment when `text` ends with one on its
|
||||
/// last line — so the same call twice finds its own text and is
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `delete_item`'s implicit-connection rule: a `.*` binds a signal without
|
||||
//! `op: delete`'s implicit-connection rule: a `.*` binds a signal without
|
||||
//! spelling it, so `find_references` (which returns only spans that spell
|
||||
//! the name) never lists it. For each deleted name, every `.*`
|
||||
//! instantiation in the item's own scope — its sibling items and the
|
||||
|
||||
@@ -25,14 +25,13 @@
|
||||
//! bytes and in the new;
|
||||
//! 6. the `` `define``/`` `undef`` entries inside the region are the same
|
||||
//! before and after — except inside a directive or macro item at the
|
||||
//! region's level, where editing the definition is the point, and for a
|
||||
//! forced deletion, which removes them and names them
|
||||
//! ([`Outcome::dropped_macros`]);
|
||||
//! region's level, where editing the definition is the point (a deletion
|
||||
//! is held to it too: the lean catalogue has no `force`, PLAN §10.1);
|
||||
//! 7. the region holds the same fence markers before and after
|
||||
//! ([`lexical`]).
|
||||
//!
|
||||
//! What is deliberately **not** verified: whether the new text makes sense —
|
||||
//! its types, widths, the names it reads. `diagnostics` answers that.
|
||||
//! its types, widths, the names it reads. `check` answers that.
|
||||
|
||||
use vlog_parser::ast::{Item, ItemKind};
|
||||
use vlog_parser::defines::DefineKind;
|
||||
@@ -53,13 +52,12 @@ pub struct Splice {
|
||||
|
||||
/// What the region must hold after the splice.
|
||||
pub enum Expect {
|
||||
/// Exactly one item, of this kind class (`replace_item`).
|
||||
/// Exactly one item, of this kind class (`op: replace`).
|
||||
One(&'static str),
|
||||
/// One item or more (`insert_item`).
|
||||
/// One item or more (`insert_before`, `insert_after`).
|
||||
Some,
|
||||
/// Nothing (`delete_item`); `force` lets rule 6 pass over the macro
|
||||
/// definitions the deleted item held (they are named instead).
|
||||
Nothing { force: bool },
|
||||
/// Nothing (`edit_item op: delete`).
|
||||
Nothing,
|
||||
}
|
||||
|
||||
/// A splice that passed: the new file, its analysis, and the items the
|
||||
@@ -68,9 +66,6 @@ pub struct Outcome {
|
||||
pub text: String,
|
||||
pub analysis: Analysis,
|
||||
pub items: Vec<(&'static str, TextRange)>,
|
||||
/// The macro definitions a forced deletion removed, as the warning
|
||||
/// names them (`W`, `X (undef)`); empty for every other edit.
|
||||
pub dropped_macros: Vec<String>,
|
||||
}
|
||||
|
||||
/// Check `splice` against `old` (see the module comment); the refusal is one
|
||||
@@ -98,21 +93,12 @@ pub fn check(old: &Analysis, splice: &Splice, expect: Expect) -> Result<Outcome,
|
||||
if let Some((class, _)) = items.iter().find(|(class, _)| !fits(container, class)) {
|
||||
return Err(format!("a {class} cannot stand in a {container}'s scope"));
|
||||
}
|
||||
let dropped_macros = match same_macros(old, &analysis, region, (&before, &after)) {
|
||||
Ok(()) => Vec::new(),
|
||||
Err(_) if matches!(expect, Expect::Nothing { force: true }) => {
|
||||
dropped(old, region, &before)
|
||||
}
|
||||
Err(why) if matches!(expect, Expect::Nothing { .. }) => {
|
||||
return Err(format!("{why}, or pass `force: true` to delete it anyway"))
|
||||
}
|
||||
Err(why) => return Err(why),
|
||||
};
|
||||
same_macros(old, &analysis, region, (&before, &after))?;
|
||||
no_new_duplicates(old, &analysis)?;
|
||||
balanced(&old.tokens, splice.start, splice.old_end, "the old item")?;
|
||||
balanced(&analysis.tokens, splice.start, new_end, "the new text")?;
|
||||
lexical::same_fences(old, &analysis, region)?;
|
||||
Ok(Outcome { text, analysis, items, dropped_macros })
|
||||
Ok(Outcome { text, analysis, items })
|
||||
}
|
||||
|
||||
/// The old text with the splice applied; a range off a character boundary
|
||||
@@ -242,14 +228,14 @@ fn expected(items: &[(&'static str, TextRange)], expect: &Expect) -> Result<(),
|
||||
match (expect, items) {
|
||||
(Expect::One(class), [(found, _)]) if found == class => Ok(()),
|
||||
(Expect::One(class), [(found, _)]) => Err(format!(
|
||||
"the text is a {found} where a {class} was; replace_item keeps an item's kind (delete_item, then insert_item, to change it)"
|
||||
"the text is a {found} where a {class} was; `replace` keeps an item's kind (`delete`, then an insert, to change it)"
|
||||
)),
|
||||
(Expect::One(_), many) => Err(format!(
|
||||
"the text holds {} items where one was; replace_item replaces one item with one (insert_item adds more)",
|
||||
"the text holds {} items where one was; `replace` replaces one item with one (an insert adds more)",
|
||||
many.len()
|
||||
)),
|
||||
(Expect::Some, []) => Err("the text holds no item".into()),
|
||||
(Expect::Nothing { .. }, [_, ..]) => {
|
||||
(Expect::Nothing, [_, ..]) => {
|
||||
Err("the deletion would leave an item behind".into())
|
||||
}
|
||||
_ => Ok(()),
|
||||
@@ -257,7 +243,7 @@ fn expected(items: &[(&'static str, TextRange)], expect: &Expect) -> Result<(),
|
||||
}
|
||||
|
||||
/// The kind class of an item: the unit of "the same kind" for
|
||||
/// `replace_item`, and what [`fits`] asks about. The table is the README's.
|
||||
/// `op: replace`, and what [`fits`] asks about. The table is the README's.
|
||||
pub fn class_of(kind: &ItemKind) -> &'static str {
|
||||
match kind {
|
||||
ItemKind::Module(module) => match module.kw.as_str() {
|
||||
@@ -384,22 +370,6 @@ fn same_macros(
|
||||
))
|
||||
}
|
||||
|
||||
/// The macro definitions a deletion of the region removes, each name once,
|
||||
/// in source order: `W` for a `` `define``, `X (undef)` for an `` `undef``.
|
||||
fn dropped(old: &Analysis, region: Region, before: &Split) -> Vec<String> {
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for (kind, name, _, _) in definitions(old, region.start, region.old_end, before) {
|
||||
let shown = match kind {
|
||||
DefineKind::Undef => format!("{name} (undef)"),
|
||||
_ => name,
|
||||
};
|
||||
if !names.contains(&shown) {
|
||||
names.push(shown);
|
||||
}
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// A define entry as compared: kind, name, parameters, body.
|
||||
type Definition = (DefineKind, String, Option<Vec<String>>, String);
|
||||
|
||||
|
||||
@@ -17,26 +17,21 @@
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::{tokenize, LineIndex};
|
||||
|
||||
use super::source::{capped, word_in};
|
||||
use super::source::word_in;
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
/// The most mentions an answer lists; the rest are counted.
|
||||
pub const CAP: usize = 50;
|
||||
|
||||
/// The longest line text a mention shows.
|
||||
const LINE_CAP: usize = 160;
|
||||
|
||||
/// One unresolved spelling: where, what kind of text holds it, and the line.
|
||||
/// One unresolved spelling: the file and line that hold it.
|
||||
pub struct Mention {
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
pub kind: &'static str,
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
/// The mentions an answer lists (at most [`CAP`]) and how many there are.
|
||||
@@ -65,41 +60,22 @@ impl Mentions {
|
||||
self.total == 0
|
||||
}
|
||||
|
||||
/// One indented line per mention, `file:line kind: text`, then the cap.
|
||||
pub fn lines(&self, indent: &str) -> String {
|
||||
let mut out = String::new();
|
||||
for mention in &self.listed {
|
||||
let (file, line, kind) = (&mention.file, mention.line, mention.kind);
|
||||
out.push_str(&format!("{indent}{file}:{line} {kind}: {}\n", mention.text));
|
||||
/// The `unresolved:` block an answer ends with — the label, then the
|
||||
/// mentions one file per line (`file:12,40`), then the cut — or nothing.
|
||||
pub fn block(&self) -> Vec<String> {
|
||||
if self.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let sites: Vec<(String, u32)> =
|
||||
self.listed.iter().map(|m| (m.file.clone(), m.line)).collect();
|
||||
let mut out = vec!["unresolved:".to_string()];
|
||||
out.extend(render::by_file(&sites).into_iter().map(|line| format!(" {line}")));
|
||||
let rest = self.total - self.listed.len();
|
||||
if rest > 0 {
|
||||
out.push_str(&format!("{indent}… and {rest} more\n"));
|
||||
out.push(format!(" {}", render::more(rest)));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The `unresolved_mentions` JSON: the listed ones.
|
||||
pub fn json(&self) -> Value {
|
||||
let listed: Vec<Value> = self
|
||||
.listed
|
||||
.iter()
|
||||
.map(|m| json!({ "file": m.file, "line": m.line, "text": m.text, "kind": m.kind }))
|
||||
.collect();
|
||||
Value::from(listed)
|
||||
}
|
||||
|
||||
/// The sentence an edit tool puts under `warnings:` — `lead` is how it
|
||||
/// begins (`the old name `x` is still spelled`) — the list below it.
|
||||
pub fn warning(&self, lead: &str) -> String {
|
||||
let places = if self.total == 1 { "1 place" } else { "these places" };
|
||||
let mut text = format!(
|
||||
"{lead} as text at {places} lucisv does not resolve (strings, comments, macro text; {} in all); check whether these are references:\n",
|
||||
self.total
|
||||
);
|
||||
text.push_str(self.lines(" ").trim_end());
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
/// The unresolved mentions of `focus.name` across `files`, nearest first.
|
||||
@@ -117,7 +93,7 @@ pub fn find<'t>(
|
||||
let spans = accounted.map_or(&[][..], |(_, spans)| spans.as_slice());
|
||||
let lines = LineIndex::new(text);
|
||||
let mut last_line = 0;
|
||||
for (at, kind) in spellings(text, focus.name) {
|
||||
for (at, _) in spellings(text, focus.name) {
|
||||
let end = at + focus.name.len() as u32;
|
||||
if spans.iter().any(|span| span.start <= at && end <= span.end) {
|
||||
continue;
|
||||
@@ -132,8 +108,7 @@ pub fn find<'t>(
|
||||
.and_then(|range| text.get(range.start as usize..range.end as usize))
|
||||
.unwrap_or("");
|
||||
let rank = rank(accounted.is_some(), focus.unit, source);
|
||||
let file = project.relative(path);
|
||||
let mention = Mention { file, line, kind, text: capped(source, LINE_CAP) };
|
||||
let mention = Mention { file: project.relative(path), line };
|
||||
found.push((rank, shared_components(path, focus.home), mention));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,31 +3,44 @@
|
||||
//! `inputSchema` a host shows the agent and the validation a call's
|
||||
//! `arguments` go through, so the two cannot disagree.
|
||||
|
||||
mod defines;
|
||||
mod declared;
|
||||
mod diagnostics;
|
||||
mod edit;
|
||||
mod find;
|
||||
mod format;
|
||||
mod glob;
|
||||
mod hierarchy;
|
||||
mod interface;
|
||||
mod item;
|
||||
mod mentions;
|
||||
mod nav;
|
||||
mod names;
|
||||
mod outline;
|
||||
mod place;
|
||||
mod port;
|
||||
mod read;
|
||||
mod read_item;
|
||||
mod refactor;
|
||||
mod select;
|
||||
mod source;
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::project::Project;
|
||||
|
||||
/// What a tool hands back: the compact text rendering the agent reads, and
|
||||
/// the same facts as JSON (`structuredContent`).
|
||||
/// What a tool hands back: the text the agent reads. A result is its text;
|
||||
/// there is no structured twin (PLAN §10.1).
|
||||
pub struct Answer {
|
||||
pub text: String,
|
||||
pub structured: Value,
|
||||
}
|
||||
|
||||
impl Answer {
|
||||
/// An answer of these lines, each ended by a newline.
|
||||
pub fn lines(lines: Vec<String>) -> Answer {
|
||||
let mut text = String::new();
|
||||
for line in lines {
|
||||
text.push_str(&line);
|
||||
text.push('\n');
|
||||
}
|
||||
Answer { text }
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool's body. `Err` is a refusal: one sentence, sent as `isError: true`.
|
||||
@@ -37,32 +50,30 @@ pub type Handler = fn(&mut Project, &Args) -> Result<Answer, String>;
|
||||
pub enum Ty {
|
||||
/// A string.
|
||||
Str,
|
||||
/// An integer no smaller than the bound.
|
||||
Int { min: i64 },
|
||||
/// One of a fixed set of strings.
|
||||
Enum(&'static [&'static str]),
|
||||
/// `true` or `false`.
|
||||
Bool,
|
||||
/// An integer inside `min..=max`.
|
||||
/// An integer inside `min..=max` — checked here; the schema says only
|
||||
/// `integer`, the tool's description names the range.
|
||||
Range { min: i64, max: i64 },
|
||||
}
|
||||
|
||||
/// One argument a tool takes.
|
||||
/// One argument a tool takes. It has no description of its own: the tool's
|
||||
/// one description names its arguments (PLAN §10.1).
|
||||
pub struct Param {
|
||||
pub name: &'static str,
|
||||
pub ty: Ty,
|
||||
pub required: bool,
|
||||
pub description: &'static str,
|
||||
}
|
||||
|
||||
/// One tool, as `tools/list` shows it and `tools/call` runs it.
|
||||
pub struct Tool {
|
||||
pub name: &'static str,
|
||||
pub title: &'static str,
|
||||
pub description: &'static str,
|
||||
pub params: &'static [Param],
|
||||
/// Whether the call walks the roots again before answering, so files
|
||||
/// created since the last walk are counted (`project_overview`).
|
||||
/// created since the last walk are part of the whole set an edit needs.
|
||||
pub rewalk: bool,
|
||||
pub handler: Handler,
|
||||
}
|
||||
@@ -74,8 +85,8 @@ pub enum Effect {
|
||||
/// Nothing on disk changes; the same call on the same disk gives the
|
||||
/// same answer.
|
||||
Read,
|
||||
/// Files inside the roots are rewritten (or created). `idempotent` when
|
||||
/// a second identical call writes nothing more.
|
||||
/// Files inside the roots are rewritten. `idempotent` when a second
|
||||
/// identical call writes nothing more.
|
||||
Edit { idempotent: bool },
|
||||
}
|
||||
|
||||
@@ -83,32 +94,15 @@ use Effect::{Edit, Read};
|
||||
|
||||
/// Every tool this server offers, in the order `tools/list` gives them.
|
||||
const TOOLS: &[(Tool, Effect)] = &[
|
||||
(read::PROJECT_OVERVIEW, Read),
|
||||
(read::LIST_UNITS, Read),
|
||||
(interface::UNIT_INTERFACE, Read),
|
||||
(read::OUTLINE, Read),
|
||||
(read_item::READ_ITEM, Read),
|
||||
(read::SEARCH_SYMBOLS, Read),
|
||||
(defines::DEFINES, Read),
|
||||
(nav::DEFINITION, Read),
|
||||
(nav::REFERENCES, Read),
|
||||
(hierarchy::HIERARCHY, Read),
|
||||
(diagnostics::DIAGNOSTICS, Read),
|
||||
(format::FORMAT, Edit { idempotent: true }),
|
||||
(format::FIX_LINT, Edit { idempotent: true }),
|
||||
(find::FIND, Read),
|
||||
(outline::OUTLINE, Read),
|
||||
(read::READ, Read),
|
||||
(diagnostics::CHECK, Read),
|
||||
(edit::RENAME, Edit { idempotent: false }),
|
||||
(edit::EXPAND_WILDCARD, Edit { idempotent: true }),
|
||||
(edit::CONVERT_PORTS, Edit { idempotent: true }),
|
||||
(edit::ORGANIZE_IMPORTS, Edit { idempotent: true }),
|
||||
(edit::INLINE_MODULE, Edit { idempotent: false }),
|
||||
(edit::PROPAGATE_PORTS, Edit { idempotent: false }),
|
||||
(edit::REMOVE_PORT, Edit { idempotent: false }),
|
||||
(refactor::ADD_PORT, Edit { idempotent: false }),
|
||||
(refactor::EXTRACT_MODULE, Edit { idempotent: false }),
|
||||
(item::REPLACE_ITEM, Edit { idempotent: true }),
|
||||
(item::INSERT_ITEM, Edit { idempotent: false }),
|
||||
(item::DELETE_ITEM, Edit { idempotent: true }),
|
||||
(refactor::INSTANTIATE, Read),
|
||||
(port::PORT, Edit { idempotent: false }),
|
||||
(item::EDIT_ITEM, Edit { idempotent: false }),
|
||||
(format::FORMAT, Edit { idempotent: true }),
|
||||
];
|
||||
|
||||
/// The tool called `name`.
|
||||
@@ -125,18 +119,16 @@ pub fn list() -> Value {
|
||||
fn describe(tool: &Tool, effect: Effect) -> Value {
|
||||
// No tool consults anything outside the roots (`openWorldHint`), and no
|
||||
// edit tool destroys: each rewrites files inside the roots through a
|
||||
// verified engine, and `dry_run` shows the diff first.
|
||||
// verified engine, all or nothing.
|
||||
let (read_only, idempotent) = match effect {
|
||||
Read => (true, true),
|
||||
Edit { idempotent } => (false, idempotent),
|
||||
};
|
||||
json!({
|
||||
"name": tool.name,
|
||||
"title": tool.title,
|
||||
"description": tool.description,
|
||||
"inputSchema": schema(tool.params),
|
||||
// The display name is `title` above; `annotations.title` would
|
||||
// repeat it in a catalogue every session reads.
|
||||
// Hosts read these; the model never sees them (PLAN §10.1).
|
||||
"annotations": {
|
||||
"readOnlyHint": read_only,
|
||||
"destructiveHint": false,
|
||||
@@ -146,18 +138,17 @@ fn describe(tool: &Tool, effect: Effect) -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
/// A JSON Schema object for an argument list: closed, with its required set.
|
||||
/// A JSON Schema object for an argument list: closed, with its required
|
||||
/// set, and `type` alone per property (an `enum` where one applies).
|
||||
fn schema(params: &[Param]) -> Value {
|
||||
let mut properties = Map::new();
|
||||
for param in params {
|
||||
let mut property = match param.ty {
|
||||
let property = match param.ty {
|
||||
Ty::Str => json!({ "type": "string" }),
|
||||
Ty::Int { min } => json!({ "type": "integer", "minimum": min }),
|
||||
Ty::Enum(values) => json!({ "type": "string", "enum": values }),
|
||||
Ty::Bool => json!({ "type": "boolean" }),
|
||||
Ty::Range { min, max } => json!({ "type": "integer", "minimum": min, "maximum": max }),
|
||||
Ty::Range { .. } => json!({ "type": "integer" }),
|
||||
};
|
||||
property["description"] = Value::from(param.description);
|
||||
properties.insert(param.name.to_string(), property);
|
||||
}
|
||||
let required: Vec<&str> =
|
||||
@@ -179,19 +170,15 @@ impl Args {
|
||||
self.0.get(name).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
/// An integer argument, when given.
|
||||
pub fn int(&self, name: &str) -> Option<i64> {
|
||||
self.0.get(name).and_then(Value::as_i64)
|
||||
}
|
||||
|
||||
/// A boolean argument, or `default`.
|
||||
pub fn flag(&self, name: &str, default: bool) -> bool {
|
||||
self.0.get(name).and_then(Value::as_bool).unwrap_or(default)
|
||||
/// A boolean argument; `false` when absent.
|
||||
pub fn flag(&self, name: &str) -> bool {
|
||||
self.0.get(name).and_then(Value::as_bool).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// A non-negative integer argument, or `default`.
|
||||
pub fn count(&self, name: &str, default: usize) -> usize {
|
||||
self.int(name).and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
|
||||
let given = self.0.get(name).and_then(Value::as_i64);
|
||||
given.and_then(|n| usize::try_from(n).ok()).unwrap_or(default)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,7 +210,6 @@ pub fn validate(tool: &Tool, arguments: Map<String, Value>) -> Result<Args, Stri
|
||||
fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
|
||||
let fits = match param.ty {
|
||||
Ty::Str => value.is_string(),
|
||||
Ty::Int { min } => value.as_i64().is_some_and(|n| n >= min),
|
||||
Ty::Enum(values) => value.as_str().is_some_and(|s| values.contains(&s)),
|
||||
Ty::Bool => value.is_boolean(),
|
||||
Ty::Range { min, max } => value.as_i64().is_some_and(|n| (min..=max).contains(&n)),
|
||||
@@ -233,7 +219,6 @@ fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
|
||||
}
|
||||
let wanted = match param.ty {
|
||||
Ty::Str => "a string".to_string(),
|
||||
Ty::Int { min } => format!("an integer >= {min}"),
|
||||
Ty::Enum(values) => format!("one of {}", values.join(", ")),
|
||||
Ty::Bool => "true or false".to_string(),
|
||||
Ty::Range { min, max } => format!("an integer from {min} to {max}"),
|
||||
@@ -250,12 +235,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_schema_is_closed_and_names_its_required_arguments() {
|
||||
fn every_schema_is_closed_and_bare_and_every_name_is_unique() {
|
||||
for (tool, _) in TOOLS {
|
||||
let schema = schema(tool.params);
|
||||
assert_eq!(schema["additionalProperties"], false, "{}", tool.name);
|
||||
assert!(schema["required"].is_array(), "{}", tool.name);
|
||||
assert!(!tool.description.is_empty() && tool.description.len() < 600, "{}", tool.name);
|
||||
for (name, property) in schema["properties"].as_object().unwrap() {
|
||||
let keys: Vec<&String> = property.as_object().unwrap().keys().collect();
|
||||
assert!(keys.iter().all(|k| *k == "type" || *k == "enum"), "{name}: {keys:?}");
|
||||
}
|
||||
assert!(!tool.description.is_empty() && tool.description.len() < 300, "{}", tool.name);
|
||||
}
|
||||
let names: Vec<&str> = TOOLS.iter().map(|(tool, _)| tool.name).collect();
|
||||
let mut unique = names.clone();
|
||||
@@ -266,25 +255,24 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn validation_names_the_offending_argument() {
|
||||
let tool = find("list_units").unwrap();
|
||||
let unknown = validate(tool, args(json!({"nme": "x"}))).err().unwrap();
|
||||
assert!(unknown.contains("`nme`"), "{unknown}");
|
||||
let wrong = validate(tool, args(json!({"kind": "struct"}))).err().unwrap();
|
||||
assert!(wrong.contains("`kind`") && wrong.contains("module"), "{wrong}");
|
||||
let negative = validate(tool, args(json!({"limit": -1}))).err().unwrap();
|
||||
assert!(negative.contains("`limit`"), "{negative}");
|
||||
let missing = validate(find("outline").unwrap(), Map::new()).err().unwrap();
|
||||
assert!(missing.contains("`file`"), "{missing}");
|
||||
assert!(validate(tool, args(json!({"kind": "module", "glob": null}))).is_ok());
|
||||
let references = find("references").unwrap();
|
||||
let flag = validate(references, args(json!({"name": "x", "include_declaration": "no"})));
|
||||
assert!(flag.err().unwrap().contains("true or false"));
|
||||
let given = validate(references, args(json!({"name": "x", "include_declaration": false})));
|
||||
assert!(!given.unwrap().flag("include_declaration", true));
|
||||
let tool = find("check").unwrap();
|
||||
let unknown = validate(tool, args(json!({"fil": "x"}))).err().unwrap();
|
||||
assert!(unknown.contains("`fil`") && unknown.contains("file"), "{unknown}");
|
||||
let wrong = validate(tool, args(json!({"file": 3}))).err().unwrap();
|
||||
assert!(wrong.contains("`file`") && wrong.contains("a string"), "{wrong}");
|
||||
let missing = validate(find("read").unwrap(), Map::new()).err().unwrap();
|
||||
assert!(missing.contains("`item`"), "{missing}");
|
||||
assert!(validate(tool, args(json!({"file": null}))).is_ok());
|
||||
let edit = find("edit_item").unwrap();
|
||||
let op = json!({"file": "a.sv", "op": "move", "item": "x"});
|
||||
let op = validate(edit, args(op)).err().unwrap();
|
||||
assert!(op.contains("`op`") && op.contains("replace"), "{op}");
|
||||
let hierarchy = find("hierarchy").unwrap();
|
||||
let flag = validate(hierarchy, args(json!({"up": "yes"}))).err().unwrap();
|
||||
assert!(flag.contains("true or false"), "{flag}");
|
||||
let deep = validate(hierarchy, args(json!({"depth": 21}))).err().unwrap();
|
||||
assert!(deep.contains("`depth`") && deep.contains("from 1 to 20"), "{deep}");
|
||||
assert!(validate(hierarchy, args(json!({"depth": 20}))).is_ok());
|
||||
assert_eq!(schema(hierarchy.params)["properties"]["depth"]["maximum"], 20);
|
||||
assert_eq!(schema(hierarchy.params)["properties"]["depth"], json!({"type": "integer"}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! Names looked up — the by-name half every lean tool shares: every
|
||||
//! declaration of a name (the index's units, exported members and module
|
||||
//! internals, every declaration the files' own symbol tables hold, and the
|
||||
//! `` `define``s), each read off the bytes on disk, and the near matches a
|
||||
//! refusal lists when there is none — from the same table — so the next
|
||||
//! call is right.
|
||||
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_parser::defines::DefineKind;
|
||||
use vlog_semantic::{Def, DefinitionKey, FileId, Surface, SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::declared::{declared, Local, Wanted};
|
||||
use super::source::{checked_site, Texts};
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
/// One declaration of a name, where it is written.
|
||||
pub struct Declaration {
|
||||
pub path: PathBuf,
|
||||
/// The byte offset of the name itself.
|
||||
pub offset: u32,
|
||||
/// The kind word (`macro` for a `` `define``).
|
||||
pub kind: &'static str,
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
}
|
||||
|
||||
impl Declaration {
|
||||
/// `kind name file:line`, as `find` lists it.
|
||||
pub fn render(&self, name: &str) -> String {
|
||||
format!("{} {name} {}:{}", self.kind, self.file, self.line)
|
||||
}
|
||||
|
||||
/// Whether this is a `` `define`` (no engine follows its uses).
|
||||
pub fn is_macro(&self) -> bool {
|
||||
self.kind == "macro"
|
||||
}
|
||||
}
|
||||
|
||||
/// A name as written, split into the unit it is qualified by (`unit.name`,
|
||||
/// `pkg::name`) and the name itself; an escaped identifier is never split.
|
||||
pub fn qualified(name: &str) -> (Option<&str>, &str) {
|
||||
if name.starts_with('\\') {
|
||||
return (None, name);
|
||||
}
|
||||
let split = name.rsplit_once("::").or_else(|| name.rsplit_once('.'));
|
||||
match split {
|
||||
Some((unit, member)) if !unit.is_empty() && !member.is_empty() => (Some(unit), member),
|
||||
_ => (None, name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration of `name` — its declarations first, then its
|
||||
/// `` `define``s — each whose file still spells the name there, in file
|
||||
/// and line order within each group. `unit.name` (or `pkg::name`) is the
|
||||
/// member of that unit only.
|
||||
pub fn declarations(project: &Project, name: &str) -> Vec<Declaration> {
|
||||
let index = project.index();
|
||||
let (unit, name) = qualified(name);
|
||||
let mut texts = Texts::default();
|
||||
let mut out: Vec<Declaration> = Vec::new();
|
||||
let defs = match unit {
|
||||
Some(unit) => index.member_in(unit, name, Surface::Hierarchical).to_vec(),
|
||||
None => defs_named(index, name),
|
||||
};
|
||||
for def in defs {
|
||||
let Some(path) = index.path(def.file) else { continue };
|
||||
let shown = def.detail_span.unwrap_or(def.name_span);
|
||||
let kind = unit_kind(project, path, &def);
|
||||
let site = checked_site(project, &mut texts, path, def.name_span, shown, name);
|
||||
if let Some(site) = site {
|
||||
let offset = def.name_span.start;
|
||||
let (file, line) = (site.file, site.line);
|
||||
out.push(Declaration { path: path.to_path_buf(), offset, kind, file, line });
|
||||
}
|
||||
}
|
||||
let locals = declared(project, &Wanted::Exact(name));
|
||||
let in_unit = |local: &&Local| unit.is_none_or(|unit| local.unit.as_deref() == Some(unit));
|
||||
for local in locals.iter().filter(in_unit) {
|
||||
let known = out.iter().any(|d| d.path == local.path && d.offset == local.offset);
|
||||
if !known {
|
||||
out.push(Declaration {
|
||||
path: local.path.clone(),
|
||||
offset: local.offset,
|
||||
kind: local.kind,
|
||||
file: project.relative(&local.path),
|
||||
line: local.line,
|
||||
});
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
|
||||
out.dedup_by(|a, b| (&a.file, a.line, a.offset) == (&b.file, b.line, b.offset));
|
||||
if unit.is_some() {
|
||||
return out;
|
||||
}
|
||||
let mut macros = macro_declarations(project, &mut texts, name);
|
||||
macros.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
|
||||
out.extend(macros);
|
||||
out
|
||||
}
|
||||
|
||||
/// Every indexed non-macro declaration of `name`, each once.
|
||||
fn defs_named(index: &WorkspaceIndex, name: &str) -> Vec<Def> {
|
||||
let mut defs: Vec<Def> = index.units(name).to_vec();
|
||||
let exported = index.workspace_symbols(name);
|
||||
let members = exported.iter().filter(|hit| hit.name == name && hit.container.is_some());
|
||||
defs.extend(members.map(|hit| hit.def.clone()));
|
||||
defs.extend(index.hierarchical_declarations(name).map(|(_, def)| def.clone()));
|
||||
let mut seen = HashSet::new();
|
||||
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
|
||||
defs
|
||||
}
|
||||
|
||||
/// Every indexed `` `define`` of `name` whose file still spells it there.
|
||||
fn macro_declarations(project: &Project, texts: &mut Texts, name: &str) -> Vec<Declaration> {
|
||||
let index = project.index();
|
||||
let defined = index.find_define(name).into_iter().filter(|(_, d)| d.kind == DefineKind::Define);
|
||||
defined
|
||||
.filter_map(|(file, define)| {
|
||||
let path = index.path(file)?;
|
||||
let span = define.name_span;
|
||||
let site = checked_site(project, texts, path, span, span, name)?;
|
||||
let (file, line) = (site.file, site.line);
|
||||
Some(Declaration {
|
||||
path: path.to_path_buf(),
|
||||
offset: span.start,
|
||||
kind: "macro",
|
||||
file,
|
||||
line,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A declaration's kind word, telling a `program` from the module it is
|
||||
/// modelled as.
|
||||
fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
|
||||
if def.kind == SymbolKind::Module && is_program(project, path, def) {
|
||||
"program"
|
||||
} else {
|
||||
render::kind(def.kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `Module`-kind unit was declared with `program`. The semantic
|
||||
/// layer models the two alike, so the keyword is read off the text between
|
||||
/// the declaration's start and its name — only for the rare file whose text
|
||||
/// spells `endprogram` at all.
|
||||
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
|
||||
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
};
|
||||
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
|
||||
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
|
||||
}
|
||||
|
||||
/// Every declaration of `name`, walking the roots once first when the index
|
||||
/// holds none (a file written since the last walk).
|
||||
pub fn declarations_walking(project: &mut Project, name: &str) -> Vec<Declaration> {
|
||||
let found = declarations(project, name);
|
||||
if found.is_empty() && project.ensure_walked_for_miss() {
|
||||
return declarations(project, name);
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// The refusal for a name nothing declares: the near matches, when any.
|
||||
pub fn no_declaration(project: &Project, name: &str) -> String {
|
||||
let similar = similar(project, qualified(name).1, 20);
|
||||
match similar.is_empty() {
|
||||
true => format!("no declaration named `{name}`."),
|
||||
false => format!("no declaration named `{name}`; similar: {}.", similar.join(", ")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Up to `cap` declared names (and macros) that contain `name`, any case —
|
||||
/// the declarations [`declarations`] would list, read from the same table.
|
||||
pub fn similar(project: &Project, name: &str, cap: usize) -> Vec<String> {
|
||||
let index = project.index();
|
||||
let mut names: BTreeSet<String> =
|
||||
index.workspace_symbols(name).iter().map(|hit| hit.name.to_string()).collect();
|
||||
let part = Wanted::Containing(name.to_ascii_lowercase());
|
||||
names.extend(declared(project, &part).into_iter().map(|local| local.name));
|
||||
for at in 0..index.files().len() {
|
||||
let Some(table) = index.defines(FileId(at as u32)) else { continue };
|
||||
let found = table.entries().iter().filter(|d| contains_any_case(&d.name, name));
|
||||
names.extend(found.map(|define| define.name.clone()));
|
||||
}
|
||||
names.into_iter().filter(|found| found != name).take(cap).collect()
|
||||
}
|
||||
|
||||
/// Up to `cap` module or interface names that contain `name`, any case.
|
||||
pub fn similar_units(index: &WorkspaceIndex, name: &str, cap: usize) -> Vec<String> {
|
||||
let mut names: Vec<String> = index
|
||||
.instantiable_units()
|
||||
.map(|(unit, _)| unit)
|
||||
.filter(|unit| contains_any_case(unit, name))
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
names.dedup();
|
||||
names.truncate(cap);
|
||||
names
|
||||
}
|
||||
|
||||
fn contains_any_case(text: &str, part: &str) -> bool {
|
||||
text.to_ascii_lowercase().contains(&part.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// The refusal for a name declared more than once: every site, and what
|
||||
/// picks one.
|
||||
pub fn ambiguous(name: &str, found: &[&Declaration], pick: &str) -> String {
|
||||
let sites: Vec<String> = found.iter().map(|d| format!("{}:{}", d.file, d.line)).collect();
|
||||
format!("`{name}` is declared {} times ({}); {pick}.", sites.len(), sites.join(", "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::qualified;
|
||||
|
||||
#[test]
|
||||
fn a_unit_qualifies_a_name_and_an_escaped_name_is_whole() {
|
||||
assert_eq!(qualified("core.state_q"), (Some("core"), "state_q"));
|
||||
assert_eq!(qualified("pkg::W"), (Some("pkg"), "W"));
|
||||
assert_eq!(qualified("a::b::c"), (Some("a::b"), "c"));
|
||||
assert_eq!(qualified("state_q"), (None, "state_q"));
|
||||
assert_eq!(qualified("\\a.b "), (None, "\\a.b "));
|
||||
assert_eq!(qualified(".x"), (None, ".x"));
|
||||
}
|
||||
}
|
||||
@@ -1,455 +0,0 @@
|
||||
//! `definition` and `references`: where a name is declared, and every place
|
||||
//! the declaration is used — the two questions an agent otherwise answers by
|
||||
//! grepping and reading.
|
||||
//!
|
||||
//! Both take one selector ([`target`]): a position (`file` + `line` + `col`,
|
||||
//! or `file` + `line` + the `name` written on that line), a name in a file
|
||||
//! (`file` + `name`), or a bare `name` (with an optional `unit`) looked up in
|
||||
//! the index. `definition` walks the server's ladder — an `` `include`` line,
|
||||
//! a macro use, the file's own symbol table, the workspace overlay — and
|
||||
//! lists every site, never a guess. `references` hands the declaration to
|
||||
//! `vlog_refactor::find_references` over every indexed file
|
||||
//! (`source::WholeSet`).
|
||||
//! The selector itself is `select.rs`.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex};
|
||||
|
||||
use super::mentions::{self, Focus, Mentions};
|
||||
use super::read::{in_glob, only_in, path_match, IN};
|
||||
use super::select::{macro_name, target, Target};
|
||||
use super::source::{self, checked_site, Site, Texts, WholeSet};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
|
||||
|
||||
/// The selector's arguments, shared by both tools.
|
||||
const FILE: Param = Param { name: "file", ty: Ty::Str, required: false, description: "The file." };
|
||||
const LINE: Param =
|
||||
Param { name: "line", ty: Ty::Int { min: 1 }, required: false, description: "Line." };
|
||||
const COL: Param =
|
||||
Param { name: "col", ty: Ty::Int { min: 1 }, required: false, description: "Byte column." };
|
||||
const NAME: Param = Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Name; alone, looked up project-wide (`` `X`` is a macro).",
|
||||
};
|
||||
const UNIT: Param = Param {
|
||||
name: "unit",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Unit declaring a bare `name`.",
|
||||
};
|
||||
|
||||
pub const DEFINITION: Tool = Tool {
|
||||
name: "definition",
|
||||
title: "Definition",
|
||||
description: "Where a name or macro is declared: file:line:col, kind, line. Select by position, `file`+`name`, or `name`.",
|
||||
params: &[FILE, LINE, COL, NAME, UNIT],
|
||||
rewalk: false,
|
||||
handler: definition,
|
||||
};
|
||||
|
||||
pub const REFERENCES: Tool = Tool {
|
||||
name: "references",
|
||||
title: "Find references",
|
||||
description: "Uses of one declaration, then its unresolved mentions (strings, comments, macro text). Select as `definition`. Module instances: `hierarchy` up.",
|
||||
params: &[
|
||||
FILE,
|
||||
LINE,
|
||||
COL,
|
||||
NAME,
|
||||
UNIT,
|
||||
Param {
|
||||
name: "include_declaration",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Default true.",
|
||||
},
|
||||
IN,
|
||||
Param {
|
||||
name: "limit",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Default 500.",
|
||||
},
|
||||
Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Hits to skip.",
|
||||
},
|
||||
],
|
||||
rewalk: true,
|
||||
handler: references,
|
||||
};
|
||||
|
||||
fn definition(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let sites = match target(project, args)? {
|
||||
Target::At { path, analysis, offset } => at_position(project, &path, &analysis, offset)?,
|
||||
Target::Named { name, unit } => {
|
||||
let mut sites = by_name(project, &name, unit.as_deref());
|
||||
if sites.is_empty() && project.ensure_walked_for_miss() {
|
||||
sites = by_name(project, &name, unit.as_deref());
|
||||
}
|
||||
if sites.is_empty() {
|
||||
return Err(format!(
|
||||
"no declaration of `{name}`{} is indexed.",
|
||||
in_unit(unit.as_deref())
|
||||
));
|
||||
}
|
||||
sites
|
||||
}
|
||||
};
|
||||
Ok(source::answer(&sites, "definitions", "no declaration"))
|
||||
}
|
||||
|
||||
fn in_unit(unit: Option<&str>) -> String {
|
||||
unit.map_or(String::new(), |unit| format!(" in `{unit}`"))
|
||||
}
|
||||
|
||||
/// The server's ladder at one position: `` `include`` line, macro use, then
|
||||
/// both symbol layers.
|
||||
fn at_position(
|
||||
project: &Project,
|
||||
path: &Path,
|
||||
analysis: &Analysis,
|
||||
offset: u32,
|
||||
) -> Result<Vec<Site>, String> {
|
||||
let file = project.relative(path);
|
||||
let (line, col) = analysis.lines.line_col(offset);
|
||||
if let Some(token) = analysis.token_at(offset) {
|
||||
if token.kind == TokenKind::Directive && token.text.starts_with("`include") {
|
||||
return included(project, path, token).map(|site| vec![site]);
|
||||
}
|
||||
if let Some(name) = macro_name(token).filter(|_| token.is_macro()) {
|
||||
return macro_sites(project, analysis, &file, name);
|
||||
}
|
||||
}
|
||||
let external = analysis.external(project.index());
|
||||
match external.definition_of(&analysis.semantics, offset) {
|
||||
Some(Definition::Local(symbol)) if !symbol.name_span.is_empty() => {
|
||||
Ok(local_sites(analysis, &file, symbol))
|
||||
}
|
||||
Some(Definition::External(defs)) => {
|
||||
let reference = analysis.semantics.reference_at(offset);
|
||||
let name = reference.map_or("", |reference| reference.name.as_str());
|
||||
Ok(def_sites(project, defs, name))
|
||||
}
|
||||
_ => Err(format!("nothing at {file}:{line}:{col} names a declaration.")),
|
||||
}
|
||||
}
|
||||
|
||||
/// A local declaration: its completing declaration first (a non-ANSI port's
|
||||
/// body line), then the name, then every redeclaration the binder folded
|
||||
/// into it (`output y; wire y;` declares `y` twice) — one site per line.
|
||||
fn local_sites(analysis: &Analysis, file: &str, symbol: &Symbol) -> Vec<Site> {
|
||||
let (text, lines) = (&analysis.text, &analysis.lines);
|
||||
let kind = render::kind(symbol.kind);
|
||||
let detail = symbol.detail_span.filter(|span| !span.is_empty());
|
||||
let mut sites: Vec<Site> = detail
|
||||
.into_iter()
|
||||
.chain([symbol.name_span])
|
||||
.map(|span| Site::at(file.to_string(), text, lines, span, kind))
|
||||
.collect();
|
||||
let id = analysis.semantics.symbol_at(symbol.name_span.start);
|
||||
for again in analysis.semantics.duplicates().iter().filter(|d| Some(d.first) == id) {
|
||||
let site =
|
||||
Site::at(file.to_string(), text, lines, again.name_span, render::kind(again.kind));
|
||||
if !sites.iter().any(|known| known.line == site.line) {
|
||||
sites.push(site);
|
||||
}
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// Indexed declarations of `name`, each checked against its file's bytes.
|
||||
fn def_sites(project: &Project, defs: &[Def], name: &str) -> Vec<Site> {
|
||||
let mut texts = Texts::default();
|
||||
let mut sites: Vec<Site> = Vec::new();
|
||||
for def in defs {
|
||||
let Some(path) = project.index().path(def.file) else { continue };
|
||||
let shown = def.detail_span.unwrap_or(def.name_span);
|
||||
let kind = render::kind(def.kind);
|
||||
let site = checked_site(project, &mut texts, path, def.name_span, shown, name, kind);
|
||||
if let Some(site) = site {
|
||||
if !sites.iter().any(|s| (&s.file, s.line, s.col) == (&site.file, site.line, site.col))
|
||||
{
|
||||
sites.push(site);
|
||||
}
|
||||
}
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// An `` `include`` line: the named file beside the including one. No
|
||||
/// include-directory ladder is searched.
|
||||
fn included(project: &Project, path: &Path, token: &Token) -> Result<Site, String> {
|
||||
let written = token.text.trim_start_matches("`include").trim();
|
||||
let spelled = written.trim_matches(|c| c == '"' || c == '<' || c == '>');
|
||||
let beside = path.parent().unwrap_or(Path::new("")).join(spelled);
|
||||
let found = beside.to_str().and_then(|candidate| project.resolve(candidate).ok());
|
||||
let Some(target) = found else {
|
||||
return Err(format!(
|
||||
"`include {written} is not beside `{}` (only the including file's directory is searched).",
|
||||
project.relative(path)
|
||||
));
|
||||
};
|
||||
let text = render::one_line(&token.text);
|
||||
Ok(Site { file: project.relative(&target), line: 1, col: 1, kind: "include", text })
|
||||
}
|
||||
|
||||
/// A macro use: this file's own last definition when it has one, else every
|
||||
/// indexed definition (the include graph is not modelled, so none is picked).
|
||||
fn macro_sites(
|
||||
project: &Project,
|
||||
analysis: &Analysis,
|
||||
file: &str,
|
||||
name: &str,
|
||||
) -> Result<Vec<Site>, String> {
|
||||
if let Some(define) = analysis.defines.latest(name) {
|
||||
let (text, lines) = (&analysis.text, &analysis.lines);
|
||||
return Ok(vec![Site::at(file.to_string(), text, lines, define.name_span, "define")]);
|
||||
}
|
||||
let sites = define_sites(project, name);
|
||||
if sites.is_empty() {
|
||||
return Err(format!("`{name} is not defined in any indexed file."));
|
||||
}
|
||||
Ok(sites)
|
||||
}
|
||||
|
||||
/// Every indexed `` `define`` of `name`.
|
||||
pub(super) fn define_sites(project: &Project, name: &str) -> Vec<Site> {
|
||||
let index = project.index();
|
||||
let mut texts = Texts::default();
|
||||
index
|
||||
.find_define(name)
|
||||
.into_iter()
|
||||
.filter_map(|(file, define)| {
|
||||
let path = index.path(file)?;
|
||||
let span = define.name_span;
|
||||
checked_site(project, &mut texts, path, span, span, name, "define")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Declarations by name: a unit's member when `unit` is given, else every
|
||||
/// unit, exported member and module internal of that name; a macro when the
|
||||
/// name is written `` `NAME`` or nothing else declares it.
|
||||
fn by_name(project: &Project, name: &str, unit: Option<&str>) -> Vec<Site> {
|
||||
if let Some(spelled) = name.strip_prefix('`') {
|
||||
return define_sites(project, spelled);
|
||||
}
|
||||
let defs = declarations(project.index(), name, unit);
|
||||
let sites = def_sites(project, &defs, name);
|
||||
if sites.is_empty() && unit.is_none() {
|
||||
return define_sites(project, name);
|
||||
}
|
||||
sites
|
||||
}
|
||||
|
||||
/// Every indexed declaration of `name` (in `unit`, when given).
|
||||
fn declarations(index: &WorkspaceIndex, name: &str, unit: Option<&str>) -> Vec<Def> {
|
||||
if let Some(unit) = unit {
|
||||
return index.member_in(unit, name, Surface::Hierarchical).to_vec();
|
||||
}
|
||||
let mut defs: Vec<Def> = index.units(name).to_vec();
|
||||
let exported = index.workspace_symbols(name);
|
||||
let members = exported.iter().filter(|hit| hit.name == name && hit.container.is_some());
|
||||
defs.extend(members.map(|hit| hit.def.clone()));
|
||||
defs.extend(index.hierarchical_declarations(name).map(|(_, def)| def.clone()));
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
defs.retain(|def| seen.insert(DefinitionKey::of(def)));
|
||||
defs
|
||||
}
|
||||
|
||||
fn references(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let (path, analysis, offset) = match target(project, args)? {
|
||||
Target::At { path, analysis, offset } => (path, analysis, offset),
|
||||
Target::Named { name, unit } => {
|
||||
let (path, offset) = declaration_position(project, &name, unit.as_deref())?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
(path, analysis, offset)
|
||||
}
|
||||
};
|
||||
if let Some(name) = analysis.token_at(offset).filter(|t| t.is_macro()).and_then(macro_name) {
|
||||
return Err(format!("`{name} is a macro; {MACRO_REFUSAL}"));
|
||||
}
|
||||
let set = WholeSet::read(project, Some(&path));
|
||||
let include = args.flag("include_declaration", true);
|
||||
let found = vlog_refactor::find_references(&set.files, &path, offset, include)
|
||||
.map_err(engine_refusal)?;
|
||||
let partial = set.warning(project);
|
||||
let mentions = unresolved(project, &set, &analysis, (&path, offset), &found, args);
|
||||
let mut texts = Texts::default();
|
||||
for (held, text) in set.files {
|
||||
texts.hold(held, text);
|
||||
}
|
||||
let hits: Vec<Site> = found
|
||||
.iter()
|
||||
.filter_map(|(file, span)| {
|
||||
let (text, lines) = texts.get(file)?;
|
||||
Some(Site::at(project.relative(file), text, lines, *span, "use"))
|
||||
})
|
||||
.collect();
|
||||
let (hits, emptied) = only_in(args, hits, |hit| hit.file.clone());
|
||||
let mut answer = render_hits(&hits, emptied, args);
|
||||
if !mentions.is_empty() {
|
||||
answer.text.push_str(MENTIONS_LABEL);
|
||||
answer.text.push_str(&mentions.lines(" "));
|
||||
}
|
||||
answer.structured["unresolved_mentions"] = mentions.json();
|
||||
// A file the index skipped was not searched: the census is partial.
|
||||
if let Some(partial) = partial {
|
||||
answer.text.push_str(&format!("warning: {partial}\n"));
|
||||
answer.structured["warning"] = Value::from(partial);
|
||||
}
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// The section `references` ends with when the name is also spelled where
|
||||
/// no engine looks.
|
||||
const MENTIONS_LABEL: &str =
|
||||
"unresolved mentions (strings, comments, macro text — not resolved by lucisv):\n";
|
||||
|
||||
/// The declaration's unresolved mentions across the set, the engine's hits
|
||||
/// accounted for — on the first page only; later pages repeat nothing.
|
||||
fn unresolved(
|
||||
project: &Project,
|
||||
set: &WholeSet,
|
||||
analysis: &Analysis,
|
||||
(path, offset): (&Path, u32),
|
||||
found: &[(PathBuf, TextRange)],
|
||||
args: &Args,
|
||||
) -> Mentions {
|
||||
let name = vlog_refactor::rename_name_at(&analysis.semantics, offset);
|
||||
let (Some(name), 0) = (name, args.count("offset", 0)) else {
|
||||
return Mentions::default();
|
||||
};
|
||||
let mut accounted: Vec<(PathBuf, Vec<TextRange>)> = Vec::new();
|
||||
for (file, span) in found {
|
||||
match accounted.iter_mut().find(|(held, _)| held == file) {
|
||||
Some((_, spans)) => spans.push(*span),
|
||||
None => accounted.push((file.clone(), vec![*span])),
|
||||
}
|
||||
}
|
||||
let unit = vlog_refactor::enclosing_module(&analysis.text, offset);
|
||||
let focus = Focus { name: &name, home: path, unit: unit.as_deref(), accounted: &accounted };
|
||||
// `in` keeps the mentions it keeps the hits of.
|
||||
let kept =
|
||||
|path: &Path| in_glob(args).is_none_or(|glob| path_match(glob, &project.relative(path)));
|
||||
let files = set.files.iter().filter(|(path, _)| kept(path));
|
||||
mentions::find(project, files.map(|(path, text)| (path.as_path(), text.as_str())), &focus)
|
||||
}
|
||||
|
||||
/// The one declaration a bare `name` selects for `references` (and `rename`).
|
||||
pub(super) fn declaration_position(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
unit: Option<&str>,
|
||||
) -> Result<(PathBuf, u32), String> {
|
||||
let mut defs = declarations(project.index(), name, unit);
|
||||
if defs.is_empty() && project.ensure_walked_for_miss() {
|
||||
defs = declarations(project.index(), name, unit);
|
||||
}
|
||||
let sites = def_sites(project, &defs, name);
|
||||
match (defs.as_slice(), sites.len()) {
|
||||
([def], 1) => {
|
||||
let path = project.index().path(def.file).map(Path::to_path_buf);
|
||||
path.map(|path| (path, def.name_span.start))
|
||||
.ok_or_else(|| format!("`{name}`'s file is no longer indexed."))
|
||||
}
|
||||
(_, 0)
|
||||
if unit.is_none()
|
||||
&& !define_sites(project, name.trim_start_matches('`')).is_empty() =>
|
||||
{
|
||||
Err(format!("`{name}` is a macro; {MACRO_REFUSAL}"))
|
||||
}
|
||||
(_, 0) => Err(format!("no declaration of `{name}`{} is indexed.", in_unit(unit))),
|
||||
_ => {
|
||||
let listed: Vec<String> =
|
||||
sites.iter().map(|site| format!("{}:{}", site.file, site.line)).collect();
|
||||
Err(format!(
|
||||
"`{name}` is declared {} times ({}); pick one with `file` and `line`.",
|
||||
listed.len(),
|
||||
listed.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `references` does not answer for a macro.
|
||||
const MACRO_REFUSAL: &str =
|
||||
"references follows declarations, not macros (`defines` lists its definitions).";
|
||||
|
||||
/// The engine's refusal, said as ours: prefixed, and its rename wording —
|
||||
/// `find_references` shares the rename's resolution — turned into this
|
||||
/// tool's.
|
||||
fn engine_refusal(sentence: String) -> String {
|
||||
const REWORDED: &[(&str, &str)] = &[
|
||||
("there is no symbol to rename at this position", "there is no symbol at this position"),
|
||||
(
|
||||
"nothing outside the project scope can be renamed",
|
||||
"nothing outside the project scope is followed",
|
||||
),
|
||||
("lucisv found nothing to rename for", "lucisv found no occurrence of"),
|
||||
("the rename was abandoned", "the search was abandoned"),
|
||||
("which declaration this rename means", "which declaration this position means"),
|
||||
(", so a rename here would only be half a rename", ", so its uses cannot all be listed"),
|
||||
];
|
||||
let mut out = sentence;
|
||||
for (from, to) in REWORDED {
|
||||
out = out.replace(from, to);
|
||||
}
|
||||
format!("lucisv cannot follow this position: {out}")
|
||||
}
|
||||
|
||||
const HITS: Noun = Noun("hit", "hits");
|
||||
|
||||
/// Hits grouped by file, `line:col text`, paged; `emptied` when the `in`
|
||||
/// glob removed every hit there was.
|
||||
fn render_hits(hits: &[Site], emptied: bool, args: &Args) -> Answer {
|
||||
let page = Page::of(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = page
|
||||
.shown
|
||||
.iter()
|
||||
.map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text)))
|
||||
.collect();
|
||||
let mut text = page.header(HITS);
|
||||
text.push_str(&render::grouped(&entries));
|
||||
render::more(&mut text, page.rest());
|
||||
if hits.is_empty() {
|
||||
text = if emptied { render::none_match(HITS) } else { "no references\n".to_string() };
|
||||
}
|
||||
let listed: Vec<Value> = page
|
||||
.shown
|
||||
.iter()
|
||||
.map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text }))
|
||||
.collect();
|
||||
let structured = json!({ "hits": listed, "total": hits.len(), "shown": page.shown_json() });
|
||||
Answer { text, structured }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::engine_refusal;
|
||||
|
||||
#[test]
|
||||
fn engine_refusals_are_prefixed_and_never_speak_of_renaming() {
|
||||
for sentence in [
|
||||
"there is no symbol to rename at this position.",
|
||||
"`x` is declared outside the files lucisv indexes, so a rename here would only be half a rename.",
|
||||
"lucisv found nothing to rename for `x`.",
|
||||
"`x` is declared in more than one indexed file; lucisv will not guess which declaration this rename means.",
|
||||
] {
|
||||
let said = engine_refusal(sentence.to_string());
|
||||
assert!(said.starts_with("lucisv cannot follow this position: "), "{said}");
|
||||
assert!(!said.contains("rename"), "{said}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! `outline`: a file's declarations as a tree with line ranges (its parse
|
||||
//! errors first), or — for `unit` — what a unit offers the code that uses
|
||||
//! it (`interface.rs`), so an agent reads the shape before the source.
|
||||
|
||||
use vlog_semantic::DocumentSymbol;
|
||||
|
||||
use super::interface;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::render;
|
||||
|
||||
/// The most lines an answer holds before `… and N more`.
|
||||
pub const CAP: usize = 300;
|
||||
|
||||
pub const OUTLINE: Tool = Tool {
|
||||
name: "outline",
|
||||
description: "Exactly one of: `file`, its declarations as a tree with line ranges, parse errors first; `unit`, its file:line, parameters and ports in order (modports, package members).",
|
||||
params: &[
|
||||
Param { name: "file", ty: Ty::Str, required: false },
|
||||
Param { name: "unit", ty: Ty::Str, required: false },
|
||||
],
|
||||
rewalk: false,
|
||||
handler: outline,
|
||||
};
|
||||
|
||||
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let lines = match (args.str("file"), args.str("unit")) {
|
||||
(Some(file), None) => file_outline(project, file)?,
|
||||
(None, Some(unit)) => interface::unit_outline(project, unit.trim())?,
|
||||
_ => return Err("give exactly one of `file` and `unit`.".into()),
|
||||
};
|
||||
Ok(Answer::lines(render::capped(lines, CAP)))
|
||||
}
|
||||
|
||||
/// `error LINE: message` per parse error, then `kind name first–last`,
|
||||
/// two spaces per level.
|
||||
pub fn file_outline(project: &mut Project, file: &str) -> Result<Vec<String>, String> {
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let mut lines: Vec<String> = analysis
|
||||
.diagnostics
|
||||
.iter()
|
||||
.map(|error| format!("error {}: {}", error.line, render::one_line(&error.message)))
|
||||
.collect();
|
||||
tree(&analysis, &analysis.semantics.document_symbols(), 0, &mut lines);
|
||||
Ok(lines)
|
||||
}
|
||||
|
||||
/// The outline tree in pre-order.
|
||||
fn tree(analysis: &Analysis, nodes: &[DocumentSymbol], level: usize, out: &mut Vec<String>) {
|
||||
for node in nodes {
|
||||
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
|
||||
continue;
|
||||
};
|
||||
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
|
||||
let (kind, name) = (render::kind(symbol.kind), &symbol.name);
|
||||
let indent = " ".repeat(level);
|
||||
out.push(format!("{indent}{kind} {name} {}", render::lines(first, last)));
|
||||
tree(analysis, &node.children, level + 1, out);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! `add_port`'s `after`: the new port placed right after a named one, in the
|
||||
//! `port`'s `after`: the new port placed right after a named one, in the
|
||||
//! layout of the line it follows, and each named connection placed right
|
||||
//! after the instance's `.after(…)`.
|
||||
//!
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
//! `port`: add a port to a module and connect it by name in every
|
||||
//! instantiation, or remove one and its connection everywhere — the
|
||||
//! design-wide edit a file write cannot do safely. `add` is
|
||||
//! `vlog_refactor::add_port`, placed after `after` by `place.rs`; `remove`
|
||||
//! is `vlog_refactor::remove_port`, refused by the engine while the body
|
||||
//! uses the port. Both write through the one write path and list the port
|
||||
//! name's unresolved mentions.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{module_definition, ModuleRef};
|
||||
use vlog_semantic::SymbolKind;
|
||||
|
||||
use super::edit::{whole_set, write_telling, Told};
|
||||
use super::place;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render;
|
||||
|
||||
pub const PORT: Tool = Tool {
|
||||
name: "port",
|
||||
description: "On `module`, `add` an ANSI port declaration (after port `after`, else last) connected in every instantiation, or `remove` a port and its connections (refused while used).",
|
||||
params: &[
|
||||
Param { name: "module", ty: Ty::Str, required: true },
|
||||
Param { name: "add", ty: Ty::Str, required: false },
|
||||
Param { name: "after", ty: Ty::Str, required: false },
|
||||
Param { name: "remove", ty: Ty::Str, required: false },
|
||||
],
|
||||
rewalk: true,
|
||||
handler: port,
|
||||
};
|
||||
|
||||
fn port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let module = args.str("module").unwrap_or_default().trim();
|
||||
let file = declaring_file(project, module)?;
|
||||
match (args.str("add"), args.str("remove"), args.str("after")) {
|
||||
(Some(add), None, after) => add_port(project, module, &file, add, after),
|
||||
(None, Some(remove), None) => remove_port(project, module, &file, remove.trim()),
|
||||
(None, Some(_), Some(_)) => Err("`after` goes with `add`, not `remove`.".into()),
|
||||
_ => Err("give exactly one of `add` and `remove`.".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one file declaring module `module`, walking once for a module
|
||||
/// written since the last walk.
|
||||
fn declaring_file(project: &mut Project, module: &str) -> Result<PathBuf, String> {
|
||||
let found = module_definition(project.index(), module).map(Path::to_path_buf);
|
||||
match found {
|
||||
Err(_) if project.ensure_walked_for_miss() => {
|
||||
module_definition(project.index(), module).map(Path::to_path_buf)
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_port(
|
||||
project: &mut Project,
|
||||
module: &str,
|
||||
file: &Path,
|
||||
declaration: &str,
|
||||
after: Option<&str>,
|
||||
) -> Result<Answer, String> {
|
||||
let set = whole_set(project, None, &[module.to_string()])?;
|
||||
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(module), declaration)
|
||||
.map_err(|why| set.rooted(project, &why))?;
|
||||
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
|
||||
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
|
||||
let show = &|path: &Path| project.relative(path);
|
||||
let edit = match after.map(str::trim) {
|
||||
Some(after) => {
|
||||
let spec = place::Spec { module, file, after, port: &port, declaration, show };
|
||||
place::after(&set.files, &edit, &spec).map_err(|why| set.rooted(project, &why))?
|
||||
}
|
||||
None => edit,
|
||||
};
|
||||
let told = Told { name: &port, home: file, unit: Some(module) };
|
||||
let (count, files) = instantiations(project, module);
|
||||
let done = write_telling(project, edit, &set, &told)?;
|
||||
let head = format!("added port {port} in module {module}: {}", census(count, files));
|
||||
Ok(Answer::lines(std::iter::once(head).chain(done.tail).collect()))
|
||||
}
|
||||
|
||||
fn remove_port(
|
||||
project: &mut Project,
|
||||
module: &str,
|
||||
file: &Path,
|
||||
port: &str,
|
||||
) -> Result<Answer, String> {
|
||||
let offset = port_offset(project, module, file, port)?;
|
||||
let set = whole_set(project, Some(file), &[port.to_string(), module.to_string()])?;
|
||||
let edit = vlog_refactor::remove_port(&set.files, file, offset)
|
||||
.map_err(|why| set.rooted(project, &why))?;
|
||||
let told = Told { name: port, home: file, unit: Some(module) };
|
||||
let (count, files) = instantiations(project, module);
|
||||
let done = write_telling(project, edit, &set, &told)?;
|
||||
let head = format!("removed port {port} in module {module}: {}", census(count, files));
|
||||
Ok(Answer::lines(std::iter::once(head).chain(done.tail).collect()))
|
||||
}
|
||||
|
||||
/// Where port `port` of `module` is named in the module's file: its header
|
||||
/// entry (an ANSI port, or a non-ANSI header name).
|
||||
fn port_offset(
|
||||
project: &mut Project,
|
||||
module: &str,
|
||||
file: &Path,
|
||||
port: &str,
|
||||
) -> Result<u32, String> {
|
||||
let analysis = project.analysis(file)?;
|
||||
let semantics = &analysis.semantics;
|
||||
let unit = semantics
|
||||
.symbols_named(module)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.find(|symbol| symbol.kind.is_instantiable())
|
||||
.and_then(|symbol| symbol.child_scope);
|
||||
let found = semantics
|
||||
.symbols_named(port)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.find(|symbol| symbol.kind == SymbolKind::Port && Some(symbol.scope) == unit);
|
||||
match found {
|
||||
Some(symbol) => Ok(symbol.name_span.start),
|
||||
None => {
|
||||
let ports: Vec<&str> = semantics
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|symbol| symbol.kind == SymbolKind::Port && Some(symbol.scope) == unit)
|
||||
.map(|symbol| symbol.name.as_str())
|
||||
.collect();
|
||||
Err(format!("`{module}` has no port `{port}` (its ports: {}).", ports.join(", ")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `N instantiations in K files`.
|
||||
fn census(count: usize, files: usize) -> String {
|
||||
format!("{} in {}", render::count(count, "instantiation"), render::count(files, "file"))
|
||||
}
|
||||
|
||||
/// How many instances of `module` the index holds, and in how many files —
|
||||
/// the instantiations a port edit connects or disconnects.
|
||||
fn instantiations(project: &Project, module: &str) -> (usize, usize) {
|
||||
let edges = project.index().instantiations_of(module);
|
||||
let count = edges.iter().map(|edge| edge.instances.len()).sum();
|
||||
let files: BTreeSet<_> = edges.iter().map(|edge| edge.file).collect();
|
||||
(count, files.len())
|
||||
}
|
||||
@@ -1,572 +1,80 @@
|
||||
//! The whole-project read tools: `project_overview`, `list_units`,
|
||||
//! `outline` and `search_symbols`. Each answers from the index (or from one
|
||||
//! file's analysis) and renders by the rules in `render.rs`.
|
||||
//! `read`: one item's exact source — a slice, never the file — preceded by
|
||||
//! `file:first–last`. In a named `file` the item is sliced as
|
||||
//! `read_item::select` slices it; without one the name is looked up
|
||||
//! design-wide and must be declared exactly once.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_semantic::{Def, DocumentSymbol, SymbolKind, WorkspaceIndex};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::names;
|
||||
use super::read_item::{declared_lines, select, split_kind, split_line, BY_LINE};
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
use crate::render::{self, Noun, Page, DEFAULT_LIMIT};
|
||||
use crate::render;
|
||||
|
||||
const LIMIT: Param =
|
||||
Param { name: "limit", ty: Ty::Int { min: 1 }, required: false, description: "Default 500." };
|
||||
const OFFSET: Param = Param {
|
||||
name: "offset",
|
||||
ty: Ty::Int { min: 0 },
|
||||
required: false,
|
||||
description: "Entries to skip.",
|
||||
};
|
||||
|
||||
/// `in`, the path filter every whole-project listing takes.
|
||||
pub(super) const IN: Param = Param {
|
||||
name: "in",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Path glob the file must match, e.g. `ip/**/rtl/*.sv`.",
|
||||
};
|
||||
|
||||
/// How many top-level modules the overview names; the rest are counted.
|
||||
const TOPS_CAP: usize = 200;
|
||||
|
||||
const UNITS: Noun = Noun("unit", "units");
|
||||
const ENTRIES: Noun = Noun("entry", "entries");
|
||||
const SYMBOLS: Noun = Noun("symbol", "symbols");
|
||||
|
||||
pub const PROJECT_OVERVIEW: Tool = Tool {
|
||||
name: "project_overview",
|
||||
title: "Project overview",
|
||||
description: "Files, units by kind, top modules, largest files. Call it first.",
|
||||
params: &[],
|
||||
rewalk: true,
|
||||
handler: project_overview,
|
||||
};
|
||||
|
||||
pub const LIST_UNITS: Tool = Tool {
|
||||
name: "list_units",
|
||||
title: "List units",
|
||||
description: "Units (modules, interfaces, packages, classes, programs) with file:line.",
|
||||
pub const READ: Tool = Tool {
|
||||
name: "read",
|
||||
description: "One item's exact source after its file:first–last line. `item`: name, kind:name, name@LINE, or always@LINE; `file` is needed for always@LINE or a name declared in several files.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "kind",
|
||||
ty: Ty::Enum(&["module", "interface", "package", "class", "program"]),
|
||||
required: false,
|
||||
description: "Only this kind.",
|
||||
},
|
||||
Param {
|
||||
name: "glob",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Name pattern with `*` and `?`.",
|
||||
},
|
||||
IN,
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
Param { name: "item", ty: Ty::Str, required: true },
|
||||
Param { name: "file", ty: Ty::Str, required: false },
|
||||
],
|
||||
rewalk: false,
|
||||
handler: list_units,
|
||||
handler: read,
|
||||
};
|
||||
|
||||
pub const OUTLINE: Tool = Tool {
|
||||
name: "outline",
|
||||
title: "File outline",
|
||||
description: "A file's declarations as a tree with line ranges, and its parse errors.",
|
||||
params: &[
|
||||
Param { name: "file", ty: Ty::Str, required: true, description: "The file." },
|
||||
Param {
|
||||
name: "depth",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "Levels (1: units only; default all).",
|
||||
},
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: outline,
|
||||
};
|
||||
|
||||
pub const SEARCH_SYMBOLS: Tool = Tool {
|
||||
name: "search_symbols",
|
||||
title: "Search symbols",
|
||||
description: "Declarations whose name contains `query` (any case), members included.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "query",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "Name substring; empty matches all.",
|
||||
},
|
||||
IN,
|
||||
LIMIT,
|
||||
OFFSET,
|
||||
],
|
||||
rewalk: false,
|
||||
handler: search_symbols,
|
||||
};
|
||||
|
||||
/// One unit in a listing.
|
||||
struct Unit {
|
||||
name: String,
|
||||
kind: &'static str,
|
||||
file: String,
|
||||
line: u32,
|
||||
}
|
||||
|
||||
/// Every unit the index holds, file-scope ones and the classes a package
|
||||
/// declares (named `pkg::cls`), sorted by file then line.
|
||||
fn units(project: &Project) -> Vec<Unit> {
|
||||
let index = project.index();
|
||||
let mut out = Vec::new();
|
||||
for kind in [SymbolKind::Module, SymbolKind::Interface, SymbolKind::Package, SymbolKind::Class]
|
||||
{
|
||||
for (name, def) in index.units_of(kind) {
|
||||
out.push(unit(project, name.to_string(), def));
|
||||
}
|
||||
fn read(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let selector = args.str("item").unwrap_or("").trim();
|
||||
if selector.is_empty() {
|
||||
return Err("`item` is empty.".into());
|
||||
}
|
||||
for (package, _) in index.units_of(SymbolKind::Package) {
|
||||
for (name, defs) in index.members_of(package) {
|
||||
for def in defs.iter().filter(|def| def.kind == SymbolKind::Class) {
|
||||
out.push(unit(project, format!("{package}::{name}"), def));
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| (&a.file, a.line, &a.name).cmp(&(&b.file, b.line, &b.name)));
|
||||
out
|
||||
}
|
||||
|
||||
fn unit(project: &Project, name: String, def: &Def) -> Unit {
|
||||
let path = project.index().path(def.file).unwrap_or(Path::new(""));
|
||||
Unit {
|
||||
name,
|
||||
kind: unit_kind(project, path, def),
|
||||
file: project.relative(path),
|
||||
line: def.lines.name,
|
||||
}
|
||||
}
|
||||
|
||||
/// A unit's kind word, telling a `program` from the module it is modelled as.
|
||||
pub fn unit_kind(project: &Project, path: &Path, def: &Def) -> &'static str {
|
||||
if def.kind == SymbolKind::Module && is_program(project, path, def) {
|
||||
"program"
|
||||
} else {
|
||||
render::kind(def.kind)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a `Module`-kind unit was declared with `program`. The semantic
|
||||
/// layer models the two alike, so the keyword is read off the text between
|
||||
/// the declaration's start and its name — only for the rare file whose text
|
||||
/// spells `endprogram` at all.
|
||||
fn is_program(project: &Project, path: &Path, def: &Def) -> bool {
|
||||
if !project.stamp(path).is_some_and(|stamp| stamp.program) {
|
||||
return false;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(path) else {
|
||||
return false;
|
||||
let path = match args.str("file") {
|
||||
Some(file) => project.resolve(file)?,
|
||||
None => locate(project, selector)?,
|
||||
};
|
||||
let head = text.get(def.decl_span.start as usize..def.name_span.start as usize);
|
||||
head.is_some_and(|head| head.split_whitespace().any(|word| word == "program"))
|
||||
}
|
||||
|
||||
/// 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();
|
||||
let name: Vec<char> = name.chars().collect();
|
||||
// Classic two-pointer match with one backtrack point per `*`.
|
||||
let (mut p, mut n, mut star, mut resume) = (0, 0, None, 0);
|
||||
while n < name.len() {
|
||||
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
|
||||
p += 1;
|
||||
n += 1;
|
||||
} else if p < pattern.len() && pattern[p] == '*' {
|
||||
star = Some(p);
|
||||
resume = n;
|
||||
p += 1;
|
||||
} else if let Some(at) = star {
|
||||
p = at + 1;
|
||||
resume += 1;
|
||||
n = resume;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
/// Whether a root-relative `path` matches a path glob: `*` and `?` within
|
||||
/// one component ([`glob_match`]), `**` as a whole component for any run of
|
||||
/// components (none included). A trailing `/` means everything below.
|
||||
pub fn path_match(pattern: &str, path: &str) -> bool {
|
||||
let pattern = pattern.strip_prefix("./").unwrap_or(pattern);
|
||||
// A bare directory (`ip/aes`, no wildcard) means everything below it, as
|
||||
// it does for `.gitignore` and `rg -g` (feedback-2 QA note 2).
|
||||
let literal = !pattern.contains(['*', '?']);
|
||||
if literal && path.strip_prefix(pattern).is_some_and(|rest| rest.starts_with('/')) {
|
||||
return true;
|
||||
}
|
||||
let mut parts: Vec<&str> = pattern.split('/').collect();
|
||||
if parts.last() == Some(&"") && parts.len() > 1 {
|
||||
parts.pop();
|
||||
parts.push("**");
|
||||
}
|
||||
// `**/**` means what `**` means; collapsing keeps the search linear-ish.
|
||||
parts.dedup_by(|a, b| *a == "**" && *b == "**");
|
||||
let components: Vec<&str> = path.split('/').collect();
|
||||
components_match(&parts, &components)
|
||||
}
|
||||
|
||||
fn components_match(pattern: &[&str], path: &[&str]) -> bool {
|
||||
match pattern.split_first() {
|
||||
None => path.is_empty(),
|
||||
Some((&"**", rest)) => (0..=path.len()).any(|skip| components_match(rest, &path[skip..])),
|
||||
Some((first, rest)) => path
|
||||
.split_first()
|
||||
.is_some_and(|(part, below)| glob_match(first, part) && components_match(rest, below)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The call's `in` path glob; an empty one filters nothing.
|
||||
pub(super) fn in_glob(args: &Args) -> Option<&str> {
|
||||
args.str("in").filter(|glob| !glob.is_empty())
|
||||
}
|
||||
|
||||
/// The entries whose root-relative file the call's `in` glob keeps (all of
|
||||
/// them without one — `file` is then never asked), and whether the glob
|
||||
/// removed every entry there was.
|
||||
pub(super) fn only_in<T>(
|
||||
args: &Args,
|
||||
items: Vec<T>,
|
||||
file: impl Fn(&T) -> String,
|
||||
) -> (Vec<T>, bool) {
|
||||
let Some(glob) = in_glob(args) else { return (items, false) };
|
||||
let had = !items.is_empty();
|
||||
let kept: Vec<T> = items.into_iter().filter(|item| path_match(glob, &file(item))).collect();
|
||||
let emptied = had && kept.is_empty();
|
||||
(kept, emptied)
|
||||
}
|
||||
|
||||
fn list_units(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let select =
|
||||
|project: &Project| only_in(args, matching_units(project, args), |u| u.file.clone());
|
||||
let (mut all, mut emptied) = select(project);
|
||||
// A glob names something the agent expects to exist — often a file it
|
||||
// has just written — so a miss walks once before it is believed.
|
||||
let named = args.str("glob").is_some() || in_glob(args).is_some();
|
||||
if all.is_empty() && named && project.ensure_walked_for_miss() {
|
||||
(all, emptied) = select(project);
|
||||
}
|
||||
let page = Page::of(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let entries: Vec<(String, String)> = page
|
||||
.shown
|
||||
.iter()
|
||||
.map(|u| (u.file.clone(), format!("{} {} {}", u.kind, u.name, u.line)))
|
||||
.collect();
|
||||
let mut text = page.header(UNITS);
|
||||
text.push_str(&render::grouped(&entries));
|
||||
render::more(&mut text, page.rest());
|
||||
if all.is_empty() {
|
||||
text = if emptied { render::none_match(UNITS) } else { "no units match\n".to_string() };
|
||||
}
|
||||
let structured: Vec<Value> = page
|
||||
.shown
|
||||
.iter()
|
||||
.map(|u| json!({ "name": u.name, "kind": u.kind, "file": u.file, "line": u.line }))
|
||||
.collect();
|
||||
let structured = json!({ "units": structured, "total": all.len(), "shown": page.shown_json() });
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The units `list_units`'s `kind` and `glob` select.
|
||||
fn matching_units(project: &Project, args: &Args) -> Vec<Unit> {
|
||||
units(project)
|
||||
.into_iter()
|
||||
.filter(|unit| args.str("kind").is_none_or(|kind| unit.kind == kind))
|
||||
.filter(|unit| args.str("glob").is_none_or(|glob| glob_match(glob, &unit.name)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn project_overview(project: &mut Project, _: &Args) -> Result<Answer, String> {
|
||||
let overview = Overview::of(project);
|
||||
Ok(Answer { text: overview.text(), structured: overview.json() })
|
||||
}
|
||||
|
||||
/// What `project_overview` reports, gathered once and rendered twice.
|
||||
struct Overview {
|
||||
roots: Vec<String>,
|
||||
config: Option<String>,
|
||||
filelist: Option<String>,
|
||||
files: usize,
|
||||
skipped_large: usize,
|
||||
by_kind: Vec<(&'static str, usize)>,
|
||||
build_ms: u128,
|
||||
age_s: u64,
|
||||
tops: Vec<String>,
|
||||
more_tops: usize,
|
||||
largest: Vec<(String, u64)>,
|
||||
warnings: Vec<String>,
|
||||
}
|
||||
|
||||
impl Overview {
|
||||
fn of(project: &Project) -> Overview {
|
||||
let all = units(project);
|
||||
let kinds = ["module", "interface", "package", "class", "program"];
|
||||
let by_kind = kinds
|
||||
.iter()
|
||||
.map(|&kind| (kind, all.iter().filter(|u| u.kind == kind).count()))
|
||||
.collect();
|
||||
let tops = top_modules(project.index());
|
||||
let (shown, more_tops) = render::page(&tops, 0, TOPS_CAP);
|
||||
let (config, config_problem) = project.config();
|
||||
let discovery = project.discovery();
|
||||
let (build, age) = project.timing();
|
||||
let mut warnings: Vec<String> = discovery.warnings.clone();
|
||||
warnings.extend(config_problem.map(str::to_string));
|
||||
warnings.extend(project.unreadable().iter().cloned());
|
||||
Overview {
|
||||
roots: project.roots().iter().map(|r| r.display().to_string()).collect(),
|
||||
config: config.source.as_ref().map(|path| path.display().to_string()),
|
||||
filelist: discovery.filelist.as_ref().map(|path| path.display().to_string()),
|
||||
files: project.files().count(),
|
||||
skipped_large: discovery.skipped_large,
|
||||
by_kind,
|
||||
build_ms: build.as_millis(),
|
||||
age_s: age.as_secs(),
|
||||
tops: shown.to_vec(),
|
||||
more_tops,
|
||||
largest: largest_files(project, 10),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
fn text(&self) -> String {
|
||||
let mut text = format!("roots: {}\n", self.roots.join(", "));
|
||||
text.push_str(&format!("config: {}\n", self.config.as_deref().unwrap_or("none")));
|
||||
text.push_str(&format!(
|
||||
"filelist: {}\n",
|
||||
self.filelist.as_deref().unwrap_or("none (walked)")
|
||||
));
|
||||
text.push_str(&format!(
|
||||
"files: {} indexed, {} over 1 MiB skipped\n",
|
||||
self.files, self.skipped_large
|
||||
));
|
||||
let counts: Vec<String> =
|
||||
self.by_kind.iter().map(|(kind, n)| format!("{n} {kind}")).collect();
|
||||
text.push_str(&format!("units: {}\n", counts.join(", ")));
|
||||
text.push_str(&format!(
|
||||
"index: built in {} ms, last changed {} s ago\n",
|
||||
self.build_ms, self.age_s
|
||||
));
|
||||
text.push_str(&format!("top: {}\n", self.tops.join(" ")));
|
||||
render::more(&mut text, self.more_tops);
|
||||
text.push_str("largest:\n");
|
||||
let rows: Vec<Vec<String>> =
|
||||
self.largest.iter().map(|(file, size)| vec![size.to_string(), file.clone()]).collect();
|
||||
text.push_str(&render::table(&rows));
|
||||
for warning in self.warnings.iter().take(10) {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
render::more(&mut text, self.warnings.len().saturating_sub(10));
|
||||
text
|
||||
}
|
||||
|
||||
fn json(&self) -> Value {
|
||||
let units: serde_json::Map<String, Value> =
|
||||
self.by_kind.iter().map(|(kind, n)| (kind.to_string(), json!(n))).collect();
|
||||
let largest: Vec<Value> = self
|
||||
.largest
|
||||
.iter()
|
||||
.map(|(file, bytes)| json!({ "file": file, "bytes": bytes }))
|
||||
.collect();
|
||||
json!({
|
||||
"roots": self.roots,
|
||||
"config": self.config,
|
||||
"filelist": self.filelist,
|
||||
"files": self.files,
|
||||
"skipped_large": self.skipped_large,
|
||||
"units": units,
|
||||
"index_build_ms": self.build_ms as u64,
|
||||
"index_age_s": self.age_s,
|
||||
"top_modules": self.tops,
|
||||
"more_top_modules": self.more_tops,
|
||||
"largest_files": largest,
|
||||
"warnings": self.warnings,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Modules (programs included) nothing in the index instantiates, by name.
|
||||
fn top_modules(index: &WorkspaceIndex) -> Vec<String> {
|
||||
let mut tops: Vec<String> = index
|
||||
.instantiable_units()
|
||||
.filter(|(_, def)| def.kind == SymbolKind::Module)
|
||||
.filter(|(name, _)| index.instantiations_of(name).is_empty())
|
||||
.map(|(name, _)| name.to_string())
|
||||
.collect();
|
||||
tops.dedup();
|
||||
tops
|
||||
}
|
||||
|
||||
/// The `n` largest indexed files, largest first.
|
||||
fn largest_files(project: &Project, n: usize) -> Vec<(String, u64)> {
|
||||
let mut sizes: Vec<(u64, &Path)> =
|
||||
project.files().map(|(path, stamp)| (stamp.size, path.as_path())).collect();
|
||||
sizes.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1)));
|
||||
sizes.into_iter().take(n).map(|(size, path)| (project.relative(path), size)).collect()
|
||||
}
|
||||
|
||||
fn outline(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let depth = args.count("depth", usize::MAX);
|
||||
let mut rows: Vec<(usize, String, &'static str, u32, u32)> = Vec::new();
|
||||
flatten(&analysis, &analysis.semantics.document_symbols(), 0, depth, &mut rows);
|
||||
let page = Page::of(&rows, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let shown = page.shown;
|
||||
let file = project.relative(&path);
|
||||
let mut text = page.header(ENTRIES);
|
||||
text.push_str(&format!("{file}\n"));
|
||||
let errors = &analysis.diagnostics;
|
||||
if let Some(first) = errors.first() {
|
||||
text.push_str(&format!(
|
||||
"parse errors: {} (first {}:{} {})\n",
|
||||
errors.len(),
|
||||
first.line,
|
||||
first.col,
|
||||
first.message
|
||||
));
|
||||
let analysis = project.analysis(&path)?;
|
||||
let (_, span) = select(&analysis, selector).map_err(|why| format!("{why} in `{file}`."))?;
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
let mut text =
|
||||
format!("{file}:{}\n{}", render::lines(first, last), analysis.slice(span.start, span.end));
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
for (level, name, kind, first, last) in shown {
|
||||
let indent = " ".repeat(level + 1);
|
||||
text.push_str(&format!("{indent}{kind} {name} {}\n", render::lines(*first, *last)));
|
||||
}
|
||||
render::more(&mut text, page.rest());
|
||||
let symbols: Vec<Value> = shown
|
||||
.iter()
|
||||
.map(|(level, name, kind, first, last)| {
|
||||
json!({ "name": name, "kind": kind, "depth": level + 1, "lines": [first, last] })
|
||||
})
|
||||
.collect();
|
||||
let parse_errors: Vec<Value> = errors
|
||||
.iter()
|
||||
.map(|e| json!({ "line": e.line, "col": e.col, "message": e.message }))
|
||||
.collect();
|
||||
let structured = json!({
|
||||
"file": file, "parse_errors": parse_errors, "symbols": symbols, "total": rows.len(),
|
||||
"shown": page.shown_json(),
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
Ok(Answer { text })
|
||||
}
|
||||
|
||||
/// The outline tree in pre-order, each node with its depth and line range.
|
||||
fn flatten(
|
||||
analysis: &crate::project::Analysis,
|
||||
nodes: &[DocumentSymbol],
|
||||
level: usize,
|
||||
depth: usize,
|
||||
out: &mut Vec<(usize, String, &'static str, u32, u32)>,
|
||||
) {
|
||||
if level >= depth {
|
||||
return;
|
||||
/// The one file declaring what `selector` names, design-wide; a refusal
|
||||
/// listing every site when there are several, or the near matches when
|
||||
/// there are none.
|
||||
fn locate(project: &mut Project, selector: &str) -> Result<PathBuf, String> {
|
||||
let (head, line) = split_line(selector)?;
|
||||
if line.is_some() && BY_LINE.contains(&head) {
|
||||
return Err(format!("`{selector}` names a block by its line; give its `file`."));
|
||||
}
|
||||
for node in nodes {
|
||||
let Some(symbol) = analysis.semantics.symbol(node.symbol) else {
|
||||
continue;
|
||||
};
|
||||
let (first, last) = analysis.line_span(symbol.decl_span.start, symbol.decl_span.end);
|
||||
out.push((level, symbol.name.clone(), render::kind(symbol.kind), first, last));
|
||||
flatten(analysis, &node.children, level + 1, depth, out);
|
||||
let (_, name) = split_kind(head);
|
||||
let mut files: Vec<PathBuf> = Vec::new();
|
||||
for declaration in names::declarations_walking(project, name) {
|
||||
if !declaration.is_macro() && !files.contains(&declaration.path) {
|
||||
files.push(declaration.path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn search_symbols(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let query = args.str("query").unwrap_or("");
|
||||
// A miss may be a file written since the last walk: walk once, then answer.
|
||||
if project.index().workspace_symbols(query).is_empty() {
|
||||
project.ensure_walked_for_miss();
|
||||
let mut sites: Vec<(PathBuf, String)> = Vec::new();
|
||||
for path in files {
|
||||
let analysis = project.analysis(&path)?;
|
||||
let file = project.relative(&path);
|
||||
let lines = declared_lines(&analysis, selector);
|
||||
sites.extend(lines.into_iter().map(|line| (path.clone(), format!("{file}:{line}"))));
|
||||
}
|
||||
let index = project.index();
|
||||
let file_of = |file| project.relative(index.path(file).unwrap_or(Path::new("")));
|
||||
let (hits, emptied) =
|
||||
only_in(args, index.workspace_symbols(query), |hit| file_of(hit.def.file));
|
||||
let page = Page::of(&hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
|
||||
let mut entries = Vec::new();
|
||||
let mut structured = Vec::new();
|
||||
for hit in page.shown {
|
||||
let file = file_of(hit.def.file);
|
||||
let name = match hit.container {
|
||||
Some(unit) => format!("{unit}{}{}", separator(index, unit), hit.name),
|
||||
None => hit.name.to_string(),
|
||||
};
|
||||
// A line and no column: the index records a client (UTF-16) column
|
||||
// for units only, and every column this server prints is a byte one.
|
||||
let line = hit.def.lines.name;
|
||||
entries.push((file.clone(), format!("{} {name} {line}", render::kind(hit.def.kind))));
|
||||
structured.push(json!({
|
||||
"name": name, "kind": render::kind(hit.def.kind), "file": file, "line": line,
|
||||
}));
|
||||
}
|
||||
let mut text = page.header(SYMBOLS);
|
||||
text.push_str(&render::grouped(&entries));
|
||||
render::more(&mut text, page.rest());
|
||||
if hits.is_empty() {
|
||||
text = if emptied { render::none_match(SYMBOLS) } else { "no symbols match\n".into() };
|
||||
}
|
||||
let total = hits.len();
|
||||
let structured = json!({ "symbols": structured, "total": total, "shown": page.shown_json() });
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// How a member is spelled after its unit: `unit.x` for a module or
|
||||
/// interface (a hierarchical name), `unit::x` for a package or a class —
|
||||
/// including a class the index holds only as a package member.
|
||||
fn separator(index: &WorkspaceIndex, unit: &str) -> &'static str {
|
||||
match index.units(unit).first().map(|def| def.kind) {
|
||||
Some(kind) if kind.is_instantiable() => ".",
|
||||
_ => "::",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{glob_match, path_match};
|
||||
|
||||
#[test]
|
||||
fn a_bare_directory_glob_means_everything_below_it() {
|
||||
assert!(super::path_match("ip/aes", "ip/aes/rtl/aes.sv"));
|
||||
assert!(super::path_match("ip/aes/", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!super::path_match("ip/aes", "ip/aes_x/rtl/aes.sv"));
|
||||
assert!(!super::path_match("ip/aes", "ip/ae"));
|
||||
assert!(super::path_match("ip/aes/rtl/aes.sv", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!super::path_match("ip/a?s", "ip/aes/rtl/aes.sv"), "a wildcard keeps glob rules");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn globs_match_runs_and_single_characters() {
|
||||
assert!(glob_match("prim_*", "prim_fifo_sync"));
|
||||
assert!(glob_match("*fifo*", "prim_fifo_sync"));
|
||||
assert!(glob_match("a?c", "abc"));
|
||||
assert!(glob_match("*", ""));
|
||||
assert!(!glob_match("a?c", "ac"));
|
||||
assert!(!glob_match("prim_*_async", "prim_fifo_sync"));
|
||||
assert!(glob_match("*_sync", "prim_fifo_sync"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_globs_keep_star_in_one_component_and_let_double_star_span_many() {
|
||||
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/rtl/aes.sv"));
|
||||
assert!(path_match("ip/**/rtl/*.sv", "ip/aes/sub/rtl/aes.sv"));
|
||||
assert!(path_match("ip/**/rtl/*.sv", "ip/rtl/x.sv"));
|
||||
assert!(!path_match("ip/**/rtl/*.sv", "ip/aes/dv/aes.sv"));
|
||||
assert!(!path_match("ip/*/*.sv", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!path_match("*.sv", "ip/aes.sv"));
|
||||
assert!(path_match("**/*.sv", "ip/aes.sv") && path_match("**/*.sv", "top.sv"));
|
||||
assert!(path_match("ip/ae?/**", "ip/aes/rtl/aes.sv"));
|
||||
assert!(!path_match("ip/ae?/**", "ip/aesx/rtl/aes.sv"));
|
||||
assert!(path_match("ip/", "ip/aes/rtl/aes.sv") && path_match("./ip/**", "ip/a.sv"));
|
||||
assert!(path_match("**/**/**/rtl/**", "a/b/rtl/c/d.sv"));
|
||||
assert!(!path_match("ip/**", "hw/ip/aes.sv"));
|
||||
match sites.as_slice() {
|
||||
[] => Err(names::no_declaration(project, name)),
|
||||
[(path, _)] => Ok(path.clone()),
|
||||
many => {
|
||||
let listed: Vec<&str> = many.iter().map(|(_, site)| site.as_str()).collect();
|
||||
Err(format!(
|
||||
"`{selector}` is declared {} times ({}); give `file`, and `name@LINE` within one file.",
|
||||
listed.len(),
|
||||
listed.join(", ")
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +1,22 @@
|
||||
//! `read_item`: one item's exact text, sliced out of its file — a module, a
|
||||
//! function, a declaration, an instance, or an unlabelled `always` block
|
||||
//! named by the line it covers.
|
||||
//! The item slicer `read` and `edit_item` share: one item's exact span in
|
||||
//! a file — a module, a function, a declaration, an instance, or an
|
||||
//! unlabelled `always` block named by the line it covers.
|
||||
//!
|
||||
//! The slicing rule is the one the M4 structural edits will replace by, so
|
||||
//! it lives here on its own: an item is the parser's `Item` node (its
|
||||
//! The slicing rule is the one the structural edits replace by, so it
|
||||
//! lives here on its own: an item is the parser's `Item` node (its
|
||||
//! attributes included, its leading comments not) that declares the name,
|
||||
//! or — for a declaration a larger construct only *contains* (an ANSI port
|
||||
//! in a module header, a function argument) — the declaration's own span.
|
||||
|
||||
use serde_json::json;
|
||||
use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_semantic::Symbol;
|
||||
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::{Analysis, Project};
|
||||
use crate::project::Analysis;
|
||||
use crate::render;
|
||||
|
||||
pub const READ_ITEM: Tool = Tool {
|
||||
name: "read_item",
|
||||
title: "Read one item",
|
||||
description: "One item's exact source and lines. Selector: `name`, `kind:name`, `name@LINE`, or `always@LINE` (also initial, final, assign).",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file.",
|
||||
},
|
||||
Param {
|
||||
name: "item",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The selector.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: read_item,
|
||||
};
|
||||
|
||||
/// The keywords that name an unlabelled item by the line it covers.
|
||||
const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
|
||||
|
||||
fn read_item(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let path = project.resolve(args.str("file").unwrap_or(""))?;
|
||||
let file = project.relative(&path);
|
||||
let analysis = project.analysis(&path)?;
|
||||
let selector = args.str("item").unwrap_or("").trim();
|
||||
let (kind, span) =
|
||||
select(&analysis, selector).map_err(|problem| format!("{problem} in `{file}`."))?;
|
||||
let (first, last) = analysis.line_span(span.start, span.end);
|
||||
let body = analysis.slice(span.start, span.end);
|
||||
let mut text = format!("{file}:{}\n{body}", render::lines(first, last));
|
||||
if !text.ends_with('\n') {
|
||||
text.push('\n');
|
||||
}
|
||||
let structured = json!({
|
||||
"file": file, "item": selector, "kind": kind, "lines": [first, last], "text": body,
|
||||
});
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
pub const BY_LINE: &[&str] = &["always", "initial", "final", "assign"];
|
||||
|
||||
/// The item `selector` names in this file: its kind word and byte span, or
|
||||
/// the reason there is not exactly one.
|
||||
@@ -83,7 +40,7 @@ pub fn select(analysis: &Analysis, selector: &str) -> Result<(&'static str, Text
|
||||
|
||||
/// `kind:` is a prefix only when it is one of the kind words; otherwise the
|
||||
/// colon is part of the name (`\k:l`, an escaped identifier).
|
||||
fn split_kind(head: &str) -> (Option<&str>, &str) {
|
||||
pub fn split_kind(head: &str) -> (Option<&str>, &str) {
|
||||
match head.split_once(':') {
|
||||
Some((kind, name)) if render::is_kind_word(kind) => (Some(kind), name),
|
||||
_ => (None, head),
|
||||
@@ -92,7 +49,7 @@ fn split_kind(head: &str) -> (Option<&str>, &str) {
|
||||
|
||||
/// Split `head@LINE` at the last `@` when only digits follow it; any other
|
||||
/// `@` belongs to the name (`\a@b`).
|
||||
fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
|
||||
pub fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
|
||||
match selector.rsplit_once('@') {
|
||||
Some((head, digits))
|
||||
if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) =>
|
||||
@@ -106,6 +63,34 @@ fn split_line(selector: &str) -> Result<(&str, Option<u32>), String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The lines of every declaration a by-name `selector` matches in this
|
||||
/// file — none for a malformed or by-line selector.
|
||||
pub fn declared_lines(analysis: &Analysis, selector: &str) -> Vec<u32> {
|
||||
let Ok((head, line)) = split_line(selector) else { return Vec::new() };
|
||||
let (kind, name) = split_kind(head);
|
||||
let mut found = matching(analysis, name, kind, line);
|
||||
if found.is_empty() && line.is_some() && name.starts_with('\\') {
|
||||
found = matching(analysis, split_kind(selector).1, kind, None);
|
||||
}
|
||||
found.iter().map(|symbol| analysis.lines.line_col(symbol.name_span.start).0).collect()
|
||||
}
|
||||
|
||||
/// Every declaration of `name` matching the optional kind word and line.
|
||||
fn matching<'a>(
|
||||
analysis: &'a Analysis,
|
||||
name: &str,
|
||||
kind: Option<&str>,
|
||||
line: Option<u32>,
|
||||
) -> Vec<&'a Symbol> {
|
||||
let semantics = &analysis.semantics;
|
||||
semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
|
||||
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The one declaration of `name` matching the optional kind word and line.
|
||||
fn by_name<'a>(
|
||||
analysis: &'a Analysis,
|
||||
@@ -113,13 +98,7 @@ fn by_name<'a>(
|
||||
kind: Option<&str>,
|
||||
line: Option<u32>,
|
||||
) -> Result<&'a Symbol, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let matches: Vec<&Symbol> = semantics
|
||||
.symbols_named(name)
|
||||
.filter_map(|id| semantics.symbol(id))
|
||||
.filter(|s| kind.is_none_or(|kind| render::kind(s.kind) == kind))
|
||||
.filter(|s| line.is_none_or(|line| analysis.lines.line_col(s.name_span.start).0 == line))
|
||||
.collect();
|
||||
let matches = matching(analysis, name, kind, line);
|
||||
match matches.as_slice() {
|
||||
[one] => Ok(one),
|
||||
[] => Err(format!("no declaration matches `{name}`{}{}", on_kind(kind), on_line(line))),
|
||||
|
||||
@@ -1,319 +0,0 @@
|
||||
//! The refactorings that are not "act at this cursor": `add_port` (a module
|
||||
//! and a declaration), `extract_module` (a line range and a new name), and
|
||||
//! `instantiate`, which writes nothing at all — it answers with the text of
|
||||
//! an instantiation for the agent to place.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use vlog_refactor::{instantiation_plan, module_definition, Home, Layout, ModuleRef};
|
||||
|
||||
use super::edit::{enclosing, finish, finish_telling, whole_set, with_check, Told, DRY_RUN};
|
||||
use super::place;
|
||||
use super::{Answer, Args, Param, Tool, Ty};
|
||||
use crate::project::Project;
|
||||
|
||||
pub const ADD_PORT: Tool = Tool {
|
||||
name: "add_port",
|
||||
title: "Add a port",
|
||||
description:
|
||||
"Add an ANSI port to a module, connected in every instantiation; `after` positions it.",
|
||||
params: &[
|
||||
Param { name: "module", ty: Ty::Str, required: false, description: "The module." },
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Instead of `module`: its file, with `line`.",
|
||||
},
|
||||
Param {
|
||||
name: "line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: false,
|
||||
description: "A line inside the module.",
|
||||
},
|
||||
Param {
|
||||
name: "declaration",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "As written, e.g. `input logic [7:0] cfg`.",
|
||||
},
|
||||
Param {
|
||||
name: "after",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Port to place it after (default last).",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: add_port,
|
||||
};
|
||||
|
||||
pub const EXTRACT_MODULE: Tool = Tool {
|
||||
name: "extract_module",
|
||||
title: "Extract a module",
|
||||
description: "Move whole items in lines `start_line`..`end_line` to a new module instantiated in their place.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The file.",
|
||||
},
|
||||
Param {
|
||||
name: "start_line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: true,
|
||||
description: "First line.",
|
||||
},
|
||||
Param {
|
||||
name: "end_line",
|
||||
ty: Ty::Int { min: 1 },
|
||||
required: true,
|
||||
description: "Last line (included).",
|
||||
},
|
||||
Param {
|
||||
name: "new_name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "An unused name.",
|
||||
},
|
||||
Param {
|
||||
name: "home",
|
||||
ty: Ty::Enum(&["new_file", "same_file"]),
|
||||
required: false,
|
||||
description: "Default `new_file` (`new_name.sv`).",
|
||||
},
|
||||
DRY_RUN,
|
||||
],
|
||||
rewalk: true,
|
||||
handler: extract_module,
|
||||
};
|
||||
|
||||
pub const INSTANTIATE: Tool = Tool {
|
||||
name: "instantiate",
|
||||
title: "Instantiation template",
|
||||
description:
|
||||
"Instantiation text for module `name`: parameters, instance name, named or `.*` ports.",
|
||||
params: &[
|
||||
Param {
|
||||
name: "name",
|
||||
ty: Ty::Str,
|
||||
required: true,
|
||||
description: "The module or interface.",
|
||||
},
|
||||
Param {
|
||||
name: "style",
|
||||
ty: Ty::Enum(&["named", "wildcard"]),
|
||||
required: false,
|
||||
description: "`named` (default) or `wildcard` (`.*`).",
|
||||
},
|
||||
Param {
|
||||
name: "with_params",
|
||||
ty: Ty::Bool,
|
||||
required: false,
|
||||
description: "Write `#(...)` overrides (default true).",
|
||||
},
|
||||
Param {
|
||||
name: "instance",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Instance name (default `u_<name>`).",
|
||||
},
|
||||
Param {
|
||||
name: "file",
|
||||
ty: Ty::Str,
|
||||
required: false,
|
||||
description: "Its file, if declared twice.",
|
||||
},
|
||||
],
|
||||
rewalk: false,
|
||||
handler: instantiate,
|
||||
};
|
||||
|
||||
fn add_port(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
with_check(add_port_to(project, args), args)
|
||||
}
|
||||
|
||||
fn add_port_to(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let declaration = args.str("declaration").unwrap_or_default();
|
||||
let (module, file, set, edit) = match (args.str("module"), args.str("file"), args.int("line")) {
|
||||
(Some(name), None, None) => {
|
||||
let set = whole_set(project, None, &[name.to_string()])?;
|
||||
let edit = vlog_refactor::add_port(&set.files, ModuleRef::Name(name), declaration)?;
|
||||
let file = module_definition(project.index(), name).map(Path::to_path_buf)?;
|
||||
(name.to_string(), file, set, edit)
|
||||
}
|
||||
(None, Some(file), Some(line)) => {
|
||||
let path = project.resolve(file)?;
|
||||
let offset = line_start(project, &path, line)?;
|
||||
let names = enclosing(&*project.analysis(&path)?, offset);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let module = ModuleRef::At { file: &path, offset };
|
||||
let edit = vlog_refactor::add_port(&set.files, module, declaration)?;
|
||||
let name = names.into_iter().next().unwrap_or_default();
|
||||
(name, path, set, edit)
|
||||
}
|
||||
_ => return Err("name the module by `module`, or by `file` and `line`, not both.".into()),
|
||||
};
|
||||
let tokens = vlog_parser::tokenize(declaration).unwrap_or_default();
|
||||
let port = place::port_name(&tokens).map(|token| token.text.clone()).unwrap_or_default();
|
||||
let show = &|path: &Path| project.relative(path);
|
||||
let edit = match args.str("after") {
|
||||
Some(after) => {
|
||||
let spec =
|
||||
place::Spec { module: &module, file: &file, after, port: &port, declaration, show };
|
||||
place::after(&set.files, &edit, &spec)?
|
||||
}
|
||||
None => edit,
|
||||
};
|
||||
let lead = format!("the new port's name `{port}` is already spelled");
|
||||
let told = Told { name: &port, lead, home: &file };
|
||||
finish_telling(project, edit, &set, args, told, Some(&module))
|
||||
}
|
||||
|
||||
/// The byte offset where 1-based `line` of `path` starts; `end` asks for
|
||||
/// where it ends instead (its line ending excluded).
|
||||
fn line_offset(project: &mut Project, path: &Path, line: i64, end: bool) -> Result<u32, String> {
|
||||
let analysis = project.analysis(path)?;
|
||||
let count = analysis.lines.line_count();
|
||||
let range = u32::try_from(line).ok().and_then(|line| analysis.lines.line_range(line));
|
||||
let Some(range) = range else {
|
||||
let file = project.relative(path);
|
||||
return Err(format!("line {line} is past the end of `{file}` ({count} lines)."));
|
||||
};
|
||||
Ok(if end { range.end } else { range.start })
|
||||
}
|
||||
|
||||
fn line_start(project: &mut Project, path: &Path, line: i64) -> Result<u32, String> {
|
||||
line_offset(project, path, line, false)
|
||||
}
|
||||
|
||||
fn extract_module(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
with_check(extract_lines(project, args), args)
|
||||
}
|
||||
|
||||
fn extract_lines(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let file = args.str("file").unwrap_or_default();
|
||||
let path = project.resolve(file)?;
|
||||
let (first, last) = (args.int("start_line").unwrap_or(1), args.int("end_line").unwrap_or(1));
|
||||
if last < first {
|
||||
return Err(format!("`end_line` {last} is before `start_line` {first}."));
|
||||
}
|
||||
let start = line_start(project, &path, first)?;
|
||||
let end = line_offset(project, &path, last, true)?;
|
||||
let home = match args.str("home") {
|
||||
Some("same_file") => Home::SameFile,
|
||||
_ => Home::NewFile,
|
||||
};
|
||||
let new_name = args.str("new_name").unwrap_or_default();
|
||||
let names = enclosing(&*project.analysis(&path)?, start);
|
||||
let set = whole_set(project, Some(&path), &names)?;
|
||||
let edit = vlog_refactor::extract_module(&set.files, &path, start, end, new_name, home)?;
|
||||
finish(project, edit, &set, args)
|
||||
}
|
||||
|
||||
fn instantiate(project: &mut Project, args: &Args) -> Result<Answer, String> {
|
||||
let name = args.str("name").unwrap_or_default();
|
||||
let path = declaring_file(project, name, args.str("file"))?;
|
||||
let text = std::fs::read_to_string(&path)
|
||||
.map_err(|e| format!("cannot read `{}`: {e}", project.relative(&path)))?;
|
||||
let mut plan = instantiation_plan(name, &text, None)?;
|
||||
if !args.flag("with_params", true) {
|
||||
plan.params.clear();
|
||||
}
|
||||
let wildcard = args.str("style") == Some("wildcard");
|
||||
if wildcard {
|
||||
plan.ports.clear();
|
||||
}
|
||||
let instance = match args.str("instance") {
|
||||
Some(instance) => identifier(instance)?.to_string(),
|
||||
None => plan.instance_name(),
|
||||
};
|
||||
// `render_with` numbers the fill-ins: each parameter, then the instance.
|
||||
let instance_hole = plan.params.len() + 1;
|
||||
let mut hole = |n: usize, default: &str| {
|
||||
if n == instance_hole {
|
||||
instance.clone()
|
||||
} else {
|
||||
default.into()
|
||||
}
|
||||
};
|
||||
let mut skeleton = plan.render_with(&layout(project), &mut hole);
|
||||
if wildcard {
|
||||
// With no ports the skeleton ends `u_x ();`.
|
||||
skeleton.truncate(skeleton.len() - "();".len());
|
||||
skeleton.push_str("(.*);");
|
||||
}
|
||||
skeleton.push('\n');
|
||||
let file = project.relative(&path);
|
||||
let structured = serde_json::json!({
|
||||
"module": name, "file": file, "text": skeleton, "warnings": plan.warnings,
|
||||
});
|
||||
let mut text = skeleton;
|
||||
for warning in &plan.warnings {
|
||||
text.push_str(&format!("warning: {warning}\n"));
|
||||
}
|
||||
Ok(Answer { text, structured })
|
||||
}
|
||||
|
||||
/// The one file declaring module `name` — `file` when given (it must be a
|
||||
/// file the index says declares it), else the index's single answer, after
|
||||
/// one walk for a module written since the last one.
|
||||
fn declaring_file(
|
||||
project: &mut Project,
|
||||
name: &str,
|
||||
file: Option<&str>,
|
||||
) -> Result<PathBuf, String> {
|
||||
if let Some(file) = file {
|
||||
let path = project.resolve(file)?;
|
||||
let declares = project.index().units(name).iter().any(|def| {
|
||||
def.kind.is_instantiable() && project.index().path(def.file) == Some(path.as_path())
|
||||
});
|
||||
if !declares {
|
||||
return Err(format!("`{file}` declares no module named `{name}`."));
|
||||
}
|
||||
return Ok(path);
|
||||
}
|
||||
let found = module_definition(project.index(), name).map(Path::to_path_buf);
|
||||
match found {
|
||||
Err(_) if project.ensure_walked_for_miss() => {
|
||||
module_definition(project.index(), name).map(Path::to_path_buf)
|
||||
}
|
||||
found => found,
|
||||
}
|
||||
.map_err(|why| {
|
||||
if why.contains("more than one") {
|
||||
format!("{why} Pass `file` to pick one.")
|
||||
} else {
|
||||
why
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// `name`, when it is one SystemVerilog identifier: a simple one
|
||||
/// (`[A-Za-z_][A-Za-z0-9_$]*`, not a keyword) or an escaped one (`\`, then
|
||||
/// printable non-space characters, then one space). Anything else would
|
||||
/// render text that does not parse.
|
||||
fn identifier(name: &str) -> Result<&str, String> {
|
||||
let simple = name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
|
||||
&& name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
|
||||
&& !vlog_parser::token::is_keyword(name);
|
||||
let escaped = name
|
||||
.strip_prefix('\\')
|
||||
.and_then(|rest| rest.strip_suffix(' '))
|
||||
.is_some_and(|body| !body.is_empty() && body.chars().all(|c| c.is_ascii_graphic()));
|
||||
if simple || escaped {
|
||||
return Ok(name);
|
||||
}
|
||||
Err(format!(
|
||||
"`instance` must be one identifier — `[A-Za-z_][A-Za-z0-9_$]*` and not a keyword, or an escaped identifier `\\name ` ending in one space; `{name}` is not."
|
||||
))
|
||||
}
|
||||
|
||||
/// Column zero, one indentation step as the project's lucisv.toml spells it.
|
||||
fn layout(project: &Project) -> Layout {
|
||||
let indent =
|
||||
project.config().0.indent.unwrap_or(vlog_formatter::Config::default().indent_width);
|
||||
Layout { base: String::new(), step: " ".repeat(indent) }
|
||||
}
|
||||
@@ -1,212 +0,0 @@
|
||||
//! The selector `definition` and `references` share: a position (`file` +
|
||||
//! `line` + `col`, or `file` + `line` + the `name` written on that line), a
|
||||
//! name in a file (`file` + `name`), or a bare `name` (with an optional
|
||||
//! `unit`) looked up in the index. A position is picked by **token**, never
|
||||
//! by text, so a comment, a string or a macro argument cannot stand in for
|
||||
//! the code; and a pick that would be a guess is refused with the choices.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_semantic::{Definition, ExternalResolutions, Symbol};
|
||||
|
||||
use super::Args;
|
||||
use crate::project::{Analysis, Project};
|
||||
|
||||
/// What a selector points at.
|
||||
pub(super) enum Target {
|
||||
/// A byte position in a file.
|
||||
At { path: PathBuf, analysis: Rc<Analysis>, offset: u32 },
|
||||
/// A name to look up in the index, optionally inside one unit.
|
||||
Named { name: String, unit: Option<String> },
|
||||
}
|
||||
|
||||
/// Read the selector; the refusal says which combination is wanted.
|
||||
pub(super) fn target(project: &mut Project, args: &Args) -> Result<Target, String> {
|
||||
let Some(file) = args.str("file") else {
|
||||
if args.int("line").is_some() || args.int("col").is_some() {
|
||||
return Err("`line` and `col` need `file`.".into());
|
||||
}
|
||||
let Some(name) = args.str("name").filter(|name| !name.is_empty()) else {
|
||||
return Err("give `file` with `line` and `col` (or `name`), or a `name`.".into());
|
||||
};
|
||||
let unit = args.str("unit").map(str::to_string);
|
||||
return Ok(Target::Named { name: name.to_string(), unit });
|
||||
};
|
||||
if args.str("unit").is_some() {
|
||||
return Err("`unit` belongs to the by-name form; drop `file`, `line` and `col`.".into());
|
||||
}
|
||||
let path = project.resolve(file)?;
|
||||
let analysis = project.analysis(&path)?;
|
||||
let shown = project.relative(&path);
|
||||
let offset =
|
||||
offset_in(project, &shown, &analysis, args).map_err(|e| format!("{e} (in `{file}`)"))?;
|
||||
Ok(Target::At { path, analysis, offset })
|
||||
}
|
||||
|
||||
/// The byte offset the position arguments name in one file.
|
||||
fn offset_in(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
args: &Args,
|
||||
) -> Result<u32, String> {
|
||||
let name = args.str("name").filter(|name| !name.is_empty());
|
||||
let line = args.int("line").map(|line| u32::try_from(line).unwrap_or(u32::MAX));
|
||||
let col = args.int("col").map(|col| u32::try_from(col).unwrap_or(u32::MAX));
|
||||
match (line, col, name) {
|
||||
(Some(line), Some(col), _) => at_column(analysis, line, col),
|
||||
(Some(line), None, Some(name)) => on_line(analysis, line, name),
|
||||
(Some(_), None, None) => Err("with `line`, give `col` or the `name` on that line".into()),
|
||||
(None, Some(_), _) => Err("`col` needs `line`".into()),
|
||||
(None, None, Some(name)) => first_occurrence(project, file, analysis, name),
|
||||
(None, None, None) => Err("say what: `line` with `col` or `name`, or a `name`".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// `line:col`, refused when the line does not exist or the column lies past
|
||||
/// its end (one past the last byte is the end itself, and allowed).
|
||||
fn at_column(analysis: &Analysis, line: u32, col: u32) -> Result<u32, String> {
|
||||
let lines = analysis.lines.line_count();
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
return Err(format!("line {line} is past the end ({lines} lines)"));
|
||||
};
|
||||
let length = analysis.line_text(line).len() as u32;
|
||||
if col > length.saturating_add(1) {
|
||||
return Err(format!("line {line} is {length} bytes long; `col` {col} is past its end"));
|
||||
}
|
||||
Ok(range.start + col - 1)
|
||||
}
|
||||
|
||||
/// The first token on `line` that spells `name`: an identifier, or a macro
|
||||
/// use when `name` is written `` `NAME``. A name found only inside a macro
|
||||
/// call's argument text is refused — lucisv does not resolve those.
|
||||
fn on_line(analysis: &Analysis, line: u32, name: &str) -> Result<u32, String> {
|
||||
let Some(range) = analysis.lines.line_range(line) else {
|
||||
return Err(format!("line {line} is past the end ({} lines)", analysis.lines.line_count()));
|
||||
};
|
||||
let touching =
|
||||
|| analysis.tokens.iter().filter(|t| t.span.end > range.start && t.span.start <= range.end);
|
||||
let wanted_macro = name.strip_prefix('`');
|
||||
let hit = touching().find(|token| match wanted_macro {
|
||||
Some(spelled) => token.is_macro() && macro_name(token) == Some(spelled),
|
||||
None => {
|
||||
token.kind == TokenKind::Ident && !token.is_macro() && token.text.trim_end() == name
|
||||
}
|
||||
});
|
||||
if let Some(token) = hit {
|
||||
return Ok(token.span.start.max(range.start));
|
||||
}
|
||||
let in_argument =
|
||||
touching().any(|t| t.is_macro() && super::source::word_in(&t.text, name).is_some());
|
||||
if wanted_macro.is_none() && in_argument {
|
||||
return Err(format!(
|
||||
"`{name}` on line {line} is inside a macro argument, which lucisv does not resolve; give `col` on a plain use"
|
||||
));
|
||||
}
|
||||
Err(format!("`{name}` is not written on line {line}"))
|
||||
}
|
||||
|
||||
/// Where `name` occurs in a file: its one declaration, else its uses when
|
||||
/// they all name one declaration, else its first macro use.
|
||||
fn first_occurrence(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
name: &str,
|
||||
) -> Result<u32, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let declared: Vec<&Symbol> =
|
||||
semantics.symbols_named(name).filter_map(|id| semantics.symbol(id)).collect();
|
||||
match declared.as_slice() {
|
||||
[one] => return Ok(one.name_span.start),
|
||||
[] => {}
|
||||
many => {
|
||||
let lines: Vec<String> = many
|
||||
.iter()
|
||||
.map(|symbol| analysis.lines.line_col(symbol.name_span.start).0.to_string())
|
||||
.collect();
|
||||
return Err(format!(
|
||||
"`{name}` is declared {} times (lines {}); add `line`",
|
||||
many.len(),
|
||||
lines.join(", ")
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(offset) = one_use(project, file, analysis, name)? {
|
||||
return Ok(offset);
|
||||
}
|
||||
let spelled = name.strip_prefix('`').unwrap_or(name);
|
||||
analysis
|
||||
.tokens
|
||||
.iter()
|
||||
.find(|token| token.is_macro() && macro_name(token) == Some(spelled))
|
||||
.map(|token| token.span.start)
|
||||
.ok_or_else(|| format!("`{name}` is not written here"))
|
||||
}
|
||||
|
||||
/// The first use of `name` in a file that declares none — refused, listing
|
||||
/// a line per declaration, when its uses name different declarations.
|
||||
fn one_use(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
name: &str,
|
||||
) -> Result<Option<u32>, String> {
|
||||
let semantics = &analysis.semantics;
|
||||
let mut uses = semantics.references().iter().filter(|reference| reference.name == name);
|
||||
let Some(first) = uses.next() else { return Ok(None) };
|
||||
let external = analysis.external(project.index());
|
||||
let mut targets: Vec<(u32, String)> = Vec::new();
|
||||
for reference in std::iter::once(first).chain(uses) {
|
||||
let offset = reference.name_span.start;
|
||||
let Some(target) = declared_at(project, file, analysis, &external, offset) else {
|
||||
continue;
|
||||
};
|
||||
if !targets.iter().any(|(_, known)| *known == target) {
|
||||
targets.push((analysis.lines.line_col(offset).0, target));
|
||||
}
|
||||
}
|
||||
if targets.len() > 1 {
|
||||
let listed: Vec<String> =
|
||||
targets.iter().map(|(line, target)| format!("line {line} → {target}")).collect();
|
||||
return Err(format!("`{name}` on {}; add `line`", listed.join(", ")));
|
||||
}
|
||||
Ok(Some(first.name_span.start))
|
||||
}
|
||||
|
||||
/// Where the use at `offset` is declared, as `file:line` (several joined
|
||||
/// with ` or `), or `None` when nothing resolves it.
|
||||
fn declared_at(
|
||||
project: &Project,
|
||||
file: &str,
|
||||
analysis: &Analysis,
|
||||
external: &ExternalResolutions,
|
||||
offset: u32,
|
||||
) -> Option<String> {
|
||||
match external.definition_of(&analysis.semantics, offset)? {
|
||||
Definition::Local(symbol) => {
|
||||
Some(format!("{file}:{}", analysis.lines.line_col(symbol.name_span.start).0))
|
||||
}
|
||||
Definition::External(defs) => {
|
||||
let index = project.index();
|
||||
let sites: Vec<String> = defs
|
||||
.iter()
|
||||
.filter_map(|def| {
|
||||
let path = index.path(def.file)?;
|
||||
Some(format!("{}:{}", project.relative(path), def.lines.name))
|
||||
})
|
||||
.collect();
|
||||
(!sites.is_empty()).then(|| sites.join(" or "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The macro a use token names: `` `NAME(args) `` → `NAME`.
|
||||
pub(super) fn macro_name(token: &Token) -> Option<&str> {
|
||||
let rest = token.text.strip_prefix('`')?;
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '$');
|
||||
let name = &rest[..end.unwrap_or(rest.len())];
|
||||
(!name.is_empty()).then_some(name)
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
//! Declaration sites read back off the disk: the navigation tools answer
|
||||
//! with `file:line:col`, the kind, and the declaration's own source line,
|
||||
//! for declarations in files no analysis is held for. One read per file per
|
||||
//! call ([`Texts`]); the index's spans are checked against the bytes before
|
||||
//! they are printed, so a stale span is omitted, never mislocated.
|
||||
//! Declaration sites read back off the disk: `find` and the by-name tools
|
||||
//! answer with `file:line` for declarations in files no analysis is held
|
||||
//! for. One read per file per call ([`Texts`]); the index's spans are
|
||||
//! checked against the bytes before they are printed, so a stale span is
|
||||
//! omitted, never mislocated. Also the whole set a cross-file engine is
|
||||
//! handed, and the small text helpers the answers share.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::LineIndex;
|
||||
|
||||
@@ -31,53 +31,12 @@ impl Texts {
|
||||
});
|
||||
held.as_ref().map(|(text, lines)| (text.as_str(), lines))
|
||||
}
|
||||
|
||||
/// Keep a text the caller already read, so it is not read again.
|
||||
pub fn hold(&mut self, path: PathBuf, text: String) {
|
||||
let lines = LineIndex::new(&text);
|
||||
self.held.insert(path, Some((text, lines)));
|
||||
}
|
||||
}
|
||||
|
||||
/// One place a declaration (or a use) is written.
|
||||
pub struct Site {
|
||||
pub file: String,
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
pub kind: &'static str,
|
||||
/// The source line, whitespace collapsed.
|
||||
pub text: String,
|
||||
}
|
||||
|
||||
impl Site {
|
||||
/// The site of `span` in `text`: its 1-based line and byte column, and
|
||||
/// that line collapsed to one line of text.
|
||||
pub fn at(
|
||||
file: String,
|
||||
text: &str,
|
||||
lines: &LineIndex,
|
||||
span: TextRange,
|
||||
kind: &'static str,
|
||||
) -> Site {
|
||||
let (line, col) = lines.line_col(span.start);
|
||||
let source = lines
|
||||
.line_range(line)
|
||||
.and_then(|range| text.get(range.start as usize..range.end as usize))
|
||||
.unwrap_or("");
|
||||
Site { file, line, col, kind, text: render::one_line(source) }
|
||||
}
|
||||
|
||||
/// `file:line:col kind: text`.
|
||||
pub fn render(&self) -> String {
|
||||
format!("{}:{}:{} {}: {}", self.file, self.line, self.col, self.kind, self.text)
|
||||
}
|
||||
|
||||
pub fn json(&self) -> Value {
|
||||
json!({
|
||||
"file": self.file, "line": self.line, "col": self.col,
|
||||
"kind": self.kind, "text": self.text,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The site of an indexed span in `path`, when the file's bytes there still
|
||||
@@ -90,24 +49,12 @@ pub fn checked_site(
|
||||
name_span: TextRange,
|
||||
shown: TextRange,
|
||||
name: &str,
|
||||
kind: &'static str,
|
||||
) -> Option<Site> {
|
||||
let (text, lines) = texts.get(path)?;
|
||||
if text.get(name_span.as_range()) != Some(name) {
|
||||
return None;
|
||||
}
|
||||
Some(Site::at(project.relative(path), text, lines, shown, kind))
|
||||
}
|
||||
|
||||
/// Sites as a text answer (one per line, or `none_text`) and as JSON under
|
||||
/// `key`, with the total.
|
||||
pub fn answer(sites: &[Site], key: &str, none_text: &str) -> super::Answer {
|
||||
let mut text: String = sites.iter().map(|site| site.render() + "\n").collect();
|
||||
if sites.is_empty() {
|
||||
text = format!("{none_text}\n");
|
||||
}
|
||||
let listed: Vec<Value> = sites.iter().map(Site::json).collect();
|
||||
super::Answer { text, structured: json!({ key: listed, "total": sites.len() }) }
|
||||
Some(Site { file: project.relative(path), line: lines.line_col(shown.start).0 })
|
||||
}
|
||||
|
||||
/// `text` on one line, cut at `cap` characters with `…`.
|
||||
@@ -120,34 +67,6 @@ pub fn capped(text: &str, cap: usize) -> String {
|
||||
format!("{cut}…")
|
||||
}
|
||||
|
||||
/// `text` with its `//` and `/* */` comments replaced by a space; string
|
||||
/// literals are kept whole.
|
||||
pub fn without_comments(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut rest = text;
|
||||
while let Some(at) = rest.find(['/', '"']) {
|
||||
out.push_str(&rest[..at]);
|
||||
let tail = &rest[at..];
|
||||
let skip = if let Some(line) = tail.strip_prefix("//") {
|
||||
out.push(' ');
|
||||
2 + line.find('\n').unwrap_or(line.len())
|
||||
} else if let Some(block) = tail.strip_prefix("/*") {
|
||||
out.push(' ');
|
||||
2 + block.find("*/").map_or(block.len(), |end| end + 2)
|
||||
} else if let Some(string) = tail.strip_prefix('"') {
|
||||
let end = 1 + string.find('"').map_or(string.len(), |end| end + 1);
|
||||
out.push_str(&tail[..end]);
|
||||
end
|
||||
} else {
|
||||
out.push('/');
|
||||
1
|
||||
};
|
||||
rest = &tail[skip..];
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// The whole in-scope set a cross-file engine is handed: every indexed file,
|
||||
/// and one more when asked, read from disk now — plus every file the set
|
||||
/// could not include (over the size cap, not UTF-8, no longer readable),
|
||||
@@ -186,6 +105,23 @@ impl WholeSet {
|
||||
})
|
||||
}
|
||||
|
||||
/// An engine sentence with each bare file name written root-relative
|
||||
/// (`p1.sv:2` → `rtl/p1.sv:2`), where the name is the base name of
|
||||
/// exactly one file of the set — the engines name files by base name,
|
||||
/// and only an unambiguous one can be placed.
|
||||
pub fn rooted(&self, project: &Project, sentence: &str) -> String {
|
||||
let mut out = sentence.to_string();
|
||||
for (path, _) in &self.files {
|
||||
let Some(base) = path.file_name().and_then(|name| name.to_str()) else { continue };
|
||||
let same = self.files.iter().filter(|(other, _)| other.file_name() == path.file_name());
|
||||
let shown = project.relative(path);
|
||||
if same.count() == 1 && shown != base {
|
||||
out = replace_file_name(&out, base, &shown);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// One line naming the skipped files (ten at most), or `None` when the
|
||||
/// set is complete.
|
||||
pub fn warning(&self, project: &Project) -> Option<String> {
|
||||
@@ -204,6 +140,26 @@ impl WholeSet {
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` with every occurrence of the file name `base` that stands alone —
|
||||
/// not the tail of a longer path or name — replaced by `path`.
|
||||
fn replace_file_name(text: &str, base: &str, path: &str) -> String {
|
||||
let glued_before = |c: char| is_ident_char(c) || matches!(c, '/' | '\\' | '.' | '-');
|
||||
let glued_after = |c: char| is_ident_char(c) || matches!(c, '/' | '-');
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut from = 0;
|
||||
while let Some(found) = text[from..].find(base) {
|
||||
let (start, end) = (from + found, from + found + base.len());
|
||||
let before = text[..start].chars().next_back();
|
||||
let after = text[end..].chars().next();
|
||||
let alone = !before.is_some_and(glued_before) && !after.is_some_and(glued_after);
|
||||
out.push_str(&text[from..start]);
|
||||
out.push_str(if alone { path } else { base });
|
||||
from = end;
|
||||
}
|
||||
out.push_str(&text[from..]);
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `name` occurs in `bytes` not glued to an identifier character on
|
||||
/// either side — how an identifier, escaped or not, is written.
|
||||
fn word_in_bytes(bytes: &[u8], name: &[u8]) -> bool {
|
||||
@@ -258,6 +214,16 @@ mod tests {
|
||||
assert_eq!(word_in("anything", ""), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_file_name_is_replaced_only_where_it_stands_alone() {
|
||||
let said = "at `u_s` (p1.sv:2), in p1.sv, not rtl/p1.sv, xp1.sv or p1.svh";
|
||||
assert_eq!(
|
||||
replace_file_name(said, "p1.sv", "rtl/p1.sv"),
|
||||
"at `u_s` (rtl/p1.sv:2), in rtl/p1.sv, not rtl/p1.sv, xp1.sv or p1.svh"
|
||||
);
|
||||
assert_eq!(replace_file_name("p1.sv:6", "p1.sv", "a/p1.sv"), "a/p1.sv:6");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skipped_file_is_searched_for_whole_words_only() {
|
||||
assert!(word_in_bytes(b"leaf u (.d(x));", b"d"));
|
||||
@@ -268,22 +234,8 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_dropped_and_strings_kept() {
|
||||
let text = "#( // why\n .W(8), /* old: 4 */ .S(\"a//b\"), .D(4 / 2) )";
|
||||
assert_eq!(
|
||||
render::one_line(&without_comments(text)),
|
||||
"#( .W(8), .S(\"a//b\"), .D(4 / 2) )"
|
||||
);
|
||||
assert_eq!(without_comments("a /* open"), "a ");
|
||||
fn a_capped_text_is_one_line_cut_with_an_ellipsis() {
|
||||
assert_eq!(capped("x y", 2), "x …");
|
||||
assert_eq!(capped("x y", 3), "x y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_site_prints_its_line_collapsed() {
|
||||
let text = "module m;\n logic [3:0] x;\nendmodule\n";
|
||||
let lines = LineIndex::new(text);
|
||||
let site = Site::at("m.sv".into(), text, &lines, TextRange::new(27, 28), "var");
|
||||
assert_eq!(site.render(), "m.sv:2:18 var: logic [3:0] x;");
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,13 @@
|
||||
//! **refused with the tree byte-identical** (every file hashed before and
|
||||
//! after). A few controls sit beside them: the nearest edit that must pass,
|
||||
//! so a refusal is known to come from the rule and not from a broken setup.
|
||||
//!
|
||||
//! The cases were written against `replace_item`, `insert_item` and
|
||||
//! `delete_item`; the lean catalogue folds the three into `edit_item`
|
||||
//! (PLAN §10.1), so [`lean`] maps each call and the cases stay as written.
|
||||
//! What the lean surface removed (`dry_run`, `rename`, `force`) is gone from
|
||||
//! the cases too: a refusal is checked once, and a forced deletion is now a
|
||||
//! refusal like any other.
|
||||
|
||||
use std::collections::hash_map::DefaultHasher;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -133,6 +140,7 @@ impl Session {
|
||||
|
||||
/// A tool call: whether it was refused, and its text.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String) {
|
||||
let (tool, arguments) = lean(tool, arguments);
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let result = &reply["result"];
|
||||
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
|
||||
@@ -147,19 +155,40 @@ impl Drop for Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// An M4 call as `edit_item` takes it: `replace_item`'s `item`,
|
||||
/// `insert_item`'s `anchor` and `position`, `delete_item`'s `item`, each
|
||||
/// under its `op`.
|
||||
fn lean(tool: &str, mut args: Value) -> (&'static str, Value) {
|
||||
let op = match tool {
|
||||
"replace_item" => "replace",
|
||||
"delete_item" => "delete",
|
||||
"insert_item" => {
|
||||
let before = args["position"] == "before";
|
||||
let object = args.as_object_mut().unwrap();
|
||||
object.remove("position");
|
||||
let anchor = object.remove("anchor").unwrap();
|
||||
object.insert("item".into(), anchor);
|
||||
if before {
|
||||
"insert_before"
|
||||
} else {
|
||||
"insert_after"
|
||||
}
|
||||
}
|
||||
other => panic!("not a structural edit: {other}"),
|
||||
};
|
||||
args["op"] = Value::from(op);
|
||||
("edit_item", args)
|
||||
}
|
||||
|
||||
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
|
||||
/// every file of the tree byte-identical — also under `dry_run`.
|
||||
/// every file of the tree byte-identical.
|
||||
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) {
|
||||
let before = tree.hashes();
|
||||
for dry_run in [true, false] {
|
||||
let mut arguments = args.clone();
|
||||
arguments["dry_run"] = Value::from(dry_run);
|
||||
let (error, text) = server.call(tool, arguments);
|
||||
assert!(error, "{tool} {args}: not refused: {text}");
|
||||
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
|
||||
assert!(text.ends_with("nothing written.") || text.contains("nothing written"), "{text}");
|
||||
assert_eq!(before, tree.hashes(), "{tool} {args}: a refusal wrote");
|
||||
}
|
||||
let (error, text) = server.call(tool, args.clone());
|
||||
assert!(error, "{tool} {args}: not refused: {text}");
|
||||
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
|
||||
assert!(text.ends_with("nothing written.") || text.contains("nothing written"), "{text}");
|
||||
assert_eq!(before, tree.hashes(), "{tool} {args}: a refusal wrote");
|
||||
}
|
||||
|
||||
/// Run `tool` and assert it wrote (the control beside an attack).
|
||||
@@ -196,11 +225,11 @@ fn a_text_that_closes_the_enclosing_module_is_refused() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_that_redeclares_a_port_is_refused_even_with_rename() {
|
||||
fn a_text_that_redeclares_a_port_is_refused() {
|
||||
let tree = Tree::with(&[]);
|
||||
let mut server = Session::over(&tree);
|
||||
// The duplicate rule fires before the name rule, so `rename` changes
|
||||
// nothing: a port is never redeclared.
|
||||
// The duplicate rule fires before the name rule: a port is never
|
||||
// redeclared.
|
||||
refused(
|
||||
&tree,
|
||||
&mut server,
|
||||
@@ -208,9 +237,6 @@ fn a_text_that_redeclares_a_port_is_refused_even_with_rename() {
|
||||
core("p", "logic d;"),
|
||||
"`d` would be declared twice",
|
||||
);
|
||||
let mut renamed = core("p", "logic d;");
|
||||
renamed["rename"] = Value::from(true);
|
||||
refused(&tree, &mut server, "replace_item", renamed, "`d` would be declared twice");
|
||||
let insert = json!({"file": "rtl/core.sv", "anchor": "p", "text": "logic [3:0] clk;"});
|
||||
refused(&tree, &mut server, "insert_item", insert, "`clk` would be declared twice");
|
||||
}
|
||||
@@ -224,7 +250,7 @@ fn two_items_where_one_was_and_an_empty_text_are_refused() {
|
||||
let empty_item = "logic p;;";
|
||||
refused(&tree, &mut server, "replace_item", core("p", empty_item), "holds 2 items");
|
||||
for empty in ["", " \n\t\r\n"] {
|
||||
refused(&tree, &mut server, "replace_item", core("p", empty), "`delete_item` removes");
|
||||
refused(&tree, &mut server, "replace_item", core("p", empty), "`op: delete` removes");
|
||||
let args = json!({"file": "rtl/core.sv", "anchor": "end", "text": empty});
|
||||
refused(&tree, &mut server, "insert_item", args, "`text` is empty");
|
||||
}
|
||||
@@ -286,7 +312,7 @@ fn nothing_inside_a_format_fence_is_edited() {
|
||||
&tree,
|
||||
&mut server,
|
||||
"delete_item",
|
||||
json!({"file": "rtl/core.sv", "item": "always@22", "force": true}),
|
||||
json!({"file": "rtl/core.sv", "item": "always@22"}),
|
||||
fence,
|
||||
);
|
||||
}
|
||||
@@ -627,9 +653,6 @@ fn a_name_spelled_inside_a_macro_is_a_possible_use() {
|
||||
args,
|
||||
"possible use (macro) at rtl/defs.svh:1 `in_other_body`",
|
||||
);
|
||||
let forced = json!({"file": "rtl/mc.sv", "item": "in_arg", "force": true});
|
||||
let answer = accepted(&mut server, "delete_item", forced);
|
||||
assert!(answer.contains("deleted with references left: possible use (macro)"), "{answer}");
|
||||
// The control: a name spelled only in a comment and a string goes.
|
||||
accepted(&mut server, "delete_item", json!({"file": "rtl/mc.sv", "item": "free"}));
|
||||
}
|
||||
@@ -758,7 +781,6 @@ fn a_signal_bound_by_a_dot_star_is_still_referenced() {
|
||||
// The controls: a signal the module has no port for; a module's own `.*`
|
||||
// does not reach another module's names.
|
||||
accepted(&mut server, "delete_item", json!({"file": "rtl/sw.sv", "item": "unrelated"}));
|
||||
let forced = json!({"file": "rtl/sw.sv", "item": "clk", "force": true});
|
||||
let answer = accepted(&mut server, "delete_item", forced);
|
||||
assert!(answer.contains("bound by `.*` at rtl/sw.sv:7:18 `clk`"), "{answer}");
|
||||
let clk = json!({"file": "rtl/sw.sv", "item": "clk"});
|
||||
refused(&tree, &mut server, "delete_item", clk, "bound by `.*` at rtl/sw.sv:7:18 `clk`");
|
||||
}
|
||||
@@ -158,9 +158,9 @@ impl Session {
|
||||
/// A session that indexes, answers, edits and ends; its stderr.
|
||||
fn whole_session(scratch: &Scratch) -> String {
|
||||
let mut session = Session::start(scratch);
|
||||
assert!(session.text("project_overview", json!({})).contains("files: 7 indexed"));
|
||||
assert!(session.text("unit_interface", json!({"name": "leaf"})).contains("module leaf"));
|
||||
session.text("format", json!({"file": "rtl/top.sv"}));
|
||||
assert!(session.text("hierarchy", json!({})).starts_with("7 files, "));
|
||||
assert!(session.text("outline", json!({"unit": "leaf"})).starts_with("rtl/leaf.sv:1\n"));
|
||||
session.text("format", json!({"files": "rtl/top.sv"}));
|
||||
// One more call, so the index has absorbed whatever the edit wrote.
|
||||
session.text("outline", json!({"file": "rtl/top.sv"}));
|
||||
let stderr = session.end();
|
||||
@@ -236,8 +236,8 @@ fn a_missing_directory_starts_cold_and_its_own_store_serves_the_next_start() {
|
||||
let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf2");
|
||||
fs::write(&leaf, text).unwrap();
|
||||
let mut session = Session::start(&scratch);
|
||||
let units = session.text("list_units", json!({}));
|
||||
assert!(units.contains("leaf2"), "{units}");
|
||||
let units = session.text("find", json!({"name": "leaf2"}));
|
||||
assert!(units.contains("module leaf2"), "{units}");
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! The opentitan census (TODO-MCP M2): the navigation tools over a real
|
||||
//! checkout, read-only, each answer checked against what the language
|
||||
//! server answers for the same question (`docs/features/references-nav`,
|
||||
//! `references-hierarchical-surface`) and each call's wall time printed.
|
||||
//! The opentitan census (TODO-MCP M2, ported to the lean catalogue in M7):
|
||||
//! `find`, `hierarchy`, `check` and `outline` over a real checkout,
|
||||
//! read-only, each answer checked against what the language server answers
|
||||
//! for the same question (`docs/features/references-nav`,
|
||||
//! `references-hierarchical-surface`) or what 0.57.0 answered, and each
|
||||
//! call's wall time printed.
|
||||
//!
|
||||
//! `#[ignore]`: it needs the checkout. Run with
|
||||
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
|
||||
@@ -95,19 +97,24 @@ impl Session {
|
||||
result["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// Every `references` hit as `file:line:col`.
|
||||
fn hits(&mut self, arguments: Value) -> Vec<String> {
|
||||
let result = self.call("references", arguments);
|
||||
let hits = result["structuredContent"]["hits"].as_array().unwrap().clone();
|
||||
hits.iter()
|
||||
.map(|h| format!("{}:{}:{}", h["file"].as_str().unwrap(), h["line"], h["col"]))
|
||||
.collect()
|
||||
/// The uses `find` lists for `name` (a `unit.name` picks one
|
||||
/// declaration), as `file:line`.
|
||||
fn uses(&mut self, name: &str) -> Vec<String> {
|
||||
let text = self.text("find", json!({"name": name, "refs": true}));
|
||||
let mut out = Vec::new();
|
||||
let used = text.lines().skip(1).take_while(|line| line.starts_with(" "));
|
||||
for line in used {
|
||||
let (file, numbers) = line.trim().rsplit_once(':').unwrap();
|
||||
out.extend(numbers.split(',').map(|n| format!("{file}:{n}")));
|
||||
}
|
||||
assert!(!out.is_empty(), "no uses: {text}");
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// The language server's answer for the same position (release
|
||||
/// `lucisv-server` over the same checkout, 2026-09-23): every location it
|
||||
/// lists must be in ours.
|
||||
/// `lucisv-server` over the same checkout, 2026-09-23), as `file:line`:
|
||||
/// every location it lists must be in ours.
|
||||
fn assert_covers(ours: &[String], server: &[&str]) {
|
||||
for location in server {
|
||||
assert!(ours.iter().any(|hit| hit == location), "missing {location}: {ours:?}");
|
||||
@@ -133,52 +140,72 @@ fn opentitan_navigation_matches_the_language_server() {
|
||||
let before = status(&root);
|
||||
let mut s = Session::over(&root);
|
||||
// The first call builds the index; its time is the startup cost.
|
||||
s.text("project_overview", json!({}));
|
||||
s.text("hierarchy", json!({}));
|
||||
|
||||
let masking =
|
||||
json!({"file": "hw/ip/aes/rtl/aes.sv", "name": "entropy_masking_req", "limit": 1000});
|
||||
let masking = s.hits(masking);
|
||||
let aes = "hw/ip/aes/rtl/aes.sv";
|
||||
let bind = "hw/ip/aes/dv/sva/aes_bind.sv";
|
||||
let server = [&format!("{bind}:45:27"), &format!("{bind}:54:26"), &format!("{aes}:89:52")];
|
||||
let masking = s.uses("aes.entropy_masking_req");
|
||||
let server = [&format!("{bind}:45"), &format!("{bind}:54"), &format!("{aes}:137")];
|
||||
assert_covers(&masking, &server.map(String::as_str));
|
||||
assert_eq!(masking.len(), 6, "{masking:?}");
|
||||
|
||||
let sm = "hw/ip/entropy_src/rtl/entropy_src_main_sm.sv";
|
||||
let state = s.hits(json!({"file": sm, "line": 42, "name": "state_q"}));
|
||||
assert_covers(&state, &["hw/ip/entropy_src/rtl/entropy_src_core.sv:3092:30"]);
|
||||
assert_eq!(state.len(), 5, "{state:?}");
|
||||
let state = s.uses("entropy_src_main_sm.state_q");
|
||||
assert_covers(&state, &["hw/ip/entropy_src/rtl/entropy_src_core.sv:3092"]);
|
||||
|
||||
// The references-nav positions: the `aes` instantiation and its `.clk_i`
|
||||
// in the testbench. The server lists 11 and 9; we list those and the
|
||||
// three top-level `*_pd_main.sv` instantiations it omits (README, work log).
|
||||
let tb = "hw/ip/aes/dv/tb/tb.sv";
|
||||
let instantiated = s.hits(json!({"file": tb, "line": 45, "name": "aes"}));
|
||||
// The `aes` instantiations the server lists, and the three top-level
|
||||
// `*_pd_main.sv` ones it omits (README of mcp-navigation, work log).
|
||||
let instantiated = s.uses("aes");
|
||||
let server = [
|
||||
"hw/ip/aes/dv/cov/aes_cov_bind.sv:8:8",
|
||||
"hw/ip/aes/dv/sva/aes_bind.sv:50:8",
|
||||
"hw/ip/aes/dv/tb/tb.sv:45:3",
|
||||
"hw/ip/aes/pre_dv/aes_tb/rtl/aes_tb.sv:215:3",
|
||||
"hw/ip/aes/rtl/aes.sv:9:8",
|
||||
"hw/ip/aes/rtl/aes_wrap.sv:79:3",
|
||||
"hw/ip/aes/dv/cov/aes_cov_bind.sv:8",
|
||||
"hw/ip/aes/dv/sva/aes_bind.sv:50",
|
||||
"hw/ip/aes/dv/tb/tb.sv:45",
|
||||
"hw/ip/aes/pre_dv/aes_tb/rtl/aes_tb.sv:215",
|
||||
"hw/ip/aes/rtl/aes_wrap.sv:79",
|
||||
];
|
||||
assert_covers(&instantiated, &server);
|
||||
let clock = s.hits(json!({"file": tb, "line": 46, "name": "clk_i"}));
|
||||
assert_covers(&clock, &["hw/ip/aes/rtl/aes.sv:42:53", "hw/ip/aes/rtl/aes.sv:197:31"]);
|
||||
|
||||
let top = json!({"root": "top_earlgrey", "depth": 2, "limit": 500, "overrides": true});
|
||||
let top = s.text("hierarchy", top);
|
||||
assert!(top.contains("\n u_aes : aes #("), "{top}");
|
||||
let top = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2}));
|
||||
assert!(top.contains("\n u_aes: aes hw/top_earlgrey/rtl/autogen/"), "{top}");
|
||||
let peek = s.text("hierarchy", json!({"root": "top_earlgrey", "peek": true}));
|
||||
assert!(peek.contains("\n earlgrey_pd_main"), "{peek}");
|
||||
|
||||
let fifo = s.text("definition", json!({"name": "prim_fifo_sync"}));
|
||||
assert!(fifo.starts_with("hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
|
||||
let fifo = s.text("find", json!({"name": "prim_fifo_sync"}));
|
||||
assert!(fifo.starts_with("module prim_fifo_sync hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
|
||||
|
||||
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "direction": "up", "depth": 1}));
|
||||
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "up": true}));
|
||||
assert!(up.contains(".u_"), "{up}");
|
||||
|
||||
s.text("diagnostics", json!({"file": "hw/ip/aes/rtl/aes.sv"}));
|
||||
let clk = json!({"file": "hw/ip/prim/rtl/prim_fifo_sync.sv", "name": "clk_i"});
|
||||
s.text("references", clk);
|
||||
s.text("check", json!({"file": aes}));
|
||||
s.text("outline", json!({"unit": "aes"}));
|
||||
s.text("read", json!({"item": "module:aes_wrap"}));
|
||||
drop(s);
|
||||
assert_eq!(status(&root), before, "the checkout was only read");
|
||||
}
|
||||
|
||||
/// `top_earlgrey`'s instances two levels down as 0.57.0's `hierarchy`
|
||||
/// answered them (`depth: 2`, every line), `level instance:module`.
|
||||
const TOP_EARLGREY_DEPTH_2: &str = "1earlgrey_pd_main:earlgrey_pd_main 2u_dft_tap_breakout:pinmux_jtag_breakout 2u_uart0:uart 2u_uart1:uart 2u_uart2:uart 2u_uart3:uart 2u_gpio:gpio 2u_spi_device:spi_device 2u_i2c0:i2c 2u_i2c1:i2c 2u_i2c2:i2c 2u_rv_timer:rv_timer 2u_otp_ctrl:otp_ctrl 2u_lc_ctrl:lc_ctrl 2u_alert_handler:alert_handler 2u_spi_host0:spi_host 2u_spi_host1:spi_host 2u_usbdev:usbdev 2u_pinmux:pinmux 2u_rram_ctrl:rram_ctrl 2u_rram_macro:rram_macro 2u_rv_dm:rv_dm 2u_rv_plic:rv_plic 2u_aes:aes 2u_hmac:hmac 2u_kmac:kmac 2u_otbn:otbn 2u_keymgr_dpe:keymgr_dpe 2u_csrng:csrng 2u_entropy_src:entropy_src 2u_edn0:edn 2u_edn1:edn 2u_sram_ctrl_main:sram_ctrl 2u_sram_ctrl_sec:sram_ctrl 2u_rom_ctrl:rom_ctrl 2u_rv_core_ibex:rv_core_ibex 2u_cheriot:cheriot 2u_sram_ctrl_meta:sram_ctrl 2u_xbar_main:xbar_main 2u_xbar_peri:xbar_peri 1earlgrey_pd_aon:earlgrey_pd_aon 2u_pwrmgr:pwrmgr 2u_rstmgr:rstmgr 2u_clkmgr:clkmgr 2u_sysrst_ctrl:sysrst_ctrl 2u_adc_ctrl:adc_ctrl 2u_aon_timer:aon_timer 2u_sensor_ctrl:sensor_ctrl 2u_sram_ctrl_ret:sram_ctrl";
|
||||
|
||||
/// PLAN §10.5: the lean `hierarchy` names the instance set 0.57.0 named,
|
||||
/// in the same order, each at its instantiation site.
|
||||
#[test]
|
||||
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
|
||||
fn opentitan_top_earlgrey_is_the_0_57_instance_set() {
|
||||
let root = checkout();
|
||||
let before = status(&root);
|
||||
let mut s = Session::over(&root);
|
||||
let tree = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2}));
|
||||
let ours: Vec<String> = tree
|
||||
.lines()
|
||||
.skip(1)
|
||||
.map(|line| {
|
||||
let level = (line.len() - line.trim_start().len()) / 2;
|
||||
let (instance, rest) = line.trim().split_once(": ").unwrap();
|
||||
let module = rest.split(' ').next().unwrap();
|
||||
format!("{level}{instance}:{module}")
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(ours.join(" "), TOP_EARLGREY_DEPTH_2, "{tree}");
|
||||
assert!(tree.lines().skip(1).all(|line| line.contains(".sv:")), "each at its site: {tree}");
|
||||
drop(s);
|
||||
assert_eq!(status(&root), before, "the checkout was only read");
|
||||
}
|
||||
@@ -194,7 +221,7 @@ fn median_ms(mut times: Vec<Duration>) -> f64 {
|
||||
fn startup(root: &Path, cache: &Path, label: &str) -> Session {
|
||||
let mut s = Session::spawn(root, Some(cache));
|
||||
let started = Instant::now();
|
||||
s.text("project_overview", json!({}));
|
||||
s.text("hierarchy", json!({}));
|
||||
println!("startup: {label}: first call {} ms", started.elapsed().as_millis());
|
||||
s
|
||||
}
|
||||
@@ -207,7 +234,9 @@ fn finish(s: Session, label: &str) {
|
||||
}
|
||||
|
||||
/// TODO-MCP M6: startup cold, warm from the editor's store and warm from
|
||||
/// this server's own; the per-call stat sweep; the whole-set `rename`. The
|
||||
/// this server's own; the per-call stat sweep; a whole-set `find` with
|
||||
/// `refs` (the read-only stand-in for the whole-set `rename`: the checkout
|
||||
/// is never written). The
|
||||
/// stores live in a scratch directory outside the checkout; the editor's is
|
||||
/// the own store renamed — the same codec, byte for byte (`src/cache.rs`,
|
||||
/// pinned against the language server's source by its unit test).
|
||||
@@ -240,12 +269,12 @@ fn opentitan_startup_cold_and_warm_and_the_stat_sweep() {
|
||||
median_ms(swept),
|
||||
median_ms(floor)
|
||||
);
|
||||
let rename = json!({"file": "hw/ip/aes/rtl/aes_cipher_core.sv", "line": 123, "name": "op_i", "new_name": "cipher_op_i", "dry_run": true});
|
||||
let uses = json!({"name": "aes_cipher_core", "refs": true});
|
||||
for pass in ["first", "second"] {
|
||||
let started = Instant::now();
|
||||
let text = s.text("rename", rename.clone());
|
||||
assert!(text.contains("(dry run: nothing written)"), "{text}");
|
||||
println!("rename: op_i dry run, {pass} call {} ms", started.elapsed().as_millis());
|
||||
let text = s.text("find", uses.clone());
|
||||
assert!(text.starts_with("module aes_cipher_core "), "{text}");
|
||||
println!("find: aes_cipher_core refs, {pass} call {} ms", started.elapsed().as_millis());
|
||||
}
|
||||
finish(s, "warm, own store");
|
||||
|
||||
|
||||
+102
-195
@@ -1,10 +1,12 @@
|
||||
//! QA attacks on lane feedback-1 (unresolved mentions, `add_port`'s `after`
|
||||
//! and its move-checker, the trimmed catalogue, the temp-store sweep),
|
||||
//! 2026-09-23.
|
||||
//! 2026-09-23 — ported to the lean catalogue: `add_port` is `port` with
|
||||
//! `add` (the calls are mapped by [`Session::call`]); the mentions are the
|
||||
//! `unresolved:` block of `find`, `rename` and `port`.
|
||||
//!
|
||||
//! Every test spawns the real binary over a scratch tree, as a host would.
|
||||
//! Placements are asserted byte for byte; refusals with every file of the
|
||||
//! tree byte-identical, under `dry_run` and for real.
|
||||
//! tree byte-identical.
|
||||
//!
|
||||
//! A test that pins a QA finding asserts the *correct* behaviour and is
|
||||
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
|
||||
@@ -129,12 +131,23 @@ impl Session {
|
||||
reply
|
||||
}
|
||||
|
||||
/// A tool call: whether it was refused, its text, its structured content.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
|
||||
/// A tool call: whether it was refused, its text, and the `file:line`
|
||||
/// of every unresolved mention it lists. `add_port` is `port` with `add`.
|
||||
fn call(&mut self, tool: &str, mut arguments: Value) -> (bool, String, Value) {
|
||||
let tool = match tool {
|
||||
"add_port" => {
|
||||
let object = arguments.as_object_mut().unwrap();
|
||||
let declaration = object.remove("declaration").unwrap();
|
||||
object.insert("add".into(), declaration);
|
||||
"port"
|
||||
}
|
||||
other => other,
|
||||
};
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let result = &reply["result"];
|
||||
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
|
||||
(result["isError"] == true, text, result["structuredContent"].clone())
|
||||
let mentions = unresolved(&text);
|
||||
(result["isError"] == true, text, mentions)
|
||||
}
|
||||
|
||||
/// Close stdin and wait for the server to exit on its own.
|
||||
@@ -158,24 +171,29 @@ fn served(files: &[(&str, &str)]) -> (Tree, Session) {
|
||||
(tree, server)
|
||||
}
|
||||
|
||||
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
|
||||
/// every file of the tree byte-identical — under `dry_run` and for real.
|
||||
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) -> String {
|
||||
let before = tree.snapshot();
|
||||
let mut said = String::new();
|
||||
for dry_run in [true, false] {
|
||||
let mut arguments = args.clone();
|
||||
arguments["dry_run"] = Value::from(dry_run);
|
||||
let (error, text, _) = server.call(tool, arguments);
|
||||
assert!(error, "{tool} {args}: not refused: {text}");
|
||||
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
|
||||
assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote");
|
||||
said = text;
|
||||
/// The `unresolved:` block of an answer, one `file:line` per mention.
|
||||
fn unresolved(text: &str) -> Value {
|
||||
let Some((_, block)) = text.split_once("unresolved:\n") else { return json!([]) };
|
||||
let mut sites = Vec::new();
|
||||
for line in block.lines().map(str::trim).filter(|line| !line.starts_with('…')) {
|
||||
let (file, lines) = line.rsplit_once(':').unwrap();
|
||||
sites.extend(lines.split(',').map(|n| Value::from(format!("{file}:{n}"))));
|
||||
}
|
||||
said
|
||||
Value::from(sites)
|
||||
}
|
||||
|
||||
/// Run `tool` for real and assert it wrote; its text and structured answer.
|
||||
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
|
||||
/// every file of the tree byte-identical.
|
||||
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) -> String {
|
||||
let before = tree.snapshot();
|
||||
let (error, text, _) = server.call(tool, args.clone());
|
||||
assert!(error, "{tool} {args}: not refused: {text}");
|
||||
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
|
||||
assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote");
|
||||
text
|
||||
}
|
||||
|
||||
/// Run `tool` for real and assert it wrote; its text and its mentions.
|
||||
fn written(server: &mut Session, tool: &str, args: Value) -> (String, Value) {
|
||||
let (error, text, structured) = server.call(tool, args.clone());
|
||||
assert!(!error, "{tool} {args}: refused: {text}");
|
||||
@@ -234,8 +252,7 @@ fn qa_after_the_last_port_puts_the_comma_before_its_trailing_comment() {
|
||||
fn qa_after_keeps_crlf_and_tabs_and_places_an_instance_in_the_modules_own_file() {
|
||||
let m = "module m (\r\n\tinput logic a,\t// tabbed\r\n\toutput logic y\r\n);\r\nendmodule\r\nmodule top2 (input logic a, en, output logic y);\r\n m u_s (\r\n .a (a),\r\n .y (y)\r\n );\r\nendmodule\r\n";
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
|
||||
let args =
|
||||
json!({"file": "rtl/m.sv", "line": 2, "declaration": "input logic en", "after": "a"});
|
||||
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
|
||||
written(&mut server, "add_port", args);
|
||||
let want = m
|
||||
.replace("// tabbed\r\n", "// tabbed\r\n\tinput logic en,\r\n")
|
||||
@@ -264,9 +281,11 @@ fn qa_after_a_parameter_an_unknown_name_or_an_ifdef_arm_is_refused() {
|
||||
let args = json!({"module": "m", "declaration": decl, "after": "b"});
|
||||
refused(&tree, &mut server, "add_port", args, "inside an `ifdef arm");
|
||||
// Just before the arm, and just after it: placed outside it.
|
||||
let args = json!({"module": "m", "declaration": decl, "after": "a", "dry_run": true});
|
||||
let text = written(&mut server, "add_port", args).0;
|
||||
assert!(text.contains(" input logic a,\n+ input logic en,\n `ifdef X\n"), "{text}");
|
||||
let args = json!({"module": "m", "declaration": decl, "after": "a"});
|
||||
written(&mut server, "add_port", args);
|
||||
let before_arm = m.replace(" input logic a,\n", " input logic a,\n input logic en,\n");
|
||||
assert_eq!(tree.read("rtl/m.sv"), before_arm);
|
||||
fs::write(tree.0.join("rtl/m.sv"), m).unwrap();
|
||||
let args = json!({"module": "m", "declaration": decl, "after": "y"});
|
||||
written(&mut server, "add_port", args);
|
||||
let want = m.replace(" output logic y\n", " output logic y,\n input logic en\n");
|
||||
@@ -279,7 +298,7 @@ fn qa_a_connection_anchor_in_an_ifdef_arm_keeps_the_engines_append_and_says_so()
|
||||
let top = "module top (input logic a, en, output logic y);\n m u_i (\n`ifdef X\n .a (a),\n`endif\n .y (y)\n );\nendmodule\n";
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
|
||||
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
|
||||
let (text, structured) = written(&mut server, "add_port", args);
|
||||
let (text, _) = written(&mut server, "add_port", args);
|
||||
assert!(text.contains("`u_i` in "), "{text}");
|
||||
assert!(
|
||||
text.contains(
|
||||
@@ -287,63 +306,11 @@ fn qa_a_connection_anchor_in_an_ifdef_arm_keeps_the_engines_append_and_says_so()
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
assert_eq!(structured["warnings"].as_array().unwrap().len(), 1, "{structured}");
|
||||
assert_eq!(text.matches("\nwarning: ").count(), 1, "{text}");
|
||||
assert_eq!(tree.read("rtl/top.sv"), top.replace(" .y (y)\n", " .y (y),\n .en(en)\n"));
|
||||
assert!(tree.read("rtl/m.sv").contains(" input logic a,\n input logic en,\n"));
|
||||
}
|
||||
|
||||
/// Apply a unified diff (as `apply::run` renders it) to `before`.
|
||||
fn patch(before: &str, diff: &str) -> String {
|
||||
let old: Vec<&str> = before.split_inclusive('\n').collect();
|
||||
let mut out = String::new();
|
||||
let mut at = 0usize;
|
||||
for line in diff.split_inclusive('\n') {
|
||||
if line.starts_with("---") || line.starts_with("+++") || line.starts_with('\\') {
|
||||
continue;
|
||||
}
|
||||
if let Some(header) = line.strip_prefix("@@ -") {
|
||||
let start: usize = header.split([',', ' ']).next().unwrap().parse().unwrap();
|
||||
while at + 1 < start {
|
||||
out.push_str(old[at]);
|
||||
at += 1;
|
||||
}
|
||||
} else if let Some(added) = line.strip_prefix('+') {
|
||||
out.push_str(added);
|
||||
} else if line.starts_with('-') {
|
||||
at += 1;
|
||||
} else {
|
||||
out.push_str(old[at]);
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
old[at..].iter().for_each(|rest| out.push_str(rest));
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_dry_run_diff_is_exactly_what_the_real_run_writes() {
|
||||
for after in ["a", "b", "y"] {
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", M_HEADER), ("rtl/top.sv", M_TOP)]);
|
||||
let args = json!({"module": "m", "declaration": "input logic [3:0] en", "after": after});
|
||||
let mut dry = args.clone();
|
||||
dry["dry_run"] = Value::from(true);
|
||||
let (_, preview) = written(&mut server, "add_port", dry);
|
||||
let diffs: BTreeMap<String, String> = preview["changed"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| (c["file"].as_str().unwrap().into(), c["diff"].as_str().unwrap().into()))
|
||||
.collect();
|
||||
let before = tree.snapshot();
|
||||
written(&mut server, "add_port", args);
|
||||
for (file, diff) in &diffs {
|
||||
let old = String::from_utf8(before[file].clone()).unwrap();
|
||||
assert_eq!(patch(&old, diff), tree.read(file), "after {after}: {file}\n{diff}");
|
||||
}
|
||||
assert_eq!(diffs.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Findings on `after` (QA log, findings 1–4).
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -360,16 +327,16 @@ fn qa_a_comment_between_the_anchor_and_its_comma_stays_with_the_anchor() {
|
||||
let m = "module m (\n input logic a /* about a */,\n input logic b // about b\n , input logic c,\n output logic y\n);\nendmodule\n";
|
||||
let top = "module top (input logic a, b, c, en, output logic y);\n m u_m (\n .a (a) /* conn a */,\n .b (b),\n .c (c),\n .y (y)\n );\nendmodule\n";
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
|
||||
let args =
|
||||
json!({"module": "m", "declaration": "input logic en", "after": "a", "dry_run": true});
|
||||
let (text, _) = written(&mut server, "add_port", args);
|
||||
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
|
||||
written(&mut server, "add_port", args);
|
||||
let text = tree.read("rtl/m.sv") + &tree.read("rtl/top.sv");
|
||||
assert!(!text.contains("en /* about a */"), "the anchor's comment moved to `en`:\n{text}");
|
||||
assert!(!text.contains(".en(en) /* conn a */"), "the connection's comment moved:\n{text}");
|
||||
let args =
|
||||
json!({"module": "m", "declaration": "input logic en", "after": "b", "dry_run": true});
|
||||
let (text, _) = written(&mut server, "add_port", args);
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
|
||||
let args = json!({"module": "m", "declaration": "input logic en", "after": "b"});
|
||||
written(&mut server, "add_port", args);
|
||||
let text = tree.read("rtl/m.sv");
|
||||
assert!(!text.contains("en // about b"), "the anchor's comment moved to `en`:\n{text}");
|
||||
drop(tree);
|
||||
}
|
||||
|
||||
/// Finding 2: the warnings and refusals `place.rs` writes name the file by
|
||||
@@ -385,8 +352,7 @@ fn qa_place_names_files_relative_to_the_root() {
|
||||
let said = refused(&tree, &mut server, "add_port", args, "by position");
|
||||
assert!(!said.contains(&root) && said.contains("rtl/top.sv"), "{said}");
|
||||
fs::write(tree.0.join("rtl/top.sv"), top.replace(" m u_p (a, y);\n", "")).unwrap();
|
||||
let args =
|
||||
json!({"module": "m", "declaration": "input logic en", "after": "a", "dry_run": true});
|
||||
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
|
||||
let (text, _) = written(&mut server, "add_port", args);
|
||||
assert!(!text.contains(&root) && text.contains("rtl/top.sv"), "{text}");
|
||||
}
|
||||
@@ -398,8 +364,7 @@ fn qa_place_names_files_relative_to_the_root() {
|
||||
fn qa_a_modport_port_after_the_anchor_does_not_refuse() {
|
||||
let n = "interface bus_if; logic v; modport mp(input v); endinterface\nmodule n (\n input logic clk,\n bus_if.mp bus,\n output logic y\n);\nendmodule\n";
|
||||
let (_tree, mut server) = served(&[("rtl/n.sv", n)]);
|
||||
let args =
|
||||
json!({"module": "n", "declaration": "input logic en", "after": "clk", "dry_run": true});
|
||||
let args = json!({"module": "n", "declaration": "input logic en", "after": "clk"});
|
||||
let (error, text, _) = server.call("add_port", args);
|
||||
assert!(!error, "{text}");
|
||||
}
|
||||
@@ -413,11 +378,10 @@ fn qa_mention_lines_name_the_file_as_written() {
|
||||
let m = "module m (\n input logic a,\n input logic b,\n output logic y\n);\n // en gates y\n assign y = a & b;\nendmodule\n";
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m)]);
|
||||
let args = json!({"module": "m", "declaration": "input logic en", "after": "a"});
|
||||
let (_, structured) = written(&mut server, "add_port", args);
|
||||
let mention = &structured["unresolved_mentions"][0];
|
||||
let line = mention["line"].as_u64().unwrap() as usize;
|
||||
let (_, mentions) = written(&mut server, "add_port", args);
|
||||
assert_eq!(mentions, json!(["rtl/m.sv:7"]));
|
||||
let on_disk = tree.read("rtl/m.sv");
|
||||
assert_eq!(on_disk.lines().nth(line - 1).map(str::trim), mention["text"].as_str(), "{on_disk}");
|
||||
assert_eq!(on_disk.lines().nth(6).map(str::trim), Some("// en gates y"), "{on_disk}");
|
||||
}
|
||||
|
||||
/// Finding 5 (BLOCKING), a: a port list holding an element the parser
|
||||
@@ -562,39 +526,14 @@ fn qa_r_mention_lines_after_a_rename_writing_out_a_star_binding() {
|
||||
let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n";
|
||||
let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n";
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
|
||||
let args = json!({"file": "rtl/m.sv", "line": 2, "name": "a", "new_name": "a_i"});
|
||||
let (text, structured) = written(&mut server, "rename", args);
|
||||
let args = json!({"name": "a", "file": "rtl/m.sv", "new_name": "a_i"});
|
||||
let (text, mentions) = written(&mut server, "rename", args);
|
||||
assert!(text.contains("added `.a_i(a)`"), "{text}");
|
||||
let on_disk = tree.read("rtl/top.sv");
|
||||
assert!(on_disk.contains(" .*,\n .a_i(a)\n"), "{on_disk}");
|
||||
let listed = structured["unresolved_mentions"].as_array().unwrap();
|
||||
assert_eq!(listed.len(), 2, "{structured}");
|
||||
for mention in listed {
|
||||
let line = mention["line"].as_u64().unwrap() as usize;
|
||||
let shown = on_disk.lines().nth(line - 1).map(str::trim);
|
||||
assert_eq!(shown, mention["text"].as_str(), "{on_disk}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding 6 (low, for the lead to rule): the rework computes mentions on
|
||||
/// the texts as they *would be* written under `dry_run` too, so a dry run's
|
||||
/// `file:line` names a line of a file that is not on disk — the comment at
|
||||
/// top.sv:5 is listed as top.sv:6, which on disk is the `$display`.
|
||||
#[test]
|
||||
#[ignore = "QA finding 6"]
|
||||
fn qa_r_dry_run_mention_lines_name_the_file_on_disk() {
|
||||
let m = "module m (\n input logic a,\n output logic y\n);\n assign y = a;\nendmodule\n";
|
||||
let top = "module top (input logic a, output logic y);\n m u_m (\n .*\n );\n // a feeds u_m\n initial $display(\"a\");\nendmodule\n";
|
||||
let (tree, mut server) = served(&[("rtl/m.sv", m), ("rtl/top.sv", top)]);
|
||||
let args =
|
||||
json!({"file": "rtl/m.sv", "line": 2, "name": "a", "new_name": "a_i", "dry_run": true});
|
||||
let (_, structured) = written(&mut server, "rename", args);
|
||||
let on_disk = tree.read("rtl/top.sv");
|
||||
for mention in structured["unresolved_mentions"].as_array().unwrap() {
|
||||
let line = mention["line"].as_u64().unwrap() as usize;
|
||||
let shown = on_disk.lines().nth(line - 1).map(str::trim);
|
||||
assert_eq!(shown, mention["text"].as_str(), "{on_disk}");
|
||||
}
|
||||
assert_eq!(mentions, json!(["rtl/top.sv:6", "rtl/top.sv:7"]), "{text}");
|
||||
let lines: Vec<&str> = on_disk.lines().map(str::trim).collect();
|
||||
assert_eq!((lines[5], lines[6]), ("// a feeds u_m", "initial $display(\"a\");"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -608,57 +547,35 @@ const DV: &str = "module dv_x;\n logic a, b;\n assign a = `HIER.u_a[2].state_q
|
||||
const CRLF: &str =
|
||||
"module c;\r\n // one\r\n // state_q two\r\n string s = \"state_q\";\r\nendmodule\r\n";
|
||||
|
||||
/// Each listed mention as `file:line kind`.
|
||||
fn sites(structured: &Value) -> Vec<String> {
|
||||
let listed = structured["unresolved_mentions"].as_array().unwrap();
|
||||
listed
|
||||
.iter()
|
||||
.map(|m| {
|
||||
format!("{}:{} {}", m["file"].as_str().unwrap(), m["line"], m["kind"].as_str().unwrap())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_mentions_find_every_kind_and_only_whole_words() {
|
||||
let files = [("rtl/sm.sv", SM), ("rtl/sub/crlf.sv", CRLF), ("dv/x.sv", DV)];
|
||||
let (_tree, mut server) = served(&files);
|
||||
let (text, structured) =
|
||||
written(&mut server, "references", json!({"name": "state_q", "unit": "main_sm"}));
|
||||
let (text, mentions) = written(&mut server, "find", json!({"name": "state_q", "refs": true}));
|
||||
assert_eq!(
|
||||
sites(&structured),
|
||||
[
|
||||
mentions,
|
||||
json!([
|
||||
// The file of the hits first: a hierarchical path in a comment,
|
||||
// a string inside a macro's arguments, a `define body (not the
|
||||
// `define whose formal is the name), a string, an escaped
|
||||
// spelling in a comment.
|
||||
"rtl/sm.sv:6 comment",
|
||||
"rtl/sm.sv:8 macro",
|
||||
"rtl/sm.sv:10 define",
|
||||
"rtl/sm.sv:12 string",
|
||||
"rtl/sm.sv:13 comment",
|
||||
"rtl/sm.sv:6",
|
||||
"rtl/sm.sv:8",
|
||||
"rtl/sm.sv:10",
|
||||
"rtl/sm.sv:12",
|
||||
"rtl/sm.sv:13",
|
||||
// Then nearest the declaration; CRLF lines counted right.
|
||||
"rtl/sub/crlf.sv:3 comment",
|
||||
"rtl/sub/crlf.sv:4 string",
|
||||
"rtl/sub/crlf.sv:3",
|
||||
"rtl/sub/crlf.sv:4",
|
||||
// A macro-rooted path through an index; `state_q_d` and a
|
||||
// name used as an index are not the path's last name.
|
||||
"dv/x.sv:3 path",
|
||||
],
|
||||
"dv/x.sv:3",
|
||||
]),
|
||||
"{text}"
|
||||
);
|
||||
assert!(text.contains(" rtl/sub/crlf.sv:4 string: string s = \"state_q\";\n"), "{text}");
|
||||
assert!(!text.contains('\r'), "no carriage return in a mention's text");
|
||||
// The JSON shape: exactly these four keys, a number for the line.
|
||||
for mention in structured["unresolved_mentions"].as_array().unwrap() {
|
||||
let keys: Vec<&String> = mention.as_object().unwrap().keys().collect();
|
||||
assert_eq!(keys, ["file", "kind", "line", "text"]);
|
||||
assert!(mention["line"].is_u64());
|
||||
}
|
||||
// A later page repeats nothing.
|
||||
let args = json!({"name": "state_q", "unit": "main_sm", "offset": 1});
|
||||
let (text, structured) = written(&mut server, "references", args);
|
||||
assert!(!text.contains("unresolved mentions"), "{text}");
|
||||
assert_eq!(structured["unresolved_mentions"], json!([]));
|
||||
assert!(text
|
||||
.ends_with("unresolved:\n rtl/sm.sv:6,8,10,12,13\n rtl/sub/crlf.sv:3,4\n dv/x.sv:3\n"));
|
||||
assert!(!text.contains('\r'), "no carriage return in an answer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -667,24 +584,16 @@ fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
|
||||
+ "module far; endmodule\n";
|
||||
let files = [("rtl/sm.sv", SM), ("zz/far.sv", far.as_str())];
|
||||
let (tree, mut server) = served(&files);
|
||||
let args = json!({"name": "state_q", "unit": "main_sm", "new_name": "st_q", "dry_run": true});
|
||||
let (text, structured) = written(&mut server, "rename", args);
|
||||
let listed = sites(&structured);
|
||||
let args = json!({"name": "state_q", "new_name": "st_q"});
|
||||
let (text, mentions) = written(&mut server, "rename", args);
|
||||
let listed = mentions.as_array().unwrap();
|
||||
assert_eq!(listed.len(), 50);
|
||||
assert_eq!(listed[0], "rtl/sm.sv:6 comment", "the edited file first");
|
||||
assert_eq!(listed[5], "zz/far.sv:1 comment");
|
||||
assert_eq!(listed[49], "zz/far.sv:45 comment");
|
||||
assert!(text.contains("(strings, comments, macro text; 65 in all)"), "{text}");
|
||||
assert!(text.contains("\n … and 15 more"), "{text}");
|
||||
assert_eq!(listed[0], "rtl/sm.sv:6", "the edited file first");
|
||||
assert_eq!(listed[5], "zz/far.sv:1");
|
||||
assert_eq!(listed[49], "zz/far.sv:45");
|
||||
assert!(text.ends_with("\n … and 15 more\n"), "{text}");
|
||||
// The renamed spellings are not mentions; the edit left the rest alone.
|
||||
assert!(!listed
|
||||
.iter()
|
||||
.any(|site| site.starts_with("rtl/sm.sv:5 ") || site.starts_with("rtl/sm.sv:11 ")));
|
||||
written(
|
||||
&mut server,
|
||||
"rename",
|
||||
json!({"name": "state_q", "unit": "main_sm", "new_name": "st_q"}),
|
||||
);
|
||||
assert!(!listed.iter().any(|site| site == "rtl/sm.sv:5" || site == "rtl/sm.sv:11"));
|
||||
let sm = tree.read("rtl/sm.sv");
|
||||
assert_eq!(
|
||||
sm,
|
||||
@@ -697,17 +606,15 @@ fn qa_mentions_are_capped_at_50_with_the_edited_file_first() {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_the_catalogue_is_small_fully_described_and_spec_shaped() {
|
||||
fn qa_the_catalogue_is_small_bare_and_spec_shaped() {
|
||||
let tree = Tree::with(&[]);
|
||||
let mut server = Session::over(&tree);
|
||||
let reply = server.request("tools/list", json!({}));
|
||||
let size = reply["result"].to_string().len();
|
||||
assert!(size <= 18_000, "tools/list is {size} bytes");
|
||||
let tools = reply["result"]["tools"].as_array().unwrap();
|
||||
assert_eq!(tools.len(), 26);
|
||||
assert_eq!(tools.len(), 9);
|
||||
for tool in tools {
|
||||
let name = tool["name"].as_str().unwrap();
|
||||
assert!(tool["title"].as_str().is_some_and(|t| !t.is_empty()), "{name} keeps its title");
|
||||
assert!(tool.get("title").is_none(), "{name}: `title` is gone (PLAN §10.1)");
|
||||
assert!(tool["description"].as_str().is_some_and(|d| !d.is_empty()), "{name}");
|
||||
let annotations = tool["annotations"].as_object().unwrap();
|
||||
assert!(!annotations.contains_key("title"), "{name}: annotations.title is gone");
|
||||
@@ -717,26 +624,26 @@ fn qa_the_catalogue_is_small_fully_described_and_spec_shaped() {
|
||||
let schema = &tool["inputSchema"];
|
||||
assert_eq!(schema["type"], "object", "{name}");
|
||||
for (param, property) in schema["properties"].as_object().unwrap() {
|
||||
let described = property["description"].as_str().is_some_and(|d| d.len() > 2);
|
||||
assert!(described, "{name}.{param} lost its description");
|
||||
assert!(property.get("description").is_none(), "{name}.{param} carries a description");
|
||||
assert!(
|
||||
tool["description"].as_str().unwrap().contains(param.as_str()),
|
||||
"{name} names `{param}`"
|
||||
);
|
||||
}
|
||||
}
|
||||
let add_port = tools.iter().find(|t| t["name"] == "add_port").unwrap();
|
||||
assert_eq!(add_port["inputSchema"]["properties"]["after"]["type"], "string");
|
||||
let required = add_port["inputSchema"]["required"].as_array().unwrap();
|
||||
assert!(!required.contains(&json!("after")));
|
||||
let port = tools.iter().find(|t| t["name"] == "port").unwrap();
|
||||
assert_eq!(port["inputSchema"]["properties"]["after"], json!({"type": "string"}));
|
||||
assert_eq!(port["inputSchema"]["required"], json!(["module"]));
|
||||
// The instructions: short, and every tool they name exists.
|
||||
let instructions = server.init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.chars().count() <= 900, "{}", instructions.chars().count());
|
||||
assert!(instructions.len() <= 400, "{}", instructions.len());
|
||||
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
|
||||
for word in words.filter(|w| w.contains('_') && *w != "dry_run") {
|
||||
for word in words.filter(|w| w.contains('_')) {
|
||||
assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool");
|
||||
}
|
||||
for word in
|
||||
["outline", "definition", "references", "hierarchy", "rename", "format", "diagnostics"]
|
||||
{
|
||||
assert!(names.contains(&word) && instructions.contains(word), "{word}");
|
||||
for word in names {
|
||||
assert!(instructions.contains(word), "{word}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -775,7 +682,7 @@ fn qa_the_sweep_takes_only_old_files_of_the_exact_temp_name() {
|
||||
"--index-cache",
|
||||
cache.to_str().unwrap(),
|
||||
]);
|
||||
server.call("list_units", json!({}));
|
||||
server.call("hierarchy", json!({}));
|
||||
server.end();
|
||||
assert!(cache.join("index-cache-mcp").is_file(), "the own store is still written");
|
||||
assert!(!stale.exists(), "an hour-old `<store>.<pid>.tmp` is swept");
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
//! QA attacks on lane feedback-2 (the count line on every paged answer, the
|
||||
//! `in` path glob, the post-edit check line), 2026-09-23.
|
||||
//!
|
||||
//! Every test spawns the real binary over a scratch tree, as a host would.
|
||||
//! The count line is checked by one rule applied to every paged tool over a
|
||||
//! grid of windows: its total is the JSON `total`, its window the JSON
|
||||
//! `shown`, the JSON list holds exactly the window, and the old
|
||||
//! `… and N more` tail says `total − b`.
|
||||
//! `in` path glob, the post-edit check line), 2026-09-23 — ported to the
|
||||
//! lean catalogue: paging, `in` and the check line are gone (PLAN §10.2),
|
||||
//! so what remains is the hierarchy walk over this tree and the path glob,
|
||||
//! which lives on as `format`'s `files` (`docs/features/mcp-lean-catalogue`
|
||||
//! lists what was deleted).
|
||||
//!
|
||||
//! A test that pins a QA finding asserts the *correct* behaviour and is
|
||||
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
|
||||
@@ -122,23 +120,19 @@ impl Session {
|
||||
reply
|
||||
}
|
||||
|
||||
/// A tool call: whether it was refused, its text, its structured content.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
|
||||
/// A tool call: whether it was refused, and its text.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String) {
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let result = &reply["result"];
|
||||
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
|
||||
(result["isError"] == true, text, result["structuredContent"].clone())
|
||||
}
|
||||
|
||||
/// A call that must answer; its text and structured content.
|
||||
fn ok(&mut self, tool: &str, arguments: Value) -> (String, Value) {
|
||||
let (error, text, structured) = self.call(tool, arguments.clone());
|
||||
assert!(!error, "{tool} {arguments}: refused: {text}");
|
||||
(text, structured)
|
||||
(result["isError"] == true, text)
|
||||
}
|
||||
|
||||
/// A call that must answer: its text.
|
||||
fn text(&mut self, tool: &str, arguments: Value) -> String {
|
||||
self.ok(tool, arguments).0
|
||||
let (error, text) = self.call(tool, arguments.clone());
|
||||
assert!(!error, "{tool} {arguments}: refused: {text}");
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,557 +188,97 @@ fn served() -> (Tree, Session) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1. The count line, one rule for every paged tool.
|
||||
// 1. The hierarchy over this tree.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What an answer's first line says: its total and its window (`None` for
|
||||
/// a whole list, `Some(None)` past the end, `Some(Some((a, b)))` cut).
|
||||
struct Header {
|
||||
total: usize,
|
||||
window: Option<Option<(usize, usize)>>,
|
||||
}
|
||||
|
||||
/// Parse the count line, checking its noun agrees with the number.
|
||||
fn header(text: &str) -> Header {
|
||||
let first = text.lines().next().unwrap_or_default();
|
||||
let (count, rest) = first.split_once(' ').unwrap_or_else(|| panic!("no count line: {text}"));
|
||||
let total: usize = count.parse().unwrap_or_else(|_| panic!("no count line: {text}"));
|
||||
let (noun, window) = match rest.split_once(" (") {
|
||||
Some((noun, window)) => (noun, Some(window.trim_end_matches(')'))),
|
||||
None => (rest, None),
|
||||
};
|
||||
assert_eq!(noun.ends_with('s'), total != 1, "singular only for one: {first}");
|
||||
let window = match window {
|
||||
None => None,
|
||||
Some("none match `in`") => {
|
||||
assert_eq!(total, 0, "{first}");
|
||||
None
|
||||
}
|
||||
Some("showing none: `offset` is past the end") => Some(None),
|
||||
Some(showing) => {
|
||||
let span = showing.strip_prefix("showing ").unwrap_or_else(|| panic!("{first}"));
|
||||
let (a, b) = span.split_once('–').unwrap_or((span, span));
|
||||
let (a, b): (usize, usize) = (a.parse().unwrap(), b.parse().unwrap());
|
||||
assert!(1 <= a && a <= b && b <= total, "{first}");
|
||||
assert!(a < b || !span.contains('–'), "one entry is `showing a`: {first}");
|
||||
assert!(a > 1 || b < total, "a whole list says no window: {first}");
|
||||
Some(Some((a, b)))
|
||||
}
|
||||
};
|
||||
Header { total, window }
|
||||
}
|
||||
|
||||
/// Check one answer against the rule: the count line's total is `total`,
|
||||
/// its window is `shown`, the JSON `key` list holds the window (plus `lead`
|
||||
/// lines that are not counted) and the tail counts what follows.
|
||||
fn agrees(label: &str, text: &str, structured: &Value, key: &str, lead: usize) {
|
||||
let listed = structured[key].as_array().map_or(0, Vec::len);
|
||||
let total = structured["total"].as_u64().unwrap() as usize;
|
||||
let tail = text.lines().find(|line| line.starts_with("… and "));
|
||||
if text.starts_with("no ") {
|
||||
// An empty list keeps its old one-line answer.
|
||||
assert_eq!((total, structured["shown"].clone()), (0, json!([0, 0])), "{label}");
|
||||
return;
|
||||
}
|
||||
let said = header(text);
|
||||
assert_eq!(said.total, total, "{label}: the count line is the JSON total\n{text}");
|
||||
let (a, b) = match said.window {
|
||||
None if total == 0 => (0, 0),
|
||||
None => (1, total),
|
||||
Some(None) => (0, 0),
|
||||
Some(Some(span)) => span,
|
||||
};
|
||||
assert_eq!(structured["shown"], json!([a, b]), "{label}: `shown` is the window\n{text}");
|
||||
let in_window = if a == 0 { 0 } else { b - a + 1 };
|
||||
assert_eq!(listed, in_window + lead, "{label}: the JSON lists the window\n{text}");
|
||||
match b < total && a > 0 {
|
||||
true => assert_eq!(tail, Some(format!("… and {} more", total - b).as_str()), "{label}"),
|
||||
false => assert_eq!(tail, None, "{label}: nothing follows\n{text}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every window worth trying on a list of `n`.
|
||||
fn windows(n: usize) -> Vec<Value> {
|
||||
let mut out = vec![json!({})];
|
||||
for (offset, limit) in
|
||||
[(0, 1), (1, 1), (0, 2), (1, 2), (n - 1, 1), (n - 1, 5), (n, 1), (n + 3, 2), (1, n)]
|
||||
{
|
||||
out.push(json!({"offset": offset, "limit": limit}));
|
||||
}
|
||||
out.push(json!({"offset": 1}));
|
||||
out
|
||||
}
|
||||
|
||||
/// The paged tools, each with arguments that give a list of several, the
|
||||
/// JSON key of its list, and the lines it prints that the count leaves out.
|
||||
fn paged_calls() -> Vec<(&'static str, Value, &'static str, usize)> {
|
||||
vec![
|
||||
("list_units", json!({}), "units", 0),
|
||||
("list_units", json!({"in": "ip/**"}), "units", 0),
|
||||
("search_symbols", json!({"query": "clk"}), "symbols", 0),
|
||||
("search_symbols", json!({"query": "clk", "in": "**/ip/**"}), "symbols", 0),
|
||||
("outline", json!({"file": "ip/aes/rtl/aes.sv"}), "symbols", 0),
|
||||
("references", json!({"name": "leaf"}), "hits", 0),
|
||||
("references", json!({"name": "leaf", "in": "ip/**"}), "hits", 0),
|
||||
("diagnostics", json!({}), "diagnostics", 0),
|
||||
("diagnostics", json!({"in": "ip/**"}), "diagnostics", 0),
|
||||
("defines", json!({}), "defines", 0),
|
||||
("defines", json!({"in": "ip/aes/**"}), "defines", 0),
|
||||
("defines", json!({"file": "ip/aes/rtl/aes.sv"}), "defines", 0),
|
||||
("hierarchy", json!({"root": "leaf", "direction": "up"}), "nodes", 1),
|
||||
("hierarchy", json!({"root": "leaf", "direction": "up", "depth": 1}), "nodes", 1),
|
||||
("hierarchy", json!({"root": "leaf", "direction": "up", "in": "ip/**"}), "nodes", 1),
|
||||
("hierarchy", json!({}), "nodes", 0),
|
||||
("hierarchy", json!({"in": "ip/**"}), "nodes", 0),
|
||||
("hierarchy", json!({"root": "tb", "depth": 5}), "nodes", 0),
|
||||
]
|
||||
}
|
||||
|
||||
fn merged(base: &Value, window: &Value) -> Value {
|
||||
let mut out = base.clone();
|
||||
for (key, value) in window.as_object().unwrap() {
|
||||
out[key] = value.clone();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_every_paged_tool_agrees_with_its_json_over_every_window() {
|
||||
fn qa_hierarchy_up_lists_every_instantiation_at_every_level() {
|
||||
let (_tree, mut server) = served();
|
||||
for (tool, base, key, lead) in paged_calls() {
|
||||
let (_, whole) = server.ok(tool, base.clone());
|
||||
let n = whole["total"].as_u64().unwrap() as usize;
|
||||
assert!(n >= 2, "{tool} {base}: the grid wants a list of several, got {n}");
|
||||
for window in windows(n) {
|
||||
let arguments = merged(&base, &window);
|
||||
let (text, structured) = server.ok(tool, arguments.clone());
|
||||
agrees(&format!("{tool} {arguments}"), &text, &structured, key, lead);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_count_line_pins_whole_cut_single_and_past_the_end() {
|
||||
let (_tree, mut server) = served();
|
||||
let units = server.text("list_units", json!({}));
|
||||
assert!(units.starts_with("9 units\ndoc/notes.sv\n"), "{units}");
|
||||
let one = server.text("list_units", json!({"limit": 1}));
|
||||
assert_eq!(one, "9 units (showing 1)\ndoc/notes.sv\n module notes 2\n… and 8 more\n");
|
||||
let last = server.text("list_units", json!({"offset": 8, "limit": 3}));
|
||||
assert_eq!(last, "9 units (showing 9)\nlib/mid.sv\n module mid 1\n");
|
||||
let past = server.text("list_units", json!({"offset": 9}));
|
||||
assert_eq!(past, "9 units (showing none: `offset` is past the end)\n");
|
||||
let single = server.text("list_units", json!({"glob": "leaf"}));
|
||||
assert_eq!(single, "1 unit\nlib/leaf.sv\n module leaf 1\n");
|
||||
assert_eq!(server.text("list_units", json!({"glob": "zz*"})), "no units match\n");
|
||||
|
||||
let outline = server.text("outline", json!({"file": "lib/leaf.sv"}));
|
||||
assert_eq!(outline, "2 entries\nlib/leaf.sv\n module leaf 1-2\n port clk_i 1\n");
|
||||
let one = server.text("outline", json!({"file": "lib/leaf.sv", "depth": 1}));
|
||||
assert_eq!(one, "1 entry\nlib/leaf.sv\n module leaf 1-2\n");
|
||||
let past = server.text("outline", json!({"file": "lib/leaf.sv", "offset": 7}));
|
||||
assert_eq!(past, "2 entries (showing none: `offset` is past the end)\nlib/leaf.sv\n");
|
||||
|
||||
let hit = server.text("references", json!({"name": "notes"}));
|
||||
assert_eq!(hit, "1 hit\ndoc/notes.sv\n 2:8 module notes; endmodule\n");
|
||||
let cut = server.text("references", json!({"name": "leaf", "limit": 2, "offset": 5}));
|
||||
assert!(cut.starts_with("7 hits (showing 6–7)\nlib/leaf.sv\n"), "{cut}");
|
||||
assert!(!cut.contains("… and"), "{cut}");
|
||||
|
||||
let finding = server.text("diagnostics", json!({"file": "hw/ip/y.sv"}));
|
||||
let whole = server.text("hierarchy", json!({"root": "leaf", "up": true, "depth": 3}));
|
||||
// Deeper lines are instantiations of the ancestors.
|
||||
assert_eq!(whole.lines().count(), 11, "{whole}");
|
||||
let direct = server.text("hierarchy", json!({"root": "leaf", "up": true}));
|
||||
assert_eq!(direct.lines().count(), 6, "{direct}");
|
||||
assert!(direct.contains("aes.u_b ip/aes/rtl/aes.sv:5\n"), "{direct}");
|
||||
assert!(direct.lines().all(|line| !line.starts_with(' ')), "one level: {direct}");
|
||||
assert_eq!(
|
||||
finding,
|
||||
"1 finding\nhw/ip/y.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n"
|
||||
);
|
||||
let define = server.text("defines", json!({"name": "IPX"}));
|
||||
assert_eq!(define, "1 define\nip/x.sv\n 1 `define IPX 1\n");
|
||||
let symbol = server.text("search_symbols", json!({"query": "leaf"}));
|
||||
assert_eq!(symbol, "1 symbol\nlib/leaf.sv\n module leaf 1\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2. `hierarchy`: `up` from one root counts instantiations, the root line
|
||||
// on every page; any other walk counts nodes.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const LEAF_UP: &str = "leaf lib/leaf.sv:1\n";
|
||||
|
||||
#[test]
|
||||
fn qa_hierarchy_up_repeats_its_root_line_on_every_page_and_counts_only_instantiations() {
|
||||
let (_tree, mut server) = served();
|
||||
let (whole, structured) = server.ok("hierarchy", json!({"root": "leaf", "direction": "up"}));
|
||||
// Deeper lines are instantiations of the ancestors and are counted.
|
||||
assert_eq!(structured["total"], 11);
|
||||
assert_eq!(whole.lines().count(), 1 + 1 + 11, "{whole}");
|
||||
assert_eq!(structured["nodes"][0]["module"], "leaf", "{structured}");
|
||||
for offset in 0..13 {
|
||||
let args = json!({"root": "leaf", "direction": "up", "limit": 2, "offset": offset});
|
||||
let (text, _) = server.ok("hierarchy", args);
|
||||
let (_, body) = text.split_once('\n').unwrap();
|
||||
assert!(body.starts_with(LEAF_UP), "offset {offset}: {text}");
|
||||
assert_eq!(body.matches(LEAF_UP).count(), 1, "offset {offset}: {text}");
|
||||
}
|
||||
let page = server.text(
|
||||
"hierarchy",
|
||||
json!({"root": "leaf", "direction": "up", "depth": 1, "limit": 2, "offset": 2}),
|
||||
server.text("hierarchy", json!({"root": "tb", "up": true})),
|
||||
"nothing instantiates tb\n"
|
||||
);
|
||||
assert_eq!(
|
||||
page,
|
||||
"6 instantiations (showing 3–4)\nleaf lib/leaf.sv:1\n aes.u_b ip/aes/rtl/aes.sv:5\n deep.u_c ip/aes/rtl/sub/deep.sv:3\n… and 2 more\n"
|
||||
server.text("hierarchy", json!({"root": "aes", "up": true})),
|
||||
"tb.u_dut ip/aes/dv/tb.sv:3\n"
|
||||
);
|
||||
let past = server.text("hierarchy", json!({"root": "leaf", "direction": "up", "offset": 40}));
|
||||
assert_eq!(
|
||||
past,
|
||||
format!("11 instantiations (showing none: `offset` is past the end)\n{LEAF_UP}")
|
||||
);
|
||||
let top = server.text("hierarchy", json!({"root": "tb", "direction": "up"}));
|
||||
assert_eq!(top, "0 instantiations\ntb ip/aes/dv/tb.sv:1\n");
|
||||
let one = server.text("hierarchy", json!({"root": "aes", "direction": "up"}));
|
||||
assert_eq!(one, "1 instantiation\naes ip/aes/rtl/aes.sv:3\n tb.u_dut ip/aes/dv/tb.sv:3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_hierarchy_up_from_a_root_declared_twice_counts_every_line_as_nodes() {
|
||||
fn qa_hierarchy_up_from_a_root_declared_twice_lists_each_instantiation_once() {
|
||||
let tree = Tree::with(&[
|
||||
("a/d1.sv", "module dup; endmodule\n"),
|
||||
("b/d2.sv", "module dup; endmodule\n"),
|
||||
("a/user.sv", "module user; dup u1 (); dup u2 (); endmodule\n"),
|
||||
]);
|
||||
let mut server = Session::over(&tree);
|
||||
let (text, structured) = server.ok("hierarchy", json!({"root": "dup", "direction": "up"}));
|
||||
assert_eq!(
|
||||
text,
|
||||
"6 nodes\ndup a/d1.sv:1\n user.u1 a/user.sv:1\n user.u2 a/user.sv:1\ndup b/d2.sv:1\n user.u1 a/user.sv:1\n user.u2 a/user.sv:1\n"
|
||||
);
|
||||
assert_eq!(
|
||||
(structured["total"].clone(), structured["shown"].clone()),
|
||||
(json!(6), json!([1, 6]))
|
||||
);
|
||||
let cut = server.text("hierarchy", json!({"root": "dup", "direction": "up", "limit": 2}));
|
||||
assert!(
|
||||
cut.starts_with("6 nodes (showing 1–2)\ndup a/d1.sv:1\n")
|
||||
&& cut.ends_with("… and 4 more\n")
|
||||
server.text("hierarchy", json!({"root": "dup", "up": true})),
|
||||
"user.u1 a/user.sv:1\nuser.u2 a/user.sv:1\n"
|
||||
);
|
||||
// Down, each declaration is a root of its own.
|
||||
assert_eq!(server.text("hierarchy", json!({"root": "dup"})), "dup a/d1.sv:1\ndup b/d2.sv:1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_hierarchy_down_from_several_tops_counts_nodes() {
|
||||
fn qa_hierarchy_without_a_root_names_every_top_at_its_declaration() {
|
||||
let (_tree, mut server) = served();
|
||||
let (tops, structured) = server.ok("hierarchy", json!({"depth": 1}));
|
||||
assert_eq!(
|
||||
tops,
|
||||
"9 nodes\n\\esc*mod esc/e.sv:1\nhwy hw/ip/y.sv:1\n u_e : leaf\nipx ip/x.sv:2\n u_a : leaf\nnotes doc/notes.sv:2\ntb ip/aes/dv/tb.sv:1\n u_dut : aes\n u_d : leaf\n"
|
||||
);
|
||||
assert_eq!(structured["total"], 9);
|
||||
let cut = server.text("hierarchy", json!({"depth": 1, "offset": 3, "limit": 3}));
|
||||
assert_eq!(
|
||||
cut,
|
||||
"9 nodes (showing 4–6)\nipx ip/x.sv:2\n u_a : leaf\nnotes doc/notes.sv:2\n… and 3 more\n"
|
||||
server.text("hierarchy", json!({})),
|
||||
"9 files, 9 modules, 5 top\n\\esc*mod esc/e.sv:1\nhwy hw/ip/y.sv:1\nipx ip/x.sv:2\nnotes doc/notes.sv:2\ntb ip/aes/dv/tb.sv:1\n"
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 3. `in`: the path matcher through the tools.
|
||||
// 2. The path glob, as `format`'s `files` reads it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The unit names `list_units` gives under `in`, or the whole text when the
|
||||
/// answer is not a list.
|
||||
fn units_in(server: &mut Session, glob: &str) -> Vec<String> {
|
||||
let (text, structured) = server.ok("list_units", json!({"in": glob}));
|
||||
if structured["total"] == 0 {
|
||||
return vec![text];
|
||||
}
|
||||
let units = structured["units"].as_array().unwrap();
|
||||
units.iter().map(|u| u["name"].as_str().unwrap().to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_in_star_stays_in_one_component_and_double_star_spans_zero_or_more() {
|
||||
let (_tree, mut server) = served();
|
||||
let none = || vec!["0 units (none match `in`)\n".to_string()];
|
||||
// `*` never crosses a `/`: `sub/deep.sv` is not in `rtl/*.sv`.
|
||||
assert_eq!(units_in(&mut server, "ip/aes/rtl/*.sv"), ["aes"]);
|
||||
assert_eq!(units_in(&mut server, "ip/aes/rtl/**"), ["aes", "deep"]);
|
||||
assert_eq!(units_in(&mut server, "ip/aes/rtl/**/*.sv"), ["aes", "deep"]);
|
||||
// `**` spans zero components too.
|
||||
assert_eq!(units_in(&mut server, "ip/**/x.sv"), ["ipx"]);
|
||||
assert_eq!(units_in(&mut server, "**/x.sv"), ["ipx"]);
|
||||
assert_eq!(units_in(&mut server, "ip/**/rtl/**/deep.sv"), ["deep"]);
|
||||
// Anchored at the root: `ip/**` is not `hw/ip/**`.
|
||||
assert_eq!(units_in(&mut server, "ip/**"), ["tb", "aes", "deep", "ipx"]);
|
||||
assert_eq!(units_in(&mut server, "**/ip/**"), ["hwy", "tb", "aes", "deep", "ipx"]);
|
||||
assert_eq!(units_in(&mut server, "hw/ip/*.sv"), ["hwy"]);
|
||||
assert_eq!(units_in(&mut server, "*/ip/*"), ["hwy"]);
|
||||
// `?` is one character of one component.
|
||||
assert_eq!(units_in(&mut server, "ip/ae?/*/*.sv"), ["tb", "aes"]);
|
||||
assert_eq!(units_in(&mut server, "ip/a?/**"), none());
|
||||
assert_eq!(units_in(&mut server, "l?b/m?d.sv"), ["mid"]);
|
||||
assert_eq!(units_in(&mut server, "ip?x.sv"), none(), "`?` never matches a `/`");
|
||||
// A leading `./`, a trailing `/`, `**/**`.
|
||||
assert_eq!(units_in(&mut server, "./lib/*"), ["leaf", "mid"]);
|
||||
assert_eq!(units_in(&mut server, "lib/"), ["leaf", "mid"]);
|
||||
assert_eq!(units_in(&mut server, "**/**/lib/**/**"), ["leaf", "mid"]);
|
||||
// A whole-path glob is not a substring search.
|
||||
assert_eq!(units_in(&mut server, "aes"), none());
|
||||
assert_eq!(units_in(&mut server, "*.sv"), none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_in_matches_paths_never_names_even_escaped_ones_holding_a_star() {
|
||||
let (_tree, mut server) = served();
|
||||
let none = vec!["0 units (none match `in`)\n".to_string()];
|
||||
// The unit is named `\esc*mod `; the glob sees only `esc/e.sv`.
|
||||
assert_eq!(units_in(&mut server, "\\esc*mod "), none);
|
||||
assert_eq!(units_in(&mut server, "esc*"), none);
|
||||
assert_eq!(units_in(&mut server, "esc*/*"), ["\\esc*mod"]);
|
||||
let named = server.text("list_units", json!({"glob": "\\esc*mod", "in": "esc/e.sv"}));
|
||||
assert_eq!(named, "1 unit\nesc/e.sv\n module \\esc*mod 1\n");
|
||||
let symbols = server.text("search_symbols", json!({"query": "esc*", "in": "esc/*"}));
|
||||
assert!(symbols.starts_with("1 symbol\nesc/e.sv\n"), "{symbols}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_in_says_none_match_only_when_it_removed_something() {
|
||||
let (_tree, mut server) = served();
|
||||
// Empty before the glob: the old answer, per tool.
|
||||
let empty = [
|
||||
("list_units", json!({"glob": "zz", "in": "nowhere/**"}), "no units match\n"),
|
||||
("search_symbols", json!({"query": "zz", "in": "nowhere/**"}), "no symbols match\n"),
|
||||
("defines", json!({"name": "ZZ", "in": "nowhere/**"}), "no defines\n"),
|
||||
("defines", json!({"file": "lib/mid.sv", "in": "nowhere/**"}), "no defines\n"),
|
||||
("diagnostics", json!({"file": "lib/mid.sv", "in": "nowhere/**"}), "no findings\n"),
|
||||
];
|
||||
for (tool, args, said) in empty {
|
||||
assert_eq!(server.text(tool, args.clone()), said, "{tool} {args}");
|
||||
}
|
||||
let refs = server.text("references", json!({"name": "clk_i", "unit": "leaf", "in": "zz/**"}));
|
||||
assert_eq!(refs, "0 hits (none match `in`)\n");
|
||||
// Emptied by the glob: said so, per tool.
|
||||
let emptied = [
|
||||
("list_units", json!({"in": "nowhere/**"}), "0 units (none match `in`)\n"),
|
||||
("search_symbols", json!({"query": "clk", "in": "doc/*"}), "0 symbols (none match `in`)\n"),
|
||||
("defines", json!({"in": "lib/**"}), "0 defines (none match `in`)\n"),
|
||||
("defines", json!({"file": "ip/x.sv", "in": "lib/**"}), "0 defines (none match `in`)\n"),
|
||||
("diagnostics", json!({"in": "nowhere/**"}), "0 findings (none match `in`)\n"),
|
||||
(
|
||||
"diagnostics",
|
||||
json!({"file": "ip/x.sv", "in": "lib/*"}),
|
||||
"0 findings (none match `in`)\n",
|
||||
),
|
||||
("hierarchy", json!({"in": "lib/**"}), "0 nodes (none match `in`)\n"),
|
||||
];
|
||||
for (tool, args, said) in emptied {
|
||||
let (text, structured) = server.ok(tool, args.clone());
|
||||
assert_eq!(text, said, "{tool} {args}");
|
||||
assert_eq!(
|
||||
(structured["total"].clone(), structured["shown"].clone()),
|
||||
(json!(0), json!([0, 0]))
|
||||
);
|
||||
}
|
||||
// Matched files with nothing to say are clean, not "none match".
|
||||
assert_eq!(server.text("diagnostics", json!({"in": "lib/**"})), "no findings\n");
|
||||
// `in` and a window together: the total is the filtered count.
|
||||
let (text, structured) =
|
||||
server.ok("references", json!({"name": "leaf", "in": "ip/**", "offset": 1, "limit": 2}));
|
||||
assert!(text.starts_with("4 hits (showing 2–3)\n"), "{text}");
|
||||
assert!(text.contains("… and 1 more\n"), "{text}");
|
||||
assert_eq!(structured["total"], 4);
|
||||
let past = server.text("list_units", json!({"in": "lib/*", "offset": 2}));
|
||||
assert_eq!(past, "2 units (showing none: `offset` is past the end)\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_in_on_references_keeps_only_the_mentions_in_matching_files() {
|
||||
let (_tree, mut server) = served();
|
||||
let (all, structured) = server.ok("references", json!({"name": "leaf"}));
|
||||
assert!(all.contains("doc/notes.sv:1 comment") && all.contains("ip/aes/dv/tb.sv:2 comment"));
|
||||
assert_eq!(structured["unresolved_mentions"].as_array().unwrap().len(), 2);
|
||||
let (rtl, structured) = server.ok("references", json!({"name": "leaf", "in": "ip/**"}));
|
||||
assert!(!rtl.contains("doc/notes.sv"), "a mention outside the glob: {rtl}");
|
||||
assert!(rtl.contains("ip/aes/dv/tb.sv:2 comment"), "{rtl}");
|
||||
assert_eq!(structured["unresolved_mentions"].as_array().unwrap().len(), 1);
|
||||
let lib = server.text("references", json!({"name": "leaf", "in": "lib/**"}));
|
||||
assert_eq!(
|
||||
lib,
|
||||
"2 hits\nlib/leaf.sv\n 1:8 module leaf (input logic clk_i);\nlib/mid.sv\n 2:3 leaf u_f (.clk_i(clk_i));\n"
|
||||
);
|
||||
// Hits emptied, a mention kept: both said.
|
||||
let doc = server.text("references", json!({"name": "leaf", "in": "doc/*"}));
|
||||
assert!(doc.starts_with("0 hits (none match `in`)\nunresolved mentions"), "{doc}");
|
||||
assert!(doc.ends_with(" doc/notes.sv:1 comment: // leaf is the unit under test\n"), "{doc}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_in_on_hierarchy_down_drops_a_whole_subtree_and_up_does_not_climb_through_a_drop() {
|
||||
let (_tree, mut server) = served();
|
||||
// `mid` lives in `lib/`; its child `deep` lives in `ip/` but is under a
|
||||
// dropped node, so it must not appear.
|
||||
let aes = server.text("hierarchy", json!({"root": "aes", "depth": 5, "in": "ip/**"}));
|
||||
assert_eq!(aes, "1 node\naes ip/aes/rtl/aes.sv:3\n");
|
||||
let tb = server.text("hierarchy", json!({"root": "tb", "depth": 5, "in": "**/rtl/**"}));
|
||||
assert_eq!(tb, "2 nodes\ntb ip/aes/dv/tb.sv:1\n u_dut : aes\n");
|
||||
let tb = server.text("hierarchy", json!({"root": "tb", "depth": 5, "in": "lib/*"}));
|
||||
assert_eq!(tb, "2 nodes\ntb ip/aes/dv/tb.sv:1\n u_d : leaf\n");
|
||||
// No root: tops by their own file, children by theirs.
|
||||
let dv = server.text("hierarchy", json!({"in": "ip/aes/dv/*", "depth": 5}));
|
||||
assert_eq!(dv, "1 node\ntb ip/aes/dv/tb.sv:1\n");
|
||||
// Up: `mid.u_g` (lib/) is dropped, so `aes.u_m` above it is not reached
|
||||
// through it; `deep.u_c` (ip/) is kept.
|
||||
let up = server.text("hierarchy", json!({"root": "deep", "direction": "up", "in": "ip/**"}));
|
||||
assert_eq!(up, "0 instantiations (none match `in`)\ndeep ip/aes/rtl/sub/deep.sv:1\n");
|
||||
let up = server.text("hierarchy", json!({"root": "leaf", "direction": "up", "in": "ip/**"}));
|
||||
assert_eq!(
|
||||
up,
|
||||
"5 instantiations\nleaf lib/leaf.sv:1\n tb.u_d ip/aes/dv/tb.sv:4\n aes.u_b ip/aes/rtl/aes.sv:5\n tb.u_dut ip/aes/dv/tb.sv:3\n deep.u_c ip/aes/rtl/sub/deep.sv:3\n ipx.u_a ip/x.sv:4\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_in_on_whole_project_diagnostics_lints_matching_files_and_reports_no_unused_waiver() {
|
||||
let (_tree, mut server) = served();
|
||||
let all = server.text("diagnostics", json!({}));
|
||||
assert!(all.starts_with("5 findings\n"), "{all}");
|
||||
assert!(all.contains("w.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n"));
|
||||
let (ip, structured) = server.ok("diagnostics", json!({"in": "ip/**"}));
|
||||
assert_eq!(
|
||||
ip,
|
||||
"3 findings\nip/aes/rtl/aes.sv\n 4:9 warning `dead_b` is declared but never used [unused-signal]\nip/aes/rtl/sub/deep.sv\n 2:9 warning `dead_c` is declared but never used [unused-signal]\nip/x.sv\n 3:9 warning `dead_a` is declared but never used [unused-signal]\n"
|
||||
);
|
||||
assert_eq!(structured["total"], 3);
|
||||
for glob in ["**/*.sv", "hw/**", "*.waiver", "w.waiver"] {
|
||||
let text = server.text("diagnostics", json!({"in": glob}));
|
||||
assert!(!text.contains("unused-waiver"), "{glob}: {text}");
|
||||
}
|
||||
// `in` + severity + a window.
|
||||
let args = json!({"in": "**/ip/**", "severity": "warning", "offset": 2, "limit": 5});
|
||||
let (text, structured) = server.ok("diagnostics", args);
|
||||
assert!(text.starts_with("3 findings (showing 3)\nip/x.sv\n"), "{text}");
|
||||
assert_eq!(structured["shown"], json!([3, 3]));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 4. The check line on the six design-wide edits.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The last line of an answer.
|
||||
fn last_line(text: &str) -> &str {
|
||||
text.trim_end_matches('\n').rsplit('\n').next().unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_each_edit_ends_with_its_check_line_dry_and_real_and_nothing_else_does() {
|
||||
/// How many files `format` took for `files` over a fresh copy of the tree
|
||||
/// (or its refusal); every file it wrote must lie under `within`.
|
||||
fn formatted_within(files: &str, within: &str) -> String {
|
||||
let (tree, mut server) = served();
|
||||
let cases = [
|
||||
("rename", json!({"name": "mid", "new_name": "mid2"}), "ip/aes/rtl/aes.sv, lib/mid.sv"),
|
||||
(
|
||||
"add_port",
|
||||
json!({"module": "deep", "declaration": "input logic en"}),
|
||||
"ip/aes/rtl/sub/deep.sv, lib/mid.sv",
|
||||
),
|
||||
("expand_wildcard", json!({"file": "ip/wild.sv", "line": 2}), "ip/wild.sv"),
|
||||
(
|
||||
"remove_port",
|
||||
json!({"file": "lib/solo.sv", "line": 1, "name": "k"}),
|
||||
"ip/wild.sv, lib/solo.sv",
|
||||
),
|
||||
("inline_module", json!({"file": "ip/wild.sv", "line": 2, "name": "u_l"}), "ip/wild.sv"),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "ip/x.sv", "start_line": 4, "end_line": 4, "new_name": "slot"}),
|
||||
"ip/slot.sv, ip/x.sv",
|
||||
),
|
||||
];
|
||||
fs::write(
|
||||
tree.0.join("lib/solo.sv"),
|
||||
"module solo (input logic a, input logic k);\nendmodule\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
tree.0.join("ip/wild.sv"),
|
||||
"module wild (input logic a, input logic k);\n solo u_l (.*);\nendmodule\n",
|
||||
)
|
||||
.unwrap();
|
||||
for (tool, args, files) in cases {
|
||||
let before = tree.snapshot();
|
||||
let mut dry = args.clone();
|
||||
dry["dry_run"] = json!(true);
|
||||
let (text, structured) = server.ok(tool, dry);
|
||||
assert_eq!(
|
||||
last_line(&text),
|
||||
format!("check after writing: diagnostics on {files}"),
|
||||
"{tool}"
|
||||
);
|
||||
assert_eq!(text.matches("diagnostics on").count(), 1, "{tool}: {text}");
|
||||
assert!(structured.get("check").is_none(), "{tool}: the JSON is unchanged");
|
||||
assert!(before == tree.snapshot(), "{tool}: a dry run wrote");
|
||||
let (text, _) = server.ok(tool, args.clone());
|
||||
assert_eq!(last_line(&text), format!("check: diagnostics on {files}"), "{tool}: {text}");
|
||||
// Once more: `unchanged` or a refusal, never a check line.
|
||||
let (_, again, _) = server.call(tool, args.clone());
|
||||
assert!(!again.contains("diagnostics on"), "{tool} again: {again}");
|
||||
let before = tree.snapshot();
|
||||
let (error, text) = server.call("format", json!({"files": files}));
|
||||
let after = tree.snapshot();
|
||||
for (file, bytes) in &after {
|
||||
assert!(before[file] == *bytes || file.starts_with(within), "{files} wrote {file}");
|
||||
}
|
||||
let unchanged = server.text("rename", json!({"name": "leaf", "new_name": "leaf"}));
|
||||
assert_eq!(unchanged, "unchanged\n");
|
||||
// The edits outside the brief carry no line.
|
||||
let args = json!({"file": "lib/leaf.sv", "line": 1, "dry_run": true});
|
||||
let (_, ports, _) = server.call("convert_ports", args);
|
||||
assert!(!ports.contains("diagnostics on"), "{ports}");
|
||||
if error {
|
||||
return text;
|
||||
}
|
||||
text.split(" file").next().unwrap().trim_start_matches("formatted ").to_string()
|
||||
}
|
||||
|
||||
fn formatted(files: &str) -> String {
|
||||
formatted_within(files, "")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_check_line_names_five_files_in_path_order_and_counts_the_rest() {
|
||||
let mut files: Vec<(String, String)> =
|
||||
vec![("z/leaf.sv".into(), "module leaf (input logic a);\nendmodule\n".into())];
|
||||
for (i, dir) in ["q", "B", "a", "a/b", "m", "a.x", "c"].iter().enumerate() {
|
||||
let text = format!("module u{i} (input logic a);\n leaf u_l (.a(a));\nendmodule\n");
|
||||
files.push((format!("{dir}/u{i}.sv"), text));
|
||||
}
|
||||
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
|
||||
let tree = Tree::with(&borrowed);
|
||||
let mut server = Session::over(&tree);
|
||||
let args = json!({"name": "leaf", "new_name": "leaf_r", "dry_run": true});
|
||||
let text = server.text("rename", args);
|
||||
// Byte order: `B` < `a.x` < `a/` (`.` < `/`) < `c` …; 8 files, 5 named.
|
||||
assert_eq!(
|
||||
last_line(&text),
|
||||
"check after writing: diagnostics on B/u1.sv, a.x/u5.sv, a/b/u3.sv, a/u2.sv, c/u6.sv and 3 more"
|
||||
);
|
||||
let text = server.text("rename", json!({"name": "leaf", "new_name": "leaf_r"}));
|
||||
assert!(text.ends_with("c/u6.sv and 3 more\n"), "{text}");
|
||||
fn qa_a_star_stays_in_one_component_and_a_double_star_spans_zero_or_more() {
|
||||
assert_eq!(formatted("ip/**/*.sv"), "4");
|
||||
assert_eq!(formatted_within("ip/*.sv", "ip/x.sv"), "1");
|
||||
assert_eq!(formatted("ip/ae?/*/*.sv"), "2");
|
||||
assert_eq!(formatted("**/rtl/**"), "2");
|
||||
assert_eq!(formatted("*.sv"), "no indexed file matches `*.sv`; nothing written.");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 5. The catalogue and the instructions.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_catalogue_and_instructions_stay_in_budget_and_name_real_tools() {
|
||||
let (_tree, mut server) = served();
|
||||
let instructions = server.init["result"]["instructions"].as_str().unwrap().to_string();
|
||||
assert!(instructions.chars().count() <= 900, "{} chars", instructions.chars().count());
|
||||
let reply = server.request("tools/list", json!({}));
|
||||
assert!(reply["result"].to_string().len() <= 18_000);
|
||||
let tools = reply["result"]["tools"].as_array().unwrap();
|
||||
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
|
||||
for word in words.filter(|w| w.contains('_') && *w != "dry_run") {
|
||||
assert!(names.contains(&word), "`{word}` in the instructions is no tool");
|
||||
}
|
||||
for bare in
|
||||
["outline", "definition", "references", "hierarchy", "format", "rename", "diagnostics"]
|
||||
{
|
||||
assert!(instructions.contains(bare) && names.contains(&bare), "{bare}");
|
||||
}
|
||||
for tool in tools {
|
||||
for (name, property) in tool["inputSchema"]["properties"].as_object().unwrap() {
|
||||
let described = property["description"].as_str().is_some_and(|d| !d.is_empty());
|
||||
assert!(described, "{}.{name} is documented", tool["name"]);
|
||||
}
|
||||
let takes_in = tool["inputSchema"]["properties"].get("in").is_some();
|
||||
let lists =
|
||||
["list_units", "search_symbols", "references", "hierarchy", "diagnostics", "defines"];
|
||||
assert_eq!(takes_in, lists.contains(&tool["name"].as_str().unwrap()), "{}", tool["name"]);
|
||||
let limit = &tool["inputSchema"]["properties"]["limit"]["description"];
|
||||
assert!(limit.is_null() || limit.as_str().unwrap().contains("500"), "{}", tool["name"]);
|
||||
}
|
||||
fn qa_a_bare_directory_means_everything_below_it_and_never_a_prefix() {
|
||||
assert_eq!(formatted_within("ip/aes", "ip/aes/"), "3");
|
||||
assert_eq!(formatted("ip/aes/"), "3");
|
||||
assert_eq!(formatted("lib"), "2");
|
||||
assert!(formatted("ip/ae").contains("`ip/ae`"), "a prefix of a name is no directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_glob_matches_paths_never_names_even_escaped_ones_holding_a_star() {
|
||||
assert_eq!(formatted("esc/*.sv"), "1");
|
||||
assert!(formatted("\\esc*mod").contains("\\esc*mod"), "a unit name is not a path");
|
||||
}
|
||||
@@ -1,430 +0,0 @@
|
||||
//! QA attacks on lane feedback-3 (`unit_interface`'s `template` and
|
||||
//! `hierarchy`'s `overrides` made opt-in, counted section headers),
|
||||
//! 2026-09-23.
|
||||
//!
|
||||
//! Every test spawns the real binary over a scratch tree, as a host would.
|
||||
//! The `OLD_*` literals are what the c2e42b8 binary (the tree before this
|
||||
//! lane, built from `git archive HEAD`) answered for the same calls, so
|
||||
//! "the opt-in is byte-identical to the old default" is pinned against the
|
||||
//! old binary's own bytes, not against a re-derivation.
|
||||
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A scratch tree holding the files a case writes; removed on drop.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
fn with(files: &[(&str, &str)]) -> Tree {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-qa-f3-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
for (name, text) in files {
|
||||
let path = dir.join(name);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
Tree(fs::canonicalize(dir).unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One running server, initialised.
|
||||
struct Session {
|
||||
child: Child,
|
||||
stdin: Option<ChildStdin>,
|
||||
lines: Receiver<String>,
|
||||
next_id: i64,
|
||||
/// The `initialize` reply.
|
||||
init: Value,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn over(tree: &Tree) -> Session {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(["--root", tree.0.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (send, lines) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
||||
if send.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let stdin = child.stdin.take().unwrap();
|
||||
let mut session =
|
||||
Session { child, stdin: Some(stdin), lines, next_id: 0, init: Value::Null };
|
||||
session.init = session
|
||||
.request("initialize", json!({"protocolVersion": "2025-06-18", "capabilities": {}}));
|
||||
session.send(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"}));
|
||||
session
|
||||
}
|
||||
|
||||
fn send(&mut self, message: &Value) {
|
||||
let stdin = self.stdin.as_mut().unwrap();
|
||||
writeln!(stdin, "{message}").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
}
|
||||
|
||||
fn request(&mut self, method: &str, params: Value) -> Value {
|
||||
self.next_id += 1;
|
||||
let id = self.next_id;
|
||||
self.send(&json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params}));
|
||||
let line = self.lines.recv_timeout(ANSWER_TIMEOUT).expect("the server answered");
|
||||
let reply: Value = serde_json::from_str(&line).unwrap();
|
||||
assert_eq!(reply["id"], id);
|
||||
reply
|
||||
}
|
||||
|
||||
/// A tool call: whether it was refused, its text, its structured content.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let result = &reply["result"];
|
||||
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
|
||||
(result["isError"] == true, text, result["structuredContent"].clone())
|
||||
}
|
||||
|
||||
/// A call that must answer; its text and structured content.
|
||||
fn ok(&mut self, tool: &str, arguments: Value) -> (String, Value) {
|
||||
let (error, text, structured) = self.call(tool, arguments.clone());
|
||||
assert!(!error, "{tool} {arguments}: refused: {text}");
|
||||
(text, structured)
|
||||
}
|
||||
|
||||
/// A call that must be refused; its text.
|
||||
fn refused(&mut self, tool: &str, arguments: Value) -> String {
|
||||
let (error, text, _) = self.call(tool, arguments.clone());
|
||||
assert!(error, "{tool} {arguments}: answered: {text}");
|
||||
text
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The tree: an interface with modports, a module with `ifdef'd lists (so
|
||||
// it has warnings), an empty module, a parameter-only module, a module of
|
||||
// multi-declarator and unpacked ports, a program, and instances whose
|
||||
// overrides are long (over the 200-byte cap), absent, and commented.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
fn long_overrides() -> String {
|
||||
format!(".A({}), .B({})", "1".repeat(96), "2".repeat(118))
|
||||
}
|
||||
|
||||
fn tree() -> Tree {
|
||||
let user2 = format!(
|
||||
"module user2 (input logic clk);\n leaf2 #({}) u_long (.clk(clk));\n leaf2 u_plain (.clk(clk));\n leaf2 #(.A(1) /* #( in a comment */) u_c (.clk(clk));\nendmodule\n",
|
||||
long_overrides()
|
||||
);
|
||||
let leaf2 =
|
||||
"module leaf2 #(parameter int A = 1, parameter int B = 2) (input logic clk);\nendmodule\n";
|
||||
Tree::with(&[
|
||||
(
|
||||
"bus.sv",
|
||||
"interface bus #(parameter int W = 8) (input logic clk);\n logic [W-1:0] data;\n logic valid;\n modport mst (output data, valid);\n modport slv (input data, valid);\nendinterface\n",
|
||||
),
|
||||
(
|
||||
"dirs.sv",
|
||||
"module dirs #(parameter int W = 1\n`ifdef X\n , parameter int V = 3\n`endif\n) (input logic a\n`ifdef X\n , output logic b\n`endif\n);\nendmodule\n",
|
||||
),
|
||||
("nothing.sv", "module nothing;\nendmodule\n"),
|
||||
("onlyp.sv", "module onlyp #(parameter int W = 1, parameter int D = 2);\nendmodule\n"),
|
||||
("np.sv", "module np (input logic a, b, output logic [3:0] y [2]);\nendmodule\n"),
|
||||
("prog.sv", "program prog (input logic clk);\nendprogram\n"),
|
||||
("pkg.sv", "package pkg;\n parameter int P = 1;\n typedef logic [3:0] nib_t;\nendpackage\n"),
|
||||
("leaf2.sv", leaf2),
|
||||
("user2.sv", user2.as_str()),
|
||||
])
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 1. `unit_interface`: the template, opt-in and byte-identical.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What c2e42b8 answered for `unit_interface` (no flag existed then).
|
||||
const OLD_UNITS: &[(&str, &str)] = &[
|
||||
(
|
||||
"bus",
|
||||
"interface bus bus.sv:1\nparameters:\n W = 8\nports:\n input logic clk\nmodports:\n mst (output data, valid)\n slv (input data, valid)\ntemplate:\nbus #(\n .W(8)\n) u_bus (\n .clk(clk)\n);\n",
|
||||
),
|
||||
(
|
||||
"dirs",
|
||||
"module dirs dirs.sv:1\nparameters:\n W = 1\n V = 3\nports:\n input logic a\n output logic b\nwarning: `dirs`'s port list carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm.\nwarning: `dirs`'s parameter list carries compiler directives, so what it declares depends on the configuration; the skeleton names every entry written, from every `ifdef arm.\ntemplate:\ndirs #(\n .W(1),\n .V(3)\n) u_dirs (\n .a(a),\n .b(b)\n);\n",
|
||||
),
|
||||
("nothing", "module nothing nothing.sv:1\ntemplate:\nnothing u_nothing ();\n"),
|
||||
(
|
||||
"np",
|
||||
"module np np.sv:1\nports:\n input logic a\n input logic b\n output logic [3:0] y [2]\ntemplate:\nnp u_np (\n .a(a),\n .b(b),\n .y(y)\n);\n",
|
||||
),
|
||||
];
|
||||
|
||||
/// The old text with this lane's counted headers: the only change the
|
||||
/// opt-in answer may carry.
|
||||
fn counted(old: &str, parameters: usize, ports: usize) -> String {
|
||||
old.replace("\nparameters:\n", &format!("\nparameters ({parameters}):\n"))
|
||||
.replace("\nports:\n", &format!("\nports ({ports}):\n"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_template_true_is_the_old_answer_byte_for_byte_and_the_default_stops_before_it() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
for (name, old) in OLD_UNITS {
|
||||
let (with, full) = s.ok("unit_interface", json!({"name": name, "template": true}));
|
||||
let parameters = full["parameters"].as_array().unwrap().len();
|
||||
let ports = full["ports"].as_array().unwrap().len();
|
||||
let expected = counted(old, parameters, ports);
|
||||
assert_eq!(with, expected, "{name}");
|
||||
let old_template = &old[old.find("template:\n").unwrap() + "template:\n".len()..];
|
||||
assert_eq!(format!("{}\n", full["template"].as_str().unwrap()), old_template, "{name}");
|
||||
|
||||
let (plain, bare) = s.ok("unit_interface", json!({"name": name}));
|
||||
assert_eq!(plain, expected[..expected.find("template:\n").unwrap()], "{name}");
|
||||
assert!(!plain.contains("template"), "{name}: {plain}");
|
||||
let object = bare.as_object().unwrap();
|
||||
assert!(!object.contains_key("template"), "{name}: no key, not null: {bare}");
|
||||
let mut stripped = full.clone();
|
||||
stripped.as_object_mut().unwrap().remove("template");
|
||||
assert_eq!(stripped, bare, "{name}: the JSON differs only by `template`");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_program_is_instantiable_and_a_package_ignores_the_flag() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
let (plain, bare) = s.ok("unit_interface", json!({"name": "prog"}));
|
||||
assert_eq!(plain, "program prog prog.sv:1\nports (1):\n input logic clk\n");
|
||||
assert!(bare.get("template").is_none());
|
||||
let (with, _) = s.ok("unit_interface", json!({"name": "prog", "template": true}));
|
||||
assert!(with.ends_with("template:\nprog u_prog (\n .clk(clk)\n);\n"), "{with}");
|
||||
|
||||
let package = s.ok("unit_interface", json!({"name": "pkg"}));
|
||||
let flagged = s.ok("unit_interface", json!({"name": "pkg", "template": true}));
|
||||
assert_eq!(package, flagged);
|
||||
assert!(package.0.contains("members:\n"), "{}", package.0);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 2. The counted headers.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// The rows under `header` in `text`: the indented lines that follow it.
|
||||
fn rows_under(text: &str, header: &str) -> Option<usize> {
|
||||
let start = text.find(&format!("\n{header}"))? + 1;
|
||||
let body = &text[start..];
|
||||
Some(body.lines().skip(1).take_while(|line| line.starts_with(" ")).count())
|
||||
}
|
||||
|
||||
/// The count a header like `ports (12):` carries.
|
||||
fn header_count(text: &str, section: &str) -> Option<usize> {
|
||||
let at = text.find(&format!("\n{section} ("))? + section.len() + 3;
|
||||
text[at..].split(')').next()?.parse().ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_every_header_count_equals_its_rows_and_the_json_and_an_empty_section_has_no_header() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
let expected: &[(&str, usize, usize)] =
|
||||
&[("bus", 1, 1), ("dirs", 2, 2), ("nothing", 0, 0), ("onlyp", 2, 0), ("np", 0, 3)];
|
||||
for (name, parameters, ports) in expected {
|
||||
let (text, json) = s.ok("unit_interface", json!({"name": name}));
|
||||
for (section, want, key) in
|
||||
[("parameters", parameters, "parameters"), ("ports", ports, "ports")]
|
||||
{
|
||||
assert_eq!(json[key].as_array().unwrap().len(), *want, "{name}.{key}");
|
||||
if *want == 0 {
|
||||
// An empty section is left out, as before the lane: no `(0)`.
|
||||
assert!(!text.contains(&format!("{section} (")), "{name}: {text}");
|
||||
assert!(!text.contains(&format!("{section}:")), "{name}: {text}");
|
||||
} else {
|
||||
assert_eq!(header_count(&text, section), Some(*want), "{name}: {text}");
|
||||
let header = format!("{section} ({want}):\n");
|
||||
assert_eq!(rows_under(&text, &header), Some(*want), "{name}: {text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// The modports header keeps no count; its rows are still all there.
|
||||
let (bus, json) = s.ok("unit_interface", json!({"name": "bus"}));
|
||||
assert!(bus.contains("\nmodports:\n"), "{bus}");
|
||||
assert_eq!(rows_under(&bus, "modports:\n"), Some(2));
|
||||
assert_eq!(json["modports"].as_array().unwrap().len(), 2);
|
||||
// A parameter-only module's answer ends at its last parameter.
|
||||
let (onlyp, _) = s.ok("unit_interface", json!({"name": "onlyp"}));
|
||||
assert_eq!(onlyp, "module onlyp onlyp.sv:1\nparameters (2):\n W = 1\n D = 2\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 3. `hierarchy`: the overrides, opt-in on the text, always in the JSON.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// What c2e42b8 answered: overrides on every text line, capped at 200.
|
||||
fn old_up() -> String {
|
||||
let capped: String = format!("#({}", long_overrides()).chars().take(200).collect();
|
||||
format!(
|
||||
"3 instantiations\nleaf2 leaf2.sv:1\n user2.u_long {capped}… user2.sv:2\n user2.u_plain user2.sv:3\n user2.u_c #(.A(1) ) user2.sv:4\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn old_down() -> String {
|
||||
let capped: String = format!("#({}", long_overrides()).chars().take(200).collect();
|
||||
format!(
|
||||
"4 nodes\nuser2 user2.sv:1\n u_long : leaf2 {capped}…\n u_plain : leaf2\n u_c : leaf2 #(.A(1) )\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_overrides_true_is_the_old_text_and_the_default_drops_only_the_segment() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
let cases = [
|
||||
(json!({"root": "leaf2", "direction": "up"}), old_up()),
|
||||
(json!({"root": "user2"}), old_down()),
|
||||
];
|
||||
for (args, old) in cases {
|
||||
let mut asked = args.clone();
|
||||
asked["overrides"] = json!(true);
|
||||
let (with, with_json) = s.ok("hierarchy", asked);
|
||||
assert_eq!(with, old, "{args}");
|
||||
let (plain, plain_json) = s.ok("hierarchy", args.clone());
|
||||
assert_eq!(plain_json, with_json, "{args}: the JSON ignores the flag");
|
||||
assert!(!plain.contains("#("), "{args}: {plain}");
|
||||
assert!(!plain.contains('…'), "{args}: {plain}");
|
||||
// Line for line, the default is the old line minus ` #(…)`, the
|
||||
// segment being the node's JSON `overrides` as the old line capped it.
|
||||
let nodes = with_json["nodes"].as_array().unwrap();
|
||||
assert_eq!(plain.lines().count(), nodes.len() + 1, "{args}: count line + nodes");
|
||||
for ((short, long), node) in plain.lines().zip(with.lines()).skip(1).zip(nodes) {
|
||||
let expected = match node["overrides"].as_str() {
|
||||
None => long.to_string(),
|
||||
Some(full) if full.chars().count() > 200 => {
|
||||
let capped: String = full.chars().take(200).collect();
|
||||
long.replacen(&format!(" {capped}…"), "", 1)
|
||||
}
|
||||
Some(full) => long.replacen(&format!(" {full}"), "", 1),
|
||||
};
|
||||
assert_eq!(short, expected, "{long}");
|
||||
}
|
||||
// Every node carries `overrides`, uncapped in full where the site has one.
|
||||
for node in with_json["nodes"].as_array().unwrap() {
|
||||
assert!(node.as_object().unwrap().contains_key("overrides"), "{node}");
|
||||
}
|
||||
let full = format!("#({})", long_overrides());
|
||||
assert!(with_json["nodes"].as_array().unwrap().iter().any(|n| n["overrides"] == full));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_overrides_hold_under_paging_the_in_glob_and_depth() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
let windows = [
|
||||
json!({"root": "leaf2", "direction": "up", "limit": 1, "offset": 1}),
|
||||
json!({"root": "leaf2", "direction": "up", "in": "user2.sv"}),
|
||||
json!({"root": "leaf2", "direction": "up", "depth": 1}),
|
||||
json!({}),
|
||||
];
|
||||
for args in windows {
|
||||
let (plain, plain_json) = s.ok("hierarchy", args.clone());
|
||||
let mut asked = args.clone();
|
||||
asked["overrides"] = json!(true);
|
||||
let (with, with_json) = s.ok("hierarchy", asked);
|
||||
assert_eq!(plain_json, with_json, "{args}");
|
||||
assert!(!plain.contains("#("), "{args}: {plain}");
|
||||
assert_eq!(plain.lines().next(), with.lines().next(), "{args}: the count line");
|
||||
assert_eq!(plain.lines().count(), with.lines().count(), "{args}");
|
||||
}
|
||||
let (page, _) = s.ok(
|
||||
"hierarchy",
|
||||
json!({"root": "leaf2", "direction": "up", "limit": 1, "offset": 1, "overrides": true}),
|
||||
);
|
||||
assert!(page.contains(" user2.u_plain user2.sv:3\n"), "{page}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 4. The arguments and the catalogue.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_a_non_boolean_flag_is_refused_naming_the_field_and_null_means_the_default() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
for bad in [json!("true"), json!(1), json!([true]), json!({})] {
|
||||
let why = s.refused("unit_interface", json!({"name": "np", "template": bad}));
|
||||
assert!(why.contains("`template`") && why.contains("true or false"), "{why}");
|
||||
let why = s.refused("hierarchy", json!({"root": "user2", "overrides": bad}));
|
||||
assert!(why.contains("`overrides`") && why.contains("true or false"), "{why}");
|
||||
}
|
||||
// `null` is taken as absent, as for every other flag.
|
||||
let plain = s.ok("unit_interface", json!({"name": "np"}));
|
||||
assert_eq!(s.ok("unit_interface", json!({"name": "np", "template": null})), plain);
|
||||
let plain = s.ok("hierarchy", json!({"root": "user2"}));
|
||||
assert_eq!(s.ok("hierarchy", json!({"root": "user2", "overrides": null})), plain);
|
||||
// The flag belongs to its own tool only.
|
||||
let why = s.refused("hierarchy", json!({"root": "user2", "template": true}));
|
||||
assert!(why.contains("`template`"), "{why}");
|
||||
let why = s.refused("unit_interface", json!({"name": "np", "overrides": true}));
|
||||
assert!(why.contains("`overrides`"), "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_catalogue_offers_both_flags_as_optional_booleans_and_stays_small() {
|
||||
let tree = tree();
|
||||
let mut s = Session::over(&tree);
|
||||
let reply = s.request("tools/list", json!({}));
|
||||
let size = reply["result"].to_string().len();
|
||||
assert!(size <= 18_000, "tools/list is {size} bytes");
|
||||
let tools = reply["result"]["tools"].as_array().unwrap();
|
||||
for (tool, flag) in [("unit_interface", "template"), ("hierarchy", "overrides")] {
|
||||
let entry = tools.iter().find(|t| t["name"] == tool).unwrap();
|
||||
let schema = &entry["inputSchema"];
|
||||
assert_eq!(schema["properties"][flag]["type"], "boolean", "{tool}.{flag}");
|
||||
let required = schema["required"].as_array().cloned().unwrap_or_default();
|
||||
assert!(!required.contains(&json!(flag)), "{tool}.{flag} is optional");
|
||||
}
|
||||
let unit = tools.iter().find(|t| t["name"] == "unit_interface").unwrap();
|
||||
assert!(unit["description"].as_str().unwrap().contains("`template: true`"));
|
||||
let hierarchy = tools.iter().find(|t| t["name"] == "hierarchy").unwrap();
|
||||
assert!(!hierarchy["description"].as_str().unwrap().contains("#("), "no longer promised");
|
||||
|
||||
let instructions = s.init["result"]["instructions"].as_str().unwrap();
|
||||
assert!(instructions.chars().count() <= 900, "{}", instructions.chars().count());
|
||||
assert!(instructions.contains("overrides: true"), "{instructions}");
|
||||
assert!(!instructions.contains("(instances, overrides)"), "{instructions}");
|
||||
let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect();
|
||||
let words = instructions.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
|
||||
for word in words.filter(|w| w.contains('_') && *w != "dry_run") {
|
||||
assert!(names.contains(&word), "the instructions name `{word}`, which is not a tool");
|
||||
}
|
||||
}
|
||||
+161
-268
@@ -254,11 +254,12 @@ fn qa_ten_megabyte_lines_are_answered_and_the_next_line_still_is() {
|
||||
let mut s = Session::ready(&scratch);
|
||||
let big_query = "q".repeat(10 * 1024 * 1024);
|
||||
let big_call = json!({"jsonrpc":"2.0","id":"big","method":"tools/call",
|
||||
"params":{"name":"search_symbols","arguments":{"query": big_query}}});
|
||||
"params":{"name":"find","arguments":{"name": big_query}}});
|
||||
s.send(&big_call.to_string());
|
||||
let reply = s.receive();
|
||||
assert_eq!(reply["id"], "big");
|
||||
assert_eq!(reply["result"]["isError"], false);
|
||||
let said = reply["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(said.starts_with("no declaration named `qqq"), "an answer, not a fault");
|
||||
s.send(&"z".repeat(10 * 1024 * 1024));
|
||||
let reply = s.receive();
|
||||
assert_eq!(reply["error"]["code"], -32700);
|
||||
@@ -275,9 +276,8 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() {
|
||||
}
|
||||
assert!(s.pings());
|
||||
s.initialize();
|
||||
// M2 added five tools (defines, definition, references, hierarchy,
|
||||
// diagnostics) to M1's six; M3 added twelve edit tools; M4 three more.
|
||||
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 26);
|
||||
// The lean catalogue: nine tools (PLAN §10.1).
|
||||
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -296,16 +296,16 @@ fn qa_an_unsupported_protocol_version_is_offered_our_newest() {
|
||||
fn qa_bad_tool_arguments_are_tool_errors_that_name_the_field() {
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let missing = s.refusal("read_item", json!({"file": "x.sv"}));
|
||||
let missing = s.refusal("read", json!({"file": "x.sv"}));
|
||||
assert!(missing.contains("`item`"), "{missing}");
|
||||
let extra = s.refusal("outline", json!({"file": "x.sv", "verbose": true}));
|
||||
assert!(extra.contains("`verbose`"), "{extra}");
|
||||
let wrong = s.refusal("outline", json!({"file": 7}));
|
||||
assert!(wrong.contains("`file`") && wrong.contains("string"), "{wrong}");
|
||||
let float = s.refusal("list_units", json!({"limit": 2.5}));
|
||||
assert!(float.contains("`limit`"), "{float}");
|
||||
let kind = s.refusal("list_units", json!({"kind": "struct"}));
|
||||
assert!(kind.contains("`kind`"), "{kind}");
|
||||
let float = s.refusal("hierarchy", json!({"root": "x", "depth": 2.5}));
|
||||
assert!(float.contains("`depth`"), "{float}");
|
||||
let op = s.refusal("edit_item", json!({"file": "x.sv", "op": "struct", "item": "y"}));
|
||||
assert!(op.contains("`op`"), "{op}");
|
||||
// An envelope the method cannot read at all stays a protocol error.
|
||||
let reply = s.request("tools/call", json!({"name": "outline", "arguments": [1]}));
|
||||
assert_eq!(reply["error"]["code"], -32602);
|
||||
@@ -382,13 +382,13 @@ fn qa_stdout_carries_only_json_lines_even_under_verbose() {
|
||||
input.push_str(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
|
||||
input.push('\n');
|
||||
let calls = [
|
||||
json!({"name": "project_overview", "arguments": {}}),
|
||||
json!({"name": "list_units", "arguments": {}}),
|
||||
json!({"name": "unit_interface", "arguments": {"name": "a"}}),
|
||||
json!({"name": "hierarchy", "arguments": {}}),
|
||||
json!({"name": "find", "arguments": {"name": "a", "refs": true}}),
|
||||
json!({"name": "outline", "arguments": {"unit": "a"}}),
|
||||
json!({"name": "outline", "arguments": {"file": "b.sv"}}),
|
||||
json!({"name": "outline", "arguments": {"file": "bad.sv"}}),
|
||||
json!({"name": "read_item", "arguments": {"file": "a.sv", "item": "u_b"}}),
|
||||
json!({"name": "search_symbols", "arguments": {"query": ""}}),
|
||||
json!({"name": "read", "arguments": {"file": "a.sv", "item": "u_b"}}),
|
||||
json!({"name": "check", "arguments": {}}),
|
||||
];
|
||||
for (at, call) in calls.iter().enumerate() {
|
||||
let line = json!({"jsonrpc":"2.0","id": at + 2,"method":"tools/call","params": call});
|
||||
@@ -423,20 +423,17 @@ fn qa_an_invalid_request_with_a_readable_id_keeps_that_id() {
|
||||
// --------------------------------------------------------------- rendering
|
||||
|
||||
#[test]
|
||||
fn qa_an_escaped_identifier_unit_is_listed_described_and_instantiable() {
|
||||
fn qa_an_escaped_identifier_unit_is_found_outlined_and_read() {
|
||||
let scratch = Scratch::with(&[(
|
||||
"esc.sv",
|
||||
"module \\my-mod (input logic [7:0] a [0:3], output logic b);\nendmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert!(s.text("list_units", json!({})).contains("module \\my-mod 1"));
|
||||
// feedback-3: the template is opt-in.
|
||||
let answer = s.text("unit_interface", json!({"name": "\\my-mod", "template": true}));
|
||||
assert!(answer.starts_with("module \\my-mod esc.sv:1\n"), "{answer}");
|
||||
// The template must still be legal: an escaped name ends at whitespace.
|
||||
assert!(answer.contains("\\my-mod \\u_my-mod ("), "{answer}");
|
||||
let item = s.text("read_item", json!({"file": "esc.sv", "item": "\\my-mod"}));
|
||||
assert!(item.starts_with("esc.sv:1-2\nmodule \\my-mod (input"), "{item}");
|
||||
assert_eq!(s.text("find", json!({"name": "\\my-mod"})), "module \\my-mod esc.sv:1\n");
|
||||
let answer = s.text("outline", json!({"unit": "\\my-mod"}));
|
||||
assert!(answer.starts_with("esc.sv:1\ninput logic [7:0] a [0:3]\n"), "{answer}");
|
||||
let item = s.text("read", json!({"file": "esc.sv", "item": "\\my-mod"}));
|
||||
assert!(item.starts_with("esc.sv:1–2\nmodule \\my-mod (input"), "{item}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -446,14 +443,10 @@ fn qa_packed_and_unpacked_ranges_are_both_reported() {
|
||||
"module hp (input logic [7:0] a [0:3], output logic [3:0][1:0] b [2][0:1]);\nendmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("unit_interface", json!({"name": "hp"}));
|
||||
let ports = &result["structuredContent"]["ports"];
|
||||
assert_eq!(ports[0]["range"], "[7:0]");
|
||||
assert_eq!(ports[0]["unpacked"], "[0:3]");
|
||||
assert_eq!(ports[1]["range"], "[3:0][1:0]");
|
||||
assert_eq!(ports[1]["unpacked"], "[2][0:1]");
|
||||
let text = result["content"][0]["text"].as_str().unwrap();
|
||||
assert!(text.contains("input logic [7:0] a [0:3]"), "{text}");
|
||||
assert_eq!(
|
||||
s.text("outline", json!({"unit": "hp"})),
|
||||
"hp.sv:1\ninput logic [7:0] a [0:3]\noutput logic [3:0][1:0] b [2][0:1]\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -463,32 +456,29 @@ fn qa_a_typed_parameter_keeps_its_default_and_a_localparam_is_not_offered() {
|
||||
"module tp #(parameter type T = logic [3:0], parameter int unsigned N = 4,\n localparam int L = 2) (input T a);\nendmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("unit_interface", json!({"name": "tp", "template": true}));
|
||||
let params = &result["structuredContent"]["parameters"];
|
||||
assert_eq!(
|
||||
params,
|
||||
&json!([{"name": "T", "default": "logic [3:0]"}, {"name": "N", "default": "4"}])
|
||||
s.text("outline", json!({"unit": "tp"})),
|
||||
"tp.sv:1\nparam T = logic [3:0]\nparam N = 4\ninput T a\n"
|
||||
);
|
||||
assert!(result["structuredContent"]["template"].as_str().unwrap().contains(".T(logic [3:0])"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_crlf_files_keep_their_line_numbers_and_read_item_returns_the_exact_bytes() {
|
||||
fn qa_crlf_files_keep_their_line_numbers_and_read_returns_the_exact_bytes() {
|
||||
let text = "// head\r\nmodule crlf (\r\n input logic clk,\r\n output logic q\r\n);\r\n logic x;\r\n always_ff @(posedge clk)\r\n q <= x;\r\nendmodule\r\n";
|
||||
let scratch = Scratch::with(&[("crlf.sv", text)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let outline = s.text("outline", json!({"file": "crlf.sv"}));
|
||||
assert_eq!(
|
||||
outline,
|
||||
"4 entries\ncrlf.sv\n module crlf 2-9\n port clk 3\n port q 4\n var x 6\n"
|
||||
s.text("outline", json!({"file": "crlf.sv"})),
|
||||
"module crlf 2–9\n port clk 3\n port q 4\n var x 6\n"
|
||||
);
|
||||
let result = s.call("read_item", json!({"file": "crlf.sv", "item": "always@8"}));
|
||||
assert_eq!(result["structuredContent"]["lines"], json!([7, 8]));
|
||||
assert_eq!(result["structuredContent"]["text"], "always_ff @(posedge clk)\r\n q <= x;");
|
||||
let module = s.call("read_item", json!({"file": "crlf.sv", "item": "crlf"}));
|
||||
assert_eq!(
|
||||
s.text("read", json!({"file": "crlf.sv", "item": "always@8"})),
|
||||
"crlf.sv:7–8\nalways_ff @(posedge clk)\r\n q <= x;\n"
|
||||
);
|
||||
let module = s.text("read", json!({"file": "crlf.sv", "item": "crlf"}));
|
||||
let start = text.find("module").unwrap();
|
||||
assert_eq!(module["structuredContent"]["text"], &text[start..text.len() - 2]);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\ncrlf.sv\n module crlf 2\n");
|
||||
assert_eq!(module, format!("crlf.sv:2–9\n{}\n", &text[start..text.len() - 2]));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\ncrlf crlf.sv:2\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -498,14 +488,11 @@ fn qa_multibyte_text_before_an_item_keeps_lines_right() {
|
||||
"// été ünïcode 日本語\nmodule utf (input logic a); /* é */ logic z;\n /* 日本 */ logic w;\nendmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let outline = s.text("outline", json!({"file": "utf.sv"}));
|
||||
assert_eq!(
|
||||
outline,
|
||||
"4 entries\nutf.sv\n module utf 2-4\n port a 2\n var z 2\n var w 3\n"
|
||||
s.text("outline", json!({"file": "utf.sv"})),
|
||||
"module utf 2–4\n port a 2\n var z 2\n var w 3\n"
|
||||
);
|
||||
let w = s.call("read_item", json!({"file": "utf.sv", "item": "w"}));
|
||||
assert_eq!(w["structuredContent"]["text"], "logic w;");
|
||||
assert_eq!(w["structuredContent"]["lines"], json!([3, 3]));
|
||||
assert_eq!(s.text("read", json!({"file": "utf.sv", "item": "w"})), "utf.sv:3\nlogic w;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -515,13 +502,16 @@ fn qa_a_module_declared_in_two_files_is_refused_naming_both() {
|
||||
("sub/d2.sv", "// two\nmodule dup (input a); endmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let refusal = s.refusal("unit_interface", json!({"name": "dup"}));
|
||||
let refusal = s.refusal("outline", json!({"unit": "dup"}));
|
||||
assert!(refusal.contains("d1.sv:1") && refusal.contains("sub/d2.sv:2"), "{refusal}");
|
||||
let picked = s.text("unit_interface", json!({"name": "dup", "file": "sub/d2.sv"}));
|
||||
assert!(picked.contains("input a"), "{picked}");
|
||||
// Listed once each, and a top module is named once.
|
||||
let overview = s.call("project_overview", json!({}));
|
||||
assert_eq!(overview["structuredContent"]["top_modules"], json!(["dup"]));
|
||||
assert!(s.text("outline", json!({"file": "sub/d2.sv"})).contains("port a 2"));
|
||||
let read = s.refusal("read", json!({"item": "dup"}));
|
||||
assert!(read.contains("d1.sv:1") && read.contains("sub/d2.sv:2"), "{read}");
|
||||
// Each declaration is a top of its own, at its own line.
|
||||
assert_eq!(
|
||||
s.text("hierarchy", json!({})),
|
||||
"2 files, 2 modules, 2 top\ndup d1.sv:1\ndup sub/d2.sv:2\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -531,56 +521,12 @@ fn qa_a_name_declared_twice_in_one_file_is_refused_with_both_spellings() {
|
||||
"module twice; logic w; endmodule\nmodule other;\n logic w;\nendmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let refusal = s.refusal("read_item", json!({"file": "w.sv", "item": "w"}));
|
||||
let refusal = s.refusal("read", json!({"file": "w.sv", "item": "w"}));
|
||||
assert!(refusal.contains("var:w@1") && refusal.contains("var:w@3"), "{refusal}");
|
||||
assert_eq!(
|
||||
s.call("read_item", json!({"file": "w.sv", "item": "w@3"}))["structuredContent"]["text"],
|
||||
"logic w;"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_list_units_glob_question_mark_is_exactly_one_character() {
|
||||
let scratch = Scratch::with(&[(
|
||||
"g.sv",
|
||||
"module dup; endmodule\nmodule dp; endmodule\nmodule duup; endmodule\nmodule d_p; endmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("list_units", json!({"glob": "d?p"}));
|
||||
let names: Vec<&str> = result["structuredContent"]["units"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|u| u["name"].as_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(names, vec!["dup", "d_p"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_outline_depth_zero_is_refused_and_a_huge_limit_is_fine() {
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let refusal = s.refusal("outline", json!({"file": "x.sv", "depth": 0}));
|
||||
assert!(refusal.contains("`depth`"), "{refusal}");
|
||||
let all = s.call("outline", json!({"file": "x.sv", "limit": i64::MAX, "offset": 0}));
|
||||
assert_eq!(all["structuredContent"]["total"], 3);
|
||||
let past = s.call("outline", json!({"file": "x.sv", "offset": i64::MAX}));
|
||||
assert_eq!(past["structuredContent"]["symbols"], json!([]));
|
||||
let top = s.call("outline", json!({"file": "x.sv", "depth": 1}));
|
||||
assert_eq!(top["structuredContent"]["symbols"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_search_symbols_with_an_empty_query_matches_everything_and_pages() {
|
||||
let scratch = Scratch::with(&[
|
||||
("a.sv", "module a (input p, input q); endmodule\n"),
|
||||
("b.sv", "package b; parameter int K = 1; endpackage\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let all = s.call("search_symbols", json!({"query": ""}));
|
||||
assert_eq!(all["structuredContent"]["total"], 5);
|
||||
let page = s.call("search_symbols", json!({"query": "", "limit": 2}));
|
||||
assert!(page["content"][0]["text"].as_str().unwrap().ends_with("… and 3 more\n"));
|
||||
assert_eq!(s.text("read", json!({"file": "w.sv", "item": "w@3"})), "w.sv:3\nlogic w;\n");
|
||||
let design = s.refusal("read", json!({"item": "w"}));
|
||||
assert!(design.contains("w.sv:1, w.sv:3"), "{design}");
|
||||
assert_eq!(s.text("read", json!({"item": "w@3"})), "w.sv:3\nlogic w;\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -592,12 +538,9 @@ fn qa_a_class_reports_its_own_base_not_a_same_named_class_s() {
|
||||
("c.sv", "class c; int top_member; endclass\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let p1 = s.call("unit_interface", json!({"name": "p1::c"}));
|
||||
assert_eq!(p1["structuredContent"]["extends"], "base1");
|
||||
let p2 = s.call("unit_interface", json!({"name": "p2::c"}));
|
||||
assert_eq!(p2["structuredContent"]["extends"], "base2", "{p2}");
|
||||
let top = s.call("unit_interface", json!({"name": "c"}));
|
||||
assert_eq!(top["structuredContent"]["extends"], Value::Null, "{top}");
|
||||
assert_eq!(s.text("outline", json!({"unit": "p1::c"})), "p1.sv:2\nextends base1\nvar a 2\n");
|
||||
assert_eq!(s.text("outline", json!({"unit": "p2::c"})), "p2.sv:2\nextends base2\nvar b 2\n");
|
||||
assert_eq!(s.text("outline", json!({"unit": "c"})), "c.sv:1\nvar top_member 1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -607,32 +550,19 @@ fn qa_two_same_named_classes_in_one_file_do_not_share_members() {
|
||||
"package p1; class c; int a; endclass endpackage\npackage p2; class c; int b; endclass endpackage\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let p1 = s.call("unit_interface", json!({"name": "p1::c"}));
|
||||
assert_eq!(
|
||||
p1["structuredContent"]["members"],
|
||||
json!([{"name": "a", "kind": "var", "line": 1}])
|
||||
);
|
||||
let p2 = s.call("unit_interface", json!({"name": "p2::c"}));
|
||||
assert_eq!(
|
||||
p2["structuredContent"]["members"],
|
||||
json!([{"name": "b", "kind": "var", "line": 2}])
|
||||
);
|
||||
assert_eq!(s.text("outline", json!({"unit": "p1::c"})), "pk.sv:1\nvar a 1\n");
|
||||
assert_eq!(s.text("outline", json!({"unit": "p2::c"})), "pk.sv:2\nvar b 2\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_columns_are_counted_in_one_unit_across_tools() {
|
||||
// `outline` reports this parse error at 1:28 — byte columns, `é` = 2.
|
||||
// In the same unit `pe` starts at column 17; search_symbols says 16
|
||||
// (UTF-16 units). Either unit is defensible; two in one server are not.
|
||||
// A parse error after `é` is at byte column 28; `find` prints a line
|
||||
// and no column at all (the lead's ruling on M1 finding 4).
|
||||
let scratch = Scratch::with(&[("pe.sv", "/* é */ module pe; assign = ; endmodule\n")]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let outline = s.call("outline", json!({"file": "pe.sv"}));
|
||||
assert_eq!(outline["structuredContent"]["parse_errors"][0]["col"], 28);
|
||||
// Lead's ruling on finding 4: one unit, 1-based bytes, and
|
||||
// search_symbols prints no column at all (a line, like a member hit).
|
||||
let hit = s.call("search_symbols", json!({"query": "pe"}));
|
||||
assert_eq!(hit["structuredContent"]["symbols"][0]["line"], 1, "{hit}");
|
||||
assert_eq!(hit["structuredContent"]["symbols"][0].get("col"), None, "{hit}");
|
||||
let check = s.text("check", json!({"file": "pe.sv"}));
|
||||
assert!(check.starts_with("pe.sv:1:28 error "), "{check}");
|
||||
assert_eq!(s.text("find", json!({"name": "pe"})), "module pe pe.sv:1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -642,44 +572,45 @@ fn qa_an_escaped_name_holding_at_or_colon_is_selectable_by_itself() {
|
||||
"module \\a@b (input z); endmodule\nmodule \\k:l (input z); endmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let at = s.text("read_item", json!({"file": "weird.sv", "item": "\\a@b"}));
|
||||
let at = s.text("read", json!({"file": "weird.sv", "item": "\\a@b"}));
|
||||
assert!(at.starts_with("weird.sv:1\nmodule \\a@b "), "{at}");
|
||||
let colon = s.text("read_item", json!({"file": "weird.sv", "item": "\\k:l"}));
|
||||
let colon = s.text("read", json!({"file": "weird.sv", "item": "\\k:l"}));
|
||||
assert!(colon.starts_with("weird.sv:2\nmodule \\k:l "), "{colon}");
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------- freshness
|
||||
//
|
||||
// A by-name hit does not walk; a miss walks once. So a hit on the new name
|
||||
// proves the stat sweep saw the change: were it missed, the miss's walk
|
||||
// would not re-read a file whose stamp looks unchanged either.
|
||||
|
||||
#[test]
|
||||
fn qa_rename_then_recreate_in_the_same_mtime_second_is_seen() {
|
||||
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n");
|
||||
assert_eq!(s.text("find", json!({"name": "alpha"})), "module alpha a.sv:1\n");
|
||||
let old = mtime(&scratch.path("a.sv"));
|
||||
fs::rename(scratch.path("a.sv"), scratch.path("b.sv")).unwrap();
|
||||
scratch.write("a.sv", b"module gamma; endmodule\n");
|
||||
// A filesystem with one-second mtimes would show the same stamp.
|
||||
set_mtime(&scratch.path("a.sv"), old);
|
||||
let units = s.text("list_units", json!({}));
|
||||
assert!(units.contains("module gamma 1") && !units.contains("a.sv\n module alpha"), "{units}");
|
||||
let item = s.text("read_item", json!({"file": "a.sv", "item": "gamma"}));
|
||||
assert_eq!(s.text("find", json!({"name": "gamma"})), "module gamma a.sv:1\n");
|
||||
let item = s.text("read", json!({"file": "a.sv", "item": "gamma"}));
|
||||
assert_eq!(item, "a.sv:1\nmodule gamma; endmodule\n");
|
||||
// The renamed file is a new file: it is found at the next walk.
|
||||
s.text("project_overview", json!({}));
|
||||
assert!(s.text("list_units", json!({})).contains("b.sv\n module alpha 1"));
|
||||
// The renamed file is a new file: the miss walks and finds it.
|
||||
assert_eq!(s.text("find", json!({"name": "alpha"})), "module alpha b.sv:1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_same_size_rewrite_with_the_same_mtime_is_caught_by_the_racy_rule() {
|
||||
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "alpha"}));
|
||||
let old = mtime(&scratch.path("a.sv"));
|
||||
scratch.write("a.sv", b"module delta; endmodule\n");
|
||||
set_mtime(&scratch.path("a.sv"), old);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module delta 1\n");
|
||||
let answer = s.text("unit_interface", json!({"name": "delta"}));
|
||||
assert!(answer.starts_with("module delta a.sv:1"), "{answer}");
|
||||
assert_eq!(s.text("find", json!({"name": "delta"})), "module delta a.sv:1\n");
|
||||
assert_eq!(s.text("outline", json!({"unit": "delta"})), "a.sv:1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -691,39 +622,36 @@ fn qa_a_same_size_rewrite_that_restores_an_old_mtime_is_seen() {
|
||||
let long_ago = SystemTime::now() - Duration::from_secs(3600);
|
||||
set_mtime(&scratch.path("c.sv"), long_ago);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "charlie"}));
|
||||
s.text("find", json!({"name": "charlie"}));
|
||||
scratch.write("c.sv", b"module chxrlie; endmodule\n");
|
||||
set_mtime(&scratch.path("c.sv"), long_ago);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chxrlie 1\n");
|
||||
assert_eq!(s.text("find", json!({"name": "chxrlie"})), "module chxrlie c.sv:1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_new_file_in_a_new_subdirectory_appears_at_the_next_walk() {
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "x"}));
|
||||
scratch.write("n1/n2/n.sv", b"module newbie (input k); endmodule\n");
|
||||
// project_overview always walks; every later call sees the file.
|
||||
let overview = s.call("project_overview", json!({}));
|
||||
assert_eq!(overview["structuredContent"]["files"], 2);
|
||||
// `hierarchy` without a root always walks; every later call sees the file.
|
||||
assert_eq!(
|
||||
s.text("list_units", json!({"glob": "newbie"})),
|
||||
"1 unit\nn1/n2/n.sv\n module newbie 1\n"
|
||||
s.text("hierarchy", json!({})),
|
||||
"2 files, 2 modules, 2 top\nnewbie n1/n2/n.sv:1\nx x.sv:1\n"
|
||||
);
|
||||
assert!(s.text("unit_interface", json!({"name": "newbie"})).contains("input k"));
|
||||
assert_eq!(s.text("find", json!({"name": "newbie"})), "module newbie n1/n2/n.sv:1\n");
|
||||
assert!(s.text("outline", json!({"unit": "newbie"})).contains("input k"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_unit_written_just_now_is_found_by_name_without_a_walk_first() {
|
||||
// The agent flow: write a new module file, then ask for its interface.
|
||||
// Within 5 s of the last walk the index does not know the file and the
|
||||
// refusal ("search_symbols finds near names") sends the agent nowhere.
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "x"}));
|
||||
scratch.write("new_mod.sv", b"module new_mod (input k); endmodule\n");
|
||||
let answer = s.text("unit_interface", json!({"name": "new_mod"}));
|
||||
let answer = s.text("outline", json!({"unit": "new_mod"}));
|
||||
assert!(answer.contains("input k"), "{answer}");
|
||||
}
|
||||
|
||||
@@ -734,15 +662,13 @@ fn qa_a_file_growing_past_one_mib_drops_out_of_the_index() {
|
||||
("c.sv", "module charlie; endmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert!(s.text("list_units", json!({})).contains("alpha"));
|
||||
assert!(s.text("hierarchy", json!({})).contains("alpha a.sv:1"));
|
||||
let mut big = b"module alpha; endmodule\n//".to_vec();
|
||||
big.extend(std::iter::repeat_n(b'x', 1024 * 1024));
|
||||
big.push(b'\n');
|
||||
scratch.write("a.sv", &big);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module charlie 1\n");
|
||||
let overview = s.call("project_overview", json!({}));
|
||||
assert_eq!(overview["structuredContent"]["skipped_large"], 1);
|
||||
assert_eq!(overview["structuredContent"]["files"], 1);
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\ncharlie c.sv:1\n");
|
||||
s.refusal("find", json!({"name": "alpha"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -752,23 +678,21 @@ fn qa_a_gitignore_added_after_startup_drops_its_files_at_the_next_walk() {
|
||||
("gen/g.sv", "module generated; endmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert!(s.text("list_units", json!({})).contains("generated"));
|
||||
assert!(s.text("hierarchy", json!({})).contains("generated gen/g.sv:1"));
|
||||
scratch.write(".gitignore", b"gen/\n");
|
||||
s.text("project_overview", json!({}));
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n");
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nalpha a.sv:1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_an_unreadable_file_warning_is_root_relative_and_current() {
|
||||
fn qa_a_file_that_is_not_utf8_is_left_out_until_it_is() {
|
||||
let scratch = Scratch::with(&[("a.sv", "module alpha; endmodule\n")]);
|
||||
scratch.write("latin.sv", b"module lat; // \xe9\xff\nendmodule\n");
|
||||
let mut s = Session::ready(&scratch);
|
||||
let warnings = s.call("project_overview", json!({}))["structuredContent"]["warnings"].clone();
|
||||
assert_eq!(warnings, json!(["latin.sv: not UTF-8 text"]));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nalpha a.sv:1\n");
|
||||
s.refusal("find", json!({"name": "lat"}));
|
||||
scratch.write("latin.sv", b"module lat; // fixed\nendmodule\n");
|
||||
let overview = s.call("project_overview", json!({}));
|
||||
assert_eq!(overview["structuredContent"]["warnings"], json!([]), "{overview}");
|
||||
assert_eq!(overview["structuredContent"]["files"], 2);
|
||||
assert!(s.text("hierarchy", json!({})).starts_with("2 files, "));
|
||||
assert_eq!(s.text("find", json!({"name": "lat"})), "module lat latin.sv:1\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------- roots
|
||||
@@ -787,23 +711,20 @@ fn qa_a_path_argument_through_a_symlink_leaving_the_root_is_refused() {
|
||||
assert!(refusal.contains("outside every root"), "{file}: {refusal}");
|
||||
}
|
||||
let absolute = outside.path("secret.sv");
|
||||
let refusal = s.refusal("read_item", json!({"file": absolute, "item": "secret_mod"}));
|
||||
let refusal = s.refusal("read", json!({"file": absolute, "item": "secret_mod"}));
|
||||
assert!(refusal.contains("outside every root"), "{refusal}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_the_walk_does_not_index_files_outside_the_roots_through_symlinks() {
|
||||
// The path arguments are contained; the walk is not. A symlink inside the
|
||||
// root makes the outside file's units, ports and absolute path answer
|
||||
// through list_units and unit_interface, while outline on the same file
|
||||
// is refused as "outside every root".
|
||||
let outside = Scratch::with(&[("secret.sv", "module secret_mod (input s); endmodule\n")]);
|
||||
let scratch = Scratch::with(SMALL);
|
||||
std::os::unix::fs::symlink(outside.path("secret.sv"), scratch.path("link.sv")).unwrap();
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nx.sv\n module x 1\n");
|
||||
s.refusal("unit_interface", json!({"name": "secret_mod"}));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nx x.sv:1\n");
|
||||
s.refusal("outline", json!({"unit": "secret_mod"}));
|
||||
s.refusal("find", json!({"name": "secret_mod"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -817,12 +738,11 @@ fn qa_nested_roots_index_each_file_once() {
|
||||
Session::spawn_in(&["--root", scratch.root(), "--root", sub.to_str().unwrap()], None);
|
||||
s.initialize();
|
||||
assert_eq!(
|
||||
s.text("list_units", json!({})),
|
||||
"2 units\na.sv\n module alpha 1\nsub/b.sv\n module beta 1\n"
|
||||
s.text("hierarchy", json!({})),
|
||||
"2 files, 2 modules, 2 top\nalpha a.sv:1\nbeta sub/b.sv:1\n"
|
||||
);
|
||||
assert_eq!(s.call("project_overview", json!({}))["structuredContent"]["files"], 2);
|
||||
// The inner root still resolves its own relative paths.
|
||||
assert!(s.text("outline", json!({"file": "b.sv"})).starts_with("1 entry\nsub/b.sv\n"));
|
||||
assert_eq!(s.text("outline", json!({"file": "b.sv"})), "module beta 1\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -830,9 +750,11 @@ fn qa_a_relative_root_is_resolved_against_the_working_directory() {
|
||||
let scratch = Scratch::with(&[("rtl/sub/b.sv", "module beta; endmodule\n")]);
|
||||
let mut s = Session::spawn_in(&["--root", "rtl/sub"], Some(&scratch.0));
|
||||
s.initialize();
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nb.sv\n module beta 1\n");
|
||||
let roots = s.call("project_overview", json!({}))["structuredContent"]["roots"].clone();
|
||||
assert_eq!(roots, json!([scratch.path("rtl/sub")]));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nbeta b.sv:1\n");
|
||||
assert_eq!(
|
||||
s.text("read", json!({"file": "b.sv", "item": "beta"})),
|
||||
"b.sv:1\nmodule beta; endmodule\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -840,8 +762,7 @@ fn qa_a_root_given_twice_is_one_root() {
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::spawn_in(&["--root", scratch.root(), "--root", scratch.root()], None);
|
||||
s.initialize();
|
||||
let roots = s.call("project_overview", json!({}))["structuredContent"]["roots"].clone();
|
||||
assert_eq!(roots, json!([scratch.root()]));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nx x.sv:1\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------- re-check of the rework (M1 QA 2)
|
||||
@@ -857,16 +778,10 @@ fn qa_rework_a_package_scoped_base_in_another_file_is_reported_as_written() {
|
||||
),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let p1 = s.call("unit_interface", json!({"name": "p1::c"}));
|
||||
assert_eq!(p1["structuredContent"]["extends"], "bp::base", "{p1}");
|
||||
let p1 = s.text("outline", json!({"unit": "p1::c"}));
|
||||
assert!(p1.contains("\nextends bp::base\n"), "{p1}");
|
||||
// p2::c has no base of its own; its nested class's base is not its.
|
||||
let p2 = s.call("unit_interface", json!({"name": "p2::c"}));
|
||||
assert_eq!(p2["structuredContent"]["extends"], Value::Null, "{p2}");
|
||||
let members = &p2["structuredContent"]["members"];
|
||||
assert_eq!(
|
||||
members,
|
||||
&json!([{"name": "b", "kind": "var", "line": 2}, {"name": "inner", "kind": "class", "line": 3}])
|
||||
);
|
||||
assert_eq!(s.text("outline", json!({"unit": "p2::c"})), "p2.sv:2\nvar b 2\nclass inner 3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -879,16 +794,12 @@ fn qa_rework_a_class_declared_twice_in_one_package_answers_the_declaration_it_na
|
||||
"package dup;\n class d extends lbase; int x; endclass\n class d extends other; int y; endclass\nendpackage\nclass lbase; endclass\nclass other; endclass\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let d = s.call("unit_interface", json!({"name": "dup::d"}));
|
||||
let answer = &d["structuredContent"];
|
||||
assert_eq!(answer["line"], 2, "{d}");
|
||||
assert_eq!(answer["extends"], "lbase", "{d}");
|
||||
assert_eq!(answer["members"], json!([{"name": "x", "kind": "var", "line": 2}]), "{d}");
|
||||
assert_eq!(s.text("outline", json!({"unit": "dup::d"})), "dup.sv:2\nextends lbase\nvar x 2\n");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_warned_and_a_loop_ends() {
|
||||
fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_and_a_loop_ends() {
|
||||
let outside = Scratch::with(&[
|
||||
("s1.sv", "module secret1; endmodule\n"),
|
||||
("deep/s2.sv", "module secret2; endmodule\n"),
|
||||
@@ -899,15 +810,10 @@ fn qa_rework_a_symlinked_directory_leaving_the_root_is_dropped_warned_and_a_loop
|
||||
std::os::unix::fs::symlink("rtl/in.sv", scratch.path("alias.sv")).unwrap();
|
||||
std::os::unix::fs::symlink(&scratch.0, outside.path("back")).unwrap();
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nrtl/in.sv\n module inner_mod 1\n");
|
||||
let overview = s.call("project_overview", json!({}))["structuredContent"].clone();
|
||||
assert_eq!(overview["files"], 1);
|
||||
let warnings = overview["warnings"].as_array().unwrap();
|
||||
assert_eq!(warnings.len(), 2, "{warnings:?}");
|
||||
assert!(warnings.iter().all(|w| w.as_str().unwrap().contains("outside every root")));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\ninner_mod rtl/in.sv:1\n");
|
||||
// The by-name miss walks again; the outside files stay out.
|
||||
s.refusal("unit_interface", json!({"name": "secret2"}));
|
||||
assert_eq!(s.text("search_symbols", json!({"query": "secret"})), "no symbols match\n");
|
||||
s.refusal("outline", json!({"unit": "secret2"}));
|
||||
assert_eq!(s.refusal("find", json!({"name": "secret"})), "no declaration named `secret`.");
|
||||
assert!(s.refusal("outline", json!({"file": "vendor/s1.sv"})).contains("outside every root"));
|
||||
}
|
||||
|
||||
@@ -918,12 +824,12 @@ fn qa_rework_a_kind_word_of_the_wrong_kind_is_refused_and_an_escaped_kind_is_a_n
|
||||
"module \\port:q (input z); endmodule\nmodule w1; logic w; endmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let refusal = s.refusal("read_item", json!({"file": "k.sv", "item": "module:w"}));
|
||||
let refusal = s.refusal("read", json!({"file": "k.sv", "item": "module:w"}));
|
||||
assert!(refusal.contains("`w` of kind `module`"), "{refusal}");
|
||||
assert_eq!(s.text("read_item", json!({"file": "k.sv", "item": "var:w"})), "k.sv:2\nlogic w;\n");
|
||||
let escaped = s.text("read_item", json!({"file": "k.sv", "item": "\\port:q"}));
|
||||
assert_eq!(s.text("read", json!({"file": "k.sv", "item": "var:w"})), "k.sv:2\nlogic w;\n");
|
||||
let escaped = s.text("read", json!({"file": "k.sv", "item": "\\port:q"}));
|
||||
assert!(escaped.starts_with("k.sv:1\nmodule \\port:q "), "{escaped}");
|
||||
let unknown = s.refusal("read_item", json!({"file": "k.sv", "item": "struct:w"}));
|
||||
let unknown = s.refusal("read", json!({"file": "k.sv", "item": "struct:w"}));
|
||||
assert!(unknown.contains("struct:w"), "{unknown}");
|
||||
}
|
||||
|
||||
@@ -934,33 +840,27 @@ fn qa_rework_line_selectors_tolerate_trailing_spaces_and_refuse_overflow_by_name
|
||||
"module w1; logic w; endmodule\nmodule w2;\n logic w;\n always_comb w = 1;\nendmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.text("read", json!({"file": "w.sv", "item": "w@3 "})), "w.sv:3\nlogic w;\n");
|
||||
assert_eq!(
|
||||
s.text("read_item", json!({"file": "w.sv", "item": "w@3 "})),
|
||||
"w.sv:3\nlogic w;\n"
|
||||
);
|
||||
assert_eq!(
|
||||
s.text("read_item", json!({"file": "w.sv", "item": " always@4\t"})),
|
||||
s.text("read", json!({"file": "w.sv", "item": " always@4\t"})),
|
||||
"w.sv:4\nalways_comb w = 1;\n"
|
||||
);
|
||||
let overflow = s.refusal("read_item", json!({"file": "w.sv", "item": "w@99999999999"}));
|
||||
let overflow = s.refusal("read", json!({"file": "w.sv", "item": "w@99999999999"}));
|
||||
assert!(overflow.contains("out of range"), "{overflow}");
|
||||
let empty = s.refusal("read_item", json!({"file": "w.sv", "item": "w@"}));
|
||||
let empty = s.refusal("read", json!({"file": "w.sv", "item": "w@"}));
|
||||
assert!(empty.contains("w@"), "{empty}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself() {
|
||||
// `\a@12 ` is a legal escaped identifier. The digits-only rule reads
|
||||
// `\a@12` as `\a` on line 12 and refuses "no declaration matches `\a` on
|
||||
// line 12" — the name itself is never tried. `\a@12@2` works.
|
||||
let scratch = Scratch::with(&[(
|
||||
"e.sv",
|
||||
"module \\a@b (input z); endmodule\nmodule \\a@12 (input z); endmodule\n",
|
||||
)]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let spelled = s.text("read_item", json!({"file": "e.sv", "item": "\\a@12@2"}));
|
||||
let spelled = s.text("read", json!({"file": "e.sv", "item": "\\a@12@2"}));
|
||||
assert!(spelled.starts_with("e.sv:2\nmodule \\a@12 "), "{spelled}");
|
||||
let bare = s.text("read_item", json!({"file": "e.sv", "item": "\\a@12"}));
|
||||
let bare = s.text("read", json!({"file": "e.sv", "item": "\\a@12"}));
|
||||
assert!(bare.starts_with("e.sv:2\nmodule \\a@12 "), "{bare}");
|
||||
}
|
||||
|
||||
@@ -968,74 +868,67 @@ fn qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself() {
|
||||
fn qa_rework_every_by_name_tool_finds_a_file_written_just_now() {
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "x"}));
|
||||
scratch.write("m1.sv", b"module fresh1 (input k1); endmodule\n");
|
||||
assert!(s.text("unit_interface", json!({"name": "fresh1"})).contains("input k1"));
|
||||
assert!(s.text("outline", json!({"unit": "fresh1"})).contains("input k1"));
|
||||
scratch.write("m2.sv", b"module fresh2 (input k2); endmodule\n");
|
||||
assert_eq!(
|
||||
s.text("list_units", json!({"glob": "fresh2"})),
|
||||
"1 unit\nm2.sv\n module fresh2 1\n"
|
||||
);
|
||||
assert_eq!(s.text("find", json!({"name": "fresh2"})), "module fresh2 m2.sv:1\n");
|
||||
scratch.write("n/m/m3.sv", b"module fresh3 (input k3); endmodule\n");
|
||||
assert_eq!(s.text("hierarchy", json!({"root": "fresh3"})), "fresh3 n/m/m3.sv:1\n");
|
||||
scratch.write("n/m/m4.sv", b"module fresh4 (input k4); endmodule\n");
|
||||
assert_eq!(
|
||||
s.text("search_symbols", json!({"query": "fresh3"})),
|
||||
"1 symbol\nn/m/m3.sv\n module fresh3 1\n"
|
||||
s.text("read", json!({"item": "fresh4"})),
|
||||
"n/m/m4.sv:1\nmodule fresh4 (input k4); endmodule\n"
|
||||
);
|
||||
// A package member and a class in a new file, by `pkg::cls`.
|
||||
scratch.write("p.sv", b"package fp; class fc; int f; endclass endpackage\n");
|
||||
assert!(s.text("unit_interface", json!({"name": "fp::fc"})).contains("var f 1"));
|
||||
assert!(s.text("outline", json!({"unit": "fp::fc"})).contains("var f 1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_a_legitimate_miss_does_not_make_later_hits_walk() {
|
||||
// The miss walks (once, in its own call); the hits after it do not, so a
|
||||
// file written after the miss stays unseen by a plain listing until the
|
||||
// 5 s walk or project_overview — PLAN §4.4 unchanged for hits.
|
||||
// file written after the miss stays out of the index until the 5 s walk
|
||||
// or `hierarchy` without a root — PLAN §4.4 unchanged for hits.
|
||||
let scratch = Scratch::with(SMALL);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "x"}));
|
||||
for _ in 0..3 {
|
||||
s.refusal("unit_interface", json!({"name": "no_such_unit"}));
|
||||
assert_eq!(s.text("search_symbols", json!({"query": "zzqq"})), "no symbols match\n");
|
||||
s.refusal("outline", json!({"unit": "no_such_unit"}));
|
||||
s.refusal("find", json!({"name": "zzqq"}));
|
||||
}
|
||||
scratch.write("late.sv", b"module late; endmodule\n");
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nx.sv\n module x 1\n");
|
||||
assert!(s.text("outline", json!({"file": "late.sv"})).contains("module late 1"));
|
||||
s.text("project_overview", json!({}));
|
||||
assert!(s.text("list_units", json!({})).contains("late.sv"));
|
||||
scratch.write("late.sv", b"module late; logic q_late; endmodule\n");
|
||||
assert_eq!(s.text("find", json!({"name": "x"})), "module x x.sv:1\n");
|
||||
assert!(!s.text("check", json!({})).contains("late.sv"), "not indexed yet");
|
||||
assert!(s.text("outline", json!({"file": "late.sv"})).contains("module late 1"));
|
||||
s.text("hierarchy", json!({}));
|
||||
assert!(s.text("check", json!({})).contains("late.sv:1:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_search_hits_carry_a_line_and_never_a_column() {
|
||||
fn qa_rework_find_hits_carry_a_line_and_never_a_column() {
|
||||
let scratch = Scratch::with(&[
|
||||
("a.sv", "/* é */ module ab (input abc); endmodule\n"),
|
||||
("p.sv", "package abp; parameter int ABQ = 1; endpackage\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let hits = s.call("search_symbols", json!({"query": "ab"}));
|
||||
let symbols = hits["structuredContent"]["symbols"].as_array().unwrap().clone();
|
||||
assert_eq!(symbols.len(), 4, "{hits}");
|
||||
for hit in &symbols {
|
||||
assert_eq!(hit["line"], 1, "{hit}");
|
||||
assert!(hit.get("col").is_none(), "{hit}");
|
||||
for name in ["ab", "abc", "abp", "ABQ"] {
|
||||
let hit = s.text("find", json!({"name": name}));
|
||||
assert!(hit.ends_with(".sv:1\n") && hit.matches(':').count() == 1, "{hit}");
|
||||
}
|
||||
let text = hits["content"][0]["text"].as_str().unwrap();
|
||||
assert!(text.lines().all(|l| !l.contains(':') || l.contains("::")), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_a_file_that_stops_being_utf8_is_warned_and_leaves_the_index() {
|
||||
fn qa_rework_a_file_that_stops_being_utf8_leaves_the_index() {
|
||||
let scratch = Scratch::with(&[
|
||||
("a.sv", "module alpha; endmodule\n"),
|
||||
("b.sv", "module beta; endmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert!(s.text("list_units", json!({})).contains("beta"));
|
||||
assert_eq!(s.text("find", json!({"name": "beta"})), "module beta b.sv:1\n");
|
||||
scratch.write("b.sv", b"module beta; // \xe9\xff\nendmodule\n");
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\na.sv\n module alpha 1\n");
|
||||
let overview = s.call("project_overview", json!({}))["structuredContent"].clone();
|
||||
assert_eq!(overview["warnings"], json!(["b.sv: not UTF-8 text"]));
|
||||
assert_eq!(overview["files"], 1);
|
||||
s.refusal("find", json!({"name": "beta"}));
|
||||
assert_eq!(s.text("hierarchy", json!({})), "1 file, 1 module, 1 top\nalpha a.sv:1\n");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1050,14 +943,14 @@ fn qa_rework_a_rename_over_with_an_old_mtime_and_the_same_size_is_seen() {
|
||||
set_mtime(&scratch.path("c.sv"), long_ago);
|
||||
set_mtime(&scratch.path("stash/c.txt"), long_ago);
|
||||
let mut s = Session::ready(&scratch);
|
||||
s.text("list_units", json!({}));
|
||||
s.text("list_units", json!({}));
|
||||
s.text("find", json!({"name": "charlie"}));
|
||||
s.text("find", json!({"name": "charlie"}));
|
||||
fs::rename(scratch.path("stash/c.txt"), scratch.path("c.sv")).unwrap();
|
||||
assert_eq!(mtime(&scratch.path("c.sv")), long_ago);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chxrlie 1\n");
|
||||
assert_eq!(s.text("find", json!({"name": "chxrlie"})), "module chxrlie c.sv:1\n");
|
||||
// cp -p of a same-size file with the same old mtime: ctime moves.
|
||||
fs::write(scratch.path("stash/d.txt"), "module chyrlie; endmodule\n").unwrap();
|
||||
fs::copy(scratch.path("stash/d.txt"), scratch.path("c.sv")).unwrap();
|
||||
set_mtime(&scratch.path("c.sv"), long_ago);
|
||||
assert_eq!(s.text("list_units", json!({})), "1 unit\nc.sv\n module chyrlie 1\n");
|
||||
assert_eq!(s.text("find", json!({"name": "chyrlie"})), "module chyrlie c.sv:1\n");
|
||||
}
|
||||
+176
-452
@@ -1,5 +1,8 @@
|
||||
//! QA attacks on lane M2 (navigation, diagnostics, defines, resources),
|
||||
//! 2026-09-23.
|
||||
//! 2026-09-23 — ported to the lean catalogue (`find`, `hierarchy`, `check`;
|
||||
//! `docs/features/mcp-lean-catalogue/README.md` lists what was deleted: the
|
||||
//! position selector and the paging are gone, so their attacks went with
|
||||
//! them).
|
||||
//!
|
||||
//! Every test spawns the real binary over a scratch tree, as a host would.
|
||||
//! A test that pins a QA finding asserts the *correct* behaviour and is
|
||||
@@ -131,34 +134,9 @@ impl Session {
|
||||
result["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// `file:line:col kind` of every definition a successful call lists.
|
||||
fn sites(&mut self, arguments: Value) -> Vec<String> {
|
||||
let result = self.call("definition", arguments.clone());
|
||||
assert_eq!(result["isError"], false, "{arguments}: {result}");
|
||||
let listed = result["structuredContent"]["definitions"].as_array().unwrap().clone();
|
||||
listed
|
||||
.iter()
|
||||
.map(|d| {
|
||||
format!(
|
||||
"{}:{}:{} {}",
|
||||
d["file"].as_str().unwrap(),
|
||||
d["line"],
|
||||
d["col"],
|
||||
d["kind"].as_str().unwrap()
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `file:line:col` of every hit a successful `references` call lists.
|
||||
fn hits(&mut self, arguments: Value) -> Vec<String> {
|
||||
let result = self.call("references", arguments.clone());
|
||||
assert_eq!(result["isError"], false, "{arguments}: {result}");
|
||||
let listed = result["structuredContent"]["hits"].as_array().unwrap().clone();
|
||||
listed
|
||||
.iter()
|
||||
.map(|h| format!("{}:{}:{}", h["file"].as_str().unwrap(), h["line"], h["col"]))
|
||||
.collect()
|
||||
/// `find`'s answer for `name`, with its uses.
|
||||
fn refs(&mut self, name: &str) -> String {
|
||||
self.text("find", json!({"name": name, "refs": true}))
|
||||
}
|
||||
|
||||
fn pings(&mut self) -> bool {
|
||||
@@ -205,40 +183,24 @@ const DESIGN: &[(&str, &str)] = &[
|
||||
fn qa_a_package_member_is_found_through_a_wildcard_import_and_a_scope() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let param = ["p.sv:2:17 parameter"];
|
||||
assert_eq!(s.sites(json!({"file": "u1.sv", "line": 1, "name": "PW"})), param);
|
||||
assert_eq!(s.sites(json!({"file": "u1.sv", "line": 2, "name": "PW"})), param);
|
||||
assert_eq!(s.sites(json!({"file": "u1.sv", "line": 1, "name": "w_t"})), ["p.sv:3:26 typedef"]);
|
||||
let all = ["p.sv:2:17", "p.sv:3:18", "u1.sv:1:52", "u1.sv:2:21"];
|
||||
assert_eq!(s.hits(json!({"name": "PW", "unit": "p"})), all);
|
||||
assert_eq!(s.hits(json!({"file": "u1.sv", "line": 2, "col": 21})), all);
|
||||
assert_eq!(s.refs("PW"), "parameter PW p.sv:2\n p.sv:3\n u1.sv:1,2\n");
|
||||
assert_eq!(s.text("find", json!({"name": "w_t"})), "typedef w_t p.sv:3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_two_level_tail_to_a_port_is_followed_both_ways() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let tail = json!({"file": "top2.sv", "line": 3, "name": "sig"});
|
||||
assert_eq!(s.sites(tail), ["leaf.sv:1:44 port"]);
|
||||
assert_eq!(
|
||||
s.hits(json!({"name": "sig", "unit": "leaf"})),
|
||||
["leaf.sv:1:44", "leaf.sv:3:10", "mid.sv:2:25", "top2.sv:3:20"]
|
||||
);
|
||||
let internal = json!({"file": "top2.sv", "line": 4, "name": "sig2"});
|
||||
assert_eq!(s.sites(internal), ["leaf.sv:2:9 var"]);
|
||||
assert_eq!(s.refs("sig"), "port sig leaf.sv:1\n leaf.sv:3\n mid.sv:2\n top2.sv:3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_1_a_two_level_tail_to_an_internal_net_is_a_reference() {
|
||||
// `mid.sv` is the file that says `u_a.u_b` is a `leaf`, but it never
|
||||
// writes `sig2`, so the narrowed set leaves it out and the engine cannot
|
||||
// resolve the tail. `vlog_refactor::find_references` over all five files
|
||||
// lists `top2.sv:4:21`.
|
||||
// writes `sig2`: only the whole set resolves the tail.
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.hits(json!({"name": "sig2", "unit": "leaf"})), ["leaf.sv:2:9", "top2.sv:4:21"]);
|
||||
let from_use = json!({"file": "top2.sv", "line": 4, "name": "sig2"});
|
||||
assert_eq!(s.hits(from_use), ["leaf.sv:2:9", "top2.sv:4:21"]);
|
||||
assert_eq!(s.refs("sig2"), "var sig2 leaf.sv:2\n top2.sv:4\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -250,12 +212,7 @@ fn qa_finding_1_a_class_handle_chain_through_a_third_file_is_a_reference() {
|
||||
("t.sv", "class t;\n env e;\n function void f();\n e.s.count = 1;\n endfunction\nendclass\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.sites(json!({"file": "t.sv", "line": 4, "name": "count"})), ["sb.sv:2:7 var"]);
|
||||
assert_eq!(s.hits(json!({"name": "count", "unit": "sb"})), ["sb.sv:2:7", "t.sv:4:9"]);
|
||||
assert_eq!(
|
||||
s.hits(json!({"file": "t.sv", "line": 4, "name": "count"})),
|
||||
["sb.sv:2:7", "t.sv:4:9"]
|
||||
);
|
||||
assert_eq!(s.refs("count"), "var count sb.sv:2\n t.sv:4\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -266,102 +223,51 @@ fn qa_a_bind_connections_bare_name_resolves_into_the_bound_module() {
|
||||
("bind.sv", "bind core chk u_chk (.s(state_q));\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.refs("state_q"), "var state_q core.sv:2\n bind.sv:1\n core.sv:3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_port_that_is_also_a_net_and_a_member_of_two_classes_list_every_declaration() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.refs("y"), "port y clamp.sv:1\n clamp.sv:2\nport y dual.sv:3\n dual.sv:3,4,5\n");
|
||||
// Never a guess: both classes' `n`, each with its own uses.
|
||||
assert_eq!(s.text("find", json!({"name": "n"})), "var n cls.sv:1\nvar n cls.sv:2\n");
|
||||
assert_eq!(s.refs("n"), "var n cls.sv:1\nvar n cls.sv:2\n cls.sv:2\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_name_nothing_declares_is_refused_with_its_near_matches() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(
|
||||
s.sites(json!({"file": "bind.sv", "line": 1, "name": "state_q"})),
|
||||
["core.sv:2:9 var"]
|
||||
s.refusal("find", json!({"name": "nonexistent"})),
|
||||
"no declaration named `nonexistent`."
|
||||
);
|
||||
let all = ["bind.sv:1:25", "core.sv:2:9", "core.sv:3:28", "core.sv:3:40"];
|
||||
assert_eq!(s.hits(json!({"file": "bind.sv", "line": 1, "name": "state_q"})), all);
|
||||
assert_eq!(s.hits(json!({"name": "state_q", "unit": "core"})), all);
|
||||
let near = s.refusal("find", json!({"name": "SIG"}));
|
||||
// The module-internal `sig2` is a declaration `find` lists, so a near
|
||||
// match too (M7 QA finding 2).
|
||||
assert_eq!(near, "no declaration named `SIG`; similar: sig, sig2.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_port_that_is_also_a_net_lists_both_and_a_class_member_lists_every_class() {
|
||||
fn qa_lines_hold_after_multibyte_text_and_in_crlf_files() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let dual = ["dual.sv:3:3 port", "dual.sv:1:17 port", "dual.sv:4:8 net"];
|
||||
assert_eq!(s.sites(json!({"file": "dual.sv", "line": 5, "col": 10})), dual);
|
||||
assert_eq!(s.sites(json!({"file": "dual.sv", "line": 4, "name": "y"})), dual);
|
||||
let every = ["dual.sv:1:17", "dual.sv:3:10", "dual.sv:4:8", "dual.sv:5:10"];
|
||||
assert_eq!(s.hits(json!({"file": "dual.sv", "line": 4, "name": "y"})), every);
|
||||
assert_eq!(s.sites(json!({"name": "n"})), ["cls.sv:1:15 var", "cls.sv:2:15 var"]);
|
||||
let twice = s.refusal("references", json!({"name": "n"}));
|
||||
assert!(twice.contains("cls.sv:1") && twice.contains("cls.sv:2"), "{twice}");
|
||||
assert_eq!(s.hits(json!({"name": "n", "unit": "c2"})), ["cls.sv:2:15", "cls.sv:2:37"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_name_declared_twice_in_one_file_is_refused_listing_the_lines() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let twice = s.refusal("definition", json!({"file": "twice.sv", "name": "t"}));
|
||||
assert!(twice.contains("2 times") && twice.contains("lines 2, 3"), "{twice}");
|
||||
let missing = s.refusal("definition", json!({"name": "sig", "unit": "nonexistent"}));
|
||||
assert!(missing.contains("`nonexistent`"), "{missing}");
|
||||
let missing = s.refusal("references", json!({"name": "sig", "unit": "nonexistent"}));
|
||||
assert!(missing.contains("`nonexistent`"), "{missing}");
|
||||
let absent = s.refusal("definition", json!({"file": "leaf.sv", "name": "nonexistent"}));
|
||||
assert!(absent.contains("not written"), "{absent}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_whitespace_keywords_comments_and_bad_lines_are_refused_cleanly() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
for (line, col) in [(1, 1), (1, 7), (2, 5), (5, 1)] {
|
||||
let at =
|
||||
json!({"file": if line == 2 { "utf.sv" } else { "leaf.sv" }, "line": line, "col": col});
|
||||
let refused = s.refusal("definition", at);
|
||||
assert!(refused.contains("names a declaration"), "{refused}");
|
||||
}
|
||||
let zero = s.refusal("definition", json!({"file": "leaf.sv", "line": 0, "col": 1}));
|
||||
assert!(zero.contains("`line`") && zero.contains(">= 1"), "{zero}");
|
||||
let past = s.refusal("definition", json!({"file": "leaf.sv", "line": 6, "col": 1}));
|
||||
assert!(past.contains("past the end (5 lines)"), "{past}");
|
||||
let huge =
|
||||
s.refusal("definition", json!({"file": "leaf.sv", "line": 5_000_000_000u64, "col": 1}));
|
||||
assert!(huge.contains("past the end"), "{huge}");
|
||||
assert_eq!(s.refs("zz"), "var zz utf.sv:2\n utf.sv:2\n");
|
||||
assert_eq!(s.refs("cc"), "var cc crlf.sv:2\n crlf.sv:3\n");
|
||||
assert!(s.pings());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_byte_columns_hold_after_multibyte_text_and_in_crlf_files() {
|
||||
fn qa_escaped_identifiers_and_macro_only_names_are_found_as_written() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// `/* héllo wörld */` is 19 bytes and 17 characters: `zz` is byte column 29.
|
||||
assert_eq!(s.sites(json!({"file": "utf.sv", "line": 2, "name": "zz"})), ["utf.sv:2:29 var"]);
|
||||
assert_eq!(s.sites(json!({"file": "utf.sv", "line": 2, "col": 40})), ["utf.sv:2:29 var"]);
|
||||
assert_eq!(
|
||||
s.hits(json!({"file": "utf.sv", "line": 2, "col": 29})),
|
||||
["utf.sv:2:29", "utf.sv:2:40"]
|
||||
);
|
||||
// A column inside `é` (bytes 7-8 on the line) is refused, never a panic.
|
||||
for col in [8, 9] {
|
||||
s.refusal("definition", json!({"file": "utf.sv", "line": 2, "col": col}));
|
||||
s.refusal("references", json!({"file": "utf.sv", "line": 2, "col": col}));
|
||||
}
|
||||
assert_eq!(s.sites(json!({"file": "crlf.sv", "line": 3, "name": "cc"})), ["crlf.sv:2:9 var"]);
|
||||
let crlf = s.text("references", json!({"file": "crlf.sv", "line": 3, "col": 10}));
|
||||
assert_eq!(crlf, "2 hits\ncrlf.sv\n 2:9 logic cc;\n 3:10 assign cc = a;\n");
|
||||
assert!(s.pings());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_escaped_identifiers_and_macro_only_names_are_selected_as_written() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.sites(json!({"name": "\\a+b"})), ["esc.sv:2:9 var"]);
|
||||
assert_eq!(
|
||||
s.hits(json!({"file": "esc.sv", "line": 4, "name": "\\a+b"})),
|
||||
["esc.sv:2:9", "esc.sv:3:10", "esc.sv:4:12"]
|
||||
);
|
||||
let define = ["mac.sv:1:9 define"];
|
||||
assert_eq!(s.sites(json!({"name": "ONLY_MAC"})), define);
|
||||
assert_eq!(s.sites(json!({"file": "mac.sv", "name": "`ONLY_MAC"})), define);
|
||||
assert_eq!(s.sites(json!({"file": "mac.sv", "line": 3, "name": "`ONLY_MAC"})), define);
|
||||
let refused =
|
||||
s.refusal("references", json!({"file": "mac.sv", "line": 3, "name": "`ONLY_MAC"}));
|
||||
assert!(refused.contains("is a macro"), "{refused}");
|
||||
assert_eq!(s.refs("\\a+b"), "var \\a+b esc.sv:2\n esc.sv:3,4\n");
|
||||
assert_eq!(s.text("find", json!({"name": "ONLY_MAC"})), "macro ONLY_MAC mac.sv:1\n");
|
||||
assert_eq!(s.text("find", json!({"name": "`ONLY_MAC"})), "macro ONLY_MAC mac.sv:1\n");
|
||||
// A macro's uses are not followed; its definition is still listed.
|
||||
assert_eq!(s.refs("ONLY_MAC"), "macro ONLY_MAC mac.sv:1\n");
|
||||
}
|
||||
|
||||
const MACRO_ARG: &[(&str, &str)] = &[
|
||||
@@ -376,68 +282,20 @@ const MACRO_ARG: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_references_never_report_a_comment_a_string_or_macro_text() {
|
||||
fn qa_uses_never_include_a_comment_a_string_or_macro_text() {
|
||||
let scratch = Scratch::with(MACRO_ARG);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// `third.sv` writes the word only in a comment and a string; `top.sv`
|
||||
// only inside a macro call's argument, which the engine does not follow
|
||||
// (the rename engine warns about such files; references is silent).
|
||||
assert_eq!(s.hits(json!({"name": "state_q", "unit": "core"})), ["core.sv:2:9", "core.sv:3:14"]);
|
||||
let paged =
|
||||
s.call("references", json!({"name": "state_q", "unit": "core", "limit": 1, "offset": 1}));
|
||||
assert_eq!(paged["structuredContent"]["total"], 2);
|
||||
assert_eq!(paged["structuredContent"]["hits"][0]["line"], 3);
|
||||
let past = s.call("references", json!({"name": "state_q", "unit": "core", "offset": 9}));
|
||||
// only inside a macro call's argument, which the engine does not follow:
|
||||
// those are the unresolved mentions, never uses.
|
||||
assert_eq!(
|
||||
(paged["structuredContent"]["total"].clone(), past["structuredContent"]["hits"].clone()),
|
||||
(json!(2), json!([]))
|
||||
s.refs("state_q"),
|
||||
"var state_q core.sv:2\n core.sv:3\nunresolved:\n third.sv:2,3\n top.sv:5\n"
|
||||
);
|
||||
let bare = json!({"name": "state_q", "unit": "core", "include_declaration": false});
|
||||
assert_eq!(s.hits(bare), ["core.sv:3:14"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_2_a_name_inside_a_macro_argument_is_not_answered_with_the_macro() {
|
||||
// `name: state_q` on `` `ID(u_core0.state_q) `` finds the word inside the
|
||||
// one macro token and answers `ID`'s `define` — a declaration of a
|
||||
// different name. The right answers are a refusal or `core.sv:2`.
|
||||
let scratch = Scratch::with(MACRO_ARG);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("definition", json!({"file": "top.sv", "line": 5, "name": "state_q"}));
|
||||
let listed = result["structuredContent"]["definitions"].as_array().cloned().unwrap_or_default();
|
||||
assert!(result["isError"] == true || listed.iter().all(|d| d["kind"] != "define"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_3_a_name_first_written_in_a_comment_is_still_found_on_its_line() {
|
||||
let scratch = Scratch::with(MACRO_ARG);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// Line 2 is `/* q */ assign q = a;`: the code `q` is at column 18.
|
||||
assert_eq!(s.sites(json!({"file": "m.sv", "line": 2, "name": "q"})), ["m.sv:1:39 port"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_8_a_column_past_the_end_of_its_line_is_refused_as_such() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// Line 2 is 14 bytes; column 99 is silently clamped to 15 today and the
|
||||
// refusal names `clamp.sv:2:15`, a position the agent never asked about.
|
||||
let refused = s.refusal("definition", json!({"file": "clamp.sv", "line": 2, "col": 99}));
|
||||
assert!(refused.contains("99"), "{refused}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_9_references_refusals_do_not_speak_of_renaming() {
|
||||
let scratch = Scratch::with(DESIGN);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let blank = s.refusal("references", json!({"file": "leaf.sv", "line": 1, "col": 7}));
|
||||
assert!(!blank.contains("rename"), "{blank}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_11_a_name_used_twice_in_a_file_for_two_declarations_is_not_a_guess() {
|
||||
// `top3.sv` declares no `sig`; its uses name `leaf`'s and `other`'s.
|
||||
// `file` + `name` takes the first use and answers `leaf` alone.
|
||||
fn qa_finding_11_a_name_used_for_two_declarations_lists_both_never_a_guess() {
|
||||
let scratch = Scratch::with(&[
|
||||
("leaf.sv", "module leaf (output logic sig); endmodule\n"),
|
||||
("other.sv", "module other (output logic sig); endmodule\n"),
|
||||
@@ -447,10 +305,10 @@ fn qa_finding_11_a_name_used_twice_in_a_file_for_two_declarations_is_not_a_guess
|
||||
),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("definition", json!({"file": "top3.sv", "name": "sig"}));
|
||||
let listed = result["structuredContent"]["definitions"].as_array().cloned().unwrap_or_default();
|
||||
assert!(result["isError"] == true || listed.len() == 2, "{result}");
|
||||
s.refusal("references", json!({"file": "top3.sv", "name": "sig"}));
|
||||
assert_eq!(
|
||||
s.refs("sig"),
|
||||
"port sig leaf.sv:1\n top3.sv:2,3\nport sig other.sv:1\n top3.sv:6,7\n"
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ hierarchy
|
||||
@@ -482,13 +340,15 @@ const HIER: &[(&str, &str)] = &[
|
||||
fn qa_hierarchy_terminates_on_self_and_mutual_recursion() {
|
||||
let scratch = Scratch::with(HIER);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// feedback-3: the overrides are on the text line only on request.
|
||||
let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20, "overrides": true}));
|
||||
assert_eq!(selfm, "2 nodes\nselfm self.sv:1\n u_s : selfm #(.N(N-1)) (recursive)\n");
|
||||
let selfm = s.text("hierarchy", json!({"root": "selfm", "depth": 20}));
|
||||
assert_eq!(selfm, "selfm self.sv:1\n u_s: selfm self.sv:3 (recursive)\n");
|
||||
let mutual = s.text("hierarchy", json!({"root": "ma", "depth": 20}));
|
||||
assert_eq!(mutual, "3 nodes\nma mutual.sv:1\n u_b : mb\n u_a : ma (recursive)\n");
|
||||
let up = s.text("hierarchy", json!({"root": "ma", "direction": "up", "depth": 20}));
|
||||
assert_eq!(up, "3 instantiations\nma mutual.sv:1\n mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\n mtop.u mutual.sv:3\n");
|
||||
assert_eq!(
|
||||
mutual,
|
||||
"ma mutual.sv:1\n u_b: mb mutual.sv:1\n u_a: ma mutual.sv:2 (recursive)\n"
|
||||
);
|
||||
let up = s.text("hierarchy", json!({"root": "ma", "up": true, "depth": 20}));
|
||||
assert_eq!(up, "mb.u_a mutual.sv:2\n ma.u_b mutual.sv:1 (recursive)\nmtop.u mutual.sv:3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -496,30 +356,19 @@ fn qa_hierarchy_depth_is_capped_and_bad_arguments_are_schema_refusals() {
|
||||
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let deep = s.text("hierarchy", json!({"root": "c0", "depth": 20}));
|
||||
// The count line, the root, twenty levels.
|
||||
assert_eq!(deep.lines().count(), 22, "{deep}");
|
||||
assert!(deep.ends_with("u19 : c20\n") && !deep.contains("c21"), "{deep}");
|
||||
for depth in [json!(0), json!(-1), json!(2.5), json!("3")] {
|
||||
// The root, twenty levels.
|
||||
assert_eq!(deep.lines().count(), 21, "{deep}");
|
||||
assert!(deep.ends_with("u19: c20 chain.sv:20\n") && !deep.contains("c21"), "{deep}");
|
||||
for depth in [json!(0), json!(-1), json!(2.5), json!("3"), json!(21)] {
|
||||
let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": depth}));
|
||||
assert!(refused.contains("`depth`"), "{refused}");
|
||||
assert!(refused.contains("`depth`") && refused.contains("from 1 to 20"), "{refused}");
|
||||
}
|
||||
for direction in ["Up", "sideways", ""] {
|
||||
let refused = s.refusal("hierarchy", json!({"root": "c0", "direction": direction}));
|
||||
assert!(refused.contains("one of down, up"), "{refused}");
|
||||
for up in [json!("up"), json!(1), json!("true")] {
|
||||
let refused = s.refusal("hierarchy", json!({"root": "c0", "up": up}));
|
||||
assert!(refused.contains("true or false"), "{refused}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_7_a_depth_above_the_cap_is_refused_or_said() {
|
||||
// `depth: 21` answers exactly what `depth: 20` does, and the schema
|
||||
// declares no maximum: the agent cannot tell it was capped.
|
||||
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("hierarchy", json!({"root": "c0", "depth": 21}));
|
||||
let text = result["content"][0]["text"].as_str().unwrap_or("");
|
||||
assert!(result["isError"] == true || text.contains("depth"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_hierarchy_marks_not_modules_duplicates_and_two_parents() {
|
||||
let scratch = Scratch::with(HIER);
|
||||
@@ -529,36 +378,36 @@ fn qa_hierarchy_marks_not_modules_duplicates_and_two_parents() {
|
||||
assert!(refused.contains(&format!("`{root}`")), "{refused}");
|
||||
}
|
||||
let dupe = s.text("hierarchy", json!({"root": "usedupe"}));
|
||||
assert_eq!(dupe, "2 nodes\nusedupe usedupe.sv:1\n u_d : dupe (declared 2 times)\n");
|
||||
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up"}));
|
||||
assert!(up.contains(" p1.u_l1 p1.sv:1\n p1.u_l2 p1.sv:1\n p2.u_l p2.sv:1\n"), "{up}");
|
||||
assert_eq!(dupe, "usedupe usedupe.sv:1\n u_d: dupe usedupe.sv:1 (declared 2 times)\n");
|
||||
let up = s.text("hierarchy", json!({"root": "leaf", "up": true}));
|
||||
assert!(up.contains("p1.u_l1 p1.sv:1\np1.u_l2 p1.sv:1\np2.u_l p2.sv:1\n"), "{up}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_hierarchy_overrides_drop_comments_and_keep_nested_parentheses() {
|
||||
fn qa_hierarchy_peek_keeps_comments_and_nested_parentheses_as_written() {
|
||||
let scratch = Scratch::with(HIER);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("hierarchy", json!({"root": "ov"}));
|
||||
let nodes = result["structuredContent"]["nodes"].as_array().unwrap().clone();
|
||||
assert_eq!(nodes[1]["instance"], "u_ov");
|
||||
assert_eq!(nodes[1]["overrides"], "#( .W(c#(4)::N), .S(\"u_x (\"), .D({2{1'b0}}) )");
|
||||
assert_eq!(nodes[2]["overrides"], "#(.W(2))");
|
||||
let peek = s.text("hierarchy", json!({"root": "ov", "peek": true}));
|
||||
assert!(
|
||||
peek.starts_with("ov ov.sv:1\n u_ov: leaf ov.sv:3\n leaf #( /* W = 4 ) oops */ .W(c#(4)::N), // tail ) comment\n .S(\"u_x (\"), .D({2{1'b0}}) ) u_ov ();\n"),
|
||||
"{peek}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_4_every_instance_of_one_statement_shows_only_the_overrides() {
|
||||
// `leaf #(.W(2)) u_a (), u_b ();` — `u_b` shows `#(.W(2)) u_a (),`.
|
||||
fn qa_finding_4_every_instance_of_one_statement_peeks_at_the_whole_statement() {
|
||||
let scratch = Scratch::with(HIER);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("hierarchy", json!({"root": "ov"}));
|
||||
assert_eq!(result["structuredContent"]["nodes"][3]["instance"], "u_b");
|
||||
assert_eq!(result["structuredContent"]["nodes"][3]["overrides"], "#(.W(2))");
|
||||
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up", "overrides": true}));
|
||||
assert!(up.contains(" ov.u_b #(.W(2)) ov.sv:4\n"), "{up}");
|
||||
let up = s.text("hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
|
||||
let statement = " leaf #(.W(2)) u_a (), u_b ();\n";
|
||||
assert!(
|
||||
up.contains(&format!("ov.u_a ov.sv:4\n{statement}ov.u_b ov.sv:4\n{statement}")),
|
||||
"{up}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_hierarchy_stops_at_the_node_cap_and_says_so() {
|
||||
fn qa_hierarchy_stops_at_the_node_cap_and_the_line_cap() {
|
||||
let wide = |name: &str, child: &str| {
|
||||
let body: String = (0..250).map(|i| format!(" {child} u{i} ();\n")).collect();
|
||||
format!("module {name};\n{body}endmodule\n")
|
||||
@@ -567,10 +416,9 @@ fn qa_hierarchy_stops_at_the_node_cap_and_says_so() {
|
||||
let scratch =
|
||||
Scratch::with(&[("w1.sv", &w1), ("w2.sv", &w2), ("w3.sv", "module w3; endmodule\n")]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let result = s.call("hierarchy", json!({"root": "w1", "limit": 2}));
|
||||
assert_eq!(result["structuredContent"]["total"], 50_000);
|
||||
assert_eq!(result["structuredContent"]["cut"], true);
|
||||
assert!(result["content"][0]["text"].as_str().unwrap().contains("tree cut at 50000 nodes"));
|
||||
let text = s.text("hierarchy", json!({"root": "w1", "depth": 2}));
|
||||
assert_eq!(text.lines().count(), 301, "300 lines, then the cut");
|
||||
assert!(text.ends_with("\n… and 49700 more\n"), "{}", &text[text.len() - 60..]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------- diagnostics
|
||||
@@ -589,56 +437,34 @@ const LINT: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_diagnostics_follow_each_files_own_config_directory() {
|
||||
fn qa_check_follows_each_files_own_config_directory() {
|
||||
let scratch = Scratch::with(LINT);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// Root config: select 3, ignore no-tabs, length 45, a/waived.sv waived.
|
||||
assert_eq!(
|
||||
s.text("diagnostics", json!({"file": "a/m.sv"})),
|
||||
"1 finding\na/m.sv\n 2:46 style line is 50 characters; the limit is 45 [line-length]\n"
|
||||
s.text("check", json!({"file": "a/m.sv"})),
|
||||
"a/m.sv:2:46 style line is 50 characters; the limit is 45 [line-length]\n"
|
||||
);
|
||||
assert_eq!(s.text("diagnostics", json!({"file": "a/waived.sv"})), "no findings\n");
|
||||
assert_eq!(s.text("check", json!({"file": "a/waived.sv"})), "ok\n");
|
||||
// b/lucisv.toml: its own select (no-tabs back) and its own line-length
|
||||
// 60, which the 59-character line 2 is inside (45 would flag it).
|
||||
assert_eq!(
|
||||
s.text("diagnostics", json!({"file": "b/n.sv"})),
|
||||
"1 finding\nb/n.sv\n 2:1 style tab character; indent with spaces [no-tabs]\n"
|
||||
s.text("check", json!({"file": "b/n.sv"})),
|
||||
"b/n.sv:2:1 style tab character; indent with spaces [no-tabs]\n"
|
||||
);
|
||||
// `rules` replaces select; the config's ignore still applies.
|
||||
assert_eq!(
|
||||
s.text("diagnostics", json!({"file": "a/m.sv", "rules": "no-tabs"})),
|
||||
"no findings\n"
|
||||
);
|
||||
let style = s.text("diagnostics", json!({"file": "a/m.sv", "rules": "style"}));
|
||||
assert!(style.contains("[port-name-suffix]") && !style.contains("[no-tabs]"), "{style}");
|
||||
let warnings = s.call("diagnostics", json!({"file": "a/m.sv", "severity": "warning"}));
|
||||
assert_eq!(warnings["structuredContent"]["total"], 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_diagnostics_list_parse_errors_before_lint_findings_and_page_the_project() {
|
||||
fn qa_check_lists_parse_errors_before_lint_findings() {
|
||||
let scratch = Scratch::with(LINT);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let broken = s.call("diagnostics", json!({"file": "c/broken.sv"}));
|
||||
let rules: Vec<String> = broken["structuredContent"]["diagnostics"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|d| format!("{}@{}", d["rule"].as_str().unwrap(), d["location"]["line"]))
|
||||
.collect();
|
||||
assert_eq!(rules, ["parse-error@3", "line-length@2"]);
|
||||
let all = s.call("diagnostics", json!({}));
|
||||
let total = all["structuredContent"]["total"].as_u64().unwrap();
|
||||
assert_eq!(total, 4);
|
||||
let mut paged = Vec::new();
|
||||
for offset in 0..total {
|
||||
let one = s.call("diagnostics", json!({"limit": 1, "offset": offset}));
|
||||
assert_eq!(one["structuredContent"]["total"], total);
|
||||
paged.push(one["structuredContent"]["diagnostics"][0].clone());
|
||||
}
|
||||
assert_eq!(Value::from(paged), all["structuredContent"]["diagnostics"]);
|
||||
let errors = s.call("diagnostics", json!({"severity": "error"}));
|
||||
assert_eq!(errors["structuredContent"]["total"], 1);
|
||||
let broken = s.text("check", json!({"file": "c/broken.sv"}));
|
||||
let rules: Vec<&str> =
|
||||
broken.lines().map(|line| line.rsplit_once('[').unwrap().1.trim_end_matches(']')).collect();
|
||||
assert_eq!(rules, ["parse-error", "line-length"], "{broken}");
|
||||
let all = s.text("check", json!({}));
|
||||
assert_eq!(all.lines().count(), 4, "{all}");
|
||||
assert!(all.starts_with("c/broken.sv:3:"), "errors first: {all}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -648,16 +474,12 @@ fn qa_a_bad_lint_option_is_refused_naming_the_config_file_and_line() {
|
||||
("m.sv", "module m; endmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let refused = s.refusal("diagnostics", json!({"file": "m.sv"}));
|
||||
let refused = s.refusal("check", json!({"file": "m.sv"}));
|
||||
assert!(refused.contains("lucisv.toml:5") && refused.contains("`line-length`"), "{refused}");
|
||||
let unknown = s.refusal("diagnostics", json!({"file": "m.sv", "rules": "no-such-rule"}));
|
||||
assert!(unknown.contains("unknown rule: no-such-rule"), "{unknown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_6_an_unused_external_waiver_is_reported_as_the_cli_does() {
|
||||
// `lucisv check .` reports `w.waiver:1:1 unused-waiver`; the MCP drops
|
||||
// `lint_with`'s used-waiver answer.
|
||||
let scratch = Scratch::with(&[
|
||||
(
|
||||
"lucisv.toml",
|
||||
@@ -667,57 +489,38 @@ fn qa_finding_6_an_unused_external_waiver_is_reported_as_the_cli_does() {
|
||||
("m.sv", "module m;\nendmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let all = s.text("diagnostics", json!({}));
|
||||
let all = s.text("check", json!({}));
|
||||
assert!(all.contains("[unused-waiver]"), "{all}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_finding_5_one_files_diagnostics_match_lucisv_check_of_the_whole_tree() {
|
||||
// Lead's ruling on finding 5: `diagnostics` answers "what will CI say",
|
||||
// i.e. `lucisv check .` over the whole tree, where the cross-file rules
|
||||
// run — so one file's answer includes `unknown-port` here, as
|
||||
// `lucisv check .` reports for top.sv (`lucisv check top.sv` alone does
|
||||
// not). Rewritten by the dev from the single-file assertion QA offered
|
||||
// for deletion under this ruling.
|
||||
fn qa_finding_5_one_files_check_matches_lucisv_check_of_the_whole_tree() {
|
||||
// `check` answers "what will CI say", i.e. `lucisv check .` over the
|
||||
// whole tree, where the cross-file rules run.
|
||||
let scratch = Scratch::with(&[
|
||||
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
|
||||
("top.sv", "module top;\n leaf u (.b(1'b0));\nendmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let one = s.text("diagnostics", json!({"file": "top.sv"}));
|
||||
let one = s.text("check", json!({"file": "top.sv"}));
|
||||
assert!(one.contains("[unknown-port]"), "{one}");
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------- defines
|
||||
|
||||
#[test]
|
||||
fn qa_defines_list_every_definition_and_never_pick_one() {
|
||||
fn qa_find_lists_every_macro_definition_and_never_picks_one() {
|
||||
let scratch = Scratch::with(&[
|
||||
("a.svh", "`define TWICE 1\n`define MULTI(a, b) \\\n begin \\\n a = b; \\\n end\n"),
|
||||
("b.svh", "`define TWICE 2\n`undef TWICE\n"),
|
||||
("d.sv", "module d; localparam int P = `TWICE; endmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let twice = "2 defines\na.svh\n 1 `define TWICE 1\nb.svh\n 1 `define TWICE 2\n";
|
||||
assert_eq!(s.text("defines", json!({"name": "TWICE"})), twice);
|
||||
assert_eq!(s.text("defines", json!({"name": "`TWICE"})), twice);
|
||||
assert_eq!(
|
||||
s.sites(json!({"file": "d.sv", "line": 1, "name": "`TWICE"})),
|
||||
["a.svh:1:9 define", "b.svh:1:9 define"]
|
||||
);
|
||||
let multi = s.call("defines", json!({"name": "MULTI"}));
|
||||
assert_eq!(
|
||||
multi["structuredContent"]["defines"][0],
|
||||
json!({"file": "a.svh", "line": 2, "name": "MULTI", "kind": "define", "params": ["a", "b"], "body": "begin a = b; end"})
|
||||
);
|
||||
assert_eq!(s.text("defines", json!({"name": "NOPE"})), "no defines\n");
|
||||
assert_eq!(
|
||||
s.text("defines", json!({"file": "b.svh", "name": "TWICE"})),
|
||||
"2 defines\nb.svh\n 1 `define TWICE 2\n 2 `undef TWICE\n"
|
||||
);
|
||||
assert_eq!(s.text("defines", json!({"file": "a.svh", "name": "NOPE"})), "no defines\n");
|
||||
let missing = s.refusal("defines", json!({"file": "nope.sv"}));
|
||||
assert!(missing.contains("nope.sv"), "{missing}");
|
||||
let twice = "macro TWICE a.svh:1\nmacro TWICE b.svh:1\n";
|
||||
assert_eq!(s.text("find", json!({"name": "TWICE"})), twice);
|
||||
assert_eq!(s.text("find", json!({"name": "`TWICE"})), twice);
|
||||
assert_eq!(s.text("find", json!({"name": "MULTI"})), "macro MULTI a.svh:2\n");
|
||||
s.refusal("find", json!({"name": "NOPE"}));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------ resources
|
||||
@@ -739,17 +542,14 @@ fn qa_resources_refuse_what_they_cannot_name_and_decode_escapes() {
|
||||
}
|
||||
}
|
||||
let read = |s: &mut Session, uri: &str| s.request("resources/read", json!({"uri": uri}));
|
||||
for (uri, starts) in [
|
||||
("lucisv://file/sp%20ace/f%20ile.sv/outline", "sp ace/f ile.sv\n"),
|
||||
("lucisv://file/%C3%BC/%C3%B1.sv/outline", "ü/ñ.sv\n"),
|
||||
("lucisv://file/pct%25/a.sv/outline", "pct%/a.sv\n"),
|
||||
("lucisv://file/x/dup1.sv/outline", "x/dup1.sv\n"),
|
||||
for (uri, outline) in [
|
||||
("lucisv://file/sp%20ace/f%20ile.sv/outline", "module spc 1\n"),
|
||||
("lucisv://file/%C3%BC/%C3%B1.sv/outline", "module uni 1\n"),
|
||||
("lucisv://file/pct%25/a.sv/outline", "module pct 1\n"),
|
||||
("lucisv://file/x/dup1.sv/outline", "module dup 1\n"),
|
||||
] {
|
||||
let reply = read(&mut s, uri);
|
||||
let text = reply["result"]["contents"][0]["text"].as_str().unwrap_or("");
|
||||
// The outline's count line, then the file.
|
||||
let (_, file) = text.split_once('\n').unwrap_or_default();
|
||||
assert!(file.starts_with(starts), "{uri}: {reply}");
|
||||
assert_eq!(reply["result"]["contents"][0]["text"], outline, "{uri}: {reply}");
|
||||
}
|
||||
for uri in [
|
||||
"lucisv://unit/dup",
|
||||
@@ -781,35 +581,35 @@ fn qa_finding_10_an_ambiguous_unit_resource_does_not_ask_for_a_file_argument() {
|
||||
// ------------------------------------------------------------ freshness
|
||||
|
||||
#[test]
|
||||
fn qa_references_and_hierarchy_follow_edits_and_deletions() {
|
||||
fn qa_find_and_hierarchy_follow_edits_and_deletions() {
|
||||
let scratch = Scratch::with(&[
|
||||
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
|
||||
("top.sv", "module top;\n logic a;\n leaf u1 (.a(a));\nendmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3"]);
|
||||
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3\n");
|
||||
scratch.write(
|
||||
"top.sv",
|
||||
"module top;\n logic a;\n leaf u1 (.a(a));\n leaf u2 (.a(a));\nendmodule\n",
|
||||
);
|
||||
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3", "top.sv:4:3"]);
|
||||
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3,4\n");
|
||||
assert_eq!(
|
||||
s.text("hierarchy", json!({"root": "top"})),
|
||||
"3 nodes\ntop top.sv:1\n u1 : leaf\n u2 : leaf\n"
|
||||
"top top.sv:1\n u1: leaf top.sv:3\n u2: leaf top.sv:4\n"
|
||||
);
|
||||
fs::remove_file(scratch.path("top.sv")).unwrap();
|
||||
assert!(s.refusal("hierarchy", json!({"root": "top"})).contains("`top`"));
|
||||
assert_eq!(
|
||||
s.text("hierarchy", json!({"root": "leaf", "direction": "up"})),
|
||||
"0 instantiations\nleaf leaf.sv:1\n"
|
||||
s.text("hierarchy", json!({"root": "leaf", "up": true})),
|
||||
"nothing instantiates leaf\n"
|
||||
);
|
||||
scratch.write("other.sv", "module other; leaf u9 (.a()); endmodule\n");
|
||||
fs::remove_file(scratch.path("leaf.sv")).unwrap();
|
||||
assert_eq!(
|
||||
s.text("hierarchy", json!({"root": "other"})),
|
||||
"2 nodes\nother other.sv:1\n u9 : leaf (not indexed)\n"
|
||||
"other other.sv:1\n u9: leaf other.sv:1 (not indexed)\n"
|
||||
);
|
||||
assert!(s.refusal("definition", json!({"name": "leaf"})).contains("`leaf`"));
|
||||
assert!(s.refusal("find", json!({"name": "leaf"})).contains("`leaf`"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------ re-check after rework
|
||||
@@ -831,29 +631,13 @@ const CHAINS: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_every_site_of_a_tail_and_a_handle_chain_gives_the_whole_set_answer() {
|
||||
fn qa_recheck_a_tail_and_a_handle_chain_give_the_whole_set_answer() {
|
||||
// The expected lists are `vlog_refactor::find_references` over all
|
||||
// seven files (QA's oracle), asked from each site in turn.
|
||||
// seven files (QA's oracle).
|
||||
let scratch = Scratch::with(CHAINS);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let tail = ["leaf.sv:2:9", "top2.sv:3:21", "top2.sv:4:21"];
|
||||
for site in [
|
||||
json!({"name": "sig2", "unit": "leaf"}),
|
||||
json!({"file": "leaf.sv", "line": 2, "name": "sig2"}),
|
||||
json!({"file": "top2.sv", "line": 3, "name": "sig2"}),
|
||||
json!({"file": "top2.sv", "line": 4, "col": 21}),
|
||||
] {
|
||||
assert_eq!(s.hits(site.clone()), tail, "{site}");
|
||||
}
|
||||
let chain = ["sb.sv:2:7", "sb.sv:3:24", "t.sv:4:9", "t2.sv:3:33"];
|
||||
for site in [
|
||||
json!({"name": "count", "unit": "sb"}),
|
||||
json!({"file": "sb.sv", "line": 3, "name": "count"}),
|
||||
json!({"file": "t.sv", "line": 4, "name": "count"}),
|
||||
json!({"file": "t2.sv", "line": 3, "name": "count"}),
|
||||
] {
|
||||
assert_eq!(s.hits(site.clone()), chain, "{site}");
|
||||
}
|
||||
assert_eq!(s.refs("sig2"), "var sig2 leaf.sv:2\n top2.sv:3,4\n");
|
||||
assert_eq!(s.refs("count"), "var count sb.sv:2\n sb.sv:3\n t.sv:4\n t2.sv:3\n");
|
||||
}
|
||||
|
||||
const TOKENS: &[(&str, &str)] = &[
|
||||
@@ -865,38 +649,16 @@ const TOKENS: &[(&str, &str)] = &[
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_a_comment_a_string_and_a_macro_argument_never_stand_in_for_the_use() {
|
||||
fn qa_recheck_a_comment_a_string_and_a_macro_argument_are_mentions_never_uses() {
|
||||
let scratch = Scratch::with(TOKENS);
|
||||
let mut s = Session::ready(&scratch);
|
||||
// Line 3 writes `q` in a comment, a string, a macro argument, as code
|
||||
// (column 60) and in a trailing comment: only the code counts.
|
||||
let q = json!({"file": "m.sv", "line": 3, "name": "q"});
|
||||
assert_eq!(s.sites(q.clone()), ["m.sv:2:39 port"]);
|
||||
assert_eq!(s.hits(q), ["m.sv:2:39", "m.sv:3:60", "m.sv:5:10", "m.sv:5:31"]);
|
||||
// Line 6 writes `q` only inside strings.
|
||||
let strings = s.refusal("definition", json!({"file": "m.sv", "line": 6, "name": "q"}));
|
||||
assert!(strings.contains("not written on line 6"), "{strings}");
|
||||
// Line 3 writes `q` in a comment, a string, a macro argument, as code and
|
||||
// in a trailing comment: only the code is a use; line 6 only in strings.
|
||||
assert_eq!(s.refs("q"), "port q m.sv:2\n m.sv:3,5\nunresolved:\n m.sv:3,4,6\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_a_name_only_in_a_macro_argument_is_refused_on_that_line_alone() {
|
||||
let scratch = Scratch::with(TOKENS);
|
||||
let mut s = Session::ready(&scratch);
|
||||
for (line, name) in [(4, "q"), (5, "a")] {
|
||||
let at = json!({"file": "m.sv", "line": line, "name": name});
|
||||
let refused = s.refusal("definition", at.clone());
|
||||
assert!(refused.contains("inside a macro argument"), "{refused}");
|
||||
assert!(s.refusal("references", at).contains("inside a macro argument"));
|
||||
}
|
||||
// The same names written plainly elsewhere are found, and the macro
|
||||
// itself is still selectable as `` `ID``.
|
||||
assert_eq!(s.sites(json!({"file": "m.sv", "line": 5, "name": "q"})), ["m.sv:2:39 port"]);
|
||||
assert_eq!(s.sites(json!({"file": "m.sv", "name": "a"})), ["m.sv:2:23 port"]);
|
||||
assert_eq!(s.sites(json!({"file": "m.sv", "line": 4, "name": "`ID"})), ["defs.svh:1:9 define"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_overrides_split_across_lines_and_comments_between_instances() {
|
||||
fn qa_recheck_peek_shows_overrides_split_across_lines_and_comments_between_instances() {
|
||||
let scratch = Scratch::with(&[
|
||||
("leaf.sv", "module leaf #(parameter int W = 1) (); endmodule\n"),
|
||||
(
|
||||
@@ -905,16 +667,19 @@ fn qa_recheck_overrides_split_across_lines_and_comments_between_instances() {
|
||||
),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(
|
||||
s.text("hierarchy", json!({"root": "ov", "overrides": true})),
|
||||
"14 nodes\nov ov.sv:1\n u_a : leaf #(.W(2))\n u_b : leaf #(.W(2))\n u_c : leaf #(.W(2))\n u_d : leaf\n u_e : leaf\n u_f : leaf\n u_g : leaf #( .W(3) )\n u_h : leaf #( .W(3) )\n u_i : leaf #( .W(3) )\n u_j : leaf #(.W(4))\n u_k : leaf #(.W(5))\n u_l : leaf\n u_m : leaf\n"
|
||||
);
|
||||
let up = s.text("hierarchy", json!({"root": "leaf", "direction": "up", "overrides": true}));
|
||||
assert!(up.contains(" ov.u_i #( .W(3) ) ov.sv:9\n ov.u_j #(.W(4)) ov.sv:10\n"), "{up}");
|
||||
let tree = s.text("hierarchy", json!({"root": "ov"}));
|
||||
let instances: Vec<&str> =
|
||||
tree.lines().skip(1).map(|line| line.trim().split(':').next().unwrap()).collect();
|
||||
let all =
|
||||
["u_a", "u_b", "u_c", "u_d", "u_e", "u_f", "u_g", "u_h", "u_i", "u_j", "u_k", "u_l", "u_m"];
|
||||
assert_eq!(instances, all);
|
||||
let up = s.text("hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
|
||||
let split = " leaf #(\n .W(3) // three\n )\n u_g (), /* between ) , */\n u_h ()\n , u_i ();\n";
|
||||
assert!(up.contains(&format!("ov.u_i ov.sv:9\n{split}ov.u_j ov.sv:10\n")), "{up}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_depth_twenty_is_the_schema_maximum() {
|
||||
fn qa_recheck_depth_twenty_is_the_maximum_and_the_schema_says_integer() {
|
||||
let scratch = Scratch::with(&[("chain.sv", &chain(30))]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let tools = s.request("tools/list", json!({}));
|
||||
@@ -925,38 +690,18 @@ fn qa_recheck_depth_twenty_is_the_schema_maximum() {
|
||||
.find(|tool| tool["name"] == "hierarchy")
|
||||
.unwrap()
|
||||
.clone();
|
||||
let depth = &hierarchy["inputSchema"]["properties"]["depth"];
|
||||
assert_eq!((depth["minimum"].clone(), depth["maximum"].clone()), (json!(1), json!(20)));
|
||||
// The count line, the root, twenty levels.
|
||||
assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 22);
|
||||
// PLAN §10.1: `type` alone per property; the description names the range.
|
||||
assert_eq!(hierarchy["inputSchema"]["properties"]["depth"], json!({"type": "integer"}));
|
||||
assert!(hierarchy["description"].as_str().unwrap().contains("1-20"));
|
||||
assert_eq!(s.text("hierarchy", json!({"root": "c0", "depth": 20})).lines().count(), 21);
|
||||
let refused = s.refusal("hierarchy", json!({"root": "c0", "depth": 21}));
|
||||
assert!(refused.contains("from 1 to 20"), "{refused}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_a_column_at_and_just_past_the_last_byte_is_a_position() {
|
||||
// Line 2 is ` wire b = a;` (13 bytes, then CRLF); line 3 is `endmodule`
|
||||
// with no newline at all.
|
||||
let scratch =
|
||||
Scratch::with(&[("crlf.sv", "module crlf (input logic a);\r\n wire b = a;\r\nendmodule")]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.sites(json!({"file": "crlf.sv", "line": 2, "col": 12})), ["crlf.sv:1:26 port"]);
|
||||
for (line, col) in [(2, 13), (2, 14), (3, 9), (3, 10)] {
|
||||
let refused = s.refusal("definition", json!({"file": "crlf.sv", "line": line, "col": col}));
|
||||
assert!(refused.contains(&format!("crlf.sv:{line}:{col} names")), "{refused}");
|
||||
}
|
||||
for (line, col, length) in [(2, 15, 13), (3, 11, 9)] {
|
||||
let refused = s.refusal("definition", json!({"file": "crlf.sv", "line": line, "col": col}));
|
||||
assert!(refused.contains(&format!("line {line} is {length} bytes long")), "{refused}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_references_from_a_file_the_walk_skips_answer_without_a_crash() {
|
||||
fn qa_recheck_by_name_uses_count_the_indexed_files_only() {
|
||||
// `ignored/` is gitignored and `notes.txt` is not a source: neither is
|
||||
// indexed, but both are files inside the root, which every read tool
|
||||
// accepts (M1's path rule). Asked from there, the answer is real and
|
||||
// names the file asked from; by name it is the indexed files only.
|
||||
// indexed, so neither is searched by name.
|
||||
let scratch = Scratch::with(&[
|
||||
(".gitignore", "ignored/\n"),
|
||||
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
|
||||
@@ -965,45 +710,29 @@ fn qa_recheck_references_from_a_file_the_walk_skips_answer_without_a_crash() {
|
||||
("notes.txt", "leaf u8 (.a());\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(
|
||||
s.hits(json!({"file": "ignored/ig.sv", "line": 2, "name": "leaf"})),
|
||||
["ignored/ig.sv:2:3", "leaf.sv:1:8", "top.sv:3:3"]
|
||||
);
|
||||
assert_eq!(
|
||||
s.hits(json!({"file": "notes.txt", "line": 1, "name": "leaf"})),
|
||||
["leaf.sv:1:8", "notes.txt:1:1", "top.sv:3:3"]
|
||||
);
|
||||
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3"]);
|
||||
let missing = s.refusal("references", json!({"file": "ignored/none.sv", "line": 1, "col": 1}));
|
||||
assert!(missing.contains("none.sv"), "{missing}");
|
||||
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3\n");
|
||||
// The unindexed file is still one a read tool accepts by path.
|
||||
assert!(s.text("outline", json!({"file": "ignored/ig.sv"})).starts_with("module ig 1–3\n"));
|
||||
assert!(s.pings());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_whole_set_references_drop_a_file_deleted_mid_session() {
|
||||
fn qa_recheck_whole_set_uses_drop_a_file_deleted_mid_session() {
|
||||
let scratch = Scratch::with(&[
|
||||
("leaf.sv", "module leaf (input logic a);\nendmodule\n"),
|
||||
("top.sv", "module top;\n logic a;\n leaf u1 (.a(a));\nendmodule\n"),
|
||||
("gone.sv", "module gone;\n leaf u9 (.a(1'b0));\nendmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(s.hits(json!({"name": "leaf"})), ["gone.sv:2:3", "leaf.sv:1:8", "top.sv:3:3"]);
|
||||
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n gone.sv:2\n top.sv:3\n");
|
||||
fs::remove_file(scratch.path("gone.sv")).unwrap();
|
||||
assert_eq!(s.hits(json!({"name": "leaf"})), ["leaf.sv:1:8", "top.sv:3:3"]);
|
||||
assert_eq!(
|
||||
s.hits(json!({"file": "top.sv", "line": 3, "name": "leaf"})),
|
||||
["leaf.sv:1:8", "top.sv:3:3"]
|
||||
);
|
||||
assert_eq!(s.refs("leaf"), "module leaf leaf.sv:1\n top.sv:3\n");
|
||||
fs::remove_file(scratch.path("leaf.sv")).unwrap();
|
||||
let orphan = s.refusal("references", json!({"file": "top.sv", "line": 3, "name": "leaf"}));
|
||||
assert!(
|
||||
orphan.starts_with("lucisv cannot follow this position: ") && !orphan.contains("rename"),
|
||||
"{orphan}"
|
||||
);
|
||||
s.refusal("find", json!({"name": "leaf", "refs": true}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_three_uses_naming_three_declarations_are_refused_line_by_line() {
|
||||
fn qa_recheck_three_declarations_of_one_name_are_listed_each_with_its_uses() {
|
||||
let scratch = Scratch::with(&[
|
||||
("l1.sv", "module l1 (output logic sig); endmodule\n"),
|
||||
("l2.sv", "module l2 (output logic sig); endmodule\n"),
|
||||
@@ -1015,21 +744,17 @@ fn qa_recheck_three_uses_naming_three_declarations_are_refused_line_by_line() {
|
||||
("same.sv", "module sa;\n l1 u1 ();\n wire w = u1.sig;\n wire v = u1.sig;\nendmodule\n"),
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
let listed = "`sig` on line 3 → l1.sv:1, line 7 → l2.sv:1, line 12 → l3.sv:1; add `line`";
|
||||
for tool in ["definition", "references"] {
|
||||
let refused = s.refusal(tool, json!({"file": "top.sv", "name": "sig"}));
|
||||
assert!(refused.starts_with(listed), "{refused}");
|
||||
}
|
||||
assert_eq!(s.sites(json!({"file": "top.sv", "line": 7, "name": "sig"})), ["l2.sv:1:25 port"]);
|
||||
// Two uses of one declaration are not ambiguous.
|
||||
assert_eq!(s.sites(json!({"file": "same.sv", "name": "sig"})), ["l1.sv:1:25 port"]);
|
||||
assert_eq!(
|
||||
s.refs("sig"),
|
||||
"port sig l1.sv:1\n same.sv:3,4\n top.sv:3\nport sig l2.sv:1\n top.sv:7,8\nport sig l3.sv:1\n top.sv:12\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_unused_waivers_match_lucisv_check_of_the_tree() {
|
||||
// `lucisv check .` here: one `unused-waiver` at w.waiver:1:1 (the second
|
||||
// directive is used by m.sv; `sub/` names the same file and it is read
|
||||
// once); `--select no-tabs` reports nothing.
|
||||
// once).
|
||||
let scratch = Scratch::with(&[
|
||||
(
|
||||
"lucisv.toml",
|
||||
@@ -1045,15 +770,14 @@ fn qa_recheck_unused_waivers_match_lucisv_check_of_the_tree() {
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(
|
||||
s.text("diagnostics", json!({})),
|
||||
"1 finding\nw.waiver\n 1:1 style unused waiver for `no-tabs` [unused-waiver]\n"
|
||||
s.text("check", json!({})),
|
||||
"w.waiver:1:1 style unused waiver for `no-tabs` [unused-waiver]\n"
|
||||
);
|
||||
assert_eq!(s.text("diagnostics", json!({"rules": "no-tabs"})), "no findings\n");
|
||||
assert_eq!(s.text("diagnostics", json!({"file": "m.sv"})), "no findings\n");
|
||||
assert_eq!(s.text("check", json!({"file": "m.sv"})), "ok\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot() {
|
||||
fn qa_recheck_one_files_check_is_its_lines_of_lucisv_check_dot() {
|
||||
// `lucisv check .` prints `./top.sv:2:12: error: `leaf` declares no port
|
||||
// `b` [unknown-port]` and nothing else.
|
||||
let scratch = Scratch::with(&[
|
||||
@@ -1062,8 +786,8 @@ fn qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot() {
|
||||
]);
|
||||
let mut s = Session::ready(&scratch);
|
||||
assert_eq!(
|
||||
s.text("diagnostics", json!({"file": "top.sv"})),
|
||||
"1 finding\ntop.sv\n 2:12 error `leaf` declares no port `b` [unknown-port]\n"
|
||||
s.text("check", json!({"file": "top.sv"})),
|
||||
"top.sv:2:12 error `leaf` declares no port `b` [unknown-port]\n"
|
||||
);
|
||||
assert_eq!(s.text("diagnostics", json!({"file": "leaf.sv"})), "no findings\n");
|
||||
assert_eq!(s.text("check", json!({"file": "leaf.sv"})), "ok\n");
|
||||
}
|
||||
+198
-366
@@ -1,9 +1,11 @@
|
||||
//! QA attacks on lane M3 (the edit tools and their one write path),
|
||||
//! 2026-09-23.
|
||||
//! 2026-09-23 — ported to the lean catalogue (`rename`, `port`,
|
||||
//! `edit_item`, `format`); the tools it dropped took their attacks with
|
||||
//! them (`docs/features/mcp-lean-catalogue/README.md` lists which).
|
||||
//!
|
||||
//! Two kinds of test. The first half includes the production write path,
|
||||
//! `src/apply.rs`, verbatim (`#[path]`) over two small stand-ins for the
|
||||
//! modules it names (`Project`'s roots and `Answer`), so `commit` — the
|
||||
//! `src/apply.rs`, verbatim (`#[path]`) over a small stand-in for the
|
||||
//! module it names (`Project`'s roots), so `commit` — the
|
||||
//! write-freshness rule — can be attacked directly with stale texts; no
|
||||
//! black box can hook the gap between a tool's read and its write. The
|
||||
//! second half spawns the real binary over scratch trees, as a host would.
|
||||
@@ -48,14 +50,6 @@ mod project {
|
||||
}
|
||||
}
|
||||
|
||||
/// Stand-in for `crate::tools`: the answer type `apply.rs` builds.
|
||||
mod tools {
|
||||
pub struct Answer {
|
||||
pub text: String,
|
||||
pub structured: serde_json::Value,
|
||||
}
|
||||
}
|
||||
|
||||
#[path = "../src/apply.rs"]
|
||||
mod apply;
|
||||
|
||||
@@ -261,13 +255,6 @@ fn text_of(result: &Value) -> String {
|
||||
result["content"][0]["text"].as_str().unwrap().to_string()
|
||||
}
|
||||
|
||||
/// `arguments` with `dry_run` set.
|
||||
fn dry(arguments: &Value, dry_run: bool) -> Value {
|
||||
let mut arguments = arguments.clone();
|
||||
arguments["dry_run"] = Value::from(dry_run);
|
||||
arguments
|
||||
}
|
||||
|
||||
/// The `lucisv` CLI built beside `lucisv-mcp`, when the build made it
|
||||
/// (`cargo test --workspace` does; `-p lucisv_mcp` alone may not).
|
||||
fn cli() -> Option<PathBuf> {
|
||||
@@ -275,15 +262,6 @@ fn cli() -> Option<PathBuf> {
|
||||
path.exists().then_some(path)
|
||||
}
|
||||
|
||||
/// `+`/`-` body lines of a unified diff (headers skipped).
|
||||
fn signed_lines(diff: &str) -> (usize, usize) {
|
||||
let body = diff.lines().filter(|l| !l.starts_with("--- ") && !l.starts_with("+++ "));
|
||||
let body: Vec<&str> = body.collect();
|
||||
let added = body.iter().filter(|l| l.starts_with('+')).count();
|
||||
let removed = body.iter().filter(|l| l.starts_with('-')).count();
|
||||
(added, removed)
|
||||
}
|
||||
|
||||
// ================================================ apply::commit, directly
|
||||
|
||||
fn change(path: &Path, before: &str, after: &str) -> apply::Change {
|
||||
@@ -432,95 +410,72 @@ fn qa_plan_refuses_an_unread_file_overlapping_edits_and_a_split_character() {
|
||||
..RefactorEdit::default()
|
||||
};
|
||||
assert!(apply::Plan::from_refactor(two, &texts).err().unwrap().contains("overlap"));
|
||||
// A fitting edit plans, and `run` in dry-run mode writes nothing.
|
||||
// A fitting edit plans, and `run` writes it and says so.
|
||||
fs::write(&read, &texts[0].1).unwrap();
|
||||
let plan = apply::Plan::from_refactor(edit(&read, 0, 6), &texts).unwrap();
|
||||
assert!(plan.warnings.is_empty());
|
||||
let project = project::Project::open(vec![scratch.0.clone()], None);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let answer = apply::run(&project, plan, true).unwrap();
|
||||
assert!(answer.text.contains("(dry run: nothing written)"), "{}", answer.text);
|
||||
assert_eq!(answer.structured["changed"][0]["file"], "r.sv");
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
|
||||
let written = apply::run(&project, &plan).unwrap();
|
||||
assert_eq!((written.changed, written.created), (vec!["r.sv".to_string()], vec![]));
|
||||
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["r.sv"]);
|
||||
assert_eq!(fs::read_to_string(&read).unwrap(), "z é; endmodule\n");
|
||||
}
|
||||
|
||||
// ================================================ corruption hunt (attack 1)
|
||||
|
||||
/// Every edit tool, one real call over a fresh fixture copy: exactly the
|
||||
/// reported files move, each reported count matches the dry run's diff, the
|
||||
/// dry-run diff is the diff of what was written, and the same call again
|
||||
/// writes nothing.
|
||||
/// expected files move, the answer's counts are the files that moved, and
|
||||
/// the same call again writes nothing.
|
||||
#[test]
|
||||
fn qa_every_edit_writes_only_what_it_reports_and_a_repeat_writes_nothing() {
|
||||
let calls = [
|
||||
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"})),
|
||||
("rename", json!({"name": "d", "unit": "leaf", "new_name": "din_i"})),
|
||||
("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6})),
|
||||
("convert_ports", json!({"file": "rtl/old.sv", "line": 1})),
|
||||
("organize_imports", json!({"file": "rtl/top.sv", "line": 6})),
|
||||
("inline_module", json!({"file": "rtl/inl.sv", "line": 5})),
|
||||
("propagate_ports", json!({"file": "rtl/partial.sv", "line": 6})),
|
||||
("remove_port", json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"})),
|
||||
("add_port", json!({"module": "leaf", "declaration": "input logic en"})),
|
||||
fn qa_every_edit_writes_only_what_it_says_and_a_repeat_writes_nothing() {
|
||||
let calls: [(&str, Value, &[&str]); 7] = [
|
||||
(
|
||||
"add_port",
|
||||
json!({"file": "rtl/cell.sv", "line": 3, "declaration": "input logic rst_ni"}),
|
||||
"rename",
|
||||
json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}),
|
||||
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
|
||||
),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}),
|
||||
"port",
|
||||
json!({"module": "spare", "remove": "unused_i"}),
|
||||
&["rtl/spare.sv", "rtl/spare_user.sv"],
|
||||
),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 8, "end_line": 8, "new_name": "reg8", "home": "same_file"}),
|
||||
"port",
|
||||
json!({"module": "leaf", "add": "input logic en"}),
|
||||
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
|
||||
),
|
||||
(
|
||||
"port",
|
||||
json!({"module": "leaf", "add": "input logic en", "after": "clk"}),
|
||||
&["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"],
|
||||
),
|
||||
("format", json!({"files": "fmt/messy.sv"}), &["fmt/messy.sv"]),
|
||||
("format", json!({"files": "fmt/messy.sv", "fix": true}), &["fmt/messy.sv"]),
|
||||
(
|
||||
"edit_item",
|
||||
json!({"file": "rtl/leaf.sv", "op": "insert_after", "item": "end", "text": "logic spare_q;"}),
|
||||
&["rtl/leaf.sv"],
|
||||
),
|
||||
("format", json!({"files": "fmt/messy.sv,rtl/mid.sv"})),
|
||||
("fix_lint", json!({"file": "fmt/messy.sv"})),
|
||||
];
|
||||
for (tool, arguments) in calls {
|
||||
for (tool, arguments, expected) in calls {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
scratch.write("fmt/messy.sv", "module messy(input logic a,output logic b); \nassign b=a;\n // keep this comment\nendmodule");
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let preview = server.ok(tool, dry(&arguments, true))["structuredContent"].clone();
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool}: dry run wrote");
|
||||
let result = server.ok(tool, dry(&arguments, false));
|
||||
let said = server.text(tool, arguments.clone());
|
||||
let written = snapshot(&scratch.0);
|
||||
let reported = &result["structuredContent"];
|
||||
let mut listed: Vec<String> = ["changed", "created"]
|
||||
.iter()
|
||||
.flat_map(|key| reported[*key].as_array().unwrap().clone())
|
||||
.map(|entry| entry["file"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
listed.sort();
|
||||
assert_eq!(moved(&pristine, &written), listed, "{tool} {arguments}: {result}");
|
||||
for key in ["changed", "created"] {
|
||||
for (real, shown) in
|
||||
reported[key].as_array().unwrap().iter().zip(preview[key].as_array().unwrap())
|
||||
{
|
||||
let file = real["file"].as_str().unwrap();
|
||||
let before = pristine.get(file).map(|(_, b)| b.clone()).unwrap_or_default();
|
||||
let after = &written[file].1;
|
||||
let diff = lucisv_core::diff::unified(
|
||||
file,
|
||||
std::str::from_utf8(&before).unwrap(),
|
||||
std::str::from_utf8(after).unwrap(),
|
||||
);
|
||||
assert_eq!(shown["diff"].as_str().unwrap(), diff, "{tool}: {file}");
|
||||
let (added, removed) = signed_lines(&diff);
|
||||
assert_eq!(
|
||||
(real["added"].as_u64(), real["removed"].as_u64()),
|
||||
(Some(added as u64), Some(removed as u64)),
|
||||
"{tool}: {file}"
|
||||
);
|
||||
}
|
||||
assert_eq!(moved(&pristine, &written), expected, "{tool} {arguments}: {said}");
|
||||
if tool == "rename" {
|
||||
assert!(said.starts_with("renamed 4 sites in 3 files\n"), "{said}");
|
||||
}
|
||||
let again = server.call(tool, dry(&arguments, false));
|
||||
// Not idempotent: the same insertion again would declare twice.
|
||||
let again = server.call(tool, arguments.clone());
|
||||
let said = text_of(&again);
|
||||
assert!(
|
||||
said.starts_with("unchanged") || again["isError"] == true,
|
||||
"{tool}: a repeat must write nothing: {said}"
|
||||
moved(&written, &snapshot(&scratch.0)).is_empty(),
|
||||
"{tool}: the repeat wrote: {said}"
|
||||
);
|
||||
assert!(moved(&written, &snapshot(&scratch.0)).is_empty(), "{tool}: the repeat wrote");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,44 +494,24 @@ fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let outside_pristine = snapshot(&outside.0);
|
||||
let leaf_d = |new_name: &str| json!({"name": "d", "file": "rtl/leaf.sv", "new_name": new_name});
|
||||
let refused = [
|
||||
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "module"})),
|
||||
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "clk"})),
|
||||
("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "\\a+b "})),
|
||||
("rename", leaf_d("module")),
|
||||
("rename", leaf_d("clk")),
|
||||
("rename", leaf_d("\\a+b ")),
|
||||
("rename", json!({"name": "clk", "new_name": "ck"})),
|
||||
("rename", json!({"file": "out/o.sv", "line": 1, "col": 8, "new_name": "p"})),
|
||||
("expand_wildcard", json!({"file": "rtl/pos.sv", "line": 2})),
|
||||
("convert_ports", json!({"file": "rtl/leaf.sv", "line": 1})),
|
||||
("organize_imports", json!({"file": "rtl/leaf.sv", "line": 99})),
|
||||
("inline_module", json!({"file": "rtl/pos.sv", "line": 2})),
|
||||
("inline_module", json!({"file": "rtl/wild.sv", "line": 6})),
|
||||
("propagate_ports", json!({"file": "rtl/mid.sv", "line": 6})),
|
||||
("propagate_ports", json!({"file": "rtl/wild.sv", "line": 6})),
|
||||
("remove_port", json!({"file": "rtl/cell.sv", "line": 3, "name": "en"})),
|
||||
("remove_port", json!({"file": "rtl/pos.sv", "line": 1, "name": "en"})),
|
||||
("add_port", json!({"module": "cell", "declaration": "input logic en"})),
|
||||
("add_port", json!({"module": "cell", "declaration": "input logic newp"})),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 1, "end_line": 2, "new_name": "x2"}),
|
||||
),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "leaf"}),
|
||||
),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "../x"}),
|
||||
),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "out/o.sv", "start_line": 1, "end_line": 1, "new_name": "x3"}),
|
||||
),
|
||||
("format", json!({"files": "fmt/messy.sv,fmt/broken.sv"})),
|
||||
("format", json!({"file": "out/o.sv"})),
|
||||
("format", json!({"file": "fmt/messy.sv", "lines": "3-1"})),
|
||||
("fix_lint", json!({"file": "/etc/hosts"})),
|
||||
("instantiate", json!({"name": "nothing_here"})),
|
||||
("rename", json!({"name": "o", "file": "out/o.sv", "new_name": "p"})),
|
||||
("port", json!({"module": "cell", "remove": "en"})),
|
||||
("port", json!({"module": "pos", "remove": "en"})),
|
||||
("port", json!({"module": "cell", "add": "input logic en"})),
|
||||
("port", json!({"module": "cell", "add": "input logic newp"})),
|
||||
("port", json!({"module": "leaf", "add": "input logic x", "after": "nope"})),
|
||||
("edit_item", json!({"file": "rtl/leaf.sv", "op": "delete", "item": "leaf"})),
|
||||
("edit_item", json!({"file": "out/o.sv", "op": "delete", "item": "o"})),
|
||||
("format", json!({"files": "fmt/broken.sv"})),
|
||||
("format", json!({"files": "out/o.sv"})),
|
||||
("format", json!({"files": "/etc/hosts"})),
|
||||
("format", json!({"files": "fpv/**/*.sv"})),
|
||||
];
|
||||
for (tool, arguments) in refused {
|
||||
let said = server.refusal(tool, arguments.clone());
|
||||
@@ -587,8 +522,8 @@ fn qa_every_refusal_leaves_every_byte_and_mode_identical() {
|
||||
}
|
||||
|
||||
/// Comments beside every edited span survive: a port with a trailing
|
||||
/// comment renamed, a `.*` with comments in its list expanded, a block with
|
||||
/// a leading and a trailing comment extracted.
|
||||
/// comment renamed, a `.*` with comments in its list written out by the
|
||||
/// rename, a port placed after a commented one.
|
||||
#[test]
|
||||
fn qa_comments_around_every_edited_span_survive() {
|
||||
let scratch = Scratch::with(&[
|
||||
@@ -600,10 +535,6 @@ fn qa_comments_around_every_edited_span_survive() {
|
||||
"top.sv",
|
||||
"module top (\n input logic clk,\n input logic [7:0] d,\n output logic [7:0] q\n);\n // the instance\n leaf u_leaf (\n // leading\n .* // trailing star comment\n /* block */\n );\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"ext.sv",
|
||||
"module ext (\n input logic clk,\n input logic [7:0] a,\n output logic [7:0] q\n);\n logic [7:0] s;\n // the adder\n assign s = a + 8'd1; // plus one\n always_ff @(posedge clk) q <= s;\nendmodule\n",
|
||||
),
|
||||
]);
|
||||
let comments = [
|
||||
"// the clock",
|
||||
@@ -614,8 +545,6 @@ fn qa_comments_around_every_edited_span_survive() {
|
||||
"// leading",
|
||||
"// trailing star comment",
|
||||
"/* block */",
|
||||
"// the adder",
|
||||
"// plus one",
|
||||
];
|
||||
let count = |scratch: &Scratch, comment: &str| -> usize {
|
||||
snapshot(&scratch.0)
|
||||
@@ -625,12 +554,8 @@ fn qa_comments_around_every_edited_span_survive() {
|
||||
};
|
||||
let before: Vec<usize> = comments.iter().map(|c| count(&scratch, c)).collect();
|
||||
let mut server = Session::over(&scratch);
|
||||
server.text("expand_wildcard", json!({"file": "top.sv", "line": 7}));
|
||||
server.text(
|
||||
"extract_module",
|
||||
json!({"file": "ext.sv", "start_line": 7, "end_line": 8, "new_name": "adder"}),
|
||||
);
|
||||
server.text("rename", json!({"file": "leaf.sv", "line": 3, "name": "d", "new_name": "din"}));
|
||||
server.text("rename", json!({"name": "d", "file": "leaf.sv", "new_name": "din"}));
|
||||
server.text("port", json!({"module": "leaf", "add": "input logic en", "after": "clk"}));
|
||||
let after: Vec<usize> = comments.iter().map(|c| count(&scratch, c)).collect();
|
||||
assert_eq!(before, after, "{:?}", snapshot(&scratch.0).keys().collect::<Vec<_>>());
|
||||
assert!(scratch.read("leaf.sv").contains("din, // data in"), "{}", scratch.read("leaf.sv"));
|
||||
@@ -650,7 +575,7 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
|
||||
let files = ["rtl/leaf.sv", "rtl/mid.sv", "rtl/top.sv"];
|
||||
let target = "rtl/mid.sv";
|
||||
let mut server = Session::over(&scratch);
|
||||
let at = |from: &str, to: &str| json!({"file": "rtl/leaf.sv", "line": 3, "name": from, "new_name": to});
|
||||
let at = |from: &str, to: &str| json!({"name": from, "file": "rtl/leaf.sv", "new_name": to});
|
||||
let original: Vec<String> = files.iter().map(|f| scratch.read(f)).collect();
|
||||
server.text("rename", at("d", "din_i"));
|
||||
let renamed: Vec<String> = files.iter().map(|f| scratch.read(f)).collect();
|
||||
@@ -704,36 +629,23 @@ fn qa_a_rename_racing_a_writer_never_tears_a_file() {
|
||||
// ================================================ paths (attack 3)
|
||||
|
||||
#[test]
|
||||
fn qa_created_and_rewritten_paths_never_leave_the_root() {
|
||||
fn qa_rewritten_paths_never_leave_the_root() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
let outside = Scratch::with(&[("ext.sv", &Scratch::edit_fixture().read("rtl/ext.sv"))]);
|
||||
std::os::unix::fs::symlink(&outside.0, scratch.path("link")).unwrap();
|
||||
std::os::unix::fs::symlink(outside.path("adder.sv"), scratch.path("rtl/adder.sv")).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let outside_pristine = snapshot(&outside.0);
|
||||
let extract = |file: &str, name: &str| json!({"file": file, "start_line": 7, "end_line": 7, "new_name": name});
|
||||
for name in ["../evil", "/tmp/evil", "\\../../evil ", "a/b", ""] {
|
||||
let said = server.refusal("extract_module", extract("rtl/ext.sv", name));
|
||||
assert!(!said.is_empty());
|
||||
}
|
||||
let said = server.refusal("extract_module", extract("link/ext.sv", "adder"));
|
||||
assert!(said.contains("outside every root"), "{said}");
|
||||
let abs = outside.path("ext.sv");
|
||||
let said = server.refusal("extract_module", extract(abs.to_str().unwrap(), "adder"));
|
||||
assert!(said.contains("outside every root"), "{said}");
|
||||
// A dangling symlink at the created path, pointing out of the root.
|
||||
let said = server.refusal("extract_module", extract("rtl/ext.sv", "adder"));
|
||||
assert!(said.contains("adder.sv"), "{said}");
|
||||
fs::remove_file(scratch.path("rtl/adder.sv")).unwrap();
|
||||
fs::create_dir(scratch.path("rtl/adder.sv")).unwrap();
|
||||
let said = server.refusal("extract_module", extract("rtl/ext.sv", "adder"));
|
||||
assert!(said.contains("adder.sv"), "{said}");
|
||||
fs::remove_dir(scratch.path("rtl/adder.sv")).unwrap();
|
||||
std::os::unix::fs::symlink(outside.path("adder.sv"), scratch.path("rtl/adder.sv")).unwrap();
|
||||
for file in ["link/ext.sv", abs.to_str().unwrap()] {
|
||||
let delete = json!({"file": file, "op": "delete", "item": "s"});
|
||||
assert!(server.refusal("edit_item", delete).contains("outside every root"));
|
||||
assert!(server.refusal("format", json!({"files": file})).contains("outside every root"));
|
||||
let rename = json!({"name": "s", "file": file, "new_name": "t"});
|
||||
assert!(server.refusal("rename", rename).contains("outside every root"));
|
||||
}
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
|
||||
assert!(moved(&outside_pristine, &snapshot(&outside.0)).is_empty());
|
||||
assert!(!Path::new("/tmp/evil.sv").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -742,19 +654,17 @@ fn qa_a_read_only_target_refuses_before_the_first_write() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
// `top.sv` sorts last of the rename's three files.
|
||||
fs::set_permissions(scratch.path("rtl/top.sv"), fs::Permissions::from_mode(0o444)).unwrap();
|
||||
// A trailing blank so `fix_lint` has something to write.
|
||||
// A trailing blank so `fix` has something to write.
|
||||
scratch.write("fmt/messy.sv", &scratch.read("fmt/messy.sv").replace("b=a;", "b=a; "));
|
||||
fs::set_permissions(scratch.path("fmt/messy.sv"), fs::Permissions::from_mode(0o444)).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let said = server.refusal(
|
||||
"rename",
|
||||
json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}),
|
||||
);
|
||||
let said =
|
||||
server.refusal("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}));
|
||||
assert_eq!(said, "`rtl/top.sv` is read-only; nothing written.");
|
||||
let said = server.refusal("format", json!({"files": "fmt/messy.sv"}));
|
||||
assert_eq!(said, "`fmt/messy.sv` is read-only; nothing written.");
|
||||
let said = server.refusal("fix_lint", json!({"file": "fmt/messy.sv"}));
|
||||
let said = server.refusal("format", json!({"files": "fmt/messy.sv", "fix": true}));
|
||||
assert_eq!(said, "`fmt/messy.sv` is read-only; nothing written.");
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
|
||||
}
|
||||
@@ -764,10 +674,11 @@ 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")]);
|
||||
std::os::unix::fs::symlink("real.sv", scratch.path("alias.sv")).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let text = server.text("format", json!({"files": "alias.sv,real.sv"}));
|
||||
assert_eq!(text, "files: 1 changed, 0 created\n real.sv +1 -1\n");
|
||||
let text = server.text("format", json!({"files": "alias.sv"}));
|
||||
assert_eq!(text, "formatted 1 file (0 unchanged)\n");
|
||||
assert!(fs::symlink_metadata(scratch.path("alias.sv")).unwrap().file_type().is_symlink());
|
||||
assert_eq!(scratch.read("real.sv"), "module r (input logic a);\nendmodule\n");
|
||||
assert_eq!(server.text("format", json!({"files": "*.sv"})), "formatted 1 file (1 unchanged)\n");
|
||||
}
|
||||
|
||||
// ================================================ concurrency with the CLI (attack 4)
|
||||
@@ -809,16 +720,15 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
|
||||
})
|
||||
};
|
||||
let mut server = Session::over(&scratch);
|
||||
let files = names.join(",");
|
||||
for _ in 0..5 {
|
||||
for (name, text) in &messy {
|
||||
scratch.write(name, text);
|
||||
}
|
||||
let result = server.call("format", json!({"files": files}));
|
||||
let result = server.call("format", json!({"files": "m*.sv"}));
|
||||
let said = text_of(&result);
|
||||
assert!(result["isError"] == false || said.contains("changed on disk"), "{said}");
|
||||
}
|
||||
server.text("format", json!({"files": files}));
|
||||
server.text("format", json!({"files": "m*.sv"}));
|
||||
stop.store(true, Ordering::SeqCst);
|
||||
let codes = checker.join().unwrap();
|
||||
assert!(!codes.is_empty());
|
||||
@@ -831,9 +741,7 @@ fn qa_lucisv_check_over_the_same_tree_while_the_server_formats() {
|
||||
// ================================================ format (attack 5)
|
||||
|
||||
/// `format` writes what `lucisv` writes, byte for byte: a CRLF file, a file
|
||||
/// under a nested lucisv.toml with a different line length, a fenced
|
||||
/// region, and `lines` ranges that overlap, run backwards in order, or pass
|
||||
/// the end.
|
||||
/// under a nested lucisv.toml with a different line length, a fenced region.
|
||||
#[test]
|
||||
fn qa_format_writes_the_clis_bytes() {
|
||||
let Some(cli) = cli() else {
|
||||
@@ -850,7 +758,6 @@ fn qa_format_writes_the_clis_bytes() {
|
||||
"fence.sv",
|
||||
"module f(input logic a,output logic b);\n// lucisv: off\nassign b=a;\n// lucisv: on\nlogic c;\nendmodule\n",
|
||||
),
|
||||
("r.sv", "module r(input logic a,output logic b);\nlogic x;\nassign b=a;\nlogic y;\nendmodule\n"),
|
||||
];
|
||||
let mcp = Scratch::with(files);
|
||||
let mut server = Session::over(&mcp);
|
||||
@@ -858,50 +765,33 @@ fn qa_format_writes_the_clis_bytes() {
|
||||
let cli_tree = Scratch::with(files);
|
||||
let out = Command::new(&cli).arg("--no-cache").arg(cli_tree.path(file)).output().unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
server.text("format", json!({"file": file}));
|
||||
server.text("format", json!({"files": file}));
|
||||
assert_eq!(mcp.read(file), cli_tree.read(file), "{file}");
|
||||
}
|
||||
for lines in ["2,1-2,99", "4,2", "4-4,2-2", "50-60", "1-999"] {
|
||||
let cli_tree = Scratch::with(files);
|
||||
let out = Command::new(&cli)
|
||||
.args(["--no-cache", "--lines", lines])
|
||||
.arg(cli_tree.path("r.sv"))
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{lines}: {out:?}");
|
||||
mcp.write("r.sv", files[5].1);
|
||||
server.text("format", json!({"file": "r.sv", "lines": lines}));
|
||||
assert_eq!(mcp.read("r.sv"), cli_tree.read("r.sv"), "lines {lines}");
|
||||
}
|
||||
// A duplicate in `files` is one file, written once.
|
||||
mcp.write("w.sv", long);
|
||||
let text = server.text("format", json!({"files": "w.sv, w.sv,./w.sv", "dry_run": true}));
|
||||
assert_eq!(text.matches("--- w.sv\n").count(), 1, "{text}");
|
||||
}
|
||||
|
||||
// ================================================ fix_lint (attack 1, 5)
|
||||
// ================================================ fix (attack 1, 5)
|
||||
|
||||
/// `fix_lint` writes what `lucisv check --fix` writes: nothing inside a
|
||||
/// `// lucisv: off` or `// verilog_format: off` fence, and never the
|
||||
/// unsafe `always-comb` fix, even when that rule is the only one asked for.
|
||||
/// `format` with `fix` writes what `lucisv check --fix` then `lucisv`
|
||||
/// write: nothing inside a `// lucisv: off` or `// verilog_format: off`
|
||||
/// fence, and never the unsafe `always-comb` fix.
|
||||
#[test]
|
||||
fn qa_fix_lint_matches_check_fix_and_never_touches_a_fence_or_an_unsafe_fix() {
|
||||
fn qa_fix_matches_check_fix_and_never_touches_a_fence_or_an_unsafe_fix() {
|
||||
let source = "module f (input logic a, output logic b, output logic c);\n\tlogic t; \n // lucisv: off \n assign b = a;; \n\tassign t = a;\n // lucisv: on\n always @* c = a;\n assign t2 = 4'b1;;\n // verilog_format: off\n wire z;; \n // verilog_format: on\nendmodule";
|
||||
let scratch = Scratch::with(&[("f.sv", source)]);
|
||||
let mut server = Session::over(&scratch);
|
||||
let unsafe_only = server.text("fix_lint", json!({"file": "f.sv", "rules": "always-comb"}));
|
||||
assert!(unsafe_only.starts_with("unchanged\n"), "{unsafe_only}");
|
||||
assert_eq!(scratch.read("f.sv"), source);
|
||||
server.text("fix_lint", json!({"file": "f.sv"}));
|
||||
server.text("format", json!({"files": "f.sv", "fix": true}));
|
||||
let fixed = scratch.read("f.sv");
|
||||
for fenced in [" // lucisv: off \n assign b = a;; \n\tassign t = a;\n", " wire z;; \n"]
|
||||
{
|
||||
assert!(fixed.contains(fenced), "a fenced line moved: {fixed:?}");
|
||||
}
|
||||
assert!(fixed.contains("always @* c = a;"), "an unsafe fix was applied: {fixed:?}");
|
||||
assert!(!fixed.contains("always_comb"), "an unsafe fix was applied: {fixed:?}");
|
||||
assert!(!fixed.contains("4'b1;;"), "the safe fix was not applied: {fixed:?}");
|
||||
if let Some(cli) = cli() {
|
||||
let cli_tree = Scratch::with(&[("f.sv", source)]);
|
||||
Command::new(&cli).args(["check", "--fix"]).arg(cli_tree.path("f.sv")).output().unwrap();
|
||||
Command::new(&cli).arg("--no-cache").arg(cli_tree.path("f.sv")).output().unwrap();
|
||||
assert_eq!(fixed, cli_tree.read("f.sv"));
|
||||
}
|
||||
}
|
||||
@@ -938,7 +828,7 @@ fn qa_rename_writes_exactly_what_the_engine_answers_over_all_files() {
|
||||
assert_eq!(expected.len(), 3);
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
server.text("rename", json!({"name": "d", "unit": "leaf", "new_name": "din_i"}));
|
||||
server.text("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}));
|
||||
let written: Vec<String> = moved(&pristine, &snapshot(&scratch.0));
|
||||
assert_eq!(written, expected.keys().cloned().collect::<Vec<_>>());
|
||||
for (file, text) in &expected {
|
||||
@@ -947,31 +837,25 @@ fn qa_rename_writes_exactly_what_the_engine_answers_over_all_files() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rename_by_bare_name_picks_the_declaration_references_picks() {
|
||||
fn qa_rename_by_name_writes_the_files_find_lists() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
let mut server = Session::over(&scratch);
|
||||
let refs = server.ok("references", json!({"name": "din"}))["structuredContent"].clone();
|
||||
let mut hit_files: Vec<String> = refs["hits"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| h["file"].as_str().unwrap().to_string())
|
||||
let found = server.text("find", json!({"name": "din", "refs": true}));
|
||||
let mut files: Vec<String> = found
|
||||
.lines()
|
||||
.map(|line| line.trim().rsplit(' ').next().unwrap().split(':').next().unwrap().to_string())
|
||||
.collect();
|
||||
hit_files.dedup();
|
||||
let preview = server.ok("rename", json!({"name": "din", "new_name": "d_in", "dry_run": true}));
|
||||
let files: Vec<String> = preview["structuredContent"]["changed"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|c| c["file"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
assert_eq!(files, hit_files);
|
||||
files.sort();
|
||||
files.dedup();
|
||||
let pristine = snapshot(&scratch.0);
|
||||
server.text("rename", json!({"name": "din", "new_name": "d_in"}));
|
||||
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), files, "{found}");
|
||||
// Ambiguous: refused, listing every site.
|
||||
let said = server.refusal("rename", json!({"name": "q", "new_name": "qq"}));
|
||||
for site in ["rtl/ext.sv:4", "rtl/leaf.sv:4"] {
|
||||
assert!(said.contains(site), "{said}");
|
||||
}
|
||||
assert!(said.contains("pick one"), "{said}");
|
||||
assert!(said.contains("pass `file`"), "{said}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -984,19 +868,17 @@ fn qa_rename_surfaces_the_engines_macro_warning() {
|
||||
),
|
||||
]);
|
||||
let mut server = Session::over(&scratch);
|
||||
let text = server.text(
|
||||
"rename",
|
||||
json!({"file": "m.sv", "line": 2, "name": "sig_a", "new_name": "sig_b", "dry_run": true}),
|
||||
);
|
||||
assert!(text.contains("warnings:\n `sig_a` appears in the arguments of the macro"), "{text}");
|
||||
let text = server.text("rename", json!({"name": "sig_a", "new_name": "sig_b"}));
|
||||
assert!(text.contains("\nwarning: `sig_a` appears in the arguments of the macro"), "{text}");
|
||||
assert!(text.ends_with("unresolved:\n m.sv:3\n"), "{text}");
|
||||
}
|
||||
|
||||
// ================================================ findings
|
||||
|
||||
/// Finding 1 (blocking, engine): renaming a port bound by an implicit
|
||||
/// connection (`.*` or `.name`), or a net such a connection binds, writes a
|
||||
/// "verified" edit that silently changes the connectivity. It must refuse
|
||||
/// (or rewrite the connection explicitly) — never leave the binding broken.
|
||||
/// connection (`.*` or `.name`), or a net such a connection binds, must
|
||||
/// refuse or rewrite the connection explicitly — never leave the binding
|
||||
/// broken (M3.5).
|
||||
#[test]
|
||||
fn qa_rename_never_breaks_an_implicit_port_connection() {
|
||||
let files: &[(&str, &str)] = &[
|
||||
@@ -1015,11 +897,11 @@ fn qa_rename_never_breaks_an_implicit_port_connection() {
|
||||
];
|
||||
let cases = [
|
||||
// The port: `.*` in top.sv and `.d` in top2.sv stop binding it.
|
||||
json!({"file": "leaf.sv", "line": 1, "name": "d", "new_name": "din"}),
|
||||
json!({"name": "d", "file": "leaf.sv", "new_name": "din"}),
|
||||
// The net `.*` binds.
|
||||
json!({"file": "top.sv", "line": 1, "name": "d", "new_name": "x"}),
|
||||
json!({"name": "d", "file": "top.sv", "new_name": "x"}),
|
||||
// The net `.d` binds.
|
||||
json!({"file": "top2.sv", "line": 1, "name": "d", "new_name": "x"}),
|
||||
json!({"name": "d", "file": "top2.sv", "new_name": "x"}),
|
||||
];
|
||||
for arguments in cases {
|
||||
let scratch = Scratch::with(files);
|
||||
@@ -1041,9 +923,8 @@ fn qa_rename_never_breaks_an_implicit_port_connection() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Finding 2 (blocking): a rename leaves unrenamed every use in a file the
|
||||
/// index skipped (over 1 MiB, or not UTF-8) and reports success without a
|
||||
/// word. It must refuse, or at least name the file it could not read.
|
||||
/// Finding 2 (blocking): a rename must not leave unrenamed a use in a file
|
||||
/// the index skipped (over 1 MiB, or not UTF-8) without a word.
|
||||
#[test]
|
||||
fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() {
|
||||
let filler: String = (0..12_000)
|
||||
@@ -1060,8 +941,7 @@ fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() {
|
||||
);
|
||||
fs::write(scratch.path("rtl/mid2.sv"), latin1).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let result = server
|
||||
.call("rename", json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i"}));
|
||||
let result = server.rename_d();
|
||||
let said = text_of(&result);
|
||||
assert!(
|
||||
result["isError"] == true || (said.contains("rtl/big.sv") && said.contains("rtl/mid2.sv")),
|
||||
@@ -1069,52 +949,23 @@ fn qa_rename_says_so_when_a_skipped_file_mentions_the_name() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Finding 3 (non-blocking, engine): `extract_module` into a CRLF file
|
||||
/// writes its instantiation with LF line endings, leaving the file mixed.
|
||||
/// Finding 4 (lead's ruling: no change), kept for the flags that remain:
|
||||
/// JSON null is "not given" for every argument; `"true"` and `1` are
|
||||
/// refused as non-booleans.
|
||||
#[test]
|
||||
#[ignore = "QA finding 3: engine-side, Handshake MCP-10 to vlog_refactor"]
|
||||
fn qa_extract_module_keeps_a_crlf_file_crlf() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
let crlf = scratch.read("rtl/ext.sv").replace('\n', "\r\n");
|
||||
scratch.write("rtl/ext.sv", &crlf);
|
||||
let mut server = Session::over(&scratch);
|
||||
server.text(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}),
|
||||
);
|
||||
let ext = scratch.read("rtl/ext.sv");
|
||||
let bare = ext.split_inclusive('\n').filter(|line| !line.ends_with("\r\n")).count();
|
||||
assert_eq!(bare, 0, "{ext:?}");
|
||||
}
|
||||
|
||||
/// Finding 4 (non-blocking, lead's ruling: no change): `"dry_run": null`
|
||||
/// means absent — JSON null is "not given" for every argument — so the edit
|
||||
/// is written; `"true"` and `1` are refused as non-booleans.
|
||||
#[test]
|
||||
fn qa_a_null_dry_run_is_absent_and_a_non_boolean_is_refused() {
|
||||
fn qa_a_null_flag_is_absent_and_a_non_boolean_is_refused() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
for not_boolean in [json!("true"), json!(1)] {
|
||||
let arguments = json!({"file": "fmt/messy.sv", "dry_run": not_boolean});
|
||||
let arguments = json!({"files": "fmt/messy.sv", "fix": not_boolean});
|
||||
server.refusal("format", arguments);
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty());
|
||||
}
|
||||
let result = server.call("format", json!({"file": "fmt/messy.sv", "dry_run": null}));
|
||||
let result = server.call("format", json!({"files": "fmt/messy.sv", "fix": null}));
|
||||
assert_eq!(moved(&pristine, &snapshot(&scratch.0)), ["fmt/messy.sv"], "{}", text_of(&result));
|
||||
}
|
||||
|
||||
/// Finding 5 (non-blocking): `instantiate` takes any `instance` string, so
|
||||
/// an empty or non-identifier name renders text that does not parse.
|
||||
#[test]
|
||||
fn qa_instantiate_refuses_an_instance_name_that_is_not_an_identifier() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
let mut server = Session::over(&scratch);
|
||||
for instance in ["", "a b", "u_x); evil (", "module"] {
|
||||
server.refusal("instantiate", json!({"name": "leaf", "instance": instance}));
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================ re-check, 2026-09-23 (finding 2's rework)
|
||||
|
||||
/// A 1.1 MB file: `module big` with `line` before `endmodule`.
|
||||
@@ -1132,7 +983,12 @@ fn latin1(body: &[u8]) -> Vec<u8> {
|
||||
bytes
|
||||
}
|
||||
|
||||
const RENAME_D: fn(bool) -> Value = |dry_run| json!({"file": "rtl/leaf.sv", "line": 3, "col": 22, "new_name": "din_i", "dry_run": dry_run});
|
||||
impl Session {
|
||||
/// A rename of `leaf`'s port `d` to `din_i`.
|
||||
fn rename_d(&mut self) -> Value {
|
||||
self.call("rename", json!({"name": "d", "file": "rtl/leaf.sv", "new_name": "din_i"}))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_recheck_a_skipped_file_spelling_the_name_refuses_naming_file_and_reason() {
|
||||
@@ -1146,13 +1002,12 @@ fn qa_recheck_a_skipped_file_spelling_the_name_refuses_naming_file_and_reason()
|
||||
fs::write(scratch.path(file), &bytes).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
for dry_run in [true, false] {
|
||||
let said = server.refusal("rename", RENAME_D(dry_run));
|
||||
assert_eq!(
|
||||
said,
|
||||
format!("`{file}` (skipped: {why}) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written.")
|
||||
);
|
||||
}
|
||||
let result = server.rename_d();
|
||||
assert_eq!(result["isError"], true, "{result}");
|
||||
assert_eq!(
|
||||
text_of(&result),
|
||||
format!("`{file}` (skipped: {why}) may reference `d`; lucisv-mcp will not edit around a file it cannot index; nothing written.")
|
||||
);
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{file}");
|
||||
}
|
||||
}
|
||||
@@ -1171,8 +1026,9 @@ fn qa_recheck_a_substring_only_is_written_with_the_skipped_file_named() {
|
||||
fs::write(scratch.path(file), &bytes).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let text = server.text("rename", RENAME_D(false));
|
||||
let line = format!("warnings:\n not indexed, so not searched or edited: {file} ({why})\n");
|
||||
let result = server.rename_d();
|
||||
let text = text_of(&result);
|
||||
let line = format!("warning: not indexed, so not searched or edited: {file} ({why})\n");
|
||||
assert!(text.contains(&line), "{text}");
|
||||
assert_eq!(text.matches("not indexed").count(), 1, "{text}");
|
||||
let written = moved(&pristine, &snapshot(&scratch.0));
|
||||
@@ -1198,14 +1054,14 @@ fn qa_recheck_the_whole_word_rule_holds_at_every_edge() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
fs::write(scratch.path("rtl/lat.sv"), bytes).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let said = server.refusal("rename", RENAME_D(true));
|
||||
let said = text_of(&server.rename_d());
|
||||
assert!(said.starts_with("`rtl/lat.sv` (skipped: not UTF-8 text)"), "{bytes:?}: {said}");
|
||||
}
|
||||
let mut at_end = oversized("").into_bytes();
|
||||
at_end.extend_from_slice(b"d");
|
||||
let scratch = Scratch::edit_fixture();
|
||||
fs::write(scratch.path("rtl/big.sv"), at_end).unwrap();
|
||||
let said = Session::over(&scratch).refusal("rename", RENAME_D(true));
|
||||
let said = text_of(&Session::over(&scratch).rename_d());
|
||||
assert!(said.starts_with("`rtl/big.sv` (skipped: over 1 MiB)"), "{said}");
|
||||
}
|
||||
|
||||
@@ -1215,8 +1071,7 @@ fn qa_recheck_the_whole_word_rule_holds_at_every_edge() {
|
||||
#[test]
|
||||
fn qa_recheck_an_escaped_name_is_guarded_by_its_escaped_spelling() {
|
||||
let esc = "module esc (input logic \\a+b , output logic y);\n assign y = \\a+b ;\nendmodule\n";
|
||||
let rename =
|
||||
json!({"file": "rtl/esc.sv", "line": 2, "col": 14, "new_name": "ab", "dry_run": true});
|
||||
let rename = json!({"name": "\\a+b", "file": "rtl/esc.sv", "new_name": "ab"});
|
||||
let cases: [(&[u8], bool); 5] = [
|
||||
(b"\\a+b\t", true),
|
||||
(b"x = \\a+b\n;", true),
|
||||
@@ -1238,9 +1093,9 @@ fn qa_recheck_an_escaped_name_is_guarded_by_its_escaped_spelling() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Every whole-set edit tool refuses over its stake (the README's table)
|
||||
/// when only a skipped file spells it; `organize_imports`, which stakes
|
||||
/// nothing, writes and names the skipped file.
|
||||
/// Every whole-set edit refuses over its stake when only a skipped file
|
||||
/// spells it; a rename of a name the skipped file does not spell writes and
|
||||
/// names the skipped file.
|
||||
#[test]
|
||||
fn qa_recheck_every_edit_tool_refuses_over_its_stake() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
@@ -1250,22 +1105,10 @@ fn qa_recheck_every_edit_tool_refuses_over_its_stake() {
|
||||
let mut server = Session::over(&scratch);
|
||||
let pristine = snapshot(&scratch.0);
|
||||
let staked = [
|
||||
("expand_wildcard", json!({"file": "rtl/wild.sv", "line": 6}), "cell"),
|
||||
("propagate_ports", json!({"file": "rtl/partial.sv", "line": 6}), "cell"),
|
||||
("inline_module", json!({"file": "rtl/inl.sv", "line": 5}), "inv"),
|
||||
("convert_ports", json!({"file": "rtl/old.sv", "line": 1}), "old"),
|
||||
("remove_port", json!({"file": "rtl/spare.sv", "line": 3, "name": "unused_i"}), "spare"),
|
||||
("add_port", json!({"module": "cell", "declaration": "input logic x_i"}), "cell"),
|
||||
(
|
||||
"add_port",
|
||||
json!({"file": "rtl/cell.sv", "line": 2, "declaration": "input logic x_i"}),
|
||||
"cell",
|
||||
),
|
||||
(
|
||||
"extract_module",
|
||||
json!({"file": "rtl/ext.sv", "start_line": 7, "end_line": 7, "new_name": "adder"}),
|
||||
"ext",
|
||||
),
|
||||
("port", json!({"module": "cell", "add": "input logic x_i"}), "cell"),
|
||||
("port", json!({"module": "spare", "remove": "unused_i"}), "spare"),
|
||||
("rename", json!({"name": "inv", "new_name": "inv2"}), "inv"),
|
||||
("rename", json!({"name": "old", "new_name": "old2"}), "old"),
|
||||
];
|
||||
for (tool, arguments, name) in staked {
|
||||
let said = server.refusal(tool, arguments.clone());
|
||||
@@ -1273,95 +1116,88 @@ fn qa_recheck_every_edit_tool_refuses_over_its_stake() {
|
||||
assert!(said.starts_with(&expected), "{tool} {arguments}: {said}");
|
||||
assert!(moved(&pristine, &snapshot(&scratch.0)).is_empty(), "{tool}");
|
||||
}
|
||||
let text = server.text("organize_imports", json!({"file": "rtl/top.sv", "line": 6}));
|
||||
let text = server.text("rename", json!({"name": "unused_i", "new_name": "spare_i"}));
|
||||
assert!(text.contains("not indexed, so not searched or edited: rtl/lat.sv"), "{text}");
|
||||
}
|
||||
|
||||
/// A skipped file that is rewritten small and UTF-8 is searched once the
|
||||
/// next walk sees it (until then the edit stays refused — the safe side);
|
||||
/// an indexed file that stops being UTF-8 is refused on the very next call.
|
||||
/// A skipped file that is rewritten small and UTF-8 is searched at once
|
||||
/// (every edit walks first); an indexed file that stops being UTF-8 is
|
||||
/// refused on the very next call.
|
||||
#[test]
|
||||
fn qa_recheck_a_file_leaving_or_entering_the_skipped_set_is_followed() {
|
||||
let use_d = " leaf u_l (.clk(clk), .d(x), .q(y));\n";
|
||||
let scratch = Scratch::edit_fixture();
|
||||
scratch.write("rtl/big.sv", &oversized(use_d));
|
||||
let mut server = Session::over(&scratch);
|
||||
assert!(server.refusal("rename", RENAME_D(true)).starts_with("`rtl/big.sv`"));
|
||||
assert!(text_of(&server.rename_d()).starts_with("`rtl/big.sv`"));
|
||||
scratch.write("rtl/big.sv", &format!("module big (input logic clk);\n{use_d}endmodule\n"));
|
||||
let soon = server.call("rename", RENAME_D(true));
|
||||
assert!(soon["isError"] == true || text_of(&soon).contains("--- rtl/big.sv"), "{soon}");
|
||||
std::thread::sleep(Duration::from_millis(5_500));
|
||||
let later = server.text("rename", RENAME_D(true));
|
||||
assert!(later.contains("--- rtl/big.sv\n"), "{later}");
|
||||
assert!(!later.contains("not indexed"), "{later}");
|
||||
let written = server.rename_d();
|
||||
assert_eq!(written["isError"], false, "{written}");
|
||||
assert!(!text_of(&written).contains("not indexed"), "{written}");
|
||||
assert!(scratch.read("rtl/big.sv").contains(".din_i(x)"));
|
||||
// The other way: `mid.sv` gains a Latin-1 byte.
|
||||
let mid = scratch.read("rtl/mid.sv");
|
||||
fs::write(scratch.path("rtl/mid.sv"), latin1(mid.as_bytes())).unwrap();
|
||||
let said = server.refusal("rename", RENAME_D(true));
|
||||
assert!(said.starts_with("`rtl/mid.sv` (skipped: not UTF-8 text) may reference `d`"), "{said}");
|
||||
let back = json!({"name": "din_i", "file": "rtl/leaf.sv", "new_name": "d"});
|
||||
let said = server.refusal("rename", back);
|
||||
assert!(
|
||||
said.starts_with("`rtl/mid.sv` (skipped: not UTF-8 text) may reference `din_i`"),
|
||||
"{said}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The merge of `edit.rs::sources` and `nav.rs::all_files` into
|
||||
/// `WholeSet::read` left `references` alone: at every identifier of the nav
|
||||
/// fixture, adding a skipped file that spells nothing changes the answer
|
||||
/// only by the one trailing warning line.
|
||||
/// `find`'s answers over a tree with a skipped file that spells nothing
|
||||
/// differ from the plain tree's only by the one trailing warning line, for
|
||||
/// every name the nav fixture spells.
|
||||
#[test]
|
||||
fn qa_recheck_references_answers_only_gain_the_warning_line() {
|
||||
fn qa_recheck_find_answers_only_gain_the_warning_line() {
|
||||
let nav = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/nav");
|
||||
let (plain, partial) = (Scratch::empty(), Scratch::empty());
|
||||
copy_tree(&nav, &plain.0);
|
||||
copy_tree(&nav, &partial.0);
|
||||
fs::write(partial.path("rtl/zz.sv"), latin1(b"\xa9\xa9\n")).unwrap();
|
||||
let (mut a, mut b) = (Session::over(&plain), Session::over(&partial));
|
||||
let warning = "not indexed, so not searched or edited: rtl/zz.sv (not UTF-8 text)";
|
||||
let mut answered = 0;
|
||||
let warning = "warning: not indexed, so not searched or edited: rtl/zz.sv (not UTF-8 text)\n";
|
||||
let mut words: Vec<String> = Vec::new();
|
||||
for (file, (_, bytes)) in snapshot(&plain.0) {
|
||||
if !file.ends_with(".sv") && !file.ends_with(".svh") {
|
||||
continue;
|
||||
}
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
for (i, line) in text.lines().enumerate() {
|
||||
let bytes = line.as_bytes();
|
||||
for col in 0..bytes.len() {
|
||||
let starts = (bytes[col].is_ascii_alphabetic() || bytes[col] == b'_')
|
||||
&& (col == 0
|
||||
|| !(bytes[col - 1].is_ascii_alphanumeric() || bytes[col - 1] == b'_'));
|
||||
if !starts {
|
||||
continue;
|
||||
}
|
||||
let args = json!({"file": file, "line": i + 1, "col": col + 1});
|
||||
let (x, mut y) =
|
||||
(a.call("references", args.clone()), b.call("references", args.clone()));
|
||||
if x["isError"] == true {
|
||||
assert_eq!(x, y, "{args}");
|
||||
continue;
|
||||
}
|
||||
answered += 1;
|
||||
assert_eq!(text_of(&y), format!("{}warning: {warning}\n", text_of(&x)), "{args}");
|
||||
assert_eq!(y["structuredContent"]["warning"], warning, "{args}");
|
||||
y["structuredContent"].as_object_mut().unwrap().remove("warning");
|
||||
assert_eq!(x["structuredContent"], y["structuredContent"], "{args}");
|
||||
}
|
||||
if file.ends_with(".sv") || file.ends_with(".svh") {
|
||||
let text = String::from_utf8(bytes).unwrap();
|
||||
let spelled = text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'));
|
||||
words.extend(
|
||||
spelled
|
||||
.filter(|w| w.starts_with(|c: char| c.is_ascii_alphabetic()))
|
||||
.map(String::from),
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(answered > 50, "{answered}");
|
||||
words.sort();
|
||||
words.dedup();
|
||||
let mut answered = 0;
|
||||
for word in words {
|
||||
let args = json!({"name": word, "refs": true});
|
||||
let (x, y) = (a.call("find", args.clone()), b.call("find", args.clone()));
|
||||
if x["isError"] == true {
|
||||
assert_eq!(x, y, "{args}");
|
||||
continue;
|
||||
}
|
||||
answered += 1;
|
||||
assert_eq!(text_of(&y), format!("{}{warning}", text_of(&x)), "{args}");
|
||||
}
|
||||
assert!(answered > 20, "{answered}");
|
||||
}
|
||||
|
||||
/// Finding 6 (blocking): the whole set is "every indexed file", and the
|
||||
/// index sees a file created since the last walk only after `REWALK_AFTER`
|
||||
/// (5 s) — the edit tools do not walk (`rewalk: false`). A rename right
|
||||
/// after an agent writes a new instantiation leaves it unrenamed and says
|
||||
/// nothing; a new over-1 MiB file escapes the skipped-file guard the same way.
|
||||
/// Finding 6 (blocking): an edit sees a file created just before it — every
|
||||
/// edit tool walks first (`rewalk: true`).
|
||||
#[test]
|
||||
fn qa_an_edit_sees_a_file_created_just_before_it() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
let mut server = Session::over(&scratch);
|
||||
server.text("rename", RENAME_D(true));
|
||||
server.text("find", json!({"name": "leaf"}));
|
||||
scratch.write(
|
||||
"rtl/newer.sv",
|
||||
"module newer (input logic clk, input logic [7:0] x, output logic [7:0] y);\n leaf u_l (.clk(clk), .d(x), .q(y));\nendmodule\n",
|
||||
);
|
||||
let result = server.call("rename", RENAME_D(false));
|
||||
let result = server.rename_d();
|
||||
let newer = scratch.read("rtl/newer.sv");
|
||||
assert!(
|
||||
result["isError"] == true || newer.contains(".din_i(x)"),
|
||||
@@ -1371,11 +1207,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 recorded as skipped (`project/files.rs`, the
|
||||
/// size-cap branch skips the containment check the indexed branch makes),
|
||||
/// so it refuses edits inside the root and the refusal prints its absolute
|
||||
/// path outside the root. A small file behind the same kind of link is
|
||||
/// dropped, as M1 rules; the large one should be too.
|
||||
/// leading out of the root is not in the skipped set.
|
||||
#[test]
|
||||
fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
|
||||
let scratch = Scratch::edit_fixture();
|
||||
@@ -1383,6 +1215,6 @@ fn qa_a_large_file_behind_a_link_out_of_the_root_is_not_in_the_skipped_set() {
|
||||
outside.write("big.sv", &oversized(" leaf u_l (.clk(clk), .d(x), .q(y));\n"));
|
||||
std::os::unix::fs::symlink(outside.path("big.sv"), scratch.path("rtl/big_link.sv")).unwrap();
|
||||
let mut server = Session::over(&scratch);
|
||||
let text = server.text("rename", RENAME_D(true));
|
||||
let text = text_of(&server.rename_d());
|
||||
assert!(!text.contains(outside.root()), "{text}");
|
||||
}
|
||||
@@ -2,10 +2,16 @@
|
||||
//! 2026-09-23.
|
||||
//!
|
||||
//! Every test spawns the real binary over a scratch tree, as a host would.
|
||||
//! Refusals are asserted with every file of the tree byte-identical, under
|
||||
//! `dry_run` and for real. Accepted edits are checked byte for byte against
|
||||
//! the span `read_item` reported before the call: the bytes before it and
|
||||
//! after it must be the bytes that were there (the prefix/suffix guarantee).
|
||||
//! Refusals are asserted with every file of the tree byte-identical.
|
||||
//! Accepted edits are checked byte for byte against the span `read`
|
||||
//! reported before the call: the bytes before it and after it must be the
|
||||
//! bytes that were there (the prefix/suffix guarantee).
|
||||
//!
|
||||
//! The lean catalogue folds `replace_item`, `insert_item` and `delete_item`
|
||||
//! into `edit_item` and `read_item` into `read` (PLAN §10.1); [`lean`] maps
|
||||
//! each call so the cases stay as written. What the lean surface removed
|
||||
//! (`dry_run`, `rename`, `force`) is gone from the cases: a forced deletion
|
||||
//! is now a refusal like any other.
|
||||
//!
|
||||
//! A test that pins a QA finding asserts the *correct* behaviour and is
|
||||
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
|
||||
@@ -136,15 +142,56 @@ impl Session {
|
||||
reply
|
||||
}
|
||||
|
||||
/// A tool call: whether it was refused, its text, its structured content.
|
||||
/// A tool call: whether it was refused, its text, and — for `read_item`
|
||||
/// — the lines and text `read`'s answer carries.
|
||||
fn call(&mut self, tool: &str, arguments: Value) -> (bool, String, Value) {
|
||||
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
|
||||
let (name, arguments) = lean(tool, arguments);
|
||||
let reply = self.request("tools/call", json!({"name": name, "arguments": arguments}));
|
||||
let result = &reply["result"];
|
||||
let text = result["content"][0]["text"].as_str().unwrap_or_default().to_string();
|
||||
(result["isError"] == true, text, result["structuredContent"].clone())
|
||||
let error = result["isError"] == true;
|
||||
let read = if tool == "read_item" && !error { sliced(&text) } else { Value::Null };
|
||||
(error, text, read)
|
||||
}
|
||||
}
|
||||
|
||||
/// An M4 call as the lean catalogue takes it: the three structural edits
|
||||
/// under `edit_item`'s `op` (`insert_item`'s `anchor` as its `item`),
|
||||
/// `read_item` as `read`, and the `dry_run` and `rename` flags dropped.
|
||||
fn lean(tool: &str, mut args: Value) -> (&'static str, Value) {
|
||||
let object = args.as_object_mut().unwrap();
|
||||
object.remove("dry_run");
|
||||
object.remove("rename");
|
||||
let op = match tool {
|
||||
"read_item" => return ("read", args),
|
||||
"check" => return ("check", args),
|
||||
"replace_item" => "replace",
|
||||
"delete_item" => "delete",
|
||||
"insert_item" => {
|
||||
let before = object.remove("position") == Some(Value::from("before"));
|
||||
let anchor = object.remove("anchor").unwrap();
|
||||
object.insert("item".into(), anchor);
|
||||
if before {
|
||||
"insert_before"
|
||||
} else {
|
||||
"insert_after"
|
||||
}
|
||||
}
|
||||
other => panic!("not a structural edit: {other}"),
|
||||
};
|
||||
args["op"] = Value::from(op);
|
||||
("edit_item", args)
|
||||
}
|
||||
|
||||
/// `read`'s `file:first–last` line and slice as `{lines: [first, last], text}`.
|
||||
fn sliced(answer: &str) -> Value {
|
||||
let (head, body) = answer.split_once('\n').unwrap();
|
||||
let range = head.rsplit_once(':').unwrap().1;
|
||||
let (first, last) = range.split_once('–').unwrap_or((range, range));
|
||||
let body = body.strip_suffix('\n').unwrap_or(body);
|
||||
json!({"lines": [first.parse::<u64>().unwrap(), last.parse::<u64>().unwrap()], "text": body})
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
@@ -153,18 +200,14 @@ impl Drop for Session {
|
||||
}
|
||||
|
||||
/// Run `tool` and assert it refuses with a sentence holding `why`, leaving
|
||||
/// every file of the tree byte-identical — also under `dry_run`.
|
||||
/// every file of the tree byte-identical.
|
||||
fn refused(tree: &Tree, server: &mut Session, tool: &str, args: Value, why: &str) {
|
||||
let before = tree.snapshot();
|
||||
for dry_run in [true, false] {
|
||||
let mut arguments = args.clone();
|
||||
arguments["dry_run"] = Value::from(dry_run);
|
||||
let (error, text, _) = server.call(tool, arguments);
|
||||
assert!(error, "{tool} {args}: not refused: {text}");
|
||||
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
|
||||
assert!(text.contains("nothing written"), "{text}");
|
||||
assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote");
|
||||
}
|
||||
let (error, text, _) = server.call(tool, args.clone());
|
||||
assert!(error, "{tool} {args}: not refused: {text}");
|
||||
assert!(text.contains(why), "{tool} {args}: `{why}` not in: {text}");
|
||||
assert!(text.contains("nothing written"), "{text}");
|
||||
assert!(before == tree.snapshot(), "{tool} {args}: a refusal wrote");
|
||||
}
|
||||
|
||||
/// Run `tool` and assert it wrote (or answered `unchanged`); its text.
|
||||
@@ -174,7 +217,7 @@ fn accepted(server: &mut Session, tool: &str, args: Value) -> String {
|
||||
text
|
||||
}
|
||||
|
||||
/// The byte span of `item` as `read_item` reports it: its lines and text,
|
||||
/// The byte span of `item` as `read` reports it: its lines and text,
|
||||
/// turned into offsets (the text located on its first line).
|
||||
fn span_of(server: &mut Session, text: &str, file: &str, item: &str) -> (usize, usize) {
|
||||
let (error, answer, structured) = server.call("read_item", json!({"file": file, "item": item}));
|
||||
@@ -311,9 +354,9 @@ fn qa_a_text_equal_to_the_item_is_unchanged_and_writes_nothing() {
|
||||
let mut server = Session::over(&tree);
|
||||
let before = tree.snapshot();
|
||||
for text in ["logic p; \n\n", "\n\t logic p;\r\n", "logic p;"] {
|
||||
for dry_run in [true, false] {
|
||||
let args =
|
||||
json!({"file": "rtl/core.sv", "item": "p", "text": text, "dry_run": dry_run});
|
||||
// Twice: the no-op stays a no-op.
|
||||
for _ in 0..2 {
|
||||
let args = json!({"file": "rtl/core.sv", "item": "p", "text": text});
|
||||
let answer = accepted(&mut server, "replace_item", args);
|
||||
assert!(answer.starts_with("unchanged"), "{answer}");
|
||||
}
|
||||
@@ -609,9 +652,10 @@ fn qa_a_use_in_another_file_or_a_bind_refuses_the_delete() {
|
||||
refused(&tree, &mut server, "delete_item", args, "rtl/top.sv:3:18 `hier_target`");
|
||||
let args = json!({"file": "rtl/mac.sv", "item": "bind_target"});
|
||||
refused(&tree, &mut server, "delete_item", args, "rtl/bind.sv:3:24 `bind_target`");
|
||||
// No `force` any more: the refusal stands.
|
||||
let forced = json!({"file": "rtl/mac.sv", "item": "hier_target", "force": true});
|
||||
let answer = accepted(&mut server, "delete_item", forced);
|
||||
assert!(answer.contains("deleted with references left: rtl/top.sv:3:18"), "{answer}");
|
||||
let (error, answer, _) = server.call("delete_item", forced);
|
||||
assert!(error && answer.contains("`force`"), "{answer}");
|
||||
}
|
||||
|
||||
/// QA finding 3: a name used only in a macro argument (`` `ID(x) ``,
|
||||
@@ -630,7 +674,7 @@ fn qa_a_use_inside_a_macro_argument_refuses_the_delete() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_forced_non_ansi_port_delete_still_parses_and_the_last_item_leaves_an_empty_module() {
|
||||
fn qa_a_non_ansi_port_delete_is_refused_and_the_last_item_leaves_an_empty_module() {
|
||||
let non_ansi =
|
||||
"module k (a, b);\n input [3:0] a;\n output b;\n assign b = 1'b0;\nendmodule\n";
|
||||
let last = "module l;\n logic a;\n logic b;\nendmodule\n";
|
||||
@@ -638,12 +682,6 @@ fn qa_a_forced_non_ansi_port_delete_still_parses_and_the_last_item_leaves_an_emp
|
||||
let mut server = Session::over(&tree);
|
||||
let args = json!({"file": "rtl/k.sv", "item": "a"});
|
||||
refused(&tree, &mut server, "delete_item", args, "`a` is also declared on line 1");
|
||||
let answer = accepted(
|
||||
&mut server,
|
||||
"delete_item",
|
||||
json!({"file": "rtl/k.sv", "item": "a", "force": true}),
|
||||
);
|
||||
assert!(answer.contains("warnings:"), "{answer}");
|
||||
assert!(strict(&tree.read("rtl/k.sv")));
|
||||
accepted(&mut server, "delete_item", json!({"file": "rtl/l.sv", "item": "b"}));
|
||||
accepted(&mut server, "delete_item", json!({"file": "rtl/l.sv", "item": "a"}));
|
||||
@@ -690,26 +728,22 @@ fn qa_a_comment_between_two_items_goes_with_the_item_it_leads() {
|
||||
fn qa_a_comment_a_blank_line_separates_from_the_item_is_not_deleted() {
|
||||
let tree = Tree::with(false, &[("rtl/m.sv", COMMENTS)]);
|
||||
let mut server = Session::over(&tree);
|
||||
let (error, answer, _) =
|
||||
server.call("delete_item", json!({"file": "rtl/m.sv", "item": "a", "dry_run": true}));
|
||||
assert!(!error, "{answer}");
|
||||
assert!(!answer.contains("- // Section: registers"), "{answer}");
|
||||
assert!(answer.contains("- // the a flop"), "{answer}");
|
||||
let (error, answer, _) =
|
||||
server.call("delete_item", json!({"file": "rtl/m.sv", "item": "m", "dry_run": true}));
|
||||
assert!(!error, "{answer}");
|
||||
assert!(!answer.contains("-// File banner"), "{answer}");
|
||||
accepted(&mut server, "delete_item", json!({"file": "rtl/m.sv", "item": "a"}));
|
||||
let text = tree.read("rtl/m.sv");
|
||||
assert!(text.contains(" // Section: registers") && !text.contains("the a flop"), "{text}");
|
||||
accepted(&mut server, "delete_item", json!({"file": "rtl/m.sv", "item": "m"}));
|
||||
assert!(tree.read("rtl/m.sv").starts_with("// File banner"), "{}", tree.read("rtl/m.sv"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_deleting_an_else_branch_label_names_both_labels() {
|
||||
let tree = Tree::with(false, &[("rtl/g.sv", GEN)]);
|
||||
let mut server = Session::over(&tree);
|
||||
let args = json!({"file": "rtl/g.sv", "item": "gen_b", "dry_run": true});
|
||||
let answer = accepted(&mut server, "delete_item", args);
|
||||
assert!(answer.contains("deleted generate `gen_a`, `gen_b`"), "{answer}");
|
||||
let args = json!({"file": "rtl/g.sv", "item": "gen_a"});
|
||||
refused(&tree, &mut server, "delete_item", args, "part of a larger item");
|
||||
let args = json!({"file": "rtl/g.sv", "item": "gen_b"});
|
||||
let answer = accepted(&mut server, "delete_item", args);
|
||||
assert!(answer.starts_with("deleted generate gen_a, gen_b rtl/g.sv:"), "{answer}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -780,7 +814,7 @@ fn qa_every_accepted_call_changes_only_its_own_region() {
|
||||
{
|
||||
let old = tree.read(file);
|
||||
let span = span_of(&mut server, &old, file, item);
|
||||
accepted(&mut server, "delete_item", json!({"file": file, "item": item, "force": true}));
|
||||
accepted(&mut server, "delete_item", json!({"file": file, "item": item}));
|
||||
let new = tree.read(file);
|
||||
only_region_changed(&old, &new, (0, old.len()));
|
||||
// The removed bytes are one run that covers the item.
|
||||
@@ -939,20 +973,14 @@ fn qa_a_line_continued_directive_cannot_swallow_the_code_below_it() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_forced_delete_leaves_uses_that_diagnostics_reports() {
|
||||
fn qa_a_delete_of_a_used_item_is_refused_and_check_stays_clean() {
|
||||
let src = "module m (output logic o);\n logic q;\n assign o = q;\nendmodule\n";
|
||||
let tree = Tree::with(false, &[("rtl/m.sv", src)]);
|
||||
let mut server = Session::over(&tree);
|
||||
let args = json!({"file": "rtl/m.sv", "item": "q"});
|
||||
refused(&tree, &mut server, "delete_item", args, "still referenced: rtl/m.sv:3:14 `q`");
|
||||
let answer = accepted(
|
||||
&mut server,
|
||||
"delete_item",
|
||||
json!({"file": "rtl/m.sv", "item": "q", "force": true}),
|
||||
);
|
||||
assert!(answer.contains("deleted with references left: rtl/m.sv:3:14 `q`"), "{answer}");
|
||||
let (_, diagnostics, _) = server.call("diagnostics", json!({"file": "rtl/m.sv"}));
|
||||
assert!(diagnostics.contains("`q` is declared nowhere"), "{diagnostics}");
|
||||
let (_, check, _) = server.call("check", json!({"file": "rtl/m.sv"}));
|
||||
assert!(!check.contains("declared nowhere"), "{check}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -981,7 +1009,7 @@ fn qa_the_line_after_a_fence_is_not_an_insertion_point() {
|
||||
}
|
||||
let args = json!({"file": "rtl/core.sv", "item": "keep_me", "text": "logic keep_me;"});
|
||||
refused(&tree, &mut server, "replace_item", args, "fence");
|
||||
let args = json!({"file": "rtl/core.sv", "item": "keep_me", "force": true});
|
||||
let args = json!({"file": "rtl/core.sv", "item": "keep_me"});
|
||||
refused(&tree, &mut server, "delete_item", args, "fence");
|
||||
}
|
||||
|
||||
@@ -1190,7 +1218,7 @@ fn qa_recheck_a_define_body_spelling_the_name_only_as_a_substring_is_no_use() {
|
||||
let mut server = Session::over(&tree);
|
||||
// `sig_x`, `xsig`, `sig_`, a formal `sig` and a string "sig": no use.
|
||||
let answer = accepted(&mut server, "delete_item", json!({"file": "rtl/s.sv", "item": "sig"}));
|
||||
assert!(!answer.contains("warnings"), "{answer}");
|
||||
assert!(!answer.contains("warning"), "{answer}");
|
||||
assert!(!tree.read("rtl/s.sv").contains("logic sig;"));
|
||||
}
|
||||
|
||||
@@ -1264,14 +1292,10 @@ fn qa_recheck_a_define_item_may_be_inserted_but_not_nested_in_an_always() {
|
||||
let undef = "always_comb begin\n`undef W\n w = 1'b1;\n end";
|
||||
let args = json!({"file": "rtl/d.sv", "item": "always@6", "text": undef});
|
||||
refused(&tree, &mut server, "replace_item", args, "rule 6");
|
||||
// Deleting the module deletes its nested `define LOCAL: refused unless
|
||||
// forced. (Amended in M6 by the M4 review's ruling — `force` relaxes rule
|
||||
// 6 on delete, with a warning; the forced delete is in `tests/wire.rs`.)
|
||||
let args = json!({"file": "rtl/d.sv", "item": "d", "force": false});
|
||||
// Deleting the module deletes its nested `define LOCAL: refused (the
|
||||
// lean catalogue has no `force`, PLAN §10.1).
|
||||
let args = json!({"file": "rtl/d.sv", "item": "d"});
|
||||
refused(&tree, &mut server, "delete_item", args, "rule 6");
|
||||
let args = json!({"file": "rtl/d.sv", "item": "d", "force": true, "dry_run": true});
|
||||
let text = accepted(&mut server, "delete_item", args);
|
||||
assert!(text.contains("deleted macro definitions: LOCAL"), "{text}");
|
||||
let args = json!({"file": "rtl/d.sv", "item": "LOCAL"});
|
||||
refused(&tree, &mut server, "delete_item", args, "no declaration matches `LOCAL`");
|
||||
// A directive item at the region's own level is the exemption.
|
||||
|
||||
@@ -202,6 +202,11 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `find` knows a declaration of `name`.
|
||||
fn declared(session: &mut Session, name: &str) -> bool {
|
||||
session.call("find", json!({"name": name}))["isError"] == false
|
||||
}
|
||||
|
||||
/// The startup line's tail for `E` editor and `O` own hits.
|
||||
fn reused(editor: usize, own: usize) -> String {
|
||||
format!(" ms ({editor} from the editor's cache, {own} from its own)\n")
|
||||
@@ -212,15 +217,15 @@ fn reused(editor: usize, own: usize) -> String {
|
||||
fn probe(scratch: &Scratch, cache: Option<&Path>) -> (Vec<String>, String) {
|
||||
let mut session = Session::start(scratch, cache);
|
||||
let answers = [
|
||||
("list_units", json!({})),
|
||||
("unit_interface", json!({"name": "leaf"})),
|
||||
("unit_interface", json!({"name": "top"})),
|
||||
("hierarchy", json!({})),
|
||||
("outline", json!({"unit": "leaf"})),
|
||||
("outline", json!({"unit": "top"})),
|
||||
("outline", json!({"file": "rtl/top.sv"})),
|
||||
("outline", json!({"file": "rtl/leaf.sv"})),
|
||||
("search_symbols", json!({"query": "word"})),
|
||||
("references", json!({"name": "leaf"})),
|
||||
("hierarchy", json!({"root": "top"})),
|
||||
("defines", json!({})),
|
||||
("find", json!({"name": "word_t"})),
|
||||
("find", json!({"name": "leaf", "refs": true})),
|
||||
("hierarchy", json!({"root": "top", "depth": 3})),
|
||||
("check", json!({})),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(tool, args)| session.text(tool, args))
|
||||
@@ -294,8 +299,7 @@ fn qa_records_for_gone_files_or_outside_the_roots_are_not_indexed_nor_kept() {
|
||||
scratch.write_editor_store(&lines);
|
||||
|
||||
let mut session = Session::cached(&scratch);
|
||||
let units = session.text("list_units", json!({}));
|
||||
assert!(!units.contains("outside_root") && !units.contains("ghost_unit"), "{units}");
|
||||
assert!(!declared(&mut session, "outside_root") && !declared(&mut session, "ghost_unit"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
|
||||
let own = fs::read_to_string(scratch.own_store()).unwrap();
|
||||
@@ -324,16 +328,14 @@ fn qa_several_records_for_one_path_serve_only_the_bytes_on_disk() {
|
||||
lines.push(record(&leaf));
|
||||
scratch.write_editor_store(&lines);
|
||||
let mut session = Session::cached(&scratch);
|
||||
let units = session.text("list_units", json!({}));
|
||||
assert!(units.contains("leaf") && !units.contains("leaf_v2"), "{units}");
|
||||
assert!(declared(&mut session, "leaf") && !declared(&mut session, "leaf_v2"));
|
||||
session.end();
|
||||
|
||||
// Now the edited version is on disk: its own record serves it.
|
||||
fs::write(&leaf, &edited).unwrap();
|
||||
fs::remove_file(scratch.own_store()).unwrap();
|
||||
let mut session = Session::cached(&scratch);
|
||||
let units = session.text("list_units", json!({}));
|
||||
assert!(units.contains("leaf_v2"), "{units}");
|
||||
assert!(declared(&mut session, "leaf_v2"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
|
||||
}
|
||||
@@ -377,7 +379,7 @@ fn qa_header_near_misses_are_ignored_whole_and_left_byte_identical() {
|
||||
scratch.write_editor_store(&lines);
|
||||
let before = hash_file(&scratch.editor_store());
|
||||
let mut session = Session::cached(&scratch);
|
||||
assert!(session.text("list_units", json!({})).contains("leaf"));
|
||||
assert!(declared(&mut session, "leaf"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(0, 0)), "{first:?}: {stderr}");
|
||||
assert_eq!(stderr.matches("ignoring the index cache").count(), 1, "{first:?}: {stderr}");
|
||||
@@ -402,7 +404,7 @@ fn qa_empty_stores_and_a_directory_named_index_cache_are_silent_cold_starts() {
|
||||
_ => fs::create_dir(scratch.editor_store()).unwrap(),
|
||||
}
|
||||
let mut session = Session::cached(&scratch);
|
||||
assert!(session.text("list_units", json!({})).contains("leaf"));
|
||||
assert!(declared(&mut session, "leaf"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(0, 0)), "{shape}: {stderr}");
|
||||
assert_eq!(stderr.lines().count(), 1, "{shape}: only the startup line: {stderr}");
|
||||
@@ -418,7 +420,7 @@ fn qa_a_directory_named_index_cache_mcp_costs_one_line_and_leaves_no_temp() {
|
||||
let scratch = Scratch::new();
|
||||
fs::create_dir_all(scratch.own_store()).unwrap();
|
||||
let mut session = Session::cached(&scratch);
|
||||
assert!(session.text("unit_interface", json!({"name": "leaf"})).contains("module leaf"));
|
||||
assert!(session.text("outline", json!({"unit": "leaf"})).starts_with("rtl/leaf.sv:1\n"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
|
||||
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
|
||||
@@ -435,7 +437,7 @@ fn qa_index_cache_naming_a_file_answers_and_leaves_the_file_alone() {
|
||||
let file = scratch.0.join("not-a-dir");
|
||||
fs::write(&file, "keep me\n").unwrap();
|
||||
let mut session = Session::start(&scratch, Some(&file));
|
||||
assert!(session.text("list_units", json!({})).contains("leaf"));
|
||||
assert!(declared(&mut session, "leaf"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(0, 0)), "{stderr}");
|
||||
assert_eq!(stderr.matches("cannot write the index cache").count(), 1, "{stderr}");
|
||||
@@ -487,8 +489,8 @@ fn qa_the_editors_store_is_never_tidied_whatever_its_shape() {
|
||||
let before = fingerprint(&scratch.editor_store());
|
||||
|
||||
let mut session = Session::cached(&scratch);
|
||||
assert!(session.text("project_overview", json!({})).contains("files: 7 indexed"));
|
||||
session.text("format", json!({"file": "rtl/top.sv"}));
|
||||
assert!(session.text("hierarchy", json!({})).starts_with("7 files, "));
|
||||
session.text("format", json!({"files": "rtl/top.sv"}));
|
||||
session.text("outline", json!({"file": "rtl/top.sv"}));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(FILES, 0)), "{stderr}");
|
||||
@@ -507,7 +509,7 @@ fn qa_a_killed_session_leaves_the_previous_own_store_intact() {
|
||||
drop(session.end()); // no call: no project, nothing written
|
||||
assert!(!scratch.own_store().exists(), "a session that never answered writes no store");
|
||||
let mut session = Session::cached(&scratch);
|
||||
session.text("list_units", json!({}));
|
||||
session.text("hierarchy", json!({}));
|
||||
session.end();
|
||||
let first = fs::read(scratch.own_store()).unwrap();
|
||||
|
||||
@@ -515,7 +517,7 @@ fn qa_a_killed_session_leaves_the_previous_own_store_intact() {
|
||||
let text = fs::read_to_string(&leaf).unwrap().replace("module leaf", "module leaf_k");
|
||||
fs::write(&leaf, text).unwrap();
|
||||
let mut session = Session::cached(&scratch);
|
||||
assert!(session.text("list_units", json!({})).contains("leaf_k"));
|
||||
assert!(declared(&mut session, "leaf_k"));
|
||||
session.child.kill().unwrap();
|
||||
session.child.wait().unwrap();
|
||||
assert_eq!(fs::read(scratch.own_store()).unwrap(), first, "the previous store, whole");
|
||||
@@ -523,7 +525,7 @@ fn qa_a_killed_session_leaves_the_previous_own_store_intact() {
|
||||
|
||||
// And the next start is right about the changed file (its hash misses).
|
||||
let mut session = Session::cached(&scratch);
|
||||
assert!(session.text("list_units", json!({})).contains("leaf_k"));
|
||||
assert!(declared(&mut session, "leaf_k"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(0, FILES - 1)), "{stderr}");
|
||||
}
|
||||
@@ -544,7 +546,7 @@ fn qa_an_orphaned_temp_file_is_swept_by_the_next_write() {
|
||||
let old = SystemTime::now() - Duration::from_secs(3600);
|
||||
fs::File::options().write(true).open(&orphan).unwrap().set_modified(old).unwrap();
|
||||
let mut session = Session::cached(&scratch);
|
||||
session.text("list_units", json!({}));
|
||||
session.text("hierarchy", json!({}));
|
||||
session.end();
|
||||
assert!(scratch.own_store().is_file());
|
||||
assert!(!orphan.exists(), "an hour-old temp file of our store is a dead writer's");
|
||||
@@ -586,14 +588,14 @@ fn qa_a_same_size_edit_and_a_new_file_since_the_store_are_seen() {
|
||||
let mut session = Session::cached(&scratch);
|
||||
let outline = session.text("outline", json!({"file": "rtl/leaf.sv"}));
|
||||
assert!(outline.contains("hold") && !outline.contains("held"), "{outline}");
|
||||
assert!(session.text("list_units", json!({})).contains("extra_unit"));
|
||||
assert!(declared(&mut session, "extra_unit"));
|
||||
let stderr = session.end();
|
||||
assert!(stderr.contains(&reused(FILES - 1, 0)), "{stderr}");
|
||||
assert!(stderr.contains(&format!("indexed {} files", FILES + 1)), "{stderr}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 4. Rule 6: the forced delete.
|
||||
// 4. Rule 6: the delete of a macro definition holder.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const HOLDER: &str = "module keep_before;
|
||||
@@ -612,45 +614,32 @@ module user_after (output logic [3:0] o);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A module holding a `define that code after it reads: refused without
|
||||
/// `force` (tree byte-identical, the refusal says how to override); forced,
|
||||
/// the warning names each macro once in source order, and every byte outside
|
||||
/// the module's lines is the byte that was there.
|
||||
/// A module holding a `define that code after it reads: refused (the
|
||||
/// lean catalogue has no `force`, so the refusal offers none), the tree
|
||||
/// byte-identical.
|
||||
#[test]
|
||||
fn qa_a_forced_delete_of_a_define_holder_leaves_the_code_after_it_unchanged() {
|
||||
fn qa_a_delete_of_a_define_holder_is_refused_and_writes_nothing() {
|
||||
let scratch = Scratch::new();
|
||||
let file = scratch.file("rtl/holder.sv");
|
||||
fs::write(&file, HOLDER).unwrap();
|
||||
let mut session = Session::start(&scratch, None);
|
||||
let args = json!({"file": "rtl/holder.sv", "item": "holder"});
|
||||
let refused = session.call("delete_item", args.clone());
|
||||
let args = json!({"file": "rtl/holder.sv", "op": "delete", "item": "holder"});
|
||||
let refused = session.call("edit_item", args);
|
||||
assert_eq!(refused["isError"], true, "{refused}");
|
||||
let said = refused["content"][0]["text"].as_str().unwrap();
|
||||
assert!(said.contains("rule 6") && said.contains("force: true"), "{said}");
|
||||
assert!(said.contains("rule 6") && !said.contains("force"), "{said}");
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), HOLDER, "a refusal writes nothing");
|
||||
|
||||
let mut forced = args;
|
||||
forced["force"] = Value::from(true);
|
||||
let applied = session.text("delete_item", forced);
|
||||
assert!(applied.contains("deleted macro definitions: LOCAL, GONE (undef) — "), "{applied}");
|
||||
let start = HOLDER.find("module holder;").unwrap();
|
||||
let end = HOLDER.find("module user_after").unwrap();
|
||||
let now = fs::read_to_string(&file).unwrap();
|
||||
assert!(now.starts_with(&HOLDER[..start]), "{now}");
|
||||
assert!(now.ends_with(&HOLDER[end - 1..]), "the code after the item, byte for byte: {now}");
|
||||
assert!(!now.contains("`define"), "{now}");
|
||||
session.end();
|
||||
}
|
||||
|
||||
/// `force` on a deletion whose item holds no macro: no macro warning, and a
|
||||
/// `define item at the file's own level is still not a delete target.
|
||||
/// A deletion whose item holds no macro says nothing about macros.
|
||||
#[test]
|
||||
fn qa_force_says_nothing_about_macros_it_did_not_remove() {
|
||||
fn qa_a_delete_says_nothing_about_macros_it_did_not_remove() {
|
||||
let scratch = Scratch::new();
|
||||
fs::write(scratch.file("rtl/holder.sv"), HOLDER).unwrap();
|
||||
let mut session = Session::start(&scratch, None);
|
||||
let args = json!({"file": "rtl/holder.sv", "item": "keep_before", "force": true});
|
||||
let applied = session.text("delete_item", args);
|
||||
let args = json!({"file": "rtl/holder.sv", "op": "delete", "item": "keep_before"});
|
||||
let applied = session.text("edit_item", args);
|
||||
assert!(!applied.contains("macro"), "{applied}");
|
||||
session.end();
|
||||
}
|
||||
@@ -659,9 +648,9 @@ fn qa_force_says_nothing_about_macros_it_did_not_remove() {
|
||||
// 5. The instructions.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// ≤ 900 characters; names the read tools, the edit tools, `dry_run`,
|
||||
/// `diagnostics`, the disk, root-relative paths and byte columns; and every
|
||||
/// snake_case or tool-like word in it is a tool `tools/list` has.
|
||||
/// ≤ 400 bytes (PLAN §10.3); names the nine tools, the disk, the
|
||||
/// all-or-nothing writes and that there is no dry run; and every snake_case
|
||||
/// word in it is a tool `tools/list` has.
|
||||
#[test]
|
||||
fn qa_the_instructions_are_short_and_name_only_real_tools() {
|
||||
let scratch = Scratch::new();
|
||||
@@ -676,35 +665,19 @@ fn qa_the_instructions_are_short_and_name_only_real_tools() {
|
||||
.map(|tool| tool["name"].as_str().unwrap().to_string())
|
||||
.collect();
|
||||
session.end();
|
||||
assert!(text.chars().count() <= 900, "{} characters", text.chars().count());
|
||||
for named in [
|
||||
"unit_interface",
|
||||
"outline",
|
||||
"read_item",
|
||||
"list_units",
|
||||
"search_symbols",
|
||||
"definition",
|
||||
"references",
|
||||
"hierarchy",
|
||||
"replace_item",
|
||||
"insert_item",
|
||||
"delete_item",
|
||||
"rename",
|
||||
"add_port",
|
||||
"remove_port",
|
||||
"format",
|
||||
"fix_lint",
|
||||
"diagnostics",
|
||||
] {
|
||||
assert!(text.len() <= 400, "{} bytes", text.len());
|
||||
for named in
|
||||
["hierarchy", "find", "outline", "read", "check", "rename", "port", "edit_item", "format"]
|
||||
{
|
||||
assert!(text.contains(named), "the instructions name {named}");
|
||||
assert!(tools.iter().any(|tool| tool == named), "{named} is a real tool");
|
||||
}
|
||||
for word in text.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) {
|
||||
if word.contains('_') && word != "dry_run" {
|
||||
if word.contains('_') {
|
||||
assert!(tools.iter().any(|tool| tool == word), "`{word}` is not a tool");
|
||||
}
|
||||
}
|
||||
for phrase in ["dry_run", "disk", "relative to a root", "1-based bytes", "never unsaved"] {
|
||||
for phrase in ["on disk", "no dry run", "all-or-nothing", "root-relative", "1-based"] {
|
||||
assert!(text.contains(phrase), "{phrase}: {text}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,807 @@
|
||||
//! QA attacks on lane M7 (the lean catalogue), 2026-09-24.
|
||||
//!
|
||||
//! Every test writes a small design into its own scratch directory, spawns
|
||||
//! the real binary over it, sends `initialize` and a batch of `tools/call`s,
|
||||
//! closes stdin and reads every answer — the host's view, nothing else.
|
||||
//!
|
||||
//! A test that pins a QA finding asserts the *correct* behaviour and is
|
||||
//! `#[ignore = "QA finding N"]` until a rework flips it; the findings are
|
||||
//! numbered as in the QA log of `docs/features/mcp-lean-catalogue/README.md`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
static NEXT_DIR: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
/// A scratch design, removed on drop.
|
||||
struct Tree(PathBuf);
|
||||
|
||||
impl Tree {
|
||||
/// A tree holding `files` (`(relative path, text)`).
|
||||
fn with(files: &[(&str, &str)]) -> Tree {
|
||||
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("lucisv-mcp-qa-m7-{}-{unique}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let tree = Tree(fs::canonicalize(dir).unwrap());
|
||||
for (rel, text) in files {
|
||||
tree.write(rel, text);
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
fn path(&self, rel: &str) -> PathBuf {
|
||||
self.0.join(rel)
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
let path = self.path(rel);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
fn read(&self, rel: &str) -> String {
|
||||
fs::read_to_string(self.path(rel)).unwrap()
|
||||
}
|
||||
|
||||
/// Every file's bytes, by relative path.
|
||||
fn snapshot(&self) -> BTreeMap<String, Vec<u8>> {
|
||||
fn walk(dir: &Path, root: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
|
||||
for entry in fs::read_dir(dir).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
walk(&path, root, out);
|
||||
} else {
|
||||
let rel = path.strip_prefix(root).unwrap().to_string_lossy().to_string();
|
||||
out.insert(rel, fs::read(&path).unwrap());
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = BTreeMap::new();
|
||||
walk(&self.0, &self.0, &mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// One answer: whether it was refused, and its text.
|
||||
struct Said {
|
||||
refused: bool,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// Run `calls` in one session over `tree`, in order.
|
||||
fn session(tree: &Tree, calls: &[(&str, Value)]) -> Vec<Said> {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
|
||||
.args(["--root", tree.0.to_str().unwrap()])
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut lines = vec![json!({"jsonrpc": "2.0", "id": 0, "method": "initialize", "params": {
|
||||
"protocolVersion": "2025-06-18", "capabilities": {},
|
||||
"clientInfo": {"name": "qa_m7", "version": "0"}}})
|
||||
.to_string()];
|
||||
lines.push(json!({"jsonrpc": "2.0", "method": "notifications/initialized"}).to_string());
|
||||
for (at, (tool, arguments)) in calls.iter().enumerate() {
|
||||
let params = json!({"name": tool, "arguments": arguments});
|
||||
let call =
|
||||
json!({"jsonrpc": "2.0", "id": at + 1, "method": "tools/call", "params": params});
|
||||
lines.push(call.to_string());
|
||||
}
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
stdin.write_all((lines.join("\n") + "\n").as_bytes()).unwrap();
|
||||
drop(stdin);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
let replies: Vec<Value> = String::from_utf8(output.stdout)
|
||||
.unwrap()
|
||||
.lines()
|
||||
.map(|line| serde_json::from_str(line).unwrap())
|
||||
.collect();
|
||||
(1..=calls.len())
|
||||
.map(|id| {
|
||||
let reply = replies.iter().find(|r| r["id"] == id).expect("every call is answered");
|
||||
let result = &reply["result"];
|
||||
Said {
|
||||
refused: result["isError"] == true,
|
||||
text: result["content"][0]["text"].as_str().unwrap_or_default().to_string(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One call that must succeed: its text.
|
||||
fn text(tree: &Tree, tool: &str, arguments: Value) -> String {
|
||||
let said = session(tree, &[(tool, arguments.clone())]).remove(0);
|
||||
assert!(!said.refused, "{tool} {arguments}: {}", said.text);
|
||||
said.text
|
||||
}
|
||||
|
||||
/// One call that must be refused, leaving every file byte-identical.
|
||||
fn refusal(tree: &Tree, tool: &str, arguments: Value) -> String {
|
||||
let before = tree.snapshot();
|
||||
let said = session(tree, &[(tool, arguments.clone())]).remove(0);
|
||||
assert!(said.refused, "{tool} {arguments}: not refused: {}", said.text);
|
||||
assert!(before == tree.snapshot(), "{tool} {arguments}: a refusal wrote");
|
||||
said.text
|
||||
}
|
||||
|
||||
/// The `… and N more` lines of an answer.
|
||||
fn more_lines(text: &str) -> Vec<&str> {
|
||||
text.lines()
|
||||
.filter(|line| line.starts_with("… and ") || line.trim_start().starts_with("… and "))
|
||||
.collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Caps: exactly one `… and N more`, the count right, every line whole.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// `big` instantiates `leaf` 400 times; `wide` has 350 ports and 320 nets
|
||||
/// no one reads; 320 modules each declare `sig`.
|
||||
fn crowded() -> Tree {
|
||||
let mut big = String::from("module big;\n logic a;\n");
|
||||
for i in 0..400 {
|
||||
big.push_str(&format!(" leaf u_{i:03} (.a(a));\n"));
|
||||
}
|
||||
big.push_str("endmodule\n");
|
||||
let ports: Vec<String> = (0..350).map(|i| format!(" input logic p{i}")).collect();
|
||||
let mut wide = format!("module wide (\n{}\n);\n", ports.join(",\n"));
|
||||
for i in 0..320 {
|
||||
wide.push_str(&format!(" logic w{i};\n"));
|
||||
}
|
||||
wide.push_str("endmodule\n");
|
||||
let mut files: Vec<(String, String)> = vec![
|
||||
("rtl/leaf.sv".into(), "module leaf(input logic a);\nendmodule\n".into()),
|
||||
("rtl/big.sv".into(), big),
|
||||
("rtl/wide.sv".into(), wide),
|
||||
];
|
||||
for i in 0..320 {
|
||||
files.push((
|
||||
format!("rtl/m{i:03}.sv"),
|
||||
format!("module m{i:03};\n logic sig;\nendmodule\n"),
|
||||
));
|
||||
}
|
||||
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
|
||||
Tree::with(&borrowed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_every_cap_cuts_once_with_the_right_count_and_whole_lines() {
|
||||
let tree = crowded();
|
||||
let calls = [
|
||||
("hierarchy", json!({"root": "big"})),
|
||||
("hierarchy", json!({"root": "leaf", "up": true})),
|
||||
("hierarchy", json!({"root": "big", "peek": true})),
|
||||
("hierarchy", json!({})),
|
||||
("find", json!({"name": "sig"})),
|
||||
("outline", json!({"unit": "wide"})),
|
||||
("outline", json!({"file": "rtl/wide.sv"})),
|
||||
("check", json!({})),
|
||||
];
|
||||
let said = session(&tree, &calls);
|
||||
// (shown lines before the cut line, the count the cut line says)
|
||||
let expected = [
|
||||
(300, 101), // the root line + 400 instances
|
||||
(300, 100), // 400 instantiations
|
||||
(299, 251), // root + 149 two-line blocks; the 150th block would pass 300
|
||||
(300, 23), // counts line + 322 tops
|
||||
(300, 20), // 320 declarations
|
||||
(300, 51), // file:line + 350 ports
|
||||
(300, 371), // module + 350 ports + 320 nets
|
||||
(200, 120), // 320 unused nets
|
||||
];
|
||||
for ((call, said), (shown, rest)) in calls.iter().zip(&said).zip(expected) {
|
||||
assert!(!said.refused, "{call:?}: {}", said.text);
|
||||
let lines: Vec<&str> = said.text.lines().collect();
|
||||
assert_eq!(more_lines(&said.text), [format!("… and {rest} more")], "{call:?}");
|
||||
assert_eq!(lines.len(), shown + 1, "{call:?}");
|
||||
assert_eq!(*lines.last().unwrap(), format!("… and {rest} more"), "{call:?}");
|
||||
assert!(lines.iter().all(|line| !line.trim().is_empty()), "{call:?}");
|
||||
}
|
||||
// Every line before the cut is a whole fact: a tree line names its site.
|
||||
for line in said[0].text.lines().skip(1).take(299) {
|
||||
let (head, site) = line.trim_start().rsplit_once(' ').unwrap();
|
||||
assert!(head.starts_with("u_") && head.ends_with(": leaf"), "{line}");
|
||||
let (file, number) = site.split_once(':').unwrap();
|
||||
assert_eq!(file, "rtl/big.sv");
|
||||
number.parse::<u32>().unwrap();
|
||||
}
|
||||
// A peek block is never split: the last shown line is a statement.
|
||||
let peek: Vec<&str> = said[2].text.lines().collect();
|
||||
assert_eq!(peek[298], " leaf u_148 (.a(a));");
|
||||
for line in said[7].text.lines().take(200) {
|
||||
assert!(line.starts_with("rtl/wide.sv:") && line.ends_with("[unused-signal]"), "{line}");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// peek
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const PEEKED: &str = "module leaf #(parameter int W = 1) (
|
||||
input logic clk,
|
||||
input logic [W-1:0] d,
|
||||
output logic [W-1:0] q
|
||||
);
|
||||
always_ff @(posedge clk) q <= d;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const PEEKER: &str = "module top (
|
||||
input logic clk,
|
||||
input logic [3:0] d,
|
||||
output logic [3:0] q
|
||||
);
|
||||
logic [3:0] mid;
|
||||
// a comment before the statement
|
||||
leaf #(
|
||||
.W(4) // width; with a semicolon in the comment
|
||||
) u_a (
|
||||
.clk, /* block ; comment */
|
||||
.d (d),
|
||||
.q (mid)
|
||||
);
|
||||
\tleaf #(.W(4)) u_b (.*);
|
||||
leaf #(
|
||||
.W(4)
|
||||
) u_long (
|
||||
.clk(clk),
|
||||
// spaced
|
||||
.d(mid),
|
||||
.q(q)
|
||||
// one
|
||||
// two
|
||||
// three
|
||||
// four
|
||||
// five
|
||||
);
|
||||
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn qa_peek_shows_a_commented_overridden_statement_exactly_and_cuts_at_12() {
|
||||
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", PEEKER)]);
|
||||
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
|
||||
let expected = "top rtl/top.sv:1
|
||||
u_a: leaf rtl/top.sv:10
|
||||
leaf #(
|
||||
.W(4) // width; with a semicolon in the comment
|
||||
) u_a (
|
||||
.clk, /* block ; comment */
|
||||
.d (d),
|
||||
.q (mid)
|
||||
);
|
||||
u_b: leaf rtl/top.sv:15
|
||||
leaf #(.W(4)) u_b (.*);
|
||||
u_long: leaf rtl/top.sv:18
|
||||
leaf #(
|
||||
.W(4)
|
||||
) u_long (
|
||||
.clk(clk),
|
||||
// spaced
|
||||
.d(mid),
|
||||
.q(q)
|
||||
// one
|
||||
// two
|
||||
// three
|
||||
// four
|
||||
// five
|
||||
…
|
||||
u_c: leaf rtl/top.sv:29
|
||||
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
|
||||
u_d: leaf rtl/top.sv:29
|
||||
leaf u_c (.clk(clk), .d(d[0]), .q()), u_d (.clk(clk), .d(d[1]), .q());
|
||||
";
|
||||
assert_eq!(down, expected);
|
||||
// Up shows the same statements under `parent.instance` lines.
|
||||
let up = text(&tree, "hierarchy", json!({"root": "leaf", "up": true, "peek": true}));
|
||||
assert!(up.starts_with("top.u_a rtl/top.sv:10\n leaf #(\n .W(4) // width;"), "{up}");
|
||||
assert_eq!(up.matches('…').count(), 1, "{up}");
|
||||
// Exactly 12 lines is not cut.
|
||||
let twelve = PEEKER.replace(" // five\n", "");
|
||||
tree.write("rtl/top.sv", &twelve);
|
||||
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
|
||||
assert!(!down.contains('…'), "{down}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_peek_never_answers_a_whitespace_only_line() {
|
||||
let spaced = PEEKER.replace(" .clk(clk),\n // spaced", " .clk(clk),\n\n // spaced");
|
||||
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", &spaced)]);
|
||||
let down = text(&tree, "hierarchy", json!({"root": "top", "peek": true}));
|
||||
// Lead's ruling on finding 4: the statement's blank line is an empty
|
||||
// line — no indent, no trailing spaces; every other line stays exact.
|
||||
assert!(down.lines().all(|line| line.is_empty() || !line.trim().is_empty()), "{down}");
|
||||
assert!(down.contains(" .clk(clk),\n\n // spaced"), "{down}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ambiguity and unknown names
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const OTHER: &str = "module other (input logic clk);
|
||||
logic mid;
|
||||
assign mid = clk;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const MID: &str = "module top2 (input logic clk);
|
||||
logic mid;
|
||||
assign mid = clk;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn qa_ambiguous_and_unknown_names_are_refused_with_what_picks_one() {
|
||||
let tree = Tree::with(&[
|
||||
("rtl/leaf.sv", PEEKED),
|
||||
("rtl/other.sv", OTHER),
|
||||
("rtl/top2.sv", MID),
|
||||
("rtl/dup.sv", "module leaf (input logic clk);\nendmodule\n"),
|
||||
]);
|
||||
let read = refusal(&tree, "read", json!({"item": "mid"}));
|
||||
assert!(read.contains("rtl/other.sv:2, rtl/top2.sv:2") && read.contains("`file`"), "{read}");
|
||||
let rename = refusal(&tree, "rename", json!({"name": "mid", "new_name": "m2"}));
|
||||
assert!(rename.contains("rtl/other.sv:2, rtl/top2.sv:2"), "{rename}");
|
||||
let module = refusal(&tree, "rename", json!({"name": "leaf", "new_name": "leaf2"}));
|
||||
assert!(module.contains("rtl/dup.sv:1, rtl/leaf.sv:1"), "{module}");
|
||||
// `file` picks one; `unit.name` picks one without it.
|
||||
let picked = text(&tree, "read", json!({"item": "mid", "file": "rtl/top2.sv"}));
|
||||
assert_eq!(picked, "rtl/top2.sv:2\nlogic mid;\n");
|
||||
let renamed = text(&tree, "rename", json!({"name": "other.mid", "new_name": "m3"}));
|
||||
assert_eq!(renamed, "renamed 2 sites in 1 file\n");
|
||||
assert!(tree.read("rtl/top2.sv").contains("logic mid;"));
|
||||
let find = refusal(&tree, "find", json!({"name": "lea"}));
|
||||
assert_eq!(find, "no declaration named `lea`; similar: leaf.");
|
||||
let none = refusal(&tree, "find", json!({"name": "qqq"}));
|
||||
assert_eq!(none, "no declaration named `qqq`.");
|
||||
let root = refusal(&tree, "hierarchy", json!({"root": "OTH"}));
|
||||
assert_eq!(root, "no module or interface named `OTH`; similar: other.");
|
||||
}
|
||||
|
||||
const FSM: &str = "module fsm (input logic clk, output logic busy);
|
||||
typedef enum logic [1:0] {StIdle, StBusy} state_e;
|
||||
state_e state_q;
|
||||
function automatic logic helper(input logic x);
|
||||
return ~x;
|
||||
endfunction
|
||||
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
|
||||
logic lane_q;
|
||||
end
|
||||
assign busy = helper(state_q == StBusy);
|
||||
always_ff @(posedge clk) state_q <= StIdle;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn qa_find_and_rename_reach_every_declaration_outline_lists() {
|
||||
let tree = Tree::with(&[("rtl/fsm.sv", FSM)]);
|
||||
// `outline` lists these; `read` with `file` slices them; 0.57.0's
|
||||
// `rename` renamed them by position. By name, the lean tools say they
|
||||
// do not exist.
|
||||
for name in ["state_e", "StIdle", "helper", "g_lane", "lane_q"] {
|
||||
let said = session(&tree, &[("find", json!({"name": name}))]).remove(0);
|
||||
assert!(!said.refused, "find {name}: {}", said.text);
|
||||
}
|
||||
let renamed = text(&tree, "rename", json!({"name": "StIdle", "new_name": "StRest"}));
|
||||
assert!(renamed.starts_with("renamed 2 sites in 1 file"), "{renamed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_find_near_matches_include_the_module_internals_find_lists() {
|
||||
let tree = Tree::with(&[("rtl/other.sv", OTHER)]);
|
||||
assert_eq!(text(&tree, "find", json!({"name": "mid"})), "var mid rtl/other.sv:2\n");
|
||||
let near = refusal(&tree, "find", json!({"name": "mi"}));
|
||||
assert!(near.contains("similar: mid"), "{near}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// port
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const SUB: &str = "module sub (
|
||||
input logic clk,
|
||||
input logic a,
|
||||
output logic y
|
||||
);
|
||||
assign y = a;
|
||||
endmodule
|
||||
";
|
||||
|
||||
const P1: &str = "module p1 (input logic clk, input logic a, output logic y);
|
||||
sub u_s (
|
||||
.clk(clk),
|
||||
.a (a),
|
||||
.y (y)
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
const P2: &str = "module p2 (input logic clk, input logic a, input logic b, output logic y);
|
||||
logic y1, y2;
|
||||
sub u_s1 (.clk, .a, .y(y1));
|
||||
sub u_s2 (.*);
|
||||
assign y = y1;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn qa_port_refuses_bad_shapes_and_connects_every_instantiation_or_none() {
|
||||
let tree = Tree::with(&[
|
||||
("rtl/sub.sv", SUB),
|
||||
("rtl/p1.sv", P1),
|
||||
("rtl/p2.sv", P2),
|
||||
("rtl/p3.sv", "module p3 (input logic clk, a, output logic y);\n sub u_pos (clk, a, y);\nendmodule\n"),
|
||||
]);
|
||||
let add = |after: Option<&str>| match after {
|
||||
Some(after) => json!({"module": "sub", "add": "input logic b", "after": after}),
|
||||
None => json!({"module": "sub", "add": "input logic b"}),
|
||||
};
|
||||
// A positional instantiation in one file refuses the whole edit.
|
||||
let whole = refusal(&tree, "port", add(None));
|
||||
assert!(whole.contains("p3.sv") && whole.contains("no edits were made"), "{whole}");
|
||||
fs::remove_file(tree.path("rtl/p3.sv")).unwrap();
|
||||
let anchor = refusal(&tree, "port", add(Some("nope")));
|
||||
assert_eq!(anchor, "`sub` has no port `nope` (its ports: clk, a, y).");
|
||||
let neither = refusal(&tree, "port", json!({"module": "sub"}));
|
||||
assert_eq!(neither, "give exactly one of `add` and `remove`.");
|
||||
let both =
|
||||
refusal(&tree, "port", json!({"module": "sub", "add": "input logic b", "remove": "a"}));
|
||||
assert_eq!(both, "give exactly one of `add` and `remove`.");
|
||||
let stray = refusal(&tree, "port", json!({"module": "sub", "remove": "a", "after": "clk"}));
|
||||
assert_eq!(stray, "`after` goes with `add`, not `remove`.");
|
||||
let used = refusal(&tree, "port", json!({"module": "sub", "remove": "a"}));
|
||||
assert!(used.contains("`a` is still used inside `sub`"), "{used}");
|
||||
let unknown = refusal(&tree, "port", json!({"module": "nosuch", "add": "input logic b"}));
|
||||
assert!(unknown.contains("`nosuch`"), "{unknown}");
|
||||
// Three instantiations in two files, each connected.
|
||||
let added = text(&tree, "port", add(Some("clk")));
|
||||
assert!(
|
||||
added.starts_with("added port b in module sub: 3 instantiations in 2 files\n"),
|
||||
"{added}"
|
||||
);
|
||||
assert!(tree.read("rtl/sub.sv").contains(" input logic clk,\n input logic b,\n"));
|
||||
assert!(
|
||||
tree.read("rtl/p1.sv").contains(" .clk(clk),\n .b"),
|
||||
"{}",
|
||||
tree.read("rtl/p1.sv")
|
||||
);
|
||||
assert!(
|
||||
tree.read("rtl/p2.sv").contains("sub u_s1 (.clk, .b(b), .a, .y(y1));"),
|
||||
"{}",
|
||||
tree.read("rtl/p2.sv")
|
||||
);
|
||||
assert!(tree.read("rtl/p2.sv").contains("sub u_s2 (.*);"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// edit_item
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ITEMS: &str = "module m (input logic clk, output logic y);
|
||||
logic used_sig;
|
||||
logic unused_sig;
|
||||
// the helper
|
||||
function automatic logic helper(input logic x);
|
||||
return ~x;
|
||||
endfunction
|
||||
assign used_sig = clk;
|
||||
assign y = helper(used_sig);
|
||||
endmodule
|
||||
|
||||
module n;
|
||||
logic z;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn qa_edit_item_refuses_used_deletes_and_renaming_replaces_and_inserts_at_a_units_end() {
|
||||
let tree = Tree::with(&[("rtl/m.sv", ITEMS)]);
|
||||
let edit = |op: &str, item: &str, text: Option<&str>| match text {
|
||||
Some(text) => json!({"file": "rtl/m.sv", "op": op, "item": item, "text": text}),
|
||||
None => json!({"file": "rtl/m.sv", "op": op, "item": item}),
|
||||
};
|
||||
let used = refusal(&tree, "edit_item", edit("delete", "used_sig", None));
|
||||
assert_eq!(
|
||||
used,
|
||||
"still referenced: rtl/m.sv:8:10 `used_sig`; rtl/m.sv:9:21 `used_sig`; nothing written."
|
||||
);
|
||||
let called = refusal(&tree, "edit_item", edit("delete", "helper", None));
|
||||
assert!(called.contains("rtl/m.sv:9:14 `helper`"), "{called}");
|
||||
let renamed = refusal(&tree, "edit_item", edit("replace", "unused_sig", Some("logic other;")));
|
||||
assert!(renamed.contains("`rename` renames"), "{renamed}");
|
||||
let at_end = text(&tree, "edit_item", edit("insert_after", "end@n", Some(" logic w;")));
|
||||
assert_eq!(at_end, "inserted declaration w rtl/m.sv:15\n");
|
||||
assert!(tree.read("rtl/m.sv").ends_with("module n;\n logic z;\n\n logic w;\nendmodule\n"));
|
||||
let nowhere = refusal(&tree, "edit_item", edit("insert_after", "end@nope", Some("logic q;")));
|
||||
assert!(nowhere.contains("`nope`"), "{nowhere}");
|
||||
// The control: an unused item goes, with its line.
|
||||
let gone = text(&tree, "edit_item", edit("delete", "unused_sig", None));
|
||||
assert_eq!(gone, "deleted declaration unused_sig rtl/m.sv:3\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// format
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_format_names_the_refused_file_writes_the_rest_and_refuses_an_empty_glob() {
|
||||
let tree = Tree::with(&[
|
||||
("rtl/a.sv", "module a(input logic x);\nlogic y;\nendmodule\n"),
|
||||
("rtl/b.sv", "module b;\n logic y ;\nendmodule\n"),
|
||||
("rtl/c.sv", "module c;\n logic y;\nendmodule\n"),
|
||||
("rtl/bad.sv", "module bad(\n input logic x\n logic y;\nendmodule\n"),
|
||||
]);
|
||||
let nothing = refusal(&tree, "format", json!({"files": "rtl/**/*.vhd"}));
|
||||
assert_eq!(nothing, "no indexed file matches `rtl/**/*.vhd`; nothing written.");
|
||||
let bad = tree.read("rtl/bad.sv");
|
||||
let answer = text(&tree, "format", json!({"files": "rtl/*.sv"}));
|
||||
let lines: Vec<&str> = answer.lines().collect();
|
||||
assert_eq!(lines[0], "formatted 3 files (1 unchanged)");
|
||||
assert_eq!(lines.len(), 2, "{answer}");
|
||||
assert!(lines[1].starts_with("not formatted: rtl/bad.sv (parse error: 3:3"), "{answer}");
|
||||
assert_eq!(tree.read("rtl/a.sv"), "module a (input logic x);\n logic y;\nendmodule\n");
|
||||
assert_eq!(tree.read("rtl/b.sv"), "module b;\n logic y;\nendmodule\n");
|
||||
assert_eq!(tree.read("rtl/bad.sv"), bad);
|
||||
let again = text(&tree, "format", json!({"files": "rtl"}));
|
||||
assert!(
|
||||
again.starts_with("formatted 3 files (3 unchanged)\nnot formatted: rtl/bad.sv"),
|
||||
"{again}"
|
||||
);
|
||||
// Only the refused file: the call itself is a refusal.
|
||||
let alone = refusal(&tree, "format", json!({"files": "rtl/bad.sv"}));
|
||||
assert!(alone.starts_with("not formatted: rtl/bad.sv"), "{alone}");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// All-or-nothing
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_a_rename_whose_later_file_is_read_only_writes_nothing() {
|
||||
let tree = Tree::with(&[("rtl/sub.sv", SUB), ("rtl/p1.sv", P1), ("rtl/p2.sv", P2)]);
|
||||
let p2 = tree.path("rtl/p2.sv");
|
||||
let mut permissions = fs::metadata(&p2).unwrap().permissions();
|
||||
permissions.set_readonly(true);
|
||||
fs::set_permissions(&p2, permissions.clone()).unwrap();
|
||||
// `p1.sv` sorts first and would be written first: it must not be.
|
||||
let refused = refusal(&tree, "rename", json!({"name": "sub", "new_name": "sub2"}));
|
||||
assert_eq!(refused, "`rtl/p2.sv` is read-only; nothing written.");
|
||||
#[allow(clippy::permissions_set_readonly_false)] // a test undoing its own chmod
|
||||
permissions.set_readonly(false);
|
||||
fs::set_permissions(&p2, permissions).unwrap();
|
||||
let renamed = text(&tree, "rename", json!({"name": "sub", "new_name": "sub2"}));
|
||||
assert_eq!(renamed, "renamed 4 sites in 3 files\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Answer shape (PLAN §10.2)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_answers_are_root_relative_one_fact_per_line_without_hints() {
|
||||
let tree = Tree::with(&[("rtl/leaf.sv", PEEKED), ("rtl/top.sv", PEEKER), ("rtl/fsm.sv", FSM)]);
|
||||
let calls = [
|
||||
("hierarchy", json!({})),
|
||||
("hierarchy", json!({"root": "top", "depth": 3})),
|
||||
("hierarchy", json!({"root": "leaf", "up": true})),
|
||||
("find", json!({"name": "leaf", "refs": true})),
|
||||
("find", json!({"name": "mid", "refs": true})),
|
||||
("outline", json!({"file": "rtl/fsm.sv"})),
|
||||
("outline", json!({"unit": "leaf"})),
|
||||
("check", json!({})),
|
||||
("check", json!({"file": "rtl/leaf.sv"})),
|
||||
];
|
||||
let root = tree.0.to_string_lossy().to_string();
|
||||
for (call, said) in calls.iter().zip(session(&tree, &calls)) {
|
||||
assert!(!said.refused, "{call:?}: {}", said.text);
|
||||
assert!(said.text.ends_with('\n'), "{call:?}");
|
||||
for line in said.text.lines() {
|
||||
assert!(!line.trim().is_empty(), "{call:?}: a blank line in {}", said.text);
|
||||
assert_eq!(line, line.trim_end(), "{call:?}");
|
||||
assert!(!line.contains(&root) && !line.contains("/private/"), "{call:?}: {line}");
|
||||
for hint in ["check:", "dry run", "use `", "call `", "next:"] {
|
||||
assert!(!line.contains(hint), "{call:?}: {line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(text(&tree, "check", json!({"file": "rtl/leaf.sv"})), "ok\n");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// find refs: at most five declarations followed
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_find_refs_follows_five_declarations_and_says_so() {
|
||||
let files: Vec<(String, String)> = (0..7)
|
||||
.map(|i| {
|
||||
let text = format!(
|
||||
"module r{i} (output logic y);\n logic sig;\n assign y = sig;\nendmodule\n"
|
||||
);
|
||||
(format!("rtl/r{i}.sv"), text)
|
||||
})
|
||||
.collect();
|
||||
let borrowed: Vec<(&str, &str)> = files.iter().map(|(p, t)| (p.as_str(), t.as_str())).collect();
|
||||
let tree = Tree::with(&borrowed);
|
||||
let answer = text(&tree, "find", json!({"name": "sig", "refs": true}));
|
||||
let mut expected = String::new();
|
||||
for i in 0..7 {
|
||||
expected.push_str(&format!("var sig rtl/r{i}.sv:2\n"));
|
||||
if i < 5 {
|
||||
expected.push_str(&format!(" rtl/r{i}.sv:3\n"));
|
||||
}
|
||||
}
|
||||
expected.push_str("uses listed for 5 of 7 declarations\n");
|
||||
assert_eq!(answer, expected);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Re-check of the rework (2026-09-24): `declared.rs`, `rooted`, `similar`.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const LOCALS: &str = "module fsm (input logic clk, output logic busy);
|
||||
typedef enum logic [1:0] {StIdle, StBusy} state_e;
|
||||
state_e state_q;
|
||||
function automatic logic helper(input logic x);
|
||||
logic hl;
|
||||
hl = ~x;
|
||||
return hl;
|
||||
endfunction
|
||||
task automatic poke(output logic o);
|
||||
o = 1'b0;
|
||||
endtask
|
||||
for (genvar gi = 0; gi < 2; gi++) begin : g_lane
|
||||
logic lane_q;
|
||||
assign lane_q = gi[0];
|
||||
end
|
||||
always_comb begin
|
||||
automatic logic tmp;
|
||||
tmp = helper(state_q == StBusy);
|
||||
busy = tmp | g_lane[0].lane_q;
|
||||
end
|
||||
always_ff @(posedge clk) state_q <= StIdle;
|
||||
endmodule
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit() {
|
||||
let cases = [
|
||||
("state_e", "typedef state_e rtl/fsm.sv:2", "renamed 2 sites in 1 file"),
|
||||
("StIdle", "enum_value StIdle rtl/fsm.sv:2", "renamed 2 sites in 1 file"),
|
||||
("helper", "function helper rtl/fsm.sv:4", "renamed 2 sites in 1 file"),
|
||||
("hl", "var hl rtl/fsm.sv:5", "renamed 3 sites in 1 file"),
|
||||
("poke", "task poke rtl/fsm.sv:9", "renamed 1 site in 1 file"),
|
||||
("gi", "genvar gi rtl/fsm.sv:12", "renamed 4 sites in 1 file"),
|
||||
("tmp", "var tmp rtl/fsm.sv:17", "renamed 3 sites in 1 file"),
|
||||
];
|
||||
for (name, found, renamed) in cases {
|
||||
let named = [
|
||||
json!({"name": name, "new_name": "zz_new"}),
|
||||
json!({"name": name, "new_name": "zz_new", "file": "rtl/fsm.sv"}),
|
||||
json!({"name": format!("fsm.{name}"), "new_name": "zz_new"}),
|
||||
];
|
||||
for args in named {
|
||||
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
|
||||
assert_eq!(text(&tree, "find", json!({"name": name})), format!("{found}\n"));
|
||||
assert_eq!(
|
||||
text(&tree, "find", json!({"name": format!("fsm.{name}")})),
|
||||
format!("{found}\n")
|
||||
);
|
||||
assert_eq!(text(&tree, "rename", args.clone()), format!("{renamed}\n"), "{args}");
|
||||
let after = tree.read("rtl/fsm.sv");
|
||||
let left = after
|
||||
.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.any(|word| word == name);
|
||||
assert!(!left, "{args}: `{name}` left in\n{after}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind() {
|
||||
// `find g_lane refs` lists no use and `rename` answers `renamed 1 site`,
|
||||
// leaving `g_lane[0].lane_q` naming a block that no longer exists —
|
||||
// while `edit_item delete g_lane` sees the use (`rtl/fsm.sv:19:18`).
|
||||
let tree = Tree::with(&[("rtl/fsm.sv", LOCALS)]);
|
||||
// Lead's ruling R1: the MCP layer refuses the rename, and the source
|
||||
// is untouched.
|
||||
let said = session(&tree, &[("rename", json!({"name": "g_lane", "new_name": "g_ln"}))]);
|
||||
assert!(said[0].refused, "{}", said[0].text);
|
||||
let why = &said[0].text;
|
||||
assert!(why.starts_with("`rename` does not rename generate block labels"), "{why}");
|
||||
assert_eq!(tree.read("rtl/fsm.sv"), LOCALS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_a_shared_base_name_is_named_by_path_or_left_alone() {
|
||||
let tree = Tree::with(&[
|
||||
("rtl/x/p1.sv", "module px (input logic clk);\n logic dup;\n assign dup = clk;\nendmodule\n"),
|
||||
(
|
||||
"rtl/y/p1.sv",
|
||||
"module py (input logic clk);\n logic dup;\n assign dup = ~clk;\n sub u_s (.*);\nendmodule\n",
|
||||
),
|
||||
("rtl/z/sub.sv", "module sub (input logic clk, input logic a);\nendmodule\n"),
|
||||
("rtl/z/p1b.sv", "module pz (input logic clk);\n logic a;\n sub u_s (.clk, .a);\nendmodule\n"),
|
||||
]);
|
||||
let both = refusal(&tree, "rename", json!({"name": "dup", "new_name": "d2"}));
|
||||
assert!(both.contains("(rtl/x/p1.sv:2, rtl/y/p1.sv:2)"), "{both}");
|
||||
let one = json!({"name": "dup", "new_name": "d2", "file": "rtl/y/p1.sv"});
|
||||
assert_eq!(text(&tree, "rename", one), "renamed 2 sites in 1 file\n");
|
||||
assert!(tree.read("rtl/y/p1.sv").contains("logic d2;"));
|
||||
assert!(tree.read("rtl/x/p1.sv").contains("logic dup;"));
|
||||
// The engine's sentences: `p1.sv` is two files, so it stays as said;
|
||||
// `p1b.sv` is one, so it is named by its path.
|
||||
let added = text(&tree, "port", json!({"module": "sub", "add": "input logic zz"}));
|
||||
assert!(added.contains("`u_s` at p1.sv:4 connects with `.*` and p1.sv has"), "{added}");
|
||||
assert!(added.contains("(rtl/z/p1b.sv:3)"), "{added}");
|
||||
assert!(!added.contains("rtl/z/rtl/"), "{added}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_an_enum_value_in_case_arms_is_renamed_across_files_with_its_mentions() {
|
||||
let tree = Tree::with(&[
|
||||
("rtl/st_pkg.sv", "package st_pkg;\n typedef enum logic [1:0] {StIdle, StRun, StDone} st_e;\nendpackage\n"),
|
||||
(
|
||||
"rtl/a.sv",
|
||||
"module a import st_pkg::*; (input logic clk, output logic o);\n st_e s;\n // StRun is the busy state\n always_comb begin\n case (s)\n StIdle: o = 1'b0;\n StRun: o = 1'b1;\n default: o = 1'b0;\n endcase\n end\n always_ff @(posedge clk) s <= StRun;\nendmodule\n",
|
||||
),
|
||||
(
|
||||
"rtl/b.sv",
|
||||
"module b (input logic clk, output logic o);\n st_pkg::st_e s;\n initial $display(\"StRun\");\n always_comb begin\n unique case (s)\n st_pkg::StRun: o = 1'b1;\n default: o = 1'b0;\n endcase\n end\n always_ff @(posedge clk) s <= st_pkg::StIdle;\nendmodule\n",
|
||||
),
|
||||
]);
|
||||
let found = text(&tree, "find", json!({"name": "StRun", "refs": true}));
|
||||
let mentions = "unresolved:\n rtl/a.sv:3\n rtl/b.sv:3\n";
|
||||
assert_eq!(
|
||||
found,
|
||||
format!("enum_value StRun rtl/st_pkg.sv:2\n rtl/a.sv:7,11\n rtl/b.sv:6\n{mentions}")
|
||||
);
|
||||
// Only in a comment or a string: no declaration, a sane near match.
|
||||
assert_eq!(refusal(&tree, "find", json!({"name": "busy"})), "no declaration named `busy`.");
|
||||
assert_eq!(
|
||||
refusal(&tree, "find", json!({"name": "StRu"})),
|
||||
"no declaration named `StRu`; similar: StRun."
|
||||
);
|
||||
let renamed = text(&tree, "rename", json!({"name": "st_pkg::StRun", "new_name": "StBusy"}));
|
||||
assert_eq!(renamed, format!("renamed 4 sites in 3 files\n{mentions}"));
|
||||
assert!(tree.read("rtl/b.sv").contains("st_pkg::StBusy: o"));
|
||||
assert!(
|
||||
tree.read("rtl/a.sv").contains("// StRun is")
|
||||
&& tree.read("rtl/a.sv").contains("s <= StBusy;")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_rework_an_escaped_net_is_still_found_through_the_index() {
|
||||
let text_e = "module e (input logic clk, output logic o);\n logic \\my.sig ;\n assign \\my.sig = clk;\n assign o = \\my.sig ;\nendmodule\n";
|
||||
let tree = Tree::with(&[("rtl/e.sv", text_e)]);
|
||||
let found = text(&tree, "find", json!({"name": "\\my.sig", "refs": true}));
|
||||
assert_eq!(found, "var \\my.sig rtl/e.sv:2\n rtl/e.sv:3,4\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "QA re-check finding R2"]
|
||||
fn qa_rework_an_escaped_local_outline_lists_is_found() {
|
||||
// The word census holds identifier-shaped words only, so `declared.rs`
|
||||
// never opens a file for an escaped name the index does not record.
|
||||
let text_g = "module g (input logic clk, output logic o);\n function automatic logic fn(input logic x);\n logic \\loc.v ;\n \\loc.v = x;\n return \\loc.v ;\n endfunction\n assign o = fn(clk);\nendmodule\n";
|
||||
let tree = Tree::with(&[("rtl/g.sv", text_g)]);
|
||||
assert!(text(&tree, "outline", json!({"file": "rtl/g.sv"})).contains("var \\loc.v 3"));
|
||||
assert_eq!(text(&tree, "find", json!({"name": "\\loc.v"})), "var \\loc.v rtl/g.sv:3\n");
|
||||
}
|
||||
+660
-1366
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,575 @@
|
||||
# mcp-lean-catalogue
|
||||
|
||||
Lane **M7** of the MCP block (`TODO-MCP.md`, `docs/mcp/PLAN.md` §10).
|
||||
|
||||
## Goal
|
||||
|
||||
The census (`mcp_analysis.md`) found `lucisv-mcp` right on every run and
|
||||
dearer than plain file reads on every small task: a 5 400-token catalogue
|
||||
read each session, answers carrying more than the question asked, and
|
||||
agents dry-running what they were told to trust. The owner's ruling is
|
||||
*accuracy over breadth*: keep what only this server can do — the design's
|
||||
hierarchy as `file:line`, where a name is declared and used, and the bulk
|
||||
edits a file write cannot make safely — as **nine tools** (`hierarchy`,
|
||||
`find`, `outline`, `read`, `check`, `rename`, `port`, `edit_item`,
|
||||
`format`), a model-visible catalogue under 3 500 bytes, instructions under
|
||||
400, short answers with fixed caps, no `dry_run` and no paging. The engines,
|
||||
the write path, the M4 verifier and its attack suite, freshness, roots and
|
||||
the cache are reused unchanged in substance.
|
||||
|
||||
## Assumptions
|
||||
|
||||
Decisions where PLAN §10 is silent (the simplest thing, recorded):
|
||||
|
||||
### Wire
|
||||
|
||||
- **Annotations** keep all four hints (`readOnlyHint`, `destructiveHint:
|
||||
false`, `idempotentHint`, `openWorldHint: false`); hosts read them, the
|
||||
budget counts only `name` + `description` + `inputSchema` (compact JSON
|
||||
array of the nine objects, `serde_json::to_string`). `idempotentHint` is
|
||||
`true` for the five read tools and `format`, `false` for `rename`, `port`
|
||||
and `edit_item`.
|
||||
- A range argument (`depth`) is `{"type": "integer"}` in the schema (§10.1:
|
||||
`type` alone); the range is still enforced by validation and named in
|
||||
the description (`1-20`).
|
||||
- `required` is always present, `[]` when nothing is required.
|
||||
- A result is `{content: [{type: text, text}], isError}` — nothing else.
|
||||
|
||||
### Rendering
|
||||
|
||||
- A line range is `first–last` (en dash), a one-line range the single
|
||||
number, everywhere (`outline`, `read`, `edit_item`).
|
||||
- Counts are pluralised (`1 file`, `2 files`), so the §10.1 forms read
|
||||
`renamed 1 site in 1 file`, `… 1 instantiation in 1 file`.
|
||||
- Engine sentences (refusals of `vlog_refactor::{rename, add_port,
|
||||
remove_port, find_references}`, `place::after`, and the engine warnings a
|
||||
rename or port edit carries) name files by base name; the MCP layer
|
||||
rewrites a base name to the root-relative path when exactly one file it
|
||||
handed the engine has that base name (`WholeSet::rooted`). When two files
|
||||
share it the sentence is left as the engine wrote it.
|
||||
- Engine and write-path warnings are facts, not hints: each is one
|
||||
`warning: …` line after the answer's first line (the skipped-file line
|
||||
`warning: not indexed, so not searched or edited: …`, the rename
|
||||
engine's macro warnings, `port`'s TODO-connection lines).
|
||||
- The `unresolved:` block is the label, then one file per line
|
||||
(` file:12,40`), at most 50 mentions then ` … and N more` — the kinds
|
||||
(string, comment, macro, define, path) and the line text are gone, per
|
||||
"the same way" in §10.1.
|
||||
|
||||
### hierarchy
|
||||
|
||||
- Without `root` it **walks the roots first** (the successor of
|
||||
`project_overview`, which always walked), then `N files, M modules, K
|
||||
top`; `M` counts `Module`-kind units (programs included), `K` and the
|
||||
list are every module nothing instantiates, **one line per declaration**
|
||||
(a module declared in two files is two tops at their two lines).
|
||||
- Down: the root line `module file:line` (its declaration) is kept at
|
||||
indent 0, instances at two spaces per level. Each instance's `file:line`
|
||||
is the line of the instance name (the old tool's site line). A module
|
||||
declared twice is still two root lines.
|
||||
- Up: no root line; level 1 at indent 0, deeper levels two spaces each;
|
||||
walked once by name (a root declared twice is not repeated). An
|
||||
uninstantiated root answers `nothing instantiates X`.
|
||||
- The notes stay as suffixes: ` (recursive)`, ` (not indexed)`,
|
||||
` (declared N times)`.
|
||||
- `peek` lines are the statement from the start of the line naming the
|
||||
module to the end of the line holding its `;`, the common indentation
|
||||
removed, indented four spaces past the node's line, at most 12 lines then
|
||||
`…`. Nothing is shown when the file no longer spells the module there.
|
||||
- The 300-line cap cuts whole nodes (a node's peek block is never split);
|
||||
`… and N more` counts the nodes left. The 50 000-node walk cap stays, so
|
||||
on a cut walk `N` is a lower bound.
|
||||
- Unknown root: up to 10 module/interface names containing it, any case.
|
||||
|
||||
### find
|
||||
|
||||
- Declarations are the index's units, exported members and module
|
||||
internals (`hierarchical_declarations`), each checked against the bytes
|
||||
on disk, sorted by file and line; then `` `define``s (`macro NAME
|
||||
file:line`, `` `undef`` omitted). A `program` says `program`.
|
||||
- **`unit.name` / `pkg::name`** (not in §10.1, which gives `find` no way to
|
||||
pick one of many declarations): the member of that unit only
|
||||
(`member_in(..., Surface::Hierarchical)`); an escaped identifier is never
|
||||
split. `rename` accepts it too. Found necessary on opentitan, where
|
||||
`state_q` has hundreds of declarations.
|
||||
- `refs` walks the roots once first (the whole set must be complete), then
|
||||
runs `find_references` (declaration excluded) per declaration — **at most
|
||||
5 declarations** (`REFS_CAP`): each is a whole-set engine run (≈ 2 s on
|
||||
opentitan), so a name declared more often gets a closing line `uses
|
||||
listed for 5 of N declarations`. Macros have no uses listed (no engine
|
||||
follows them). An engine refusal is ` uses not listed: …`, reworded so it
|
||||
never speaks of renaming.
|
||||
- Besides the index, every declaration the files' own symbol tables hold
|
||||
is found (`declared.rs`): the files whose word census holds the name are
|
||||
read from disk and analysed, and each symbol of that name is a
|
||||
declaration (typedefs, enum values, functions, tasks, genvars, generate
|
||||
blocks and what they declare, procedural locals). `unit.name` keeps those
|
||||
whose innermost enclosing module, interface, package or class is `unit`.
|
||||
An escaped identifier is not in the word census (it holds plain
|
||||
identifiers only), so an escaped *local* name the index does not record —
|
||||
a function's `\loc.v`, say — is not found by name (QA re-check R2,
|
||||
accepted; `outline` and `read` with `file` still reach it).
|
||||
- No declaration: `no declaration named X; similar: …` — up to 20 names
|
||||
containing it, any case, from the same table (`declared.rs` with a part
|
||||
of a name, plus `workspace_symbols` for escaped names) and the define
|
||||
tables. A short part reads most files (≈ 1–2 s on opentitan, refusal
|
||||
path only).
|
||||
|
||||
### outline, read, check
|
||||
|
||||
- `outline unit:` first line is the unit's `file:line` alone; then
|
||||
`param NAME = DEFAULT` (`param NAME` without one), ports
|
||||
`dir type [range] name [unpacked]` with empty parts left out, `modport
|
||||
…` lines, and for packages and classes `extends BASE` and `kind name
|
||||
LINE`. A unit declared twice is refused listing both (the file outline
|
||||
is the way to pick one); via the `lucisv://unit/` resource the sentence
|
||||
points at the file outline resource instead.
|
||||
- `outline file:` parse errors are `error LINE: message` (the column is in
|
||||
`check`).
|
||||
- `read` without `file` looks the name up among the index's declarations,
|
||||
counts matching declarations (kind and `@LINE` honoured) in each file,
|
||||
and needs exactly one; `always@LINE` and friends need `file`.
|
||||
- `check` sorts stably by severity (error, warning, rest), so a file's
|
||||
parse errors lead and each file keeps its order within a severity; the
|
||||
message is collapsed to one line; `rules`, `severity` and `in` are gone.
|
||||
|
||||
### Edits
|
||||
|
||||
- **`rename`**: `name` may be `name@LINE` (with `file`, picks one of two
|
||||
declarations in one file) or `unit.name`. A name already equal to
|
||||
`new_name` answers `renamed 0 sites in 0 files`. `N sites` is the
|
||||
engine's edit count, `M files` the files written.
|
||||
- **`rename`** refuses every `block`-kind declaration (the symbol table's
|
||||
kind for a generate block label, and for a named `begin : label` too):
|
||||
no engine rewrites or reports a hierarchical path through a block.
|
||||
- **`port`**: the module is found by `module_definition` (exactly one
|
||||
declaring file). `remove` finds the port by name in the module's own
|
||||
scope in that file. `N instantiations in K files` is the index's census
|
||||
of the module's instances before the edit (every instance the engine
|
||||
visits), not the files written.
|
||||
- **`edit_item`**: `item` is the anchor for inserts. `replace` refuses a
|
||||
text declaring other names (no `rename` flag) and points at `rename`;
|
||||
the no-op answers `unchanged CLASS NAMES file:lines`. `delete` has no
|
||||
`force`: a used item, a nested `` `define``, a fence stay refusals. The
|
||||
answer's lines are the new item's (replace/insert) or the removed lines
|
||||
(delete). `rewalk: true` (a delete needs the complete set).
|
||||
- **`format`**: `files` is a path (resolved as every path argument), else
|
||||
a directory or glob matched against every indexed file's root-relative
|
||||
path (`glob.rs`, the old `in` matcher). `formatted N files (M
|
||||
unchanged)`: `N` counts every file that passed the safety net, `M` those
|
||||
already formatted. A refused file is one `not formatted: FILE (why)` line
|
||||
and the rest are still written (all-or-nothing among them); when every
|
||||
file is refused the call is a refusal. `fix` runs the safe fixes (the
|
||||
CLI's `--fix` filter, fences honoured, parse-error guard), then formats.
|
||||
- There is no dry run anywhere: `apply::run` checks roots and freshness,
|
||||
then writes, and returns which files it wrote.
|
||||
|
||||
### The verifier
|
||||
|
||||
- `Expect::Nothing { force }` became `Expect::Nothing` and the forced
|
||||
path (`dropped` macros) was removed from `tools/item/verify.rs`: dead
|
||||
once `force` left the wire, and it was a *relaxation* — removing it can
|
||||
only refuse more (CLAUDE.md invariant 4 is about widening). Every other
|
||||
rule is byte-identical; `tests/attacks.rs` passes with its cases as
|
||||
written (a call translator maps them; the three forced cases became
|
||||
refusals).
|
||||
|
||||
## Handshakes
|
||||
|
||||
Consumed (unchanged): `vlog_refactor::{rename, add_port, remove_port,
|
||||
find_references, instantiation_plan, module_definition, enclosing_module}`,
|
||||
`vlog_semantic::WorkspaceIndex` (`units`, `member_in`, `members_of`,
|
||||
`workspace_symbols`, `hierarchical_declarations`, `find_define`, `defines`,
|
||||
`instantiations`, `instantiations_of`, `instantiable_units`, `units_of`),
|
||||
the linter and formatter entry points `diagnostics.rs`/`format.rs` used
|
||||
before. No longer consumed: `lucisv_core::diff::unified`,
|
||||
`vlog_formatter::format_range`, the six cursor refactorings.
|
||||
|
||||
Promised: the spawn contract with the extension is amended — `tools/list`
|
||||
is exactly the nine names in order (`editors/vscode/mcp_smoke.js`
|
||||
`TOOLS`, was `MIN_TOOLS = 26`); `docs/topo.md` §2.8 updated.
|
||||
|
||||
Requests (not edits):
|
||||
|
||||
- **MCP-11 → `vlog_refactor`:** `find_references` over several
|
||||
declarations in one `Scope` (one index build), so `find refs` need not
|
||||
cap at 5 declarations. Today each declaration is a full build.
|
||||
- **MCP-14 → `vlog_refactor`/`vlog_semantic` (topo §2.9 row 43):** a
|
||||
rename of a generate block label leaves hierarchical paths through it
|
||||
(`g_lane[0].lane_q`) unrewritten, and `find_references` does not report
|
||||
them; the MCP layer refuses the rename (any `block`-kind declaration);
|
||||
the LSP still allows it.
|
||||
- **MCP-13 → release/docs owners (outside this lane's files):**
|
||||
`tools/release.sh` (comments at lines 134 and 257), `tools/RELEASING.md:129`
|
||||
("at least 26 tools, one `project_overview`") and
|
||||
`docs/manual-acceptance.md` rows 19 and 24 ("call lucisv's
|
||||
project_overview") name the old catalogue; the smoke gate itself
|
||||
(`mcp_smoke.js`) is updated. They should say nine tools and `hierarchy`.
|
||||
- **MCP-12 → lead:** PLAN §10.3's instruction text is 444 bytes against
|
||||
its own 400-byte budget; the shipped text (398 bytes) is a tightening of
|
||||
it (below). Rule on the wording.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] registry: nine tools in order, no `title`/`structuredContent`, no
|
||||
per-argument descriptions; `wire.rs` pins names, order, budgets and
|
||||
the absence of `dry_run`, `limit`, `offset`, `in`, `template`,
|
||||
`overrides`, `force`
|
||||
- [x] `hierarchy` (no root, down, up, peek, cap, near matches); opentitan
|
||||
instance set identical to 0.57.0 (`tests/opentitan.rs`)
|
||||
- [x] `find` (declarations, macros, `refs`, `unresolved:`, near matches)
|
||||
- [x] `outline` (`file` xor `unit`), `read` (design-wide), `check` (`ok`;
|
||||
0.57.0 line set on every fixture)
|
||||
- [x] `rename`, `port`, `edit_item`, `format`
|
||||
- [x] instructions ≤ 400 bytes; resources render through `hierarchy` and
|
||||
`outline`
|
||||
- [x] tests ported or deleted (below); invariants kept
|
||||
- [x] docs: this README, Agents guide table + promises, extension
|
||||
README/CHANGELOG, `CHANGELOG.md` 0.58.0, topo §2.8, PLAN §4.3/§4.5
|
||||
marked superseded
|
||||
- [x] QA (2026-09-24: PASS with findings — QA log)
|
||||
- [ ] census round 4 (lead), release 0.58.0
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-23 — dev (M7)
|
||||
|
||||
**Byte figures** (release binary, `tools/list` over the design fixture):
|
||||
model-visible catalogue **3 440 bytes** (was 17 900 for `tools/list`);
|
||||
instructions **398 bytes**. Per tool (compact name+description+schema):
|
||||
`hierarchy` 433, `find` 362, `outline` 345, `read` 357, `check` 294,
|
||||
`rename` 395, `port` 404, `edit_item` 482, `format` 358.
|
||||
|
||||
**Instructions shipped** (§10.3's text is 444 bytes; tightened, same
|
||||
facts): "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."
|
||||
|
||||
**Code.** `tools/mod.rs` holds the nine; `Answer` is `{text}`; `Param` has
|
||||
no description; `Ty::Int` gone. New: `find.rs`, `names.rs` (declarations
|
||||
by name, near matches, `unit.name`), `outline.rs`, `port.rs`, `glob.rs`
|
||||
(moved from `read.rs`). Rewritten: `hierarchy.rs`, `read.rs` (the `read`
|
||||
tool; the slicer stays `read_item.rs`), `interface.rs` (outline's unit
|
||||
half), `diagnostics.rs` (`check`), `edit.rs` (`rename` + the shared
|
||||
whole-set/write/mentions step), `item.rs` (`edit_item`), `format.rs`,
|
||||
`apply.rs` (no dry run, no diff, returns `Written`), `render.rs` (caps,
|
||||
`by_file`, counts), `mentions.rs` (the `unresolved:` block), `source.rs`.
|
||||
Deleted: `defines.rs` (macros are `find` declarations), `select.rs`
|
||||
(position selectors; name-based now), `nav.rs` (→ `find.rs`/`names.rs`),
|
||||
`refactor.rs` (`add_port` → `port.rs`; `extract_module`, `instantiate`
|
||||
dropped). Dead project/analysis helpers removed. All files under 460 lines.
|
||||
|
||||
**Differential.** Built `v0.57.0` (`git archive` into scratch) and
|
||||
compared: `check` line sets identical on all six fixtures and on five
|
||||
opentitan files; `hierarchy top_earlgrey` identical at depth 1 (2) and 2
|
||||
(49 instances), depth 3 identical over the 299 lines shown (464 in all);
|
||||
`hierarchy prim_fifo_sync up` identical (77). The r4 eval binary reports
|
||||
0.56.0 and agrees too. The depth-2 set is pinned in `tests/opentitan.rs`.
|
||||
Opentitan timings (release): startup 2.1 s cold / 0.9 s warm; `find
|
||||
aes.entropy_masking_req refs` 2.1 s; `find aes refs` (5 declarations)
|
||||
9.4 s; `hierarchy top_earlgrey depth 2` 0.4 s; the checkout's `git status`
|
||||
unchanged by every run.
|
||||
|
||||
**Tests** (347 pass, 3 ignored opentitan pass with `--ignored`):
|
||||
|
||||
| suite | before → after | what happened |
|
||||
|---|---|---|
|
||||
| unit (`src`) | 77 → 72 | paging/table/`in`/check-line/overrides/`defines` unit tests deleted with their code; glob tests moved; `qualified`, `count`, `by_file`, instructions-budget tests added |
|
||||
| `attacks.rs` | 23 → 23 | unchanged cases through a `lean` call translator; `rename: true` variant dropped (the refusal was the same); the three `force` controls are now asserted refusals |
|
||||
| `wire.rs` | 57 → 40 | rewritten per tool; budgets, names/order, bare schemas, text-only results pinned |
|
||||
| `qa_m1.rs` | 51 → 48 | `list_units` freshness checks → `find` hits / `hierarchy` walks; deleted: `list_units` glob `?` (covered by `glob.rs`), `outline depth/limit/offset`, `search_symbols` empty query |
|
||||
| `qa_m2.rs` | 43 → 35 | `references`/`definition` → `find refs`; deleted: position-selector attacks (whitespace/keyword/column/byte-column/macro-argument positions, findings 2, 3, 8, 9-by-position), paging, `rules`/`severity` filters, `defines` table shape, overrides JSON |
|
||||
| `qa_m3.rs` | 33 → 31 | edit tools → `rename`/`port`/`edit_item`/`format`; deleted: cursor refactorings, `extract_module` paths and CRLF (finding 3), `instantiate` (finding 5), `lines` ranges, `dry_run` diff checks; the references-vs-warning sweep now sweeps `find` |
|
||||
| `qa_m4.rs` | 45 → 45 | unchanged cases through a translator; forced deletes are refusals; dry-run diffs → real writes |
|
||||
| `qa_m6.rs` | 17 → 17 | probes and instructions ported; forced-delete pair → refusal + plain delete |
|
||||
| `qa_f1.rs` | 23 → 21 | `add_port` → `port`; mentions read from the `unresolved:` block; deleted: the dry-run-diff-equals-write test and QA finding 6 (dry-run mention lines) |
|
||||
| `qa_f2.rs` | 14 → 6 | paging, count lines, `in` on every tool and the check line deleted; kept the hierarchy walk over the tree and the path glob (now `format`'s) |
|
||||
| `qa_f3.rs` | 7 → deleted | `template` and `overrides` are gone; the flag-type refusals are covered in `wire.rs`/`qa_m3.rs` |
|
||||
| `cache.rs` | 4 → 4 | tool names |
|
||||
| `opentitan.rs` | 2 → 3 | `find`/`hierarchy`/`check`; the whole-set timing is `find refs` (read-only; the old dry-run rename would now write); new 0.57.0 instance-set test |
|
||||
|
||||
Kept invariants, with their tests: verifier attacks (`attacks.rs`,
|
||||
`qa_m4.rs`), all-or-nothing writes (`apply.rs` unit tests, `qa_m3.rs`
|
||||
commit tests, the racing-writer test), roots (`wire.rs`, `qa_m1.rs`,
|
||||
`qa_m3.rs::qa_rewritten_paths_never_leave_the_root`), freshness (`qa_m1.rs`
|
||||
freshness section, `wire.rs::answers_follow_the_disk_between_calls`), cache
|
||||
read-only (`cache.rs`, `qa_m6.rs`), unresolved mentions on `rename`/`find`/
|
||||
`port` (`wire.rs`, `qa_f1.rs`), rename over `.name`/`.*` (`qa_m3.rs`
|
||||
finding 1, `qa_f1.rs` star binding).
|
||||
|
||||
**Deviations from §10.** Instructions text tightened to fit 400 bytes
|
||||
(MCP-12). `find`/`rename` accept `unit.name`. `find refs` caps at 5
|
||||
declarations. `format` answers `not formatted: FILE (why)` lines and is a
|
||||
refusal only when every file is refused. The hierarchy root line is kept
|
||||
for `down`. `verify.rs` lost its dead forced path.
|
||||
|
||||
### 2026-09-24 — dev (M7 rework after QA)
|
||||
|
||||
- **Finding 1 (every declaration by name).** New `tools/declared.rs`: the
|
||||
files whose word census holds the name are read and analysed, and every
|
||||
symbol of that name in their own tables is a declaration, merged (by file
|
||||
and offset) with the index's. `find`, `read` without `file` and `rename`
|
||||
now reach typedefs, enum values, functions, tasks, genvars, generate
|
||||
blocks and their contents, and procedural locals; `unit.name` filters by
|
||||
the enclosing unit. `rename` hands the declaration's file and offset to
|
||||
`vlog_refactor::rename` exactly as before (no new rename). Repro fixed:
|
||||
`rename {"name":"StIdle","new_name":"StRest","file":"rtl/fsm.sv"}` →
|
||||
`renamed 2 sites in 1 file`. Opentitan: `find clk_i` + `find StIdle` +
|
||||
a miss, with the index build, 3.1 s; census timings unchanged (`find aes
|
||||
refs` 8.4 s, `aes.entropy_masking_req` 1.9 s).
|
||||
- **Finding 2 (near matches).** `similar` reads the same table with a part
|
||||
of a name (`Wanted::Containing`). `qa_m2` near-match expectation updated
|
||||
(`similar: sig, sig2` — `sig2` is a module internal `find` lists).
|
||||
- **Finding 4 (peek blank line).** A blank line of a peeked statement is
|
||||
an empty line — no indent; every other line exact. QA's pinned test
|
||||
asserted *no* empty line at all, which contradicts the ruling; its
|
||||
assertion now forbids whitespace-only lines and checks the empty one
|
||||
(the test name already said "whitespace-only").
|
||||
- **Finding 3 (root-relative files).** `WholeSet::rooted` rewrites a base
|
||||
file name in an engine sentence to the root-relative path when exactly
|
||||
one file of the set has it; applied to `rename`, `port` (engine and
|
||||
`place::after` refusals), the engine warnings of both, and `find`'s
|
||||
`uses not listed`. Test `wire.rs::engine_sentences_name_files_root_relative`
|
||||
(and a unit test of the whole-word replacement). The MCP-built lines were
|
||||
root-relative already.
|
||||
- Findings 5 and 6: no change (lead's ruling).
|
||||
- Catalogue unchanged: 3 440 bytes; instructions 398.
|
||||
|
||||
### 2026-09-24 — dev (M7 rework 2)
|
||||
|
||||
- **R1:** `rename` of a `block`-kind declaration is refused with the
|
||||
lead's sentence before any engine runs; QA's pinned test un-ignored, its
|
||||
assertion now requires the refusal and an untouched source. Topo §2.9
|
||||
row 43 (MCP-14) and a Handshakes line added.
|
||||
- **R2:** accepted; the Assumptions sentence on escaped local names made
|
||||
exact; the pinned test stays ignored with its reason. **R3:** no change.
|
||||
- Catalogue 3 440 bytes, instructions 398 (unchanged).
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-24 — QA (M7)
|
||||
|
||||
**Verdict: PASS with findings.** Every attack in the TODO M7 QA box held;
|
||||
no corruption, no partial write, no invariant broken. Finding 1 is a
|
||||
capability regression against 0.57.0 the lead should rule on before the
|
||||
0.58.0 release.
|
||||
|
||||
**Gates.** `cargo fmt --all` clean; `cargo clippy --all-targets -p
|
||||
lucisv_mcp` clean; `tools/guard.sh -t 1500 -- cargo test -p lucisv_mcp`
|
||||
**356 passed**, 6 ignored (3 opentitan, 3 QA findings pinned below) —
|
||||
the dev's 347 + 9 new in `tests/qa_m7.rs`.
|
||||
|
||||
**What was verified, and how.**
|
||||
|
||||
1. *Byte budget.* `wire.rs::tools_list_is_the_nine_tools_in_order_within_the_byte_budget`
|
||||
measures `serde_json::to_string` of `{name, description, inputSchema}`
|
||||
for all nine; an external measure (Python, compact, UTF-8) gives the same
|
||||
3 440. Mutation: `format`'s description +57 bytes (3 497) passes, +76
|
||||
(3 516) fails at `wire.rs:211` "the model-visible catalogue is 3516
|
||||
bytes"; reverted, `cmp` identical. Instructions 398 bytes, also pinned in
|
||||
`rpc.rs::the_instructions_stay_under_400_bytes`.
|
||||
2. *Caps* (400 instances, 350 ports + 320 nets, 320 declarations of `sig`):
|
||||
`hierarchy` down (`… and 101 more`), up (100), down+peek (whole blocks,
|
||||
251), no root (23), `find` (20), `outline unit` (51) and `file` (371),
|
||||
`check` (200 lines, 120 more) — each exactly one cut line, counts right,
|
||||
every line before it whole. On the eval clone `hierarchy prim_fifo_sync
|
||||
up depth 20` says `… and 22588 more` = the old tool's 22 888 − 300.
|
||||
3. *Ambiguity*: `read`/`rename` of a name in two files refuse listing both
|
||||
`file:line` and what picks one; `unit.name` picks without `file`;
|
||||
unknown `find`/`hierarchy root` list contains-matches (but see finding 2).
|
||||
4. *peek*: a statement with `#(…)` over two lines, `//` and `/* */`
|
||||
comments holding `;`, a tab-indented `.*` line, a two-instance statement
|
||||
and a 16-line statement: exact text (common indent removed), the 12-line
|
||||
cut ends `…`, exactly 12 lines is not cut.
|
||||
5. *port*: `after` a non-existent port, both / neither of add/remove,
|
||||
`after` with `remove`, `remove` of a port the body uses, an unknown
|
||||
module — all refused, tree byte-identical. `add` on a module instantiated
|
||||
3× in 2 files (named, `.name` shorthand, `.*`) connected each (`.*` gets
|
||||
its warning); with a positional instantiation in a third file the whole
|
||||
edit is refused and nothing is written.
|
||||
6. *edit_item*: delete of a used signal and a called function refused with
|
||||
`file:line:col` sites; `replace` that changes the name refused pointing
|
||||
at `rename`; `insert_after end@n` lands before `endmodule` of `n`;
|
||||
`end@nope` refused. `tests/attacks.rs` diffed against HEAD: 23 tests,
|
||||
62 → 63 `refused(` (the three forced deletes became refusals), 24 → 22
|
||||
`accepted(` (the two forced ones); the `lean` translator only renames
|
||||
tools/arguments; the one dropped case is `rename: true` (argument gone).
|
||||
`verify.rs` diff only removes the forced relaxation. `qa_m4.rs`: 45
|
||||
tests kept, the removed assertions are dry-run diffs and forced deletes.
|
||||
7. *format*: a glob matching nothing refused (`nothing written`); one
|
||||
unparsable file among four: the other three written, one `not
|
||||
formatted: rtl/bad.sv (…)` line, the bad file untouched; the refused file
|
||||
alone is a refusal. A non-UTF-8 file is not indexed, so a glob skips it.
|
||||
8. *Differential against the r4 binary on the eval clone*:
|
||||
`hierarchy top_earlgrey depth 2` — 49 instances, same tree (the old
|
||||
one had no sites; all 49 new `file:line` checked to spell the instance);
|
||||
`hierarchy prim_fifo_sync up` — first 300 identical, same total;
|
||||
`check` vs `diagnostics` on `earlgrey_pd_main.sv` (10 findings),
|
||||
`uart.sv`, `prim_fifo_sync.sv`, `i2c_fifos.sv`, `uart_core.sv`,
|
||||
`aes_core.sv`, `cheriot_tag_filter.sv` — identical line sets; whole design
|
||||
2 101 both; `find prim_fifo_sync refs` vs `references` — 78 uses = the
|
||||
old 79 hits minus the declaration itself, `unresolved:` 29 sites = the
|
||||
old 29. The clone's `git status` was clean after every run.
|
||||
9. *Answer shape*: every read tool over the six fixtures plus the attack
|
||||
trees — no absolute path, no hint line, no trailing whitespace, no blank
|
||||
line except finding 4; refusals are one sentence.
|
||||
10. *Invariants*: freshness (`qa_m1`, `wire`), roots (`wire`, `qa_m1`,
|
||||
`qa_m3`), cache read-only (`cache`, `qa_m6`), all-or-nothing
|
||||
(`apply.rs` units, `qa_m3`) all pass. Manual: `rename sub` over three
|
||||
files with `rtl/p2.sv` chmod 444 → `` `rtl/p2.sv` is read-only; nothing
|
||||
written.`` and `p1.sv` (written first in path order) untouched; pinned
|
||||
as `qa_a_rename_whose_later_file_is_read_only_writes_nothing`.
|
||||
|
||||
**Findings** (pinned ones are `#[ignore = "QA finding N"]` in
|
||||
`tests/qa_m7.rs`, asserting the correct behaviour):
|
||||
|
||||
1. **Medium — name lookup cannot reach module-local declarations other
|
||||
than ports, parameters, nets, variables and top-level instances.**
|
||||
`names.rs:88` `defs_named` reads units, exported members and
|
||||
`hierarchical_declarations`; a module's `typedef`, enum values,
|
||||
functions, tasks, genvars, generate blocks and everything inside them,
|
||||
and procedural locals are in none. `outline` lists them and `read` with
|
||||
`file` slices them, but `find`, `read` without `file` and **`rename`**
|
||||
answer `no declaration named X` — with `file` too. 0.57.0 renamed them
|
||||
by position (checked: the r4 binary renames `StIdle` via
|
||||
`file/line/col`), so an FSM state rename is no longer possible through
|
||||
MCP. Repro: `rtl/fsm.sv` = `module fsm; typedef enum logic [1:0]
|
||||
{StIdle, StBusy} state_e; …` then `rename {"name":"StIdle",
|
||||
"new_name":"StRest","file":"rtl/fsm.sv"}` → refused. Pinned:
|
||||
`qa_find_and_rename_reach_every_declaration_outline_lists`. A likely
|
||||
remedy: with `file`, fall back to the file's own semantics (as `read`'s
|
||||
slicer does) for the offset handed to `vlog_refactor::rename`.
|
||||
2. **Low — near matches omit module internals.** `names.rs:165`
|
||||
`similar` reads `workspace_symbols` (units and exported members) and the
|
||||
define tables, not the module internals `find` lists. Repro: `logic mid;`
|
||||
in a module, `find {"name":"mi"}` → `no declaration named `mi`.` with no
|
||||
`similar`; on the eval clone `find rx_fifo_rvali` suggests only
|
||||
`rx_fifo_rvalid_o` although `find rx_fifo_rvalid` lists 3 declarations.
|
||||
Pinned: `qa_find_near_matches_include_the_module_internals_find_lists`.
|
||||
3. **Low — engine sentences name files by basename, not root-relative
|
||||
(§10.2).** `port` refusals `would not leave p3.sv with the signature…`,
|
||||
`still used inside `sub` at sub.sv:6`; `port` warnings `at `u_s`
|
||||
(p1.sv:2)`; `rename` refusal `` `u_b` at top.sv:16 connects with `.*` ``.
|
||||
The sentences come from `vlog_refactor` unchanged (so 0.57.0 said the
|
||||
same); ambiguous when two directories share a basename. Not pinned.
|
||||
4. **Low — `peek` answers a whitespace-only line** for a blank line inside
|
||||
an instantiation statement (`hierarchy.rs:284` indents every source line,
|
||||
`statement` at `hierarchy.rs:328` keeps blank ones): `" "` in the
|
||||
answer, against §10.2 "no blank lines". Exactness vs the rule is the
|
||||
lead's call. Pinned: `qa_peek_never_answers_a_whitespace_only_line`.
|
||||
5. **Cosmetic — four descriptions are two sentences** (`hierarchy`,
|
||||
`read`, `rename`, `format`) where §10.1 says "the one-sentence tool
|
||||
description". Not pinned; merging them costs no bytes.
|
||||
6. *Info* — `port add` then `port remove` of the same port is refused when
|
||||
the add left `/* TODO: connect */` (comments are never dropped), so the
|
||||
pair is not an undo. Safe; engine behaviour, noted for the agent guide.
|
||||
|
||||
**Fixed directly:** nothing in production code.
|
||||
|
||||
**Tests added** (`crates/lucisv_mcp/tests/qa_m7.rs`, 9 + 3 ignored):
|
||||
caps with counts, peek exactness and the 12-line cut, ambiguity and
|
||||
unknown-name refusals, `port` shapes and all-or-nothing across files,
|
||||
`edit_item` delete/replace/`end@UNIT`, `format` partial and empty glob,
|
||||
read-only all-or-nothing, answer shape, `find refs` five-declaration line.
|
||||
|
||||
### 2026-09-24 — QA re-check (M7 rework)
|
||||
|
||||
**Verdict: PASS with findings.** Findings 1–4 are fixed and their pinned
|
||||
tests pass un-ignored. The rework opens a gap that was already in the
|
||||
engine but is now reachable by name with no dry run (R1). Gates: fmt and
|
||||
clippy clean; `tools/guard.sh -t 1500 -- cargo test -p lucisv_mcp`
|
||||
**365 passed**, 5 ignored (3 opentitan, R1, R2).
|
||||
|
||||
- *(a) Declarations local to a module* — typedef, enum value, function,
|
||||
function-local, task, genvar, generate block, generate-local and
|
||||
procedural local: `find` and `find unit.name` answer each; `rename` by
|
||||
name, with `file` and with `fsm.name` rewrites every use and leaves no
|
||||
old name behind, except for the generate label (R1). `read hl` / `read
|
||||
tmp` / `read gi` return only the name's bytes — 0.57.0's `read_item` did
|
||||
the same (the slicer never changed), so this is noted, not a finding.
|
||||
- *(b)* `rtl/x/p1.sv` and `rtl/y/p1.sv` both declare `dup`: `rename`
|
||||
without `file` lists both root-relative paths, and with `file` renames
|
||||
only the right file. Engine sentences keep the bare `p1.sv` (two files
|
||||
have that name) and rewrite `p1b.sv` to `rtl/z/p1b.sv:3`. No
|
||||
sub-string damage.
|
||||
- *(c)* A package enum value used in `case` arms in two files, plain and
|
||||
`pkg::`: `find refs` lists `rtl/a.sv:7,11` and `rtl/b.sv:6`; `rename`
|
||||
answers `renamed 4 sites in 3 files` and lists the comment and string
|
||||
mentions as `unresolved:`.
|
||||
- *(d)* A name that appears only in a comment or string gets `no declaration
|
||||
named` with no similar names; `StRu` suggests `StRun`.
|
||||
- *(e)* The escaped net `\my.sig` is still found, with its uses and
|
||||
renamed across a hierarchical reference. See R2 for escaped locals.
|
||||
- *(f)* The eval clone has no `StIdle` in `entropy_src_main_sm` (its state is
|
||||
`Idle`, from a package). `find StIdle` lists 35 enum values (1.96 s).
|
||||
`rename StIdle file ip/hmac/rtl/hmac_core.sv` gives `renamed 7 sites in
|
||||
1 file`; all 7 spellings changed, no other file was touched, and it took
|
||||
13.8 s. The 20 warnings about macro arguments belong to *other* modules'
|
||||
`StIdle` and match what 0.57.0 printed for a position-based rename.
|
||||
Restored with `git checkout`; the clone's status is clean.
|
||||
- *(g)* The only `tests/` files changed since the first QA run are
|
||||
`qa_m7.rs`, `qa_m2.rs` and `wire.rs`. `qa_m7.rs`: every assertion is
|
||||
intact except the three un-ignores and the finding-4 assertion (the
|
||||
ruling's reading). `qa_m2.rs`: the `similar: sig, sig2.` expectation.
|
||||
`wire.rs`: one new test, `engine_sentences_name_files_root_relative`
|
||||
(test count 40 → 41).
|
||||
- *(h) Timing on the eval clone* (release build; `hierarchy {}` takes
|
||||
2.03 s, which is the startup): `find clk_i` (a hit) 2.62 s; misses
|
||||
`clk_x` 1.84 s, `rst_` 2.87 s (about 2 131 files hold a word containing
|
||||
it, and `similar` in `declared.rs` parses them all), `zzzz` 1.86 s, `q_`
|
||||
2.93 s (about 1 693 files); a hit on the common `dat` takes 1.83 s. Every
|
||||
miss is well under 10 s, so there is no finding here.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- **R1 — Medium (code-breaking rename, no warning).** Renaming a
|
||||
generate block label leaves a hierarchical path through the block
|
||||
unchanged. `rename {"name":"g_lane","new_name":"g_ln"}` on
|
||||
`for (…) begin : g_lane … end` plus `busy = tmp | g_lane[0].lane_q;`
|
||||
answers `renamed 1 site in 1 file`. Line 19 still says `g_lane[0]`,
|
||||
which is now undeclared. The answer has no warning and no `unresolved:`
|
||||
line, and `find g_lane refs` lists no uses. Yet `edit_item delete
|
||||
g_lane` refuses, citing `rtl/fsm.sv:19:18`. The engine
|
||||
(`vlog_refactor::rename`) did the same by position in 0.57.0, but
|
||||
`declared.rs` now makes generate labels reachable by name, and the
|
||||
instructions say to trust edits. Remedy for the lead to rule on: refuse
|
||||
a `block`-kind rename, or have the engine warn the way it does for
|
||||
`lane_q`'s tail. Pinned:
|
||||
`qa_rework_renaming_a_generate_label_never_leaves_a_path_through_it_behind`.
|
||||
- **R2 — Low.** Escaped local names are not found. `declared.rs:35`
|
||||
(`in_census`) checks the word census, which holds identifier-shaped
|
||||
words only, so a file is never opened for `\loc.v` (a function-local)
|
||||
or an escaped enum value. The dev records this as an assumption (under find: escaped names are found "through the index only"), so it is known, but `outline` lists them, but `find`, `rename`
|
||||
and `read` without `file` answer `no declaration`. Pinned:
|
||||
`qa_rework_an_escaped_local_outline_lists_is_found`.
|
||||
- **R3 — Cosmetic.** `find e.\my.sig` is refused because `qualified`
|
||||
(`names.rs:44`) splits on the `.` inside the escaped member. `find my`
|
||||
does not suggest `\my.sig`. Not pinned.
|
||||
|
||||
**Tests added** (`tests/qa_m7.rs`, 4 + 2 ignored):
|
||||
`qa_rework_every_local_kind_is_found_and_renamed_by_name_file_and_unit`,
|
||||
`qa_rework_a_shared_base_name_is_named_by_path_or_left_alone`,
|
||||
`qa_rework_an_enum_value_in_case_arms_is_renamed_across_files_with_its_mentions`,
|
||||
`qa_rework_an_escaped_net_is_still_found_through_the_index`; R1 and R2
|
||||
pinned.
|
||||
|
||||
## Review
|
||||
|
||||
2026-09-24 (lead). Examined the diff (51 files, +2 649/−7 620), the
|
||||
registry, `declared.rs`/`names.rs`, the QA logs and the live answers on
|
||||
the fixture design and the eval clone. Accepted. The catalogue is
|
||||
3 440 bytes for nine tools (was 17.9 kB for 26), instructions 398 bytes,
|
||||
answers one line per fact with fixed caps. Rulings: MCP-12 — the shipped
|
||||
398-byte instructions stand, PLAN §10.3 is amended to them; finding 4 — a
|
||||
blank line inside a peeked statement is an empty line; R1 — `rename` of a
|
||||
`block`-kind declaration is refused in the MCP layer and the engine gap is
|
||||
filed as topo §2.9 row 43 (MCP-14) for the LSP/CLI; R2 accepted as an
|
||||
assumption; MCP-13 fixed by the lead (release script comments,
|
||||
RELEASING.md, manual-acceptance rows 19/24). Deviations from §10 accepted:
|
||||
qualified `unit.name`/`pkg::name`, the 5-declaration cap on `find refs`
|
||||
(MCP-11 filed), per-file `format` refusals, the root line on `hierarchy`
|
||||
down. Gates at commit: lucisv_mcp 366 passed / 4 ignored, workspace 4 922
|
||||
passed / 0 failed. Census round 4 follows on this binary.
|
||||
@@ -25,12 +25,12 @@ hour. Record the release, the date and any failure in the table at the end.
|
||||
| 16 | Star `aes`, then `hmac`. | Five sections in that order; "Other modules" has 297 roots; each section opens and closes on its own; a module under both keeps its own open state in each. Title bar "Clear DUTs" removes both. |
|
||||
| 17 | Add `"lucisv.hierarchy.duts": ["aes"]` to the workspace `.vscode/settings.json`. | The section appears without starring; right-clicking `aes` offers only a greyed "DUT from settings" whose tooltip names the setting; "Clear DUTs" leaves it. Remove the setting again. |
|
||||
| 18 | MCP (VS Code 1.101+, platform `.vsix` in a clean profile: `code --profile lucisv-mcp-qa --install-extension lucisv-<v>-darwin-arm64.vsix`, opentitan open). Command palette → **MCP: List Servers**. | `lucisv (opentitan)` listed under the `lucisv` provider without opening a Verilog file first (the contribution point activates the extension); no error toast. |
|
||||
| 19 | Start it from that list; accept VS Code's trust prompt. In Chat (agent mode) ask: "call lucisv's project_overview". | One trust prompt; the tool call answers with `roots: …/opentitan`, the file and unit counts; the server's MCP output log shows `lucisv-mcp: indexed N files` and no error. |
|
||||
| 19 | Start it from that list; accept VS Code's trust prompt. In Chat (agent mode) ask: "call lucisv's hierarchy with no arguments". | One trust prompt; the tool call answers with the file/module counts line and the top modules as `name file:line`; the server's MCP output log shows `lucisv-mcp: indexed N files` and no error. |
|
||||
| 20 | Settings → `lucisv.mcp.enabled` off, then on again (no reload). | The server leaves **MCP: List Servers** when off and returns when on; Output → lucisv logged nothing new except, on the next activation with it off, one "lucisv.mcp.enabled is false" line. |
|
||||
| 21 | File → Add Folder to Workspace… (a second folder); then remove it. | Two servers, `lucisv (opentitan)` and `lucisv (<second>)`, appear without a reload; removing the folder leaves one. |
|
||||
| 22 | `lucisv.mcp.path` set to `/nowhere/lucisv-mcp`; start the server from the list. Reset the setting. | Not started; Output → lucisv: `cannot start the MCP server: "/nowhere/lucisv-mcp" not found …`; record whether VS Code itself adds a toast (acceptable if it is only VS Code's own "did not start" notice, not an extension error dialog). |
|
||||
| 23 | Universal `lucisv-<v>.vsix` with no `lucisv-mcp` on PATH; start the server. | Same as 22 with `"lucisv-mcp" not found`; the language server (steps 1–5) unaffected. |
|
||||
| 24 | **lucisv: Copy MCP server config** → Claude Code; paste into `.mcp.json` of a scratch copy of a project; in a terminal there run `claude`, `/mcp`. Repeat for VS Code → `.vscode/mcp.json` in another window. | The info message names `.mcp.json` and warns the bundled path moves on update; Claude Code lists `lucisv` connected and answers `project_overview`; the `.vscode/mcp.json` server (`"type": "stdio"`) starts too. |
|
||||
| 24 | **lucisv: Copy MCP server config** → Claude Code; paste into `.mcp.json` of a scratch copy of a project; in a terminal there run `claude`, `/mcp`. Repeat for VS Code → `.vscode/mcp.json` in another window. | The info message names `.mcp.json` and warns the bundled path moves on update; Claude Code lists `lucisv` connected and answers `hierarchy` (no arguments); the `.vscode/mcp.json` server (`"type": "stdio"`) starts too. |
|
||||
| 25 | Optional, if a VS Code older than 1.101 is at hand: install the platform `.vsix` there. | Extension activates normally; Output → lucisv has one "no MCP server API (needs 1.101+)" line; the copy-config command still works. |
|
||||
|
||||
## Runs
|
||||
|
||||
+11
-8
@@ -247,6 +247,8 @@ newlines, stdout is protocol-only, stderr is human-only.
|
||||
|
||||
### 4.3 The tools
|
||||
|
||||
> **Superseded by §10 (the lean catalogue, 0.58).** Kept as the record of the 0.57 surface.
|
||||
|
||||
Inputs name things the way an agent already has them: a **file path**
|
||||
(absolute or root-relative), a **unit name**, a **line** (1-based) and
|
||||
optional **column**, or a **symbol name** with an optional **unit**. Outputs
|
||||
@@ -342,6 +344,8 @@ records MCP's own).
|
||||
|
||||
### 4.5 Rendering rules (the token budget is the product)
|
||||
|
||||
> **Superseded by §10.2.** Kept as the record of the 0.57 rules.
|
||||
|
||||
- Paths root-relative; a file named once per group, never per line.
|
||||
- Line numbers 1-based, columns 1-based, in `file:line:col` form.
|
||||
- Lists capped (`limit`, default 500 since feedback-2) with `… and N more` — the agent can
|
||||
@@ -532,15 +536,14 @@ 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)
|
||||
### 10.3 Instructions (≤ 400 bytes; the shipped text, 398 bytes)
|
||||
|
||||
> lucisv-mcp answers from the SystemVerilog sources on disk (save first).
|
||||
> Use it before reading files: hierarchy for the instance tree and top
|
||||
> modules, find for where a name is declared and used, outline for a file
|
||||
> or a unit's ports, read for one item's source, check after edits. Edits
|
||||
> (rename, port, edit_item, format) are verified, all-or-nothing writes to
|
||||
> disk: call them like a file write, no dry run. Paths are root-relative,
|
||||
> lines 1-based.
|
||||
> 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.
|
||||
|
||||
### 10.4 What stays
|
||||
|
||||
|
||||
@@ -5,11 +5,13 @@ description: Give Claude Code, Cursor and VS Code's agent mode lucisv's parser,
|
||||
|
||||
`lucisv-mcp` is lucisv as a [Model Context Protocol](https://modelcontextprotocol.io)
|
||||
server. A coding agent spawns it over stdio and asks it about the
|
||||
Verilog/SystemVerilog tree instead of reading whole files: a module's ports,
|
||||
a file's outline, one `always` block, who instantiates what, every reference
|
||||
to a signal. It can also make the edits lucisv already knows how to make
|
||||
safely — format, lint fixes, rename, the port refactorings and single-item
|
||||
replacements — each one verified before anything is written.
|
||||
Verilog/SystemVerilog tree instead of reading whole files: the instance
|
||||
hierarchy and where each instance is written, where a name is declared and
|
||||
used, a module's ports, a file's outline, one `always` block. It can also
|
||||
make the edits a plain file write cannot make safely — a rename across the
|
||||
design, adding or removing a port in every instantiation, a single-item
|
||||
edit, formatting with the safe lint fixes — each one verified before
|
||||
anything is written.
|
||||
|
||||
It is the same engine as the CLI and the language server (parser, index,
|
||||
formatter, linter, refactorings), in a third binary that shares no state with
|
||||
@@ -97,48 +99,38 @@ description. The agent sees the full description and input schema.
|
||||
|
||||
| tool | writes | what it answers |
|
||||
|---|---|---|
|
||||
| `project_overview` | | Files, units by kind, top modules, largest files. |
|
||||
| `list_units` | | Units (modules, interfaces, packages, classes, programs) with file:line. |
|
||||
| `unit_interface` | | A unit's parameters, ports (direction, type, range), modports or members; `template: true` adds an instantiation. |
|
||||
| `outline` | | A file's declarations as a tree with line ranges, and its parse errors. |
|
||||
| `read_item` | | One item's exact source and lines. |
|
||||
| `search_symbols` | | Declarations whose name contains `query` (any case), members included. |
|
||||
| `defines` | | The \`define table (name, parameters, body, file:line) of a `file`, a macro `name`, or all. |
|
||||
| `definition` | | Where a name or macro is declared: file:line:col, kind, line. |
|
||||
| `references` | | Uses of one declaration, then its unresolved mentions (strings, comments, macro text). |
|
||||
| `hierarchy` | | Who instantiates a module (`up`, with file:line) or what it instantiates (`down`, default). |
|
||||
| `diagnostics` | | Parse errors and lint findings (`line:col severity message [rule]`) of `file` or all. |
|
||||
| `format` | yes | Format `file`/`files` as `lucisv format`; `lines` limits it. |
|
||||
| `fix_lint` | yes | Apply the safe lint fixes to `file`/`files`; says what remains. |
|
||||
| `rename` | yes | Rename a declaration and its uses; select as `definition`. |
|
||||
| `expand_wildcard` | yes | Replace one instance's `.*` with the named connections it binds. |
|
||||
| `convert_ports` | yes | Rewrite a module's non-ANSI header as an ANSI port list. |
|
||||
| `organize_imports` | yes | Remove unused `import`s in the scope at a position; sort the rest. |
|
||||
| `inline_module` | yes | Replace one instance with its module's body, connections substituted. |
|
||||
| `propagate_ports` | yes | Connect by name every port one instance leaves unconnected. |
|
||||
| `remove_port` | yes | Delete a port and its connection in every instantiation; refused while the body uses it. |
|
||||
| `add_port` | yes | Add an ANSI port to a module, connected in every instantiation; `after` positions it. |
|
||||
| `extract_module` | yes | Move whole items in lines `start_line`..`end_line` to a new module instantiated in their place. |
|
||||
| `replace_item` | yes | Replace one item with `text`: one item, same kind and names (unless `rename`; references untouched). |
|
||||
| `insert_item` | yes | Insert items `text` before or after item `anchor`, or at `end` (`end@NAME`) of the last unit (unit NAME). |
|
||||
| `delete_item` | yes | Delete one item and its leading comments; refused while its names are used (sites listed) or it holds a \`define, unless `force`. |
|
||||
| `instantiate` | | Instantiation text for module `name`: parameters, instance name, named or `.*` ports. |
|
||||
| `hierarchy` | | The instance tree of `root` to `depth` (1-20, default 1), each at its instantiation file:line; `up`: its instantiations; `peek`: each statement's source. |
|
||||
| `find` | | Every declaration of `name` or unit.name (kind name file:line; macros too); `refs: true` adds each one's uses as file:line and the unresolved mentions (strings, comments, macro text). |
|
||||
| `outline` | | Exactly one of: `file`, its declarations as a tree with line ranges, parse errors first; `unit`, its file:line, parameters and ports in order (modports, package members). |
|
||||
| `read` | | One item's exact source after its file:first–last line. |
|
||||
| `check` | | 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. |
|
||||
| `rename` | yes | Rename declaration `name` (or unit.name) to `new_name` with every resolved use (.name/.* written out); `file` and name@LINE pick among declarations. |
|
||||
| `port` | yes | On `module`, `add` an ANSI port declaration (after port `after`, else last) connected in every instantiation, or `remove` a port and its connections (refused while used). |
|
||||
| `edit_item` | yes | One item of `file` (selector as read): `op` replace it by `text` (same kind and names), insert `text` before/after it (item `end`/`end@UNIT`: a unit's end), or delete it if unused. |
|
||||
| `format` | yes | Format `files` (a path, directory or glob like `rtl/**/*.sv`) as lucisv format; `fix: true` applies safe lint fixes first. |
|
||||
|
||||
## What it promises
|
||||
|
||||
- **Answers come from the disk.** Every call first re-checks the files it
|
||||
indexes, so no answer is older than the disk at the moment the call
|
||||
arrived. Unsaved editor buffers are invisible to it — save before asking.
|
||||
- **Edits are verified, then written whole.** Every edit tool computes and
|
||||
verifies every file's new text before the first write; a refusal names the
|
||||
reason and touches nothing. The formatter's own safety net applies to
|
||||
`format`; `replace_item`, `insert_item` and `delete_item` require the file to
|
||||
still parse and change no byte outside the item.
|
||||
- **`dry_run: true`** on any edit tool returns the unified diff instead of
|
||||
writing.
|
||||
- **Answers are short.** One line per fact, root-relative `file:line`, no
|
||||
headers; a long answer is cut at a fixed cap with one `… and N more` line,
|
||||
and a better question (`root`, `file`, `depth`, `unit.name`) narrows it.
|
||||
A refusal is one sentence, and when a name is unknown it lists the near
|
||||
matches.
|
||||
- **Edits are verified, then written whole — there is no dry run.** Every
|
||||
edit tool computes and verifies every file's new text before the first
|
||||
write, and writes all of it or none of it; call it like a file write and
|
||||
trust the answer (`check` afterwards, when you want the lint verdict). A
|
||||
refusal names the reason and touches nothing. The formatter's own safety
|
||||
net applies to `format` (a file it refuses is named and left as it was);
|
||||
`edit_item` requires the file to still parse and changes no byte outside
|
||||
the item; `rename` and `port` list the name's unresolved mentions
|
||||
(strings, comments, macro text) for you to check.
|
||||
- **Nothing outside the roots.** Every path a tool takes must resolve inside a
|
||||
`--root`; anything else is refused.
|
||||
- **The language server's cache is never written.** `--index-cache` names
|
||||
the directory the extension gives `lucisv-server`; `lucisv-mcp` accepts it
|
||||
today and will read that store (read-only) for a warm start in a later
|
||||
release — never write it, so there are never two writers.
|
||||
the directory the extension gives `lucisv-server`; `lucisv-mcp` reads that
|
||||
store for a warm start and writes only its own, `index-cache-mcp`, beside
|
||||
it — never two writers of one file.
|
||||
+4
-3
@@ -153,7 +153,7 @@ what a change on the pointed-to side must not silently break.
|
||||
| `lucisv_server ◀──▶ vlog_refactor` | handshake | Request-scope selectors added for the performance wave: `prepare_rename_here` must produce the same answer/refusal text as whole-scope `prepare_rename`; `rename_name_at` must name the target that the rename engine acts on; `port_action_modules` and `enclosing_module` must name every module the corresponding port action/command can edit. The server uses those names to choose an index-derived file set; `extract_site`, `inline_site` and `imported_packages` also name source requirements. **`rename_preflight(semantics, offset, new_name)` (perf5r-preflight, 2026-09-08)** owes whole-scope `rename` the same *refusal* text one-directionally — it may always stand aside with `Ok(())` and never invents a refusal — and deliberately reads no workspace index (unlike `prepare_rename_here`): only refusals that are a pure function of the request buffer's own text (the new-name check, no symbol here, an unresolved or inherited-candidate reference, an unspelled declaration, the same name at a non-file-scope declaration); every index-answered refusal stays on the slow road. The engine remains the authority, and every selector must supply a superset of files needed for edits and refusals (inline gap: §2.9-33). |
|
||||
| `lucisv_server ──▶ vlog_formatter` | depends | `format_source`, `format_range`/`LineRanges` (range, ranges, on-type formatting), `Config`, `fence::protected_regions` (quick-fix filter). |
|
||||
| `lucisv_server ──▶ vlog_linter` | depends | `run`, `lint` + `LintContext::from_parse` (lints from the `Document`'s own parse — one-parse), `default_rules`, `apply_fixes`, `rule_by_name`. Same three promises the CLI relies on. |
|
||||
| `lucisv_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic`/`diff::unified` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); every refactoring entry point + `find_references` + `instantiation_plan` (refactor); `format_source`/`format_range`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. |
|
||||
| `lucisv_mcp ──▶ lucisv_core, vlog_parser, vlog_semantic, vlog_refactor, vlog_formatter, vlog_linter` | depends | The MCP block (2026-09-23, `docs/mcp/PLAN.md`, `TODO-MCP.md`): `lucisv-mcp` composes the six libraries through their public APIs only — `Discovery`/`filelist`/`walk`/`content_hash`/`write_atomic` (core); `tokenize`, `parse_tolerant`, `parse_source` (strict, the structural edits' rule 1), `LineIndex`, `defines`, the AST (`Item`/`ItemKind`, `Meta::leading`, `Connections`), `PARSE_STACK_SIZE` (parser); `analyze`, `IndexBuilder::{add_file, add_facts}`, `WorkspaceIndex::{absorb, fingerprint, units, members_of, member_in, instantiations, workspace_symbols, find_define, files_mentioning, …}`, `resolve_external`, `FileFacts::{of, decode}`, `FACTS_FORMAT` (semantic); `rename`, `add_port`, `remove_port`, `find_references`, `instantiation_plan`, `module_definition`, `enclosing_module` (refactor); `format_source`/`fence` (formatter); `LintContext::from_parse`, `lint_with`, `select_rules`, `apply_fixes`, `rules_markdown`, `MentionOracle` (linter). **Never `lucisv_server`** (bin-only) and never `lsp-types`. Feature READMEs `docs/features/mcp-*`. **M7 (2026-09-23, the lean catalogue):** nine tools; `diff::unified`, `format_range` and the cursor refactorings (`expand_wildcard`, `convert_to_ansi`, `organize_imports`, `inline_module`, `propagate_ports`, `extract_module`) are no longer called — they stay in the CLI and the server. |
|
||||
| `lucisv_server ──▶ lsp-server / lsp-types` | depends | The transport (synchronous, no async runtime) and the protocol data model. Both pinned exactly. cancel-request additionally relies on `lsp-server 0.10.0`'s stdio transport being a **rendezvous channel** (its own forwarder queue exists because of it) — a version bump must re-read that crate's `stdio.rs`. |
|
||||
| `editors/vscode ◀──▶ lucisv_server` | handshake | The **spawn contract**: binary named `lucisv-server`, no env, LSP over stdio, `initialize` works with no roots (single-file mode). The extension passes exactly `[]` by default or `['--verbose']` when `lucisv.verbose` is true; the server accepts only that spelling (repeats are idempotent) and refuses any other argument with exit 2. Changing that setting restarts the server because it is a process argument, not an LSP setting. Wire shapes pinned on both sides: the custom `lucisv/scopePairs` result, the other `lucisv.*` settings section (push and pull), `initializationOptions.storagePath`, the markdown fence tag `systemverilog` (server emits it, extension's grammar registers it), the `bin/` layouts of the platform `.vsix` packages. `smoke.js` still drives the default no-argument contract headlessly; `tests/e2e.rs` pins both spawns and `tests/grammar.rs` pins the grammar. |
|
||||
| `editors/vscode ◀──▶ vlog_parser` | handshake | The TextMate grammar's keyword alternation is **hand-maintained and test-locked to `vlog_parser::KEYWORDS`**: `crates/lucisv_server/tests/grammar.rs` fails, naming the missing/extra words, when they diverge (there is no generator script). Adding a keyword to `token.rs`'s `keywords!` macro is therefore also a hand edit to `editors/vscode/syntaxes/systemverilog.tmLanguage.json`. |
|
||||
@@ -659,7 +659,7 @@ engine-lane features are listed above; this table is the server-internal web.
|
||||
| `ci-release ──▶ release-prep / editor-platform-vsix` | depends | Workflow = one-liners over `tools/`; consumes the exact seven `.vsix` names (`prune_release_assets.sh` checks each), the `CHANGELOG.md` heading convention, tag == workspace version. |
|
||||
| `release-prep ──▶ editor-packaging` | depends | `release.sh` runs `smoke.js` as its gate; closed the missing-`LICENSE` item editor-packaging filed. Version lives in exactly four files — a promise to everyone. |
|
||||
| `editor-marketplace-page ──▶ lucisv-server` (docs) | depends | The Details page mirrors the shipped capability table in the server's README; drifts if that table does. |
|
||||
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-packaging) | handshake | The MCP spawn contract (2026-09-23): the binary `lucisv-mcp[.exe]` found by the same three-rung ladder as the server (`lucisv.mcp.path` → `bin/` → `PATH`), spawned by VS Code from `McpStdioServerDefinition(label, command, ["--root", folder, "--index-cache", storage], env, version)` — the constructor is positional — one per workspace folder; `serverInfo.name == "lucisv-mcp"`, ≥ 26 tools (`mcp_smoke.js` `MIN_TOOLS`). Provider id `lucisv.mcp`; settings `lucisv.mcp.enabled`/`.path`; command `lucisv.mcp.copyConfig`. |
|
||||
| `editor-packaging ◀──▶ lucisv-mcp` (mcp-packaging) | handshake | The MCP spawn contract (2026-09-23): the binary `lucisv-mcp[.exe]` found by the same three-rung ladder as the server (`lucisv.mcp.path` → `bin/` → `PATH`), spawned by VS Code from `McpStdioServerDefinition(label, command, ["--root", folder, "--index-cache", storage], env, version)` — the constructor is positional — one per workspace folder; `serverInfo.name == "lucisv-mcp"`, exactly the nine lean tools in order — `hierarchy, find, outline, read, check, rename, port, edit_item, format` (`mcp_smoke.js` `TOOLS`; **amended by M7, 2026-09-23**, was ≥ 26); `mcp_smoke.js --tool-table` regenerates the Agents guide's table. Provider id `lucisv.mcp`; settings `lucisv.mcp.enabled`/`.path`; command `lucisv.mcp.copyConfig`. |
|
||||
| `release-prep / editor-platform-vsix ──▶ lucisv-mcp` (mcp-packaging) | depends | `release.sh` builds `-p lucisv_mcp` for every triple and stages it as the THIRD `bin/` entry (fifteen in the `all` package); `expect_vsix_bins` and `audit_artifacts.sh` pin the name; the seven `.vsix` names are unchanged. `mcp_smoke.js` is the gate beside `smoke.js`. |
|
||||
| `lucisv-mcp ──▶ lucisv-server` (index cache, M6) | depends (read-only) | MCP reads the server's `index-cache` store read-only when `--index-cache DIR` names it (header `CACHE_FORMAT`/`FACTS_FORMAT`/version must match, else ignored) and writes its own `index-cache-mcp` beside it; it never writes the server's file. A codec change on the server side costs MCP its warm start, never its correctness. |
|
||||
|
||||
@@ -704,7 +704,7 @@ update the filing README(s) and this file.
|
||||
| 32 | **The refactoring verifier does not catch a same-file relocation of a never-dropped piece written as two well-formed edits** (delete here, insert there): `verify_move` computes `after` by applying the edits, so `positions_match`'s reconstruction cannot diverge from it and equation 3 of the ledger is unreachable through any real caller. No planner produces the shape today. Wanted: an independent `after` (the client's applied text, or a second reconstruction) and a test that isolates equation 3. Found by extract-module's QA re-attack. | extract-inline-module (QA) | vlog_refactor |
|
||||
| ~~33~~ | ~~**`module_sources`' fan-out has no rung for a file that reaches an instance through an intermediate module it does not itself instantiate** (a bench naming `wrap.u_S.x` where `wrap` instantiates `S`): inline-module's hierarchical-reference refusal sees only the handed files, so such a reference is missed. Wanted: a transitive-instantiators rung (§49's hierarchical surface knows the path) in `module_sources` for the refactorings that must see every hierarchical use. Found by §53.2's QA.~~ — **closed 2026-09-07 by perf5-p2 (TODO §60.2): a fifth, opt-in rung** `Workspace::module_sources_reaching(file, modules, Reach { scopes })` in `lucisv_server/src/module_select.rs` — every file whose *token census* (`WorkspaceIndex::files_mentioning`, i.e. `FileFacts::words`) writes the dissolved instance's name down. That is exactly the set `no_hierarchy` can refuse from, so the selected set answers the refusal as the whole workspace does (asserted engine-run-twice on six shapes; QA attacked seven more incl. `$root`, a macro-built `bind` path, an escaped identifier, a generate label). **The transitive-instantiator walk this row asked for was implemented and rejected:** a `bind tb.u_wrapper.u_top.u_sub …` in an SVA file that instantiates nothing in the chain has no instantiation edge for any walk to follow — structurally weaker, confirmed by QA. Only inline-module asks for the rung (extract and ports pass `Reach::none()`, unchanged in answer and cost); worst corpus cost 2 % of files on a command, +1.2 ms at the measured site. | extract-inline-module (QA) | lucisv_server / vlog_refactor |
|
||||
| ~~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 | mcp-navigation | vlog_parser |
|
||||
| 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 |
|
||||
| 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`) | mcp-edit-tools | vlog_refactor |
|
||||
@@ -712,6 +712,7 @@ update the filing README(s) and this file.
|
||||
| 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`) | mcp-structural-edits | vlog_refactor, vlog_semantic |
|
||||
| 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 | mcp-lean-catalogue | vlog_refactor, vlog_semantic |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -5,6 +5,17 @@ for you. The extension and its bundled language server share one version
|
||||
number; the full engineering notes live in the
|
||||
[project changelog](https://git.luci.ooo/lucio/lucisv/src/branch/master/CHANGELOG.md).
|
||||
|
||||
## Unreleased (0.58.0)
|
||||
|
||||
- `lucisv-mcp`, the agent server, now offers nine tools instead of 26 —
|
||||
`hierarchy`, `find`, `outline`, `read`, `check`, `rename`, `port`,
|
||||
`edit_item`, `format` — and the whole catalogue an agent reads each
|
||||
session is under 3.5 kB (it was 17.9 kB). Answers are one line per fact
|
||||
with fixed caps; there is no dry run and no paging: every edit is a
|
||||
verified, all-or-nothing write. An agent config that names an old tool
|
||||
(`references`, `unit_interface`, `replace_item`, …) needs the new name;
|
||||
the Agents guide has the table.
|
||||
|
||||
## 0.57.0 — 2026-09-23
|
||||
|
||||
- The platform packages (and the `all` package) now carry `lucisv-mcp`, the
|
||||
|
||||
@@ -185,11 +185,13 @@ enabling both paths formats twice.
|
||||
### Agents (MCP)
|
||||
|
||||
The platform packages carry a third binary, `lucisv-mcp`: lucisv as a Model
|
||||
Context Protocol server, so a coding agent can ask for a module's ports, a
|
||||
file's outline, one block's source, references or the instance hierarchy
|
||||
instead of reading whole files — and make verified edits (format, lint fixes,
|
||||
rename, the port refactorings, single-item replace/insert/delete, each with
|
||||
`dry_run`).
|
||||
Context Protocol server, so a coding agent can ask for the instance
|
||||
hierarchy, where a name is declared and used, a file's or a module's
|
||||
outline, one block's source or the lint verdict instead of reading whole
|
||||
files — and make the edits a file write cannot make safely: a design-wide
|
||||
rename, adding or removing a port in every instantiation, a single-item
|
||||
edit, formatting with the safe lint fixes. Nine tools, short answers; every
|
||||
edit is verified and written whole, with no dry run.
|
||||
|
||||
| Feature | What you get |
|
||||
|---|---|
|
||||
|
||||
+12
-10
@@ -1,7 +1,8 @@
|
||||
// Pre-release smoke test for `lucisv-mcp`: spawn it the way the extension's
|
||||
// provider does (`--root <folder> --index-cache <dir>`, the folder as cwd) over
|
||||
// a tiny temporary project and drive one MCP session at it over stdio —
|
||||
// initialize, notifications/initialized, tools/list, one project_overview.
|
||||
// initialize, notifications/initialized, tools/list, one `hierarchy` without a
|
||||
// root (the project overview).
|
||||
// Plain node, no dependencies, hand-rolled newline-delimited JSON-RPC, like
|
||||
// `smoke.js` does for the language server.
|
||||
//
|
||||
@@ -23,8 +24,8 @@ const named = args.find((arg) => arg !== '--tool-table') || 'lucisv-mcp';
|
||||
// relative path would no longer point at the binary. A bare name stays a PATH lookup.
|
||||
const binary = /[\\/]/.test(named) ? path.resolve(named) : named;
|
||||
|
||||
/** The fewest tools a build of this block may advertise (TODO-MCP M1–M4). */
|
||||
const MIN_TOOLS = 26;
|
||||
/** The lean catalogue, in order (PLAN §10.1, TODO-MCP M7). */
|
||||
const TOOLS = ['hierarchy', 'find', 'outline', 'read', 'check', 'rename', 'port', 'edit_item', 'format'];
|
||||
|
||||
/** Give up on a server that has not answered and exited by then. */
|
||||
const TIMEOUT_MS = 30000;
|
||||
@@ -59,7 +60,7 @@ const REQUESTS = [
|
||||
},
|
||||
{ jsonrpc: '2.0', method: 'notifications/initialized' },
|
||||
{ jsonrpc: '2.0', id: 2, method: 'tools/list' },
|
||||
{ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'project_overview', arguments: {} } },
|
||||
{ jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'hierarchy', arguments: {} } },
|
||||
];
|
||||
|
||||
/** Every request is written up front and stdin closed: the server answers in order and exits on EOF. */
|
||||
@@ -114,13 +115,14 @@ function check(byId) {
|
||||
}
|
||||
const listed = byId.get(2);
|
||||
const tools = (listed && listed.tools) || [];
|
||||
if (tools.length < MIN_TOOLS) fail(`tools/list has ${tools.length} tools, expected at least ${MIN_TOOLS}`);
|
||||
const names = tools.map((tool) => tool.name).join(', ');
|
||||
if (names !== TOOLS.join(', ')) fail(`tools/list is [${names}], expected [${TOOLS.join(', ')}]`);
|
||||
const overview = byId.get(3);
|
||||
if (!overview) fail('no project_overview answer');
|
||||
if (overview.isError) fail(`project_overview is an error: ${JSON.stringify(overview.content)}`);
|
||||
if (!overview) fail('no hierarchy answer');
|
||||
if (overview.isError) fail(`hierarchy is an error: ${JSON.stringify(overview.content)}`);
|
||||
const text = (overview.content || []).map((part) => part.text || '').join('');
|
||||
if (text.trim() === '') fail('project_overview answered no text');
|
||||
if (!text.includes('top')) fail(`project_overview does not name the top module:\n${text}`);
|
||||
if (text.trim() === '') fail('hierarchy answered no text');
|
||||
if (!text.includes('top top.sv:1')) fail(`hierarchy does not name the top module:\n${text}`);
|
||||
return { init, tools };
|
||||
}
|
||||
|
||||
@@ -145,7 +147,7 @@ async function main() {
|
||||
const { init, tools } = check(answers(stdout));
|
||||
if (code !== 0) fail(`the server exited with status ${code} after stdin closed`);
|
||||
console.log(
|
||||
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, project_overview`,
|
||||
`mcp smoke: OK — "${binary}" ${init.serverInfo.version}: initialize, ${tools.length} tools, hierarchy`,
|
||||
);
|
||||
if (toolTable) console.log(markdownTable(tools));
|
||||
} finally {
|
||||
|
||||
+2
-2
@@ -126,8 +126,8 @@ tools/release.sh # or: tools/release.sh -o /some/other/dir
|
||||
It builds `--release`, copies the three binaries into `dist/` under
|
||||
version-and-host names, smoke-tests the server binary with
|
||||
`editors/vscode/smoke.js` and the MCP server with `editors/vscode/mcp_smoke.js`
|
||||
(initialize, `tools/list` with at least 26 tools, one `project_overview` over a
|
||||
tiny temporary project), packages the extension into `dist/lucisv-<version>.vsix`
|
||||
(initialize, `tools/list` with exactly the nine tools in order, one `hierarchy`
|
||||
over a tiny temporary project), packages the extension into `dist/lucisv-<version>.vsix`
|
||||
and into the host's platform package, runs both smoke tests again against the
|
||||
binaries *unzipped out of* that package (and, with `--cross`, out of the `all`
|
||||
package), and writes `dist/SHA256SUMS`. `dist/` is gitignored and is
|
||||
|
||||
+3
-2
@@ -131,7 +131,8 @@ fi
|
||||
# Prove the server binary still speaks LSP before it is handed to anyone.
|
||||
# `smoke.js` is plain node with no dependencies, so this runs before `npm ci`.
|
||||
# The MCP server gets the same treatment from `mcp_smoke.js`: initialize,
|
||||
# tools/list and one project_overview over stdio against a tiny temp project.
|
||||
# tools/list (the nine tools, in order) and one `hierarchy` over stdio against a
|
||||
# tiny temp project.
|
||||
if command -v node >/dev/null 2>&1; then
|
||||
echo "==> smoke-testing the server binary"
|
||||
node "$repo_root/editors/vscode/smoke.js" "$dist/lucisv-server-$version-$host"
|
||||
@@ -254,7 +255,7 @@ smoke_embedded_server() { # vsix file name, the bin/ path inside the package
|
||||
}
|
||||
|
||||
# The same for the MCP server the package carries: unzipped, then driven through
|
||||
# initialize, tools/list and one project_overview by `mcp_smoke.js`.
|
||||
# initialize, tools/list and one `hierarchy` by `mcp_smoke.js`.
|
||||
smoke_embedded_mcp() { # vsix file name, the bin/ path inside the package
|
||||
vsix=$1
|
||||
inner=$2
|
||||
|
||||
Reference in new issue
Block a user