Cursor answers binary-search the token stream instead of sweeping it

Expand-selection, on-type formatting, the completion scope gates and
the inline template trigger each walked every token in the file to
find the one at the cursor. The stream is sorted by start and does not
overlap, so the position is a binary search: 77 µs → 20 ns in a
10 000-line buffer, and 130 µs → 36 ns for completion's balanced
window, which had no upper bound and so swept the whole file to reach
a window a few dozen tokens wide.

Two primitives rather than one, and deliberately not `token_at`:
`selection.rs`'s `covers` takes `span.end` inclusively, so at a byte
two tokens share, the sweep returned the *earlier* token where
`token_at` returns the later one. Reaching for the existing helper
would have changed an answer.

No answer changes. Each swap is pinned by a test comparing the new
expression against the predicate it replaced at every byte of a buffer
written to be full of touching tokens, and the precondition they all
rest on — that the stream rises and never overlaps — is pinned
separately, so it is the test that fails first if the parser ever
changes shape.

Left alone, with reasons: signature help's paren depth is a function
of every bracket before the cursor and so is inherently a prefix scan;
`pairs.rs` is not a position query; and completion's comment gate
cannot be answered by any search of the stream, because comments are
trivia attached to whichever token happens to be adjacent. That last
one is the remaining per-keystroke whole-buffer walk.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
lucioandClaude Opus 5 committed 2026-08-28 03:16:34 -07:00
1 parent 611dd23069
commit de8a7e129c
5 files changed
+260 -15

No files matched your search

