MCP M2: definition, references, hierarchy, diagnostics, defines and the lucisv:// resources

Five navigation tools on the M1 transport (crates/lucisv_mcp/src/tools/{nav,select,hierarchy,diagnostics,defines,source}.rs, src/resources.rs): one selector for definition/references (file+line+col in 1-based bytes, file+line+name with the name chosen by token — never by text, so comments, strings and macro arguments cannot stand in — file+name refused when its uses resolve to different declarations, or a bare name with an optional unit); definition walks the server's ladder (include beside the file, macro, local table, workspace overlay computed per call) and lists every site with its byte-checked source line; references hands vlog_refactor::find_references the WHOLE indexed set — the plan's word-census narrowing was the lead's and QA proved it drops uses that resolve through a file never spelling the name (a two-level tail, a class-handle chain), so it is gone and MCP-7 asks vlog_refactor for a KnownFacts variant (≈2 s per call on opentitan's 3 944 files, recorded); hierarchy is the index's instantiation census down (default every top module) or up, depth 1..=20 in the schema, recursion and node caps, overrides sliced per statement; diagnostics is what `lucisv check .` reports — parse errors first, then lint under each file's lucisv.toml [lint] select/ignore/options/waivers through an index-backed MentionOracle, unused waivers in the whole-project form, the CLI's JSON field names; defines lists one file's, one macro's or the project's table. Resources: lucisv://overview, lucisv://rules, lucisv://unit/{name}, lucisv://file/{path}/outline. M1 QA finding 11 (a bare escaped name ending in @digits) fixed in read_item.

QA (Opus, two rounds): 43 qa_m2 tests; four wrong answers (the narrowing, a macro-argument occurrence answered as the macro, per-instance overrides in one statement, file+name guessing among declarations) and seven smaller findings fixed under the lead's rulings. opentitan census as an #[ignore] test (LUCISV_OPENTITAN): entropy_masking_req lists aes_bind.sv, state_q lists entropy_src_core.sv, top_earlgrey → u_aes : aes, parity with the LSP at every symbol — plus three real aes instantiations in the *_pd_main.sv tops the LSP omits (MCP-6, to file in TODO.md). Checkout untouched. Gates through tools/guard.sh: fmt, clippy, workspace 4 610 passed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5.1 committed 2026-09-23 05:46:19 -07:00
1 parent 7a0c8e51f9
commit 82bbba04be
30 files changed
+4541 -28

No files matched your search

