Files
lucisv/crates/lucisv_server/src/state.rs
T

828 lines
35 KiB
Rust

//! What the server remembers: one analysis per open buffer, one index for the
//! workspace. The invalidation rules are in
//! `docs/features/lucisv-server/README.md`; the short version is that a buffer's
//! analysis is rebuilt on every change and the index only on save.
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use lsp_types::Uri;
use vlog_parser::ast::SourceFile;
use vlog_parser::defines::{collect_defines, DefineTable};
use vlog_parser::token::Token;
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, ParseDiagnostic};
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
use lucisv_core::config::Discovery;
use lucisv_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;
/// How many `workspace/symbol` hits are returned. Each one costs a file read
/// to turn its byte span into a line, so an unbounded answer to the empty
/// query would read the whole workspace.
pub const WORKSPACE_SYMBOL_LIMIT: usize = 256;
/// One open buffer, fully analyzed. Every field is derived from `text`, so a
/// change throws the whole thing away and builds a new one.
pub struct Document {
/// The buffer's path, absent for a `untitled:` document.
pub path: Option<PathBuf>,
pub text: String,
pub line_index: LineIndex,
/// Empty when the file does not lex — the lexer is all-or-nothing.
pub tokens: Vec<Token>,
/// The tolerant parse of `text` — the tree `semantics` was analyzed from,
/// kept so the lint pass reads it instead of parsing the buffer again
/// ("one parse, two tools", `docs/features/one-parse/README.md`).
pub tree: SourceFile,
pub diagnostics: Vec<ParseDiagnostic>,
pub semantics: Semantics,
pub defines: DefineTable,
/// The workspace layer's answers for this file's external candidates.
pub external: ExternalResolutions,
}
impl Document {
/// Analyze a buffer from scratch against the current workspace index.
pub fn new(path: Option<PathBuf>, text: String, index: &WorkspaceIndex) -> Document {
// One lex: the tree is built from a clone of the token stream instead
// of re-lexing the buffer (`parse_source_tolerant` is exactly
// `tokenize` + `parse_tolerant`, so the tree is identical). A buffer
// that does not lex keeps the old path, so its all-error tree and its
// lex diagnostic are byte-for-byte what they always were.
let (tokens, (tree, diagnostics)) = match tokenize(&text) {
Ok(tokens) => {
let parsed = parse_tolerant(tokens.clone(), &text);
(tokens, parsed)
}
Err(_) => (Vec::new(), parse_source_tolerant(&text)),
};
let defines = collect_defines(&tokens);
let semantics = analyze(&tree, &text);
let external = resolve_external(&semantics, index);
let line_index = LineIndex::new(&text);
Document { path, text, line_index, tokens, tree, diagnostics, semantics, defines, external }
}
/// This document's position converter.
pub fn positions(&self) -> Positions<'_> {
Positions::new(&self.text, &self.line_index)
}
/// Re-run only the workspace overlay, after the index was rebuilt. The
/// single-file analysis is unaffected by other files, by construction.
pub fn refresh_overlay(&mut self, index: &WorkspaceIndex) {
self.external = resolve_external(&self.semantics, index);
}
}
/// 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<PathBuf>,
/// The filelist's `+incdir+`s, in filelist order. Empty for every rung
/// but the filelist — nothing else names an include path.
incdirs: Vec<PathBuf>,
warnings: Vec<String>,
}
/// A `Scope` with its files read: what one index rebuild works from.
struct Sources {
texts: Vec<(PathBuf, String)>,
incdirs: Vec<PathBuf>,
warnings: Vec<String>,
}
/// Every open buffer plus the workspace index they are resolved against.
#[derive(Default)]
pub struct Workspace {
docs: HashMap<Uri, Document>,
roots: Vec<PathBuf>,
index: WorkspaceIndex,
/// The project-wide completion tables, rebuilt with `index` and from the
/// 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 `lucisv.*` settings a client pushed. Default until it does.
client: ClientSettings,
}
impl Workspace {
/// Adopt the workspace roots and build the index for the first time.
/// Returns whatever the caller should tell the user about the scope.
pub fn open_roots(&mut self, roots: Vec<PathBuf>) -> Vec<String> {
self.roots = roots;
self.rebuild_index()
}
pub fn index(&self) -> &WorkspaceIndex {
&self.index
}
/// The project-wide completion tables, as of the last index rebuild.
pub fn candidates(&self) -> &Candidates {
&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
/// opening a file widens it — which is why `server.rs` rebuilds on
/// `didOpen` in that case and not in any other.
pub fn has_roots(&self) -> bool {
!self.roots.is_empty()
}
/// The `lucisv.*` settings in force, for the resolution points in
/// `format.rs` to fold in.
pub fn client_settings(&self) -> &ClientSettings {
&self.client
}
/// Adopt the settings a client pushed.
///
/// Returns `true` when the caller must rebuild the index: `exclude` and
/// `filelist` are the two that change *which files exist* as far as this
/// server is concerned. `lineLength` and `indent` are read afresh by every
/// formatting request, so they need no invalidation at all.
pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool {
let rescan =
self.client.exclude != settings.exclude || self.client.filelist != settings.filelist;
self.client = settings;
rescan
}
pub fn document(&self, uri: &Uri) -> Option<&Document> {
self.docs.get(uri)
}
/// Replace a buffer's contents and re-analyze it.
pub fn set_document(&mut self, uri: Uri, text: String) {
let path = uri_to_path(&uri);
let doc = Document::new(path, text, &self.index);
self.docs.insert(uri, doc);
}
pub fn close_document(&mut self, uri: &Uri) {
self.docs.remove(uri);
}
/// Every open buffer's URI, for republishing diagnostics after a rebuild.
pub fn open_uris(&self) -> Vec<Uri> {
self.docs.keys().cloned().collect()
}
/// Re-scan the workspace and rebuild the index and the completion tables,
/// then refresh every open buffer's overlay. Called on `initialize` and on
/// every `didSave`.
///
/// Returns the warnings from resolving the scope — a filelist naming a
/// file that is gone, say. Rendering them is `server.rs`'s job; this
/// module speaks no protocol.
pub fn rebuild_index(&mut self) -> Vec<String> {
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);
}
scope.warnings
}
/// The in-scope files and their current text — what a refactoring reads.
///
/// The same list `rebuild_index` feeds the index, recomputed rather than
/// 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().texts
}
/// Read every in-scope file, with open buffers overriding disk.
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) {
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 };
texts.retain(|(p, _)| p != &path);
texts.push((path, doc.text.clone()));
}
Sources { texts, incdirs: scope.incdirs, warnings: scope.warnings }
}
/// The text of a workspace file: the open buffer if there is one, else
/// what is on disk. Same precedence the index rebuild uses, so a location
/// is never computed against text the index did not see.
pub fn text_of(&self, path: &Path) -> Option<String> {
let open = self.docs.values().find(|d| d.path.as_deref() == Some(path));
match open {
Some(doc) => Some(doc.text.clone()),
None => fs::read_to_string(path).ok(),
}
}
/// The files the index covers, and what the user should be told about how
/// they were chosen. The scope ladder, highest first:
///
/// 1. **A filelist** — `lucisv.filelist`, else a `filelist` key in the
/// config governing a workspace root. It names *exactly* the files to
/// index; the project said so, and guessing past it would defeat the
/// point of having one.
/// 2. **The workspace-folder walk**, unchanged from before filelists.
/// 3. **Each open buffer's own directory**, non-recursive, when there is
/// no workspace root at all — a single file opened on its own still
/// resolves against the files beside it.
///
/// 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.
///
/// 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 lucisv_core::filelist::read(&path) {
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")],
},
}
}
/// The filelist governing this workspace, if any: the client's setting
/// first (absolute, or relative to the first root), else the `filelist`
/// key of the config governing a root, in root order.
///
/// Public because the file watchers must name it: a `.f` edited outside
/// the editor changes the index's scope, and nothing else on disk would
/// tell us (`docs/features/file-watching/README.md`).
pub fn filelist_path(&self) -> Option<PathBuf> {
if let Some(setting) = &self.client.filelist {
let path = Path::new(setting);
return Some(match self.roots.first() {
Some(root) if path.is_relative() => root.join(path),
_ => path.to_path_buf(),
});
}
let mut discovery = Discovery::new(true);
// A broken `lucisv.toml` names no filelist, exactly as it contributes no
// excludes below: the user hears about it when they format.
self.roots.iter().find_map(|root| discovery.for_dir(root).ok()?.filelist)
}
/// Rungs 2 and 3 of the ladder: the workspace walk, or — with no workspace
/// at all — the directories the open buffers live in.
fn default_files(&self) -> Vec<PathBuf> {
if self.roots.is_empty() {
self.sibling_files()
} else {
self.walked_files()
}
}
/// The source files sitting beside each open buffer, one directory deep.
/// No walk, no `.gitignore`: this is the fallback for "a file opened on
/// its own", where descending a tree the user never named would be a
/// surprise.
fn sibling_files(&self) -> Vec<PathBuf> {
let mut dirs: Vec<&Path> =
self.docs.values().filter_map(|d| d.path.as_deref()?.parent()).collect();
dirs.sort();
dirs.dedup();
let mut out = Vec::new();
for dir in dirs {
let Ok(entries) = fs::read_dir(dir) else { continue };
for entry in entries.flatten() {
let path = entry.path();
let extension = path.extension().and_then(|e| e.to_str()).unwrap_or_default();
if path.is_file() && EXTENSIONS.contains(&extension) {
out.push(path);
}
}
}
out.sort();
out.dedup();
out
}
/// Every source file under the roots, found by the CLI's own walk: the
/// same extensions, the same `.gitignore` handling, and the `exclude`
/// patterns of the config governing each root. What `lucisv` skips, the
/// index skips.
fn walked_files(&self) -> Vec<PathBuf> {
let mut discovery = Discovery::new(true);
let mut out = Vec::new();
for root in &self.roots {
// The walk names its inputs as strings; every root came from a
// `file:` URI, which cannot carry a non-UTF-8 path.
let Some(input) = root.to_str() else { continue };
// A broken `lucisv.toml` must not stop the server from indexing: an
// index that excludes nothing is a far better failure than a
// server that comes up empty. The error is reported when the user
// formats a file in this tree (`format::settings_for`).
let mut exclude =
discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
// The client's `lucisv.exclude` is *appended*, never substituted —
// the CLI appends a config's excludes to `--exclude` the same way,
// and a setting that silently dropped a checked-in exclude would
// put vendored code back in the index for one user only.
exclude.extend(self.client.exclude.iter().cloned());
// `.gitignore` is always honoured: it is the CLI's default, and an
// editor has no `--no-gitignore` to type. An unreadable root is
// simply not indexed, exactly as before this walk was shared.
let _ = collect_files(input, &exclude, true, &mut out);
}
out.sort();
out.dedup();
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
fn uri(s: &str) -> Uri {
Uri::from_str(s).expect("test uri parses")
}
#[test]
fn a_document_analyzes_a_clean_file() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.diagnostics.is_empty());
assert_eq!(doc.path.as_deref(), Some(Path::new("/rtl/m.sv")));
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"));
assert!(!doc.tokens.is_empty());
}
#[test]
fn a_broken_file_still_analyzes() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire ;\nendmodule\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(!doc.diagnostics.is_empty(), "a broken buffer must report");
assert!(doc.semantics.symbols().iter().any(|s| s.name == "m"), "and still bind");
}
#[test]
fn a_file_that_does_not_lex_has_no_tokens_but_has_a_diagnostic() {
let mut ws = Workspace::default();
ws.set_document(uri("file:///rtl/m.sv"), "module m;\n wire a; /* unterminated\n".into());
let doc = ws.document(&uri("file:///rtl/m.sv")).expect("open");
assert!(doc.tokens.is_empty());
assert_eq!(doc.diagnostics.len(), 1);
}
#[test]
fn an_untitled_buffer_has_no_path() {
let mut ws = Workspace::default();
ws.set_document(uri("untitled:Untitled-1"), "module m;\nendmodule\n".into());
let doc = ws.document(&uri("untitled:Untitled-1")).expect("open");
assert_eq!(doc.path, None);
}
#[test]
fn an_open_buffer_overrides_disk_in_the_index() {
let dir = std::env::temp_dir().join(format!("lucisv_server_state_{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir).expect("temp dir");
let path = dir.join("pkg.sv");
fs::write(&path, "package p;\n localparam ON_DISK = 1;\nendpackage\n").expect("write");
let mut ws = Workspace::default();
ws.open_roots(vec![dir.clone()]);
assert_eq!(ws.index().member("p", "ON_DISK").len(), 1);
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0);
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package p;\n localparam IN_BUFFER = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 1, "buffer must win");
assert_eq!(ws.index().member("p", "ON_DISK").len(), 0, "disk must lose");
let _ = fs::remove_dir_all(&dir);
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
}
impl Tree {
fn new(name: &str) -> Tree {
let path = std::env::temp_dir()
.join(format!("lucisv_server_scan_{}_{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) {
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");
}
/// A package declaring one localparam, so the index can be asked
/// whether this file was scanned at all.
fn package(&self, rel: &str, name: &str) {
self.write(rel, &format!("package {name};\n localparam K = 1;\nendpackage\n"));
}
}
impl Drop for Tree {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.path);
}
}
#[test]
fn the_scan_skips_what_a_gitignore_skips() {
let tree = Tree::new("gitignore");
tree.write(".gitignore", "generated/\n*_gen.sv\n");
tree.package("kept.sv", "kept");
tree.package("generated/netlist.sv", "generated_pkg");
tree.package("rtl/top_gen.sv", "gen_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "a plain file is indexed");
assert_eq!(ws.index().member("generated_pkg", "K").len(), 0, "an ignored directory");
assert_eq!(ws.index().member("gen_pkg", "K").len(), 0, "an ignored name, at depth");
}
#[test]
fn the_scan_honours_the_root_configs_excludes() {
let tree = Tree::new("excludes");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "lucisv.toml excludes apply");
}
#[test]
fn a_broken_root_config_does_not_stop_the_scan() {
// Exit 2 is the CLI's answer to a broken config; a server that indexed
// nothing because of a typo would look simply broken instead.
let tree = Tree::new("brokencfg");
tree.write("lucisv.toml", "bogus = 1\n");
tree.package("kept.sv", "kept");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1);
}
/// `lucisv.exclude` as a client would push it.
fn excluding(patterns: &[&str]) -> ClientSettings {
ClientSettings {
exclude: patterns.iter().map(|p| p.to_string()).collect(),
..Default::default()
}
}
#[test]
fn a_pushed_exclude_hides_files_from_the_index() {
let tree = Tree::new("clientexclude");
tree.package("kept.sv", "kept");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 1, "premise: indexed at first");
assert!(ws.set_client_settings(excluding(&["scratch"])), "an exclude change rescans");
ws.rebuild_index();
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "the excluded one is gone");
}
#[test]
fn a_pushed_exclude_is_appended_to_the_configs_and_does_not_replace_it() {
// The failure this guards: a user setting `lucisv.exclude` in their
// editor and thereby putting the project's vendored code — which the
// checked-in `lucisv.toml` excludes — back into the index for them only.
let tree = Tree::new("bothexcludes");
tree.write("lucisv.toml", "exclude = [\"vendor\"]\n");
tree.package("kept.sv", "kept");
tree.package("vendor/ip.sv", "vendor_pkg");
tree.package("scratch/wip.sv", "scratch_pkg");
let mut ws = Workspace::default();
ws.set_client_settings(excluding(&["scratch"]));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(ws.index().member("kept", "K").len(), 1, "an unmatched file stays");
assert_eq!(ws.index().member("vendor_pkg", "K").len(), 0, "the config's exclude holds");
assert_eq!(ws.index().member("scratch_pkg", "K").len(), 0, "and the pushed one applies");
}
#[test]
fn only_an_exclude_change_asks_for_a_rescan() {
// `lineLength` and `indent` are read afresh by every formatting
// request, so re-walking the workspace for them would be pure cost.
let mut ws = Workspace::default();
assert!(!ws.set_client_settings(ClientSettings::default()), "nothing changed");
assert!(
!ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
..Default::default()
}),
"widths do not move files"
);
assert!(ws.set_client_settings(excluding(&["a"])), "a new exclude does");
assert!(!ws.set_client_settings(excluding(&["a"])), "the same one again does not");
assert!(ws.set_client_settings(excluding(&["a", "b"])), "an added pattern does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
#[test]
fn a_filelist_change_asks_for_a_rescan_too() {
// It changes which files exist as far as this server is concerned,
// which is the whole test for whether a rescan is owed.
let mut ws = Workspace::default();
assert!(ws.set_client_settings(using_filelist("files.f")), "a new filelist rescans");
assert!(!ws.set_client_settings(using_filelist("files.f")), "the same one does not");
assert!(ws.set_client_settings(using_filelist("other.f")), "a different one does");
assert!(ws.set_client_settings(ClientSettings::default()), "and so does clearing it");
}
#[test]
fn the_pushed_settings_are_readable_where_formatting_needs_them() {
let mut ws = Workspace::default();
assert_eq!(ws.client_settings(), &ClientSettings::default(), "default until pushed");
ws.set_client_settings(ClientSettings {
line_length: Some(120),
indent: Some(4),
..Default::default()
});
assert_eq!(ws.client_settings().indent, Some(4));
assert_eq!(ws.client_settings().line_length, Some(120));
}
/// `lucisv.filelist` as a client would push it.
fn using_filelist(path: &str) -> ClientSettings {
ClientSettings { filelist: Some(path.to_string()), ..Default::default() }
}
/// A tree with three packages, one of which a filelist deliberately omits.
fn filelist_tree(name: &str) -> Tree {
let tree = Tree::new(name);
tree.package("rtl/a.sv", "a");
tree.package("rtl/b.sv", "b");
tree.package("rtl/unlisted.sv", "unlisted");
tree.write("files.f", "// the project\nrtl/a.sv\nrtl/b.sv\n");
tree
}
/// What the index holds, as the names of the packages it found.
fn indexed(ws: &Workspace, names: &[&str]) -> Vec<String> {
names
.iter()
.filter(|n| ws.index().member(n, "K").len() == 1)
.map(|n| n.to_string())
.collect()
}
#[test]
fn a_configured_filelist_defines_the_index_exactly() {
// The point of a filelist: a file sitting in the tree that the project
// does not build is not indexed, however much the walk would find it.
let tree = filelist_tree("filelistkey");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
let mut ws = Workspace::default();
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
assert!(warnings.is_empty(), "{warnings:?}");
}
#[test]
fn the_filelist_setting_beats_the_config_key_and_may_be_absolute() {
let tree = filelist_tree("filelistsetting");
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
tree.write("other.f", "rtl/unlisted.sv\n");
// Relative: against the workspace root, not the current directory.
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("other.f"));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"], "the setting wins");
// Absolute: taken as written.
let absolute = tree.path.join("other.f");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist(&absolute.display().to_string()));
ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["unlisted"]);
}
#[test]
fn a_filelist_that_cannot_be_read_falls_back_to_the_walk_and_says_so() {
// The failure that must never happen: an empty index and no
// explanation because a path in a settings UI has a typo.
let tree = filelist_tree("filelistgone");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("typo.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"], "the walk ran");
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("typo.f"), "{warnings:?}");
assert!(warnings[0].contains("indexing the workspace instead"), "{warnings:?}");
}
#[test]
fn a_filelists_own_warnings_reach_the_caller() {
let tree = filelist_tree("filelistwarn");
tree.write("files.f", "rtl/a.sv\nrtl/moved.sv\n-nonsense\n");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
let warnings = ws.open_roots(vec![tree.path.clone()]);
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a"], "the rest is still indexed");
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("moved.sv")), "{warnings:?}");
assert!(warnings.iter().any(|w| w.contains("-nonsense")), "{warnings:?}");
}
#[test]
fn an_open_buffer_is_indexed_even_when_the_filelist_omits_it() {
// Open buffers overlay every rung of the ladder: a scratch file the
// project does not build still gets its own symbols.
let tree = filelist_tree("filelistbuffer");
let mut ws = Workspace::default();
ws.set_client_settings(using_filelist("files.f"));
ws.open_roots(vec![tree.path.clone()]);
let path = tree.path.join("rtl/unlisted.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package unlisted;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b", "unlisted"]);
}
#[test]
fn with_no_workspace_root_the_open_files_own_directory_is_indexed() {
// The single-file case: no folder was opened, so the scope is what
// sits beside the buffer — and nothing below it.
let tree = Tree::new("noroot");
tree.package("rtl/open.sv", "open_pkg");
tree.package("rtl/sibling.sv", "sibling");
tree.package("rtl/deeper/below.sv", "below");
tree.package("elsewhere/far.sv", "far");
let mut ws = Workspace::default();
assert!(!ws.has_roots(), "the premise: no workspace folder");
let path = tree.path.join("rtl/open.sv");
let uri = crate::uri::path_to_uri(&path).expect("uri");
ws.set_document(uri, "package open_pkg;\n localparam K = 1;\nendpackage\n".into());
ws.rebuild_index();
assert_eq!(
indexed(&ws, &["open_pkg", "sibling", "below", "far"]),
["open_pkg", "sibling"],
"the buffer and its neighbours only"
);
}
#[test]
fn a_filelist_still_wins_when_there_is_no_workspace_root() {
let tree = filelist_tree("norootfilelist");
let mut ws = Workspace::default();
// With no root a relative setting cannot be anchored, so an absolute
// path is the only sensible way to name one — and it works.
ws.set_client_settings(using_filelist(&tree.path.join("files.f").display().to_string()));
ws.rebuild_index();
assert_eq!(indexed(&ws, &["a", "b", "unlisted"]), ["a", "b"]);
}
/// Where `ws` would look for `` `include "<name>" `` written in `from`.
fn resolved_include(ws: &Workspace, from: &Path, name: &str) -> Option<PathBuf> {
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");
tree.package("a.sv", "a");
tree.package("b.v", "b");
tree.package("c.svh", "c");
tree.package("d.vh", "d");
tree.package("e.txt", "e");
let mut ws = Workspace::default();
ws.open_roots(vec![tree.path.clone()]);
for name in ["a", "b", "c", "d"] {
assert_eq!(ws.index().member(name, "K").len(), 1, "{name} is a source file");
}
assert_eq!(ws.index().member("e", "K").len(), 0, "a .txt is not");
}
}