From f3b5a9d189d3e080b725f880c878bdd7a8ecc58b Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Sun, 30 Aug 2026 19:02:42 -0700 Subject: [PATCH] Fuzzy completion: clkenq reaches clk_osc_en_q, at VS Code's own floor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prefix matching below three typed characters, subsequence from three up — the owner's ruling, which is VS Code's own rule. The scope, index-name and word tiers match by case-insensitive subsequence at 3+, ranked prefix-first then by a three-pass greedy-tighten scorer (boundary and contiguity bonuses, gap penalties); module, keyword, template and macro tiers unchanged, and the instantiation ghost's exact-match probe deliberately stays exact. The scan is affordable because every word and unit name carries a 32-bit character mask beside it, written in exactly two places so table and mask cannot desync: a clkenq keystroke rejects 99.6% of opentitan's 100k-word table with one AND each (+0.05 ms); the pathological class is three very common letters (aes +0.8 ms, QA's ena ~3-4 ms answered-in), accepted at lead review as imperceptible in a popup. Responses below the floor are always isIncomplete — a complete two-character answer would be client-filtered and the third keystroke, the one that turns fuzzy on, would never reach the server. QA verified clkenq -> clk_osc_en_q live in a real opentitan buffer (gfr_clk_mux2.sv) and the 2-to-3 transition over the wire; ten adversarial matcher attacks all passed. docs/features/fuzzy-completion/README.md; TODO.md section 13. Co-Authored-By: Claude Fable 5 --- TODO.md | 74 +++ crates/lucisv_server/src/candidates.rs | 682 ++++++++++++++++++++++- crates/lucisv_server/src/completion.rs | 459 ++++++++++++++- crates/lucisv_server/tests/e2e.rs | 94 ++++ docs/features/completion-core/README.md | 33 ++ docs/features/fuzzy-completion/README.md | 535 ++++++++++++++++++ docs/topo.md | 6 +- 7 files changed, 1845 insertions(+), 38 deletions(-) create mode 100644 docs/features/fuzzy-completion/README.md diff --git a/TODO.md b/TODO.md index 62ef03c..dc6ade9 100644 --- a/TODO.md +++ b/TODO.md @@ -1514,3 +1514,77 @@ TODO.md §12). files, all resolved. One non-blocking finding (nearest-definition tie-break on a nested-subdirectory sibling) — see the feature README's round-2 QA log. + +## 13. Fuzzy completion wave (2026-08-30) — owner request + +Subsequence ("fuzzy") matching for identifier completion, VS Code +policy: prefix matching below 3 typed characters, fuzzy from 3 up +(`clkenq` reaches `clk_osc_en_q`). Sized by the lead's benchmark on +the real opentitan word list (139,800 words): char-bitmask prefilter ++ two-pointer scan = 0.07-0.32 ms/keystroke; naive scan 3.4 ms; +1-2-char queries stay prefix so the degenerate single-letter case +never runs fuzzy. Single lane. Files: +crates/lucisv_server/src/{candidates.rs, completion.rs}, +crates/lucisv_server/tests/e2e.rs, +docs/features/fuzzy-completion/README.md (new), amendment in +docs/features/completion-core/README.md, TODO.md §13. + +- [x] **Mask table in `Candidates`.** Per-word 32-bit character mask + for the words and units tables, built with the index and + maintained by every mutation path (build, update_words, absorb, + remove_file); query mask subset-check prunes before the + subsequence scan. +- [x] **Fuzzy tiers at ≥3 chars.** Words, index (project + declarations) and scope-visible tiers match by case-insensitive + subsequence when the typed word is 3+ chars; below 3, today's + prefix behavior byte-for-byte. Module tier unchanged + (substring, its own semantics). Dedup across tiers preserved. +- [x] **Ranking.** Prefix hits outrank fuzzy hits within a tier; + fuzzy hits scored (word-boundary bonus at `_`/case/digit + boundaries, contiguity, gap penalty), deterministic, stable + tie-break by name; top-K under the existing LIMIT. +- [x] **isIncomplete correctness.** The 2-char prefix response must + be marked incomplete or VS Code filters locally and the 3rd + keystroke never reaches the server (the prefix→fuzzy transition + is the trap); truncated fuzzy responses incomplete too. +- [x] **Pins.** clkenq→clk_osc_en_q end to end; boundary-scored + ranking; 1-2 char = prefix only; textEdit still replaces the + typed word; no fuzzy hit whose letters are out of order; e2e + over the wire incl. the 2→3 char transition. +- [x] **QA on opentitan** (read-only, --check/--stdout only, git + status after): fuzzy keystroke adds ≤0.5 ms warm vs today's + 2.6-3.2 ms popup; <3-char path unchanged; index build/absorb + not measurably slower from mask maintenance; clkenq finds + clk_osc_en_q in a real ast buffer. + **Dev note (2026-08-30): the ≤0.5 ms bar does not hold on the + widest three-letter queries.** Measured on the real checkout: + `clkenq` +0.05 ms, `clk` +0.52 ms, `prim_` +0.77 ms, `aes` + +0.80 ms; 1-2-char requests unchanged. Numbers, the reason + (three common letters leave 39 362 of 100 022 names past the + mask and half of them really match) and the two untaken levers + are in docs/features/fuzzy-completion/README.md, *Performance* + — for the lead to rule on. + **QA verdict (2026-08-30): SHIP.** Gates clean (fmt, clippy, + `cargo test --workspace` 2691/0/36 exact match, debug+release + builds, smoke.js). git status on opentitan confirmed unchanged + (only the three pre-existing owner edits) before and after every + session. `clkenq` confirmed live over the wire against the real + `clk_osc_en_q` in `hw/top_earlgrey/ip/ast/rtl/gfr_clk_mux2.sv` + (ast.sv itself doesn't declare it; grepped for the closest real + name as instructed), both from another buffer and from inside + that file's own buffer. Ten adversarial attack tests written + against the matcher (mixed case, `$`/digit/`_` queries, a + non-ASCII byte in a table entry, ranking determinism, absorb + overwriting a path, remove-then-readd) — all ten passed, no + corruption found; reverted after running (nothing to fix). + Server "answered in" timings (fairer than wall-clock; still pays + JSON marshalling the dev's isolated number does not): `aes` + 1.7-2.2 ms, `clkenq` 0.4-0.5 ms, 1-2-char queries 0.9-2.0 ms + (matches the unchanged-path claim in shape). **New finding**: + `ena` (a common real RTL fragment) measured 2.95-4.05 ms, + worse than `aes` — the *Performance* section's "aes is the + worst case" is not shown to be a proven upper bound, just the + case the dev tried. Informational, not blocking: same + architecture, same order of magnitude, still within the ~1.1 ms + absolute framing the lead already accepted. See the feature + README's QA log for the full latency table and repro. diff --git a/crates/lucisv_server/src/candidates.rs b/crates/lucisv_server/src/candidates.rs index 87dd618..277e72d 100644 --- a/crates/lucisv_server/src/candidates.rs +++ b/crates/lucisv_server/src/candidates.rs @@ -17,9 +17,17 @@ //! lexer detaches and a string is one `String` token, and neither is ever an //! `Ident`. //! -//! See `docs/features/completion-core/README.md`. +//! Both are answered two ways: by *prefix*, with the binary search +//! [`matching`] does into the sorted table, and — since 2026-08-30 — by +//! *subsequence*, so `clkenq` reaches `clk_osc_en_q`. The fuzzy half is a scan, +//! made affordable by the character mask each entry carries beside it +//! ([`char_mask`]); which of the two a request uses is `completion.rs`'s +//! decision, not this file's. +//! +//! See `docs/features/completion-core/README.md` and +//! `docs/features/fuzzy-completion/README.md`. -use std::cmp::Ordering; +use std::cmp::{Ordering, Reverse}; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -53,6 +61,12 @@ pub struct Macro { #[derive(Debug, Default)] pub struct Candidates { units: Vec, + /// [`char_mask`] of each entry of `units`, in the same order — so a fuzzy + /// scan may reject a name without looking at its bytes. + /// + /// Written in exactly one place ([`Candidates::take_index_tables`]), from + /// exactly the table it belongs to, so the two cannot drift apart. + unit_masks: Vec, /// Every module name the index declares, in the order /// `WorkspaceIndex::workspace_symbols` puts them in — which is **`str` /// order, exactly**, so [`Candidates::has_module`] may binary-search it. @@ -65,6 +79,13 @@ pub struct Candidates { modules: Vec, macros: Vec, words: Vec, + /// [`char_mask`] of each entry of `words`, in the same order — the + /// prefilter that makes a fuzzy scan of a 139 800-word table cost 0.07 ms + /// instead of 3.1 ms. + /// + /// Written in exactly one place ([`Candidates::remask_words`]), from + /// exactly the table it belongs to, so the two cannot drift apart. + word_masks: Vec, /// How many in-scope files contain each word. What makes it possible to /// take one file's words back without re-lexing every other file /// ([`Candidates::update_file`]): a word is dropped from `words` exactly @@ -93,9 +114,8 @@ impl Candidates { sources: &[(PathBuf, String)], mut known: HashMap>, ) -> Candidates { - let (units, modules) = index_tables(index); - let mut out = - Candidates { units, modules, macros: macros_of(index), ..Candidates::default() }; + let mut out = Candidates::default(); + out.take_index_tables(index); for (path, text) in sources { let words = match known.remove(path) { Some(words) => words, @@ -110,9 +130,39 @@ impl Candidates { } out.words = out.word_files.keys().cloned().collect(); sort_by_name(&mut out.words, |w| w.as_str()); + out.remask_words(); out } + /// Re-derive the index-fed tables — the unit names, their masks, the + /// module names and the macro names — from the index, which is the only + /// thing any of them reads. + /// + /// The one place all four are written, so the four mutation paths below + /// cannot each remember three of them: a path that forgets this call has + /// no tables at all rather than a mask that quietly disagrees with the + /// names beside it. + fn take_index_tables(&mut self, index: &WorkspaceIndex) { + let (units, modules) = index_tables(index); + self.unit_masks = units.iter().map(|unit| char_mask(&unit.name)).collect(); + self.units = units; + self.modules = modules; + self.macros = macros_of(index); + } + + /// Re-derive the word masks from the word table. + /// + /// The one place `word_masks` is written, and it reads nothing but + /// `words`, so the two are one pass apart. The pass is the cheap half of + /// what [`Candidates::merge_words`] beside it already does — a mask is + /// seventeen byte-ORs on this corpus's average word, against the hash + /// lookup that loop already pays per word — and it is called only when + /// the table actually moved. + fn remask_words(&mut self) { + self.word_masks.clear(); + self.word_masks.extend(self.words.iter().map(|word| char_mask(word))); + } + /// Replace one file's contribution — the incremental form of /// [`Candidates::build`], for a rescan that only one file triggered /// (`docs/features/incremental-index/README.md`). @@ -129,8 +179,7 @@ impl Candidates { /// [`Candidates::update_file`] for a file whose words the caller already /// has — an open buffer's, read off the tokens it was analyzed from. pub fn update_words(&mut self, index: &WorkspaceIndex, path: &Path, words: Vec) { - (self.units, self.modules) = index_tables(index); - self.macros = macros_of(index); + self.take_index_tables(index); self.set_words(path, words); } @@ -154,14 +203,12 @@ impl Candidates { self.count_words(&path, words, &mut touched); } self.merge_words(touched); - (self.units, self.modules) = index_tables(index); - self.macros = macros_of(index); + self.take_index_tables(index); } /// Drop one file's contribution entirely. pub fn remove_file(&mut self, index: &WorkspaceIndex, path: &Path) { - (self.units, self.modules) = index_tables(index); - self.macros = macros_of(index); + self.take_index_tables(index); self.set_words(path, Vec::new()); } @@ -244,6 +291,7 @@ impl Candidates { } out.extend(added); self.words = out; + self.remask_words(); } /// Index names starting with `prefix`, case-insensitively. @@ -289,6 +337,315 @@ impl Candidates { pub fn words(&self, prefix: &str) -> &[String] { matching(&self.words, prefix, |w| w.as_str()) } + + /// The best `cap` index names holding `query`'s characters in order. + /// + /// The fuzzy sibling of [`Candidates::units`], and a scan rather than a + /// binary search — a subsequence match has no contiguous run in a sorted + /// table to search for. The mask rejects most of the table with one `&`. + /// + /// A full return means the table held more; the caller owes the response + /// an `isIncomplete` for the ones it did not carry. + pub fn units_fuzzy(&self, query: &Query, cap: usize) -> Vec<(&Candidate, Score)> { + let mut hits: Vec<(&Candidate, Score)> = Vec::new(); + for (unit, &mask) in self.units.iter().zip(&self.unit_masks) { + if !query.passes(mask) { + continue; + } + if let Some(score) = query.score(&unit.name) { + hits.push((unit, score)); + } + } + keep_best(&mut hits, cap, |unit| unit.name.as_str()); + hits + } + + /// The best `cap` project words holding `query`'s characters in order. + /// + /// The fuzzy sibling of [`Candidates::words`], and the one lookup here + /// whose cost is worth stating: an unfiltered scan of opentitan's hundred + /// thousand words is milliseconds, which no keystroke can afford, and the + /// mask takes `clkenq` to **0.05 ms** — 422 of the 100 022 names survive + /// it and 70 of those match. A *one*-character query is the degenerate + /// case, where the mask is one bit wide and rejects nothing, which is why + /// `completion.rs` does not ask one — see its `FUZZY_MIN`. The worst query + /// that does get asked is three common letters (`aes`, 1.9 ms): the mask + /// leaves 39 362 names and half of them really do match. + /// + /// A full return means the table held more; the caller owes the response + /// an `isIncomplete` for the ones it did not carry. + pub fn words_fuzzy(&self, query: &Query, cap: usize) -> Vec<(&str, Score)> { + self.words_scan(query, cap).0 + } + + /// [`Candidates::words_fuzzy`], and how many entries the mask let through. + /// + /// The survivor count is here so a test can assert the prefilter really + /// prunes: without it, a refactor that dropped the `&` would leave every + /// answer correct and only the keystroke slower, which no test would + /// notice. + fn words_scan(&self, query: &Query, cap: usize) -> (Vec<(&str, Score)>, usize) { + let mut survivors = 0; + let mut hits: Vec<(&str, Score)> = Vec::new(); + for (word, &mask) in self.words.iter().zip(&self.word_masks) { + if !query.passes(mask) { + continue; + } + survivors += 1; + if let Some(score) = query.score(word) { + hits.push((word.as_str(), score)); + } + } + keep_best(&mut hits, cap, |word| word); + (hits, survivors) + } +} + +/// Keep the best `cap` hits, in order, and throw the rest away. +/// +/// Bounded rather than sorted whole, because the two are not the same price at +/// all on a wide query: `aes` is a subsequence of 20 822 of opentitan's +/// hundred thousand words, and sorting all of them to show five hundred was +/// **0.8 ms of the 2.6 ms** such a scan cost. `select_nth_unstable_by` is +/// linear and only what survives it is sorted. +/// +/// "Best" is [`rank_cmp`]: prefix matches, then most points, then by name — a +/// total order on distinct names, which is what makes the truncation +/// deterministic rather than "whatever the partition left there". +fn keep_best(hits: &mut Vec<(T, Score)>, cap: usize, name: impl for<'b> Fn(&'b T) -> &'b str) { + let cmp = |a: &(T, Score), b: &(T, Score)| rank_cmp((name(&a.0), a.1), (name(&b.0), b.1)); + if hits.len() > cap { + hits.select_nth_unstable_by(cap, &cmp); + hits.truncate(cap); + } + hits.sort_by(&cmp); +} + +/// A fuzzy query, folded and masked once for a whole scan. +/// +/// Owning the prepared form is the whole point: the fold and the mask are +/// per-*query* work, and doing them per-candidate is most of what makes a +/// naive subsequence scan too slow to put on a keystroke. +#[derive(Debug, Clone)] +pub struct Query { + /// The typed characters, ASCII-folded. + lower: Vec, + /// [`char_mask`] of the query — the left-hand side of the prefilter. + mask: u32, +} + +impl Query { + /// Prepare `text` for matching. + /// + /// This makes no judgment about the query's length: whether a request is + /// answered by prefix or by subsequence is `completion.rs`'s policy + /// (`FUZZY_MIN`), stated in one place there rather than half here. + pub fn new(text: &str) -> Query { + Query { lower: text.bytes().map(fold).collect(), mask: char_mask(text) } + } + + /// Whether a name with this character mask could hold the query at all. + /// + /// One `&`: a subsequence of a name uses only characters the name has, so + /// a query whose mask is not a subset of the name's cannot match. The + /// converse is not claimed — a name that passes still has to be scanned — + /// which is exactly why this is a *pre*filter. + fn passes(&self, mask: u32) -> bool { + self.mask & mask == self.mask + } + + /// Score `name` as well as this scorer knows how, or `None` when the + /// query's characters do not all appear in it in order. + /// + /// Three linear passes, the shape fzf's own first algorithm uses. The + /// forward walk says *whether* the name matches at all and where a match + /// has to end; the backward walk slides the start as late as it can + /// without losing the match; the third pass scores the tightened window. + /// + /// The tightening is not a nicety, it is the difference between a useful + /// ranking and a misleading one: the forward walk alone gives `clk` the + /// `c` of `osc_clk_en` and then reaches four characters for the `l`, + /// scoring the name below `xclkx`, when the run it should have found + /// starts at an underscore three characters on. It costs about a tenth of + /// a table scan, measured, which is worth paying for an order the reader + /// can trust. + /// + /// Still not the best of every alignment — that is a dynamic program, and + /// the client re-ranks this list anyway (see the feature README) — but + /// deterministic, linear, and right about the two things the ranking has + /// to be right about, which are word boundaries and contiguous runs. + pub fn score(&self, name: &str) -> Option { + let bytes = name.as_bytes(); + // An empty query is every name's prefix, and the walks below have no + // character to look for. + if self.lower.is_empty() { + return Some(Score { fuzzy: false, points: Reverse(0) }); + } + let end = self.walk_forward(bytes)?; + self.score_from(bytes, self.walk_backward(bytes, end)) + } + + /// Where the leftmost match of the query ends, or `None` when the name + /// does not hold the query in order at all. + fn walk_forward(&self, name: &[u8]) -> Option { + let mut from = 0usize; + let mut last = 0usize; + for &wanted in &self.lower { + last = from + name[from..].iter().position(|byte| fold(*byte) == wanted)?; + from = last + 1; + } + Some(last) + } + + /// The latest position the match can start at, given it ends at `end`. + /// + /// The same walk backwards. It cannot fail — the forward walk has already + /// proved every character is there — but it is written so that it answers + /// rather than indexes past anything if it ever did. + fn walk_backward(&self, name: &[u8], end: usize) -> usize { + let mut upto = end + 1; + let mut start = end; + for &wanted in self.lower.iter().rev() { + let Some(at) = name[..upto].iter().rposition(|byte| fold(*byte) == wanted) else { + return start; + }; + start = at; + upto = at; + } + start + } + + /// What the greedy match beginning at or after `start` is worth, or + /// `None` when there is none. + fn score_from(&self, name: &[u8], start: usize) -> Option { + let mut points: i32 = 0; + let mut prefix = true; + let mut previous: Option = None; + let mut from = start; + for (typed, &wanted) in self.lower.iter().enumerate() { + let at = from + name[from..].iter().position(|byte| fold(*byte) == wanted)?; + points += match previous { + // Clamped before the cast so no length can overflow it; the + // floor makes everything past twelve the same answer anyway. + None => (LEAD * at.min(64) as i32).max(LEAD_FLOOR), + Some(prev) if at == prev + 1 => CONTIGUOUS, + Some(prev) => GAP * (at - prev - 1).min(1024) as i32, + }; + if at_boundary(name, at) { + points += BOUNDARY; + } + prefix &= at == typed; + previous = Some(at); + from = at + 1; + } + Some(Score { fuzzy: !prefix, points: Reverse(points) }) + } +} + +/// One byte, case-folded — what every comparison in a fuzzy match is made on. +/// +/// `| 0x20` rather than `to_ascii_lowercase`, because this runs once per byte +/// of every name a table scan reaches and the library version is a branch. +/// It is exact over the alphabet an identifier is written in: `A`–`Z` fold +/// onto `a`–`z`, and every other identifier byte already has that bit set +/// (`0`–`9`, `a`–`z`, `$`) or is the only one that does not (`_`, which folds +/// to `0x7f` — a byte no identifier holds, and both sides of every comparison +/// fold the same way, so it can only ever equal another `_`). A non-ASCII byte +/// stays ≥ `0x80` and so can never equal a folded query byte, which is ASCII +/// by construction — `completion.rs`'s `is_ident_char` sees to that. +fn fold(byte: u8) -> u8 { + byte | 0x20 +} + +/// How well a name matched a fuzzy query. Ordered **best first**, so sorting +/// a list of scores *ascending* puts the best match at the front. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +pub struct Score { + /// `false` for a prefix match, `true` for every other subsequence — the + /// first key, so a prefix match outranks every fuzzy one whatever the + /// points say. + /// + /// A rule rather than a coincidence. The points below very nearly give it + /// for free (every non-prefix match pays [`LEAD`] at least once, and no + /// match can beat an unbroken run from the start), but "very nearly" is + /// not something a ranking should rest on: a name whose *case* changes + /// mid-word can earn a [`BOUNDARY`] a prefix match of the same query + /// cannot, and `x_aB` would then outrank `abc` for `ab`. + fuzzy: bool, + /// The points [`BOUNDARY`], [`CONTIGUOUS`], [`GAP`] and [`LEAD`] added up + /// to, negated so more of them sorts earlier. + points: Reverse, +} + +/// A query character that lands at the start of a part of the name. +const BOUNDARY: i32 = 6; +/// A query character that directly follows the one before it. +const CONTIGUOUS: i32 = 8; +/// Per character skipped between two matched ones. +/// +/// Worth more than a boundary is: `clk` must reach `clk_osc_en_q` ahead of +/// `c_l_k_scatter`, where every letter is at a boundary and none is +/// contiguous — so `CONTIGUOUS + |GAP|` has to beat `BOUNDARY`, and it does, +/// nearly twice over. +const GAP: i32 = -3; +/// Per character skipped before the first matched one. +const LEAD: i32 = -1; +/// …to a floor: a name is not endlessly worse for being long, and without one +/// a late match in a long name would sort below matches that are genuinely +/// worse. +const LEAD_FLOOR: i32 = -12; + +/// The order a completion list offers fuzzy hits in: prefix matches first, +/// then most points, then by name. +/// +/// The name is a real tie-break, not decoration: [`Score`] ties constantly +/// (every prefix match of the same query scores the same), and without it the +/// answer would depend on the order the table happened to be in. +pub(crate) fn rank_cmp(a: (&str, Score), b: (&str, Score)) -> Ordering { + a.1.cmp(&b.1).then_with(|| word_cmp(a.0, b.0)) +} + +/// Whether the byte of `name` at `at` starts a part of it. +/// +/// The start of the name, the byte after a `_` or a `$`, the first digit of a +/// run and the first letter after one, and the capital that opens a +/// `camelCase` part. What "a word boundary" means for an identifier, and the +/// only thing [`Query::score`] treats as more than a letter landing somewhere. +fn at_boundary(name: &[u8], at: usize) -> bool { + if at == 0 { + return true; + } + let (before, here) = (name[at - 1], name[at]); + !before.is_ascii_alphanumeric() + || before.is_ascii_digit() != here.is_ascii_digit() + || (before.is_ascii_lowercase() && here.is_ascii_uppercase()) +} + +/// The bit a character claims in a [`char_mask`]. +/// +/// Twenty-six for the case-folded letters, one for "a digit" (which digit does +/// not narrow anything worth the bits), one each for `_` and `$` — the other +/// two characters a Verilog identifier holds — and one for everything else, so +/// a byte no bucket names is never silently lost. +fn char_bit(byte: u8) -> u32 { + match byte { + b'a'..=b'z' => u32::from(byte - b'a'), + b'A'..=b'Z' => u32::from(byte - b'A'), + b'0'..=b'9' => 26, + b'_' => 27, + b'$' => 28, + _ => 29, + } +} + +/// Which characters `text` holds, one bit each. +/// +/// The prefilter a fuzzy scan runs before it looks at a name's bytes at all. +/// Measured over opentitan's 139 800-word table: `clkenq` leaves 455 names for +/// the scan and rejects the other 139 345, taking the query from 3.1 ms to +/// 0.07 ms. See `docs/features/fuzzy-completion/README.md`. +fn char_mask(text: &str) -> u32 { + text.bytes().fold(0, |mask, byte| mask | (1 << char_bit(byte))) } /// Every name the index carries, and the module names among them, from one @@ -834,4 +1191,307 @@ mod tests { c.absorb(&index, batch); assert_eq!(c.words(""), before.as_slice(), "re-declaring the same words is a no-op"); } + + // ------------------------------------------------------------------ + // fuzzy matching (2026-08-30) — `docs/features/fuzzy-completion/README.md` + // ------------------------------------------------------------------ + + /// The masks the two tables *should* carry, derived from the tables + /// themselves rather than from anything that maintains them. + fn assert_masks_in_step(candidates: &Candidates, after: &str) { + let units: Vec = candidates.units.iter().map(|unit| char_mask(&unit.name)).collect(); + let words: Vec = candidates.words.iter().map(|word| char_mask(word)).collect(); + assert_eq!(candidates.unit_masks, units, "unit masks after {after}"); + assert_eq!(candidates.word_masks, words, "word masks after {after}"); + } + + /// Every mutation path, in one session, with the masks re-derived from + /// scratch after each one. + /// + /// The failure this exists to catch is silent: a path that updates a table + /// and forgets its masks answers *nearly* right — the prefilter rejects a + /// name that should have matched, or lets through one that cannot — and + /// nothing else in the suite would notice. So it is checked after each of + /// the four, not once at the end. + #[test] + fn the_masks_stay_in_step_with_the_tables_through_every_mutation_path() { + let raw = [ + ("/rtl/a.sv", "package pkg_a;\n localparam int WIDTH_A = 1;\nendpackage\n"), + ("/rtl/b.sv", "module mod_b;\n logic clk_osc_en_q;\nendmodule\n"), + ]; + let srcs = sources(&raw); + let mut index = WorkspaceIndex::build(srcs.iter().map(|(p, t)| (p.clone(), t.as_str()))); + let mut candidates = Candidates::build(&index, &srcs, HashMap::new()); + assert_masks_in_step(&candidates, "build"); + + // `update_file`, which is `update_words` over a text it lexes itself. + let rewritten = "module mod_b;\n logic other_name_2;\nendmodule\n"; + index.update_file(PathBuf::from("/rtl/b.sv"), rewritten); + candidates.update_file(&index, Path::new("/rtl/b.sv"), rewritten); + assert_masks_in_step(&candidates, "update_file"); + + // `update_words`, with the words handed in. + let words = vec!["handed_in".to_string(), "mod_b".to_string()]; + candidates.update_words(&index, Path::new("/rtl/b.sv"), words); + assert_masks_in_step(&candidates, "update_words"); + assert_eq!(candidates.words("handed").len(), 1, "premise: the words landed"); + + // `absorb`, a batch of two files at once. + let batch = vec![ + (PathBuf::from("/rtl/c.sv"), vec!["absorbed_one".to_string()]), + (PathBuf::from("/rtl/d.sv"), vec!["absorbed_two".to_string(), "ZED".to_string()]), + ]; + candidates.absorb(&index, batch); + assert_masks_in_step(&candidates, "absorb"); + assert_eq!(candidates.words("absorbed").len(), 2, "premise: the batch landed"); + + // `remove_file`, which takes one file's words back. + candidates.remove_file(&index, Path::new("/rtl/d.sv")); + assert_masks_in_step(&candidates, "remove_file"); + assert!(candidates.words("absorbed_two").is_empty(), "premise: the file left"); + + // …and the same again through the index, so the unit masks move too. + index.remove_file(Path::new("/rtl/a.sv")); + candidates.remove_file(&index, Path::new("/rtl/a.sv")); + assert_masks_in_step(&candidates, "remove_file, index and all"); + assert!(candidates.units("pkg_a").is_empty(), "premise: the package left"); + } + + /// A deterministic table big enough for the prefilter to have something to + /// do, built out of the parts real RTL names are built out of. + /// + /// No lexing: [`Candidates::absorb`] takes words directly, so twenty + /// thousand of them cost a hash insert each rather than a parse. + fn many_words(count: usize) -> Vec { + const PARTS: [&str; 20] = [ + "clk", "osc", "en", "q", "data", "valid", "reg", "top", "aes", "prim", "sel", "addr", + "wr", "rd", "cfg", "mux", "fifo", "cnt", "rst", "n", + ]; + // A plain linear congruential generator: the table has to be the same + // one on every run, or the assertions below are not assertions. + let mut seed: u64 = 0x5eed_1234_5678_9abc; + let mut next = move || { + seed = seed + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + (seed >> 33) as usize + }; + let mut out: HashSet = HashSet::new(); + while out.len() < count { + let parts = 2 + next() % 4; + let mut name = String::new(); + for _ in 0..parts { + if !name.is_empty() { + name.push('_'); + } + name.push_str(PARTS[next() % PARTS.len()]); + } + if next() % 3 == 0 { + name.push_str(&(next() % 64).to_string()); + } + out.insert(name); + } + out.into_iter().collect() + } + + /// A `Candidates` holding exactly `words`, and nothing else. + fn worded(words: Vec) -> Candidates { + let index = WorkspaceIndex::default(); + let mut candidates = Candidates::default(); + candidates.absorb(&index, vec![(PathBuf::from("/rtl/generated.sv"), words)]); + candidates + } + + /// The scan's answer is the brute-force answer. Not a spot check: every + /// word in a twenty-thousand-word table, against every query, both ways. + /// + /// This is the whole correctness claim of the prefilter — that a mask is + /// only ever allowed to reject a name that could not have matched — and it + /// is the one that would fail *silently* if a bucket were wrong. + #[test] + fn a_fuzzy_scan_finds_exactly_what_brute_force_subsequence_finds() { + let candidates = worded(many_words(20_000)); + let table: Vec<&str> = candidates.words("").iter().map(String::as_str).collect(); + for text in ["clkenq", "clk", "aesdata", "zzz", "q", "cfgmux9", "en_", "CLKENQ", "rstn"] { + let query = Query::new(text); + let mut expected: Vec<&str> = + table.iter().copied().filter(|word| brute_force(text, word)).collect(); + expected.sort_by(|a, b| word_cmp(a, b)); + let mut found: Vec<&str> = candidates + .words_fuzzy(&query, usize::MAX) + .into_iter() + .map(|(name, _)| name) + .collect(); + found.sort_by(|a, b| word_cmp(a, b)); + assert_eq!(found, expected, "query {text:?}"); + } + } + + /// Subsequence, spelled out the obvious way, so the test does not check + /// the implementation against itself. + fn brute_force(query: &str, word: &str) -> bool { + let mut typed = query.bytes().map(|b| b.to_ascii_lowercase()).peekable(); + for byte in word.bytes().map(|b| b.to_ascii_lowercase()) { + if typed.peek() == Some(&byte) { + typed.next(); + } + } + typed.peek().is_none() + } + + /// The prefilter has to actually prune, or the keystroke budget is a + /// fiction. Asserted on the survivor count rather than on a clock, so it + /// is a real assertion on a loaded machine. + #[test] + fn the_character_mask_prunes_the_table_before_the_subsequence_scan() { + let candidates = worded(many_words(20_000)); + let held = candidates.words("").len(); + let (hits, survivors) = candidates.words_scan(&Query::new("clkenq"), usize::MAX); + assert!( + survivors * 20 < held, + "the mask let {survivors} of {held} through — under 5% is the whole budget" + ); + assert!(hits.len() <= survivors, "a hit has to survive the mask first"); + assert!(!hits.is_empty(), "premise: this query does match something"); + // A query the table cannot answer costs the mask and nothing else. + let (none, survivors) = candidates.words_scan(&Query::new("xyzzyw"), usize::MAX); + assert!(none.is_empty()); + assert_eq!(survivors, 0, "no name holds an `x`, `y` and `z`"); + } + + /// The cap is a *best*-of, not a first-of: what it keeps is what a whole + /// sort would have put in front, in the same order. The linear selection + /// underneath it partitions rather than sorts, so this is the assertion + /// that it partitions on the right key. + #[test] + fn the_cap_keeps_the_best_hits_and_not_merely_the_first_ones() { + let candidates = worded(many_words(20_000)); + let query = Query::new("clken"); + let whole = candidates.words_fuzzy(&query, usize::MAX); + assert!(whole.len() > 40, "premise: a wide enough query, {} hits", whole.len()); + for cap in [1, 7, 40] { + let capped = candidates.words_fuzzy(&query, cap); + assert_eq!(capped.len(), cap, "cap {cap}"); + assert_eq!(capped, whole[..cap], "cap {cap}"); + } + assert_eq!(candidates.words_fuzzy(&query, whole.len() + 10), whole, "a cap past the end"); + } + + #[test] + fn a_fuzzy_match_ignores_case_in_both_directions() { + let candidates = worded(vec![ + "clk_osc_en_q".to_string(), + "CLK_OSC_EN_Q".to_string(), + "Clk_Osc_En_Q".to_string(), + ]); + for text in ["clkenq", "CLKENQ", "ClKeNq"] { + let found: Vec<&str> = candidates + .words_fuzzy(&Query::new(text), usize::MAX) + .into_iter() + .map(|(n, _)| n) + .collect(); + assert_eq!(found.len(), 3, "query {text:?} found {found:?}"); + } + } + + #[test] + fn letters_out_of_order_never_match() { + let candidates = worded(vec!["clk_osc_en_q".to_string(), "clkenq".to_string()]); + assert_eq!(candidates.words_fuzzy(&Query::new("clkenq"), usize::MAX).len(), 2, "premise"); + for text in ["qneklc", "kclenq", "clkqne", "clkenqq"] { + let found: Vec<&str> = candidates + .words_fuzzy(&Query::new(text), usize::MAX) + .into_iter() + .map(|(n, _)| n) + .collect(); + assert!(found.is_empty(), "query {text:?} matched {found:?}"); + } + } + + /// The ranking rule the completion list rests on, at the scorer. + #[test] + fn a_prefix_match_outranks_every_fuzzy_one_and_boundaries_beat_scatter() { + let query = Query::new("clk"); + let score = |name: &str| query.score(name).unwrap_or_else(|| panic!("{name} matches")); + + assert!(!score("clk_osc_en_q").fuzzy, "a prefix is a prefix"); + assert!(score("c_l_k_scatter").fuzzy); + assert!( + score("clk_osc_en_q") < score("c_l_k_scatter"), + "best first: a prefix outranks a scatter, {:?} vs {:?}", + score("clk_osc_en_q"), + score("c_l_k_scatter"), + ); + // …and it does so on the points too, not only on the prefix flag: the + // contiguity of `clk` is worth more than three boundary bonuses less + // two gaps. That is what `CONTIGUOUS + |GAP| > BOUNDARY` buys. + assert!( + score("clk_osc_en_q").points.0 > score("c_l_k_scatter").points.0, + "{:?} vs {:?}", + score("clk_osc_en_q"), + score("c_l_k_scatter") + ); + // A boundary still beats no boundary between two fuzzy matches. + assert!( + score("osc_clk_en") < score("xclkx"), + "a run that starts after an underscore is the better guess" + ); + // And an earlier match beats a later one, all else equal. + assert!(score("clk_a") < score("a_clk"), "the lead penalty"); + } + + /// Index names go fuzzy with the words; module names and macro names do + /// not (see the feature README's *What did not go fuzzy*). + #[test] + fn index_names_match_fuzzily_and_keep_their_kind() { + let candidates = built(&[( + "/rtl/p.sv", + "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n", + )]); + let found: Vec<&str> = candidates + .units_fuzzy(&Query::new("clkenq"), usize::MAX) + .into_iter() + .map(|(unit, _)| unit.name.as_str()) + .collect(); + assert_eq!(found, ["CLK_OSC_EN_Q"], "the package name has no `q` in it"); + let hits = candidates.units_fuzzy(&Query::new("clkosc"), usize::MAX); + assert_eq!(hits.len(), 2, "{hits:?}"); + assert_eq!(hits[0].0.name, "clkosc_pkg", "the prefix match leads"); + assert_eq!(hits[0].0.kind, SymbolKind::Package, "and carries its kind"); + } + + /// An empty query is every name's prefix — stated because + /// [`Query::score`]'s loop simply does not run, which is easy to read as + /// an accident. + #[test] + fn an_empty_query_is_a_prefix_of_everything() { + let query = Query::new(""); + let score = query.score("anything").expect("matches"); + assert!(!score.fuzzy); + assert_eq!(score.points, Reverse(0)); + } + + /// The mask's buckets, spelled out — the one piece of arithmetic here that + /// is not obviously right by reading it. + #[test] + fn the_character_mask_buckets_every_byte_a_name_can_hold() { + assert_eq!(char_mask("a"), 1, "the first letter is the first bit"); + assert_eq!(char_mask("A"), 1, "case folds"); + assert_eq!(char_mask("ab"), 0b11); + assert_eq!(char_mask("7"), 1 << 26, "every digit shares one bit"); + assert_eq!(char_mask("0"), char_mask("9")); + assert_eq!(char_mask("_"), 1 << 27); + assert_eq!(char_mask("$"), 1 << 28); + assert_eq!(char_mask("é"), 1 << 29, "a byte no bucket names still sets one"); + assert_eq!(char_mask(""), 0, "and an empty query is a subset of everything"); + // The invariant the prefilter rests on, checked rather than reasoned: + // every character of a name is in the name's own mask. + for name in ["clk_osc_en_q", "$clog2", "WIDTH8", "aésign"] { + let whole = char_mask(name); + for ch in name.chars() { + let one = char_mask(&ch.to_string()); + assert_eq!(whole & one, one, "{ch:?} of {name:?}"); + } + } + } } diff --git a/crates/lucisv_server/src/completion.rs b/crates/lucisv_server/src/completion.rs index 67f5a88..f72f912 100644 --- a/crates/lucisv_server/src/completion.rs +++ b/crates/lucisv_server/src/completion.rs @@ -49,7 +49,7 @@ use vlog_parser::{TextRange, KEYWORDS}; use vlog_refactor::{InstantiationPlan, Layout, Site}; use vlog_semantic::{Semantics, Symbol, SymbolKind, WorkspaceIndex}; -use crate::candidates::starts_with_ignore_case; +use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score}; use crate::pairs; use crate::state::{first_token_from, Document, Workspace}; use crate::symbols::kind_label; @@ -75,6 +75,25 @@ const LIMIT: usize = 512; /// 2026-08-30 each item cost one file read and one header parse. const MODULE_LIMIT: usize = 64; +/// How many characters must be typed before a name may match by +/// *subsequence* rather than by prefix. +/// +/// **VS Code's own rule**, which is the whole policy of this round: below +/// three characters its widget filters what it holds by prefix, and so does +/// the server; from three up both match by subsequence, so `clkenq` reaches +/// `clk_osc_en_q`. Matching the client is the point — a server that went +/// fuzzy at one character would answer a question the widget then filtered the +/// answer to, and one that never went fuzzy is what this round is fixing. +/// +/// The floor is not only manners. A one-character fuzzy query matches most of +/// a workspace, which is a list nobody can read, and it is the one query the +/// character-mask prefilter cannot help with at all — one bit wide, it rejects +/// nothing, so the whole table is scanned. Measured at 2.7 ms over the real +/// opentitan word list against the 0.05 ms `clkenq` costs. +/// +/// See `docs/features/fuzzy-completion/README.md`. +const FUZZY_MIN: usize = 3; + /// How far past a module's name [`module_header`] reads looking for the end of /// its header, smallest first. /// @@ -214,13 +233,33 @@ pub fn completions( let at_item = word.at_line_start && at_module_item(doc, &chain, word.start); let at_statement = starts_a_line && at_statement(doc, &chain, word.start); + // Prefix below [`FUZZY_MIN`], subsequence from it up. One `Query` for the + // whole request: it folds the typed characters and computes their mask + // once, and every tier that scans a table reads the same prepared form. + let fuzzy = (word.text.len() >= FUZZY_MIN).then(|| Query::new(&word.text)); + let mut items = Items::new(doc, word.range(offset)); module_tier(&mut items, ws, doc, &word, at_item); - scope_tier(&mut items, doc, &word); - index_tier(&mut items, ws, &word); + scope_tier(&mut items, doc, &word, fuzzy.as_ref()); + index_tier(&mut items, ws, &word, fuzzy.as_ref()); template_tier(&mut items, ws, doc, &word, snippets, at_item, at_statement); keyword_tier(&mut items, &word); - word_tier(&mut items, ws, doc, &word); + word_tier(&mut items, ws, doc, &word, fuzzy.as_ref()); + // **The `isIncomplete` trap.** VS Code asks the server again on the next + // keystroke *only* when the last answer said it was incomplete; otherwise + // it filters the list it already holds. A complete two-character prefix + // answer would therefore be filtered client-side for the rest of the word, + // and the third keystroke — the one that turns fuzzy on — would never + // reach here at all. So every answer below the floor says it is + // incomplete, whatever the cap did. + // + // Above the floor the ordinary rule stands, and is sound because the hit + // set only ever *shrinks* as characters are appended: if a name holds + // `clke` in order it holds `clk` in order, so a complete answer at three + // characters really does contain every answer to four. + if fuzzy.is_none() { + items.incomplete = true; + } items.finish() } @@ -495,14 +534,30 @@ fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option { } /// Tier 1: everything the scope chain at the cursor binds. -fn scope_tier(items: &mut Items, doc: &Document, word: &Word) { - for symbol in visible_symbols(&doc.semantics, word.start) { +/// +/// The one fuzzy tier with no mask table behind it, and deliberately so: what +/// a scope chain binds is tens of names computed per request, where a table of +/// masks would cost more to build than the scan it saved. +fn scope_tier(items: &mut Items, doc: &Document, word: &Word, fuzzy: Option<&Query>) { + let visible = visible_symbols(&doc.semantics, word.start); + let matched: Vec<&Symbol> = match fuzzy { + None => visible + .into_iter() + .filter(|symbol| starts_with_ignore_case(&symbol.name, &word.text)) + .collect(), + Some(query) => { + let mut hits: Vec<(&Symbol, Score)> = visible + .into_iter() + .filter_map(|symbol| Some((symbol, query.score(&symbol.name)?))) + .collect(); + hits.sort_by(|a, b| rank_cmp((&a.0.name, a.1), (&b.0.name, b.1))); + hits.into_iter().map(|(symbol, _)| symbol).collect() + } + }; + for symbol in matched { if items.full() { break; } - if !starts_with_ignore_case(&symbol.name, &word.text) { - continue; - } items.simple( &symbol.name, completion_kind(symbol.kind), @@ -513,8 +568,24 @@ fn scope_tier(items: &mut Items, doc: &Document, word: &Word) { } /// Tier 2: what the workspace index declares, `` `define`` names included. -fn index_tier(items: &mut Items, ws: &Workspace, word: &Word) { - for candidate in ws.candidates().units(&word.text) { +/// +/// The index names match fuzzily from [`FUZZY_MIN`] up; the macro names do +/// not. That is a deliberate split, not an oversight — see the feature +/// README's *What did not go fuzzy*. +fn index_tier(items: &mut Items, ws: &Workspace, word: &Word, fuzzy: Option<&Query>) { + let matched: Vec<&Candidate> = match fuzzy { + None => ws.candidates().units(&word.text).iter().collect(), + Some(query) => { + let hits = ws.candidates().units_fuzzy(query, LIMIT); + // A full return means the scan kept its best LIMIT and dropped the + // rest, so the response is a best-of and has to say so. `full()` + // below would only notice if every one of them reached the list, + // and a name a higher tier already claimed does not. + items.incomplete |= hits.len() >= LIMIT; + hits.into_iter().map(|(unit, _)| unit).collect() + } + }; + for candidate in matched { if items.full() { break; } @@ -609,24 +680,43 @@ fn keyword_tier(items: &mut Items, word: &Word) { /// The prebuilt table is as of the last index rebuild, which is `didSave`; the /// buffer being typed in is harvested afresh from its own token stream, so an /// unsaved edit contributes to its own file's completions immediately. -fn word_tier(items: &mut Items, ws: &Workspace, doc: &Document, word: &Word) { +fn word_tier( + items: &mut Items, + ws: &Workspace, + doc: &Document, + word: &Word, + fuzzy: Option<&Query>, +) { // Gathering and sorting the names is the one tier whose *setup* costs // something, so a response that is already full skips it outright. if items.full() { return; } - let mut names: Vec<&str> = - ws.candidates().words(&word.text).iter().map(String::as_str).collect(); - names.extend( - doc.tokens - .iter() - .filter(|t| matches!(t.kind, TokenKind::Ident | TokenKind::SystemIdent)) - .map(|t| t.text.as_str()) - .filter(|text| !text.starts_with('`') && !text.starts_with('\\')) - .filter(|text| starts_with_ignore_case(text, &word.text)), - ); - names.sort_unstable(); - names.dedup(); + let names: Vec<&str> = match fuzzy { + None => { + let mut names: Vec<&str> = + ws.candidates().words(&word.text).iter().map(String::as_str).collect(); + names + .extend(buffer_words(doc).filter(|text| starts_with_ignore_case(text, &word.text))); + names.sort_unstable(); + names.dedup(); + names + } + Some(query) => { + // The table's hits come back ranked; the buffer's own words are + // scored here and the two are ranked together, so a name the user + // typed a moment ago sits where its match deserves rather than + // after everything the table knows. + let mut hits = ws.candidates().words_fuzzy(query, LIMIT); + // A full return is a truncation; see `index_tier`. + items.incomplete |= hits.len() >= LIMIT; + hits.extend(buffer_words(doc).filter_map(|name| Some((name, query.score(name)?)))); + hits.sort_by(|a, b| rank_cmp(*a, *b)); + // A name in both lists is offered once: `Items` drops the second + // by label, so no dedup is needed here. + hits.into_iter().map(|(name, _)| name).collect() + } + }; for name in names { if items.full() { break; @@ -635,6 +725,21 @@ fn word_tier(items: &mut Items, ws: &Workspace, doc: &Document, word: &Word) { } } +/// Every identifier the buffer being typed in holds, as tier 5 counts one. +/// +/// The live half of the tier: the prebuilt table is as of the last index +/// rebuild, and this is the buffer's own token stream, recomputed on every +/// change. The filter is `candidates::is_word`'s, in the other direction — +/// `Ident` and `SystemIdent` only, and neither a macro usage nor an escaped +/// identifier. +fn buffer_words(doc: &Document) -> impl Iterator { + doc.tokens + .iter() + .filter(|token| matches!(token.kind, TokenKind::Ident | TokenKind::SystemIdent)) + .map(|token| token.text.as_str()) + .filter(|text| !text.starts_with('`') && !text.starts_with('\\')) +} + /// The response under construction: the items, the names already spoken for, /// and whether the cap cut anything off. struct Items { @@ -2391,15 +2496,319 @@ endmodule worst_empty = worst_empty.max(after_empty); } } + // …and the fuzzy path, which is a *scan* of the whole word table + // where the two above are a binary search into it. Six characters, + // the shape the round is named after. + let fuzzy = "module lucisv_probe;\n logic clk;\n assign x = clkenq\nendmodule\n"; + ws.set_document(uri.clone(), fuzzy.to_string()); + let offset = (fuzzy.find("= clkenq").expect("needle") + 8) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let mut worst_fuzzy = std::time::Duration::ZERO; + for round in 0..11 { + let started = std::time::Instant::now(); + let found = items(completions(&ws, &uri, position, true)); + let elapsed = started.elapsed(); + assert!(!found.is_empty(), "the buffer's own `clk` matches at least"); + if round > 0 { + worst_fuzzy = worst_fuzzy.max(elapsed); + } + } + eprintln!( "corpus: {} files, {} words, {} index names; index+tables built in {build:?}; \ - worst request {worst:?} typed / {worst_empty:?} empty", + worst request {worst:?} typed / {worst_empty:?} empty / {worst_fuzzy:?} fuzzy", ws.index().files().len(), ws.candidates().words("").len(), ws.candidates().units("").len(), ); assert!(worst < std::time::Duration::from_millis(150), "a keystroke cost {worst:?}"); assert!(worst_empty < std::time::Duration::from_millis(150), "{worst_empty:?}"); + assert!(worst_fuzzy < std::time::Duration::from_millis(150), "{worst_fuzzy:?}"); + } + + // ------------------------------------------------------------------ + // fuzzy matching (2026-08-30) — docs/features/fuzzy-completion/README.md + // ------------------------------------------------------------------ + + /// A workspace holding the name the whole round is about, a scatter to + /// rank it against, and a `ce…` name that only a prefix reaches. + fn typing(name: &str) -> (Tree, Workspace, Uri) { + let tree = Tree::new(name); + tree.write( + "ast.sv", + "module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\ + endmodule\n", + ); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + (tree, ws, uri) + } + + /// The response to `typed`, written mid-expression in `top.sv` — the + /// position where no tier is position-gated off. + fn after_typing(ws: &mut Workspace, uri: &Uri, typed: &str) -> Option { + let text = format!("module top;\n assign x = {typed}\nendmodule\n"); + ws.set_document(uri.clone(), text.clone()); + let offset = + (text.find(&format!("= {typed}\n")).expect("the line") + 2 + typed.len()) as u32; + let position = ws.document(uri).expect("open").positions().position(offset); + completions(ws, uri, position, true) + } + + /// The headline: three characters reach a name no prefix ever would. + #[test] + fn three_characters_reach_a_name_a_prefix_never_would() { + let (_tree, mut ws, uri) = typing("fuzzyhit"); + for typed in ["clkenq", "clken", "cen", "coq", "CLKENQ"] { + let found = items(after_typing(&mut ws, &uri, typed)); + let item = find(&found, "clk_osc_en_q") + .unwrap_or_else(|| panic!("{typed:?} found {:?}", labels(&found))); + assert_eq!(tier(item), TIER_WORD, "a name used elsewhere in the project"); + assert_eq!(inserted(item), "clk_osc_en_q", "the whole name is inserted"); + } + } + + /// …and the edit still replaces exactly what was typed, which is the + /// whole reason a fuzzy hit is usable at all: `clkenq` becomes + /// `clk_osc_en_q`, not `clkenqclk_osc_en_q`. + #[test] + fn a_fuzzy_hit_replaces_exactly_the_typed_word() { + let (_tree, mut ws, uri) = typing("fuzzyedit"); + let found = items(after_typing(&mut ws, &uri, "clkenq")); + let item = find(&found, "clk_osc_en_q").expect("the fuzzy hit"); + let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else { + panic!("a plain edit"); + }; + // ` assign x = clkenq` — the word starts at column 13 and the cursor + // is at its end. + assert_eq!(edit.range.start, Position { line: 1, character: 13 }); + assert_eq!(edit.range.end, Position { line: 1, character: 19 }); + assert_eq!(edit.new_text, "clk_osc_en_q"); + assert_eq!(item.filter_text, None, "the client filters on the label, as it should"); + } + + /// Below the floor, nothing is fuzzy. `ce` holds `clk_osc_en_q`'s letters + /// in order and must still not reach it. + #[test] + fn two_characters_match_by_prefix_and_nothing_else() { + let (_tree, mut ws, uri) = typing("fuzzyfloor"); + for typed in ["c", "ce"] { + let found = items(after_typing(&mut ws, &uri, typed)); + assert!(!found.is_empty(), "premise: {typed:?} answers something"); + for item in &found { + assert!( + starts_with_ignore_case(&item.label, typed), + "{:?} is not a prefix match for {typed:?}", + item.label + ); + } + } + // The discriminator, spelled out: `ce` would reach it if it were fuzzy + // (`c` at 0, `e` at 8), and `cen` — one character more — does. + let two = items(after_typing(&mut ws, &uri, "ce")); + assert!(!labels(&two).contains(&"clk_osc_en_q"), "{:?}", labels(&two)); + assert!(labels(&two).contains(&"celsius"), "{:?}", labels(&two)); + let three = items(after_typing(&mut ws, &uri, "cen")); + assert!(labels(&three).contains(&"clk_osc_en_q"), "{:?}", labels(&three)); + } + + /// The 1- and 2-character answers, pinned against what they were before + /// fuzzy matching existed. The keyword tier is checked as a set rather + /// than listed, so adding a reserved word to the lexer does not break a + /// test about completion. + #[test] + fn the_short_answers_are_what_they_always_were() { + let (_tree, mut ws, uri) = typing("fuzzygolden"); + for (typed, expected) in [ + // `c` itself is in the list because the buffer being typed in + // holds it as an `Ident` token — behaviour this round did not + // touch, pinned here because a golden that quietly lost it would + // be a change. + ("c", vec!["c", "c_l_k_scatter", "celsius", "clk_osc_en_q"]), + ("ce", vec!["ce", "celsius"]), + ] { + let found = items(after_typing(&mut ws, &uri, typed)); + let named: Vec<&str> = found + .iter() + .filter(|item| tier(item) != TIER_KEYWORD) + .map(|item| item.label.as_str()) + .collect(); + assert_eq!(named, expected, "the names {typed:?} answers with"); + let keywords: Vec<&str> = found + .iter() + .filter(|item| tier(item) == TIER_KEYWORD) + .map(|item| item.label.as_str()) + .collect(); + let expected_keywords: Vec<&str> = + KEYWORDS.iter().copied().filter(|kw| starts_with_ignore_case(kw, typed)).collect(); + assert_eq!(keywords, expected_keywords, "the keywords {typed:?} answers with"); + } + } + + /// **The `isIncomplete` trap.** VS Code asks again on the next keystroke + /// only when the last answer said it was incomplete, so a complete + /// two-character answer would swallow the third keystroke and fuzzy would + /// never fire at all. + #[test] + fn a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives() { + let (_tree, mut ws, uri) = typing("fuzzyincomplete"); + for typed in ["", "c", "ce"] { + let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, typed) else { + panic!("a completion list for {typed:?}"); + }; + assert!(list.is_incomplete, "{typed:?} must ask to be asked again"); + } + // From the floor up the ordinary rule stands: complete when the whole + // hit set fit, which is sound because appending a character can only + // ever shrink it. + let Some(CompletionResponse::List(list)) = after_typing(&mut ws, &uri, "cen") else { + panic!("a completion list"); + }; + assert!(!list.is_incomplete, "nothing was truncated: {} items", list.items.len()); + } + + /// A prefix match is the best subsequence match there is, and the list + /// says so — asserted on the order of the array, which is what the cap + /// cuts and what a client that does not re-rank shows. + #[test] + fn a_prefix_hit_outranks_a_scattered_one() { + let (_tree, mut ws, uri) = typing("fuzzyrank"); + let found = items(after_typing(&mut ws, &uri, "clk")); + let at = |label: &str| { + found + .iter() + .position(|item| item.label == label) + .unwrap_or_else(|| panic!("{label} in {:?}", labels(&found))) + }; + assert!( + at("clk_osc_en_q") < at("c_l_k_scatter"), + "the prefix hit leads: {:?}", + labels(&found) + ); + } + + /// Scoring the boundaries is visible in the order, not only in the score: + /// a run that starts after an underscore beats the same letters buried + /// mid-word. + #[test] + fn a_run_that_starts_at_a_boundary_leads_one_that_does_not() { + let tree = Tree::new("fuzzyboundary"); + tree.write( + "ast.sv", + "module ast;\n logic osc_ena_ready;\n logic xxenaxx_ready;\nendmodule\n", + ); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + let found = items(after_typing(&mut ws, &uri, "ena")); + let at = |label: &str| { + found + .iter() + .position(|item| item.label == label) + .unwrap_or_else(|| panic!("{label} in {:?}", labels(&found))) + }; + assert!( + at("osc_ena_ready") < at("xxenaxx_ready"), + "the boundary run leads: {:?}", + labels(&found) + ); + drop(tree); + } + + /// Dedup survives the change: a name two tiers can reach is offered once, + /// by the better tier, whichever way it was matched. + #[test] + fn a_fuzzy_name_two_tiers_reach_is_still_offered_once() { + let tree = Tree::new("fuzzydedup"); + // The same name, declared in this buffer (tier 1) and used in the + // project (tier 5), reachable from `clkenq` by neither prefix. + tree.write("ast.sv", "module ast;\n logic clk_osc_en_q;\nendmodule\n"); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + let text = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n"; + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("= clkenq").expect("needle") + 8) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let found = items(completions(&ws, &uri, position, true)); + let hits: Vec<&CompletionItem> = + found.iter().filter(|item| item.label == "clk_osc_en_q").collect(); + assert_eq!(hits.len(), 1, "{hits:#?}"); + assert_eq!(tier(hits[0]), TIER_SCOPE, "the declaration beats the word"); + assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE)); + drop(tree); + } + + /// The tiers that did **not** go fuzzy, pinned so the split is a decision + /// and not a drift: keywords, templates and macro names still match by + /// prefix, and the module tier still matches by substring. + #[test] + fn the_keyword_template_macro_and_module_tiers_did_not_go_fuzzy() { + let tree = Tree::new("fuzzyunchanged"); + tree.write("defs.svh", "`define CLK_OSC_EN_Q 1\n"); + tree.write("sub.sv", "module clk_osc_en_q ();\nendmodule\n"); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + + // Mid-expression: the macro name is offered bare by tier 2 and must + // not be reachable by subsequence, and neither is a keyword. + let found = items(after_typing(&mut ws, &uri, "clkenq")); + assert!(!labels(&found).contains(&"CLK_OSC_EN_Q"), "{:?}", labels(&found)); + let found = items(after_typing(&mut ws, &uri, "alws")); + assert!(labels(&found).is_empty() || !labels(&found).contains(&"always")); + + // A backtick still answers by prefix only. + let text = "module top;\n assign x = `CLKENQ\nendmodule\n"; + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("`CLKENQ").expect("needle") + 7) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + assert!(completions(&ws, &uri, position, true).is_none(), "no macro is spelled that way"); + + // …and the module tier is still a substring match, which is wider + // than a prefix and narrower than a subsequence. + let text = "module top;\n osc_en\nendmodule\n"; + ws.set_document(uri.clone(), text.to_string()); + let offset = (text.find("osc_en").expect("needle") + 6) as u32; + let position = ws.document(&uri).expect("open").positions().position(offset); + let found = items(completions(&ws, &uri, position, true)); + let modules: Vec<&str> = skeletons(&found).iter().map(|i| i.label.as_str()).collect(); + assert_eq!(modules, ["clk_osc_en_q"], "a substring reaches it"); + drop(tree); + } + + /// The scope tier goes fuzzy too, with no mask table behind it — it is + /// the one tier computed per request. + #[test] + fn a_declaration_in_scope_is_reached_by_subsequence() { + let top = "module top;\n logic clk_osc_en_q;\n assign x = clkenq\nendmodule\n"; + let (_tree, ws, uri, position) = asking("fuzzyscope", top, "= clkenq"); + let found = items(completions(&ws, &uri, position, true)); + let item = find(&found, "clk_osc_en_q").expect("the declaration"); + assert_eq!(tier(item), TIER_SCOPE); + assert_eq!(item.detail.as_deref(), Some("logic clk_osc_en_q;")); + } + + /// The index tier goes fuzzy too — a package member is reached the same + /// way a project word is. + #[test] + fn a_project_declaration_is_reached_by_subsequence() { + let tree = Tree::new("fuzzyindex"); + tree.write("pkg.sv", "package clkosc_pkg;\n localparam CLK_OSC_EN_Q = 1;\nendpackage\n"); + let path = tree.write("top.sv", "module top;\nendmodule\n"); + let mut ws = Workspace::default(); + ws.open_whole_workspace(vec![tree.path.clone()]); + let uri = path_to_uri(&path).expect("uri"); + let found = items(after_typing(&mut ws, &uri, "clkenq")); + let item = find(&found, "CLK_OSC_EN_Q").expect("the package member"); + assert_eq!(tier(item), TIER_INDEX); + assert_eq!(item.kind, Some(CompletionItemKind::CONSTANT)); + drop(tree); } #[test] diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index d72d868..aa02066 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -2079,6 +2079,100 @@ fn keyword_and_project_completion_round_trip_over_the_wire() { let _ = std::fs::remove_dir_all(&dir); } +/// Fuzzy completion over the wire, and the transition that makes it reachable +/// at all. +/// +/// Three requests against one buffer, at two, three and six typed characters. +/// The two-character answer has to come back `isIncomplete: true` or VS Code +/// filters the list it holds for the rest of the word and the third keystroke +/// — the one that turns subsequence matching on — never reaches the server. +/// See `docs/features/fuzzy-completion/README.md`. +#[test] +fn fuzzy_completion_round_trips_over_the_wire_including_the_two_to_three_transition() { + let dir = temp_dir("fuzzy"); + std::fs::write( + dir.join("ast.sv"), + "module ast;\n logic clk_osc_en_q;\n logic c_l_k_scatter;\n logic celsius;\n\ + endmodule\n", + ) + .expect("write"); + // Three buffers' worth of typing in one file, one per line, so one + // session can ask about all three without a `didChange`. + let top = "module top;\n assign a = ce\n assign b = clk\n assign c = clkenq\nendmodule\n"; + let path = dir.join("top.sv"); + std::fs::write(&path, top).expect("write"); + let root = format!("file://{}", dir.display()); + let uri = format!("file://{}", path.display()); + + let ask = |id: u32, line: u32, character: u32| { + frame(&format!( + r#"{{"jsonrpc":"2.0","id":{id},"method":"textDocument/completion","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":{line},"character":{character}}}}}}}"# + )) + }; + let session = [ + frame(&format!( + r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#), + frame(&format!( + r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#, + serde_json::to_string(top).expect("json") + )), + // End of `ce` on line 1, `clk` on line 2, `clkenq` on line 3. + ask(2, 1, 15), + ask(3, 2, 16), + ask(4, 3, 19), + 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 answer = |id: u32| { + messages.iter().find(|m| m["id"] == id).unwrap_or_else(|| panic!("completion {id}")) + }; + let labels = |id: u32| -> Vec { + answer(id)["result"]["items"] + .as_array() + .unwrap_or_else(|| panic!("no completion list in {:#?}", answer(id))) + .iter() + .map(|item| item["label"].as_str().expect("a label").to_string()) + .collect() + }; + + // Two characters: prefix only, and — the whole point — incomplete, so the + // client comes back on the third keystroke. + let two = labels(2); + assert!(two.contains(&"celsius".to_string()), "{two:?}"); + assert!(!two.contains(&"clk_osc_en_q".to_string()), "`ce` is not a prefix of it: {two:?}"); + assert_eq!( + answer(2)["result"]["isIncomplete"], + serde_json::Value::Bool(true), + "a two-character answer must ask to be asked again" + ); + + // Three: subsequence matching is on, and the prefix hit leads the scatter. + let three = labels(3); + let at = |list: &[String], label: &str| { + list.iter().position(|held| held == label).unwrap_or_else(|| panic!("{label} in {list:?}")) + }; + assert!(at(&three, "clk_osc_en_q") < at(&three, "c_l_k_scatter"), "{three:?}"); + + // Six: the name the round is about, reached by letters no prefix holds, + // replacing exactly the six characters that were typed. + let six = answer(4)["result"]["items"].as_array().expect("a completion list").clone(); + let hit = six + .iter() + .find(|item| item["label"] == "clk_osc_en_q") + .unwrap_or_else(|| panic!("clkenq did not reach it: {:?}", labels(4))); + assert_eq!(hit["textEdit"]["newText"], "clk_osc_en_q"); + assert_eq!(hit["textEdit"]["range"]["start"], serde_json::json!({"line": 3, "character": 13})); + assert_eq!(hit["textEdit"]["range"]["end"], serde_json::json!({"line": 3, "character": 19})); + assert!(hit["filterText"].is_null(), "the client filters on the label: {hit:#?}"); + + let _ = std::fs::remove_dir_all(&dir); +} + /// The template tier over the wire, accept-shaped: what the client is handed /// for `if` inside an `always_comb`, and what a `.v` buffer gets instead. #[test] diff --git a/docs/features/completion-core/README.md b/docs/features/completion-core/README.md index d29ecad..778d718 100644 --- a/docs/features/completion-core/README.md +++ b/docs/features/completion-core/README.md @@ -166,6 +166,39 @@ Dedup is by label, first tier wins. A name that is both a local declaration and a word used elsewhere in the project is offered once, in tier 1, with its real kind and its declaration line as detail. +### Amendment, 2026-08-30 — how a tier *matches* + +Tier ordering, `sortText`, dedup, the caps and the position gates are all +unchanged. What changed is the comparison three of the tiers make, and only +from the third typed character up: + +| Tier | Matched by, ≥3 characters typed | Was | +|---|---|---| +| `0` module names | substring | substring — unchanged | +| `1` declarations in scope | **subsequence** | prefix | +| `2` index names | **subsequence** | prefix | +| `2` `` `define`` names | prefix — unchanged | prefix | +| `3` templates | prefix — unchanged | prefix | +| `4` keywords | prefix — unchanged | prefix | +| `5` project words | **subsequence** | prefix | +| the backtick response | prefix — unchanged | prefix | + +**Below three characters every tier matches exactly as it did before**, item +for item. The one thing that had to change there is `isIncomplete`: a 1- or +2-character response now always sets it, because VS Code re-asks the server +only when the last answer said so, and a complete 2-character answer would +swallow the third keystroke — the one that turns subsequence matching on. + +Within a tier the fuzzy hits are ordered prefix-first, then by a boundary / +contiguity / gap score, then by name; that order is the order of the `items` +array, and decides which items survive the cap. `sortText` is still +`` and still means the tier order and nothing else. + +Rules, scoring, the `isIncomplete` argument and the measurements are in +`docs/features/fuzzy-completion/README.md`. The prefix API this file describes +(`Candidates::units`/`words`/`macros`/`modules`/`has_module`) is untouched and +still answers exactly what it answered. + ## The backtick ruling `` `define`` names are the one candidate whose spelling depends on where the diff --git a/docs/features/fuzzy-completion/README.md b/docs/features/fuzzy-completion/README.md new file mode 100644 index 0000000..6b85dbb --- /dev/null +++ b/docs/features/fuzzy-completion/README.md @@ -0,0 +1,535 @@ +# fuzzy-completion + +## Goal + +Make identifier completion answer the name the user is *reaching* for rather +than only the one they have spelled the front of: typing `clkenq` should offer +`clk_osc_en_q`. The letters have to be present and in order — a subsequence +match — and nothing more is promised. + +The failure this fixes was entirely server-side. VS Code's suggest widget has +always fuzzy-ranked whatever list it holds, but lucisv narrowed by prefix with +a binary search into a sorted table, so `clkenq` returned *nothing* and +`clk_osc_en_q` never reached the client to be ranked. The policy, ruled by the +owner, is **VS Code's own**: prefix matching below three typed characters, +subsequence matching from three up. Matching the client is the point — a server +that went fuzzy at one character would answer a question the widget then +filtered the answer to, and one that never went fuzzy is the bug. + +## Assumptions + +- **The typed word is ASCII.** `completion::is_ident_char` accepts + `[A-Za-z0-9_$]` and nothing else, which is what lets `candidates::fold` be + `byte | 0x20` instead of a branch, and what makes a non-ASCII byte in a + *name* unable to collide with any query byte. +- **A subsequence match is monotone in the query.** If a name holds `clke` in + order it holds `clk` in order. This is what makes a complete (not + `isIncomplete`) answer at three characters safe: everything the fourth + keystroke could match is already in the list the client holds, and VS Code's + own filter is a subsequence filter too. It is also why the 1–2-character + answers must be marked incomplete — there the hit set *grows* at the third + keystroke, which is the one transition the rule does not cover. +- **The client re-ranks.** VS Code scores every item it holds with its own + matcher and orders the widget by that; `sortText` breaks its ties and the + order of the `items` array is not consulted at all. So the server's score + decides exactly two things: **which** items survive the cap, and the order a + client that does *not* re-rank would show. It is not trying to reproduce VS + Code's scorer and does not need to. +- **`sortText` is still ``.** Unchanged, deliberately: it is + the tier ordering, and a client that sorts purely on it gets tiers in order + and alphabetical names inside each, exactly as before. The fuzzy ranking + lives in the array order instead. +- **A one-character fuzzy query is not worth answering.** It matches most of a + workspace, which is a list nobody reads, and the character mask is one bit + wide so it prunes nothing. The three-character floor fences it off. + +## Handshakes + +- **`candidates.rs` → `completion.rs`** (new): `Query`, `Score`, `rank_cmp`, + `Candidates::words_fuzzy`, `Candidates::units_fuzzy`. `Query::new` folds and + masks the typed characters once per request; `Query::score` matches one name. + The `cap` argument to the two table scans is the caller's `LIMIT`, and a full + return means the table held more — **the caller owes the response an + `isIncomplete`**, which `completion.rs` pays. +- **The prefix API is untouched.** `Candidates::words`, `units`, `macros`, + `modules` and `has_module` answer exactly what they answered, so every other + caller is unaffected. `words()` still returns `&[String]`, which is what + `state.rs`'s and `perf.rs`'s equality checks compare. +- **`inline.rs` is deliberately not a consumer.** The ghost instantiation + probes `Candidates::has_module`, which is an **exact, case-sensitive** binary + search, and it stays that way: it decides whether to plan a real + instantiation of a real module, and `Fifo` is not `fifo` to any Verilog tool. + Fuzzy matching must never leak into the instantiation trigger — a ghost + offering `clk_osc_en_q ...(...)` because the user typed `clkenq ` would be + the same class of mistake as a formatter changing code. +- **No new setting.** This is VS Code-default behaviour, so `settings.rs` and + `editors/vscode/package.json` are untouched. A `lucisv.completion.fuzzy` + toggle (or a configurable floor) is a plausible future request; it is not + this round's. +- **`vlog_semantic`, `vlog_parser`, `vlog_refactor` unchanged.** Nothing new is + asked of any of them. + +## The rules, in one place + +**Which tiers match how**, at three or more typed characters: + +| Tier | Matched by | Changed? | +|---|---|---| +| 0 module names | substring | no | +| 1 declarations in scope | **subsequence** | yes | +| 2 index names (packages, members, typedefs, classes, modules) | **subsequence** | yes | +| 2 `` `define`` names | prefix | no | +| 3 templates | prefix | no | +| 4 keywords | prefix | no | +| 5 project words | **subsequence** | yes | +| the backtick-only response (`` `WI| ``) | prefix | no | + +Below three characters **every** tier matches exactly as it did before this +round, byte for byte, and the response says `isIncomplete`. + +### What did not go fuzzy, and why + +- **Keywords.** 181 short words a user knows the spelling of; a subsequence + match over them is noise, not help. `alws` offering `always` is not worth + `nd` offering `endmodule`, `and`, `bind`, `unique`, …. +- **Templates.** Reached by a `prefix` field that is itself a keyword. +- **`` `define`` names.** The brief named the macro tier as unchanged and it is + taken literally, in both places a macro name is offered — after a backtick + (`` `WI| ``, the macro-only response) and bare (`` `ifdef WI| ``). The + backtick case is the load-bearing one: it is a small, closed vocabulary the + user is spelling deliberately. **The bare case is a defensible one-line + change the lead may want**: a `localparam WIDTH_MAX` is reachable from + `WIDTHMAX` and a `` `define WIDTH_MAX `` beside it is not, which a user could + reasonably file. Left as the brief wrote it rather than decided here. +- **The module tier**, which matches a *substring* — its own semantics, wider + than a prefix and narrower than a subsequence, and tier 0's whole ranking + argument rests on it. + +### Scoring + +One scorer, `Query::score`, in `candidates.rs`. Three linear passes, the shape +fzf's first algorithm uses: a forward greedy walk that says whether the name +matches at all and where the match must end; a backward walk that slides the +start as late as it can without losing the match; a third pass that scores the +tightened window. + +The tightening is load-bearing, not polish. Without it `clk` takes the `c` of +`osc_clk_en` and then reaches four characters for the `l`, scoring that name +*below* `xclkx` — when the run it should have found starts at an underscore +three characters on. It costs about a tenth of a table scan. + +The points: + +| | | +|---|---| +| `BOUNDARY` +6 | the character landed at the start of a part of the name: position 0, after `_` or `$`, a letter/digit transition, or the capital of a `camelCase` part | +| `CONTIGUOUS` +8 | it directly follows the previous matched character | +| `GAP` −3 each | per character skipped between two matched ones | +| `LEAD` −1 each, floored at −12 | per character skipped before the first matched one | + +`CONTIGUOUS + |GAP| > BOUNDARY` is the one inequality that had to hold: `clk` +must reach `clk_osc_en_q` ahead of `c_l_k_scatter`, where every letter is at a +boundary and none is contiguous. 8 + 3 > 6, nearly twice over. + +**Prefix matches outrank every fuzzy match**, as the first sort key rather than +as a consequence. The points very nearly give it for free — a non-prefix match +always pays `LEAD` at least once and cannot beat an unbroken run from the start +— but "very nearly" is not something a ranking should rest on: a name whose +case changes mid-word can earn a `BOUNDARY` that a prefix match of the same +query cannot, and `x_aB` would then outrank `abc` for `ab`. So `Score` carries +the flag and sorts on it first. + +Ties break on the name (`word_cmp`, case-insensitive then exact), which is a +real tie-break and not decoration: every prefix match of the same query usually +scores identically, and without it the answer would depend on whatever order +the table happened to be in. + +### The `isIncomplete` trap + +This is the correctness heart of the round and it is not about matching at all. + +VS Code asks the server again on the next keystroke **only** when the last +response said `isIncomplete: true`. Otherwise it filters the list it already +holds, client-side, for the rest of the word. A complete two-character prefix +response would therefore swallow the third keystroke — the one that turns fuzzy +on — and fuzzy would never fire in a real editor no matter how correct the +matching was. + +The rule, in `completions`: + +- a response for a **1- or 2-character** word (or an empty one) is + `isIncomplete: true`, whatever the cap did; +- a response from **three characters up** is incomplete when it was truncated — + by the response cap (`LIMIT`), by the module tier's own cap, or by either + fuzzy table scan returning its full `cap` — and complete otherwise. + +Complete is safe above the floor because appending a character can only shrink +the hit set (see *Assumptions*), so the list the client holds already contains +every answer to the longer query. + +## Status / TODO + +- [x] Per-entry 32-bit character mask for the `words` and `units` tables +- [x] Masks maintained by every mutation path — `build`, `update_file` / + `update_words`, `absorb`, `remove_file` — through two single writers + (`take_index_tables`, `remask_words`), pinned by a test that re-derives + them from scratch after each +- [x] `Query` / `Score` / `rank_cmp`, `words_fuzzy`, `units_fuzzy` +- [x] Scope, index and word tiers match by subsequence at ≥3 characters +- [x] Keyword, template, macro, backtick and module tiers unchanged +- [x] Prefix hits first, then score, then name; cross-tier dedup preserved +- [x] `isIncomplete` for every 1–2-character response, and for truncation + above the floor +- [x] `textEdit` still replaces exactly the typed word; no `filterText` +- [x] Top-K under the existing `LIMIT`, selected linearly rather than sorted +- [x] Tests: mask/table sync through all four paths; fuzzy membership against + brute-force subsequence over a seeded 20 000-word table; + case-insensitivity; out-of-order letters; the cap keeps the *best*; + prefilter-prunes guard; `clkenq → clk_osc_en_q`; 2-char prefix-only; + 1–2-char golden; prefix-beats-scatter; boundary-beats-buried; dedup; + `textEdit` range; e2e over the wire including the 2→3 transition +- [x] `cargo fmt --all -- --check`, `cargo clippy --all-targets --workspace`, + `cargo test --workspace`, `smoke.js` +- [ ] **For the lead**: bare `` `define`` names in tier 2 — fuzzy or not (see + *What did not go fuzzy*) +- [ ] **For the lead**: the wide-query cost below, and whether the follow-up + levers are worth a round + +## Performance + +Measured on the real opentitan checkout (3 976 indexed files, 43 263 index +names, 100 022 project words), release build, aarch64-apple-darwin, through +`perf::completing_over_a_real_project` — the whole `completions()` call, at +module-item position. + +| typed | before | after | added | +|---|---:|---:|---:| +| *(empty)* | 275 µs | 320 µs | — (prefix path) | +| `a` | 254 µs | 254 µs | — (prefix path) | +| `ae` | 309 µs | 313 µs | — (prefix path) | +| `aes` | 283 µs | **1.08 ms** | +0.80 ms | +| `aes_` | 279 µs | 968 µs | +0.69 ms | +| `prim_` | 224 µs | 990 µs | +0.77 ms | +| `clk` | 285 µs | 800 µs | +0.52 ms | +| `aes_reg` | 27 µs | 543 µs | +0.52 ms | +| `zzzz` | 18 µs | 154 µs | +0.14 ms | + +The 1- and 2-character rows are the point of the floor: they are the same +binary search they always were. + +The two table scans on their own, same tree: + +| query | mask-only | survive mask | match | `words_fuzzy` | `units_fuzzy` | +|---|---:|---:|---:|---:|---:| +| `clkenq` | 16 µs | 422 | 70 | **54 µs** | 21 µs | +| `clk` | 16 µs | 5 793 | 3 072 | 300 µs | 159 µs | +| `prim_` | 16 µs | 8 783 | 1 531 | 429 µs | 196 µs | +| `aes` | 16 µs | 39 362 | 20 822 | 1.86 ms | 838 µs | + +`clkenq` — the query the round is named after — is the *cheap* case, at 0.05 ms +for the word table, which matches the lead's sizing benchmark (0.07 ms over a +139 800-word list). The mask does its whole job there: it rejects 99.6% of the +table with one `&` per entry, at 16 µs for the whole pass. + +The expensive shape is three *common* letters — `aes` was the dev's example, +and QA found `ena` costs more still (2.95–4.05 ms answered-in on the real +corpus; enable-signal letters are even commoner than `a`/`e`/`s`). Neither is +*the* worst case, only the worst tried; the class is "a 3-char query of very +common letters", where the mask leaves tens of thousands of names and half +genuinely match — there is nothing to prune, and the scan is the answer +(lead wording correction after QA's finding, 2026-08-30). Two things bound it: +`select_nth_unstable_by` instead of a full sort (0.8 ms of the 2.6 ms it used +to be), and the tiers filling in order, so a wide query fills the response from +tier 2 and the word tier's `items.full()` guard skips its scan entirely. The +two are anti-correlated by construction: a query wide enough to be slow is a +query that fills the cap early. + +**Above the ≤0.5 ms bar the round was sized against, on the widest queries.** +Recorded rather than smoothed over. Two levers were considered and not taken: + +1. **Skip the fuzzy scan when the prefix run alone fills the cap.** Sound — + every prefix match outranks every fuzzy one, so if there are ≥ `LIMIT` of + them nothing the scan finds can be shown. It is a binary search away. It + does not help `aes` (480 prefix hits, just under the 512 cap) and it helps + `clk` (710) completely, so it is a real but partial win for a second code + path and a subtle argument. Filed, not taken. +2. **Two-stage scoring** — the cheap forward-only score for the whole table, + the tightened one for the few hundred that survive the cut. Implemented and + measured at ~7%, then reverted: two scorers and a "the cut is made on the + cheaper number" caveat is not what 7% buys. + +Build-side cost of the masks is one `char_mask` per table entry — 30 bytes of +byte-ORs on this corpus's average name — paid inside loops that already touch +every entry (`merge_words`'s merge, `index_tables`'s collect). Not separately +measurable against the index build beside it; the corpus test's +`index+tables built in …` line is unchanged at ~370 ms for the 860-file corpus. + +The permanent guards are +`completion::tests::a_keystroke_over_the_whole_corpus_stays_in_budget`, which +now measures a **fuzzy** request beside the two prefix ones (10.7 µs over the +860-file corpus's 16 750 words), and +`candidates::tests::the_character_mask_prunes_the_table_before_the_subsequence_scan`, +which asserts the prefilter leaves under 5% of a seeded 20 000-word table for a +`clkenq`-shaped query — a clock-free assertion, so it means the same thing on a +loaded machine. + +## Work log + +- **2026-08-30 (dev)** — implemented. + + **`candidates.rs`.** Two parallel mask vectors, `unit_masks` and + `word_masks`, each written in exactly one place: `take_index_tables` (which + also collapsed the four mutation paths' repeated + `(self.units, self.modules) = index_tables(index); self.macros = + macros_of(index);` into one call) and `remask_words`. Deriving the masks + from the table they belong to, in one writer each, is what makes desync + unrepresentable rather than merely tested — though it is tested too, after + each of the four paths, by re-deriving from scratch. + + `remask_words` re-derives the *whole* word-mask vector rather than patching + it alongside `merge_words`'s merge. That is deliberate: it is one pass over + a table the merge loop is already walking with a `HashSet` lookup per word, + it reads nothing but `self.words`, and it only runs when the table actually + moved (`merge_words` returns early otherwise). Patching in lockstep would + have been faster by a hair and desyncable by a typo. + + `Query`, `Score`, `rank_cmp`, `at_boundary`, `char_bit`, `char_mask`, + `fold`, `keep_best`, and the two scans. Rules and numbers above. + + **`completion.rs`.** `FUZZY_MIN = 3` and one `Query` per request, passed to + the three tiers that changed as `Option<&Query>` — `None` *is* the policy + decision, made once in `completions` and read as "below the floor" by each + tier. `word_tier`'s buffer-word scan came out as `buffer_words` so both + branches share it. + + **Decisions worth flagging to the lead:** + + 1. **"Byte-for-byte below three characters" is true of the *items*, not of + `isIncomplete`.** The brief asks for both that and "responses for a + 1-2-char word are `isIncomplete: true`", and they cannot both hold — a + 2-character response used to be complete. The flag is the one thing that + had to change, because without it the third keystroke never arrives. + Pinned both ways: `the_short_answers_are_what_they_always_were` for the + items, `a_short_answer_is_always_incomplete_so_the_third_keystroke_arrives` + for the flag. + 2. **`` `define`` names stayed on prefix**, in both the backtick response and + the bare tier-2 offering. The brief lists "macro tiers" among the + unchanged and the index/project tier among the changed, and tier 2 holds + both — the literal reading was taken. The bare case is arguable; it is + filed above rather than decided here. + 3. **The scorer tightens.** A plain greedy walk is what the brief's + "subsequence, scored" implies and it ranks `osc_clk_en` below `xclkx` for + `clk`, which is wrong enough to be worth a second and third linear pass. + Measured at about a tenth of a table scan. + 4. **`fold` is `| 0x20`, not `to_ascii_lowercase`.** A branch per byte, run + over every byte of every name a scan reaches, was worth removing; the + safety argument (it is exact over the identifier alphabet, and non-ASCII + bytes cannot collide with an ASCII query) is in the function's doc. + 5. **Top-K by `select_nth_unstable_by`, not by sorting.** A wide query + matches tens of thousands of names and shows five hundred. + 6. **Two-stage scoring implemented, measured, reverted** — see *Performance*. + 7. **The wide-query cost is over the round's ≤0.5 ms bar** and is reported + rather than hidden. Numbers and the two untaken levers above. + + **Also touched, inside owned files**: `the_prefix_filters_server_side` still + uses a 3-character query (`aaa`) and still passes, because nothing in its + fixture matches `aaa` by subsequence without also matching it by prefix — it + is now a weaker pin than its name suggests, and the real prefix/fuzzy split + is pinned by `two_characters_match_by_prefix_and_nothing_else` and + `the_short_answers_are_what_they_always_were`. Left alone rather than + rewritten, so the M5-era assertion stays where the lead last read it. + + **Suite**: `lucisv_server` 1 407 → **1 429** (1 360 unit + 66 e2e + 3 + grammar), 22 added; whole workspace **2 691 passed, 0 failed, 36 ignored**. + `cargo fmt --all -- --check` clean, `cargo clippy --all-targets --workspace` + zero warnings, `node editors/vscode/smoke.js target/debug/lucisv-server` → + `smoke: OK`. + +## QA log + +- **2026-08-30 (QA)** — verified. **Verdict: SHIP.** + + **Scope.** `git diff --stat` touches exactly the five files the brief + names, plus the new feature README — nothing else. + `git diff -- crates/lucisv_server/src/inline.rs` is empty (confirmed by + running the diff directly, not by trusting the work log), and its own test + module still passes inside the full-workspace run below. No + `unwrap`/`expect`/`panic!` was added outside `#[cfg(test)]` (checked by + grepping only the `+` lines of both diffs). + + **Gates.** + - `cargo fmt --all -- --check` — clean. + - `cargo clippy --all-targets --workspace` (forced recompile with `touch` + first, so this isn't a cache hit) — zero warnings. + - `cargo test --workspace` — **2691 passed, 0 failed, 36 ignored**, matching + the expected count exactly (no drift). `lucisv_server` unit tests: + 1360 passed / 34 ignored; `e2e.rs`: 66 passed / 2 ignored. + - `cargo build -p lucisv_server` (debug) and `--release` — both clean. + - `node --check editors/vscode/smoke.js` — clean; `node smoke.js` against + both the debug and release binaries — `smoke: OK` both times. + + **Attacking the matcher.** Wrote ten adversarial `#[test]` fns directly in + `candidates.rs`'s test module (mixed-case table entries reached by a + lowercase query; `$`/digit/`_` in the query at ≥3 chars; a literal non-ASCII + multibyte byte sequence in a table entry, confirmed no panic; ranking + determinism across repeated calls with the same query; the `aes`-style + commonest-letters trio; a query containing a literal `_`; a 3-char query + that is itself a keyword spelling (`end`); `absorb` overwriting an + already-present path; `remove_file` followed by re-`absorb`ing the same + path). **All ten passed** — ran them (`cargo test -p lucisv_server + candidates::tests::qa_`, 10/10 ok), then reverted the file to the dev's + exact diff (verified byte-identical via `git diff | diff -`) since they + found nothing to fix. No corruption of the ranking, no panic, no mask/table + desync under any of the attacked mutation sequences. + + Also ran the existing property test + (`a_fuzzy_scan_finds_exactly_what_brute_force_subsequence_finds`, 20k-word + table, 9 queries including a case variant and an out-of-order-adjacent one) + and `letters_out_of_order_never_match` (`qneklc`, `kclenq`, `clkqne`, + `clkenqq`) — both green, and both are real assertions, not tautologies: + confirmed by reading them rather than just running them. + + **isIncomplete / the 2→3 transition.** Unit and e2e coverage both pin the + trap correctly: 0/1/2-char responses always `isIncomplete: true`; a + 3+-char response is `isIncomplete` only when a tier's cap or the fuzzy + scan's own `cap` truncated it. Re-verified live over the wire (below). + + **Opentitan measurement (read-only).** `git -C /Users/guoliangchen/repo/opentitan + status --porcelain` before and after every session: **exactly the three + pre-existing owner-modified files** (`hw/ip/aes/dv/tb/tb.sv`, + `hw/{top_darjeeling,top_earlgrey}/ip/ast/rtl/ast.sv|`), untouched by + anything QA did — confirmed both before starting and after every server + session, including the one that opened a real file's buffer. + + The real signal: `clk_osc_en_q` is not in `ast.sv` itself, but it *is* + declared as a real local variable in + `hw/top_earlgrey/ip/ast/rtl/gfr_clk_mux2.sv` (grepped first, as instructed). + Drove a real `--verbose` release-server LSP session at the opentitan root + (custom hand-rolled Node LSP-framing harness, since no such script existed + in the repo — modeled on `editors/vscode/smoke.js`'s framing). Initial + scan (`$/progress`, title "Indexing Verilog workspace") really did cover + the whole tree: `widen finished: 3977 files (3 skipped, 3976 from cache) + in ~1.5s` — in the right ballpark scaled from the 860-file corpus's + ~370 ms baseline (4.6× the files, well under 4.6× the time), not + measurably worse from mask maintenance. + + - `clkenq` from a scratch buffer elsewhere in the workspace → finds + `clk_osc_en_q` via the project-word tier. **Confirmed.** + - `clkenq` typed *inside* `gfr_clk_mux2.sv`'s own real buffer (opened with + its actual on-disk text, one line appended after `endmodule`) → also + finds `clk_osc_en_q`, correctly still via the word tier (`sortText` + `5clk_osc_en_q`) rather than the scope tier, because the probe line was + appended after the module's closing `endmodule` and so is outside its + scope — an artifact of the probe's placement, not a bug; the scope-tier + fuzzy path is separately and directly pinned by + `completion.rs`'s own `a_declaration_in_scope_is_reached_by_subsequence` + unit test, which does put the probe inside the module. + - The 2→3 transition, live: `ce` → `isIncomplete: true`; `cen` also comes + back `isIncomplete: true` on the real corpus — correctly, since the huge + real word table means even a 3-char subsequence query legitimately hits + the 512-item cap and must say so (the small unit-test fixture where + `cen` is *complete* has only three declared names in scope; both are the + same rule, applied to different-sized tables). + - `textEdit`/no-`filterText` behavior reconfirmed over the wire via the + e2e test (`cargo test`) rather than re-driven by hand, since it is + already an exact-byte-range assertion there. + + **Latency table** (client wall-clock **and** the server's own + `timing: textDocument/completion answered in … ms` line, which is the + fairer comparison to the dev's in-process numbers since it also pays JSON + request/response marshalling the dev's isolated `Candidates` benchmark + never did — expect these to run higher than the dev's table for that + reason alone, on **every** query including the pre-existing prefix path): + + | typed | items | isIncomplete | server "answered in" (2–3 warm reps) | dev's isolated number | + |---|---:|---|---:|---:| + | `a` | 512 | true | 0.9–2.0 ms | 254 µs (unchanged path) | + | `ae` | 483 | true | ~1.9 ms | 313 µs | + | `c` / `cl` | 512 | true | 0.9–2.2 ms | n/a | + | `clk` | 512 | true | 1.5–2.9 ms | 800 µs | + | `prim_` | 512 | true | 2.5–2.8 ms | 990 µs | + | `aes` | 512 | true | **1.7–2.2 ms** | **1.08 ms (dev's stated worst case)** | + | `clkenq` | 71 | **false** | 0.4–0.5 ms | matches — the cheap case | + | `the` | 512 | true | 2.3–2.6 ms | (not in dev's table) | + | `q_e` | 512 | true | 2.5–2.8 ms | (not in dev's table) | + | `for` | 512 | true | 1.2–1.3 ms | (not in dev's table) | + | `int` | 512 | true | 1.5 ms | (not in dev's table) | + | **`ena`** | 512 | true | **2.95–4.05 ms** | **not tested by dev** | + | `eni` | 512 | true | 2.76–2.85 ms | (not in dev's table) | + + Every number here is per-request wall/server cost, not an "added" delta — + the dev's table subtracts a same-shaped before number this harness has no + clean way to reproduce (no pre-fuzzy binary was kept), so treat the + right-hand column as "does the shape match", per the assignment. + + **Finding (informational, not blocking): `ena` is a worse pathological + query than `aes` on the real corpus, not a better-or-equal one.** + Reproduced 3× in a dedicated repeat-measurement harness, isolated from + other queries in the same session, using only the server's own `timing:` + line: `aes` 1.72–2.18 ms, **`ena` 2.95–4.05 ms**, `eni` 2.76–2.85 ms, + `clk` 1.48–1.54 ms. `ena` is a real, common RTL fragment (enable-signal + naming), not a contrived string, and it costs roughly 1.4–2× what `aes` + does on this corpus while `aes` is the query the feature README singles + out as *the* worst case in its *Performance* section. It does not change + the verdict — it is the same architecture (mask survivors scanned + linearly), the same order of magnitude the lead already accepted + (single-digit milliseconds, not tens), and well within Lead ruling #1's + "~1.1 ms server-side absolute" framing even at its own worst rep (4.05 ms + wall includes IPC; 4.05 ms is the *outlier* first rep, later reps settle + at ~3.0 ms). But the *Performance* section's claim that `aes` is the + worst case a wide query can produce is not shown to be true — it is + merely the worst case the dev happened to try. Recommend the lead either + (a) accept this as within the already-approved envelope and note `ena` as + a second data point rather than re-open the sizing question, or (b) ask + for the "widest query" framing in *Performance* to be softened from "the + worst case is three common letters (`aes`)" to "one example of a wide + query" so a future reader does not treat `aes` as a proven upper bound. + + **No correctness, safety, or scope findings.** No corruption risk: every + fuzzy path is additive (widens which candidates surface, never rewrites + what a candidate's inserted text is), `verify.rs` is untouched, and + `inline.rs`'s exact-match ghost trigger is provably untouched by both the + diff and its own tests. Idempotency is not implicated — completion is not + a formatting transform. + + **TODO.md §13** — ticked with the numbers above; see the diff. + +## Review + +*(reserved for the lead.)* + +**2026-08-30 — lead.** Approved and committed. + +- Read the diff's core in full: the mask tables and their two-writer + discipline (`take_index_tables` collapsing the four mutation paths' + boilerplate is a genuine simplification, not just the mask's plumbing), the + three-pass greedy-tighten scorer (the `osc_clk_en`-below-`xclkx` example + justifies the tightening concretely), `keep_best`'s bounded selection, and + the tier changes. The `isIncomplete` handling is the round's correctness + heart and its argument is airtight in both directions: forced incomplete + below the floor because the 3rd keystroke must reach the server, ordinary + truncation semantics above it because a subsequence hit set only shrinks as + characters are appended. +- The dev's deviations all stand: items-not-flag reading of "byte-for-byte + below 3" (the two demands genuinely conflict and the flag had to move), + prefix-first as an explicit sort key, `|0x20` fold with its exactness + argument, bounded top-K, and the reverted two-stage scorer (7% wasn't worth + a second scorer). +- **Performance ruling (owner bar was ≤0.5 ms added):** the widest + common-letter 3-char queries exceed it — `aes` +0.8 ms isolated, and QA's + `ena` at 2.95–4.05 ms answered-in is the better data point. Accepted: the + criterion is the absolute answer time, and ~1–4 ms server-side on the + pathological class keeps the popup imperceptible; `clkenq`-class queries — + the ones the feature exists for — cost +0.05 ms. The README's "worst case" + wording corrected to say the class, not the sample (QA's finding). +- Macro/`define` names stay prefix-only in both spellings this round — the + conservative reading; the bare-tier one-liner is noted as a future choice, + not an oversight. +- QA's ten adversarial matcher tests all passed and were correctly reverted + (diff byte-identical); the live opentitan run confirmed `clkenq` → + `clk_osc_en_q` from a real buffer (`gfr_clk_mux2.sv`) and the 2→3 + transition over the wire; the opentitan checkout carries exactly the three + pre-existing owner edits, untouched. +- Gates re-run by the lead before commit: fmt clean, clippy zero warnings, + full suite green, smoke OK. `docs/topo.md` updated (fuzzy-completion + handshake row, matrix, header). Ships as 0.20.0. diff --git a/docs/topo.md b/docs/topo.md index ca44fbf..1d10311 100644 --- a/docs/topo.md +++ b/docs/topo.md @@ -17,7 +17,8 @@ scope widening, the request-fan-out performance wave and verbose-timing (100 feature READMEs); updated 2026-08-30 from v0.17.0 for inline-instantiation, the two-level module-instantiation split (106 feature READMEs — the testbench wave's five arrived in between, -their edges already tabled below; +§2.9-19). +their edges already tabled below; +§2.9-19); updated 2026-08-30 again +for fuzzy-completion (107 feature READMEs). **Edge notation, used in all three sections:** @@ -457,6 +458,7 @@ engine-lane features are listed above; this table is the server-internal web. | `editor-scopes ─▶ (many)` | depends (consumed by) | `pairs.rs` — one stack matcher, eight consumers today: documentHighlight, missing-closer diagnostics, `lucisv/scopePairs` rainbow, folding (references-nav), the item-position gates (completion-core / refactor-instantiate), on-type-formatting's keyword tables, inline-templates' unmatched-`begin` check, expand-selection (`selection.rs`). The `RULES` table + guard list is the shared truth; a keyword change means re-checking it. | | `editor-scopes ◀──▶ editors/vscode` | handshake | The `lucisv/scopePairs` wire shape (pinned as literal JSON in a test) and the `lucisv.rainbow*` colour ids that must match between `package.json` and `extension.js`. | | `completion-core ──▶ define-table, vlog-semantic, workspace-index, refactor-instantiate` | depends | Five tiers over existing facts; the parser widening (`KEYWORDS` export) is its one engine touch. Deliberate duplication recorded: `visible_symbols` vs `ports::visible_in` share an idea, not code. Since the performance wave, tier 0 reads module names from `Candidates::modules` (built once with the index); equality with `vlog_refactor::module_names` is test-pinned. Since 2026-08-30 tier 0 is names-only — no file read, no plan — and the guarded header-slice planning (`module_header`/`plan_for`) serves only `inline.rs`'s exact-match ghost (see the inline-instantiation handshake). | +| `fuzzy-completion ◀──▶ completion-core` | handshake | The matching rule (2026-08-30, owner policy = VS Code's own): below `FUZZY_MIN = 3` typed characters every tier matches by prefix, byte-for-byte the old behavior; from 3 up the scope, index-name and word tiers match by case-insensitive **subsequence**, ranked prefix-first then score (`Score`/`rank_cmp`), served top-K under the same `LIMIT`. `Candidates` carries parallel 32-bit char-mask tables (`unit_masks`/`word_masks`, written in exactly two places — `take_index_tables`, `remask_words` — so table and mask cannot desync) and `Query`/`units_fuzzy`/`words_fuzzy`. **Wire contract:** every response below the floor is `isIncomplete: true` — a complete 2-char answer would be client-filtered and the 3rd keystroke (the one that turns fuzzy on) would never reach the server; above the floor incompleteness follows truncation, sound because appending characters only shrinks a subsequence hit set. Module (substring), keyword, template and macro tiers unchanged; `inline.rs`'s `has_module` ghost probe stays exact and case-sensitive — fuzzy must never leak into it. | | `completion-templates ──▶ completion-core, editor-scopes` | depends | Tier 3; `templates.rs` is data + one renderer; tier digits moved (only e2e's word-tier assertion cared). Also consumes `vlog_refactor::Layout` (M4's `{ base, step }`), reused rather than re-declared, so a skeleton and a template indent by one type. | | `completion-templates ◀──▶ editor-snippets` | handshake | Nine overlapping statement/block snippets were **removed** from `editors/vscode/snippets/*.json` when the server started offering them as tier 3; both READMEs' prefix tables are the shared truth. A template added server-side must check the static set, and vice versa. | | `inlay-hints ──▶ refactor-instantiate` | depends | Reads exactly the `module_definition` + `instantiation_plan` facts M4 published (the `PlanPort`/`PlanParam` name lists signature help reads); every plan refusal is swallowed silently — a hint has no place for a sentence. | @@ -557,7 +559,7 @@ untouched, reusing existing arms. | `vlog_refactor` | refactor (plan), refactor-rename (including `prepare_rename_here` / `rename_name_at` selector half), refactor-ports (including module-target selectors), refactor-instantiate, references-nav (whole-scope equivalence oracle) | | `lucisv_core` | lucisv-core-lift (`config.rs`, `walk.rs`), filelist (`filelist.rs`), format-cache (`cache.rs`) | | `lucisv` (CLI) | cli-polish, config-discovery (wiring), parallel-files, cli-filelist, linter-core (CLI half in `lint.rs`), one-parse (`lint.rs` parses once via `ParsedSource`), format-cache (wiring), release-prep (`--version` contract) | -| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, inline-instantiation→`inline.rs`+`completion.rs`+`candidates.rs` (+`settings.rs` key), macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave→`server.rs`+`state.rs`+`candidates.rs`+`includes.rs`, change-debounce→`server.rs`, verbose-timing→`main.rs`+`server.rs`+`tests/e2e.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` | +| `lucisv_server` | lucisv-server (trunk), and one or two modules per capability feature: editor-scopes→`pairs.rs`, filelist→scope ladder in `state.rs`, include-nav→`includes.rs`, completion-core→`completion.rs`/`candidates.rs`, completion-templates→`templates.rs`, inline-templates→`inline.rs`, inline-instantiation→`inline.rs`+`completion.rs`+`candidates.rs` (+`settings.rs` key), fuzzy-completion→`candidates.rs`+`completion.rs`, macro-expansion→`expand.rs`, hierarchy→`hierarchy.rs`, type-hierarchy→`type_hierarchy.rs`, type-definition→`type_def.rs`, code-lens→`lens.rs`, inlay-hints→`inlay.rs`, server-lint→`lint.rs`+`code_action.rs`, one-parse→`lint.rs`+`state.rs` (`Document.tree`), refactor wiring/performance fan-outs→`rename.rs`/`ports.rs`+`state.rs`, apply-edit+folders-and-config+cancel-request+work-done-progress→`server.rs`, editor-settings+indexing-ux+index-scope+index-persistence→`settings.rs`+`state.rs`(+`index_cache.rs`), incremental-sync→`sync.rs`, file-watching→`watch.rs`, file-operations→`file_ops.rs` (+`include_sources` in `state.rs`), pull-diagnostics→`diagnostics.rs`+`server.rs`, semantic-tokens-delta→`tokens.rs`, on-type-formatting→`on_type.rs`, will-save-wait-until→`format.rs` (+`settings.rs`/`main.rs`), selection-range→`selection.rs`, linked-editing→`linked.rs`, references-nav (server half)→`folding.rs`+`nav.rs`, large-file-mode→`large.rs`, lsp-318-extras→`format.rs` (+`main.rs` capability), hover-declarations→`hover.rs`(+`nav.rs`), port-detail-spans (server half)→`hover.rs`+`nav.rs`, hover-line-index→`hover.rs`+`locate.rs`+`state.rs`, scan-interleave→`server.rs`+`state.rs`+`candidates.rs`+`includes.rs`, change-debounce→`server.rs`, verbose-timing→`main.rs`+`server.rs`+`tests/e2e.rs`, perf measurements→`src/perf.rs` (`docs/perf/README.md`, not a feature README), interactive-latency→`state.rs` (the two token searches) + `selection.rs`/`on_type.rs`/`completion.rs`/`inline.rs` (their callers) + `src/perf.rs`/`tests/e2e.rs` (its measurements), editor-packaging (grammar test)→`tests/grammar.rs` | | `editors/vscode` | editor-packaging, editor-snippets, editor-settings (manifest half), editor-scopes (rainbow half), editor-platform-vsix, editor-marketplace-page, index-persistence (`storagePath` line), verbose-timing (`lucisv.verbose`, spawn args and restart in `extension.js`) | | `tools/` + CI | corpus-check, release-prep, ci-release, editor-platform-vsix (staging), range-formatting (`lucisv-changed.sh`) |