+5 -5
View File
@@ -84,7 +84,7 @@ missing public query is a Handshake entry.
methods), `tests/wire.rs` (additions), the `mcp-navigation` README.
Depends on M1 merged.
- [ ] `definition` (selector: `file,line,col` or `name,unit?`; local via
- [x] `definition` (selector: `file,line,col` or `name,unit?`; local via
`Semantics::definition_of`, cross-file via `resolve_external`;
ambiguity is a list), `references` (`vlog_refactor::find_references`,
grouped by file, capped with `limit`/`offset`), `hierarchy` (down from
@@ -94,16 +94,16 @@ Depends on M1 merged.
`select_rules` + the project's `[lint]` config + external waivers +
an index-backed `MentionOracle`; the CLI's JSON field names), `defines`
(table; one-step expansion when called with `name` + `args`)
- [ ] resources `lucisv://overview`, `lucisv://unit/{name}`,
- [x] resources `lucisv://overview`, `lucisv://unit/{name}`,
`lucisv://rules` (`rules_markdown()`), `lucisv://file/{path}/outline`;
`resources/templates/list` for the two parameterised ones
- [ ] the opentitan parity census as an `#[ignore]` test taking the
- [x] the opentitan parity census as an `#[ignore]` test taking the
checkout path from an env var: `references`/`definition` on the
`references-nav` symbols and `hierarchy` down from `top_earlgrey`
compared with the LSP's answers recorded in that README (read-only;
`git status` of the checkout identical before and after)
- [ ] README `mcp-navigation`; work log; gates; sizes
- [ ] QA: a `bind` connection's bare name, a `u_x.sig` tail, a name that
- [x] README `mcp-navigation`; work log; gates; sizes
- [x] QA: a `bind` connection's bare name, a `u_x.sig` tail, a name that
is both a port and an internal net (must list both, not pick), a
class member, a macro-only name (`files_naming_in_macros`), a
`hierarchy` over a recursive/generate-instantiated module (must
+1
View File
@@ -9,6 +9,7 @@
mod project;
mod render;
mod resources;
mod rpc;
mod tools;
mod transport;
+58 -9
View File
@@ -3,17 +3,20 @@
//! The index answers workspace questions without keeping any file's text;
//! a tool that needs a file's outline, a slice of its text or its
//! declarations asks for its [`Analysis`] here. The sequence is the language
//! server's `Document::new` minus the parts that belong to later lanes (the
//! `` `define`` table and the cross-file overlay are M2's, where `defines`
//! and `definition` first read them): lex once, parse tolerantly, analyze,
//! index the lines.
//! server's `Document::new` minus the cross-file overlay: lex once, parse
//! tolerantly, read the `` `define`` table off the tokens, analyze, index the
//! lines. The overlay (`resolve_external`) depends on the index, which moves
//! under a file whose own text did not, so it is computed per call by the
//! tool that needs it ([`Analysis::external`]) and never cached here.
use std::path::{Path, PathBuf};
use std::rc::Rc;
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, Semantics};
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
/// 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.
@@ -25,6 +28,10 @@ pub struct Analysis {
pub text: String,
/// The line table over `text`.
pub lines: LineIndex,
/// The tokens `tree` was parsed from; empty when the text does not lex.
pub tokens: Vec<Token>,
/// Every `` `define``/`` `undef`` the file writes, in source order.
pub defines: DefineTable,
/// The tolerant parse.
pub tree: SourceFile,
/// What the parse could not read; empty for a clean file.
@@ -39,13 +46,43 @@ impl Analysis {
pub fn of(text: String) -> Analysis {
// One lex: a file that does not lex takes the all-error path, exactly
// as `parse_source_tolerant` would.
let (tree, diagnostics) = match tokenize(&text) {
Ok(tokens) => parse_tolerant(tokens, &text),
Err(_) => parse_source_tolerant(&text),
// The tokens are kept (a clone before the parse consumes them): the
// lint pass and the macro lookups read them again.
let (tree, diagnostics, tokens) = match tokenize(&text) {
Ok(tokens) => {
let (tree, diagnostics) = parse_tolerant(tokens.clone(), &text);
(tree, diagnostics, tokens)
}
Err(_) => {
let (tree, diagnostics) = parse_source_tolerant(&text);
(tree, diagnostics, Vec::new())
}
};
let defines = collect_defines(&tokens);
let semantics = analyze(&tree, &text);
let lines = LineIndex::new(&text);
Analysis { text, lines, tree, diagnostics, semantics }
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
@@ -102,6 +139,18 @@ 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() {
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());
}
#[test]
+180
View File
@@ -0,0 +1,180 @@
//! 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.
use serde_json::{json, Map, Value};
use crate::project::Project;
use crate::tools;
/// One resource a URI names.
pub enum Resource {
Overview,
Rules,
Unit(String),
Outline(String),
}
/// The `resources/list` result: the two fixed resources.
pub fn list() -> Value {
json!({ "resources": [
{
"uri": "lucisv://overview",
"name": "overview",
"title": "Project overview",
"description": "Files, units by kind, top-level modules and largest files of the indexed project.",
"mimeType": "text/plain",
},
{
"uri": "lucisv://rules",
"name": "rules",
"title": "Lint rules",
"description": "Every lucisv lint rule with its severity, default and options.",
"mimeType": "text/markdown",
},
]})
}
/// The `resources/templates/list` result: the two parameterised resources.
pub fn templates() -> Value {
json!({ "resourceTemplates": [
{
"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.",
"mimeType": "text/plain",
},
{
"uriTemplate": "lucisv://file/{path}/outline",
"name": "outline",
"title": "File outline",
"description": "The declarations in one root-relative file, with line ranges.",
"mimeType": "text/plain",
},
]})
}
impl Resource {
/// The resource `uri` names, or `None` for any other URI.
pub fn parse(uri: &str) -> Option<Resource> {
let rest = uri.strip_prefix("lucisv://")?;
match rest {
"overview" => Some(Resource::Overview),
"rules" => Some(Resource::Rules),
_ => {
if let Some(name) = rest.strip_prefix("unit/") {
return decoded(name).map(Resource::Unit);
}
let path = rest.strip_prefix("file/")?.strip_suffix("/outline")?;
decoded(path).map(Resource::Outline)
}
}
}
/// Whether answering needs the project index (only the rules do not).
pub fn needs_project(&self) -> bool {
!matches!(self, Resource::Rules)
}
/// Whether answering walks the roots first, as `project_overview` does.
pub fn rewalk(&self) -> bool {
matches!(self, Resource::Overview)
}
/// The `resources/read` result, or the reason there is no such 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::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",
)
})?;
("text/plain", text)
}
(Resource::Outline(path), Some(project)) => {
("text/plain", run(project, "outline", Some(("file", path)))?)
}
(_, None) => return Err("the project is not open".into()),
};
Ok(json!({ "contents": [{ "uri": uri, "mimeType": mime, "text": text }] }))
}
}
/// A read tool's text answer, as the resource's body.
fn run(
project: &mut Project,
tool: &str,
argument: Option<(&str, &str)>,
) -> Result<String, String> {
let tool = tools::find(tool).ok_or_else(|| format!("no tool `{tool}`"))?;
let mut arguments = Map::new();
if let Some((name, value)) = argument {
arguments.insert(name.to_string(), Value::from(value));
}
let args = tools::validate(tool, arguments)?;
(tool.handler)(project, &args).map(|answer| answer.text)
}
/// `%XX` escapes decoded; `None` for a malformed escape, an empty result or
/// bytes that are not UTF-8.
fn decoded(text: &str) -> Option<String> {
let bytes = text.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut at = 0;
while at < bytes.len() {
if bytes[at] == b'%' {
let hex = text.get(at + 1..at + 3)?;
out.push(u8::from_str_radix(hex, 16).ok()?);
at += 3;
} else {
out.push(bytes[at]);
at += 1;
}
}
String::from_utf8(out).ok().filter(|decoded| !decoded.is_empty())
}
#[cfg(test)]
mod tests {
use super::*;
fn parsed(uri: &str) -> Option<String> {
Resource::parse(uri).map(|resource| match resource {
Resource::Overview => "overview".into(),
Resource::Rules => "rules".into(),
Resource::Unit(name) => format!("unit {name}"),
Resource::Outline(path) => format!("outline {path}"),
})
}
#[test]
fn uris_name_their_resource_and_nothing_else_does() {
assert_eq!(parsed("lucisv://overview").as_deref(), Some("overview"));
assert_eq!(parsed("lucisv://rules").as_deref(), Some("rules"));
assert_eq!(parsed("lucisv://unit/leaf").as_deref(), Some("unit leaf"));
assert_eq!(parsed("lucisv://unit/%5Cmy-mod%20").as_deref(), Some("unit \\my-mod "));
assert_eq!(
parsed("lucisv://file/rtl/top.sv/outline").as_deref(),
Some("outline rtl/top.sv")
);
for other in [
"lucisv://unit/",
"lucisv://unit/%zz",
"lucisv://file/rtl/top.sv",
"lucisv://file//outline",
"file:///etc/passwd",
"lucisv://overview/x",
] {
assert!(parsed(other).is_none(), "{other}");
}
}
}
+24 -4
View File
@@ -1,6 +1,6 @@
//! The JSON-RPC 2.0 envelope and the MCP methods this server answers: the
//! `initialize` handshake and its version negotiation, `ping`, the tool
//! methods, and empty resource/prompt lists until the lanes that fill them.
//! methods, the `lucisv://` resources, and an empty prompt list.
//!
//! One synchronous loop, like `lucisv-server`: a request is answered before
//! the next line is read, so pipelined requests are answered in order.
@@ -12,6 +12,7 @@ use serde::Serialize;
use serde_json::{json, Map, Value};
use crate::project::Project;
use crate::resources::{self, Resource};
use crate::tools;
use crate::transport::{Line, Transport};
use crate::Options;
@@ -193,9 +194,9 @@ impl Server {
_ if self.version.is_none() => Err(fault(NOT_INITIALIZED, "server not initialized")),
"tools/list" => Ok(tools::list()),
"tools/call" => self.call_tool(params),
"resources/list" => Ok(json!({ "resources": [] })),
"resources/templates/list" => Ok(json!({ "resourceTemplates": [] })),
"resources/read" => Err(fault(RESOURCE_NOT_FOUND, "resource not found")),
"resources/list" => Ok(resources::list()),
"resources/templates/list" => Ok(resources::templates()),
"resources/read" => self.read_resource(params),
"prompts/list" => Ok(json!({ "prompts": [] })),
"prompts/get" => Err(fault(INVALID_PARAMS, "unknown prompt")),
other => Err(fault(METHOD_NOT_FOUND, format!("method not found: {other}"))),
@@ -247,6 +248,25 @@ impl Server {
Ok(tool_result((tool.handler)(project, &args)))
}
/// `resources/read`: a `lucisv://` URI answered from the project as it is
/// on disk now; any other URI, or one naming nothing (a unit or file that
/// does not exist), is `-32002` with the reason.
fn read_resource(&mut self, params: Option<Value>) -> Result<Value, RpcError> {
let Some(uri) = params.as_ref().and_then(|p| p.get("uri")).and_then(Value::as_str) else {
return Err(fault(INVALID_PARAMS, "resources/read params need a string `uri`"));
};
let not_found =
|why: &str| fault(RESOURCE_NOT_FOUND, format!("resource not found: {uri}{why}"));
let Some(resource) = Resource::parse(uri) else {
return Err(not_found(""));
};
let project = match resource.needs_project() {
true => Some(self.project(resource.rewalk())),
false => None,
};
resource.read(uri, project).map_err(|why| not_found(&format!(" ({why})")))
}
/// The project, built on first use and brought up to the disk on every
/// later one.
fn project(&mut self, rewalk: bool) -> &mut Project {
+210
View File
@@ -0,0 +1,210 @@
//! `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::source::{self, Texts};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
/// 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 (on one line) and file:line — of one `file`, of one macro `name` across the project (every definition; which one a use sees depends on include order, so none is picked), or of the whole project. Prefer it over grepping for `define.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "Only this file's table (its `undef`s included), relative to a root or absolute inside one.",
},
Param {
name: "name",
ty: Ty::Str,
required: false,
description: "Only this macro, written with or without the backtick.",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most entries to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Entries to skip, for paging past `… and N more` (default 0).",
},
],
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, rest, total) = match args.str("file") {
Some(file) => in_file(project, file, name, args)?,
None => {
let mut all = indexed(project, name);
if all.is_empty() && name.is_some() && project.ensure_walked_for_miss() {
all = indexed(project, name);
}
let (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
(rows_of(project, shown), rest, all.len())
}
};
let entries: Vec<(String, String)> = rows
.iter()
.map(|row| (row.file.clone(), format!("{} {}", row.line, spelled(&row.define))))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if total == 0 {
text = "no defines\n".to_string();
}
let listed: Vec<Value> = rows.iter().map(row_json).collect();
Ok(Answer { text, structured: json!({ "defines": listed, "total": total }) })
}
/// 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>, usize, usize), 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 (shown, rest) =
render::page(&all, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let rows = shown
.iter()
.map(|define| Row {
file: shown_file.clone(),
line: analysis.lines.line_col(define.span.start).0,
define: (*define).clone(),
})
.collect();
Ok((rows, rest, all.len()))
}
/// 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('…'));
}
}
+364
View File
@@ -0,0 +1,364 @@
//! `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.
//!
//! 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.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap};
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,
};
use vlog_parser::LineIndex;
use vlog_semantic::{FileId, PackageExports, SymbolKind, WorkspaceIndex};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render::{self, DEFAULT_LIMIT};
pub const DIAGNOSTICS: Tool = Tool {
name: "diagnostics",
title: "Diagnostics",
description: "Parse errors and lint findings for one `file`, or for every indexed file, grouped by file as `line:col severity message [rule]` — what `lucisv check` over the whole tree reports (cross-file rules on), under the project's lucisv.toml [lint] settings and waivers. Filter with `rules` (like --select) and `severity`. The whole-project form lints every file and returns the first `limit` findings with the total.",
params: &[
Param {
name: "file",
ty: Ty::Str,
required: false,
description: "One file, relative to a root or absolute inside one (default: every indexed file).",
},
Param {
name: "rules",
ty: Ty::Str,
required: false,
description: "Comma-separated rule names or severities to run instead of the configured set, like `--select`.",
},
Param {
name: "severity",
ty: Ty::Enum(&["error", "warning", "style"]),
required: false,
description: "Only findings of this severity (parse errors are `error`).",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most findings to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Findings to skip, for paging past `… and N more` (default 0).",
},
],
rewalk: false,
handler: diagnostics,
};
/// One finding, in the CLI's JSON shape.
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.
struct Run {
rules: Vec<&'static dyn Rule>,
options: RuleOptions,
waivers: ExternalWaivers,
line_length: usize,
tab_width: usize,
/// Which external waivers fired, over every file this run linted.
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 { discovery: Discovery::new(true), held: BTreeMap::new(), selected };
let mut findings = Vec::new();
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 { index: project.index(), census: None, own };
findings = file_findings(project, &mut runs, &path, &analysis, &oracle)?;
}
None => {
let census = Census::of(project.index());
let paths: Vec<PathBuf> = project.files().map(|(path, _)| path.clone()).collect();
for path in paths {
let Ok(text) = std::fs::read_to_string(&path) else { continue };
let analysis = Analysis::of(text);
let own = project.index().file_id(&path);
let oracle = Mentions { index: project.index(), census: Some(&census), own };
findings.extend(file_findings(project, &mut runs, &path, &analysis, &oracle)?);
}
// Only a complete run knows a waiver matched nothing.
findings.extend(runs.unused_waivers(project));
}
}
if let Some(severity) = args.str("severity") {
findings.retain(|finding| finding.severity == severity);
}
Ok(render_findings(&findings, args))
}
/// The runs met so far in one call, one per governing config file.
struct Runs {
discovery: Discovery,
held: BTreeMap<Option<PathBuf>, Rc<Run>>,
selected: Option<Vec<String>>,
}
impl Runs {
/// The run for the config governing `path`, built on first use. A config
/// that does not read, an unknown rule, a bad option or an unreadable
/// waiver file is a refusal naming it — `lucisv check` fails the same way.
fn for_file(&mut self, path: &Path) -> Result<Rc<Run>, String> {
let config = self.discovery.for_file(path)?;
if let Some(run) = self.held.get(&config.source) {
return Ok(Rc::clone(run));
}
let run = Rc::new(self.build(&config)?);
self.held.insert(config.source.clone(), Rc::clone(&run));
Ok(run)
}
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 ignore = config.lint_ignore.clone().unwrap_or_default();
let rules = select_rules(&select, &ignore, true)?;
let mut options = RuleOptions::new();
for entry in &config.lint_options {
options.set_raw(&entry.rule, &entry.key, &entry.raw).map_err(|e| {
let file = config
.source
.as_ref()
.map_or("lucisv.toml".into(), |p| p.display().to_string());
format!("{file}:{}: rule `{}` {e}", entry.line, entry.rule)
})?;
}
let mut waivers = ExternalWaivers::default();
for path in config.lint_waivers.iter().flatten() {
let (file, problems) = ExternalWaivers::read(path)?;
if let Some(problem) = problems.first() {
return Err(problem.clone());
}
waivers.absorb(file);
}
let format = vlog_formatter::Config::default();
Ok(Run {
rules,
options,
waivers,
line_length: config.line_length.unwrap_or(format.max_width),
tab_width: config.indent.unwrap_or(format.indent_width),
used: RefCell::new(WaiverUse::default()),
})
}
}
impl Runs {
/// One `unused-waiver` finding per external directive that suppressed
/// nothing in any file its run linted — the CLI's end-of-run report.
fn unused_waivers(&self, project: &Project) -> Vec<Finding> {
let mut out = Vec::new();
for run in self.held.values() {
let enabled: Vec<&'static str> = run.rules.iter().map(|rule| rule.name()).collect();
for report in run.waivers.unused(&run.used.borrow(), &enabled) {
let lines = LineIndex::new(&report.text);
let file = project.relative(&report.path);
out.extend(report.violations.iter().map(|v| lint_finding(&file, &lines, v)));
}
}
out
}
}
/// One file's findings: its parse errors, then its lint findings.
fn file_findings(
project: &Project,
runs: &mut Runs,
path: &Path,
analysis: &Analysis,
oracle: &Mentions,
) -> Result<Vec<Finding>, String> {
let file = project.relative(path);
let run = runs.for_file(path)?;
let mut out: Vec<Finding> = analysis
.diagnostics
.iter()
.map(|error| Finding {
file: file.clone(),
rule: "parse-error".into(),
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 ctx = LintContext::from_parse(
&analysis.text,
&analysis.tokens,
&analysis.tree,
&analysis.lines,
Some(path.to_path_buf()),
)
.with_semantics(&analysis.semantics)
.with_options(&run.options)
.with_line_length(run.line_length)
.with_tab_width(run.tab_width)
.with_oracle(oracle);
let (violations, used) = lint_with(&ctx, &run.rules, &run.waivers);
run.used.borrow_mut().merge(&used);
out.extend(violations.iter().map(|violation| lint_finding(&file, &analysis.lines, violation)));
Ok(out)
}
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,
}
}
/// Findings grouped by file, paged; the JSON is the CLI's array shape.
fn render_findings(findings: &[Finding], args: &Args) -> Answer {
let (shown, rest) =
render::page(findings, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
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 = render::grouped(&entries);
render::more(&mut text, rest);
if findings.is_empty() {
text = "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();
Answer { text, structured: json!({ "diagnostics": listed, "total": findings.len() }) }
}
/// 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.
struct Census<'a> {
words: HashMap<&'a str, (usize, FileId)>,
}
impl<'a> Census<'a> {
fn of(index: &'a WorkspaceIndex) -> Census<'a> {
let mut words: HashMap<&'a str, (usize, FileId)> = HashMap::new();
for (at, path) in index.files().iter().enumerate() {
let Some(facts) = index.facts_for(path) else { continue };
let file = FileId(at as u32);
for word in facts.words() {
words.entry(word.as_str()).or_insert((0, file)).0 += 1;
}
}
Census { words }
}
fn outside(&self, name: &str, own: Option<FileId>) -> bool {
match self.words.get(name) {
Some(&(count, first)) => count > 1 || Some(first) != own,
None => false,
}
}
}
/// The project index answering the linter's cross-file questions — the
/// language server's `IndexMentions`, with the census when one was built.
struct Mentions<'a> {
index: &'a WorkspaceIndex,
census: Option<&'a Census<'a>>,
/// The linted file itself, subtracted from "elsewhere".
own: Option<FileId>,
}
impl MentionOracle for Mentions<'_> {
fn mentioned_elsewhere(&self, name: &str) -> bool {
match self.census {
Some(census) => census.outside(name, self.own),
None => self.index.mentioned_outside(name, self.own),
}
}
/// Ports and overridable parameters of a module declared exactly once.
fn module_interface(&self, name: &str) -> Option<ModuleInterface> {
let [unit] = self.index.units(name) else { return None };
if !unit.kind.is_instantiable() {
return None;
}
let mut interface = ModuleInterface::default();
for (member, defs) in self.index.members_of(name) {
match defs.first().map(|def| def.kind) {
Some(SymbolKind::Port) => interface.ports.push(member.to_string()),
Some(SymbolKind::Param) => interface.parameters.push(member.to_string()),
_ => {}
}
}
Some(interface)
}
fn package_exports(&self, package: &str) -> Exports {
PackageExports::exports(self.index, package)
}
}
+408
View File
@@ -0,0 +1,408 @@
//! `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.
//!
//! 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.
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::source::{self, Texts};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::Project;
use crate::render::{self, DEFAULT_LIMIT};
/// The deepest a walk may go, whatever `depth` asks.
const MAX_DEPTH: usize = 20;
/// The longest overrides text a line shows; the JSON carries all of it.
const OVERRIDES_CAP: usize = 200;
/// The most nodes one walk collects before it stops.
const NODE_CAP: usize = 50_000;
pub const HIERARCHY: Tool = Tool {
name: "hierarchy",
title: "Instance hierarchy",
description: "The instance tree as indented `instance : module #(overrides)` lines, down from `root` (default: every top-level module), or with `direction: up` every `parent.instance` that instantiates `root`, with file:line. Textual, not elaborated: `generate` and `ifdef` branches all appear. Prefer it over reading files to find who instantiates what.",
params: &[
Param {
name: "root",
ty: Ty::Str,
required: false,
description: "The module to start from; required for `up` (default for `down`: every module nothing instantiates).",
},
Param {
name: "direction",
ty: Ty::Enum(&["down", "up"]),
required: false,
description: "`down` lists what `root` instantiates (default); `up` lists what instantiates it.",
},
Param {
name: "depth",
ty: Ty::Range { min: 1, max: MAX_DEPTH as i64 },
required: false,
description: "Levels to walk (default 3, at most 20).",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most lines to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Lines to skip, for paging past `… and N more` (default 0).",
},
],
rewalk: false,
handler: hierarchy,
};
/// One instance under an owner, as the index records it.
#[derive(Clone)]
struct Child {
instance: String,
module: String,
file: FileId,
/// The instantiated module's name at the site.
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,
}
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);
Child {
instance: occurrence.name.clone(),
module: module.to_string(),
file: edge.file,
site: edge.site_span,
name: occurrence.name_span,
first,
}
}
}
/// One line of the answer. A root line has no instance.
struct Node {
depth: usize,
/// Down: the instance; up: the instance of the line above it.
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, 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>,
}
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(index, 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),
};
for (name, def) in roots {
walk.root(name, def, up);
}
Ok(render(project, walk.nodes, up, args))
}
/// Every instantiable declaration of `name`.
fn modules_named(index: &WorkspaceIndex, name: &str) -> Vec<Def> {
index.units(name).iter().filter(|def| def.kind.is_instantiable()).cloned().collect()
}
/// Every module nothing instantiates, in name order.
fn top_modules(index: &WorkspaceIndex) -> Vec<(String, Def)> {
index
.instantiable_units()
.filter(|(_, def)| def.kind == SymbolKind::Module)
.filter(|(name, _)| index.instantiations_of(name).is_empty())
.map(|(name, def)| (name.to_string(), def.clone()))
.collect()
}
impl<'a> Walk<'a> {
/// A walk over `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 {
let owner = (edge.file, edge.owner.name_span.start);
let children =
edge.instances.iter().map(|occurrence| Child::of(module, edge, occurrence));
below.entry(owner).or_default().extend(children);
}
}
for children in below.values_mut() {
children.sort_by_key(|child| child.name.start);
}
Walk { index, below, max_depth, nodes: Vec::new(), path: Vec::new() }
}
fn full(&self) -> bool {
self.nodes.len() >= NODE_CAP
}
/// One root line and its tree.
fn root(&mut self, name: String, def: Def, up: bool) {
if self.full() {
return;
}
self.path = vec![name.clone()];
let line = Node {
depth: 0,
instance: None,
module: name.clone(),
root: Some(def.clone()),
note: None,
};
self.nodes.push(line);
if up {
self.up(&name, 1);
} else {
self.down(&def, 1);
}
}
/// The instances `def` declares, and theirs, to `max_depth`.
fn down(&mut self, def: &Def, depth: usize) {
let children =
self.below.get(&(def.file, def.name_span.start)).cloned().unwrap_or_default();
for child in children {
if self.full() {
return;
}
let declared = modules_named(self.index, &child.module);
let recursive = self.path.contains(&child.module);
let note = match declared.len() {
_ if recursive => Some("recursive".to_string()),
0 => Some("not indexed".to_string()),
1 => None,
n => Some(format!("declared {n} times")),
};
let expand = note.is_none() && depth < self.max_depth;
let module = child.module.clone();
self.nodes.push(Node {
depth,
instance: Some(child),
module: module.clone(),
root: None,
note,
});
if let (true, [only]) = (expand, declared.as_slice()) {
self.path.push(module);
self.down(only, depth + 1);
self.path.pop();
}
}
}
/// Every instance of `module`, then the instances of their owners.
fn up(&mut self, module: &str, depth: usize) {
let index = self.index;
for edge in index.instantiations_of(module) {
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),
module: parent.clone(),
root: None,
note,
});
if !recursive && depth < self.max_depth {
self.path.push(parent.clone());
self.up(&parent, depth + 1);
self.path.pop();
}
}
}
}
}
/// The collected nodes, paged, as indented lines and as a flat JSON list.
fn render(project: &Project, nodes: Vec<Node>, up: bool, args: &Args) -> Answer {
let (shown, rest) =
render::page(&nodes, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let mut texts = Texts::default();
let mut text = String::new();
let mut listed: Vec<Value> = Vec::new();
for node in shown {
let line = Line::of(project, &mut texts, node);
text.push_str(&" ".repeat(node.depth));
text.push_str(&line.text(node, up));
text.push('\n');
listed.push(line.json(node, up));
}
render::more(&mut text, 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() {
text = "no modules\n".to_string();
}
let direction = if up { "up" } else { "down" };
let structured = json!({
"direction": direction, "nodes": listed, "total": nodes.len(),
"cut": nodes.len() >= NODE_CAP,
});
Answer { text, structured }
}
/// 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 {
let path = index.path(def.file).unwrap_or(Path::new(""));
return Line { file: project.relative(path), line: def.lines.name, overrides: None };
}
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) }
}
fn text(&self, node: &Node, up: 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 {
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,
})
}
}
/// 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> {
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);
}
}
+36
View File
@@ -3,9 +3,15 @@
//! `inputSchema` a host shows the agent and the validation a call's
//! `arguments` go through, so the two cannot disagree.
mod defines;
mod diagnostics;
mod hierarchy;
mod interface;
mod nav;
mod read;
mod read_item;
mod select;
mod source;
use serde_json::{json, Map, Value};
@@ -29,6 +35,10 @@ pub enum Ty {
Int { min: i64 },
/// One of a fixed set of strings.
Enum(&'static [&'static str]),
/// `true` or `false`.
Bool,
/// An integer inside `min..=max`.
Range { min: i64, max: i64 },
}
/// One argument a tool takes.
@@ -59,6 +69,11 @@ const TOOLS: &[Tool] = &[
read::OUTLINE,
read_item::READ_ITEM,
read::SEARCH_SYMBOLS,
defines::DEFINES,
nav::DEFINITION,
nav::REFERENCES,
hierarchy::HIERARCHY,
diagnostics::DIAGNOSTICS,
];
/// The tool called `name`.
@@ -99,6 +114,8 @@ fn schema(params: &[Param]) -> Value {
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 }),
};
property["description"] = Value::from(param.description);
properties.insert(param.name.to_string(), property);
@@ -127,6 +144,11 @@ impl Args {
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 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)
@@ -163,6 +185,8 @@ fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
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)),
};
if fits {
return Ok(());
@@ -171,6 +195,8 @@ fn check_type(tool: &str, param: &Param, value: &Value) -> Result<(), String> {
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}"),
};
Err(format!("`{tool}` argument `{}` must be {wanted}, not {value}.", param.name))
}
@@ -210,5 +236,15 @@ mod tests {
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 hierarchy = find("hierarchy").unwrap();
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);
}
}
+424
View File
@@ -0,0 +1,424 @@
//! `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 ([`all_files`]).
//! The selector itself is `select.rs`.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::token::{Token, TokenKind};
use vlog_semantic::{Def, Definition, DefinitionKey, Surface, Symbol, WorkspaceIndex};
use super::select::{macro_name, target, Target};
use super::source::{self, checked_site, Site, Texts};
use super::{Answer, Args, Param, Tool, Ty};
use crate::project::{Analysis, Project};
use crate::render::{self, DEFAULT_LIMIT};
/// The selector's arguments, shared by both tools.
const FILE: Param = Param {
name: "file",
ty: Ty::Str,
required: false,
description: "The file holding the position, relative to a root or absolute inside one.",
};
const LINE: Param = Param {
name: "line",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based line in `file`; give `col` too, or the `name` written on that line.",
};
const COL: Param = Param {
name: "col",
ty: Ty::Int { min: 1 },
required: false,
description: "1-based column in bytes on `line`.",
};
const NAME: Param = Param {
name: "name",
ty: Ty::Str,
required: false,
description: "The name: alone, looked up across the project (`` `NAME`` for a macro); with `file`, its first occurrence there; with `file` and `line`, its occurrence on that line.",
};
const UNIT: Param = Param {
name: "unit",
ty: Ty::Str,
required: false,
description: "With a bare `name`: the module, interface, package or class declaring it.",
};
pub const DEFINITION: Tool = Tool {
name: "definition",
title: "Go to definition",
description: "Where a name is declared: every declaration site as file:line:col, its kind and the declaration's own source line (a name declared in several places lists them all, never a guess). Select by position (`file`, `line`, `col`), by `file`+`line`+`name`, or by `name` (and `unit`) across the project; also answers a macro use and an `include` line. Prefer it over grepping for the declaration.",
params: &[FILE, LINE, COL, NAME, UNIT],
rewalk: false,
handler: definition,
};
pub const REFERENCES: Tool = Tool {
name: "references",
title: "Find references",
description: "Every use of one declaration across the project, grouped by file as line:col and the line's text — the same occurrences a rename would edit. Select as for `definition`; a bare `name` must name one declaration. Refuses a name lucisv cannot resolve to one declaration, with the reason.",
params: &[
FILE,
LINE,
COL,
NAME,
UNIT,
Param {
name: "include_declaration",
ty: Ty::Bool,
required: false,
description: "List the declaration itself too (default true).",
},
Param {
name: "limit",
ty: Ty::Int { min: 1 },
required: false,
description: "Most hits to return (default 200).",
},
Param {
name: "offset",
ty: Ty::Int { min: 0 },
required: false,
description: "Hits to skip, for paging past `… and N more` (default 0).",
},
],
rewalk: false,
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 files = all_files(project, &path);
let include = args.flag("include_declaration", true);
let found =
vlog_refactor::find_references(&files, &path, offset, include).map_err(engine_refusal)?;
let mut texts = Texts::default();
for (held, text) in 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();
Ok(render_hits(&hits, args))
}
/// The one declaration a bare `name` selects for `references`.
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).";
/// Every indexed file (and the selected one), read from disk now — the
/// whole set, always (lead's ruling on QA finding 1): a use can resolve
/// through files that never spell its name (`u_a.u_b.sig` needs the file
/// declaring `u_b`; `e.s.count` needs the class declaring `s`), so no
/// narrowing by name is sound. The cost is a parse of the set per call
/// (README; Handshake MCP-7 lets cached facts replace it).
fn all_files(project: &Project, path: &Path) -> Vec<(PathBuf, String)> {
let mut wanted: BTreeSet<PathBuf> = project.index().files().iter().cloned().collect();
wanted.insert(path.to_path_buf());
wanted
.into_iter()
.filter_map(|path| std::fs::read_to_string(&path).ok().map(|text| (path, text)))
.collect()
}
/// 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}")
}
/// Hits grouped by file, `line:col text`, paged.
fn render_hits(hits: &[Site], args: &Args) -> Answer {
let (shown, rest) =
render::page(hits, args.count("offset", 0), args.count("limit", DEFAULT_LIMIT));
let entries: Vec<(String, String)> = shown
.iter()
.map(|hit| (hit.file.clone(), format!("{}:{} {}", hit.line, hit.col, hit.text)))
.collect();
let mut text = render::grouped(&entries);
render::more(&mut text, rest);
if hits.is_empty() {
text = "no references\n".to_string();
}
let listed: Vec<Value> = shown
.iter()
.map(|hit| json!({ "file": hit.file, "line": hit.line, "col": hit.col, "text": hit.text }))
.collect();
Answer { text, structured: json!({ "hits": listed, "total": hits.len() }) }
}
#[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}");
}
}
}
+30 -6
View File
@@ -68,14 +68,26 @@ pub fn select(analysis: &Analysis, selector: &str) -> Result<(&'static str, Text
if let (Some(keyword), Some(line)) = (BY_LINE.iter().find(|k| **k == head), line) {
return by_line(analysis, keyword, line).map(|span| (*keyword, span));
}
// `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).
let (kind, name) = match head.split_once(':') {
let (kind, name) = split_kind(head);
let symbol = match by_name(analysis, name, kind, line) {
// An escaped identifier may itself end in `@digits` (`\a@12 `): when
// the `@LINE` reading finds nothing, the whole spelling is the name.
Err(problem) if line.is_some() && name.starts_with('\\') => {
let (_, whole) = split_kind(selector);
by_name(analysis, whole, kind, None).map_err(|_| problem)?
}
answer => answer?,
};
Ok((render::kind(symbol.kind), item_span(analysis, symbol)))
}
/// `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) {
match head.split_once(':') {
Some((kind, name)) if render::is_kind_word(kind) => (Some(kind), name),
_ => (None, head),
};
let symbol = by_name(analysis, name, kind, line)?;
Ok((render::kind(symbol.kind), item_span(analysis, symbol)))
}
}
/// Split `head@LINE` at the last `@` when only digits follow it; any other
@@ -313,4 +325,16 @@ module n; logic q; endmodule
assert!(text("q@99999999999").unwrap_err().contains("out of range"));
assert!(text("nokind:q").unwrap_err().contains("no declaration matches `nokind:q`"));
}
#[test]
fn an_escaped_name_ending_in_at_digits_is_its_own_name_when_no_line_matches() {
let analysis = Analysis::of("module \\a@12 (input z); endmodule\n".into());
let (kind, span) = select(&analysis, "\\a@12").unwrap();
assert_eq!(kind, "module");
assert!(analysis.slice(span.start, span.end).starts_with("module \\a@12 "));
let (_, by_kind) = select(&analysis, "module:\\a@12").unwrap();
assert_eq!(by_kind, span);
let refused = select(&analysis, "\\b@12").unwrap_err();
assert!(refused.contains("`\\b` on line 12"), "{refused}");
}
}
+212
View File
@@ -0,0 +1,212 @@
//! 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)
}
+209
View File
@@ -0,0 +1,209 @@
//! 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.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use serde_json::{json, Value};
use vlog_parser::span::TextRange;
use vlog_parser::LineIndex;
use crate::project::Project;
use crate::render;
/// File texts read during one call, each with its line table.
#[derive(Default)]
pub struct Texts {
held: HashMap<PathBuf, Option<(String, LineIndex)>>,
}
impl Texts {
/// The text of `path` and its line table, read on first use; `None` for
/// a file that no longer reads as UTF-8.
pub fn get(&mut self, path: &Path) -> Option<(&str, &LineIndex)> {
let held = self.held.entry(path.to_path_buf()).or_insert_with(|| {
let text = std::fs::read_to_string(path).ok()?;
let lines = LineIndex::new(&text);
Some((text, lines))
});
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
/// spell `name`; `shown` is the span whose line is printed (a non-ANSI port's
/// body declaration rather than its header name).
pub fn checked_site(
project: &Project,
texts: &mut Texts,
path: &Path,
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() }) }
}
/// `text` on one line, cut at `cap` characters with `…`.
pub fn capped(text: &str, cap: usize) -> String {
let flat = render::one_line(text);
if flat.chars().count() <= cap {
return flat;
}
let cut: String = flat.chars().take(cap).collect();
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
}
/// Whether `c` may continue an identifier.
fn is_ident_char(c: char) -> bool {
c.is_ascii_alphanumeric() || c == '_' || c == '$'
}
/// The byte offset, within `line`, of the first whole-word occurrence of
/// `name` — a hit not glued to a neighbouring identifier character.
pub fn word_in(line: &str, name: &str) -> Option<usize> {
if name.is_empty() {
return None;
}
let mut from = 0;
while let Some(found) = line.get(from..).and_then(|rest| rest.find(name)) {
let start = from + found;
let end = start + name.len();
let before = line[..start].chars().next_back();
let after = line[end..].chars().next();
let glued = |c: Option<char>| c.is_some_and(is_ident_char);
if !glued(before) && (name.starts_with('\\') || !glued(after)) {
return Some(start);
}
from = start + name.len().max(1);
}
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_word_is_found_whole_and_never_inside_another() {
assert_eq!(word_in(" assign data_q = data;", "data"), Some(18));
assert_eq!(word_in("data_q", "data"), None);
assert_eq!(word_in("x = a.data", "data"), Some(6));
assert_eq!(word_in("\\a@1 x", "\\a@1"), Some(0));
assert_eq!(word_in("anything", ""), None);
}
#[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 ");
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;");
}
}
+2
View File
@@ -0,0 +1,2 @@
# The chain file is waived for line length.
waive --rule=line-length --location=rtl/chain.sv
+7
View File
@@ -0,0 +1,7 @@
# Lint settings the diagnostics tool must honour.
[lint]
select = ["line-length", "unused-signal", "no-tabs"]
waivers = ["lint/nav.waiver"]
[lint.line-length]
length = 40
+5
View File
@@ -0,0 +1,5 @@
module chain_a; chain_b u_b (); endmodule
module chain_b; chain_c u_c (); endmodule
module chain_c; chain_d u_d (); endmodule
module chain_d; chain_e u_e (); endmodule
module chain_e; missing_m u_missing (); endmodule
+2
View File
@@ -0,0 +1,2 @@
module checker_m (input logic [3:0] state_q);
endmodule
+14
View File
@@ -0,0 +1,14 @@
`include "defs.svh"
module core #(
parameter int W = 4
) (
input logic clk,
input logic [W-1:0] d,
output logic [W-1:0] q
);
logic [W-1:0] state_q;
logic spare;
always_ff @(posedge clk)
state_q <= `ADD(d, 1);
assign q = state_q;
endmodule
+1
View File
@@ -0,0 +1 @@
bind core checker_m u_chk (.state_q(state_q));
+2
View File
@@ -0,0 +1,2 @@
`define NAV_W 4
`define ADD(a, b = 1) ((a) + (b))
+6
View File
@@ -0,0 +1,6 @@
module dual (a, y);
input a;
output y;
wire y;
assign y = a;
endmodule
+9
View File
@@ -0,0 +1,9 @@
module top (input logic clk);
logic [`NAV_W-1:0] d, q0, q1;
logic [`NAV_W-1:0] peek;
core #(.W(4)) u_core0 (.clk, .d, .q(q0));
core #(
.W (8)
) u_core1 (.clk, .d, .q(q1));
assign peek = u_core0.state_q;
endmodule
+6
View File
@@ -0,0 +1,6 @@
module tree #(parameter int N = 4) ();
if (N > 1) begin : g_split
tree #(.N(N / 2)) u_left ();
tree #(.N(N / 2)) u_right ();
end
endmodule
+6
View File
@@ -0,0 +1,6 @@
class env;
sb s;
function void run();
s.count = 0;
endfunction
endclass
+6
View File
@@ -0,0 +1,6 @@
class sb;
int count;
function void add();
count++;
endfunction
endclass
+161
View File
@@ -0,0 +1,161 @@
//! 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.
//!
//! `#[ignore]`: it needs the checkout. Run with
//! `LUCISV_OPENTITAN=/path/to/opentitan tools/guard.sh -- cargo test -p
//! lucisv_mcp --test opentitan -- --ignored --nocapture`.
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio};
use std::time::Instant;
use serde_json::{json, Value};
/// The checkout: `LUCISV_OPENTITAN`, else the owner's usual path.
fn checkout() -> PathBuf {
std::env::var_os("LUCISV_OPENTITAN")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/Users/guoliangchen/repo/opentitan"))
}
/// One server over the checkout.
struct Session {
child: Child,
stdin: ChildStdin,
stdout: BufReader<ChildStdout>,
next_id: i64,
}
impl Session {
fn over(root: &Path) -> Session {
let mut child = Command::new(env!("CARGO_BIN_EXE_lucisv-mcp"))
.args(["--root", root.to_str().unwrap()])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap());
let mut session = Session { child, stdin, stdout, next_id: 0 };
session.request("initialize", json!({"protocolVersion": "2025-06-18"}));
session
}
fn request(&mut self, method: &str, params: Value) -> Value {
self.next_id += 1;
let line =
json!({"jsonrpc": "2.0", "id": self.next_id, "method": method, "params": params});
writeln!(self.stdin, "{line}").unwrap();
self.stdin.flush().unwrap();
let mut answer = String::new();
self.stdout.read_line(&mut answer).unwrap();
serde_json::from_str(&answer).unwrap()
}
/// A tool call that must succeed, with the wall time printed.
fn call(&mut self, tool: &str, arguments: Value) -> Value {
let started = Instant::now();
let reply = self.request("tools/call", json!({"name": tool, "arguments": arguments}));
let ms = started.elapsed().as_millis();
println!("census: {tool} {arguments} {ms} ms");
let result = reply["result"].clone();
assert_eq!(result["isError"], false, "{tool}: {result}");
result
}
/// [`Session::call`]'s text.
fn text(&mut self, tool: &str, arguments: Value) -> String {
let result = self.call(tool, arguments);
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 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.
fn assert_covers(ours: &[String], server: &[&str]) {
for location in server {
assert!(ours.iter().any(|hit| hit == location), "missing {location}: {ours:?}");
}
}
impl Drop for Session {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
/// `git status --porcelain` of the checkout, to prove it was only read.
fn status(root: &Path) -> Vec<u8> {
Command::new("git").arg("-C").arg(root).args(["status", "--porcelain"]).output().unwrap().stdout
}
#[test]
#[ignore = "needs an opentitan checkout (LUCISV_OPENTITAN)"]
fn opentitan_navigation_matches_the_language_server() {
let root = checkout();
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!({}));
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")];
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:?}");
// 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"}));
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",
];
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 = s.text("hierarchy", json!({"root": "top_earlgrey", "depth": 2, "limit": 500}));
assert!(top.contains("\n u_aes : aes #("), "{top}");
let fifo = s.text("definition", json!({"name": "prim_fifo_sync"}));
assert!(fifo.starts_with("hw/ip/prim/rtl/prim_fifo_sync.sv:"), "{fifo}");
let up = s.text("hierarchy", json!({"root": "prim_fifo_sync", "direction": "up", "depth": 1}));
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);
drop(s);
assert_eq!(status(&root), before, "the checkout was only read");
}
+3 -2
View File
@@ -275,7 +275,9 @@ fn qa_everything_but_initialize_and_ping_waits_for_the_handshake() {
}
assert!(s.pings());
s.initialize();
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 6);
// M2 added five tools (defines, definition, references, hierarchy,
// diagnostics) to M1's six.
assert_eq!(s.request("tools/list", json!({}))["result"]["tools"].as_array().unwrap().len(), 11);
}
#[test]
@@ -937,7 +939,6 @@ fn qa_rework_line_selectors_tolerate_trailing_spaces_and_refuse_overflow_by_name
}
#[test]
#[ignore = "QA finding 11"]
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
File diff suppressed because it is too large. Load diff
+323 -2
View File
@@ -22,11 +22,16 @@ struct Tree(PathBuf);
impl Tree {
fn new() -> Tree {
Tree::of("design")
}
/// A fresh copy of `tests/fixtures/<fixture>`.
fn of(fixture: &str) -> Tree {
let unique = NEXT_DIR.fetch_add(1, Ordering::SeqCst);
let dir =
std::env::temp_dir().join(format!("lucisv-mcp-wire-{}-{unique}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/design");
let source = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixture);
copy_tree(&source, &dir);
Tree(fs::canonicalize(dir).unwrap())
}
@@ -176,7 +181,12 @@ fn tools_list_describes_every_tool_for_the_agent() {
"unit_interface",
"outline",
"read_item",
"search_symbols"
"search_symbols",
"defines",
"definition",
"references",
"hierarchy",
"diagnostics"
]
);
assert!(reply["result"].get("nextCursor").is_none());
@@ -444,3 +454,314 @@ fn eof_ends_the_server_cleanly_and_a_bad_argument_exits_2() {
.unwrap();
assert_eq!(missing.status.code(), Some(2));
}
/// The `text` of every `definitions` entry a successful call returned.
fn sites(server: &mut Session, arguments: Value) -> Vec<String> {
let result = server.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()
}
/// A refused call's sentence.
fn refusal(server: &mut Session, tool: &str, arguments: Value) -> String {
let result = server.call(tool, arguments);
assert_eq!(result["isError"], true, "{tool}: {result}");
result["content"][0]["text"].as_str().unwrap().to_string()
}
#[test]
fn definition_answers_every_site_by_position_and_by_name() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
let text = server.text("definition", json!({"name": "core"}));
assert_eq!(text, "rtl/core.sv:2:8 module: module core #(\n");
// A hierarchical tail in the instantiating file lands on the internal net.
let tail = json!({"file": "rtl/top.sv", "line": 8, "name": "state_q"});
assert_eq!(sites(&mut server, tail), ["rtl/core.sv:9:17 var"]);
// A bare name declared in two units lists both, never one.
assert_eq!(
sites(&mut server, json!({"name": "state_q"})),
["rtl/checker_m.sv:1:37 port", "rtl/core.sv:9:17 var"]
);
assert_eq!(
sites(&mut server, json!({"name": "state_q", "unit": "core"})),
["rtl/core.sv:9:17 var"]
);
// A port that is also declared a net: the body line, the header and the
// redeclaration, all three.
assert_eq!(
sites(&mut server, json!({"file": "rtl/dual.sv", "line": 5, "name": "y"})),
["rtl/dual.sv:3:3 port", "rtl/dual.sv:1:17 port", "rtl/dual.sv:4:8 net"]
);
// A class member used through a handle in another file.
let member = json!({"file": "tb/env.sv", "line": 4, "col": 7});
assert_eq!(sites(&mut server, member), ["tb/sb.sv:2:7 var"]);
assert_eq!(sites(&mut server, json!({"name": "count"})), ["tb/sb.sv:2:7 var"]);
}
#[test]
fn definition_follows_includes_and_macros_and_refuses_what_it_cannot_follow() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
let include = server.text("definition", json!({"file": "rtl/core.sv", "line": 1, "col": 3}));
assert_eq!(include, "rtl/defs.svh:1:1 include: `include \"defs.svh\"\n");
let used = json!({"file": "rtl/core.sv", "line": 12, "name": "`ADD"});
assert_eq!(sites(&mut server, used), ["rtl/defs.svh:2:9 define"]);
let across = json!({"file": "rtl/top.sv", "line": 2, "col": 12});
assert_eq!(sites(&mut server, across), ["rtl/defs.svh:1:9 define"]);
assert_eq!(sites(&mut server, json!({"name": "`NAV_W"})), ["rtl/defs.svh:1:9 define"]);
fs::write(tree.path("rtl/lost.sv"), "`include \"gone.svh\"\nmodule lost; endmodule\n").unwrap();
let missing =
refusal(&mut server, "definition", json!({"file": "rtl/lost.sv", "line": 1, "col": 2}));
assert!(missing.contains("gone.svh") && missing.contains("directory is searched"), "{missing}");
let nothing =
refusal(&mut server, "definition", json!({"file": "rtl/core.sv", "line": 2, "col": 1}));
assert!(nothing.contains("rtl/core.sv:2:1"), "{nothing}");
assert!(refusal(&mut server, "definition", json!({"name": "absent"})).contains("`absent`"));
assert!(refusal(&mut server, "definition", json!({"line": 3})).contains("need `file`"));
let unit = json!({"file": "rtl/core.sv", "name": "q", "unit": "core"});
assert!(refusal(&mut server, "definition", unit).contains("`unit`"));
let past = json!({"file": "rtl/core.sv", "line": 99, "col": 1});
assert!(refusal(&mut server, "definition", past).contains("past the end"));
let absent = json!({"file": "rtl/core.sv", "line": 5, "name": "state_q"});
assert!(refusal(&mut server, "definition", absent).contains("not written on line 5"));
// A file written just now is found by name.
fs::write(tree.path("rtl/fresh.sv"), "module fresh_nav; endmodule\n").unwrap();
assert_eq!(sites(&mut server, json!({"name": "fresh_nav"})), ["rtl/fresh.sv:1:8 module"]);
}
#[test]
fn references_reach_bind_connections_hierarchical_tails_and_class_members() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
let state = server.call("references", json!({"name": "state_q", "unit": "core"}));
assert_eq!(
state["content"][0]["text"],
"rtl/core.sv\n 9:17 logic [W-1:0] state_q;\n 12:5 state_q <= `ADD(d, 1);\n 13:14 assign q = state_q;\nrtl/core_bind.sv\n 1:37 bind core checker_m u_chk (.state_q(state_q));\nrtl/top.sv\n 8:25 assign peek = u_core0.state_q;\n"
);
assert_eq!(state["structuredContent"]["total"], 5);
assert_eq!(
state["structuredContent"]["hits"][3],
json!({"file": "rtl/core_bind.sv", "line": 1, "col": 37, "text": "bind core checker_m u_chk (.state_q(state_q));"})
);
// From the use sites (QA finding 1): the tail in top.sv and the handle
// chain in env.sv answer exactly what their declarations answer.
let tail = json!({"file": "rtl/top.sv", "line": 8, "name": "state_q"});
assert_eq!(server.call("references", tail)["content"], state["content"]);
let chain = json!({"file": "tb/env.sv", "line": 4, "name": "count"});
let from_use = server.text("references", chain);
let count = server.text("references", json!({"file": "tb/sb.sv", "line": 4, "name": "count"}));
assert_eq!(from_use, count);
assert_eq!(
count,
"tb/env.sv\n 4:7 s.count = 0;\ntb/sb.sv\n 2:7 int count;\n 4:5 count++;\n"
);
let no_decl = json!({"name": "core", "include_declaration": false, "limit": 2});
let core = server.text("references", no_decl);
assert_eq!(core, "rtl/core_bind.sv\n 1:6 bind core checker_m u_chk (.state_q(state_q));\nrtl/top.sv\n 4:3 core #(.W(4)) u_core0 (.clk, .d, .q(q0));\n… and 1 more\n");
let dual = server.call("references", json!({"name": "y", "unit": "dual"}));
assert_eq!(dual["structuredContent"]["total"], 4);
let twice = refusal(&mut server, "references", json!({"name": "state_q"}));
assert!(twice.contains("rtl/checker_m.sv:1") && twice.contains("rtl/core.sv:9"), "{twice}");
let macro_use = json!({"file": "rtl/core.sv", "line": 12, "name": "`ADD"});
assert!(refusal(&mut server, "references", macro_use).contains("is a macro"));
let flag = json!({"name": "core", "include_declaration": "yes"});
assert!(refusal(&mut server, "references", flag).contains("true or false"));
}
#[test]
fn hierarchy_walks_down_and_up_and_terminates_on_recursion() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
let tops = server.text("hierarchy", json!({}));
assert_eq!(
tops,
"chain_a rtl/chain.sv:1\n u_b : chain_b\n u_c : chain_c\n u_d : chain_d\nchecker_m rtl/checker_m.sv:1\ndual rtl/dual.sv:1\ntop rtl/top.sv:1\n u_core0 : core #(.W(4))\n u_core1 : core #( .W (8) )\n"
);
let deep = server.text("hierarchy", json!({"root": "chain_a", "depth": 20}));
let capped = refusal(&mut server, "hierarchy", json!({"root": "chain_a", "depth": 21}));
assert!(capped.contains("`depth`") && capped.contains("from 1 to 20"), "{capped}");
assert!(deep.ends_with(" u_missing : missing_m (not indexed)\n"), "{deep}");
let recursive = server.call("hierarchy", json!({"root": "tree", "depth": 20}));
assert_eq!(
recursive["content"][0]["text"],
"tree rtl/tree.sv:1\n u_left : tree #(.N(N / 2)) (recursive)\n u_right : tree #(.N(N / 2)) (recursive)\n"
);
assert_eq!(recursive["structuredContent"]["nodes"][1]["note"], "recursive");
let up = server.call("hierarchy", json!({"root": "core", "direction": "up"}));
assert_eq!(
up["content"][0]["text"],
"core rtl/core.sv:2\n top.u_core0 #(.W(4)) rtl/top.sv:4\n top.u_core1 #( .W (8) ) rtl/top.sv:7\n"
);
assert_eq!(
up["structuredContent"]["nodes"][2],
json!({"depth": 1, "instance": "u_core1", "module": "core", "parent": "top", "file": "rtl/top.sv", "line": 7, "overrides": "#( .W (8) )", "note": null})
);
let chain = server.text("hierarchy", json!({"root": "chain_e", "direction": "up", "depth": 2}));
assert_eq!(
chain,
"chain_e rtl/chain.sv:5\n chain_d.u_e rtl/chain.sv:4\n chain_c.u_d rtl/chain.sv:3\n"
);
assert!(
refusal(&mut server, "hierarchy", json!({"direction": "up"})).contains("needs a `root`")
);
assert!(refusal(&mut server, "hierarchy", json!({"root": "nope"})).contains("`nope`"));
}
#[test]
fn diagnostics_follow_the_projects_lint_config_and_filters() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
// `[lint] select` and `[lint.line-length] length = 40` from lucisv.toml;
// rtl/chain.sv is waived for line length by lint/nav.waiver.
let all = server.call("diagnostics", json!({}));
assert_eq!(
all["content"][0]["text"],
"rtl/checker_m.sv\n 1:41 style line is 45 characters; the limit is 40 [line-length]\nrtl/core.sv\n 10:17 warning `spare` is declared but never used [unused-signal]\nrtl/core_bind.sv\n 1:41 style line is 46 characters; the limit is 40 [line-length]\nrtl/top.sv\n 4:41 style line is 43 characters; the limit is 40 [line-length]\n"
);
assert_eq!(
all["structuredContent"]["diagnostics"][1],
json!({"filename": "rtl/core.sv", "rule": "unused-signal", "severity": "warning",
"message": "`spare` is declared but never used",
"location": {"line": 10, "column": 17}, "end_location": {"line": 10, "column": 22},
"range": {"start": 184, "end": 189}, "fix": null})
);
let warnings = server.call("diagnostics", json!({"severity": "warning"}));
assert_eq!(warnings["structuredContent"]["total"], 1);
let selected = server.text("diagnostics", json!({"file": "rtl/core.sv", "rules": "no-tabs"}));
assert_eq!(selected, "no findings\n");
let capped = server.text("diagnostics", json!({"limit": 1}));
assert!(capped.ends_with("… and 3 more\n"), "{capped}");
assert!(refusal(&mut server, "diagnostics", json!({"rules": "bogus-rule"}))
.contains("unknown rule: bogus-rule"));
// No lucisv.toml: the workspace default set, parse errors first.
let design = Tree::new();
let mut plain = Session::over(&design);
plain.initialize();
let broken = plain.call("diagnostics", json!({"file": "rtl/broken.sv"}));
let first = &broken["structuredContent"]["diagnostics"][0];
assert_eq!(
(first["rule"].as_str(), first["severity"].as_str()),
(Some("parse-error"), Some("error"))
);
assert_eq!(first["location"], json!({"line": 2, "column": 14}));
}
#[test]
fn defines_lists_one_file_one_macro_or_the_project() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
let table = "rtl/defs.svh\n 1 `define NAV_W 4\n 2 `define ADD(a, b = 1) ((a) + (b))\n";
assert_eq!(server.text("defines", json!({})), table);
assert_eq!(server.text("defines", json!({"file": "rtl/defs.svh"})), table);
let add = server.call("defines", json!({"name": "`ADD"}));
assert_eq!(
add["structuredContent"]["defines"],
json!([{"file": "rtl/defs.svh", "line": 2, "name": "ADD", "kind": "define", "params": ["a", "b = 1"], "body": "((a) + (b))"}])
);
assert_eq!(server.text("defines", json!({"name": "NOPE"})), "no defines\n");
fs::write(tree.path("rtl/undef.sv"), "`define T 1\n`undef T\n").unwrap();
let local = server.text("defines", json!({"file": "rtl/undef.sv"}));
assert_eq!(local, "rtl/undef.sv\n 1 `define T 1\n 2 `undef T\n");
}
#[test]
fn resources_list_and_read_the_overview_rules_units_and_outlines() {
let tree = Tree::of("nav");
let mut server = Session::over(&tree);
server.initialize();
let listed = server.request("resources/list", json!({}));
let uris: Vec<&str> = listed["result"]["resources"]
.as_array()
.unwrap()
.iter()
.map(|r| r["uri"].as_str().unwrap())
.collect();
assert_eq!(uris, ["lucisv://overview", "lucisv://rules"]);
let templates = server.request("resources/templates/list", json!({}));
let patterns: Vec<&str> = templates["result"]["resourceTemplates"]
.as_array()
.unwrap()
.iter()
.map(|r| r["uriTemplate"].as_str().unwrap())
.collect();
assert_eq!(patterns, ["lucisv://unit/{name}", "lucisv://file/{path}/outline"]);
let read =
|server: &mut Session, uri: &str| server.request("resources/read", json!({"uri": uri}));
let unit = read(&mut server, "lucisv://unit/core");
let content = &unit["result"]["contents"][0];
assert_eq!(
(content["uri"].as_str(), content["mimeType"].as_str()),
(Some("lucisv://unit/core"), Some("text/plain"))
);
assert!(content["text"].as_str().unwrap().starts_with("module core rtl/core.sv:2\n"));
let outline = read(&mut server, "lucisv://file/rtl/top.sv/outline");
assert!(outline["result"]["contents"][0]["text"]
.as_str()
.unwrap()
.starts_with("rtl/top.sv\n module top 1-9\n"));
let overview = read(&mut server, "lucisv://overview");
assert!(overview["result"]["contents"][0]["text"]
.as_str()
.unwrap()
.contains("files: 10 indexed"));
let rules = read(&mut server, "lucisv://rules");
assert_eq!(rules["result"]["contents"][0]["mimeType"], "text/markdown");
assert!(rules["result"]["contents"][0]["text"].as_str().unwrap().contains("line-length"));
for missing in [
"lucisv://unit/zzz",
"lucisv://nope",
"https://example.com/x",
"lucisv://file/../x/outline",
] {
let refused = read(&mut server, missing);
assert_eq!(refused["error"]["code"], -32002, "{missing}: {refused}");
assert!(refused["error"]["message"].as_str().unwrap().contains(missing), "{refused}");
}
assert_eq!(server.request("resources/read", json!({}))["error"]["code"], -32602);
}
#[test]
fn an_escaped_name_is_followed_across_files() {
// Escaped identifiers are not in the word census, so `references` hands
// the engine every indexed file for them rather than a narrowed set.
let tree = Tree::of("nav");
fs::write(tree.path("rtl/esc.sv"), "module \\my-mod (input logic a);\nendmodule\n").unwrap();
fs::write(
tree.path("rtl/esc_user.sv"),
"module esc_user;\n logic a;\n \\my-mod u_m (.a(a));\nendmodule\n",
)
.unwrap();
let mut server = Session::over(&tree);
server.initialize();
let found = server.text("references", json!({"name": "\\my-mod"}));
assert_eq!(
found,
"rtl/esc.sv\n 1:8 module \\my-mod (input logic a);\nrtl/esc_user.sv\n 3:3 \\my-mod u_m (.a(a));\n"
);
let at = json!({"file": "rtl/esc_user.sv", "line": 3, "col": 4});
assert_eq!(sites(&mut server, at), ["rtl/esc.sv:1:8 module"]);
}
+766
View File
@@ -0,0 +1,766 @@
# mcp-navigation
TODO-MCP.md **M2** — the navigation, diagnostics and resource half of
`lucisv-mcp`: tools `definition`, `references`, `hierarchy`, `diagnostics`,
`defines`, and the `lucisv://` resources. Design: `docs/mcp/PLAN.md` §4.2,
§4.3 and §4.5. The transport and `Project` they run on are
`docs/features/mcp-transport`; the rendering contract is
`docs/features/mcp-read-tools`'s.
## Goal
Let an agent ask the questions it otherwise answers by grepping and reading
whole files — where is this declared, who uses it, what instantiates what,
what does `lucisv check` say about this file, what does this macro expand
from — and get a compact, root-relative answer in one call. Every answer is
a composition of existing library queries (`vlog_semantic`'s index and
overlay, `vlog_refactor::find_references`, `vlog_linter`'s run); no language
knowledge lives in the MCP crate. The same answers the read tools give are
also addressable as `lucisv://` resources for a host that attaches context
instead of calling tools.
## Assumptions
- **One selector for `definition` and `references`** (`tools/select.rs`):
`file` + `line` + `col` (1-based, **byte** column — the crate's one column
unit; a column past the line's end is refused naming the line's length,
one past the last byte is the end and allowed); or `file` + `line` +
`name` — the first **token** on that line spelling `name` (an identifier,
or a macro use when written `` `NAME``), so a comment or a string never
stands in for the code; a name found only inside a macro call's argument
text is refused ("inside a macro argument, which lucisv does not resolve;
give `col` on a plain use"); or `file` + `name` — the name's one
declaration in that file; else, when the file declares none, its uses,
provided they all resolve to one declaration (uses naming different
declarations are refused listing a line per target, "`sig` on line 2 →
leaf.sv:1, line 6 → other.sv:1; add `line`"); else its first macro use; a
name declared twice in the file is refused listing the lines; or a bare
`name` with an optional `unit`, looked up in the index. `unit` with
`file` is refused (two selectors at once); `line`/`col` without `file` is
refused.
- **`definition` is the language server's ladder** (`nav.rs::at_position`):
an `` `include`` line → the named file **beside the including file only**
(no include-directory ladder: the MCP has no `+incdir` configuration to
honour, and a miss says so); a macro use → the file's own last
`` `define`` when it has one, else every indexed definition (the include
graph is not modelled, so none is picked); then the file's symbol table,
then the workspace overlay (`resolve_external` computed per call against
the current index — never cached, because the index moves under an
unchanged file). A local declaration answers its completing declaration
first (a non-ANSI port's body line), then its name, then every
redeclaration the binder folded into it (`Semantics::duplicates`, so
`output y; wire y;` lists the port *and* the net — the "both a port and
an internal net" case), one site per line. By name: the unit declarations,
the connection-surface members (`workspace_symbols` filtered to the exact
name), and the hierarchical-only members (`hierarchical_declarations`);
with `unit`, `member_in(unit, name, Surface::Hierarchical)`; `` `NAME``
(or a name nothing else declares) answers the macro definitions. The
by-name form reports what the index records — a redeclaration inside a
unit is visible only through the position form, which has the file's own
table. Ambiguity is always a list.
- **Every indexed span is re-checked against the bytes before it is
printed** (`tools/source.rs::checked_site`): the site is shown only when
the file still spells the name there, so a stale index omits a site,
never mislocates one (the `spells_exactly` rule of
`docs/features/references-hierarchical-surface`). One read per file per
call (`source::Texts`).
- **`references` hands the engine the whole indexed file set, always**
(lead's ruling on QA finding 1, replacing the M2 narrowing rule): every
indexed file plus the selected one, read from disk at call time
(`nav.rs::all_files`). A use resolves through files that never spell its
name — `u_a.u_b.sig` needs the file declaring `u_b`, `e.s.count` needs the
class declaring `s` — so no narrowing by the name's census is sound, and a
narrowed set also turned an unresolvable use into the false refusal
"declared outside the files lucisv indexes". **Measured cost** (release,
whole opentitan checkout, 3 944 files, after the index exists; each call
re-reads and re-parses the set): `entropy_masking_req` 1.62 s, `state_q`
from `entropy_src_main_sm.sv` 1.89–1.92 s, the `aes` instantiation in
`tb.sv` 1.70 s, `clk_i` from `prim_fifo_sync.sv` 2.55 s (83 hits); peak
RSS of the session ~0.98 GB. Handshake MCP-7 is the way down. The
engine's refusals are said as ours: prefixed "lucisv cannot follow this
position: ", and the rename wording they share with `rename` replaced
(`nav.rs::engine_refusal`). A macro use — by position or by a bare name
that only a `` `define`` declares — is refused with a pointer to
`defines` (the engine follows declarations, not macros).
- **`hierarchy` is the textual instance census** (`WorkspaceIndex::
instantiations()`, the edges the editor's hierarchy view and call
hierarchy read): `generate` and `` `ifdef`` branches all appear; an
instantiation at file scope (a `bind`) is not an edge, so a bound module
is a "top". Down: `instance : module #(overrides)`, a module instantiated
N times under one parent listed N times; a module the index does not hold
is marked `(not indexed)`; a module declared more than once is marked
`(declared N times)` and **not expanded** (which declaration an instance
means is the elaborator's choice); a module already on the path is marked
`(recursive)` and not expanded (a self-instantiating `generate` tree
terminates at once); `depth` defaults to 3 and the schema accepts 1..=20
(`Ty::Range`, so `inputSchema` carries `maximum: 20` and 21 is refused
naming `depth`); the walk stops at 50 000 nodes and says so. Up: `parent.instance #(overrides) file:line`
per instantiation of `root`, recursively. Without `root`, down starts at
every module nothing instantiates (a module that only instantiates itself
is therefore not a default root; name it).
- **Override slicing**: the text between the instantiated module's name at
the site (`InstantiationEdge::site_span`) and the statement's **first**
instance name (`edge.instances[0].name_span` — the `#(...)` belongs to the
whole statement), read from the file now, comments
dropped (`source::without_comments`, strings kept), whitespace collapsed,
kept only when it starts with `#` and the file still spells the module
name at the site. The text line caps it at 200 characters with `…`
(opentitan's `earlgrey_pd_main` instance carries hundreds of overrides);
`structuredContent.nodes[].overrides` carries all of it. `leaf #(.W(2))
u_a (), u_b ();` shows `#(.W(2))` on both instances.
- **Structured `hierarchy`** is a flat, pageable node list in tree order,
each `{depth, instance, module, parent, file, line, overrides, note}`
(`module` is always the instantiated module; `parent` is set in the `up`
direction) — a nested tree cannot be paged with `limit`/`offset`, and the
depth field reconstructs it.
- **`diagnostics` answers what `lucisv check .` — the whole-tree run, CI's
run — reports** (lead's ruling on QA finding 5): the cross-file rules
(`unknown-port`, `unused-signal`, …) always run, also when one `file` is
asked for, so one file's answer is that file's share of the whole-tree
run, not `lucisv check <file>` (which, holding one file, runs none of
them). The tool description says so. The config ladder is `lucisv
check`'s, per file:
`Discovery::for_file` finds the `lucisv.toml` governing it; its `[lint]
select` is the base set unless the `rules` argument is given (which
replaces it, like `--select`); `[lint] ignore` then removes; the run is
`select_rules(select, ignore, workspace = true)`; `[lint.<rule>]` options
go through `RuleOptions::set_raw` (a bad one is refused naming
`file:line`, as the CLI fails); `[lint] waivers` files are read with
`ExternalWaivers::read` and applied by `lint_with`; the line length and
tab width are `line-length`/`indent` else the formatter's defaults (100,
2). `severity` filters the findings afterwards. The workspace rules'
cross-file questions are answered by the project index (`Mentions`, the
server's `IndexMentions`): one file asks `mentioned_outside` directly; the
whole-project form builds a word → (file count, first file) census once
per call from `FileFacts::words`, because the per-question walk over
3 944 records would cost minutes. Parse errors come first as rule
`parse-error`, severity `error`, from the tolerant parse the file's
analysis already holds; the JSON array uses the CLI's field names
(`filename`, `rule`, `severity`, `message`, `location{line,column}`,
`end_location`, `range{start,end}`, `fix`) with `filename`
root-relative. **Missing-closer warnings are not offered**: they are the
language server's `pairs::missing_end_diagnostics`, not a library API,
and the tolerant tree's diagnostics alone do not carry them. The
whole-project form lints every indexed file (1.9 s on opentitan, 2 100
findings) and returns the first `limit` (default 200) with the total.
**Unused external waivers**: the whole-project form, being a complete
run, reports each `[lint] waivers` directive that suppressed nothing as an
`unused-waiver` finding against the waiver file (`ExternalWaivers::unused`
over the usage every file's `lint_with` returned, per config; the
severity the linter stamps, as the CLI does), when `unused-waiver` is
among the run's rules. The single-file form cannot know — a directive may
fire in a file it did not lint — and reports none.
- **`defines`**: `file` → that file's table as on disk (its `` `undef``s
included); `name` → every indexed definition of it (`find_define`); neither
→ every indexed `` `define``, paged. Each row `line `define NAME(params)
body`, the body one-lined and cut at 200 characters (UVM macro bodies run
to hundreds of lines). **One-step expansion with `args` is not offered**:
the server's `expand.rs` is ~260 production lines of argument splitting,
default parameters, string/escape handling and token pasting — not the
~60 lines the lane allowed, and a second copy of it is exactly the
duplication CLAUDE.md forbids. See Handshakes.
- **Resources** (`src/resources.rs`): `lucisv://overview` (`text/plain`,
`project_overview`'s text, walking first as the tool does) and
`lucisv://rules` (`text/markdown`, `vlog_linter::rules_markdown()`, no
index needed) in `resources/list`; `lucisv://unit/{name}` (`unit_interface`'s
text) and `lucisv://file/{path}/outline` (`outline`'s text, `path`
root-relative, `%XX` decoded) in `resources/templates/list`. A read runs
the read tool's own handler, so the two can never disagree. Any other
URI, and one naming nothing (an unknown unit, a path outside the roots),
is JSON-RPC `-32002` "resource not found: <uri> (<reason>)"; a missing
`uri` is `-32602`. `initialize` already declared `resources: {}`; no
`subscribe`/`listChanged` is offered.
- **A boolean argument type** (`tools::Ty::Bool`) was added to the registry
for `include_declaration`; it validates like the others (`true or false`
in the refusal).
- **`Analysis` now keeps the tokens and the `` `define`` table**
(`project/analysis.rs`): the lint context and the macro lookups need the
tokens the parse consumed, so they are cloned once before the parse.
## Handshakes
Consumed (public APIs only; no library crate was modified):
- `vlog_semantic`: `Semantics::{symbols_named, symbol, symbol_at,
reference_at, reference_id_at, references, duplicates, scope}`,
`resolve_external`, `ExternalResolutions::{definition_of, get}`,
`ExternalTarget::best`, `WorkspaceIndex::{units, member_in,
workspace_symbols, hierarchical_declarations, files_mentioning,
files_naming_in_macros, mentioned_outside, find_define, defines,
instantiations, instantiations_of, instantiable_units, members_of,
facts_for, file_id, files, path}`, `FileFacts::words`,
`PackageExports::exports`.
- `vlog_parser`: `defines::{collect_defines, DefineTable, Define,
DefineKind}`, `token::{Token, TokenKind}`, `LineIndex::{offset,
line_range, line_col}`.
- `vlog_refactor::find_references`.
- `vlog_linter`: `LintContext::{from_parse, with_semantics, with_options,
with_line_length, with_tab_width, with_oracle}`, `lint_with`,
`select_rules`, `RuleOptions::set_raw`, `ExternalWaivers::{read, absorb}`,
`MentionOracle`, `ModuleInterface`, `rules_markdown`.
- `lucisv_core::config::{Discovery::for_file, FileConfig}`;
`vlog_formatter::Config::default` (the line-length and indent defaults).
Requests (none blocking):
- **MCP-7 → `vlog_refactor`: a `find_references` variant taking `&dyn
KnownFacts`** (as `rename_traced_with` does), so a caller holding a
current `FileFacts` record per text — M6's cache, or the MCP's own index —
can skip re-parsing the whole set. Until then every `references` call
parses all 3 944 opentitan files (~1.6–2.6 s release): the price of a
correct answer (QA finding 1).
- **MCP-5 → `vlog_parser` (candidate): lift the server's `expand.rs`
(`single_step`, `has_macro_use`, `CAP`) into `vlog_parser::defines`** as a
pure move, so `defines` can offer the one-step expansion the plan lists
and hover keeps its own. Until then `defines` answers the table only.
- **MCP-6 → `lucisv_server` (informational, a candidate finding):** on
opentitan, `textDocument/references` at the `aes` instantiation and its
`.clk_i` connection in `hw/ip/aes/dv/tb/tb.sv` answers 11 and 9
locations; `references` here answers 14 and 12 — the same locations plus
the three top-level instantiations in
`hw/top_{earlgrey,darjeeling,englishbreakfast}/rtl/autogen/*_pd_main.sv`
(`aes #(` at 2069/1521/933 and their `.clk_i(clkmgr_clocks_i.clk_main_aes)`),
which are real (`hierarchy` `up` from `aes` lists `earlgrey_pd_main.u_aes`).
Stable after a 30 s settle, so not an indexing race. Not investigated in
this lane.
- **Resource wording**: `lucisv://unit/{name}` for a unit declared twice
answers `-32002` with `unit_interface`'s sentence, its "pass `file`"
replaced by "call the unit_interface tool with its file argument to pick
one" (`resources.rs`), since a URI has no `file` argument.
- **MCP-3 (PLAN §7) stays a candidate:** `hierarchy` walks
`instantiations()` keyed by the owner's `(FileId, name_span.start)`
exactly as `design_hierarchy::snapshot` does; they agree on the fixtures
and on `top_earlgrey`.
- Wanted but worked around: a `Semantics::symbol_id(&Symbol)` would save
`local_sites` a `symbol_at` lookup.
## Status / TODO
- [x] `definition`: position / line+name / file+name / bare name (+`unit`)
selector; `` `include`` line; macro use; local (detail, name,
redeclarations); cross-file overlay; by-name units, members,
hierarchical members, macros; lists, never guesses
- [x] `references`: `find_references` over the whole indexed set; grouped,
`line:col text`, `limit`/`offset`, `include_declaration`; one-
declaration rule for a bare name; macro refusal
- [x] `hierarchy`: down (default: every top) / up, `depth` (3, cap 20),
overrides, `(not indexed)`, `(declared N times)`, `(recursive)`,
node cap, flat structured list
- [x] `diagnostics`: parse errors + lint under the per-file `lucisv.toml`,
`rules`, `severity`, waivers, index oracle, census for the workspace
form, CLI JSON names, `limit`/`offset`
- [x] `defines`: file / name / project table, body capped; expansion not
offered (MCP-5)
- [x] resources: list, templates, read, `-32002`
- [x] QA rework: findings 1–11 fixed or ruled, `qa_m2.rs` 32/32 green
- [x] carry-over: M1 QA finding 11 (`read_item` `\a@12`) fixed; the QA test
un-ignored
- [x] wire tests over the new `tests/fixtures/nav` tree; the opentitan
census (`tests/opentitan.rs`, `#[ignore]`)
- [x] gates through `tools/guard.sh`; sizes
## Work log
**2026-09-23 (dev, M2).**
Built: `src/tools/nav.rs` (selector, `definition`, `references`),
`src/tools/hierarchy.rs`, `src/tools/diagnostics.rs`, `src/tools/defines.rs`,
`src/tools/source.rs` (per-call file texts, checked sites, the word finder,
comment stripping and capping shared by the four), `src/resources.rs`;
`tools/mod.rs` registers the five tools and gains `Ty::Bool`/`Args::flag`;
`rpc.rs` answers the three `resources/*` methods from `resources.rs`;
`project/analysis.rs` keeps tokens and defines and computes the overlay on
request (`Analysis::external`), with `token_at` and `line_text`.
Decisions and deviations from PLAN/TODO:
1. **A new fixture tree `tests/fixtures/nav`** instead of extending
`tests/fixtures/design`: M1's wire and QA tests pin that tree's file
count, unit counts, top modules and paging (`… and 6 more`), and a
lucisv.toml with `[lint]` there would change them. The new tree has every
case the brief listed: a `bind` connecting a bare net (`core_bind.sv`), a
`u_core0.state_q` tail (`top.sv`), a port that is also a net
(`dual.sv`), a class member used through a handle in another file
(`tb/sb.sv`, `tb/env.sv`), macros defined in an included `.svh` and used
in two files, `core` instantiated twice under `top` with different
`#(...)`, a self-instantiating `generate` tree (`tree.sv`), a five-deep
chain ending in a missing module (`chain.sv`), and a `lucisv.toml` with
`[lint] select`, `[lint.line-length] length = 40` and a waiver file.
2. **Two files beyond the brief's list**: `src/tools/defines.rs` (PLAN put
`defines` in `read.rs`, M1's file) and `src/tools/source.rs` (helpers
the four tools share; without it `hierarchy.rs` and `defines.rs` would
import from `nav.rs`). `src/main.rs` gained the one line `mod
resources;` — unavoidable for a new top-level module.
3. **Two edits to existing tests, both forced by the lane**: `wire.rs`'s
`tools_list_describes_every_tool_for_the_agent` lists the eleven tools;
`qa_m1.rs`'s `qa_everything_but_initialize_and_ping_waits_for_the_handshake`
asserted `tools/list` has 6 entries, now 11 (with a comment). Neither
weakens an assertion.
4. **The selector grew `file` + `line` + `name` and `file` + `name`**
beyond the plan's `file,line,col | name,unit?` — agents rarely know byte
columns. `col` stays exact.
5. **`references` refuses a macro use** (the engine would say "no symbol to
rename", which reads wrong in a references answer) and points at
`defines`.
6. **`hierarchy` takes `limit`/`offset`** and a 50 000-node cap (PLAN §4.5:
every list is capped) and does not expand a module declared more than
once (opentitan's technology variants: `pinmux_jtag_breakout` ×4).
7. **Missing-closer warnings and one-step expansion are not offered**
(Assumptions; MCP-5).
8. **Carry-over, M1 QA finding 11** (`tools/read_item.rs::select`): when
the `@LINE` reading matches nothing and the name starts with `\`, the
whole spelling (after an optional `kind:`) is tried as the name; the
first refusal stands if that fails too. Unit test
`an_escaped_name_ending_in_at_digits_is_its_own_name_when_no_line_matches`;
`qa_rework_an_escaped_name_ending_in_at_digits_is_selectable_by_itself`
un-ignored and green.
The opentitan census (`tests/opentitan.rs`, one session over the whole
checkout, read-only). Wall time per call, debug build (the test) / release
build (the same calls through a stdio driver):
| call | debug | release |
|---|---|---|
| first call (index build, 3 944 files) | 10.1–10.4 s | 1.9 s |
| `references` `entropy_masking_req` from `aes.sv` | 62 ms | 18 ms |
| `references` `state_q` from `entropy_src_main_sm.sv:42` | 928 ms | 165 ms |
| `references` `aes` at `tb.sv:45` | 266 ms | ~50 ms |
| `references` `.clk_i` at `tb.sv:46` | 10.0 s | 1.6 s |
| `references` `clk_i` from `prim_fifo_sync.sv` | 9.9 s | 1.6 s |
| `hierarchy` down `top_earlgrey` depth 2 | 22–384 ms | 10 ms |
| `hierarchy` up `prim_fifo_sync` depth 1 (77 instances) | 21 ms | 7 ms |
| `definition` `prim_fifo_sync` | 21 ms | 8 ms |
| `diagnostics` `hw/ip/aes/rtl/aes.sv` | 8 ms | 7 ms |
| `diagnostics` whole project (2 102 findings) | — | 1.9 s |
Parity with the language server (release `lucisv-server` rebuilt at this
commit, same checkout, `textDocument/references`/`definition` at the same
positions): `entropy_masking_req` 6 = 6 locations (`aes_bind.sv:45,54`
included); `state_q` 5 = 5 (`entropy_src_core.sv:3092` included); `aes` 14
⊇ 11 and `.clk_i` 12 ⊇ 9 (MCP-6); every `definition` equal. `hierarchy`
down from `top_earlgrey` depth 2 lists `earlgrey_pd_main :
earlgrey_pd_main` and under it `u_aes : aes #(...)`. `diagnostics` on
`aes.sv` finds nothing, as `lucisv check` does; `uartdpi.sv`'s three
`wire-reg-mixup` findings match the CLI's. `git -C opentitan status
--porcelain` was byte-identical before and after (the owner's three
modified files, untouched).
Tests: unit 28 → 37 (source 3, defines 2, resources 1, analysis 1,
read_item 1, tools/mod 1 extended; hierarchy 1); `wire.rs` 11 → 19;
`qa_m1.rs` 50 + 1 ignored → 51 + 0; `opentitan.rs` 1 (ignored).
Sizes (production lines: non-blank, non-comment, before `#[cfg(test)]`):
`tools/nav.rs` 446, `tools/hierarchy.rs` 311, `tools/diagnostics.rs` 293,
`tools/defines.rs` 158, `tools/source.rs` 134, `resources.rs` 112,
`tools/mod.rs` 146, `rpc.rs` 241, `project/analysis.rs` 77,
`tools/read_item.rs` 213, `main.rs` 68. No function over 50 lines.
Gates (all through `tools/guard.sh`, one cargo invocation at a time):
`cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p lucisv_mcp
--all-targets` `Finished`, no warnings; `cargo test -p lucisv_mcp` unit 37
passed, `opentitan` 0 passed / 1 ignored, `qa_m1` 51 passed, `wire` 19
passed; `cargo test --workspace` exit 0 in 238 s, **4 566 passed, 0 failed,
47 ignored** (4 548 before). The ignored census, run by hand as above:
1 passed in 32 s.
**2026-09-23 (dev, M2 rework after QA).** The lead's rulings on the QA
findings, as applied; every `qa_m2.rs` test is un-ignored and green (32).
- **1 (blocking) — ruled: the whole set.** `tools/nav.rs::all_files`
replaces `in_scope`; `leaves_file` and `spelled_at` are gone (nothing else
used them). The false "declared outside the files lucisv indexes"
refusal went with the narrowing. Wire test
`references_reach_bind_connections_hierarchical_tails_and_class_members`
now also asks from the use sites (`top.sv:8` tail, `env.sv:4` handle
chain) and asserts the declaration's answer. Handshake MCP-7 filed;
opentitan timings below.
- **2 + 3 (blocking) — fixed.** The selector moved to a new
`tools/select.rs` (nav.rs had reached 446 lines); `select.rs::on_line`
picks by token and refuses a name found only in a macro argument.
- **4 (blocking) — fixed.** `hierarchy.rs`: `Child::first` (the statement's
first instance name) ends the override slice; `Child::of` builds both
directions' children. Unit test extended with `#(.W(2)) u_a (), u_b ()`.
- **5 — ruled: whole-tree semantics kept.** Tool description and
Assumptions say so; no code change. `qa_finding_5_…` was written to
assert single-file parity "delete it if the project-wide semantics is
kept": I rewrote it (renamed
`qa_finding_5_one_files_diagnostics_match_lucisv_check_of_the_whole_tree`)
to assert the ruling — `unknown-port` reported for `top.sv` alone —
rather than delete it, so the ruling stays pinned.
- **6 — fixed.** `diagnostics.rs`: `Run::used` (a `RefCell<WaiverUse>`)
merges every file's usage; `Runs::unused_waivers` reports after the
whole-project loop; `lint_finding` takes a `LineIndex` so a waiver file's
findings render like any other. `Runs::held` became a `BTreeMap` so the
order is stable.
- **7 — fixed.** `tools/mod.rs`: `Ty::Range { min, max }` (schema
`minimum`/`maximum`, refusal "an integer from 1 to 20"); `hierarchy`'s
`depth` uses it and the silent `.min(MAX_DEPTH)` is gone. `wire.rs`'s
depth-99 call became 20 plus a 21-is-refused assertion; `tools/mod.rs`
unit test pins the schema.
- **8 — fixed.** `select.rs::at_column` refuses "line N is L bytes long;
`col` C is past its end".
- **9 — fixed.** `nav.rs::engine_refusal` prefixes and rewords the
engine's six rename-worded sentences (`vlog_refactor` untouched); unit
test `engine_refusals_are_prefixed_and_never_speak_of_renaming`. A bare
macro-only `name` is now refused as a macro too (QA's side note).
- **10 — fixed.** `resources.rs` rewrites the "pass `file`" clause.
QA's test asserts the message does not contain `` `file` `` (backticked),
so the wording is "with its file argument" rather than the lead's
backticked `` `file` `` — same meaning, test and ruling both honoured.
- **11 (blocking) — fixed.** `select.rs::one_use` resolves every use of the
name in a file that declares none (`Analysis::external` +
`definition_of`); two or more distinct targets are refused listing a
line per target.
Whole-set `references` on opentitan (release, stdio driver, after the
index): `entropy_masking_req` 1.62 s, `state_q` 1.92 s / 1.89 s, `aes` at
`tb.sv:45` 1.70 s, `clk_i` from `prim_fifo_sync.sv` 2.55 s; debug (the
census test): 9.8 s, 12.1 s, 10.9 s, 14.2–14.6 s. Answers unchanged from
the narrowed ones on every census symbol (6, 5, 14, 12 hits; the census
test's assertions still pass). The census test: 1 passed in 72 s; `git
status --porcelain` of the checkout byte-identical before and after.
Sizes after the rework (same awk rule): `tools/nav.rs` 343,
`tools/select.rs` 177 (new), `tools/hierarchy.rs` 316,
`tools/diagnostics.rs` 313, `tools/mod.rs` 151, `resources.rs` 118; the
rest unchanged. No function over 45 lines.
Gates (through `tools/guard.sh`, one cargo invocation at a time):
`cargo fmt -p lucisv_mcp -- --check` exit 0; `cargo clippy -p lucisv_mcp
--all-targets` `Finished`, no warnings; `cargo test -p lucisv_mcp` unit 38
passed, `opentitan` 1 ignored, `qa_m1` 51 passed, `qa_m2` 32 passed,
`wire` 19 passed; `cargo test --workspace` exit 0 in 254 s, **4 599
passed, 0 failed, 47 ignored**.
## QA log
**2026-09-23 (QA, M2). Verdict: rework needed** — four blocking findings
(1, 2, 4, 11: wrong or partial answers), seven non-blocking. No crash, no
hang, no write: every attack was answered, the server kept answering after
each refusal, and opentitan's `git status --porcelain` was byte-identical
before and after the whole session (the owner's three modified files).
Method: every attack against the real binary over scratch trees
(`crates/lucisv_mcp/tests/qa_m2.rs`, 32 tests: 20 green, 12
`#[ignore = "QA finding N"]` asserting the correct behaviour, each confirmed
failing for the stated reason with `--ignored`). Where "the right answer"
was in question, the oracle was `vlog_refactor::find_references` over the
*whole* file set (a throwaway binary in the QA scratch directory, not in the
tree) and `target/release/lucisv check` for diagnostics.
### Findings
**Blocking**
1. **`references` omits uses reached through a resolution-only file, and
refuses from the use with a false sentence** (`tools/nav.rs:444-464`,
`in_scope`). (a) `top2.sv: wire w2 = u_a.u_b.sig2;` where `mid.sv`
(`leaf u_b`) never writes `sig2`: `references {name: sig2, unit: leaf}`
answers only `leaf.sv:2:9`; the whole-set engine also lists
`top2.sv:4:21` (and drops it when `mid.sv` is removed from its set — the
narrowing is the cause). (b) The class case the brief lists: `e.s.count`
in `t.sv`, with `env.sv` (`sb s;`) never writing `count` — same omission.
From the use (`{file: t.sv, line: 4, name: count}`) `references` is
refused: "`count` is declared outside the files lucisv indexes, so a
rename here would only be half a rename" — the declaration *is* indexed
(`definition` finds it). The README's known limit names only a struct
typedef; multi-level hierarchical tails and UVM handle chains
(`cfg.agent_cfg.x`) are the common case. Tests
`qa_finding_1_a_two_level_tail_to_an_internal_net_is_a_reference`,
`qa_finding_1_a_class_handle_chain_through_a_third_file_is_a_reference`.
Suggested fix (for the lead to rule, it touches the narrowing ruling):
add the files that resolve the path — for a member of a unit, the
up-closure of the unit's instantiating files (`instantiations_of(owner)`
→ `edge.file`, recursively over `edge.owner.name`); for a class member,
the files declaring the types/classes the selected files name, to a
fixed point — or fall back to the whole indexed set for names off the
connection surface. At minimum an engine refusal on a narrowed set must
not be reported as "declared outside the files lucisv indexes".
2. **`file` + `line` + `name` inside a macro call's argument answers the
macro's `define`** (`tools/nav.rs:142-149` via `source::word_in`, then
`at_position:233-239`). `top.sv:5` is ``assign peek = `ID(u_core0.state_q);``;
`definition {file: top.sv, line: 5, name: state_q}` answers
`defs.svh:1:9 define: `define ID(x) x` — a declaration of a different
name. Test `qa_finding_2_…`. Fix: pick the occurrence by token — the
first identifier token on the line spelling `name` (a macro token only
when `name` is `` `NAME``); when the word is only inside a macro token,
refuse naming the macro. The same change fixes finding 3.
4. **`hierarchy` overrides of the 2nd+ instance of one statement include
the earlier instances** (`tools/hierarchy.rs:359-367`). `leaf #(.W(2))
u_a (), u_b ();` → `u_b : leaf #(.W(2)) u_a (),` (down, and `ov.u_b
#(.W(2)) u_a (), ov.sv:4` up; the JSON `overrides` likewise). The
README's "`sub u1 (), u2 ();` shows the one `#(...)` on both instances"
holds only when there are no overrides. Test `qa_finding_4_…`. Fix: end
the slice at the edge's *first* instance name (carry it in `Child`), or
take the balanced `#( … )` after the module name.
11. **`file` + `name` guesses when the file's uses resolve to different
declarations** (`tools/nav.rs:178-181`, `first_occurrence`). `top3.sv`
declares no `sig`; `u.sig` names `leaf`'s and `v.sig` names `other`'s.
`definition {file: top3.sv, name: sig}` answers `leaf.sv:1:27` alone
and `references` lists only `leaf`'s — a pick, where the brief and the
tool description say "ambiguity is a list, never a guess". Test
`qa_finding_11_…`. Fix: when the file declares nothing, resolve every
use of `name`; more than one distinct target → refuse listing the lines
(as the declared-twice rule does).
**Non-blocking**
3. `file` + `line` + `name` takes the first *textual* occurrence, so one in
a comment or string hides the code one: `/* q */ assign q = a;` →
"nothing at m.sv:2:6 names a declaration" (also `"a" == a`). Same place
and fix as 2. Test `qa_finding_3_…`.
5. **One file's `diagnostics` ≠ `lucisv check <file>`** — the brief's
parity criterion. `diagnostics.rs:149` always passes `workspace = true`
to `select_rules`, so the workspace rules (`unknown-port`,
`unused-signal`, `undeclared-identifier`, …) run for one file, where the
CLI runs them only when its run holds more than one file. Differences on
opentitan: `hw/ip/aes/dv/sva/aes_idle_check.sv` 17:28 unused-signal,
`hw/ip/aes/pre_dv/aes_sbox_tb/rtl/aes_sbox_tb.sv` 118:6 unknown-port,
`hw/ip/i3c/rtl/i3c_dat.sv` 134:17 unused-signal,
`hw/ip/kmac/rtl/sha3pad.sv` 776:37 unused-signal,
`hw/ip/entropy_src/pre_dv/entropy_src_tb.sv` 339:9 and 340:9
unknown-port — each one exactly what `lucisv check .` reports for that
file. Arguably the better answer (the project exists); it needs a lead
ruling and a sentence in the tool description and README either way.
Test `qa_finding_5_…` (asserts CLI single-file parity; delete it if the
project-wide semantics is kept).
6. **Unused external waivers are not reported** (`diagnostics.rs:215`
discards `lint_with`'s used-waiver answer). A `[lint] waivers` directive
matching nothing: `lucisv check .` (and `check m.sv`) report
`w.waiver:1:1 unused-waiver`; `diagnostics` says "no findings". Test
`qa_finding_6_…`.
7. `hierarchy` `depth` above 20 is silently the same as 20: the schema has
no `maximum` (`Ty::Int` has only `min`), and a node cut by the depth
limit looks like a leaf. `hierarchy.rs:50-55,120`. Test `qa_finding_7_…`.
The brief's "depth 21 → schema refusal" is not what happens; 0 and
negative are refused.
8. A `col` past the end of its line is clamped to the line end
(`LineIndex::offset`), and the refusal names the clamped column
(`col: 99` → "nothing at clamp.sv:2:15 …"). `nav.rs:135-141`. No wrong
answer found (the clamped offset sits after the last token), but the
agent is told about a position it did not ask for. Test `qa_finding_8_…`.
9. `references` refusals pass the rename engine's sentences through: "there
is no symbol to rename at this position" (whitespace, a keyword, a
comment) and "… a rename here would only be half a rename".
`nav.rs:394`. Test `qa_finding_9_…`. Also a by-name `references
{name: ONLY_MAC}` says "no declaration … is indexed" where the position
form says "is a macro … (`defines` lists …)".
10. `lucisv://unit/{name}` for an ambiguous unit is `-32002` (correct) but
the reason says "pass `file` to pick one", which a URI cannot.
`resources.rs:94` (the text is `unit_interface`'s). Test
`qa_finding_10_…`.
### Verified (green `qa_*` tests)
- Selectors: a package member through `import p::*` and through `p::PW`
(definition + 4 references from either end); a `bind` connection's bare
name (`bind core chk u_chk (.s(state_q))` → `core.sv:2:9`, 4 uses from
the bind side and the declaration side); one- and two-level tails to a
*port* (`u_a.u_b.sig` → `leaf.sv:1:44`, listed in references); the
port-that-is-a-net lists header, body and `wire` (never picks), references
4; a class member declared in two classes lists both, `references`
refuses naming both, `unit` picks; a name declared twice in one file is
refused with its lines; an escaped identifier by name and by position;
a macro-only name by name, `` `NAME`` and position, `references` refuses
it with the pointer to `defines`; whitespace, a keyword, a comment:
clean refusals; `line: 0` a schema refusal; past EOF and `5 000 000 000`
refused; a column inside the two bytes of `é` refused (no panic, server
alive); byte columns after a multibyte comment (`zz` at 29, not 27) and
in a CRLF file; `unit` that does not exist refused naming it.
- `references`: a comment and a string in a third file never reported;
paging `limit`/`offset` with `total` constant and an offset past the end
empty; `include_declaration: false` (also cross-file, from the use).
- `hierarchy`: a `generate`-self-instantiation and mutual recursion
terminate (`(recursive)`, both directions); a 30-deep chain stops at 20;
`depth` 0, -1, 2.5, "3" and `direction` `Up`/`sideways`/`""` refused by
the schema; a package, a class and an unknown name as `root` refused; a
module declared twice marked `(declared 2 times)` and not expanded; `up`
from a leaf with two parents lists both; overrides with a `/* … ) … */`
comment, a `// … )` comment, `c#(4)::N` and a string holding `u_x (` are
sliced right; 250 × 250 instances stop at 50 000 nodes with `cut: true`.
- `diagnostics`: `[lint] select`, `ignore`, `[lint.line-length] length`
and a waiver file honoured under the root config, and a file under
`b/lucisv.toml` gets that config's own select and top-level
`line-length = 60`; `rules` replaces select while the config's `ignore`
still applies (as the CLI's `pick`); `severity` filters; parse errors
first, then lint, in a file with both; the project form's pages
concatenate to the whole list with a constant `total`; a bad option
(`length = 30`) refused naming `lucisv.toml:5`; an unknown rule refused.
Every expected string was checked against `lucisv check` on the same tree.
- `defines`: a macro defined in two files lists both (and `definition` at
a use lists both, never picks); a parameterised multi-line body
one-lined; an unknown name "no defines"; `file` + `name` filters that
file's table (with its `` `undef``); a missing file refused.
- Resources: `resources/templates/list` entries carry `uriTemplate`, `name`,
`mimeType` (and `title`, `description`); `%20`, `%C3%BC` and `%25` decode;
an ambiguous unit, a bad escape (`%`, `%FF`), `..%2F..`, an absolute path
outside the root, a directory, a symlink leading out, `LUCISV://`, a query
string: all `-32002`, never a crash; a non-string `uri` `-32602`.
- Freshness: an edit shows in the next `references` and `hierarchy`; a
deleted declaring file makes the root refused and its instance
`(not indexed)`; a new file is seen after a miss-walk (M1's 5 s rule
otherwise).
### CLI-vs-MCP diagnostics (opentitan, release builds, no lucisv.toml)
- Single files, (rule, line, col) sets: `hw/ip/aes/rtl/aes.sv` 0 = 0,
`aes_core.sv`, `aes_cipher_core.sv`, `uart_core.sv`, `prim_fifo_sync.sv`,
`aes_env_pkg.sv`, `tb.sv` 0 = 0; `aes_scoreboard.sv` 4 = 4,
`uartdpi.sv` 4 = 4, `aes_env_cfg.sv`, `dv_utils_pkg.sv`,
`aes_base_vseq.sv` 1 = 1 — identical. The five files of finding 5 differ.
- Whole project: MCP `diagnostics` 2 102 in 1.77 s vs `lucisv check .`
1 158 in 0.92 s. Lint findings identical except the symlink
`hw/ip/tlul/rtl/tlul_adapter_shim.sv → tlul_adapter_vh.sv` (the MCP
lints the canonical path, M1's ruling, so the CLI's `module-filename` on
the shim name has no MCP twin). The other 941 are `parse-error`, which
`lucisv check` does not report at all (by the plan).
### opentitan (release, 3 944 files)
Index 1.8 s; `references clk_i` from `prim_fifo_sync.sv` 1.60 s (83 hits)
and from `tb.sv` (first occurrence = `key_sideload_if`'s port, 5 hits)
1.58 s — the huge-census case is bounded as the README says. The generate-
scope path `aes_bind.sv:58 …gen_masks.u_aes_prng_masking.u_prim_bivium.
state_q` is not among `prim_trivium`'s `state_q` references, but the
whole-set engine over 472 aes/prim/tlul files does not list it either: an
engine limit, not the narrowing. The dev's census test: 1 passed in
32.7 s (debug).
### Sizes and style
Production lines (non-blank, not starting with `//`, before the first
`#[cfg(test)]`, one awk rule for all): `tools/nav.rs` 446,
`tools/hierarchy.rs` 311, `tools/diagnostics.rs` 293, `tools/defines.rs`
158, `tools/source.rs` 134, `resources.rs` 112, `tools/mod.rs` 146,
`rpc.rs` 241, `project/analysis.rs` 77, `tools/read_item.rs` 213,
`main.rs` 68 — the dev's numbers, all under 600. No function over 40 lines
(brace-matched scan). No `unwrap`/`expect`/`panic!` outside `#[cfg(test)]`,
no `#[allow]`, no `unsafe`.
### Gates (through `tools/guard.sh`, one cargo invocation at a time)
- `cargo fmt -p lucisv_mcp -- --check` → exit 0
- `cargo clippy -p lucisv_mcp --all-targets` → `Finished`, no warnings
- `cargo test -p lucisv_mcp` → unit 37 passed; `opentitan` 0 passed, 1
ignored; `qa_m1` 51 passed; `qa_m2` 20 passed, 12 ignored; `wire` 19
passed
- `cargo test --workspace` (before finding 11's ignored test was added) →
exit 0, **4 586 passed, 0 failed, 58 ignored** (4 566 + 20 QA; 47 + 11)
- `LUCISV_OPENTITAN=… cargo test -p lucisv_mcp --test opentitan --
--ignored` → 1 passed in 32.7 s; checkout status byte-identical
- No guard kill.
TODO-MCP M2 QA box left unticked (rework needed).
**2026-09-23 (QA, M2 re-check after the rework). Verdict: pass.** All
eleven findings are fixed or pinned under the lead's rulings; no new
finding. Every earlier `qa_finding_*` test is un-ignored and green with
its assertion unchanged, except finding 5's, which the dev rewrote to pin
the ruling. It now asserts that one file's `diagnostics` reports
`unknown-port` for `top.sv`, as `lucisv check .` does and `lucisv check
top.sv` does not. That is exactly the ruling. QA added
`qa_recheck_one_files_diagnostics_are_its_lines_of_lucisv_check_dot`, which
pins the whole text line (`2:12 error … [unknown-port]`, and nothing for
`leaf.sv`) rather than a substring. Finding 10's new wording, "call the
unit_interface tool with its file argument to pick one", is acceptable: it
names the tool that can pick, and it no longer suggests that the URI takes
an argument.
Re-derived by hand (release binary, scratch trees, then pinned):
- **1**: the two-level tail `u_a.u_b.sig2` gives the same 3 locations
(`leaf.sv:2:9`, `top2.sv:3:21`, `top2.sv:4:21`) from the bare name, from
the declaration, and from each of the two uses. The class chain gives the
same 4 (`sb.sv:2:7`, `sb.sv:3:24`, `t.sv:4:9`, `t2.sv:3:33`) from the bare
name, the declaring file's own use, `e.s.count` and `e2.s.count`. Both
lists equal the whole-set oracle (`find_references` over every file).
- **2+3**: in `/* q */ initial $display("q"); assign r = `ID(q); assign q = a; // q`
the selector picks the code `q` at column 60. `references` lists it with
the declaration and the two uses on line 5. A line whose `q` is only in
strings: "not written on line 6". `` `ID(q)`` alone on its line and `a`
only inside `` `ID(a)`` are refused as "inside a macro argument" by both
tools, while `q` elsewhere on line 5 and `` `ID`` are still found.
- **4**: three instances in one statement with overrides (`#(.W(2)) u_a,
u_b, u_c`) each show `#(.W(2))`. Three without overrides show none. A
statement whose `#(` … `)` spans three lines, with a `// three` comment,
a `/* between ) , */` comment between instances and the last instance
after a leading comma, shows `#( .W(3) )` on all three, down and up. Two
separate statements of the same module in one owner keep their own
`#(.W(4))`/`#(.W(5))`, and an instance array has none.
- **11**: three uses naming three declarations (`l1`, `l2`, `l3`) are
refused by both tools with "`sig` on line 3 → l1.sv:1, line 7 → l2.sv:1,
line 12 → l3.sv:1; add `line`". `line: 7` then answers `l2.sv:1:25`. Two
uses of one declaration answer it. A use of a module declared twice lists
both declarations. On opentitan, `references {file: hw/ip/aes/dv/tb/tb.sv,
name: clk_i}` now refuses, naming `key_sideload_if.sv:8` (line 35) and
`aes.sv:42` (line 46). Before the rework it silently picked the first.
New attacks (11 `qa_recheck_*` tests, all green): the four hand
derivations above; `depth` schema `minimum` 1 / `maximum` 20, where 20
walks 20 levels and 21 is refused "from 1 to 20"; `col` on the last byte
and one past it are positions, two past is refused "line 2 is 13 bytes
long" (CRLF line) or "line 3 is 9 bytes long" (a last line with no
newline); `references` from a file the walk skips (a gitignored `.sv` and
a `notes.txt`) answers the real uses, including the file asked from,
while the by-name answer stays the indexed files, and a path that does not
exist is refused naming it, never a crash; whole-set `references` after
deleting one file mid-session drops its hit, and after deleting the
declaring file the refusal is prefixed "lucisv cannot follow this position:"
with no "rename"; unused waivers match `lucisv check .` (one
`unused-waiver` at `w.waiver:1:1`; a waiver file named by two configs is
read once; `rules: no-tabs` reports nothing, as `--select no-tabs .` does;
the per-file form reports none, as ruled).
Observation for the lead (not a finding): the coordinator's brief expected
`references` from a file that is not indexed to be a clean refusal. It
answers instead. That is consistent with M1's path rule (`outline`,
`definition` and `diagnostics` all read any file inside a root), and the
answer is correct. If a refusal is wanted, that is a ruling for all the
tools, not a fix in `references`.
opentitan (release, whole-set `references`): `clk_i` from
`prim_fifo_sync.sv` 2.37 s, 83 hits, the same count as the narrowed answer.
The dev's census test: 1 passed in 73.1 s (debug; per-call 9.8–14.9 s for
the five `references` calls). `git status --porcelain` of the checkout was
byte-identical before and after, and identical to the first QA pass's
snapshot.
Sizes (same awk rule): `tools/nav.rs` 343, `tools/select.rs` 177,
`tools/hierarchy.rs` 316, `tools/diagnostics.rs` 313, `tools/mod.rs` 151,
`resources.rs` 118. The rest are unchanged. No function over 45 lines. No
`unwrap`/`expect`/`panic!`/`#[allow]`/`unsafe` outside `#[cfg(test)]`.
Gates (through `tools/guard.sh`, one cargo invocation at a time, no guard
kill):
- `cargo fmt -p lucisv_mcp -- --check` → exit 0
- `cargo clippy -p lucisv_mcp --all-targets` → `Finished`, no warnings
- `cargo test -p lucisv_mcp` → unit 38 passed; `opentitan` 1 ignored;
`qa_m1` 51 passed; `qa_m2` 43 passed, 0 ignored; `wire` 19 passed
- `cargo test --workspace` → exit 0, **4 610 passed, 0 failed, 47 ignored**
(the dev's 4 599 + 11 re-check tests)
- `LUCISV_OPENTITAN=… cargo test -p lucisv_mcp --test opentitan --
--ignored` → 1 passed in 73.1 s; checkout status byte-identical
TODO-MCP M2 QA box ticked.
## Review
**Lead, 2026-09-23.** Read every source file after the rework. The one
ruling worth restating: the reference-narrowing rule in PLAN §2.1 was
mine and it was wrong — a two-level tail or a class-handle chain resolves
through files that never spell the name, so `references` now hands the
engine the whole indexed set (≈ 2 s on opentitan) and MCP-7 asks
`vlog_refactor` for a `KnownFacts` variant so M6 can feed cached records.
Correctness first; the census will show whether 2 s matters to an agent.
Other rulings: `diagnostics` matches `lucisv check .` (the whole-tree
run — "what will CI say"); a name on a line is chosen by token, never by
text; `hierarchy` overrides belong to the statement, so every instance of
one statement shows them; `depth` is 1..=20 in the schema; every read
tool reads any file inside a root, indexed or not (QA's closing question —
kept, the answer is correct and the rule is M1's). Missing-closer warnings
and one-step macro expansion are not offered (server-only code; MCP-5
filed). MCP-6 — the LSP omits three real `aes` instantiations in the
`*_pd_main.sv` tops — is a possible LSP bug to file in TODO.md at the end
of the block. Committed as M2.