editor-packaging: a minimal VS Code extension (41-line plain JS on
vscode-languageclient =9.0.1, one setting vfmt.serverPath, languages
verilog/systemverilog) with a zero-dependency smoke.js that validates
the extension's exact spawn contract against the real binary, plus
Neovim/Vim/coc setup docs (including the load-bearing
vim.filetype.add — Vim maps *.v by content heuristic and *.vh not at
all). Everything headless-validatable was validated: the .vsix
builds, smoke passes with negative controls, npm ci reproduces.
vfmt-core-lift: config.rs and walk.rs moved to a new std-only
vfmt_core crate as byte-identical 100% renames (CLI suite untouched,
corpus TSV md5 equal from HEAD and lifted builds). The LSP server
now discovers vfmt.toml per document with precedence config > client
tabSize > built-in default (an editor default is not a deliberate
override), warns once per document change on a broken config while
formatting with defaults, and scans the workspace with the lifted
gitignore-aware walk. QA drove every claim live over stdio.
With these, every TODO §6 item is delivered: spans, tolerant
parsing, define table, single-file semantics, workspace index, the
server, and both editors. Lead trued up the caveats this round made
stale across five documents.
Dev: 2 Opus agents; QA: 2 Sonnet agents; reviews in
docs/features/{editor-packaging,vfmt-core-lift}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
327 lines
13 KiB
Rust
327 lines
13 KiB
Rust
//! What the server remembers: one analysis per open buffer, one index for the
|
|
//! workspace. The invalidation rules are in
|
|
//! `docs/features/vfmt-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::defines::{collect_defines, DefineTable};
|
|
use vlog_parser::token::Token;
|
|
use vlog_parser::{parse_source_tolerant, tokenize, LineIndex, ParseDiagnostic};
|
|
use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex};
|
|
|
|
use vfmt_core::config::Discovery;
|
|
use vfmt_core::walk::collect_files;
|
|
|
|
use crate::convert::Positions;
|
|
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>,
|
|
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 {
|
|
let tokens = tokenize(&text).unwrap_or_default();
|
|
let defines = collect_defines(&tokens);
|
|
let (tree, diagnostics) = parse_source_tolerant(&text);
|
|
let semantics = analyze(&tree, &text);
|
|
let external = resolve_external(&semantics, index);
|
|
let line_index = LineIndex::new(&text);
|
|
Document { path, text, line_index, tokens, 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);
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
}
|
|
|
|
impl Workspace {
|
|
/// Adopt the workspace roots and build the index for the first time.
|
|
pub fn open_roots(&mut self, roots: Vec<PathBuf>) {
|
|
self.roots = roots;
|
|
self.rebuild_index();
|
|
}
|
|
|
|
pub fn index(&self) -> &WorkspaceIndex {
|
|
&self.index
|
|
}
|
|
|
|
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 roots and rebuild the index, then refresh every open
|
|
/// buffer's overlay. Called on `initialize` and on every `didSave`.
|
|
pub fn rebuild_index(&mut self) {
|
|
let mut sources: Vec<(PathBuf, String)> = Vec::new();
|
|
for path in self.source_files() {
|
|
if let Ok(text) = fs::read_to_string(&path) {
|
|
sources.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()));
|
|
}
|
|
self.index = WorkspaceIndex::build(sources.iter().map(|(p, t)| (p.clone(), t.as_str())));
|
|
for doc in self.docs.values_mut() {
|
|
doc.refresh_overlay(&self.index);
|
|
}
|
|
}
|
|
|
|
/// 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(),
|
|
}
|
|
}
|
|
|
|
/// 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 `vfmt` skips, the
|
|
/// index skips.
|
|
fn source_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 `vfmt.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 exclude = discovery.for_dir(root).unwrap_or_default().exclude.unwrap_or_default();
|
|
// `.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!("vfmt_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!("vfmt_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("vfmt.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, "vfmt.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("vfmt.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);
|
|
}
|
|
|
|
#[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");
|
|
}
|
|
}
|