+54 -4
View File
@@ -37,7 +37,7 @@ use vlog_semantic::{Semantics, Symbol, SymbolKind};
use crate::candidates::starts_with_ignore_case;
use crate::pairs;
use crate::state::{Document, Workspace};
use crate::state::{first_token_from, Document, Workspace};
use crate::symbols::kind_label;
use crate::templates::{self, Gate, Template};
@@ -849,9 +849,12 @@ fn enclosing_scopes(tokens: &[Token], at: u32) -> Vec<(&'static str, TextRange)>
/// `for (genvar i = 0; ...) begin` reaches the `;` inside its own header and a
/// `generate begin` reaches `generate`. Whichever comes first decides.
fn is_procedural(tokens: &[Token], offset: u32) -> bool {
let Some(begin) = tokens.iter().position(|token| token.span.start == offset) else {
// A token starting exactly at `offset` is the first one that starts at or
// after it: every earlier token starts before, every later token after.
let begin = first_token_from(tokens, offset);
if tokens.get(begin).map(|token| token.span.start) != Some(offset) {
return false;
};
}
for token in tokens[..begin].iter().rev() {
if PROCEDURAL.iter().any(|kw| token.text == *kw) {
return true;
@@ -866,7 +869,11 @@ fn is_procedural(tokens: &[Token], offset: u32) -> bool {
/// Whether every parenthesis opened between `from` and `at` was closed again.
fn balanced(tokens: &[Token], from: u32, at: u32) -> bool {
let mut depth = 0i32;
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
// The tokens whose start falls in `[from, at)` are a contiguous run,
// because starts rise across the vector — so the filter this replaced was
// reading the whole buffer to reach a window the two bounds name outright.
let window = first_token_from(tokens, from)..first_token_from(tokens, at);
for token in &tokens[window] {
if token.kind != TokenKind::Symbol {
continue;
}
@@ -898,6 +905,49 @@ module sub #(
endmodule
";
/// [`is_procedural`] used to sweep the vector for the token starting at
/// the keyword, and [`balanced`] used to sweep all of it to reach a window
/// two offsets name. Both now binary-search; both must answer exactly what
/// the sweeps answered, at every byte and for every window.
#[test]
fn the_scope_gates_answer_what_their_sweeps_answered() {
let text = crate::state::mixed_buffer(20);
let doc = Document::new(None, text.clone(), &vlog_semantic::WorkspaceIndex::default());
let tokens = &doc.tokens;
for offset in 0..=text.len() as u32 {
let swept = tokens.iter().position(|token| token.span.start == offset);
let searched = {
let begin = first_token_from(tokens, offset);
tokens.get(begin).filter(|token| token.span.start == offset).map(|_| begin)
};
assert_eq!(swept, searched, "the token starting at {offset}");
}
// Every `begin`/`end` opener in the buffer against a spread of cursors
// after it: the two bounds are what pick the window out.
let openers: Vec<u32> = tokens
.iter()
.filter(|t| t.text == "begin" || t.text == "(")
.map(|t| t.span.end)
.collect();
assert!(openers.len() > 20, "premise: plenty of windows to check");
for from in openers {
for at in [from, from + 7, from + 60, from + 400, text.len() as u32] {
let mut depth = 0i32;
for token in tokens.iter().filter(|t| t.span.start >= from && t.span.start < at) {
if token.kind != TokenKind::Symbol {
continue;
}
match token.text.as_str() {
"(" => depth += 1,
")" => depth -= 1,
_ => {}
}
}
assert_eq!(depth == 0, balanced(tokens, from, at), "window {from}..{at}");
}
}
}
/// A scratch workspace root. Removed on drop.
struct Tree {
path: PathBuf,
+30 -4
View File
@@ -281,10 +281,13 @@ fn triggered(doc: &Document, offset: u32) -> Option<(&'static Trigger, Opened)>
// no trailing newline, nothing typed after it yet — it shares the
// trigger token's `span.end`. Skipping it here is what lets a trigger at
// the true end of the file still fire (QA find, 2026-08-25).
let index = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset)?;
//
// Token ends rise across the vector, so the tokens ending at or before
// `offset` are a prefix of it: no token outside that prefix could have
// satisfied the reverse sweep this replaced, and inside it the sweep's
// remaining condition is the `Eof` test alone.
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let index = doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof)?;
let last = doc.tokens.get(index)?;
if last.span.end != offset {
return None;
@@ -412,6 +415,29 @@ mod tests {
(ws, uri, position)
}
/// [`triggered`] used to sweep the token vector backwards from its end for
/// the last non-`Eof` token ending at or before the cursor. It now bounds
/// that sweep with a binary search; the token it lands on must be the same
/// one at every byte.
#[test]
fn the_last_token_before_the_cursor_is_the_one_the_reverse_sweep_found() {
let text = crate::state::mixed_buffer(20);
let uri = path_to_uri(&PathBuf::from("/rtl/top.sv")).expect("uri");
let mut ws = Workspace::default();
ws.set_document(uri.clone(), text.clone());
let doc = ws.document(&uri).expect("open");
for offset in 0..=text.len() as u32 {
let swept = doc
.tokens
.iter()
.rposition(|token| token.kind != TokenKind::Eof && token.span.end <= offset);
let reached = doc.tokens.partition_point(|token| token.span.end <= offset);
let searched =
doc.tokens[..reached].iter().rposition(|token| token.kind != TokenKind::Eof);
assert_eq!(swept, searched, "at offset {offset}");
}
}
/// The same, in a SystemVerilog buffer.
fn asking(text: &str, needle: &str) -> (Workspace, Uri, Position) {
asking_in("/rtl/top.sv", text, needle)
+51 -5
View File
@@ -26,7 +26,7 @@ use vlog_parser::token::{Token, TokenKind};
use crate::format;
use crate::pairs;
use crate::state::Document;
use crate::state::{first_token_from, first_token_reaching, Document};
/// The character the client is told to trigger on. A newline is the one
/// keystroke that opens a line whose indentation nobody has chosen yet.
@@ -71,8 +71,14 @@ fn statement_edit(doc: &Document, position: Position, config: &Config) -> Option
let offset = doc.positions().offset(position);
// The character the client named has to actually be there, and it has to
// be a `;` the lexer sees: one inside a string or a comment ends no
// statement, and re-laying-out its line would be a guess.
let typed = doc.tokens.iter().find(|token| token.span.end == offset)?;
// statement, and re-laying-out its line would be a guess. A token that
// ends exactly at `offset` is the first one that *reaches* it — everything
// before ends earlier, everything after ends later — so a binary search
// finds what the sweep this replaced found.
let typed = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|t| t.span.end == offset)?;
if !typed.is_sym(SEMICOLON) {
return None;
}
@@ -264,9 +270,12 @@ fn inside_a_comment(token: &Token, at: u32) -> bool {
/// line the user has just opened has none.
fn first_on_line(doc: &Document, content: u32) -> Option<&Token> {
let line = doc.line_index.line_col(content).0;
doc.tokens
// Every token before this index starts before `content`, so none of them
// could have satisfied the sweep this replaced; within the tail the sweep's
// remaining condition is the `Eof` test alone.
doc.tokens[first_token_from(&doc.tokens, content)..]
.iter()
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
.find(|token| token.kind != TokenKind::Eof)
.filter(|token| doc.line_index.line_col(token.span.start).0 == line)
}
@@ -646,6 +655,43 @@ mod tests {
f(ws.document(&uri).expect("open"))
}
/// The `;` handler used to sweep the token vector for the token ending at
/// the cursor. Every byte of a buffer full of touching tokens must still
/// name the same token — or no token, where the sweep found none.
#[test]
fn the_token_ending_at_the_cursor_is_the_one_the_sweep_returned() {
let text = crate::state::mixed_buffer(20);
with(&text, |doc| {
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().find(|token| token.span.end == offset);
let searched = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|t| t.span.end == offset);
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
}
});
}
/// The same, for the indent handler's "first token at or after this byte":
/// [`first_on_line`] is compared against the sweep it was written as.
#[test]
fn the_first_token_on_a_line_is_the_one_the_sweep_returned() {
let text = crate::state::mixed_buffer(20);
with(&text, |doc| {
for content in 0..=text.len() as u32 {
let line = doc.line_index.line_col(content).0;
let swept = doc
.tokens
.iter()
.find(|token| token.kind != TokenKind::Eof && token.span.start >= content)
.filter(|token| doc.line_index.line_col(token.span.start).0 == line);
let searched = first_on_line(doc, content);
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at byte {content}");
}
});
}
fn config(indent_width: usize) -> Config {
Config { indent_width, ..Config::default() }
}
+32 -2
View File
@@ -13,7 +13,7 @@ use vlog_parser::ast::{GenBlock, GenElse, GenIf, Item, ItemKind, Stmt, StmtKind}
use vlog_parser::TextRange;
use crate::pairs::analyze;
use crate::state::Document;
use crate::state::{first_token_reaching, Document};
/// One chain per requested position, in the order they were asked for.
///
@@ -41,7 +41,17 @@ fn chain(doc: &Document, offset: u32) -> SelectionRange {
/// source, unordered and possibly overlapping — [`nested`] sorts it out.
fn enclosing(doc: &Document, offset: u32) -> Vec<TextRange> {
let mut spans = Vec::new();
if let Some(token) = doc.tokens.iter().find(|token| covers(token.span, offset)) {
// The first token that reaches `offset` is the first that can cover it,
// and — because the tokens after it all start no earlier — the only one
// the sweep this replaced could ever have returned. Note that `covers`
// takes `span.end` inclusively, so this is deliberately *not*
// `Document::token_at`: at a byte two adjacent tokens share, the sweep
// answered with the earlier one and so does this.
if let Some(token) = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|token| covers(token.span, offset))
{
spans.push(token.span);
}
items(&doc.tree.items, offset, &mut spans);
@@ -219,6 +229,26 @@ mod tests {
Document::new(None, text.to_string(), &WorkspaceIndex::default())
}
/// The innermost step of a chain used to come from a sweep of the whole
/// token vector; it now comes from a binary search. `covers` takes
/// `span.end` inclusively, so at a byte two adjacent tokens share the
/// sweep answered with the earlier of the two — this pins that the search
/// answers with the earlier one too, at every byte of a buffer written to
/// have plenty of them.
#[test]
fn the_innermost_step_is_the_token_the_sweep_returned_at_every_offset() {
let text = crate::state::mixed_buffer(20);
let doc = doc_of(&text);
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().find(|token| covers(token.span, offset));
let searched = doc
.tokens
.get(first_token_reaching(&doc.tokens, offset))
.filter(|token| covers(token.span, offset));
assert_eq!(swept.map(|t| t.span), searched.map(|t| t.span), "at offset {offset}");
}
}
/// The chain for the first occurrence of `needle`, as the source text of
/// each step, innermost first.
fn steps(text: &str, needle: &str) -> Vec<String> {
+93
View File
@@ -137,6 +137,60 @@ impl Document {
}
}
// ----------------------------------------------------------------------
// Finding a token by offset without sweeping the buffer
// ----------------------------------------------------------------------
//
// The lexer emits tokens in source order and they never overlap, so
// `span.start` and `span.end` both rise across the vector: `end[i] <=
// start[i+1] <= end[i+1]`. That makes both predicates below monotone, which
// is the whole precondition `partition_point` needs. Every handler that used
// to sweep the vector looking for a token at the cursor is one comparison
// away from one of these two indices — see
// `docs/features/interactive-latency/README.md` for the per-call-site
// argument that each swap returns exactly what the sweep returned.
/// The index of the first token that **reaches** `offset` — the first with
/// `span.end >= offset`. `tokens.len()` when none does.
///
/// Every token before it ends strictly before `offset`, so it cannot cover,
/// end at, or contain `offset`. The token *at* this index is therefore the
/// first candidate any such question has.
pub fn first_token_reaching(tokens: &[Token], offset: u32) -> usize {
tokens.partition_point(|token| token.span.end < offset)
}
/// The index of the first token that **begins** at or after `offset` — the
/// first with `span.start >= offset`. `tokens.len()` when none does.
pub fn first_token_from(tokens: &[Token], offset: u32) -> usize {
tokens.partition_point(|token| token.span.start < offset)
}
/// A buffer of `blocks` repeated blocks, for the tests that check a binary
/// search against the sweep it replaced.
///
/// Deliberately awkward: tokens written with no space between them (`a=b;`),
/// line and block comments, a string, nested `begin`/`end` and several depths
/// of parentheses. The offsets those tests walk are *every byte*, and the ones
/// that could tell a binary search from a sweep are exactly the bytes two
/// tokens share — which only adjacent punctuation produces.
#[cfg(test)]
pub fn mixed_buffer(blocks: usize) -> String {
let mut src = String::from("module mixed (input logic clk, output logic [7:0] q);\n");
for n in 0..blocks {
src.push_str(&format!(
" // block {n}\n \
wire [7:0] w{n};assign w{n}=(q[0]?8'd1:8'd2)+{{4'h0,4'hF}};\n \
/* {n} */ always @(posedge clk) begin\n \
if (w{n}[0]) begin q<=w{n}; end else begin q<=8'd0; end\n \
end\n \
initial $display(\"block {n}\", w{n});\n"
));
}
src.push_str("endmodule\n");
src
}
/// What the scope ladder decided: the files to index, the directories an
/// `` `include`` in them is looked for in, and what to tell the user.
#[derive(Default)]
@@ -931,6 +985,45 @@ mod tests {
Uri::from_str(s).expect("test uri parses")
}
/// The precondition both binary searches rest on. If the lexer ever emits
/// a token out of order, or two tokens that overlap, `partition_point`'s
/// predicates stop being monotone and every handler that calls
/// [`first_token_reaching`] or [`first_token_from`] starts answering
/// something else. This is the test that would fail first.
#[test]
fn the_token_stream_rises_and_never_overlaps() {
let text = mixed_buffer(20);
let doc = Document::new(None, text, &WorkspaceIndex::default());
assert!(doc.tokens.len() > 500, "premise: a stream worth searching");
for pair in doc.tokens.windows(2) {
assert!(pair[0].span.start <= pair[1].span.start, "{pair:?}");
assert!(pair[0].span.end <= pair[1].span.start, "overlapping tokens: {pair:?}");
assert!(pair[0].span.start <= pair[0].span.end, "an inverted span: {pair:?}");
}
}
/// Both searches, against the sweep they stand in for, at every byte of a
/// buffer full of tokens that touch.
#[test]
fn every_offset_finds_the_token_a_sweep_would_have_found() {
let text = mixed_buffer(20);
let doc = Document::new(None, text.clone(), &WorkspaceIndex::default());
for offset in 0..=text.len() as u32 {
let swept = doc.tokens.iter().position(|t| t.span.end >= offset);
assert_eq!(
first_token_reaching(&doc.tokens, offset),
swept.unwrap_or(doc.tokens.len()),
"first token reaching {offset}"
);
let swept = doc.tokens.iter().position(|t| t.span.start >= offset);
assert_eq!(
first_token_from(&doc.tokens, offset),
swept.unwrap_or(doc.tokens.len()),
"first token from {offset}"
);
}
}
#[test]
fn a_document_analyzes_a_clean_file() {
let mut ws = Workspace::default();