textDocument/references now reads declaration-to-occurrence postings merged in WorkspaceIndex from compact per-file reference facts, with open buffers overlaying live semantics — 0.062 ms/request over 820 files vs 21.7 ms for the old Workspace::sources() walk (~350x). The walk stays as rename's engine and the equivalence oracle in tests. FACTS_FORMAT 1->2 discards v1 caches whole. Cursor lookups (symbol_at/reference_at/token_at) and macro-define lookup move to binary-searched sorted tables; include definition inspects only the cursor's line. Ambiguity refusals preserved throughout. External dev: codex. Lead-reviewed, gates re-run, probe reproduced. Co-Authored-By: Claude Fable 5 <[email protected]>
854 lines
37 KiB
Rust
854 lines
37 KiB
Rust
//! `` `include`` lines: what they name, which file that is, and what a file
|
|
//! reaches through them.
|
|
//!
|
|
//! Two capabilities are spent off one graph — `textDocument/documentLink` and
|
|
//! `textDocument/definition` make an include line clickable, and
|
|
//! `textDocument/hover` uses reachability to pick the `` `define`` a file
|
|
//! actually sees. The search order and the deliberate narrowings are in
|
|
//! `docs/features/include-nav/README.md`.
|
|
|
|
use std::collections::{HashMap, HashSet};
|
|
use std::path::{Component, Path, PathBuf};
|
|
|
|
use lsp_types::{DocumentLink, Location, Range, Uri};
|
|
use vlog_parser::TextRange;
|
|
|
|
use crate::state::{Document, Workspace};
|
|
use crate::uri::path_to_uri;
|
|
|
|
/// One `` `include`` directive, as written.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Include {
|
|
/// The path as written, delimiters stripped.
|
|
pub target: String,
|
|
/// Whether it was written `` `include <x.svh> `` rather than with quotes.
|
|
pub system: bool,
|
|
/// The quoted path, its delimiters included — the clickable range.
|
|
pub path_span: TextRange,
|
|
/// The backtick through the closing delimiter — what the cursor may sit
|
|
/// anywhere inside for go-to-definition.
|
|
pub span: TextRange,
|
|
}
|
|
|
|
/// Every `` `include`` in one file's text, in source order.
|
|
///
|
|
/// A line scan, not a parse: the directive has to be the first thing on its
|
|
/// line, which is how every real one is written and what keeps this cheap
|
|
/// enough to run over the whole workspace on each index rebuild.
|
|
pub fn scan(text: &str) -> Vec<Include> {
|
|
let mut out = Vec::new();
|
|
let mut offset = 0u32;
|
|
for line in text.split_inclusive('\n') {
|
|
if let Some(include) = include_on_line(line, offset) {
|
|
out.push(include);
|
|
}
|
|
offset += line.len() as u32;
|
|
}
|
|
out
|
|
}
|
|
|
|
/// The `` `include`` one line holds, if it opens with one and names a path.
|
|
fn include_on_line(line: &str, base: u32) -> Option<Include> {
|
|
let trimmed = line.trim_start();
|
|
let indent = (line.len() - trimmed.len()) as u32;
|
|
let rest = trimmed.strip_prefix("`include")?;
|
|
// Whitespace before the path is optional, matching the lexer: it ends the
|
|
// directive name at the first character that cannot be part of one, so
|
|
// `` `include"x.svh" `` is one directive there and has to be one here.
|
|
// `` `includes "x.svh" `` still scans to nothing, because the delimiter
|
|
// must be the very next thing after the keyword.
|
|
let after = rest.trim_start();
|
|
let opened = (trimmed.len() - after.len()) as u32;
|
|
let (open, close, system) = match after.as_bytes().first()? {
|
|
b'"' => ('"', '"', false),
|
|
b'<' => ('<', '>', true),
|
|
_ => return None,
|
|
};
|
|
let body = after.strip_prefix(open)?;
|
|
// A delimiter that never closes on this line names nothing.
|
|
let end = body.find(close)?;
|
|
let target = &body[..end];
|
|
if target.is_empty() || target.contains('\n') {
|
|
return None;
|
|
}
|
|
let start = base + indent;
|
|
let path_start = start + opened;
|
|
let path_end = path_start + end as u32 + 2;
|
|
Some(Include {
|
|
target: target.to_string(),
|
|
system,
|
|
path_span: TextRange::new(path_start, path_end),
|
|
span: TextRange::new(start, path_end),
|
|
})
|
|
}
|
|
|
|
/// Where `` `include``s are looked for, and which file includes which.
|
|
///
|
|
/// Rebuilt whole on every index rebuild, from the same source list — and
|
|
/// patched one file at a time when only one file's text moved
|
|
/// ([`IncludeGraph::update_file`]).
|
|
#[derive(Debug, Default, Clone)]
|
|
pub struct IncludeGraph {
|
|
/// The `+incdir+` directories of the configured filelist, in filelist
|
|
/// order. Empty when no filelist governs the workspace.
|
|
incdirs: Vec<PathBuf>,
|
|
/// Including file → the files it resolves to, in source order.
|
|
edges: HashMap<PathBuf, Vec<PathBuf>>,
|
|
/// Every in-scope file, exactly as the index spells it.
|
|
known: HashSet<PathBuf>,
|
|
/// Lower-cased spelling → the one in-scope file that has it, or `None`
|
|
/// when several do. See [`IncludeGraph::as_the_index_spells_it`].
|
|
folded: HashMap<String, Option<PathBuf>>,
|
|
}
|
|
|
|
impl IncludeGraph {
|
|
/// Scan every in-scope file for its `` `include``s and resolve them.
|
|
pub fn build(sources: &[(PathBuf, String)], incdirs: Vec<PathBuf>) -> IncludeGraph {
|
|
let mut graph = IncludeGraph { incdirs, ..IncludeGraph::default() };
|
|
// Learned before the edges: `resolve` consults both tables, and an edge
|
|
// resolved against a half-filled one would be keyed inconsistently.
|
|
let paths: Vec<PathBuf> = sources.iter().map(|(path, _)| path.clone()).collect();
|
|
graph.relearn(&paths);
|
|
for (path, text) in sources {
|
|
let targets: Vec<PathBuf> = scan(text)
|
|
.iter()
|
|
.filter_map(|include| graph.resolve(Some(path), include))
|
|
.collect();
|
|
if !targets.is_empty() {
|
|
graph.edges.insert(path.clone(), targets);
|
|
}
|
|
}
|
|
graph
|
|
}
|
|
|
|
/// Re-scan one file's `` `include``s, the rest of the graph left standing.
|
|
///
|
|
/// `known` is the index's file list as it stands *after* the update, which
|
|
/// is what the known-file and folded-spelling tables are: cheap to rebuild
|
|
/// from a list already in memory, and wrong to leave stale when a file has
|
|
/// come or gone.
|
|
///
|
|
/// One honest limit, and the reason the incremental path in `state.rs`
|
|
/// takes it only for a file that already existed: an edge of a *different*
|
|
/// file is not re-resolved. So a file appearing or vanishing does not
|
|
/// change whether some other file's `` `include "x.svh"`` resolves until
|
|
/// the next whole rebuild. For the case this is used in — one file's text
|
|
/// changed, the file set did not — there is nothing stale at all.
|
|
pub fn update_file(&mut self, path: &Path, text: &str, known: &[PathBuf]) {
|
|
self.relearn(known);
|
|
let targets: Vec<PathBuf> =
|
|
scan(text).iter().filter_map(|include| self.resolve(Some(path), include)).collect();
|
|
match targets.is_empty() {
|
|
true => self.edges.remove(path),
|
|
false => self.edges.insert(path.to_path_buf(), targets),
|
|
};
|
|
}
|
|
|
|
/// Drop one file from the graph: its own edges, and its place among the
|
|
/// known files.
|
|
pub fn remove_file(&mut self, path: &Path, known: &[PathBuf]) {
|
|
self.relearn(known);
|
|
self.edges.remove(path);
|
|
}
|
|
|
|
/// Re-derive the known-file set and the folded-spelling table from the
|
|
/// index's file list. The same two loops [`IncludeGraph::build`] runs, over
|
|
/// paths rather than over `(path, text)` pairs.
|
|
fn relearn(&mut self, known: &[PathBuf]) {
|
|
self.known = known.iter().cloned().collect();
|
|
self.folded.clear();
|
|
for path in known {
|
|
let Some(key) = path.to_str().map(str::to_lowercase) else { continue };
|
|
self.folded
|
|
.entry(key)
|
|
// A second file with the same folded spelling makes the
|
|
// spelling ambiguous, and an ambiguous one decides nothing.
|
|
.and_modify(|found| *found = None)
|
|
.or_insert_with(|| Some(path.clone()));
|
|
}
|
|
}
|
|
|
|
/// The `+incdir+` directories an include is looked for in, in filelist
|
|
/// order — the search rungs past the including file's own directory.
|
|
pub fn incdirs(&self) -> &[PathBuf] {
|
|
&self.incdirs
|
|
}
|
|
|
|
/// The file an `` `include`` names, or `None` when nothing on disk
|
|
/// answers to it.
|
|
///
|
|
/// The EDA search order: an absolute path is itself; otherwise the
|
|
/// including file's own directory first, then each `+incdir+` in filelist
|
|
/// order. The `<angled>` form skips the own-directory rung, which is the C
|
|
/// convention and the only difference the two spellings make here.
|
|
pub fn resolve(&self, from: Option<&Path>, include: &Include) -> Option<PathBuf> {
|
|
self.resolve_as_if(from, include, &|path| path.is_file())
|
|
}
|
|
|
|
/// [`IncludeGraph::resolve`], asked about a filesystem that has not
|
|
/// happened yet: `exists` decides which paths are files.
|
|
///
|
|
/// The one search order, spent twice — `file_ops.rs` has to know where an
|
|
/// include *will* land once a rename the client has announced goes
|
|
/// through, and a second copy of the rung order there could disagree with
|
|
/// this one in exactly the corner cases nobody tests. See
|
|
/// `docs/features/file-operations/README.md`.
|
|
pub fn resolve_as_if(
|
|
&self,
|
|
from: Option<&Path>,
|
|
include: &Include,
|
|
exists: &dyn Fn(&Path) -> bool,
|
|
) -> Option<PathBuf> {
|
|
let target = Path::new(&include.target);
|
|
if target.is_absolute() {
|
|
return exists(target).then(|| self.as_the_index_spells_it(normalize(target)));
|
|
}
|
|
let own = match include.system {
|
|
true => None,
|
|
false => from.and_then(Path::parent),
|
|
};
|
|
own.into_iter()
|
|
.chain(self.incdirs.iter().map(PathBuf::as_path))
|
|
.map(|dir| dir.join(target))
|
|
.find(|candidate| exists(candidate))
|
|
.map(|found| self.as_the_index_spells_it(normalize(&found)))
|
|
}
|
|
|
|
/// A resolved path, re-spelled the way the index spells that file.
|
|
///
|
|
/// macOS and Windows default to case-insensitive filesystems, so
|
|
/// `` `include "defs.svh" `` happily opens a file called `Defs.svh`. The
|
|
/// path as written is then a *different* `PathBuf` from the one the index
|
|
/// recorded, and every comparison against the index — the reachability
|
|
/// check hover narrows on, and the URI go-to-definition hands the editor —
|
|
/// silently misses a file that really is reachable. Hover would then show
|
|
/// one confident answer where the honest one is "defined twice", which is
|
|
/// the one direction this feature must never fail in (QA finding, HIGH,
|
|
/// 2026-08-25).
|
|
///
|
|
/// So: an exact match keeps its spelling, and otherwise **exactly one**
|
|
/// in-scope file matching case-insensitively lends its own. Zero matches
|
|
/// (a header outside the index's scope) or several (a case-sensitive
|
|
/// filesystem really holding both `defs.svh` and `Defs.svh`) keep the path
|
|
/// as written — guessing between two real files would be the widening
|
|
/// this whole rule exists to prevent. No filesystem call and no platform
|
|
/// test: it is a lookup in the file list the graph was built from.
|
|
fn as_the_index_spells_it(&self, path: PathBuf) -> PathBuf {
|
|
if self.known.contains(&path) {
|
|
return path;
|
|
}
|
|
let Some(key) = path.to_str().map(str::to_lowercase) else { return path };
|
|
match self.folded.get(&key) {
|
|
Some(Some(indexed)) => indexed.clone(),
|
|
_ => path,
|
|
}
|
|
}
|
|
|
|
/// Every file reachable from `seeds` through include edges, the seeds
|
|
/// themselves included.
|
|
///
|
|
/// Cycle-safe by construction: a file already visited is never expanded
|
|
/// again, so `a` including `b` including `a` terminates with both in the
|
|
/// set.
|
|
pub fn reachable(&self, seeds: Vec<PathBuf>) -> HashSet<PathBuf> {
|
|
let mut seen: HashSet<PathBuf> = HashSet::new();
|
|
let mut queue = seeds;
|
|
while let Some(path) = queue.pop() {
|
|
if !seen.insert(path.clone()) {
|
|
continue;
|
|
}
|
|
if let Some(targets) = self.edges.get(&path) {
|
|
queue.extend(targets.iter().cloned());
|
|
}
|
|
}
|
|
seen
|
|
}
|
|
}
|
|
|
|
/// Fold `.`/`..` away so one file has one spelling, and so a resolved include
|
|
/// compares equal to the same file's path in the index. Symlinks are
|
|
/// deliberately not resolved, matching `lucisv_core`'s lexical rule.
|
|
///
|
|
/// Public since 2026-08-27 so `file_ops.rs` folds a renamed file's path the
|
|
/// same way a resolved include is folded — the two are compared, and a fourth
|
|
/// private copy of this loop is the one thing that guarantees they disagree.
|
|
pub fn normalize(path: &Path) -> PathBuf {
|
|
let mut out = PathBuf::new();
|
|
for component in path.components() {
|
|
match component {
|
|
Component::CurDir => {}
|
|
Component::ParentDir => {
|
|
out.pop();
|
|
}
|
|
other => out.push(other),
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
// ----------------------------------------------------------------------
|
|
// the two capabilities
|
|
// ----------------------------------------------------------------------
|
|
|
|
/// Every resolvable `` `include`` in an open buffer, paired with the file it
|
|
/// names.
|
|
///
|
|
/// Resolved against the buffer's *current* text rather than looked up in the
|
|
/// graph: the graph is rebuilt on save, and an include line just typed should
|
|
/// be clickable before then.
|
|
fn resolved(ws: &Workspace, doc: &Document) -> Vec<(Include, PathBuf)> {
|
|
let graph = ws.includes();
|
|
scan(&doc.text)
|
|
.into_iter()
|
|
.filter_map(|include| {
|
|
let path = graph.resolve(doc.path.as_deref(), &include)?;
|
|
Some((include, path))
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// `textDocument/documentLink`: one link per resolvable `` `include``.
|
|
///
|
|
/// An include nothing answers to gets no link at all — an underline that goes
|
|
/// nowhere is worse than none.
|
|
pub fn document_links(ws: &Workspace, uri: &Uri) -> Vec<DocumentLink> {
|
|
let Some(doc) = ws.document(uri) else { return Vec::new() };
|
|
let positions = doc.positions();
|
|
resolved(ws, doc)
|
|
.into_iter()
|
|
.filter_map(|(include, path)| {
|
|
Some(DocumentLink {
|
|
range: positions.range(include.path_span),
|
|
target: Some(path_to_uri(&path)?),
|
|
tooltip: Some(path.display().to_string()),
|
|
data: None,
|
|
})
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// The included file's start, for a cursor anywhere on an `` `include`` line.
|
|
///
|
|
/// The same computation the links use, so F12 and ctrl-click can never
|
|
/// disagree about where a line goes.
|
|
pub fn definition(ws: &Workspace, doc: &Document, offset: u32) -> Option<Location> {
|
|
// Definition is a cursor request, so inspect only its line. `documentLink`
|
|
// still scans the whole file because it must return every include.
|
|
let (line, _) = doc.line_index.line_col(offset);
|
|
let line = doc.line_index.line_range(line)?;
|
|
let text = doc.text.get(line.as_range())?;
|
|
let include =
|
|
include_on_line(text, line.start).filter(|include| include.span.contains(offset))?;
|
|
let path = ws.includes().resolve(doc.path.as_deref(), &include)?;
|
|
Some(Location { uri: path_to_uri(&path)?, range: Range::default() })
|
|
}
|
|
|
|
/// Every file this buffer reaches through `` `include``, transitively.
|
|
///
|
|
/// The first hop is resolved from the buffer's own text and the rest walks
|
|
/// the graph, so an include added since the last save already counts. The
|
|
/// buffer itself is *not* in the set unless an include cycle reaches it.
|
|
pub fn reachable_from(ws: &Workspace, doc: &Document) -> HashSet<PathBuf> {
|
|
let seeds: Vec<PathBuf> = resolved(ws, doc).into_iter().map(|(_, path)| path).collect();
|
|
if seeds.is_empty() {
|
|
return HashSet::new();
|
|
}
|
|
ws.includes().reachable(seeds)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::fs;
|
|
|
|
fn one(text: &str) -> Include {
|
|
let found = scan(text);
|
|
assert_eq!(found.len(), 1, "expected one include in {text:?}, got {found:?}");
|
|
found.into_iter().next().expect("one")
|
|
}
|
|
|
|
#[test]
|
|
fn a_quoted_include_is_read_off_the_line() {
|
|
let text = "`include \"defs.svh\"\nmodule m;\nendmodule\n";
|
|
let include = one(text);
|
|
assert_eq!(include.target, "defs.svh");
|
|
assert!(!include.system);
|
|
assert_eq!(&text[include.path_span.as_range()], "\"defs.svh\"");
|
|
assert_eq!(&text[include.span.as_range()], "`include \"defs.svh\"");
|
|
}
|
|
|
|
#[test]
|
|
fn an_indented_include_with_a_trailing_comment_is_still_found() {
|
|
let text = "module m;\n `include \"a.svh\" // pull it in\nendmodule\n";
|
|
let include = one(text);
|
|
assert_eq!(include.target, "a.svh");
|
|
assert_eq!(&text[include.span.as_range()], "`include \"a.svh\"", "the comment is not part");
|
|
}
|
|
|
|
#[test]
|
|
fn the_angled_form_is_kept_and_marked() {
|
|
let include = one("`include <uvm_macros.svh>\n");
|
|
assert_eq!(include.target, "uvm_macros.svh");
|
|
assert!(include.system, "the angled form resolves differently");
|
|
}
|
|
|
|
#[test]
|
|
fn what_is_not_an_include_is_not_scanned() {
|
|
assert!(scan("`includes \"x.svh\"\n").is_empty(), "another directive entirely");
|
|
assert!(scan("`include\n").is_empty(), "no path at all");
|
|
assert!(scan("`include \"unterminated\n").is_empty(), "no closing quote on the line");
|
|
assert!(scan("`include \"\"\n").is_empty(), "an empty path names nothing");
|
|
assert!(scan("`define X `include \"a.svh\"\n").is_empty(), "not first on its line");
|
|
assert!(scan("wire a; `include \"a.svh\"\n").is_empty(), "nor here");
|
|
}
|
|
|
|
#[test]
|
|
fn several_includes_come_back_in_source_order() {
|
|
let text = "`include \"a.svh\"\n`include \"b.svh\"\n";
|
|
let found = scan(text);
|
|
assert_eq!(found.len(), 2);
|
|
assert_eq!(found[0].target, "a.svh");
|
|
assert_eq!(found[1].target, "b.svh");
|
|
assert!(found[0].span.start < found[1].span.start);
|
|
}
|
|
|
|
/// A scratch tree, removed on drop.
|
|
struct Tree {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl Tree {
|
|
fn new(name: &str) -> Tree {
|
|
let path = std::env::temp_dir()
|
|
.join(format!("lucisv_server_includes_{}_{name}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&path);
|
|
fs::create_dir_all(&path).expect("temp dir");
|
|
Tree { path }
|
|
}
|
|
|
|
fn write(&self, rel: &str, text: &str) -> PathBuf {
|
|
let path = self.path.join(rel);
|
|
if let Some(parent) = path.parent() {
|
|
fs::create_dir_all(parent).expect("parent");
|
|
}
|
|
fs::write(&path, text).expect("write");
|
|
path
|
|
}
|
|
}
|
|
|
|
impl Drop for Tree {
|
|
fn drop(&mut self) {
|
|
let _ = fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn the_including_files_own_directory_beats_every_incdir() {
|
|
let tree = Tree::new("owndir");
|
|
let here = tree.write("rtl/defs.svh", "`define W 1\n");
|
|
tree.write("inc/defs.svh", "`define W 2\n");
|
|
let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n");
|
|
|
|
let graph = IncludeGraph::build(&[], vec![tree.path.join("inc")]);
|
|
let include = one("`include \"defs.svh\"\n");
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(here));
|
|
}
|
|
|
|
#[test]
|
|
fn incdirs_are_tried_in_filelist_order() {
|
|
let tree = Tree::new("incdirorder");
|
|
let first = tree.write("a/defs.svh", "`define W 1\n");
|
|
tree.write("b/defs.svh", "`define W 2\n");
|
|
let top = tree.write("rtl/top.sv", "`include \"defs.svh\"\n");
|
|
let include = one("`include \"defs.svh\"\n");
|
|
|
|
let graph = IncludeGraph::build(&[], vec![tree.path.join("a"), tree.path.join("b")]);
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(first.clone()));
|
|
|
|
// The other way round, the other file — the order is the answer.
|
|
let graph = IncludeGraph::build(&[], vec![tree.path.join("b"), tree.path.join("a")]);
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(tree.path.join("b/defs.svh")));
|
|
}
|
|
|
|
#[test]
|
|
fn the_angled_form_skips_the_own_directory_rung() {
|
|
let tree = Tree::new("angled");
|
|
tree.write("rtl/defs.svh", "`define W 1\n");
|
|
let in_incdir = tree.write("inc/defs.svh", "`define W 2\n");
|
|
let top = tree.write("rtl/top.sv", "`include <defs.svh>\n");
|
|
|
|
let graph = IncludeGraph::build(&[], vec![tree.path.join("inc")]);
|
|
let include = one("`include <defs.svh>\n");
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(in_incdir));
|
|
|
|
// And with no `+incdir+` at all it resolves to nothing, even though a
|
|
// file of that name sits right beside the includer.
|
|
let graph = IncludeGraph::build(&[], Vec::new());
|
|
assert_eq!(graph.resolve(Some(&top), &include), None);
|
|
}
|
|
|
|
#[test]
|
|
fn with_no_filelist_only_the_own_directory_answers() {
|
|
let tree = Tree::new("nofilelist");
|
|
let beside = tree.write("rtl/defs.svh", "`define W 1\n");
|
|
tree.write("inc/other.svh", "`define X 1\n");
|
|
let top = tree.write("rtl/top.sv", "x\n");
|
|
|
|
let graph = IncludeGraph::build(&[], Vec::new());
|
|
assert_eq!(graph.resolve(Some(&top), &one("`include \"defs.svh\"\n")), Some(beside));
|
|
assert_eq!(graph.resolve(Some(&top), &one("`include \"other.svh\"\n")), None);
|
|
}
|
|
|
|
#[test]
|
|
fn a_relative_path_with_dots_resolves_to_the_indexs_own_spelling() {
|
|
let tree = Tree::new("dots");
|
|
let defs = tree.write("inc/defs.svh", "`define W 1\n");
|
|
let top = tree.write("rtl/top.sv", "x\n");
|
|
|
|
let graph = IncludeGraph::build(&[], Vec::new());
|
|
let resolved = graph.resolve(Some(&top), &one("`include \"../inc/defs.svh\"\n"));
|
|
assert_eq!(resolved, Some(defs), "`..` folded away, not left in the path");
|
|
}
|
|
|
|
#[test]
|
|
fn an_absolute_include_is_itself_and_a_missing_one_is_nothing() {
|
|
let tree = Tree::new("absolute");
|
|
let defs = tree.write("inc/defs.svh", "`define W 1\n");
|
|
let named = format!("`include \"{}\"\n", defs.display());
|
|
let graph = IncludeGraph::build(&[], Vec::new());
|
|
assert_eq!(graph.resolve(None, &one(&named)), Some(defs));
|
|
assert_eq!(graph.resolve(None, &one("`include \"/nowhere/at/all.svh\"\n")), None);
|
|
}
|
|
|
|
/// The case-canonicalization rule, at the level it is implemented.
|
|
///
|
|
/// Case-gated for the same reason the hover regression test is: the
|
|
/// premise is `is_file` succeeding for a spelling the file does not have,
|
|
/// which only a case-insensitive filesystem does.
|
|
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
|
#[test]
|
|
fn a_resolved_path_is_re_spelled_the_way_the_index_spells_it() {
|
|
let tree = Tree::new("case");
|
|
let on_disk = tree.write("Defs.svh", "`define W 8\n");
|
|
let top = tree.write("top.sv", "`include \"defs.svh\"\n");
|
|
let include = one("`include \"defs.svh\"\n");
|
|
let as_written = tree.path.join("defs.svh");
|
|
|
|
// Nothing in scope: the path as written, which is all there is to go on.
|
|
let graph = IncludeGraph::build(&[], Vec::new());
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(as_written.clone()));
|
|
|
|
// Exactly one in-scope file matches case-insensitively: its spelling
|
|
// wins, so the edge compares equal to the index's own path.
|
|
let sources = vec![(on_disk.clone(), "`define W 8\n".to_string())];
|
|
let graph = IncludeGraph::build(&sources, Vec::new());
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(on_disk.clone()));
|
|
|
|
// Two in-scope files fold to the same spelling: ambiguous, so nothing
|
|
// is adopted. (Only one of them exists on disk here; the folded table
|
|
// is built from the file list, not from the filesystem.)
|
|
let sources = vec![
|
|
(on_disk, "`define W 8\n".to_string()),
|
|
(tree.path.join("DEFS.svh"), "`define W 9\n".to_string()),
|
|
];
|
|
let graph = IncludeGraph::build(&sources, Vec::new());
|
|
assert_eq!(graph.resolve(Some(&top), &include), Some(as_written));
|
|
}
|
|
|
|
#[test]
|
|
fn reachability_is_transitive_and_survives_a_cycle() {
|
|
let tree = Tree::new("cycle");
|
|
let a = tree.write("a.svh", "`include \"b.svh\"\n");
|
|
let b = tree.write("b.svh", "`include \"a.svh\"\n");
|
|
let top = tree.write("top.sv", "`include \"a.svh\"\n");
|
|
let sources: Vec<(PathBuf, String)> = [&a, &b, &top]
|
|
.iter()
|
|
.map(|p| ((*p).clone(), fs::read_to_string(p).expect("read")))
|
|
.collect();
|
|
|
|
let graph = IncludeGraph::build(&sources, Vec::new());
|
|
let reached = graph.reachable(vec![top.clone()]);
|
|
assert!(reached.contains(&a) && reached.contains(&b), "both, and no hang: {reached:?}");
|
|
// From `a`, the cycle brings `a` itself back into the set.
|
|
let reached = graph.reachable(vec![a.clone()]);
|
|
assert!(reached.contains(&a) && reached.contains(&b), "{reached:?}");
|
|
}
|
|
|
|
/// A workspace over `tree`, governed by the filelist `files.f` it holds,
|
|
/// with `rel` opened as a buffer.
|
|
fn workspace_over(tree: &Tree, rel: &str) -> (Workspace, Uri) {
|
|
let mut ws = Workspace::default();
|
|
ws.set_client_settings(crate::settings::ClientSettings {
|
|
filelist: Some(tree.path.join("files.f").display().to_string()),
|
|
..Default::default()
|
|
});
|
|
ws.open_whole_workspace(vec![tree.path.clone()]);
|
|
let path = tree.path.join(rel);
|
|
let uri = path_to_uri(&path).expect("uri");
|
|
let text = fs::read_to_string(&path).expect("read");
|
|
ws.set_document(uri.clone(), text);
|
|
(ws, uri)
|
|
}
|
|
|
|
/// The one link a document has, as `(line, start character, target)`.
|
|
fn only_link(ws: &Workspace, uri: &Uri) -> (u32, u32, String) {
|
|
let links = document_links(ws, uri);
|
|
assert_eq!(links.len(), 1, "expected exactly one link, got {links:#?}");
|
|
let link = &links[0];
|
|
(
|
|
link.range.start.line,
|
|
link.range.start.character,
|
|
link.target.as_ref().expect("a target").as_str().to_string(),
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn a_link_and_a_definition_answer_the_same_include_line() {
|
|
let tree = Tree::new("links");
|
|
let defs = tree.write("inc/defs.svh", "`define W 8\n");
|
|
tree.write(
|
|
"rtl/top.sv",
|
|
"`include \"defs.svh\"\n`include \"gone.svh\"\nmodule t;\nendmodule\n",
|
|
);
|
|
tree.write("files.f", "+incdir+inc\nrtl/top.sv\ninc/defs.svh\n");
|
|
let (ws, uri) = workspace_over(&tree, "rtl/top.sv");
|
|
let target = path_to_uri(&defs).expect("uri").as_str().to_string();
|
|
|
|
// One link: the resolvable include, on the quoted path itself.
|
|
assert_eq!(
|
|
only_link(&ws, &uri),
|
|
(0, 9, target.clone()),
|
|
"the second include resolves to nothing"
|
|
);
|
|
|
|
// And go-to-definition from anywhere on that line agrees with it.
|
|
let doc = ws.document(&uri).expect("open");
|
|
for offset in [0u32, 3, 10, 18] {
|
|
let found = definition(&ws, doc, offset).expect("a definition at {offset}");
|
|
assert_eq!(found.uri.as_str(), target, "at offset {offset}");
|
|
assert_eq!(found.range, Range::default(), "the top of the included file");
|
|
}
|
|
assert!(definition(&ws, doc, 19).is_none(), "past the closing quote");
|
|
assert!(definition(&ws, doc, 25).is_none(), "the unresolvable include line");
|
|
}
|
|
|
|
#[test]
|
|
fn a_path_with_a_space_in_it_comes_back_percent_encoded() {
|
|
// `path_to_uri` owns the encoding; this pins that an include target
|
|
// goes through it rather than being pasted into a URI as written.
|
|
let tree = Tree::new("spaces");
|
|
let defs = tree.write("inc dir/defs.svh", "`define W 8\n");
|
|
tree.write("rtl/top.sv", "`include \"../inc dir/defs.svh\"\n");
|
|
tree.write("files.f", "rtl/top.sv\n");
|
|
let (ws, uri) = workspace_over(&tree, "rtl/top.sv");
|
|
|
|
let (_, _, target) = only_link(&ws, &uri);
|
|
assert!(target.contains("inc%20dir/defs.svh"), "got {target}");
|
|
assert_eq!(target, path_to_uri(&defs).expect("uri").as_str());
|
|
}
|
|
|
|
#[test]
|
|
fn an_include_typed_since_the_last_rebuild_is_already_clickable() {
|
|
// The graph is rebuilt on save; the buffer's own includes are resolved
|
|
// live, so a line just typed does not wait for one.
|
|
let tree = Tree::new("fresh");
|
|
let defs = tree.write("rtl/defs.svh", "`define W 8\n");
|
|
tree.write("rtl/top.sv", "module t;\nendmodule\n");
|
|
tree.write("files.f", "rtl/top.sv\n");
|
|
let (mut ws, uri) = workspace_over(&tree, "rtl/top.sv");
|
|
assert!(document_links(&ws, &uri).is_empty(), "the premise: nothing yet");
|
|
|
|
ws.set_document(uri.clone(), "`include \"defs.svh\"\nmodule t;\nendmodule\n".to_string());
|
|
let target = path_to_uri(&defs).expect("uri").as_str().to_string();
|
|
assert_eq!(only_link(&ws, &uri), (0, 9, target));
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_that_includes_nothing_reaches_nothing() {
|
|
let tree = Tree::new("noedges");
|
|
let lone = tree.write("m.sv", "module m;\nendmodule\n");
|
|
let graph = IncludeGraph::build(
|
|
&[(lone.clone(), "module m;\nendmodule\n".to_string())],
|
|
Vec::new(),
|
|
);
|
|
assert_eq!(graph.reachable(vec![lone.clone()]), HashSet::from([lone]));
|
|
}
|
|
|
|
/// Order-of-magnitude perf checks, not run as part of the ordinary suite:
|
|
/// timing assertions in a shared runner are flaky by nature. Run with
|
|
/// `cargo test --release -p lucisv_server --bin lucisv-server perf -- --ignored --nocapture`.
|
|
mod perf {
|
|
use super::*;
|
|
|
|
/// Every source file of the checked-in corpus, read once.
|
|
fn corpus() -> Vec<(PathBuf, String)> {
|
|
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
|
let mut out = Vec::new();
|
|
let mut stack = vec![root];
|
|
while let Some(dir) = stack.pop() {
|
|
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if path.is_dir() {
|
|
stack.push(path);
|
|
continue;
|
|
}
|
|
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
|
|
if matches!(extension, "v" | "vh" | "sv" | "svh") {
|
|
if let Ok(text) = fs::read_to_string(&path) {
|
|
out.push((path, text));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
out
|
|
}
|
|
|
|
#[test]
|
|
#[ignore]
|
|
fn building_the_graph_over_the_whole_corpus_is_milliseconds() {
|
|
// The cost this feature adds to every index rebuild. Measured
|
|
// 2026-08-25: 860 files (119 of which include something), ~6ms
|
|
// release / this machine — a line scan of each file plus one
|
|
// `is_file` per include, next to the tokenize-and-analyze pass
|
|
// the same rebuild already runs over the same 860 files.
|
|
let sources = corpus();
|
|
assert!(sources.len() > 500, "the corpus is checked in: got {}", sources.len());
|
|
let start = std::time::Instant::now();
|
|
let graph = IncludeGraph::build(&sources, Vec::new());
|
|
let elapsed = start.elapsed();
|
|
eprintln!(
|
|
"perf: include graph over {} corpus files in {elapsed:?} ({} files include something)",
|
|
sources.len(),
|
|
graph.edges.len()
|
|
);
|
|
}
|
|
}
|
|
|
|
/// QA finding (M10, MEDIUM), fixed 2026-08-25: `` `include`` with no
|
|
/// whitespace before the opening delimiter used to be missed, though
|
|
/// `vlog_parser`'s lexer — the scanner's behavioral reference — ends the
|
|
/// directive name at the first character that cannot be part of one and
|
|
/// so lexes `` `include"x.svh" `` as one directive
|
|
/// (`crates/vlog_parser/src/lexer.rs:219-238`). The scanner now matches
|
|
/// it, and still declines the keyword-prefix case.
|
|
#[test]
|
|
fn a_missing_space_before_the_delimiter_is_still_an_include() {
|
|
let quoted = one("`include\"nospace.svh\"\n");
|
|
assert_eq!(quoted.target, "nospace.svh");
|
|
assert_eq!(&"`include\"nospace.svh\"\n"[quoted.path_span.as_range()], "\"nospace.svh\"");
|
|
assert_eq!(one("`include<nospace.svh>\n").target, "nospace.svh", "the angled form too");
|
|
assert!(scan("`includes\"x.svh\"\n").is_empty(), "but not another directive's name");
|
|
assert!(scan("`include_foo\"x.svh\"\n").is_empty(), "nor a longer name");
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod qa_scope_probe {
|
|
use super::*;
|
|
use crate::settings::ClientSettings;
|
|
use crate::uri::path_to_uri;
|
|
use std::fs;
|
|
|
|
/// QA (M10 include-nav): the link/definition capabilities resolve purely
|
|
/// off disk (`IncludeGraph::resolve` never consults `sources`/the index),
|
|
/// so a header the filelist does not name — only its directory's incdir
|
|
/// does — is still clickable. Only `find_define`'s narrowing is
|
|
/// index-scoped ("an include is not an index edge", per the Status/TODO
|
|
/// section); `documentLink`/`definition` are not, and that asymmetry is
|
|
/// not currently spelled out in the Assumptions section. Not a defect —
|
|
/// matches how `vcs`/`xrun` resolve a header outside `-f`'s own file
|
|
/// list — but pinned here since it was previously untested.
|
|
#[test]
|
|
fn a_link_resolves_to_a_file_the_filelist_never_names() {
|
|
let dir = std::env::temp_dir().join(format!("lucisv_qa_outscope_{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&dir);
|
|
fs::create_dir_all(dir.join("inc")).expect("mkdir");
|
|
// defs.svh exists on disk but is not named in files.f.
|
|
let defs = dir.join("inc/defs.svh");
|
|
fs::write(&defs, "`define W 1\n").expect("write");
|
|
let top = dir.join("top.sv");
|
|
fs::write(&top, "`include \"defs.svh\"\nmodule top;\nendmodule\n").expect("write");
|
|
fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\n").expect("write");
|
|
|
|
let mut ws = Workspace::default();
|
|
ws.set_client_settings(ClientSettings {
|
|
filelist: Some(dir.join("files.f").display().to_string()),
|
|
..Default::default()
|
|
});
|
|
ws.open_whole_workspace(vec![dir.clone()]);
|
|
let uri = path_to_uri(&top).expect("uri");
|
|
ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read"));
|
|
|
|
let links = document_links(&ws, &uri);
|
|
assert_eq!(links.len(), 1, "the link still resolves off disk, scope or not: {links:#?}");
|
|
assert_eq!(links[0].target, path_to_uri(&defs), "got {links:#?}");
|
|
|
|
let _ = fs::remove_dir_all(&dir);
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod qa_round2 {
|
|
use super::*;
|
|
use std::fs;
|
|
|
|
/// QA round 2: the dev's own collision test only tries two colliding
|
|
/// spellings; three in scope still has to collapse to "ambiguous", not
|
|
/// pick a majority or a first-writer. `folded`'s `and_modify` sets `None`
|
|
/// unconditionally once a collision exists, so a third colliding entry is
|
|
/// a no-op over an already-`None` slot rather than something that could
|
|
/// re-arm it — confirmed here rather than only read off the source.
|
|
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
|
#[test]
|
|
fn three_files_colliding_on_one_folded_spelling_stay_ambiguous() {
|
|
let dir =
|
|
std::env::temp_dir().join(format!("lucisv_qa_r2_threeway_{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&dir);
|
|
fs::create_dir_all(&dir).expect("mkdir");
|
|
let top = dir.join("top.sv");
|
|
fs::write(&top, "x\n").expect("write");
|
|
// Only one needs to exist on the real fs for `is_file` to succeed at
|
|
// all; `folded` is built from `sources`, never from a directory read.
|
|
let a = dir.join("Defs.svh");
|
|
fs::write(&a, "`define W 1\n").expect("write");
|
|
let sources = vec![
|
|
(a, "`define W 1\n".to_string()),
|
|
(dir.join("DEFS.svh"), "`define W 2\n".to_string()),
|
|
(dir.join("defS.svh"), "`define W 3\n".to_string()),
|
|
];
|
|
let graph = IncludeGraph::build(&sources, Vec::new());
|
|
let include = scan("`include \"defs.svh\"\n").into_iter().next().expect("one");
|
|
assert_eq!(
|
|
graph.resolve(Some(&top), &include),
|
|
Some(dir.join("defs.svh")),
|
|
"ambiguous among three colliding spellings, so the path as written"
|
|
);
|
|
}
|
|
|
|
/// QA round 2: a case-mismatched target that resolves on disk but names a
|
|
/// file *outside* the graph's `sources` (excluded by the filelist, say)
|
|
/// must come back exactly as before this fix — `folded` only ever learns
|
|
/// about in-scope files, so an out-of-scope collision has no entry to
|
|
/// find and falls through to the "no match" arm, unchanged.
|
|
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
|
#[test]
|
|
fn a_case_mismatch_on_a_file_outside_the_graphs_scope_is_unchanged() {
|
|
let dir =
|
|
std::env::temp_dir().join(format!("lucisv_qa_r2_outscope_{}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&dir);
|
|
fs::create_dir_all(&dir).expect("mkdir");
|
|
let top = dir.join("top.sv");
|
|
fs::write(&top, "x\n").expect("write");
|
|
// On disk, but never passed to `IncludeGraph::build` as a source.
|
|
fs::write(dir.join("Defs.svh"), "`define W 1\n").expect("write");
|
|
let graph = IncludeGraph::build(&[], Vec::new());
|
|
let include = scan("`include \"defs.svh\"\n").into_iter().next().expect("one");
|
|
assert_eq!(
|
|
graph.resolve(Some(&top), &include),
|
|
Some(dir.join("defs.svh")),
|
|
"nothing in scope to adopt a spelling from, so the pre-fix answer stands"
|
|
);
|
|
}
|
|
}
|