Merge branch 'decomp-server'
This commit is contained in:
commit
de6f04bf7d
38 files changed
+14102
-13030
No files matched your search
@@ -3005,7 +3005,7 @@ module names, `README.md`'s architecture section updated. Runs AFTER
|
||||
- [x] Lane A `vlog_parser` — parser/ and ast/ module maps; tests moved;
|
||||
counts pinned; byte-identity proven
|
||||
- [x] Lane B `vlog_formatter` — format/ module map; counts; byte-identity
|
||||
- [ ] Lane C `lucisv_server` — server/ and completion/ module maps;
|
||||
- [x] Lane C `lucisv_server` — server/ and completion/ module maps;
|
||||
tests out of server.rs first; counts; e2e unchanged; vsix smoke
|
||||
- [ ] Lane D `vlog_semantic` + `vlog_refactor`
|
||||
- [ ] Docs: decomposition README, topo §3.1, README.md architecture
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,114 @@
|
||||
//! The completion tests' harness: a scratch workspace on disk, and the
|
||||
//! handful of helpers every provider's tests ask through.
|
||||
//!
|
||||
//! `#[cfg(test)]` only; the tests themselves sit at the foot of the file
|
||||
//! whose code they pin.
|
||||
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
pub(super) const SUB: &str = "\
|
||||
module sub #(
|
||||
parameter int WIDTH = 8
|
||||
) (
|
||||
input logic clk,
|
||||
input logic [WIDTH-1:0] data,
|
||||
output logic ready
|
||||
);
|
||||
endmodule
|
||||
";
|
||||
|
||||
/// A scratch workspace root. Removed on drop.
|
||||
pub(super) struct Tree {
|
||||
pub(super) path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
pub(super) fn new(name: &str) -> Tree {
|
||||
let path = std::env::temp_dir()
|
||||
.join(format!("lucisv_server_completion_{}_{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
pub(super) fn write(&self, rel: &str, text: &str) -> PathBuf {
|
||||
let path = self.path.join(rel);
|
||||
fs::write(&path, text).expect("write");
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A two-file workspace with `top.sv` open, and the cursor at `needle`'s
|
||||
/// end. `sub.sv` declares [`SUB`].
|
||||
pub(super) fn asking(name: &str, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
opened(tree, top, needle)
|
||||
}
|
||||
|
||||
/// The same, with whatever `tree` already holds and no `sub.sv` implied.
|
||||
pub(super) fn opened(tree: Tree, top: &str, needle: &str) -> (Tree, Workspace, Uri, Position) {
|
||||
opened_named(tree, "top.sv", top, needle)
|
||||
}
|
||||
|
||||
/// The same again, with the buffer's file name spelled out — which is what
|
||||
/// decides its dialect.
|
||||
pub(super) fn opened_named(
|
||||
tree: Tree,
|
||||
file: &str,
|
||||
top: &str,
|
||||
needle: &str,
|
||||
) -> (Tree, Workspace, Uri, Position) {
|
||||
let path = tree.write(file, top);
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle present") + needle.len()) as u32;
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let position = doc.positions().position(offset);
|
||||
(tree, ws, uri, position)
|
||||
}
|
||||
|
||||
pub(super) fn items(response: Option<CompletionResponse>) -> Vec<CompletionItem> {
|
||||
match response {
|
||||
Some(CompletionResponse::List(list)) => list.items,
|
||||
Some(CompletionResponse::Array(items)) => items,
|
||||
None => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn inserted(item: &CompletionItem) -> String {
|
||||
match item.text_edit.as_ref().expect("a text edit") {
|
||||
CompletionTextEdit::Edit(edit) => edit.new_text.clone(),
|
||||
CompletionTextEdit::InsertAndReplace(edit) => edit.new_text.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The tier an item was filed under, read off its `sortText`.
|
||||
pub(super) fn tier(item: &CompletionItem) -> char {
|
||||
item.sort_text.as_ref().and_then(|s| s.chars().next()).expect("every item is sorted")
|
||||
}
|
||||
|
||||
/// Only the module skeletons — tier 0, the M4 items.
|
||||
pub(super) fn skeletons(items: &[CompletionItem]) -> Vec<&CompletionItem> {
|
||||
items.iter().filter(|item| tier(item) == TIER_MODULE).collect()
|
||||
}
|
||||
|
||||
pub(super) fn find<'a>(items: &'a [CompletionItem], label: &str) -> Option<&'a CompletionItem> {
|
||||
items.iter().find(|item| item.label == label)
|
||||
}
|
||||
|
||||
pub(super) fn labels(items: &[CompletionItem]) -> Vec<&str> {
|
||||
items.iter().map(|item| item.label.as_str()).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,837 @@
|
||||
//! `textDocument/completion` — module hinting, templates, keywords, and every
|
||||
//! name the project uses.
|
||||
//!
|
||||
//! One response, six tiers, ordered by `sortText`:
|
||||
//!
|
||||
//! 0. **module names** — at module-item position only, every module the
|
||||
//! workspace declares whose name contains what is typed. The item inserts
|
||||
//! the **name alone**; the instantiation follows as ghost text once the
|
||||
//! name is spelled exactly and a space follows it (`inline.rs`,
|
||||
//! 2026-08-30);
|
||||
//! 1. **what is visible here** — the declarations the scope chain at the
|
||||
//! cursor binds, from this file's `Semantics`;
|
||||
//! 2. **what the project declares** — packages, their members, typedefs,
|
||||
//! classes, modules and `` `define`` names, from the workspace index;
|
||||
//! 3. **templates** — `if`/`case`/`always_ff`/declaration skeletons with
|
||||
//! tabstops, offered only where the construct may be written;
|
||||
//! 4. **keywords** — every reserved word `vlog_parser` knows;
|
||||
//! 5. **project words** — every identifier the in-scope files' *token
|
||||
//! streams* contain, the rope/VS Code word-completion tier.
|
||||
//!
|
||||
//! A name is offered once, by the highest tier that claims it. Nothing is
|
||||
//! offered inside a comment or a string literal, and nothing that only ever
|
||||
//! appears inside one is ever a candidate — see `candidates.rs`.
|
||||
//!
|
||||
//! **Every tier is a table lookup.** No request here reads a file or parses
|
||||
//! one, which is what makes the answer affordable on a keystroke in a
|
||||
//! workspace the size of opentitan. The planning half of the old tier 0 —
|
||||
//! [`plan_for`] and [`module_header`](module::module_header), still here
|
||||
//! because they are still the way an instantiation is planned — is now called by `inline.rs` for exactly
|
||||
//! one module, once the user has spelled its whole name and typed the space
|
||||
//! that says so.
|
||||
//!
|
||||
//! See `docs/features/completion-core/README.md`, for tier 0
|
||||
//! `docs/features/inline-instantiation/README.md` and
|
||||
//! `docs/features/refactor-instantiate/README.md`, and for tier 3
|
||||
//! `docs/features/completion-templates/README.md`.
|
||||
//!
|
||||
//! The module is one directory: this file is the entry point, the response
|
||||
//! under construction (`Items`) and the small helpers every tier shares; the
|
||||
//! rest is one file per answer, in the order `completions` consults them:
|
||||
//!
|
||||
//! * `word` — what is typed: the identifier run at the cursor, the backtick
|
||||
//! or the `.`/`::` before it, and the spine a separator follows;
|
||||
//! * `site` — what may be written here: the module-item and statement gates
|
||||
//! over the token stream's scope chain;
|
||||
//! * `member` — the exclusive answer after a `.` or a `::`, the connection
|
||||
//! list included;
|
||||
//! * `module` — tier 0, and the instantiation planning `inline.rs` and
|
||||
//! `instantiate.rs` share;
|
||||
//! * `tiers` — tiers 1 to 5, the five ordinary tiers in the order they fill
|
||||
//! the response.
|
||||
//!
|
||||
//! Functions a sibling file calls are `pub(super)`; the four `pub(crate)`
|
||||
//! entry points other modules of the crate use keep their paths through the
|
||||
//! re-exports below. Each file's tests sit at its foot, on the harness in
|
||||
//! `harness.rs`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::{
|
||||
CompletionItem, CompletionItemKind, CompletionList, CompletionResponse, CompletionTextEdit,
|
||||
Documentation, InsertTextFormat, InsertTextMode, MarkupContent, MarkupKind, Position, Range,
|
||||
TextEdit, Uri,
|
||||
};
|
||||
use vlog_parser::token::{Comment, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Symbol, SymbolKind};
|
||||
|
||||
use crate::candidates::Query;
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::Template;
|
||||
use member::member_answer;
|
||||
use module::module_tier;
|
||||
use site::{at_module_item, at_statement, enclosing_scopes};
|
||||
use tiers::{index_tier, keyword_tier, scope_tier, template_tier, word_tier};
|
||||
use word::typed_word;
|
||||
|
||||
pub(crate) use module::{nearest_definition, plan_for};
|
||||
// `perf.rs`, the one caller outside this module, is itself test-only; an
|
||||
// unconditional re-export would be an unused import in every other build.
|
||||
#[cfg(test)]
|
||||
pub(crate) use module::module_header;
|
||||
pub(crate) use site::at_instantiation_site;
|
||||
pub(crate) use tiers::layout_at;
|
||||
|
||||
#[cfg(test)]
|
||||
mod harness;
|
||||
mod member;
|
||||
mod module;
|
||||
mod site;
|
||||
mod tiers;
|
||||
mod word;
|
||||
|
||||
/// How many items one response carries, over every tier.
|
||||
///
|
||||
/// Large enough that an *empty* prefix still reaches the last tier — 64
|
||||
/// modules plus 181 keywords plus what one scope binds leaves room — and small
|
||||
/// enough to bound the payload at a few tens of kilobytes. Tiers fill in
|
||||
/// order, so a truncated list loses the least useful end of it and comes back
|
||||
/// `isIncomplete`: the protocol's way of saying "ask me again when you have
|
||||
/// typed more".
|
||||
const LIMIT: usize = 512;
|
||||
|
||||
/// 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;
|
||||
|
||||
/// `sortText` prefixes. The client sorts on these, so they *are* the tier
|
||||
/// order; the name follows so each tier is alphabetical within itself.
|
||||
const TIER_MODULE: char = '0';
|
||||
/// Members, after a `.` or a `::`.
|
||||
///
|
||||
/// The same digit as tier 0 and not a contradiction: the member answer is
|
||||
/// **exclusive**, so no other tier's item is ever in the same response and
|
||||
/// the digit orders members among themselves and nothing else. `'0'` because
|
||||
/// these are not one tier of an answer but the whole of it. A sixth digit
|
||||
/// would say there is a ranking against the other tiers to express, and there
|
||||
/// is not.
|
||||
const TIER_MEMBER: char = '0';
|
||||
const TIER_SCOPE: char = '1';
|
||||
const TIER_INDEX: char = '2';
|
||||
const TIER_TEMPLATE: char = '3';
|
||||
const TIER_KEYWORD: char = '4';
|
||||
const TIER_WORD: char = '5';
|
||||
|
||||
/// What a multi-line item tells the client about its own whitespace.
|
||||
///
|
||||
/// Every skeleton here is laid out at the *site's* indentation already: a
|
||||
/// `Layout`'s `base` is the trigger line's leading whitespace, and every line
|
||||
/// after the first carries it. An editor that "helpfully" indents the
|
||||
/// insertion again would double it — VS Code's `SnippetSession.adjustWhitespace`
|
||||
/// prepends the insertion line's own indentation to every line after the first,
|
||||
/// and it is on by default (`SuggestController._insertSuggestion` passes
|
||||
/// `adjustWhitespace: !(insertTextRules & KeepWhitespace)`). `asIs` is the
|
||||
/// protocol's way of saying "the text is already positioned, do not touch it",
|
||||
/// and `vscode-languageclient` turns it into exactly the `keepWhitespace` flag
|
||||
/// that clears the rule. Single-line items neither need it nor are harmed by
|
||||
/// it; only the two tiers that write more than one line send it.
|
||||
///
|
||||
/// This is the sibling of the fix `inline.rs` had to make differently: an
|
||||
/// inline completion has no such field, so its bodies are *relative* instead.
|
||||
/// See `docs/features/inline-templates/README.md`, 2026-08-25.
|
||||
const KEEP_MY_INDENTATION: InsertTextMode = InsertTextMode::AS_IS;
|
||||
|
||||
/// The completions available at a position, or nothing when the cursor is
|
||||
/// somewhere no name may be written.
|
||||
///
|
||||
/// `snippets` is what the client advertised: without it a module skeleton is
|
||||
/// inserted as plain text, because a literal `${1:clk}` left in a buffer is
|
||||
/// worse than no tabstops at all.
|
||||
pub fn completions(
|
||||
ws: &Workspace,
|
||||
uri: &Uri,
|
||||
position: Position,
|
||||
snippets: bool,
|
||||
) -> Option<CompletionResponse> {
|
||||
let doc = ws.document(uri)?;
|
||||
let offset = doc.positions().offset(position);
|
||||
// A buffer that does not lex has no token stream, so nothing here can tell
|
||||
// a comment from code — and the commonest way to break the lexer is to
|
||||
// open a string or a block comment and keep typing. Declining is the safe
|
||||
// half of that trade; the buffer lexes again as soon as it is closed.
|
||||
if doc.tokens.is_empty() || in_comment_or_string(doc, offset) {
|
||||
return None;
|
||||
}
|
||||
let word = typed_word(doc, offset)?;
|
||||
|
||||
// A backtick admits exactly one kind of name, so the answer is only that
|
||||
// kind — and the backtick already typed is inside the replaced range, so
|
||||
// it is never doubled.
|
||||
if word.backtick {
|
||||
// The backtick itself is replaced, so the item may carry its own.
|
||||
let replacing = TextRange::new(word.start.saturating_sub(1), offset);
|
||||
let mut items = Items::new(doc, replacing);
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
items.simple(
|
||||
&format!("`{}", entry.name),
|
||||
CompletionItemKind::CONSTANT,
|
||||
TIER_INDEX,
|
||||
entry.detail.clone(),
|
||||
);
|
||||
}
|
||||
return items.finish();
|
||||
}
|
||||
|
||||
// A `.` or a `::` admits exactly one kind of name too — a member of what
|
||||
// stands before it — so the answer is only those. See [`member_answer`].
|
||||
if word.sep.is_some() {
|
||||
return member_answer(ws, doc, &word, offset);
|
||||
}
|
||||
|
||||
// Both position gates read the same scope chain, and neither can be true
|
||||
// unless the word starts a line — so a keystroke in the middle of an
|
||||
// expression pays for neither.
|
||||
let starts_a_line = word.at_line_start || word.statement_head;
|
||||
let chain = match starts_a_line {
|
||||
true => enclosing_scopes(&doc.tokens, word.start),
|
||||
false => Vec::new(),
|
||||
};
|
||||
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, 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, 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()
|
||||
}
|
||||
|
||||
/// The response under construction: the items, the names already spoken for,
|
||||
/// and whether the cap cut anything off.
|
||||
struct Items {
|
||||
/// The bytes every item replaces, as the client reads them.
|
||||
range: Range,
|
||||
items: Vec<CompletionItem>,
|
||||
seen: HashSet<String>,
|
||||
incomplete: bool,
|
||||
}
|
||||
|
||||
impl Items {
|
||||
fn new(doc: &Document, replacing: TextRange) -> Items {
|
||||
Items {
|
||||
range: doc.positions().range(replacing),
|
||||
items: Vec::new(),
|
||||
seen: HashSet::new(),
|
||||
incomplete: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the cap has been reached. Once it has, every further candidate
|
||||
/// only sets [`Items::incomplete`] — which is why the tiers ask first
|
||||
/// rather than building items nobody will see.
|
||||
fn full(&mut self) -> bool {
|
||||
if self.items.len() >= LIMIT {
|
||||
self.incomplete = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Add an item, unless a higher tier already offered that name or the
|
||||
/// response is full.
|
||||
fn push(&mut self, item: CompletionItem) {
|
||||
if self.full() || !self.seen.insert(item.label.clone()) {
|
||||
return;
|
||||
}
|
||||
self.items.push(item);
|
||||
}
|
||||
|
||||
/// A plain-text item that inserts exactly its own name.
|
||||
fn simple(&mut self, name: &str, kind: CompletionItemKind, tier: char, detail: String) {
|
||||
if self.full() || self.seen.contains(name) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: name.to_string(),
|
||||
kind: Some(kind),
|
||||
detail: Some(detail),
|
||||
sort_text: Some(format!("{tier}{name}")),
|
||||
insert_text_format: Some(InsertTextFormat::PLAIN_TEXT),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: name.to_string(),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
/// One template: the skeleton it inserts, the word it is reached by, and
|
||||
/// the shape it expands to.
|
||||
///
|
||||
/// A client that never said it understands snippets gets the same text
|
||||
/// with every hole filled in rather than nothing at all — the M4 ruling,
|
||||
/// applied to a body whose defaults were chosen so that the result parses.
|
||||
fn template(&mut self, template: &Template, layout: &Layout, snippets: bool) {
|
||||
if self.full() || self.seen.contains(template.label) {
|
||||
return;
|
||||
}
|
||||
let item = CompletionItem {
|
||||
label: template.label.to_string(),
|
||||
kind: Some(CompletionItemKind::SNIPPET),
|
||||
detail: Some(format!("{} — template", template.detail)),
|
||||
documentation: Some(Documentation::MarkupContent(MarkupContent {
|
||||
kind: MarkupKind::Markdown,
|
||||
value: format!("```systemverilog\n{}\n```", template.expansion()),
|
||||
})),
|
||||
// The label is prose, so the client must be told what the user
|
||||
// types to reach the item — otherwise `if` would not match
|
||||
// `if begin/end` at all.
|
||||
filter_text: Some(template.prefix.to_string()),
|
||||
sort_text: Some(format!("{TIER_TEMPLATE}{}", template.label)),
|
||||
insert_text_format: Some(match snippets {
|
||||
true => InsertTextFormat::SNIPPET,
|
||||
false => InsertTextFormat::PLAIN_TEXT,
|
||||
}),
|
||||
insert_text_mode: Some(KEEP_MY_INDENTATION),
|
||||
text_edit: Some(CompletionTextEdit::Edit(TextEdit {
|
||||
range: self.range,
|
||||
new_text: template.render(layout, snippets),
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
self.push(item);
|
||||
}
|
||||
|
||||
fn finish(self) -> Option<CompletionResponse> {
|
||||
if self.items.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(self.into_list())
|
||||
}
|
||||
|
||||
/// The response whether or not anything is in it.
|
||||
///
|
||||
/// [`Items::finish`]'s `None` means "this was not my question", which is
|
||||
/// the right answer for a tiered response nobody filled. For the
|
||||
/// **exclusive** member answer an empty list is the answer — the site
|
||||
/// resolved and holds no matching member — and it has to be sent rather
|
||||
/// than declined, because `None` carries no `isIncomplete` and so cannot
|
||||
/// ask the client to come back with the third character.
|
||||
fn into_list(self) -> CompletionResponse {
|
||||
CompletionResponse::List(CompletionList {
|
||||
is_incomplete: self.incomplete,
|
||||
items: self.items,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The LSP icon a declaration gets in a completion list. The same choices
|
||||
/// `symbols::lsp_kind` makes for the outline, in the other enum.
|
||||
fn completion_kind(kind: SymbolKind) -> CompletionItemKind {
|
||||
match kind {
|
||||
SymbolKind::Module | SymbolKind::Package | SymbolKind::Block => CompletionItemKind::MODULE,
|
||||
SymbolKind::Interface | SymbolKind::Modport => CompletionItemKind::INTERFACE,
|
||||
SymbolKind::Clocking => CompletionItemKind::EVENT,
|
||||
SymbolKind::Port | SymbolKind::StructMember => CompletionItemKind::FIELD,
|
||||
SymbolKind::Net | SymbolKind::Var | SymbolKind::Genvar | SymbolKind::Instance => {
|
||||
CompletionItemKind::VARIABLE
|
||||
}
|
||||
SymbolKind::Param | SymbolKind::LocalParam | SymbolKind::TfArg => {
|
||||
CompletionItemKind::CONSTANT
|
||||
}
|
||||
SymbolKind::Typedef => CompletionItemKind::TYPE_PARAMETER,
|
||||
SymbolKind::EnumVariant => CompletionItemKind::ENUM_MEMBER,
|
||||
SymbolKind::Function | SymbolKind::Task => CompletionItemKind::FUNCTION,
|
||||
SymbolKind::Class => CompletionItemKind::CLASS,
|
||||
SymbolKind::Constraint | SymbolKind::Coverpoint | SymbolKind::Cross => {
|
||||
CompletionItemKind::PROPERTY
|
||||
}
|
||||
SymbolKind::Covergroup => CompletionItemKind::CLASS,
|
||||
// A property and a sequence are named declarations a concurrent
|
||||
// assertion calls by name, so they take the icon a function does.
|
||||
SymbolKind::Property | SymbolKind::Sequence => CompletionItemKind::FUNCTION,
|
||||
}
|
||||
}
|
||||
|
||||
/// What a visible declaration shows beside its name: the line it was declared
|
||||
/// on, which is the cheapest honest summary there is.
|
||||
fn declaration_detail(doc: &Document, symbol: &Symbol) -> String {
|
||||
let line = doc.positions().whole_lines(symbol.decl_span).lines().next().unwrap_or("").trim();
|
||||
match line.is_empty() {
|
||||
true => kind_label(symbol.kind).to_string(),
|
||||
false => shorten(line, 80),
|
||||
}
|
||||
}
|
||||
|
||||
/// `text`, cut to `max` characters on a character boundary.
|
||||
fn shorten(text: &str, max: usize) -> String {
|
||||
match text.char_indices().nth(max) {
|
||||
Some((at, _)) => format!("{}…", &text[..at]),
|
||||
None => text.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `offset` sits inside a comment or a string literal — the two places
|
||||
/// a completion list has no business appearing.
|
||||
///
|
||||
/// Comments are lexer trivia hanging off the token that follows (or precedes)
|
||||
/// them, so this reads both. A linear pass over the token stream: a scan of a
|
||||
/// few tens of thousands of tokens is tens of microseconds, and a binary
|
||||
/// search would have to reason about which token a comment attached to.
|
||||
fn in_comment_or_string(doc: &Document, offset: u32) -> bool {
|
||||
for token in &doc.tokens {
|
||||
if token.kind == TokenKind::String && token.span.start < offset && offset < token.span.end {
|
||||
return true;
|
||||
}
|
||||
if token.leading.iter().chain(token.trailing.as_ref()).any(|c| in_comment(c, offset)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `offset` is inside `comment`. A `//` comment runs to the end of the
|
||||
/// line, so a cursor at its last byte is still inside it; a `/* */` one ends
|
||||
/// at its marker, and the byte after that is code again.
|
||||
fn in_comment(comment: &Comment, offset: u32) -> bool {
|
||||
if offset <= comment.span.start {
|
||||
return false;
|
||||
}
|
||||
match comment.text.starts_with("//") {
|
||||
true => offset <= comment.span.end,
|
||||
false => offset < comment.span.end,
|
||||
}
|
||||
}
|
||||
|
||||
/// One tabstop: `${n:default}`, or a bare `${n}` when there is no default to
|
||||
/// preselect. The default is escaped, because `$`, `}` and `\` are the snippet
|
||||
/// grammar's own punctuation and a type like `logic [$bits(t)-1:0]` really
|
||||
/// does contain one.
|
||||
///
|
||||
/// `pub(crate)` for `inline.rs`, whose ghost instantiation writes the same
|
||||
/// holes: one spelling of a tabstop, one place to fix an escaping bug.
|
||||
pub(crate) fn snippet_hole(n: usize, default: &str) -> String {
|
||||
if default.is_empty() {
|
||||
return format!("${{{n}}}");
|
||||
}
|
||||
let mut escaped = String::with_capacity(default.len());
|
||||
for ch in default.chars() {
|
||||
if matches!(ch, '$' | '}' | '\\') {
|
||||
escaped.push('\\');
|
||||
}
|
||||
escaped.push(ch);
|
||||
}
|
||||
format!("${{{n}:{escaped}}}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::candidates::starts_with_ignore_case;
|
||||
use crate::completion::harness::*;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::uri::path_to_uri;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it() {
|
||||
assert_eq!(snippet_hole(1, ""), "${1}");
|
||||
assert_eq!(snippet_hole(2, "8"), "${2:8}");
|
||||
assert_eq!(snippet_hole(3, "$bits(t)"), "${3:\\$bits(t)}");
|
||||
assert_eq!(snippet_hole(4, "a}b\\c"), "${4:a\\}b\\\\c}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// comments and strings, both ways round
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn nothing_is_offered_inside_a_comment_or_a_string() {
|
||||
for (name, top, needle) in [
|
||||
("line", "module top;\n // wid\nendmodule\n", "// wid"),
|
||||
("block", "module top;\n /* wid */\nendmodule\n", "/* wid"),
|
||||
("trailing", "module top;\n logic a; // wid\nendmodule\n", "// wid"),
|
||||
("string", "module top;\n initial $display(\"wid\");\nendmodule\n", "\"wid"),
|
||||
] {
|
||||
let (_tree, ws, uri, position) = asking(&format!("in{name}"), top, needle);
|
||||
assert!(completions(&ws, &uri, position, true).is_none(), "{name}: {top}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_byte_after_a_block_comment_is_code_again() {
|
||||
// The other half of the boundary: `/* x */w|` is not inside anything.
|
||||
let top = "module top;\n /* c */ wid\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("afterblock", top, "*/ wid");
|
||||
assert!(completions(&ws, &uri, position, true).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_only_a_comment_or_a_string_holds_is_never_a_candidate() {
|
||||
let tree = Tree::new("harvest");
|
||||
tree.write(
|
||||
"other.sv",
|
||||
"module other;\n // widget_in_comment\n logic widget_in_code;\n\
|
||||
initial $display(\"widget_in_string\");\nendmodule\n",
|
||||
);
|
||||
let top = "module top;\n assign x = widget\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= widget");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let labels = labels(&items);
|
||||
assert!(labels.contains(&"widget_in_code"), "{labels:?}");
|
||||
assert!(!labels.contains(&"widget_in_comment"), "a comment is not code: {labels:?}");
|
||||
assert!(!labels.contains(&"widget_in_string"), "a string is not code: {labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_does_not_lex_is_declined_rather_than_guessed_at() {
|
||||
let top = "module top;\n logic a; /* unterminated\n wid\n";
|
||||
let (_tree, ws, uri, position) = asking("nolex", top, " wid");
|
||||
assert!(completions(&ws, &uri, position, true).is_none());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `define names and the backtick
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_backtick_offers_macro_names_and_only_macro_names() {
|
||||
let tree = Tree::new("macro");
|
||||
tree.write("defs.svh", "`define WIDTH 8\n`define MAX(a, b) 0\n");
|
||||
tree.write("other.sv", "module other;\n logic WIDGET;\nendmodule\n");
|
||||
let top = "module top;\n assign x = `WI\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "`WI");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(labels(&items), ["`WIDTH"], "only a macro may follow a backtick");
|
||||
assert_eq!(inserted(&items[0]), "`WIDTH");
|
||||
let CompletionTextEdit::Edit(edit) = items[0].text_edit.as_ref().expect("edit") else {
|
||||
panic!("a plain edit");
|
||||
};
|
||||
assert_eq!(
|
||||
edit.range.start,
|
||||
Position { line: 1, character: 13 },
|
||||
"the typed backtick is replaced, not doubled"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_macro_name_without_a_backtick_is_offered_bare() {
|
||||
// Where a macro name is written without one: `` `ifdef NAME ``.
|
||||
let tree = Tree::new("macrobare");
|
||||
tree.write("defs.svh", "`define WIDTH 8\n");
|
||||
let top = "module top;\n assign x = WID\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= WID");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "WIDTH").expect("the macro name");
|
||||
assert_eq!(inserted(item), "WIDTH", "no backtick is invented");
|
||||
assert_eq!(item.detail.as_deref(), Some("`define WIDTH"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// filtering, the cap, and the scope ladder
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_prefix_filters_server_side() {
|
||||
let tree = Tree::new("prefix");
|
||||
tree.write("other.sv", "module other;\n logic aaa_one, bbb_two;\nendmodule\n");
|
||||
let top = "module top;\n assign x = aaa\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= aaa");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(!items.is_empty());
|
||||
for item in &items {
|
||||
assert!(
|
||||
starts_with_ignore_case(&item.label, "aaa"),
|
||||
"{} does not start with the typed prefix",
|
||||
item.label
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_response_is_truncated_and_says_it_is_incomplete() {
|
||||
let mut top = String::from("module top;\n");
|
||||
for i in 0..LIMIT + 40 {
|
||||
top.push_str(&format!(" logic wsig{i:04};\n"));
|
||||
}
|
||||
top.push_str(" assign x = wsig\nendmodule\n");
|
||||
let (_tree, ws, uri, position) = asking("cap", &top, "= wsig");
|
||||
let Some(CompletionResponse::List(list)) = completions(&ws, &uri, position, true) else {
|
||||
panic!("a completion list");
|
||||
};
|
||||
assert_eq!(list.items.len(), LIMIT);
|
||||
assert!(list.is_incomplete, "a truncated list must say so");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_outside_the_filelist_contributes_no_words() {
|
||||
// M1's ladder decides what "the project" is, and the word tier is
|
||||
// built from exactly that list.
|
||||
let tree = Tree::new("filelist");
|
||||
tree.write("listed.sv", "module listed;\n logic word_listed;\nendmodule\n");
|
||||
tree.write("unlisted.sv", "module unlisted;\n logic word_unlisted;\nendmodule\n");
|
||||
tree.write("files.f", "listed.sv\n");
|
||||
let top = "module top;\n assign x = word_\nendmodule\n";
|
||||
let path = tree.write("top.sv", top);
|
||||
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_client_settings(ClientSettings {
|
||||
filelist: Some("files.f".to_string()),
|
||||
..Default::default()
|
||||
});
|
||||
ws.open_whole_workspace(vec![tree.path.clone()]);
|
||||
let uri = path_to_uri(&path).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
ws.rebuild_index();
|
||||
let offset = (top.find("= word_").expect("needle") + 7) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let labels = labels(&items);
|
||||
assert!(labels.contains(&"word_listed"), "{labels:?}");
|
||||
assert!(!labels.contains(&"word_unlisted"), "outside the project: {labels:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unsaved_edit_contributes_its_own_words_at_once() {
|
||||
// The buffer's own token stream is read per request, so a name typed
|
||||
// a moment ago is a candidate before anything is saved.
|
||||
let top = "module top;\n logic fresh_name;\n assign x = fre\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("unsaved", top, "= fre");
|
||||
// The file on disk is `top` too, so make the buffer differ from it.
|
||||
let edited = "module top;\n logic fresher_name;\n assign x = fre\nendmodule\n";
|
||||
let mut ws = ws;
|
||||
ws.set_document(uri.clone(), edited.to_string());
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(labels(&items).contains(&"fresher_name"), "{:?}", labels(&items));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the performance claim, measured
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// What a keystroke costs over the real corpus, and what the tables cost
|
||||
/// to build. Skipped when `corpus/` is not checked out
|
||||
/// (`tools/corpus_fetch.sh`), exactly like the other corpus tests.
|
||||
///
|
||||
/// The budgets are deliberately loose — a debug build on a loaded machine
|
||||
/// is the worst case this ever runs in — and exist to catch an *order of
|
||||
/// magnitude* regression, not to pin a number. The numbers themselves are
|
||||
/// in `docs/features/completion-core/README.md`.
|
||||
#[test]
|
||||
fn a_keystroke_over_the_whole_corpus_stays_in_budget() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let build = started.elapsed();
|
||||
|
||||
// A buffer that is not on disk: it overlays the walk, so the corpus is
|
||||
// never written to.
|
||||
let top = "module lucisv_probe;\n logic clk;\n assign x = pr\nendmodule\n";
|
||||
let uri = path_to_uri(&corpus.join("lucisv_probe.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find("= pr").expect("needle") + 4) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
// Warm, then the measurement: ten requests, worst one reported. Twice
|
||||
// — once for a typed prefix, once for the empty one, which is the
|
||||
// worst case there is (every tier matches, and the cap does the work).
|
||||
let empty = ws.document(&uri).expect("open").positions().position(offset - 2);
|
||||
let mut worst = std::time::Duration::ZERO;
|
||||
let mut worst_empty = std::time::Duration::ZERO;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let typed = items(completions(&ws, &uri, position, true));
|
||||
let after_typed = started.elapsed();
|
||||
let started = std::time::Instant::now();
|
||||
let all = items(completions(&ws, &uri, empty, true));
|
||||
let after_empty = started.elapsed();
|
||||
assert!(!typed.is_empty());
|
||||
assert_eq!(all.len(), LIMIT, "the empty prefix fills the response");
|
||||
if round > 0 {
|
||||
worst = worst.max(after_typed);
|
||||
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_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:?}");
|
||||
}
|
||||
|
||||
/// What a **member** request costs over the real corpus, against the
|
||||
/// shapes the feature is named for: a generated register struct
|
||||
/// (`uart_reg2hw_t`, eleven fields whose types are eleven more structs in
|
||||
/// the same package), one of its inner registers reached by the
|
||||
/// synthesized key, a package, and a connection list on a real wide
|
||||
/// module.
|
||||
///
|
||||
/// The member answer is a table lookup like every other tier — one
|
||||
/// `member_site` walk over one file's scopes, then one `BTreeMap` scan
|
||||
/// per unit on the chain — so it should be *cheaper* than the tiered
|
||||
/// answer, which scans three tables. Same loose budget, same reason: an
|
||||
/// order of magnitude, not a number.
|
||||
#[test]
|
||||
fn a_member_request_over_the_whole_corpus_stays_in_budget() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let uri = path_to_uri(&corpus.join("lucisv_member_probe.sv")).expect("uri");
|
||||
|
||||
let mut worst = Vec::new();
|
||||
for (what, top, needle) in [
|
||||
(
|
||||
"reg2hw.",
|
||||
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.\n end\nendmodule\n",
|
||||
" reg2hw.",
|
||||
),
|
||||
(
|
||||
"reg2hw.ctrl.",
|
||||
"module lucisv_member_probe;\n uart_reg_pkg::uart_reg2hw_t reg2hw;\n initial begin\n reg2hw.ctrl.\n end\nendmodule\n",
|
||||
" reg2hw.ctrl.",
|
||||
),
|
||||
(
|
||||
"uart_reg_pkg::",
|
||||
"module lucisv_member_probe;\n initial begin\n $display(uart_reg_pkg::);\n end\nendmodule\n",
|
||||
"uart_reg_pkg::",
|
||||
),
|
||||
// The connection list, against a real wide module in another
|
||||
// file — the position the 2026-09-02 rework exists for.
|
||||
(
|
||||
"uart_core (.",
|
||||
"module lucisv_member_probe;\n uart_core u_core (\n .\n );\nendmodule\n",
|
||||
" .",
|
||||
),
|
||||
] {
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find(needle).expect("needle") + needle.len()) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
let mut slowest = std::time::Duration::ZERO;
|
||||
let mut count = 0;
|
||||
for round in 0..11 {
|
||||
let started = std::time::Instant::now();
|
||||
let found = items(completions(&ws, &uri, position, true));
|
||||
let elapsed = started.elapsed();
|
||||
count = found.len();
|
||||
if round > 0 {
|
||||
slowest = slowest.max(elapsed);
|
||||
}
|
||||
}
|
||||
assert!(count > 0, "{what} must list members over the corpus");
|
||||
worst.push(format!("{what} {count} members in {slowest:?}"));
|
||||
assert!(slowest < std::time::Duration::from_millis(150), "{what} cost {slowest:?}");
|
||||
}
|
||||
eprintln!("corpus member requests: {}", worst.join(" / "));
|
||||
}
|
||||
|
||||
/// **QA's own reproduction, against the real file.** `prim_fifo_sync`
|
||||
/// derives `localparam int DepthW = prim_util_pkg::vbits(Depth+1)` in its
|
||||
/// header; six `parameter`s stand above it. A `#(.` list must offer the
|
||||
/// six and not the seventh. Skipped when `corpus/` is not checked out,
|
||||
/// like every other corpus test.
|
||||
#[test]
|
||||
fn the_opentitan_shape_that_found_the_localparam_bug() {
|
||||
let corpus = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let mut ws = Workspace::default();
|
||||
ws.open_whole_workspace(vec![corpus.clone()]);
|
||||
let top = "module lucisv_param_probe;\n prim_fifo_sync #(.) u_fifo ();\nendmodule\n";
|
||||
let uri = path_to_uri(&corpus.join("lucisv_param_probe.sv")).expect("uri");
|
||||
ws.set_document(uri.clone(), top.to_string());
|
||||
let offset = (top.find("#(.").expect("needle") + 3) as u32;
|
||||
let position = ws.document(&uri).expect("open").positions().position(offset);
|
||||
|
||||
let answer = items(completions(&ws, &uri, position, true));
|
||||
let mut found = labels(&answer);
|
||||
found.sort();
|
||||
assert_eq!(
|
||||
found,
|
||||
vec!["Depth", "NeverClears", "OutputZeroIfEmpty", "Pass", "Secure", "Width"],
|
||||
"the six overridable parameters, and not the derived `DepthW`",
|
||||
);
|
||||
// …and `DepthW` is still *there*: a hierarchical read of it is legal
|
||||
// and still resolves, which is what the split deliberately preserved.
|
||||
assert!(
|
||||
ws.index().members_of_chain("prim_fifo_sync").iter().any(|(name, _)| *name == "DepthW"),
|
||||
"the localparam is still exported",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,913 @@
|
||||
//! Tier 0 — module names at module-item position — and the instantiation
|
||||
//! planning that `inline.rs`'s ghost and `instantiate.rs`'s command share.
|
||||
//!
|
||||
//! The tier itself is a table scan: the names the workspace declares, ranked
|
||||
//! above everything else where an instantiation may be written. The planning
|
||||
//! half is the one part of completion that costs a *parse*, and it is here
|
||||
//! rather than in `inline.rs` because there must be exactly one answer to
|
||||
//! "which file, and which header, is this module planned from" —
|
||||
//! `nearest_definition` chooses among duplicate declarations and
|
||||
//! `module_header` slices the declaring file down to its header before the
|
||||
//! plan is built. See `docs/features/inline-instantiation/README.md` and
|
||||
//! `docs/features/refactor-instantiate/README.md`.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::Token;
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_refactor::{InstantiationPlan, Site};
|
||||
use vlog_semantic::{SymbolKind, WorkspaceIndex};
|
||||
|
||||
use super::word::Word;
|
||||
use super::{Items, TIER_MODULE};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
|
||||
/// How many module names one response carries.
|
||||
///
|
||||
/// Its own cap, below [`LIMIT`](super::LIMIT), because tier 0 matches a
|
||||
/// *substring* and so answers far more widely than the prefix tiers: an empty word at item
|
||||
/// position matches all 1 544 modules of opentitan, and letting one tier fill
|
||||
/// the whole response would starve the five below it. It no longer bounds any
|
||||
/// *work* — the tier is a scan of a table and nothing else, where until
|
||||
/// 2026-08-30 each item cost one file read and one header parse.
|
||||
const MODULE_LIMIT: usize = 64;
|
||||
|
||||
/// How far past a module's name [`module_header`] reads looking for the end of
|
||||
/// its header, smallest first.
|
||||
///
|
||||
/// A ladder rather than one bound because the lex is the whole cost of the
|
||||
/// slice and it is linear in what it is handed, so every header would
|
||||
/// otherwise pay for the widest one. The rungs come from measuring opentitan's
|
||||
/// 344 RTL modules: **59% of headers end inside 256 bytes**, 90% inside 2 KB,
|
||||
/// and the largest — `aes_control_fsm_n`, sixty commented ports — is 6.6 KB.
|
||||
/// The top rung is well past that, because a rung that is too small is not a
|
||||
/// wrong answer but a whole-file parse, and for those files that is 2–4 ms
|
||||
/// against the 0.6 ms of lexing 16 KB.
|
||||
const HEADER_WINDOWS: [usize; 3] = [256, 2 * 1024, 16 * 1024];
|
||||
|
||||
/// Tier 0: the names of the modules that could be instantiated here, at
|
||||
/// module-item position only.
|
||||
///
|
||||
/// **Names, not skeletons, since 2026-08-30** (owner ruling). Until then each
|
||||
/// item carried the whole instantiation, which cost one `module_definition`
|
||||
/// lookup, one file read and one header parse *per candidate* — up to
|
||||
/// [`MODULE_LIMIT`] of each, on every keystroke, for a list the user reads one
|
||||
/// line of. The instantiation is now offered by `inline.rs` as ghost text,
|
||||
/// once the name before the cursor is spelled exactly and a space follows it,
|
||||
/// and is planned once.
|
||||
/// See `docs/features/inline-instantiation/README.md`.
|
||||
///
|
||||
/// What survives is the ranking, which is the tier's real job: at a position
|
||||
/// where an instantiation may be written, a module name beats every other kind
|
||||
/// of name, and it is matched as a *substring* so `reg_top` reaches
|
||||
/// `aes_reg_top`.
|
||||
pub(super) fn module_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
at_item: bool,
|
||||
) {
|
||||
if !at_item {
|
||||
return;
|
||||
}
|
||||
// The same names `vlog_refactor::module_names` answers, off the table
|
||||
// built with the index instead of off the index's whole symbol table —
|
||||
// which the old call rebuilt and re-sorted on every keystroke.
|
||||
let names = ws.candidates().modules(&word.text);
|
||||
if names.len() > MODULE_LIMIT {
|
||||
items.incomplete = true;
|
||||
}
|
||||
for name in names.into_iter().take(MODULE_LIMIT) {
|
||||
items.simple(
|
||||
name,
|
||||
CompletionItemKind::MODULE,
|
||||
TIER_MODULE,
|
||||
module_detail(ws.index(), name, doc.path.as_deref()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a module item shows beside its name: where the module is declared.
|
||||
///
|
||||
/// A lookup in the index's unit table — no file is opened. The wording is tier
|
||||
/// 2's, so a module offered by either tier reads the same.
|
||||
///
|
||||
/// **The file named is the one the ghost will read** ([`nearest_definition`]),
|
||||
/// which since round 2 (2026-08-30) is an answer even for a name two files
|
||||
/// declare: `ast_dft` under `top_earlgrey` and `ast_dft` under `top_darjeeling`
|
||||
/// are two different headers, and the popup saying which one is coming is worth
|
||||
/// more than the bare kind label it used to fall back to.
|
||||
fn module_detail(index: &WorkspaceIndex, module: &str, from: Option<&Path>) -> String {
|
||||
// An interface is instantiated exactly as a module is and rides this same
|
||||
// list, so the label is read off what the index actually holds — a card
|
||||
// that said "module" over an `interface` would be the wrong answer this
|
||||
// round exists to remove.
|
||||
let kind = index
|
||||
.units(module)
|
||||
.iter()
|
||||
.find(|def| def.kind.is_instantiable())
|
||||
.map_or(SymbolKind::Module, |def| def.kind);
|
||||
let label = kind_label(kind);
|
||||
let Some(path) = nearest_definition(index, module, from) else {
|
||||
return label.to_string();
|
||||
};
|
||||
match path.file_name().and_then(|name| name.to_str()) {
|
||||
Some(file) => format!("{label} — {file}"),
|
||||
None => label.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file whose declaration of `module` a request made in `from` should be
|
||||
/// planned from.
|
||||
///
|
||||
/// **This never refuses on multiplicity**, which is the whole of what parts it
|
||||
/// from `vlog_refactor::module_definition`. That one errors when a name is
|
||||
/// declared twice and will not guess; in opentitan `ast_dft` and `io_osc` are
|
||||
/// each declared once under `hw/top_earlgrey/ip/ast/rtl` and once under
|
||||
/// `hw/top_darjeeling/ip/ast/rtl`, so refusing meant two whole IP blocks with
|
||||
/// no ghost at all. The owner's ruling of 2026-08-30 is that every indexed
|
||||
/// module expands, so the server chooses instead of declining — and
|
||||
/// `module_definition` keeps its refusal for its own callers, which want an
|
||||
/// error message rather than a guess.
|
||||
///
|
||||
/// The rule is **nearest to the asker**: the declaration whose path shares the
|
||||
/// longest run of leading *path components* with the document being typed in,
|
||||
/// so a buffer under `hw/top_earlgrey/…` is offered top_earlgrey's copy. A tie
|
||||
/// — and a buffer with no path at all — falls to the lexicographically smallest
|
||||
/// path, so the answer never depends on the order the index happened to be
|
||||
/// built in. Where the two declarations have different headers the user gets
|
||||
/// the nearest one's; that is the accepted semantics, not an approximation.
|
||||
///
|
||||
/// A module only one file declares is chosen by exactly this path too, and
|
||||
/// picks that one file — the same answer `module_definition` gives.
|
||||
pub(crate) fn nearest_definition<'i>(
|
||||
index: &'i WorkspaceIndex,
|
||||
module: &str,
|
||||
from: Option<&Path>,
|
||||
) -> Option<&'i Path> {
|
||||
index
|
||||
.units(module)
|
||||
.iter()
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.filter_map(|def| index.path(def.file))
|
||||
// Most shared leading components first; among those, the *shallowest*
|
||||
// candidate — fewest components of its own past the shared prefix —
|
||||
// then the lexicographically smallest path. The depth key is the QA
|
||||
// round-2 fix: a copy in the asking buffer's own directory and one in
|
||||
// a subdirectory of it share the same prefix with the buffer (the
|
||||
// buffer's filename never matches a directory), and without the depth
|
||||
// key the lexicographic tie-break could prefer the deeper, less
|
||||
// related copy (`rstmgr/dv/rstmgr_cnsty_chk/tb.sv` over the direct
|
||||
// sibling `rstmgr/dv/tb.sv`, because `'r' < 't'`).
|
||||
.min_by_key(|path| {
|
||||
let shared = shared_components(path, from);
|
||||
(Reverse(shared), path.components().count() - shared, *path)
|
||||
})
|
||||
}
|
||||
|
||||
/// How many leading path components `path` and `from` spell the same way.
|
||||
///
|
||||
/// Components, not bytes: `hw/top_earlgrey` and `hw/top_darjeeling` share `hw`
|
||||
/// and nothing else, where a byte-wise prefix would count `hw/top_` as shared
|
||||
/// and rank two unrelated copies by a coincidence of spelling.
|
||||
fn shared_components(path: &Path, from: Option<&Path>) -> usize {
|
||||
let Some(from) = from else { return 0 };
|
||||
path.components().zip(from.components()).take_while(|(ours, theirs)| ours == theirs).count()
|
||||
}
|
||||
|
||||
/// One module's instantiation plan, off its header alone where that is the
|
||||
/// whole of what the plan reads, and off its whole file otherwise.
|
||||
///
|
||||
/// The slice is an optimisation and never an answer of its own. Two things
|
||||
/// send this back to the whole file, and both leave the answer exactly what it
|
||||
/// was before the slice existed:
|
||||
///
|
||||
/// * the slice does not plan at all — [`module_header`] cut a header this
|
||||
/// parser does not read as one;
|
||||
/// * the plan it produced has a port with neither a direction nor a type,
|
||||
/// which is what a **non-ANSI** port list looks like once its body is gone:
|
||||
/// `module m (a); input wire a;` writes the direction below the header, and
|
||||
/// the body is the part the slice drops.
|
||||
///
|
||||
/// `pub(crate)` for `inline.rs`, which plans the one module the user has
|
||||
/// spelled out. One planner on purpose: a second answer to "what is this
|
||||
/// module's instantiation" would eventually disagree with this one, and any
|
||||
/// future non-ghost spelling of the skeleton (a command for clients without
|
||||
/// `inlineCompletion`, say — filed in `docs/topo.md` §2.9) must come through
|
||||
/// here too.
|
||||
pub(crate) fn plan_for(
|
||||
index: &WorkspaceIndex,
|
||||
module: &str,
|
||||
definition: &str,
|
||||
site: Site<'_>,
|
||||
) -> Result<InstantiationPlan, String> {
|
||||
let whole = || vlog_refactor::instantiation_plan(module, definition, Some(site));
|
||||
let Some(header) = module_header(index, module, definition) else { return whole() };
|
||||
match vlog_refactor::instantiation_plan(module, &header, Some(site)) {
|
||||
Ok(plan) if plan.ports.iter().all(|p| !p.dir.is_empty() || !p.ty.is_empty()) => Ok(plan),
|
||||
_ => whole(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The text one skeleton is planned from: the declaring file's header alone
|
||||
/// where this function can find it, and the whole file where it cannot.
|
||||
///
|
||||
/// Tier 0 is the one tier that costs a *parse*, and until 2026-08-28 it parsed
|
||||
/// the whole declaring file — three hundred lines of body to read a header a
|
||||
/// few hundred bytes long, [`MODULE_LIMIT`] times per keystroke. A plan reads
|
||||
/// nothing but the header, so nothing but the header needs to be parsed.
|
||||
///
|
||||
/// The prefix is kept **byte for byte**: every span the plan reads is an offset
|
||||
/// into the text it was parsed from, so cutting the front off would move them
|
||||
/// all. Only the body is dropped, and an `endmodule` is written in its place so
|
||||
/// the declaration is closed.
|
||||
///
|
||||
/// **Every declaration of the name is tried, not just a lone one** (round 2,
|
||||
/// 2026-08-30). Until then a name two files declared made this decline outright,
|
||||
/// which cost `ast_dft` and `io_osc` their ghost; it now walks them, because
|
||||
/// the index's span is only ever a *hint* here and the guard below is what
|
||||
/// makes a hint safe. A span from the wrong file either does not spell the
|
||||
/// module's name in this text — declined, and the caller parses the whole file
|
||||
/// instead, exactly as it did before — or it does, in which case the slice is
|
||||
/// taken from a real occurrence of the name in the text actually being read.
|
||||
pub(crate) fn module_header(index: &WorkspaceIndex, module: &str, text: &str) -> Option<String> {
|
||||
index
|
||||
.units(module)
|
||||
.iter()
|
||||
.filter(|def| def.kind.is_instantiable())
|
||||
.find_map(|def| header_from(module, def.name_span, text))
|
||||
}
|
||||
|
||||
/// The header of the declaration `text` spells at `name`, or `None` when it
|
||||
/// does not spell one there at all.
|
||||
fn header_from(module: &str, name: TextRange, text: &str) -> Option<String> {
|
||||
// The index's span is as of the last scan, and may belong to a sibling
|
||||
// file that declares the same module. A file edited on disk since then has
|
||||
// moved it, and a slice taken at a stale offset would be a different
|
||||
// module's header — so the name has to still be there.
|
||||
if text.get(name.start as usize..name.end as usize) != Some(module) {
|
||||
return None;
|
||||
}
|
||||
let from = name.end as usize;
|
||||
for size in HEADER_WINDOWS {
|
||||
// A window that cuts a block comment or a string in half does not lex,
|
||||
// and one that cuts the port list in half runs out of tokens before
|
||||
// the `;`. Both answer "not in this window" and are asked again at the
|
||||
// next rung; both answer `None` at the last one.
|
||||
let window = text.get(from..text.len().min(from + size))?;
|
||||
if let Ok(tokens) = vlog_parser::tokenize(window) {
|
||||
if let Some(end) = header_end(&tokens) {
|
||||
let head = text.get(..from + end as usize)?;
|
||||
return Some(format!("{head}\nendmodule\n"));
|
||||
}
|
||||
}
|
||||
if from + size >= text.len() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Where the header that begins just after a module's name ends: the offset
|
||||
/// one past its terminating `;`, in the window's own coordinates.
|
||||
///
|
||||
/// A **whitelist**, not a scan for the first `;`: `module aes import
|
||||
/// aes_pkg::*; #(...) (...);` writes three of them and only the last ends the
|
||||
/// header. Anything this does not recognise — a compiler directive between the
|
||||
/// name and the port list, a header longer than the window — answers `None`,
|
||||
/// and the caller parses the whole file rather than guessing.
|
||||
fn header_end(tokens: &[Token]) -> Option<u32> {
|
||||
let mut at = 0;
|
||||
loop {
|
||||
let token = tokens.get(at)?;
|
||||
match token.text.as_str() {
|
||||
";" => return Some(token.span.end),
|
||||
// A lifetime qualifier: `module automatic foo (...);`.
|
||||
"static" | "automatic" => at += 1,
|
||||
// A package import written into the header, whose own `;` is not
|
||||
// the header's.
|
||||
"import" => at = skip_to_semicolon(tokens, at + 1)?,
|
||||
// The parameter list, the port list, and an attribute instance —
|
||||
// each one parenthesised, each one skipped whole.
|
||||
"#" | "(" => at = skip_parens(tokens, at)?,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the parenthesised group starting at `at`, which a `#` may introduce.
|
||||
fn skip_parens(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
while tokens.get(at)?.text == "#" {
|
||||
at += 1;
|
||||
}
|
||||
if tokens.get(at)?.text != "(" {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" if depth == 1 => return Some(at + 1),
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Past the next `;` written outside any parentheses.
|
||||
fn skip_to_semicolon(tokens: &[Token], mut at: usize) -> Option<usize> {
|
||||
let mut depth = 0i32;
|
||||
loop {
|
||||
match tokens.get(at)?.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
";" if depth == 0 => return Some(at + 1),
|
||||
_ => {}
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Completion's own view of the three new kinds, and the detail card that
|
||||
/// used to hard-code "module" over an interface — the C2 wrong answer
|
||||
/// (`docs/features/interface-semantics/README.md`).
|
||||
#[test]
|
||||
fn an_interface_completes_as_an_interface() {
|
||||
assert_eq!(completion_kind(SymbolKind::Interface), CompletionItemKind::INTERFACE);
|
||||
assert_eq!(completion_kind(SymbolKind::Modport), CompletionItemKind::INTERFACE);
|
||||
assert_eq!(completion_kind(SymbolKind::Clocking), CompletionItemKind::EVENT);
|
||||
|
||||
let index = vlog_semantic::WorkspaceIndex::build([
|
||||
(PathBuf::from("/rtl/bus_if.sv"), "interface bus_if;\nendinterface\n"),
|
||||
(PathBuf::from("/rtl/sub.sv"), SUB),
|
||||
]);
|
||||
assert!(module_detail(&index, "bus_if", None).starts_with("interface"));
|
||||
assert!(module_detail(&index, "sub", None).starts_with("module"));
|
||||
// The ghost-instantiation lookups reach an interface too.
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "bus_if", None).map(|p| p.display().to_string()),
|
||||
Some("/rtl/bus_if.sv".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 0's header slice (2026-08-28) — it must change no answer
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Every header shape the slice has to survive, as (file text, module).
|
||||
///
|
||||
/// The list is the argument that the slice changes nothing: each entry is
|
||||
/// planned both ways below and the two plans are compared field by field.
|
||||
const SHAPES: &[(&str, &str)] = &[
|
||||
// The ordinary ANSI header, params and all.
|
||||
(SUB, "sub"),
|
||||
// No ports at all.
|
||||
("module bare;\nendmodule\n", "bare"),
|
||||
// An empty port list.
|
||||
("module empty ();\n logic x;\nendmodule\n", "empty"),
|
||||
// A package import written into the header: its `;` is not the
|
||||
// header's, and a slice that stopped there would report no ports.
|
||||
(
|
||||
"package p;\n localparam int W = 4;\nendpackage\n\
|
||||
module imported import p::*; #(\n parameter int W = 8\n) (\n \
|
||||
input logic clk,\n output logic [W-1:0] q\n);\n \
|
||||
assign q = '0;\nendmodule\n",
|
||||
"imported",
|
||||
),
|
||||
// Two imports, then a parameter list.
|
||||
(
|
||||
"package p;\nendpackage\npackage q;\nendpackage\n\
|
||||
module twice import p::*; import q::*; (input logic a);\nendmodule\n",
|
||||
"twice",
|
||||
),
|
||||
// A **non-ANSI** port list: the directions live in the body, which is
|
||||
// exactly what the slice drops.
|
||||
(
|
||||
"module old (a, b);\n input wire [7:0] a;\n output reg b;\n \
|
||||
always @* b = |a;\nendmodule\n",
|
||||
"old",
|
||||
),
|
||||
// Non-ANSI with nothing declaring the ports at all.
|
||||
("module silent (a, b);\nendmodule\n", "silent"),
|
||||
// A comment and an attribute inside the header.
|
||||
(
|
||||
"module noisy /* mid */ #(\n parameter int W = 2 // the width\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"noisy",
|
||||
),
|
||||
// A lifetime qualifier.
|
||||
("module automatic lifetime (input logic a);\nendmodule\n", "lifetime"),
|
||||
// A second module in the same file, after the one being planned.
|
||||
(
|
||||
"module first (input logic a);\nendmodule\n\
|
||||
module second (output logic b);\nendmodule\n",
|
||||
"first",
|
||||
),
|
||||
// …and before it, so the slice's prefix carries a whole module.
|
||||
(
|
||||
"module first (input logic a);\nendmodule\n\
|
||||
module second (output logic b);\nendmodule\n",
|
||||
"second",
|
||||
),
|
||||
// A compiler directive between the name and the port list, which the
|
||||
// whitelist refuses outright.
|
||||
("`define PORTS input logic clk\nmodule gated `PORTS ;\nendmodule\n", "gated"),
|
||||
// A directive *inside* the port list, which carries a warning the two
|
||||
// plans must both raise.
|
||||
(
|
||||
"module ifdefd (\n input logic clk\n`ifdef EXTRA\n , input logic more\n\
|
||||
`endif\n);\nendmodule\n",
|
||||
"ifdefd",
|
||||
),
|
||||
// An escaped identifier for the module and for a port.
|
||||
("module \\odd-name ( input logic \\a-b );\nendmodule\n", "\\odd-name"),
|
||||
// A header longer than the first rung of the window ladder.
|
||||
(WIDE, "wide"),
|
||||
// QA (performance wave Lane B, 2026-08-28): a genuine attribute
|
||||
// instance, `(* ... *)`, right after the module name and before the
|
||||
// parameter list — the one shape the "noisy" case above is commented
|
||||
// as covering but does not (it has two comments, no attribute).
|
||||
// **Finding, not a regression this round introduced**: a module with
|
||||
// an attribute anywhere near its header is not indexed as a `Module`
|
||||
// unit at all (see
|
||||
// `a_module_with_an_attribute_near_its_header_is_not_indexed_at_all`),
|
||||
// so this pins the safe side effect — `module_header` declines before
|
||||
// its whitelist walk ever runs — rather than the whitelist's own
|
||||
// handling of attributes, which this shape cannot reach.
|
||||
(
|
||||
"module attributed (* some_attr *) #(\n parameter int W = 2\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"attributed",
|
||||
),
|
||||
// An attribute instance *inside* the port list, attached to one port.
|
||||
// Same finding as `attributed`: not indexed, so not reached either.
|
||||
(
|
||||
"module port_attributed (\n input logic clk,\n (* keep *) output logic q\n\
|
||||
);\nendmodule\n",
|
||||
"port_attributed",
|
||||
),
|
||||
// A single import declaration naming several packages, comma
|
||||
// separated (`import a::*, b::*;`) — one statement, not two, and the
|
||||
// whitelist's `skip_to_semicolon` must not stop at the first `::`.
|
||||
(
|
||||
"package p;\nendpackage\npackage q;\nendpackage\n\
|
||||
module chained import p::*, q::*; (input logic a);\nendmodule\n",
|
||||
"chained",
|
||||
),
|
||||
// A parameter default whose string literal carries the exact bytes
|
||||
// the whitelist watches for — `;` and `)` — which must stay inside
|
||||
// the `String` token and never be mistaken for header punctuation.
|
||||
(
|
||||
"module stringy #(\n parameter string S = \"a;b)c\"\n) (\n \
|
||||
input logic clk\n);\nendmodule\n",
|
||||
"stringy",
|
||||
),
|
||||
// CRLF line endings through the whole header.
|
||||
("module crlf (\r\n input logic clk\r\n);\r\nendmodule\r\n", "crlf"),
|
||||
];
|
||||
|
||||
/// A header wider than [`HEADER_WINDOWS`]`[0]`, so the ladder has to climb.
|
||||
const WIDE: &str = "module wide (\n input logic port_number_zero_with_a_long_name,\n \
|
||||
input logic port_number_one_with_a_long_name,\n \
|
||||
input logic port_number_two_with_a_long_name,\n \
|
||||
input logic port_number_three_with_a_long_name,\n \
|
||||
input logic port_number_four_with_a_long_name,\n \
|
||||
input logic port_number_five_with_a_long_name,\n \
|
||||
output logic port_number_six_with_a_long_name\n);\n \
|
||||
assign port_number_six_with_a_long_name = port_number_zero_with_a_long_name;\nendmodule\n";
|
||||
|
||||
/// The whole argument for the slice: for every shape above, the plan built
|
||||
/// from the header alone is the plan built from the whole file. Where it
|
||||
/// would not be — a non-ANSI list, a header the whitelist refuses — the
|
||||
/// guard in [`plan_for`] sends the question back to the whole file, so the
|
||||
/// comparison holds there too.
|
||||
#[test]
|
||||
fn the_header_slice_plans_exactly_what_the_whole_file_plans() {
|
||||
for (text, module) in SHAPES {
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), *text)]);
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let site = Site { semantics: &semantics, offset: 0 };
|
||||
let whole = vlog_refactor::instantiation_plan(module, text, Some(site));
|
||||
let ours = plan_for(&index, module, text, site);
|
||||
assert_eq!(ours, whole, "{module}");
|
||||
}
|
||||
}
|
||||
|
||||
/// QA (performance wave Lane B, 2026-08-28): the equality above holds
|
||||
/// trivially for a shape the whitelist declines — both sides parse the
|
||||
/// whole file, so a wrong slice could hide behind that. These shapes must
|
||||
/// actually slice, so the comparison exercises the whitelist walk it is
|
||||
/// meant to pin: an `import a::*, b::*;` chain (one statement, several
|
||||
/// packages — `skip_to_semicolon` must not stop at the first `::`), a
|
||||
/// `;`/`)` sitting inside a string literal, and CRLF endings.
|
||||
#[test]
|
||||
fn the_attack_shapes_actually_slice_rather_than_passing_the_pin_vacuously() {
|
||||
for module in ["chained", "stringy", "crlf", "twice", "imported"] {
|
||||
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, *text)]);
|
||||
assert!(
|
||||
module_header(&index, module, text).is_some(),
|
||||
"{module}: expected the header to actually slice, not fall back whole-file"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// QA finding (performance wave Lane B, 2026-08-28), not a regression this
|
||||
/// round introduced: a module with an attribute instance (`(* ... *)`)
|
||||
/// anywhere near its header — right after its name, or on one of its
|
||||
/// ports — is not indexed as a `Module` unit **at all**.
|
||||
/// `WorkspaceIndex::units` comes back empty, so [`module_header`] declines
|
||||
/// at the very first line (no `[def]` to anchor on) before the whitelist
|
||||
/// walk ever runs, and completion's module tier — which sources its
|
||||
/// candidate names from the same table — never offers the module in the
|
||||
/// first place. This is a `vlog_semantic`/`vlog_parser` parsing gap, not a
|
||||
/// completion-core one: it is filed in `docs/features/completion-core/
|
||||
/// README.md`'s QA log rather than fixed here, because `vlog_semantic` is
|
||||
/// outside this round's touched files. The two "attribute" shapes this QA
|
||||
/// round added to [`SHAPES`] (`attributed`, `port_attributed`) still pass
|
||||
/// [`the_header_slice_plans_exactly_what_the_whole_file_plans`] — but only
|
||||
/// because both sides of that comparison fall back to the same whole-file
|
||||
/// parse, which this test makes explicit rather than leaving it as an
|
||||
/// unremarked side effect of the pin.
|
||||
#[test]
|
||||
fn a_module_with_an_attribute_near_its_header_is_not_indexed_at_all() {
|
||||
for module in ["attributed", "port_attributed"] {
|
||||
let (text, _) = SHAPES.iter().find(|(_, m)| *m == module).expect("in SHAPES");
|
||||
let path = PathBuf::from("/rtl/shape.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, *text)]);
|
||||
assert!(
|
||||
index.units(module).is_empty(),
|
||||
"{module}: if this starts finding a unit, module_header should be re-audited \
|
||||
for whether it now slices attributes correctly rather than by lucky fallback"
|
||||
);
|
||||
assert!(
|
||||
module_header(&index, module, text).is_none(),
|
||||
"{module}: no unit to anchor on"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The guard is not decoration: a non-ANSI module really does plan
|
||||
/// differently off its header, and really is sent back to the whole file.
|
||||
#[test]
|
||||
fn a_non_ansi_port_list_is_planned_from_the_whole_file() {
|
||||
let text = "module old (a, b);\n input wire [7:0] a;\n output reg b;\nendmodule\n";
|
||||
let path = PathBuf::from("/rtl/old.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path, text)]);
|
||||
let header = module_header(&index, "old", text).expect("the header slices");
|
||||
let sliced = vlog_refactor::instantiation_plan("old", &header, None).expect("a plan");
|
||||
assert!(
|
||||
sliced.ports.iter().all(|p| p.dir.is_empty() && p.ty.is_empty()),
|
||||
"premise: the header alone knows nothing about these ports"
|
||||
);
|
||||
let (tree, _) = vlog_parser::parse_source_tolerant(text);
|
||||
let semantics = vlog_semantic::analyze(&tree, text);
|
||||
let site = Site { semantics: &semantics, offset: 0 };
|
||||
let guarded = plan_for(&index, "old", text, site).expect("a plan");
|
||||
assert_eq!(guarded.ports[0].dir, "input");
|
||||
assert_eq!(guarded.ports[0].ty, "wire [7:0]");
|
||||
}
|
||||
|
||||
/// The whole answer, pinned at the prefixes the hot path is worst at — the
|
||||
/// empty one and a one-character one, where every tier is at its widest.
|
||||
/// Tier 0 answers with names, so the pin spells out every module item's
|
||||
/// label *and* the text it inserts, which is now the label again.
|
||||
#[test]
|
||||
fn the_answer_is_pinned_at_the_prefixes_the_hot_path_is_worst_at() {
|
||||
let tree = Tree::new("pinned");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("alpha.sv", "module alpha (\n input logic clk\n);\nendmodule\n");
|
||||
tree.write("submarine.sv", "module submarine ();\nendmodule\n");
|
||||
let (_tree, mut ws, uri, _) =
|
||||
opened(tree, "module top;\n logic clk;\n \nendmodule\n", " ");
|
||||
|
||||
// Nothing typed, then one character — the two widest requests there
|
||||
// are. `top` is in the answer because the buffer declares it and the
|
||||
// index holds it like any other module.
|
||||
let mut answer = |typed: &str| {
|
||||
let text = format!("module top;\n logic clk;\n {typed}\nendmodule\n");
|
||||
ws.set_document(uri.clone(), text.clone());
|
||||
let offset = (text.find(&format!("\n {typed}\n")).expect("the line") + 3) as u32
|
||||
+ typed.len() as u32;
|
||||
let doc = ws.document(&uri).expect("open");
|
||||
let position = doc.positions().position(offset);
|
||||
items(completions(&ws, &uri, position, true))
|
||||
};
|
||||
for (typed, expected) in
|
||||
[("", vec!["alpha", "sub", "submarine", "top"]), ("s", vec!["sub", "submarine"])]
|
||||
{
|
||||
let items = answer(typed);
|
||||
let found: Vec<&str> =
|
||||
skeletons(&items).iter().map(|item| item.label.as_str()).collect();
|
||||
assert_eq!(found, expected, "module items after typing {typed:?}");
|
||||
}
|
||||
|
||||
// …and the exact text each of them inserts, which is the name and
|
||||
// nothing else however many ports the module has. The instantiation is
|
||||
// `inline.rs`'s business now.
|
||||
let items = answer("");
|
||||
for name in ["sub", "alpha", "submarine"] {
|
||||
let item = find(&items, name).expect("the module item");
|
||||
assert_eq!(inserted(item), name, "the popup inserts the name alone");
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
assert_eq!(item.insert_text_mode, None, "there is no indentation to keep");
|
||||
}
|
||||
}
|
||||
|
||||
/// A file edited on disk since the index last read it has moved every span
|
||||
/// the index holds, so the slice must not take one on trust.
|
||||
#[test]
|
||||
fn a_stale_index_span_declines_to_slice_rather_than_slicing_the_wrong_bytes() {
|
||||
let text =
|
||||
"module a (input logic p);\nendmodule\nmodule sliced (input logic q);\nendmodule\n";
|
||||
let index = WorkspaceIndex::build(vec![(PathBuf::from("/rtl/a.sv"), text)]);
|
||||
assert!(module_header(&index, "sliced", text).is_some(), "premise: it slices normally");
|
||||
// The same index against a file whose text has shifted underneath it.
|
||||
let moved = format!("// a line nobody told the index about\n{text}");
|
||||
assert_eq!(module_header(&index, "sliced", &moved), None, "the name is no longer there");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 0 — module names (level 1 of the instantiation wave, 2026-08-30)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_module_name_at_item_position_completes_to_the_name_alone() {
|
||||
let top = "module top;\n logic clk;\n su\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("nameonly", top, " su");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let modules = skeletons(&items);
|
||||
assert_eq!(modules.len(), 1, "{items:#?}");
|
||||
let item = modules[0];
|
||||
assert_eq!(item.label, "sub");
|
||||
assert_eq!(item.kind, Some(CompletionItemKind::MODULE), "still a module icon");
|
||||
assert_eq!(item.detail.as_deref(), Some("module — sub.sv"));
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
assert_eq!(inserted(item), "sub", "the name, and the ghost writes the rest");
|
||||
assert_eq!(item.documentation, None, "no plan was read, so there is nothing to show");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_snippet_flag_no_longer_changes_the_module_item() {
|
||||
// The M4 fallback — a plain-text spelling of the skeleton for a client
|
||||
// that never advertised `snippetSupport` — has nothing left to fall
|
||||
// back from: the item is a word either way.
|
||||
let top = "module top;\n logic clk;\n su\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("plain", top, " su");
|
||||
for snippets in [true, false] {
|
||||
let items = items(completions(&ws, &uri, position, snippets));
|
||||
let item = skeletons(&items)[0];
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
assert_eq!(inserted(item), "sub", "snippets: {snippets}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole point of level 1: the popup no longer reads the files it
|
||||
/// offers names from. Proved by deleting the declaring file after the
|
||||
/// index has been built — the old tier answered nothing at all here,
|
||||
/// because every item needed that file's text.
|
||||
#[test]
|
||||
fn the_module_tier_reads_no_file_and_so_answers_one_that_is_gone() {
|
||||
let tree = Tree::new("noread");
|
||||
let sub = tree.write("sub.sv", SUB);
|
||||
let (_tree, ws, uri, position) =
|
||||
opened(tree, "module top;\n logic clk;\n su\nendmodule\n", " su");
|
||||
fs::remove_file(&sub).expect("remove the declaring file");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert_eq!(
|
||||
skeletons(&items).iter().map(|item| item.label.as_str()).collect::<Vec<_>>(),
|
||||
["sub"],
|
||||
"the name comes from the index's table, not from the file: {items:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_edit_replaces_exactly_the_typed_word() {
|
||||
let top = "module top;\n su\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("replace", top, " su");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
for item in &items {
|
||||
let CompletionTextEdit::Edit(edit) = item.text_edit.as_ref().expect("edit") else {
|
||||
panic!("a plain edit");
|
||||
};
|
||||
assert_eq!(edit.range.start, Position { line: 1, character: 2 }, "{item:#?}");
|
||||
assert_eq!(edit.range.end, Position { line: 1, character: 4 });
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_in_the_middle_of_an_expression() {
|
||||
// The other tiers answer here — a name is a name wherever it is
|
||||
// written — but a fifteen-line instantiation is not.
|
||||
for (name, top, needle) in [
|
||||
("assign", "module top;\n wire x;\n assign x = su\nendmodule\n", "= su"),
|
||||
("decl", "module top;\n logic su\nendmodule\n", "logic su"),
|
||||
("conn", "module top;\n sub u (.clk(su\nendmodule\n", ".clk(su"),
|
||||
("header", "module top (su\n);\nendmodule\n", "top (su"),
|
||||
] {
|
||||
let (_tree, ws, uri, position) = asking(name, top, needle);
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(skeletons(&items).is_empty(), "{name}: {top}\n{items:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_inside_a_procedural_block() {
|
||||
let top = "module top;\n always_ff @(posedge clk) begin\n su\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("always", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
|
||||
let top = "module top;\n initial begin\n su\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("initial", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_inside_a_function_or_a_class() {
|
||||
let top = "module top;\n function int f();\n su\n endfunction\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("function", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
|
||||
let top = "package p;\n class c;\n su\n endclass\nendpackage\n";
|
||||
let (_tree, ws, uri, position) = asking("class", top, " su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_generate_block_is_still_item_position() {
|
||||
let top = "\
|
||||
module top;
|
||||
for (genvar i = 0; i < 4; i++) begin : g
|
||||
su
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("genfor", top, " su");
|
||||
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1, "{top}");
|
||||
|
||||
let top = "module top;\n generate\n su\n endgenerate\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("generate", top, " su");
|
||||
assert_eq!(skeletons(&items(completions(&ws, &uri, position, true))).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_skeleton_is_offered_outside_a_design_unit() {
|
||||
let top = "su\nmodule top;\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("toplevel", top, "su");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_prefix_that_matches_no_module_offers_no_skeleton() {
|
||||
let top = "module top;\n zzz\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("nomatch", top, " zzz");
|
||||
assert!(skeletons(&items(completions(&ws, &uri, position, true))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_declared_twice_is_offered_by_name_and_names_the_copy_it_will_ghost() {
|
||||
// Until 2026-08-30 tier 0 skipped it: there is no single definition to
|
||||
// build a *skeleton* from, and the skeleton was the item. A name needs
|
||||
// no definition, so round 1 offered the name and left the detail
|
||||
// blank. Round 2 (owner ruling, same day) makes the ghost choose a
|
||||
// copy rather than decline, so the popup names the copy the ghost will
|
||||
// read — `nearest_definition`'s answer, which for a buffer at the tree
|
||||
// root is the lexicographically smaller path.
|
||||
let tree = Tree::new("dup");
|
||||
tree.write("a.sv", "module dup ();\nendmodule\n");
|
||||
tree.write("b.sv", "module dup ();\nendmodule\n");
|
||||
let (_tree, ws, uri, position) = opened(tree, "module top;\n du\nendmodule\n", " du");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "dup").expect("the name is still known");
|
||||
assert_eq!(tier(item), TIER_MODULE, "{items:#?}");
|
||||
assert_eq!(item.detail.as_deref(), Some("module — a.sv"));
|
||||
}
|
||||
|
||||
/// The nearest-definition chooser, at the level `inline.rs` consumes it.
|
||||
///
|
||||
/// The rule is components, not bytes: `top_earlgrey` and `top_darjeeling`
|
||||
/// share `hw` and nothing more, and a byte-wise prefix would count the
|
||||
/// `hw/top_` they spell alike and rank the copies by a coincidence.
|
||||
#[test]
|
||||
fn the_nearest_definition_is_the_one_sharing_the_most_path_components() {
|
||||
let earlgrey = PathBuf::from("/hw/top_earlgrey/ip/ast/rtl/ast_dft.sv");
|
||||
let darjeeling = PathBuf::from("/hw/top_darjeeling/ip/ast/rtl/ast_dft.sv");
|
||||
let text = "module ast_dft ();\nendmodule\n";
|
||||
let index =
|
||||
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
|
||||
|
||||
let asking = |from: &str| {
|
||||
nearest_definition(&index, "ast_dft", Some(&PathBuf::from(from)))
|
||||
.expect("a definition")
|
||||
.to_path_buf()
|
||||
};
|
||||
assert_eq!(asking("/hw/top_earlgrey/rtl/top_earlgrey.sv"), earlgrey);
|
||||
assert_eq!(asking("/hw/top_darjeeling/rtl/top_darjeeling.sv"), darjeeling);
|
||||
// Near neither, and no path at all: the tie falls to the smaller path
|
||||
// rather than to whatever the index happens to hold first.
|
||||
assert_eq!(asking("/hw/ip/uart/rtl/uart.sv"), darjeeling);
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "ast_dft", None).expect("a definition"),
|
||||
darjeeling.as_path()
|
||||
);
|
||||
}
|
||||
|
||||
/// QA round-2 finding, fixed at lead review: a copy in the asking
|
||||
/// buffer's own directory and one in a subdirectory of it share the same
|
||||
/// number of leading components with the buffer (its filename never
|
||||
/// matches a directory), and the lexicographic tie-break alone could pick
|
||||
/// the deeper, less related copy. The real shape is opentitan's 61-way
|
||||
/// `tb`: `rstmgr/dv/tb.sv` must beat `rstmgr/dv/rstmgr_cnsty_chk/tb.sv`
|
||||
/// for a buffer in `rstmgr/dv`, even though `'r' < 't'`.
|
||||
#[test]
|
||||
fn the_direct_sibling_beats_a_deeper_copy_that_ties_on_the_shared_prefix() {
|
||||
let sibling = PathBuf::from("/hw/ip/rstmgr/dv/tb.sv");
|
||||
let deeper = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/tb.sv");
|
||||
let text = "module tb ();\nendmodule\n";
|
||||
for sources in [
|
||||
vec![(sibling.clone(), text), (deeper.clone(), text)],
|
||||
vec![(deeper.clone(), text), (sibling.clone(), text)],
|
||||
] {
|
||||
let index = WorkspaceIndex::build(sources);
|
||||
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_env.sv");
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
|
||||
sibling.as_path(),
|
||||
"the shallower copy is the nearer one"
|
||||
);
|
||||
}
|
||||
// …and depth only breaks a tie: a deeper copy that genuinely shares
|
||||
// more of the asking path still wins.
|
||||
let index = WorkspaceIndex::build(vec![(sibling.clone(), text), (deeper.clone(), text)]);
|
||||
let from = PathBuf::from("/hw/ip/rstmgr/dv/rstmgr_cnsty_chk/checker.sv");
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "tb", Some(&from)).expect("a definition"),
|
||||
deeper.as_path(),
|
||||
"sharing more components outranks being shallow"
|
||||
);
|
||||
}
|
||||
|
||||
/// The answer is a property of the paths, not of the order the index was
|
||||
/// built in — which is what makes it the same answer twice in a row, and
|
||||
/// the same answer in two editors.
|
||||
#[test]
|
||||
fn the_nearest_definition_does_not_depend_on_the_order_the_index_was_built_in() {
|
||||
let earlgrey = PathBuf::from("/hw/top_earlgrey/ast_dft.sv");
|
||||
let darjeeling = PathBuf::from("/hw/top_darjeeling/ast_dft.sv");
|
||||
let text = "module ast_dft ();\nendmodule\n";
|
||||
let forwards =
|
||||
WorkspaceIndex::build(vec![(earlgrey.clone(), text), (darjeeling.clone(), text)]);
|
||||
let backwards =
|
||||
WorkspaceIndex::build(vec![(darjeeling.clone(), text), (earlgrey.clone(), text)]);
|
||||
for index in [&forwards, &backwards] {
|
||||
let from = PathBuf::from("/hw/top_earlgrey/rtl/top.sv");
|
||||
assert_eq!(
|
||||
nearest_definition(index, "ast_dft", Some(&from)).expect("a definition"),
|
||||
earlgrey.as_path()
|
||||
);
|
||||
assert_eq!(
|
||||
nearest_definition(index, "ast_dft", None).expect("a definition"),
|
||||
darjeeling.as_path()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A module only one file declares goes through the same chooser and comes
|
||||
/// back with the file `vlog_refactor::module_definition` picks — the
|
||||
/// equivalence that says round 2 widened the twice-declared case and moved
|
||||
/// nothing else.
|
||||
#[test]
|
||||
fn one_declaration_is_chosen_exactly_as_module_definition_chooses_it() {
|
||||
let path = PathBuf::from("/rtl/sub.sv");
|
||||
let index = WorkspaceIndex::build(vec![(path.clone(), SUB)]);
|
||||
let expected = vlog_refactor::module_definition(&index, "sub").expect("one definition");
|
||||
assert_eq!(expected, path.as_path());
|
||||
for from in [None, Some(PathBuf::from("/rtl/top.sv")), Some(PathBuf::from("/other/x.sv"))] {
|
||||
assert_eq!(
|
||||
nearest_definition(&index, "sub", from.as_deref()).expect("a definition"),
|
||||
expected,
|
||||
"{from:?}"
|
||||
);
|
||||
}
|
||||
// And a name nothing declares is `None` here where it is an `Err`
|
||||
// there — the same "no answer", spelled the way each caller reads it.
|
||||
assert!(nearest_definition(&index, "nope", None).is_none());
|
||||
assert!(vlog_refactor::module_definition(&index, "nope").is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! What may be written here: the module-item gate and the statement gate,
|
||||
//! judged over the token stream's scope chain.
|
||||
//!
|
||||
//! Both are heuristics over `pairs::analyze` — the same scope matcher the
|
||||
//! begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
|
||||
//! an unbalanced one still answers. Tier 0, the templates, `inline.rs`'s
|
||||
//! ghost instantiation and `instantiate.rs` all ask these two questions, and
|
||||
//! they ask them here so there is one answer to "may an instantiation go
|
||||
//! here". The consts at the top are the whole of the grammar the gates know.
|
||||
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use super::word::line_head_is_blank;
|
||||
use crate::pairs;
|
||||
use crate::state::{first_token_from, Document};
|
||||
|
||||
/// The scopes a module instantiation may be written directly inside.
|
||||
const ITEM_SCOPES: &[&str] =
|
||||
&["module", "macromodule", "interface", "program", "generate", "begin"];
|
||||
|
||||
/// Scopes that make everything inside them something other than a module item:
|
||||
/// a subprogram body, a class body, a checker-ish declaration, a `case` arm's
|
||||
/// interior, a `fork` block.
|
||||
const NOT_ITEM_SCOPES: &[&str] = &[
|
||||
"function",
|
||||
"task",
|
||||
"class",
|
||||
"covergroup",
|
||||
"property",
|
||||
"sequence",
|
||||
"clocking",
|
||||
"specify",
|
||||
"primitive",
|
||||
"fork",
|
||||
"case",
|
||||
"casex",
|
||||
"casez",
|
||||
"randcase",
|
||||
];
|
||||
|
||||
/// The scopes a *statement* may be written directly inside. A `begin` or a
|
||||
/// `fork` qualifies only when it is procedural (see [`at_statement`]); a
|
||||
/// `function`/`task` body always does.
|
||||
const STATEMENT_SCOPES: &[&str] = &["begin", "fork", "function", "task"];
|
||||
|
||||
/// Keywords that make the `begin` after them procedural, so nothing inside it
|
||||
/// is a module item. `@` is on the list because it is the whole of what stands
|
||||
/// between `always` and its `begin`.
|
||||
const PROCEDURAL: &[&str] =
|
||||
&["always", "always_ff", "always_comb", "always_latch", "initial", "final", "@"];
|
||||
|
||||
/// Tokens that end whatever came before them, stopping the backward scan that
|
||||
/// looks for a [`PROCEDURAL`] keyword.
|
||||
const STATEMENT_END: &[&str] =
|
||||
&["begin", "end", "endcase", "join", "join_any", "join_none", "generate", ";"];
|
||||
|
||||
/// Whether a module instantiation may be written starting at `at`.
|
||||
///
|
||||
/// **Tier 0's own gate**, factored out so `inline.rs`'s ghost instantiation
|
||||
/// asks the identical question: the two features offer the same construct, and
|
||||
/// a second answer to "may an instantiation go here" would eventually disagree
|
||||
/// with this one. Both halves are here — the word must start its line, and the
|
||||
/// scope chain covering it must be one an item belongs to (see
|
||||
/// [`at_module_item`] for what that means and what it cannot see).
|
||||
pub(crate) fn at_instantiation_site(doc: &Document, at: u32) -> bool {
|
||||
if !line_head_is_blank(&doc.text, at) {
|
||||
return false;
|
||||
}
|
||||
at_module_item(doc, &enclosing_scopes(&doc.tokens, at), at)
|
||||
}
|
||||
|
||||
/// Whether `at` is somewhere a module instantiation could be written, judged
|
||||
/// over the token stream.
|
||||
///
|
||||
/// This is a **heuristic, not a parse**, and the README says exactly what it
|
||||
/// gets wrong. It reuses `pairs::analyze` — the same scope matcher the
|
||||
/// begin/end rainbow runs on — so a half-typed buffer costs nothing extra and
|
||||
/// an unbalanced one still answers. Three conditions, all necessary:
|
||||
///
|
||||
/// 1. the innermost scope open here is one of [`ITEM_SCOPES`];
|
||||
/// 2. no scope in the chain is one of [`NOT_ITEM_SCOPES`], so a `begin` inside
|
||||
/// a `function` or a `case` arm is rejected however module-ish its parent;
|
||||
/// 3. the outermost `begin` in the chain is not a procedural one — a
|
||||
/// generate-`for`'s `begin` qualifies, an `always @(...)`'s does not.
|
||||
///
|
||||
/// Parentheses close the door too: an item never starts inside one, which is
|
||||
/// what keeps a port list and a connection list out.
|
||||
pub(super) fn at_module_item(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
|
||||
let tokens = &doc.tokens;
|
||||
if tokens.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(&(innermost, opener)) = chain.first() else { return false };
|
||||
if !ITEM_SCOPES.contains(&innermost) {
|
||||
return false;
|
||||
}
|
||||
if chain.iter().any(|(keyword, _)| NOT_ITEM_SCOPES.contains(keyword)) {
|
||||
return false;
|
||||
}
|
||||
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
|
||||
if let Some(&(_, span)) = outermost_begin {
|
||||
if is_procedural(tokens, span.start) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
balanced(tokens, opener.end, at)
|
||||
}
|
||||
|
||||
/// Whether `at` is somewhere a *statement* could be written, judged over the
|
||||
/// same scope chain [`at_module_item`] reads.
|
||||
///
|
||||
/// Two ways to qualify, and they are the only two this asks about:
|
||||
///
|
||||
/// 1. the innermost open scope is a `function` or a `task`, whose body is
|
||||
/// statements all the way down; or
|
||||
/// 2. it is a `begin`/`fork` whose outermost `begin` is a procedural one — the
|
||||
/// exact inverse of the test that keeps module items out of an `always`.
|
||||
///
|
||||
/// Everything else is refused, `case` arms included: a bare `if` is not a
|
||||
/// legal case item, and a gate that guesses at one would offer a template that
|
||||
/// does not compile. Parentheses close the door here too.
|
||||
pub(super) fn at_statement(doc: &Document, chain: &[(&'static str, TextRange)], at: u32) -> bool {
|
||||
let tokens = &doc.tokens;
|
||||
if tokens.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let Some(&(innermost, opener)) = chain.first() else { return false };
|
||||
if !STATEMENT_SCOPES.contains(&innermost) {
|
||||
return false;
|
||||
}
|
||||
if innermost == "begin" || innermost == "fork" {
|
||||
let in_subprogram = chain.iter().any(|(kw, _)| *kw == "function" || *kw == "task");
|
||||
let outermost_begin = chain.iter().rev().find(|(keyword, _)| *keyword == "begin");
|
||||
let procedural = match outermost_begin {
|
||||
Some(&(_, span)) => is_procedural(tokens, span.start),
|
||||
None => false,
|
||||
};
|
||||
if !in_subprogram && !procedural {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
balanced(tokens, opener.end, at)
|
||||
}
|
||||
|
||||
/// The scopes open at `at`, innermost first, as `(keyword, opener span)`.
|
||||
pub(super) fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)> {
|
||||
let analysis = pairs::analyze(tokens);
|
||||
let mut out: Vec<(&'static str, TextRange)> = analysis
|
||||
.pairs
|
||||
.iter()
|
||||
.filter(|pair| pair.open.end <= at && at <= pair.close.start)
|
||||
.map(|pair| (pair.keyword, pair.open))
|
||||
.chain(
|
||||
analysis
|
||||
.unmatched_open
|
||||
.iter()
|
||||
.filter(|open| open.span.end <= at)
|
||||
.map(|open| (open.keyword, open.span)),
|
||||
)
|
||||
.collect();
|
||||
// Innermost first: the scope that opened last is the one we are in.
|
||||
out.sort_by_key(|(_, span)| std::cmp::Reverse(span.start));
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the `begin` starting at `offset` belongs to a procedural block.
|
||||
///
|
||||
/// Read backwards from the keyword: `always @(posedge clk) begin` reaches `@`
|
||||
/// and then `always`, `initial begin` reaches `initial`, while a generate
|
||||
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
|
||||
/// `generate begin` reaches `generate`. Whichever comes first decides.
|
||||
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
|
||||
// A token starting exactly at `offset` is the first one that starts at or
|
||||
// after it: every earlier token starts before, every later token after.
|
||||
let begin = first_token_from(tokens, offset);
|
||||
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
|
||||
return false;
|
||||
}
|
||||
for token in tokens[..begin].iter().rev() {
|
||||
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
|
||||
return true;
|
||||
}
|
||||
if STATEMENT_END.iter().any(|kw| token.text == *kw) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether every parenthesis opened between `from` and `at` was closed again.
|
||||
pub(super) fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
|
||||
let mut depth = 0i32;
|
||||
// The tokens whose start falls in `[from, at)` are a contiguous run,
|
||||
// because starts rise across the vector — so the filter this replaced was
|
||||
// reading the whole buffer to reach a window the two bounds name outright.
|
||||
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
|
||||
for token in &tokens[window] {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
depth == 0
|
||||
}
|
||||
|
||||
/// The whitespace the line holding `offset` begins with.
|
||||
pub(super) fn line_indent(text: &str, offset: u32) -> String {
|
||||
let Some(head) = text.get(..offset as usize) else { return String::new() };
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).unwrap_or("").chars().take_while(|c| *c == ' ' || *c == '\t').collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// [`is_procedural`] used to sweep the vector for the token starting at
|
||||
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
|
||||
/// two offsets name. Both now binary-search; both must answer exactly what
|
||||
/// the sweeps answered, at every byte and for every window.
|
||||
#[test]
|
||||
fn the_scope_gates_answer_what_their_sweeps_answered() {
|
||||
let text = crate::state::mixed_buffer(20);
|
||||
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
|
||||
let tokens = &doc.tokens;
|
||||
for offset in 0..=text.len() as u32 {
|
||||
let swept = tokens.iter().position(|token| token.span.start == offset);
|
||||
let searched = {
|
||||
let begin = first_token_from(tokens, offset);
|
||||
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
|
||||
};
|
||||
assert_eq!(swept, searched, "the token starting at {offset}");
|
||||
}
|
||||
// Every `begin`/`end` opener in the buffer against a spread of cursors
|
||||
// after it: the two bounds are what pick the window out.
|
||||
let openers: Vec<u32> = tokens
|
||||
.iter()
|
||||
.filter(|t| t.text == "begin" || t.text == "(")
|
||||
.map(|t| t.span.end)
|
||||
.collect();
|
||||
assert!(openers.len() > 20, "premise: plenty of windows to check");
|
||||
for from in openers {
|
||||
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
|
||||
let mut depth = 0i32;
|
||||
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
|
||||
if token.kind != TokenKind::Symbol {
|
||||
continue;
|
||||
}
|
||||
match token.text.as_str() {
|
||||
"(" => depth += 1,
|
||||
")" => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,941 @@
|
||||
//! Tiers 1 to 5: the five ordinary tiers, in the order they fill the
|
||||
//! response.
|
||||
//!
|
||||
//! What the scope chain binds, what the workspace index declares (macro
|
||||
//! names included), the templates, the keywords, and every identifier the
|
||||
//! project's token streams contain. Each is a filter over one table with the
|
||||
//! house matching rule — prefix below `FUZZY_MIN`, subsequence from it up —
|
||||
//! and each stops the moment the response is full. Tier 0 lives in
|
||||
//! `module.rs` because its planning half is a different kind of work; the
|
||||
//! member answer lives in `member.rs` because it is exclusive rather than a
|
||||
//! tier.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_types::CompletionItemKind;
|
||||
use vlog_parser::token::TokenKind;
|
||||
use vlog_parser::KEYWORDS;
|
||||
use vlog_refactor::Layout;
|
||||
use vlog_semantic::{Semantics, Symbol};
|
||||
|
||||
use super::site::line_indent;
|
||||
use super::word::Word;
|
||||
use super::{
|
||||
completion_kind, declaration_detail, Items, LIMIT, TIER_INDEX, TIER_KEYWORD, TIER_SCOPE,
|
||||
TIER_WORD,
|
||||
};
|
||||
use crate::candidates::{rank_cmp, starts_with_ignore_case, Candidate, Query, Score};
|
||||
use crate::state::{Document, Workspace};
|
||||
use crate::symbols::kind_label;
|
||||
use crate::templates::{self, Gate, Template};
|
||||
|
||||
/// Tier 1: everything the scope chain at the cursor binds.
|
||||
///
|
||||
/// 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.
|
||||
pub(super) 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;
|
||||
}
|
||||
items.simple(
|
||||
&symbol.name,
|
||||
completion_kind(symbol.kind),
|
||||
TIER_SCOPE,
|
||||
declaration_detail(doc, symbol),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every declaration the scope chain covering `offset` binds, innermost scope
|
||||
/// first, each name only once — the inner declaration shadows the outer one,
|
||||
/// which is the rule `vlog_semantic`'s own lookup follows.
|
||||
fn visible_symbols(semantics: &Semantics, offset: u32) -> Vec<&Symbol> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = HashSet::new();
|
||||
let mut at = innermost_scope(semantics, offset);
|
||||
while let Some(id) = at {
|
||||
let Some(scope) = semantics.scope(id) else { break };
|
||||
for symbol in scope.symbols.iter().filter_map(|&id| semantics.symbol(id)) {
|
||||
if seen.insert(symbol.name.as_str()) {
|
||||
out.push(symbol);
|
||||
}
|
||||
}
|
||||
at = scope.parent;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The smallest scope whose span covers `offset`.
|
||||
pub(super) fn innermost_scope(
|
||||
semantics: &Semantics,
|
||||
offset: u32,
|
||||
) -> Option<vlog_semantic::ScopeId> {
|
||||
semantics
|
||||
.scopes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, scope)| scope.span.contains(offset))
|
||||
.min_by_key(|(_, scope)| scope.span.len())
|
||||
.map(|(i, _)| vlog_semantic::ScopeId(i as u32))
|
||||
}
|
||||
|
||||
/// Tier 2: what the workspace index declares, `` `define`` names included.
|
||||
///
|
||||
/// The index names match fuzzily from [`FUZZY_MIN`](super::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*.
|
||||
pub(super) 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;
|
||||
}
|
||||
items.simple(
|
||||
&candidate.name,
|
||||
completion_kind(candidate.kind),
|
||||
TIER_INDEX,
|
||||
format!("{} — {}", kind_label(candidate.kind), candidate.detail),
|
||||
);
|
||||
}
|
||||
// Bare, with no backtick invented. A macro *use* is spelled with one and
|
||||
// the user types it (see the early return above); the places a macro name
|
||||
// is written without one — `` `ifdef NAME ``, `` `undef NAME `` — are
|
||||
// exactly where this item is the right text.
|
||||
for entry in ws.candidates().macros(&word.text) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(&entry.name, CompletionItemKind::CONSTANT, TIER_INDEX, entry.detail.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 3: the statement, item and declaration templates.
|
||||
///
|
||||
/// Above the keywords because a user who typed `if` almost always wants
|
||||
/// `if (…) begin … end` rather than the three letters they already typed, and
|
||||
/// below both semantic tiers because a name the code actually declares beats a
|
||||
/// skeleton every time. The templates a *position* rules out never reach the
|
||||
/// list at all, so the ranking argument only has to hold where they do.
|
||||
pub(super) fn template_tier(
|
||||
items: &mut Items,
|
||||
ws: &Workspace,
|
||||
doc: &Document,
|
||||
word: &Word,
|
||||
snippets: bool,
|
||||
at_item: bool,
|
||||
at_statement: bool,
|
||||
) {
|
||||
if !at_item && !at_statement {
|
||||
return;
|
||||
}
|
||||
let layout = layout_at(ws, doc, word.start);
|
||||
let dialect = templates::dialect(doc.path.as_deref());
|
||||
for template in templates::for_dialect(dialect) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
if !offered(template, at_item, at_statement) {
|
||||
continue;
|
||||
}
|
||||
if !starts_with_ignore_case(template.prefix, &word.text) {
|
||||
continue;
|
||||
}
|
||||
items.template(template, &layout, snippets);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a template's gate lets it be written where the cursor is.
|
||||
fn offered(template: &Template, at_item: bool, at_statement: bool) -> bool {
|
||||
match template.gate {
|
||||
Gate::Statement | Gate::ElseTail => at_statement,
|
||||
Gate::Item => at_item,
|
||||
// A declaration is a module item and a block item both.
|
||||
Gate::Declaration => at_item || at_statement,
|
||||
}
|
||||
}
|
||||
|
||||
/// How generated text is indented at `offset`: the line's own indentation, and
|
||||
/// one step as `lucisv.indent` spells it.
|
||||
///
|
||||
/// Private from 2026-08-25 to 2026-09-02: `inline.rs` stopped sharing it when
|
||||
/// ghost text moved to *relative* indentation and let the editor place it
|
||||
/// (see `inline.rs`'s `render`). `pub(crate)` again for `instantiate.rs`,
|
||||
/// whose `workspace/applyEdit` is plain text no editor re-indents, so it needs
|
||||
/// exactly this — the real indentation of the real line.
|
||||
pub(crate) fn layout_at(ws: &Workspace, doc: &Document, offset: u32) -> Layout {
|
||||
let step = " ".repeat(ws.client_settings().indent.unwrap_or(2));
|
||||
Layout { base: line_indent(&doc.text, offset), step }
|
||||
}
|
||||
|
||||
/// Tier 4: every reserved word the lexer knows.
|
||||
pub(super) fn keyword_tier(items: &mut Items, word: &Word) {
|
||||
for keyword in KEYWORDS.iter().filter(|kw| starts_with_ignore_case(kw, &word.text)) {
|
||||
if items.full() {
|
||||
break;
|
||||
}
|
||||
items.simple(keyword, CompletionItemKind::KEYWORD, TIER_KEYWORD, "keyword".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// Tier 5: identifiers used anywhere in the project scope.
|
||||
///
|
||||
/// 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.
|
||||
pub(super) 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 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;
|
||||
}
|
||||
items.simple(name, CompletionItemKind::TEXT, TIER_WORD, "used in this project".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<Item = &str> {
|
||||
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('\\'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::completion::harness::*;
|
||||
use crate::completion::*;
|
||||
use crate::uri::path_to_uri;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 3 — templates
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Only the templates — tier 3.
|
||||
fn template_labels(items: &[CompletionItem]) -> Vec<&str> {
|
||||
items
|
||||
.iter()
|
||||
.filter(|item| tier(item) == TIER_TEMPLATE)
|
||||
.map(|item| item.label.as_str())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The items offered at `needle`'s end in a buffer named `file`.
|
||||
fn offering(name: &str, file: &str, top: &str, needle: &str) -> Vec<CompletionItem> {
|
||||
let (_tree, ws, uri, position) = opened_named(Tree::new(name), file, top, needle);
|
||||
items(completions(&ws, &uri, position, true))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_statement_template_expands_where_a_statement_may_be_written() {
|
||||
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
|
||||
let items = offering("stmt", "top.sv", top, " if");
|
||||
let item = find(&items, "if begin/end").expect("the if template");
|
||||
assert_eq!(item.kind, Some(CompletionItemKind::SNIPPET));
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
|
||||
assert_eq!(item.filter_text.as_deref(), Some("if"), "the client filters on what is typed");
|
||||
assert_eq!(
|
||||
inserted(item),
|
||||
"if (${1:cond}) begin\n $0\n end",
|
||||
"the site's own indentation, the condition first and the body last"
|
||||
);
|
||||
assert!(template_labels(&items).contains(&"if/else"), "{:?}", template_labels(&items));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_never_swallows_the_keyword_it_is_reached_by() {
|
||||
// Dedup is by label, so the labels are prose on purpose: `if` the
|
||||
// keyword and `if begin/end` the template are two items, in that
|
||||
// order of specificity.
|
||||
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
|
||||
let items = offering("both", "top.sv", top, " if");
|
||||
let keyword = find(&items, "if").expect("the bare keyword");
|
||||
let template = find(&items, "if begin/end").expect("the template");
|
||||
assert_eq!(tier(keyword), TIER_KEYWORD);
|
||||
assert_eq!(tier(template), TIER_TEMPLATE);
|
||||
assert!(template.sort_text < keyword.sort_text, "a template outranks the bare word");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_template_ranks_below_a_name_the_code_declares() {
|
||||
let top = "\
|
||||
module top;
|
||||
logic if_enable;
|
||||
always_comb begin
|
||||
if
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let items = offering("rank", "top.sv", top, " if");
|
||||
let symbol = find(&items, "if_enable").expect("a declaration in scope");
|
||||
let template = find(&items, "if begin/end").expect("the template");
|
||||
assert_eq!(tier(symbol), TIER_SCOPE);
|
||||
assert!(symbol.sort_text < template.sort_text, "a real name beats a skeleton");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statement_templates_and_item_templates_swap_places_with_the_position() {
|
||||
// One prefix, `i`, reaching `if` in one place and `initial` in the
|
||||
// other — so this is the gate and not the filter.
|
||||
let inside = offering(
|
||||
"posstmt",
|
||||
"top.sv",
|
||||
"module top;\n always_comb begin\n i\n end\nendmodule\n",
|
||||
" i",
|
||||
);
|
||||
assert!(template_labels(&inside).contains(&"if begin/end"));
|
||||
assert!(
|
||||
!template_labels(&inside).contains(&"initial begin/end"),
|
||||
"an initial block is not a statement: {:?}",
|
||||
template_labels(&inside)
|
||||
);
|
||||
|
||||
let at_item = offering("positem", "top.sv", "module top;\n i\nendmodule\n", " i");
|
||||
assert!(template_labels(&at_item).contains(&"initial begin/end"));
|
||||
assert!(
|
||||
!template_labels(&at_item).contains(&"if begin/end"),
|
||||
"a bare if is not a module item: {:?}",
|
||||
template_labels(&at_item)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_always_template_is_a_module_item_and_nothing_else() {
|
||||
let at_item = offering("alwitem", "top.sv", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&at_item),
|
||||
["always_ff @(posedge clk)", "always_ff with reset", "always_comb begin/end"],
|
||||
"and `alw` finds every one of them"
|
||||
);
|
||||
|
||||
let inside = offering(
|
||||
"alwstmt",
|
||||
"top.sv",
|
||||
"module top;\n always_comb begin\n alw\n end\nendmodule\n",
|
||||
" alw",
|
||||
);
|
||||
assert!(template_labels(&inside).is_empty(), "{:?}", template_labels(&inside));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_declaration_template_is_offered_as_an_item_and_as_a_block_item() {
|
||||
let at_item = offering("declitem", "top.sv", "module top;\n log\nendmodule\n", " log");
|
||||
assert_eq!(template_labels(&at_item), ["logic name;", "logic [N:0] name;"]);
|
||||
|
||||
let inside = offering(
|
||||
"declstmt",
|
||||
"top.sv",
|
||||
"module top;\n always_comb begin\n log\n end\nendmodule\n",
|
||||
" log",
|
||||
);
|
||||
assert_eq!(template_labels(&inside), ["logic name;", "logic [N:0] name;"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_name_decides_which_dialect_is_offered() {
|
||||
let sv = offering("dialectsv", "top.sv", "module top;\n l\nendmodule\n", " l");
|
||||
assert!(template_labels(&sv).contains(&"logic name;"));
|
||||
assert!(template_labels(&sv).contains(&"localparam int NAME = 0;"));
|
||||
|
||||
let v = offering("dialectv", "top.v", "module top;\n l\nendmodule\n", " l");
|
||||
assert!(!template_labels(&v).contains(&"logic name;"), "`logic` is not Verilog");
|
||||
assert!(template_labels(&v).contains(&"localparam integer NAME = 0;"));
|
||||
|
||||
let reg = offering("dialectreg", "top.v", "module top;\n r\nendmodule\n", " r");
|
||||
assert_eq!(template_labels(®), ["reg name;", "reg [N:0] name;"]);
|
||||
let sv_reg = offering("dialectsvreg", "top.sv", "module top;\n r\nendmodule\n", " r");
|
||||
assert!(template_labels(&sv_reg).is_empty(), "no `reg` template in a .sv file");
|
||||
|
||||
let always = offering("dialectalw", "top.v", "module top;\n alw\nendmodule\n", " alw");
|
||||
assert_eq!(
|
||||
template_labels(&always),
|
||||
["always @(posedge clk)", "always @(posedge clk or negedge rst_n)", "always @(*)"],
|
||||
"and no always_ff, which a .v file's compiler would reject"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_else_template_follows_an_end_on_the_same_line() {
|
||||
let top = "\
|
||||
module top;
|
||||
always_comb begin
|
||||
if (a) begin
|
||||
end el
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let items = offering("elsetail", "top.sv", top, "end el");
|
||||
assert_eq!(template_labels(&items), ["else if", "else begin/end"]);
|
||||
assert_eq!(
|
||||
inserted(find(&items, "else if").expect("the else-if template")),
|
||||
"else if (${1:cond}) begin\n $0\n end"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_word_in_the_middle_of_a_line_starts_no_statement() {
|
||||
// The other half of the same rule: `x = if` is an expression, not a
|
||||
// place a template belongs — and the general tiers still answer there.
|
||||
let top = "module top;\n always_comb begin\n x = if\n end\nendmodule\n";
|
||||
let items = offering("midline", "top.sv", top, "x = if");
|
||||
assert!(template_labels(&items).is_empty(), "{:?}", template_labels(&items));
|
||||
assert!(find(&items, "if").is_some(), "the keyword tier still answers");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_template_is_offered_where_a_statement_cannot_go() {
|
||||
for (name, top, needle) in [
|
||||
// A generate block is item position, not statement position.
|
||||
("generate", "module top;\n generate\n if\n endgenerate\nendmodule\n", " if"),
|
||||
// A `case` arm wants `label:`, not a bare statement.
|
||||
(
|
||||
"casearm",
|
||||
"module top;\n always_comb begin\n case (s)\n if\n endcase\n end\nendmodule\n",
|
||||
" if",
|
||||
),
|
||||
// Nothing at all is open here.
|
||||
("toplevel", "if\nmodule top;\nendmodule\n", "if"),
|
||||
// A port list is not a statement, however much it starts a line.
|
||||
("ports", "module top (\n if\n);\nendmodule\n", " if"),
|
||||
] {
|
||||
let items = offering(name, "top.sv", top, needle);
|
||||
assert!(template_labels(&items).is_empty(), "{name}: {:?}", template_labels(&items));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_subprogram_body_is_statement_position() {
|
||||
for (name, top, needle) in [
|
||||
("function", "module top;\n function int f();\n if\n endfunction\nendmodule\n", " if"),
|
||||
("task", "module top;\n task t();\n if\n endtask\nendmodule\n", " if"),
|
||||
(
|
||||
"fnbegin",
|
||||
"module top;\n function int f();\n begin\n if\n end\n endfunction\nendmodule\n",
|
||||
" if",
|
||||
),
|
||||
] {
|
||||
let items = offering(name, "top.sv", top, needle);
|
||||
assert!(template_labels(&items).contains(&"if begin/end"), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_templated_is_offered_inside_a_comment() {
|
||||
let top = "module top;\n always_comb begin\n // if\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("tmplcomment", top, "// if");
|
||||
assert!(completions(&ws, &uri, position, true).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_snippet_support_gets_the_template_filled_in() {
|
||||
let top = "module top;\n always_comb begin\n if\n end\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("tmplplain", top, " if");
|
||||
let items = items(completions(&ws, &uri, position, false));
|
||||
let item = find(&items, "if begin/end").expect("the if template");
|
||||
assert_eq!(item.insert_text_format, Some(InsertTextFormat::PLAIN_TEXT));
|
||||
let text = inserted(item);
|
||||
assert!(!text.contains('$'), "no tabstop syntax may reach a plain client: {text}");
|
||||
assert_eq!(text, "if (cond) begin\n\n end");
|
||||
let probe = format!("module p;\n always_comb begin\n {text}\n end\nendmodule\n");
|
||||
assert!(
|
||||
vlog_parser::parse_source_tolerant(&probe).1.is_empty(),
|
||||
"the inserted text must parse: {text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_templates_documentation_shows_what_it_expands_to() {
|
||||
let top = "module top;\n alw\nendmodule\n";
|
||||
let items = offering("tmpldocs", "top.sv", top, " alw");
|
||||
let item = find(&items, "always_comb begin/end").expect("the always_comb template");
|
||||
let Some(Documentation::MarkupContent(docs)) = &item.documentation else {
|
||||
panic!("markdown documentation");
|
||||
};
|
||||
// Fenced with the language id the extension's TextMate grammar is
|
||||
// registered for, so the panel renders highlighted rather than grey.
|
||||
assert!(docs.value.starts_with("```systemverilog\n"), "{}", docs.value);
|
||||
assert!(docs.value.contains("always_comb begin\n\nend"), "{}", docs.value);
|
||||
assert_eq!(item.detail.as_deref(), Some("combinational block — template"));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tier 4 — keywords
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
|
||||
fn every_keyword_the_lexer_knows_is_offered() {
|
||||
let top = "module top;\n assign x = alw\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("keyword", top, "= alw");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let keywords: Vec<&str> =
|
||||
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
|
||||
assert_eq!(keywords, ["always", "always_comb", "always_ff", "always_latch"]);
|
||||
let always = find(&items, "always").expect("`always`");
|
||||
assert_eq!(always.kind, Some(CompletionItemKind::KEYWORD));
|
||||
assert_eq!(inserted(always), "always");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_keyword_tier_is_exactly_the_lexers_list() {
|
||||
let top = "module top;\n assign x = \nendmodule\n";
|
||||
let (_tree, ws, uri, position) = asking("allkeywords", top, "= ");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let offered: HashSet<&str> =
|
||||
items.iter().filter(|i| tier(i) == TIER_KEYWORD).map(|i| i.label.as_str()).collect();
|
||||
let known: HashSet<&str> = KEYWORDS.iter().copied().collect();
|
||||
assert_eq!(offered, known, "no keyword may be missing and none invented");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// tiers, ordering and dedup
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_tiers_are_ordered_scope_then_project_then_keywords_then_words() {
|
||||
let tree = Tree::new("tiers");
|
||||
tree.write("pkg.sv", "package w_pkg;\n localparam K = 1;\nendpackage\n");
|
||||
tree.write("other.sv", "module other;\n logic w_elsewhere;\nendmodule\n");
|
||||
let top = "module top;\n logic w_local;\n assign x = w\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= w");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
|
||||
assert_eq!(tier(find(&items, "w_local").expect("in scope")), TIER_SCOPE);
|
||||
assert_eq!(tier(find(&items, "w_pkg").expect("a package")), TIER_INDEX);
|
||||
assert_eq!(tier(find(&items, "wire").expect("a keyword")), TIER_KEYWORD);
|
||||
assert_eq!(tier(find(&items, "w_elsewhere").expect("a project word")), TIER_WORD);
|
||||
|
||||
let scope = find(&items, "w_local").expect("in scope");
|
||||
let word = find(&items, "w_elsewhere").expect("a project word");
|
||||
assert!(scope.sort_text < word.sort_text, "the client sorts scope above words");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_that_is_both_in_scope_and_a_project_word_is_offered_once() {
|
||||
let tree = Tree::new("dedup");
|
||||
// The same name, declared here and used elsewhere in the project.
|
||||
tree.write("other.sv", "module other;\n logic shared_name;\nendmodule\n");
|
||||
let top = "module top;\n logic shared_name;\n assign x = shared\nendmodule\n";
|
||||
let (_tree, ws, uri, position) = opened(tree, top, "= shared");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let hits: Vec<&CompletionItem> =
|
||||
items.iter().filter(|i| i.label == "shared_name").collect();
|
||||
assert_eq!(hits.len(), 1, "{hits:#?}");
|
||||
assert_eq!(tier(hits[0]), TIER_SCOPE, "the semantic tier wins");
|
||||
assert_eq!(hits[0].kind, Some(CompletionItemKind::VARIABLE), "and its real kind with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_visible_declaration_carries_its_kind_and_the_line_it_was_written_on() {
|
||||
let top = "\
|
||||
module top #(parameter int WIDTH = 8) (input logic clk);
|
||||
typedef logic [1:0] pair_t;
|
||||
logic [WIDTH-1:0] data;
|
||||
function int f(); return 0; endfunction
|
||||
assign x =
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("kinds", top, "assign x =");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let kind = |label: &str| find(&items, label).unwrap_or_else(|| panic!("{label}")).kind;
|
||||
assert_eq!(kind("WIDTH"), Some(CompletionItemKind::CONSTANT));
|
||||
assert_eq!(kind("clk"), Some(CompletionItemKind::FIELD));
|
||||
assert_eq!(kind("pair_t"), Some(CompletionItemKind::TYPE_PARAMETER));
|
||||
assert_eq!(kind("data"), Some(CompletionItemKind::VARIABLE));
|
||||
assert_eq!(kind("f"), Some(CompletionItemKind::FUNCTION));
|
||||
assert_eq!(
|
||||
find(&items, "data").expect("data").detail.as_deref(),
|
||||
Some("logic [WIDTH-1:0] data;"),
|
||||
"the declaration as written"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_what_the_scope_chain_reaches_is_in_the_semantic_tier() {
|
||||
// `inner` is declared in a block the cursor is not in, so it may only
|
||||
// arrive as a project word — never as a visible declaration.
|
||||
let top = "\
|
||||
module top;
|
||||
initial begin : b
|
||||
integer inner_only;
|
||||
end
|
||||
initial begin
|
||||
x = inner
|
||||
end
|
||||
endmodule
|
||||
";
|
||||
let (_tree, ws, uri, position) = asking("scopewalk", top, "x = inner");
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
let item = find(&items, "inner_only").expect("known as a word at least");
|
||||
assert_eq!(tier(item), TIER_WORD, "{item:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 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<CompletionResponse> {
|
||||
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]
|
||||
fn another_open_buffer_overlays_disk_once_the_index_is_rebuilt() {
|
||||
let tree = Tree::new("overlay");
|
||||
let other = tree.write("other.sv", "module other;\n logic on_disk_name;\nendmodule\n");
|
||||
let top = "module top;\n assign x = ov\nendmodule\n";
|
||||
let (_tree, mut ws, uri, position) = opened(tree, top, "= ov");
|
||||
|
||||
let other_uri = path_to_uri(&other).expect("uri");
|
||||
ws.set_document(other_uri, "module other;\n logic ov_in_buffer;\nendmodule\n".to_string());
|
||||
ws.rebuild_index();
|
||||
let items = items(completions(&ws, &uri, position, true));
|
||||
assert!(labels(&items).contains(&"ov_in_buffer"), "{:?}", labels(&items));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! What is typed: the identifier run ending at the cursor and what stands
|
||||
//! around it — a backtick, a `.` or a `::`, and the spine a separator
|
||||
//! follows.
|
||||
//!
|
||||
//! Everything here reads the buffer's *text* backwards from the cursor and
|
||||
//! nothing else; the token-stream questions (is this an item position, a
|
||||
//! statement position) are `site.rs`'s. The one shape decision made here is
|
||||
//! `Word::sep`: a separator says the response is a member list and nothing
|
||||
//! else, which is why the spine is read this early.
|
||||
|
||||
use vlog_parser::TextRange;
|
||||
|
||||
use crate::state::Document;
|
||||
|
||||
/// What may stand between the start of a line and a statement: the `end` of
|
||||
/// the block before it and the `else` that chains onto it. Anything else on
|
||||
/// the line means the word being typed is part of an expression, not the start
|
||||
/// of a statement.
|
||||
const STATEMENT_HEADS: &[&str] = &["end", "else", "end else"];
|
||||
|
||||
/// The identifier the user is part-way through typing, and what stands around
|
||||
/// it.
|
||||
pub(super) struct Word {
|
||||
/// The identifier run, backtick excluded. Empty when the cursor follows
|
||||
/// something that is not an identifier character.
|
||||
pub(super) text: String,
|
||||
/// Where the run starts — the byte after the backtick, when there is one.
|
||||
pub(super) start: u32,
|
||||
/// Whether a `` ` `` immediately precedes the run, making this a macro
|
||||
/// name being typed and nothing else.
|
||||
pub(super) backtick: bool,
|
||||
/// Whether nothing but whitespace precedes the run on its line.
|
||||
///
|
||||
/// Half of the *module* gate, and deliberately blunt: an instantiation is
|
||||
/// written at the start of a line, and a word that is not (`assign x =
|
||||
/// fo|`, `logic fo|`, `.clk(cl|`) is somewhere a module name would be
|
||||
/// wrong. It costs the rare user who writes two items on one line their
|
||||
/// skeleton — a far better failure than offering a fifteen-line
|
||||
/// instantiation in the middle of an expression. Every other tier ignores
|
||||
/// it: a name is a name wherever it is written.
|
||||
pub(super) at_line_start: bool,
|
||||
/// Whether the only thing before the run on its line is [`STATEMENT_HEADS`]
|
||||
/// — the `end` a statement follows, or the `else` it hangs off.
|
||||
///
|
||||
/// Half of the *template* gate, and the reason `end else if` completes: a
|
||||
/// statement is written at the start of a line or right after one of those
|
||||
/// two words, and nowhere else.
|
||||
pub(super) statement_head: bool,
|
||||
/// The `.` or `::` the run immediately follows, when it follows one.
|
||||
///
|
||||
/// Its presence alone decides the shape of the whole response: a
|
||||
/// separator says the user is naming a **member** of what stands before
|
||||
/// it, and nothing else may be written there — so the member answer is
|
||||
/// exclusive, exactly as the backtick's is. A lone `:` (a case item, a
|
||||
/// label, a ternary) is not a separator and is `None`.
|
||||
pub(super) sep: Option<Sep>,
|
||||
/// What stands before the separator, when it is a spine this can read.
|
||||
/// `None` with a `sep` set means the response is nothing at all: there is
|
||||
/// a member question here and no head to answer it about.
|
||||
pub(super) spine: Option<Spine>,
|
||||
}
|
||||
|
||||
/// The two separators that make the run after them a member name.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Sep {
|
||||
/// `handle.`, `vif.cb.`, `this.` — a member of a *value*'s type.
|
||||
Dot,
|
||||
/// `pkg::`, `cls::` — a member of a named unit.
|
||||
Scope,
|
||||
}
|
||||
|
||||
/// The head of a member access as the buffer spells it: the first identifier
|
||||
/// of the chain, and the names between it and the cursor.
|
||||
///
|
||||
/// `item.hdr.` is `head = "item"`, `mids = ["hdr"]` — exactly the two
|
||||
/// arguments [`vlog_semantic::Semantics::member_site`] takes, because they
|
||||
/// are exactly what `bind.rs`'s own `spine` records for the same expression.
|
||||
/// For [`Sep::Scope`] the head is the whole `::` path (`pkg`, `pkg::cls`) and
|
||||
/// `mids` is empty.
|
||||
pub(super) struct Spine {
|
||||
pub(super) head: String,
|
||||
pub(super) mids: Vec<String>,
|
||||
}
|
||||
|
||||
impl Word {
|
||||
/// The bytes a completion replaces: the word as typed.
|
||||
pub(super) fn range(&self, cursor: u32) -> TextRange {
|
||||
TextRange::new(self.start, cursor)
|
||||
}
|
||||
}
|
||||
|
||||
/// The identifier run ending at the cursor, and the shape of the line it sits
|
||||
/// on. `None` only when the cursor is not on a character boundary of the text
|
||||
/// the server holds.
|
||||
pub(super) fn typed_word(doc: &Document, cursor: u32) -> Option<Word> {
|
||||
let text = doc.text.get(..cursor as usize)?;
|
||||
let head = text.trim_end_matches(is_ident_char);
|
||||
let start = head.len();
|
||||
let backtick = head.ends_with('`');
|
||||
let bare = match backtick {
|
||||
true => head.get(..head.len() - 1)?,
|
||||
false => head,
|
||||
};
|
||||
let line_start = bare.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
let head = bare.get(line_start..)?;
|
||||
let at_line_start = !backtick && line_head_is_blank(&doc.text, start as u32);
|
||||
// `end else` and `end else` are the same head; nothing else is compared,
|
||||
// so one `split_whitespace` join is the whole normalization needed.
|
||||
let words = head.split_whitespace().collect::<Vec<&str>>().join(" ");
|
||||
let statement_head = !backtick && STATEMENT_HEADS.contains(&words.as_str());
|
||||
// A backtick admits only a macro name, and a macro name follows no
|
||||
// separator, so the two questions never both apply.
|
||||
let (sep, spine) = match backtick {
|
||||
true => (None, None),
|
||||
false => separator(bare),
|
||||
};
|
||||
Some(Word {
|
||||
text: text.get(start..)?.to_string(),
|
||||
start: start as u32,
|
||||
backtick,
|
||||
at_line_start,
|
||||
statement_head,
|
||||
sep,
|
||||
spine,
|
||||
})
|
||||
}
|
||||
|
||||
/// The separator `before` ends with, and the head spine standing before that.
|
||||
///
|
||||
/// `::` is checked first, so a `pkg::` is never read as the lone `:` of a
|
||||
/// case item, a block label or a ternary — that one is deliberately **not** a
|
||||
/// separator, and a request there falls through to the ordinary six tiers
|
||||
/// exactly as it always did.
|
||||
fn separator(before: &str) -> (Option<Sep>, Option<Spine>) {
|
||||
if let Some(rest) = before.strip_suffix("::") {
|
||||
return (Some(Sep::Scope), scope_head(rest));
|
||||
}
|
||||
if let Some(rest) = before.strip_suffix('.') {
|
||||
return (Some(Sep::Dot), dot_spine(rest));
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
/// The `::` path ending at `before`: `pkg`, `pkg::cls`.
|
||||
fn scope_head(before: &str) -> Option<Spine> {
|
||||
let mut segments = Vec::new();
|
||||
let mut rest = before;
|
||||
loop {
|
||||
let (head, name) = split_ident(rest)?;
|
||||
segments.push(name.to_string());
|
||||
match head.strip_suffix("::") {
|
||||
Some(next) => rest = next,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
segments.reverse();
|
||||
Some(Spine { head: segments.join("::"), mids: Vec::new() })
|
||||
}
|
||||
|
||||
/// The `.`-joined spine ending at `before`: `item`, `cfg.vif`, `q[i]`,
|
||||
/// `this`, `super`.
|
||||
///
|
||||
/// **What it reads, and nothing else**: identifiers joined by `.`, each
|
||||
/// optionally carrying balanced `[…]` index suffixes, which are stripped —
|
||||
/// `q[i].` and `arr[3][k].` name a member of the element type, which is the
|
||||
/// declared type name either way. Everything else answers `None`, and `None`
|
||||
/// means the response is nothing at all rather than a guess: a call
|
||||
/// (`f().b`), a cast, a concatenation, a macro invocation, a `::`-qualified
|
||||
/// head (`pkg::cls.`, which is not how a class member is written anyway), and
|
||||
/// whitespace anywhere in the spine (`a . b`, legal SystemVerilog nobody
|
||||
/// writes — refusing it costs a popup, accepting it would mean deciding where
|
||||
/// an expression ends by scanning backwards over arbitrary text).
|
||||
fn dot_spine(before: &str) -> Option<Spine> {
|
||||
let mut segments: Vec<String> = Vec::new();
|
||||
let mut rest = before;
|
||||
loop {
|
||||
let (head, name) = split_ident(strip_indices(rest)?)?;
|
||||
segments.push(name.to_string());
|
||||
match head.strip_suffix('.') {
|
||||
Some(next) => rest = next,
|
||||
None => {
|
||||
// A head reached through `::` is a unit, not a value, and
|
||||
// `member_site` resolves the head on the lexical chain.
|
||||
if head.ends_with(':') {
|
||||
return None;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
segments.reverse();
|
||||
let mut mids = segments;
|
||||
let head = mids.remove(0);
|
||||
Some(Spine { head, mids })
|
||||
}
|
||||
|
||||
/// `text` split at the start of the identifier run it ends with, as
|
||||
/// (what precedes it, the identifier). `None` when it does not end with one,
|
||||
/// or when the run starts with a digit — that is a number, not a name.
|
||||
fn split_ident(text: &str) -> Option<(&str, &str)> {
|
||||
let head = text.trim_end_matches(is_ident_char);
|
||||
let name = text.get(head.len()..)?;
|
||||
if name.is_empty() || name.starts_with(|c: char| c.is_ascii_digit()) {
|
||||
return None;
|
||||
}
|
||||
Some((head, name))
|
||||
}
|
||||
|
||||
/// `text` with every balanced `[…]` it ends with removed. `None` when a `]`
|
||||
/// has no matching `[` — an expression this cannot read, so nothing is
|
||||
/// offered for it.
|
||||
fn strip_indices(text: &str) -> Option<&str> {
|
||||
let mut rest = text;
|
||||
while rest.ends_with(']') {
|
||||
let mut depth = 0usize;
|
||||
let mut opened = None;
|
||||
for (i, byte) in rest.bytes().enumerate().rev() {
|
||||
match byte {
|
||||
b']' => depth += 1,
|
||||
b'[' => {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
opened = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
rest = rest.get(..opened?)?;
|
||||
}
|
||||
Some(rest)
|
||||
}
|
||||
|
||||
fn is_ident_char(ch: char) -> bool {
|
||||
ch.is_ascii_alphanumeric() || ch == '_' || ch == '$'
|
||||
}
|
||||
|
||||
/// Whether nothing but indentation stands before `at` on its line — half of
|
||||
/// the module gate, shared by [`typed_word`] and
|
||||
/// [`at_instantiation_site`](super::site::at_instantiation_site).
|
||||
pub(super) fn line_head_is_blank(text: &str, at: u32) -> bool {
|
||||
let Some(head) = text.get(..at as usize) else { return false };
|
||||
let line_start = head.rfind('\n').map_or(0, |newline| newline + 1);
|
||||
head.get(line_start..).is_some_and(|head| head.chars().all(|c| c == ' ' || c == '\t'))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,188 @@
|
||||
//! Reading a burst of messages before any of it is served.
|
||||
//!
|
||||
//! `lsp-server` hands messages over a rendezvous channel, one at a time; the
|
||||
//! forwarder here moves them onto a queue of our own so that "everything the
|
||||
//! client has already sent" is a question with an answer. The rest of the
|
||||
//! file reads a burst without handling anything in it: which requests it
|
||||
//! cancels, which files it opens, and — for a `didOpen` — whether the index
|
||||
//! scope grew, stayed, or has to be rebuilt. The loop in `mod.rs` and the
|
||||
//! mid-scan drain in `index.rs` both read bursts through here, which is why
|
||||
//! this is its own file rather than part of either.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use lsp_server::{Connection, Message, RequestId, Response};
|
||||
use lsp_types::notification::{Cancel, DidOpenTextDocument, Notification as _};
|
||||
use lsp_types::request::{Request as _, Shutdown};
|
||||
use lsp_types::{CancelParams, NumberOrString};
|
||||
|
||||
use super::dispatch::document_uri;
|
||||
|
||||
/// Whether this message is the `shutdown` request. `lsp-server` keeps its own
|
||||
/// answer to that question private, so it is asked here by method name — the
|
||||
/// same name `handle_shutdown` matches on.
|
||||
pub(super) fn is_shutdown(message: &Message) -> bool {
|
||||
matches!(message, Message::Request(request) if request.method == Shutdown::METHOD)
|
||||
}
|
||||
|
||||
/// Move the incoming messages onto a queue of our own, and report it.
|
||||
///
|
||||
/// Necessary because `lsp-server`'s transport hands messages over
|
||||
/// *rendezvous* channels — `bounded(0)`. Its reader thread parks holding one
|
||||
/// message until this loop takes it, so a client's backlog never sits on
|
||||
/// `connection.receiver` at all: it sits in the OS pipe, invisible and one
|
||||
/// message deep. Forwarding onto an unbounded queue is what makes "everything
|
||||
/// already sent" observable without blocking, which is the whole premise of
|
||||
/// [`burst`] — and of the drain a scan does between two of its files.
|
||||
///
|
||||
/// The forwarder stops at `shutdown` and never reads past it, because
|
||||
/// `handle_shutdown` reads the `exit` notification off the *connection*
|
||||
/// itself — a forwarder that kept going would steal it and strand the
|
||||
/// handshake for thirty seconds. It owns nothing but messages in flight and
|
||||
/// touches no server state — and it never parses, which is why it is the one
|
||||
/// thread the server spawns without `vlog_parser::PARSE_STACK_SIZE`
|
||||
/// (`docs/features/recursion-limit`).
|
||||
pub(super) fn forward(
|
||||
connection: &Connection,
|
||||
) -> (std::sync::mpsc::Sender<Message>, std::sync::mpsc::Receiver<Message>) {
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
let source = connection.receiver.clone();
|
||||
let ours = sender.clone();
|
||||
// A failed spawn would leave the server unable to receive anything at
|
||||
// all; there is nothing useful to do with that but let `run` end when the
|
||||
// queue's sender is dropped.
|
||||
let _ = std::thread::Builder::new().name("lucisv-queue".to_string()).spawn(move || {
|
||||
while let Ok(message) = source.recv() {
|
||||
let last = is_shutdown(&message);
|
||||
if sender.send(message).is_err() || last {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
(ours, receiver)
|
||||
}
|
||||
|
||||
/// `first` plus everything already waiting on the queue behind it — the
|
||||
/// client's backlog, in arrival order. Never blocks: what is not there yet
|
||||
/// belongs to the next burst.
|
||||
pub(super) fn burst(queue: &std::sync::mpsc::Receiver<Message>, first: Message) -> Vec<Message> {
|
||||
let mut batch = vec![first];
|
||||
while let Ok(message) = queue.try_recv() {
|
||||
batch.push(message);
|
||||
}
|
||||
batch
|
||||
}
|
||||
|
||||
/// The ids this burst cancels: every `$/cancelRequest` in it that names a
|
||||
/// request the burst *also* carries.
|
||||
///
|
||||
/// A cancel naming anything else is dropped right here — it refers to a
|
||||
/// request answered in some earlier burst, or to one this server never
|
||||
/// received, and either way there is nothing left to cancel. That is what
|
||||
/// keeps this from becoming a set that grows for the life of the session.
|
||||
pub(super) fn cancelled_in(batch: &[Message]) -> HashSet<RequestId> {
|
||||
let queued: HashSet<&RequestId> = batch
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) => Some(&request.id),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
batch.iter().filter_map(cancelled_id).filter(|id| queued.contains(id)).collect()
|
||||
}
|
||||
|
||||
/// The request id a `$/cancelRequest` names, or `None` for any other message.
|
||||
/// Both id forms the protocol allows are read; a cancel whose params do not
|
||||
/// parse is dropped, because there is no id to act on.
|
||||
fn cancelled_id(message: &Message) -> Option<RequestId> {
|
||||
let Message::Notification(notification) = message else { return None };
|
||||
if notification.method != Cancel::METHOD {
|
||||
return None;
|
||||
}
|
||||
let params: CancelParams = serde_json::from_value(notification.params.clone()).ok()?;
|
||||
Some(match params.id {
|
||||
NumberOrString::Number(number) => RequestId::from(number),
|
||||
NumberOrString::String(text) => RequestId::from(text),
|
||||
})
|
||||
}
|
||||
|
||||
/// What a cancelled request is answered with. Every request gets exactly one
|
||||
/// response, cancelled or not — the protocol's own `RequestCancelled`
|
||||
/// (-32800), which a client reads as "the one you asked me to drop" rather
|
||||
/// than as a failure worth showing the user.
|
||||
pub(super) fn cancelled_response(id: RequestId) -> Response {
|
||||
Response::new_err(
|
||||
id,
|
||||
lsp_server::ErrorCode::RequestCanceled as i32,
|
||||
"lucisv: request cancelled by the client".to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// What a `didOpen` did to the index scope, and therefore which of the three
|
||||
/// answers it is owed.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum Widen {
|
||||
/// The scope did not move: the file is in a folder already covered, or the
|
||||
/// rung in force is one an open buffer cannot widen (a filelist, or the
|
||||
/// whole-workspace walk). Publish and index nothing.
|
||||
Nothing,
|
||||
/// Folders were added and nothing else changed — the cheap path, indexing
|
||||
/// only what the added folders bring in
|
||||
/// ([`Server::reindex_widened`](super::Server::reindex_widened)).
|
||||
Added(Vec<std::path::PathBuf>),
|
||||
/// Anything else. The whole rescan, which is always a correct answer.
|
||||
Whole,
|
||||
}
|
||||
|
||||
/// Which of the three [`Widen`] answers a move from `before` to `after` is.
|
||||
///
|
||||
/// **The chooser, and it is deliberately narrow**: only a scope that grew and
|
||||
/// lost nothing takes the incremental path, because that is the only shape
|
||||
/// whose result is the whole rescan's by construction — a directory that left
|
||||
/// the scope can take files out of the index, and working out *which* files is
|
||||
/// the walk the widen exists not to do. Nothing in the server takes a directory
|
||||
/// out of the folder scope today (`opened_dirs` only grows, and a `didClose`
|
||||
/// costs no rescan at all), so the third arm is a rule kept rather than a case
|
||||
/// reached; a future shrink gets a correct answer instead of a subtle one.
|
||||
///
|
||||
/// **A directory that subsumes one already in scope is an add** (2026-08-29,
|
||||
/// `docs/features/index-scope/README.md`). At `scopeDepth: 2` the second file a
|
||||
/// user opens routinely raises to a *parent* of the directory the first one
|
||||
/// raised to — opentitan's `hw/ip/aes` then `hw/ip`. That is still a pure add
|
||||
/// here, because every opened directory is raised on its own and the list keeps
|
||||
/// them all: the contained directory is in `after` beside the containing one,
|
||||
/// and nothing was lost. The overlap is not re-read either, because
|
||||
/// `Workspace::begin_widen`'s work list is diffed **by file against what the
|
||||
/// index holds** rather than by folder against the old walk.
|
||||
///
|
||||
/// Both lists come from `Workspace::scope_dirs`, which sorts and dedups, so
|
||||
/// equality is set equality and `contains` is over a handful of directories.
|
||||
pub(super) fn widen_of(before: &[std::path::PathBuf], after: &[std::path::PathBuf]) -> Widen {
|
||||
if before == after {
|
||||
return Widen::Nothing;
|
||||
}
|
||||
if before.iter().any(|dir| !after.contains(dir)) {
|
||||
return Widen::Whole;
|
||||
}
|
||||
Widen::Added(after.iter().filter(|dir| !before.contains(dir)).cloned().collect())
|
||||
}
|
||||
|
||||
/// The files a burst opened, in the order the client opened them.
|
||||
///
|
||||
/// Read off the raw messages rather than off the workspace afterwards,
|
||||
/// because the workspace holds its buffers in a `HashMap` and "which file did
|
||||
/// the user just open" is a question about order.
|
||||
pub(super) fn opened_in(batch: &[Message]) -> Vec<std::path::PathBuf> {
|
||||
batch
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == DidOpenTextDocument::METHOD =>
|
||||
{
|
||||
document_uri(¬ification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.filter_map(|uri| crate::uri::uri_to_path(&uri))
|
||||
.collect()
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
//! What goes to the client other than a response.
|
||||
//!
|
||||
//! Three kinds of traffic, all server-initiated: the requests the server
|
||||
//! makes of the client (`send_request` and the six things asked through it —
|
||||
//! an edit to apply, a document to show, its settings, a watcher
|
||||
//! registration, a lens refresh) and the two answers it acts on; the
|
||||
//! messages a user sees or can grep for (`show_message`, `report_scope`, the
|
||||
//! plain `notify`); and the `--verbose` timing lines. The free functions at
|
||||
//! the end are the connection-level forms that work while the `Server` is
|
||||
//! borrowed elsewhere, plus the two words every log line is spelled with.
|
||||
|
||||
use lsp_server::{Connection, Message, Notification, Request, RequestId, Response};
|
||||
use lsp_types::notification::{LogMessage, Notification as _, ShowMessage};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CodeLensRefresh, RegisterCapability, Request as _, ShowDocument,
|
||||
UnregisterCapability, WorkspaceConfiguration,
|
||||
};
|
||||
use lsp_types::{
|
||||
ApplyWorkspaceEditParams, ApplyWorkspaceEditResponse, ConfigurationItem, ConfigurationParams,
|
||||
Location, LogMessageParams, MessageType, RegistrationParams, ShowDocumentParams,
|
||||
ShowMessageParams, UnregistrationParams, WorkspaceEdit,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::dispatch::{to_value, Failure};
|
||||
use super::{Pending, Server};
|
||||
use crate::{settings, watch};
|
||||
|
||||
impl Server {
|
||||
/// Ask the client something, reporting the id it will answer on — a
|
||||
/// repeated id is a protocol error, so this only ever counts up.
|
||||
pub(super) fn send_request(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: impl serde::Serialize,
|
||||
) -> RequestId {
|
||||
let id = RequestId::from(format!("lucisv-{}", self.request_ids));
|
||||
self.request_ids += 1;
|
||||
let request = Request::new(id.clone(), method.to_string(), params);
|
||||
// A closed channel means the client is gone; there is nobody left to
|
||||
// report the failure to.
|
||||
let _ = self.connection.sender.send(Message::Request(request));
|
||||
id
|
||||
}
|
||||
|
||||
/// Ask the client for the `lucisv` section of its settings.
|
||||
///
|
||||
/// Silent for a client that did not advertise `workspace.configuration` —
|
||||
/// that one is only ever pushed settings, which is what every client got
|
||||
/// before this existed. No `scopeUri`: this server holds one set of
|
||||
/// settings for the whole session, not one per folder, so asking
|
||||
/// per-resource would be asking for answers it has nowhere to put.
|
||||
pub(super) fn request_configuration(&mut self) {
|
||||
if !self.abilities.configuration {
|
||||
return;
|
||||
}
|
||||
let params = ConfigurationParams {
|
||||
items: vec![ConfigurationItem {
|
||||
scope_uri: None,
|
||||
section: Some(settings::SECTION.to_string()),
|
||||
}],
|
||||
};
|
||||
let id = self.send_request(WorkspaceConfiguration::METHOD, params);
|
||||
self.pending.insert(id, Pending::Configuration);
|
||||
}
|
||||
|
||||
/// Ask the client to watch the source files and the filelist for us,
|
||||
/// replacing any registration already in force.
|
||||
///
|
||||
/// Silent for a client that cannot be asked — that one keeps the save-only
|
||||
/// staleness model, which is what it had before this feature existed.
|
||||
pub(super) fn register_watchers(&mut self) {
|
||||
if !self.abilities.file_watching {
|
||||
return;
|
||||
}
|
||||
// Unregister first, so a client that keys watchers by id is never
|
||||
// holding two registrations that both fire for `**/*.sv`.
|
||||
if let Some(id) = self.watchers.take() {
|
||||
let params = UnregistrationParams { unregisterations: vec![watch::unregistration(id)] };
|
||||
self.send_request(UnregisterCapability::METHOD, params);
|
||||
}
|
||||
let filelist = self.workspace.filelist_path();
|
||||
let registration = watch::registration(self.registrations, filelist.as_deref());
|
||||
self.registrations += 1;
|
||||
self.watchers = Some(registration.id.clone());
|
||||
let params = RegistrationParams { registrations: vec![registration] };
|
||||
self.send_request(RegisterCapability::METHOD, params);
|
||||
}
|
||||
|
||||
/// Ask the client to re-request its code lenses, because the rescan just
|
||||
/// finished may have changed every instantiation count in every buffer it
|
||||
/// is showing.
|
||||
///
|
||||
/// Silent for a client that did not advertise
|
||||
/// `workspace.codeLens.refreshSupport` — the request is server-initiated
|
||||
/// and the spec makes that capability the gate. Since scan-interleave, the
|
||||
/// startup scan can send it too: a `didOpen` answered mid-scan leaves a
|
||||
/// buffer whose lenses were computed against the half-built index, and
|
||||
/// `started` refreshes them once the bar comes down. The answer is
|
||||
/// ignorable and rides `response`'s fall-through path.
|
||||
pub(super) fn refresh_code_lenses(&mut self) {
|
||||
if !self.abilities.code_lens_refresh {
|
||||
return;
|
||||
}
|
||||
self.send_request(CodeLensRefresh::METHOD, ());
|
||||
}
|
||||
|
||||
/// Deliver a command's `WorkspaceEdit` the way the client can take it.
|
||||
///
|
||||
/// The protocol has no place for an edit in an `executeCommand` *result*:
|
||||
/// a client applies what a server pushes with `workspace/applyEdit`, and
|
||||
/// drops the result on the floor. So the edit is pushed and the result is
|
||||
/// `null` — except for a client that never advertised `workspace.applyEdit`,
|
||||
/// which gets the old return-the-edit behavior because for that one it is
|
||||
/// the only behavior that could ever work.
|
||||
///
|
||||
/// The push goes out *before* the command's own response, which the loop
|
||||
/// sends when this returns. The protocol allows a server to request at any
|
||||
/// time, and a client that waited for the command result before applying
|
||||
/// the edit would deadlock on any server that does this — VS Code and
|
||||
/// Neovim both apply it immediately.
|
||||
pub(super) fn deliver(&mut self, command: &str, edit: WorkspaceEdit) -> Result<Value, Failure> {
|
||||
if !self.abilities.apply_edit {
|
||||
return to_value(edit);
|
||||
}
|
||||
let params = ApplyWorkspaceEditParams { label: Some(format!("lucisv: {command}")), edit };
|
||||
let id = self.send_request(ApplyWorkspaceEdit::METHOD, params);
|
||||
self.pending.insert(id, Pending::ApplyEdit(command.to_string()));
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// Answer `lucisv.showInstantiations` with its sites, and — for a client
|
||||
/// that can be sent one — push a `window/showDocument` for the first of
|
||||
/// them, so clicking the lens actually moves a cursor.
|
||||
///
|
||||
/// `executeCommand`'s *result* cannot navigate: it goes back to whatever
|
||||
/// invoked the command, and no editor moves on one. So the locations are
|
||||
/// the answer for a caller that wants the list, and the push is what makes
|
||||
/// the lens do something in an editor. Only the **first** site is shown:
|
||||
/// `window/showDocument` opens one document, and the protocol has no
|
||||
/// server-initiated "peek these seven places" — that is a VS Code command,
|
||||
/// and this repo's extension declares none. The client's answer is
|
||||
/// ignorable and falls through `response`'s `applying` lookup, as the
|
||||
/// progress `create`'s does.
|
||||
pub(super) fn show_instantiations(
|
||||
&mut self,
|
||||
locations: Vec<Location>,
|
||||
) -> Result<Value, Failure> {
|
||||
if let Some(first) = locations.first().filter(|_| self.abilities.show_document) {
|
||||
let params = ShowDocumentParams {
|
||||
uri: first.uri.clone(),
|
||||
external: None,
|
||||
take_focus: Some(true),
|
||||
selection: Some(first.range),
|
||||
};
|
||||
self.send_request(ShowDocument::METHOD, params);
|
||||
}
|
||||
to_value(locations)
|
||||
}
|
||||
|
||||
/// What the client answered.
|
||||
///
|
||||
/// Two answers are read: a `workspace/applyEdit`'s and a
|
||||
/// `workspace/configuration`'s. Nothing else this server asks of the
|
||||
/// client has an answer worth acting on: one that refuses the
|
||||
/// file-watcher (un)registration simply keeps the save-only staleness
|
||||
/// model; one that errors a `window/workDoneProgress/create` renders no
|
||||
/// bar and ignores the `$/progress` that named that token, per spec; one
|
||||
/// that declines a `workspace/codeLens/refresh` keeps the counts it has,
|
||||
/// and the next save asks again; and one that could not open a
|
||||
/// `window/showDocument` has already told the user so itself. None of
|
||||
/// those ids is ever in `pending`, so they all fall out here — in any
|
||||
/// arrival order, since the id is the whole of the lookup.
|
||||
pub(super) fn response(&mut self, response: Response) {
|
||||
match self.pending.remove(&response.id) {
|
||||
Some(Pending::ApplyEdit(command)) => self.applied(command, response),
|
||||
Some(Pending::Configuration) => self.configured(response),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Say so when the client did not apply an edit the server pushed.
|
||||
fn applied(&mut self, command: String, response: Response) {
|
||||
// A refusal is worth saying out loud: the user ran a command, watched
|
||||
// nothing happen, and would otherwise have no idea why. An answer that
|
||||
// does not parse is a refusal too — nothing was seen to be applied.
|
||||
let reason = match response.response_result {
|
||||
Ok(value) => match serde_json::from_value::<ApplyWorkspaceEditResponse>(value) {
|
||||
Ok(applied) if applied.applied => return,
|
||||
Ok(applied) => applied.failure_reason,
|
||||
Err(problem) => Some(problem.to_string()),
|
||||
},
|
||||
Err(error) => Some(error.message),
|
||||
};
|
||||
let message = match reason {
|
||||
Some(reason) => {
|
||||
format!("lucisv: {command} — the editor did not apply the edit: {reason}")
|
||||
}
|
||||
None => format!("lucisv: {command} — the editor did not apply the edit."),
|
||||
};
|
||||
self.show_message(MessageType::ERROR, message);
|
||||
}
|
||||
|
||||
/// Adopt the settings the client answered a `workspace/configuration`
|
||||
/// with.
|
||||
///
|
||||
/// **Never an error path.** The answer is an array with one entry per
|
||||
/// requested item, and this asked for exactly one — so entry 0 is the
|
||||
/// `lucisv` section. Anything else the client can send (an error, a
|
||||
/// `null` entry, an empty array, an object where an array belongs, a
|
||||
/// string) means the same thing: the client has no settings for us, which
|
||||
/// is the defaults. Nothing here is worth a popup — the user did not ask
|
||||
/// for this request and cannot act on its failure.
|
||||
fn configured(&mut self, response: Response) {
|
||||
let answered = response.response_result.unwrap_or(Value::Null);
|
||||
let section = answered.get(0).cloned().unwrap_or(Value::Null);
|
||||
self.apply_settings(settings::from_section(§ion));
|
||||
}
|
||||
|
||||
/// Say what went wrong while working out which files to index — a
|
||||
/// filelist naming a file that has moved, an unset variable, an option
|
||||
/// lucisv does not know.
|
||||
///
|
||||
/// Every one is logged, but only the first is *shown*: a filelist that has
|
||||
/// drifted from the tree can easily carry forty stale paths, and forty
|
||||
/// popups would be worse than the problem. Said once per rebuild, which is
|
||||
/// once per save — the same rhythm the `lucisv.toml` warning has.
|
||||
///
|
||||
/// `workspace/willRenameFiles` reports through here too: an `` `include``
|
||||
/// a rename strands is the same kind of news, said at the same volume, and
|
||||
/// a rename that strands forty of them must not open forty popups.
|
||||
pub(super) fn report_scope(&self, warnings: Vec<String>) {
|
||||
for warning in &warnings {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::WARNING,
|
||||
message: format!("lucisv: {warning}"),
|
||||
},
|
||||
);
|
||||
}
|
||||
let Some(first) = warnings.first() else { return };
|
||||
let rest = warnings.len() - 1;
|
||||
let message = match rest {
|
||||
0 => format!("lucisv: {first}"),
|
||||
_ => format!("lucisv: {first} (and {rest} more — see the lucisv log)"),
|
||||
};
|
||||
self.notify(ShowMessage::METHOD, ShowMessageParams { typ: MessageType::WARNING, message });
|
||||
}
|
||||
|
||||
pub(super) fn show_message(&self, typ: MessageType, message: String) {
|
||||
self.notify(ShowMessage::METHOD, ShowMessageParams { typ, message: message.clone() });
|
||||
self.notify(LogMessage::METHOD, LogMessageParams { typ, message });
|
||||
}
|
||||
|
||||
pub(super) fn notify(&self, method: &str, params: impl serde::Serialize) {
|
||||
notify_on(&self.connection, method, params);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// timing (`--verbose`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The clock a timing line reads, started **only** when `--verbose` asked
|
||||
/// for one.
|
||||
///
|
||||
/// `None` is the whole of what verbose-off costs: one branch here, and
|
||||
/// then no clock read, no `format!` and no notification anywhere below.
|
||||
/// Every timing site starts with this.
|
||||
pub(super) fn timer(&self) -> Option<std::time::Instant> {
|
||||
self.verbose.then(std::time::Instant::now)
|
||||
}
|
||||
|
||||
/// One timing line for work that was being timed — and nothing at all,
|
||||
/// closure included, for work that was not.
|
||||
pub(super) fn timed(
|
||||
&self,
|
||||
started: Option<std::time::Instant>,
|
||||
line: impl FnOnce(&str) -> String,
|
||||
) {
|
||||
let Some(started) = started else { return };
|
||||
self.timing(line(&ms(started)));
|
||||
}
|
||||
|
||||
/// One `timing:` line in the client's output channel.
|
||||
///
|
||||
/// `MessageType::LOG` and the same `window/logMessage` the per-file index
|
||||
/// log uses — the channel is already this server's, and the one-word
|
||||
/// prefix is what lets a reader (or a `grep`) pick these out of it. Sent
|
||||
/// straight down the writer thread like every other notification, so it
|
||||
/// cannot block on anything the loop is holding.
|
||||
pub(super) fn timing(&self, line: String) {
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams { typ: MessageType::LOG, message: format!("timing: {line}") },
|
||||
);
|
||||
}
|
||||
|
||||
/// One line for a request the order contract makes wait, naming which of
|
||||
/// [`Server::must_wait`]'s three clauses held it.
|
||||
///
|
||||
/// The question this answers is the one a slow-looking editor raises:
|
||||
/// "was that request slow, or was it never started?". Silent for anything
|
||||
/// that is not a request — nothing else waits.
|
||||
pub(super) fn say_held(&self, message: &Message) {
|
||||
if !self.verbose {
|
||||
return;
|
||||
}
|
||||
let Message::Request(request) = message else { return };
|
||||
self.timing(format!(
|
||||
"{} HELD behind a rescan (answering={}, wanted={}, already held={})",
|
||||
request.method,
|
||||
self.answering_a_rescan,
|
||||
self.rescan_wanted,
|
||||
self.held.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// One notification, on a connection rather than through a `Server`.
|
||||
pub(super) fn notify_on(connection: &Connection, method: &str, params: impl serde::Serialize) {
|
||||
let notification = Notification::new(method.to_string(), params);
|
||||
// A closed channel means the client is gone; there is nobody left to
|
||||
// report the failure to.
|
||||
let _ = connection.sender.send(Message::Notification(notification));
|
||||
}
|
||||
|
||||
/// How long ago, in milliseconds — the one unit every timing line is written
|
||||
/// in, to two decimals so that a sub-millisecond answer is still a number.
|
||||
pub(super) fn ms(started: std::time::Instant) -> String {
|
||||
format!("{:.2} ms", started.elapsed().as_secs_f64() * 1_000.0)
|
||||
}
|
||||
|
||||
/// The `s` a count needs, or nothing. One file is not "1 files".
|
||||
pub(super) fn plural(count: usize) -> &'static str {
|
||||
if count == 1 {
|
||||
""
|
||||
} else {
|
||||
"s"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
//! What the server says about a buffer's contents, and when.
|
||||
//!
|
||||
//! *When* is the change debounce: a `didChange` marks a buffer dirty and the
|
||||
//! first thing that needs its analysis flushes it, so a typing burst costs
|
||||
//! one reparse (`docs/features/change-debounce/README.md`). *What* is one
|
||||
//! parse-and-lint pass, `diagnostics_of`, that both delivery models answer
|
||||
//! from: the push (`publish`, gated so a pulling client is never pushed) and
|
||||
//! the pull (`document_report`, `workspace_report`, stamped with the
|
||||
//! generation — `docs/features/pull-diagnostics/README.md`).
|
||||
|
||||
use lsp_types::notification::{LogMessage, Notification as _, PublishDiagnostics};
|
||||
use lsp_types::{
|
||||
DocumentDiagnosticReport, FullDocumentDiagnosticReport, LogMessageParams, MessageType,
|
||||
PreviousResultId, PublishDiagnosticsParams, RelatedFullDocumentDiagnosticReport,
|
||||
RelatedUnchangedDocumentDiagnosticReport, UnchangedDocumentDiagnosticReport, Uri,
|
||||
WorkspaceDiagnosticReport, WorkspaceDocumentDiagnosticReport,
|
||||
WorkspaceFullDocumentDiagnosticReport, WorkspaceUnchangedDocumentDiagnosticReport,
|
||||
};
|
||||
|
||||
use super::client::plural;
|
||||
use super::Server;
|
||||
use crate::diagnostics;
|
||||
|
||||
impl Server {
|
||||
/// Replace a buffer's text, re-arming its `lucisv.toml` warning: the user
|
||||
/// has moved on, and a config problem is worth saying once more.
|
||||
pub(super) fn set_document(&mut self, uri: Uri, text: String) {
|
||||
self.config_warnings.remove(&uri);
|
||||
let was_large = self.workspace.document(&uri).is_some_and(|doc| doc.large);
|
||||
self.workspace.set_document(uri.clone(), text);
|
||||
self.generation += 1;
|
||||
self.announce_fast_path(&uri, was_large);
|
||||
}
|
||||
|
||||
/// Hold a buffer's newest text for later analysis. A change already held
|
||||
/// is replaced in place, so the entry's position in the flush order — the
|
||||
/// order the buffers were first dirtied in — survives a burst.
|
||||
pub(super) fn mark_dirty(&mut self, uri: Uri, text: String) {
|
||||
match self.dirty.iter_mut().find(|(pending, _)| *pending == uri) {
|
||||
Some(entry) => entry.1 = text,
|
||||
None => self.dirty.push((uri, text)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Analyze and republish every dirty buffer, oldest first. One flush is
|
||||
/// one `set_document` per buffer, so a whole typing burst costs one
|
||||
/// reparse per buffer it touched instead of one per keystroke.
|
||||
pub(super) fn flush_dirty(&mut self) {
|
||||
if self.dirty.is_empty() {
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
let buffers = self.dirty.len();
|
||||
for (uri, text) in std::mem::take(&mut self.dirty) {
|
||||
self.set_document(uri.clone(), text);
|
||||
self.publish(&uri);
|
||||
}
|
||||
self.timed(started, |took| {
|
||||
format!("flush of {buffers} dirty buffer{} took {took}", plural(buffers))
|
||||
});
|
||||
}
|
||||
|
||||
/// Say once, in the output channel, that a buffer is on the large-file
|
||||
/// fast path.
|
||||
///
|
||||
/// Once per *entry* into the mode, not once per notification: a keystroke
|
||||
/// in a 100 MB buffer must not log a line, and a buffer edited past the
|
||||
/// threshold mid-session must. Nothing is said on the way back out —
|
||||
/// leaving the mode restores every answer, which is not news.
|
||||
fn announce_fast_path(&self, uri: &Uri, was_large: bool) {
|
||||
let Some(doc) = self.workspace.document(uri).filter(|doc| doc.large && !was_large) else {
|
||||
return;
|
||||
};
|
||||
let what = match doc.path.as_deref() {
|
||||
Some(path) => path.display().to_string(),
|
||||
None => uri.as_str().to_string(),
|
||||
};
|
||||
let size = doc.text.len();
|
||||
self.notify(
|
||||
LogMessage::METHOD,
|
||||
LogMessageParams {
|
||||
typ: MessageType::INFO,
|
||||
message: format!(
|
||||
"lucisv: large-file fast path: {what} ({size} bytes) — \
|
||||
syntax highlighting only, nothing is parsed or indexed"
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Everything the server has to say about a buffer — the one computation
|
||||
/// both diagnostic models answer from. A buffer that is not open has
|
||||
/// nothing said about it.
|
||||
fn diagnostics_of(&self, uri: &Uri) -> Vec<lsp_types::Diagnostic> {
|
||||
let Some(doc) = self.workspace.document(uri) else { return Vec::new() };
|
||||
// The lint pass is given the project: the rule selection
|
||||
// `lucisv.lint.*` resolved to, and the index's identifier census, which
|
||||
// is what lets the semantic rules default on here without accusing a
|
||||
// signal another file reads (`docs/features/semantic-lints-on/`).
|
||||
diagnostics::all_in(doc, &crate::lint::LintRun::for_document(&self.workspace, doc))
|
||||
}
|
||||
|
||||
/// Publish everything known about a buffer — parse errors and lint
|
||||
/// warnings — in one notification. Two publishes for one version would
|
||||
/// leave only the second on screen, since LSP replaces rather than merges.
|
||||
pub(super) fn publish(&self, uri: &Uri) {
|
||||
// `send_diagnostics` would drop this anyway for a pulling client; the
|
||||
// early return is so the parse+lint pass is not run for nobody, once
|
||||
// per open buffer, on every index rebuild.
|
||||
if self.abilities.pull_diagnostics || self.workspace.document(uri).is_none() {
|
||||
return;
|
||||
}
|
||||
self.send_diagnostics(uri.clone(), self.diagnostics_of(uri));
|
||||
}
|
||||
|
||||
/// Push one buffer's diagnostics — unless the client pulls them.
|
||||
///
|
||||
/// A client that advertised `textDocument.diagnostic` owns the timing and
|
||||
/// the lifecycle of every diagnostic it shows: it asks when it wants them
|
||||
/// and drops them when it closes the document, so a push would be a second
|
||||
/// set of squiggles arriving on a schedule it did not choose. This is the
|
||||
/// one gate that keeps the two models from ever running for one client —
|
||||
/// the `didClose` clear goes through here too, for the same reason.
|
||||
pub(super) fn send_diagnostics(&self, uri: Uri, diagnostics: Vec<lsp_types::Diagnostic>) {
|
||||
if self.abilities.pull_diagnostics {
|
||||
return;
|
||||
}
|
||||
let params = PublishDiagnosticsParams { uri, diagnostics, version: None };
|
||||
self.notify(PublishDiagnostics::METHOD, params);
|
||||
}
|
||||
|
||||
/// One buffer's diagnostics, or an unchanged report when nothing that
|
||||
/// feeds them has moved since the client's last pull.
|
||||
pub(super) fn document_report(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
previous: Option<String>,
|
||||
) -> DocumentDiagnosticReport {
|
||||
let result_id = self.result_id();
|
||||
if previous.as_deref() == Some(result_id.as_str()) {
|
||||
let unchanged = UnchangedDocumentDiagnosticReport { result_id };
|
||||
return DocumentDiagnosticReport::Unchanged(RelatedUnchangedDocumentDiagnosticReport {
|
||||
related_documents: None,
|
||||
unchanged_document_diagnostic_report: unchanged,
|
||||
});
|
||||
}
|
||||
let full = FullDocumentDiagnosticReport {
|
||||
result_id: Some(result_id),
|
||||
items: self.diagnostics_of(uri),
|
||||
};
|
||||
DocumentDiagnosticReport::Full(RelatedFullDocumentDiagnosticReport {
|
||||
related_documents: None,
|
||||
full_document_diagnostic_report: full,
|
||||
})
|
||||
}
|
||||
|
||||
/// Every open buffer's diagnostics, in URI order so two pulls of the same
|
||||
/// state read the same way.
|
||||
///
|
||||
/// Open buffers are the whole scope: this server has never diagnosed a
|
||||
/// file it was not shown, and pulling would be the wrong place to start —
|
||||
/// linting the workspace on a keystroke-driven request is a rescan of
|
||||
/// every file per pull. The limit is stated in the feature README.
|
||||
pub(super) fn workspace_report(
|
||||
&self,
|
||||
previous: &[PreviousResultId],
|
||||
) -> WorkspaceDiagnosticReport {
|
||||
let result_id = self.result_id();
|
||||
let mut uris = self.workspace.open_uris();
|
||||
uris.sort();
|
||||
let items = uris
|
||||
.into_iter()
|
||||
.map(|uri| {
|
||||
let known = previous.iter().any(|seen| seen.uri == uri && seen.value == result_id);
|
||||
if known {
|
||||
let unchanged =
|
||||
UnchangedDocumentDiagnosticReport { result_id: result_id.clone() };
|
||||
return WorkspaceDocumentDiagnosticReport::Unchanged(
|
||||
WorkspaceUnchangedDocumentDiagnosticReport {
|
||||
uri,
|
||||
version: None,
|
||||
unchanged_document_diagnostic_report: unchanged,
|
||||
},
|
||||
);
|
||||
}
|
||||
let full = FullDocumentDiagnosticReport {
|
||||
result_id: Some(result_id.clone()),
|
||||
items: self.diagnostics_of(&uri),
|
||||
};
|
||||
WorkspaceDocumentDiagnosticReport::Full(WorkspaceFullDocumentDiagnosticReport {
|
||||
uri,
|
||||
version: None,
|
||||
full_document_diagnostic_report: full,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
WorkspaceDiagnosticReport { items }
|
||||
}
|
||||
|
||||
/// What a report is stamped with: the generation everything was computed
|
||||
/// against. Coarse on purpose — a change anywhere costs one extra full
|
||||
/// report elsewhere, and a stale "unchanged" would cost a wrong squiggle.
|
||||
fn result_id(&self) -> String {
|
||||
self.generation.to_string()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
//! `answer_request`: the dispatch table over request methods.
|
||||
//!
|
||||
//! One `match` arm per method, each a decode and a call into the module that
|
||||
//! owns the feature, so a reader looking for "what answers hover" finds the
|
||||
//! line here and follows it. The table stays whole on purpose — a dispatch
|
||||
//! table over an enum-shaped set is the one function the size rule exempts —
|
||||
//! and everything it merely delegates to lives elsewhere: the formatting
|
||||
//! entries in `formatting.rs`, the token deltas in `semantic_tokens.rs`, the
|
||||
//! pull reports in `diagnostics.rs`, the large-buffer gate in
|
||||
//! `large_file.rs`. Below the table is its vocabulary: `Failure`, the
|
||||
//! protocol's own words for a request that could not be answered, and the
|
||||
//! decoders every arm uses.
|
||||
|
||||
use lsp_server::{Request, RequestId, Response};
|
||||
use lsp_types::request::{
|
||||
CallHierarchyIncomingCalls, CallHierarchyOutgoingCalls, CallHierarchyPrepare,
|
||||
CodeActionRequest, CodeLensRequest, Completion, DocumentDiagnosticRequest,
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, GotoTypeDefinition, GotoTypeDefinitionParams,
|
||||
GotoTypeDefinitionResponse, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
|
||||
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
|
||||
TypeHierarchyPrepare, TypeHierarchySubtypes, TypeHierarchySupertypes, WillRenameFiles,
|
||||
WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
CallHierarchyIncomingCallsParams, CallHierarchyOutgoingCallsParams, CallHierarchyPrepareParams,
|
||||
CodeActionKind, CodeActionParams, CodeLensParams, CompletionParams, DocumentDiagnosticParams,
|
||||
DocumentDiagnosticReportResult, DocumentHighlightParams, DocumentLinkParams,
|
||||
DocumentSymbolParams, DocumentSymbolResponse, ExecuteCommandParams, FoldingRangeParams,
|
||||
GotoDefinitionParams, GotoDefinitionResponse, HoverParams, InlayHintParams,
|
||||
InlineCompletionParams, LinkedEditingRangeParams, Position, ReferenceParams, RenameFilesParams,
|
||||
RenameParams, SelectionRangeParams, SemanticTokens, SemanticTokensDeltaParams,
|
||||
SemanticTokensParams, SemanticTokensRangeParams, SemanticTokensRangeResult,
|
||||
SemanticTokensResult, SignatureHelpParams, TextDocumentPositionParams,
|
||||
TypeHierarchyPrepareParams, TypeHierarchySubtypesParams, TypeHierarchySupertypesParams, Uri,
|
||||
WorkspaceDiagnosticParams, WorkspaceDiagnosticReportResult, WorkspaceSymbolParams,
|
||||
WorkspaceSymbolResponse,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_json::Value;
|
||||
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{
|
||||
code_action, completion, design_hierarchy, file_ops, folding, format, hierarchy, hover,
|
||||
includes, inlay, inline, lens, linked, nav, pairs, ports, rename, selection, signature,
|
||||
symbols, tokens, type_def, type_hierarchy,
|
||||
};
|
||||
|
||||
impl Server {
|
||||
/// Answer one request, timing it when `--verbose` asked.
|
||||
///
|
||||
/// **The line goes out before the response it describes.** The dispatch is
|
||||
/// here and the response is sent by the caller, so a wrapper can only
|
||||
/// speak first — which is also what keeps the measurement to exactly the
|
||||
/// handler, with none of the transport in it. Nothing keys off the order:
|
||||
/// a `window/logMessage` carries no id, and a client pairs the response
|
||||
/// with its request by id whatever arrived in between.
|
||||
pub(super) fn request(&mut self, request: Request) -> Response {
|
||||
let Some(started) = self.timer() else { return self.answer_request(request) };
|
||||
let method = request.method.clone();
|
||||
let response = self.answer_request(request);
|
||||
self.timing(format!("{method} answered in {}", ms(started)));
|
||||
response
|
||||
}
|
||||
|
||||
fn answer_request(&mut self, request: Request) -> Response {
|
||||
// A request answers from a buffer's analysis, so any change the client
|
||||
// has already sent is in effect before it is answered — the order
|
||||
// contract the loop has always promised. Here is also where a typing
|
||||
// burst is coalesced: the changes before this request all become one
|
||||
// `set_document` in `flush_dirty`.
|
||||
self.flush_dirty();
|
||||
let id = request.id.clone();
|
||||
let method = request.method.clone();
|
||||
// The large-file fast path answers first, and for most methods it
|
||||
// answers "nothing" before any handler is entered. Everything it lets
|
||||
// through is either cheap on an empty analysis or is the one request
|
||||
// that does real work on a large buffer — see
|
||||
// `docs/features/large-file-mode/README.md` for the whole table.
|
||||
if let Some(answer) = self.large_file_answer(&method, &request.params) {
|
||||
return match answer {
|
||||
Ok(value) => Response::new_ok(id, value),
|
||||
Err(failure) => failure.into_response(id),
|
||||
};
|
||||
}
|
||||
let result = match method.as_str() {
|
||||
Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)),
|
||||
RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)),
|
||||
// LSP 3.18's multi-range form of the line above — `n` ranges, one
|
||||
// round trip, one answer. Answered whether or not the capability
|
||||
// was widened for this client: a request we can serve is not
|
||||
// refused because the client asked without saying it would.
|
||||
format::RANGES_FORMATTING => decode(request).and_then(|p| self.ranges_formatting(p)),
|
||||
// One keystroke, at most one edit, never a word to the user — see
|
||||
// `on_type_formatting`.
|
||||
OnTypeFormatting::METHOD => decode(request).and_then(|p| self.on_type_formatting(p)),
|
||||
// Format-on-save, protocol-native: the client asks before it
|
||||
// writes, and applies whatever comes back. Opt-in, and the decline
|
||||
// is the cheap path — see `will_save_wait_until`.
|
||||
WillSaveWaitUntil::METHOD => decode(request).and_then(|p| self.will_save_wait_until(p)),
|
||||
HoverRequest::METHOD => decode(request).and_then(|p: HoverParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.map(|offset| hover::hover(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
GotoDefinition::METHOD => decode(request).and_then(|p: GotoDefinitionParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| nav::definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
}),
|
||||
// The same answer shape as go-to-definition, deliberately: an
|
||||
// array in every case, empty where there is nothing to jump to,
|
||||
// and every candidate where the workspace holds the type name
|
||||
// twice. A buffer this server has not been sent is the empty
|
||||
// array too, which is what `unwrap_or_default` on the position
|
||||
// conversion means here as it does above.
|
||||
GotoTypeDefinition::METHOD => {
|
||||
decode(request).and_then(|p: GotoTypeDefinitionParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| type_def::type_definition(&self.workspace, &uri, offset))
|
||||
.unwrap_or_default();
|
||||
to_value(GotoTypeDefinitionResponse::Array(locations))
|
||||
})
|
||||
}
|
||||
// A closing label and the name it repeats, edited together. `null`
|
||||
// for every position that is not one of those two names — and for
|
||||
// a pair that could not be linked honestly (no label written, a
|
||||
// label that does not match, an escaped identifier), because an
|
||||
// empty `ranges` list is not what "nothing to link" means here.
|
||||
LinkedEditingRange::METHOD => {
|
||||
decode(request).and_then(|p: LinkedEditingRangeParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| {
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
linked::linked_editing_ranges(doc, offset)
|
||||
})
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
// The underline half of include navigation. Unresolvable includes
|
||||
// are simply absent from the list — never an error, and never a
|
||||
// link that goes nowhere.
|
||||
DocumentLinkRequest::METHOD => decode(request).and_then(|p: DocumentLinkParams| {
|
||||
to_value(includes::document_links(&self.workspace, &p.text_document.uri))
|
||||
}),
|
||||
References::METHOD => decode(request).and_then(|p: ReferenceParams| {
|
||||
let include = p.context.include_declaration;
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let locations = self
|
||||
.offset(&uri, position)
|
||||
.map(|offset| nav::references(&self.workspace, &uri, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
}),
|
||||
// Two answers behind one request: a scope keyword pairs with its
|
||||
// own closer, and anything else is a symbol whose other
|
||||
// occurrences in this file are what to draw. A cursor that is
|
||||
// neither answers `null` rather than an empty list — an empty list
|
||||
// means "no occurrences anywhere", which suppresses the editor's
|
||||
// own word highlighting, and losing that everywhere would be a
|
||||
// poor trade for gaining this.
|
||||
DocumentHighlightRequest::METHOD => {
|
||||
decode(request).and_then(|p: DocumentHighlightParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let found = self.offset(&uri, position).and_then(|offset| {
|
||||
let doc = self.workspace.document(&uri)?;
|
||||
pairs::highlights(doc, offset)
|
||||
.or_else(|| nav::document_highlights(doc, offset))
|
||||
});
|
||||
found.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
FoldingRangeRequest::METHOD => decode(request).and_then(|p: FoldingRangeParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => to_value(folding::folding_ranges(doc)),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
// Ghost port names on ordered connection lists. Range-scoped, as
|
||||
// the protocol asks: the client sends the lines it is showing and
|
||||
// gets the hints inside them.
|
||||
InlayHintRequest::METHOD => decode(request).and_then(|p: InlayHintParams| {
|
||||
to_value(inlay::inlay_hints(&self.workspace, &p.text_document.uri, p.range))
|
||||
}),
|
||||
SemanticTokensFullRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensParams| {
|
||||
self.semantic_tokens_full(&p.text_document.uri)
|
||||
.map(SemanticTokensResult::Tokens)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
// The same answer as `full`, said as what changed since the
|
||||
// client's last one — or as a whole new answer when we cannot
|
||||
// prove what it holds.
|
||||
SemanticTokensFullDeltaRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensDeltaParams| {
|
||||
self.semantic_tokens_delta(&p.text_document.uri, &p.previous_result_id)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
// The visible lines only, for the first paint of a large file.
|
||||
// Self-contained and unremembered: a range answer is not what a
|
||||
// later delta is computed against, so it carries no `resultId`.
|
||||
//
|
||||
// On a buffer over `lucisv.largeFile.threshold` this is the *only*
|
||||
// colouring request that answers, and it lexes the window rather
|
||||
// than filtering the document's tokens — there are none.
|
||||
SemanticTokensRangeRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensRangeParams| {
|
||||
let data = match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) if doc.large => tokens::semantic_tokens_in_window(doc, p.range),
|
||||
Some(doc) => tokens::semantic_tokens_in_range(doc, p.range),
|
||||
None => return Ok(Value::Null),
|
||||
};
|
||||
to_value(SemanticTokensRangeResult::Tokens(SemanticTokens {
|
||||
result_id: None,
|
||||
data,
|
||||
}))
|
||||
})
|
||||
}
|
||||
DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => {
|
||||
to_value(DocumentSymbolResponse::Nested(symbols::document_symbols(doc)))
|
||||
}
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
CodeActionRequest::METHOD => decode(request).and_then(|p: CodeActionParams| {
|
||||
let uri = p.text_document.uri;
|
||||
let only = p.context.only;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
// A code-action request carries no `tabSize`, so the width a
|
||||
// `no-tabs` fix writes comes from the buffer's own `lucisv.toml`
|
||||
// or from the built-in default.
|
||||
let tab_width =
|
||||
format::indent_width(doc.path.as_deref(), self.workspace.client_settings());
|
||||
let mut actions =
|
||||
code_action::code_actions(&uri, doc, p.range, only.as_deref(), tab_width);
|
||||
// The port refactorings answer for the cursor, not for a range:
|
||||
// the request's start is where the user is.
|
||||
if code_action::wanted(only.as_deref(), &CodeActionKind::new(ports::REFACTOR_PORTS))
|
||||
{
|
||||
let offset = doc.positions().offset(p.range.start);
|
||||
actions.extend(ports::code_actions(&self.workspace, &uri, offset));
|
||||
}
|
||||
to_value(actions)
|
||||
}),
|
||||
// Custom method, so it is matched by name rather than through a
|
||||
// `lsp_types::request` type. Nothing advertises it: a client that
|
||||
// does not know it never asks.
|
||||
pairs::SCOPE_PAIRS_METHOD => decode(request).and_then(|p: pairs::ScopePairsParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => to_value(pairs::scope_pairs(doc)),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
design_hierarchy::METHOD => to_value(design_hierarchy::snapshot(
|
||||
&self.workspace,
|
||||
self.hierarchy_revision,
|
||||
self.index_is_complete(),
|
||||
)),
|
||||
// A rename the engine declines comes back as a request error
|
||||
// carrying its own sentence, which is what an editor shows in the
|
||||
// rename box. `prepareRename` declines the same way, so the box
|
||||
// never opens for a rename that would then fail.
|
||||
PrepareRenameRequest::METHOD => {
|
||||
decode(request).and_then(|at: TextDocumentPositionParams| {
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::prepare(&self.workspace, &uri, offset) {
|
||||
Ok(response) => to_value(response),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
})
|
||||
}
|
||||
Rename::METHOD => decode(request).and_then(|p: RenameParams| {
|
||||
let new_name = p.new_name;
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
let Some(offset) = self.offset(&uri, position) else {
|
||||
return Ok(Value::Null);
|
||||
};
|
||||
match rename::rename(&self.workspace, &uri, offset, &new_name) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
to_value(edit)
|
||||
}
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// "N instantiations" over every module and interface declared in
|
||||
// the buffer. Every lens is complete when it is returned — there
|
||||
// is no `codeLens/resolve` — and a buffer this server has not been
|
||||
// sent answers `null`, as every other document-scoped request
|
||||
// does.
|
||||
CodeLensRequest::METHOD => decode(request).and_then(|p: CodeLensParams| {
|
||||
lens::code_lenses(&self.workspace, &p.text_document.uri)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
// The port refactorings, and the code lens's own jump. A refusal
|
||||
// is the engine's own sentence, returned as `RequestFailed`
|
||||
// exactly as a declined rename is.
|
||||
ExecuteCommand::METHOD => decode(request).and_then(|p: ExecuteCommandParams| {
|
||||
if p.command == lens::SHOW_INSTANTIATIONS {
|
||||
return match lens::execute(&self.workspace, &p.arguments) {
|
||||
Ok(locations) => self.show_instantiations(locations),
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
};
|
||||
}
|
||||
match ports::execute(&self.workspace, &p.command, &p.arguments) {
|
||||
Ok((edit, warnings)) => {
|
||||
self.report_scope(warnings);
|
||||
self.deliver(&p.command, edit)
|
||||
}
|
||||
Err(message) => Err(Failure::Request(message)),
|
||||
}
|
||||
}),
|
||||
// Pull diagnostics, LSP 3.17. Same parse+lint pass the push model
|
||||
// publishes; only the timing and the caching differ.
|
||||
DocumentDiagnosticRequest::METHOD => {
|
||||
decode(request).and_then(|p: DocumentDiagnosticParams| {
|
||||
let report = self.document_report(&p.text_document.uri, p.previous_result_id);
|
||||
to_value(DocumentDiagnosticReportResult::Report(report))
|
||||
})
|
||||
}
|
||||
WorkspaceDiagnosticRequest::METHOD => {
|
||||
decode(request).and_then(|p: WorkspaceDiagnosticParams| {
|
||||
let report = self.workspace_report(&p.previous_result_ids);
|
||||
to_value(WorkspaceDiagnosticReportResult::Report(report))
|
||||
})
|
||||
}
|
||||
// Expand-selection. One chain per position, in the order asked —
|
||||
// a client sends one position per cursor, and a multi-cursor
|
||||
// editor matches the answers up by index.
|
||||
SelectionRangeRequest::METHOD => decode(request).and_then(|p: SelectionRangeParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => to_value(selection::selection_ranges(doc, &p.positions)),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
// Module hinting. A position that is not a module item answers
|
||||
// `null` rather than an empty list, so the editor's own word
|
||||
// completion is left in charge there.
|
||||
Completion::METHOD => decode(request).and_then(|p: CompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
completion::completions(&self.workspace, &uri, position, self.abilities.snippets)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
// Ghost text. `null` for every position that is not one of the
|
||||
// two triggers, which is nearly all of them — the request arrives
|
||||
// on every keystroke, so the decline has to be the cheap path.
|
||||
InlineCompletionRequest::METHOD => {
|
||||
decode(request).and_then(|p: InlineCompletionParams| {
|
||||
let at = p.text_document_position;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
inline::inline_completions(&self.workspace, &uri, position)
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
SignatureHelpRequest::METHOD => decode(request).and_then(|p: SignatureHelpParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| signature::signature_help(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
}),
|
||||
// The module hierarchy. `prepare` answers `null` for a position
|
||||
// that is not a module name, which is what stops an editor from
|
||||
// opening an empty hierarchy view; the two directions then answer
|
||||
// one hop each, and the client drives the expansion.
|
||||
CallHierarchyPrepare::METHOD => {
|
||||
decode(request).and_then(|p: CallHierarchyPrepareParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| hierarchy::prepare(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
CallHierarchyIncomingCalls::METHOD => {
|
||||
decode(request).and_then(|p: CallHierarchyIncomingCallsParams| {
|
||||
to_value(hierarchy::incoming(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
CallHierarchyOutgoingCalls::METHOD => {
|
||||
decode(request).and_then(|p: CallHierarchyOutgoingCallsParams| {
|
||||
to_value(hierarchy::outgoing(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
// The class inheritance tree. Same contract as the call hierarchy
|
||||
// above: `prepare` answers `null` for a position that is not a
|
||||
// class name, and the two directions answer one hop each while the
|
||||
// client drives the expansion.
|
||||
TypeHierarchyPrepare::METHOD => {
|
||||
decode(request).and_then(|p: TypeHierarchyPrepareParams| {
|
||||
let at = p.text_document_position_params;
|
||||
let (uri, position) = (at.text_document.uri, at.position);
|
||||
self.offset(&uri, position)
|
||||
.and_then(|offset| type_hierarchy::prepare(&self.workspace, &uri, offset))
|
||||
.map_or(Ok(Value::Null), to_value)
|
||||
})
|
||||
}
|
||||
TypeHierarchySupertypes::METHOD => {
|
||||
decode(request).and_then(|p: TypeHierarchySupertypesParams| {
|
||||
to_value(type_hierarchy::supertypes(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
TypeHierarchySubtypes::METHOD => {
|
||||
decode(request).and_then(|p: TypeHierarchySubtypesParams| {
|
||||
to_value(type_hierarchy::subtypes(&self.workspace, &p.item))
|
||||
})
|
||||
}
|
||||
// The client is about to rename files and asks what that costs.
|
||||
// Every `` `include`` that *resolves* to one of them is re-spelled
|
||||
// so it still resolves afterwards; one that no include path can
|
||||
// reach is left exactly as written and named in a warning, because
|
||||
// inventing a path that resolves to nothing would be worse than
|
||||
// the stale one. `null` when there is nothing to do.
|
||||
WillRenameFiles::METHOD => decode(request).and_then(|p: RenameFilesParams| {
|
||||
let rewrite = file_ops::will_rename(&self.workspace, &p.files);
|
||||
self.report_scope(rewrite.warnings);
|
||||
match rewrite.edit {
|
||||
Some(edit) => to_value(edit),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
}),
|
||||
WorkspaceSymbolRequest::METHOD => {
|
||||
decode(request).and_then(|p: WorkspaceSymbolParams| {
|
||||
to_value(WorkspaceSymbolResponse::Flat(symbols::workspace_symbols(
|
||||
&self.workspace,
|
||||
&p.query,
|
||||
)))
|
||||
})
|
||||
}
|
||||
_ => Err(Failure::MethodNotFound(method)),
|
||||
};
|
||||
match result {
|
||||
Ok(value) => Response::new_ok(id, value),
|
||||
Err(failure) => failure.into_response(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The byte offset an LSP position names in an open document.
|
||||
fn offset(&self, uri: &Uri, position: Position) -> Option<u32> {
|
||||
self.workspace.document(uri).map(|doc| doc.positions().offset(position))
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a request could not be answered, in the protocol's own terms.
|
||||
pub(super) enum Failure {
|
||||
MethodNotFound(String),
|
||||
InvalidParams(String),
|
||||
Internal(String),
|
||||
/// The request was well-formed and the server declined it, with a reason
|
||||
/// meant for the user — LSP's `RequestFailed`.
|
||||
Request(String),
|
||||
/// The server chose not to compute an answer it could have computed, with
|
||||
/// a code that tells the client to keep what it has and ask again rather
|
||||
/// than to treat this as the answer. The large-file fast path declines
|
||||
/// `semanticTokens/full` this way; nothing else uses it.
|
||||
Declined(lsp_server::ErrorCode, String),
|
||||
}
|
||||
|
||||
impl Failure {
|
||||
fn into_response(self, id: RequestId) -> Response {
|
||||
let (code, message) = match self {
|
||||
Failure::MethodNotFound(method) => (
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
format!("unhandled method: {method}"),
|
||||
),
|
||||
Failure::InvalidParams(message) => {
|
||||
(lsp_server::ErrorCode::InvalidParams as i32, message)
|
||||
}
|
||||
Failure::Internal(message) => (lsp_server::ErrorCode::InternalError as i32, message),
|
||||
Failure::Request(message) => {
|
||||
(lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}"))
|
||||
}
|
||||
Failure::Declined(code, message) => (code as i32, format!("lucisv: {message}")),
|
||||
};
|
||||
Response::new_err(id, code, message)
|
||||
}
|
||||
}
|
||||
|
||||
/// The sentence every large-buffer refusal carries. One string, because a
|
||||
/// user who meets it twice should not have to work out whether they are the
|
||||
/// same thing.
|
||||
pub(super) const TOO_LARGE: &str =
|
||||
"this buffer is over lucisv.largeFile.threshold and is open on the large-file fast path";
|
||||
|
||||
/// The `textDocument.uri` a request names, read out of the raw params.
|
||||
///
|
||||
/// Before the typed decode on purpose: the fast-path gate has to know which
|
||||
/// buffer a request is about without knowing which of thirty parameter types
|
||||
/// it carries, and every document-scoped request in LSP spells it exactly
|
||||
/// here. A request with no `textDocument` (the hierarchy resolutions, the
|
||||
/// workspace-wide ones, `executeCommand`) is not gated at all, which is
|
||||
/// correct: none of them can reach a buffer's text.
|
||||
pub(super) fn document_uri(params: &Value) -> Option<Uri> {
|
||||
params.get("textDocument")?.get("uri")?.as_str()?.parse().ok()
|
||||
}
|
||||
|
||||
fn decode<P: DeserializeOwned>(request: Request) -> Result<P, Failure> {
|
||||
serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string()))
|
||||
}
|
||||
|
||||
pub(super) fn to_value(value: impl serde::Serialize) -> Result<Value, Failure> {
|
||||
serde_json::to_value(value).map_err(|e| Failure::Internal(e.to_string()))
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! The five formatting entries — whole document, one range, several ranges,
|
||||
//! on-type, and the save hook — and what each says when the engine refuses.
|
||||
//!
|
||||
//! All five climb the same settings ladder and run the same engine
|
||||
//! (`crate::format`); what differs is the trigger, and the trigger decides
|
||||
//! the manners: a command the user pressed refuses out loud, a keystroke and
|
||||
//! a save decline in silence. The once-per-change `lucisv.toml` warning and
|
||||
//! the edit-or-nothing contract are the two pieces of server state this
|
||||
//! needs, which is why the entries live here and not in `crate::format`.
|
||||
|
||||
use lsp_types::{
|
||||
DocumentFormattingParams, DocumentOnTypeFormattingParams, DocumentRangeFormattingParams,
|
||||
MessageType, Uri, WillSaveTextDocumentParams,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::dispatch::{to_value, Failure};
|
||||
use super::Server;
|
||||
use crate::{format, on_type};
|
||||
|
||||
impl Server {
|
||||
pub(super) fn formatting(
|
||||
&mut self,
|
||||
params: DocumentFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::formatting(doc, &settings.config);
|
||||
// A broken `lucisv.toml` is a warning, not a failure: the CLI exits 2 on
|
||||
// one, but an editor that refuses to format because of a typo in a
|
||||
// config file is an editor the user turns off. The buffer is formatted
|
||||
// with the built-in defaults, and the reason is said once per change of
|
||||
// the file — a format-on-save loop would otherwise repeat it forever.
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// `textDocument/rangeFormatting`, on the same engine and the same
|
||||
/// all-or-nothing contract as whole-document formatting.
|
||||
pub(super) fn range_formatting(
|
||||
&mut self,
|
||||
params: DocumentRangeFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::range_formatting(doc, &settings.config, params.range);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// `textDocument/rangesFormatting` — LSP 3.18's multi-range form.
|
||||
///
|
||||
/// Line for line the handler above, with `ranges` where it has `range`:
|
||||
/// the same settings ladder, the same engine, the same `edits` and the
|
||||
/// same config warning. That is the point of the feature — a client asking
|
||||
/// for five ranges gets one verified answer instead of five requests whose
|
||||
/// edits it would have to reconcile itself. See
|
||||
/// `docs/features/lsp-318-extras/README.md`.
|
||||
pub(super) fn ranges_formatting(
|
||||
&mut self,
|
||||
params: format::RangesFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let result = format::ranges_formatting(doc, &settings.config, ¶ms.ranges);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// `textDocument/onTypeFormatting` — the newline and the semicolon.
|
||||
///
|
||||
/// Two things about it are unlike every other formatting entry, and both
|
||||
/// follow from its trigger being a keystroke rather than a command:
|
||||
///
|
||||
/// * **It never speaks.** A formatter refusal is `[]` and silence, where
|
||||
/// `textDocument/formatting` shows an ERROR and `willSaveWaitUntil`
|
||||
/// shows one per save. Mid-edit code the engine declines is the *normal*
|
||||
/// case here, not a failure worth a popup on every semicolon.
|
||||
/// * **It never warns about a broken `lucisv.toml` either.** That warning
|
||||
/// is deduped per buffer *state*, and `set_document` re-arms it — so a
|
||||
/// request that by definition follows the `didChange` the user's own
|
||||
/// keystroke produced would re-arm and re-show it on every character.
|
||||
/// The user is told on their next explicit format or save, which are the
|
||||
/// two moments they asked lucisv for something.
|
||||
///
|
||||
/// The settings ladder is the one `textDocument/formatting` climbs,
|
||||
/// `tabSize` rung included: unlike `willSaveWaitUntil`, this request does
|
||||
/// carry `FormattingOptions`.
|
||||
pub(super) fn on_type_formatting(
|
||||
&mut self,
|
||||
params: DocumentOnTypeFormattingParams,
|
||||
) -> Result<Value, Failure> {
|
||||
let at = params.text_document_position;
|
||||
let Some(doc) = self.workspace.document(&at.text_document.uri) else {
|
||||
return to_value(Vec::<lsp_types::TextEdit>::new());
|
||||
};
|
||||
let settings = format::settings_for(doc, self.workspace.client_settings(), ¶ms.options);
|
||||
let edits = on_type::on_type_formatting(doc, at.position, ¶ms.ch, &settings.config);
|
||||
to_value(edits)
|
||||
}
|
||||
|
||||
/// `textDocument/willSaveWaitUntil` — format the buffer the client is
|
||||
/// about to write, for the editors that have no format-on-save of their
|
||||
/// own.
|
||||
///
|
||||
/// `null` unless `lucisv.formatOnSave` is on. A capable client sends this
|
||||
/// before *every* save, so declining has to be the cheap path — and an
|
||||
/// editor that already formats on save (VS Code's `editor.formatOnSave`,
|
||||
/// which runs `textDocument/formatting`) would otherwise format twice.
|
||||
///
|
||||
/// When it is on, this is `textDocument/formatting` with a different
|
||||
/// trigger: the same engine, the same settings ladder, the same
|
||||
/// all-or-nothing contract — one whole-document edit built from verified
|
||||
/// output, or no edit at all. The save's `reason` is not read: manual,
|
||||
/// after-delay and focus-out are all saves, and the user asked for their
|
||||
/// saves to be formatted. The text is the buffer the server holds, because
|
||||
/// the request carries none and the client has not written yet.
|
||||
pub(super) fn will_save_wait_until(
|
||||
&mut self,
|
||||
params: WillSaveTextDocumentParams,
|
||||
) -> Result<Value, Failure> {
|
||||
if !self.workspace.client_settings().format_on_save {
|
||||
return Ok(Value::Null);
|
||||
}
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
// No `FormattingOptions` on this request — the protocol carries none —
|
||||
// so the ladder runs without its `tabSize` rung.
|
||||
let settings =
|
||||
format::settings_without_editor_options(doc, self.workspace.client_settings());
|
||||
let result = format::formatting(doc, &settings.config);
|
||||
self.warn_about_config(&uri, settings.problem);
|
||||
self.edits(result)
|
||||
}
|
||||
|
||||
/// Say once per change of a file that its `lucisv.toml` could not be read.
|
||||
fn warn_about_config(&mut self, uri: &Uri, problem: Option<String>) {
|
||||
if let Some(problem) = problem {
|
||||
if self.config_warnings.insert(uri.clone()) {
|
||||
self.show_message(
|
||||
MessageType::WARNING,
|
||||
format!("lucisv: {problem} — formatting with default settings"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One edit, none, or — when the formatter refused — none plus the reason.
|
||||
///
|
||||
/// It never emits partial output (CLAUDE.md invariant #1), so neither do
|
||||
/// we. Diagnostics are not used for the failure: they belong to the parse
|
||||
/// pass and are cleared on the next keystroke, which would erase an
|
||||
/// explicit format failure the user asked for.
|
||||
pub(super) fn edits(
|
||||
&mut self,
|
||||
result: Result<Option<lsp_types::TextEdit>, String>,
|
||||
) -> Result<Value, Failure> {
|
||||
match result {
|
||||
Ok(Some(edit)) => to_value(vec![edit]),
|
||||
Ok(None) => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
Err(message) => {
|
||||
self.show_message(MessageType::ERROR, format!("lucisv: cannot format — {message}"));
|
||||
to_value(Vec::<lsp_types::TextEdit>::new())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
//! The rescans: how the workspace index is rebuilt, and what a rebuild owes
|
||||
//! every open buffer afterwards.
|
||||
//!
|
||||
//! Four entries — `reindex` (the whole scope), `reindex_one` (a save),
|
||||
//! `reindex_widened` (a `didOpen` that grew the scope) and `reindex_for` (a
|
||||
//! file operation, filtered) — over one loop, `scan_until_settled`, which is
|
||||
//! the whole of the coalescing rule: a rescan asked for mid-scan is one more
|
||||
//! scan when this one ends, never a scan inside a scan. `scan_once` is the
|
||||
//! scan that answers the client's messages between two of its files
|
||||
//! (`docs/features/scan-interleave/README.md`); the bar and the log it runs
|
||||
//! under are `progress.rs`'s.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_types::ProgressToken;
|
||||
|
||||
use super::batch::opened_in;
|
||||
use super::client::{notify_on, plural};
|
||||
use super::progress::IndexWatch;
|
||||
use super::{Server, INTERLEAVE_ABOVE};
|
||||
use crate::state::{IndexEvent, Scan, Workspace};
|
||||
use crate::{design_hierarchy, file_ops};
|
||||
|
||||
impl Server {
|
||||
/// Rescan the workspace and republish every open buffer against the new
|
||||
/// index. Every caller changed what the index should contain — a save, a
|
||||
/// new `lucisv.exclude`/`lucisv.filelist`, a watched file changing on disk,
|
||||
/// or a file the client renamed or deleted.
|
||||
pub(super) fn reindex(&mut self) {
|
||||
// A rescan asked for by a message this scan answered is *this* scan's
|
||||
// successor, not a scan inside it. See `scan_until_settled`.
|
||||
if self.scanning {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
let warnings = self.scan_until_settled(true);
|
||||
if self.stopped {
|
||||
return;
|
||||
}
|
||||
// A rescan can change any module's instantiation count, so every lens
|
||||
// a client is holding may now read wrong. Sent after the bar comes
|
||||
// down, for the same reason the bar comes down before the republishes:
|
||||
// the bar names the scan, and everything after it is work done on the
|
||||
// scan's result.
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
// Every open buffer's diagnostics are computed against the index, so a
|
||||
// pulling client's cached answers are all stale from here.
|
||||
self.generation += 1;
|
||||
self.report_scope(warnings);
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// [`Server::reindex`] for a trigger that named exactly **one** file, when
|
||||
/// that file is one the index already holds. Reports whether it ran; a
|
||||
/// `false` means the caller owes a whole rebuild.
|
||||
///
|
||||
/// Everything a rebuild does *after* the scan happens here too, for the
|
||||
/// same reasons: the code-lens refresh (the file that moved may have
|
||||
/// changed an instantiation count in any buffer), the diagnostics
|
||||
/// generation bump (every open buffer's diagnostics are computed against
|
||||
/// the index), and a republish of every open buffer. The republish stays
|
||||
/// wholesale rather than narrowing to the buffers that could have moved:
|
||||
/// a lint reads the index, so any buffer's diagnostics may have changed,
|
||||
/// and narrowing it correctly needs a dependency graph this server does not
|
||||
/// have. Worth doing later; wrong to guess at now.
|
||||
///
|
||||
/// Three things a whole rebuild does that this deliberately does not:
|
||||
///
|
||||
/// * **no progress bar.** The bar exists because a whole scan takes
|
||||
/// perceptible seconds on a large workspace; one file is one parse, and a
|
||||
/// bar that appears and vanishes inside a frame is noise, not progress.
|
||||
/// * **no per-file log line.** Same reason, and the log's purpose — "which
|
||||
/// files is this scan reading?" — is a question about a scan.
|
||||
/// * **no scope warnings.** They come from *resolving* the scope, and the
|
||||
/// scope was not re-resolved: nothing about which files exist changed, so
|
||||
/// repeating a filelist's complaints would be repeating stale news.
|
||||
pub(super) fn reindex_one(&mut self, path: &Path) -> bool {
|
||||
// Mid-scan the cheap path is not available and is not needed: the scan
|
||||
// holds the text this file had when it started and will index *that*,
|
||||
// so patching the half-built index here would be overwritten by older
|
||||
// bytes a moment later. One more scan when this one ends is the whole
|
||||
// answer, and it is the same flag every other mid-scan trigger sets.
|
||||
// `true` because the caller's fallback — a whole rebuild, right now —
|
||||
// is exactly what must not happen.
|
||||
if self.scanning {
|
||||
self.rescan_wanted = true;
|
||||
return true;
|
||||
}
|
||||
let started = self.timer();
|
||||
if !self.workspace.update_one(path) {
|
||||
// No line: nothing was reindexed, and the caller is about to
|
||||
// rebuild the whole index — which times itself.
|
||||
return false;
|
||||
}
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
self.timed(started, |took| format!("reindex_one({}) took {took}", path.display()));
|
||||
true
|
||||
}
|
||||
|
||||
/// [`Server::reindex`] for a `didOpen` that only ever **added** folders to
|
||||
/// the scope: index those folders and fold them in, leaving every file
|
||||
/// already indexed exactly as it is.
|
||||
///
|
||||
/// Everything after the scan is what a whole rescan does, for the same
|
||||
/// reasons — the widen changes which names exist, so lenses, the
|
||||
/// diagnostics generation and every open buffer's publish all move with it.
|
||||
///
|
||||
/// **Mid-scan this defers to one whole rescan rather than widening.** A
|
||||
/// scan already running holds a work list taken from the *old* scope, and
|
||||
/// folding a widen into it would mean two answers to "which files exist"
|
||||
/// inside one scan; the follow-up scan the flag asks for reads the
|
||||
/// persistent store for everything the running scan already parsed, so it
|
||||
/// is the cheap kind. This is the same flag every other mid-scan trigger
|
||||
/// sets, and it is what keeps the coalescing rule one rule
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
pub(super) fn reindex_widened(&mut self, added: Vec<std::path::PathBuf>) {
|
||||
if self.scanning {
|
||||
self.rescan_wanted = true;
|
||||
return;
|
||||
}
|
||||
let started = self.timer();
|
||||
if started.is_some() {
|
||||
// The folders by name: which folder a jump widened into is the one
|
||||
// thing the file log below it does not say in one line.
|
||||
let paths: Vec<String> = added.iter().map(|p| p.display().to_string()).collect();
|
||||
let folders = added.len();
|
||||
self.timing(format!(
|
||||
"widen started: {folders} folder{} added: {}",
|
||||
plural(folders),
|
||||
paths.join(", ")
|
||||
));
|
||||
}
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan =
|
||||
self.watching(bar.as_ref(), |workspace, watch| workspace.begin_widen(&added, watch));
|
||||
let total = scan.total();
|
||||
// No drain between the files: a widen is a rescan a message asked for,
|
||||
// and `must_wait` would hold every request queued behind it anyway. It
|
||||
// is also the point of the round that there is no longer a wait worth
|
||||
// interleaving — a widen indexes one folder, not the whole scope.
|
||||
loop {
|
||||
let step = |workspace: &mut Workspace, watch: &mut dyn FnMut(IndexEvent)| {
|
||||
workspace.scan_step(&mut scan, watch)
|
||||
};
|
||||
if !self.watching(bar.as_ref(), step) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
self.end_indexing(bar, skipped, cached);
|
||||
self.timed(started, |took| {
|
||||
format!(
|
||||
"widen finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
self.refresh_code_lenses();
|
||||
self.hierarchy_index_changed();
|
||||
self.generation += 1;
|
||||
self.report_scope(warnings);
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
/// Rescan, but only when the paths a file-operation notification named are
|
||||
/// paths the index reads. The same test a watched-file notification gets.
|
||||
pub(super) fn reindex_for(&mut self, paths: Vec<std::path::PathBuf>) {
|
||||
let filelist = self.workspace.filelist_path();
|
||||
if file_ops::touches_scope(&paths, filelist.as_deref()) {
|
||||
self.reindex();
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan, and go on scanning while the messages answered along the way keep
|
||||
/// asking for one. Reports the last scan's scope warnings.
|
||||
///
|
||||
/// **The whole of the coalescing rule, and it is a loop rather than a
|
||||
/// recursion on purpose.** A `didSave`, a widened scope, a changed
|
||||
/// setting or a watched-file burst answered mid-scan sets
|
||||
/// `rescan_wanted`; any number of them is one more scan. Finishing the
|
||||
/// current scan and then running another was chosen over aborting and
|
||||
/// restarting it because it needs no way to unwind a half-published index
|
||||
/// and cannot loop for ever on its own — the follow-up scan reads the
|
||||
/// persistent cache for every file the abandoned one already parsed, so
|
||||
/// it is the cheap kind. Each scan gets its own progress token, which is
|
||||
/// what a client showing a bar expects of two scans.
|
||||
pub(super) fn scan_until_settled(&mut self, mut asked_for: bool) -> Vec<String> {
|
||||
self.scanning = true;
|
||||
let warnings = loop {
|
||||
self.answering_a_rescan = asked_for;
|
||||
let warnings = self.scan_once();
|
||||
if !std::mem::take(&mut self.rescan_wanted) || self.stopped {
|
||||
break warnings;
|
||||
}
|
||||
// Every scan after the first one here is one a message asked for,
|
||||
// whatever the first one was.
|
||||
asked_for = true;
|
||||
};
|
||||
self.answering_a_rescan = false;
|
||||
self.scanning = false;
|
||||
warnings
|
||||
}
|
||||
|
||||
/// One whole scan: the bar up, every file indexed with the client's
|
||||
/// messages answered between two of them, the bar down.
|
||||
///
|
||||
/// A scan a `shutdown` interrupted stops where it stands and reports no
|
||||
/// warnings: nothing after this may speak to a client that has gone. The
|
||||
/// records of the files it did index are already in the persistent store —
|
||||
/// they are written through per file — so the next session resumes from
|
||||
/// them, exactly as it does after any other half-done scan.
|
||||
fn scan_once(&mut self) -> Vec<String> {
|
||||
// Before the bar and before the work list is built: resolving the
|
||||
// scope and walking it is part of what a scan costs, and a number that
|
||||
// left it out would be the wrong answer to "why was that slow?".
|
||||
let started = self.timer();
|
||||
let bar = self.begin_indexing();
|
||||
let mut scan = self.watching(bar.as_ref(), |workspace, watch| workspace.begin_scan(watch));
|
||||
let interleave = scan.total() > INTERLEAVE_ABOVE;
|
||||
let total = scan.total();
|
||||
if started.is_some() {
|
||||
// Whether it interleaves is said here because it is decided here,
|
||||
// and because it is the answer to "why did my hover wait?" — a
|
||||
// scan that does not interleave answers nothing until it is done.
|
||||
let interleaving = if interleave { ", interleaved" } else { "" };
|
||||
self.timing(format!("scan started: {total} file{}{interleaving}", plural(total)));
|
||||
}
|
||||
while self.watching(bar.as_ref(), |workspace, watch| workspace.scan_step(&mut scan, watch))
|
||||
{
|
||||
if interleave && self.answer_what_is_waiting(&mut scan) {
|
||||
// Nothing after this may speak to a client that has gone, the
|
||||
// timing line included.
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let (skipped, cached) = (scan.skipped(), scan.cached());
|
||||
let warnings = self.workspace.finish_scan(scan);
|
||||
self.end_indexing(bar, skipped, cached);
|
||||
self.timed(started, |took| {
|
||||
format!(
|
||||
"scan finished: {total} file{} ({skipped} skipped, {cached} from cache) in {took}",
|
||||
plural(total)
|
||||
)
|
||||
});
|
||||
warnings
|
||||
}
|
||||
|
||||
/// Do one piece of a scan with the progress bar and the per-file log
|
||||
/// watching it.
|
||||
///
|
||||
/// The fields are split apart because the watcher writes to the connection
|
||||
/// while the workspace is borrowed mutably for the work it is watching —
|
||||
/// the split `Server::new` used to make inline, made once here because a
|
||||
/// scan is now several calls instead of one. A fresh `IndexWatch` per call
|
||||
/// costs nothing and re-reads `lucisv.index.logFiles`, so a settings change
|
||||
/// answered mid-scan is honoured by the very next file's log line.
|
||||
fn watching<T>(
|
||||
&mut self,
|
||||
bar: Option<&ProgressToken>,
|
||||
step: impl FnOnce(&mut Workspace, &mut dyn FnMut(IndexEvent)) -> T,
|
||||
) -> T {
|
||||
let Server { connection, workspace, .. } = self;
|
||||
let mut watch = IndexWatch::new(connection, bar, workspace.client_settings());
|
||||
step(workspace, &mut |event| watch.see(event))
|
||||
}
|
||||
|
||||
/// Answer everything the client has already sent, against the index as far
|
||||
/// as this scan has built it. Reports whether the client shut us down.
|
||||
///
|
||||
/// **This is the round's whole point, and its whole cost.** Polling costs
|
||||
/// one `try_recv` per file and finds nothing in a scan nobody is waiting
|
||||
/// on, so a quiet scan pays nothing at all; a scan somebody *is* waiting
|
||||
/// on pays one merge per burst to make the records it has taken since the
|
||||
/// last one answerable ([`Workspace::publish_scan`]). The messages then go
|
||||
/// through the same `process_batch` the loop uses, so a `didChange` queued
|
||||
/// ahead of a hover is applied before that hover is answered and a cancel
|
||||
/// beside its request still answers it `RequestCancelled` — the order
|
||||
/// contract is the loop's, unchanged, because it is the loop's code.
|
||||
///
|
||||
/// An error here is a client that has gone: there is nobody to report it
|
||||
/// to and no reason to go on scanning, so it stops the scan the same way a
|
||||
/// `shutdown` does.
|
||||
fn answer_what_is_waiting(&mut self, scan: &mut Scan) -> bool {
|
||||
let mut batch = Vec::new();
|
||||
while let Ok(message) = self.queue.try_recv() {
|
||||
batch.push(message);
|
||||
}
|
||||
if batch.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let opened = opened_in(&batch);
|
||||
self.workspace.publish_scan(scan);
|
||||
self.stopped = !matches!(self.process_batch(batch), Ok(false));
|
||||
// The file the user has just opened is the one they are looking at, so
|
||||
// it is indexed next rather than when the alphabet reaches it — the
|
||||
// open-first rule, for a file opened after the work list was taken.
|
||||
for path in opened {
|
||||
scan.index_next(&path);
|
||||
}
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// Publish a new completed hierarchy revision after any index mutation.
|
||||
pub(super) fn hierarchy_index_changed(&mut self) {
|
||||
self.hierarchy_revision = self.hierarchy_revision.saturating_add(1);
|
||||
if !self.abilities.hierarchy_view {
|
||||
return;
|
||||
}
|
||||
notify_on(
|
||||
&self.connection,
|
||||
design_hierarchy::CHANGED_METHOD,
|
||||
serde_json::json!({ "revision": self.hierarchy_revision }),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! The large-file fast path: what a buffer over `lucisv.largeFile.threshold`
|
||||
//! answers *instead of* the dispatch.
|
||||
//!
|
||||
//! Runs ahead of every request and costs one boolean when no large buffer is
|
||||
//! open. Its own file because it is a second, smaller table over the same
|
||||
//! method names as `dispatch.rs`, with a different answer for each — and
|
||||
//! because it is the one place the large-file feature lane touches on the
|
||||
//! server side (`docs/features/large-file-mode/README.md`).
|
||||
|
||||
use lsp_types::request::{
|
||||
CodeActionRequest, DocumentLinkRequest, Formatting, GotoDefinition, HoverRequest,
|
||||
OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References, Rename, Request as _,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, WillSaveWaitUntil,
|
||||
};
|
||||
use lsp_types::{GotoDefinitionResponse, Location, Position, Uri};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::dispatch::{document_uri, to_value, Failure, TOO_LARGE};
|
||||
use super::Server;
|
||||
use crate::{format, large};
|
||||
|
||||
impl Server {
|
||||
/// What a buffer over `lucisv.largeFile.threshold` answers `method`, or
|
||||
/// `None` when the normal dispatch may run.
|
||||
///
|
||||
/// Four groups, and the reason each is what it is:
|
||||
///
|
||||
/// * **`semanticTokens/full` and `/full/delta` are declined with an
|
||||
/// error.** Answering them with an empty set would be worse than not
|
||||
/// answering: VS Code marks a model whose *document* provider returned
|
||||
/// anything at all as having complete semantic tokens, and its viewport
|
||||
/// contribution then never asks for a range again — the file would lose
|
||||
/// all colour. An error leaves the model incomplete, so the range
|
||||
/// provider keeps painting. The evidence for both halves is in
|
||||
/// `docs/features/large-file-mode/README.md`.
|
||||
/// * **The formatting requests refuse out loud.** A user pressed a key and
|
||||
/// is owed a reason; silence there reads as a broken formatter. The
|
||||
/// exceptions are the two the user did not press: `onTypeFormatting`
|
||||
/// (a keystroke, and it never speaks) and `willSaveWaitUntil` (every
|
||||
/// save), which decline the way they already decline.
|
||||
/// * **`definition` and `references` scan the buffer.** The only two
|
||||
/// answers a text scan can honestly give, and the whole reason the
|
||||
/// buffer's text is still in memory.
|
||||
/// * **Everything else answers nothing, fast** — and most of it is not
|
||||
/// listed here at all: a fast-path `Document` holds the analysis of an
|
||||
/// *empty* file, so those handlers already answer empty without knowing
|
||||
/// this mode exists. Named below are only the ones that would otherwise
|
||||
/// read the text itself.
|
||||
pub(super) fn large_file_answer(
|
||||
&mut self,
|
||||
method: &str,
|
||||
params: &Value,
|
||||
) -> Option<Result<Value, Failure>> {
|
||||
// One boolean before anything is parsed: this runs ahead of every
|
||||
// request, and a session with no large buffer in it — which is every
|
||||
// session but one — must not pay a URI parse for the privilege.
|
||||
if !self.workspace.has_large_documents() {
|
||||
return None;
|
||||
}
|
||||
let uri = document_uri(params)?;
|
||||
if !self.workspace.document(&uri).is_some_and(|doc| doc.large) {
|
||||
return None;
|
||||
}
|
||||
let answer = match method {
|
||||
SemanticTokensFullRequest::METHOD | SemanticTokensFullDeltaRequest::METHOD => {
|
||||
Err(self.tokens_declined())
|
||||
}
|
||||
Formatting::METHOD | RangeFormatting::METHOD | format::RANGES_FORMATTING => {
|
||||
self.edits(Err(TOO_LARGE.to_string()))
|
||||
}
|
||||
// Silent, both of them: one fires on every keystroke and one on
|
||||
// every save.
|
||||
OnTypeFormatting::METHOD => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
WillSaveWaitUntil::METHOD => Ok(Value::Null),
|
||||
// A rename would rewrite every *other* file and leave this one
|
||||
// untouched — the buffer is not in the index and not in
|
||||
// `sources()` — so it is refused rather than half-applied.
|
||||
// `prepareRename` declines quietly, so the box never opens.
|
||||
PrepareRenameRequest::METHOD => Ok(Value::Null),
|
||||
Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())),
|
||||
// These three read the buffer's text rather than its analysis: the
|
||||
// include scan, the `` `include`` line lookup a hover does, and
|
||||
// the fix application a code action tries.
|
||||
HoverRequest::METHOD => Ok(Value::Null),
|
||||
DocumentLinkRequest::METHOD => to_value(Vec::<lsp_types::DocumentLink>::new()),
|
||||
CodeActionRequest::METHOD => to_value(Vec::<lsp_types::CodeActionOrCommand>::new()),
|
||||
GotoDefinition::METHOD => self.large_definition(&uri, params),
|
||||
References::METHOD => self.large_references(&uri, params),
|
||||
_ => return None,
|
||||
};
|
||||
Some(answer)
|
||||
}
|
||||
|
||||
/// The error `semanticTokens/full` is declined with.
|
||||
///
|
||||
/// `ServerCancelled` for a client that advertised `serverCancelSupport`,
|
||||
/// which is the code the spec reserves for exactly this and the code
|
||||
/// `vscode-languageclient` turns into a `CancellationError`;
|
||||
/// `ContentModified` for one that did not, which the same client turns
|
||||
/// into the same `CancellationError` (semantic tokens are on its
|
||||
/// `retryOnContentModified` list) and which every 3.16 client already
|
||||
/// understands.
|
||||
fn tokens_declined(&self) -> Failure {
|
||||
let code = match self.abilities.token_server_cancel {
|
||||
true => lsp_server::ErrorCode::ServerCancelled,
|
||||
false => lsp_server::ErrorCode::ContentModified,
|
||||
};
|
||||
Failure::Declined(code, TOO_LARGE.to_string())
|
||||
}
|
||||
|
||||
/// `textDocument/definition` on a large buffer: the first occurrence of
|
||||
/// the name under the cursor that a declaring keyword introduces.
|
||||
fn large_definition(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
||||
let locations = self
|
||||
.large_scan(uri, params, |doc, offset| {
|
||||
large::definition(doc, offset).into_iter().collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
}
|
||||
|
||||
/// `textDocument/references` on a large buffer: every whole-word
|
||||
/// occurrence of the name under the cursor, capped.
|
||||
fn large_references(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
||||
let include = params
|
||||
.get("context")
|
||||
.and_then(|context| context.get("includeDeclaration"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
let locations = self
|
||||
.large_scan(uri, params, |doc, offset| large::references(doc, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
}
|
||||
|
||||
/// Run one of the fast path's scans at the position `params` names, and
|
||||
/// turn its spans into locations in the same file.
|
||||
fn large_scan(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
params: &Value,
|
||||
scan: impl Fn(&crate::state::Document, u32) -> Vec<vlog_parser::TextRange>,
|
||||
) -> Option<Vec<Location>> {
|
||||
let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?;
|
||||
let doc = self.workspace.document(uri)?;
|
||||
let positions = doc.positions();
|
||||
let offset = positions.offset(position);
|
||||
// Both scans answer in ascending order, so one monotonic cursor
|
||||
// measures each line once — a thousand hits on one netlist line would
|
||||
// otherwise re-measure that line a thousand times over.
|
||||
let mut walker = positions.walker();
|
||||
Some(
|
||||
scan(doc, offset)
|
||||
.into_iter()
|
||||
.map(|span| Location { uri: uri.clone(), range: walker.range(span) })
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,540 @@
|
||||
//! The request loop: one burst in, one response per request, on one thread.
|
||||
//!
|
||||
//! `lsp-server` runs two I/O threads of its own and hands this loop framed
|
||||
//! messages over a channel. Everything below is synchronous — Verilog files
|
||||
//! are small, every handler is milliseconds, and a worker pool would buy
|
||||
//! nothing yet. A request that has already started therefore runs to
|
||||
//! completion; the one thing `$/cancelRequest` can do here is answer a request
|
||||
//! still *queued* behind the one being served, which is what the burst drain
|
||||
//! in `run` is for. See `docs/features/lucisv-server/README.md` and
|
||||
//! `docs/features/cancel-request/README.md`.
|
||||
//!
|
||||
//! The server is one directory of modules, each the answer to one question;
|
||||
//! this file holds the `Server` itself — what the client can do, what the
|
||||
//! server owns, and the loop (`run`, `process_batch`, the order contract in
|
||||
//! `must_wait`). The rest, in the order a message meets them:
|
||||
//!
|
||||
//! * `batch` — reading a burst before any of it is served: the forwarder
|
||||
//! thread, the drain, the cancels a burst carries, the `didOpen`s that widen
|
||||
//! the scope;
|
||||
//! * `dispatch` — `answer_request`, the table over request methods, with the
|
||||
//! decoding it needs and the `Failure` it answers in;
|
||||
//! * `large_file` — what a buffer over the large-file threshold answers
|
||||
//! instead of the dispatch;
|
||||
//! * `formatting` — the five formatting entries and how a refusal is said;
|
||||
//! * `semantic_tokens` — the remembered answer a token delta is computed
|
||||
//! against;
|
||||
//! * `diagnostics` — when a buffer is analyzed (the change debounce) and how
|
||||
//! what it says reaches the client, pushed or pulled;
|
||||
//! * `notification` — `handle_notification`, the table over notification
|
||||
//! methods, and the settings applier both settings doors share;
|
||||
//! * `index` — the rescans: whole, one file, widened, and the scan that
|
||||
//! answers messages while it runs;
|
||||
//! * `progress` — the indexing bar and the per-file log a rescan runs under;
|
||||
//! * `client` — what goes to the client other than a response: the requests
|
||||
//! made of it and the answers read back, the messages, the timing lines.
|
||||
//!
|
||||
//! Methods a sibling file calls are `pub(super)`; everything else is private
|
||||
//! to its file. The tests are in `tests/`, one file per feature.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::error::Error;
|
||||
|
||||
use lsp_server::{Connection, Message, RequestId};
|
||||
use lsp_types::notification::{Cancel, Notification as _};
|
||||
use lsp_types::{SemanticToken, Uri};
|
||||
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::Workspace;
|
||||
|
||||
use batch::{burst, cancelled_in, cancelled_response, forward};
|
||||
|
||||
mod batch;
|
||||
mod client;
|
||||
mod diagnostics;
|
||||
mod dispatch;
|
||||
mod formatting;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod notification;
|
||||
mod progress;
|
||||
mod semantic_tokens;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// What the client said it can do, read once at `initialize` because that is
|
||||
/// the only time those capabilities are sent.
|
||||
#[derive(Default)]
|
||||
pub struct ClientAbilities {
|
||||
/// Whether the client can expand a completion item's tabstops.
|
||||
pub snippets: bool,
|
||||
/// Whether the client accepts a `workspace/didChangeWatchedFiles`
|
||||
/// registration. There is no static form of that capability, so a client
|
||||
/// that says nothing keeps the save-only staleness model.
|
||||
pub file_watching: bool,
|
||||
/// Whether the client applies a `workspace/applyEdit` request. A client
|
||||
/// that cannot gets a command's edit back as the request result instead,
|
||||
/// which is what every client got before this was read.
|
||||
pub apply_edit: bool,
|
||||
/// Whether the client *pulls* diagnostics (LSP 3.17). One client is never
|
||||
/// served both models: a pulling client is pushed nothing at all.
|
||||
pub pull_diagnostics: bool,
|
||||
/// Whether the client renders server-initiated work-done progress. The
|
||||
/// spec forbids creating any without it, so a client that said nothing
|
||||
/// sees the workspace rescan exactly as it did before — silently.
|
||||
pub work_done_progress: bool,
|
||||
/// Whether the client accepts a `workspace/codeLens/refresh`. A client
|
||||
/// that said nothing is never asked, and keeps the instantiation counts it
|
||||
/// last requested until it asks again for its own reasons.
|
||||
pub code_lens_refresh: bool,
|
||||
/// Whether the client opens a document the server asks it to
|
||||
/// (`window/showDocument`). This is what lets the instantiation lens
|
||||
/// navigate; a client without it still gets the sites back as the
|
||||
/// command's result.
|
||||
pub show_document: bool,
|
||||
/// Whether the client answers `workspace/configuration` — the pull model
|
||||
/// for settings. A client that said nothing is only ever *pushed*
|
||||
/// settings, which is what every client got before this was read.
|
||||
pub configuration: bool,
|
||||
/// Whether the client understands a server-cancelled semantic-tokens
|
||||
/// request (`textDocument.semanticTokens.serverCancelSupport`). Decides
|
||||
/// which error code declines `semanticTokens/full` on a large buffer —
|
||||
/// see `docs/features/large-file-mode/README.md`.
|
||||
pub token_server_cancel: bool,
|
||||
/// Whether the client hosts the custom lucisv hierarchy sidebar and wants
|
||||
/// a notification whenever the installed workspace index changes.
|
||||
pub hierarchy_view: bool,
|
||||
}
|
||||
|
||||
/// Everything the server owns.
|
||||
pub struct Server {
|
||||
connection: Connection,
|
||||
workspace: Workspace,
|
||||
/// Documents whose `lucisv.toml` problem has already been reported. Cleared
|
||||
/// for a document whenever its text changes, so the warning is said once
|
||||
/// per file change rather than once per format-on-save.
|
||||
config_warnings: HashSet<Uri>,
|
||||
abilities: ClientAbilities,
|
||||
/// The id of the file-watcher registration in force, if any. Kept so a
|
||||
/// changed `lucisv.filelist` can replace it: the watched filelist path is
|
||||
/// part of the registration, so a new path needs a new registration.
|
||||
watchers: Option<String>,
|
||||
/// Numbers the file-watcher registrations, so a replacement can name the
|
||||
/// one it supersedes.
|
||||
registrations: u32,
|
||||
/// Numbers the requests made *of* the client. A repeated id is a protocol
|
||||
/// error, so this only ever counts up.
|
||||
request_ids: u32,
|
||||
/// The requests the server has made of the client whose answers it will
|
||||
/// act on, by the id they were sent with. Everything *not* in here is a
|
||||
/// request whose answer is ignorable, which is what makes `response`'s
|
||||
/// fall-through correct rather than lossy.
|
||||
pending: HashMap<RequestId, Pending>,
|
||||
/// Counts everything that can change what a pull request would answer: a
|
||||
/// buffer's text, and the workspace index. It is the whole of a
|
||||
/// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`.
|
||||
generation: u64,
|
||||
/// Revision of the completed index exposed to the custom hierarchy view.
|
||||
hierarchy_revision: u64,
|
||||
/// The last full-or-delta semantic-token answer for each open buffer —
|
||||
/// what a delta is computed *against*. Dropped on `didClose`, so this
|
||||
/// only ever holds what the editor is showing. See
|
||||
/// `docs/features/semantic-tokens-delta/README.md`.
|
||||
tokens: HashMap<Uri, TokenAnswer>,
|
||||
/// Numbers the semantic-token answers. Per answer, not per generation: a
|
||||
/// client's `previousResultId` has to name the exact data it holds, and
|
||||
/// two buffers' answers are never comparable.
|
||||
token_results: u64,
|
||||
/// Numbers the progress tokens the index rescans run under. One rescan is
|
||||
/// one token, and a token is never reused: a client keys the bar it is
|
||||
/// showing off it.
|
||||
indexings: u32,
|
||||
/// Buffers that are text-current but analysis-stale: the newest applied
|
||||
/// text for each, in first-dirtied order. A `didChange` lands here instead
|
||||
/// of running a reparse, and every one of them is flushed — analyzed,
|
||||
/// republished — by the first thing that needs the analysis: the next
|
||||
/// request, the next non-`didChange` notification, or the quiet-period
|
||||
/// timer in `run`. See `docs/features/change-debounce/README.md`.
|
||||
dirty: Vec<(Uri, String)>,
|
||||
/// Everything the client has sent, forwarded off the transport's
|
||||
/// rendezvous channel by [`forward`]. Held here rather than made in `run`
|
||||
/// because a **scan** drains it too: the loop must not go quiet for the
|
||||
/// length of one (`docs/features/scan-interleave/README.md`).
|
||||
queue: std::sync::mpsc::Receiver<Message>,
|
||||
/// Whether a scan is running. A message answered mid-scan can ask for
|
||||
/// another one, and this is what turns that into the flag below rather
|
||||
/// than a scan inside a scan.
|
||||
scanning: bool,
|
||||
/// A rescan asked for while a scan was running. Coalesced: any number of
|
||||
/// requests is one more scan when this one ends, whatever asked for them.
|
||||
rescan_wanted: bool,
|
||||
/// Whether the scan now running is one a *message* asked for. The startup
|
||||
/// scan is not — nothing was queued ahead of it — and that is the whole
|
||||
/// difference between a request answered mid-scan and one that waits. See
|
||||
/// [`Server::must_wait`].
|
||||
answering_a_rescan: bool,
|
||||
/// Whether the client has shut the server down. Set by a `shutdown`
|
||||
/// answered mid-scan, which stops the scan where it stands and keeps `run`
|
||||
/// from taking another message.
|
||||
stopped: bool,
|
||||
/// Messages a mid-scan drain would have answered out of order, kept in
|
||||
/// arrival order until the rescan they are queued behind has run. See
|
||||
/// [`Server::must_wait`] — this is the order contract, not a queue of its
|
||||
/// own.
|
||||
held: Vec<Message>,
|
||||
/// `--verbose`: whether every operation says how long it took, in the
|
||||
/// client's log channel. Off is the shipped state and the whole of what it
|
||||
/// costs is the branch that reads this field — see
|
||||
/// [`Server::timer`] and `docs/features/verbose-timing/README.md`.
|
||||
verbose: bool,
|
||||
}
|
||||
|
||||
/// How long a burst of `didChange` notifications may sit unanalyzed once the
|
||||
/// typing has stopped, before the quiet-period timer flushes them anyway. The
|
||||
/// coalescing this buys — one reparse per burst instead of one per keystroke —
|
||||
/// is worth nothing if diagnostics never arrive until the next request does.
|
||||
const CHANGE_DEBOUNCE: std::time::Duration = std::time::Duration::from_millis(150);
|
||||
|
||||
/// How many files a scan must have to be worth answering messages in the
|
||||
/// middle of.
|
||||
///
|
||||
/// **The whole trade of `docs/features/scan-interleave/README.md`, in one
|
||||
/// number.** A mid-scan answer reads the index as far as the scan has built
|
||||
/// it, so it can be *less* than the answer the same request would get a
|
||||
/// moment later — and that is only ever worth it when "a moment later" is a
|
||||
/// wait a person can feel. Below this, a scan is over in a few milliseconds
|
||||
/// (the 860-file corpus is 340 ms, so sixty-four files is under thirty), and
|
||||
/// trading a complete answer for those milliseconds would be a bad bargain;
|
||||
/// above it, the measured wait is hundreds of milliseconds and the trade is
|
||||
/// the point of the round.
|
||||
///
|
||||
/// A count rather than a clock deliberately: a rule about elapsed time makes
|
||||
/// what a server answers depend on how loaded the machine was, which is
|
||||
/// exactly the property a test suite — and a bug report — cannot work with.
|
||||
/// The known limit of counting is a workspace of a *few very large* files,
|
||||
/// which is under this bar and can still take a second; that is written down
|
||||
/// as a deliberate not-done rather than papered over with a second rule.
|
||||
const INTERLEAVE_ABOVE: usize = 64;
|
||||
|
||||
/// A request the server sent the client and still owes itself an answer to.
|
||||
///
|
||||
/// One map rather than one per kind: `response` then has a single lookup and
|
||||
/// a single `match`, and adding a third kind is a variant the compiler makes
|
||||
/// you handle rather than a map somebody forgets to consult.
|
||||
enum Pending {
|
||||
/// A `workspace/applyEdit`, remembering the command that asked for it so
|
||||
/// a refusal can be named to the user.
|
||||
ApplyEdit(String),
|
||||
/// A `workspace/configuration` asking for the `lucisv` section.
|
||||
Configuration,
|
||||
}
|
||||
|
||||
/// One semantic-token answer, kept so the next delta request can be answered
|
||||
/// against it.
|
||||
struct TokenAnswer {
|
||||
result_id: String,
|
||||
data: Vec<SemanticToken>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// The server, with its first index built.
|
||||
///
|
||||
/// The startup scan runs at the **default** settings — including the
|
||||
/// folder scope — because neither settings door can deliver anything
|
||||
/// before `initialized`; a client whose `lucisv.index.scope` differs pays
|
||||
/// one extra rescan when its settings land, exactly as `lucisv.exclude`
|
||||
/// has always cost one.
|
||||
pub fn new(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
) -> Server {
|
||||
Server::started(
|
||||
connection,
|
||||
roots,
|
||||
abilities,
|
||||
ClientSettings::default(),
|
||||
storage,
|
||||
verbose,
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
/// [`Server::new`] with a client's settings already in hand — the seam the
|
||||
/// tests start a session from. Only a test has any settings this early:
|
||||
/// one whose subject is not the scope says so here rather than driving a
|
||||
/// `didChangeConfiguration` and then reasoning about the extra rescan it
|
||||
/// buys.
|
||||
///
|
||||
/// `queued` is what the client had already sent when the server was built
|
||||
/// — the opening burst, put straight onto the queue the startup scan
|
||||
/// drains. Empty for [`Server::new`]; a test fills it because racing the
|
||||
/// forwarder thread for it would make the test a coin toss rather than a
|
||||
/// check.
|
||||
fn started(
|
||||
connection: Connection,
|
||||
roots: Vec<std::path::PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
client: ClientSettings,
|
||||
storage: Option<std::path::PathBuf>,
|
||||
verbose: bool,
|
||||
queued: Vec<Message>,
|
||||
) -> Server {
|
||||
// Started before the first scan, not in `run`: the scan below answers
|
||||
// whatever the client has already sent, and it can only do that off a
|
||||
// queue that is already being filled.
|
||||
let (forwarded, queue) = forward(&connection);
|
||||
for message in queued {
|
||||
let _ = forwarded.send(message);
|
||||
}
|
||||
let mut server = Server {
|
||||
connection,
|
||||
workspace: Workspace::default(),
|
||||
config_warnings: HashSet::new(),
|
||||
abilities,
|
||||
watchers: None,
|
||||
registrations: 0,
|
||||
request_ids: 0,
|
||||
pending: HashMap::new(),
|
||||
generation: 0,
|
||||
hierarchy_revision: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
indexings: 0,
|
||||
dirty: Vec::new(),
|
||||
queue,
|
||||
scanning: false,
|
||||
rescan_wanted: false,
|
||||
answering_a_rescan: false,
|
||||
stopped: false,
|
||||
held: Vec::new(),
|
||||
verbose,
|
||||
};
|
||||
// Nothing has been built yet, so there is no rebuild to owe: the
|
||||
// `true` this returns for a non-default `client` is the rebuild that
|
||||
// is about to happen anyway.
|
||||
let _ = server.workspace.set_client_settings(client);
|
||||
// Before the first build, because it is one rung of the ladder that
|
||||
// decides where that build reads its cache from
|
||||
// (`docs/features/index-persistence/README.md`).
|
||||
server.workspace.set_storage_path(storage);
|
||||
// The earliest legal moment for anything server-initiated: `main`
|
||||
// builds this only after `initialize_finish`, which returns once the
|
||||
// client's `initialized` notification has arrived — and consumes it,
|
||||
// so the loop below never sees one to hang these off instead. The
|
||||
// first index build is the slowest one of the session, so it gets the
|
||||
// same bar every later rescan gets.
|
||||
//
|
||||
// And it answers messages while it runs, which is what stops the first
|
||||
// request of a session waiting out the whole scan
|
||||
// (`docs/features/scan-interleave/README.md`). Everything below it is
|
||||
// therefore reached with the client's opening burst already handled —
|
||||
// and skipped altogether if that burst shut the server down.
|
||||
server.workspace.adopt_roots(roots);
|
||||
let warnings = server.scan_until_settled(false);
|
||||
if server.stopped {
|
||||
return server;
|
||||
}
|
||||
server.hierarchy_index_changed();
|
||||
// A buffer can now be *opened* during the startup scan, and what was
|
||||
// published for it then was computed against a half-built index. This
|
||||
// is the same debt a rescan pays at the end of `reindex`, owed here
|
||||
// for the first time because before this round no buffer could exist
|
||||
// at this point. Nothing at all is sent when nothing is open, which is
|
||||
// every session whose client did not get a `didOpen` in edgeways.
|
||||
if !server.workspace.open_uris().is_empty() {
|
||||
server.refresh_code_lenses();
|
||||
server.generation += 1;
|
||||
for uri in server.workspace.open_uris() {
|
||||
server.publish(&uri);
|
||||
}
|
||||
}
|
||||
server.report_scope(warnings);
|
||||
server.register_watchers();
|
||||
// The pull half of the settings model. Asked here because this is the
|
||||
// same moment the watchers are registered — the earliest legal one —
|
||||
// and answered later, in the loop: the settings therefore arrive
|
||||
// *after* the first index build, exactly as a pushed
|
||||
// `didChangeConfiguration` always has (it cannot arrive before
|
||||
// `initialized` either). A pulled `lucisv.exclude` or `lucisv.filelist`
|
||||
// costs one extra rescan when it lands; nothing is stale in between,
|
||||
// it is simply the default scope until the client answers.
|
||||
server.request_configuration();
|
||||
server
|
||||
}
|
||||
|
||||
/// Receive until the client shuts us down or the channel closes.
|
||||
///
|
||||
/// One blocking receive, then everything already queued behind it, then
|
||||
/// that whole burst in arrival order. The drain is what makes
|
||||
/// `$/cancelRequest` mean anything: while a handler runs, the client's
|
||||
/// later requests and its cancels for them pile up together, and a cancel
|
||||
/// found next to its request answers that request for free.
|
||||
///
|
||||
/// A buffer sitting dirty past [`CHANGE_DEBOUNCE`] with nothing arriving is
|
||||
/// flushed here rather than left waiting for a request that may never
|
||||
/// come — diagnostics are the one answer the client never asks for.
|
||||
pub fn run(&mut self) -> Result<(), Box<dyn Error + Sync + Send>> {
|
||||
use std::sync::mpsc::RecvTimeoutError;
|
||||
loop {
|
||||
// A `shutdown` the startup scan answered has already been through
|
||||
// `handle_shutdown`; there is nothing left to receive and nothing
|
||||
// left to answer.
|
||||
if self.stopped {
|
||||
return Ok(());
|
||||
}
|
||||
// Whatever a scan set aside is answered before anything newer is
|
||||
// taken — the rescan those messages were queued behind has run,
|
||||
// and they are older than everything still on the queue. Handling
|
||||
// them here rather than at the end of the scan is what keeps this
|
||||
// a loop instead of a scan inside a scan inside a scan.
|
||||
if !self.held.is_empty() {
|
||||
let batch = std::mem::take(&mut self.held);
|
||||
if self.process_batch(batch)? {
|
||||
return Ok(());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let message = if self.dirty.is_empty() {
|
||||
match self.queue.recv() {
|
||||
Ok(message) => message,
|
||||
Err(_) => return Ok(()),
|
||||
}
|
||||
} else {
|
||||
match self.queue.recv_timeout(CHANGE_DEBOUNCE) {
|
||||
Ok(message) => message,
|
||||
Err(RecvTimeoutError::Timeout) => {
|
||||
self.flush_dirty();
|
||||
continue;
|
||||
}
|
||||
Err(RecvTimeoutError::Disconnected) => return Ok(()),
|
||||
}
|
||||
};
|
||||
let batch = burst(&self.queue, message);
|
||||
if self.process_batch(batch)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle one burst in arrival order, reporting whether the client shut us
|
||||
/// down.
|
||||
///
|
||||
/// Order is the whole contract: a `didChange` queued ahead of a completion
|
||||
/// is applied before that completion is answered, exactly as it would be
|
||||
/// one message at a time. The only thing the burst adds is that a request
|
||||
/// this burst also carries a cancel for is answered `RequestCancelled`
|
||||
/// instead of computed — except `shutdown`, which is honoured before the
|
||||
/// cancelled set is ever consulted, so no cancel can talk the server out
|
||||
/// of shutting down.
|
||||
fn process_batch(&mut self, batch: Vec<Message>) -> Result<bool, Box<dyn Error + Sync + Send>> {
|
||||
let mut cancelled = cancelled_in(&batch);
|
||||
// Where this burst's own held messages have to be spliced in. A scan
|
||||
// this burst starts can hold messages of its *own* — ones that arrived
|
||||
// while it ran, and therefore after everything still in this burst —
|
||||
// so what is held from here goes in front of those and behind whatever
|
||||
// was already waiting when the burst began.
|
||||
let already_waiting = self.held.len();
|
||||
// The `$/cancelRequest`s this burst has already carried, kept only
|
||||
// long enough to put them back if a request behind them has to wait.
|
||||
let mut consumed_cancels: Vec<Message> = Vec::new();
|
||||
let mut messages = batch.into_iter();
|
||||
while let Some(message) = messages.next() {
|
||||
// A request that must wait takes everything behind it with it, or
|
||||
// the burst's arrival order would not survive the wait —
|
||||
// `shutdown` included, because a request sent before a shutdown
|
||||
// is a request the client is still owed an answer to.
|
||||
if self.must_wait() && matches!(message, Message::Request(_)) {
|
||||
self.say_held(&message);
|
||||
// The cancels this burst carried were consumed on the way
|
||||
// here, and `cancelled_in` runs again over the held batch — so
|
||||
// they go back in front of what they cancel rather than being
|
||||
// lost. A cancel naming nothing in the held batch is dropped
|
||||
// there exactly as it was dropped here.
|
||||
let mut rest: Vec<Message> = std::mem::take(&mut consumed_cancels);
|
||||
rest.push(message);
|
||||
rest.extend(messages);
|
||||
rest.extend(self.held.split_off(already_waiting));
|
||||
self.held.extend(rest);
|
||||
return Ok(false);
|
||||
}
|
||||
match message {
|
||||
Message::Request(request) => {
|
||||
if self.connection.handle_shutdown(&request)? {
|
||||
return Ok(true);
|
||||
}
|
||||
// Removed as it is used: a second cancel for the same id
|
||||
// then finds nothing, and the set cannot outlive the burst.
|
||||
let response = if cancelled.remove(&request.id) {
|
||||
cancelled_response(request.id)
|
||||
} else {
|
||||
self.request(request)
|
||||
};
|
||||
self.connection.sender.send(Message::Response(response))?;
|
||||
}
|
||||
// The cancels themselves are consumed here — `notification`
|
||||
// has nothing to do with one, and everything it could do has
|
||||
// already been done above. Kept only so that a request behind
|
||||
// one that has to wait takes its cancel with it.
|
||||
Message::Notification(notification) if notification.method == Cancel::METHOD => {
|
||||
consumed_cancels.push(Message::Notification(notification));
|
||||
}
|
||||
Message::Notification(notification) => self.notification(notification),
|
||||
Message::Response(response) => self.response(response),
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Whether a request reaching the dispatch right now must wait instead of
|
||||
/// being answered.
|
||||
///
|
||||
/// **This is the order contract, and it is the one thing interleaving a
|
||||
/// scan with the message loop must not cost.** The loop has always
|
||||
/// promised that everything queued *ahead* of a request is applied before
|
||||
/// that request is answered — a `didChange` before a completion, and
|
||||
/// equally a `didOpen` that widened the scope, a `didSave`, a changed
|
||||
/// setting or an added workspace folder before a go-to-definition. Those
|
||||
/// four ask for a rescan, and "applied" for them means the rescan has
|
||||
/// **run**: one message at a time, the server would have finished it
|
||||
/// before ever taking the request. Three clauses, one rule:
|
||||
///
|
||||
/// * `answering_a_rescan` — this scan is one a message asked for, so
|
||||
/// every request that arrives while it runs arrived *after* that
|
||||
/// message and is owed its effect;
|
||||
/// * `rescan_wanted` — a message in this very burst has just asked for
|
||||
/// one, and the requests behind it in the burst are owed the same;
|
||||
/// * `held` — a request is already waiting, and answering a newer one
|
||||
/// ahead of it would reorder them just as badly.
|
||||
///
|
||||
/// What is left answered mid-scan is exactly what is queued behind
|
||||
/// *nothing*: the opening burst of a session, whose scan is the server's
|
||||
/// own startup and not something a message asked for. That is the case
|
||||
/// the round is about, and it is the one a user feels
|
||||
/// (`docs/features/scan-interleave/README.md`).
|
||||
fn must_wait(&self) -> bool {
|
||||
self.answering_a_rescan || self.rescan_wanted || !self.held.is_empty()
|
||||
}
|
||||
|
||||
/// Whether the installed index covers the whole scope with no indexing
|
||||
/// work outstanding — what the hierarchy snapshot reports as `complete`.
|
||||
///
|
||||
/// **Both clauses, not just `scanning`.** `!self.scanning` alone would be
|
||||
/// answering "is a scan running *this instant*", and a snapshot taken
|
||||
/// between a finished scan and a rescan already asked for would call a
|
||||
/// stale index complete. Today [`Server::must_wait`] makes that
|
||||
/// unreachable — a request arriving with `rescan_wanted` set or anything
|
||||
/// `held` is set aside rather than answered, so a snapshot only ever
|
||||
/// reaches this function when both are already clear, and `rescan_wanted`
|
||||
/// is in any case only ever set while `scanning` is true. Saying it here
|
||||
/// anyway costs nothing and means the honesty of the flag does not depend
|
||||
/// on a scheduling invariant two hundred lines away staying true; a
|
||||
/// hypothetical future exemption from `must_wait` would degrade the flag,
|
||||
/// not break it. Pinned by
|
||||
/// `a_snapshot_is_never_answered_complete_while_a_rescan_is_owed`.
|
||||
fn index_is_complete(&self) -> bool {
|
||||
!self.scanning && !self.must_wait()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! `handle_notification`: the dispatch table over notification methods.
|
||||
//!
|
||||
//! Everything the client tells the server without expecting an answer —
|
||||
//! documents opened, changed, saved and closed; files and folders moved on
|
||||
//! disk; settings pushed — comes through the one `match` here, which stays
|
||||
//! whole for the same reason `answer_request` does. With it are the three
|
||||
//! decoders only it uses and `apply_settings`, the one applier the pushed and
|
||||
//! the pulled settings share so the two doors can never disagree about what a
|
||||
//! setting costs.
|
||||
|
||||
use lsp_server::{ExtractError, Notification};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, Notification as _,
|
||||
};
|
||||
use lsp_types::{
|
||||
DeleteFilesParams, DidChangeConfigurationParams, DidChangeTextDocumentParams,
|
||||
DidChangeWatchedFilesParams, DidChangeWorkspaceFoldersParams, DidCloseTextDocumentParams,
|
||||
DidOpenTextDocumentParams, DidSaveTextDocumentParams, RenameFilesParams, Uri, WorkspaceFolder,
|
||||
};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use super::batch::{widen_of, Widen};
|
||||
use super::client::ms;
|
||||
use super::Server;
|
||||
use crate::{file_ops, settings, sync, watch};
|
||||
|
||||
impl Server {
|
||||
/// Handle one notification, timing it when `--verbose` asked. A
|
||||
/// notification has no response, so there is no ordering question here:
|
||||
/// the line follows the work.
|
||||
pub(super) fn notification(&mut self, notification: Notification) {
|
||||
let Some(started) = self.timer() else { return self.handle_notification(notification) };
|
||||
let method = notification.method.clone();
|
||||
self.handle_notification(notification);
|
||||
self.timing(format!("{method} handled in {}", ms(started)));
|
||||
}
|
||||
|
||||
fn handle_notification(&mut self, notification: Notification) {
|
||||
let method = notification.method.clone();
|
||||
// A closing buffer's pending text is dropped *before* the flush, not
|
||||
// in the `didClose` arm below it: the flush would otherwise analyze
|
||||
// and publish diagnostics for a file the client has stopped looking
|
||||
// at, only for the close handler to clear them again a line later.
|
||||
// Every other dirty buffer still flushes, as it must — closing one
|
||||
// file says nothing about the rest (QA, change-debounce CD-1).
|
||||
if method == DidCloseTextDocument::METHOD {
|
||||
if let Some(uri) = closing_uri(¬ification) {
|
||||
self.dirty.retain(|(pending, _)| *pending != uri);
|
||||
}
|
||||
}
|
||||
// Everything but a `didChange` needs the buffers' analyses current —
|
||||
// a `didSave` rebuilds the index on top of them — so the same flush a
|
||||
// request gets happens here, with the one exception that *is* the
|
||||
// thing being deferred.
|
||||
if method != DidChangeTextDocument::METHOD {
|
||||
self.flush_dirty();
|
||||
}
|
||||
match method.as_str() {
|
||||
DidOpenTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidOpenTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
// Opening a file in a folder the index does not cover
|
||||
// *widens the scope*, so the folders it added are indexed
|
||||
// and folded into the index beside what is already there;
|
||||
// the widen rides the same bar and the same generation bump
|
||||
// every other rescan trigger does. Opening one the scope
|
||||
// already covers changes nothing about which files exist,
|
||||
// and the save path still owns rebuilding.
|
||||
//
|
||||
// Only a *pure add* takes the cheap path, and `widen_of` is
|
||||
// where that is decided: anything else — a scope directory
|
||||
// that left, which nothing does today — falls back to the
|
||||
// whole rescan (`docs/features/index-scope/README.md`).
|
||||
//
|
||||
// This is the rootless rule from before 2026-08-27,
|
||||
// generalized: rung 3 is now the default rung with a root
|
||||
// too, so "did this file widen the scope" is the one test,
|
||||
// and it answers "no" for the filelist and whole-workspace
|
||||
// rungs, which an open buffer cannot widen.
|
||||
let before = self.workspace.scope_dirs();
|
||||
self.set_document(uri.clone(), p.text_document.text);
|
||||
match widen_of(&before, &self.workspace.scope_dirs()) {
|
||||
Widen::Nothing => self.publish(&uri),
|
||||
Widen::Added(dirs) => self.reindex_widened(dirs),
|
||||
Widen::Whole => self.reindex(),
|
||||
}
|
||||
}
|
||||
}
|
||||
DidChangeTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeTextDocumentParams>(notification) {
|
||||
// Incremental sync: the changes are ranges into the buffer
|
||||
// we hold — the newest applied text, which while dirty is
|
||||
// the pending one, not the last analyzed one — applied in
|
||||
// order. A full-sync client's rangeless change still
|
||||
// replaces the whole buffer, so "the last one wins" stays
|
||||
// true for it. A burst of changes is coalesced into one
|
||||
// `set_document` — one reparse, one generation bump — when
|
||||
// the buffer is flushed; see `mark_dirty`.
|
||||
if p.content_changes.is_empty() {
|
||||
return;
|
||||
}
|
||||
let uri = p.text_document.uri;
|
||||
let text = {
|
||||
let base = self
|
||||
.dirty
|
||||
.iter()
|
||||
.find(|(pending, _)| *pending == uri)
|
||||
.map(|(_, text)| text.as_str())
|
||||
.or_else(|| self.workspace.document(&uri).map(|doc| doc.text.as_str()))
|
||||
.unwrap_or("");
|
||||
sync::apply_changes(base, &p.content_changes)
|
||||
};
|
||||
self.mark_dirty(uri, text);
|
||||
}
|
||||
}
|
||||
DidSaveTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidSaveTextDocumentParams>(notification) {
|
||||
if let Some(text) = p.text {
|
||||
self.set_document(p.text_document.uri.clone(), text);
|
||||
}
|
||||
// A save is one of the things that rebuild the index; the
|
||||
// others are a change to `lucisv.exclude`/`lucisv.filelist`
|
||||
// below, and a watched file changing on disk. The
|
||||
// staleness window that is left is in the feature README.
|
||||
//
|
||||
// A save names exactly one file, which is the case the
|
||||
// index can replace in place — so this is where the
|
||||
// incremental path earns its keep, and the whole rebuild is
|
||||
// the fallback for a file the index does not already hold.
|
||||
let one = crate::uri::uri_to_path(&p.text_document.uri);
|
||||
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
|
||||
self.reindex();
|
||||
}
|
||||
}
|
||||
}
|
||||
// Something changed on disk that no buffer told us about — a `git
|
||||
// pull`, a checkout, a generated file, an externally edited
|
||||
// filelist. One rebuild per *notification*, never one per file:
|
||||
// the params carry a list, and a checkout fills it.
|
||||
DidChangeWatchedFiles::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeWatchedFilesParams>(notification) {
|
||||
let filelist = self.workspace.filelist_path();
|
||||
if watch::touches_scope(&p.changes, filelist.as_deref()) {
|
||||
// One file named is the incremental case; a checkout
|
||||
// filling the list, or the filelist itself moving, is
|
||||
// the whole rebuild.
|
||||
let one = watch::one_scope_file(&p.changes, filelist.as_deref());
|
||||
if !one.is_some_and(|path| self.reindex_one(path.as_path())) {
|
||||
self.reindex();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The client moved or removed files itself. The same nudge a
|
||||
// watched-file event gives, filtered by the same predicate, and
|
||||
// deliberately not deduplicated against it: a client is free to
|
||||
// send both, and a second rebuild is a pure re-read of the tree —
|
||||
// it costs one scan and one diagnostics generation, never a
|
||||
// different answer.
|
||||
DidRenameFiles::METHOD => {
|
||||
if let Ok(p) = extract::<RenameFilesParams>(notification) {
|
||||
self.reindex_for(file_ops::renamed(&p.files));
|
||||
}
|
||||
}
|
||||
DidDeleteFiles::METHOD => {
|
||||
if let Ok(p) = extract::<DeleteFilesParams>(notification) {
|
||||
self.reindex_for(file_ops::deleted(&p.files));
|
||||
}
|
||||
}
|
||||
// The `lucisv.*` settings, pushed at startup and on every change.
|
||||
// Nothing here trusts the payload — `settings::from_payload`
|
||||
// drops whatever it cannot use.
|
||||
//
|
||||
// An **empty** payload is not a settings payload at all: it is the
|
||||
// 3.17 client saying "something changed, ask me for what you
|
||||
// need", so a client that can be asked is asked and nothing is
|
||||
// applied until it answers. A client that cannot be asked keeps
|
||||
// the behaviour it has always had — an empty payload is no
|
||||
// opinion about anything, which resolves to the defaults.
|
||||
DidChangeConfiguration::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeConfigurationParams>(notification) {
|
||||
if settings::says_nothing(&p.settings) && self.abilities.configuration {
|
||||
self.request_configuration();
|
||||
return;
|
||||
}
|
||||
self.apply_settings(settings::from_payload(&p.settings));
|
||||
}
|
||||
}
|
||||
// The user added or removed a workspace folder mid-session. One
|
||||
// rescan per *notification* — an event carries both lists, and
|
||||
// the progress bar, the code-lens refresh and the diagnostics
|
||||
// generation all ride along inside `reindex()`. An event that
|
||||
// changes nothing (a folder already held, one never held, an
|
||||
// empty event) rescans nothing.
|
||||
DidChangeWorkspaceFolders::METHOD => {
|
||||
if let Ok(p) = extract::<DidChangeWorkspaceFoldersParams>(notification) {
|
||||
let watched = self.workspace.filelist_path();
|
||||
let added = folder_paths(&p.event.added);
|
||||
let removed = folder_paths(&p.event.removed);
|
||||
if self.workspace.change_roots(added, &removed) {
|
||||
self.reindex();
|
||||
}
|
||||
// A relative `lucisv.filelist` is anchored at the *first*
|
||||
// root, so a folder change can move the watched path
|
||||
// without anyone touching the setting. Same rule, same
|
||||
// reason as a changed setting: the path is baked into the
|
||||
// registration. The source glob itself is workspace-wide
|
||||
// and needs no re-registration — see
|
||||
// `docs/features/folders-and-config/README.md`.
|
||||
if self.workspace.filelist_path() != watched {
|
||||
self.register_watchers();
|
||||
}
|
||||
}
|
||||
}
|
||||
DidCloseTextDocument::METHOD => {
|
||||
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.config_warnings.remove(&uri);
|
||||
// The buffer's unanalyzed change is already gone — it was
|
||||
// dropped at the top of this function, ahead of the flush
|
||||
// that would otherwise have analyzed it.
|
||||
//
|
||||
// The remembered token answer goes with the buffer: the
|
||||
// client drops what it was holding too, and nothing may
|
||||
// grow with the number of files ever opened.
|
||||
self.tokens.remove(&uri);
|
||||
self.workspace.close_document(&uri);
|
||||
// Clear what we drew: the buffer is gone.
|
||||
self.send_diagnostics(uri, Vec::new());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Adopt `lucisv.*` settings, from wherever they came, and pay whatever
|
||||
/// they cost.
|
||||
///
|
||||
/// One applier for the push and the pull, so the two can never disagree
|
||||
/// about what a setting *does* any more than `settings::from_payload` and
|
||||
/// `from_section` can disagree about what it says.
|
||||
pub(super) fn apply_settings(&mut self, settings: settings::ClientSettings) {
|
||||
let watched = self.workspace.filelist_path();
|
||||
let linted = self.lint_selection();
|
||||
// Only `exclude` and `filelist` change which files exist as far as
|
||||
// this server is concerned; the other settings are read afresh by the
|
||||
// next request that wants them and need no invalidation.
|
||||
if self.workspace.set_client_settings(settings) {
|
||||
self.reindex();
|
||||
} else if self.lint_selection() != linted {
|
||||
// `lucisv.lint.select`/`ignore` change which rules run and nothing
|
||||
// else: no file's contents moved, so there is nothing to rescan —
|
||||
// but every published squiggle was drawn under the old selection,
|
||||
// and a client that pulls has cached answers under it too.
|
||||
self.generation += 1;
|
||||
for uri in self.workspace.open_uris() {
|
||||
self.publish(&uri);
|
||||
}
|
||||
}
|
||||
// The watched filelist path is baked into the registration, so a new
|
||||
// one needs a new registration.
|
||||
if self.workspace.filelist_path() != watched {
|
||||
self.register_watchers();
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule selection in force, as a value two settings pushes can be
|
||||
/// compared by.
|
||||
fn lint_selection(&self) -> (Vec<String>, Vec<String>) {
|
||||
let client = self.workspace.client_settings();
|
||||
(client.lint_select.clone(), client.lint_ignore.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// A notification's params, or `Err` when they do not parse — a malformed
|
||||
/// notification is dropped, because there is no id to answer it on.
|
||||
fn extract<P: DeserializeOwned>(
|
||||
notification: Notification,
|
||||
) -> Result<P, ExtractError<Notification>> {
|
||||
let method = notification.method.clone();
|
||||
notification.extract(&method)
|
||||
}
|
||||
|
||||
/// The buffer a `didClose` names, read without consuming the notification —
|
||||
/// the close handler runs after the flush, and dropping a pending change has
|
||||
/// to happen before it. `None` for params that do not parse, which the
|
||||
/// handler below ignores in exactly the same way.
|
||||
fn closing_uri(notification: &Notification) -> Option<Uri> {
|
||||
serde_json::from_value::<DidCloseTextDocumentParams>(notification.params.clone())
|
||||
.ok()
|
||||
.map(|p| p.text_document.uri)
|
||||
}
|
||||
|
||||
/// The paths behind a `didChangeWorkspaceFolders` list.
|
||||
///
|
||||
/// A folder whose URI is not a `file:` URI — or is not valid UTF-8 once
|
||||
/// decoded — is dropped rather than guessed at, the same rule `uri.rs` holds
|
||||
/// everywhere else: there is nothing on disk to walk for it.
|
||||
fn folder_paths(folders: &[WorkspaceFolder]) -> Vec<std::path::PathBuf> {
|
||||
folders.iter().filter_map(|folder| crate::uri::uri_to_path(&folder.uri)).collect()
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
//! The indexing bar and the per-file log a rescan runs under.
|
||||
//!
|
||||
//! `begin_indexing` puts the bar up and `end_indexing` takes it down with
|
||||
//! the count; between them `IndexWatch` — which holds the connection rather
|
||||
//! than the `Server`, because the workspace is borrowed mutably for the
|
||||
//! whole of the rebuild it watches — turns each `IndexEvent` into a report
|
||||
//! and a log line, thinned past `MAX_REPORTS` files so a 40 000-file
|
||||
//! workspace does not send 40 000 notifications per save. Its own file
|
||||
//! because it is the one part of a rescan that is about *saying* rather than
|
||||
//! *doing*, and `index.rs` reads better without it.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use lsp_server::Connection;
|
||||
use lsp_types::notification::{LogMessage, Notification as _, Progress};
|
||||
use lsp_types::request::{Request as _, WorkDoneProgressCreate};
|
||||
use lsp_types::{
|
||||
LogMessageParams, MessageType, ProgressParams, ProgressParamsValue, ProgressToken,
|
||||
WorkDoneProgress, WorkDoneProgressBegin, WorkDoneProgressCreateParams, WorkDoneProgressEnd,
|
||||
WorkDoneProgressReport,
|
||||
};
|
||||
|
||||
use super::client::notify_on;
|
||||
use super::Server;
|
||||
use crate::settings::ClientSettings;
|
||||
use crate::state::IndexEvent;
|
||||
|
||||
/// What the workspace-rescan progress bar calls itself. One title for every
|
||||
/// rescan — startup, save, watched file, changed scope — because they are the
|
||||
/// same work and a user reading the status bar wants to know that.
|
||||
const INDEXING_TITLE: &str = "Indexing Verilog workspace";
|
||||
|
||||
impl Server {
|
||||
/// Put a progress bar up for the rescan that is about to run, and report
|
||||
/// the token it must be taken down with. `None` for a client that cannot
|
||||
/// show one — the spec forbids creating progress it never asked for.
|
||||
///
|
||||
/// The `begin` goes out immediately after the `create`, without waiting
|
||||
/// for its answer: the rescan blocks this thread the moment this returns,
|
||||
/// so waiting would mean the bar appears only once the work it describes
|
||||
/// is over. The spec allows it, and a client that errors the `create`
|
||||
/// ignores the `$/progress` that follows.
|
||||
///
|
||||
/// The `begin` carries no percentage: the first one that means anything
|
||||
/// is the first file's, and it is `IndexWatch` that sends it. Every
|
||||
/// percentage from there on is measured — `n` files of a work list whose
|
||||
/// length was known before the first parse — never invented.
|
||||
pub(super) fn begin_indexing(&mut self) -> Option<ProgressToken> {
|
||||
if !self.abilities.work_done_progress {
|
||||
return None;
|
||||
}
|
||||
let token = ProgressToken::String(format!("lucisv-index-{}", self.indexings));
|
||||
self.indexings += 1;
|
||||
let params = WorkDoneProgressCreateParams { token: token.clone() };
|
||||
self.send_request(WorkDoneProgressCreate::METHOD, params);
|
||||
self.progress(
|
||||
token.clone(),
|
||||
WorkDoneProgress::Begin(WorkDoneProgressBegin {
|
||||
title: INDEXING_TITLE.to_string(),
|
||||
// Nothing already running in this server can be cancelled: the
|
||||
// loop is one thread and a rescan runs to completion — the
|
||||
// `$/cancelRequest` support only answers requests still
|
||||
// queued. Saying so is what keeps a cancel button the user
|
||||
// could press off the bar.
|
||||
cancellable: Some(false),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
Some(token)
|
||||
}
|
||||
|
||||
/// Take the bar down, naming what the rescan found. The count is the
|
||||
/// index's own file list, which is the only number this costs nothing to
|
||||
/// know. Called the moment the rescan returns, before the scope warnings
|
||||
/// and the republishes — the bar names the scan, and what follows it is
|
||||
/// per-open-buffer work the user already pays on every keystroke.
|
||||
///
|
||||
/// `skipped` is how many files the size cap kept out, and it is named here
|
||||
/// whether or not the per-file log is on: the log is the *detail*, and a
|
||||
/// user who turned it off should still learn that part of their workspace
|
||||
/// is not in the index. `cached` is how many were restored from the
|
||||
/// persistent index cache rather than parsed, and is named for the
|
||||
/// opposite reason — a scan that finished suspiciously fast should say
|
||||
/// why (`docs/features/index-persistence/README.md`).
|
||||
pub(super) fn end_indexing(&self, token: Option<ProgressToken>, skipped: usize, cached: usize) {
|
||||
let Some(token) = token else { return };
|
||||
let files = self.workspace.index().files().len();
|
||||
let plural = if files == 1 { "" } else { "s" };
|
||||
let mut message = format!("{files} file{plural} indexed");
|
||||
if cached > 0 {
|
||||
message.push_str(&format!(", {cached} from cache"));
|
||||
}
|
||||
if skipped > 0 {
|
||||
message.push_str(&format!(", {skipped} skipped"));
|
||||
}
|
||||
self.progress(token, WorkDoneProgress::End(WorkDoneProgressEnd { message: Some(message) }));
|
||||
}
|
||||
|
||||
/// One `$/progress` notification for a token the client already knows.
|
||||
fn progress(&self, token: ProgressToken, value: WorkDoneProgress) {
|
||||
progress_on(&self.connection, &token, value);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many `$/progress` reports one rescan may send.
|
||||
///
|
||||
/// One per file is right for the workspaces people actually have — the 860-file
|
||||
/// corpus is 860 small notifications across two thirds of a second — but a
|
||||
/// 40,000-file filelist would be 40,000 of them on every save. Past this many
|
||||
/// files the reports thin out to every ⌈total/1000⌉-th, which still moves the
|
||||
/// bar by a tenth of a percent at a time: under a pixel.
|
||||
pub(super) const MAX_REPORTS: usize = 1000;
|
||||
|
||||
/// Whether the file numbered `done` (from 0) of `total` gets a `report`.
|
||||
///
|
||||
/// The last file always reports, so a rescan's final bar position is always
|
||||
/// `total/total` at 100%. Without that, a 10,000-file scan would stop
|
||||
/// reporting at 10,000 exactly — but a 10,001-file one would stop at 10,000
|
||||
/// and leave the bar a file short of the work it had finished.
|
||||
pub(super) fn reports(done: usize, total: usize) -> bool {
|
||||
let step = total.div_ceil(MAX_REPORTS).max(1);
|
||||
(done + 1).is_multiple_of(step) || done + 1 == total
|
||||
}
|
||||
|
||||
/// Watches one index rebuild: a `$/progress` report and a log line per file,
|
||||
/// and a count of the files the size cap skipped.
|
||||
///
|
||||
/// Holds the connection rather than the `Server`, because the workspace is
|
||||
/// borrowed mutably for the whole of the rebuild being watched. Everything it
|
||||
/// sends is a notification, so nothing here can fail in a way a caller could
|
||||
/// act on.
|
||||
pub(super) struct IndexWatch<'a> {
|
||||
connection: &'a Connection,
|
||||
/// The bar to report against — `None` for a client that cannot show one,
|
||||
/// which is the same gate `begin_indexing` applied.
|
||||
bar: Option<&'a ProgressToken>,
|
||||
/// `lucisv.index.logFiles`: whether the per-file lines are sent at all.
|
||||
log_files: bool,
|
||||
}
|
||||
|
||||
impl<'a> IndexWatch<'a> {
|
||||
pub(super) fn new(
|
||||
connection: &'a Connection,
|
||||
bar: Option<&'a ProgressToken>,
|
||||
settings: &ClientSettings,
|
||||
) -> IndexWatch<'a> {
|
||||
IndexWatch { connection, bar, log_files: settings.log_files }
|
||||
}
|
||||
|
||||
/// Report one thing the rebuild just did.
|
||||
pub(super) fn see(&mut self, event: IndexEvent) {
|
||||
match event {
|
||||
IndexEvent::Parsing { done, total, path } => {
|
||||
self.say(format!("indexing: {}", path.display()));
|
||||
self.tick(done, total, path);
|
||||
}
|
||||
// A different word for a file that cost nothing, and the same
|
||||
// tick: a cached file is a file of the work list, and the bar
|
||||
// flying through them is exactly what the cache bought.
|
||||
IndexEvent::Cached { done, total, path } => {
|
||||
self.say(format!("cached: {}", path.display()));
|
||||
self.tick(done, total, path);
|
||||
}
|
||||
// A third word, and no count in the end message: an open buffer's
|
||||
// own analysis costs nothing either, but one file out of a
|
||||
// workspace is not why a scan finished fast, and a bar that grew a
|
||||
// clause on every session with a file open would say less, not
|
||||
// more. The per-file log still names it, which is where a user
|
||||
// asking "did it re-parse my huge buffer?" looks.
|
||||
IndexEvent::Analyzed { done, total, path } => {
|
||||
self.say(format!("analyzed: {}", path.display()));
|
||||
self.tick(done, total, path);
|
||||
}
|
||||
IndexEvent::Skipped { path, size, cap } => {
|
||||
self.say(format!(
|
||||
"skipped ({} > {} cap): {}",
|
||||
human_size(size),
|
||||
human_size(cap),
|
||||
path.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Move the bar to `done + 1` of `total`, if this file is one of the ones
|
||||
/// that reports.
|
||||
///
|
||||
/// The message names the file rather than its path: the bar is a strip of
|
||||
/// status bar a few dozen characters wide, and the path is in the log for
|
||||
/// anyone who wants it. The percentage is `(done + 1) / total`, which
|
||||
/// only ever counts up.
|
||||
fn tick(&self, done: usize, total: usize, path: &Path) {
|
||||
let Some(token) = self.bar else { return };
|
||||
if !reports(done, total) {
|
||||
return;
|
||||
}
|
||||
let name = path.file_name().unwrap_or(path.as_os_str()).to_string_lossy();
|
||||
let report = WorkDoneProgressReport {
|
||||
cancellable: Some(false),
|
||||
message: Some(format!("{}/{total} {name}", done + 1)),
|
||||
// `total` cannot be 0 here — this is called from inside the loop
|
||||
// over the files — but a percentage is not worth a division that
|
||||
// has to be argued about.
|
||||
percentage: Some(((done + 1) * 100 / total.max(1)) as u32),
|
||||
};
|
||||
progress_on(self.connection, token, WorkDoneProgress::Report(report));
|
||||
}
|
||||
|
||||
/// One line in the client's output channel, if the user left the file log
|
||||
/// on.
|
||||
///
|
||||
/// `MessageType::LOG`, unprefixed: these are hundreds of lines per rescan
|
||||
/// in a channel that is already this server's, and "lucisv: " on every one
|
||||
/// of them would be noise plus traffic. The scope warnings, which are
|
||||
/// rare and also shown in a popup, keep their prefix.
|
||||
fn say(&self, message: String) {
|
||||
if !self.log_files {
|
||||
return;
|
||||
}
|
||||
let params = LogMessageParams { typ: MessageType::LOG, message };
|
||||
notify_on(self.connection, LogMessage::METHOD, params);
|
||||
}
|
||||
}
|
||||
|
||||
/// A byte count in the largest unit that keeps it readable.
|
||||
///
|
||||
/// The cap is written in bytes and can be set to anything, so a fixed unit is
|
||||
/// wrong at one end or the other: "0.0 MiB > 0.0 MiB cap" says nothing about a
|
||||
/// 4 KiB file under a 1 KiB cap, and "4194304 B" says nothing quickly about a
|
||||
/// netlist.
|
||||
fn human_size(bytes: u64) -> String {
|
||||
const KIB: f64 = 1024.0;
|
||||
const MIB: f64 = KIB * 1024.0;
|
||||
// The unit is chosen by what the ROUNDED number reads as, not the raw
|
||||
// size: 1 048 575 bytes is "1.0 MiB", never "1024.0 KiB" (QA log,
|
||||
// 2026-08-27 — the same class of bug the e2e's "0.0 MiB > 0.0 MiB"
|
||||
// caught at the opposite edge).
|
||||
let size = bytes as f64;
|
||||
if size < KIB {
|
||||
format!("{bytes} B")
|
||||
} else if (size / KIB).round() < KIB {
|
||||
format!("{:.1} KiB", size / KIB)
|
||||
} else {
|
||||
format!("{:.1} MiB", size / MIB)
|
||||
}
|
||||
}
|
||||
|
||||
/// One `$/progress` notification, on a connection rather than through a
|
||||
/// `Server` — what the index watcher has while the workspace is borrowed.
|
||||
fn progress_on(connection: &Connection, token: &ProgressToken, value: WorkDoneProgress) {
|
||||
let params =
|
||||
ProgressParams { token: token.clone(), value: ProgressParamsValue::WorkDone(value) };
|
||||
notify_on(connection, Progress::METHOD, params);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod human_size_tests {
|
||||
use super::human_size;
|
||||
|
||||
#[test]
|
||||
fn the_unit_is_chosen_by_what_the_rounded_number_reads_as() {
|
||||
// QA finding, 2026-08-27: a byte short of a MiB must not print as
|
||||
// "1024.0 KiB". The unit flips when the smaller unit's rounded
|
||||
// number would read as the next unit.
|
||||
assert_eq!(human_size(1_048_575), "1.0 MiB");
|
||||
assert_eq!(human_size(1_048_576), "1.0 MiB");
|
||||
assert_eq!(human_size(1023), "1023 B");
|
||||
assert_eq!(human_size(1024), "1.0 KiB");
|
||||
assert_eq!(human_size(4_096), "4.0 KiB");
|
||||
assert_eq!(human_size(2_411_724), "2.3 MiB");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
//! Semantic tokens with a memory: the full answer that is stamped and kept,
|
||||
//! and the delta computed against it.
|
||||
//!
|
||||
//! The encoding is `crate::tokens`'; this file is only the bookkeeping the
|
||||
//! delta form needs — one remembered answer per open buffer, dropped on
|
||||
//! `didClose` — which is state and so belongs to the `Server`. See
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
|
||||
use lsp_types::{
|
||||
SemanticToken, SemanticTokens, SemanticTokensDelta, SemanticTokensFullDeltaResult, Uri,
|
||||
};
|
||||
|
||||
use super::{Server, TokenAnswer};
|
||||
use crate::tokens;
|
||||
|
||||
impl Server {
|
||||
/// The whole buffer's tokens, stamped and remembered.
|
||||
///
|
||||
/// A client may mix `full` and `full/delta` freely — the protocol lets it
|
||||
/// — so this answer is remembered exactly as a delta's is, and its
|
||||
/// `resultId` is as good a starting point for the next delta.
|
||||
pub(super) fn semantic_tokens_full(&mut self, uri: &Uri) -> Option<SemanticTokens> {
|
||||
let data = tokens::semantic_tokens(self.workspace.document(uri)?);
|
||||
let result_id = self.remember_tokens(uri, data.clone());
|
||||
Some(SemanticTokens { result_id: Some(result_id), data })
|
||||
}
|
||||
|
||||
/// What changed since the answer the client says it holds.
|
||||
///
|
||||
/// A `previousResultId` that does not name the answer we remember — a
|
||||
/// stale one, a buffer we have no state for, one from before a
|
||||
/// `didClose` — is answered with a full set instead. The protocol allows
|
||||
/// either, and a delta against data we cannot see would be a guess.
|
||||
pub(super) fn semantic_tokens_delta(
|
||||
&mut self,
|
||||
uri: &Uri,
|
||||
previous: &str,
|
||||
) -> Option<SemanticTokensFullDeltaResult> {
|
||||
let new = tokens::semantic_tokens(self.workspace.document(uri)?);
|
||||
let known = self.tokens.get(uri).filter(|answer| answer.result_id == previous);
|
||||
let edits = known.map(|answer| tokens::delta(&answer.data, &new));
|
||||
let result_id = Some(self.remember_tokens(uri, new.clone()));
|
||||
Some(match edits {
|
||||
Some(edits) => {
|
||||
SemanticTokensFullDeltaResult::TokensDelta(SemanticTokensDelta { result_id, edits })
|
||||
}
|
||||
None => SemanticTokensFullDeltaResult::Tokens(SemanticTokens { result_id, data: new }),
|
||||
})
|
||||
}
|
||||
|
||||
/// Stamp an answer with a fresh id and keep it as the one the next delta
|
||||
/// is computed against. One buffer holds one answer: a client that asks
|
||||
/// again has moved on from the previous one.
|
||||
fn remember_tokens(&mut self, uri: &Uri, data: Vec<SemanticToken>) -> String {
|
||||
self.token_results += 1;
|
||||
let result_id = self.token_results.to_string();
|
||||
self.tokens.insert(uri.clone(), TokenAnswer { result_id: result_id.clone(), data });
|
||||
result_id
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! `workspace/applyEdit`: how a command's edit reaches the client, and what a refusal says.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `workspace/applyEdit`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_command_pushes_its_edit_when_the_client_can_apply_one() {
|
||||
// The bug this fixes: the edit used to be the request *result*, which
|
||||
// the protocol does not define and every stock client drops.
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("applyedit", abilities);
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert_eq!(result, Value::Null, "the edit is not the result any more");
|
||||
|
||||
let sent = session.sent();
|
||||
assert_eq!(sent.len(), 1, "{sent:#?}");
|
||||
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
|
||||
assert_eq!(
|
||||
sent[0].params["label"],
|
||||
serde_json::json!(format!("lucisv: {}", ports::PROPAGATE_PORTS)),
|
||||
"the undo stack needs a name for it"
|
||||
);
|
||||
let changes = sent[0].params["edit"]["changes"].as_object().expect("changes");
|
||||
let edits = changes.values().next().expect("one file edited");
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)", "{:#?}", sent[0].params);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_apply_edits_still_gets_the_edit_back() {
|
||||
// The documented fallback: for such a client, returning the edit is
|
||||
// the only thing that could ever work.
|
||||
let (_tree, mut session, params) = propagating("noapplyedit", ClientAbilities::default());
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
let changes = result["changes"].as_object().expect("the edit is the result");
|
||||
let edits = changes.values().next().expect("one file edited");
|
||||
assert_eq!(edits[0]["newText"], ", .rst(rst)");
|
||||
assert!(session.sent().is_empty(), "and nothing is pushed at it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_the_editor_refused_is_reported_to_the_user() {
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("refused", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let sent = session.sent();
|
||||
let id = sent[0].id.clone();
|
||||
|
||||
session.answer(
|
||||
id,
|
||||
serde_json::json!({ "applied": false, "failureReason": "the file is read-only" }),
|
||||
);
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
|
||||
assert!(shown[0].1.contains("the file is read-only"), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_the_editor_applied_is_said_nothing_about() {
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("applied", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let id = session.sent()[0].id.clone();
|
||||
|
||||
session.answer(id.clone(), serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "success is silent");
|
||||
|
||||
// And the id is spent: a duplicate answer says nothing either.
|
||||
session.answer(id, serde_json::json!({ "applied": false }));
|
||||
assert!(session.shown().is_empty(), "an answer to nothing is ignored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_apply_edit_answer_is_reported_as_a_refusal() {
|
||||
// QA attack: "a response that does not parse is a refusal" is stated
|
||||
// in the Assumptions but was only exercised through `Err` results and
|
||||
// a well-typed `applied: false`. This drives the branch where the
|
||||
// payload is `Ok` JSON that does not deserialize as
|
||||
// `ApplyWorkspaceEditResponse` at all (missing the required `applied`
|
||||
// field) — the honest-refusal path, not a panic or a silent success.
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("malformedapplyedit", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let id = session.sent()[0].id.clone();
|
||||
|
||||
session.answer(id, serde_json::json!({ "notApplied": "whatever" }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "an unparseable answer must still surface: {shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains(ports::PROPAGATE_PORTS), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_response_with_a_jsonrpc_error_is_reported_too() {
|
||||
// The `Err` half of `response_result` — a client that rejects the
|
||||
// `applyEdit` request outright at the JSON-RPC level, rather than
|
||||
// answering it with `applied: false`.
|
||||
let abilities = ClientAbilities { apply_edit: true, ..Default::default() };
|
||||
let (_tree, mut session, params) = propagating("rpcerror", abilities);
|
||||
session.result(ExecuteCommand::METHOD, params);
|
||||
let id = session.sent()[0].id.clone();
|
||||
|
||||
session.server.response(Response::new_err(id, 1, "internal error".to_string()));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("internal error"), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_watcher_registration_answer_is_still_ignored() {
|
||||
// The one response that was always ignored must stay ignored now that
|
||||
// responses are read at all — including an error one.
|
||||
let tree = Tree::new("registeranswer");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let id = session.sent()[0].id.clone();
|
||||
session.answer(id.clone(), Value::Null);
|
||||
session.server.response(Response::new_err(id, 1, "no thanks".to_string()));
|
||||
assert!(session.shown().is_empty(), "nothing to tell the user");
|
||||
}
|
||||
@@ -0,0 +1,388 @@
|
||||
//! `$/cancelRequest` (`docs/features/cancel-request/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// $/cancelRequest — docs/features/cancel-request/README.md
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A `textDocument/documentSymbol` request, queued. Any request would do;
|
||||
/// this one is cheap and its answer names what the buffer holds, which is
|
||||
/// what the ordering test needs.
|
||||
fn ask(id: i32, uri: &Uri) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
DocumentSymbolRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
))
|
||||
}
|
||||
|
||||
/// A `$/cancelRequest` naming `id`, exactly as a client sends it — the id
|
||||
/// is passed as raw JSON so both protocol forms can be tested.
|
||||
fn cancel(id: Value) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": id }),
|
||||
))
|
||||
}
|
||||
|
||||
/// The protocol's `RequestCancelled`.
|
||||
const CANCELLED: i32 = -32800;
|
||||
|
||||
/// Every response since the last drain, as (id, error code or `None`).
|
||||
fn outcomes(session: &Session) -> Vec<(RequestId, Option<i32>)> {
|
||||
session
|
||||
.answers()
|
||||
.into_iter()
|
||||
.map(|response| {
|
||||
let code = response.response_result.err().map(|error| error.code);
|
||||
(response.id, code)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The top-level symbol names in a `documentSymbol` answer.
|
||||
fn symbol_names(result: &Value) -> Vec<String> {
|
||||
result
|
||||
.as_array()
|
||||
.expect("an array of symbols")
|
||||
.iter()
|
||||
.map(|symbol| symbol["name"].as_str().expect("a name").to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A session with one open buffer, drained of the startup traffic.
|
||||
fn cancelling_session(name: &str, text: &str) -> (Tree, Session, Uri) {
|
||||
let tree = Tree::new(name);
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
let _ = session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
const ONE_MODULE: &str = "module m;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_request_cancelled_in_the_same_burst_is_answered_cancelled() {
|
||||
// The point of the whole feature: the client asked and changed its
|
||||
// mind while the server was busy elsewhere, so the answer costs
|
||||
// nothing to produce.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelsame", ONE_MODULE);
|
||||
let shutdown = session.batch(vec![ask(1, &uri), cancel(serde_json::json!(1))]);
|
||||
|
||||
assert!(!shutdown, "a cancel is not a shutdown");
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_dequeued_before_its_request_still_cancels_it() {
|
||||
// The batch is scanned as a whole before any of it runs, so a cancel
|
||||
// the transport happened to deliver first is not a cancel that
|
||||
// arrived too early.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelfirst", ONE_MODULE);
|
||||
session.batch(vec![cancel(serde_json::json!(1)), ask(1, &uri)]);
|
||||
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(1), Some(CANCELLED))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_names_one_request_and_leaves_the_rest_of_the_burst_alone() {
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelone", ONE_MODULE);
|
||||
session.batch(vec![ask(1, &uri), ask(2, &uri), cancel(serde_json::json!(1))]);
|
||||
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
|
||||
"id 2 was answered normally, and in its own place in the queue"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_for_a_request_that_is_not_in_the_burst_is_dropped_on_the_spot() {
|
||||
// A cancel that arrives in a later burst than its request is too late
|
||||
// — that request was answered already — and remembering it would be a
|
||||
// set that grows for the life of the session. The identical id in the
|
||||
// burst after proves nothing was kept: real clients never reuse an
|
||||
// id, so only a leak could cancel this one.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancellate", ONE_MODULE);
|
||||
let shutdown = session.batch(vec![cancel(serde_json::json!(1))]);
|
||||
|
||||
assert!(!shutdown);
|
||||
assert_eq!(outcomes(&session), vec![], "a lone cancel is answered with nothing at all");
|
||||
|
||||
session.batch(vec![ask(1, &uri)]);
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), None)],
|
||||
"the dropped cancel did not survive into the next burst"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_notification_queued_ahead_of_a_request_is_applied_before_it_is_answered() {
|
||||
// The invariant the burst must not break: order. A `didChange` the
|
||||
// client sent before its request has to be in effect when that
|
||||
// request is answered, exactly as it would be one message at a time.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelorder", ONE_MODULE);
|
||||
session.batch(vec![changed(&uri, 2, "module renamed;\nendmodule\n"), ask(1, &uri)]);
|
||||
|
||||
let answers = session.answers();
|
||||
assert_eq!(answers.len(), 1);
|
||||
let result = answers[0].response_result.clone().expect("an answer");
|
||||
assert_eq!(symbol_names(&result), vec!["renamed".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_never_cancels_a_notification() {
|
||||
// Notifications carry no id and get no response, so nothing in a
|
||||
// burst can suppress one — whatever id the cancel names.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelnotify", ONE_MODULE);
|
||||
session.batch(vec![
|
||||
changed(&uri, 2, "module renamed;\nendmodule\n"),
|
||||
cancel(serde_json::json!(1)),
|
||||
cancel(serde_json::json!("textDocument/didChange")),
|
||||
]);
|
||||
|
||||
assert_eq!(buffer(&session, &uri), "module renamed;\nendmodule\n");
|
||||
assert_eq!(outcomes(&session), vec![], "no ids were cancelled, so no responses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shutdown_is_honoured_however_it_is_cancelled() {
|
||||
// The spec lets a server answer a cancelled request normally, and for
|
||||
// `shutdown` that is the only safe reading: a client that cannot shut
|
||||
// the server down leaks a process. `handle_shutdown` runs before the
|
||||
// cancelled set is consulted, so the cancel never gets a say.
|
||||
let (_tree, mut session, _uri) = cancelling_session("cancelshutdown", ONE_MODULE);
|
||||
// `handle_shutdown` waits for the `exit` that follows, and reads it off
|
||||
// the *connection* — so the forwarder has to have stopped first, or it
|
||||
// takes the `exit` and the handshake finds nothing. It stops at the
|
||||
// first `shutdown` it forwards, so one is sent through it and waited
|
||||
// for: once that message is off the queue the forwarder has already
|
||||
// broken out of its loop and will never read the connection again.
|
||||
// (Before 2026-08-28 the forwarder did not exist until `run`, which
|
||||
// this test never calls, so the `exit` simply sat there.)
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Request(Request::new(
|
||||
RequestId::from(99),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
)))
|
||||
.expect("queue a shutdown for the forwarder to stop at");
|
||||
session
|
||||
.server
|
||||
.queue
|
||||
.recv_timeout(std::time::Duration::from_secs(5))
|
||||
.expect("the forwarder stops at it");
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
|
||||
.expect("queue exit");
|
||||
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from(9),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
));
|
||||
let shutdown = session.batch(vec![request, cancel(serde_json::json!(9))]);
|
||||
|
||||
assert!(shutdown, "the loop exits");
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(9), None)],
|
||||
"shutdown was answered, and answered successfully"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_one_request_twice_answers_it_once() {
|
||||
let (_tree, mut session, uri) = cancelling_session("canceltwice", ONE_MODULE);
|
||||
session.batch(vec![
|
||||
ask(1, &uri),
|
||||
cancel(serde_json::json!(1)),
|
||||
cancel(serde_json::json!(1)),
|
||||
ask(2, &uri),
|
||||
]);
|
||||
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), Some(CANCELLED)), (RequestId::from(2), None)],
|
||||
"the second cancel changed nothing — id 2 is not collateral damage"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_id_may_be_a_number_or_a_string() {
|
||||
// The protocol allows both, and a client that numbers its requests
|
||||
// with strings is not exotic.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelstring", ONE_MODULE);
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from("abc".to_string()),
|
||||
DocumentSymbolRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": &uri } }),
|
||||
));
|
||||
session.batch(vec![request, cancel(serde_json::json!("abc"))]);
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from("abc".to_string()), Some(CANCELLED))]);
|
||||
|
||||
session.batch(vec![ask(7, &uri), cancel(serde_json::json!(7))]);
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(7), Some(CANCELLED))]);
|
||||
|
||||
// A string that spells a number is not the number: `RequestId` keeps
|
||||
// the two apart, and so must the cancel.
|
||||
session.batch(vec![ask(8, &uri), cancel(serde_json::json!("8"))]);
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(8), None)],
|
||||
"the string \"8\" does not cancel the number 8"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_cancel_is_dropped_rather_than_guessed_at() {
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelmalformed", ONE_MODULE);
|
||||
let broken = Message::Notification(Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": { "nested": true } }),
|
||||
));
|
||||
session.batch(vec![ask(1, &uri), broken]);
|
||||
|
||||
assert_eq!(outcomes(&session), vec![(RequestId::from(1), None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn is_shutdown_matches_only_the_shutdown_request_never_a_notification_of_the_same_name() {
|
||||
// The forwarder stops forwarding the moment it sees this return
|
||||
// `true`. A malformed or adversarial client sending a *notification*
|
||||
// named "shutdown" must not trip it — that would silently stall the
|
||||
// whole backlog, with `handle_shutdown` never having run to explain
|
||||
// why.
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from(1),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
));
|
||||
let notification =
|
||||
Message::Notification(Notification::new(Shutdown::METHOD.to_string(), Value::Null));
|
||||
let other_request = Message::Request(Request::new(
|
||||
RequestId::from(2),
|
||||
DocumentSymbolRequest::METHOD.to_string(),
|
||||
Value::Null,
|
||||
));
|
||||
|
||||
assert!(is_shutdown(&request));
|
||||
assert!(
|
||||
!is_shutdown(¬ification),
|
||||
"a notification named shutdown is not the shutdown request"
|
||||
);
|
||||
assert!(!is_shutdown(&other_request));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn burst_collects_everything_already_queued_in_arrival_order() {
|
||||
// `burst` is what turns "one blocking receive" into "the whole
|
||||
// backlog" — the only place FIFO order could be broken. Nothing here
|
||||
// touches `Server`, so the check is on the free function alone.
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
sender
|
||||
.send(Message::Notification(Notification::new("second".to_string(), Value::Null)))
|
||||
.expect("send");
|
||||
sender
|
||||
.send(Message::Notification(Notification::new("third".to_string(), Value::Null)))
|
||||
.expect("send");
|
||||
|
||||
let first = Message::Notification(Notification::new("first".to_string(), Value::Null));
|
||||
let batch = burst(&receiver, first);
|
||||
|
||||
let methods: Vec<&str> = batch
|
||||
.iter()
|
||||
.map(|message| match message {
|
||||
Message::Notification(notification) => notification.method.as_str(),
|
||||
_ => "?",
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec!["first", "second", "third"],
|
||||
"the blocked-for message first, then the backlog, in order"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_forwarder_stops_at_shutdown_and_leaves_what_follows_for_handle_shutdown() {
|
||||
// The handoff this whole feature depends on: once the forwarder has
|
||||
// pushed a `shutdown` request onto the queue, it must not call `recv`
|
||||
// on `connection.receiver` again — that channel is where
|
||||
// `handle_shutdown` reads the `exit` that follows. An eager forwarder
|
||||
// would steal it and strand the handshake for thirty seconds.
|
||||
let (_tree, session, _uri) = cancelling_session("forwarderstop", ONE_MODULE);
|
||||
let shutdown_id = RequestId::from(9);
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Request(Request::new(
|
||||
shutdown_id.clone(),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
)))
|
||||
.expect("queue shutdown");
|
||||
session
|
||||
.client
|
||||
.sender
|
||||
.send(Message::Notification(Notification::new("exit".to_string(), Value::Null)))
|
||||
.expect("queue exit");
|
||||
|
||||
// The server's own queue — the one the forwarder started at
|
||||
// construction is filling — rather than a second one: two forwarders
|
||||
// over one connection would each take half the messages.
|
||||
let queue = &session.server.queue;
|
||||
let forwarded =
|
||||
queue.recv_timeout(std::time::Duration::from_secs(1)).expect("shutdown is forwarded");
|
||||
assert!(matches!(&forwarded, Message::Request(request) if request.id == shutdown_id));
|
||||
|
||||
// Give the forwarder thread every chance to (wrongly) keep reading
|
||||
// before asserting that it did not.
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
assert!(
|
||||
queue.try_recv().is_err(),
|
||||
"the forwarder must not forward anything after the shutdown request"
|
||||
);
|
||||
|
||||
// The `exit` is still sitting on the real connection, unread — right
|
||||
// where `handle_shutdown` looks for it.
|
||||
let direct = session
|
||||
.server
|
||||
.connection
|
||||
.receiver
|
||||
.recv_timeout(std::time::Duration::from_secs(1))
|
||||
.expect("exit is still there for handle_shutdown to read");
|
||||
assert!(
|
||||
matches!(&direct, Message::Notification(notification) if notification.method == "exit")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancel_naming_a_server_initiated_id_does_not_touch_response_routing() {
|
||||
// `lucisv-0`, `lucisv-1`, … are ids the server hands out for requests
|
||||
// it sends *to* the client (`applyEdit`, watcher registration,
|
||||
// progress `create`) — they come back as a `Message::Response`, a
|
||||
// different match arm entirely from the `Message::Request`s a burst
|
||||
// scans for cancellable ids. A client cancelling one by name has
|
||||
// nothing to reach.
|
||||
let (_tree, mut session, uri) = cancelling_session("cancelserverid", ONE_MODULE);
|
||||
let server_id = session.server.send_request("workspace/applyEdit", serde_json::json!({}));
|
||||
assert_eq!(server_id, RequestId::from("lucisv-0".to_string()));
|
||||
|
||||
session.batch(vec![ask(1, &uri), cancel(serde_json::json!("lucisv-0"))]);
|
||||
assert_eq!(
|
||||
outcomes(&session),
|
||||
vec![(RequestId::from(1), None)],
|
||||
"the client's own request was untouched by a cancel naming a server-initiated id"
|
||||
);
|
||||
|
||||
// The server-initiated request can still be answered normally — the
|
||||
// cancel did not intercept it.
|
||||
session.answer(server_id, Value::Null);
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! File operations (`docs/features/file-operations/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// file operations (`docs/features/file-operations/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `workspace/willRenameFiles` for `from` → `to`, driven through the
|
||||
/// real dispatch.
|
||||
fn will_rename(session: &mut Session, from: &Path, to: &Path) -> Value {
|
||||
session.result(
|
||||
WillRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{
|
||||
"oldUri": path_to_uri(from).expect("uri"),
|
||||
"newUri": path_to_uri(to).expect("uri"),
|
||||
}] }),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn will_rename_answers_the_edit_that_keeps_an_include_resolving() {
|
||||
let tree = Tree::new("willrename");
|
||||
tree.write("defs.svh", "`define W 8\n");
|
||||
tree.write("top.sv", "`include \"defs.svh\"\nmodule t;\nendmodule\n");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
|
||||
let (from, to) = (tree.path.join("defs.svh"), tree.path.join("widths.svh"));
|
||||
let answer = will_rename(&mut session, &from, &to);
|
||||
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
||||
let edits = &answer["changes"][uri.as_str()];
|
||||
assert_eq!(edits[0]["newText"], serde_json::json!("widths.svh"), "{answer:#?}");
|
||||
// The range is the path token: line 0, inside the quotes.
|
||||
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 10 }));
|
||||
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 0, "character": 18 }));
|
||||
assert!(session.shown().is_empty(), "a rewrite everything could reach says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn will_rename_works_for_a_file_no_editor_ever_opened() {
|
||||
// Includes live in unopened files; the sweep reads them off disk
|
||||
// through the same `sources()` the index is built from.
|
||||
let tree = Tree::new("willrenameunopened");
|
||||
tree.write("defs.svh", "`define W 8\n");
|
||||
tree.write("top.sv", "`include \"defs.svh\"\n");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert!(session.server.workspace.open_uris().is_empty(), "premise: nothing open");
|
||||
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("defs.svh"), &tree.path.join("widths.svh"));
|
||||
let uri = path_to_uri(&tree.path.join("top.sv")).expect("uri");
|
||||
assert_eq!(
|
||||
answer["changes"][uri.as_str()][0]["newText"],
|
||||
serde_json::json!("widths.svh"),
|
||||
"{answer:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn will_rename_answers_null_when_there_is_nothing_to_rewrite() {
|
||||
let tree = Tree::new("willrenamenull");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("notes.md", "prose\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
|
||||
// A source file nothing includes.
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
|
||||
assert_eq!(answer, Value::Null, "{answer:#?}");
|
||||
// And a file this server has no opinion about at all.
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("notes.md"), &tree.path.join("NOTES.md"));
|
||||
assert_eq!(answer, Value::Null, "{answer:#?}");
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_include_a_rename_strands_is_shown_once_and_logged() {
|
||||
// The same "first shown, all logged" rule the scope warnings follow —
|
||||
// a rename that strands forty includes must not open forty popups.
|
||||
let tree = Tree::new("willrenamewarn");
|
||||
std::fs::create_dir_all(tree.path.join("inc")).expect("mkdir");
|
||||
tree.write("inc/defs.svh", "`define W 8\n");
|
||||
tree.write("a.sv", "`include <defs.svh>\n");
|
||||
tree.write("b.sv", "`include <defs.svh>\n");
|
||||
tree.write("files.f", "+incdir+inc\na.sv\nb.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let _ = session.drain();
|
||||
|
||||
// The angled form resolves against incdirs only, so a move out of the
|
||||
// one include path cannot be spelled from either file.
|
||||
let answer =
|
||||
will_rename(&mut session, &tree.path.join("inc/defs.svh"), &tree.path.join("far.svh"));
|
||||
assert_eq!(answer, Value::Null, "nothing invented: {answer:#?}");
|
||||
let shown = session.drain();
|
||||
let popups: Vec<&Message> = shown
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == ShowMessage::METHOD))
|
||||
.collect();
|
||||
let logs: Vec<&Message> = shown
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == LogMessage::METHOD))
|
||||
.collect();
|
||||
assert_eq!(popups.len(), 1, "one popup for two stranded includes: {popups:#?}");
|
||||
assert_eq!(logs.len(), 2, "both are logged: {logs:#?}");
|
||||
}
|
||||
|
||||
/// One `workspace/didRenameFiles` for `from` → `to`.
|
||||
fn did_rename(session: &mut Session, from: &Path, to: &Path) {
|
||||
session.notify(
|
||||
DidRenameFiles::METHOD,
|
||||
serde_json::json!({ "files": [{
|
||||
"oldUri": path_to_uri(from).expect("uri"),
|
||||
"newUri": path_to_uri(to).expect("uri"),
|
||||
}] }),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_notification_rebuilds_the_index() {
|
||||
let tree = Tree::new("didrename");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert_eq!(indexed(&session, "a"), 1, "premise: indexed under its old name");
|
||||
|
||||
std::fs::rename(tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")).expect("rename");
|
||||
did_rename(&mut session, &tree.path.join("rtl/a.sv"), &tree.path.join("rtl/b.sv"));
|
||||
assert_eq!(indexed(&session, "a"), 1, "still one package, found at its new path");
|
||||
|
||||
// And the same nudge from the watcher for the same move changes
|
||||
// nothing: the rebuild is a re-read of the tree, not an increment.
|
||||
session.watched(&[tree.path.join("rtl/b.sv")]);
|
||||
assert_eq!(indexed(&session, "a"), 1, "reindexing twice is harmless");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delete_notification_rebuilds_the_index() {
|
||||
let tree = Tree::new("diddelete");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/gone.sv", "gone_pkg");
|
||||
let mut session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert_eq!(indexed(&session, "gone_pkg"), 1, "premise: indexed");
|
||||
|
||||
std::fs::remove_file(tree.path.join("rtl/gone.sv")).expect("remove");
|
||||
session.notify(
|
||||
DidDeleteFiles::METHOD,
|
||||
serde_json::json!({ "files": [
|
||||
{ "uri": path_to_uri(&tree.path.join("rtl/gone.sv")).expect("uri") },
|
||||
] }),
|
||||
);
|
||||
assert_eq!(indexed(&session, "gone_pkg"), 0, "gone from the index too");
|
||||
assert_eq!(indexed(&session, "a"), 1, "and the rest survives");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_operation_notification_for_nothing_the_index_reads_costs_no_rebuild() {
|
||||
let tree = Tree::new("didrenamestray");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
||||
|
||||
did_rename(&mut session, &tree.path.join("README.md"), &tree.path.join("READ.md"));
|
||||
session.notify(
|
||||
DidDeleteFiles::METHOD,
|
||||
serde_json::json!({ "files": [
|
||||
{ "uri": path_to_uri(&tree.path.join("notes.txt")).expect("uri") },
|
||||
] }),
|
||||
);
|
||||
assert_eq!(session.publishes(), 0, "neither is a path the index reads");
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
//! Workspace folders (2026-08-27) and the scope a `didOpen` widens.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// workspace folders (2026-08-27)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A `workspace/didChangeWorkspaceFolders` event, as a client sends it.
|
||||
fn folder_event(added: &[&Path], removed: &[&Path]) -> Value {
|
||||
let folders = |paths: &[&Path]| -> Vec<Value> {
|
||||
paths
|
||||
.iter()
|
||||
.map(|path| {
|
||||
serde_json::json!({
|
||||
"uri": path_to_uri(path).expect("uri"),
|
||||
"name": path.file_name().and_then(|n| n.to_str()).unwrap_or("folder"),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
serde_json::json!({ "event": { "added": folders(added), "removed": folders(removed) } })
|
||||
}
|
||||
|
||||
fn folders_changed(session: &mut Session, added: &[&Path], removed: &[&Path]) {
|
||||
session.notify(DidChangeWorkspaceFolders::METHOD, folder_event(added, removed));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_didopen_rebuilds_exactly_when_it_widens_the_scope() {
|
||||
// Superseded this round (index-scope, 2026-08-27): the test that stood
|
||||
// here — `a_rootless_session_gaining_its_first_folder_flips_didopen_
|
||||
// from_reindex_to_publish` — pinned `didOpen`'s *root*-conditional,
|
||||
// rootless reindexing and rooted publishing. Rung 3 is now the default
|
||||
// rung with a root as well, so the root set is not the question any
|
||||
// more; the question is whether the file just opened brought a folder
|
||||
// the index does not cover, and this is the same case list under the
|
||||
// rule that replaced it. The pinned property is strictly stronger: it
|
||||
// holds in a rootless session and in a rooted one, and it is the same
|
||||
// one line of code for both.
|
||||
let outside = Tree::new("didopenscopeoutside");
|
||||
outside.package("a.sv", "a");
|
||||
let folder = Tree::new("didopenscopefolder");
|
||||
folder.package("rtl/b.sv", "b");
|
||||
folder.package("rtl/beside.sv", "beside");
|
||||
|
||||
let mut session = Session::new(Vec::new(), false);
|
||||
assert!(!session.server.workspace.has_roots(), "premise: rootless");
|
||||
|
||||
// `generation` counts a buffer's text *and* the index, so an open that
|
||||
// widens is `set_document`'s bump plus `reindex`'s own — two.
|
||||
let before = session.server.generation;
|
||||
let _ =
|
||||
session.open(&outside.path.join("a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(session.server.generation, before + 2, "a new folder widens by reindexing");
|
||||
|
||||
folders_changed(&mut session, &[&folder.path], &[]);
|
||||
assert!(session.server.workspace.has_roots(), "the workspace now has a root");
|
||||
|
||||
// A root does not make the scope wide: this file's folder has still
|
||||
// never been opened from, so it widens and rebuilds exactly as the
|
||||
// rootless one did.
|
||||
let after_folder = session.server.generation;
|
||||
let uri = session
|
||||
.open(&folder.path.join("rtl/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
after_folder + 2,
|
||||
"a folder outside the scope widens it, root or no root"
|
||||
);
|
||||
assert_eq!(indexed(&session, "b"), 1, "and the widened scope really was scanned");
|
||||
assert!(session.published().iter().any(|p| p.uri == uri), "and it is published too");
|
||||
|
||||
// The second file in a folder already in scope costs only
|
||||
// `set_document`'s bump: nothing about which files exist moved.
|
||||
let quiet = session.server.generation;
|
||||
let uri = session.open(
|
||||
&folder.path.join("rtl/beside.sv"),
|
||||
"package beside;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
quiet + 1,
|
||||
"a file the scope already covers must not cost a rescan"
|
||||
);
|
||||
assert!(
|
||||
session.published().iter().any(|p| p.uri == uri),
|
||||
"it is still published, just not rescanned"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn widen_of_takes_the_cheap_path_for_a_pure_add_and_nothing_else() {
|
||||
// The chooser, as a table. Everything but "grew and lost nothing"
|
||||
// falls back to the whole rescan, which is always a correct answer.
|
||||
let a = PathBuf::from("/w/a");
|
||||
let b = PathBuf::from("/w/b");
|
||||
let c = PathBuf::from("/w/c");
|
||||
let all = [a.clone(), b.clone(), c.clone()];
|
||||
|
||||
assert_eq!(widen_of(&[], &[]), Widen::Nothing, "a scope that never moved");
|
||||
assert_eq!(
|
||||
widen_of(&all, &all),
|
||||
Widen::Nothing,
|
||||
"and one an open buffer could not widen — a filelist or the wide rung, both empty"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&a), &[a.clone(), b.clone()]),
|
||||
Widen::Added(vec![b.clone()]),
|
||||
"one folder added: only that folder is indexed"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(&[], &all),
|
||||
Widen::Added(all.to_vec()),
|
||||
"the first open of a session adds every directory it has"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&b), &[a.clone(), b.clone(), c.clone()]),
|
||||
Widen::Added(vec![a.clone(), c.clone()]),
|
||||
"two added around one held: both, and never the held one"
|
||||
);
|
||||
// The `scopeDepth: 2` shape `performance_take2.md` §5b measured: the
|
||||
// newly opened file raises to a directory that *contains* one already
|
||||
// in scope. The contained directory is still in `after` — every opened
|
||||
// directory is raised on its own and none of them is ever dropped — so
|
||||
// this is an add like any other, and the widen's own file diff is what
|
||||
// stops the overlap being read twice
|
||||
// (`state::tests::a_widen_that_subsumes_the_old_scope_reads_only_the_files_it_adds`).
|
||||
let ip = PathBuf::from("/w");
|
||||
assert_eq!(
|
||||
widen_of(std::slice::from_ref(&a), &[ip.clone(), a.clone()]),
|
||||
Widen::Added(vec![ip]),
|
||||
"a folder that subsumes the old scope is an add, not a removal"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(&[a.clone(), b.clone()], std::slice::from_ref(&a)),
|
||||
Widen::Whole,
|
||||
"a directory that left is not an add: the whole rescan settles what went with it"
|
||||
);
|
||||
assert_eq!(
|
||||
widen_of(&[a.clone(), b.clone()], &[a, c]),
|
||||
Widen::Whole,
|
||||
"and a swap is a removal too, however many arrived beside it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_didopen_widen_leaves_the_index_a_whole_rescan_would_have_left() {
|
||||
// The round's claim, through the real dispatch: two jumps into two new
|
||||
// folders, each answered by indexing only that folder, and the tables
|
||||
// that come out are the ones a whole rescan produces — asked by
|
||||
// running that rescan afterwards and comparing.
|
||||
let tree = Tree::new("didopenwidenequal");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/a2.sv", "a2");
|
||||
tree.package("lib/b.sv", "b");
|
||||
tree.package("lib/b2.sv", "b2");
|
||||
tree.package("tb/c.sv", "c");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let _ =
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let _ =
|
||||
session.open(&tree.path.join("lib/b.sv"), "package b;\n localparam K = 1;\nendpackage\n");
|
||||
let _ =
|
||||
session.open(&tree.path.join("tb/c.sv"), "package c;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(session.server.workspace.index().files().len(), 5, "all three folders");
|
||||
assert_eq!(indexed(&session, "b2"), 1, "including files nobody opened");
|
||||
|
||||
let widened = session.server.workspace.index().fingerprint();
|
||||
let words = session.server.workspace.candidates().words("").to_vec();
|
||||
let includes = session.server.workspace.includes().fingerprint();
|
||||
session.server.workspace.rebuild_index();
|
||||
assert_eq!(widened, session.server.workspace.index().fingerprint(), "index");
|
||||
assert_eq!(words, session.server.workspace.candidates().words(""), "completion words");
|
||||
assert_eq!(includes, session.server.workspace.includes().fingerprint(), "include graph");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_widen_asked_for_mid_scan_defers_to_one_whole_rescan_behind_it() {
|
||||
// A widen answered while a scan runs cannot fold itself in: that scan
|
||||
// holds a work list taken from the *old* scope, so folding a widen
|
||||
// into it would make "which files exist" mean two things inside one
|
||||
// scan. It sets the same `rescan_wanted` flag every other mid-scan
|
||||
// trigger sets — one more whole scan after this one, coalesced with
|
||||
// whatever else asked (`docs/features/scan-interleave/README.md`).
|
||||
//
|
||||
// Driven directly rather than over the wire, because the wire cannot
|
||||
// reach it in one step: a widen itself never drains the queue, and the
|
||||
// startup scan under the folder scope indexes nothing and so never
|
||||
// interleaves. The reachable route is a `didOpen` answered inside a
|
||||
// long *whole* rescan, which is this flag and this call.
|
||||
let tree = Tree::new("widenmidscan");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("lib/late.sv", "late");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
// The shipped depth is 2 since 2026-08-28, which would have `lib/` in
|
||||
// scope before the widen this test is about — so the premise names the
|
||||
// narrow depth rather than assuming it.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "index": { "scopeDepth": 0 } } } }),
|
||||
);
|
||||
let _ =
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(indexed(&session, "a"), 1, "premise: the first folder is in scope");
|
||||
|
||||
session.server.scanning = true;
|
||||
session.server.reindex_widened(vec![tree.path.join("lib")]);
|
||||
assert!(session.server.rescan_wanted, "the widen was deferred, not run inside the scan");
|
||||
assert_eq!(indexed(&session, "late"), 0, "and nothing was folded into the running scan");
|
||||
|
||||
// What the running scan's own loop then does with the flag.
|
||||
session.server.scanning = false;
|
||||
let warnings = session.server.scan_until_settled(true);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
assert!(!session.server.rescan_wanted, "one more scan is all it was owed");
|
||||
// Not indexed, and correctly so: the deferred rescan is a *whole* one
|
||||
// over the scope as it now stands, and `lib/` entered that scope only
|
||||
// because a buffer was opened from it — which this test never did.
|
||||
assert_eq!(indexed(&session, "late"), 0, "the scope itself did not move");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_added_mid_session_is_indexed_and_answers_workspace_symbol() {
|
||||
// The whole point: "Add Folder to Workspace" used to change nothing
|
||||
// until the editor was restarted.
|
||||
let first = Tree::new("folderadd");
|
||||
first.package("rtl/a.sv", "a");
|
||||
let second = Tree::new("folderaddsecond");
|
||||
second.package("rtl/b.sv", "b");
|
||||
|
||||
let mut session = Session::wide(vec![first.path.clone()], false);
|
||||
assert_eq!(indexed(&session, "b"), 0, "premise: the second folder is not open yet");
|
||||
|
||||
folders_changed(&mut session, &[&second.path], &[]);
|
||||
assert_eq!(indexed(&session, "b"), 1, "the added folder is scanned");
|
||||
assert_eq!(indexed(&session, "a"), 1, "and the one already open survives");
|
||||
|
||||
// And it is reachable through a real request, not only in the index.
|
||||
let hits = session.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query":"b"}));
|
||||
let found = hits.as_array().expect("a symbol list");
|
||||
assert!(
|
||||
found.iter().any(|hit| hit["location"]["uri"]
|
||||
.as_str()
|
||||
.is_some_and(|uri| uri.contains("folderaddsecond"))),
|
||||
"{found:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_removed_folder_leaves_the_index_and_its_open_buffer_keeps_being_diagnosed() {
|
||||
// The client owns buffer lifecycle: closing a folder does not close
|
||||
// the editors that were open in it. Such a buffer keeps the deal
|
||||
// every rootless buffer has always had — it is still analyzed, still
|
||||
// published, and still overrides disk in the index.
|
||||
let first = Tree::new("folderremove");
|
||||
first.package("rtl/a.sv", "a");
|
||||
let second = Tree::new("folderremovesecond");
|
||||
second.package("rtl/open.sv", "open_pkg");
|
||||
second.package("rtl/other.sv", "other_pkg");
|
||||
|
||||
let mut session = Session::wide(vec![first.path.clone(), second.path.clone()], false);
|
||||
let uri = session.open(
|
||||
&second.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(indexed(&session, "other_pkg"), 1, "premise: the whole folder is indexed");
|
||||
|
||||
folders_changed(&mut session, &[], &[&second.path]);
|
||||
assert_eq!(indexed(&session, "other_pkg"), 0, "the folder's files left the index");
|
||||
assert_eq!(indexed(&session, "a"), 1, "the folder that stayed is untouched");
|
||||
assert_eq!(
|
||||
indexed(&session, "open_pkg"),
|
||||
1,
|
||||
"the open buffer contributes itself, as every out-of-scope buffer does"
|
||||
);
|
||||
|
||||
// The rebuild republished it, and an edit to it is still diagnosed.
|
||||
let published = session.published();
|
||||
assert!(published.iter().any(|p| p.uri == uri), "{published:#?}");
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "package open_pkg;\n localparam ;\nendpackage\n" }]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "{published:#?}");
|
||||
assert_eq!(published[0].uri, uri);
|
||||
assert!(!published[0].diagnostics.is_empty(), "a broken buffer still reports");
|
||||
|
||||
// And closing it clears cleanly — the removed folder is not a special
|
||||
// case for `didClose`, which already sends an empty publish for
|
||||
// whatever buffer is named regardless of where it lived.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "{published:#?}");
|
||||
assert_eq!(published[0].uri, uri);
|
||||
assert!(published[0].diagnostics.is_empty(), "the close cleared it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_folder_notification_is_one_rescan_with_one_bar_and_one_generation() {
|
||||
// Everything a rescan owes rides inside `reindex()`; an event carries
|
||||
// both lists, so it must cost exactly one of each.
|
||||
let first = Tree::new("folderonce");
|
||||
first.package("rtl/a.sv", "a");
|
||||
let second = Tree::new("folderoncesecond");
|
||||
second.package("rtl/b.sv", "b");
|
||||
let third = Tree::new("folderoncethird");
|
||||
third.package("rtl/c.sv", "c");
|
||||
|
||||
let abilities =
|
||||
ClientAbilities { work_done_progress: true, code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![first.path.clone(), second.path.clone()], abilities);
|
||||
session.open(&first.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let before = session.server.generation;
|
||||
let _ = session.drain();
|
||||
|
||||
// One notification that both adds and removes: two changes, one scan.
|
||||
folders_changed(&mut session, &[&third.path], &[&second.path]);
|
||||
assert_eq!(indexed(&session, "c"), 1, "the addition took");
|
||||
assert_eq!(indexed(&session, "b"), 0, "and so did the removal");
|
||||
assert_eq!(session.server.generation, before + 1, "one generation bump");
|
||||
|
||||
let messages = session.drain();
|
||||
let steps: Vec<&'static str> =
|
||||
messages.iter().cloned().filter_map(progress_step).map(|(step, _)| step).collect();
|
||||
// One bar, up and down — with a report for each of the two files the
|
||||
// new root set holds (`a.sv` and `c.sv`).
|
||||
assert_eq!(steps, vec!["create", "begin", "report", "report", "end"], "one bar");
|
||||
let publishes = messages
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Notification(n) if n.method == PublishDiagnostics::METHOD))
|
||||
.count();
|
||||
assert_eq!(publishes, 1, "the one open buffer is republished once");
|
||||
let refreshes = messages
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
||||
.count();
|
||||
assert_eq!(refreshes, 1, "the counts on screen were invalidated once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rapid_add_remove_add_of_the_same_folder_costs_three_rescans_and_ends_up_added() {
|
||||
// Three separate notifications, each of which genuinely moves the
|
||||
// root set (unlike the no-op shapes above), must cost three separate
|
||||
// rescans — `change_roots` has no batching across notifications, only
|
||||
// within one — and the state after must be consistent with the net
|
||||
// effect: two adds and one remove is "present".
|
||||
// QA (2026-08-27): "own shapes" case from the review checklist.
|
||||
let root = Tree::new("rapidflaproot");
|
||||
root.package("rtl/a.sv", "a");
|
||||
let flapping = Tree::new("rapidflapfolder");
|
||||
flapping.package("rtl/b.sv", "b");
|
||||
|
||||
let mut session = Session::wide(vec![root.path.clone()], false);
|
||||
let before = session.server.generation;
|
||||
|
||||
folders_changed(&mut session, &[&flapping.path], &[]);
|
||||
assert_eq!(indexed(&session, "b"), 1, "added");
|
||||
folders_changed(&mut session, &[], &[&flapping.path]);
|
||||
assert_eq!(indexed(&session, "b"), 0, "removed");
|
||||
folders_changed(&mut session, &[&flapping.path], &[]);
|
||||
assert_eq!(indexed(&session, "b"), 1, "added again");
|
||||
|
||||
assert_eq!(session.server.generation, before + 3, "one rescan per notification, three total");
|
||||
assert_eq!(indexed(&session, "a"), 1, "the folder that never moved is untouched throughout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_event_that_moves_nothing_costs_nothing() {
|
||||
// Total and no-op-safe: every shape a client can send that leaves the
|
||||
// root set where it was must cost no rescan at all.
|
||||
let tree = Tree::new("foldernoop");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let before = session.server.generation;
|
||||
let _ = session.drain();
|
||||
|
||||
folders_changed(&mut session, &[], &[]);
|
||||
folders_changed(&mut session, &[&tree.path], &[]);
|
||||
folders_changed(&mut session, &[], &[&tree.path.join("never-added")]);
|
||||
folders_changed(&mut session, &[&tree.path], &[&tree.path]);
|
||||
// Params that do not parse at all, and a folder that is not a path.
|
||||
session.notify(DidChangeWorkspaceFolders::METHOD, serde_json::json!({ "nonsense": 1 }));
|
||||
session.notify(
|
||||
DidChangeWorkspaceFolders::METHOD,
|
||||
serde_json::json!({ "event": {
|
||||
"added": [{ "uri": "untitled:Untitled-1", "name": "scratch" }], "removed": [],
|
||||
} }),
|
||||
);
|
||||
|
||||
assert!(session.progress().is_empty(), "no rescan for any of them");
|
||||
assert_eq!(session.publishes(), 0, "and nothing was republished");
|
||||
assert_eq!(session.server.generation, before, "and no generation moved");
|
||||
assert_eq!(indexed(&session, "a"), 1, "the root itself survived every one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_change_re_registers_the_watchers_only_when_the_watched_path_moves() {
|
||||
// The source glob is workspace-wide — the client matches it against
|
||||
// whatever folders it holds, so a folder change needs no new
|
||||
// registration for it. The *filelist* watcher is an absolute path
|
||||
// anchored at the first root, so a folder change can move it without
|
||||
// anyone touching the setting.
|
||||
let first = Tree::new("folderwatch");
|
||||
first.package("rtl/a.sv", "a");
|
||||
first.write("files.f", "rtl/a.sv\n");
|
||||
let second = Tree::new("folderwatchsecond");
|
||||
second.package("rtl/b.sv", "b");
|
||||
second.write("files.f", "rtl/b.sv\n");
|
||||
|
||||
let mut session = Session::new(vec![first.path.clone()], true);
|
||||
let _ = session.drain();
|
||||
|
||||
// No filelist setting: nothing about the registration depends on the
|
||||
// roots, so adding a folder re-registers nothing.
|
||||
folders_changed(&mut session, &[&second.path], &[]);
|
||||
assert!(session.requests().is_empty(), "the source glob is workspace-wide");
|
||||
|
||||
// With a *relative* filelist the watched path is `<first root>/files.f`...
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
let _ = session.drain();
|
||||
// ...so dropping that root moves it to the second folder's copy.
|
||||
folders_changed(&mut session, &[], &[&first.path]);
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
|
||||
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
||||
assert_eq!(
|
||||
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
||||
second.path.join("files.f").to_str().expect("utf-8").to_string(),
|
||||
"{requests:#?}"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,628 @@
|
||||
//! `onTypeFormatting`, `rangesFormatting` and `willSaveWaitUntil`, through the real dispatch.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/onTypeFormatting`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One `onTypeFormatting` for a buffer: the character typed, and the
|
||||
/// position the client reports for the cursor after it.
|
||||
fn on_type(session: &mut Session, uri: &Uri, typed: &str, line: u32, character: u32) -> Value {
|
||||
on_type_with(session, uri, typed, line, character, serde_json::json!({}))
|
||||
}
|
||||
|
||||
fn on_type_with(
|
||||
session: &mut Session,
|
||||
uri: &Uri,
|
||||
typed: &str,
|
||||
line: u32,
|
||||
character: u32,
|
||||
options: Value,
|
||||
) -> Value {
|
||||
let mut all = serde_json::json!({ "tabSize": 2, "insertSpaces": true });
|
||||
if let (Some(all), Some(extra)) = (all.as_object_mut(), options.as_object()) {
|
||||
for (key, value) in extra {
|
||||
all.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
session.result(
|
||||
OnTypeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": line, "character": character },
|
||||
"ch": typed,
|
||||
"options": all,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_newline_re_indents_the_line_it_opened() {
|
||||
// The dispatch arm, end to end: a real request, decoded by the real
|
||||
// decoder, answered by the real handler.
|
||||
let tree = Tree::new("ontypenewline");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session
|
||||
.open(&tree.path.join("m.sv"), "module m;\n always_comb begin\n\n end\nendmodule\n");
|
||||
|
||||
let edits = on_type(&mut session, &uri, "\n", 2, 0);
|
||||
assert_eq!(edits[0]["newText"], " ", "{edits:#?}");
|
||||
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 2, "character": 0 }));
|
||||
assert_eq!(edits[0]["range"]["end"], serde_json::json!({ "line": 2, "character": 0 }));
|
||||
assert!(session.shown().is_empty(), "a keystroke says nothing to the user");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_typed_semicolon_lays_out_the_statement_through_the_range_engine() {
|
||||
let tree = Tree::new("ontypesemi");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let text = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("m.sv"), text);
|
||||
|
||||
let typed = on_type(&mut session, &uri, ";", 1, 11);
|
||||
assert_eq!(typed[0]["newText"], "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
// The same answer `textDocument/rangeFormatting` gives for that line,
|
||||
// byte for byte: this path is that request with a different trigger.
|
||||
let ranged = session.result(
|
||||
RangeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": { "start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 1, "character": 0 } },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
assert_eq!(typed, ranged);
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/rangesFormatting` (LSP 3.18), through the real dispatch
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// One LSP range, as a client writes it.
|
||||
fn json_range(sl: u32, sc: u32, el: u32, ec: u32) -> Value {
|
||||
serde_json::json!({
|
||||
"start": { "line": sl, "character": sc },
|
||||
"end": { "line": el, "character": ec },
|
||||
})
|
||||
}
|
||||
|
||||
fn ranges_result(session: &mut Session, uri: &Uri, ranges: Vec<Value>) -> Value {
|
||||
session.result(
|
||||
format::RANGES_FORMATTING,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"ranges": ranges,
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn range_result(session: &mut Session, uri: &Uri, range: Value) -> Value {
|
||||
session.result(
|
||||
RangeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": range,
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Four items on four lines, so two ranges can straddle one they leave.
|
||||
const FOUR_ITEMS: &str = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_ranges_request_lays_out_every_range_it_names_in_one_answer() {
|
||||
// The dispatch arm, end to end: a real request with a real `ranges`
|
||||
// array, decoded by the hand-rolled params and answered by the real
|
||||
// handler. Lines 2 and 4, leaving line 3 exactly as written.
|
||||
let tree = Tree::new("rangesfmt");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
let edits =
|
||||
ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0), json_range(3, 0, 4, 0)]);
|
||||
assert_eq!(
|
||||
edits[0]["newText"], "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n",
|
||||
"{edits:#?}"
|
||||
);
|
||||
// Still one whole-document edit, the shape `rangeFormatting` answers.
|
||||
assert_eq!(edits.as_array().map(Vec::len), Some(1));
|
||||
assert_eq!(edits[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 0 }));
|
||||
assert!(session.shown().is_empty(), "a clean config says nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_range_through_the_new_method_answers_what_the_old_method_answers() {
|
||||
// The two requests are the same engine, and a client must never have
|
||||
// to choose between them for correctness — only for round trips.
|
||||
let tree = Tree::new("rangesone");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
for range in [
|
||||
json_range(1, 0, 2, 0),
|
||||
json_range(1, 4, 1, 4),
|
||||
json_range(0, 0, 99, 0),
|
||||
json_range(4, 0, 4, 9),
|
||||
] {
|
||||
let one = range_result(&mut session, &uri, range.clone());
|
||||
let many = ranges_result(&mut session, &uri, vec![range.clone()]);
|
||||
assert_eq!(one, many, "{range}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_ranges_array_is_answered_with_no_edit_and_no_word() {
|
||||
let tree = Tree::new("rangesempty");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![]), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "an empty ask is not a problem");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ranges_request_for_a_buffer_the_server_does_not_hold_is_null() {
|
||||
// What every other formatting handler answers for an unknown document.
|
||||
let tree = Tree::new("rangesunknown");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert_eq!(ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0)]), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_is_the_same_answer_and_the_same_popup_on_both_range_methods() {
|
||||
// No partial output (CLAUDE.md invariant #1), and the multi-range path
|
||||
// reaches the *same* `edits()` — so the answer and the message must be
|
||||
// equal values, not merely similar shapes.
|
||||
let tree = Tree::new("rangesrefuse");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
let one = range_result(&mut session, &uri, json_range(0, 0, 1, 0));
|
||||
let said_once = session.shown();
|
||||
let many =
|
||||
ranges_result(&mut session, &uri, vec![json_range(0, 0, 1, 0), json_range(2, 0, 3, 0)]);
|
||||
let said_again = session.shown();
|
||||
|
||||
assert_eq!(one, serde_json::json!([]), "no edit at all");
|
||||
assert_eq!(one, many, "byte-identical answers");
|
||||
assert_eq!(said_once.len(), 1, "{said_once:?}");
|
||||
assert_eq!(said_once, said_again, "and byte-identical ERRORs: {said_again:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_warns_once_from_the_multi_range_path_too() {
|
||||
// It shares `warn_about_config` with the other explicit formatting
|
||||
// requests, dedup included — this is an explicit request the user made,
|
||||
// not a keystroke, so it does speak.
|
||||
let tree = Tree::new("rangesconfig");
|
||||
std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
||||
std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
let _ = session.drain();
|
||||
|
||||
let edits = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]);
|
||||
assert_eq!(
|
||||
edits[0]["newText"],
|
||||
"module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"
|
||||
);
|
||||
let warned = session.shown();
|
||||
assert_eq!(warned.len(), 1, "{warned:?}");
|
||||
assert_eq!(warned[0].0, MessageType::WARNING);
|
||||
assert!(warned[0].1.contains("unknown key `bogus`"), "{warned:?}");
|
||||
// And once per buffer state, exactly as the other paths.
|
||||
let _ = ranges_result(&mut session, &uri, vec![json_range(1, 0, 2, 0)]);
|
||||
assert!(session.shown().is_empty(), "said once, not once per request");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn params_that_do_not_carry_ranges_are_invalid_params_and_not_a_panic() {
|
||||
// The params are hand-rolled, so their refusal is ours to get right:
|
||||
// a missing `ranges` is a client bug and answers an error, never a
|
||||
// guess about what the client meant.
|
||||
let tree = Tree::new("rangesjunk");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), FOUR_ITEMS);
|
||||
|
||||
let response = session.request(
|
||||
format::RANGES_FORMATTING,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
let error = response.response_result.expect_err("missing `ranges` is not answerable");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::InvalidParams as i32, "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_the_engine_refuses_is_answered_with_silence_and_not_a_popup() {
|
||||
// The deliberate contrast with `textDocument/formatting` and the save
|
||||
// hook, both of which show an ERROR on a refusal. Mid-edit code the
|
||||
// engine declines is the *normal* case on a keystroke, and a modal the
|
||||
// user cannot type past would arrive on every semicolon.
|
||||
let tree = Tree::new("ontypequiet");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\n wire ;\n");
|
||||
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 11), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "not one word: {:?}", session.shown());
|
||||
// ...and the whole-document request on the same buffer still does say
|
||||
// something, so the silence is this path's decision and not a
|
||||
// regression in `edits()`.
|
||||
let _ = formatting_result(&mut session, &uri);
|
||||
assert_eq!(session.shown().len(), 1, "the explicit request still reports");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_is_never_reported_from_a_keystroke() {
|
||||
// `warn_about_config`'s dedup is cleared by `set_document`, and an
|
||||
// on-type request follows the `didChange` the user's own keystroke
|
||||
// produced — so warning here would mean one popup per character. The
|
||||
// user is told on their next explicit format instead.
|
||||
let tree = Tree::new("ontypeconfig");
|
||||
std::fs::write(tree.path.join(".git"), "gitdir: nowhere\n").expect("write .git");
|
||||
std::fs::write(tree.path.join("lucisv.toml"), "bogus = 1\n").expect("write config");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
for _ in 0..3 {
|
||||
let edits = on_type(&mut session, &uri, "\n", 1, 0);
|
||||
assert_eq!(edits[0]["newText"], " ", "it still formats with the defaults");
|
||||
assert!(session.shown().is_empty(), "and still says nothing");
|
||||
}
|
||||
// The explicit request is where the user hears about it.
|
||||
let _ = formatting_result(&mut session, &uri);
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:?}");
|
||||
assert!(shown[0].1.contains("unknown key `bogus`"), "{shown:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_climbs_the_same_settings_ladder_a_manual_format_does() {
|
||||
// Unlike `willSaveWaitUntil`, this request carries `FormattingOptions`,
|
||||
// so the editor's own tab size is a rung — outranked by a pushed
|
||||
// `lucisv.indent`, exactly as `format::settings_for` documents.
|
||||
let tree = Tree::new("ontypesettings");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n\n wire a;\nendmodule\n");
|
||||
|
||||
let tabbed = serde_json::json!({ "tabSize": 4 });
|
||||
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed.clone());
|
||||
assert_eq!(edits[0]["newText"], " ", "rung 3, the editor's tab size");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
||||
);
|
||||
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, tabbed);
|
||||
assert_eq!(edits[0]["newText"], " ", "rung 2 outranks it");
|
||||
|
||||
// Hard tabs are not a width this formatter can honour, so rung 3 drops
|
||||
// out entirely and the built-in default answers.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": {} } }),
|
||||
);
|
||||
let hard = serde_json::json!({ "tabSize": 4, "insertSpaces": false });
|
||||
let edits = on_type_with(&mut session, &uri, "\n", 1, 0, hard);
|
||||
assert_eq!(edits[0]["newText"], " ", "never a tab, and never a guess");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keystroke_in_a_buffer_the_server_does_not_hold_answers_an_empty_array() {
|
||||
// `[]` rather than `null`: the protocol's answer for "no edits", and
|
||||
// what every other request on this path already returns.
|
||||
let tree = Tree::new("ontypeunopened");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert_eq!(on_type(&mut session, &uri, "\n", 1, 0), serde_json::json!([]));
|
||||
assert_eq!(on_type(&mut session, &uri, ";", 1, 0), serde_json::json!([]));
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trigger_character_this_server_never_advertised_answers_nothing() {
|
||||
let tree = Tree::new("ontypeunknown");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
for typed in ["}", ")", "e"] {
|
||||
assert_eq!(on_type(&mut session, &uri, typed, 1, 11), serde_json::json!([]), "{typed}");
|
||||
}
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/willSaveWaitUntil`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The `lucisv.formatOnSave` push a client makes, on or off.
|
||||
fn format_on_save(on: bool) -> Value {
|
||||
serde_json::json!({ "settings": { "lucisv": { "formatOnSave": on } } })
|
||||
}
|
||||
|
||||
/// One `willSaveWaitUntil` for a buffer, for the reason given (1 = manual,
|
||||
/// 2 = after delay, 3 = focus out).
|
||||
fn will_save(session: &mut Session, uri: &Uri, reason: u8) -> Value {
|
||||
session.result(
|
||||
WillSaveWaitUntil::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "reason": reason }),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_declines_until_format_on_save_is_pushed() {
|
||||
let tree = Tree::new("willsaveoff");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
|
||||
// The default: a client that never pushed the setting is answered
|
||||
// `null`, and told nothing at all.
|
||||
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "off by default");
|
||||
assert!(session.shown().is_empty(), "a decline is silent");
|
||||
|
||||
// Pushed on, mid-session, with no restart.
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(edits[0]["newText"], "module m;\n wire a;\nendmodule\n", "{edits:#?}");
|
||||
|
||||
// And off again: the hook goes back to declining.
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
|
||||
assert_eq!(will_save(&mut session, &uri, 1), Value::Null, "turned back off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn toggling_format_on_save_neither_rescans_nor_bumps_the_generation() {
|
||||
// QA (2026-08-26): `lucisv.formatOnSave` is read afresh by every save,
|
||||
// like `indent`/`lineLength` already are by every format — it must not
|
||||
// cost a re-walk of the workspace, and (since a rescan is what bumps
|
||||
// it) must not move the generation counter a pull-diagnostics client's
|
||||
// `resultId` is stamped with either. `only_an_exclude_change_asks_for_a_rescan`
|
||||
// (state.rs) pins the same thing one layer down; this pins it through
|
||||
// the real notification handler.
|
||||
let tree = Tree::new("willsavenoreindex");
|
||||
tree.package("kept.sv", "kept_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let before = session.server.generation;
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
assert_eq!(session.server.generation, before, "turning it on moved nothing");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(false));
|
||||
assert_eq!(session.server.generation, before, "turning it off moved nothing either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_answers_exactly_what_the_formatting_request_answers() {
|
||||
// The whole contract: this is `textDocument/formatting` with a
|
||||
// different trigger, so the bytes must be identical — not merely
|
||||
// equivalent.
|
||||
let tree = Tree::new("willsavesame");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\n wire b;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
assert_eq!(will_save(&mut session, &uri, 1), formatting_result(&mut session, &uri));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_save_reason_is_a_save() {
|
||||
// Manual, after-delay and focus-out all format: the user asked for
|
||||
// their saves to be formatted, and all three write the file.
|
||||
let tree = Tree::new("willsavereason");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
for reason in [1, 2, 3] {
|
||||
let edits = will_save(&mut session, &uri, reason);
|
||||
assert_eq!(
|
||||
edits[0]["newText"], "module m;\n wire a;\nendmodule\n",
|
||||
"reason {reason}: {edits:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_answers_null_for_a_buffer_it_does_not_hold() {
|
||||
// The request carries no text — the client has not written yet — so a
|
||||
// buffer the server never saw is one it cannot format.
|
||||
let tree = Tree::new("willsaveclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
assert_eq!(will_save(&mut session, &uri, 1), Value::Null);
|
||||
assert!(session.shown().is_empty(), "and nothing is said about it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_already_formatted_buffer_is_saved_with_no_edits() {
|
||||
// The same `[]` the formatting request gives for `Ok(None)`: an edit
|
||||
// that changes nothing still moves the cursor in some editors.
|
||||
let tree = Tree::new("willsaveclean");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(edits, serde_json::json!([]), "{edits:#?}");
|
||||
assert_eq!(edits, formatting_result(&mut session, &uri), "the same as the request's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_the_formatter_refuses_is_saved_unedited_and_the_reason_is_shown() {
|
||||
// CLAUDE.md invariant #1 on the save path: no partial output, ever.
|
||||
// The message repeats per save on purpose — a save the user asked to
|
||||
// be formatted, that was not, is worth saying every time it happens.
|
||||
let tree = Tree::new("willsavebroken");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire ;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let _ = session.drain();
|
||||
|
||||
for save in 1..=2 {
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(edits, serde_json::json!([]), "save {save}: no edit at all");
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "save {save}: {shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.starts_with("lucisv: cannot format — "), "{}", shown[0].1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do() {
|
||||
// The formatter's own idempotency, asserted through this path: the
|
||||
// buffer the client writes is a fixed point, so a save right after a
|
||||
// save cannot keep rewriting the file.
|
||||
let tree = Tree::new("willsaveidempotent");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session
|
||||
.open(&tree.path.join("m.sv"), "module m;\nwire a;\n assign a = 1;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
|
||||
let edits = will_save(&mut session, &uri, 1);
|
||||
let formatted = edits[0]["newText"].as_str().expect("newText").to_string();
|
||||
// The client applies the edit and writes; the buffer it holds is what
|
||||
// the next save asks about.
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
|
||||
assert_eq!(buffer(&session, &uri), formatted);
|
||||
assert_eq!(will_save(&mut session, &uri, 1), serde_json::json!([]), "a fixed point");
|
||||
}
|
||||
|
||||
/// What `textDocument/formatting` answers for the given `tabSize`.
|
||||
fn formatting_with_tab_size(session: &mut Session, uri: &Uri, tab_size: u32) -> Value {
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": tab_size, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_save_hook_and_a_manual_format_can_legitimately_disagree_on_indent() {
|
||||
// QA (2026-08-26): the documented gap in Assumptions/Handshakes,
|
||||
// constructed for real. No `lucisv.toml`, no `lucisv.indent` pushed,
|
||||
// and an editor whose tab size is 4: a manual format honors rung 3
|
||||
// (the editor's `tabSize`) and indents 4; the save hook has no rung 3
|
||||
// to consult at all and falls straight to the built-in default, 2.
|
||||
let tree = Tree::new("willsavetabgap");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
|
||||
let manual = formatting_with_tab_size(&mut session, &uri, 4);
|
||||
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
|
||||
|
||||
let saved = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(saved[0]["newText"], "module m;\n wire a;\nendmodule\n", "{saved:#?}");
|
||||
assert_ne!(manual, saved, "the documented gap is real, not just written down");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lucisv_toml_erases_the_tab_size_gap() {
|
||||
// QA (2026-08-26): with a checked-in config, rung 1 outranks both the
|
||||
// editor's `tabSize` and the built-in default, so the two paths agree
|
||||
// exactly again — no `lucisv.toml`, and this would be the previous
|
||||
// test.
|
||||
let tree = Tree::new("willsavetabgapclosed");
|
||||
tree.write("lucisv.toml", "indent = 4\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
|
||||
// A wildly different editor tab size changes nothing: the config wins.
|
||||
let manual = formatting_with_tab_size(&mut session, &uri, 8);
|
||||
let saved = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(manual[0]["newText"], "module m;\n wire a;\nendmodule\n", "{manual:#?}");
|
||||
assert_eq!(manual, saved, "the config makes the two paths agree exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_config_still_saves_with_defaults_and_warns_once() {
|
||||
// QA (2026-08-26): the interaction attack-surface 4 calls out —
|
||||
// `formatOnSave` on, the buffer itself fine, but `lucisv.toml` broken.
|
||||
// The save must not be sacrificed to a typo in a file the user is not
|
||||
// even editing: it formats with the built-in defaults, and the
|
||||
// warning follows the same per-file-change dedup a broken config
|
||||
// already gets everywhere else, so a save loop cannot turn it into
|
||||
// spam the way the formatter-refusal ERROR deliberately can.
|
||||
//
|
||||
// The buffer is already at the built-in default (2-space indent), so
|
||||
// neither save produces an edit and — crucially — neither save is
|
||||
// followed by the client-applies-the-edit `didChange` that would
|
||||
// itself re-arm the warning (`set_document` clears
|
||||
// `config_warnings`). That is what isolates the dedup this test is
|
||||
// actually about from the unrelated re-arming a *changed* buffer gets.
|
||||
let tree = Tree::new("willsavebrokenconfig");
|
||||
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let _ = session.drain();
|
||||
|
||||
let first = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(first, serde_json::json!([]), "the buffer needed no edit: {first:#?}");
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::WARNING);
|
||||
assert!(shown[0].1.contains("formatting with default settings"), "{}", shown[0].1);
|
||||
|
||||
// A second save of the same still-broken config, with nothing having
|
||||
// changed the buffer in between, says nothing new.
|
||||
let second = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(second, serde_json::json!([]), "{second:#?}");
|
||||
assert!(session.shown().is_empty(), "the warning does not repeat per save");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reformatting_save_re_arms_the_broken_config_warning_on_the_very_next_save() {
|
||||
// QA (2026-08-26) finding, not a fix: `warn_about_config`'s dedup is
|
||||
// keyed on `set_document`, and `set_document` is exactly what runs
|
||||
// when the client applies a save hook's edit and the resulting
|
||||
// `didChange` reaches the server (see
|
||||
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`,
|
||||
// which does this on purpose to model the real sequence). So "warns
|
||||
// once" (Assumptions, work log) only holds once the buffer stops
|
||||
// needing edits — a save that *itself* reformats the buffer re-arms
|
||||
// the same warning for the very next save, because that save is
|
||||
// preceded by a `didChange` the dedup treats as a fresh state. Two
|
||||
// back-to-back saves of a buffer that needs reformatting under a
|
||||
// broken config warn twice, not once; the third (once the buffer is a
|
||||
// fixed point and no further `didChange` lands) is finally silent.
|
||||
// This is consistent with the doc comment on `warn_about_config`
|
||||
// ("once per change of a file") — it is the *save hook's own* prose
|
||||
// ("warns once") that does not spell out this edge, and a future
|
||||
// reader relying on literally one warning per broken config should
|
||||
// know better.
|
||||
let tree = Tree::new("willsavebrokenconfigrearm");
|
||||
tree.write("lucisv.toml", "indent = 4\nbogus = 1\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
session.notify(DidChangeConfiguration::METHOD, format_on_save(true));
|
||||
let _ = session.drain();
|
||||
|
||||
let first = will_save(&mut session, &uri, 1);
|
||||
let formatted = first[0]["newText"].as_str().expect("newText").to_string();
|
||||
assert_eq!(formatted, "module m;\n wire a;\nendmodule\n", "{first:#?}");
|
||||
assert_eq!(session.shown().len(), 1, "the first save warns");
|
||||
|
||||
// The client applies the edit and writes, exactly as
|
||||
// `applying_the_save_hooks_edit_leaves_the_next_save_nothing_to_do`
|
||||
// does — this is what re-arms the dedup.
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": formatted.clone() }]));
|
||||
let second = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(second, serde_json::json!([]), "already formatted: {second:#?}");
|
||||
assert_eq!(session.shown().len(), 1, "the second save warns again, not zero times");
|
||||
|
||||
// No further `didChange` follows a no-op save, so the third finally
|
||||
// stays quiet — the dedup this test is not disputing.
|
||||
let third = will_save(&mut session, &uri, 1);
|
||||
assert_eq!(third, serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
//! The index rebuild as the client sees it: the persistent cache, the size cap, the per-file log, and one bar per rescan path.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A tree with one file the default cap would keep and one it would not.
|
||||
/// The big one is padded with a trailing comment, so what makes it big is
|
||||
/// not what makes it a package.
|
||||
fn oversized_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.package("rtl/keep.sv", "keep_pkg");
|
||||
let head = "package netlist_pkg;\n localparam K = 1;\nendpackage\n// ";
|
||||
let mut text = String::from(head);
|
||||
while text.len() < 4096 {
|
||||
text.push('x');
|
||||
}
|
||||
text.push('\n');
|
||||
tree.write("rtl/netlist.sv", &text);
|
||||
tree
|
||||
}
|
||||
|
||||
/// The `message` of every `$/progress` end in one drained batch, and every
|
||||
/// `window/logMessage` line in it. Read off one drain rather than through
|
||||
/// `Session::ended`/`logged`, because a test that wants both cannot drain
|
||||
/// twice.
|
||||
fn ends(messages: &[Message]) -> Vec<Option<String>> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params.clone()).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::End(end) => Some(end.message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn log_lines(messages: &[Message]) -> Vec<String> {
|
||||
messages
|
||||
.iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params.clone()).expect("log params");
|
||||
Some(params.message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_session_over_the_same_storage_folder_resumes_from_the_cache() {
|
||||
// The owner's case, end to end through the real dispatch: a session
|
||||
// indexes a tree, the editor goes away, and the next session over the
|
||||
// same storage folder gets the same index without parsing anything.
|
||||
let tree = Tree::new("resume");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
tree.package("rtl/b.sv", "b_pkg");
|
||||
let storage = Tree::new("resume_storage");
|
||||
let wide = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut first = Session::started_in(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide.clone(),
|
||||
Some(storage.path.clone()),
|
||||
);
|
||||
let cold = first.drain();
|
||||
assert_eq!(ends(&cold), vec![Some("2 files indexed".to_string())], "a cold session");
|
||||
assert_eq!(
|
||||
log_lines(&cold).iter().filter(|line| line.starts_with("indexing: ")).count(),
|
||||
2,
|
||||
"both files were parsed: {:?}",
|
||||
log_lines(&cold)
|
||||
);
|
||||
let before = first.server.workspace.index().fingerprint();
|
||||
let answer = first.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"}));
|
||||
drop(first);
|
||||
|
||||
let mut second = Session::started_in(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide,
|
||||
Some(storage.path.clone()),
|
||||
);
|
||||
let warm = second.drain();
|
||||
assert_eq!(
|
||||
ends(&warm),
|
||||
vec![Some("2 files indexed, 2 from cache".to_string())],
|
||||
"the bar says where the files came from"
|
||||
);
|
||||
let lines = log_lines(&warm);
|
||||
assert_eq!(
|
||||
lines.iter().filter(|line| line.starts_with("cached: ")).count(),
|
||||
2,
|
||||
"and so does the log, file by file: {lines:?}"
|
||||
);
|
||||
assert!(
|
||||
!lines.iter().any(|line| line.starts_with("indexing: ")),
|
||||
"nothing was parsed: {lines:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
second.server.workspace.index().fingerprint(),
|
||||
before,
|
||||
"the same index, byte for byte"
|
||||
);
|
||||
assert_eq!(
|
||||
second.result(WorkspaceSymbolRequest::METHOD, serde_json::json!({"query": "pkg"})),
|
||||
answer,
|
||||
"and the same answers over the wire"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_was_offered_no_storage_folder_keeps_its_index_in_memory() {
|
||||
// What every client but ours does, and what `smoke.js` does: no
|
||||
// `storagePath`, no workspace root to key an OS-directory store on,
|
||||
// so nothing is persisted and nothing is read — today's behaviour,
|
||||
// unchanged.
|
||||
let tree = Tree::new("nostorage");
|
||||
tree.package("rtl/a.sv", "a_pkg");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let first = session.drain();
|
||||
assert_eq!(ends(&first), vec![Some("1 file indexed".to_string())]);
|
||||
assert!(
|
||||
log_lines(&first).iter().all(|line| !line.starts_with("cached: ")),
|
||||
"nothing can come from a cache that was never written: {:?}",
|
||||
log_lines(&first)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_end_message_names_what_the_cap_skipped() {
|
||||
// The count survives even when the per-file log is off, because it is
|
||||
// the only place a user who turned the log off would hear that part of
|
||||
// their workspace is not indexed.
|
||||
let tree = oversized_tree("capend");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())], "premise: no cap");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": {
|
||||
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
assert_eq!(
|
||||
session.ended(),
|
||||
vec![Some("1 file indexed, 1 skipped".to_string())],
|
||||
"the cap change rescanned, and the end message counts the skip"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_capped_file_is_out_of_the_index_and_an_open_buffer_is_not() {
|
||||
let tree = oversized_tree("capserver");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(1024));
|
||||
assert_eq!(indexed(&session, "netlist_pkg"), 0, "the big file is not indexed");
|
||||
assert_eq!(indexed(&session, "keep_pkg"), 1, "and the small one still is");
|
||||
|
||||
// Opening it is the user saying they want it: the buffer is indexed
|
||||
// whatever the cap says.
|
||||
let text = std::fs::read_to_string(tree.path.join("rtl/netlist.sv")).expect("read");
|
||||
session.open(&tree.path.join("rtl/netlist.sv"), &text);
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": path_to_uri(&tree.path.join("rtl/netlist.sv")).expect("uri") }
|
||||
}),
|
||||
);
|
||||
assert_eq!(indexed(&session, "netlist_pkg"), 1, "an open buffer is exempt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_indexed_file_is_named_in_the_log_and_so_is_every_skip() {
|
||||
let tree = oversized_tree("caplog");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let _ = session.drain();
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(1024));
|
||||
|
||||
let logged = session.logged();
|
||||
assert!(
|
||||
logged.iter().all(|(typ, _)| *typ == MessageType::LOG),
|
||||
"the file log is LOG, never a popup-worthy level: {logged:?}"
|
||||
);
|
||||
let lines: Vec<&String> = logged.iter().map(|(_, line)| line).collect();
|
||||
assert_eq!(
|
||||
lines.iter().filter(|l| l.starts_with("indexing: ")).count(),
|
||||
1,
|
||||
"one line per file parsed: {lines:?}"
|
||||
);
|
||||
assert!(
|
||||
lines.iter().any(|l| l.ends_with("rtl/keep.sv") && l.starts_with("indexing: ")),
|
||||
"named by full path: {lines:?}"
|
||||
);
|
||||
let skip = lines
|
||||
.iter()
|
||||
.find(|l| l.starts_with("skipped ("))
|
||||
.unwrap_or_else(|| panic!("a skip line: {lines:?}"));
|
||||
assert!(skip.contains("1.0 KiB cap"), "the cap it was measured against: {skip}");
|
||||
assert!(skip.contains("4.0 KiB >"), "and the size that broke it: {skip}");
|
||||
assert!(skip.ends_with("rtl/netlist.sv"), "and the file it kept out: {skip}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_log_goes_quiet_when_the_setting_is_off() {
|
||||
let tree = oversized_tree("caplogoff");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let _ = session.drain();
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": {
|
||||
"index": { "maxFileSize": 1024, "logFiles": false, "scope": "workspace" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
let logged = session.logged();
|
||||
assert!(logged.is_empty(), "not one line, skips included: {logged:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_log_does_not_wait_for_a_progress_bar() {
|
||||
// The two features are independent: the log is a `window/logMessage`,
|
||||
// which every client gets, and the bar is gated on a capability.
|
||||
let tree = Tree::new("caplognobar");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::wide(vec![tree.path.clone()], false);
|
||||
// One drain, both questions: `Session::drain` consumes.
|
||||
let messages = session.drain();
|
||||
assert!(
|
||||
messages.iter().cloned().filter_map(progress_step).next().is_none(),
|
||||
"premise: no bar for this client"
|
||||
);
|
||||
let logged: Vec<String> = messages
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params).expect("log message params");
|
||||
Some(params.message)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(logged.len(), 1, "{logged:?}");
|
||||
assert!(logged[0].starts_with("indexing: "), "{logged:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_cap_rescans_and_a_new_log_setting_does_not() {
|
||||
// `lucisv.index.maxFileSize` changes which files exist, so it costs a
|
||||
// rescan exactly as `exclude` does; `logFiles` changes nothing but the
|
||||
// narration of the next one.
|
||||
let tree = Tree::new("caprescan");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(4096));
|
||||
assert_eq!(session.progress().len(), 4, "create, begin, one report, end");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, capping(4096));
|
||||
assert!(session.progress().is_empty(), "the same cap again buys nothing");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": {
|
||||
"index": { "maxFileSize": 4096, "logFiles": false, "scope": "workspace" }
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
assert!(session.progress().is_empty(), "and neither does turning the log off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_index_scope_or_depth_rescans_through_the_real_dispatch() {
|
||||
// The other two settings that change which files exist. Driven through
|
||||
// `didChangeConfiguration` rather than `set_client_settings`, because
|
||||
// the parser, the change test and the rescan are three separate places
|
||||
// a scope setting could be dropped.
|
||||
let tree = Tree::new("scoperescan");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("include/defs.sv", "defs_pkg");
|
||||
let scoped = |scope: &str, depth: u32| {
|
||||
serde_json::json!({
|
||||
"settings": { "lucisv": { "index": { "scope": scope, "scopeDepth": depth } } }
|
||||
})
|
||||
};
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
// The shipped depth is 2 since 2026-08-28, which already reaches the
|
||||
// sibling folder — so the narrow premise this test raises the depth
|
||||
// *from* is asked for out loud.
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 0));
|
||||
let uri = session.open(
|
||||
&tree.path.join("rtl/a.sv"),
|
||||
"package a;\n localparam K = 1;\n\
|
||||
endpackage\n",
|
||||
);
|
||||
let _ = (uri, session.drain());
|
||||
assert_eq!(indexed(&session, "defs_pkg"), 0, "premise: the sibling folder is out of scope");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
|
||||
assert_eq!(session.progress().len(), 5, "create, begin, two reports, end");
|
||||
assert_eq!(indexed(&session, "defs_pkg"), 1, "one level up reaches the sibling folder");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("folder", 1));
|
||||
assert!(session.progress().is_empty(), "the same depth again buys nothing");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, scoped("workspace", 1));
|
||||
assert!(!session.progress().is_empty(), "and a new scope does");
|
||||
assert_eq!(indexed(&session, "defs_pkg"), 1, "the whole workspace, now");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_names_the_open_file_before_the_rest_of_the_scope() {
|
||||
// The progress half of the open-first ordering: the file the user is
|
||||
// waiting on is `1/N`, not wherever its name happens to sort. The
|
||||
// index it produces is identical either way — that is pinned in
|
||||
// `state.rs` and in `vlog_semantic`, because it is a property of the
|
||||
// builder rather than of the bar.
|
||||
let tree = Tree::new("scopeorderbar");
|
||||
tree.package("rtl/a_first.sv", "a_first");
|
||||
tree.package("rtl/m_open.sv", "m_open");
|
||||
tree.package("rtl/z_last.sv", "z_last");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/m_open.sv"), "package m_open;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// A whole rescan, since that is what has a bar to name files on: a
|
||||
// save of one held file takes the incremental path now
|
||||
// (incremental-index, 2026-08-27).
|
||||
session.watched(&[tree.path.join("rtl/a_first.sv"), tree.path.join("rtl/z_last.sv")]);
|
||||
let named: Vec<Option<String>> =
|
||||
session.reported().into_iter().map(|(message, _)| message).collect();
|
||||
assert_eq!(
|
||||
named,
|
||||
vec![
|
||||
Some("1/3 m_open.sv".to_string()),
|
||||
Some("2/3 a_first.sv".to_string()),
|
||||
Some("3/3 z_last.sv".to_string()),
|
||||
],
|
||||
"the open buffer first, then path order"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_for_a_bar_is_sent_no_progress_at_all() {
|
||||
// The spec forbids server-initiated progress without the capability,
|
||||
// so this is not a cosmetic difference: it is a protocol violation
|
||||
// avoided.
|
||||
let tree = Tree::new("progressnone");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
assert!(session.progress().is_empty(), "not even at startup");
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert!(session.progress().is_empty(), "and not on a save either");
|
||||
// The watcher registration is the only thing such a client is asked.
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "nothing at all is asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_rescan_path_gets_its_own_bar_and_its_own_token() {
|
||||
// The three non-startup callers of the *whole* `reindex`: a save of a
|
||||
// file the index does not hold, a watcher event naming more than one
|
||||
// file, and a changed scope. One begin/end pair each, and no token
|
||||
// twice. (Superseded this round: the first two used to be a plain save
|
||||
// and a one-file watcher event, both of which take the incremental
|
||||
// path now and put no bar up at all.)
|
||||
let tree = Tree::new("progresspaths");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
let fresh = tree.path.join("rtl/c.sv");
|
||||
tree.package("rtl/c.sv", "c");
|
||||
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
|
||||
);
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
|
||||
);
|
||||
|
||||
let steps = session.progress();
|
||||
let begins: Vec<&String> =
|
||||
steps.iter().filter(|(step, _)| *step == "begin").map(|(_, token)| token).collect();
|
||||
let ends: Vec<&String> =
|
||||
steps.iter().filter(|(step, _)| *step == "end").map(|(_, token)| token).collect();
|
||||
assert_eq!(begins, vec!["lucisv-index-1", "lucisv-index-2", "lucisv-index-3"], "{steps:#?}");
|
||||
assert_eq!(ends, begins, "every bar that went up came down");
|
||||
// Superseded this round: there *are* reports now, and every one of
|
||||
// them belongs to a bar that is up. What must never happen is a
|
||||
// report on a token whose `end` has already gone out.
|
||||
let mut open: Option<&String> = None;
|
||||
for (step, token) in &steps {
|
||||
match *step {
|
||||
"begin" => open = Some(token),
|
||||
"report" => {
|
||||
assert_eq!(open, Some(token), "a report outside its own bar: {steps:#?}")
|
||||
}
|
||||
"end" => open = None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_progress_create_answer_is_ignored_and_never_disturbs_an_apply_edit() {
|
||||
// Both request kinds are in flight at once. The progress answers —
|
||||
// one `Ok`, one `Err` — must fall straight through `response`, and the
|
||||
// one `applyEdit` answer must still be the one that speaks.
|
||||
let abilities =
|
||||
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
|
||||
let (tree, mut session, params) = propagating("progressapplyedit", abilities);
|
||||
let _ = session.drain();
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
|
||||
// Force a *whole* rescan while the edit is outstanding, so a progress
|
||||
// create sits between the push and its answer. Two files, because one
|
||||
// takes the incremental path and puts no bar up
|
||||
// (incremental-index, 2026-08-27).
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
let sent = session.sent();
|
||||
let edit =
|
||||
sent.iter().find(|request| request.method == ApplyWorkspaceEdit::METHOD).expect("the push");
|
||||
let creates: Vec<&Request> =
|
||||
sent.iter().filter(|r| r.method == WorkDoneProgressCreate::METHOD).collect();
|
||||
assert_eq!(creates.len(), 1, "one rescan, one create: {sent:#?}");
|
||||
|
||||
// Answer the create both ways a client can, then refuse the edit.
|
||||
session.answer(creates[0].id.clone(), serde_json::json!(null));
|
||||
session.server.response(Response::new_err(
|
||||
creates[0].id.clone(),
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
"no progress here".to_string(),
|
||||
));
|
||||
assert!(session.shown().is_empty(), "a create answer says nothing to the user");
|
||||
|
||||
session.answer(edit.id.clone(), serde_json::json!({ "applied": false }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_create_answer_after_the_apply_edit_already_answered_is_ignored_too() {
|
||||
// The reverse interleaving from the test above: here the outstanding
|
||||
// `applyEdit` is answered first, and the progress `create` for a
|
||||
// rescan that started while it was outstanding answers only after.
|
||||
// Same fall-through path in `response`, opposite arrival order — both
|
||||
// must leave the refusal-reporting untouched.
|
||||
let abilities =
|
||||
ClientAbilities { apply_edit: true, work_done_progress: true, ..Default::default() };
|
||||
let (tree, mut session, params) = propagating("progressapplyedit2", abilities);
|
||||
let _ = session.drain();
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
|
||||
// Two files, so the rescan is the whole one that puts a bar up.
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
let sent = session.sent();
|
||||
let edit =
|
||||
sent.iter().find(|request| request.method == ApplyWorkspaceEdit::METHOD).expect("the push");
|
||||
let create = sent
|
||||
.iter()
|
||||
.find(|request| request.method == WorkDoneProgressCreate::METHOD)
|
||||
.expect("the create");
|
||||
|
||||
// The edit resolves first, cleanly...
|
||||
session.answer(edit.id.clone(), serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "an accepted edit says nothing to the user");
|
||||
|
||||
// ...and only afterward does the create answer arrive, for a bar that
|
||||
// came down long ago. It must still fall straight through.
|
||||
session.server.response(Response::new_ok(create.id.clone(), serde_json::json!(null)));
|
||||
assert!(session.shown().is_empty(), "a late create answer says nothing either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_watcher_registration_arrives_after_the_indexing_bar_comes_down() {
|
||||
// `Server::new` now asks a fully-capable client two things at
|
||||
// startup: the progress create/begin/end around `open_roots`, then
|
||||
// `register_watchers`. This pins the order the restructuring must
|
||||
// preserve — the watcher request must not land in the middle of the
|
||||
// bar it was rewritten to make room for.
|
||||
let tree = Tree::new("progressandwatchers");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let abilities =
|
||||
ClientAbilities { file_watching: true, work_done_progress: true, ..Default::default() };
|
||||
let session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match &message {
|
||||
Message::Request(request) if request.method == RegisterCapability::METHOD => {
|
||||
Some("register".to_string())
|
||||
}
|
||||
_ => progress_step(message).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(order, vec!["create", "begin", "report", "end", "register"], "{order:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_the_bar_gets_none_on_the_watcher_or_config_paths_either() {
|
||||
// The existing off-test drives only startup and a save. `begin_indexing`
|
||||
// is called from the same `reindex()` on all three rescan triggers, but
|
||||
// the other two deserve their own witness rather than resting on that
|
||||
// being obvious from reading the code.
|
||||
let tree = Tree::new("progressnonewatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
let _ = session.drain();
|
||||
|
||||
session.watched(&[tree.path.join("rtl/a.sv")]);
|
||||
assert!(session.progress().is_empty(), "not on a watched file change");
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": "files.f" } } }),
|
||||
);
|
||||
assert!(session.progress().is_empty(), "not on a changed filelist either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rootless_workspace_with_no_open_files_says_zero_at_startup_without_crashing() {
|
||||
// No roots and no open buffers: `sibling_files` has nothing to walk,
|
||||
// so the index is empty. The end message must still be honest — and
|
||||
// the plural rule still holds, "0 files" and not "0 file".
|
||||
let session = Session::with(Vec::new(), watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("0 files indexed".to_string())]);
|
||||
}
|
||||
@@ -0,0 +1,421 @@
|
||||
//! The large-file fast path (`docs/features/large-file-mode/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// the large-file fast path (`docs/features/large-file-mode/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A session whose fast path starts at 100 bytes, so a test buffer can be
|
||||
/// three lines long instead of four megabytes.
|
||||
fn fast_path_settings() -> ClientSettings {
|
||||
ClientSettings { large_file_threshold: 100, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A source file that is real Verilog and over the test threshold.
|
||||
fn big_source() -> String {
|
||||
let mut text = String::from("module top;\n wire sig_a;\n");
|
||||
for i in 0..20 {
|
||||
text.push_str(&format!(" assign sig_a = w{i};\n"));
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
assert!(text.len() > 100, "the premise: over the test threshold");
|
||||
text
|
||||
}
|
||||
|
||||
/// A session with one large buffer open, and its URI.
|
||||
///
|
||||
/// Every call gets its own tree: this is the one `Tree::new` name shared
|
||||
/// by roughly a dozen tests (every large-file-mode test that does not
|
||||
/// need bespoke source text), which — unlike the rest of this module's
|
||||
/// trees, each named for the one test that uses it — would otherwise
|
||||
/// collide on the same `/tmp` directory under `cargo test`'s default
|
||||
/// parallelism and race each other's `remove_dir_all`/`create_dir_all`.
|
||||
/// The counter is what makes the shared literal safe to share.
|
||||
fn fast_path_session(abilities: ClientAbilities) -> (Tree, Session, Uri) {
|
||||
static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
let tree = Tree::new(&format!("largefile{n}"));
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
let mut session = Session::started(vec![tree.path.clone()], abilities, fast_path_settings());
|
||||
let uri = session.open(&path, &big_source());
|
||||
let _ = session.drain();
|
||||
(tree, session, uri)
|
||||
}
|
||||
|
||||
/// The params a document-scoped request carries, at a position on the
|
||||
/// `sig_a` declaration.
|
||||
fn at_sig_a(uri: &Uri) -> Value {
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 9 },
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_over_the_threshold_opens_on_the_fast_path_and_says_so_once() {
|
||||
let (_tree, mut session, uri) = {
|
||||
let tree = Tree::new("largeannounce");
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
let mut session = Session::started(
|
||||
vec![tree.path.clone()],
|
||||
ClientAbilities::default(),
|
||||
fast_path_settings(),
|
||||
);
|
||||
let uri = session.open(&path, &big_source());
|
||||
(tree, session, uri)
|
||||
};
|
||||
let lines: Vec<String> = session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.map(|(_, message)| message)
|
||||
.filter(|message| message.contains("large-file fast path"))
|
||||
.collect();
|
||||
assert_eq!(lines.len(), 1, "once per entry into the mode: {lines:?}");
|
||||
assert!(lines[0].contains("net.v"), "{}", lines[0]);
|
||||
assert!(lines[0].contains("bytes"), "{}", lines[0]);
|
||||
|
||||
// A keystroke in it does not say it again.
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
!session.logged().iter().any(|(_, m)| m.contains("large-file fast path")),
|
||||
"the line is per entry, not per notification"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_large_buffer_is_diagnosed_as_empty_and_clears_what_it_left_behind() {
|
||||
let tree = Tree::new("largesquiggles");
|
||||
let path = tree.path.join("grow.v");
|
||||
let mut session =
|
||||
Session::started(vec![tree.path.clone()], ClientAbilities::default(), fast_path_settings());
|
||||
// Small and broken: a real diagnostic is drawn.
|
||||
let uri = session.open(&path, "module m;\n wire ;\nendmodule\n");
|
||||
let drawn = session.published();
|
||||
assert_eq!(drawn.len(), 1);
|
||||
assert!(!drawn[0].diagnostics.is_empty(), "premise: squiggles were drawn");
|
||||
|
||||
// The same buffer, edited past the threshold: one publish, empty, so
|
||||
// the squiggles go away rather than being left frozen on screen.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }]),
|
||||
);
|
||||
let cleared = session.published();
|
||||
assert_eq!(cleared.len(), 1, "one publish, as every change makes");
|
||||
assert!(cleared[0].diagnostics.is_empty(), "and it is empty: {cleared:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_tokens_range_paints_a_large_buffer() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let data = session.result(
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 3, "character": 0 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
let tokens = data["data"].as_array().expect("a token array").clone();
|
||||
assert!(!tokens.is_empty(), "the window was lexed: {data}");
|
||||
assert!(data["resultId"].is_null(), "a range answer is not delta material");
|
||||
// First token: `wire` on line 1, five numbers per token.
|
||||
assert_eq!(tokens.len() % 5, 0);
|
||||
assert_eq!(tokens[0], 1, "delta_line — the first line of the window");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_tokens_full_is_declined_rather_than_answered_empty() {
|
||||
// The whole reason: VS Code marks a model whose document provider
|
||||
// answered *anything* as complete and never asks its range provider
|
||||
// again. An error leaves it incomplete, so the viewport keeps
|
||||
// painting. `serverCancelSupport` decides which code says so.
|
||||
let cancels = ClientAbilities { token_server_cancel: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = fast_path_session(cancels);
|
||||
let params = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
for method in [SemanticTokensFullRequest::METHOD, SemanticTokensFullDeltaRequest::METHOD] {
|
||||
let mut params = params.clone();
|
||||
params["previousResultId"] = serde_json::json!("1");
|
||||
let error = session.request(method, params).response_result.expect_err("declined");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::ServerCancelled as i32, "{method}");
|
||||
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
|
||||
}
|
||||
|
||||
// A client that never advertised it gets the code every 3.16 client
|
||||
// already understands.
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let error = session
|
||||
.request(
|
||||
SemanticTokensFullRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
)
|
||||
.response_result
|
||||
.expect_err("declined");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::ContentModified as i32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formatting_a_large_buffer_refuses_out_loud_and_edits_nothing() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let edits = session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
assert_eq!(edits, serde_json::json!([]), "no edit, ever");
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "the user pressed a key and is owed a reason: {shown:?}");
|
||||
assert_eq!(shown[0].0, MessageType::ERROR);
|
||||
assert!(shown[0].1.contains("largeFile.threshold"), "{}", shown[0].1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_two_formatting_requests_the_user_did_not_press_stay_silent() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let edits = session.result(
|
||||
OnTypeFormatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 1, "character": 9 },
|
||||
"ch": ";",
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
);
|
||||
assert_eq!(edits, serde_json::json!([]));
|
||||
let saved = session.result(
|
||||
WillSaveWaitUntil::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "reason": 1 }),
|
||||
);
|
||||
assert_eq!(saved, Value::Null);
|
||||
assert!(session.shown().is_empty(), "neither fires on a key the user pressed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rename_is_refused_rather_than_applied_to_every_file_but_this_one() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
assert_eq!(
|
||||
session.result(PrepareRenameRequest::METHOD, at_sig_a(&uri)),
|
||||
Value::Null,
|
||||
"the box never opens"
|
||||
);
|
||||
let mut params = at_sig_a(&uri);
|
||||
params["newName"] = serde_json::json!("sig_b");
|
||||
let error = session.request(Rename::METHOD, params).response_result.expect_err("refused");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
||||
assert!(error.message.contains("largeFile.threshold"), "{}", error.message);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_and_references_answer_from_one_scan_of_the_buffer() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
// The cursor is on the `sig_a` of `wire sig_a;`, and every `sig_a` in
|
||||
// the file is one answer.
|
||||
let found = session.result(GotoDefinition::METHOD, at_sig_a(&uri));
|
||||
let locations = found.as_array().expect("an array");
|
||||
assert_eq!(locations.len(), 1, "{found}");
|
||||
assert_eq!(locations[0]["range"]["start"]["line"], 1);
|
||||
assert_eq!(locations[0]["uri"].as_str(), Some(uri.as_str()));
|
||||
|
||||
let mut params = at_sig_a(&uri);
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": true });
|
||||
let all = session.result(References::METHOD, params.clone());
|
||||
assert_eq!(all.as_array().expect("an array").len(), 21, "the wire and its 20 uses");
|
||||
params["context"] = serde_json::json!({ "includeDeclaration": false });
|
||||
let uses = session.result(References::METHOD, params);
|
||||
assert_eq!(uses.as_array().expect("an array").len(), 20, "minus the declaration");
|
||||
}
|
||||
|
||||
/// **The dispatch table.** Every document-scoped request, and what a
|
||||
/// buffer on the fast path answers it. The point is that the list is
|
||||
/// complete and pinned: a handler added later that reads a large buffer's
|
||||
/// *text* will fail here rather than in a user's editor.
|
||||
#[test]
|
||||
fn every_other_request_a_large_buffer_gets_answers_nothing_at_all() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
let document = serde_json::json!({ "textDocument": { "uri": uri } });
|
||||
let position = at_sig_a(&uri);
|
||||
let range = serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 3, "character": 0 },
|
||||
},
|
||||
});
|
||||
let empty = serde_json::json!([]);
|
||||
// (method, params, expected answer)
|
||||
let table: Vec<(&str, Value, Value)> = vec![
|
||||
(HoverRequest::METHOD, position.clone(), Value::Null),
|
||||
(GotoTypeDefinition::METHOD, position.clone(), empty.clone()),
|
||||
(LinkedEditingRange::METHOD, position.clone(), Value::Null),
|
||||
(DocumentLinkRequest::METHOD, document.clone(), empty.clone()),
|
||||
(DocumentHighlightRequest::METHOD, position.clone(), Value::Null),
|
||||
(FoldingRangeRequest::METHOD, document.clone(), empty.clone()),
|
||||
(DocumentSymbolRequest::METHOD, document.clone(), empty.clone()),
|
||||
(CodeLensRequest::METHOD, document.clone(), empty.clone()),
|
||||
(InlayHintRequest::METHOD, range.clone(), empty.clone()),
|
||||
(
|
||||
CodeActionRequest::METHOD,
|
||||
{
|
||||
let mut params = range.clone();
|
||||
params["context"] = serde_json::json!({ "diagnostics": [] });
|
||||
params
|
||||
},
|
||||
empty.clone(),
|
||||
),
|
||||
(Completion::METHOD, position.clone(), Value::Null),
|
||||
(SignatureHelpRequest::METHOD, position.clone(), Value::Null),
|
||||
(
|
||||
InlineCompletionRequest::METHOD,
|
||||
{
|
||||
let mut params = position.clone();
|
||||
params["context"] =
|
||||
serde_json::json!({ "triggerKind": 2, "selectedCompletionInfo": null });
|
||||
params
|
||||
},
|
||||
Value::Null,
|
||||
),
|
||||
(CallHierarchyPrepare::METHOD, position.clone(), Value::Null),
|
||||
(TypeHierarchyPrepare::METHOD, position.clone(), Value::Null),
|
||||
// The one custom method: an object with both lists empty, which is
|
||||
// what "this buffer has no scopes" already looks like.
|
||||
(
|
||||
pairs::SCOPE_PAIRS_METHOD,
|
||||
document.clone(),
|
||||
serde_json::json!({ "pairs": [], "unmatched": [] }),
|
||||
),
|
||||
];
|
||||
for (method, params, expected) in table {
|
||||
assert_eq!(session.result(method, params), expected, "{method}");
|
||||
}
|
||||
// `selectionRange` is the one request that answers something: the
|
||||
// whole document is a legal expand-selection step even with nothing
|
||||
// parsed, and it costs one span.
|
||||
let mut selection = document.clone();
|
||||
selection["positions"] = serde_json::json!([{ "line": 1, "character": 9 }]);
|
||||
let chain = session.result(SelectionRangeRequest::METHOD, selection);
|
||||
assert_eq!(chain.as_array().expect("one chain per position").len(), 1);
|
||||
assert!(chain[0]["parent"].is_null(), "one step, the file: {chain}");
|
||||
// Nothing above said a word to the user.
|
||||
assert!(session.shown().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer() {
|
||||
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = fast_path_session(pulling);
|
||||
let report = session.result(
|
||||
DocumentDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(report["items"], serde_json::json!([]), "{report}");
|
||||
}
|
||||
|
||||
/// `workspace/diagnostic` walks every open buffer (`workspace_report`
|
||||
/// above), a large one included — it is not skipped, it is present with
|
||||
/// an empty **full** report, the same answer `diagnostics::all` gives
|
||||
/// `textDocument/diagnostic`. Pinned because the workspace-scoped sweep is
|
||||
/// a different code path from the per-document one already covered by
|
||||
/// `a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer`.
|
||||
#[test]
|
||||
fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report() {
|
||||
let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() };
|
||||
let (_tree, mut session, uri) = fast_path_session(pulling);
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 1, "{report:#?}");
|
||||
assert_eq!(items[0]["uri"].as_str(), Some(uri.as_str()));
|
||||
assert_eq!(items[0]["kind"], "full", "present, not skipped: {report:#?}");
|
||||
assert_eq!(items[0]["items"], serde_json::json!([]), "{report:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() {
|
||||
let tree = Tree::new("largethreshold");
|
||||
let path = tree.path.join("net.v");
|
||||
tree.write("net.v", &big_source());
|
||||
// Default settings: the buffer is nowhere near 4 MiB, so it is
|
||||
// analyzed in full.
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&path, &big_source());
|
||||
assert!(!session.server.workspace.document(&uri).expect("open").large);
|
||||
|
||||
// Pushed. The buffer already open does not change mode on the spot —
|
||||
// the decision is taken where a document is built.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
||||
assert!(
|
||||
!session.server.workspace.document(&uri).expect("open").large,
|
||||
"the open buffer keeps the mode it was built in"
|
||||
);
|
||||
change(&mut session, &uri, 2, serde_json::json!([{ "text": big_source() }]));
|
||||
assert!(
|
||||
session.server.workspace.document(&uri).expect("open").large,
|
||||
"and takes the fast path at its next change"
|
||||
);
|
||||
|
||||
// Pulled: the same value through the other door.
|
||||
let mut session = Session::with(
|
||||
vec![tree.path.clone()],
|
||||
ClientAbilities { configuration: true, ..Default::default() },
|
||||
);
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([{ "largeFile": { "threshold": 100 } }]));
|
||||
assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100);
|
||||
let uri = session.open(&path, &big_source());
|
||||
assert!(session.server.workspace.document(&uri).expect("open").large);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_to_a_large_buffer_moves_its_lines_and_the_next_window_agrees() {
|
||||
let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default());
|
||||
// Insert a line at the top. `sig_a`'s declaration moves from line 1
|
||||
// to line 2, which is only true if the line index was rebuilt.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{
|
||||
"range": {
|
||||
"start": { "line": 0, "character": 0 },
|
||||
"end": { "line": 0, "character": 0 },
|
||||
},
|
||||
"text": "// a new first line\n",
|
||||
}],
|
||||
}),
|
||||
);
|
||||
let data = session.result(
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": 2, "character": 0 },
|
||||
"end": { "line": 3, "character": 0 },
|
||||
},
|
||||
}),
|
||||
);
|
||||
let tokens = data["data"].as_array().expect("tokens");
|
||||
assert_eq!(tokens[0], 2, "the window's own line, after the insertion");
|
||||
let found = session.result(
|
||||
GotoDefinition::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 2, "character": 9 },
|
||||
}),
|
||||
);
|
||||
assert_eq!(found[0]["range"]["start"]["line"], 2, "{found}");
|
||||
}
|
||||
@@ -0,0 +1,555 @@
|
||||
//! The `Server` tests: one file per feature, every one driven through the
|
||||
//! real `process_batch` against a scratch workspace on disk.
|
||||
//!
|
||||
//! This file is the harness — `Tree`, a workspace root removed on drop, and
|
||||
//! `Session`, a server on an in-memory connection whose every outgoing
|
||||
//! message can be read back — followed by the helpers more than one file
|
||||
//! uses. The sibling files are the sections the one big test module used to
|
||||
//! have, under the names they had; a helper used by one section only stayed
|
||||
//! with it.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::str::FromStr;
|
||||
|
||||
use lsp_server::{Notification, Request, Response};
|
||||
use lsp_types::notification::{
|
||||
DidChangeConfiguration, DidChangeTextDocument, DidChangeWatchedFiles,
|
||||
DidChangeWorkspaceFolders, DidCloseTextDocument, DidDeleteFiles, DidOpenTextDocument,
|
||||
DidRenameFiles, DidSaveTextDocument, LogMessage, Notification as _, Progress,
|
||||
PublishDiagnostics, ShowMessage,
|
||||
};
|
||||
use lsp_types::request::{
|
||||
ApplyWorkspaceEdit, CallHierarchyPrepare, CodeActionRequest, CodeLensRefresh, CodeLensRequest,
|
||||
Completion, DocumentDiagnosticRequest, DocumentHighlightRequest, DocumentLinkRequest,
|
||||
DocumentSymbolRequest, ExecuteCommand, FoldingRangeRequest, Formatting, GotoDefinition,
|
||||
GotoTypeDefinition, HoverRequest, InlayHintRequest, InlineCompletionRequest,
|
||||
LinkedEditingRange, OnTypeFormatting, PrepareRenameRequest, RangeFormatting, References,
|
||||
RegisterCapability, Rename, Request as _, SelectionRangeRequest,
|
||||
SemanticTokensFullDeltaRequest, SemanticTokensFullRequest, SemanticTokensRangeRequest,
|
||||
ShowDocument, Shutdown, SignatureHelpRequest, TypeHierarchyPrepare, UnregisterCapability,
|
||||
WillRenameFiles, WillSaveWaitUntil, WorkDoneProgressCreate, WorkspaceConfiguration,
|
||||
WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
DidChangeWatchedFilesParams, FileChangeType, FileEvent, LogMessageParams, MessageType,
|
||||
ProgressParams, ProgressParamsValue, ProgressToken, PublishDiagnosticsParams,
|
||||
ShowMessageParams, WorkDoneProgress, WorkDoneProgressCreateParams,
|
||||
};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::batch::{is_shutdown, widen_of, Widen};
|
||||
use super::progress::{reports, MAX_REPORTS};
|
||||
use super::*;
|
||||
use crate::uri::path_to_uri;
|
||||
use crate::{design_hierarchy, diagnostics, format, lens, pairs, ports};
|
||||
|
||||
mod apply_edit;
|
||||
mod cancel;
|
||||
mod file_ops;
|
||||
mod folders;
|
||||
mod formatting;
|
||||
mod index;
|
||||
mod large_file;
|
||||
mod progress;
|
||||
mod pull_diagnostics;
|
||||
mod requests;
|
||||
mod scan;
|
||||
mod settings;
|
||||
mod sync;
|
||||
mod tokens;
|
||||
mod watchers;
|
||||
|
||||
/// A scratch workspace root, removed on drop.
|
||||
struct Tree {
|
||||
path: PathBuf,
|
||||
}
|
||||
|
||||
impl Tree {
|
||||
fn new(name: &str) -> Tree {
|
||||
let path =
|
||||
std::env::temp_dir().join(format!("lucisv_server_watch_{}_{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
std::fs::create_dir_all(&path).expect("temp dir");
|
||||
Tree { path }
|
||||
}
|
||||
|
||||
/// A package declaring one localparam, so the index can be asked
|
||||
/// whether this file was scanned at all.
|
||||
fn package(&self, rel: &str, name: &str) {
|
||||
let path = self.path.join(rel);
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).expect("parent");
|
||||
}
|
||||
std::fs::write(&path, format!("package {name};\n localparam K = 1;\nendpackage\n"))
|
||||
.expect("write");
|
||||
}
|
||||
|
||||
fn write(&self, rel: &str, text: &str) {
|
||||
std::fs::write(self.path.join(rel), text).expect("write");
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Tree {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// A real `Server` on an in-memory connection, plus the client end of it —
|
||||
/// so a test can drive a notification and read every message it produced.
|
||||
struct Session {
|
||||
server: Server,
|
||||
client: Connection,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
fn new(roots: Vec<PathBuf>, file_watching: bool) -> Session {
|
||||
Session::with(roots, ClientAbilities { file_watching, ..Default::default() })
|
||||
}
|
||||
|
||||
/// A session against a client that said exactly `abilities`.
|
||||
fn with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
|
||||
Session::started(roots, abilities, ClientSettings::default())
|
||||
}
|
||||
|
||||
/// A session whose client had already asked for
|
||||
/// `lucisv.index.scope: "workspace"` when the startup scan ran — the
|
||||
/// scope every session had before 2026-08-27.
|
||||
///
|
||||
/// Used by every test in this module whose subject is not the scope:
|
||||
/// they want their whole fixture tree indexed from the first bar, and
|
||||
/// saying so here keeps the folder scope from being a hidden variable
|
||||
/// in a test about a progress report or a rename. The folder scope's
|
||||
/// own behaviour is tested by the tests named in
|
||||
/// `docs/features/index-scope/README.md`.
|
||||
fn wide(roots: Vec<PathBuf>, file_watching: bool) -> Session {
|
||||
Session::wide_with(roots, ClientAbilities { file_watching, ..Default::default() })
|
||||
}
|
||||
|
||||
/// [`Session::wide`] against a client that said exactly `abilities`.
|
||||
fn wide_with(roots: Vec<PathBuf>, abilities: ClientAbilities) -> Session {
|
||||
let wide = ClientSettings {
|
||||
index_scope: crate::settings::IndexScope::Workspace,
|
||||
..Default::default()
|
||||
};
|
||||
Session::started(roots, abilities, wide)
|
||||
}
|
||||
|
||||
fn started(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
settings: ClientSettings,
|
||||
) -> Session {
|
||||
Session::started_in(roots, abilities, settings, None)
|
||||
}
|
||||
|
||||
/// [`Session::started`] against a client that offered a storage
|
||||
/// folder — `initializationOptions.storagePath`, which is where the
|
||||
/// persistent index cache goes.
|
||||
fn started_in(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
settings: ClientSettings,
|
||||
storage: Option<PathBuf>,
|
||||
) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
// Verbose off, which is how the server ships: every assertion in
|
||||
// this module counts the messages a session produces, and the
|
||||
// timing lines are tested where they are observable as protocol
|
||||
// traffic — `tests/e2e.rs`, against the real binary and its flag.
|
||||
let server =
|
||||
Server::started(server_end, roots, abilities, settings, storage, false, Vec::new());
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
/// [`Session::started`] against a client that had **already sent**
|
||||
/// `queued` when the server was built.
|
||||
///
|
||||
/// The opening burst of a real editor: `initialized` is answered by
|
||||
/// `initialize_finish`, and everything the client sent behind it is
|
||||
/// sitting on the transport before the startup scan takes its first
|
||||
/// file. That is the case
|
||||
/// `docs/features/scan-interleave/README.md` is about, and the only
|
||||
/// way to reach it is to put the messages there first.
|
||||
fn started_behind(
|
||||
roots: Vec<PathBuf>,
|
||||
abilities: ClientAbilities,
|
||||
settings: ClientSettings,
|
||||
on_the_wire: Vec<Message>,
|
||||
queued: Vec<Message>,
|
||||
) -> Session {
|
||||
let (server_end, client) = Connection::memory();
|
||||
// Anything that has to reach the *connection* rather than the
|
||||
// queue — an `exit`, which `handle_shutdown` reads for itself —
|
||||
// goes here, ahead of the forwarder ever starting.
|
||||
for message in on_the_wire {
|
||||
client.sender.send(message).expect("the client's wire traffic");
|
||||
}
|
||||
let server = Server::started(server_end, roots, abilities, settings, None, false, queued);
|
||||
Session { server, client }
|
||||
}
|
||||
|
||||
fn notify(&mut self, method: &str, params: impl serde::Serialize) {
|
||||
self.server.notification(Notification::new(method.to_string(), params));
|
||||
}
|
||||
|
||||
/// Drive one request through the real dispatch, as the loop would.
|
||||
fn request(&mut self, method: &str, params: impl serde::Serialize) -> Response {
|
||||
let id = RequestId::from(format!("test-{method}"));
|
||||
self.server.request(Request::new(id, method.to_string(), params))
|
||||
}
|
||||
|
||||
/// A request's result, or the reason it was refused.
|
||||
fn result(&mut self, method: &str, params: impl serde::Serialize) -> Value {
|
||||
match self.request(method, params).response_result {
|
||||
Ok(value) => value,
|
||||
Err(error) => panic!("{method} failed: {error:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Answer the last request the server made of us.
|
||||
fn answer(&mut self, id: RequestId, result: impl serde::Serialize) {
|
||||
self.server.response(Response::new_ok(id, result));
|
||||
}
|
||||
|
||||
/// Everything the server has said since the last drain.
|
||||
fn drain(&self) -> Vec<Message> {
|
||||
self.client.receiver.try_iter().collect()
|
||||
}
|
||||
|
||||
/// The requests the server has made of the client, as (method, params).
|
||||
fn requests(&self) -> Vec<(String, Value)> {
|
||||
self.sent().into_iter().map(|request| (request.method, request.params)).collect()
|
||||
}
|
||||
|
||||
/// The requests the server has made of the client, ids included.
|
||||
fn sent(&self) -> Vec<Request> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) => Some(request),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every progress message since the last drain, in order, as
|
||||
/// (step, token) — one `create` per request, one `begin`/`report`/`end`
|
||||
/// per `$/progress`. Order and token are the whole protocol here.
|
||||
fn progress(&self) -> Vec<(&'static str, String)> {
|
||||
self.drain().into_iter().filter_map(progress_step).collect()
|
||||
}
|
||||
|
||||
/// The `message` on every `$/progress` end since the last drain.
|
||||
fn ended(&self) -> Vec<Option<String>> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::End(end) => Some(end.message),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Every `$/progress` report since the last drain, as
|
||||
/// (message, percentage) — what the bar was told to say and where to
|
||||
/// stand.
|
||||
fn reported(&self) -> Vec<(Option<String>, Option<u32>)> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams =
|
||||
serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
match work {
|
||||
WorkDoneProgress::Report(report) => {
|
||||
Some((report.message, report.percentage))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Everything the server logged since the last drain, as
|
||||
/// (type, message) — the client's output channel, in order.
|
||||
fn logged(&self) -> Vec<(MessageType, String)> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == LogMessage::METHOD => {
|
||||
let params: LogMessageParams =
|
||||
serde_json::from_value(n.params).expect("log message params");
|
||||
Some((params.typ, params.message))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// What the server showed the user since the last drain, as
|
||||
/// (type, message).
|
||||
fn shown(&self) -> Vec<(MessageType, String)> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == ShowMessage::METHOD => {
|
||||
let params: ShowMessageParams =
|
||||
serde_json::from_value(n.params).expect("show message params");
|
||||
Some((params.typ, params.message))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many diagnostics publishes the server pushed since the last
|
||||
/// drain. With exactly one open buffer this counts index rebuilds:
|
||||
/// `reindex` republishes every open document, once.
|
||||
fn publishes(&self) -> usize {
|
||||
self.drain()
|
||||
.iter()
|
||||
.filter(|message| match message {
|
||||
Message::Notification(n) => n.method == PublishDiagnostics::METHOD,
|
||||
_ => false,
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
/// The diagnostics the server pushed since the last drain.
|
||||
fn published(&self) -> Vec<PublishDiagnosticsParams> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
|
||||
Some(serde_json::from_value(n.params).expect("publish params"))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn open(&mut self, path: &Path, text: &str) -> Uri {
|
||||
let uri = path_to_uri(path).expect("uri");
|
||||
self.notify(
|
||||
DidOpenTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": uri, "languageId": "systemverilog",
|
||||
"version": 1, "text": text,
|
||||
}
|
||||
}),
|
||||
);
|
||||
uri
|
||||
}
|
||||
|
||||
/// Drive one burst through the real loop body — the whole of `run`
|
||||
/// except the receiving — reporting whether the client shut us down.
|
||||
fn batch(&mut self, messages: Vec<Message>) -> bool {
|
||||
self.server.process_batch(messages).expect("the burst is handled")
|
||||
}
|
||||
|
||||
/// The responses the server sent since the last drain, in order.
|
||||
fn answers(&self) -> Vec<Response> {
|
||||
self.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Response(response) => Some(response),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn watched(&mut self, paths: &[PathBuf]) {
|
||||
let changes: Vec<FileEvent> = paths
|
||||
.iter()
|
||||
.map(|path| FileEvent {
|
||||
uri: path_to_uri(path).expect("uri"),
|
||||
typ: FileChangeType::CHANGED,
|
||||
})
|
||||
.collect();
|
||||
self.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
|
||||
}
|
||||
}
|
||||
|
||||
/// One message's place in the progress protocol, or `None` when it is not
|
||||
/// progress at all.
|
||||
fn progress_step(message: Message) -> Option<(&'static str, String)> {
|
||||
match message {
|
||||
Message::Request(request) if request.method == WorkDoneProgressCreate::METHOD => {
|
||||
let params: WorkDoneProgressCreateParams =
|
||||
serde_json::from_value(request.params).expect("create params");
|
||||
Some(("create", token_text(¶ms.token)))
|
||||
}
|
||||
Message::Notification(n) if n.method == Progress::METHOD => {
|
||||
let params: ProgressParams = serde_json::from_value(n.params).expect("progress params");
|
||||
let ProgressParamsValue::WorkDone(work) = params.value;
|
||||
let step = match work {
|
||||
WorkDoneProgress::Begin(_) => "begin",
|
||||
WorkDoneProgress::Report(_) => "report",
|
||||
WorkDoneProgress::End(_) => "end",
|
||||
};
|
||||
Some((step, token_text(¶ms.token)))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn token_text(token: &ProgressToken) -> String {
|
||||
match token {
|
||||
ProgressToken::String(text) => text.clone(),
|
||||
ProgressToken::Number(number) => number.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A client that shows a progress bar and nothing else.
|
||||
fn watching_progress() -> ClientAbilities {
|
||||
ClientAbilities { work_done_progress: true, ..Default::default() }
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// helpers more than one file uses
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
const SUB: &str = "module sub (\n input logic clk,\n input logic rst\n);\nendmodule\n";
|
||||
|
||||
const TOP: &str = "module top;\n logic clk, rst;\n sub u_sub (.clk(clk));\nendmodule\n";
|
||||
|
||||
/// One `didChange`, carrying whatever changes were given. The flush at the
|
||||
/// end is the quiet-period timer firing: a test drives notifications one
|
||||
/// at a time, so the burst the loop would have coalesced never forms, and
|
||||
/// without this the buffer would sit dirty forever.
|
||||
fn change(session: &mut Session, uri: &Uri, version: u32, changes: Value) {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": version },
|
||||
"contentChanges": changes,
|
||||
}),
|
||||
);
|
||||
session.server.flush_dirty();
|
||||
}
|
||||
|
||||
/// The text the server currently holds for a buffer — the newest applied
|
||||
/// text, which while a change sits dirty is the pending one.
|
||||
fn buffer(session: &Session, uri: &Uri) -> String {
|
||||
if let Some((_, text)) = session.server.dirty.iter().find(|(pending, _)| pending == uri) {
|
||||
return text.clone();
|
||||
}
|
||||
session.server.workspace.document(uri).expect("an open buffer").text.clone()
|
||||
}
|
||||
|
||||
/// A whole-buffer `didChange`, queued.
|
||||
fn changed(uri: &Uri, version: u32, text: &str) -> Message {
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": version },
|
||||
"contentChanges": [{ "text": text }],
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// The `didChangeConfiguration` push that sets the index size cap.
|
||||
///
|
||||
/// It carries `scope: "workspace"` because a push replaces *every*
|
||||
/// setting: a cap pushed on its own would take the index back to the
|
||||
/// folder scope in the same breath, which is not what a test about the cap
|
||||
/// is asking. Same reason `state.rs`'s `wide()` exists.
|
||||
fn capping(bytes: u64) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"settings": {
|
||||
"lucisv": { "index": { "maxFileSize": bytes, "scope": "workspace" } }
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A client that pulls diagnostics rather than being pushed them.
|
||||
fn pulling() -> ClientAbilities {
|
||||
ClientAbilities { pull_diagnostics: true, ..Default::default() }
|
||||
}
|
||||
|
||||
fn document_pull(session: &mut Session, uri: &Uri, previous: Option<&str>) -> Value {
|
||||
session.result(
|
||||
DocumentDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultId": previous,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// How many times the index holds a package of this name.
|
||||
fn indexed(session: &Session, name: &str) -> usize {
|
||||
session.server.workspace.index().member(name, "K").len()
|
||||
}
|
||||
|
||||
/// A `lucisv.filelist` push, in the shape a client sends it.
|
||||
fn filelist_push(path: &str) -> Value {
|
||||
serde_json::json!({ "settings": { "lucisv": { "filelist": path } } })
|
||||
}
|
||||
|
||||
/// Settings a test uses when its subject is not the scope, spelled once.
|
||||
fn wide_ish() -> ClientSettings {
|
||||
ClientSettings { index_scope: crate::settings::IndexScope::Workspace, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A workspace holding `sub` and two instantiations of it, with `sub.sv`
|
||||
/// open — the shape every lens test below asks about.
|
||||
fn lens_tree(name: &str) -> Tree {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
tree.write("top.sv", "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
|
||||
tree
|
||||
}
|
||||
|
||||
/// A two-module workspace with `top.sv` open, and the arguments that ask
|
||||
/// for the one port its instantiation is missing.
|
||||
fn propagating(name: &str, abilities: ClientAbilities) -> (Tree, Session, Value) {
|
||||
let tree = Tree::new(name);
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
let _ = session.drain();
|
||||
let params = serde_json::json!({
|
||||
"command": ports::PROPAGATE_PORTS,
|
||||
"arguments": [uri, { "line": 2, "character": 6 }],
|
||||
});
|
||||
(tree, session, params)
|
||||
}
|
||||
|
||||
/// What `textDocument/formatting` answers for the same buffer, asking for
|
||||
/// the 2-space tab an editor defaults to — which is also the built-in
|
||||
/// indent, so the two paths resolve to the same settings.
|
||||
fn formatting_result(session: &mut Session, uri: &Uri) -> Value {
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// The id of the one outstanding `workspace/configuration`, and the params
|
||||
/// it went out with.
|
||||
fn configuration_request(session: &Session) -> (RequestId, Value) {
|
||||
let sent = session.sent();
|
||||
let asked: Vec<&Request> =
|
||||
sent.iter().filter(|r| r.method == WorkspaceConfiguration::METHOD).collect();
|
||||
assert_eq!(asked.len(), 1, "exactly one pull is outstanding: {sent:#?}");
|
||||
(asked[0].id.clone(), asked[0].params.clone())
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
//! The indexing bar: when it goes up, what it counts, when it comes down.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_startup_index_build_runs_under_the_first_bar() {
|
||||
// It is the slowest rescan of the session, and it happens after
|
||||
// `initialize_finish` — the earliest moment a server request is legal.
|
||||
let tree = Tree::new("progressstartup");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
// One `report` because the tree holds one file: the counting reports
|
||||
// this round added ride the same path the begin/end pair does.
|
||||
assert_eq!(
|
||||
session.progress(),
|
||||
vec![
|
||||
("create", "lucisv-index-0".to_string()),
|
||||
("begin", "lucisv-index-0".to_string()),
|
||||
("report", "lucisv-index-0".to_string()),
|
||||
("end", "lucisv-index-0".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_whole_rescan_puts_a_bar_up_and_takes_it_down_again() {
|
||||
// Superseded this round (incremental-index, 2026-08-27):
|
||||
// `a_save_puts_a_bar_up_and_takes_it_down_again` pinned the bar on a
|
||||
// save, and a save of a file the index already holds is now one parse
|
||||
// on the incremental path — see
|
||||
// `a_one_file_save_costs_no_bar_and_no_log_line` below. The bar's own
|
||||
// rule is unchanged and is pinned here on a trigger that really does
|
||||
// rescan: two files changing at once.
|
||||
let tree = Tree::new("progresssave");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
// One create, one begin, one report per file, one end — the rescan's
|
||||
// own token, not the startup one.
|
||||
assert_eq!(
|
||||
session.progress(),
|
||||
vec![
|
||||
("create", "lucisv-index-1".to_string()),
|
||||
("begin", "lucisv-index-1".to_string()),
|
||||
("report", "lucisv-index-1".to_string()),
|
||||
("report", "lucisv-index-1".to_string()),
|
||||
("end", "lucisv-index-1".to_string()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fast_path_is_taken_for_one_held_file_and_for_nothing_else() {
|
||||
// The trigger table, all four rows in one place. The bar is the tell:
|
||||
// a whole rescan puts one up, the incremental path never does.
|
||||
let tree = Tree::new("fastpathtable");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let uri =
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// 1. A save naming one file the index holds — incremental.
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert!(session.progress().is_empty(), "one held file on a save is incremental");
|
||||
|
||||
// 2. One watched file — incremental too, same rule.
|
||||
session.watched(&[tree.path.join("rtl/a.sv")]);
|
||||
assert!(session.progress().is_empty(), "and one watched file is the same case");
|
||||
|
||||
// 3. Two files in one watcher event — the whole rescan.
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
assert!(!session.progress().is_empty(), "two files is a rescan");
|
||||
|
||||
// 4. A settings change that moves which files exist — the whole
|
||||
// rescan, whatever it names.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "exclude": ["rtl/b.sv"], "index": { "scope": "workspace" } } } }),
|
||||
);
|
||||
assert!(!session.progress().is_empty(), "a settings change is a rescan");
|
||||
|
||||
// 5. A save naming a file the index does not hold — the whole rescan,
|
||||
// which is how a new file gets in at all.
|
||||
let fresh = tree.path.join("rtl/c.sv");
|
||||
tree.package("rtl/c.sv", "c");
|
||||
let fresh_uri = crate::uri::path_to_uri(&fresh).expect("uri");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": fresh_uri } }),
|
||||
);
|
||||
assert!(!session.progress().is_empty(), "a file the index does not hold is a rescan");
|
||||
assert_eq!(indexed(&session, "c"), 1, "and the new file is in the index after it");
|
||||
}
|
||||
|
||||
/// QA (incremental-index, 2026-08-27): the fast-path discipline under a
|
||||
/// burst. `process_batch` handles one message at a time
|
||||
/// (`for message in batch`), so two `didSave`s that arrive in the same
|
||||
/// burst are not coalesced into one rescan — each is its own notification,
|
||||
/// each independently names one held file, and each takes the incremental
|
||||
/// path on its own. Not a rebuild, and not a dropped update either.
|
||||
#[test]
|
||||
fn two_saves_of_different_held_files_in_one_batch_are_two_incremental_updates() {
|
||||
let tree = Tree::new("batchtwosaves");
|
||||
tree.write("a.sv", "module a;\nendmodule\n");
|
||||
tree.write("sub.sv", "module sub;\nendmodule\n");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let uri_a = session.open(&tree.path.join("a.sv"), "module a;\nendmodule\n");
|
||||
let uri_sub = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let before = session.server.generation;
|
||||
|
||||
let a_with_sub = "module a;\n sub u1 ();\nendmodule\n";
|
||||
let sub_v2 = "module sub;\n logic marker;\nendmodule\n";
|
||||
let save = |uri: &Uri, text: &str| {
|
||||
Message::Notification(Notification::new(
|
||||
DidSaveTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": text }),
|
||||
))
|
||||
};
|
||||
session.batch(vec![save(&uri_a, a_with_sub), save(&uri_sub, sub_v2)]);
|
||||
|
||||
assert!(session.progress().is_empty(), "neither save alone is a whole rescan");
|
||||
// Each save bumps the generation twice — once in `set_document` for
|
||||
// the buffer's own new text (every text change does that, save or
|
||||
// not), once in `reindex_one` for the fast-path update — so two saves
|
||||
// is four, not two and not one shared bump for the whole batch.
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
before + 4,
|
||||
"two independent fast-path updates, not one bump shared by the batch"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.index().instantiations_of("sub").len(),
|
||||
1,
|
||||
"a.sv's edit reached the index"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.candidates().words("marker").len(),
|
||||
1,
|
||||
"sub.sv's own edit reached the index too, not just a.sv's"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses() {
|
||||
// Everything the fast path keeps: a pulling client's cached
|
||||
// diagnostics are stale from here, and every lens a client is holding
|
||||
// may now read a different count.
|
||||
let tree = lens_tree("fastpathafter");
|
||||
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session
|
||||
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let before = session.server.generation;
|
||||
|
||||
let one_site = "module top;\n sub u_a ();\nendmodule\n";
|
||||
std::fs::write(tree.path.join("top.sv"), one_site).expect("write");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": one_site }),
|
||||
);
|
||||
assert!(session.server.generation > before, "the generation moved");
|
||||
let refreshes =
|
||||
session.sent().iter().filter(|request| request.method == CodeLensRefresh::METHOD).count();
|
||||
assert_eq!(refreshes, 1, "one refresh, as a whole rescan sends");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_file_save_answers_from_the_file_it_saved() {
|
||||
// The point of the whole path: one file's edit really does reach the
|
||||
// index, and the rest of the workspace really is left alone.
|
||||
let tree = lens_tree("fastpathanswer");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let two_sites = "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n";
|
||||
let uri = session.open(&tree.path.join("top.sv"), two_sites);
|
||||
let _ = session.drain();
|
||||
assert_eq!(
|
||||
session.server.workspace.index().instantiations_of("sub").len(),
|
||||
2,
|
||||
"premise: top.sv instantiates `sub` twice"
|
||||
);
|
||||
|
||||
let emptied = "module top;\nendmodule\n";
|
||||
std::fs::write(tree.path.join("top.sv"), emptied).expect("write");
|
||||
session.notify(
|
||||
DidSaveTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri }, "text": emptied }),
|
||||
);
|
||||
assert!(
|
||||
session.server.workspace.index().instantiations_of("sub").is_empty(),
|
||||
"the saved file's edges are gone"
|
||||
);
|
||||
assert_eq!(
|
||||
session.server.workspace.index().units("sub").len(),
|
||||
1,
|
||||
"and sub.sv, which nothing named, is untouched"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_one_file_save_costs_no_bar_and_no_log_line() {
|
||||
// The fast path's whole visible protocol delta: a save that names one
|
||||
// file the index already holds does its work inside a frame, so there
|
||||
// is no bar to put up and no scan to narrate. What it does still do —
|
||||
// the generation bump and the code-lens refresh — is pinned by
|
||||
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
||||
let tree = Tree::new("progressonefile");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let abilities = ClientAbilities { work_done_progress: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert!(session.progress().is_empty(), "one file is not a scan to report");
|
||||
assert!(session.logged().is_empty(), "and not a scan to narrate either");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_says_how_many_files_were_indexed() {
|
||||
// The one number this costs nothing to know: the index's own file
|
||||
// list. Anything richer would mean plumbing a count through
|
||||
// `rebuild_index`.
|
||||
let tree = Tree::new("progresscount");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("2 files indexed".to_string())]);
|
||||
|
||||
let one = Tree::new("progresscountone");
|
||||
one.package("rtl/a.sv", "a");
|
||||
let session = Session::wide_with(vec![one.path.clone()], watching_progress());
|
||||
assert_eq!(session.ended(), vec![Some("1 file indexed".to_string())], "not `1 files`");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_counts_the_files_as_it_goes() {
|
||||
// The whole of feature 2: how many of how many, which file, and a
|
||||
// percentage that was measured rather than guessed.
|
||||
let tree = Tree::new("progressreports");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
assert_eq!(
|
||||
session.reported(),
|
||||
vec![(Some("1/2 a.sv".to_string()), Some(50)), (Some("2/2 b.sv".to_string()), Some(100)),],
|
||||
"counts ascending, the file named, the percentage monotonic and ending at 100"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_reports_thin_out_when_the_workspace_is_huge() {
|
||||
// A report per file is right for hundreds and wrong for tens of
|
||||
// thousands. Past `MAX_REPORTS` files they thin out — but the last
|
||||
// file always reports, so the bar always finishes where the work did.
|
||||
let tree = Tree::new("progressflood");
|
||||
let files = MAX_REPORTS + 100;
|
||||
for i in 0..files {
|
||||
tree.package(&format!("f{i:05}.sv",), &format!("p{i}"));
|
||||
}
|
||||
let session = Session::wide_with(vec![tree.path.clone()], watching_progress());
|
||||
let reports = session.reported();
|
||||
assert!(reports.len() <= MAX_REPORTS, "{} reports for {files} files", reports.len());
|
||||
assert!(reports.len() > MAX_REPORTS / 2, "but not silence: {}", reports.len());
|
||||
|
||||
let percentages: Vec<u32> = reports.iter().filter_map(|(_, p)| *p).collect();
|
||||
assert_eq!(percentages.len(), reports.len(), "every report carries one");
|
||||
assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "monotonic: {percentages:?}");
|
||||
assert_eq!(percentages.last(), Some(&100), "and it ends at 100");
|
||||
let last = reports.last().expect("a report").0.clone().expect("a message");
|
||||
assert!(last.starts_with(&format!("{files}/{files} ")), "the last file reports: {last}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_report_schedule_never_floods_and_never_stops_short() {
|
||||
// The rule itself, across both regimes and their boundary — cheaper to
|
||||
// check exhaustively here than to build 40,000 files.
|
||||
for total in [1, 2, 999, 1000, 1001, 1999, 2000, 12_345, 40_000] {
|
||||
let reporting: Vec<usize> = (0..total).filter(|d| reports(*d, total)).collect();
|
||||
assert!(!reporting.is_empty(), "{total} files must report something");
|
||||
assert!(reporting.len() <= MAX_REPORTS, "{total} files: {} reports", reporting.len());
|
||||
assert_eq!(
|
||||
reporting.last(),
|
||||
Some(&(total - 1)),
|
||||
"{total} files: the last file must report"
|
||||
);
|
||||
assert!(reporting.windows(2).all(|w| w[0] < w[1]), "{total}: strictly ascending");
|
||||
// The percentage a client sees only ever counts up, and lands on
|
||||
// 100 exactly once, at the end.
|
||||
let percentages: Vec<usize> = reporting.iter().map(|d| (d + 1) * 100 / total).collect();
|
||||
assert!(percentages.windows(2).all(|w| w[0] <= w[1]), "{total}: monotonic");
|
||||
assert_eq!(percentages.last(), Some(&100), "{total}: ends at 100");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bar_is_down_before_the_republish() {
|
||||
// Pinned because either order is defensible and a reader would
|
||||
// wonder: the bar names the *scan*, so it ends the moment the scan
|
||||
// returns — the republish that follows is per-open-buffer work the
|
||||
// user already pays on every keystroke.
|
||||
let tree = Tree::new("progressorder");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
let mut session = Session::with(vec![tree.path.clone()], watching_progress());
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// Two files at once, so this is a whole rescan and there is a bar to
|
||||
// order the republish against (incremental-index, 2026-08-27).
|
||||
session.watched(&[tree.path.join("rtl/a.sv"), tree.path.join("rtl/b.sv")]);
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match &message {
|
||||
Message::Notification(n) if n.method == PublishDiagnostics::METHOD => {
|
||||
Some("publish".to_string())
|
||||
}
|
||||
_ => progress_step(message).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(order, vec!["create", "begin", "report", "report", "end", "publish"]);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Pull diagnostics (LSP 3.17): one client is never served both models.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// pull diagnostics
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A buffer with one parse error and one lint finding in it.
|
||||
const BROKEN: &str = "module m;\n\twire ;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_pulling_client_is_never_pushed_diagnostics() {
|
||||
// Never both models for one client: the second set of squiggles would
|
||||
// arrive on a schedule the client did not choose.
|
||||
let tree = Tree::new("pullnopush");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let path = tree.path.join("m.sv");
|
||||
let uri = session.open(&path, BROKEN);
|
||||
assert_eq!(session.publishes(), 0, "`didOpen` pushed nothing");
|
||||
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": BROKEN }],
|
||||
}),
|
||||
);
|
||||
assert_eq!(session.publishes(), 0, "nor did a change");
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert_eq!(session.publishes(), 0, "nor a save's republish");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(session.publishes(), 0, "and the close clears nothing it never drew");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pushing_client_keeps_being_pushed() {
|
||||
let tree = Tree::new("pushstays");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(&tree.path.join("m.sv"), BROKEN);
|
||||
assert_eq!(session.publishes(), 1, "unchanged from before this feature");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pull_is_full_once_and_unchanged_until_something_moves() {
|
||||
let tree = Tree::new("pullunchanged");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
|
||||
|
||||
let first = document_pull(&mut session, &uri, None);
|
||||
assert_eq!(first["kind"], "full");
|
||||
assert!(!first["items"].as_array().expect("items").is_empty(), "{first:#?}");
|
||||
let result_id = first["resultId"].as_str().expect("a result id").to_string();
|
||||
|
||||
let again = document_pull(&mut session, &uri, Some(&result_id));
|
||||
assert_eq!(again["kind"], "unchanged", "nothing moved: {again:#?}");
|
||||
assert_eq!(again["resultId"], serde_json::json!(result_id), "and it stays namable");
|
||||
|
||||
// A buffer change moves it.
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": "module m;\n wire a;\nendmodule\n" }],
|
||||
}),
|
||||
);
|
||||
let after = document_pull(&mut session, &uri, Some(&result_id));
|
||||
assert_eq!(after["kind"], "full", "the buffer changed: {after:#?}");
|
||||
assert!(after["items"].as_array().expect("items").is_empty(), "and it is clean now");
|
||||
assert_ne!(after["resultId"], serde_json::json!(result_id), "a new stamp");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_rebuild_moves_the_result_id_too() {
|
||||
// `inter_file_dependencies: true` is a promise: a save rebuilds the
|
||||
// index, and what the index says can change what a *different* buffer
|
||||
// reports. A stale "unchanged" there would be a wrong squiggle.
|
||||
let tree = Tree::new("pullreindex");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), BROKEN);
|
||||
let stamp = document_pull(&mut session, &uri, None)["resultId"]
|
||||
.as_str()
|
||||
.expect("a result id")
|
||||
.to_string();
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
let after = document_pull(&mut session, &uri, Some(&stamp));
|
||||
assert_eq!(after["kind"], "full", "the index moved: {after:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pull_for_a_buffer_that_is_not_open_is_empty_rather_than_an_error() {
|
||||
let tree = Tree::new("pullclosed");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let report = document_pull(&mut session, &uri, None);
|
||||
assert_eq!(report["kind"], "full");
|
||||
assert!(report["items"].as_array().expect("items").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_workspace_pull_reports_every_open_buffer_and_honours_its_stamps() {
|
||||
let tree = Tree::new("workspacepull");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let first = session.open(&tree.path.join("a.sv"), BROKEN);
|
||||
let second = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
|
||||
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items").clone();
|
||||
assert_eq!(items.len(), 2, "{report:#?}");
|
||||
assert!(items.iter().all(|item| item["kind"] == "full"), "{report:#?}");
|
||||
let uris: Vec<&str> = items.iter().map(|item| item["uri"].as_str().unwrap_or("")).collect();
|
||||
assert!(uris.contains(&first.as_str()) && uris.contains(&second.as_str()), "{uris:?}");
|
||||
let mut sorted = uris.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(uris, sorted, "URI order, so two pulls of one state read alike");
|
||||
let stamp = items[0]["resultId"].as_str().expect("a result id").to_string();
|
||||
|
||||
// Re-asked with what the client already holds, both come back unchanged.
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [
|
||||
{ "uri": first, "value": stamp },
|
||||
{ "uri": second, "value": stamp },
|
||||
],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 2);
|
||||
assert!(items.iter().all(|item| item["kind"] == "unchanged"), "{items:#?}");
|
||||
|
||||
// A stamp from another generation is not the one we hold.
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [{ "uri": first, "value": "0" }],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert!(items.iter().all(|item| item["kind"] == "full"), "{items:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_workspace_answers_a_well_formed_empty_report() {
|
||||
// QA attack: no open buffers at all — does `workspace/diagnostic`
|
||||
// still answer a well-formed (if empty) report, rather than an error
|
||||
// or a missing field?
|
||||
let tree = Tree::new("workspaceemptypull");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
);
|
||||
assert_eq!(report["items"], serde_json::json!([]), "{report:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_previous_result_id_for_a_uri_that_is_since_closed_is_harmless() {
|
||||
// QA attack: the client's `previousResultIds` can name a document it
|
||||
// has since closed (it does not have to prune its own cache eagerly).
|
||||
// That URI is no longer among the open buffers `workspace_report`
|
||||
// walks, so it must simply be absent from the answer — not an error,
|
||||
// not a phantom entry.
|
||||
let tree = Tree::new("workspaceclosedstamp");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let first = session.open(&tree.path.join("a.sv"), BROKEN);
|
||||
let closed = session.open(&tree.path.join("b.sv"), "module b;\nendmodule\n");
|
||||
let stamp = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }),
|
||||
)["items"][0]["resultId"]
|
||||
.as_str()
|
||||
.expect("a result id")
|
||||
.to_string();
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": closed } }),
|
||||
);
|
||||
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [
|
||||
{ "uri": first, "value": stamp },
|
||||
{ "uri": closed, "value": stamp },
|
||||
],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 1, "the closed uri is gone, not phantom-reported: {items:#?}");
|
||||
assert_eq!(items[0]["uri"], first.as_str(), "{items:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_previous_result_id_for_a_uri_never_seen_is_ignored() {
|
||||
// QA attack: a `previousResultIds` entry naming a document this
|
||||
// server never opened (a client warm-starting from a stale cache, or
|
||||
// simply a typo'd uri) must not confuse the match-up for the uris
|
||||
// that *are* open.
|
||||
let tree = Tree::new("workspaceneverseenstamp");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let opened = session.open(&tree.path.join("a.sv"), BROKEN);
|
||||
let never_seen = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
|
||||
let report = session.result(
|
||||
WorkspaceDiagnosticRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"identifier": diagnostics::SOURCE,
|
||||
"previousResultIds": [{ "uri": never_seen, "value": "0" }],
|
||||
}),
|
||||
);
|
||||
let items = report["items"].as_array().expect("items");
|
||||
assert_eq!(items.len(), 1, "{items:#?}");
|
||||
assert_eq!(items[0]["uri"], opened.as_str(), "{items:#?}");
|
||||
assert_eq!(items[0]["kind"], "full");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_models_say_exactly_the_same_thing_about_a_buffer() {
|
||||
// One computation, two deliveries. A second conversion path would be
|
||||
// a second set of off-by-one bugs.
|
||||
let tree = Tree::new("samediagnostics");
|
||||
let mut pushed = Session::new(vec![tree.path.clone()], false);
|
||||
pushed.open(&tree.path.join("m.sv"), BROKEN);
|
||||
let published = pushed.published();
|
||||
assert_eq!(published.len(), 1);
|
||||
|
||||
let mut pulled = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = pulled.open(&tree.path.join("m.sv"), BROKEN);
|
||||
let report = document_pull(&mut pulled, &uri, None);
|
||||
|
||||
assert_eq!(
|
||||
report["items"],
|
||||
serde_json::to_value(&published[0].diagnostics).expect("diagnostics"),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,431 @@
|
||||
//! Small document requests through the real dispatch: `selectionRange`, `linkedEditingRange`, `codeLens` and its command, the hierarchy view.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/selectionRange`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_selection_range_request_answers_one_chain_per_position() {
|
||||
let tree = Tree::new("selection");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
let result = session.result(
|
||||
SelectionRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"positions": [{ "line": 1, "character": 2 }, { "line": 0, "character": 0 }],
|
||||
}),
|
||||
);
|
||||
let chains = result.as_array().expect("one chain per position");
|
||||
assert_eq!(chains.len(), 2, "{result:#?}");
|
||||
assert!(chains[0]["parent"].is_object(), "the innermost step has a parent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_selection_range_request_for_an_unopened_buffer_answers_null() {
|
||||
let tree = Tree::new("selectionclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let result = session.result(
|
||||
SelectionRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"positions": [{ "line": 0, "character": 0 }],
|
||||
}),
|
||||
);
|
||||
assert_eq!(result, Value::Null);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/linkedEditingRange`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_linked_editing_request_answers_both_halves_of_a_closing_label() {
|
||||
let tree = Tree::new("linked");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule : m\n");
|
||||
// The cursor on the header name.
|
||||
let result = session.result(
|
||||
LinkedEditingRange::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 7 },
|
||||
}),
|
||||
);
|
||||
let ranges = result["ranges"].as_array().expect("a range list").clone();
|
||||
assert_eq!(ranges.len(), 2, "{result:#?}");
|
||||
assert_eq!(ranges[0]["start"], serde_json::json!({ "line": 0, "character": 7 }));
|
||||
assert_eq!(ranges[1]["start"], serde_json::json!({ "line": 1, "character": 12 }));
|
||||
assert!(result["wordPattern"].is_string(), "the SV word pattern is sent: {result:#?}");
|
||||
|
||||
// A position on no name at all declines, rather than answering an
|
||||
// empty list.
|
||||
let nothing = session.result(
|
||||
LinkedEditingRange::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 0 },
|
||||
}),
|
||||
);
|
||||
assert_eq!(nothing, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_linked_editing_request_for_an_unopened_buffer_answers_null() {
|
||||
let tree = Tree::new("linkedclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let result = session.result(
|
||||
LinkedEditingRange::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"position": { "line": 0, "character": 0 },
|
||||
}),
|
||||
);
|
||||
assert_eq!(result, Value::Null);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `textDocument/codeLens`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_code_lens_request_counts_the_workspaces_instantiations() {
|
||||
let tree = lens_tree("lens");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let result = session
|
||||
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
let lenses = result.as_array().expect("a lens list").clone();
|
||||
assert_eq!(lenses.len(), 1, "{result:#?}");
|
||||
assert_eq!(lenses[0]["command"]["title"], "2 instantiations");
|
||||
assert_eq!(lenses[0]["command"]["command"], lens::SHOW_INSTANTIATIONS);
|
||||
assert_eq!(lenses[0]["command"]["arguments"], serde_json::json!(["sub"]));
|
||||
assert_eq!(lenses[0]["range"]["start"], serde_json::json!({ "line": 0, "character": 7 }));
|
||||
assert!(lenses[0]["data"].is_null(), "nothing is left for a resolve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_code_lens_request_for_an_unopened_buffer_answers_null() {
|
||||
let tree = lens_tree("lensclosed");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
let result = session
|
||||
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert_eq!(result, Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_show_instantiations_command_answers_every_site() {
|
||||
let tree = lens_tree("lenscommand");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let result = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
|
||||
);
|
||||
let locations = result.as_array().expect("a location list").clone();
|
||||
assert_eq!(locations.len(), 2, "{result:#?}");
|
||||
assert!(locations[0]["uri"].as_str().expect("uri").ends_with("top.sv"));
|
||||
assert_eq!(locations[0]["range"]["start"], serde_json::json!({ "line": 1, "character": 2 }));
|
||||
assert_eq!(locations[1]["range"]["start"], serde_json::json!({ "line": 2, "character": 2 }));
|
||||
// Nothing was pushed: this client cannot be shown a document.
|
||||
assert!(session.requests().is_empty(), "no showDocument for a client without it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_show_instantiations_command_pushes_a_show_document_when_it_can() {
|
||||
let tree = lens_tree("lensshow");
|
||||
let abilities = ClientAbilities { show_document: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let result = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
|
||||
);
|
||||
assert_eq!(result.as_array().expect("locations").len(), 2, "and still the whole list");
|
||||
let asked = session.requests();
|
||||
assert_eq!(asked.len(), 1, "{asked:#?}");
|
||||
assert_eq!(asked[0].0, ShowDocument::METHOD);
|
||||
assert!(asked[0].1["uri"].as_str().expect("uri").ends_with("top.sv"));
|
||||
assert_eq!(asked[0].1["selection"]["start"], serde_json::json!({ "line": 1, "character": 2 }));
|
||||
assert_eq!(asked[0].1["takeFocus"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_module_with_no_instantiations_pushes_nothing_and_shows_nothing() {
|
||||
let tree = Tree::new("lensempty");
|
||||
tree.write("lonely.sv", "module lonely;\nendmodule\n");
|
||||
let abilities = ClientAbilities { show_document: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("lonely.sv"), "module lonely;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
let result = session
|
||||
.result(CodeLensRequest::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
assert_eq!(result[0]["command"]["title"], "no instantiations");
|
||||
assert_eq!(result[0]["command"]["command"], "", "display-only");
|
||||
let empty = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["lonely"] }),
|
||||
);
|
||||
assert_eq!(empty, serde_json::json!([]));
|
||||
assert!(session.requests().is_empty(), "nothing to show, nothing pushed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_show_instantiations_command_declines_arguments_it_cannot_read() {
|
||||
let tree = lens_tree("lensbadargs");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let error = session
|
||||
.request(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS }),
|
||||
)
|
||||
.response_result
|
||||
.expect_err("declined");
|
||||
assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32);
|
||||
assert!(error.message.contains("module name"), "{error:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_asks_a_capable_client_to_refresh_its_code_lenses() {
|
||||
let tree = lens_tree("lensrefresh");
|
||||
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
assert!(session.requests().is_empty(), "nothing to refresh at startup: no buffer is open");
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
// Every rescan trigger, one refresh each.
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
session.watched(&[tree.path.join("top.sv")]);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "exclude": ["nothing"] } } }),
|
||||
);
|
||||
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
|
||||
assert_eq!(
|
||||
methods,
|
||||
vec![CodeLensRefresh::METHOD; 3],
|
||||
"one per rescan, on the save, watched-file and config paths"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_refresh_code_lenses_is_never_asked_to() {
|
||||
let tree = lens_tree("lensnorefresh");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
session.watched(&[tree.path.join("top.sv")]);
|
||||
assert!(session.requests().is_empty(), "silence, on every rescan path");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hierarchy_view_gets_a_snapshot_and_one_notification_per_completed_index() {
|
||||
let tree = Tree::new("hierarchyviewrefresh");
|
||||
tree.write("sub.sv", "module sub; endmodule\n");
|
||||
tree.write("top.sv", "module top; sub u (); endmodule\n");
|
||||
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
|
||||
let started: Vec<Value> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == design_hierarchy::CHANGED_METHOD =>
|
||||
{
|
||||
Some(notification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(started, [serde_json::json!({ "revision": 1 })]);
|
||||
|
||||
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
|
||||
assert_eq!(snapshot["revision"], 1);
|
||||
assert_eq!(snapshot["complete"], true);
|
||||
assert_eq!(snapshot["modules"].as_array().expect("modules").len(), 2);
|
||||
|
||||
tree.write("top.sv", "module top; sub renamed (); endmodule\n");
|
||||
session.watched(&[tree.path.join("top.sv")]);
|
||||
let changed: Vec<Value> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Notification(notification)
|
||||
if notification.method == design_hierarchy::CHANGED_METHOD =>
|
||||
{
|
||||
Some(notification.params)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(changed, [serde_json::json!({ "revision": 2 })]);
|
||||
let snapshot = session.result(design_hierarchy::METHOD, serde_json::json!({}));
|
||||
assert_eq!(snapshot["revision"], 2);
|
||||
let top = snapshot["modules"]
|
||||
.as_array()
|
||||
.expect("modules")
|
||||
.iter()
|
||||
.find(|module| module["moduleName"] == "top")
|
||||
.expect("top");
|
||||
assert_eq!(top["instances"][0]["instanceName"], "renamed");
|
||||
}
|
||||
|
||||
/// `complete` says "this is the whole workspace", and the window it has to
|
||||
/// be honest about is the one between a finished scan and a rescan already
|
||||
/// asked for — where `scanning` alone is false over an index that is about
|
||||
/// to be rebuilt. Two answers, both pinned here: the flag itself is false,
|
||||
/// and the request does not reach it at all, because `must_wait` sets a
|
||||
/// request owed a rescan aside instead of answering it.
|
||||
#[test]
|
||||
fn a_snapshot_is_never_answered_complete_while_a_rescan_is_owed() {
|
||||
let tree = Tree::new("hierarchycomplete");
|
||||
tree.write("top.sv", "module top; endmodule\n");
|
||||
let abilities = ClientAbilities { hierarchy_view: true, ..Default::default() };
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], abilities);
|
||||
session.drain();
|
||||
assert!(session.server.index_is_complete(), "settled: nothing is owed");
|
||||
assert_eq!(session.result(design_hierarchy::METHOD, serde_json::json!({}))["complete"], true);
|
||||
|
||||
session.server.rescan_wanted = true;
|
||||
assert!(!session.server.scanning, "premise: no scan is running this instant");
|
||||
assert!(!session.server.index_is_complete(), "but one is owed, so nothing is complete");
|
||||
|
||||
let request = Message::Request(Request::new(
|
||||
RequestId::from(99),
|
||||
design_hierarchy::METHOD.to_string(),
|
||||
serde_json::json!({}),
|
||||
));
|
||||
assert!(!session.batch(vec![request]));
|
||||
assert_eq!(session.server.held.len(), 1, "the snapshot waits for the rescan");
|
||||
assert!(session.answers().is_empty(), "nothing was answered off the stale index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_without_the_hierarchy_view_gets_no_custom_notifications() {
|
||||
let tree = Tree::new("nohierarchyviewrefresh");
|
||||
tree.write("top.sv", "module top; endmodule\n");
|
||||
let session = Session::wide(vec![tree.path.clone()], false);
|
||||
assert!(session.drain().into_iter().all(|message| {
|
||||
!matches!(message, Message::Notification(notification)
|
||||
if notification.method == design_hierarchy::CHANGED_METHOD)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refresh_rides_after_the_indexing_bar_comes_down() {
|
||||
// The documented order: the bar names the scan, and the refresh is
|
||||
// work done on the scan's result — as the republishes are.
|
||||
let tree = lens_tree("lensorder");
|
||||
let abilities =
|
||||
ClientAbilities { code_lens_refresh: true, work_done_progress: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
// Two files at once, so this is a whole rescan and there is a bar for
|
||||
// the refresh to ride after (incremental-index, 2026-08-27); the
|
||||
// one-file path's own refresh is pinned in
|
||||
// `a_one_file_save_still_bumps_the_generation_and_refreshes_the_lenses`.
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
let order: Vec<String> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(|message| match message {
|
||||
Message::Request(request) if request.method == CodeLensRefresh::METHOD => {
|
||||
Some("refresh".to_string())
|
||||
}
|
||||
other => progress_step(other).map(|(step, _)| step.to_string()),
|
||||
})
|
||||
.collect();
|
||||
// Two files in `lens_tree`, so two reports between the begin and the
|
||||
// end; the refresh is still after all of them.
|
||||
assert_eq!(order, ["create", "begin", "report", "report", "end", "refresh"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_rescan_with_several_open_buffers_still_sends_exactly_one_refresh() {
|
||||
// `refresh_code_lenses()` is called once in `reindex()`, before the
|
||||
// loop that republishes every open buffer's diagnostics — not once
|
||||
// per buffer that loop republishes. Two open buffers make that
|
||||
// distinction observable: a refresh-per-publish regression would
|
||||
// send two.
|
||||
let tree = lens_tree("qa_lensrefresh_multi");
|
||||
let abilities = ClientAbilities { code_lens_refresh: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let uri = session.open(&tree.path.join("sub.sv"), "module sub;\nendmodule\n");
|
||||
session
|
||||
.open(&tree.path.join("top.sv"), "module top;\n sub u_a ();\n sub u_b ();\nendmodule\n");
|
||||
let _ = session.drain();
|
||||
|
||||
session
|
||||
.notify(DidSaveTextDocument::METHOD, serde_json::json!({ "textDocument": { "uri": uri } }));
|
||||
let methods: Vec<String> = session.requests().into_iter().map(|(method, _)| method).collect();
|
||||
assert_eq!(methods, vec![CodeLensRefresh::METHOD], "one refresh, not one per open buffer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_showdocument_push_and_an_applyedit_push_stay_independent_when_both_are_outstanding() {
|
||||
// Both `deliver` (applyEdit) and `show_instantiations` (showDocument)
|
||||
// push a server-initiated request and rely on the same mechanism —
|
||||
// `response()` only reacts to an id it finds in `applying`, and only
|
||||
// `deliver` ever inserts one. Two requests outstanding at once, one of
|
||||
// each kind, must not cross-contaminate: a showDocument answer must
|
||||
// not be mistaken for the applyEdit one (or vice versa), whichever
|
||||
// order the client answers in.
|
||||
let tree = Tree::new("qa_interleave");
|
||||
tree.write("sub.sv", SUB);
|
||||
tree.write("top.sv", TOP);
|
||||
let abilities = ClientAbilities { apply_edit: true, show_document: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let top_uri = session.open(&tree.path.join("top.sv"), TOP);
|
||||
session.open(&tree.path.join("sub.sv"), SUB);
|
||||
let _ = session.drain();
|
||||
|
||||
// First outstanding request: an applyEdit push from a port command.
|
||||
let propagate = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({
|
||||
"command": ports::PROPAGATE_PORTS,
|
||||
"arguments": [top_uri, { "line": 2, "character": 6 }],
|
||||
}),
|
||||
);
|
||||
assert_eq!(propagate, Value::Null);
|
||||
|
||||
// Second outstanding request: a showDocument push from the lens's
|
||||
// own command, over the same `sub` instantiation.
|
||||
let sites = session.result(
|
||||
ExecuteCommand::METHOD,
|
||||
serde_json::json!({ "command": lens::SHOW_INSTANTIATIONS, "arguments": ["sub"] }),
|
||||
);
|
||||
assert_eq!(sites.as_array().expect("locations").len(), 1);
|
||||
|
||||
let sent = session.sent();
|
||||
assert_eq!(sent.len(), 2, "{sent:#?}");
|
||||
assert_eq!(sent[0].method, ApplyWorkspaceEdit::METHOD);
|
||||
assert_eq!(sent[1].method, ShowDocument::METHOD);
|
||||
let apply_id = sent[0].id.clone();
|
||||
let show_id = sent[1].id.clone();
|
||||
|
||||
// Answer the showDocument push FIRST, out of send order — it carries
|
||||
// no `applied` field at all, so if `response()` ever matched it to
|
||||
// the applyEdit command by anything other than its own id, this would
|
||||
// either panic or wrongly report a failed edit.
|
||||
session.answer(show_id, serde_json::json!({ "success": true }));
|
||||
assert!(session.shown().is_empty(), "the showDocument answer must not be interpreted");
|
||||
|
||||
// Now answer the applyEdit push — a real success — and confirm it is
|
||||
// still routed correctly to its own command.
|
||||
session.answer(apply_id, serde_json::json!({ "applied": true }));
|
||||
assert!(session.shown().is_empty(), "a successful apply reports nothing");
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
//! A scan that answers messages while it runs (`docs/features/scan-interleave/README.md`).
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// a scan that answers messages while it runs
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A tree of `files` one-package files, plus one that names the last of
|
||||
/// them — enough files that a scan over it interleaves.
|
||||
fn workspace_of(tag: &str, files: usize) -> Tree {
|
||||
let tree = Tree::new(tag);
|
||||
for n in 0..files {
|
||||
tree.package(&format!("p{n:03}.sv"), &format!("p{n:03}"));
|
||||
}
|
||||
tree
|
||||
}
|
||||
|
||||
/// A `workspace/symbol` request over the wire, by id.
|
||||
fn symbol_request(id: i32, query: &str) -> Message {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(id),
|
||||
WorkspaceSymbolRequest::METHOD.to_string(),
|
||||
serde_json::json!({ "query": query }),
|
||||
))
|
||||
}
|
||||
|
||||
/// Where the indexing bar's `end` sits among everything the server said,
|
||||
/// and where the response to `id` sits. `None` for either if it never
|
||||
/// came.
|
||||
fn positions(messages: &[Message], id: i32) -> (Option<usize>, Option<usize>) {
|
||||
let ended = messages.iter().position(|message| {
|
||||
matches!(message, Message::Notification(n) if n.method == Progress::METHOD
|
||||
&& n.params["value"]["kind"] == "end")
|
||||
});
|
||||
let answered = messages
|
||||
.iter()
|
||||
.position(|message| matches!(message, Message::Response(r) if r.id == RequestId::from(id)));
|
||||
(ended, answered)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_the_client_had_already_sent_is_answered_during_the_startup_scan() {
|
||||
// The round's point, over the real dispatch: a request sitting on the
|
||||
// transport when the server is built used to wait for the whole
|
||||
// startup scan, because `Server::new` ran that scan before `run()`
|
||||
// took its first message. It is now answered *inside* the scan — the
|
||||
// response goes out before the bar comes down, which is the only
|
||||
// ordering a test can check without a stopwatch.
|
||||
let tree = workspace_of("interleaveanswer", INTERLEAVE_ABOVE + 6);
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
let said = session.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
let answered = answered.expect("the request is answered at all");
|
||||
let ended = ended.expect("the bar comes down");
|
||||
assert!(
|
||||
answered < ended,
|
||||
"the answer must go out before the scan ends, not after it: {said:#?}"
|
||||
);
|
||||
// And the index really did finish, so nothing was traded for the
|
||||
// latency but the completeness of that one answer.
|
||||
assert_eq!(session.server.workspace.index().files().len(), INTERLEAVE_ABOVE + 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scan_short_enough_to_wait_for_answers_nothing_in_the_middle_of_itself() {
|
||||
// The other side of `INTERLEAVE_ABOVE`. A handful of files is over in
|
||||
// milliseconds, so a request that arrived with them is answered from
|
||||
// the *finished* index — the complete answer, which is worth more than
|
||||
// the few milliseconds an interleaved one would have saved.
|
||||
let tree = workspace_of("interleaveshort", 4);
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
// Nothing is answered during construction at all: the burst is still
|
||||
// on the queue for `run` to take.
|
||||
let said = session.drain();
|
||||
assert_eq!(positions(&said, 7).1, None, "{said:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interleave_above_is_a_hard_boundary_at_the_file_count_not_before_or_after() {
|
||||
// QA attack (`docs/features/scan-interleave/README.md`, settling
|
||||
// attacks): the exact edge of `INTERLEAVE_ABOVE`. `scan_once` compares
|
||||
// with `>`, not `>=`, so a scan of *exactly* the threshold must still
|
||||
// run one-shot and one file more must interleave. Both sides in one
|
||||
// test so a future off-by-one in that comparison shows up as a single
|
||||
// failing assertion rather than two tests that each only prove half.
|
||||
let at_threshold = workspace_of("interleaveboundaryat", INTERLEAVE_ABOVE);
|
||||
let one_shot = Session::started_behind(
|
||||
vec![at_threshold.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
let said = one_shot.drain();
|
||||
assert_eq!(
|
||||
positions(&said, 7).1,
|
||||
None,
|
||||
"exactly INTERLEAVE_ABOVE files must run one-shot: {said:#?}"
|
||||
);
|
||||
|
||||
let above_threshold = workspace_of("interleaveboundaryabove", INTERLEAVE_ABOVE + 1);
|
||||
let interleaved = Session::started_behind(
|
||||
vec![above_threshold.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![symbol_request(7, "p0")],
|
||||
);
|
||||
let said = interleaved.drain();
|
||||
let (ended, answered) = positions(&said, 7);
|
||||
assert!(
|
||||
answered.expect("answered mid-scan") < ended.expect("the bar comes down"),
|
||||
"one file over INTERLEAVE_ABOVE must interleave: {said:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_queued_behind_a_rescan_waits_for_that_rescan() {
|
||||
// The order contract, which interleaving must not cost: a message
|
||||
// that asks for a rescan is *applied* — rescan run and all — before
|
||||
// anything queued behind it is answered. Here the cap is pushed down
|
||||
// to nothing, which empties the index, and the request behind it must
|
||||
// see the empty one rather than the half-built one it was sent into.
|
||||
let tree = workspace_of("interleaveorder", INTERLEAVE_ABOVE + 6);
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeConfiguration::METHOD.to_string(),
|
||||
capping(1),
|
||||
)),
|
||||
symbol_request(7, "p0"),
|
||||
],
|
||||
);
|
||||
// The configuration was applied mid-scan and the rescan it asked for
|
||||
// ran; the request behind it is still waiting, because it is owed that
|
||||
// rescan's result.
|
||||
assert!(session.server.held.len() == 1, "the request waits: {:?}", session.server.held);
|
||||
assert_eq!(session.server.workspace.index().files().len(), 0, "the cap emptied the index");
|
||||
let said = session.drain();
|
||||
assert_eq!(positions(&said, 7).1, None, "not answered yet: {said:#?}");
|
||||
|
||||
// `run` answers it before it takes anything newer, and by then the
|
||||
// rescan the client asked for has happened.
|
||||
let held = std::mem::take(&mut session.server.held);
|
||||
assert!(!session.batch(held), "the held burst is handled");
|
||||
let answered = session.answers();
|
||||
assert_eq!(answered.len(), 1, "{answered:#?}");
|
||||
assert_eq!(
|
||||
answered[0].response_result.as_ref().ok().and_then(|v| v.as_array()).map(Vec::len),
|
||||
Some(0),
|
||||
"answered from the index the push asked for, not the one it was sent into"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_held_request_keeps_its_place_and_takes_its_cancel_with_it() {
|
||||
// Two corners of holding, in one experiment. The burst carries a
|
||||
// cancel for the request it also carries, and the scan the burst's
|
||||
// settings push asks for holds a *newer* request of its own along the
|
||||
// way. What comes out has to be: the burst's own request first (it
|
||||
// arrived first), the newer one behind it, and the cancel still in
|
||||
// front of what it cancels — a cancel dropped by the wait would turn
|
||||
// into a computed answer the client has stopped listening for.
|
||||
let tree = workspace_of("interleaveheldorder", INTERLEAVE_ABOVE + 6);
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeConfiguration::METHOD.to_string(),
|
||||
capping(1),
|
||||
)),
|
||||
Message::Notification(Notification::new(
|
||||
Cancel::METHOD.to_string(),
|
||||
serde_json::json!({ "id": 7 }),
|
||||
)),
|
||||
symbol_request(7, "p0"),
|
||||
symbol_request(8, "p0"),
|
||||
],
|
||||
);
|
||||
let held: Vec<String> = session
|
||||
.server
|
||||
.held
|
||||
.iter()
|
||||
.map(|message| match message {
|
||||
Message::Request(request) => format!("req {}", request.id),
|
||||
Message::Notification(n) => format!("notif {}", n.method),
|
||||
Message::Response(r) => format!("resp {}", r.id),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(held, ["notif $/cancelRequest", "req 7", "req 8"], "{held:?}");
|
||||
|
||||
let batch = std::mem::take(&mut session.server.held);
|
||||
assert!(!session.batch(batch), "the held burst is handled");
|
||||
let answered = session.answers();
|
||||
assert_eq!(answered.len(), 2, "{answered:#?}");
|
||||
assert_eq!(answered[0].id, RequestId::from(7));
|
||||
assert!(
|
||||
answered[0]
|
||||
.response_result
|
||||
.as_ref()
|
||||
.is_err_and(|e| e.code == lsp_server::ErrorCode::RequestCanceled as i32),
|
||||
"the cancel survived the wait: {:#?}",
|
||||
answered[0]
|
||||
);
|
||||
assert_eq!(answered[1].id, RequestId::from(8), "and the newer one is behind it");
|
||||
assert!(answered[1].response_result.is_ok(), "which is answered normally: {:#?}", answered[1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rescan_asked_for_mid_scan_is_coalesced_into_exactly_one_more_scan() {
|
||||
// Three settings pushes land inside one startup scan, each of which
|
||||
// would rebuild the index on its own. They cost one more scan between
|
||||
// them, not three, and no scan runs inside another: two bars, two
|
||||
// tokens, in order.
|
||||
let tree = workspace_of("interleavecoalesce", INTERLEAVE_ABOVE + 6);
|
||||
let cap = |bytes: u64| {
|
||||
Message::Notification(Notification::new(
|
||||
DidChangeConfiguration::METHOD.to_string(),
|
||||
capping(bytes),
|
||||
))
|
||||
};
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![cap(1), cap(2), cap(3)],
|
||||
);
|
||||
assert!(!session.server.scanning, "no scan is left running");
|
||||
assert!(!session.server.rescan_wanted, "and none is left owed");
|
||||
let bars: Vec<(&str, String)> = session
|
||||
.drain()
|
||||
.into_iter()
|
||||
.filter_map(progress_step)
|
||||
.filter(|(step, _)| *step != "report")
|
||||
.collect();
|
||||
assert_eq!(
|
||||
bars,
|
||||
vec![
|
||||
("create", "lucisv-index-0".to_string()),
|
||||
("begin", "lucisv-index-0".to_string()),
|
||||
("end", "lucisv-index-0".to_string()),
|
||||
("create", "lucisv-index-1".to_string()),
|
||||
("begin", "lucisv-index-1".to_string()),
|
||||
("end", "lucisv-index-1".to_string()),
|
||||
],
|
||||
"one startup scan and exactly one coalesced rescan behind it"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shutdown_answered_mid_scan_stops_the_scan_where_it_stands() {
|
||||
// A scan is interruptible now that it takes messages, and `shutdown`
|
||||
// is what interrupts it: the bar never comes down, nothing is
|
||||
// published after it, and `run` returns without taking another
|
||||
// message. What the scan had already parsed is in the persistent
|
||||
// store — it is written through per file — so the next session
|
||||
// resumes from it exactly as it does after any other half-done scan.
|
||||
let tree = workspace_of("interleaveshutdown", INTERLEAVE_ABOVE + 6);
|
||||
let shutdown = || {
|
||||
Message::Request(Request::new(
|
||||
RequestId::from(9),
|
||||
Shutdown::METHOD.to_string(),
|
||||
Value::Null,
|
||||
))
|
||||
};
|
||||
let mut session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
watching_progress(),
|
||||
wide_ish(),
|
||||
// On the connection as well as on the queue, and in this order:
|
||||
// the queued copy is what the scan's first drain is *certain* to
|
||||
// see, and the copy the forwarder carries is what stops it reading
|
||||
// — so the `exit` behind it is still there for `handle_shutdown`,
|
||||
// which reads the connection itself. Whichever of the two the
|
||||
// handshake ends up consuming, the scan stops here.
|
||||
vec![shutdown(), Message::Notification(Notification::new("exit".into(), Value::Null))],
|
||||
vec![shutdown()],
|
||||
);
|
||||
assert!(session.server.stopped, "the scan saw the shutdown");
|
||||
assert_eq!(session.ended(), Vec::<Option<String>>::new(), "the bar never came down");
|
||||
assert!(
|
||||
session.server.workspace.index().files().len() < INTERLEAVE_ABOVE + 6,
|
||||
"the scan stopped where it stood rather than running to the end"
|
||||
);
|
||||
session.server.run().expect("run returns at once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_opened_during_the_startup_scan_is_published_and_lenses_refreshed_once() {
|
||||
// QA attack (`docs/features/scan-interleave/README.md`,
|
||||
// progress/log-continuity): before this round no buffer could be
|
||||
// *open* while `Server::new` was still running, so `Server::started`
|
||||
// never had to pay the one-time republish-and-refresh `reindex` has
|
||||
// always owed at the end of a rescan. A `didOpen` answered mid-scan
|
||||
// now creates exactly that buffer, and the work log says
|
||||
// `Server::started` pays the debt at the end of construction.
|
||||
//
|
||||
// Two publishes for the opened file are both correct, not a
|
||||
// duplicate: `didOpen`'s own handler has always published against
|
||||
// whatever index exists the moment a file opens (unrelated to this
|
||||
// round), which here is the half-built one — so the debt payment
|
||||
// after the bar comes down is what gives the client a diagnostics set
|
||||
// computed against the *finished* index, and it must come after the
|
||||
// `end` event, not folded into the mid-scan one.
|
||||
let tree = workspace_of("interleaveopenedpublish", INTERLEAVE_ABOVE + 6);
|
||||
let target = tree.path.join("p000.sv");
|
||||
let opened = Message::Notification(Notification::new(
|
||||
DidOpenTextDocument::METHOD.to_string(),
|
||||
serde_json::json!({
|
||||
"textDocument": {
|
||||
"uri": path_to_uri(&target).expect("uri"),
|
||||
"languageId": "systemverilog",
|
||||
"version": 1,
|
||||
"text": "package p000;\nendpackage\n",
|
||||
}
|
||||
}),
|
||||
));
|
||||
let abilities =
|
||||
ClientAbilities { work_done_progress: true, code_lens_refresh: true, ..Default::default() };
|
||||
let session = Session::started_behind(
|
||||
vec![tree.path.clone()],
|
||||
abilities,
|
||||
wide_ish(),
|
||||
Vec::new(),
|
||||
vec![opened],
|
||||
);
|
||||
let said = session.drain();
|
||||
let target_uri = path_to_uri(&target).expect("uri");
|
||||
let ended = said
|
||||
.iter()
|
||||
.position(|m| {
|
||||
matches!(m, Message::Notification(n) if n.method == Progress::METHOD
|
||||
&& n.params["value"]["kind"] == "end")
|
||||
})
|
||||
.expect("the bar comes down");
|
||||
let publish_positions: Vec<usize> = said
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, m)| match m {
|
||||
Message::Notification(n)
|
||||
if n.method == PublishDiagnostics::METHOD
|
||||
&& serde_json::from_value::<PublishDiagnosticsParams>(n.params.clone())
|
||||
.is_ok_and(|p| p.uri == target_uri) =>
|
||||
{
|
||||
Some(i)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
publish_positions.len(),
|
||||
2,
|
||||
"one publish from didOpen's own handler, one from the debt Server::started pays: \
|
||||
{said:#?}"
|
||||
);
|
||||
assert!(
|
||||
publish_positions[0] < ended,
|
||||
"the first publish is didOpen's own, against the half-built index: {said:#?}"
|
||||
);
|
||||
assert!(
|
||||
publish_positions[1] > ended,
|
||||
"the second is the debt payment, against the finished index: {said:#?}"
|
||||
);
|
||||
let refreshes = said
|
||||
.iter()
|
||||
.filter(|m| matches!(m, Message::Request(r) if r.method == CodeLensRefresh::METHOD))
|
||||
.count();
|
||||
assert_eq!(refreshes, 1, "exactly one lens refresh, not one per drain: {said:#?}");
|
||||
}
|
||||
@@ -0,0 +1,410 @@
|
||||
//! Pulled settings (2026-08-27): `workspace/configuration` beside the push.
|
||||
|
||||
use super::*;
|
||||
use crate::settings;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// pulled settings (2026-08-27)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A client that answers `workspace/configuration`.
|
||||
fn pulling_settings() -> ClientAbilities {
|
||||
ClientAbilities { configuration: true, ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_can_be_asked_is_asked_for_its_settings_at_startup() {
|
||||
let tree = Tree::new("pullstartup");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
let session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (_id, params) = configuration_request(&session);
|
||||
assert_eq!(
|
||||
params,
|
||||
serde_json::json!({ "items": [{ "section": "lucisv" }] }),
|
||||
"one item, our section, no scope"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_startup_pull_is_sent_after_the_watcher_registration_on_the_wire() {
|
||||
// `Server::new` calls `register_watchers` and then
|
||||
// `request_configuration`, in that order — this pins it on the actual
|
||||
// wire rather than trusting the call order in the source. Every
|
||||
// outgoing request's id is `lucisv-{n}` off one monotonically
|
||||
// increasing counter, so the numeric suffix *is* the send order.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item
|
||||
// ("verify on the wire").
|
||||
let tree = Tree::new("pulloraftwatch");
|
||||
let abilities =
|
||||
ClientAbilities { file_watching: true, configuration: true, ..pulling_settings() };
|
||||
let session = Session::with(vec![tree.path.clone()], abilities);
|
||||
let sent = session.sent();
|
||||
let index_of = |method: &str| -> usize {
|
||||
sent.iter()
|
||||
.position(|r| r.method == method)
|
||||
.unwrap_or_else(|| panic!("no {method} in {sent:#?}"))
|
||||
};
|
||||
let watchers = index_of(RegisterCapability::METHOD);
|
||||
let pull = index_of(WorkspaceConfiguration::METHOD);
|
||||
assert!(watchers < pull, "watcher registration must precede the pull: {sent:#?}");
|
||||
|
||||
let numeric_suffix = |request: &Request| -> u32 {
|
||||
request
|
||||
.id
|
||||
.to_string()
|
||||
.trim_matches('"')
|
||||
.trim_start_matches("lucisv-")
|
||||
.parse()
|
||||
.unwrap_or_else(|_| panic!("not a lucisv-N id: {:?}", request.id))
|
||||
};
|
||||
assert!(
|
||||
numeric_suffix(&sent[watchers]) < numeric_suffix(&sent[pull]),
|
||||
"the pull's id must be issued after the watcher registration's: {sent:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_cannot_be_asked_is_never_asked() {
|
||||
// Every client that predates this — `smoke.js` included — sends
|
||||
// `capabilities: {}` and must see nothing new at all.
|
||||
let tree = Tree::new("pullnone");
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "{:#?}", session.requests());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_answer_reaches_the_formatter_through_the_same_parser_a_push_uses() {
|
||||
let tree = Tree::new("pullapply");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nwire a;\nendmodule\n");
|
||||
let (id, _) = configuration_request(&session);
|
||||
|
||||
// The editor's tab size, until the client answers.
|
||||
assert_eq!(
|
||||
formatting_result(&mut session, &uri)[0]["newText"],
|
||||
serde_json::json!("module m;\n wire a;\nendmodule\n")
|
||||
);
|
||||
|
||||
// The answer is an array with one entry per requested item, and the
|
||||
// entry is the *section*, not the `{lucisv: ...}` wrapper a push has.
|
||||
session.answer(id, serde_json::json!([{ "indent": 4, "lineLength": 120 }]));
|
||||
assert_eq!(
|
||||
formatting_result(&mut session, &uri)[0]["newText"],
|
||||
serde_json::json!("module m;\n wire a;\nendmodule\n"),
|
||||
"the pulled indent is in force"
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().line_length, Some(120));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_answer_that_changes_the_scope_rebuilds_the_index() {
|
||||
// The pull applies through the same path a push does, so an `exclude`
|
||||
// that arrives this way must cost the same rescan.
|
||||
let tree = Tree::new("pullexclude");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("scratch/wip.sv", "scratch_pkg");
|
||||
let mut session = Session::wide_with(vec![tree.path.clone()], pulling_settings());
|
||||
assert_eq!(indexed(&session, "scratch_pkg"), 1, "premise: indexed at first");
|
||||
|
||||
let (id, _) = configuration_request(&session);
|
||||
// The pulled section carries the scope for the same reason a pushed
|
||||
// one does: an answer is the *whole* section, so leaving it out would
|
||||
// narrow the index in the same breath as the exclude.
|
||||
session.answer(
|
||||
id,
|
||||
serde_json::json!([{ "exclude": ["scratch"], "index": { "scope": "workspace" } }]),
|
||||
);
|
||||
assert_eq!(indexed(&session, "scratch_pkg"), 0, "the pulled exclude took effect");
|
||||
assert_eq!(indexed(&session, "a"), 1, "and nothing else moved");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pulled_filelist_re_registers_the_watchers_through_the_same_chain_a_push_uses() {
|
||||
// `apply_settings` is the one function both doors go through, but
|
||||
// nothing pinned it for the *pull* path specifically before this: the
|
||||
// answer changing `lucisv.filelist` must move `filelist_path()` and
|
||||
// cost a watcher re-registration exactly as a pushed one does.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item
|
||||
// ("the full chain: pull answer -> apply_settings -> filelist moved
|
||||
// -> re-register").
|
||||
let tree = Tree::new("pullfilelistwatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
let abilities =
|
||||
ClientAbilities { configuration: true, file_watching: true, ..Default::default() };
|
||||
let mut session = Session::with(vec![tree.path.clone()], abilities);
|
||||
// Drains the startup watcher registration and the startup pull's own
|
||||
// request together; `configuration_request` needs only the latter.
|
||||
let (id, _) = configuration_request(&session);
|
||||
|
||||
session.answer(id, serde_json::json!([{ "filelist": "files.f" }]));
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, UnregisterCapability::METHOD, "the old registration first");
|
||||
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
||||
assert_eq!(
|
||||
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
||||
tree.path.join("files.f").to_str().expect("utf-8").to_string(),
|
||||
"{requests:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_pull_answer_leaves_the_defaults_and_says_nothing() {
|
||||
// Nothing here is the user's fault and nothing here is actionable, so
|
||||
// every one of these must be as quiet as a client that answered
|
||||
// `null` — which is what the spec asks a client without the section
|
||||
// to do.
|
||||
let tree = Tree::new("pulljunk");
|
||||
for answer in [
|
||||
serde_json::json!(null),
|
||||
serde_json::json!([]),
|
||||
serde_json::json!([null]),
|
||||
serde_json::json!("lucisv"),
|
||||
serde_json::json!({ "indent": 4 }),
|
||||
serde_json::json!([{ "indent": "four", "exclude": 7 }]),
|
||||
serde_json::json!([{ "lucisv": { "indent": 4 } }]),
|
||||
] {
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, answer.clone());
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings(),
|
||||
&settings::ClientSettings::default(),
|
||||
"the answer {answer} must leave the defaults"
|
||||
);
|
||||
assert!(session.shown().is_empty(), "and must not open a popup");
|
||||
}
|
||||
|
||||
// An error response is the same news, said differently.
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.server.response(Response::new_err(
|
||||
id,
|
||||
lsp_server::ErrorCode::MethodNotFound as i32,
|
||||
"no configuration here".to_string(),
|
||||
));
|
||||
assert_eq!(session.server.workspace.client_settings(), &settings::ClientSettings::default());
|
||||
assert!(session.shown().is_empty(), "a refused pull is not worth a popup");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_push_pulls_instead_of_resetting_everything_to_default() {
|
||||
// The modern client's "something changed, ask me for what you need".
|
||||
// Applying it as a payload would silently clear the settings it just
|
||||
// told us to come and fetch.
|
||||
let tree = Tree::new("pushempty");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
||||
|
||||
for empty in [serde_json::json!({ "settings": {} }), serde_json::json!({ "settings": null })] {
|
||||
let _ = session.drain();
|
||||
session.notify(DidChangeConfiguration::METHOD, empty.clone());
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"{empty} must not clear what was pulled"
|
||||
);
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([{ "indent": 8 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "{empty}");
|
||||
// Put it back for the next round.
|
||||
session.server.workspace.set_client_settings(settings::ClientSettings {
|
||||
indent: Some(4),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_push_to_a_client_that_cannot_be_asked_still_means_no_opinion() {
|
||||
// The legacy path, unchanged: with nobody to ask, an empty payload is
|
||||
// what it has always been — no opinion about anything.
|
||||
let tree = Tree::new("pushemptylegacy");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 4 } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, None, "cleared, as before");
|
||||
assert!(session.requests().is_empty(), "and nothing was asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_push_with_a_payload_is_applied_directly_even_when_the_client_could_be_asked() {
|
||||
// The legacy `synchronize.configurationSection` path survives the
|
||||
// pull model: a client that sends both must not have its own push
|
||||
// ignored in favour of a round trip.
|
||||
let tree = Tree::new("pushpayload");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id, serde_json::json!([null]));
|
||||
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8));
|
||||
let sent = session.sent();
|
||||
assert!(
|
||||
!sent.iter().any(|r| r.method == WorkspaceConfiguration::METHOD),
|
||||
"a payload is not a request to go and fetch one: {sent:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_pull_answer_overrides_a_push_that_landed_while_it_was_outstanding() {
|
||||
// The other half of the precedence question: a client that both
|
||||
// pushes (the legacy `synchronize.configurationSection`) and can be
|
||||
// pulled may have its own push arrive *before* the startup pull's
|
||||
// answer does — both mechanisms firing off the same connection at
|
||||
// once. The loop is single-threaded and processes messages strictly
|
||||
// in receive order, with no notion of "the push is newer" beyond
|
||||
// that: `apply_settings` always replaces the whole struct, so
|
||||
// whichever of the two is processed *last* is simply what is in
|
||||
// force afterward. QA (2026-08-27): pinned per the dev's own review
|
||||
// checklist item ("push-with-payload arriving while a pull is
|
||||
// outstanding — which wins").
|
||||
let tree = Tree::new("latepullwins");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
|
||||
// The push lands first, while the startup pull is still outstanding.
|
||||
session.notify(
|
||||
DidChangeConfiguration::METHOD,
|
||||
serde_json::json!({ "settings": { "lucisv": { "indent": 8 } } }),
|
||||
);
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the push landed");
|
||||
|
||||
// The pull's answer arrives after — and, being processed last,
|
||||
// overwrites it.
|
||||
session.answer(id, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"processed last, so in force last — the pull's answer, not the push"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_outstanding_requests_are_answered_by_id_in_any_order() {
|
||||
// `applyEdit`, a progress `create` and a `workspace/configuration`
|
||||
// all in flight at once. Only two of them are in `pending`, and the
|
||||
// arrival order is not the send order — the id is the whole lookup,
|
||||
// and neither answer may be delivered to the other's handler.
|
||||
let abilities = ClientAbilities {
|
||||
apply_edit: true,
|
||||
work_done_progress: true,
|
||||
configuration: true,
|
||||
..Default::default()
|
||||
};
|
||||
let (tree, mut session, params) = propagating("threeway", abilities);
|
||||
let _ = session.drain();
|
||||
// `propagating` answered nothing, so the startup pull is already
|
||||
// spent; an empty push asks again, and that one is left outstanding
|
||||
// alongside the other two.
|
||||
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
||||
|
||||
let result = session.result(ExecuteCommand::METHOD, params);
|
||||
assert!(result.is_null(), "the edit was pushed, not returned");
|
||||
// Two files, so the rescan is the whole one that puts a bar up.
|
||||
session.watched(&[tree.path.join("sub.sv"), tree.path.join("top.sv")]);
|
||||
|
||||
let sent = session.sent();
|
||||
let of = |method: &str| -> RequestId {
|
||||
sent.iter()
|
||||
.find(|request| request.method == method)
|
||||
.unwrap_or_else(|| panic!("no {method} in {sent:#?}"))
|
||||
.id
|
||||
.clone()
|
||||
};
|
||||
let (edit, create, pull) = (
|
||||
of(ApplyWorkspaceEdit::METHOD),
|
||||
of(WorkDoneProgressCreate::METHOD),
|
||||
of(WorkspaceConfiguration::METHOD),
|
||||
);
|
||||
|
||||
// Backwards: the pull first, then the ignorable create, then the edit.
|
||||
session.answer(pull, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "the pull landed");
|
||||
assert!(session.shown().is_empty(), "and said nothing to the user");
|
||||
|
||||
session.answer(create, serde_json::json!(null));
|
||||
assert!(session.shown().is_empty(), "a create answer says nothing either");
|
||||
|
||||
session.answer(edit, serde_json::json!({ "applied": false }));
|
||||
let shown = session.shown();
|
||||
assert_eq!(shown.len(), 1, "{shown:#?}");
|
||||
assert!(shown[0].1.contains("lucisv.propagatePorts"), "{shown:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_outstanding_configuration_pulls_are_each_answered_by_their_own_id() {
|
||||
// A second pull can go out before the first is answered — an empty
|
||||
// `didChangeConfiguration` racing the client's answer to the startup
|
||||
// pull, say. Both ids sit in `pending` at once; each answer is
|
||||
// applied through its own id, and whichever is processed last is
|
||||
// simply what ends up in force — there is no notion of the newer
|
||||
// pull's answer winning over the older one, only processing order.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
||||
let tree = Tree::new("twopulls");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let sent = session.sent();
|
||||
let first = sent
|
||||
.iter()
|
||||
.find(|r| r.method == WorkspaceConfiguration::METHOD)
|
||||
.expect("the startup pull")
|
||||
.id
|
||||
.clone();
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, serde_json::json!({ "settings": null }));
|
||||
let sent = session.sent();
|
||||
let second = sent
|
||||
.iter()
|
||||
.find(|r| r.method == WorkspaceConfiguration::METHOD)
|
||||
.expect("the re-pull")
|
||||
.id
|
||||
.clone();
|
||||
assert_ne!(first, second, "two distinct outstanding requests, not one reused");
|
||||
|
||||
// Answered out of order: the second (newer) pull first, then the
|
||||
// first (older, startup) one.
|
||||
session.answer(second, serde_json::json!([{ "indent": 8 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(8), "the newer landed");
|
||||
session.answer(first, serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"whichever answer is processed last is what is in force — no id-based precedence"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_to_a_request_the_server_never_tracked_is_silently_ignored() {
|
||||
// An id the server never sent, or a duplicate answer to one already
|
||||
// consumed, names nothing in `pending`: `response` must not panic and
|
||||
// must leave whatever settings are in force untouched.
|
||||
// QA (2026-08-27): pinned per the dev's own review checklist item.
|
||||
let tree = Tree::new("forgottenid");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling_settings());
|
||||
let (id, _) = configuration_request(&session);
|
||||
session.answer(id.clone(), serde_json::json!([{ "indent": 4 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4), "premise");
|
||||
|
||||
// The same id, answered a second time — already removed from `pending`.
|
||||
session.answer(id, serde_json::json!([{ "indent": 8 }]));
|
||||
assert_eq!(
|
||||
session.server.workspace.client_settings().indent,
|
||||
Some(4),
|
||||
"a stale re-answer is a no-op"
|
||||
);
|
||||
|
||||
// An id that was never sent by this server at all.
|
||||
session.answer(RequestId::from("never-sent".to_string()), serde_json::json!([{ "indent": 2 }]));
|
||||
assert_eq!(session.server.workspace.client_settings().indent, Some(4));
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
//! Incremental text sync and the change debounce.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// incremental text sync
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn incremental_changes_land_the_same_buffer_as_one_full_change() {
|
||||
let tree = Tree::new("incrementalsame");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
// Three ranges, each positioned against what the last one left.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([
|
||||
{ "range": { "start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 1, "character": 0 } }, "text": "\n" },
|
||||
{ "range": { "start": { "line": 1, "character": 0 },
|
||||
"end": { "line": 1, "character": 0 } }, "text": " wire " },
|
||||
{ "range": { "start": { "line": 1, "character": 7 },
|
||||
"end": { "line": 1, "character": 7 } }, "text": "w;" },
|
||||
]),
|
||||
);
|
||||
let composed = "module m;\n wire w;\nendmodule\n";
|
||||
assert_eq!(buffer(&session, &uri), composed);
|
||||
|
||||
// The same buffer reached by a full-sync client, for comparison.
|
||||
let mut full = Session::new(vec![tree.path.clone()], false);
|
||||
let other = full.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
change(&mut full, &other, 2, serde_json::json!([{ "text": composed }]));
|
||||
assert_eq!(buffer(&full, &other), composed);
|
||||
|
||||
// And the answers computed from it agree, not just the text.
|
||||
assert_eq!(
|
||||
session.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
),
|
||||
full.result(
|
||||
Formatting::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": other },
|
||||
"options": { "tabSize": 2, "insertSpaces": true },
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_burst_of_changes_coalesces_into_one_reparse() {
|
||||
// The change debounce's whole payoff: a burst of `didChange`
|
||||
// notifications costs one reparse when the next thing that needs the
|
||||
// analysis flushes them, not one per keystroke.
|
||||
let tree = Tree::new("debounce");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
let before = session.server.generation;
|
||||
session.batch(vec![
|
||||
changed(&uri, 2, "module m;\n wire a;\nendmodule\n"),
|
||||
changed(&uri, 3, "module m;\n wire a;\n wire b;\nendmodule\n"),
|
||||
]);
|
||||
// Text-current, analysis-stale: nothing has reparsed yet, and the
|
||||
// newest text is already what the server holds.
|
||||
assert_eq!(session.server.generation, before, "no keystroke reparses on its own");
|
||||
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire b;\nendmodule\n");
|
||||
|
||||
// The first request after the burst is answered from one flush.
|
||||
session.result(
|
||||
DocumentSymbolRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert_eq!(session.server.generation, before + 1, "one reparse for the whole burst");
|
||||
assert!(session.server.dirty.is_empty(), "and nothing is left pending");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_dirty_buffer_discards_its_change_and_leaves_the_others_alone() {
|
||||
// The debounce's other half: a buffer closed mid-edit is never
|
||||
// analyzed. Its pending text is dropped ahead of the flush at the top
|
||||
// of `notification`, so the client gets the one clearing publish and
|
||||
// nothing else — while every *other* dirty buffer still flushes,
|
||||
// because closing one file says nothing about the rest (QA, CD-1).
|
||||
let tree = Tree::new("closedirty");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let closing = session.open(&tree.path.join("closing.sv"), "module a;\nendmodule\n");
|
||||
let staying = session.open(&tree.path.join("staying.sv"), "module b;\nendmodule\n");
|
||||
let _ = session.published();
|
||||
|
||||
// Both buffers go dirty with text that would diagnose if analyzed.
|
||||
let before = session.server.generation;
|
||||
for (uri, text) in [
|
||||
(&closing, "module a;\n wire ;\nendmodule\n"),
|
||||
(&staying, "module b;\n wire ;\nendmodule\n"),
|
||||
] {
|
||||
session.notify(
|
||||
DidChangeTextDocument::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri, "version": 2 },
|
||||
"contentChanges": [{ "text": text }],
|
||||
}),
|
||||
);
|
||||
}
|
||||
assert_eq!(session.server.generation, before, "a keystroke reparses nothing on its own");
|
||||
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": closing } }),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
session.server.generation,
|
||||
before + 1,
|
||||
"one reparse — the buffer still open; the closing one's text went with it"
|
||||
);
|
||||
assert!(session.server.dirty.is_empty(), "nothing left pending");
|
||||
|
||||
let published = session.published();
|
||||
let closed: Vec<_> = published.iter().filter(|p| p.uri == closing).collect();
|
||||
assert_eq!(closed.len(), 1, "exactly one publish for the closed buffer: {published:?}");
|
||||
assert!(closed[0].diagnostics.is_empty(), "and it is the clearing one: {published:?}");
|
||||
let open: Vec<_> = published.iter().filter(|p| p.uri == staying).collect();
|
||||
assert_eq!(open.len(), 1, "the other buffer publishes once: {published:?}");
|
||||
assert!(
|
||||
!open[0].diagnostics.is_empty(),
|
||||
"the other buffer's pending edit was flushed as usual: {published:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_notification_is_one_generation_bump_however_many_ranges() {
|
||||
// The pull-diagnostics `resultId` is this counter. One reparse and one
|
||||
// stamp per notification: a bump per range would make every keystroke
|
||||
// look like several to a pulling client, and none would make a
|
||||
// changed buffer answer "unchanged".
|
||||
let tree = Tree::new("incrementalgeneration");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
|
||||
let before = session.server.generation;
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([
|
||||
{ "range": { "start": { "line": 0, "character": 9 },
|
||||
"end": { "line": 0, "character": 9 } }, "text": "\n wire a;" },
|
||||
{ "range": { "start": { "line": 1, "character": 9 },
|
||||
"end": { "line": 1, "character": 9 } }, "text": "\n wire b;" },
|
||||
{ "range": { "start": { "line": 2, "character": 7 },
|
||||
"end": { "line": 2, "character": 8 } }, "text": "c" },
|
||||
]),
|
||||
);
|
||||
assert_eq!(session.server.generation, before + 1, "one stamp per notification");
|
||||
assert_eq!(buffer(&session, &uri), "module m;\n wire a;\n wire c;\nendmodule\n");
|
||||
|
||||
// An empty batch is not a change: nothing to reparse, nothing to stamp.
|
||||
let stamp = session.server.generation;
|
||||
change(&mut session, &uri, 3, serde_json::json!([]));
|
||||
assert_eq!(session.server.generation, stamp, "an empty batch moves nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_sync_clients_batch_still_lets_the_last_change_win() {
|
||||
// A client that ignores the new capability and keeps sending whole
|
||||
// buffers must behave exactly as it did before this feature.
|
||||
let tree = Tree::new("incrementalfullsync");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\nendmodule\n");
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([
|
||||
{ "text": "module a;\nendmodule\n" },
|
||||
{ "text": "module b;\nendmodule\n" },
|
||||
{ "text": "module c;\nendmodule\n" },
|
||||
]),
|
||||
);
|
||||
assert_eq!(buffer(&session, &uri), "module c;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_naming_a_buffer_that_was_never_opened_is_taken_as_written() {
|
||||
// Out of protocol, but a full-text change used to be adopted whatever
|
||||
// the state was, and still is: there is no base text to be wrong
|
||||
// about. A *ranged* change against nothing lands its text at the
|
||||
// start, which is the clamping rule, not a special case.
|
||||
let tree = Tree::new("incrementalunopened");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = path_to_uri(&tree.path.join("never-opened.sv")).expect("uri");
|
||||
change(&mut session, &uri, 1, serde_json::json!([{ "text": "module m;\nendmodule\n" }]));
|
||||
assert_eq!(buffer(&session, &uri), "module m;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ranged_change_over_multi_byte_text_edits_the_right_columns() {
|
||||
// The whole reason positions are converted rather than counted: the
|
||||
// comment above the edited line is four characters and nine bytes.
|
||||
let tree = Tree::new("incrementalunicode");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "// é ✓ 🎉\nmodule m;\n wire a;\nendmodule\n");
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{
|
||||
"range": { "start": { "line": 2, "character": 7 },
|
||||
"end": { "line": 2, "character": 8 } },
|
||||
"text": "renamed",
|
||||
}]),
|
||||
);
|
||||
assert_eq!(buffer(&session, &uri), "// é ✓ 🎉\nmodule m;\n wire renamed;\nendmodule\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ranged_change_republishes_diagnostics_for_what_it_produced() {
|
||||
let tree = Tree::new("incrementalpublish");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), "module m;\n wire a;\nendmodule\n");
|
||||
let _ = session.published();
|
||||
|
||||
// Delete the `a`, leaving `wire ;` — a parse error.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{
|
||||
"range": { "start": { "line": 1, "character": 7 },
|
||||
"end": { "line": 1, "character": 8 } },
|
||||
"text": "",
|
||||
}]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1, "one publish per notification: {published:#?}");
|
||||
assert!(!published[0].diagnostics.is_empty(), "the broken buffer is reported");
|
||||
|
||||
// Put it back: the diagnostics clear.
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
3,
|
||||
serde_json::json!([{
|
||||
"range": { "start": { "line": 1, "character": 7 },
|
||||
"end": { "line": 1, "character": 7 } },
|
||||
"text": "a",
|
||||
}]),
|
||||
);
|
||||
let published = session.published();
|
||||
assert_eq!(published.len(), 1);
|
||||
assert!(published[0].diagnostics.is_empty(), "{published:#?}");
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
//! Semantic tokens: full, range, full/delta.
|
||||
|
||||
use super::*;
|
||||
use crate::tokens;
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// semantic tokens: full, range, full/delta
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn full_tokens(session: &mut Session, uri: &Uri) -> Value {
|
||||
session.result(
|
||||
SemanticTokensFullRequest::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
)
|
||||
}
|
||||
|
||||
fn delta_tokens(session: &mut Session, uri: &Uri, previous: &str) -> Value {
|
||||
session.result(
|
||||
SemanticTokensFullDeltaRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"previousResultId": previous,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn range_tokens(session: &mut Session, uri: &Uri, from: (u32, u32), to: (u32, u32)) -> Value {
|
||||
session.result(
|
||||
SemanticTokensRangeRequest::METHOD,
|
||||
serde_json::json!({
|
||||
"textDocument": { "uri": uri },
|
||||
"range": {
|
||||
"start": { "line": from.0, "character": from.1 },
|
||||
"end": { "line": to.0, "character": to.1 },
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// A `data` array as the client reads it: flat numbers.
|
||||
fn numbers(value: &Value) -> Vec<u64> {
|
||||
value
|
||||
.as_array()
|
||||
.unwrap_or_else(|| panic!("an array of numbers, got {value:#?}"))
|
||||
.iter()
|
||||
.map(|n| n.as_u64().expect("a number"))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The client's side of a delta: splice each edit into the data it holds.
|
||||
fn applied(previous: &[u64], answer: &Value) -> Vec<u64> {
|
||||
let mut data = previous.to_vec();
|
||||
let edits = answer["edits"].as_array().unwrap_or_else(|| panic!("edits in {answer:#?}"));
|
||||
for edit in edits {
|
||||
let start = edit["start"].as_u64().expect("start") as usize;
|
||||
let end = start + edit["deleteCount"].as_u64().expect("deleteCount") as usize;
|
||||
let inserted = edit.get("data").map(numbers).unwrap_or_default();
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
const TOKEN_SOURCE: &str = "module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn a_full_token_answer_is_stamped_so_a_delta_can_name_it() {
|
||||
let tree = Tree::new("tokensfull");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let full = full_tokens(&mut session, &uri);
|
||||
assert!(full["resultId"].is_string(), "{full:#?}");
|
||||
assert!(!numbers(&full["data"]).is_empty(), "the buffer really has tokens");
|
||||
assert_eq!(
|
||||
session.server.tokens[&uri].result_id,
|
||||
full["resultId"].as_str().expect("resultId"),
|
||||
"the answer is remembered under the id it was stamped with"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delta_after_a_change_reconstructs_the_new_token_set_exactly() {
|
||||
// The whole invariant, end to end through the dispatch: what the
|
||||
// client is left holding after applying the edits must be what a
|
||||
// fresh full answer would have given it.
|
||||
let tree = Tree::new("tokensdelta");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let held = numbers(&first["data"]);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
|
||||
change(
|
||||
&mut session,
|
||||
&uri,
|
||||
2,
|
||||
serde_json::json!([{ "text": "module m;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n" }]),
|
||||
);
|
||||
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(answer.get("edits").is_some(), "a known id gets edits: {answer:#?}");
|
||||
let reconstructed = applied(&held, &answer);
|
||||
let now = full_tokens(&mut session, &uri);
|
||||
assert_eq!(reconstructed, numbers(&now["data"]), "the edits must reconstruct the truth");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delta_over_an_unchanged_buffer_is_an_empty_edit_list() {
|
||||
let tree = Tree::new("tokensnochange");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert_eq!(answer["edits"], serde_json::json!([]), "{answer:#?}");
|
||||
assert_ne!(answer["resultId"], first["resultId"], "and it is a new answer to name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_delta_naming_an_id_we_do_not_hold_is_answered_in_full() {
|
||||
let tree = Tree::new("tokensstale");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
// Never asked for a full answer: there is nothing to diff against.
|
||||
let cold = delta_tokens(&mut session, &uri, "1");
|
||||
assert!(cold.get("edits").is_none(), "no state, no edits: {cold:#?}");
|
||||
assert!(!numbers(&cold["data"]).is_empty(), "{cold:#?}");
|
||||
|
||||
// And an id that has since been superseded — the client fell behind,
|
||||
// or another id's answer overwrote this one.
|
||||
let _ = full_tokens(&mut session, &uri);
|
||||
let stale = delta_tokens(&mut session, &uri, "not-an-id-we-ever-sent");
|
||||
assert!(stale.get("edits").is_none(), "a stale id, a full answer: {stale:#?}");
|
||||
assert!(stale["resultId"].is_string(), "which is itself nameable: {stale:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_buffer_drops_the_answer_a_delta_would_be_computed_against() {
|
||||
// Memory: nothing may grow with the number of files ever opened. The
|
||||
// observable half is that a delta naming the old id gets a full set.
|
||||
let tree = Tree::new("tokensclose");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let path = tree.path.join("m.sv");
|
||||
let uri = session.open(&path, TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri } }),
|
||||
);
|
||||
assert!(!session.server.tokens.contains_key(&uri), "the state went with the buffer");
|
||||
|
||||
session.open(&path, TOKEN_SOURCE);
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(answer.get("edits").is_none(), "the old id names nothing now: {answer:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_covers_the_lines_it_names_and_nothing_else() {
|
||||
let tree = Tree::new("tokensrange");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let whole = numbers(&full_tokens(&mut session, &uri)["data"]);
|
||||
let everything = range_tokens(&mut session, &uri, (0, 0), (99, 0));
|
||||
assert_eq!(numbers(&everything["data"]), whole, "a range over everything is the full set");
|
||||
|
||||
let one_line = range_tokens(&mut session, &uri, (1, 0), (2, 0));
|
||||
let data = numbers(&one_line["data"]);
|
||||
assert!(!data.is_empty() && data.len() < whole.len(), "{one_line:#?}");
|
||||
assert_eq!(data[0], 1, "the first token's deltaLine is absolute from the file start");
|
||||
|
||||
let nothing = range_tokens(&mut session, &uri, (2, 0), (2, 0));
|
||||
assert_eq!(numbers(¬hing["data"]), Vec::<u64>::new(), "an empty range: {nothing:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_request_is_not_the_answer_a_later_delta_is_computed_against() {
|
||||
// A range answer is a partial view, so remembering it would make the
|
||||
// next delta a diff against something the client never held whole.
|
||||
let tree = Tree::new("tokensrangestate");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let ranged = range_tokens(&mut session, &uri, (1, 0), (2, 0));
|
||||
assert!(ranged.get("resultId").is_none(), "nothing to name: {ranged:#?}");
|
||||
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert_eq!(answer["edits"], serde_json::json!([]), "the full answer still stands");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_token_request_for_a_buffer_that_is_not_open_answers_null() {
|
||||
let tree = Tree::new("tokensunopened");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = crate::uri::path_to_uri(&tree.path.join("never.sv")).expect("uri");
|
||||
|
||||
assert!(full_tokens(&mut session, &uri).is_null());
|
||||
assert!(delta_tokens(&mut session, &uri, "1").is_null());
|
||||
assert!(range_tokens(&mut session, &uri, (0, 0), (9, 0)).is_null());
|
||||
assert!(session.server.tokens.is_empty(), "and nothing was remembered about it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_token_request_bumps_the_diagnostics_generation() {
|
||||
// Every token request is read-only. Bumping the generation would
|
||||
// invalidate a pulling client's whole diagnostic cache each time the
|
||||
// editor repainted a viewport.
|
||||
let tree = Tree::new("tokensgeneration");
|
||||
let mut session = Session::with(vec![tree.path.clone()], pulling());
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let before = session.server.generation;
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let _ = delta_tokens(&mut session, &uri, &previous);
|
||||
let _ = range_tokens(&mut session, &uri, (0, 0), (9, 0));
|
||||
assert_eq!(session.server.generation, before, "nothing about diagnostics moved");
|
||||
|
||||
// Said the way the client would see it: a pull stamped before the
|
||||
// token requests is still `unchanged` after them.
|
||||
let pull = document_pull(&mut session, &uri, None);
|
||||
let stamp = pull["resultId"].as_str().expect("resultId").to_string();
|
||||
let _ = full_tokens(&mut session, &uri);
|
||||
let again = document_pull(&mut session, &uri, Some(&stamp));
|
||||
assert_eq!(again["kind"], "unchanged", "{again:#?}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): state-lifecycle attack surfaces
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn qa_two_open_buffers_ids_do_not_cross_contaminate() {
|
||||
// Buffer A's resultId presented against buffer B must not be
|
||||
// mistaken for one of B's own — they share one counter, so the
|
||||
// strings can coincide only by the map being keyed on the wrong
|
||||
// thing.
|
||||
let tree = Tree::new("tokenstwobuffers");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri_a = session.open(&tree.path.join("a.sv"), TOKEN_SOURCE);
|
||||
let uri_b = session.open(&tree.path.join("b.sv"), "module other;\n wire z;\nendmodule\n");
|
||||
|
||||
let full_a = full_tokens(&mut session, &uri_a);
|
||||
let full_b = full_tokens(&mut session, &uri_b);
|
||||
let id_a = full_a["resultId"].as_str().expect("resultId").to_string();
|
||||
let id_b = full_b["resultId"].as_str().expect("resultId").to_string();
|
||||
assert_ne!(id_a, id_b, "two answers, two distinct ids");
|
||||
|
||||
// A's id, asked of B: B has no memory of ever answering that id, so
|
||||
// this must be a full answer, not edits computed against A's data.
|
||||
let cross = delta_tokens(&mut session, &uri_b, &id_a);
|
||||
assert!(cross.get("edits").is_none(), "A's id names nothing for B: {cross:#?}");
|
||||
// That full answer itself mints a fresh id and becomes B's new
|
||||
// remembered answer (every answer does, full or delta) — so it is
|
||||
// *that* id, not `id_b`, that now names B's data.
|
||||
let cross_id = cross["resultId"].as_str().expect("resultId").to_string();
|
||||
assert_ne!(cross_id, id_b, "a fresh id was minted for the cross-request's own answer");
|
||||
let _ = id_b; // superseded by `cross_id`; kept above only to assert distinctness of the two original ids
|
||||
|
||||
let same = delta_tokens(&mut session, &uri_b, &cross_id);
|
||||
assert_eq!(same["edits"], serde_json::json!([]), "B's latest id still names B's data");
|
||||
|
||||
// And closing A must not disturb B's remembered answer.
|
||||
session.notify(
|
||||
DidCloseTextDocument::METHOD,
|
||||
serde_json::json!({ "textDocument": { "uri": uri_a } }),
|
||||
);
|
||||
assert!(!session.server.tokens.contains_key(&uri_a));
|
||||
assert!(session.server.tokens.contains_key(&uri_b), "B's state is untouched by A's close");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_full_delta_full_delta_stays_consistent_across_edits() {
|
||||
// Mixing the two requests repeatedly, the way a real client would:
|
||||
// each new answer must be nameable by the next delta, regardless of
|
||||
// whether the previous answer was a `full` or a `full/delta`.
|
||||
let tree = Tree::new("tokensmixedcycle");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let mut previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let mut held = numbers(&first["data"]);
|
||||
|
||||
let edits_after = [
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\n // note\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
];
|
||||
for (i, text) in edits_after.iter().enumerate() {
|
||||
change(&mut session, &uri, i as u32 + 2, serde_json::json!([{ "text": text }]));
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(answer.get("edits").is_some(), "step {i}: known id gets edits: {answer:#?}");
|
||||
held = applied(&held, &answer);
|
||||
|
||||
let truth = full_tokens(&mut session, &uri);
|
||||
assert_eq!(held, numbers(&truth["data"]), "step {i}: delta chain matches the truth");
|
||||
// The `full` answer just taken is itself a fresh, valid base for
|
||||
// the next delta in the cycle.
|
||||
previous = truth["resultId"].as_str().expect("resultId").to_string();
|
||||
held = numbers(&truth["data"]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A flat `data` array computed straight off the document, bypassing the
|
||||
/// request dispatch entirely — so checking against it does not depend on
|
||||
/// the very `tokens`/`token_results` bookkeeping under test.
|
||||
fn ground_truth(session: &Session, uri: &Uri) -> Vec<u64> {
|
||||
let doc = session.server.workspace.document(uri).expect("open");
|
||||
tokens::semantic_tokens(doc)
|
||||
.iter()
|
||||
.flat_map(|t| {
|
||||
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
|
||||
})
|
||||
.map(u64::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between() {
|
||||
// A client need not re-request `full` just because it received a
|
||||
// `full/delta` answer: that answer's own `resultId` must itself be a
|
||||
// valid base for the *next* delta. Every `full_tokens` call in the
|
||||
// test above also re-remembers the answer, which would silently
|
||||
// paper over a bug where only a *full* answer's id chains correctly
|
||||
// — so this test never calls `full` again after the first one.
|
||||
let tree = Tree::new("tokensdeltachain");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
let uri = session.open(&tree.path.join("m.sv"), TOKEN_SOURCE);
|
||||
|
||||
let first = full_tokens(&mut session, &uri);
|
||||
let mut previous = first["resultId"].as_str().expect("resultId").to_string();
|
||||
let mut held = numbers(&first["data"]);
|
||||
|
||||
let edits_after = [
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\n // note\nendmodule\n",
|
||||
"module m;\n localparam W = 16;\n wire [W-1:0] a;\nendmodule\n",
|
||||
];
|
||||
for (i, text) in edits_after.iter().enumerate() {
|
||||
change(&mut session, &uri, i as u32 + 2, serde_json::json!([{ "text": text }]));
|
||||
let answer = delta_tokens(&mut session, &uri, &previous);
|
||||
assert!(
|
||||
answer.get("edits").is_some(),
|
||||
"step {i}: the chained id is still known: {answer:#?}"
|
||||
);
|
||||
held = applied(&held, &answer);
|
||||
previous = answer["resultId"].as_str().expect("resultId").to_string();
|
||||
assert_eq!(held, ground_truth(&session, &uri), "step {i}: the chain matches the truth");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! File watchers: the registration, and the rebuilds a watched-file event does or does not cost.
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_is_never_sent_a_registration() {
|
||||
// Such a client keeps the save-only staleness model, and must not be
|
||||
// sent a request it has no handler for.
|
||||
let tree = Tree::new("noregister");
|
||||
let session = Session::new(vec![tree.path.clone()], false);
|
||||
assert!(session.requests().is_empty(), "nothing may be asked of it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_asked_is_registered_after_initialized() {
|
||||
let tree = Tree::new("register");
|
||||
let session = Session::new(vec![tree.path.clone()], true);
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 1, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, RegisterCapability::METHOD);
|
||||
assert_eq!(
|
||||
requests[0].1,
|
||||
serde_json::json!({
|
||||
"registrations": [{
|
||||
"id": "lucisv-watched-files-0",
|
||||
"method": "workspace/didChangeWatchedFiles",
|
||||
"registerOptions": {
|
||||
"watchers": [{ "globPattern": "**/*.{v,vh,sv,svh}" }]
|
||||
},
|
||||
}]
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_configured_filelist_is_watched_too() {
|
||||
let tree = Tree::new("registerfilelist");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let session = Session::new(vec![tree.path.clone()], true);
|
||||
let requests = session.requests();
|
||||
let watchers = &requests[0].1["registrations"][0]["registerOptions"]["watchers"];
|
||||
assert_eq!(
|
||||
watchers,
|
||||
&serde_json::json!([
|
||||
{ "globPattern": "**/*.{v,vh,sv,svh}" },
|
||||
{ "globPattern": tree.path.join("files.f").to_str().expect("utf-8") },
|
||||
]),
|
||||
"the filelist is watched by its own path"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_filelist_setting_replaces_the_registration() {
|
||||
// The watched path is baked into the registration, so the old one must
|
||||
// go and a new one take its place — otherwise the new filelist is
|
||||
// exactly the file nobody is watching.
|
||||
let tree = Tree::new("rewatch");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("other.f", "rtl/a.sv\n");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
assert_eq!(session.requests().len(), 1, "the registration made at startup");
|
||||
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].0, UnregisterCapability::METHOD);
|
||||
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-0");
|
||||
assert_eq!(requests[1].0, RegisterCapability::METHOD);
|
||||
let registration = &requests[1].1["registrations"][0];
|
||||
assert_eq!(registration["id"], "lucisv-watched-files-1", "a fresh id");
|
||||
assert_eq!(
|
||||
registration["registerOptions"]["watchers"][1]["globPattern"],
|
||||
tree.path.join("files.f").to_str().expect("utf-8").to_string()
|
||||
);
|
||||
|
||||
// The same value again moves nothing, so nothing is re-registered.
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
assert!(session.requests().is_empty(), "re-pushing the same path is not a change");
|
||||
|
||||
// A different one is.
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("other.f"));
|
||||
let requests = session.requests();
|
||||
assert_eq!(requests.len(), 2, "{requests:#?}");
|
||||
assert_eq!(requests[0].1["unregisterations"][0]["id"], "lucisv-watched-files-1");
|
||||
assert_eq!(
|
||||
requests[1].1["registrations"][0]["registerOptions"]["watchers"][1]["globPattern"],
|
||||
tree.path.join("other.f").to_str().expect("utf-8").to_string()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_client_that_did_not_ask_is_not_re_registered_either() {
|
||||
let tree = Tree::new("norewatch");
|
||||
tree.write("files.f", "\n");
|
||||
let mut session = Session::new(vec![tree.path.clone()], false);
|
||||
session.notify(DidChangeConfiguration::METHOD, filelist_push("files.f"));
|
||||
assert!(session.requests().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_notification_rebuilds_the_index_once_however_many_files_it_names() {
|
||||
// The `git checkout` shape. Rebuilding per event would re-scan the
|
||||
// workspace once per changed file for a single answer.
|
||||
let tree = Tree::new("oncepernotification");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
||||
|
||||
for i in 0..40 {
|
||||
tree.package(&format!("rtl/f{i}.sv"), &format!("p{i}"));
|
||||
}
|
||||
let changed: Vec<PathBuf> = (0..40).map(|i| tree.path.join(format!("rtl/f{i}.sv"))).collect();
|
||||
session.watched(&changed);
|
||||
assert_eq!(session.publishes(), 1, "one rebuild for the whole list");
|
||||
assert_eq!(indexed(&session, "p0"), 1, "and it really did rebuild");
|
||||
assert_eq!(indexed(&session, "p39"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_created_file_reaches_the_index_with_no_save_anywhere() {
|
||||
let tree = Tree::new("created");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(indexed(&session, "pulled"), 0, "premise: not there yet");
|
||||
|
||||
tree.package("rtl/pulled.sv", "pulled");
|
||||
session.watched(&[tree.path.join("rtl/pulled.sv")]);
|
||||
assert_eq!(indexed(&session, "pulled"), 1, "the `git pull` case");
|
||||
|
||||
// ... and a deletion is a change in the other direction.
|
||||
std::fs::remove_file(tree.path.join("rtl/pulled.sv")).expect("remove");
|
||||
session.watched(&[tree.path.join("rtl/pulled.sv")]);
|
||||
assert_eq!(indexed(&session, "pulled"), 0, "the `git checkout` case");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_event_for_a_file_outside_the_scope_still_rebuilds_but_indexes_nothing() {
|
||||
// The ladder re-applies during the rebuild, so an unlisted file stays
|
||||
// unlisted — and one rebuild for a stray in-tree source is cheaper than
|
||||
// deciding, per event, whether the filelist names it.
|
||||
let tree = Tree::new("outsidescope");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/unlisted.sv", "unlisted");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
assert_eq!(indexed(&session, "unlisted"), 0, "premise: the filelist omits it");
|
||||
|
||||
session.watched(&[tree.path.join("rtl/unlisted.sv")]);
|
||||
assert_eq!(indexed(&session, "a"), 1, "the listed file survives the rebuild");
|
||||
assert_eq!(indexed(&session, "unlisted"), 0, "and the unlisted one stays out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrelated_file_event_costs_no_rebuild() {
|
||||
let tree = Tree::new("stray");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
assert_eq!(session.publishes(), 1, "premise: `didOpen` published once");
|
||||
|
||||
session.watched(&[tree.path.join("README.md"), tree.path.join("target/build.log")]);
|
||||
assert_eq!(session.publishes(), 0, "a stray event is dropped, not re-scanned");
|
||||
|
||||
session
|
||||
.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes: Vec::new() });
|
||||
assert_eq!(session.publishes(), 0, "and so is an empty notification");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_buffer_still_beats_disk_after_a_watched_file_rebuild() {
|
||||
// The rule the rebuild has always had, checked on the new path into
|
||||
// it: an external change must never clobber what the user is looking
|
||||
// at. Here the file on disk is *also* the open one, rewritten behind
|
||||
// the editor's back — the buffer still wins.
|
||||
let tree = Tree::new("overlay");
|
||||
tree.package("rtl/open.sv", "on_disk");
|
||||
let path = tree.path.join("rtl/open.sv");
|
||||
|
||||
let mut session = Session::wide(vec![tree.path.clone()], true);
|
||||
let uri = session.open(&path, "package in_buffer;\n localparam K = 1;\nendpackage\n");
|
||||
assert_eq!(indexed(&session, "on_disk"), 1, "premise: indexed from disk at startup");
|
||||
|
||||
tree.package("rtl/open.sv", "rewritten_on_disk");
|
||||
session.watched(std::slice::from_ref(&path));
|
||||
assert_eq!(indexed(&session, "in_buffer"), 1, "the buffer wins the rebuild");
|
||||
assert_eq!(indexed(&session, "rewritten_on_disk"), 0, "disk loses");
|
||||
assert_eq!(indexed(&session, "on_disk"), 0, "and the stale copy is gone");
|
||||
let doc = session.server.workspace.document(&uri).expect("still open");
|
||||
assert!(doc.text.contains("in_buffer"), "and the buffer's own text is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_uri_helper_and_the_watch_filter_agree_about_the_filelist() {
|
||||
// `touches_scope` compares paths, and the path it compares against is
|
||||
// whatever `filelist_path` resolved — a mismatch would silently stop
|
||||
// filelist edits from rebuilding anything.
|
||||
let tree = Tree::new("filelistevent");
|
||||
tree.package("rtl/a.sv", "a");
|
||||
tree.package("rtl/b.sv", "b");
|
||||
tree.write("files.f", "rtl/a.sv\n");
|
||||
tree.write("lucisv.toml", "filelist = \"files.f\"\n");
|
||||
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(&tree.path.join("rtl/a.sv"), "package a;\n localparam K = 1;\nendpackage\n");
|
||||
let _ = session.drain();
|
||||
assert_eq!(indexed(&session, "b"), 0, "premise: not listed yet");
|
||||
|
||||
tree.write("files.f", "rtl/a.sv\nrtl/b.sv\n");
|
||||
session.watched(&[tree.path.join("files.f")]);
|
||||
assert_eq!(session.publishes(), 1, "the filelist's own edit rebuilds");
|
||||
assert_eq!(indexed(&session, "b"), 1, "and the newly listed file is in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_malformed_watched_files_notification_is_dropped() {
|
||||
let tree = Tree::new("malformed");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
let _ = session.drain();
|
||||
|
||||
session.notify(DidChangeWatchedFiles::METHOD, serde_json::json!({ "changes": "nonsense" }));
|
||||
assert_eq!(session.publishes(), 0, "no id to answer on, so nothing happens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_non_file_uri_in_an_event_is_ignored() {
|
||||
let tree = Tree::new("nonfileuri");
|
||||
tree.package("rtl/open.sv", "open_pkg");
|
||||
let mut session = Session::new(vec![tree.path.clone()], true);
|
||||
session.open(
|
||||
&tree.path.join("rtl/open.sv"),
|
||||
"package open_pkg;\n localparam K = 1;\nendpackage\n",
|
||||
);
|
||||
let _ = session.drain();
|
||||
|
||||
let changes = vec![FileEvent {
|
||||
uri: Uri::from_str("untitled:Untitled-1").expect("uri"),
|
||||
typ: FileChangeType::CREATED,
|
||||
}];
|
||||
session.notify(DidChangeWatchedFiles::METHOD, DidChangeWatchedFilesParams { changes });
|
||||
assert_eq!(session.publishes(), 0);
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
# decomposition-server — TODO §28 Lane C: `lucisv_server`'s `server.rs` and `completion.rs`
|
||||
|
||||
## Goal
|
||||
|
||||
Split the two files every server feature lane collides in — `server.rs`
|
||||
(8 851 lines: 2 558 non-test + 6 293 test) and `completion.rs` (4 178
|
||||
lines: 1 716 + 2 462) — into module directories a human can navigate:
|
||||
`server/`, eleven files each the answer to one question about the request
|
||||
loop, with its tests in `server/tests/`, one file per feature; and
|
||||
`completion/`, six files each one answer the response is built from, with
|
||||
each provider's tests at the foot of the file whose code they pin. A
|
||||
**pure move**: no behaviour change, no renamed item, every path another
|
||||
module of the crate imports preserved by re-exports, test counts
|
||||
identical per binary, the CLI byte-identical against the 0.33.0 baseline,
|
||||
the e2e suite and the vsix smoke unchanged. `perf.rs` (1 189 lines) is
|
||||
left whole, and the reason is below.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- `lucisv_server` is a binary crate (no `lib.rs`); "public path" here
|
||||
means the paths other modules of the crate import.
|
||||
`crate::server::{ClientAbilities, Server}` (used by `main.rs`) stay in
|
||||
`server/mod.rs`; `crate::completion::{completions, plan_for,
|
||||
nearest_definition, at_instantiation_site, layout_at, snippet_hole}`
|
||||
(used by `inline.rs`, `instantiate.rs`, `server/dispatch.rs`) are either
|
||||
still defined in `completion/mod.rs` or re-exported from it with
|
||||
`pub(crate) use`. `completion::module_header` is used only by `perf.rs`,
|
||||
which is itself `#[cfg(test)]`, so its re-export is `#[cfg(test)]` too —
|
||||
an unconditional `pub(crate) use` would be an unused import in every
|
||||
other build, and the comment above it says so. `main.rs` is untouched:
|
||||
`mod server;` and `mod completion;` resolve to the new `mod.rs` files.
|
||||
- Sibling files are private modules; everything a sibling calls is
|
||||
`pub(super)` (taken from the compiler, not guessed: the build was
|
||||
iterated until it named nothing more), and that marking doubles as each
|
||||
file's list of entry points. `Server`'s fields stay private — child
|
||||
modules see their ancestor's private items — so no field widened.
|
||||
`completion::word::Word`'s and `Spine`'s fields are `pub(super)`
|
||||
because every other file reads them.
|
||||
- The server tests are one `#[cfg(test)] mod tests;` in `server/mod.rs`
|
||||
→ `server/tests/mod.rs`, whose sibling files are the sections the one
|
||||
big test module had (same banner names). A helper more than one
|
||||
section used moved to `tests/mod.rs` under a banner saying so; a helper
|
||||
one section used stayed with it. The three production items only the
|
||||
tests reach (`batch::is_shutdown`, `progress::{reports, MAX_REPORTS}`)
|
||||
are `pub(super)` and imported in `tests/mod.rs`, which every test file
|
||||
globs.
|
||||
- The completion tests are in-file (`#[cfg(test)] mod tests` at the foot
|
||||
of each provider) on a shared `#[cfg(test)] mod harness;` — in-file so
|
||||
each file's tests reach its private functions through `use super::*`
|
||||
without a widening for every helper a test touches.
|
||||
- The corpus byte-identity check for this lane is the ten-file sample
|
||||
the brief asks for (this crate does not touch formatting; the release
|
||||
binary is built anyway); opentitan is not run at all.
|
||||
- "Production lines" in the brief's numbers (2 559 / 1 716) count every
|
||||
non-test line, comments included; the tables below use that metric
|
||||
(non-test lines) and give code-only lines beside it.
|
||||
|
||||
## Handshakes
|
||||
|
||||
- **Consumes** (unchanged): everything `server.rs` and `completion.rs`
|
||||
imported before — `crate::{state, settings, format, on_type, tokens,
|
||||
diagnostics, lint, watch, file_ops, candidates, pairs, signature,
|
||||
symbols, templates, uri, …}` and the leaf feature modules the dispatch
|
||||
delegates to.
|
||||
- **Promises** (unchanged): `crate::server::{ClientAbilities, Server}`
|
||||
with `Server::new` and `Server::run` at the same signatures;
|
||||
`crate::completion::{completions, plan_for, nearest_definition,
|
||||
at_instantiation_site, layout_at, snippet_hole}` at the same paths and
|
||||
signatures; `completion::module_header` at the same path in test
|
||||
builds (its only caller is `perf.rs`, `#[cfg(test)]`).
|
||||
- **Requests**: none. Nothing outside `crates/lucisv_server/src/server/`,
|
||||
`crates/lucisv_server/src/completion/`, this README and the Lane C line
|
||||
of `TODO.md` changes. `main.rs`, `perf.rs`, `hover.rs`, `nav.rs`,
|
||||
`inline.rs`, `instantiate.rs`, `ports.rs` and every other file of the
|
||||
crate are byte-identical to 35f0b8d.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] Baseline pinned: per-binary test counts, `cargo doc` item list
|
||||
(667 pages), longest-function census, `/tmp/lucisv-0.33.0-baseline`
|
||||
present and `--version` 0.33.0
|
||||
- [x] `git mv src/server.rs src/server/mod.rs`,
|
||||
`git mv src/completion.rs src/completion/mod.rs`
|
||||
- [x] Tests out of `server.rs` first: `server/tests/{mod + 15 files}.rs`
|
||||
- [x] `server/` production split into eleven files; `cargo build` and
|
||||
`cargo test -p lucisv_server` green after each carve
|
||||
- [x] `completion/` split into six files + `harness.rs`, tests in-file
|
||||
- [x] `perf.rs` left whole (reason in the work log)
|
||||
- [x] Text-level purity: line-multiset check for both files (below)
|
||||
- [x] `cargo test -p lucisv_server` per binary identical to baseline
|
||||
(1435 passed / 34 ignored, 85 / 2, 3)
|
||||
- [x] `cargo fmt -p lucisv_server` (`--check` clean), `cargo clippy
|
||||
--all-targets --workspace` 0 warnings, `cargo doc -p lucisv_server
|
||||
--no-deps` 8 warnings = the 8 pre-existing ones (none in the moved
|
||||
files), `cargo test --workspace` (see work log)
|
||||
- [x] `cargo doc` item list diffed: same items, in the new module pages
|
||||
- [x] e2e (85 passed) and vsix smoke (`node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server` → OK, 20 messages) unchanged
|
||||
- [x] Release `lucisv --version` = 0.33.0, ten corpus files `--stdout`
|
||||
byte-identical (stdout, stderr, exit code) to the baseline binary
|
||||
- [x] `TODO.md` Lane C line ticked
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-09-02 — baseline
|
||||
|
||||
Branch `decomp-server` at 35f0b8d (master with Lane B merged), worktree
|
||||
`.claude/worktrees/decomp-server`.
|
||||
|
||||
Pinned `cargo test -p lucisv_server` (per binary):
|
||||
|
||||
| binary | passed | ignored |
|
||||
|---|---|---|
|
||||
| `src/main.rs` unit tests | 1435 | 34 |
|
||||
| `tests/e2e.rs` | 85 | 2 |
|
||||
| `tests/grammar.rs` | 3 | 0 |
|
||||
| **sum** | **1523** | **36** |
|
||||
|
||||
`cargo doc -p lucisv_server --no-deps`: 667 HTML pages, 8 warnings (all
|
||||
unresolved intra-doc links in `nav.rs`, `state.rs`, `diagnostics.rs`,
|
||||
`lint.rs` — untouched files).
|
||||
|
||||
Longest functions before (brace-matched, whole function incl. comments):
|
||||
|
||||
| file | fn | lines |
|
||||
|---|---|---|
|
||||
| server.rs | `answer_request` | 393 |
|
||||
| server.rs | `handle_notification` | 197 |
|
||||
| server.rs | `started` | 91 |
|
||||
| server.rs | `process_batch` | 58 |
|
||||
| completion.rs | `completions` | 81 |
|
||||
| completion.rs | `member_answer` | 76 |
|
||||
|
||||
Two functions are over 150 lines and both are dispatch tables over a
|
||||
method-name set — `answer_request` over request methods,
|
||||
`handle_notification` over notification methods. They stay whole; each
|
||||
file's module doc says so. Nothing else is over 100. No function was
|
||||
split.
|
||||
|
||||
### 2026-09-02 — `server.rs` → `server/`
|
||||
|
||||
**Method.** `git mv` first so history follows; then every new file was
|
||||
*copied* out of the HEAD blob by a plan of named items (a script resolved
|
||||
`fn name` / `struct name` / `const NAME` to "doc comment through closing
|
||||
brace" and refused any name that matched twice), and `mod.rs` was
|
||||
rewritten wholesale from the items it keeps. Nothing was deleted by
|
||||
script; the proof that nothing was lost is the line-multiset check
|
||||
below. Visibility widenings (`pub(super) `) were inserted one at a time
|
||||
from the compiler's own "is private" list, and the three unused imports
|
||||
that produced were removed by hand. The one code-order edit is
|
||||
`progress.rs`: `progress_on` moved above the in-file `human_size_tests`
|
||||
module, which clippy's `items_after_test_module` asked for.
|
||||
|
||||
**Module map, old `server.rs` line → new file** (production; the file is
|
||||
8 851 lines and the 12–74 `use` block became one per-file block):
|
||||
|
||||
| old lines | what | new file |
|
||||
|---|---|---|
|
||||
| 1–10 | module doc | `mod.rs` (extended with the module map) |
|
||||
| 76–228, 235–253 | `ClientAbilities`, `Server`, `CHANGE_DEBOUNCE`, `INTERLEAVE_ABOVE`, `Pending`, `TokenAnswer` | `mod.rs` |
|
||||
| 230–233 | `INDEXING_TITLE` | `progress.rs` |
|
||||
| 255–555 | `new`, `started`, `run`, `process_batch`, `must_wait`, `index_is_complete` | `mod.rs` |
|
||||
| 557–969 | `request`, `answer_request` | `dispatch.rs` |
|
||||
| 971–1110 | `large_file_answer`, `tokens_declined`, `large_definition`, `large_references`, `large_scan` | `large_file.rs` |
|
||||
| 1112–1256 | `formatting`, `range_formatting`, `ranges_formatting`, `on_type_formatting`, `will_save_wait_until`, `warn_about_config`, `edits` | `formatting.rs` |
|
||||
| 1258–1306 | `deliver`, `show_instantiations` | `client.rs` |
|
||||
| 1308–1354 | `semantic_tokens_full`, `semantic_tokens_delta`, `remember_tokens` | `semantic_tokens.rs` |
|
||||
| 1356–1438 | `document_report`, `workspace_report`, `result_id`, `diagnostics_of` | `diagnostics.rs` |
|
||||
| 1440–1650 | `notification`, `handle_notification` | `notification.rs` |
|
||||
| 1652–1713 | `response`, `applied`, `configured` | `client.rs` |
|
||||
| 1715–1755 | `apply_settings`, `lint_selection` | `notification.rs` |
|
||||
| 1757–1811 | `request_configuration`, `register_watchers`, `send_request` | `client.rs` |
|
||||
| 1813–2099 | `reindex_for`, `reindex_one`, `reindex_widened`, `reindex`, `scan_until_settled`, `scan_once`, `watching`, `answer_what_is_waiting` | `index.rs` |
|
||||
| 2101–2164 | `begin_indexing`, `end_indexing` | `progress.rs` |
|
||||
| 2166–2182 | `refresh_code_lenses` | `client.rs` |
|
||||
| 2184–2195 | `hierarchy_index_changed` | `index.rs` |
|
||||
| 2197–2200 | `progress` | `progress.rs` |
|
||||
| 2202–2233 | `report_scope` | `client.rs` |
|
||||
| 2235–2326 | `set_document`, `mark_dirty`, `flush_dirty`, `announce_fast_path`, `publish`, `send_diagnostics` | `diagnostics.rs` |
|
||||
| 2328–2411 | `show_message`, `notify`, the timing section (`timer`, `timed`, `timing`, `say_held`), `ms`, `plural` | `client.rs` |
|
||||
| 2393–2395 | `offset` | `dispatch.rs` |
|
||||
| 2413–2584 | `MAX_REPORTS`, `reports`, `IndexWatch`, `human_size` + `human_size_tests`, `progress_on` | `progress.rs` |
|
||||
| 2585–2592 | `notify_on` | `client.rs` |
|
||||
| 2594–2765 | cancellation: `is_shutdown`, `forward`, `burst`, `cancelled_in`, `Widen`, `widen_of`, `opened_in`, `cancelled_id`, `cancelled_response` | `batch.rs` |
|
||||
| 2767–2830 | `Failure`, `TOO_LARGE`, `document_uri`, `decode`, `to_value` | `dispatch.rs` |
|
||||
| 2832–2858 | `folder_paths`, `extract`, `closing_uri` | `notification.rs` |
|
||||
| 2860–8851 | `mod tests` | `tests/` (next table) |
|
||||
|
||||
Within a file the order is the original's except where the file's own
|
||||
reading order is better: `diagnostics.rs` reads dirty → analysis → push →
|
||||
pull; `client.rs` reads requests-out → answers-in → messages → timing →
|
||||
the connection-level free functions.
|
||||
|
||||
**Test map, old `server.rs` line → `server/tests/`** (the section banner
|
||||
names are the file docs):
|
||||
|
||||
| old lines | section | new file |
|
||||
|---|---|---|
|
||||
| 2862–3230 | `Tree`, `Session`, `progress_step`, `token_text`, `watching_progress` | `tests/mod.rs` |
|
||||
| 3231–3623 | a scan that answers messages while it runs | `tests/scan.rs` |
|
||||
| 3625–3969 | the indexing bar | `tests/progress.rs` |
|
||||
| 3971–4560 | cache, size cap, file log, one bar per rescan path | `tests/index.rs` |
|
||||
| 4561–4834 | file watchers | `tests/watchers.rs` |
|
||||
| 4835–4976 | `workspace/applyEdit` | `tests/apply_edit.rs` |
|
||||
| 4977–5244 | pull diagnostics | `tests/pull_diagnostics.rs` |
|
||||
| 5245–5707 | `selectionRange`, `linkedEditingRange`, `codeLens`, hierarchy view | `tests/requests.rs` |
|
||||
| 5708–5989 | incremental text sync | `tests/sync.rs` |
|
||||
| 5990–6630 | `onTypeFormatting`, `rangesFormatting`, `willSaveWaitUntil` | `tests/formatting.rs` |
|
||||
| 6631–6984 | semantic tokens | `tests/tokens.rs` |
|
||||
| 6985–7380 | `$/cancelRequest` | `tests/cancel.rs` |
|
||||
| 7381–7552 | file operations | `tests/file_ops.rs` |
|
||||
| 7553–8005 | workspace folders | `tests/folders.rs` |
|
||||
| 8006–8429 | pulled settings | `tests/settings.rs` |
|
||||
| 8430–8850 | the large-file fast path | `tests/large_file.rs` |
|
||||
|
||||
Fifteen helpers were used by more than one section and moved to
|
||||
`tests/mod.rs` under "helpers more than one file uses": `SUB`, `TOP`,
|
||||
`change`, `buffer`, `changed`, `capping`, `pulling`, `document_pull`,
|
||||
`indexed`, `filelist_push`, `wide_ish`, `lens_tree`, `propagating`,
|
||||
`formatting_result`, `configuration_request`. The test bodies were
|
||||
de-indented by four spaces (they left a `mod tests { … }` block for
|
||||
files); rustfmt then re-joined a few dozen lines that now fit in the
|
||||
width, in the tests only.
|
||||
|
||||
**Cuts that differ from the brief, and why.** The brief's list was
|
||||
`{mod, dispatch, lifecycle, diagnostics, workspace, client}`. What the
|
||||
code said:
|
||||
|
||||
- there is no `lifecycle.rs`: `initialize` lives in `main.rs` and
|
||||
`shutdown`/`exit` are two lines of `process_batch`, so the file would
|
||||
have held only the notification dispatch — which is what it is, so it
|
||||
is named `notification.rs`;
|
||||
- `workspace` split in two by what a reader wants: `index.rs` is the
|
||||
rescans (the loop and its four entries), `progress.rs` is the bar and
|
||||
the log they run under — 600 lines together, and the second is about
|
||||
*saying* while the first is about *doing*. Config changes and folder
|
||||
events are notifications and stayed with the dispatch that handles
|
||||
them (`notification.rs`, with `apply_settings`); watcher registration
|
||||
and the settings pull are requests made of the client and went to
|
||||
`client.rs`;
|
||||
- `batch.rs` is new: the forwarder, the burst drain, the cancels and the
|
||||
`didOpen` widen are all "reading a burst before serving it", used by
|
||||
both the loop in `mod.rs` and the mid-scan drain in `index.rs`, so
|
||||
neither could own them;
|
||||
- three small files rather than one `handlers.rs`: `formatting.rs`
|
||||
(170), `large_file.rs` (159), `semantic_tokens.rs` (60). Each is what
|
||||
one feature lane touches on the server side (format-on-save,
|
||||
large-file mode, token deltas) and each is one sentence; a
|
||||
`handlers.rs` would have been three unrelated sentences joined by
|
||||
"and", which is the rule's definition of a file that wants splitting.
|
||||
|
||||
**Line counts after** (non-test lines are the brief's metric; code-only
|
||||
excludes comment lines):
|
||||
|
||||
| file | total | non-test | code-only | one sentence |
|
||||
|---|---|---|---|---|
|
||||
| `server/mod.rs` | 540 | 540 | 215 | the `Server`, what the client can do, the loop and its order contract |
|
||||
| `server/dispatch.rs` | 528 | 528 | 380 | `answer_request`, the table over request methods, and its decoders/`Failure` |
|
||||
| `server/client.rs` | 341 | 341 | 173 | what goes to the client other than a response |
|
||||
| `server/index.rs` | 325 | 325 | 172 | the rescans and what a rebuild owes every open buffer |
|
||||
| `server/notification.rs` | 303 | 303 | 165 | `handle_notification` and the settings applier |
|
||||
| `server/progress.rs` | 272 | 255 | 130 | the indexing bar and the per-file log |
|
||||
| `server/diagnostics.rs` | 206 | 206 | 130 | when a buffer is analyzed and how what it says reaches the client |
|
||||
| `server/batch.rs` | 188 | 188 | 89 | reading a burst before any of it is served |
|
||||
| `server/formatting.rs` | 170 | 170 | 90 | the five formatting entries and their manners |
|
||||
| `server/large_file.rs` | 159 | 159 | 88 | what a large buffer answers instead of the dispatch |
|
||||
| `server/semantic_tokens.rs` | 60 | 60 | 32 | the remembered answer a token delta is computed against |
|
||||
| `server/tests/*.rs` (16 files) | 5 999 | — | — | one file per feature, harness in `mod.rs` |
|
||||
|
||||
No file over 600. Longest functions after: `answer_request` 393
|
||||
(`dispatch.rs`), `handle_notification` 197 (`notification.rs`),
|
||||
`started` 91, `process_batch` 58 (`mod.rs`) — identical to before;
|
||||
`pub(super)` on a signature made rustfmt wrap six of them, nothing else
|
||||
moved a line.
|
||||
|
||||
### 2026-09-02 — `completion.rs` → `completion/`
|
||||
|
||||
Same method. **Module map, old `completion.rs` line → new file:**
|
||||
|
||||
| old lines | what | new file |
|
||||
|---|---|---|
|
||||
| 1–36 | module doc | `mod.rs` (extended with the module map) |
|
||||
| 59–67, 79–96, 111–146 | `LIMIT`, `FUZZY_MIN`, the `TIER_*` consts, `KEEP_MY_INDENTATION` | `mod.rs` |
|
||||
| 69–77, 98–109 | `MODULE_LIMIT`, `HEADER_WINDOWS` | `module.rs` |
|
||||
| 148–170, 172–175, 183–192 | `ITEM_SCOPES`, `NOT_ITEM_SCOPES`, `STATEMENT_SCOPES`, `PROCEDURAL`, `STATEMENT_END` | `site.rs` |
|
||||
| 177–181 | `STATEMENT_HEADS` | `word.rs` |
|
||||
| 194–280 | `completions` | `mod.rs` |
|
||||
| 282–589 | `member_answer`, `Member`, `indexed_detail`, `members_at`, `connection_members`, `connected_names`, `Members`, `last_segment` | `member.rs` |
|
||||
| 591–868 | `module_tier`, `module_detail`, `nearest_definition`, `shared_components`, `plan_for`, `module_header`, `header_from`, `header_end`, `skip_parens`, `skip_to_semicolon` | `module.rs` |
|
||||
| 870–1076 | `scope_tier`, `index_tier`, `template_tier`, `offered`, `layout_at`, `keyword_tier`, `word_tier`, `buffer_words` | `tiers.rs` |
|
||||
| 1078–1242 | `Items`, `completion_kind`, `declaration_detail`, `shorten` | `mod.rs` |
|
||||
| 1244–1272 | `visible_symbols`, `innermost_scope` | `tiers.rs` |
|
||||
| 1274–1325 | `in_comment_or_string`, `in_comment`, `snippet_hole` | `mod.rs` |
|
||||
| 1327–1555 | "where the cursor is": `Word`, `Sep`, `Spine`, `typed_word`, `separator`, `scope_head`, `dot_spine`, `split_ident`, `strip_indices`, `is_ident_char`, `line_head_is_blank` | `word.rs` |
|
||||
| 1557–1715 | `at_instantiation_site`, `line_indent`, `at_module_item`, `at_statement`, `enclosing_scopes`, `is_procedural`, `balanced` | `site.rs` |
|
||||
| 1725–1735, 1801–1892 | `SUB`, `Tree`, `asking`, `opened`, `opened_named`, `items`, `inserted`, `tier`, `skeletons`, `find`, `labels` | `harness.rs` (`#[cfg(test)]`, items `pub(super)`) |
|
||||
| 1736–1761 | interface kinds + `module_detail` card | `module.rs` tests (it reads `module_detail`) |
|
||||
| 1762–1799 | the scope-gate sweeps | `site.rs` tests |
|
||||
| 1893–2439 | tier 0's header slice, planning, `nearest_definition` | `module.rs` tests |
|
||||
| 2441–2447 | `snippet_hole` escaping | `mod.rs` tests |
|
||||
| 2449–2727, 2777–2859, 3163–3460 | templates, keywords, tier order/dedup, fuzzy matching | `tiers.rs` tests |
|
||||
| 2728–2776, 2860–2975, 2976–3162 | comments/strings, backtick, filtering/cap, the perf claims | `mod.rs` tests |
|
||||
| 3461–4177 | the member answer, the connection list | `member.rs` tests |
|
||||
|
||||
**Cuts that differ from the brief, and why.** The brief's list was
|
||||
`{mod, members, modules, templates, keywords, symbols, fuzzy}`:
|
||||
|
||||
- no `fuzzy.rs`: the fuzzy matcher is `candidates.rs`'s `Query`; in this
|
||||
module "fuzzy" is one constant (`FUZZY_MIN`, in `mod.rs`) and a
|
||||
two-arm `match` repeated in each tier, which is not a module;
|
||||
- no `templates.rs`, `keywords.rs`, `symbols.rs`: the template tier is
|
||||
40 lines, the keyword tier 8, and each would have been a file whose
|
||||
only sentence is "one tier". `tiers.rs` holds tiers 1–5 in the order
|
||||
`completions` runs them, which is the sentence a reader wants;
|
||||
- `word.rs` and `site.rs` are new and carry what was the "where the
|
||||
cursor is" banner: what is *typed* (text read backwards from the
|
||||
cursor) and what may be *written* here (the token-stream gates) are
|
||||
two questions with two kinds of code, and `inline.rs`/`instantiate.rs`
|
||||
ask only the second.
|
||||
|
||||
**Line counts after:**
|
||||
|
||||
| file | total | non-test | in-file test | code-only (non-test) | one sentence |
|
||||
|---|---|---|---|---|---|
|
||||
| `completion/mod.rs` | 837 | 464 | 373 | 240 | the entry point, the response under construction, the shared helpers |
|
||||
| `completion/member.rs` | 1 060 | 336 | 724 | 183 | the exclusive member answer after `.`/`::`, connection lists included |
|
||||
| `completion/module.rs` | 913 | 335 | 578 | 146 | tier 0 and the instantiation planning two other modules share |
|
||||
| `completion/tiers.rs` | 941 | 272 | 669 | 183 | tiers 1–5 in the order they fill the response |
|
||||
| `completion/word.rs` | 246 | 246 | 0 | 136 | what is typed at the cursor |
|
||||
| `completion/site.rs` | 264 | 217 | 47 | 129 | what may be written here |
|
||||
| `completion/harness.rs` | 114 | (test) | — | — | the tests' scratch workspace and helpers |
|
||||
|
||||
`mod.rs` is 464 non-test lines by the brief's metric (QA correction,
|
||||
2026-09-02: the work log's original 822/15 split undercounted the
|
||||
in-file `mod tests` block — see QA log) and 240 lines of code. Splitting
|
||||
`Items` out to make the number smaller would put the response builder
|
||||
one file away from the only function that drives it; not done.
|
||||
|
||||
Longest functions after: `completions` 81 (`mod.rs`), `member_answer`
|
||||
76 (`member.rs`) — identical to before.
|
||||
|
||||
**`perf.rs` left whole.** Its one sentence is already on its first line:
|
||||
"Perf measurements for the paths a keystroke and a hover run through."
|
||||
It is `#[cfg(test)]`, every function is one `#[ignore]`d measurement
|
||||
printing a number, and the 1 189 lines are twelve such measurements plus
|
||||
the generated inputs they share. A split "by what it measures" would be
|
||||
two files whose sentences differ only in the noun, sharing the same
|
||||
inputs across a module boundary. The brief said split only if the
|
||||
sentence needs an "and"; it does not.
|
||||
|
||||
### 2026-09-02 — proofs
|
||||
|
||||
**Line multiset** (`scratchpad/multiset.py`: every non-blank line of the
|
||||
HEAD blob, stripped of indentation, `use` statements, visibility
|
||||
keywords, `//!` docs, `// ----` rules, `#[cfg(test)]`, `mod x {`/`impl X
|
||||
{` openers and lone braces, must appear at least as often in the new
|
||||
files):
|
||||
|
||||
- `server.rs`: 7 227 lines → 7 218 present. **Missing: 10**, all of them
|
||||
the banner *title* lines under the `// ----` rules (`// requests`,
|
||||
`// the large-file fast path`, `// semantic tokens`, `// pull
|
||||
diagnostics`, `// notifications`, `// responses to what we asked`,
|
||||
`// outgoing`, `// watching an index rebuild`, `// cancellation`,
|
||||
`// decoding and failures`) — each became the file it names. Extra: 1
|
||||
(the `// helpers more than one file uses` banner in `tests/mod.rs`).
|
||||
- `completion.rs`: 3 303 → 3 304. **Missing: 1**, the `// where the
|
||||
cursor is` banner title (now `word.rs` + `site.rs`). Extra: 2, the
|
||||
two-line comment over the `#[cfg(test)]` re-export of
|
||||
`module_header`.
|
||||
|
||||
The check ran before `cargo fmt`; rustfmt's diff afterwards was the
|
||||
per-file `use` blocks, six `pub(super)` signatures wrapped in the
|
||||
production files, and re-joined lines in the de-indented tests.
|
||||
|
||||
**Counts.** `cargo test -p lucisv_server`: 1435 passed / 34 ignored,
|
||||
85 / 2, 3 / 0 — identical per binary to the baseline. `cargo test
|
||||
--workspace`: see the last entry below.
|
||||
|
||||
**Gates.** `cargo fmt -p lucisv_server -- --check` clean; `cargo clippy
|
||||
--all-targets --workspace` 0 warnings (the one it raised during the
|
||||
work, `items_after_test_module` in `progress.rs`, fixed by moving
|
||||
`progress_on` above the test module); `cargo doc -p lucisv_server
|
||||
--no-deps` 8 warnings — the same 8 unresolved links in `nav.rs`,
|
||||
`state.rs`, `diagnostics.rs`, `lint.rs` the baseline had. Five links
|
||||
that broke because their target moved to a sibling file were
|
||||
re-pointed (`[`LIMIT`](super::LIMIT)` and the like), so none of the
|
||||
moved files warns.
|
||||
|
||||
**Public item list.** `cargo doc` pages: 667 before, 682 after. Diffed
|
||||
by item name the two lists are identical except for 15 added
|
||||
`index.html` — one per new module. Diffed by full path, every moved
|
||||
item appears under its new module page (`server/dispatch/enum.Failure`
|
||||
where it was `server/enum.Failure`) and nothing appears or disappears
|
||||
otherwise. The only paths other files import are unchanged and listed
|
||||
under Handshakes.
|
||||
|
||||
**Behaviour.** `tests/e2e.rs`: 85 passed / 2 ignored (unchanged). vsix
|
||||
smoke: `node editors/vscode/smoke.js target/debug/lucisv-server` → `OK
|
||||
— completed initialize/didOpen/shutdown/exit (20 messages)`. Release
|
||||
`lucisv --version` = `lucisv 0.33.0`, same as `/tmp/lucisv-0.33.0-
|
||||
baseline`; ten corpus files (every 86th of the sorted 860, from
|
||||
`common_cells/formal/counter_properties.sv` to
|
||||
`ibex/vendor/lowrisc_ip/ip/prim_xilinx/rtl/prim_pad_attr.sv`) through
|
||||
`--stdout` on both binaries: 10/10 identical in stdout, stderr and exit
|
||||
code. Opentitan was not touched; `git -C ~/repo/opentitan status
|
||||
--porcelain` shows only the three pre-existing modified files.
|
||||
|
||||
**`pub(super)` census.** 105 markings across the two
|
||||
directories, 14 of them in `completion/harness.rs` (test
|
||||
helpers); every one was demanded by the compiler.
|
||||
|
||||
### 2026-09-02 — `cargo test --workspace`
|
||||
|
||||
48 binaries, **3 215 passed / 0 failed / 40 ignored** — the baseline's 3 215 (the 40 ignored are the 34 + 2 of this crate plus the 4 elsewhere,
|
||||
unchanged). Run after every edit above, on the tree as it is handed over.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-09-02 — independent verification (Sonnet QA)
|
||||
|
||||
All checks run in-tree at `.claude/worktrees/decomp-server`, read-only
|
||||
except the one correction below and the throwaway worktree used for the
|
||||
behavioural diff (removed after use). No `git checkout`/`reset`/`stash`/
|
||||
`clean` run anywhere.
|
||||
|
||||
**1. Gates.**
|
||||
- `cargo fmt -p lucisv_server -- --check`: clean (exit 0).
|
||||
- Forced rebuild (`touch main.rs`) + `cargo clippy --all-targets
|
||||
--workspace`: 0 warnings. `grep -rn '#\[allow'` over
|
||||
`crates/lucisv_server/src/server/` and `.../completion/`: no hits —
|
||||
no new `#[allow]`.
|
||||
- `cargo test --workspace --no-fail-fast`: 48 binaries,
|
||||
**3 215 passed / 0 failed / 40 ignored** — matches the pinned
|
||||
baseline exactly. Per-binary for `lucisv_server`: main.rs unittests
|
||||
1435/34 ignored, `tests/e2e.rs` 85/2 ignored, `tests/grammar.rs` 3/0
|
||||
— all three identical to the README's claim.
|
||||
- `cargo doc -p lucisv_server --no-deps`: 8 warnings, all in untouched
|
||||
files (`diagnostics.rs`, `lint.rs` ×2, `nav.rs`, `state.rs` ×3) — the
|
||||
same 8 the work log names, none in a moved file.
|
||||
- `git status --porcelain`: confined to `crates/lucisv_server/src/`,
|
||||
`docs/features/decomposition-server/`, and `TODO.md` (only the Lane C
|
||||
line — confirmed by `git diff master -- TODO.md`).
|
||||
- `git diff 35f0b8d -- crates/lucisv_server/src/{main,inline,instantiate,
|
||||
perf,hover,nav,state}.rs`: 0 lines for all seven. Confirmed.
|
||||
|
||||
**2. Pure move — independent, from scratch (not the dev's script).**
|
||||
Wrote my own line-multiset checker (strip whole `use …;` blocks
|
||||
including multi-line import lists, `mod x;`, `//!` docs, `// ----`
|
||||
fence lines, lone braces, `impl X {` / `mod x {` openers, normalize
|
||||
leading `pub(…)`), comparing `git show 35f0b8d:…server.rs` against the
|
||||
concatenation of `src/server/**/*.rs`, and `completion.rs` against
|
||||
`src/completion/*.rs`.
|
||||
- `server.rs`: after excluding the 10 banner-title lines, the 6
|
||||
`pub(super)`-triggered signature rewraps (`formatting`,
|
||||
`show_instantiations`, `document_report`, `workspace_report`,
|
||||
`send_request`, `timed` — matches "six … wrapped" in the work log
|
||||
exactly), the one re-pointed `reindex_widened` doc link, and the one
|
||||
extra "helpers more than one file uses" banner, a token-level
|
||||
re-check (ignoring all whitespace) of the remaining ~170/~100
|
||||
one-sided lines found a residual of **10 stray commas vs 7
|
||||
braces/semicolons** — trailing-comma additions/removals from
|
||||
rustfmt re-joining lines that fit once the tests were de-indented.
|
||||
No identifier, no logic token, differs anywhere.
|
||||
- `completion.rs`: 8 missing / 19 extra lines total. All accounted
|
||||
for: the `// where the cursor is` banner (1), two more
|
||||
`pub(super)`-triggered signature rewraps (`module_tier`,
|
||||
`innermost_scope`), three of the five re-pointed doc links
|
||||
(`LIMIT`, `FUZZY_MIN`, `at_instantiation_site`; the other two —
|
||||
`plan_for`/`module_header` and `Server::reindex_widened` — live in
|
||||
`//!` lines or `server.rs` respectively and are excluded/counted
|
||||
there), and the logged 2-line `module_header` re-export comment.
|
||||
Zero unaccounted lines.
|
||||
- **Function-signature census** (independent regex over both trees,
|
||||
not trusting the dev's line-range table): `server.rs` 360 `fn` names
|
||||
→ 360 in `server/**`, exact multiset match, none added/removed/
|
||||
split. `completion.rs` 188 → 188, exact match.
|
||||
- **15 hoisted test helpers**: `grep -rl "fn <name>("` over
|
||||
`server/tests/*.rs` for all 15 (`SUB`/`TOP` are `const`, checked
|
||||
separately) — every one defined in exactly one file
|
||||
(`tests/mod.rs`), confirming the claimed dedup.
|
||||
- **`pub(super)` census**: 62 (server) + 43 (completion) = **105**,
|
||||
exactly the dev's number; 14 of them in `completion/harness.rs`,
|
||||
also exact.
|
||||
- **Test name census**: extracted every `#[test] fn` name from the
|
||||
35f0b8d blobs and diffed against the new trees. `server.rs`: 190
|
||||
names, all 190 present (189 in `server/tests/*.rs` + 1,
|
||||
`the_unit_is_chosen_by_what_the_rounded_number_reads_as`, in
|
||||
`server/progress.rs`'s in-file `human_size_tests` module exactly as
|
||||
the module map says). `completion.rs`: 110/110, exact match, all in
|
||||
`completion/*.rs`.
|
||||
- **Test-body spot-check**: 10 helper/test bodies compared
|
||||
whitespace-normalized across `scan.rs`, `progress.rs`,
|
||||
`watchers.rs`, `apply_edit.rs`, `pull_diagnostics.rs`, `requests.rs`,
|
||||
`sync.rs`, `tests/mod.rs` helpers — 9/10 identical outright; the
|
||||
10th (`a_pulling_client_is_never_pushed_diagnostics`) differs only
|
||||
in a rustfmt-collapsed `session.notify(…)` call losing its trailing
|
||||
comma when its two-line form joined into one after de-indentation —
|
||||
confirmed token-identical otherwise. Same rustfmt artifact as the
|
||||
aggregate multiset check above, not a content change.
|
||||
|
||||
**3. Behaviour.**
|
||||
- `cargo test -p lucisv_server --test e2e`: 85 passed / 2 ignored,
|
||||
standalone run, matches.
|
||||
- `cargo build -p lucisv_server` + `node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: `OK — completed
|
||||
initialize/didOpen/shutdown/exit (20 messages)`.
|
||||
- `cargo build --release -p lucisv`: `lucisv 0.33.0`. Corpus
|
||||
byte-identity: reconstructed the sorted-860-file list myself
|
||||
(`command find corpus -name '*.sv' -o … | sort`, 860 files, first
|
||||
entry `common_cells/formal/counter_properties.sv` matching the work
|
||||
log) and diffed every-86th sample's stdout/stderr/exit code between
|
||||
this build and `/tmp/lucisv-0.33.0-baseline`: **10/10 identical**.
|
||||
(My reconstructed 774th/860th files differ slightly from the two the
|
||||
work log names — `common_cells`/`ibex`/`opentitan`/`picorv32` sort
|
||||
order is locale-sensitive — but since this crate cannot affect the
|
||||
formatter, the exact file identities don't matter; what matters is
|
||||
that all 10 sampled files, whichever they are, are identical.)
|
||||
- **LSP session vs. 35f0b8d**, read-only: built `lucisv_server` in a
|
||||
throwaway worktree at 35f0b8d (created under scratch, `git worktree
|
||||
add`, removed after use — main tree and `decomp-semantic` worktree
|
||||
never touched). Drove both servers with a hand-rolled Node LSP
|
||||
client (`didOpen` on
|
||||
`opentitan/hw/ip/aes/dv/tb/tb.sv`, workspace root
|
||||
`hw/ip/aes` so cross-file resolution actually engages, 3 s settle
|
||||
time for the read-only index scan) then `textDocument/completion`
|
||||
at the `edn_if[0].` site, `hover` and `definition` on the `aes`
|
||||
instantiation's module name, and `documentSymbol`. Filtering out
|
||||
`window/logMessage`/`$/progress` noise (which differed only in
|
||||
`indexing:` vs `cached:` labels — a filesystem index-cache artifact
|
||||
of running two server processes against the same tree, not a code
|
||||
difference), the 7 substantive messages (initialize response, the 4
|
||||
probe responses, `publishDiagnostics`, shutdown) are **byte-for-byte
|
||||
identical** between the two builds. Hover/definition resolved
|
||||
cross-file correctly in both (`aes.sv:9`); completion returned
|
||||
`null` in both (interface member completion needs `edn_if`'s
|
||||
typedef, outside the scoped workspace root — same in both builds,
|
||||
not a regression).
|
||||
- `git -C ~/repo/opentitan status --porcelain`: only the three
|
||||
pre-existing files (`hw/ip/aes/dv/tb/tb.sv`,
|
||||
`hw/top_darjeeling/ip/ast/rtl/ast.sv`,
|
||||
`hw/top_earlgrey/ip/ast/rtl/ast.sv`). No new modification —
|
||||
confirmed both before and after the LSP session.
|
||||
|
||||
**4. Size rule.** Independent per-file line count (own script: total
|
||||
lines, and a proper character-level scan for `#[cfg(test)]` item
|
||||
spans — attribute-line-to-`;` for a bare `mod x;`/`use` item,
|
||||
attribute-line-to-matching-brace otherwise) plus a from-scratch longest
|
||||
`fn` by brace-matching.
|
||||
- All 11 `server/*.rs` total line counts match the work log exactly
|
||||
(`mod.rs` 540, `dispatch.rs` 528, … `semantic_tokens.rs` 60); no file
|
||||
over 600. Longest functions confirmed identical to baseline:
|
||||
`answer_request` 393/394 (one extra line is the `pub(super)` keyword
|
||||
itself, expected), `handle_notification` 197/198 likewise, `started`
|
||||
91, `process_batch` reported separately — all dispatch tables or
|
||||
under the 150-line threshold, matches.
|
||||
- `completion/{member,module,site,tiers,word}.rs` and `harness.rs`:
|
||||
every total/non-test/in-file-test number matches the work log
|
||||
exactly, and I confirmed each file's single `#[cfg(test)] mod tests`
|
||||
block genuinely runs to true EOF (no truncation) before trusting the
|
||||
match.
|
||||
- **Finding (MEDIUM) — `completion/mod.rs` line count row was wrong.**
|
||||
The work log's table (837 total / 822 non-test / 15 in-file-test /
|
||||
515 code-only) undercounts the in-file test block by ~354 lines.
|
||||
Reproduction: `mod tests { … }` in `crates/lucisv_server/src/
|
||||
completion/mod.rs` actually runs from the `#[cfg(test)]` at line 469
|
||||
to the file's closing `}` at line 837 (369 lines, 14 `#[test]`
|
||||
functions, confirmed by `grep -c '#\[test\]'` and manual read) — not
|
||||
15 lines. Both the dev's counting script and my first attempt at one
|
||||
hit the same bug: a naive brace-counter doesn't understand Rust
|
||||
string-literal contents, and the test
|
||||
`a_tabstop_default_is_escaped_so_the_snippet_grammar_cannot_read_it`
|
||||
(line ~478) contains `"a}b\\c"` and `"${4:a\\}b\\\\c}"` — literal
|
||||
`}` characters inside string literals — which drive a naive
|
||||
per-character `{`/`}` counter back to net-zero depth 15 lines into a
|
||||
369-line block. Corrected numbers, computed with the true block
|
||||
boundary: **total 837, non-test 464, in-file-test 373, code-only
|
||||
240**. This does not change the size-rule verdict (464 is still
|
||||
comfortably under the 600 target, no split needed) and does not
|
||||
affect the pure-move verification above (that check operates on raw
|
||||
line/token multisets across the whole file, unaffected by the
|
||||
test/production split). It is a documentation-accuracy issue only —
|
||||
fixed directly in the table and the paragraph below it per the QA
|
||||
small-fix allowance, since the correct number is mechanically
|
||||
verifiable and unambiguous. All four other completion files' single
|
||||
`#[cfg(test)]` block was confirmed (by checking the skip range's end
|
||||
line equals the file's total line count) to run cleanly to true EOF,
|
||||
so this bug is isolated to `mod.rs`.
|
||||
- One-sentence test: every file's stated sentence matches what it
|
||||
actually contains, spot-checked by reading each file's public items
|
||||
against its "one sentence" column. No "and" files. `perf.rs`'s
|
||||
stay-whole reason holds (verified unchanged, `#[cfg(test)]`, single
|
||||
topic).
|
||||
|
||||
**5. Docs.** All required README sections present (Goal, Assumptions,
|
||||
Handshakes, Status/TODO, Work log, QA log, Review-reserved). Five line
|
||||
ranges from each module map (server: 557, 971, 1813, 2413, 2767;
|
||||
completion: 69, 177, 591, 1327, 1557) diffed against
|
||||
`git show 35f0b8d:…` — all ten match exactly.
|
||||
|
||||
**Fix applied directly**: corrected the `completion/mod.rs` row in the
|
||||
line-counts table (§ "`completion.rs` → `completion/`" work log
|
||||
section) from `837 | 822 | 15 | 515` to `837 | 464 | 373 | 240`, and
|
||||
rewrote the paragraph beneath it that referenced the wrong non-test/
|
||||
code-only split, per the finding above.
|
||||
|
||||
**Verdict: PASS.** No HIGH or CRITICAL findings. One MEDIUM
|
||||
(documentation line-count error in the `completion/mod.rs` table row,
|
||||
fixed directly above) and no LOW findings beyond that. The pure-move
|
||||
claim is independently verified at the line-multiset, token, function-
|
||||
signature, `pub(super)`, test-name, and test-body level; behaviour
|
||||
(e2e, vsix smoke, corpus byte-identity, and a live read-only LSP
|
||||
session against opentitan compared byte-for-byte against a 35f0b8d
|
||||
baseline build) is unchanged; the opentitan tree carries no
|
||||
modification beyond the three pre-existing files.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-09-02 — lead.** Accepted; merged onto master after lanes A and B.
|
||||
The server split is the one that pays back fastest: 6 000 test lines
|
||||
out of the way of 2 500 production lines, and then eleven files where
|
||||
"what does this do" has a one-sentence answer — the loop, the dispatch
|
||||
table, what goes to the client, the rescans, the notifications, the
|
||||
progress bar, diagnostics, batching, and three feature lanes. The cuts
|
||||
that differ from the plan are argued from the code (no `lifecycle`
|
||||
because initialize lives in `main.rs`; `index` + `progress` instead of
|
||||
`workspace`; `batch` on its own), and the completion providers are
|
||||
grouped by what they answer rather than by the sketch's names, which
|
||||
was a sketch. `perf.rs` left whole with the one-sentence test passed is
|
||||
the rule applied honestly. Proof: counts identical, 105 `pub(super)`
|
||||
markings each demanded by the compiler, a from-scratch signature and
|
||||
multiset census by QA, a live LSP session against opentitan producing
|
||||
byte-identical responses from this build and the base. QA's MEDIUM (a
|
||||
brace-counter fooled by a `}` inside a string literal — a good catch,
|
||||
and the kind of thing that argues for counting with a parser) fixed in
|
||||
the README by QA.
|
||||
Reference in new issue
Block a user