diff --git a/TODO.md b/TODO.md index a4177a2..ac379d6 100644 --- a/TODO.md +++ b/TODO.md @@ -604,7 +604,7 @@ section only tracks the milestones. - [x] **M9 `file-watching`** — `workspace/didChangeWatchedFiles` for sources and the filelist; reindex on external changes (git pull, filelist edits outside the editor). -- [ ] **M10 `include-nav`** — clickable `` `include`` lines resolved +- [x] **M10 `include-nav`** — clickable `` `include`` lines resolved through the filelist's `+incdir+`s; cross-file `` `define`` lookup along the include graph. - [ ] **M11 `hierarchy`** — module hierarchy both directions (who diff --git a/crates/vfmt_core/src/filelist.rs b/crates/vfmt_core/src/filelist.rs index 33fdc9d..9425161 100644 --- a/crates/vfmt_core/src/filelist.rs +++ b/crates/vfmt_core/src/filelist.rs @@ -30,7 +30,8 @@ pub const MAX_NESTING_DEPTH: usize = 256; pub struct Filelist { /// Every existing source file it lists, in list order, without repeats. pub files: Vec, - /// `+incdir+` directories, resolved but otherwise unused today. + /// `+incdir+` directories, resolved. Searched by the server's + /// `` `include`` resolution (`docs/features/include-nav/README.md`). pub incdirs: Vec, /// `+define+NAME` / `+define+NAME=VALUE`, recorded but unused today. pub defines: Vec<(String, Option)>, diff --git a/crates/vfmt_server/src/hover.rs b/crates/vfmt_server/src/hover.rs index 50d5519..b01a06d 100644 --- a/crates/vfmt_server/src/hover.rs +++ b/crates/vfmt_server/src/hover.rs @@ -9,7 +9,7 @@ use lsp_types::{Hover, HoverContents, MarkupContent, MarkupKind, Uri}; use vlog_parser::defines::Define; use vlog_parser::token::Token; use vlog_parser::TextRange; -use vlog_semantic::{Definition, Symbol}; +use vlog_semantic::{Definition, FileId, Symbol}; use crate::locate::{display_name, line_number}; use crate::state::{Document, Workspace}; @@ -26,8 +26,9 @@ pub fn hover(ws: &Workspace, uri: &Uri, offset: u32) -> Option { // ---------------------------------------------------------------------- /// A macro usage under the cursor: the file's own definition wins, then the -/// workspace's — **all** of the workspace's, because no `` `include`` graph is -/// modelled and picking one would be a guess. +/// one it reaches through its `` `include``s, then the workspace's — **all** +/// of the workspace's, because outside the include graph picking one would be +/// a guess. fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { let token = doc.tokens.iter().find(|t| t.is_macro() && t.span.contains(offset))?; let name = macro_name(token)?; @@ -36,7 +37,7 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { return Some(markdown(doc, define_text(name, define, None), token.span)); } - let candidates = ws.index().find_define(name); + let candidates = narrowed_to_the_include_graph(ws, doc, ws.index().find_define(name)); if candidates.is_empty() { return Some(markdown(doc, format!("`` `{name} `` — no definition found"), token.span)); } @@ -61,6 +62,38 @@ fn macro_hover(ws: &Workspace, doc: &Document, offset: u32) -> Option { Some(markdown(doc, joined, token.span)) } +/// The one definition this file actually *reaches*, when there is exactly +/// one, and every candidate otherwise. +/// +/// The include graph is the only thing that can order two definitions of one +/// macro name, so where it has an unambiguous answer the hover shows that +/// answer alone. Where it does not — nothing reachable defines the name, or +/// several reachable files do — the honest all-candidates list from before +/// this feature stands: an empty include graph must never make hover worse +/// than it was (`docs/features/include-nav/README.md`). +fn narrowed_to_the_include_graph<'a>( + ws: &Workspace, + doc: &Document, + candidates: Vec<(FileId, &'a Define)>, +) -> Vec<(FileId, &'a Define)> { + if candidates.len() < 2 { + return candidates; + } + let reachable = crate::includes::reachable_from(ws, doc); + if reachable.is_empty() { + return candidates; + } + let narrowed: Vec<(FileId, &Define)> = candidates + .iter() + .filter(|(file, _)| ws.index().path(*file).is_some_and(|p| reachable.contains(p))) + .cloned() + .collect(); + match narrowed.len() { + 1 => narrowed, + _ => candidates, + } +} + /// The macro's name: the identifier after the backtick, argument list excluded. fn macro_name(token: &Token) -> Option<&str> { let rest = token.text.strip_prefix('`')?; @@ -258,6 +291,125 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + /// A workspace whose files are `files`, with `top.sv` opened. + fn included(tag: &str, files: &[(&str, &str)]) -> (PathBuf, Workspace, Uri) { + let dir = temp_dir(tag); + for (name, text) in files { + fs::write(dir.join(name), text).expect("write"); + } + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let top = dir.join("top.sv"); + let uri = path_to_uri(&top).expect("uri"); + ws.set_document(uri.clone(), fs::read_to_string(&top).expect("read")); + (dir, ws, uri) + } + + /// A `top.sv` using `` `W ``, with whatever include lines precede it. + fn top_using_w(includes: &str) -> String { + format!("{includes}module top;\n wire [`W-1:0] a;\nendmodule\n") + } + + #[test] + fn one_hop_of_include_picks_the_definition_the_file_actually_reaches() { + // Two files define `W`; only one of them is included. Before the + // include graph this hover listed both and refused to choose. + let (dir, ws, uri) = included( + "reach1", + &[ + ("a.svh", "`define W 8\n"), + ("b.svh", "`define W 16\n"), + ("top.sv", &top_using_w("`include \"a.svh\"\n")), + ], + ); + let body = text_of( + &hover(&ws, &uri, at(&top_using_w("`include \"a.svh\"\n"), "`W-")).expect("hover"), + ); + assert!(body.contains("`define W 8"), "the reachable one: got {body}"); + assert!(!body.contains("`define W 16"), "and not the other: got {body}"); + assert!(body.contains("a.svh:1"), "named with its origin: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn two_hops_of_include_reach_just_as_far() { + let text = top_using_w("`include \"mid.svh\"\n"); + let (dir, ws, uri) = included( + "reach2", + &[ + ("mid.svh", "`include \"deep.svh\"\n"), + ("deep.svh", "`define W 8\n"), + ("elsewhere.svh", "`define W 16\n"), + ("top.sv", &text), + ], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("`define W 8") && body.contains("deep.svh:1"), "got {body}"); + assert!(!body.contains("`define W 16"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn an_include_cycle_terminates_and_both_files_stay_reachable() { + let text = top_using_w("`include \"a.svh\"\n"); + let (dir, ws, uri) = included( + "reachcycle", + &[ + ("a.svh", "`include \"b.svh\"\n"), + ("b.svh", "`include \"a.svh\"\n`define W 8\n"), + ("elsewhere.svh", "`define W 16\n"), + ("top.sv", &text), + ], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("`define W 8") && body.contains("b.svh:2"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_definition_nothing_includes_is_still_shown_when_it_is_all_there_is() { + // The fallback that must not regress: an unreachable definition is + // better than none, and a project that does not use `` `include`` at + // all sees exactly what it saw before this feature. + let text = top_using_w(""); + let (dir, ws, uri) = + included("reachnone", &[("far.svh", "`define W 8\n"), ("top.sv", &text)]); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("`define W 8") && body.contains("far.svh:1"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn two_definitions_neither_of_them_reachable_are_still_both_listed() { + let text = top_using_w("`include \"empty.svh\"\n"); + let (dir, ws, uri) = included( + "reachambiguous", + &[ + ("empty.svh", "// nothing here\n"), + ("a.svh", "`define W 8\n"), + ("b.svh", "`define W 16\n"), + ("top.sv", &text), + ], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("is defined 2 times"), "the honest answer: got {body}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn two_reachable_definitions_are_listed_rather_than_guessed_between() { + // The graph orders nothing here — both files are included — so the + // all-candidates answer stands. + let text = top_using_w("`include \"a.svh\"\n`include \"b.svh\"\n"); + let (dir, ws, uri) = included( + "reachboth", + &[("a.svh", "`define W 8\n"), ("b.svh", "`define W 16\n"), ("top.sv", &text)], + ); + let body = text_of(&hover(&ws, &uri, at(&text, "`W-")).expect("hover")); + assert!(body.contains("is defined 2 times"), "got {body}"); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn hovering_a_use_shows_its_declaration() { let text = "module m;\n localparam WIDTH = 8;\n wire [WIDTH-1:0] a;\nendmodule\n"; @@ -315,3 +467,107 @@ mod tests { assert_eq!(macro_name(token), Some("M")); } } + +/// QA (M10 include-nav): a defect pinned rather than fixed — see the QA log +/// in `docs/features/include-nav/README.md` for the writeup and the fix +/// options weighed there. +#[cfg(test)] +mod qa_findings { + use super::*; + use crate::settings::ClientSettings; + use crate::uri::path_to_uri; + use std::fs; + + /// The angled form is correctly wired into the narrowing overlay: not a + /// finding, recorded as a permanent regression test since the six tests + /// the dev shipped in this file only exercise the quoted form. + #[test] + fn an_angled_include_narrows_hover_same_as_a_quoted_one() { + let dir = std::env::temp_dir().join(format!("vfmt_qa_hover_sys_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("inc")).expect("mkdir"); + fs::write(dir.join("inc/uvm_macros.svh"), "`define W 8\n").expect("write"); + fs::write(dir.join("elsewhere.svh"), "`define W 16\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "`include \nmodule top;\n wire [`W-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/uvm_macros.svh\nelsewhere.svh\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_roots(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover"); + let body = match &h.contents { + HoverContents::Markup(m) => m.value.clone(), + _ => panic!("markup"), + }; + assert!(body.contains("`define W 8") && body.contains("uvm_macros.svh:1"), "got {body}"); + assert!(!body.contains("`define W 16"), "got {body}"); + + let _ = fs::remove_dir_all(&dir); + } + + /// QA finding (M10, HIGH), fixed 2026-08-25. On a case-insensitive + /// filesystem (the default on macOS — this machine — and on Windows) + /// `Path::is_file` succeeds for a case-mismatched candidate, and + /// `normalize` only folds `.`/`..`, so `IncludeGraph::resolve` used to + /// return the path *as written* in the `` `include ``. `WorkspaceIndex` + /// meanwhile records the file under the case that was read off disk, so + /// the two spellings were different `PathBuf`s and + /// `narrowed_to_the_include_graph`'s `reachable.contains(p)` check + /// silently missed a file that **is** genuinely reachable. + /// + /// Below, `top.sv` includes both `defs.svh` (case-mismatched: the file is + /// `Defs.svh`) and `other.svh` (spelled correctly), and both are equally + /// reachable in truth. Two reachable definitions must fall back to the + /// honest "defined 2 times" answer — the same thing + /// `two_reachable_definitions_are_listed_rather_than_guessed_between` + /// above pins for the case-matched spelling. Before the fix this narrowed + /// to the correctly-cased file alone and showed it with full confidence, + /// which is "may only narrow, never widen" failing in the one direction + /// that matters. `IncludeGraph::as_the_index_spells_it` now re-spells a + /// resolved path to the index's own when exactly one in-scope file + /// matches it case-insensitively. + /// + /// Case-gated: only macOS/Windows default to a case-insensitive + /// filesystem, so only there does the premise (`is_file` succeeding for + /// the wrong case) hold. + #[cfg(any(target_os = "macos", target_os = "windows"))] + #[test] + fn a_case_mismatched_include_still_counts_as_reachable() { + let dir = std::env::temp_dir().join(format!("vfmt_qa_hover_case_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).expect("mkdir"); + fs::write(dir.join("Defs.svh"), "`define W 8\n").expect("write"); + fs::write(dir.join("other.svh"), "`define W 16\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "`include \"defs.svh\"\n`include \"other.svh\"\nmodule top;\n \ + wire [`W-1:0] a;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let h = hover(&ws, &uri, top_text.find("`W-").expect("needle") as u32).expect("hover"); + let body = match &h.contents { + HoverContents::Markup(m) => m.value.clone(), + _ => panic!("markup"), + }; + // Both files are reachable, so neither may be dropped and neither may + // be presented as the answer. + assert!(body.contains("is defined 2 times"), "got {body}"); + assert!(body.contains("`define W 8") && body.contains("Defs.svh:1"), "got {body}"); + assert!(body.contains("`define W 16") && body.contains("other.svh:1"), "got {body}"); + + let _ = fs::remove_dir_all(&dir); + } +} diff --git a/crates/vfmt_server/src/includes.rs b/crates/vfmt_server/src/includes.rs new file mode 100644 index 0000000..2739e00 --- /dev/null +++ b/crates/vfmt_server/src/includes.rs @@ -0,0 +1,783 @@ +//! `` `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 `` 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 { + 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 { + 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: includes +/// are a handful of lines per file, so there is nothing here worth updating +/// incrementally. +#[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, + /// Including file → the files it resolves to, in source order. + edges: HashMap>, + /// Every in-scope file, exactly as the index spells it. + known: HashSet, + /// 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>, +} + +impl IncludeGraph { + /// Scan every in-scope file for its `` `include``s and resolve them. + pub fn build(sources: &[(PathBuf, String)], incdirs: Vec) -> IncludeGraph { + let mut graph = IncludeGraph { + incdirs, + edges: HashMap::new(), + known: sources.iter().map(|(path, _)| path.clone()).collect(), + folded: HashMap::new(), + }; + // Built before the edges: `resolve` consults it, and an edge resolved + // against a half-filled table would be keyed inconsistently. + for (path, _) in sources { + let Some(key) = path.to_str().map(str::to_lowercase) else { continue }; + graph + .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())); + } + for (path, text) in sources { + let targets: Vec = scan(text) + .iter() + .filter_map(|include| graph.resolve(Some(path), include)) + .collect(); + if !targets.is_empty() { + graph.edges.insert(path.clone(), targets); + } + } + graph + } + + /// 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 `` 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 { + let target = Path::new(&include.target); + if target.is_absolute() { + return target.is_file().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| candidate.is_file()) + .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) -> HashSet { + let mut seen: HashSet = 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 `vfmt_core`'s lexical rule. +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 { + 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 { + let (_, path) = resolved(ws, doc).into_iter().find(|(inc, _)| inc.span.contains(offset))?; + 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 { + let seeds: Vec = 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 \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!("vfmt_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 \n"); + + let graph = IncludeGraph::build(&[], vec![tree.path.join("inc")]); + let include = one("`include \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_roots(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 vfmt_server --bin vfmt-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\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!("vfmt_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_roots(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!("vfmt_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!("vfmt_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" + ); + } +} diff --git a/crates/vfmt_server/src/main.rs b/crates/vfmt_server/src/main.rs index 7f7cb78..9b44f35 100644 --- a/crates/vfmt_server/src/main.rs +++ b/crates/vfmt_server/src/main.rs @@ -14,6 +14,7 @@ mod diagnostics; mod folding; mod format; mod hover; +mod includes; mod inlay; mod lint; mod locate; @@ -37,8 +38,8 @@ use std::path::PathBuf; use lsp_server::Connection; use lsp_types::{ CodeActionKind, CodeActionOptions, CodeActionProviderCapability, CompletionOptions, - ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, InlayHintOptions, - InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, + DocumentLinkOptions, ExecuteCommandOptions, FoldingRangeProviderCapability, InitializeParams, + InlayHintOptions, InlayHintServerCapabilities, OneOf, PositionEncodingKind, RenameOptions, SemanticTokensFullOptions, SemanticTokensLegend, SemanticTokensOptions, SemanticTokensServerCapabilities, ServerCapabilities, SignatureHelpOptions, TextDocumentSyncCapability, TextDocumentSyncKind, WorkDoneProgressOptions, @@ -79,6 +80,14 @@ fn capabilities() -> ServerCapabilities { document_range_formatting_provider: Some(OneOf::Left(true)), definition_provider: Some(OneOf::Left(true)), references_provider: Some(OneOf::Left(true)), + // `` `include`` lines, underlined and ctrl-clickable. Every link is + // returned with its target already resolved, so there is nothing for + // `documentLink/resolve` to do — and go-to-definition answers the same + // lines, for the editors that have no ctrl-click. + document_link_provider: Some(DocumentLinkOptions { + resolve_provider: Some(false), + work_done_progress_options: WorkDoneProgressOptions::default(), + }), // The cursor on a `begin` highlights its own `end`, matched over the // token stream; anywhere else, the symbol under it highlights its own // other occurrences in this file. The handler declines a position @@ -213,6 +222,7 @@ mod tests { assert!(caps.document_range_formatting_provider.is_some()); assert!(caps.definition_provider.is_some()); assert!(caps.references_provider.is_some()); + assert!(caps.document_link_provider.is_some()); assert!(caps.document_highlight_provider.is_some()); assert!(caps.folding_range_provider.is_some()); assert!(caps.hover_provider.is_some()); @@ -227,6 +237,12 @@ mod tests { assert!(caps.inlay_hint_provider.is_some()); } + #[test] + fn document_links_resolve_nothing_because_every_target_is_already_known() { + let options = capabilities().document_link_provider.expect("document links"); + assert_eq!(options.resolve_provider, Some(false)); + } + #[test] fn inlay_hints_resolve_nothing_because_every_hint_is_complete() { let Some(OneOf::Right(InlayHintServerCapabilities::Options(options))) = diff --git a/crates/vfmt_server/src/nav.rs b/crates/vfmt_server/src/nav.rs index 2dfd6a0..0f4ea93 100644 --- a/crates/vfmt_server/src/nav.rs +++ b/crates/vfmt_server/src/nav.rs @@ -5,16 +5,24 @@ use lsp_types::{DocumentHighlight, DocumentHighlightKind, Location, Uri}; use vlog_parser::TextRange; use vlog_semantic::{Definition, Semantics, SymbolId}; +use crate::includes; use crate::locate::location; use crate::state::{Document, Workspace}; use crate::uri::path_to_uri; -/// Go-to-definition, through both layers: the in-file symbol table first, then -/// the workspace overlay. An ambiguous workspace answer returns **every** -/// location rather than guessing — LSP accepts a list, and the index's -/// duplicate-name policy says the guess would be a coin flip. +/// Go-to-definition, through three layers: an `` `include`` line first, then +/// the in-file symbol table, then the workspace overlay. An ambiguous +/// workspace answer returns **every** location rather than guessing — LSP +/// accepts a list, and the index's duplicate-name policy says the guess would +/// be a coin flip. pub fn definition(ws: &Workspace, uri: &Uri, offset: u32) -> Vec { let Some(doc) = ws.document(uri) else { return Vec::new() }; + // An include line holds no identifiers the two layers below could answer + // for, so asking first costs nothing and keeps the case in one place + // (`docs/features/include-nav/README.md`). + if let Some(location) = includes::definition(ws, doc, offset) { + return vec![location]; + } match doc.external.definition_of(&doc.semantics, offset) { Some(Definition::Local(symbol)) => { if symbol.name_span.is_empty() { @@ -331,6 +339,34 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn an_include_line_jumps_into_the_file_it_names() { + // Go-to-definition's third case, and the one that answers where the + // other two have no identifier to work with. + let dir = temp_dir("include"); + let defs = dir.join("defs.svh"); + fs::write(&defs, "`define W 8\n").expect("write"); + let top_path = dir.join("top.sv"); + let top_text = "`include \"defs.svh\"\nmodule top;\nendmodule\n"; + fs::write(&top_path, top_text).expect("write"); + + let mut ws = Workspace::default(); + ws.open_roots(vec![dir.clone()]); + let uri = path_to_uri(&top_path).expect("uri"); + ws.set_document(uri.clone(), top_text.to_string()); + + let locations = definition(&ws, &uri, at(top_text, "defs.svh")); + assert_eq!(locations.len(), 1); + assert_eq!(locations[0].uri, path_to_uri(&defs).expect("uri")); + assert_eq!(locations[0].range.start.line, 0, "the top of the included file"); + assert_eq!(locations[0].range.end.character, 0); + + // And a cursor on the module below is unaffected by any of this. + assert!(definition(&ws, &uri, at(top_text, "module top") + 7).len() == 1); + + let _ = fs::remove_dir_all(&dir); + } + // ------------------------------------------------------------------ // cross-file references // ------------------------------------------------------------------ diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 8cc6e76..aca99be 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -15,30 +15,31 @@ use lsp_types::notification::{ ShowMessage, }; use lsp_types::request::{ - CodeActionRequest, Completion, DocumentHighlightRequest, DocumentSymbolRequest, ExecuteCommand, - FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest, - PrepareRenameRequest, RangeFormatting, References, RegisterCapability, Rename, Request as _, - SemanticTokensFullRequest, SignatureHelpRequest, UnregisterCapability, WorkspaceSymbolRequest, + CodeActionRequest, Completion, DocumentHighlightRequest, DocumentLinkRequest, + DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition, + HoverRequest, InlayHintRequest, PrepareRenameRequest, RangeFormatting, References, + RegisterCapability, Rename, Request as _, SemanticTokensFullRequest, SignatureHelpRequest, + UnregisterCapability, WorkspaceSymbolRequest, }; use lsp_types::{ CodeActionKind, CodeActionParams, CompletionParams, DidChangeConfigurationParams, DidChangeTextDocumentParams, DidChangeWatchedFilesParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams, DidSaveTextDocumentParams, DocumentFormattingParams, - DocumentHighlightParams, DocumentRangeFormattingParams, DocumentSymbolParams, - DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, GotoDefinitionParams, - GotoDefinitionResponse, HoverParams, InlayHintParams, LogMessageParams, MessageType, Position, - PublishDiagnosticsParams, ReferenceParams, RegistrationParams, RenameParams, - SemanticTokensParams, SemanticTokensResult, ShowMessageParams, SignatureHelpParams, - TextDocumentPositionParams, UnregistrationParams, Uri, WorkspaceSymbolParams, - WorkspaceSymbolResponse, + DocumentHighlightParams, DocumentLinkParams, DocumentRangeFormattingParams, + DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams, + GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams, LogMessageParams, + MessageType, Position, PublishDiagnosticsParams, ReferenceParams, RegistrationParams, + RenameParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams, + SignatureHelpParams, TextDocumentPositionParams, UnregistrationParams, Uri, + WorkspaceSymbolParams, WorkspaceSymbolResponse, }; use serde::de::DeserializeOwned; use serde_json::Value; use crate::state::Workspace; use crate::{ - code_action, completion, diagnostics, folding, format, hover, inlay, nav, pairs, ports, rename, - settings, signature, symbols, tokens, watch, + code_action, completion, diagnostics, folding, format, hover, includes, inlay, nav, pairs, + ports, rename, settings, signature, symbols, tokens, watch, }; /// What the client said it can do, read once at `initialize` because that is @@ -147,6 +148,12 @@ impl Server { .unwrap_or_default(); to_value(GotoDefinitionResponse::Array(locations)) }), + // The underline half of include navigation. Unresolvable includes + // are simply absent from the list — never an error, and never a + // link that goes nowhere. + DocumentLinkRequest::METHOD => decode(request).and_then(|p: DocumentLinkParams| { + to_value(includes::document_links(&self.workspace, &p.text_document.uri)) + }), References::METHOD => decode(request).and_then(|p: ReferenceParams| { let include = p.context.include_declaration; let at = p.text_document_position; diff --git a/crates/vfmt_server/src/state.rs b/crates/vfmt_server/src/state.rs index 0a43043..8db85f1 100644 --- a/crates/vfmt_server/src/state.rs +++ b/crates/vfmt_server/src/state.rs @@ -19,6 +19,7 @@ use vfmt_core::walk::{collect_files, EXTENSIONS}; use crate::candidates::Candidates; use crate::convert::Positions; +use crate::includes::IncludeGraph; use crate::settings::ClientSettings; use crate::uri::uri_to_path; @@ -81,6 +82,24 @@ impl Document { } } +/// What the scope ladder decided: the files to index, the directories an +/// `` `include`` in them is looked for in, and what to tell the user. +#[derive(Default)] +struct Scope { + files: Vec, + /// The filelist's `+incdir+`s, in filelist order. Empty for every rung + /// but the filelist — nothing else names an include path. + incdirs: Vec, + warnings: Vec, +} + +/// A `Scope` with its files read: what one index rebuild works from. +struct Sources { + texts: Vec<(PathBuf, String)>, + incdirs: Vec, + warnings: Vec, +} + /// Every open buffer plus the workspace index they are resolved against. #[derive(Default)] pub struct Workspace { @@ -91,6 +110,9 @@ pub struct Workspace { /// same file list. Precomputed because completion fires per keystroke and /// nothing that walks the workspace may. candidates: Candidates, + /// What every in-scope file `` `include``s, and the `+incdir+`s an + /// include is looked for in. Rebuilt with `index`, from the same list. + includes: IncludeGraph, /// The last `vfmt.*` settings a client pushed. Default until it does. client: ClientSettings, } @@ -112,6 +134,11 @@ impl Workspace { &self.candidates } + /// The `` `include`` graph, as of the last index rebuild. + pub fn includes(&self) -> &IncludeGraph { + &self.includes + } + /// Whether the client opened a workspace at all. /// /// Without one the index's scope is the open buffers' own directories, so @@ -168,15 +195,19 @@ impl Workspace { /// file that is gone, say. Rendering them is `server.rs`'s job; this /// module speaks no protocol. pub fn rebuild_index(&mut self) -> Vec { - let (sources, warnings) = self.collect_sources(); + let scope = self.collect_sources(); + let sources = scope.texts; self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str()))); // Built here, from the same list, so a file the scope ladder excluded // contributes no completion candidates either. self.candidates = Candidates::build(&self.index, &sources); + // Same list again: an `` `include`` in a file the scope excluded is + // not an edge, and a file it excluded is not a hop away from anything. + self.includes = IncludeGraph::build(&sources, scope.incdirs); for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index); } - warnings + scope.warnings } /// The in-scope files and their current text — what a refactoring reads. @@ -185,26 +216,26 @@ impl Workspace { /// kept: a refactoring is a rare, user-initiated request, and a second /// copy of the workspace in memory is a high price for saving one walk. pub fn sources(&self) -> Vec<(PathBuf, String)> { - self.collect_sources().0 + self.collect_sources().texts } /// Read every in-scope file, with open buffers overriding disk. - fn collect_sources(&self) -> (Vec<(PathBuf, String)>, Vec) { - let (files, warnings) = self.source_files(); - let mut sources: Vec<(PathBuf, String)> = Vec::new(); - for path in files { + fn collect_sources(&self) -> Sources { + let scope = self.source_files(); + let mut texts: Vec<(PathBuf, String)> = Vec::new(); + for path in scope.files { if let Ok(text) = fs::read_to_string(&path) { - sources.push((path, text)); + texts.push((path, text)); } } // Open buffers override what is on disk, and contribute themselves // when they are not on disk at all. for doc in self.docs.values() { let Some(path) = doc.path.clone() else { continue }; - sources.retain(|(p, _)| p != &path); - sources.push((path, doc.text.clone())); + texts.retain(|(p, _)| p != &path); + texts.push((path, doc.text.clone())); } - (sources, warnings) + Sources { texts, incdirs: scope.incdirs, warnings: scope.warnings } } /// The text of a workspace file: the open buffer if there is one, else @@ -233,13 +264,21 @@ impl Workspace { /// A configured filelist that cannot be read falls back to rung 2 (or 3) /// with a warning. An editor that shows no symbols because of a typo in a /// path is worse than one that quietly indexes what it can and says so. - fn source_files(&self) -> (Vec, Vec) { - let Some(path) = self.filelist_path() else { return (self.default_files(), Vec::new()) }; + /// + /// Only rung 1 can carry `+incdir+` directories: a walked workspace names + /// none, so an `` `include`` there resolves against the including file's + /// own directory alone (`docs/features/include-nav/README.md`). + fn source_files(&self) -> Scope { + let Some(path) = self.filelist_path() else { + return Scope { files: self.default_files(), ..Default::default() }; + }; match vfmt_core::filelist::read(&path) { - Ok(list) => (list.files, list.warnings), - Err(problem) => { - (self.default_files(), vec![format!("{problem} — indexing the workspace instead")]) - } + Ok(list) => Scope { files: list.files, incdirs: list.incdirs, warnings: list.warnings }, + Err(problem) => Scope { + files: self.default_files(), + incdirs: Vec::new(), + warnings: vec![format!("{problem} — indexing the workspace instead")], + }, } } @@ -700,6 +739,75 @@ mod tests { assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]); } + /// Where `ws` would look for `` `include "" `` written in `from`. + fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option { + let text = format!("`include \"{name}\"\n"); + let include = crate::includes::scan(&text).into_iter().next().expect("one include"); + ws.includes().resolve(Some(from), &include) + } + + /// A tree whose filelist names one `+incdir+` and nests a filelist naming + /// another, with a header in each — plus one only the nested incdir holds. + fn incdir_tree(name: &str) -> Tree { + let tree = Tree::new(name); + tree.package("rtl/a.sv", "a"); + tree.write("first/defs.svh", "`define W 1\n"); + tree.write("ip/include/defs.svh", "`define W 2\n"); + tree.write("ip/include/ip_only.svh", "`define X 1\n"); + tree.write("ip/ip.f", "+incdir+include\n"); + tree.write("files.f", "+incdir+first\n-f ip/ip.f\nrtl/a.sv\n"); + tree + } + + #[test] + fn a_filelists_incdirs_reach_the_include_graph_in_filelist_order() { + // M1 recorded `+incdir+` and used it for nothing; this is the wire + // that spends it. A nested `-f`'s incdirs come through flattened, + // *after* the ones named before the `-f` — which is the order an + // include is searched in, so it is worth pinning here and not only in + // the parser. + let tree = incdir_tree("incdirs"); + let mut ws = Workspace::default(); + ws.set_client_settings(using_filelist("files.f")); + let warnings = ws.open_roots(vec![tree.path.clone()]); + assert!(warnings.is_empty(), "{warnings:?}"); + + let from = tree.path.join("rtl/a.sv"); + assert_eq!( + resolved_include(&ws, &from, "defs.svh"), + Some(tree.path.join("first/defs.svh")), + "the root filelist's incdir is searched before the nested one's" + ); + assert_eq!( + resolved_include(&ws, &from, "ip_only.svh"), + Some(tree.path.join("ip/include/ip_only.svh")), + "and the nested one is searched at all" + ); + } + + #[test] + fn without_a_filelist_there_are_no_incdirs_at_all() { + // Rung 2 of the ladder names no include path, so an `` `include`` + // there has only the including file's own directory to go on. + let tree = incdir_tree("noincdirs"); + let mut ws = Workspace::default(); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!(resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), None); + } + + #[test] + fn a_broken_filelist_leaves_the_include_graph_without_incdirs() { + let tree = incdir_tree("badfilelistincdirs"); + let mut ws = Workspace::default(); + ws.set_client_settings(using_filelist("typo.f")); + ws.open_roots(vec![tree.path.clone()]); + assert_eq!( + resolved_include(&ws, &tree.path.join("rtl/a.sv"), "defs.svh"), + None, + "the walk fallback names no include path" + ); + } + #[test] fn the_scan_takes_only_source_extensions() { let tree = Tree::new("extensions"); diff --git a/crates/vfmt_server/tests/e2e.rs b/crates/vfmt_server/tests/e2e.rs index 74feaa8..02e1a28 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -1863,3 +1863,232 @@ fn a_client_that_cannot_watch_files_is_never_asked_to() { let _ = std::fs::remove_dir_all(&dir); } + +/// A project whose filelist carries a `+incdir+`: `top.sv` includes a header +/// that only that incdir can find, and two files in the index define the same +/// macro — one reachable through the include, one not. +const INCLUDE_TOP: &str = "\ +`include \"defs.svh\" +module include_top; + wire [`WIDTH-1:0] a; +endmodule +"; + +#[test] +fn include_links_definition_and_a_reachable_define_round_trip_over_the_wire() { + // What only an e2e test can check: that `documentLinkProvider` is + // advertised in the shape a client reads, that the `+incdir+` from a + // `vfmt.toml`-configured filelist survives the whole trip from disk to a + // resolved URI, and that the two capabilities answer the same line. + let dir = temp_dir("include"); + std::fs::create_dir_all(dir.join("inc")).expect("inc"); + std::fs::create_dir_all(dir.join("other")).expect("other"); + std::fs::create_dir_all(dir.join("rtl")).expect("rtl"); + let defs = dir.join("inc/defs.svh"); + std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); + std::fs::write(dir.join("other/elsewhere.svh"), "`define WIDTH 16\n").expect("write"); + let top = dir.join("rtl/top.sv"); + std::fs::write(&top, INCLUDE_TOP).expect("write"); + std::fs::write( + dir.join("files.f"), + "+incdir+inc\nrtl/top.sv\ninc/defs.svh\nother/elsewhere.svh\n", + ) + .expect("write"); + std::fs::write(dir.join("vfmt.toml"), "filelist = \"files.f\"\n").expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top.display()); + let defs_uri = format!("file://{}", defs.display()); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(INCLUDE_TOP).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + // The cursor in the middle of the quoted path on line 0. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":12}}}}}}"# + )), + // `` `WIDTH `` on line 2: two files define it, one of them included. + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":9}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + + let capabilities = &response(1)["result"]["capabilities"]; + assert_eq!(capabilities["documentLinkProvider"]["resolveProvider"], serde_json::json!(false)); + + let links = response(2)["result"].as_array().expect("a link list"); + assert_eq!(links.len(), 1, "one resolvable include: {links:#?}"); + assert_eq!(links[0]["target"], defs_uri.as_str(), "found through `+incdir+inc`"); + assert_eq!(links[0]["range"]["start"], serde_json::json!({"line": 0, "character": 9})); + assert_eq!(links[0]["range"]["end"], serde_json::json!({"line": 0, "character": 19})); + + let locations = response(3)["result"].as_array().expect("a location list"); + assert_eq!(locations.len(), 1, "{locations:#?}"); + assert_eq!(locations[0]["uri"], defs_uri.as_str(), "the same file the link names"); + assert_eq!(locations[0]["range"]["start"], serde_json::json!({"line": 0, "character": 0})); + + let hover = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(hover.contains("`define WIDTH 8"), "the included definition: got {hover}"); + assert!(!hover.contains("`define WIDTH 16"), "not the unreachable one: got {hover}"); + assert!(hover.contains("defs.svh:1"), "named with its origin: got {hover}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// QA (M10 include-nav): the same round trip as +/// `include_links_definition_and_a_reachable_define_round_trip_over_the_wire`, +/// but with a space in the workspace directory name. `path_to_uri` +/// percent-encodes a space (pinned in `includes.rs`'s +/// `a_path_with_a_space_in_it_comes_back_percent_encoded`) but every e2e +/// session in this file hand-rolls its `file://` URIs unencoded, because none +/// of them has ever needed a space in a directory name — so this is the first +/// test that exercises the wire format's own percent-encoding requirement +/// (`uri_to_path` decodes it, `rootUri`/`textDocument.uri` must supply it) for +/// this feature specifically. +#[test] +fn include_nav_round_trips_in_a_workspace_whose_directory_has_a_space() { + let dir = temp_dir("include spaced"); + std::fs::create_dir_all(dir.join("inc")).expect("inc"); + let defs = dir.join("inc/defs.svh"); + std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); + let top = dir.join("top.sv"); + std::fs::write(&top, INCLUDE_TOP).expect("write"); + std::fs::write(dir.join("files.f"), "+incdir+inc\ntop.sv\ninc/defs.svh\n").expect("write"); + std::fs::write(dir.join("vfmt.toml"), "filelist = \"files.f\"\n").expect("write"); + + // The URIs the wire actually needs: the directory's own space encoded, + // matching what `path_to_uri` would produce and `uri_to_path` requires. + let root = format!("file://{}", dir.display()).replace(' ', "%20"); + let uri = format!("file://{}", top.display()).replace(' ', "%20"); + let defs_uri = format!("file://{}", defs.display()).replace(' ', "%20"); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(INCLUDE_TOP).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":12}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/hover","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":2,"character":9}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + + let links = response(2)["result"].as_array().expect("a link list"); + assert_eq!(links.len(), 1, "{links:#?}"); + assert_eq!(links[0]["target"], defs_uri.as_str(), "the space survived the round trip"); + + let locations = response(3)["result"].as_array().expect("a location list"); + assert_eq!(locations.len(), 1, "{locations:#?}"); + assert_eq!(locations[0]["uri"], defs_uri.as_str()); + + let hover = response(4)["result"]["contents"]["value"].as_str().expect("hover markdown"); + assert!(hover.contains("`define WIDTH 8"), "got {hover}"); + assert!(hover.contains("defs.svh:1"), "got {hover}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// QA round 2 (M10 include-nav, re-verifying the case-sensitivity fix): the +/// real binary, over the real wire, on a case-mismatched include — the thing +/// a unit test calling `IncludeGraph::resolve` or `hover(...)` directly +/// cannot fully settle, since it never proves what URI actually lands in the +/// client's hands. `top.sv` writes `` `include "defs.svh"``, but the file on +/// disk (and in the filelist) is `Defs.svh`. Both `documentLink`'s target and +/// F12 (`textDocument/definition`) must carry the *index's* spelling +/// (`Defs.svh`), not the as-written one — otherwise an editor that diffs URIs +/// against its own open-buffer list (most do, to decide whether a jump lands +/// on an already-open tab) would treat the two spellings as different files. +/// Case-gated: the premise is a case-insensitive default filesystem. +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[test] +fn go_to_definition_lands_on_the_indexs_own_spelling_not_the_includes() { + let dir = temp_dir("casewire"); + let defs = dir.join("Defs.svh"); + std::fs::write(&defs, "`define WIDTH 8\n").expect("write"); + let top = dir.join("top.sv"); + let top_text = "`include \"defs.svh\"\nmodule top;\nendmodule\n"; + std::fs::write(&top, top_text).expect("write"); + + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", top.display()); + // The URI the *index* would produce for the real file, capital D. + let indexed_uri = format!("file://{}", defs.display()); + assert_ne!(indexed_uri, indexed_uri.to_lowercase(), "premise: the fixture has a real capital"); + + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top_text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/documentLink","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":0,"character":12}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let messages = talk(&session); + let response = |id: u32| -> &serde_json::Value { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("no {id}: {messages:#?}")) + }; + + let links = response(2)["result"].as_array().expect("a link list"); + assert_eq!(links.len(), 1, "{links:#?}"); + assert_eq!( + links[0]["target"], + indexed_uri.as_str(), + "documentLink must carry the index's own spelling, not `defs.svh` as written" + ); + + let locations = response(3)["result"].as_array().expect("a location list"); + assert_eq!(locations.len(), 1, "{locations:#?}"); + assert_eq!( + locations[0]["uri"], + indexed_uri.as_str(), + "F12 must land on the file the way the index spells it" + ); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/filelist/README.md b/docs/features/filelist/README.md index d6075e2..75d0748 100644 --- a/docs/features/filelist/README.md +++ b/docs/features/filelist/README.md @@ -16,12 +16,16 @@ filelist are a `filelist` key in `vfmt.toml` and the VS Code setting ## Assumptions -- **The filelist is a *scope*, not a build description.** M1 records - `+incdir+` and `+define+` and uses neither: vfmt does not preprocess, so +- **The filelist is a *scope*, not a build description.** M1 recorded + `+incdir+` and `+define+` and used neither: vfmt does not preprocess, so an include path and a macro value change nothing about what the index - contains. They are parsed now because a filelist that silently dropped + contains. They were parsed anyway because a filelist that silently dropped them would have to be re-parsed later, and because "unknown flag" warnings - would otherwise fire on the two flags every real filelist carries. + would otherwise fire on the two flags every real filelist carries. Since + **M10 (`docs/features/include-nav/README.md`) `incdirs` is consumed**: it + is the search path an `` `include`` is resolved against, in filelist order, + after the including file's own directory. `defines` is still recorded and + used by nothing. - **A token starting `//` or `#` ends the line.** That is comment handling at token granularity, not at character granularity: `rtl/a.sv // top` comments out `// top`, and a path that genuinely contains a `#` in the @@ -78,7 +82,7 @@ pub const MAX_NESTING_DEPTH: usize = 256; // how deep `-f` may nest pub struct Filelist { pub files: Vec, // existing source files, in list order, deduped - pub incdirs: Vec, // recorded, unused in M1 + pub incdirs: Vec, // searched by `` `include`` since M10 pub defines: Vec<(String, Option)>, // recorded, unused in M1 pub warnings: Vec, // ":: " } @@ -158,9 +162,12 @@ extension code change. - [ ] Not done, deliberately: the CLI does not consume `filelist` yet (M1 is config-level plumbing plus the server; a `vfmt -f` flag is its own change with its own exit-code questions). -- [ ] Not done, deliberately: `+incdir+`/`+define+` feed nothing. vfmt does - not preprocess; when `` `include`` resolution arrives, it consumes - `Filelist::incdirs` unchanged. +- [x] ~~Not done, deliberately: `+incdir+`/`+define+` feed nothing.~~ + `` `include`` resolution arrived in M10 and consumes `Filelist::incdirs` + unchanged, exactly as this line predicted — resolved, in filelist order, + nested `-f` incdirs flattened in place + (`docs/features/include-nav/README.md`). `+define+` still feeds + nothing: vfmt does not preprocess. - [ ] Not done, deliberately: no file watching. The filelist is re-read on every index rebuild (save, settings change, open with no root). diff --git a/docs/features/include-nav/README.md b/docs/features/include-nav/README.md new file mode 100644 index 0000000..cb9a8c9 --- /dev/null +++ b/docs/features/include-nav/README.md @@ -0,0 +1,557 @@ +# include-nav + +## Goal + +Make `` `include`` a real edge in the project graph instead of a comment the +server walks past. M1 taught vfmt to read a filelist and recorded its +`+incdir+` directories; nothing consumed them, so an include line was dead +text and a `` `define`` used in one file could only be answered with "here is +every definition of that name in the workspace, good luck". This milestone +builds the include graph once per index rebuild and spends it twice: an +include line becomes clickable (`textDocument/documentLink` for the underline, +`textDocument/definition` for F12 and `gd`), and hover on `` `NAME `` prefers +the definition the hovered file actually *reaches* through its includes — the +first thing vfmt has that can order two definitions of one macro name. + +## Assumptions + +- **The search order is the EDA one.** For `` `include "path" ``: an absolute + path is itself; otherwise the **including file's own directory** first, then + each **`+incdir+` of the configured filelist, in filelist order** (nested + `-f` incdirs included, flattened where the reader met them). The first + candidate that is an existing file wins. With no filelist there are no + incdirs at all, so only the own-directory rung applies — which is exactly + what `vcs`/`xrun` do when handed no `+incdir+`. +- **`` `include `` is kept by the lexer and resolved against the + incdirs only**, skipping the own-directory rung. The angled form is not in + IEEE 1800 — it is a vendor extension borrowed from C — and the one thing + every tool that supports it agrees on is that it means "a header from the + search path, not from beside me". The lexer keeps the whole directive line + verbatim (`TokenKind::Directive`), so the form survives to here unchanged; + the only alternative was to drop such lines silently, which would leave a + UVM-style `` `include `` mysteriously unclickable. +- **An include is found by a line scan, not by the parser.** The directive has + to be the first non-whitespace thing on its line, and the opening delimiter + the very next thing after the keyword — whitespace between them is optional, + which is what the lexer does too (`` `include"x.svh" `` is one directive + there and here). That is how every real one + is written, it costs one pass over the bytes instead of a second tokenize of + the workspace (see Cost), and it works in a buffer that does not lex — the + state an editor is in half the time someone is typing. What it gives up: a + `` `include`` written at the start of a line *inside a block comment* is + scanned as one (it would then resolve, and get a link, in a commented-out + region), and a `` `include`` that is not first on its line is missed. Both + are rare and both fail in the harmless direction. +- **An unresolvable include is silent.** No link, no location, no diagnostic. + vfmt does not preprocess, and a project routinely builds with incdirs vfmt + was never told about; underlining those lines in red would be wrong far + more often than right. +- **The graph is rebuilt whole with the index**, from the same source list, so + a file the scope ladder excluded is neither an includer nor a target. The + *open buffer's own* includes are resolved live against its current text + instead, so a line typed since the last save is already clickable. +- **A file the index does not cover contributes no `` `define``s**, even when + an include reaches it. Reachability narrows `find_define`'s answer; it + cannot add to it. A `.svh` outside the filelist is therefore invisible to + hover exactly as it was before this feature. +- **Reachability is a set, not an order.** The graph knows *which* files a + file pulls in, not in what order or under which `` `ifdef``, and it does not + model `` `undef`` or redefinition across files. So it is only allowed to + decide when the answer is unambiguous — exactly one reachable definition — + and otherwise it steps aside and the all-candidates hover stands. +- **A resolved path is re-spelled the way the index spells that file, when + the index is sure which file it is.** macOS and Windows default to + case-insensitive filesystems, so `` `include "defs.svh" `` opens a file + named `Defs.svh` quite happily — and the path as written is then a + *different* `PathBuf` from the one the index recorded, which makes every + comparison against the index miss a file that really is reachable. After + resolution, an exact match keeps its spelling, and otherwise **exactly one** + in-scope file matching case-insensitively lends the graph its own spelling. + Zero matches (a header outside the index's scope) or several (a + case-sensitive filesystem genuinely holding both spellings) keep the path as + written: guessing between two real files would be exactly the widening this + rule exists to prevent. It is a lookup in the file list the graph is built + from — no filesystem call, no platform test — and it applies to the + `definition`/`documentLink` targets too, so F12 lands on the file the index + knows. +- **Symlinks are not resolved.** Resolved paths are folded lexically + (`.`/`..` removed) so they compare equal to the index's own spelling, the + same lexical rule `vfmt_core::config::Discovery` and + `vfmt_core::filelist` follow. + +## Handshakes + +### Consumed + +- `vfmt_core::filelist::Filelist::incdirs` — recorded since M1, used here for + the first time. Resolved absolute and in filelist order, which is the order + they are searched. **`state.rs` no longer drops them**: the scope ladder + carries them alongside the file list (`Scope`/`Sources` in `state.rs`) and + hands them to the graph on every rebuild. Only rung 1 (a filelist) can + produce any; rungs 2 and 3 name none. +- `vlog_semantic::WorkspaceIndex::find_define` — **unchanged**. It still + returns every workspace definition, in file order, implying no resolution + order. The include-graph precedence is an overlay applied in + `vfmt_server::hover`, so no `vlog_semantic` change was needed at all and the + workspace-index contract is exactly what it was. +- `vlog_parser` — nothing new. The line scan reads text; the lexer's + treatment of `` `include`` (one `TokenKind::Directive` token carrying the + whole line) is only relied on as documentation that the angled form is not + thrown away. + +### Promised + +- `vfmt_server::includes::IncludeGraph` — `build`, `resolve` and `reachable` + are the whole surface. `Workspace::includes()` hands the current one out. + A default-constructed `Workspace` has an empty graph, which resolves + nothing and reaches nothing; every caller must behave as it did before this + feature when that is what it gets. +- `vfmt_server::includes::scan` — the one include scanner. `documentLink`, + `definition` and the graph build all go through it, so the three can never + disagree about what an include line is. +- **A third lexical `normalize`.** `includes.rs` carries its own copy of the + `.`/`..` folding that `vfmt_core::filelist::Reader::normalize` and + `vfmt_core::config::Discovery::absolute` already have (both private, both + on stateful structs). Two copies were deliberate duplication (filelist work + log, 2026-08-24); three is the point at which extracting a + `vfmt_core::path::normalize` and pointing all three at it becomes worth + doing. **Request for the lead**, not done here: it touches two modules + outside this feature's scope. + +## Cost + +The graph build is what this feature adds to every index rebuild. Measured +2026-08-25 on the checked-in 860-file corpus, `--release`: + +| | | +|---|---| +| files scanned | 860 | +| files that include something | 119 | +| include graph build | **~6 ms** | +| the `WorkspaceIndex::build` it runs beside | ~322 ms | + +So roughly 2% of a rebuild that was already happening — a line scan per file +plus one `is_file` per include. Pinned by an `#[ignore]`d probe +(`cargo test --release -p vfmt_server --bin vfmt-server includes::tests::perf +-- --ignored --nocapture`), the same shape as `inlay.rs`'s: timing assertions +in a shared runner are flaky, so it prints and asserts nothing but the +corpus's presence. + +## Status / TODO + +- [x] `crates/vfmt_server/src/includes.rs`: `scan`, `Include`, `IncludeGraph` + (`build`/`resolve`/`reachable`), the two capability entry points. +- [x] `+incdir+` plumbed from the filelist through `state.rs` to the graph, + nested `-f` incdirs included and in order. +- [x] `textDocument/documentLink`, advertised with `resolveProvider: false`. +- [x] `textDocument/definition` on an include line, sharing the computation. +- [x] Hover's include-graph precedence, one definition or the old answer. +- [x] Tests: resolution order, angled form, unresolved, links + definition on + one fixture, a space in the path, one and two hops, a cycle, an + unreachable-only fallback, nested-filelist incdirs, no-filelist mode, + and one e2e stdio session covering all three requests. +- [x] QA round 1: case-canonicalization against the index's spelling (HIGH), + and the scanner loosened to the lexer's own rule for a missing space + before the delimiter (MEDIUM). +- [x] `cargo fmt`, `cargo clippy --all-targets`, `cargo test --workspace`, + `node editors/vscode/smoke.js`. +- [ ] **Not done, deliberately:** no `` `ifdef``/`` `undef`` awareness. A + reachable definition inside a false `` `ifdef`` branch is still offered; + modelling that means preprocessing, which TODO.md §7 rules out. +- [ ] **Not done, deliberately:** an include is not an index edge. Symbols + declared in an included file are found because the *file* is in the + index, not because it was included; a header outside the filelist stays + invisible. +- [ ] **Not done, deliberately:** no completion of include paths, and no + diagnostic for an include that resolves to nothing. Both are their own + features, and the second one needs vfmt to be sure it knows every + incdir — which it is not. + +## Work log + +### 2026-08-25 — dev agent, M10 + +Written in the order the brief lists: resolver, then the two capabilities, +then the hover overlay. Decisions worth recording: + +- **One scanner, a line scan, used by everything.** The alternative was to + read includes off `Document::tokens` for the open buffer (the lexer already + gets comments and strings right) and to line-scan for the graph, since + tokenizing the workspace a second time to build the graph would have cost + far more than the graph. Two scanners would have meant `documentLink` and + the graph disagreeing in exactly the corner cases nobody tests. The price is + named under Assumptions: a `` `include`` at the start of a line inside a + block comment is treated as one. +- **The angled form resolves against incdirs only.** The lexer keeps it — + checked, not assumed: a throwaway `vlog_parser` example (deleted, not + committed) tokenized `` `include `` and got back one + `Directive` token whose text is the whole line, because the raw lexer + captures every line directive verbatim to end of line. So the choice was + resolve-it-somehow or drop it. The C convention is the only + precedent every tool that supports the form agrees on, and it makes the two + spellings mean different things — which is the only reason to write the + angled one. +- **Resolution is live for the open buffer, cached for everything else.** The + graph is rebuilt on save like the index; a link that appeared only after a + save would look broken. The buffer's own includes are therefore resolved + from its current text on each request (one line scan of one file), and only + the hops *past* the buffer come from the graph. +- **The hover overlay narrows, never widens, and only when it is sure.** It + runs at all only when `find_define` returned two or more candidates, and + replaces them only when exactly one is reachable. Every other shape — no + graph, nothing reachable, several reachable — leaves the pre-existing + all-candidates answer byte-for-byte alone, which is what keeps this from + being a regression for a project that does not use `` `include``. +- **No `vlog_semantic` change.** The brief allowed a minimal one; none turned + out to be needed. `find_define`'s contract ("no resolution order is + implied") is still true, and the ordering lives in the server where the + graph lives. + +**Files touched outside this feature's own module**, all of them the wiring +the brief asked for: `state.rs` (the `Scope`/`Sources` structs that carry +incdirs, the `includes` field and its accessor, three tests), `main.rs` (the +module, the `documentLink` capability, two tests), `server.rs` (the +`documentLink` handler), `nav.rs` (the include case of `definition`, one +test), `hover.rs` (the narrowing overlay, six tests). + +**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy +--all-targets` silent; `cargo test --workspace` green — 1420 tests, 28 of them +new (16 `includes`, 6 `hover`, 3 `state`, 1 `nav`, 1 `main`, 1 e2e session). +`node editors/vscode/smoke.js target/debug/vfmt-server` OK. Perf measured as +above. No new dependency; no version bump. + +### 2026-08-25 — dev agent, QA round 1 fixes + +**Finding 1 (HIGH), fixed: a case-mismatched include silently dropped a +reachable definition.** `IncludeGraph` now carries the in-scope file list it +was built from — `known` (exact spellings) and `folded` (lower-cased spelling +→ the one file that has it, or `None` when several do) — and every path +`resolve` returns goes through `as_the_index_spells_it` +(`crates/vfmt_server/src/includes.rs`). Exact match: unchanged. Exactly one +case-insensitive match: the index's spelling is adopted, so the graph edge, +the reachability comparison in `hover.rs` and the URI go-to-definition hands +the editor all name the same file. Zero or several matches: the path as +written, which is what a case-sensitive filesystem and an out-of-scope header +both keep doing. + +Why this shape rather than `fs::canonicalize`: canonicalization is a syscall +per include *and* resolves symlinks, which this project deliberately does not +do anywhere (`config-discovery`'s lexical rule). The tables are built from a +list the graph already holds, so the fix costs one `HashSet`/`HashMap` of the +workspace's paths and one lower-casing pass at build time — the perf probe +still reports ~6ms over the 860-file corpus, unchanged within noise. + +Why the zero/several cases stay as written: adopting a spelling when two real +files fold together would be a guess between them, which is the *widening* +the narrowing rule exists to prevent. Better to keep the honest all-candidates +hover. + +**Regression test** — QA's pinned test flipped from asserting the bug to +asserting the fix: `hover::qa_findings::a_case_mismatched_include_still_counts_as_reachable` +now requires "is defined 2 times" with both `Defs.svh:1` and `other.svh:1` +named. Added `includes::tests::a_resolved_path_is_re_spelled_the_way_the_index_spells_it` +at the level the rule is implemented: nothing in scope → as written; one +in-scope match → the index's spelling; two folding together → as written. +Both are `cfg(any(target_os = "macos", target_os = "windows"))`-gated, as +QA's was, because the premise is `is_file` succeeding for a spelling the file +does not have. + +**Mutation-checked**, because a regression test that cannot fail is worthless: +made `as_the_index_spells_it` return its argument unchanged and re-ran — both +tests failed, exactly the shape QA reproduced. Restored. + +**Finding 2 (MEDIUM), fixed: `` `include"x.svh" `` (no space) was missed.** +The whitespace requirement in `include_on_line` is gone; the opening +delimiter must simply be the next thing after the keyword, which keeps +`` `includes "x.svh" `` and `` `include_foo"x.svh" `` declining (the +delimiter does not immediately follow) without a separate guard. QA's pinned +test became +`includes::tests::a_missing_space_before_the_delimiter_is_still_an_include`, +covering both delimiters and both keyword-prefix cases. Assumptions updated. + +**Finding 3**: nothing to do, as ruled — QA's probe pins intended behavior. + +**Gates after the fixes.** `cargo fmt --all -- --check` clean, `cargo clippy +--all-targets` silent, `cargo test --workspace` green — 1426 tests on macOS +(1425 QA left, plus the one new test above; no test was removed, QA's two +pinned ones were rewritten in place). `node +editors/vscode/smoke.js target/debug/vfmt-server` OK. Perf probe re-run after +the fix: ~6ms over the 860-file corpus. + +## QA log + +### 2026-08-25 — QA agent, M10 + +**Gates.** `cargo fmt --all -- --check` clean. `cargo clippy --all-targets` +silent. `cargo test --workspace` green — re-ran repeatedly while adding the +tests below; **1425** tests at the end (1420 the dev shipped + 5 added here). +`node editors/vscode/smoke.js target/debug/vfmt-server` OK. Perf probe re-run: +`cargo test --release -p vfmt_server --bin vfmt-server includes::tests::perf +-- --ignored --nocapture` → **6.5ms** over the 860-file corpus (dev measured +~6ms) — confirmed, order of magnitude and absolute number both hold. + +**Design review of the riskiest piece — hover's "narrows, never widens" +claim.** Traced both edge cases the brief asked about directly: +- *Define in the hovered file itself, plus a same-name define elsewhere.* + Safe by construction: `macro_hover` (`hover.rs:36`) checks + `doc.defines.latest(name)` **before** it ever calls + `narrowed_to_the_include_graph`. A file's own definition short-circuits the + whole overlay; the include graph never gets a vote. No finding. +- *A define reached only through a path the resolver can't resolve.* + `reachable_from` (`includes.rs`) seeds from `resolved(ws, doc)`, which drops + any `` `include`` `graph.resolve` returns `None` for. If every include on + the seed hop is unresolved, `reachable_from` returns an empty set, and + `narrowed_to_the_include_graph` (`hover.rs:82-84`) takes the `reachable.is_empty()` + early return straight back to all-candidates. Safe. No finding. + +**Finding 1 — HIGH. Case-insensitive filesystem breaks the narrowing +invariant: a genuinely-reachable definition is silently dropped, and hover +shows a single wrong-confidence answer instead of the honest "defined N +times."** + +`IncludeGraph::resolve` (`includes.rs:121-135`) resolves an `` `include`` +by trying `dir.join(target).is_file()` and, on success, returning +`normalize(&found)` — the path **as written**, only `.`/`..`-folded, never +canonicalized against the filesystem's actual on-disk spelling. On the +default filesystem for macOS (this machine) and Windows — case-insensitive, +case-preserving — `is_file()` succeeds for a spelling that differs only in +case from the real file name. `WorkspaceIndex`, in the meantime, records the +file under whatever case `collect_files`/the filelist reader actually read +off disk. The two `PathBuf`s differ, so the `reachable.contains(p)` check in +`narrowed_to_the_include_graph` (`hover.rs:88`) silently fails to recognize a +file that **is** reachable. + +Concretely: `top.sv` contains `` `include "defs.svh"`` and +`` `include "other.svh"``. The real file is `Defs.svh` (capital D); `other.svh` +is spelled correctly. Both are genuinely included and both define `` `W ``. +The two-reachable case is supposed to fall back to "is defined 2 times" (this +is exactly what `two_reachable_definitions_are_listed_rather_than_guessed_between` +in `hover.rs` pins for the case-matched case) — but here, `Defs.svh` drops out +of the `reachable.contains` comparison (not out of the graph — the edge is +there, just under the wrong-case key), leaving exactly one candidate. The +overlay then does precisely what it is built to do with one candidate: shows +it alone, with full confidence, never mentioning the other one exists. +Reproduced and pinned as `hover::qa_findings::qa_a_case_mismatched_include_silently_drops_a_reachable_define` +(`crates/vfmt_server/src/hover.rs`, gated `cfg(any(target_os = "macos", +target_os = "windows"))` since the premise needs a case-insensitive default +FS). The test asserts *today's* wrong output rather than the correct one, so +the suite stays green — a fix must touch this test. + +Not attempted here: this is a design decision (canonicalize `resolve`'s +output against the real directory entry — costly per include; or compare +paths case-insensitively only where narrowing needs to decide reachability; +or normalize both the graph's and the index's paths through one canonical +form) that belongs to the dev, not a QA-sized fix. **Recommend: fix before +shipping**, since it is a silent-wrong-answer failure of the feature's core +documented safety property, on the platform this was developed and tested on. + +**Finding 2 — LOW/MEDIUM. An undocumented scanner narrowing: `` `include`` +with no whitespace before the opening delimiter is silently missed, and it +diverges from the very lexer the README cites as this scanner's behavioral +reference.** + +`include_on_line` (`includes.rs:56`) requires `rest.starts_with(char::is_whitespace)` +right after stripping `` `include``, so `` `include"x.svh"`` (no space) scans +to nothing — no link, no definition, no graph edge, no diagnostic. But +`vlog_parser`'s lexer — which the Assumptions section leans on directly +("a throwaway `vlog_parser` example... tokenized `` `include `` +and got back one `Directive` token") — recognizes the directive name by +scanning identifier characters with no whitespace requirement at all +(`crates/vlog_parser/src/lexer.rs:219-238`, `is_line_directive` list at +line 702: `` `include"x.svh"`` lexes as one whole-line `Directive` token, +same as the spaced form). So this scanner is *stricter* than the tool it +claims consistency with, and unlike the two narrowings the README does +document (block-comment false positive, mid-line miss), this one isn't +written down anywhere. Real-world impact is small — nobody's style guide +omits the space — but it is a genuine, silent false negative and an +inconsistency between the documented behavioral reference and the actual +scan rule. Pinned as `includes::tests::qa_a_missing_space_before_the_quote_is_silently_missed`. +**Recommend:** either loosen the scanner to match the lexer (drop the +whitespace requirement, keep the `` `includes`` guard some other way — e.g. +require the next byte be `"` or `<|` rather than merely non-alphanumeric) or +add one sentence to the Assumptions section admitting the gap. Not a blocker. + +**Finding 3 — informational, not a defect.** `documentLink`/`definition` +resolve purely off disk (`IncludeGraph::resolve` takes no `sources`/index +argument), so a header the configured filelist never names — reachable only +through its incdir — is still clickable, even though it is outside +`WorkspaceIndex`'s scope. This is consistent with `vcs`/`xrun` (the search +path is not the same thing as the compiled unit list) and is not a bug, but +it is an asymmetry with `find_define`'s explicit index-scoping ("an include +is not an index edge") that the Assumptions section does not spell out for +the other two capabilities, and it was previously untested. Pinned as +`includes::qa_scope_probe::a_link_resolves_to_a_file_the_filelist_never_names`. +No action required. + +**Coverage added, no defect found:** +- `hover::qa_findings::an_angled_include_narrows_hover_same_as_a_quoted_one` — + the six hover narrowing tests the dev shipped only ever use the quoted + form; the angled (``) form narrows correctly too, now pinned. +- `crates/vfmt_server/tests/e2e.rs::include_nav_round_trips_in_a_workspace_whose_directory_has_a_space` — + the one e2e session for this feature used a plain temp dir; every other + e2e test in the file hand-rolls unencoded `file://` URIs, so a directory + with a space had never gone over the wire for any feature, this one + included. Passes: `path_to_uri`'s percent-encoding (already unit-tested in + `includes.rs`) round-trips correctly end to end. + +**Tried and found solid, no test added (already covered or the fix would be +redundant with an existing test):** +- Tab-indented `` `include``, CRLF line endings, a file whose last line is an + include with no trailing newline, `` `include?`` (keyword-prefix collision), + a string literal at line start beginning with the directive's own text — + all scan correctly or correctly decline, matching the documented rules. +- Two `` `include``s on one physical line: only the first (line-initial) one + is scanned, the second is silently dropped — this is the direct, intended + consequence of the documented "first non-whitespace on its line" rule, not + a separate gap. +- Resolution order (own dir beats every incdir), the angled form skipping the + own-directory rung, a relative `../` path that lexically escapes above the + workspace root (folds correctly to the real absolute path — `PathBuf::pop` + on an already-root path is a harmless no-op, matching POSIX `..`-at-root + semantics), and an absolute include — all match the dev's own tests and the + documented EDA search order; re-verified by direct code reading rather than + new tests, since the existing suite already exercises each one. +- 500 `` `include``s in one file: `documentLink` answered in 3.5ms — no + quadratic surprise (`resolved` scans once and resolves inline). +- Stale-graph honesty: an unsaved buffer edit that *adds* an include is + clickable immediately (`resolved()` scans the live buffer text for the + first hop), but any hop *past* that first one still comes from the graph as + of the last rebuild — exactly as the Assumptions section and work log say. + Not misleading; the README's own wording already draws this line correctly. + +**Verdict: ship after fixing Finding 1.** The scanner, resolver, and the two +navigation capabilities are solid — 500-include perf is fine, the search +order matches the documented EDA convention, and the narrowing overlay is +provably safe by construction in the two cases the brief worried about most +(a file's own definition, and an unresolvable seed). But Finding 1 is a real +violation of the feature's central documented promise ("narrows, never +widens, and only when it is sure") on the platform this shipped from, using +an unremarkable real-world input (one file whose include-site spelling +doesn't match its own filename's case — common when headers come from a +vendor IP or a different OS's checkout). It should not corrupt anything vfmt +formats (out of scope for the hard invariants in `CLAUDE.md`, which are about +formatter output), but it is a silently-wrong LSP answer, not a +conservatively-declined one, and that is exactly the failure mode this +feature was built to avoid. Finding 2 is real but low-impact and can ship +with a documentation fix or wait. Finding 3 needs nothing. + +### 2026-08-25 — QA agent, round 2 (re-verification of the dev's rework) + +Dev's rework: `IncludeGraph` now carries `known` (exact in-scope spellings) +and `folded` (lowercased spelling → the one in-scope file that has it, or +`None` when several do), and every `resolve` result passes through +`as_the_index_spells_it` (`includes.rs:179-188`) — an exact match keeps its +spelling; exactly one case-insensitive match adopts the index's spelling +(so the graph edge, `documentLink`'s target, and `definition`'s `Location` +URI all carry it); zero or several matches keep the path as written. Pure +`HashMap`/`HashSet` lookup, no `fs::canonicalize`. `include_on_line` +(`includes.rs:51-66`) dropped the whitespace-before-delimiter requirement: +the delimiter must be the very next byte after `` `include``, matching the +lexer, while `` `includes`` / `` `include_foo`` still decline because the +keyword itself doesn't match. Finding 1's test flipped to +`hover::qa_findings::a_case_mismatched_include_still_counts_as_reachable`, +now asserting "is defined 2 times" with both files named. Finding 2's test +flipped to `includes::tests::a_missing_space_before_the_delimiter_is_still_an_include`. + +**Gates, re-run clean.** `cargo fmt --all -- --check` clean. `cargo clippy +--all-targets` silent. `cargo test --workspace` green at **1429** — the +1426 the dev's rework landed at, plus 3 added in this round (below). Perf +probe re-run: **6.3ms** over the 860-file corpus (dev claimed ~7ms; this +machine has consistently measured 6-6.5ms across both rounds — same order of +magnitude, no regression). `node editors/vscode/smoke.js target/debug/vfmt-server` +OK. + +**Mechanism-level re-verification of Finding 1's fix.** Read +`as_the_index_spells_it` and the `folded` construction in `build` +(`includes.rs:104-134, 179-188`) directly rather than trusting the summary: + +- `known.contains(&path)` is checked first, so an exact-spelling match never + touches `folded` at all — the common case is untouched by the new logic. +- `folded` is populated with `.and_modify(|found| *found = None).or_insert_with(...)`. + A key seen once stores `Some(path)`; seen again, unconditionally flips to + `None` and *stays* `None` no matter how many more times the same key comes + through — verified this isn't a last-writer-wins bug by re-deriving it from + the `Entry` API semantics, then confirming with a fresh three-way collision + test (below) rather than trusting the two-file test the dev already had. +- `folded` is built entirely from `sources` (the in-scope file list handed to + `IncludeGraph::build`), never from a directory read or `fs::canonicalize`, + so a case collision against a file the graph was never told about (outside + the filelist's scope) has no entry to match and falls through to "keep the + path as written" — re-verified with a dedicated out-of-scope test rather + than assuming the "built from sources" comment is accurate. + +**Round-2 attacks, all done against real code/binaries, not by re-reading the +round-1 writeup:** + +1. **Three files colliding on one folded spelling, all in scope.** Extended + the dev's own two-file collision test to three + (`includes::qa_round2::three_files_colliding_on_one_folded_spelling_stay_ambiguous`, + `includes.rs`). Confirmed `None` sticks through a third collision and the + path comes back as written — no false adoption, no "third one breaks the + tie" surprise. +2. **Case-mismatched include whose target is out of scope.** A file that + really exists on disk under a different case, but was never passed to + `IncludeGraph::build` as a source (e.g. excluded by the filelist). + Confirmed unchanged behavior — the path comes back exactly as written, the + same answer this would have gotten before the fix + (`includes::qa_round2::a_case_mismatch_on_a_file_outside_the_graphs_scope_is_unchanged`). +3. **The real binary, once, on a case-mismatched fixture.** Unit tests calling + `resolve`/`hover` directly can't settle what URI an editor actually + receives, so this drives `vfmt-server` over real stdio JSON-RPC — the same + harness `e2e.rs` uses for every other capability. `top.sv` writes + `` `include "defs.svh"``; the real (and indexed) file is `Defs.svh`. + Confirmed both `documentLink`'s `target` and F12's `Location.uri` carry + the capital-D URI, not the as-written lowercase one + (`go_to_definition_lands_on_the_indexs_own_spelling_not_the_includes`, + `crates/vfmt_server/tests/e2e.rs`, case-gated). This is the one check none + of the unit-level tests — the dev's or mine — could have caught a + regression in: it is the only test that round-trips the URI through the + actual wire encoding (`path_to_uri`) with a real spawned process on the + other end. +4. **`` `include`` — angled, no space.** Already covered by the dev's + own flipped test (`a_missing_space_before_the_delimiter_is_still_an_include` + asserts `one("`include\n").target == "nospace.svh"`). + Independently re-confirmed by direct `scan()` call before writing this + entry; not re-added as a separate test since the dev's already pins it. +5. **A tab between the keyword and the quote.** `rest.trim_start()` + (`includes.rs:60`) trims every `char::is_whitespace` byte, tab included — + "whitespace optional" was never "whitespace forbidden", and nothing in the + rework narrowed it. Confirmed directly by calling `scan` on a line with a + literal tab between `` `include `` and the opening quote; not pinned as a + new test since it exercises the same `trim_start` call the dev's + spaced-form tests already cover and no distinct code path is at risk. +6. **Mutation check.** Temporarily reverted `as_the_index_spells_it` to + `{ path }` (identity) in a scratch copy, re-ran the full `vfmt_server` + unit suite: exactly two tests failed — + `includes::tests::a_resolved_path_is_re_spelled_the_way_the_index_spells_it` + and `hover::qa_findings::a_case_mismatched_include_still_counts_as_reachable` + — and nothing else. That is precisely the two tests whose whole point is + this function, with no collateral breakage and no false negative from a + test that would have passed either way. Restored the real implementation + before re-running the full gate suite. + +**Verdict: ship.** Finding 1 (HIGH) is fixed at the mechanism level, not just +at the level of the one scenario the round-1 test happened to check — the +three-way collision, the out-of-scope collision, and the real-binary wire +round trip were all attacks the fix's *design* had to survive, not just its +one pinned test, and it did. Finding 2 (LOW/MEDIUM) is fixed and the +whitespace-optional behavior is exactly as documented, angled and quoted +forms alike, tabs included. Finding 3 (informational) is unaffected by this +rework and still needs nothing. No new findings this round. + +## Review + +**2026-08-25 — lead.** Reviewed after QA round 2's ship verdict; gates +run independently (1429 tests, 0 failures). The one-scanner-three- +consumers design keeps links, definition and the graph from ever +disagreeing, and spending M1's until-now-unused `+incdir+`s here closes +a loop the plan had open since the first milestone. QA's HIGH was the +round's real work: the case-insensitive-filesystem trap produced exactly +the confident-incomplete hover this feature was built to avoid, and the +fix — re-spelling resolved paths the way the index spells them, latching +to ambiguity on collisions, no fs::canonicalize — is the boring pure +lookup I'd have asked for. Round-2 verified it by construction, by +three-way-collision attack, by real-wire F12, and by mutation. The +hover-narrowing invariant (narrow, never widen; local defines always +win) held under every probe. Accepted; M10 checked off in the umbrella +plan and TODO §8. diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md index 3e5d4eb..927f4be 100644 --- a/docs/features/refactor/README.md +++ b/docs/features/refactor/README.md @@ -159,7 +159,7 @@ built but nothing consumes yet. Ordered by value ÷ cost: didOpen only; a `git pull`, an external edit, or editing the `.f` filelist itself goes unnoticed until the next save. Register `workspace/didChangeWatchedFiles` (sources + the filelist) and reindex. -- [ ] **`` `include`` navigation and `+incdir+` consumption** — M1 records +- [x] **`` `include`` navigation and `+incdir+` consumption** — M1 records incdirs and nothing uses them; `` `include "x.svh" `` is not clickable and the define table stays per-file. Document links (or definition) on include lines, resolved through the filelist's incdirs, and a @@ -264,6 +264,7 @@ commit — in order: - [x] M7 references-nav — done, QA clean first pass, reviewed - [x] M8 inlay-hints — done, one QA HIGH fixed in-round, reviewed - [x] M9 file-watching — done, QA clean first pass, reviewed +- [x] M10 include-nav — done, one QA HIGH reworked, reviewed ## Work log diff --git a/docs/features/vfmt-server/README.md b/docs/features/vfmt-server/README.md index ef3ab9e..1c4bb0d 100644 --- a/docs/features/vfmt-server/README.md +++ b/docs/features/vfmt-server/README.md @@ -20,8 +20,9 @@ looks like language knowledge in here is a bug or a `Handshake` request. | `textDocument/rangeFormatting` | `vlog_formatter::format_range` | Same edit shape; the LSP `Range`'s *lines* become the engine's `--lines` (round 18) | | `textDocument/publishDiagnostics` | `vlog_parser::parse_source_tolerant` | Pushed on `didOpen`/`didChange`/`didSave`, full-text sync | | `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries | -| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex` | Macro body, or declaration kind + snippet | -| `textDocument/definition` | `Semantics` then `ExternalResolutions` | `Ambiguous` returns every location | +| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise | +| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` | +| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README | | `textDocument/references` | `vlog_refactor::find_references`, else `Semantics::references_of` | Cross-file when the symbol is one the workspace index holds (a module, a package, an exported member, a port); in-file for everything else, which is what keeps a local `wire` off the workspace walk. See `docs/features/references-nav/README.md` | | `textDocument/documentHighlight` | `pairs::analyze`, else `Semantics::references_of` | A scope keyword highlights its own closer; anything else highlights the symbol's occurrences in this file. Kind is always `Text`; neither answer means `null`, so the editor keeps its word highlighting. Same feature README | | `textDocument/foldingRange` | `pairs::analyze` + comment trivia | One `Region` per matched scope pair, folded through the line *before* the closer so `end`/`endmodule` stays visible, plus one `Comment` per multi-line block comment. An unmatched opener folds nothing. Same feature README | @@ -190,6 +191,7 @@ handler is milliseconds; the complexity of a worker pool buys nothing yet. |---|---|---| | a document's `Semantics` + tokens + diagnostics | every `didOpen`/`didChange` | one file, full recompute | | the `WorkspaceIndex` | `initialize`, every `didSave`, every `workspace/didChangeWatchedFiles`, and a changed `vfmt.exclude`/`vfmt.filelist` | full re-scan of the roots | +| the `` `include`` graph | with the `WorkspaceIndex`, from the same file list | a line scan per file (~6ms over the 860-file corpus). An open buffer's *own* includes are re-resolved on every request instead, so a line just typed is clickable before the next save | **Per-file recompute on every keystroke** is the strategy TODO.md §6 states ("per-file recompute is fine at Verilog file sizes"); salsa is explicitly @@ -381,10 +383,15 @@ Two rules that are easy to get wrong and are tested: `` `ifdef``-style directive is *not* included): the file's own `DefineTable::latest` wins, rendered as the joined body plus the definition's own source lines. If this file does not define it, - `WorkspaceIndex::find_define` supplies every workspace definition — **all - of them, each with its file and line**, because the index models no - `` `include`` graph and picking one silently would be a guess - (`docs/features/workspace-index/README.md` makes the same call). + `WorkspaceIndex::find_define` supplies every workspace definition, each + with its file and line — and since M10 the **`` `include`` graph gets to + narrow that list**: when the file reaches exactly one of the candidates + through its includes (transitively, cycles included), that one is shown + alone. When it reaches none of them, or more than one, every candidate is + listed as before — the index still models no order of its own + (`docs/features/workspace-index/README.md`), and the graph is only allowed + to speak where its answer is unambiguous + (`docs/features/include-nav/README.md`). 2. **A reference** resolved in-file: the symbol's kind, its name, and the source lines its `decl_span` covers. 3. **A reference** answered only by the workspace overlay: the kind and name, @@ -462,6 +469,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: parameter names on ordered connection lists, off the same `instantiation_plan` completion and signature help read. `docs/features/inlay-hints/README.md`. +- [x] `textDocument/documentLink` — delivered by **include-nav** (M10), + together with the include case of `textDocument/definition` and hover's + include-graph precedence for `` `define``. + `docs/features/include-nav/README.md`. - [ ] **Not done:** editor packaging (the VS Code extension and the `lspconfig` snippet are their own TODO.md §6 item).