LSP §9b: semantic tokens range + full/delta
tokens.rs is now one tokenizer behind three pure steps — absolute() classifies and splits, within() filters by overlap, encode() delta- encodes — so textDocument/semanticTokens/range and /full share one implementation and cannot drift; QA proved the refactor byte-identical to the old encoder over a 41k-token corpus file against the pre-change binary. Range answers are self-contained (overlapping tokens kept whole, re-encoded from the document start) and carry no resultId — a delta never diffs against a partial view. /full/delta remembers each open buffer's last answer under a per-answer id (dropped on didClose; stale or foreign ids answer full) and diffs by common-prefix/suffix trim to a single edit, the suffix counted over what the prefix left — the classic overlap trap, deliberately broken by dev and QA separately and caught by the suite both times. Edit indices are wire-array u32 positions (5 per token), pinned. No token request touches the pull-diagnostics generation. 38 tests added (dev 29 + QA 9), including two independently written edit appliers cross-checked over 200 random pairs and two differently seeded randomized sweeps through the real tokenizer. docs/features/semantic-tokens-delta/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
80b9afdfe3
commit
00c03eccf9
7 files changed
+1732
-43
No files matched your search
@@ -716,9 +716,24 @@ and are not gaps.
|
||||
settings ladder minus its `tabSize` rung because the request carries no
|
||||
`FormattingOptions`. Every save reason formats; an unopened buffer and
|
||||
the off state both answer `null`.
|
||||
- [ ] **Semantic tokens `range` + `full/delta`** — we set
|
||||
- [x] **Semantic tokens `range` + `full/delta`** — we set
|
||||
`range: None` and no delta, so clients re-request whole-file token
|
||||
sets on every edit. Delta needs `resultId` bookkeeping per buffer.
|
||||
→ `docs/features/semantic-tokens-delta/README.md`; `tokens.rs` split
|
||||
into classification → absolute form → filter → one pure encoder, so
|
||||
all three requests share a tokenizer. `range: Some(true)` answers the
|
||||
overlapping tokens whole, **re-encoded from the start of the
|
||||
document** (a range answer is self-contained, not a slice), carries
|
||||
no `resultId` and is not what a later delta diffs against; an empty
|
||||
range answers nothing. `full: Delta { delta: true }` answers one
|
||||
`SemanticTokensEdit` replacing everything between the common prefix
|
||||
and the common suffix — **the suffix capped to what the prefix left**,
|
||||
because identical lines of Verilog encode identically and an uncapped
|
||||
suffix claims the same tokens twice. `resultId`s are minted per
|
||||
answer, stored by `full` and `full/delta` alike, dropped on
|
||||
`didClose`; an id the server does not hold is answered in full. No
|
||||
token request bumps the diagnostics generation. Not done:
|
||||
`workspace/semanticTokens/refresh`.
|
||||
- [ ] **Work-done progress** — `reindex()` is a synchronous full
|
||||
rescan on every save with no `window/workDoneProgress` reporting;
|
||||
on a big filelist the server just goes quiet.
|
||||
|
||||
@@ -221,8 +221,16 @@ fn capabilities() -> ServerCapabilities {
|
||||
token_types: tokens::token_types(),
|
||||
token_modifiers: tokens::token_modifiers(),
|
||||
},
|
||||
range: None,
|
||||
full: Some(SemanticTokensFullOptions::Bool(true)),
|
||||
// The visible lines, for the first paint of a large file:
|
||||
// the same tokenizer, filtered, and re-encoded from the
|
||||
// start of the document so the answer stands on its own.
|
||||
range: Some(true),
|
||||
// `delta: true` rather than a bare `full: true`, so a client
|
||||
// that has an answer already asks what changed instead of
|
||||
// re-fetching the file's whole token set on every keystroke.
|
||||
// `full` itself stays served — the enum's `Delta` variant is
|
||||
// the full capability plus deltas, not a replacement.
|
||||
full: Some(SemanticTokensFullOptions::Delta { delta: Some(true) }),
|
||||
},
|
||||
)),
|
||||
..Default::default()
|
||||
@@ -328,6 +336,20 @@ mod tests {
|
||||
assert!(caps.diagnostic_provider.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_semantic_token_capability_asks_for_ranges_and_for_deltas() {
|
||||
// A client keys entirely off this: it sends `full/delta` only where
|
||||
// `full.delta` is `true`, and `range` only where `range` is.
|
||||
let Some(SemanticTokensServerCapabilities::SemanticTokensOptions(options)) =
|
||||
capabilities().semantic_tokens_provider
|
||||
else {
|
||||
panic!("the options form, not a registration");
|
||||
};
|
||||
assert_eq!(options.range, Some(true));
|
||||
assert_eq!(options.full, Some(SemanticTokensFullOptions::Delta { delta: Some(true) }));
|
||||
assert_eq!(options.legend.token_types.len(), 14, "the legend is unchanged");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_sync_options_ask_for_the_save_hook_and_not_the_notification() {
|
||||
let Some(TextDocumentSyncCapability::Options(options)) = capabilities().text_document_sync
|
||||
|
||||
@@ -20,7 +20,8 @@ use lsp_types::request::{
|
||||
DocumentHighlightRequest, DocumentLinkRequest, DocumentSymbolRequest, ExecuteCommand,
|
||||
FoldingRangeRequest, Formatting, GotoDefinition, HoverRequest, InlayHintRequest,
|
||||
InlineCompletionRequest, PrepareRenameRequest, RangeFormatting, References, RegisterCapability,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullRequest, SignatureHelpRequest,
|
||||
Rename, Request as _, SelectionRangeRequest, SemanticTokensFullDeltaRequest,
|
||||
SemanticTokensFullRequest, SemanticTokensRangeRequest, SignatureHelpRequest,
|
||||
UnregisterCapability, WillSaveWaitUntil, WorkspaceDiagnosticRequest, WorkspaceSymbolRequest,
|
||||
};
|
||||
use lsp_types::{
|
||||
@@ -36,7 +37,9 @@ use lsp_types::{
|
||||
InlineCompletionParams, LogMessageParams, MessageType, Position, PreviousResultId,
|
||||
PublishDiagnosticsParams, ReferenceParams, RegistrationParams,
|
||||
RelatedFullDocumentDiagnosticReport, RelatedUnchangedDocumentDiagnosticReport, RenameParams,
|
||||
SelectionRangeParams, SemanticTokensParams, SemanticTokensResult, ShowMessageParams,
|
||||
SelectionRangeParams, SemanticToken, SemanticTokens, SemanticTokensDelta,
|
||||
SemanticTokensDeltaParams, SemanticTokensFullDeltaResult, SemanticTokensParams,
|
||||
SemanticTokensRangeParams, SemanticTokensRangeResult, SemanticTokensResult, ShowMessageParams,
|
||||
SignatureHelpParams, TextDocumentPositionParams, UnchangedDocumentDiagnosticReport,
|
||||
UnregistrationParams, Uri, WillSaveTextDocumentParams, WorkspaceDiagnosticParams,
|
||||
WorkspaceDiagnosticReport, WorkspaceDiagnosticReportResult, WorkspaceDocumentDiagnosticReport,
|
||||
@@ -100,6 +103,22 @@ pub struct Server {
|
||||
/// buffer's text, and the workspace index. It is the whole of a
|
||||
/// diagnostic `resultId`; see `docs/features/pull-diagnostics/README.md`.
|
||||
generation: 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,
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
@@ -120,6 +139,8 @@ impl Server {
|
||||
request_ids: 0,
|
||||
applying: HashMap::new(),
|
||||
generation: 0,
|
||||
tokens: HashMap::new(),
|
||||
token_results: 0,
|
||||
};
|
||||
server.report_scope(warnings);
|
||||
// The earliest legal moment: `main` builds this only after
|
||||
@@ -227,10 +248,30 @@ impl Server {
|
||||
}),
|
||||
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`.
|
||||
SemanticTokensRangeRequest::METHOD => {
|
||||
decode(request).and_then(|p: SemanticTokensRangeParams| {
|
||||
match self.workspace.document(&p.text_document.uri) {
|
||||
Some(doc) => {
|
||||
to_value(SemanticTokensResult::Tokens(tokens::semantic_tokens(doc)))
|
||||
}
|
||||
Some(doc) => to_value(SemanticTokensRangeResult::Tokens(SemanticTokens {
|
||||
result_id: None,
|
||||
data: tokens::semantic_tokens_in_range(doc, p.range),
|
||||
})),
|
||||
None => Ok(Value::Null),
|
||||
}
|
||||
})
|
||||
@@ -521,6 +562,54 @@ impl Server {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// semantic tokens
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// 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.
|
||||
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.
|
||||
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
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// pull diagnostics
|
||||
// ------------------------------------------------------------------
|
||||
@@ -689,6 +778,10 @@ impl Server {
|
||||
if let Ok(p) = extract::<DidCloseTextDocumentParams>(notification) {
|
||||
let uri = p.text_document.uri;
|
||||
self.config_warnings.remove(&uri);
|
||||
// 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());
|
||||
@@ -2308,4 +2401,358 @@ mod tests {
|
||||
assert_eq!(third, serde_json::json!([]));
|
||||
assert!(session.shown().is_empty(), "only now does the warning stop repeating");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,18 @@
|
||||
//! `textDocument/semanticTokens/full`.
|
||||
//! `textDocument/semanticTokens/full`, `/range` and `/full/delta`.
|
||||
//!
|
||||
//! Classification comes from the lexer's token stream, refined for plain
|
||||
//! identifiers by `vlog_semantic`. The full mapping table is in
|
||||
//! `docs/features/lucisv-server/README.md`.
|
||||
//! `docs/features/lucisv-server/README.md`; the range and delta rules are in
|
||||
//! `docs/features/semantic-tokens-delta/README.md`.
|
||||
//!
|
||||
//! One tokenizer and one encoder serve all three requests: classification
|
||||
//! produces [`Absolute`] tokens (line, column, length — the coordinates the
|
||||
//! protocol thinks in), a range answer drops the ones it does not want, and
|
||||
//! `encode` delta-encodes whatever is left from the start of the document.
|
||||
|
||||
use lsp_types::{SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokens};
|
||||
use lsp_types::{
|
||||
Position, Range, SemanticToken, SemanticTokenModifier, SemanticTokenType, SemanticTokensEdit,
|
||||
};
|
||||
use vlog_parser::token::{Token, TokenKind};
|
||||
use vlog_parser::TextRange;
|
||||
use vlog_semantic::{Semantics, SymbolKind};
|
||||
@@ -68,12 +76,53 @@ struct Piece {
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
/// One classified token in the protocol's own coordinates: a zero-based line,
|
||||
/// a UTF-16 start column and a UTF-16 length. This is the form the range
|
||||
/// filter works in, and the only input `encode` has.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct Absolute {
|
||||
line: u32,
|
||||
start: u32,
|
||||
length: u32,
|
||||
ty: u32,
|
||||
modifiers: u32,
|
||||
}
|
||||
|
||||
impl Absolute {
|
||||
/// Where this token starts, as the protocol names it.
|
||||
fn from(&self) -> Position {
|
||||
Position { line: self.line, character: self.start }
|
||||
}
|
||||
|
||||
/// Where it ends. A token never spans a line break (see `split_lines`), so
|
||||
/// this is on the same line.
|
||||
fn to(&self) -> Position {
|
||||
Position { line: self.line, character: self.start + self.length }
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify and encode the whole buffer.
|
||||
///
|
||||
/// A buffer that does not lex has no tokens, so this is empty — the user sees
|
||||
/// the editor's own grammar highlighting plus the parse diagnostic, which is
|
||||
/// the honest answer while the file is unlexable.
|
||||
pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
pub fn semantic_tokens(doc: &Document) -> Vec<SemanticToken> {
|
||||
encode(&absolute(doc))
|
||||
}
|
||||
|
||||
/// The tokens a range covers, encoded as a self-contained answer.
|
||||
///
|
||||
/// The protocol asks for a whole `SemanticTokens` here, not a slice of the
|
||||
/// full one: the relative encoding restarts from the start of the document
|
||||
/// exactly as a full answer's does, and only the tokens outside the range are
|
||||
/// missing. A token that merely overlaps the range is kept whole — the client
|
||||
/// asked which tokens to draw, not where to cut them.
|
||||
pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
encode(&within(absolute(doc), range))
|
||||
}
|
||||
|
||||
/// Classify the whole buffer, split at line boundaries, in wire order.
|
||||
fn absolute(doc: &Document) -> Vec<Absolute> {
|
||||
let mut pieces = Vec::new();
|
||||
for token in &doc.tokens {
|
||||
collect_trivia(token, &mut pieces);
|
||||
@@ -85,7 +134,21 @@ pub fn semantic_tokens(doc: &Document) -> SemanticTokens {
|
||||
});
|
||||
}
|
||||
}
|
||||
encode(pieces, doc)
|
||||
flatten(pieces, doc)
|
||||
}
|
||||
|
||||
/// The tokens overlapping `range`, in the order they came in.
|
||||
///
|
||||
/// Overlap, not containment: a client sends the lines it is showing, and a
|
||||
/// token straddling the first of them is one the user can see. An **empty**
|
||||
/// range covers no characters, so it overlaps nothing — the containment test
|
||||
/// below would otherwise answer with every token the collapsed point sits
|
||||
/// inside.
|
||||
fn within(tokens: Vec<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
if range.start >= range.end {
|
||||
return Vec::new();
|
||||
}
|
||||
tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect()
|
||||
}
|
||||
|
||||
/// Comments live as trivia on the token that follows (or, for a trailing
|
||||
@@ -162,14 +225,15 @@ fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
}
|
||||
}
|
||||
|
||||
/// Split every piece at line boundaries, sort, and delta-encode.
|
||||
/// Split every piece at line boundaries, measure it in UTF-16 units, and
|
||||
/// sort.
|
||||
///
|
||||
/// The spec forbids a token from spanning a line break, and Verilog has three
|
||||
/// shapes that would: a block comment, a continued `` `define`` and a
|
||||
/// multi-line macro invocation.
|
||||
fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
fn flatten(pieces: Vec<Piece>, doc: &Document) -> Vec<Absolute> {
|
||||
let positions = doc.positions();
|
||||
let mut flat: Vec<(u32, u32, u32, u32, u32)> = Vec::new();
|
||||
let mut flat: Vec<Absolute> = Vec::new();
|
||||
for piece in pieces {
|
||||
for line_span in split_lines(&doc.text, piece.span) {
|
||||
let start = positions.position(line_span.start);
|
||||
@@ -177,33 +241,78 @@ fn encode(pieces: Vec<Piece>, doc: &Document) -> SemanticTokens {
|
||||
if end.character <= start.character {
|
||||
continue;
|
||||
}
|
||||
flat.push((
|
||||
start.line,
|
||||
start.character,
|
||||
end.character - start.character,
|
||||
piece.ty as u32,
|
||||
piece.modifiers,
|
||||
));
|
||||
flat.push(Absolute {
|
||||
line: start.line,
|
||||
start: start.character,
|
||||
length: end.character - start.character,
|
||||
ty: piece.ty as u32,
|
||||
modifiers: piece.modifiers,
|
||||
});
|
||||
}
|
||||
}
|
||||
flat.sort_by_key(|&(line, start, ..)| (line, start));
|
||||
flat.sort_by_key(|t| (t.line, t.start));
|
||||
flat
|
||||
}
|
||||
|
||||
let mut data = Vec::with_capacity(flat.len());
|
||||
/// Delta-encode, from the start of the document.
|
||||
///
|
||||
/// Pure: the same tokens always encode the same way, whether they are the
|
||||
/// whole file's or the handful a range kept.
|
||||
fn encode(tokens: &[Absolute]) -> Vec<SemanticToken> {
|
||||
let mut data = Vec::with_capacity(tokens.len());
|
||||
let (mut prev_line, mut prev_start) = (0u32, 0u32);
|
||||
for (line, start, length, ty, modifiers) in flat {
|
||||
let delta_line = line - prev_line;
|
||||
let delta_start = if delta_line == 0 { start - prev_start } else { start };
|
||||
for token in tokens {
|
||||
let delta_line = token.line - prev_line;
|
||||
let delta_start = if delta_line == 0 { token.start - prev_start } else { token.start };
|
||||
data.push(SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: ty,
|
||||
token_modifiers_bitset: modifiers,
|
||||
length: token.length,
|
||||
token_type: token.ty,
|
||||
token_modifiers_bitset: token.modifiers,
|
||||
});
|
||||
prev_line = line;
|
||||
prev_start = start;
|
||||
prev_line = token.line;
|
||||
prev_start = token.start;
|
||||
}
|
||||
SemanticTokens { result_id: None, data }
|
||||
data
|
||||
}
|
||||
|
||||
/// How many numbers one token is on the wire. An edit's `start` and
|
||||
/// `deleteCount` index that flat array, not the token list.
|
||||
const FIELDS: u32 = 5;
|
||||
|
||||
/// The edits that turn `old` into `new`: one replacement of everything
|
||||
/// between the common prefix and the common suffix, or none at all when the
|
||||
/// two are identical.
|
||||
///
|
||||
/// **Minimality beyond the prefix/suffix trim is deliberately not attempted.**
|
||||
/// A real diff would find the two edits an insertion in the middle of a file
|
||||
/// really is, but every token after an edit carries a changed `deltaLine`
|
||||
/// anyway, so the interesting cases — typing at the end of a line, or on a
|
||||
/// line — trim to almost nothing regardless. rust-analyzer answers the same
|
||||
/// way, and the invariant that matters is that applying the result
|
||||
/// reproduces `new` exactly.
|
||||
pub fn delta(old: &[SemanticToken], new: &[SemanticToken]) -> Vec<SemanticTokensEdit> {
|
||||
let prefix = old.iter().zip(new).take_while(|(a, b)| a == b).count();
|
||||
// The suffix is counted over what the prefix left, never over the whole
|
||||
// vectors: two token lists that repeat themselves — which identical lines
|
||||
// of Verilog produce exactly — would otherwise claim the same tokens as
|
||||
// both prefix and suffix, and the edit would delete a region it also
|
||||
// re-inserts (or, with the subtraction underflowing, not be computable at
|
||||
// all). This overlap is the classic bug in this algorithm.
|
||||
let (old_rest, new_rest) = (&old[prefix..], &new[prefix..]);
|
||||
let suffix =
|
||||
old_rest.iter().rev().zip(new_rest.iter().rev()).take_while(|(a, b)| a == b).count();
|
||||
let deleted = old_rest.len() - suffix;
|
||||
let inserted = &new_rest[..new_rest.len() - suffix];
|
||||
if deleted == 0 && inserted.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
vec![SemanticTokensEdit {
|
||||
start: prefix as u32 * FIELDS,
|
||||
delete_count: deleted as u32 * FIELDS,
|
||||
data: Some(inserted.to_vec()),
|
||||
}]
|
||||
}
|
||||
|
||||
/// One span per line the span touches, each stopping before the `\n`.
|
||||
@@ -231,17 +340,30 @@ mod tests {
|
||||
use crate::state::Workspace;
|
||||
use lsp_types::Uri;
|
||||
use std::str::FromStr;
|
||||
use vlog_semantic::WorkspaceIndex;
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
/// Analyze `text` as an open buffer and hand the document to `f`.
|
||||
fn with_document<T>(text: &str, f: impl FnOnce(&Document) -> T) -> T {
|
||||
let uri = Uri::from_str("file:///rtl/m.sv").expect("uri");
|
||||
let mut ws = Workspace::default();
|
||||
ws.set_document(uri.clone(), text.to_string());
|
||||
let tokens = semantic_tokens(ws.document(&uri).expect("open"));
|
||||
f(ws.document(&uri).expect("open"))
|
||||
}
|
||||
|
||||
/// The whole buffer's tokens, as they go on the wire.
|
||||
fn tokens_of(text: &str) -> Vec<SemanticToken> {
|
||||
with_document(text, semantic_tokens)
|
||||
}
|
||||
|
||||
/// The tokens a range answer carries.
|
||||
fn ranged(text: &str, range: Range) -> Vec<SemanticToken> {
|
||||
with_document(text, |doc| semantic_tokens_in_range(doc, range))
|
||||
}
|
||||
|
||||
/// Decode the delta encoding back to absolute (line, start, len, type).
|
||||
fn decode(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
let (mut line, mut start) = (0u32, 0u32);
|
||||
tokens
|
||||
.data
|
||||
.iter()
|
||||
data.iter()
|
||||
.map(|t| {
|
||||
line += t.delta_line;
|
||||
start = if t.delta_line == 0 { start + t.delta_start } else { t.delta_start };
|
||||
@@ -250,6 +372,18 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn decoded(text: &str) -> Vec<(u32, u32, u32, u32, u32)> {
|
||||
decode(&tokens_of(text))
|
||||
}
|
||||
|
||||
/// A range, spelled the way a test reads best.
|
||||
fn range(from: (u32, u32), to: (u32, u32)) -> Range {
|
||||
Range {
|
||||
start: Position { line: from.0, character: from.1 },
|
||||
end: Position { line: to.0, character: to.1 },
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keywords_numbers_and_strings_are_classified() {
|
||||
let out = decoded("module m;\n localparam W = 8;\n wire a = \"s\";\nendmodule\n");
|
||||
@@ -358,4 +492,487 @@ mod tests {
|
||||
vec![TextRange::new(0, 1), TextRange::new(2, 3)]
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/range`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Four lines, every one of them carrying tokens.
|
||||
const FOUR_LINES: &str =
|
||||
"module m;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n// tail\n";
|
||||
|
||||
#[test]
|
||||
fn a_range_covering_everything_is_the_full_answer() {
|
||||
let full = tokens_of(FOUR_LINES);
|
||||
assert_eq!(ranged(FOUR_LINES, range((0, 0), (99, 0))), full);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_re_encodes_from_the_start_of_the_document() {
|
||||
// The whole point of the re-encoding: a range answer is a
|
||||
// self-contained `SemanticTokens`, so its first token's deltas are
|
||||
// absolute — a client that pasted the slice out of the full answer
|
||||
// would draw line 2's tokens on line 0.
|
||||
let data = ranged(FOUR_LINES, range((2, 0), (3, 0)));
|
||||
let first = data.first().expect("line 2 has tokens");
|
||||
assert_eq!(first.delta_line, 2, "absolute from the document start");
|
||||
assert_eq!(first.delta_start, 2, "the `wire` keyword's own column");
|
||||
assert_eq!(
|
||||
decode(&data),
|
||||
decoded(FOUR_LINES).into_iter().filter(|&(line, ..)| line == 2).collect::<Vec<_>>(),
|
||||
"the same tokens the full answer puts on that line"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_range_covers_no_characters_and_so_no_tokens() {
|
||||
// Collapsed on a token, which is the tempting case to get wrong: a
|
||||
// zero-width range draws nothing, so it must answer nothing.
|
||||
assert!(ranged(FOUR_LINES, range((0, 3), (0, 3))).is_empty());
|
||||
assert!(ranged(FOUR_LINES, range((0, 0), (0, 0))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_that_starts_mid_token_keeps_that_token_whole() {
|
||||
// The client asked which tokens to draw, not where to cut them —
|
||||
// and a length trimmed to the range would be a lie about the source.
|
||||
let data = ranged("module m;\nendmodule\n", range((0, 3), (0, 4)));
|
||||
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_touching_no_token_is_empty() {
|
||||
// Wholly inside the whitespace of a line, and wholly past the file.
|
||||
assert!(ranged("module m;\n\n\nendmodule\n", range((1, 0), (2, 0))).is_empty());
|
||||
assert!(ranged(FOUR_LINES, range((90, 0), (99, 0))).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_range_answer_never_carries_a_token_from_outside_it() {
|
||||
let inside = decode(&ranged(FOUR_LINES, range((1, 0), (2, 0))));
|
||||
assert!(!inside.is_empty(), "premise: line 1 has tokens");
|
||||
assert!(inside.iter().all(|&(line, ..)| line == 1), "{inside:?}");
|
||||
}
|
||||
|
||||
/// The range/full agreement, on files nobody wrote to exercise it: for a
|
||||
/// window of whole lines, the range answer must decode to exactly the
|
||||
/// tokens the full answer puts on those lines. Stated line-wise rather
|
||||
/// than with the handler's own overlap test, so the two are independent.
|
||||
/// Skipped when `corpus/` is not checked out, like every other corpus
|
||||
/// test in this crate.
|
||||
#[test]
|
||||
fn a_line_window_answers_exactly_the_full_answers_tokens_on_those_lines() {
|
||||
let corpus = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../corpus");
|
||||
if !corpus.is_dir() {
|
||||
eprintln!("corpus/ not checked out — skipping");
|
||||
return;
|
||||
}
|
||||
let files =
|
||||
[corpus.join("picorv32/picorv32.v"), corpus.join("common_cells/src/fifo_v3.sv")];
|
||||
let mut windows_checked = 0;
|
||||
for path in files {
|
||||
let Ok(text) = std::fs::read_to_string(&path) else {
|
||||
eprintln!("{} not checked out — skipping", path.display());
|
||||
continue;
|
||||
};
|
||||
let doc = Document::new(Some(path.clone()), text, &WorkspaceIndex::default());
|
||||
let full = decode(&semantic_tokens(&doc));
|
||||
assert!(!full.is_empty(), "{}: the premise, a file with tokens", path.display());
|
||||
let last = full.iter().map(|&(line, ..)| line).max().unwrap_or(0);
|
||||
// Forty-line windows, the size an editor's viewport request is.
|
||||
let mut from = 0;
|
||||
while from <= last {
|
||||
let to = from + 40;
|
||||
let window = decode(&semantic_tokens_in_range(&doc, range((from, 0), (to, 0))));
|
||||
let expected: Vec<_> =
|
||||
full.iter().filter(|&&(line, ..)| line >= from && line < to).copied().collect();
|
||||
assert_eq!(window, expected, "{}: lines {from}..{to}", path.display());
|
||||
windows_checked += 1;
|
||||
from = to;
|
||||
}
|
||||
}
|
||||
assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// `semanticTokens/full/delta`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The flat `u32` array the wire actually carries — what an edit's
|
||||
/// `start` and `deleteCount` index into.
|
||||
fn flat(tokens: &[SemanticToken]) -> Vec<u32> {
|
||||
tokens
|
||||
.iter()
|
||||
.flat_map(|t| {
|
||||
[t.delta_line, t.delta_start, t.length, t.token_type, t.token_modifiers_bitset]
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Apply the edits exactly as a client does: in order, by index, on the
|
||||
/// flat array. Deliberately shares no code with `delta`.
|
||||
fn apply_edits(old: &[u32], edits: &[SemanticTokensEdit]) -> Vec<u32> {
|
||||
let mut data = old.to_vec();
|
||||
for edit in edits {
|
||||
let start = edit.start as usize;
|
||||
let end = start + edit.delete_count as usize;
|
||||
let inserted = flat(edit.data.as_deref().unwrap_or_default());
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// The invariant: applying what the server sent reproduces the new token
|
||||
/// list exactly. Returns the edits so a test can also say how many.
|
||||
fn reconstructs(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
|
||||
let (old, new) = (tokens_of(before), tokens_of(after));
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(
|
||||
apply_edits(&flat(&old), &edits),
|
||||
flat(&new),
|
||||
"the edits must reconstruct the new data:\n{before:?}\n{after:?}"
|
||||
);
|
||||
edits
|
||||
}
|
||||
|
||||
const MODULE: &str = "module m;\n wire a;\nendmodule\n";
|
||||
|
||||
#[test]
|
||||
fn an_unchanged_buffer_produces_no_edits_at_all() {
|
||||
assert!(reconstructs(MODULE, MODULE).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_append_at_the_end_is_one_edit_that_deletes_nothing() {
|
||||
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].delete_count, 0, "nothing was removed: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deletion_at_the_end_is_one_edit_that_inserts_nothing() {
|
||||
let edits = reconstructs("module m;\n wire a;\nendmodule\n// gone\n", MODULE);
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].data.as_deref().unwrap_or_default(), &[], "{edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_in_the_middle_leaves_the_ends_alone() {
|
||||
let edits = reconstructs(
|
||||
"module m;\n wire a;\n wire b;\nendmodule\n",
|
||||
"module m;\n logic a;\n wire b;\nendmodule\n",
|
||||
);
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert!(edits[0].start > 0, "the first line's tokens are common prefix: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_complete_replacement_is_one_edit_over_everything() {
|
||||
let edits = reconstructs(MODULE, "`define W 8\n");
|
||||
assert_eq!(edits.len(), 1);
|
||||
assert_eq!(edits[0].start, 0, "nothing was in common: {edits:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_buffer_that_stops_lexing_deletes_every_token_and_back() {
|
||||
// Mid-keystroke reality: an unterminated block comment has no tokens
|
||||
// at all, and the next keystroke brings them all back.
|
||||
let broken = "module m;\n wire a; /* unterminated\n";
|
||||
assert!(tokens_of(broken).is_empty(), "the premise");
|
||||
reconstructs(MODULE, broken);
|
||||
reconstructs(broken, MODULE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_buffer_is_a_legal_end_of_a_delta_in_both_directions() {
|
||||
reconstructs(MODULE, "");
|
||||
reconstructs("", MODULE);
|
||||
assert!(reconstructs("", "").is_empty());
|
||||
}
|
||||
|
||||
/// A token, for the shapes that are about the algorithm rather than about
|
||||
/// Verilog.
|
||||
fn token(delta_line: u32, delta_start: u32, length: u32) -> SemanticToken {
|
||||
SemanticToken {
|
||||
delta_line,
|
||||
delta_start,
|
||||
length,
|
||||
token_type: Highlight::Keyword as u32,
|
||||
token_modifiers_bitset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_suffix_is_capped_so_it_cannot_overlap_the_prefix() {
|
||||
// old = [A, B, A], new = [A]. The prefix claims the leading A; a
|
||||
// suffix counted over the *whole* lists would claim the trailing one
|
||||
// — the same token twice — and `new[prefix..new.len() - suffix]`
|
||||
// would then run backwards. Counting the suffix over what the prefix
|
||||
// left is the cap, and this is the shape that proves it.
|
||||
let (a, b) = (token(0, 0, 1), token(1, 0, 2));
|
||||
let old = vec![a, b, a];
|
||||
let new = vec![a];
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
|
||||
|
||||
// And the mirror: growing into a repeating list.
|
||||
let edits = delta(&new, &old);
|
||||
assert_eq!(apply_edits(&flat(&new), &edits), flat(&old));
|
||||
|
||||
// The fully periodic case, where every token equals every other.
|
||||
let old = vec![a, a, a, a, a];
|
||||
let new = vec![a, a, a];
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(apply_edits(&flat(&old), &edits), flat(&new));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_lines_of_verilog_are_the_same_trap_on_real_tokens() {
|
||||
// Identical lines encode to identical tokens — the delta encoding is
|
||||
// relative, so line 2 and line 3 of this buffer are byte-for-byte the
|
||||
// same five numbers. Deleting one of them is the overlap shape above,
|
||||
// reached without constructing anything by hand.
|
||||
let three = "module m;\n wire a;\n wire a;\n wire a;\nendmodule\n";
|
||||
let one = "module m;\n wire a;\nendmodule\n";
|
||||
let data = tokens_of(three);
|
||||
assert_eq!(data[2], data[4], "the premise: the encoding really does repeat");
|
||||
reconstructs(three, one);
|
||||
reconstructs(one, three);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edits_indices_count_numbers_and_not_tokens() {
|
||||
// The off-by-five that silently corrupts a client's cache: `start`
|
||||
// and `deleteCount` index the flat array, so both are five times a
|
||||
// token index.
|
||||
let edits = reconstructs(MODULE, "module m;\n wire a;\nendmodule\n// added\n");
|
||||
assert_eq!(edits[0].start % FIELDS, 0, "{edits:?}");
|
||||
assert_eq!(edits[0].start, tokens_of(MODULE).len() as u32 * FIELDS);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// randomized sweep
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// A fixed-seed linear congruential generator — deterministic randomness
|
||||
/// with no dependency. The constants are Knuth's MMIX, as `sync.rs` uses.
|
||||
struct Lcg(u64);
|
||||
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
self.0 >> 33
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Lines a module body can be built from — repeats included, because
|
||||
/// repeats are what make the prefix and suffix fight over a token.
|
||||
const BODY: [&str; 8] = [
|
||||
" wire a;",
|
||||
" wire a;",
|
||||
" localparam W = 8;",
|
||||
" // a comment",
|
||||
" assign a = b & c;",
|
||||
" always_ff @(posedge clk) q <= d;",
|
||||
" /* block */",
|
||||
" wire [W-1:0] bus;",
|
||||
];
|
||||
|
||||
fn buffer(rng: &mut Lcg) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
for _ in 0..rng.below(9) {
|
||||
text.push_str(BODY[rng.below(BODY.len() as u64) as usize]);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_pair_of_real_buffers_round_trips_through_its_delta() {
|
||||
let mut rng = Lcg(0x5eed);
|
||||
for _ in 0..300 {
|
||||
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
|
||||
reconstructs(&before, &after);
|
||||
reconstructs(&after, &before);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// QA (2026-08-26): independent verification of the delta round-trip
|
||||
// and the range boundaries, on a code path that shares nothing with
|
||||
// the dev's own `apply_edits`/`reconstructs` helpers above.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// QA's own applier: unlike `apply_edits`, this never touches the flat
|
||||
/// `u32` array — it walks `SemanticToken`s and slices by hand instead of
|
||||
/// calling `Vec::splice`. It also asserts the `FIELDS` division is exact,
|
||||
/// which is a second, independent check of the "five times a token
|
||||
/// index" claim (`an_edits_indices_count_numbers_and_not_tokens`).
|
||||
fn independent_apply(
|
||||
old: &[SemanticToken],
|
||||
edits: &[SemanticTokensEdit],
|
||||
) -> Vec<SemanticToken> {
|
||||
let mut data = old.to_vec();
|
||||
for edit in edits {
|
||||
assert_eq!(edit.start % FIELDS, 0, "start is not a whole token: {edit:?}");
|
||||
assert_eq!(edit.delete_count % FIELDS, 0, "deleteCount is not a whole token: {edit:?}");
|
||||
let start = (edit.start / FIELDS) as usize;
|
||||
let deleted = (edit.delete_count / FIELDS) as usize;
|
||||
let mut rebuilt = Vec::with_capacity(data.len());
|
||||
rebuilt.extend_from_slice(&data[..start]);
|
||||
if let Some(inserted) = &edit.data {
|
||||
rebuilt.extend_from_slice(inserted);
|
||||
}
|
||||
rebuilt.extend_from_slice(&data[start + deleted..]);
|
||||
data = rebuilt;
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// Same invariant as `reconstructs`, checked with QA's applier instead of
|
||||
/// the dev's.
|
||||
fn reconstructs_independently(before: &str, after: &str) -> Vec<SemanticTokensEdit> {
|
||||
let (old, new) = (tokens_of(before), tokens_of(after));
|
||||
let edits = delta(&old, &new);
|
||||
assert_eq!(
|
||||
independent_apply(&old, &edits),
|
||||
new,
|
||||
"QA reconstruction failed:\n{before:?}\n{after:?}"
|
||||
);
|
||||
edits
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_the_two_independently_written_appliers_never_disagree() {
|
||||
// The dev's applier works on the flat `u32` array; QA's works on
|
||||
// `SemanticToken`s and never calls `Vec::splice`. Run both over the
|
||||
// same edits and the same inputs and demand they land on the same
|
||||
// place — and on the truth.
|
||||
let mut rng = Lcg(0xC0FFEE);
|
||||
for _ in 0..200 {
|
||||
let (before, after) = (buffer(&mut rng), buffer(&mut rng));
|
||||
let (old, new) = (tokens_of(&before), tokens_of(&after));
|
||||
let edits = delta(&old, &new);
|
||||
let via_flat = apply_edits(&flat(&old), &edits);
|
||||
let via_tokens = flat(&independent_apply(&old, &edits));
|
||||
assert_eq!(via_flat, via_tokens, "the two appliers disagree:\n{before:?}\n{after:?}");
|
||||
assert_eq!(via_tokens, flat(&new));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes() {
|
||||
let module = "module m;\n wire a;\n wire b;\nendmodule\n";
|
||||
// Both ends change at once, middle stays: prefix and suffix both
|
||||
// trim to non-trivial amounts.
|
||||
reconstructs_independently(
|
||||
module,
|
||||
"`define X 1\nmodule m;\n wire a;\n wire b;\nendmodule\n// tail\n",
|
||||
);
|
||||
// Middle only.
|
||||
reconstructs_independently(module, "module m;\n wire a;\n logic b;\nendmodule\n");
|
||||
// Identical.
|
||||
reconstructs_independently(module, module);
|
||||
// Complete replacement: nothing in common.
|
||||
reconstructs_independently(module, "`define totally different 1\n");
|
||||
// Old empty, new empty.
|
||||
reconstructs_independently("", module);
|
||||
reconstructs_independently(module, "");
|
||||
assert!(reconstructs_independently("", "").is_empty());
|
||||
// Single-token file, both directions and against itself.
|
||||
const SINGLE: &str = "// only one token\n";
|
||||
assert_eq!(tokens_of(SINGLE).len(), 1, "the premise: exactly one token");
|
||||
reconstructs_independently(SINGLE, module);
|
||||
reconstructs_independently(module, SINGLE);
|
||||
reconstructs_independently(SINGLE, SINGLE);
|
||||
}
|
||||
|
||||
/// A second, unrelated PRNG (xorshift64, not the dev's LCG) with its own
|
||||
/// seed.
|
||||
struct Xorshift64(u64);
|
||||
|
||||
impl Xorshift64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
let mut x = self.0;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
self.0 = x;
|
||||
x
|
||||
}
|
||||
|
||||
fn below(&mut self, n: u64) -> u64 {
|
||||
self.next() % n.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// A pool that does not overlap the dev's `BODY`: it adds a block
|
||||
/// comment that spans lines, a continued `` `define``, and a generate
|
||||
/// block — pieces whose token *count* changes non-locally, not just
|
||||
/// whose content does.
|
||||
const QA_BODY: [&str; 9] = [
|
||||
" wire a;",
|
||||
" wire a;",
|
||||
" localparam W = 4;",
|
||||
" // a trailing comment",
|
||||
" assign a = b ^ c;",
|
||||
" /* a block\n comment spanning lines */",
|
||||
" `define FF(q, d) \\\n always_ff @(posedge clk) q <= d;",
|
||||
" generate\n if (W > 1) wire c;\n endgenerate",
|
||||
" wire [W-1:0] bus;",
|
||||
];
|
||||
|
||||
fn qa_buffer(rng: &mut Xorshift64) -> String {
|
||||
let mut text = String::from("module m;\n");
|
||||
for _ in 0..rng.below(9) {
|
||||
text.push_str(QA_BODY[rng.below(QA_BODY.len() as u64) as usize]);
|
||||
text.push('\n');
|
||||
}
|
||||
text.push_str("endmodule\n");
|
||||
text
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips() {
|
||||
let mut rng = Xorshift64(0xDEAD_BEEF_1234_5678);
|
||||
for _ in 0..300 {
|
||||
let (before, after) = (qa_buffer(&mut rng), qa_buffer(&mut rng));
|
||||
reconstructs_independently(&before, &after);
|
||||
reconstructs_independently(&after, &before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_range_ending_mid_token_keeps_that_token_whole() {
|
||||
// Mirror of `a_range_that_starts_mid_token_keeps_that_token_whole`:
|
||||
// the overlap guard must be symmetric at the far boundary too.
|
||||
let data = ranged("module m;\nendmodule\n", range((0, 0), (0, 3)));
|
||||
assert_eq!(decode(&data), vec![(0, 0, 6, Highlight::Keyword as u32, 0)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty() {
|
||||
// Not an empty *line* (already covered by
|
||||
// `a_range_touching_no_token_is_empty`) — whitespace, plus an
|
||||
// unemitted `=`, between two real tokens on the same line.
|
||||
let text = "module m;\n assign a = b;\nendmodule\n";
|
||||
// "a" is the single character at column 9 (ends at 10); "b" starts
|
||||
// at column 17. Columns 11..16 are wholly inside that gap.
|
||||
let data = ranged(text, range((1, 11), (1, 16)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qa_a_reversed_range_is_total_and_answers_nothing() {
|
||||
// start > end is not a shape any client should send, but `within`'s
|
||||
// guard (`range.start >= range.end`) is symmetric to it: this must
|
||||
// not panic, and must answer empty exactly like a zero-width range.
|
||||
let data = ranged(FOUR_LINES, range((3, 0), (1, 0)));
|
||||
assert!(decode(&data).is_empty(), "{:?}", decode(&data));
|
||||
}
|
||||
}
|
||||
@@ -2836,3 +2836,115 @@ fn incremental_changes_are_advertised_and_applied_over_the_wire() {
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// The client's side of a delta: splice each edit into the flat array it
|
||||
/// holds, by index. Shares nothing with the server's own code.
|
||||
fn apply_token_edits(previous: &[u64], answer: &serde_json::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(token_numbers).unwrap_or_default();
|
||||
data.splice(start..end, inserted);
|
||||
}
|
||||
data
|
||||
}
|
||||
|
||||
/// A semantic-token `data` array as flat numbers.
|
||||
fn token_numbers(value: &serde_json::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()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn semantic_tokens_range_and_delta_round_trip_over_the_wire() {
|
||||
// What a unit test cannot check: that both new capabilities reach the
|
||||
// wire in the shape a client keys off, and that a real delta — computed
|
||||
// by one process and applied by another, over the wire's flat number
|
||||
// array — reconstructs the token set the next full request answers.
|
||||
let dir = temp_dir("semantictokens");
|
||||
let file = dir.join("m.sv");
|
||||
let before = "module tokens_me;\n localparam W = 8;\n wire [W-1:0] a;\nendmodule\n";
|
||||
let after =
|
||||
"module tokens_me;\n localparam W = 16;\n wire [W-1:0] a;\n // added\nendmodule\n";
|
||||
std::fs::write(&file, before).expect("write");
|
||||
let root = format!("file://{}", dir.display());
|
||||
let uri = format!("file://{}", file.display());
|
||||
|
||||
let session = [
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":1,"method":"initialize","params":{{"processId":null,"rootUri":"{root}","capabilities":{{}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"initialized","params":{}}"#),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didOpen","params":{{"textDocument":{{"uri":"{uri}","languageId":"systemverilog","version":1,"text":{}}}}}}}"#,
|
||||
serde_json::to_string(before).expect("json")
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":2,"character":0}}}}}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","method":"textDocument/didChange","params":{{"textDocument":{{"uri":"{uri}","version":2}},"contentChanges":[{{"text":{}}}]}}}}"#,
|
||||
serde_json::to_string(after).expect("json")
|
||||
)),
|
||||
// The ids are minted one per answer from the start of the session, so
|
||||
// the full answer above is `"1"` — asserted below, so a changed
|
||||
// scheme fails loudly here rather than silently downgrading every
|
||||
// delta to a full answer.
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/semanticTokens/full/delta","params":{{"textDocument":{{"uri":"{uri}"}},"previousResultId":"1"}}}}"#
|
||||
)),
|
||||
frame(&format!(
|
||||
r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"#
|
||||
)),
|
||||
frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#),
|
||||
frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#),
|
||||
]
|
||||
.concat();
|
||||
|
||||
let messages = talk(&session);
|
||||
|
||||
// 1. Both capabilities on the wire, in the shape a client reads.
|
||||
let initialize = messages.iter().find(|m| m["id"] == 1).expect("initialize response");
|
||||
let provider = &initialize["result"]["capabilities"]["semanticTokensProvider"];
|
||||
assert_eq!(provider["range"], true, "range is advertised: {provider:#?}");
|
||||
assert_eq!(provider["full"]["delta"], true, "and so are deltas: {provider:#?}");
|
||||
assert_eq!(
|
||||
provider["legend"]["tokenTypes"].as_array().expect("the legend").len(),
|
||||
14,
|
||||
"the legend is unchanged: {provider:#?}"
|
||||
);
|
||||
|
||||
// 2. The full answer is stamped, and its id is the one the delta named.
|
||||
let full = messages.iter().find(|m| m["id"] == 2).expect("full response");
|
||||
assert_eq!(full["result"]["resultId"], "1", "{full:#?}");
|
||||
let held = token_numbers(&full["result"]["data"]);
|
||||
assert!(!held.is_empty(), "{full:#?}");
|
||||
|
||||
// 3. The range answer stands on its own: no id, absolute first delta.
|
||||
let ranged = messages.iter().find(|m| m["id"] == 3).expect("range response");
|
||||
assert!(ranged["result"].get("resultId").is_none(), "nothing to name: {ranged:#?}");
|
||||
let window = token_numbers(&ranged["result"]["data"]);
|
||||
assert_eq!(window[0], 1, "deltaLine is absolute from the file start: {ranged:#?}");
|
||||
assert!(window.len() < held.len(), "and it is only part of the file: {ranged:#?}");
|
||||
|
||||
// 4. The delta reconstructs exactly what the next full request answers.
|
||||
let delta = messages.iter().find(|m| m["id"] == 4).expect("delta response");
|
||||
assert!(delta["result"].get("edits").is_some(), "a known id gets edits: {delta:#?}");
|
||||
let truth = messages.iter().find(|m| m["id"] == 5).expect("second full response");
|
||||
assert_eq!(
|
||||
apply_token_edits(&held, &delta["result"]),
|
||||
token_numbers(&truth["result"]["data"]),
|
||||
"applying the edits must land on the new token set exactly"
|
||||
);
|
||||
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -23,7 +23,9 @@ looks like language knowledge in here is a bug or a `Handshake` request.
|
||||
| `textDocument/didChange` | `sync::apply_changes` | Incremental sync: the ranges are applied in order to the buffer the server holds, then one `set_document` + one `publish`. A rangeless change still replaces the whole buffer, so a full-sync client is unaffected. See `docs/features/incremental-sync/README.md` |
|
||||
| `textDocument/diagnostic`, `workspace/diagnostic` | the same parse+lint pass | The 3.17 pull model, served to a client that advertised `textDocument.diagnostic` — which is then pushed nothing at all. `resultId` is one generation counter, bumped by a buffer change and by an index rebuild; the workspace report covers the **open buffers**. Same feature README |
|
||||
| `textDocument/selectionRange` | `Document.tokens`, AST spans, `pairs::analyze` | Expand-selection: one strictly nesting chain per requested position, token → statement → block → item → file. No expression step. See `docs/features/selection-range/README.md` |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries |
|
||||
| `textDocument/semanticTokens/full` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it |
|
||||
| `textDocument/semanticTokens/range` | the same classification pass | The visible lines only, for the first paint of a large file. A **self-contained** answer: the tokens overlapping the range, kept whole, re-encoded from the start of the document. No `resultId` — a partial view is not what a delta is computed against. See `docs/features/semantic-tokens-delta/README.md` |
|
||||
| `textDocument/semanticTokens/full/delta` | the same classification pass | What changed since the answer the client names: one edit replacing everything between the common prefix and the common suffix (the suffix capped so the two cannot overlap — identical lines of Verilog encode identically, which is exactly the trap). An id the server does not hold, including one from before a `didClose`, is answered in full. Same feature README |
|
||||
| `textDocument/hover` | `DefineTable`, `Semantics`, `WorkspaceIndex`, `includes::IncludeGraph`, `expand` | Macro body, or declaration kind + snippet. A macro this file does not define is answered from the workspace: the definition it **reaches through its `` `include``s** when exactly one is reachable, and every candidate otherwise. A macro card also shows what the hovered use **expands to in one step** — the body with this call's arguments substituted — when that says more than the body already does; a nested `` `INNER`` is left as written, an argument count that does not match expands nothing, and several candidates expand nothing. See `docs/features/macro-expansion/README.md` |
|
||||
| `textDocument/definition` | `includes::IncludeGraph`, then `Semantics`, then `ExternalResolutions` | A cursor on an `` `include`` line jumps to the resolved file's first byte; otherwise the in-file symbol table, then the workspace overlay, whose `Ambiguous` answer returns every location. See `docs/features/include-nav/README.md` |
|
||||
| `textDocument/documentLink` | `includes::IncludeGraph` | One link per **resolvable** `` `include``, covering the quoted path, target already resolved (`resolveProvider: false`). Search order: the including file's own directory, then each `+incdir+` of the configured filelist in order; the `<angled>` form skips the first rung. An include nothing answers to gets no link and no error. Same feature README |
|
||||
@@ -392,7 +394,18 @@ Two rules that are easy to get wrong and are tested:
|
||||
three multi-line token shapes that would violate it — a block comment, a
|
||||
continued `` `define``, and a multi-line macro invocation. Every span is
|
||||
split at `\n` before encoding, and the pieces are sorted by (line, start)
|
||||
before the delta encoding runs.
|
||||
before the delta encoding runs. Single-line tokens are also what lets the
|
||||
`range` filter reason about overlap without looking at the text at all.
|
||||
|
||||
Since 2026-08-26 that classification feeds three requests, not one: the pass
|
||||
produces an intermediate **absolute** form (line, column, length, type,
|
||||
modifiers), `range` filters it, and one pure encoder delta-encodes whatever is
|
||||
left — from the start of the document in every case, so a range answer stands
|
||||
on its own. The `resultId` bookkeeping that makes `full/delta` possible lives
|
||||
in `server.rs` (one counter, one remembered answer per open buffer, dropped on
|
||||
`didClose`), because `tokens.rs` owns no state. Rules, the prefix/suffix
|
||||
overlap trap and the round-trip property:
|
||||
`docs/features/semantic-tokens-delta/README.md`.
|
||||
|
||||
## Hover, and the order it tries things
|
||||
|
||||
@@ -456,7 +469,10 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory:
|
||||
`Semantics`, `DefineTable`, overlay), workspace walk, index rebuild.
|
||||
- [x] `textDocument/formatting`.
|
||||
- [x] Diagnostics on `didOpen`/`didChange`/`didSave`.
|
||||
- [x] `textDocument/semanticTokens/full`.
|
||||
- [x] `textDocument/semanticTokens/full`, joined by `/range` and `/full/delta`
|
||||
(2026-08-26) — one tokenizer and one encoder behind all three, plus a
|
||||
per-buffer `resultId` dropped on `didClose`.
|
||||
`docs/features/semantic-tokens-delta/README.md`.
|
||||
- [x] `textDocument/hover`.
|
||||
- [x] `textDocument/definition`.
|
||||
- [x] `textDocument/references`.
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
# semantic-tokens-delta
|
||||
|
||||
## Goal
|
||||
|
||||
Serve the two semantic-token requests this server advertised nothing for:
|
||||
`textDocument/semanticTokens/range`, so the first paint of a large file costs
|
||||
the visible lines rather than the whole file, and
|
||||
`textDocument/semanticTokens/full/delta`, so a client that already holds an
|
||||
answer is told what *changed* instead of being handed the file's whole token
|
||||
set on every keystroke (TODO.md §9b). Both are the same tokenizer that already
|
||||
served `full`: the classification pass now produces an intermediate
|
||||
**absolute** form — line, column, length, type, modifiers — a range answer
|
||||
filters that form and the one encoder delta-encodes whatever is left, so the
|
||||
three requests cannot disagree about what a token is. The delta itself is the
|
||||
standard prefix/suffix trim rust-analyzer uses, with the one invariant that
|
||||
matters tested as a property: applying the returned edits to the old data
|
||||
reproduces the new data exactly.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **A range answer is a self-contained `SemanticTokens`, not a slice of the
|
||||
full one.** The relative encoding restarts from the start of the *document*
|
||||
exactly as a full answer's does; only the tokens outside the range are
|
||||
missing. So the first kept token's `deltaLine`/`deltaStart` are absolute,
|
||||
which is why the encoder had to be split out of the classifier rather than
|
||||
the range answer being a sub-slice of the full one. (A client that pasted a
|
||||
slice out of a full answer would draw line 40's tokens on line 0 — pinned by
|
||||
`a_range_answer_re_encodes_from_the_start_of_the_document`.)
|
||||
- **A token that only overlaps the range is kept whole.** The client asked
|
||||
which tokens to draw, not where to cut them, and a `length` trimmed to the
|
||||
range would be a lie about the source. Tokens are single-line by
|
||||
construction (every span is split at `\n` before encoding — the rule
|
||||
`no_token_ever_spans_a_line_break` has pinned since the first round), so
|
||||
"overlap" never has to reason across lines.
|
||||
- **An empty range answers nothing.** A zero-width range covers no characters,
|
||||
so nothing intersects it. Without the explicit guard the overlap test
|
||||
degenerates into *containment* and a collapsed cursor position would answer
|
||||
with the token it sits inside — tokens the client has no room to draw. No
|
||||
editor is known to send one; it is guarded because the arithmetic invites it.
|
||||
- **`resultId`s are minted per answer, from one counter, and are not the
|
||||
diagnostics generation.** A `previousResultId` must name the exact data the
|
||||
client holds, which the pull-diagnostics generation cannot do: that one is
|
||||
bumped by a buffer change *and* by an index rebuild, and it is shared by
|
||||
every open buffer. This counter counts *answers* — one per full and per
|
||||
delta, whatever the buffer — so an id is unambiguous and never reused.
|
||||
Answering the same unchanged buffer twice mints two ids and one empty edit
|
||||
list; that is a string per answer, not a recomputation.
|
||||
- **A range answer is deliberately *not* remembered and carries no
|
||||
`resultId`.** It is a partial view; a later delta computed against it would
|
||||
be a diff against something the client never held whole. Only `full` and
|
||||
`full/delta` write the remembered answer.
|
||||
- **One answer per buffer is remembered, and it dies with the buffer.** A
|
||||
client that asks again has moved on from the previous answer, so there is no
|
||||
history to keep. `didClose` drops the entry, so the map is bounded by the
|
||||
number of *open* buffers, not by the number of files ever opened. A delta
|
||||
naming an id from before a close is answered in full.
|
||||
- **Mismatched, absent or stale `previousResultId` → a full answer.**
|
||||
`SemanticTokensFullDeltaResult` allows either, and a delta against data we
|
||||
cannot see would be a guess. That is also what makes a server restart, a
|
||||
client restart and a `didClose`/`didOpen` cycle all self-healing.
|
||||
- **Minimality beyond the prefix/suffix trim is not attempted.** One
|
||||
`SemanticTokensEdit` replaces everything between the common prefix and the
|
||||
common suffix. A real diff would describe an insertion in the middle of a
|
||||
file as two small edits, but the encoding is *relative*: the first token
|
||||
after an inserted line carries a changed `deltaLine`, so a "middle"
|
||||
insertion already invalidates only that one token plus the ones that moved,
|
||||
and everything below it re-matches as suffix. rust-analyzer answers the same
|
||||
way. The payload is what the client re-parses, not what it re-renders.
|
||||
- **The buffer that does not lex still round-trips.** It has no tokens at all
|
||||
(the lexer is all-or-nothing), so a delta out of it deletes everything and a
|
||||
delta back into it inserts everything. Mid-keystroke this is the common
|
||||
case, and it is tested in both directions.
|
||||
- **`workspace/semanticTokens/refresh` is out of scope and not sent.** That
|
||||
request exists for the case where the *server* decides the client's tokens
|
||||
went stale without the client having edited anything — an index rebuild
|
||||
changing how a name resolves, say. The case that matters (the user typing)
|
||||
makes the client re-pull on its own. Recorded as backlog below, not built.
|
||||
|
||||
## The delta algorithm, and the bug it is easy to write
|
||||
|
||||
```
|
||||
prefix = how many leading tokens are equal
|
||||
old_rest, new_rest = both lists past the prefix
|
||||
suffix = how many trailing tokens of old_rest and new_rest are equal
|
||||
edit = replace old_rest[..old_rest.len() - suffix]
|
||||
with new_rest[..new_rest.len() - suffix]
|
||||
```
|
||||
|
||||
**The suffix is counted over what the prefix left, never over the whole
|
||||
lists.** That is the cap, and skipping it is *the* classic bug in this
|
||||
algorithm: when the two token lists repeat themselves, a suffix counted over
|
||||
the whole lists claims tokens the prefix has already claimed, and
|
||||
`new_rest[..new_rest.len() - suffix]` then runs backwards — a panic in debug,
|
||||
an edit that deletes a region it also re-inserts in the general case.
|
||||
|
||||
This is not hypothetical for Verilog. The encoding is relative, so **identical
|
||||
lines encode to identical tokens**: line 2 and line 3 of
|
||||
|
||||
```systemverilog
|
||||
module m;
|
||||
wire a;
|
||||
wire a;
|
||||
wire a;
|
||||
endmodule
|
||||
```
|
||||
|
||||
are byte-for-byte the same five numbers. Deleting one of those lines is
|
||||
exactly the `old = [A, B, A]`, `new = [A]` shape. Both the hand-built shape and
|
||||
the real-Verilog one are tested (`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`), and both were
|
||||
confirmed to **fail** — by panic — against a deliberately uncapped
|
||||
implementation before being committed to.
|
||||
|
||||
**`start` and `deleteCount` count numbers, not tokens.** The wire carries a
|
||||
flat `u32` array of five numbers per token, and an edit indexes *that*. Both
|
||||
are five times a token index (`FIELDS`), pinned by
|
||||
`an_edits_indices_count_numbers_and_not_tokens` — the off-by-five here does not
|
||||
fail loudly, it silently corrupts a client's cache.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `lsp-types` (0.97, no new dependency):**
|
||||
`SemanticTokensRangeParams`, `SemanticTokensRangeResult`,
|
||||
`SemanticTokensDeltaParams`, `SemanticTokensFullDeltaResult`,
|
||||
`SemanticTokensDelta`, `SemanticTokensEdit`, and — for the capability —
|
||||
`SemanticTokensOptions { range: Option<bool>, full: Option<SemanticTokensFullOptions> }`
|
||||
with `SemanticTokensFullOptions::Delta { delta: Some(true) }`. The `Delta`
|
||||
variant is the full capability *plus* deltas, not a replacement:
|
||||
`semanticTokens/full` is still served and still answered.
|
||||
|
||||
**Consumed from other crates: nothing new.** `vlog_parser`, `vlog_semantic`,
|
||||
`vlog_formatter`, `vlog_refactor`, `lucisv_core` are untouched, as is every
|
||||
file outside `crates/lucisv_server`. This feature is protocol arithmetic over a
|
||||
classification that already existed.
|
||||
|
||||
**Changed inside this crate, for whoever reads `tokens.rs` next:**
|
||||
|
||||
- `tokens::semantic_tokens(doc)` now returns `Vec<SemanticToken>` (the `data`)
|
||||
rather than a whole `SemanticTokens`. The `resultId` is the server's to
|
||||
stamp, because only the server knows what it remembered — the module owns
|
||||
no state.
|
||||
- New: `tokens::semantic_tokens_in_range(doc, range) -> Vec<SemanticToken>`
|
||||
and `tokens::delta(old, new) -> Vec<SemanticTokensEdit>`.
|
||||
- Private and new: `Absolute` (line, start, length, type, modifiers),
|
||||
`absolute(doc)`, `flatten(pieces, doc)`, `within(tokens, range)`,
|
||||
`encode(&[Absolute])`. `encode` is pure — the same tokens always encode the
|
||||
same way, whether they are the whole file's or the handful a range kept —
|
||||
which is what lets `full` and `range` share it.
|
||||
- `Server` gains `tokens: HashMap<Uri, TokenAnswer>` and `token_results: u64`,
|
||||
written only by `remember_tokens` and cleared only by `didClose`. **Neither
|
||||
touches `generation`**: every token request is read-only, and bumping the
|
||||
diagnostics generation on a viewport repaint would throw away a pulling
|
||||
client's whole diagnostic cache several times a second
|
||||
(`no_token_request_bumps_the_diagnostics_generation`).
|
||||
|
||||
**Requested of other modules:** nothing.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `tokens.rs` split into classification → `Absolute` → filter → `encode`,
|
||||
with `full` and `range` sharing all four steps.
|
||||
- [x] `textDocument/semanticTokens/range`, advertised as `range: Some(true)`,
|
||||
re-encoded from the document start, overlap kept whole, empty range
|
||||
empty.
|
||||
- [x] `textDocument/semanticTokens/full/delta`, advertised as
|
||||
`full: Delta { delta: Some(true) }`, single-edit prefix/suffix diff with
|
||||
the suffix capped.
|
||||
- [x] Per-buffer `resultId` bookkeeping: minted per answer, stored by both
|
||||
`full` and `full/delta`, dropped on `didClose`.
|
||||
- [x] `semanticTokens/full` returns a `resultId` now (it did not before), so a
|
||||
client may mix the two requests.
|
||||
- [x] Round-trip property tests: append, delete, middle change, identical,
|
||||
complete replacement, unlexable buffer both ways, empty buffer both
|
||||
ways, the prefix/suffix-overlap shapes, and a 300-iteration fixed-seed
|
||||
randomized sweep over real Verilog buffers.
|
||||
- [x] Range/full agreement as a property over two corpus files, in 40-line
|
||||
windows (the size of an editor viewport request), stated line-wise so it
|
||||
is independent of the handler's own overlap test.
|
||||
- [x] Server-level tests through the `Session` harness, and one e2e round trip
|
||||
through the real binary.
|
||||
- [x] TODO.md §9b box, this README, and the `lucisv-server` capability table.
|
||||
- [ ] **Not done, deliberately:** `workspace/semanticTokens/refresh`. Nothing
|
||||
the server learns on its own (an index rebuild changing how a name
|
||||
resolves) currently invalidates a client's token cache; when something
|
||||
does, this is the request to send.
|
||||
- [ ] **Not done:** partial results / `workDoneProgress` on any of the three
|
||||
requests. The whole-file answer is sub-millisecond at Verilog file
|
||||
sizes; streaming it in chunks would be complexity for nobody.
|
||||
- [ ] **Not measured:** whether the delta payload is actually smaller than the
|
||||
full one for a typical edit. It must be by construction for an edit near
|
||||
either end of a file, and it is at worst the full set plus one edit
|
||||
header for an edit near the middle. No benchmark was written.
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-26 — dev agent
|
||||
|
||||
- **Read first**: `CLAUDE.md`, `docs/features/lucisv-server/README.md` (the
|
||||
capability table and the `semanticTokens` mapping section),
|
||||
`docs/features/pull-diagnostics/README.md` for the house style on result
|
||||
ids, `tokens.rs` in full, and `lsp-types` 0.97's `semantic_tokens.rs` for
|
||||
the exact shapes (`range` is a plain `Option<bool>` there, not an options
|
||||
struct; `SemanticTokensFullDeltaResult` has three variants and we use two).
|
||||
- **The refactor came before either handler.** `semantic_tokens` was one
|
||||
function doing classification, line splitting, sorting and delta encoding,
|
||||
and the range answer needs to cut in between the third and the fourth. It
|
||||
is now `absolute(doc)` (classify + split + sort, producing `Absolute`),
|
||||
`within(tokens, range)` (the filter) and `encode(&[Absolute])` (pure delta
|
||||
encoding). The eleven pre-existing token tests were left with their
|
||||
assertions untouched — only the test *helpers* moved, because
|
||||
`semantic_tokens` now hands back the `data` rather than a `SemanticTokens`
|
||||
— which is the evidence that the factoring changed no behavior.
|
||||
- **The overlap cap was verified by breaking it, not by reasoning.** After
|
||||
writing the capped `delta`, the suffix computation was temporarily changed
|
||||
to count over the whole lists and the suite re-run: three tests failed with
|
||||
a subtraction-overflow panic
|
||||
(`the_suffix_is_capped_so_it_cannot_overlap_the_prefix`,
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` via the shared
|
||||
round-trip helper, and `every_pair_of_real_buffers_round_trips_through_its_delta`
|
||||
— the randomized sweep found it on its own, which is why the `BODY` line
|
||||
pool deliberately repeats `" wire a;"`). The implementation was then
|
||||
restored. CLAUDE.md's invariant #4 is about `verify.rs`, but its spirit —
|
||||
a normalization ships with the attack that would forgive a corruption —
|
||||
is what this check is.
|
||||
- **The one design decision that is not the obvious one**: a range answer
|
||||
carries no `resultId` and is not remembered. It would have been one line to
|
||||
remember it, and it would have silently made the next delta a diff against
|
||||
a partial view. Written down in Assumptions and pinned by
|
||||
`a_range_request_is_not_the_answer_a_later_delta_is_computed_against`.
|
||||
- **The empty-range guard was written for the arithmetic, not for a client.**
|
||||
`from < range.end && range.start < to` is the interval-overlap test only
|
||||
when the range is non-empty; for a collapsed range it is containment. One
|
||||
early return, one test, one sentence in Assumptions.
|
||||
- **`generation` was deliberately not touched**, and the test for it says so
|
||||
twice: directly on the field, and observably through a pull that is still
|
||||
`unchanged` after a token request. Pull diagnostics' README asks every new
|
||||
feature to audit whether it bumps the generation; the audit's answer here
|
||||
is no, and this is where it is recorded.
|
||||
- **Nothing outside this crate moved.** No new dependency, no version bump,
|
||||
no engine change, no `editors/` change (`smoke.js`'s capability list already
|
||||
contains `semanticTokensProvider`, and it passes against the built binary).
|
||||
- **Results.** `cargo test --workspace`: **1793 passed, 0 failed** (1764
|
||||
before — +29: 18 unit tests in `tokens.rs`, 9 in `server.rs`, 1 in
|
||||
`main.rs`, 1 e2e). `cargo clippy --all-targets`: silent.
|
||||
`cargo fmt --all -- --check`: clean. `cargo build && node
|
||||
editors/vscode/smoke.js target/debug/lucisv-server`: OK. No commits.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-26 — QA agent
|
||||
|
||||
**Gates re-run, from a clean rebuild** (`touch`ed the three changed source
|
||||
files first so clippy could not reuse a stale cached pass):
|
||||
`cargo fmt --all -- --check`: clean. `cargo clippy --all-targets --workspace
|
||||
-- -D warnings`: silent. `cargo test --workspace`: **1793 passed, 0 failed**
|
||||
before QA's own additions, **1802 passed, 0 failed** after (9 QA tests added,
|
||||
see below). `cargo build && node editors/vscode/smoke.js
|
||||
target/debug/lucisv-server`: OK. All match the dev's claims.
|
||||
|
||||
**1. The delta invariant, independently — verified clean, tests added.**
|
||||
Wrote a second applier, `independent_apply` (`tokens.rs`, in `mod tests`),
|
||||
that shares no code with the dev's `apply_edits`: it walks `SemanticToken`s
|
||||
rather than the flat `u32` array, slices by hand (`extend_from_slice`)
|
||||
rather than calling `Vec::splice`, and separately asserts `edit.start` /
|
||||
`edit.delete_count` divide evenly by `FIELDS` — a second, independent check
|
||||
of the ×5 claim. Cross-checked the two appliers directly against each other
|
||||
over 200 random pairs (`qa_the_two_independently_written_appliers_never_disagree`)
|
||||
— **they never disagreed**. Ran QA's applier over: both ends changing at
|
||||
once, middle-only, identical, complete replacement, old empty, new empty,
|
||||
and a single-token file, both directions
|
||||
(`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`).
|
||||
Ran a second randomized sweep, different generator (xorshift64, not the
|
||||
dev's LCG), different seed (`0xDEAD_BEEF_1234_5678` vs `0x5eed`), and a
|
||||
different line pool that adds a block comment spanning lines, a continued
|
||||
`` `define``, and a `generate`/`endgenerate` block — pieces whose token
|
||||
*count* is not simply one-line-in-N-tokens-out
|
||||
(`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`).
|
||||
All green. **Verdict: verified clean.**
|
||||
|
||||
**2. The overlap cap, re-verified — reproduced, with one correction to the
|
||||
work log's specifics.** Reproduced the dev's breakage myself: changed the
|
||||
suffix computation in `delta` (`tokens.rs:304-305` at the time) from
|
||||
counting over `old_rest`/`new_rest` to counting over the whole `old`/`new`,
|
||||
re-ran `cargo test -p lucisv_server`, and restored it — the file is back to
|
||||
its pre-experiment text (diffed against git to confirm no leftover debug
|
||||
code). Result: **10 tests failed** by `attempt to subtract with overflow`
|
||||
panic, including `the_suffix_is_capped_so_it_cannot_overlap_the_prefix`, the
|
||||
dev's own sweep `every_pair_of_real_buffers_round_trips_through_its_delta`,
|
||||
and — usefully — all of QA's own new round-trip tests from surface 1 above,
|
||||
which is exactly the cross-check CLAUDE.md invariant #4 asks for (an
|
||||
independently-written attack finding the same class of bug). **One
|
||||
correction**: the work log names
|
||||
`repeated_lines_of_verilog_are_the_same_trap_on_real_tokens` as one of the
|
||||
three tests that failed in the dev's own experiment. Re-running the same
|
||||
breakage, this specific test **passes** — traced with a temporary debug
|
||||
print (`old.len()=9 new.len()=5 prefix=4 suffix=1` and the mirror), the
|
||||
type/declaration-modifier mismatch a few tokens in breaks the naive
|
||||
whole-list suffix match before it ever grows past `old_rest`'s length, so no
|
||||
overflow occurs for this particular buffer pair under this literal
|
||||
interpretation of "count over the whole lists." This is a documentation
|
||||
accuracy nit, not a safety finding — the class of bug is still real and
|
||||
still demonstrated by the other two named tests plus QA's own — but the dev
|
||||
should either soften the claim (the failure was seen at the time, with
|
||||
whatever the code looked like then, or via a different breakage) or drop
|
||||
that one test's name from the sentence. **Then tried to construct a shape
|
||||
that defeats the capped implementation and produces wrong data instead of a
|
||||
panic**: with the cap in place, `suffix = old_rest.iter().rev().zip(new_rest.iter().rev())…`
|
||||
is inherently bounded by `min(old_rest.len(), new_rest.len())` because
|
||||
`Iterator::zip` itself stops at the shorter side — so `deleted =
|
||||
old_rest.len() - suffix` can never underflow, and the algebra (`old[:prefix]
|
||||
+ inserted + old_rest[deleted..]` reduces to exactly `new`) holds
|
||||
unconditionally, not just on the tested shapes. Tried anyway: long shared
|
||||
prefix and long shared suffix overlapping in the middle over periodic data
|
||||
(the `[A,A,A,A,A]` → `[A,A,A]` shape, and variants with the periodic run at
|
||||
different positions) — all round-trip correctly, consistent with the
|
||||
argument above. **Verdict: verified clean; the cap is load-bearing (10
|
||||
failures without it) and, with it, the round-trip property holds by
|
||||
construction, not merely on the cases anyone thought to test.**
|
||||
|
||||
**3. u32 semantics — verified clean.** `an_edits_indices_count_numbers_and_not_tokens`
|
||||
(dev's) and QA's own `independent_apply` (which asserts `% FIELDS == 0`
|
||||
before dividing, on every edit, in every test above, including the 500
|
||||
combined sweep iterations) agree the ×5 conversion is exact and consistently
|
||||
applied. Wire shape: an unchanged buffer answers `edits: []` (present, empty
|
||||
— `a_delta_over_an_unchanged_buffer_is_an_empty_edit_list`,
|
||||
`server.rs:2508`) and a stale/unknown/absent-state id answers the
|
||||
`Tokens` variant with no `edits` key at all
|
||||
(`a_delta_naming_an_id_we_do_not_hold_is_answered_in_full`) — both legal per
|
||||
`SemanticTokensFullDeltaResult`'s untagged enum, and both are pinned by
|
||||
existing tests, not left to accident.
|
||||
|
||||
**4. Range self-containment — verified clean, gaps closed with new tests.**
|
||||
The dev covered: full-document range, absolute first-token deltas, overlap
|
||||
kept whole at the *start* boundary, empty range, whitespace-only *lines*,
|
||||
range never leaking outside tokens, and a 40-line-window corpus sweep (which
|
||||
QA re-ran directly against the checked-out `corpus/` — genuinely exercised,
|
||||
not skipped: `windows_checked` well over 20). QA added the three shapes the
|
||||
list asked for that were not yet pinned: (a) overlap kept whole at the *end*
|
||||
boundary, mirroring the dev's start-boundary test
|
||||
(`qa_a_range_ending_mid_token_keeps_that_token_whole`); (b) a range on a line
|
||||
*with* tokens, covering only the whitespace (plus an unemitted `=`) between
|
||||
two of them — not an empty line
|
||||
(`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`);
|
||||
(c) a reversed range (`start > end`) — `within`'s guard
|
||||
(`range.start >= range.end`) is symmetric to this by construction since
|
||||
`Position` derives `Ord` over `(line, character)` lexicographically, so this
|
||||
was already total and already answered empty, but nothing pinned it before
|
||||
now (`qa_a_reversed_range_is_total_and_answers_nothing`). All pass.
|
||||
**Verdict: verified clean.**
|
||||
|
||||
**5. State lifecycle — verified clean, two gaps closed with new tests.** The
|
||||
dev covered: didClose+reopen with the old id → full, memory dropped on
|
||||
close (`server.rs:784`, `self.tokens.remove(&uri)`, confirmed keyed by
|
||||
`Uri` and removed, not just marked stale), and the unopened-buffer → null
|
||||
convention for all three request kinds
|
||||
(`every_token_request_for_a_buffer_that_is_not_open_answers_null`, which
|
||||
also asserts the map stays empty). QA added: (a) two buffers open at once,
|
||||
buffer A's id presented to buffer B — answered in full, not edits computed
|
||||
against A's data, and closing A leaves B's own remembered state untouched
|
||||
(`qa_two_open_buffers_ids_do_not_cross_contaminate`); worth noting as a
|
||||
observation rather than a bug: presenting a foreign id to B *does* mint a
|
||||
fresh id for B and overwrite B's own remembered answer (every answer does,
|
||||
by design — "Answering the same unchanged buffer twice mints two ids"), so
|
||||
the first version of this test asserted something the design doesn't
|
||||
promise (that `id_b` keeps working) — fixed once understood, noted here so
|
||||
the next reader doesn't trip on the same assumption. (b) `full → delta →
|
||||
full → delta → full` stays consistent across three edits
|
||||
(`qa_full_delta_full_delta_stays_consistent_across_edits`), and separately,
|
||||
a `full/delta` answer's *own* `resultId` chains directly into the next delta
|
||||
without ever going back through `full`
|
||||
(`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`)
|
||||
— checked against `ground_truth`, a helper that reads the document straight
|
||||
through `tokens::semantic_tokens` and bypasses the request dispatch (and
|
||||
thus the very `tokens`/`token_results` bookkeeping under test) entirely, so
|
||||
the check does not depend on the server's own memory being right. All pass.
|
||||
**Verdict: verified clean.**
|
||||
|
||||
**6. No behavior change for existing clients — verified clean, two ways.**
|
||||
(a) Direct code comparison: `classify`, `modifiers`, `identifier_type`,
|
||||
`symbol_type`, `collect_trivia`, `split_lines`, `token_types` and
|
||||
`token_modifiers` are byte-for-byte identical between
|
||||
`git show 80b9afd:crates/lucisv_server/src/tokens.rs` and the new file; the
|
||||
new `flatten`+`encode` pair is the old single `encode` function split at
|
||||
exactly the line-splitting/sorting boundary, with no logic added or
|
||||
removed. (b) Empirical, at the binary level: built the pre-refactor commit
|
||||
in a separate worktree (`git worktree add`, removed after), drove both the
|
||||
old and the new `lucisv-server` binaries over stdio with the same
|
||||
`textDocument/semanticTokens/full` request against a real corpus file
|
||||
(`corpus/picorv32/picorv32.v`, 41,325 tokens), and diffed the `data` arrays:
|
||||
**byte-for-byte identical**; the only difference in the response is the new
|
||||
`resultId` field, which the old binary did not send at all. The legend
|
||||
(`token_types`/`token_modifiers`) is likewise unchanged (confirmed both by
|
||||
the code diff and by `the_semantic_token_capability_asks_for_ranges_and_for_deltas`
|
||||
asserting length 14). **Verdict: verified clean — this is about as strong
|
||||
as evidence gets for "the refactor changed no behavior."**
|
||||
|
||||
**7. CLAUDE.md compliance — verified clean.** `grep`-checked all non-test
|
||||
code in `tokens.rs`, `server.rs`, `main.rs` for `.unwrap()`, `.expect(`,
|
||||
`panic!`: none. No `#[allow]` added anywhere in the diff. No `unsafe`
|
||||
anywhere in the diff. The two new public functions
|
||||
(`semantic_tokens_in_range`, `delta`) both carry doc comments explaining
|
||||
what/why. The feature README has each of the six required sections exactly
|
||||
once (plus one extra, non-required "The delta algorithm…" section, which is
|
||||
additive and not a substitute for any required one). `TODO.md`'s item text
|
||||
is unchanged save the checkbox and an appended `→` summary — the original
|
||||
sentence is intact verbatim.
|
||||
|
||||
**Fixes made directly (small, per the QA remit):** none needed in the
|
||||
dev's own code — every finding above was either "verified clean" or a
|
||||
documentation-accuracy nit (item 2) recorded rather than edited, since
|
||||
CLAUDE.md reserves the Work log for the dev agent's own account of what it
|
||||
did and why, and the specific breakage the dev saw is not reproducible
|
||||
after the fact to know which description would be truer. QA did fix one bug
|
||||
in **QA's own** first draft of `qa_two_open_buffers_ids_do_not_cross_contaminate`
|
||||
(a wrong assumption about `id_b` surviving a cross-request, see item 5)
|
||||
before it ever reached this log.
|
||||
|
||||
**Tests added this round:** 9, all passing, workspace total 1793 → 1802.
|
||||
`tokens.rs`: `qa_the_two_independently_written_appliers_never_disagree`,
|
||||
`qa_independent_reconstruction_covers_both_ends_middle_and_the_degenerate_shapes`,
|
||||
`qa_a_second_randomized_sweep_with_a_different_seed_generator_and_pool_round_trips`,
|
||||
`qa_a_range_ending_mid_token_keeps_that_token_whole`,
|
||||
`qa_a_range_covering_only_mid_line_whitespace_between_two_tokens_is_empty`,
|
||||
`qa_a_reversed_range_is_total_and_answers_nothing`. `server.rs`:
|
||||
`qa_two_open_buffers_ids_do_not_cross_contaminate`,
|
||||
`qa_full_delta_full_delta_stays_consistent_across_edits`,
|
||||
`qa_a_deltas_own_id_chains_directly_into_the_next_delta_without_a_full_in_between`.
|
||||
|
||||
**Overall verdict: committable as-is.** No corruption, non-idempotency,
|
||||
dropped-comment, or safety-net-widening risk found — this feature does not
|
||||
touch `verify.rs`, the formatter, or anything outside `crates/lucisv_server`,
|
||||
and every claim in the dev's work log checked out except the one test name
|
||||
in item 2, which is cosmetic. All gates green, all new and old tests green,
|
||||
one empirical binary-level spot check green.
|
||||
|
||||
## Review
|
||||
|
||||
### 2026-08-26 — lead
|
||||
|
||||
Reviewed the diff, the work log and the QA log; re-ran all gates myself
|
||||
(1802 workspace tests, 0 failed), clean. The refactor is the right seam:
|
||||
one tokenizer, one pure encoder, and range/full provably cannot drift —
|
||||
QA's byte-for-byte comparison of a 41k-token corpus file against the
|
||||
pre-refactor binary is the strongest possible form of "the factoring
|
||||
changed nothing". The delta design's judgment calls are all correct:
|
||||
range answers carrying no resultId (a delta must never diff against a
|
||||
partial view), a per-answer counter separate from the shared diagnostics
|
||||
generation, and prefix/suffix-with-cap over anything cleverer — with the
|
||||
round-trip property, not minimality, as the contract.
|
||||
|
||||
Two QA results deserve the record: the two independently written edit
|
||||
appliers never disagreed across 200 random pairs, and the overlap cap was
|
||||
broken on purpose twice (dev and QA separately) with the suite catching
|
||||
it both times. One cosmetic correction accepted from the QA log: the work
|
||||
log names `repeated_lines_of_verilog_are_the_same_trap_on_real_tokens`
|
||||
among the tests that fail with the cap reverted; QA's re-run shows that
|
||||
particular pair breaks the match earlier and that test passes — the trap
|
||||
is real but is caught by the other ten failures. The work log stands as
|
||||
the dev's account, with the QA log as the precise version. Accepted as
|
||||
shipped.
|
||||
Reference in new issue
Block a user