diff --git a/README.md b/README.md index 2f15392..039a200 100644 --- a/README.md +++ b/README.md @@ -121,8 +121,16 @@ the current directory if that flag is absent. `--no-config` skips all of this. line-length = 100 # 40..400, same as --line-length indent = 2 # 1..8, same as --indent exclude = [ "*_gen.sv", "build" ] # added to --exclude patterns +filelist = "rtl/files.f" # an EDA `.f` filelist, relative to this file ``` +`filelist` names the project's sources the way the rest of the EDA world +already does — one path per line, `-f` to nest another filelist, `+incdir+`, +`+define+`, `#`/`//` comments, `$VAR` expansion, paths relative to the +filelist that names them. It is read by `vfmt-server`, where it defines +exactly which files are indexed ([Editor setup](#editor-setup)); the CLI does +not consume it yet. Details: `docs/features/filelist/README.md`. + **Precedence: CLI flag > config file > default**, per setting (`--indent 4` with a file that sets only `line-length` uses both). `exclude` is the exception: config patterns are *added* to `--exclude`, not replaced by it. @@ -580,8 +588,8 @@ Sideloading that `.vsix` is the supported install; the extension is not on any marketplace. To package it by hand instead: `cd editors/vscode && npm ci && npx @vscode/vsce package`. -One setting, `vfmt.serverPath`. Full steps, F5 development flow and -troubleshooting: `editors/vscode/README.md`. +Settings are listed in `editors/vscode/README.md`, along with the full steps, +the F5 development flow and troubleshooting. **Neovim / Vim** — no plugin, just configuration. Neovim 0.11+: @@ -598,6 +606,14 @@ vim.lsp.enable('vfmt') `nvim-lspconfig`, Vim 9 (`vim-lsp`) and coc.nvim equivalents: `editors/nvim/README.md`. +**Which files the server indexes.** A filelist if the project has one — the +`filelist` key of its `vfmt.toml`, or the editor setting `vfmt.filelist` +(a path, absolute or relative to the workspace folder) — and then exactly the +files it names. Otherwise the workspace folder, walked as the CLI walks it; +and with no folder open at all, the current file's own directory. Open buffers +are always indexed on top. A filelist that cannot be read warns and falls back +to the folder walk, so the index is never silently empty. + **Checking the server without an editor.** `node editors/vscode/smoke.js ` spawns it exactly as the extension does and drives a whole `initialize`/`didOpen`/`shutdown`/`exit` session over stdio, exiting 0 only if diff --git a/TODO.md b/TODO.md index fd04197..b3fb7e2 100644 --- a/TODO.md +++ b/TODO.md @@ -572,3 +572,23 @@ later: necessary exception. - No semantic claims in v1 lint rules: syntax-only rules first (Verible's scope), semantic rules only after `vlog_semantic` exists. + +## 8. Refactoring — the rope port (owner request, 2026-08-24) + +Port the ideas of `python-rope/rope` to Verilog/SV, server-first. The full +rope→Verilog mapping, feature checklist and milestone specs live in +`docs/features/refactor/README.md` — that file is the source of truth; this +section only tracks the milestones. + +- [x] **M1 `filelist`** — EDA `.f` filelist defines the index scope + (`-f` nesting, `+incdir+`/`+define+` recorded, env vars); fallback: + workspace walk, then current file's directory when rootless. +- [ ] **M2 `refactor-rename`** — new crate `vlog_refactor`; LSP + `prepareRename`/`rename` for every symbol kind `vlog_semantic` resolves, + cross-file, whole-edit-or-nothing verified by re-parse. +- [ ] **M3 `refactor-ports`** — add/remove/propagate module ports across + the declaration and every instantiation (named/ordered/`.*`). +- [ ] **M4 `refactor-instantiate`** — module hinting: instantiation + skeleton completion from the definition, auto-connect, signature help. +- [ ] Backlog (extract module, inline, `.*` expansion, ANSI conversion, + organize imports, …) — triaged in the umbrella README after M4. diff --git a/crates/vfmt/src/args.rs b/crates/vfmt/src/args.rs index e22224b..13c8233 100644 --- a/crates/vfmt/src/args.rs +++ b/crates/vfmt/src/args.rs @@ -209,7 +209,8 @@ CONFIGURATION: or `.vfmt.toml` (the first found wins; the search also stops at a directory containing `.git`, after checking it). Recognized keys, all optional: `line-length` (40-400), `indent` (1-8), `exclude` (array of - patterns, added to `--exclude`). A command line flag overrides the file. + patterns, added to `--exclude`), `filelist` (path to an EDA `.f` file, + read by vfmt-server only). A command line flag overrides the file. RANGE FORMATTING: `--lines` formats one construct at a time: an item whose lines meet a range @@ -432,7 +433,7 @@ mod tests { #[test] fn a_cli_flag_beats_the_config_file_which_beats_the_default() { - let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None }; + let file = FileConfig { line_length: Some(120), indent: Some(4), ..Default::default() }; let default = Config::default(); let opts = parse(&["rtl"]).unwrap(); @@ -450,8 +451,7 @@ mod tests { #[test] fn config_excludes_are_appended_to_cli_excludes() { - let file = - FileConfig { line_length: None, indent: None, exclude: Some(vec!["gen".to_string()]) }; + let file = FileConfig { exclude: Some(vec!["gen".to_string()]), ..Default::default() }; let opts = parse(&["--exclude", "build", "rtl"]).unwrap(); assert_eq!(opts.exclude_with(&file), vec!["build", "gen"]); assert_eq!(opts.exclude_with(&FileConfig::default()), vec!["build"]); diff --git a/crates/vfmt_core/src/config.rs b/crates/vfmt_core/src/config.rs index c01ec0e..62cc3b5 100644 --- a/crates/vfmt_core/src/config.rs +++ b/crates/vfmt_core/src/config.rs @@ -22,6 +22,13 @@ pub struct FileConfig { pub indent: Option, /// `exclude`: patterns appended to the CLI's `--exclude` list. pub exclude: Option>, + /// `filelist`: the `.f` file naming the project's sources. + /// + /// [`parse`] records it exactly as written, since it has no idea where + /// the config file lives; [`Discovery`] resolves it against that file's + /// directory, so every `FileConfig` a `Discovery` hands out carries a + /// usable path. See `docs/features/filelist/README.md`. + pub filelist: Option, } /// Parses the supported TOML subset. Errors are prefixed `: ` so the @@ -62,7 +69,16 @@ fn parse_entry(line: &str, config: &mut FileConfig) -> Result<(), String> { config.exclude = Some(parse_array(value)?); Ok(()) } - _ => Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude)")), + "filelist" => { + if config.filelist.is_some() { + return Err(format!("duplicate key `{key}`")); + } + config.filelist = Some(PathBuf::from(parse_string(value)?)); + Ok(()) + } + _ => { + Err(format!("unknown key `{key}` (known keys: line-length, indent, exclude, filelist)")) + } } } @@ -224,7 +240,15 @@ fn config_file_in(dir: &Path) -> Option { fn load(path: &Path) -> Result { let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; - parse(&text).map_err(|e| format!("{}:{e}", path.display())) + let mut config = parse(&text).map_err(|e| format!("{}:{e}", path.display()))?; + // `filelist` is the one value that names another file, so it is resolved + // here — against the config file's own directory, which `parse` cannot + // know. An absolute path is left alone (`join` already does that). + if let Some(filelist) = config.filelist.take() { + let dir = path.parent().unwrap_or(Path::new(".")); + config.filelist = Some(dir.join(filelist)); + } + Ok(config) } #[cfg(test)] @@ -254,6 +278,39 @@ exclude = [ \"build\", \"*_gen.sv\", ] assert_eq!(config.exclude, Some(vec!["build".to_string(), "*_gen.sv".to_string()])); } + #[test] + fn the_filelist_key_is_a_string_and_nothing_else() { + assert_eq!(ok("filelist = \"rtl/files.f\"").filelist, Some(PathBuf::from("rtl/files.f"))); + assert!(err("filelist = 3").contains("expected a quoted string")); + assert!(err("filelist = [\"a.f\"]").contains("expected a quoted string")); + assert!(err("filelist = \"a.f\"\nfilelist = \"b.f\"").contains("duplicate key `filelist`")); + // The key is named in the unknown-key message, so a typo says what + // was available. + assert!(err("file-list = \"a.f\"").contains("filelist")); + } + + #[test] + fn a_relative_filelist_resolves_against_the_config_files_directory() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "filelist = \"rtl/files.f\"\n"); + let deep = tree.write("a/b/x.sv", ""); + let mut discovery = Discovery::new(true); + let found = discovery.for_file(&deep).unwrap(); + assert_eq!(found.filelist, Some(tree.path.join("rtl/files.f"))); + } + + #[test] + fn an_absolute_filelist_is_left_alone() { + let tree = TempTree::new(); + tree.write("vfmt.toml", "filelist = \"/opt/project/files.f\"\n"); + let file = tree.write("x.sv", ""); + let mut discovery = Discovery::new(true); + assert_eq!( + discovery.for_file(&file).unwrap().filelist, + Some(PathBuf::from("/opt/project/files.f")) + ); + } + #[test] fn an_empty_file_sets_nothing() { assert_eq!(ok(""), FileConfig::default()); diff --git a/crates/vfmt_core/src/filelist.rs b/crates/vfmt_core/src/filelist.rs new file mode 100644 index 0000000..33fdc9d --- /dev/null +++ b/crates/vfmt_core/src/filelist.rs @@ -0,0 +1,592 @@ +//! EDA filelist (`-f`) parsing: the project file every Verilog build +//! already has. +//! +//! One source path per line, `-f` to nest another filelist, `+incdir+` and +//! `+define+` recorded for later, `//` and `#` comments, `$VAR` expansion. +//! Nothing here fails on bad content: a filelist that names a deleted file, +//! nests one that cannot be read, carries a flag vfmt does not know, or nests +//! `-f` past [`MAX_NESTING_DEPTH`] still produces the files it did name, plus +//! a warning for each problem. See `docs/features/filelist/README.md`. + +use std::collections::HashSet; +use std::path::{Component, Path, PathBuf}; + +/// How deep `-f` may nest before the reader stops descending. +/// +/// A filelist that nests at all nests two or three deep, so the limit is far +/// above anything real and far below the depth at which this recursion +/// overflows the stack (measured at ~1500 frames in an unoptimized build, QA +/// 2026-08-24). It has to be *below* it by a wide margin because a stack +/// overflow is not a panic: it aborts the process, taking the whole language +/// server down with it rather than spoiling one filelist. Past the limit the +/// chain is reported and abandoned, like every other problem here. +/// +/// The same reasoning, and the same shape of fix, as `vlog_parser`'s +/// `MAX_NESTING_DEPTH` — see `docs/features/recursion-limit/README.md`. +pub const MAX_NESTING_DEPTH: usize = 256; + +/// What one filelist names, after every nested `-f` was followed. +#[derive(Debug, Default, Clone, PartialEq, Eq)] +pub struct Filelist { + /// Every existing source file it lists, in list order, without repeats. + pub files: Vec, + /// `+incdir+` directories, resolved but otherwise unused today. + pub incdirs: Vec, + /// `+define+NAME` / `+define+NAME=VALUE`, recorded but unused today. + pub defines: Vec<(String, Option)>, + /// Everything that went wrong, as `:: `. + pub warnings: Vec, +} + +/// Read a filelist and everything it nests. +/// +/// `Err` means the named file itself could not be read — the one failure a +/// caller learns nothing from. Every other problem is a warning on an +/// otherwise usable result. +pub fn read(path: &Path) -> Result { + read_with(path, &|name| std::env::var(name).ok()) +} + +/// The body of [`read`], with the environment injected so the expansion +/// tests need not mutate the process environment. +fn read_with(path: &Path, env: &dyn Fn(&str) -> Option) -> Result { + let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + let mut reader = Reader { + out: Filelist::default(), + env, + cwd, + seen: HashSet::new(), + listed: HashSet::new(), + depth: 0, + }; + let normalized = reader.normalize(path); + reader.seen.insert(normalized); + reader.filelist(path, &text); + Ok(reader.out) +} + +/// One filelist read in progress, including everything it nests. +struct Reader<'a> { + out: Filelist, + env: &'a dyn Fn(&str) -> Option, + cwd: PathBuf, + /// Filelists already read, so a cycle — or a plain repeat, which has the + /// same effect — is skipped instead of followed. + seen: HashSet, + /// Source files already listed, so `files` holds no repeats. + listed: HashSet, + /// How many `-f` levels down the reader currently is. The `seen` set + /// stops a cycle; only this stops a long chain of *distinct* filelists, + /// which is otherwise unbounded recursion. + depth: usize, +} + +impl Reader<'_> { + /// Consume one filelist's text. `path` is only used for resolving the + /// paths it names and for naming it in warnings. + fn filelist(&mut self, path: &Path, text: &str) { + let dir = path.parent().unwrap_or(Path::new(".")).to_path_buf(); + for (index, raw) in text.lines().enumerate() { + let line = Line { file: path, number: index + 1 }; + self.line(&line, &dir, raw); + } + } + + fn line(&mut self, line: &Line<'_>, dir: &Path, raw: &str) { + // `-f` names its target in the next token, so one token of lookahead + // is enough state, and it does not survive the end of the line. + let mut expecting_filelist = false; + for token in raw.split_whitespace() { + if token.starts_with("//") || token.starts_with('#') { + break; + } + let token = self.expand(line, token); + if token.is_empty() { + continue; + } + if expecting_filelist { + expecting_filelist = false; + self.nested(line, dir, &token); + } else if token == "-f" { + expecting_filelist = true; + } else if let Some(rest) = token.strip_prefix("+incdir+") { + for item in rest.split('+').filter(|s| !s.is_empty()) { + let resolved = self.normalize(&dir.join(item)); + self.out.incdirs.push(resolved); + } + } else if let Some(rest) = token.strip_prefix("+define+") { + for item in rest.split('+').filter(|s| !s.is_empty()) { + self.out.defines.push(match item.split_once('=') { + Some((name, value)) => (name.to_string(), Some(value.to_string())), + None => (item.to_string(), None), + }); + } + } else if token.starts_with('+') || token.starts_with('-') { + self.warn(line, format!("ignoring unsupported option `{token}`")); + } else { + self.source(line, dir, &token); + } + } + if expecting_filelist { + self.warn(line, "`-f` names no filelist".to_string()); + } + } + + /// A `-f` target: read it here and now, so its files land in list order. + fn nested(&mut self, line: &Line<'_>, dir: &Path, token: &str) { + if self.depth >= MAX_NESTING_DEPTH { + // Descending anyway would eventually abort the process, which is + // a far worse answer than an incomplete file list and a warning. + self.warn( + line, + format!( + "filelist `{token}` nests more than {MAX_NESTING_DEPTH} levels deep, \ + not descending further" + ), + ); + return; + } + let path = dir.join(token); + let normalized = self.normalize(&path); + if !self.seen.insert(normalized) { + self.warn(line, format!("filelist `{token}` was already included, skipping it")); + return; + } + match std::fs::read_to_string(&path) { + Ok(text) => { + self.depth += 1; + self.filelist(&path, &text); + self.depth -= 1; + } + Err(e) => self.warn(line, format!("cannot read filelist `{token}`: {e}")), + } + } + + /// A source file: kept when it exists, warned about when it does not. + fn source(&mut self, line: &Line<'_>, dir: &Path, token: &str) { + let path = dir.join(token); + if !path.is_file() { + self.warn(line, format!("no such file `{token}`, skipping it")); + return; + } + let normalized = self.normalize(&path); + if self.listed.insert(normalized.clone()) { + self.out.files.push(normalized); + } + } + + /// Expand `$VAR` and `${VAR}` in one token. An unset variable expands to + /// nothing and says so — the same thing the simulators do, and the + /// missing-file warning that usually follows repeats it more usefully. + fn expand(&mut self, line: &Line<'_>, token: &str) -> String { + let mut out = String::new(); + let mut rest = token; + while let Some(at) = rest.find('$') { + out.push_str(&rest[..at]); + let after = &rest[at + 1..]; + let (name, tail) = match after.strip_prefix('{') { + Some(braced) => match braced.split_once('}') { + Some((name, tail)) => (name, tail), + // An unterminated `${` is not a variable reference. + None => ("", after), + }, + None => { + let end = after + .find(|c: char| !c.is_ascii_alphanumeric() && c != '_') + .unwrap_or(after.len()); + after.split_at(end) + } + }; + if name.is_empty() { + out.push('$'); + rest = after; + continue; + } + match (self.env)(name) { + Some(value) => out.push_str(&value), + None => self.warn(line, format!("`{name}` is not set, expanding it to nothing")), + } + rest = tail; + } + out.push_str(rest); + out + } + + fn warn(&mut self, line: &Line<'_>, what: String) { + self.out.warnings.push(format!("{}:{}: {what}", line.file.display(), line.number)); + } + + /// Fold `.`/`..` away and resolve against the current directory, so two + /// spellings of one file are one entry. Symlinks are deliberately not + /// resolved, matching `config::Discovery`'s lexical rule. + fn normalize(&self, path: &Path) -> PathBuf { + let joined = if path.is_absolute() { path.to_path_buf() } else { self.cwd.join(path) }; + let mut out = PathBuf::new(); + for component in joined.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + out.pop(); + } + other => out.push(other), + } + } + out + } +} + +/// Where a warning happened. +struct Line<'a> { + file: &'a Path, + number: usize, +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// A throwaway directory tree under the system temp dir. + struct TempTree { + path: PathBuf, + } + + impl TempTree { + fn new() -> TempTree { + static COUNTER: AtomicUsize = AtomicUsize::new(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = + std::env::temp_dir().join(format!("vfmt-filelist-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&path); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempTree { path } + } + + fn write(&self, rel: &str, contents: &str) -> PathBuf { + let path = self.path.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, contents).expect("write"); + path + } + + /// An empty source file, so the existence check has something to find. + fn source(&self, rel: &str) -> PathBuf { + self.write(rel, "// nothing\n") + } + } + + impl Drop for TempTree { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.path); + } + } + + /// Read a filelist with no environment at all. + fn read_bare(path: &Path) -> Filelist { + read_with(path, &|_| None).expect("the root filelist is readable") + } + + /// The file names (not whole paths) a filelist resolved to. + fn names(list: &Filelist) -> Vec { + list.files + .iter() + .map(|p| p.file_name().unwrap_or_default().to_string_lossy().into_owned()) + .collect() + } + + #[test] + fn an_unreadable_root_filelist_is_the_one_error() { + let tree = TempTree::new(); + let missing = tree.path.join("nope.f"); + let error = read(&missing).expect_err("a missing filelist cannot be read"); + assert!(error.starts_with(&missing.display().to_string()), "{error}"); + } + + #[test] + fn plain_paths_blank_lines_and_both_comment_forms() { + let tree = TempTree::new(); + tree.source("rtl/a.sv"); + tree.source("rtl/b.sv"); + let f = tree.write( + "files.f", + "\ +# a hash comment +// a slash comment + +rtl/a.sv +rtl/b.sv // the trailing form +", + ); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv", "b.sv"]); + assert!(list.warnings.is_empty(), "{:?}", list.warnings); + } + + #[test] + fn paths_resolve_against_the_filelist_that_names_them() { + // `sub/inner.f` names `c.sv` next to itself, not next to the root. + let tree = TempTree::new(); + tree.source("rtl/a.sv"); + tree.source("sub/c.sv"); + tree.write("sub/inner.f", "c.sv\n"); + let f = tree.write("files.f", "rtl/a.sv\n-f sub/inner.f\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv", "c.sv"]); + assert_eq!(list.files[1], tree.path.join("sub/c.sv")); + assert!(list.warnings.is_empty(), "{:?}", list.warnings); + } + + #[test] + fn dotted_paths_are_folded_so_one_file_is_one_entry() { + let tree = TempTree::new(); + tree.source("rtl/a.sv"); + let f = tree.write("files.f", "rtl/a.sv\n./rtl/../rtl/a.sv\n"); + let list = read_bare(&f); + assert_eq!(list.files, vec![tree.path.join("rtl/a.sv")], "one file, however spelled"); + } + + #[test] + fn a_repeated_filelist_is_skipped_with_a_warning() { + let tree = TempTree::new(); + tree.source("a.sv"); + tree.write("inner.f", "a.sv\n"); + let f = tree.write("files.f", "-f inner.f\n-f ./inner.f\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv"]); + assert_eq!(list.warnings.len(), 1); + assert!(list.warnings[0].contains("already included"), "{:?}", list.warnings); + assert!(list.warnings[0].contains(":2:"), "the warning names the line"); + } + + #[test] + fn a_cycle_terminates_and_warns() { + let tree = TempTree::new(); + tree.source("a.sv"); + tree.source("b.sv"); + let f = tree.write("first.f", "a.sv\n-f second.f\n"); + tree.write("second.f", "b.sv\n-f first.f\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv", "b.sv"]); + assert_eq!(list.warnings.len(), 1); + assert!(list.warnings[0].contains("already included"), "{:?}", list.warnings); + } + + #[test] + fn a_chain_of_distinct_filelists_stops_at_the_depth_limit() { + // The crash this guards (QA finding, 2026-08-24): `seen` rejects a + // *repeat*, so a chain of uniquely named filelists — the shape a + // generator emits — recursed until the stack overflowed and aborted + // the process. An abort cannot be caught, so the whole language + // server died on `initialize`. Now it is one more warning. + let tree = TempTree::new(); + let chain = MAX_NESTING_DEPTH * 4; + for level in 0..chain { + tree.source(&format!("src{level}.sv")); + tree.write(&format!("f{level}.f"), &format!("src{level}.sv\n-f f{}.f\n", level + 1)); + } + let list = read_bare(&tree.path.join("f0.f")); + + // Everything down to the limit is listed, and nothing below it. + assert_eq!(list.files.len(), MAX_NESTING_DEPTH + 1, "one filelist per level, inclusive"); + assert_eq!(list.files[0], tree.path.join("src0.sv")); + assert_eq!( + list.files[MAX_NESTING_DEPTH], + tree.path.join(format!("src{MAX_NESTING_DEPTH}.sv")) + ); + // One warning, at the level that refused to descend — not one per + // remaining level, and not silence. + assert_eq!(list.warnings.len(), 1, "{:?}", list.warnings); + assert!( + list.warnings[0].contains("nests more than 256 levels deep"), + "{:?}", + list.warnings + ); + assert!( + list.warnings[0].contains(&format!("f{MAX_NESTING_DEPTH}.f:")), + "the warning names the filelist that stopped: {:?}", + list.warnings + ); + } + + #[test] + fn a_nested_filelist_that_cannot_be_read_is_only_a_warning() { + let tree = TempTree::new(); + tree.source("a.sv"); + let f = tree.write("files.f", "a.sv\n-f gone.f\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv"], "the rest of the list still counts"); + assert_eq!(list.warnings.len(), 1); + assert!(list.warnings[0].contains("cannot read filelist `gone.f`"), "{:?}", list.warnings); + } + + #[test] + fn a_dangling_dash_f_warns_rather_than_eating_the_next_line() { + let tree = TempTree::new(); + tree.source("a.sv"); + let f = tree.write("files.f", "-f\na.sv\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv"], "the next line is a path, not the `-f` target"); + assert_eq!(list.warnings.len(), 1); + assert!(list.warnings[0].contains("names no filelist"), "{:?}", list.warnings); + } + + #[test] + fn incdirs_are_recorded_in_both_the_single_and_the_multi_form() { + let tree = TempTree::new(); + let f = tree.write("files.f", "+incdir+inc\n+incdir+a+../b\n"); + let list = read_bare(&f); + assert_eq!( + list.incdirs, + vec![tree.path.join("inc"), tree.path.join("a"), tree.path.parent().unwrap().join("b")] + ); + assert!(list.warnings.is_empty(), "{:?}", list.warnings); + } + + #[test] + fn defines_are_recorded_with_and_without_values() { + let tree = TempTree::new(); + let f = tree.write("files.f", "+define+SYNTHESIS\n+define+W=8+DEPTH=16+FLAG\n"); + let list = read_bare(&f); + assert_eq!( + list.defines, + vec![ + ("SYNTHESIS".to_string(), None), + ("W".to_string(), Some("8".to_string())), + ("DEPTH".to_string(), Some("16".to_string())), + ("FLAG".to_string(), None), + ] + ); + assert!(list.warnings.is_empty(), "{:?}", list.warnings); + } + + #[test] + fn an_unknown_option_is_skipped_with_a_warning() { + let tree = TempTree::new(); + tree.source("a.sv"); + let f = tree.write("files.f", "-sverilog +v2k a.sv\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv"]); + assert_eq!(list.warnings.len(), 2); + assert!(list.warnings[0].contains("`-sverilog`"), "{:?}", list.warnings); + assert!(list.warnings[1].contains("`+v2k`"), "{:?}", list.warnings); + } + + #[test] + fn a_listed_file_that_does_not_exist_is_skipped_with_a_warning() { + let tree = TempTree::new(); + tree.source("a.sv"); + let f = tree.write("files.f", "a.sv\nrtl/gone.sv\n"); + let list = read_bare(&f); + assert_eq!(names(&list), ["a.sv"]); + assert_eq!(list.warnings.len(), 1); + assert!(list.warnings[0].contains("no such file `rtl/gone.sv`"), "{:?}", list.warnings); + } + + #[test] + fn a_directory_is_not_a_source_file() { + let tree = TempTree::new(); + tree.source("rtl/a.sv"); + let f = tree.write("files.f", "rtl\n"); + let list = read_bare(&f); + assert!(list.files.is_empty()); + assert_eq!(list.warnings.len(), 1); + } + + #[test] + fn environment_variables_expand_in_both_spellings() { + let tree = TempTree::new(); + tree.source("rtl/a.sv"); + tree.source("rtl/b.sv"); + let f = tree.write("files.f", "$DIR/a.sv\n${DIR}/b.sv\n"); + let list = + read_with(&f, &|name| (name == "DIR").then(|| "rtl".to_string())).expect("readable"); + assert_eq!(names(&list), ["a.sv", "b.sv"]); + assert!(list.warnings.is_empty(), "{:?}", list.warnings); + } + + #[test] + fn an_unset_variable_expands_to_nothing_with_a_warning() { + let tree = TempTree::new(); + tree.source("a.sv"); + let f = tree.write("files.f", "$MISSING_ROOT/a.sv\n${ALSO_MISSING}a.sv\n"); + let list = read_bare(&f); + // The first line becomes `/a.sv`, an absolute path that does not + // exist; the second becomes `a.sv`, which does. + assert_eq!(names(&list), ["a.sv"]); + assert_eq!(list.warnings.len(), 3, "two unset variables and one missing file"); + let said = |what: &str| list.warnings.iter().any(|w| w.contains(what)); + assert!(said("`MISSING_ROOT` is not set"), "{:?}", list.warnings); + assert!(said("`ALSO_MISSING` is not set"), "{:?}", list.warnings); + assert!(said("no such file `/a.sv`"), "{:?}", list.warnings); + } + + #[test] + fn a_dollar_that_names_nothing_stays_literal() { + let tree = TempTree::new(); + let f = tree.write("files.f", "$ $/x.sv\n"); + let list = read_with(&f, &|_| Some("SET".to_string())).expect("readable"); + // Neither token is a variable reference — there is no name after the + // `$` — so nothing is expanded and nothing is reported unset. + let said = |what: &str| list.warnings.iter().any(|w| w.contains(what)); + assert!(said("no such file `$`"), "{:?}", list.warnings); + assert!(said("no such file `$/x.sv`"), "{:?}", list.warnings); + assert_eq!(list.warnings.len(), 2, "{:?}", list.warnings); + } + + #[test] + fn an_unterminated_brace_is_not_a_variable() { + let tree = TempTree::new(); + let f = tree.write("files.f", "${OPEN\n"); + let list = read_bare(&f); + assert_eq!(list.warnings.len(), 1); + assert!(list.warnings[0].contains("no such file `${OPEN`"), "{:?}", list.warnings); + } + + #[test] + fn the_public_read_uses_the_real_environment() { + // `read` differs from `read_with` only in the lookup it closes over, + // and a wrong closure there would be invisible to every other test. + let tree = TempTree::new(); + tree.source("a.sv"); + let f = tree.write("files.f", "${VFMT_FILELIST_UNSET_PROBE}a.sv\n"); + let list = read(&f).expect("readable"); + assert_eq!(names(&list), ["a.sv"]); + assert!(list.warnings[0].contains("VFMT_FILELIST_UNSET_PROBE"), "{:?}", list.warnings); + } + + #[test] + fn absolute_paths_are_taken_as_written() { + let tree = TempTree::new(); + let absolute = tree.source("rtl/a.sv"); + let f = tree.write("files.f", &format!("{}\n", absolute.display())); + assert_eq!(read_bare(&f).files, vec![absolute]); + } + + #[test] + fn everything_at_once_still_parses() { + let tree = TempTree::new(); + tree.source("rtl/top.sv"); + tree.source("ip/fifo.sv"); + tree.write("ip/ip.f", "+incdir+include\nfifo.sv\n"); + let f = tree.write( + "files.f", + "\ +// the project ++define+SYNTHESIS+W=8 ++incdir+rtl +-f ip/ip.f +rtl/top.sv # the top level +-unknown +missing.sv +", + ); + let list = read_bare(&f); + assert_eq!(names(&list), ["fifo.sv", "top.sv"]); + assert_eq!(list.incdirs, vec![tree.path.join("rtl"), tree.path.join("ip/include")]); + assert_eq!(list.defines.len(), 2); + assert_eq!(list.warnings.len(), 2, "{:?}", list.warnings); + } +} diff --git a/crates/vfmt_core/src/lib.rs b/crates/vfmt_core/src/lib.rs index 05160c6..c0f92c7 100644 --- a/crates/vfmt_core/src/lib.rs +++ b/crates/vfmt_core/src/lib.rs @@ -5,10 +5,13 @@ //! front ends cannot silently disagree: an editor's format-on-save must find //! the same `vfmt.toml` and skip the same files as CI's `vfmt --check`. //! `cache` answers the third question of the same family — whether a file -//! needs to be processed at all. See `docs/features/vfmt-core-lift/README.md`, -//! and `docs/features/{config-discovery,parallel-files,format-cache}/README.md` +//! needs to be processed at all, and `filelist` answers the first one the way +//! an EDA project already does, from a `.f` file. See +//! `docs/features/vfmt-core-lift/README.md`, and +//! `docs/features/{config-discovery,parallel-files,format-cache,filelist}/README.md` //! for the rules themselves. pub mod cache; pub mod config; +pub mod filelist; pub mod walk; diff --git a/crates/vfmt_server/src/format.rs b/crates/vfmt_server/src/format.rs index fa59868..91699a5 100644 --- a/crates/vfmt_server/src/format.rs +++ b/crates/vfmt_server/src/format.rs @@ -319,12 +319,12 @@ mod tests { // The precedence decision, pinned: `tab_size` is the editor's default // unless the user changed it, and a checked-in `vfmt.toml` is always // deliberate. See `settings_for`. - let file = FileConfig { line_length: Some(120), indent: Some(4), exclude: None }; + let file = FileConfig { line_length: Some(120), indent: Some(4), ..Default::default() }; let config = config_from(&file, &none(), &options(2, true)); assert_eq!(config.indent_width, 4, "vfmt.toml wins over tab_size"); assert_eq!(config.max_width, 120, "line-length has no client analog at all"); // Where the config is silent the tab size still beats the default. - let only_width = FileConfig { line_length: Some(120), indent: None, exclude: None }; + let only_width = FileConfig { line_length: Some(120), ..Default::default() }; assert_eq!(config_from(&only_width, &none(), &options(3, true)).indent_width, 3); } @@ -395,7 +395,7 @@ mod tests { /// `vfmt.*` settings as a client would push them. fn pushed(line_length: Option, indent: Option) -> ClientSettings { - ClientSettings { line_length, indent, exclude: Vec::new() } + ClientSettings { line_length, indent, ..Default::default() } } #[test] diff --git a/crates/vfmt_server/src/server.rs b/crates/vfmt_server/src/server.rs index 917c0c6..d5661f9 100644 --- a/crates/vfmt_server/src/server.rs +++ b/crates/vfmt_server/src/server.rs @@ -46,8 +46,10 @@ pub struct Server { impl Server { pub fn new(connection: Connection, roots: Vec) -> Server { let mut workspace = Workspace::default(); - workspace.open_roots(roots); - Server { connection, workspace, config_warnings: HashSet::new() } + let warnings = workspace.open_roots(roots); + let server = Server { connection, workspace, config_warnings: HashSet::new() }; + server.report_scope(warnings); + server } /// Receive until the client shuts us down or the channel closes. @@ -258,7 +260,15 @@ impl Server { if let Ok(p) = extract::(notification) { let uri = p.text_document.uri; self.set_document(uri.clone(), p.text_document.text); - self.publish(&uri); + // With no workspace root the index's scope *is* the open + // buffers' own directories, so opening a file widens it. + // With a root, nothing about the scope changed and the + // save path still owns rebuilding. + if self.workspace.has_roots() { + self.publish(&uri); + } else { + self.reindex(); + } } } DidChangeTextDocument::METHOD => { @@ -317,12 +327,37 @@ impl Server { /// index. Both callers changed what the index should contain — a save, or /// a new `vfmt.exclude`. fn reindex(&mut self) { - self.workspace.rebuild_index(); + let warnings = self.workspace.rebuild_index(); + self.report_scope(warnings); for uri in self.workspace.open_uris() { self.publish(&uri); } } + /// Say what went wrong while working out which files to index — a + /// filelist naming a file that has moved, an unset variable, an option + /// vfmt does not know. + /// + /// Every one is logged, but only the first is *shown*: a filelist that has + /// drifted from the tree can easily carry forty stale paths, and forty + /// popups would be worse than the problem. Said once per rebuild, which is + /// once per save — the same rhythm the `vfmt.toml` warning has. + fn report_scope(&self, warnings: Vec) { + for warning in &warnings { + self.notify( + LogMessage::METHOD, + LogMessageParams { typ: MessageType::WARNING, message: format!("vfmt: {warning}") }, + ); + } + let Some(first) = warnings.first() else { return }; + let rest = warnings.len() - 1; + let message = match rest { + 0 => format!("vfmt: {first}"), + _ => format!("vfmt: {first} (and {rest} more — see the vfmt log)"), + }; + self.notify(ShowMessage::METHOD, ShowMessageParams { typ: MessageType::WARNING, message }); + } + /// Replace a buffer's text, re-arming its `vfmt.toml` warning: the user /// has moved on, and a config problem is worth saying once more. fn set_document(&mut self, uri: Uri, text: String) { diff --git a/crates/vfmt_server/src/settings.rs b/crates/vfmt_server/src/settings.rs index fd1804d..82858f6 100644 --- a/crates/vfmt_server/src/settings.rs +++ b/crates/vfmt_server/src/settings.rs @@ -1,10 +1,13 @@ //! The `vfmt.*` settings a client pushes over `workspace/didChangeConfiguration`. //! -//! These are the editor's copy of what `vfmt.toml` carries — the same three -//! keys, so a user with no config file in the tree can still say "indent 4" -//! from their editor's settings UI. They never *beat* a `vfmt.toml`: see the -//! precedence ladder in `format::settings_for` and -//! `docs/features/editor-settings/README.md`. +//! These are the editor's copy of what `vfmt.toml` carries — the same keys, so +//! a user with no config file in the tree can still say "indent 4" from their +//! editor's settings UI. The three formatting ones never *beat* a `vfmt.toml`: +//! see the precedence ladder in `format::settings_for` and +//! `docs/features/editor-settings/README.md`. `filelist` is the exception, and +//! deliberately so — it names a *scope* rather than a style, and the person +//! who typed it into their editor is the one saying which project they are +//! working on (`docs/features/filelist/README.md`). //! //! Not to be confused with `format::Settings`, which is what one formatting //! request resolved to after every rung of that ladder was applied. @@ -35,6 +38,10 @@ pub struct ClientSettings { pub indent: Option, /// `vfmt.exclude`, appended to the config's excludes in the workspace scan. pub exclude: Vec, + /// `vfmt.filelist`: the `.f` file that defines the index's scope, absolute + /// or relative to the workspace root. Empty means "unset", which is what + /// the VS Code default is — see `docs/features/filelist/README.md`. + pub filelist: Option, } /// Read the `vfmt` section out of a `workspace/didChangeConfiguration` payload. @@ -57,9 +64,19 @@ pub fn from_payload(settings: &Value) -> ClientSettings { line_length: bounded(vfmt.get("lineLength"), LINE_LENGTH_RANGE), indent: bounded(vfmt.get("indent"), INDENT_RANGE), exclude: strings(vfmt.get("exclude")), + filelist: path(vfmt.get("filelist")), } } +/// A non-empty JSON string, or nothing. The empty string is `vfmt.filelist`'s +/// default and means "no filelist", not "the filelist named by the empty +/// path"; anything that is not a string is dropped like every other +/// wrong-typed value here. +fn path(value: Option<&Value>) -> Option { + let text = value?.as_str()?.trim(); + (!text.is_empty()).then(|| text.to_string()) +} + /// A JSON integer inside `range`, or nothing. /// /// `as_u64` rejects null, strings, booleans, negatives and fractions in one @@ -100,11 +117,35 @@ mod tests { "rainbowBeginEnd": true, "lineLength": line_length, "indent": indent, - "exclude": exclude + "exclude": exclude, + "filelist": "" } }) } + #[test] + fn a_filelist_is_taken_when_it_names_something() { + let found = settings(json!({ "vfmt": { "filelist": "rtl/files.f" } })); + assert_eq!(found.filelist.as_deref(), Some("rtl/files.f")); + let found = settings(json!({ "vfmt": { "filelist": " /abs/files.f " } })); + assert_eq!( + found.filelist.as_deref(), + Some("/abs/files.f"), + "surrounding space is not path" + ); + } + + #[test] + fn an_empty_or_wrong_typed_filelist_is_no_opinion() { + // `""` is the setting's own default: it must mean "no filelist", not + // "a filelist whose path is empty". + for bad in [json!(""), json!(" "), json!(null), json!(3), json!(["a.f"]), json!(true)] { + let found = settings(json!({ "vfmt": { "filelist": bad } })); + assert_eq!(found.filelist, None, "filelist {bad} must be ignored"); + } + assert_eq!(settings(json!({ "vfmt": {} })).filelist, None, "and so must its absence"); + } + #[test] fn the_default_vscode_payload_is_no_opinion_about_anything() { // Every setting at its `package.json` default: nulls and an empty diff --git a/crates/vfmt_server/src/state.rs b/crates/vfmt_server/src/state.rs index 319ec10..135964a 100644 --- a/crates/vfmt_server/src/state.rs +++ b/crates/vfmt_server/src/state.rs @@ -15,7 +15,7 @@ use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex, Pa use vlog_semantic::{analyze, resolve_external, ExternalResolutions, Semantics, WorkspaceIndex}; use vfmt_core::config::Discovery; -use vfmt_core::walk::collect_files; +use vfmt_core::walk::{collect_files, EXTENSIONS}; use crate::convert::Positions; use crate::settings::ClientSettings; @@ -92,15 +92,25 @@ pub struct Workspace { impl Workspace { /// Adopt the workspace roots and build the index for the first time. - pub fn open_roots(&mut self, roots: Vec) { + /// Returns whatever the caller should tell the user about the scope. + pub fn open_roots(&mut self, roots: Vec) -> Vec { self.roots = roots; - self.rebuild_index(); + self.rebuild_index() } pub fn index(&self) -> &WorkspaceIndex { &self.index } + /// 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 `vfmt.*` settings in force, for the resolution points in /// `format.rs` to fold in. pub fn client_settings(&self) -> &ClientSettings { @@ -109,12 +119,13 @@ impl Workspace { /// Adopt the settings a client pushed. /// - /// Returns `true` when the caller must rebuild the index: `exclude` is the - /// only one of the three that changes *which files exist* as far as this + /// 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; + let rescan = + self.client.exclude != settings.exclude || self.client.filelist != settings.filelist; self.client = settings; rescan } @@ -139,11 +150,16 @@ impl Workspace { self.docs.keys().cloned().collect() } - /// Re-scan the roots and rebuild the index, then refresh every open + /// Re-scan the workspace and rebuild the index, then refresh every open /// buffer's overlay. Called on `initialize` and on every `didSave`. - pub fn rebuild_index(&mut self) { + /// + /// 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 { + let (files, warnings) = self.source_files(); let mut sources: Vec<(PathBuf, String)> = Vec::new(); - for path in self.source_files() { + for path in files { if let Ok(text) = fs::read_to_string(&path) { sources.push((path, text)); } @@ -159,6 +175,7 @@ impl Workspace { for doc in self.docs.values_mut() { doc.refresh_overlay(&self.index); } + warnings } /// The text of a workspace file: the open buffer if there is one, else @@ -172,11 +189,88 @@ impl Workspace { } } + /// 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** — `vfmt.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. + fn source_files(&self) -> (Vec, Vec) { + let Some(path) = self.filelist_path() else { return (self.default_files(), Vec::new()) }; + match vfmt_core::filelist::read(&path) { + Ok(list) => (list.files, list.warnings), + Err(problem) => { + (self.default_files(), 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. + fn filelist_path(&self) -> Option { + 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 `vfmt.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 { + 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 { + 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 `vfmt` skips, the /// index skips. - fn source_files(&self) -> Vec { + fn walked_files(&self) -> Vec { let mut discovery = Discovery::new(true); let mut out = Vec::new(); for root in &self.roots { @@ -402,7 +496,7 @@ mod tests { !ws.set_client_settings(ClientSettings { line_length: Some(120), indent: Some(4), - exclude: Vec::new() + ..Default::default() }), "widths do not move files" ); @@ -412,6 +506,17 @@ mod tests { 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(); @@ -419,12 +524,149 @@ mod tests { ws.set_client_settings(ClientSettings { line_length: Some(120), indent: Some(4), - exclude: Vec::new(), + ..Default::default() }); assert_eq!(ws.client_settings().indent, Some(4)); assert_eq!(ws.client_settings().line_length, Some(120)); } + /// `vfmt.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 { + 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("vfmt.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("vfmt.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"]); + } + #[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 5aa48c1..a5da885 100644 --- a/crates/vfmt_server/tests/e2e.rs +++ b/crates/vfmt_server/tests/e2e.rs @@ -771,3 +771,130 @@ fn a_pushed_exclude_rebuilds_the_index_mid_session() { let _ = std::fs::remove_dir_all(&dir); } + +#[test] +fn a_pushed_filelist_narrows_the_index_mid_session_and_reports_a_bad_one() { + // The filelist's whole promise on the wire: a file that is in the tree but + // not in the project stops being indexed the moment the setting arrives, + // and a path that cannot be read says so instead of emptying the index. + let dir = temp_dir("filelist"); + std::fs::create_dir_all(dir.join("rtl")).expect("subdir"); + std::fs::write(dir.join("rtl/a.sv"), "package a_pkg;\n localparam K = 1;\nendpackage\n") + .expect("write"); + std::fs::write(dir.join("rtl/b.sv"), "package b_pkg;\n localparam K = 1;\nendpackage\n") + .expect("write"); + std::fs::write(dir.join("files.f"), "// only a\nrtl/a.sv\n").expect("write"); + let root = format!("file://{}", dir.display()); + + let query = |id: u32, name: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# + )) + }; + let filelist = |path: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"workspace/didChangeConfiguration","params":{{"settings":{{"vfmt":{{"filelist":"{path}"}}}}}}}}"# + )) + }; + 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":{}}"#), + query(2, "b_pkg"), + filelist("files.f"), + query(3, "b_pkg"), + query(4, "a_pkg"), + // A path that does not exist: the walk answers instead, and the user + // is told why rather than left with an empty index. + filelist("typo.f"), + query(5, "b_pkg"), + // Clearing it hands the workspace walk back. + filelist(""), + query(6, "b_pkg"), + 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 hits = |id: u32| -> usize { + let response = messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); + response["result"].as_array().map_or(0, |a| a.len()) + }; + assert_eq!(hits(2), 1, "premise: the walk indexes both files"); + assert_eq!(hits(3), 0, "the filelist does not name b.sv, so it is not indexed"); + assert_eq!(hits(4), 1, "and the file it does name still is"); + assert_eq!(hits(5), 1, "an unreadable filelist falls back to the walk"); + assert_eq!(hits(6), 1, "clearing the setting hands the walk back"); + + let complained = messages.iter().filter(|m| m["method"] == "window/showMessage").any(|m| { + let text = m["params"]["message"].as_str().unwrap_or_default(); + text.contains("typo.f") && text.contains("indexing the workspace instead") + }); + assert!(complained, "the unreadable filelist must be reported, in {messages:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn with_no_workspace_folder_the_open_files_own_directory_is_indexed() { + // A single file opened with no folder: the scope is what sits beside it, + // and the index has to be built on `didOpen` rather than on the first save. + let dir = temp_dir("noroot"); + std::fs::create_dir_all(dir.join("rtl/deeper")).expect("subdir"); + std::fs::write(dir.join("rtl/open.sv"), "package open_pkg;\n localparam K = 1;\nendpackage\n") + .expect("write"); + std::fs::write( + dir.join("rtl/sibling.sv"), + "package sibling_pkg;\n localparam K = 1;\nendpackage\n", + ) + .expect("write"); + std::fs::write( + dir.join("rtl/deeper/below.sv"), + "package below_pkg;\n localparam K = 1;\nendpackage\n", + ) + .expect("write"); + + let open_uri = format!("file://{}", dir.join("rtl/open.sv").display()); + let source = std::fs::read_to_string(dir.join("rtl/open.sv")).expect("read"); + let query = |id: u32, name: &str| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"workspace/symbol","params":{{"query":"{name}"}}}}"# + )) + }; + let session = [ + // No `rootUri` and no `workspaceFolders`: the single-file case. + frame( + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"processId":null,"capabilities":{}}}"#, + ), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + query(2, "sibling_pkg"), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{open_uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(&source).expect("json") + )), + query(3, "sibling_pkg"), + query(4, "below_pkg"), + 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 hits = |id: u32| -> usize { + let response = messages + .iter() + .find(|m| m["id"] == id) + .unwrap_or_else(|| panic!("no response {id} in {messages:#?}")); + response["result"].as_array().map_or(0, |a| a.len()) + }; + assert_eq!(hits(2), 0, "premise: nothing is indexed before a file is open"); + assert_eq!(hits(3), 1, "the neighbour of the open file is indexed"); + assert_eq!(hits(4), 0, "but the walk does not descend — this is one directory"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/filelist/README.md b/docs/features/filelist/README.md new file mode 100644 index 0000000..d6075e2 --- /dev/null +++ b/docs/features/filelist/README.md @@ -0,0 +1,449 @@ +# filelist + +## Goal + +Teach vfmt the EDA world's own project file. A `.f` filelist — one source +path per line, `-f` nesting, `+incdir+`, `+define+`, comments and `$VAR` +expansion — is what every Verilog build already has, so it is the honest +answer to rope's `.ropeproject`: when a project has one, it defines +*exactly* the set of files the server indexes, and the guesswork of walking +a workspace folder disappears. This is M1 of +`docs/features/refactor/README.md`: the parser lives in `vfmt_core` (next +to config and walk, so a future CLI `-f` reuses it unchanged), the scope +precedence lives in `vfmt_server`, and the two front doors that name a +filelist are a `filelist` key in `vfmt.toml` and the VS Code setting +`vfmt.filelist`. + +## Assumptions + +- **The filelist is a *scope*, not a build description.** M1 records + `+incdir+` and `+define+` and uses 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 + them would have to be re-parsed later, and because "unknown flag" warnings + would otherwise fire on the two flags every real filelist carries. +- **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 + middle of a component survives. A path *starting* with `#` cannot be + written; nobody writes one. +- **Paths resolve against the directory of the filelist that names them** + — the EDA convention, and the same rule for source files, nested `-f` + targets and `+incdir+` directories. The result carries them normalized + (`.`/`..` folded, joined onto the current directory when the filelist + itself was named relatively) so the index sees one spelling per file. + Symlinks are deliberately **not** resolved, matching + `config-discovery`'s "lexical, not symlink-aware" rule. +- **An unknown flag is skipped alone, not with its argument.** vfmt has no + table of which EDA flags take a value, and inventing one would be a + guess. So `-y lib/` warns about `-y` and then reports `lib/` as a missing + source file (a directory is not a file). Two warnings for one line is + noisier than one, and it is honest: nothing was silently swallowed. +- **A repeated filelist is skipped, whether or not it is a true cycle.** + One `seen` set covers both, because the effect is identical — the same + paths would be added twice — and the warning says which file was skipped. +- **`-f` nests at most `MAX_NESTING_DEPTH` = 256 levels**, after which the + chain is warned about and abandoned. The `seen` set stops a *cycle*; only + a depth limit stops a long chain of **distinct** filelists, which is the + shape a generator emits and which recursed until the stack overflowed + (QA finding, 2026-08-24). A stack overflow is not a panic — it aborts the + process, so the whole language server died on `initialize` rather than one + filelist going bad. 256 is far above anything real (a hand-written + filelist nests two or three deep) and far below the ~1500 frames at which + an unoptimized build overflows, the same margin reasoning as + `docs/features/recursion-limit/README.md`. +- **A path containing whitespace cannot be listed.** Tokens are split on + whitespace with no quoting, so `sp ace/file.sv` is two dead tokens and two + "no such file" warnings, not one entry. EDA tools disagree about quoting + and Verilog build trees conventionally have no spaces in them; support can + be added when someone has such a tree, and until then the failure is at + least loud rather than silent. +- **An unset environment variable expands to nothing**, with a warning, + rather than failing the whole filelist. That is what `vcs`/`xrun` do, and + the missing-file warning that usually follows says the same thing again + in more useful terms. +- **Reading a filelist is I/O the server does on every index rebuild.** No + caching, no watching: `rebuild_index` already re-reads the whole workspace + on save, and one extra small file is nothing next to that. +- **`vfmt.toml`'s `filelist` value is a path, not a glob.** It is resolved + against the config file's own directory when the config is loaded, so the + `FileConfig` a caller receives already carries a usable path. + +## Handshakes + +### `vfmt_core::filelist` (new module) + +```rust +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 defines: Vec<(String, Option)>, // recorded, unused in M1 + pub warnings: Vec, // ":: " +} + +pub fn read(path: &Path) -> Result; +``` + +`Err` is reserved for the **root** filelist being unreadable — the one case +where the caller learns nothing at all. Everything else (a nested `-f` that +cannot be read, a listed file that does not exist, an unknown flag, an unset +variable, a repeated filelist, a chain nested past `MAX_NESTING_DEPTH`) is a +warning on an otherwise usable result. `read` neither panics nor aborts: on +any input, including an adversarial one, it returns. + +### `vfmt_core::config` + +`FileConfig` gains `filelist: Option`, from the new `vfmt.toml` key +`filelist = "path"`. `parse` records the path **as written** (it has no idea +where the file lives); `Discovery` resolves it against the config file's +directory, so every `FileConfig` handed out by `Discovery` carries a +resolved path. Same strictness as the other keys: a non-string value, a +duplicate, or any unknown key is still a hard error naming file and line. + +### `vfmt_server` + +- `ClientSettings` gains `filelist: Option` from `vfmt.filelist`. + An empty string means "unset", which is what the VS Code default is. +- `Workspace::set_client_settings` now returns `true` for a `filelist` + change as well as an `exclude` change — both change *which files exist*. +- `Workspace::rebuild_index()` and `open_roots()` now **return + `Vec`**, the warnings from resolving the scope. `state.rs` does + no protocol I/O; `server.rs` renders them (one `window/showMessage`, + every warning to `window/logMessage`), once per rebuild. +- `Workspace::has_roots()` is new: with no workspace root the index scope + follows the open buffers, so `server.rs` rebuilds on `didOpen` instead of + only on save. + +### The scope ladder (the contract this feature is) + +Highest first, resolved on every index rebuild: + +| # | Scope | When | +|---|---|---| +| 1 | The files a **filelist** names | `vfmt.filelist` is set (absolute, or relative to the first workspace root), else the workspace root's `vfmt.toml` has a `filelist` key | +| 2 | The **workspace-folder walk** | there is a workspace root — unchanged from before this feature | +| 3 | Each **open file's own directory**, non-recursive | there is no workspace root at all (a single file opened) | + +Open buffers overlay every rung exactly as they did before: a buffer's text +beats what is on disk, and a buffer whose path the scope does not name is +added to the index anyway. A configured filelist that cannot be read falls +back to rung 2 (or 3) with a visible warning — never a crash, never an empty +index. + +### `editors/vscode` + +New setting `vfmt.filelist` (string, default `""`), forwarded by the +existing `synchronize.configurationSection: 'vfmt'` machinery — no +extension code change. + +## Status / TODO + +- [x] `crates/vfmt_core/src/filelist.rs`: parser + `Filelist` + `read` +- [x] comments (`//`, `#`), blank lines, `-f` nesting with cycle/repeat + detection and a 256-level depth limit, `+incdir+` (multi-`+`), + `+define+NAME[=VAL]` (multi-`+`), + `$VAR`/`${VAR}` expansion, unknown `+arg`/`-flag` warnings, missing + files warned and skipped, relative resolution against the naming + filelist +- [x] `vfmt.toml` key `filelist`, resolved against the config's directory +- [x] `vfmt.filelist` client setting, and the rescan it forces +- [x] Server scope ladder (filelist ⊃ workspace walk ⊃ open-file directory) + with warnings surfaced once per rebuild +- [x] `vfmt.filelist` in `editors/vscode/package.json` + README; root + README config and editor sections +- [x] Unit tests in `vfmt_core` and `vfmt_server`; `cargo fmt`, `cargo + clippy --all-targets`, `cargo test` all clean +- [ ] 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. +- [ ] Not done, deliberately: no file watching. The filelist is re-read on + every index rebuild (save, settings change, open with no root). + +## Work log + +### 2026-08-24 — dev agent, M1 + +Written in the order the brief lists: parser, config key, server scope, +editor setting. Decisions worth recording: + +- **`read` returns `Result` only for the root file.** Every other failure + is a warning on a usable result. The alternative — failing the whole + filelist because one of 400 listed files was deleted — would make the + server fall back to a workspace walk exactly when the user most wanted + the filelist honoured. +- **Comment stripping is per token, not per line.** A `#` at character + granularity would truncate any path containing one; a token-initial `#` + or `//` cannot be a path anyone writes. Recorded under Assumptions + because it is the one place this parser is deliberately narrower than + "strip everything after the first `#`". +- **Environment lookup is injected** (`read_with(path, &dyn Fn(&str) -> + Option)`, private) so the expansion tests do not mutate the + process environment — `std::env::set_var` from parallel test threads is + a race even when it compiles. The public `read` closes over + `std::env::var`, and one test drives it through a real variable to prove + the wiring. +- **Paths come out normalized and absolute.** Two spellings of one file + (`rtl/../rtl/a.sv`) would otherwise become two `FileId`s in the index. + `normalize` folds `.`/`..` textually and joins the current directory, + exactly as `config::Discovery::absolute` does, and for the same reason: + the path the user typed is the path they mean, symlinks included. +- **Scope resolution returns its warnings instead of printing them.** + `state.rs` has never spoken protocol and does not start now; the two + functions that could produce warnings (`open_roots`, `rebuild_index`) + return `Vec` and `server.rs` decides how loud to be. It shows the + first warning and logs all of them — a filelist with 40 stale paths must + not open 40 popups. +- **`didOpen` rebuilds the index when there is no workspace root.** Rung 3 + is defined by the open buffers, so without this the sibling-directory + index would stay empty until the first save. With a root, nothing + changed. + +**Files touched outside the brief's scope**, all forced by the new field and +kept to the minimum: + +- `crates/vfmt/src/args.rs` — two `FileConfig`/help edits. Adding a public + field breaks every struct literal, so the two test literals became + `..Default::default()`; and `--help`'s CONFIGURATION paragraph lists the + recognized keys by name, which would have been a lie the moment the parser + accepted a fourth. The new line says `filelist` is read by `vfmt-server` + only, so nobody expects the CLI to act on it. +- `crates/vfmt_server/src/format.rs` — the same struct-literal fix in two + tests. No behavior in that module changed. + +**Deviations from the brief.** Two, both narrowing: + +1. `Filelist::files` is **deduplicated** (first occurrence wins). The brief + named the field but not the policy; `-f` nesting makes a file listed + twice ordinary, and "exactly the set of files to index" is a set. +2. `+incdir+` directories are **resolved** against the naming filelist's + directory and normalized, not recorded verbatim. The brief said + "recorded, not used further"; recording an unresolvable relative path + would make the eventual consumer resolve it against the wrong + directory, and the information needed (which filelist named it) is gone + by then. + +Also noted and **not** touched, being outside this feature's scope: the +root `README.md`'s editor section still says "the server does **not** read +`vfmt.toml` yet", which the `editor-settings` feature already made false. +Flagged for the lead rather than fixed here. (The neighbouring sentence +"One setting, `vfmt.serverPath`" *was* rewritten, because this feature adds +a setting and leaving a count that is now wrong by three would have been +worse than the one-line edit.) + +**Verification.** `cargo fmt --all -- --check` clean; `cargo clippy +--all-targets` silent; `cargo test --workspace` green — 1007 tests, of +which 34 are new: 23 in `vfmt_core` (20 `filelist` + 3 `config`), 9 in +`vfmt_server` (2 `settings`, 7 `state`) and 2 e2e sessions against the real +binary (a filelist pushed, narrowed and broken mid-session; a file opened +with no workspace folder). `node editors/vscode/smoke.js +target/debug/vfmt-server` OK, `node --check` on both JS files, and +`package.json` parses. + +### 2026-08-24 — dev agent, QA round 1 fixes + +**Finding 1 (Medium), fixed: unbounded `-f` recursion aborted the process.** +`Reader` gained a `depth` counter and `filelist.rs` a documented +`MAX_NESTING_DEPTH = 256`; `Reader::nested` checks it before descending and, +past it, emits an ordinary warning naming the filelist that stopped and the +target it refused (`f256.f:2: filelist \`f257.f\` nests more than 256 levels +deep, not descending further`). The `seen` set was doing the job it was +written for — cycles — and QA is right that it never bounded a chain of +*distinct* files. + +Why a depth guard rather than an iterative worklist: the recursion is what +makes files land in list order (a nested filelist's files belong where the +`-f` sits), and a worklist would have to carry every pending filelist's text +to preserve that. A counter is three lines and matches the precedent the +parser already set for the identical failure +(`docs/features/recursion-limit/README.md`). + +Why 256: a filelist that nests at all nests two or three deep, so 256 costs +nobody anything real, and QA measured the overflow floor at ~1500 frames in +an unoptimized build — a ~6× margin, in the direction where being wrong is +an uncatchable abort rather than a diagnostic. Reasoning recorded on the +constant and in Assumptions. + +**Regression test** +(`a_chain_of_distinct_filelists_stops_at_the_depth_limit`): a chain of +`MAX_NESTING_DEPTH * 4` uniquely-named filelists, each naming its own source +and `-f`-ing the next. Asserts `Ok`, exactly `MAX_NESTING_DEPTH + 1` files, +the first and last of them by name, and exactly one warning naming the +limit and the filelist that hit it — not one per remaining level, and not +silence. + +**Mutation-checked, because a guard test that cannot fail is worthless.** +Raised the constant to 1 000 000 and pointed a throwaway test at a +20 000-deep chain: `fatal runtime error: stack overflow, aborting`, SIGABRT, +exactly QA's reproduction. Restored the constant and the file; the probe +test is not in the tree. + +**Re-verified on the real binary, as QA asked.** Built +`target/release/vfmt-server`, gave it a scratch workspace whose `vfmt.toml` +names a 20 000-level chain, and drove a raw stdio LSP session +(`initialize` + `workspace/symbol` + `shutdown`/`exit`): exit code 0, both +requests answered, the package declared in the chain found in the index, and +one `window/showMessage` + one `window/logMessage` carrying the depth +warning. Before the fix this same session died with SIGABRT on `initialize`. +Scratch tree deleted. + +**Finding 2 (Low), documented not fixed** — per the coordinator: paths +containing whitespace are not representable, now stated in Assumptions with +the reason (no quoting, EDA tools disagree, Verilog trees conventionally have +no spaces) rather than left as an unstated gap. No parser change. + +**Finding 3** needed nothing: QA agrees the `normalize` / +`Discovery::absolute` duplication is deliberate and already justified in the +work log above. + +**Gates after the fix.** `cargo fmt --all -- --check` clean, `cargo clippy +--all-targets` silent, `cargo test --workspace` green — 1008 tests (one new +regression test), `vfmt_core` at 69 unit tests. + +## QA log + +### 2026-08-24 — QA agent, M1 + +**Verification of the dev's claims.** `cargo fmt --all -- --check` clean, +`cargo clippy --all-targets --workspace` silent, `cargo test --workspace` +green — 1007 tests, matching the Work log's count exactly. Built +`target/debug/vfmt-server` and `target/release/vfmt-server` and ran `node +editors/vscode/smoke.js target/debug/vfmt-server` — OK. `node --check` on +`editors/vscode/extension.js` and `smoke.js`, and `package.json` parses as +JSON. Read `filelist.rs`, the `config.rs` diff, `state.rs`, `server.rs` and +`settings.rs` in full; every claim in the Handshakes/Status sections checks +out against the code, and the scope-ladder precedence (filelist > workspace +walk > sibling directory) matches both the unit tests and my own probing. +CLAUDE.md Rust standards: no `unwrap()`/`expect()`/`panic!` outside `#[cfg(test)]` +in any changed file (`grep` over the diffs and over `filelist.rs`), no +`unsafe`, no new dependency (`Cargo.toml`s unchanged), public items carry doc +comments (`Filelist`, `read`, the new `FileConfig::filelist`, +`ClientSettings::filelist`, `Workspace::has_roots`, etc.). + +**Adversarial testing.** Built a throwaway `vfmt_core` example (`cargo run -p +vfmt_core --example `, deleted afterwards — not committed) to drive +`filelist::read` directly, plus a small Node script driving the real +`vfmt-server` binary over stdio the way `smoke.js` does, against a +`vfmt.toml`-configured filelist. Tried: a filelist that `-f`s itself, two +filelists that `-f` each other, `-f` with no argument, a bare `+define+` +line, `+define+N=a=b`, an unterminated `${VAR`, CRLF line endings, a path +naming a directory, an empty filelist, a path containing a space, a `$` alone +and at end of line, a unicode path, `-y lib/` (unknown flag with an +argument-shaped next token), and deep `-f` nesting. All but the last behaved +exactly as documented and as the existing unit tests assert: + +- Self-`-f` and mutual `-f` cycles: caught by the `seen` set, one warning, + no infinite loop, no crash. +- CRLF: `str::lines()` already strips a trailing `\r`, so this needed no + special-casing and there isn't any — confirmed it just works. +- `+define+N=a=b` → `("N", Some("a=b"))` (first `=` splits, rest is the + value) — matches `split_once` semantics, no test for it existed so I added + none either (behavior is obvious from the code and not worth pinning). +- A bare `+define+` line: silently defines nothing (the split-on-`+` + iterator is empty). No warning, but also no claim anywhere that one should + fire — not a bug. +- `${VAR` and a lone `$`: both fall through to "not a variable reference," + stay literal, and go on to fail the missing-file check exactly as the + existing `an_unterminated_brace_is_not_a_variable` test pins. +- `-y lib/`: two warnings, `-y` unsupported and `lib/` no-such-file (it's a + directory) — exactly the Assumptions section's own worked example. +- A path with a space (`sp ace/file.sv`, unquoted): splits into two dead + tokens (`sp`, `ace/file.sv`), each warned "no such file". Not a crash, but + worth recording — see Finding 2. + +**Finding 1 (Medium) — unbounded `-f` recursion overflows the stack and +aborts the whole server process.** `Reader::filelist` → `Reader::nested` → +`Reader::filelist` is plain function recursion with no depth limit; the +`seen` set only rejects a *repeated* path, not a long chain of distinct +ones. A straight chain of uniquely-named filelists, each `-f`-ing the next +(no cycle, no repeat), crashes with `fatal runtime error: stack overflow, +aborting` (SIGABRT) once it's deep enough: + - `filelist::read` alone: overflows around 1500–3000 levels in a debug + build, and somewhere between 10 000 and 30 000 in `--release`. + - The **real `target/release/vfmt-server` binary**, given a workspace + whose `vfmt.toml` names such a filelist, crashes the same way on + `initialize` (confirmed via a raw stdio LSP session): `closed: code=null + signal=SIGABRT`. This takes down the whole language-server process for + every open file, not just a diagnostic on one buffer. + + This contradicts the feature's own promise — `filelist.rs`'s module doc + says "Nothing here fails on bad content... `read` never panics" (line 6-9), + and the README's Handshakes section says the same ("`read` never panics"). + A stack overflow isn't technically a Rust `panic!` (it can't be caught by + `catch_unwind` either), but the practical effect — an uncontrolled process + abort instead of a graceful `Err`/warning — is exactly the failure mode + hard invariant 1 and this feature's Assumptions ("never a crash, never an + empty index") both rule out. 10k–30k levels of genuine hand-nested `-f` is + unrealistic, but it is a very plausible shape for a *generated* filelist + (a build script that emits one `.f` per source file, each nesting the + next) at the scale of a large SoC's file count, and there's no guard + today. Reproduction left as the two temp trees I generated and then + deleted (not committed, since 20k+ tiny files don't belong in the repo); + regenerate with a Python loop writing `f{i}.f` containing `-f f{i+1}.f` + for `i` in `0..N`, terminated by a real source path, `N` in the low + thousands for a debug build. Filed for the dev/lead — this is bigger than + a QA-fixable typo (it needs either an explicit depth counter with a + warning-and-stop, or converting the recursion to an explicit worklist), + so I did not attempt a fix myself. + +**Finding 2 (Low) — no quoting, so a path containing a space cannot be +listed.** The tokenizer is `raw.split_whitespace()` +(`crates/vfmt_core/src/filelist.rs:76`); a filelist line like `sp ace/file.sv` +splits into two tokens and neither resolves, producing two spurious +"no such file" warnings instead of one correct entry. Real EDA tools vary +here (some support `"quoted paths"`, some don't support spaces at all), so +this isn't necessarily wrong, but the Assumptions section documents several +other narrowing decisions explicitly and this one isn't mentioned anywhere. +Suggest either a one-line Assumptions addition ("paths containing whitespace +are not representable, matching tools that require no-space build trees") or +backlog quoting support — not a functional bug, not fixing myself since it's +a documentation/scope call for the dev or lead to make. + +**Finding 3 (trivial, informational only, not fixed) —** `Reader::normalize` +(`filelist.rs:183-196`) is a byte-for-byte duplicate of +`config::Discovery::absolute` (`config.rs:221-234`). The dev's Work log +already calls this out and justifies it ("exactly as `config::Discovery::absolute` +does, and for the same reason"); `Discovery::absolute` is a private method on +a stateful struct so sharing it isn't a trivial extraction. Not filing as a +real finding, just recording that I saw it and agree with leaving it as +tracked, deliberate duplication rather than a missed reuse opportunity. + +**Not re-verified independently (accepted on the dev's word, tests back it up):** +the exact `Filelist::files` dedup-first-wins order and the `+incdir+` +resolution-against-naming-directory behavior — both have direct unit tests +(`dotted_paths_are_folded...`, `incdirs_are_recorded_in_both_the_single_and_the_multi_form`) +that I read and consider adequate; I did not additionally hand-probe them. + +**Verdict: ship-after-fixes.** Every claim in the feature README checks out, +all three gates (`fmt`/`clippy`/`test`) are clean, and the server-side scope +ladder is solid under real stdio sessions. Finding 1 is the one thing I would +not ship as-is: it's a genuine crash of the whole server process, reachable +through nothing more exotic than a large generated filelist, and it +contradicts a promise the feature's own docs make twice. Findings 2 and 3 +are not blockers. Recommend the dev add a depth guard (or iterative +worklist) to `Reader::nested`/`Reader::filelist` before this ships, with a +masked-corruption-style regression test pinning that a filelist nested +past the guard still returns a usable `Filelist` with a warning rather than +aborting — and re-run the same deep-chain probe against the real +`vfmt-server` binary as part of that fix's verification, since that's where +the failure is actually user-visible. + +## Review + +**2026-08-24 — lead.** Reviewed the full diff, the QA log and the QA-round-1 +fixes; ran `cargo fmt --check` / `clippy --all-targets` / `test --workspace` +independently (28 suites, 0 failures). The parser is the boring, std-only +implementation the plan asked for; the depth-guard fix is the right shape +(same precedent as the parser's recursion limit), and the mutation check plus +the real-binary re-verification is exactly the level of proof wanted for a +crash fix. The scope ladder in `state.rs` keeps protocol out of the state +layer and the `didOpen`-reindexes-only-when-rootless distinction is correctly +reasoned. Deviations (dedup policy, resolved incdirs, the two out-of-scope +test-literal touches) are all justified and logged. Accepted; M1 is checked +off in the umbrella plan and TODO.md §8. Follow-ups inherited by later +milestones: none blocking — the whitespace-path gap and `-F` stay documented +non-goals until someone asks. diff --git a/docs/features/refactor/README.md b/docs/features/refactor/README.md new file mode 100644 index 0000000..7784b43 --- /dev/null +++ b/docs/features/refactor/README.md @@ -0,0 +1,201 @@ +# refactor — a rope for Verilog/SystemVerilog (umbrella plan) + +This is the **umbrella plan** for porting the ideas of +[rope](https://github.com/python-rope/rope) — Python's refactoring library — +to vfmt. It is the single source of truth for the refactoring roadmap: the +feature list below is the checklist the lead crosses off as milestones land +and pass QA. Each milestone is implemented as its **own feature** with its own +`docs/features//README.md`, per the repo's document-based workflow; this +file links to them. + +## Goal + +Give vfmt the refactoring layer that ruff/Pylance users take for granted and +no Verilog tool ships well: rename that actually updates every reference +across files, module signature changes (add/remove ports) that update every +instantiation, and "module hinting" — instantiation skeletons generated from +the module's real definition, the way type hints drive completion in Python. +All of it server-first (VS Code + Vim through the one `vfmt-server` binary), +scoped by an explicit **filelist** when the user has one and by sensible +defaults when they don't, and covered by the same never-corrupt-code contract +as the formatter. + +## The rope → Verilog/SV mapping + +What rope does for Python, and what the honest Verilog/SV equivalent is. +This mapping is where the feature list comes from. + +| rope feature | Verilog/SV translation | +|---|---| +| Rename (variables, functions, modules, params; optional in-comments) | Rename nets/variables, ports, parameters, modules, instances, functions/tasks, typedefs, enum members, struct fields, packages, genvars — cross-file through the workspace index | +| Change signature (add/remove/reorder args, `autodef` defaults) | Add/remove/reorder **module ports and parameters**, updating the declaration *and every instantiation* (named, ordered, `.*`), plus task/function arguments | +| Type hinting driving completion | **Module hinting**: the workspace index knows every module's ports/params, so instantiation is generated, completed and signature-helped from the definition | +| Extract method | **Extract module**: lift a selected block of logic into a new module with inferred ports (read → input, driven → output), instantiate it in place | +| Inline (function/parameter) | Inline a `localparam`/`parameter` value; inline a net with a single continuous assign into its uses | +| Move (class/function to another module) | Move a typedef/function/localparam into a package; move a module to its own file (with `module-filename` agreement) | +| Organize imports | Sort/dedupe `import pkg::*` / explicit imports; drop unused imports | +| Restructure (pattern-based rewriting) | Deliberately deferred — a pattern language is a project of its own | +| Project scope (`.ropeproject`) | **Filelist (`.f`)** — the EDA-native project file; fallback scope rules below | +| Undo/redo history | Deliberate non-goal: LSP `WorkspaceEdit` gives client-side undo, and git is the history (rope predates ubiquitous VCS; we don't) | +| Preview diffs | `WorkspaceEdit` is previewable in the client; CLI paths get `--diff`/`--check` | +| Static object analysis (SOA/DOA) | Already exists: `vlog_semantic` + `WorkspaceIndex` are the analysis layer; refactorings consume them, never re-implement resolution | + +## Feature list — what a good Verilog/SV refactoring tool supports + +The lead checks items off **only after the milestone's QA log is clean and +the work is reviewed**. Owner-priority items first (2026-08-24). + +### Scope / project model +- [x] **Filelist support** — accept a standard EDA filelist (`-f` style: one + path per line, `-f` nesting, `+incdir+`, `+define+`, comments, env vars); + when given, it defines *exactly* the set of indexed files + → `docs/features/filelist/README.md` (M1) +- [x] **Fallback scope without a filelist** — workspace folders as today; + when there is no workspace root (single file opened), index the files + sharing the current file's directory → same feature (M1) + +### Rename +- [ ] **Rename any symbol** the semantic layer resolves — wire/reg/logic + nets and variables, ports, parameters/localparams, genvars, typedefs, + enum members, functions/tasks, modules, instances, packages, class + members — via LSP `textDocument/rename` → `docs/features/refactor-rename/README.md` (M2) +- [ ] **`prepareRename`** — reject up front what can't be renamed (keywords, + macro uses, unresolved names), so the editor never offers a broken rename → M2 +- [ ] **Cross-file rename** through the workspace index (module names update + every instantiation; package members update every import site) → M2 +- [ ] **Rename safety**: refuse on collision with an existing name in any + affected scope, on invalid identifiers, and whenever any resulting file + would no longer parse — whole-edit-or-nothing, like the formatter → M2 +- [ ] Rename in comments/strings as an *option* (rope's `docs=True`) — off + by default; deferred until asked for + +### Module signature (change signature) +- [ ] **Add a port** to a module: declaration + every instantiation gains a + named connection (`.p(p)` when a same-named signal is in scope at the + instantiation, else `.p(/* connect */)`), non-ANSI decls updated too → `docs/features/refactor-ports/README.md` (M3) +- [ ] **Remove a port**: dropped from the declaration and from every + instantiation (named connection deleted; ordered connection turned into + an explicit empty positional; refuse if the connected expression has + visible side effects to preserve) → M3 +- [ ] **Propagate ports**: diff a module's declaration against each + instantiation and add the missing named connections — the code action + form that needs no free-form input → M3 +- [ ] Reorder ports / rename-a-port-as-signature-change (rename already + covers the references; this is about connection order) — backlog +- [ ] Parameter add/remove with default propagation (rope's `autodef`) — backlog +- [ ] Task/function argument add/remove/reorder — backlog + +### Module hinting (instantiation assist) +- [ ] **Instantiate-from-definition**: completion on a module name at item + position expands a full skeleton — parameter overrides with their + declared defaults, every port as `.port(port)` with snippet tabstops → `docs/features/refactor-instantiate/README.md` (M4) +- [ ] **Auto-connect**: a port whose name matches a signal in the enclosing + scope is connected to it; the rest get placeholder tabstops → M4 +- [ ] **Signature help inside a connection list** — remaining ports, their + directions and types, from the definition → M4 +- [ ] Declare-missing-signals companion action (generate `logic` decls for + unconnected skeleton ports) — backlog + +### Structural refactorings (backlog, post-M4) +- [ ] **Extract module** from a selected statement range (infer ports from + read/driven sets) — the flagship, hardest one +- [ ] **Inline localparam/parameter** value at every use +- [ ] **Inline net** with a single continuous assign +- [ ] **Expand `.*`** into explicit named connections (and the reverse) +- [ ] **Ordered → named connections** conversion +- [ ] **Non-ANSI → ANSI header** conversion +- [ ] **`reg`/`wire` → `logic`** modernization (pairs with the + `wire-reg-mixup` lint rule's fix slot) +- [ ] **Move typedef/function/localparam into a package**; update imports +- [ ] **Organize imports** (sort, dedupe, drop unused) +- [ ] **Rename module together with its file** (`module-filename` rule + agreement; needs LSP `workspace/willRenameFiles` plumbing) + +## Assumptions + +- The semantic layer is the ground truth for "what references what". + Refactorings **never do textual search-and-replace**; every edit comes + from a resolved reference span. Where resolution is honest about + uncertainty (`InheritedCandidate`, ambiguous duplicates), the refactoring + refuses rather than guesses — rope's "unsure matches" mode is *not* ported. +- vfmt does not preprocess. A rename target whose name also appears inside + a `` `define`` body or an `` `ifdef``-excluded region is reported as a + warning on the response, and those occurrences are left untouched. +- Verification budget: re-parsing every touched file after an edit is + affordable (files are small; the corpus parses at ~ms each). No + refactoring needs the *formatter's* verify pass, and none touches + `verify.rs` (hard invariant 4 stays untouched). +- Filelist paths are resolved relative to the filelist's own directory, + the EDA convention. `+incdir+`/`+define+` are recorded but only paths + feed the index in M1. +- Owner interpretation (2026-08-24): "no filelist → index files sharing the + current file's path" is implemented as the *no-workspace-root* fallback; + when the editor did open a workspace, the existing folder walk already + covers (and supersedes) the sibling-directory behavior. + +## Handshakes + +- **`vlog_semantic`**: refactorings consume `Semantics` (`symbol_at`, + `references_of`), `WorkspaceIndex` and `ExternalResolutions` read-only. + Any resolution gap found while refactoring is filed against + `vlog-semantic`, not patched around in the refactor crate. +- **`vfmt_server`**: owns only the protocol mapping (WorkspaceEdit, + completion/snippet encoding, signature help); all edit *computation* + lives in the new `vlog_refactor` crate so Vim gets identical behavior. +- **`vfmt_core`**: filelist parsing lives here (next to config/walk), so a + future CLI `-f` flag reuses it unchanged. +- **`vlog_formatter`**: not a dependency. Refactored output is *edited + source*, not reformatted source — the user runs the formatter separately. + (Keeps refactor edits minimal and reviewable, and keeps the formatter's + safety net out of scope.) +- **`editors/vscode`**: new setting `vfmt.filelist` (string path, default + empty) forwarded like the existing `vfmt.*` settings. + +## Milestones + +Each is one feature dir, one dev agent, one QA pass, one lead review, one +commit — in order: + +1. **M1 `filelist`** — `.f` parsing in `vfmt_core` (paths, `-f` nesting with + cycle detection, `+incdir+`/`+define+` recorded, `#`//`//` comments, + `$VAR`/`${VAR}` expansion; unknown `+args`/`-flags` skipped with a + warning), server scope resolution (filelist ⊃ workspace walk ⊃ + current-file directory), `vfmt.filelist` VS Code setting + vfmt.toml + `filelist` key. +2. **M2 `refactor-rename`** — new crate `vlog_refactor` with the edit-plan + model (`RefactorEdit { file → Vec }`, verification by + re-parse), rename engine, LSP `prepareRename`/`rename`. +3. **M3 `refactor-ports`** — add/remove/propagate port across declaration + + all instantiations, exposed as code actions + `workspace/executeCommand`. +4. **M4 `refactor-instantiate`** — instantiation completion snippets, + auto-connect, signature help in connection lists. +5. **Backlog** — the unchecked structural items above, re-planned when the + first four have soaked. + +## Status / TODO + +- [x] Plan written; rope docs surveyed (overview: rename, extract, inline, + move, change signature, restructure, organize imports, SOA/DOA, history) +- [x] M1 filelist — done, QA clean, reviewed +- [ ] M2 refactor-rename +- [ ] M3 refactor-ports +- [ ] M4 refactor-instantiate +- [ ] Backlog triage after M4 + +## Work log + +- **2026-08-24 (lead)**: Umbrella plan created from the rope overview docs + and the current state of `vlog_semantic`/`vfmt_server`/`WorkspaceIndex`. + Key decisions: server-first (no CLI surface yet), semantic-resolution-only + edits (no textual fallback), whole-edit-or-nothing verification by + re-parse, filelist in `vfmt_core`, rope's history/restructure explicitly + not ported. Milestone READMEs are created by their dev agents. + +## QA log + +(reserved for the QA agents of the milestone features; this umbrella doc +itself carries no code) + +## Review + +(reserved) diff --git a/editors/vscode/README.md b/editors/vscode/README.md index b7196ef..ee89f89 100644 --- a/editors/vscode/README.md +++ b/editors/vscode/README.md @@ -77,9 +77,11 @@ if it ever happens. | `vfmt.lineLength` | unset | Maximum line width, same as `line-length` in a `vfmt.toml`. 40–400. | | `vfmt.indent` | unset | Indent width in spaces, same as `indent` in a `vfmt.toml`. 1–8. | | `vfmt.exclude` | `[]` | Extra patterns to keep out of the workspace index, same as `exclude` in a `vfmt.toml`. **Added to** the project's excludes, never replacing them. | +| `vfmt.filelist` | `""` | Path to an EDA filelist (`.f`), absolute or relative to the workspace folder. When set, exactly the files it names are indexed. Overrides a `filelist` key in the project's `vfmt.toml`. | -The last three mirror the three keys `vfmt.toml` supports, for people with no -config file in the tree. **A `vfmt.toml` always wins over them**, so a project +The last four mirror the four keys `vfmt.toml` supports, for people with no +config file in the tree. **A `vfmt.toml` always wins over them** — except +`vfmt.filelist`, which is a scope, not a style, and is explained below. So a project that checks one in keeps one source of truth and format-on-save cannot drift from CI's `vfmt --check`. Full precedence, highest first: @@ -95,6 +97,26 @@ naming only `indent` still lets `vfmt.lineLength` choose the width. Changes take effect on the next format — no reload — and out-of-range or wrong-typed values are ignored rather than half-honoured. +## Which files are indexed + +Navigation, hover and workspace symbols answer from an index of the project's +files. What goes into it, highest first: + +1. **A filelist**, if there is one — `vfmt.filelist`, else a `filelist` key in + the project's `vfmt.toml`. Exactly the files it names are indexed, so a + vendored copy your build does not compile stops showing up in + go-to-definition. Standard `.f` syntax: one path per line, `-f other.f` to + nest, `+incdir+`/`+define+` (recorded, unused for now), `#` and `//` + comments, `$VAR`/`${VAR}` expansion, paths relative to the filelist itself. +2. **The workspace folder**, walked as `vfmt` itself walks it — same + extensions, same `.gitignore`, same excludes. +3. **The open file's own directory**, when no folder is open at all. + +Open buffers are always indexed on top of that, so a scratch file the project +does not list still works. A filelist that names a file which has moved warns +and skips it; a filelist that cannot be read at all warns and falls back to +walking the folder — the index is never silently empty. + ## Rainbow begin/end Each nesting level of `begin`/`end` and `fork`/`join` is coloured differently, diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 3d3b2b8..ec2946d 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -97,6 +97,11 @@ }, "default": [], "markdownDescription": "Extra path patterns to keep out of the workspace index, the same as `exclude` in a `vfmt.toml`. These are **added to** the project's own excludes, never replacing them." + }, + "vfmt.filelist": { + "type": "string", + "default": "", + "markdownDescription": "Path to an EDA filelist (`.f`), absolute or relative to the workspace folder. When set, **exactly** the files it names are indexed instead of the whole folder — `-f` nesting, `+incdir+`, `+define+`, `#`/`//` comments and `$VAR` expansion are all understood. Overrides a `filelist` key in the project's `vfmt.toml`; leave it empty to index the workspace folder." } } }