diff --git a/TODO.md b/TODO.md index ccef98e..fceed2b 100644 --- a/TODO.md +++ b/TODO.md @@ -780,6 +780,14 @@ and are not gaps. persistent index cache logs `cached:` rather than `indexing:` and is counted in the `end` message — `860 files indexed, 860 from cache` — so a rescan that flew past says why. + → **The other half of the size story, 2026-08-27** + (`docs/features/large-file-mode/README.md`): the walk cap covers files + nobody opened, and `lucisv.largeFile.threshold` (4 MiB) now covers the file + that *is* open. Over it, a buffer is line-indexed and nothing else — 41 ms + for 100 MB — coloured a viewport at a time by `semanticTokens/range`, + answered `null`/empty everywhere else, and left out of the index entirely + (the one exception to "an open buffer is never capped"). It logs + `large-file fast path: ( bytes)` once per buffer. Everything else above — the capability gate, the token scheme, the create's ignored answer, the ordering against the republish — is unchanged. diff --git a/crates/lucisv_server/src/convert.rs b/crates/lucisv_server/src/convert.rs index c968df0..cdf01be 100644 --- a/crates/lucisv_server/src/convert.rs +++ b/crates/lucisv_server/src/convert.rs @@ -35,6 +35,13 @@ impl<'a> Positions<'a> { Position { line: line - 1, character: utf16_len(slice) } } + /// A cursor for converting many byte offsets in one non-decreasing sweep, + /// in amortized O(1) each rather than [`position`](Self::position)'s + /// O(offset within its line). + pub fn walker(&self) -> PositionWalker<'_> { + PositionWalker { positions: self, line: 0, line_start: 0, cursor: 0, units: 0 } + } + /// The byte offset of an LSP position, clamped into the document. pub fn offset(&self, pos: Position) -> u32 { let Some(line) = self.index.line_range(pos.line.saturating_add(1)) else { @@ -112,6 +119,62 @@ impl<'a> Positions<'a> { } } +/// A monotonic byte-offset → [`Position`] cursor, for a caller that has a +/// whole sequence of offsets to convert and already has them in order. +/// +/// [`Positions::position`] measures a line from its start on every call, which +/// is free on ordinary source and quadratic when thousands of tokens sit on +/// **one** very long line — the netlist shape the large-file fast path exists +/// for, where it cost seconds per keystroke. The walker carries the +/// measurement forward instead: one line lookup per call, and each byte of a +/// line counted once however many offsets fall on it. +/// +/// **Total, not merely fast.** An offset below the last one is not an error +/// and never panics: the walker restarts at that line's start and re-measures, +/// which is exactly the work [`Positions::position`] would have done. So every +/// answer is that function's answer — by construction, and pinned by +/// `the_walker_agrees_with_the_per_call_converter_on_every_shape`. +pub struct PositionWalker<'a> { + positions: &'a Positions<'a>, + /// The 1-based line the cursor sits on. Zero before the first call, which + /// is a line number no offset has, so the first call always restarts. + line: u32, + /// The byte offset that line starts at. + line_start: u32, + /// How far into the text the cursor has measured, on that line. + cursor: u32, + /// UTF-16 units of `line_start..cursor`, before the `\r` rule below. + units: u32, +} + +impl PositionWalker<'_> { + /// The LSP position of a byte offset — [`Positions::position`]'s answer, + /// reached without re-measuring the line for offsets already passed. + pub fn position(&mut self, offset: u32) -> Position { + let offset = self.positions.floor_boundary(offset); + let (line, _) = self.positions.index.line_col(offset); + if line != self.line || offset < self.cursor { + self.line = line; + self.line_start = self.positions.index.line_range(line).map_or(0, |r| r.start); + self.cursor = self.line_start; + self.units = 0; + } + let step = self.positions.text.get(self.cursor as usize..offset as usize).unwrap_or(""); + self.units += utf16_len(step); + self.cursor = offset; + // The one `\r` `Positions::position`'s `strip_suffix` would drop: LSP + // line content excludes the whole `\r\n`, and `\r` is one UTF-16 unit. + let carriage = offset > self.line_start + && self.positions.text.as_bytes().get(offset as usize - 1) == Some(&b'\r'); + Position { line: line - 1, character: self.units - u32::from(carriage) } + } + + /// The LSP range of a byte range, whose two ends are in order already. + pub fn range(&mut self, span: TextRange) -> Range { + Range { start: self.position(span.start), end: self.position(span.end) } + } +} + /// How many UTF-16 code units a string occupies — the unit LSP counts in. fn utf16_len(s: &str) -> u32 { s.chars().map(|c| c.len_utf16() as u32).sum() @@ -283,6 +346,171 @@ mod tests { }); } + // ------------------------------------------------------------------ + // the monotonic walker + // ------------------------------------------------------------------ + + /// A fixed-seed linear congruential generator — deterministic randomness + /// with no dependency. The constants are Knuth's MMIX, as `sync.rs` and + /// `tokens.rs` use. + 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) + } + } + + /// Every shape a byte → position converter has to survive: multi-byte and + /// astral characters, CRLF, empty lines, a last line with no terminator, + /// and a buffer that is one enormous line — the shape the walker exists + /// for. + fn fixtures() -> Vec { + let mut giant = String::from("module m; wire "); + for n in 0..2_000 { + giant.push_str(&format!("a{n},")); + } + giant.push_str("last;\nendmodule\n"); + let mut wide_and_wide = String::from("// é ✓ 🎉 "); + for n in 0..500 { + wide_and_wide.push_str(&format!("würe_{n}_✓, ")); + } + wide_and_wide.push_str("\r\nendmodule\n"); + vec![ + String::new(), + "module m;\nendmodule\n".to_string(), + "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule".to_string(), + "ab\r\ncd\r\n\r\nef\r\n".to_string(), + "\n".repeat(50), + giant, + wide_and_wide, + ] + } + + #[test] + fn the_walker_agrees_with_the_per_call_converter_on_every_shape() { + let mut rng = Lcg(0x5EEDA11); + for text in fixtures() { + let index = LineIndex::new(&text); + let positions = Positions::new(&text, &index); + let len = text.len() as u64; + for trial in 0..20 { + // Two strides, alternating: a crawl of a few bytes at a time + // (many offsets on one line, which is what the walker is for) + // and one that crosses the whole fixture in a few dozen steps. + let stride = if trial % 2 == 0 { 4 } else { (len / 20).max(1) }; + let mut offset = rng.below(len + 1) as u32; + let mut walker = positions.walker(); + for _ in 0..60 { + assert_eq!( + walker.position(offset), + positions.position(offset), + "{text:?} at {offset}" + ); + offset += rng.below(stride * 2) as u32; + } + } + } + } + + #[test] + fn the_walker_agrees_at_every_byte_of_a_gnarly_buffer() { + // Ascending one byte at a time walks through the middle of every + // multi-byte character and over both bytes of every `\r\n`. + let text = "// é ✓ 🎉\r\nmodule mü;\n\r\n wire ✓a;\r\nendmodule"; + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + let mut walker = positions.walker(); + for offset in 0..=text.len() as u32 + 2 { + assert_eq!(walker.position(offset), positions.position(offset), "at {offset}"); + } + } + + #[test] + fn a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position() { + // Out of order is debug-unreachable for the callers, but the walker + // is total: a backwards offset restarts the measurement rather than + // returning a stale column. + let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule"; + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + let mut rng = Lcg(0xBACC1); + let mut walker = positions.walker(); + for _ in 0..500 { + let offset = rng.below(text.len() as u64 + 4) as u32; + assert_eq!(walker.position(offset), positions.position(offset), "at {offset}"); + } + } + + /// QA attack (fix-round re-verification): the walker's restart is a + /// per-line promise, not a per-document one. Two huge lines far apart, + /// hit in alternation — the shape that would expose an accidental + /// document-wide rescan hiding inside the "reset to line start" path. + /// Each call still answers `Positions::position`'s answer exactly, and + /// (checked by hand alongside this test, not asserted here to keep the + /// test itself fast and non-flaky) costs only that one line's length, + /// never the whole document's. + #[test] + fn a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly() { + let mut text = String::new(); + text.push_str(&"a".repeat(20_000)); + text.push('\n'); + text.push_str(&"b".repeat(20_000)); + text.push('\n'); + let index = LineIndex::new(&text); + let positions = Positions::new(&text, &index); + let line1_positions = [0u32, 1, 5_000, 19_999, 20_000]; + let line2_start = 20_001u32; + let line2_positions = + [line2_start, line2_start + 1, line2_start + 5_000, line2_start + 19_999]; + let mut walker = positions.walker(); + for round in 0..50 { + let (a, b) = line1_positions + .iter() + .zip(line2_positions.iter().cycle()) + .nth(round % line1_positions.len()) + .expect("non-empty"); + for &offset in [*a, *b].iter() { + assert_eq!( + walker.position(offset), + positions.position(offset), + "round {round}, offset {offset}" + ); + } + } + } + + #[test] + fn the_walkers_range_is_the_per_call_range() { + let text = "module m;\r\n wire ✓a, b, c;\nendmodule\n"; + let index = LineIndex::new(text); + let positions = Positions::new(text, &index); + let mut walker = positions.walker(); + for span in [ + TextRange::new(0, 6), + TextRange::new(9, 11), + TextRange::new(13, 17), + TextRange::new(20, 21), + TextRange::new(30, text.len() as u32), + ] { + assert_eq!(walker.range(span), positions.range(span), "{span:?}"); + } + } + + #[test] + fn a_walker_over_an_empty_document_answers_the_one_position_there_is() { + with("", |p| { + let mut walker = p.walker(); + assert_eq!(walker.position(0), pos(0, 0)); + assert_eq!(walker.position(99), pos(0, 0)); + }); + } + #[test] fn an_empty_document_has_one_position() { with("", |p| { diff --git a/crates/lucisv_server/src/diagnostics.rs b/crates/lucisv_server/src/diagnostics.rs index 0426478..c303fe2 100644 --- a/crates/lucisv_server/src/diagnostics.rs +++ b/crates/lucisv_server/src/diagnostics.rs @@ -24,6 +24,15 @@ pub const SOURCE: &str = "lucisv"; /// error rather than add an opinion, and they exist at all only when the parse /// already failed (`pairs::missing_end_diagnostics`). pub fn all(doc: &Document) -> Vec { + // A buffer on the large-file fast path was never parsed, so there is + // nothing to say about it — and both passes below would read its *text* + // (the lint context builds one, the fence filter scans for them), which is + // the whole-file work the fast path exists to skip. The empty list is not + // a silent no-op either: it is what clears the squiggles a buffer that has + // just grown past the threshold left behind. + if doc.large { + return Vec::new(); + } let mut all = diagnostics(doc); all.extend(crate::pairs::missing_end_diagnostics(doc)); all.extend(crate::lint::diagnostics(doc)); diff --git a/crates/lucisv_server/src/file_ops.rs b/crates/lucisv_server/src/file_ops.rs index 20dd517..8104cb5 100644 --- a/crates/lucisv_server/src/file_ops.rs +++ b/crates/lucisv_server/src/file_ops.rs @@ -599,6 +599,37 @@ mod tests { ); } + /// Renaming a file that is open **on the large-file fast path** + /// (`docs/features/large-file-mode/README.md`). The renamed file's own + /// `` `include``s (it has none here — a netlist would not) are out of + /// `will_rename`'s sweep because `Workspace::sources()` already leaves a + /// fast-path buffer out entirely; what this pins is the other half: an + /// **unrelated** small file's include *of* the large file still resolves + /// and still gets rewritten, because resolution walks the filesystem + /// (`IncludeGraph::resolve`, `Path::is_file`) rather than the source list + /// the fast-path buffer was excluded from. + #[test] + fn renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it() { + let tree = Tree::new("largerename"); + let net = tree.write("rtl/net.v", "module net;\nendmodule\n"); + let top = tree.write("rtl/top.sv", "`include \"net.v\"\nmodule t;\nendmodule\n"); + tree.write("files.f", "rtl/top.sv\nrtl/net.v\n"); + let mut ws = tree.workspace(); + ws.set_client_settings(crate::settings::ClientSettings { + filelist: Some(tree.path.join("files.f").display().to_string()), + large_file_threshold: 10, + ..Default::default() + }); + let net_uri = path_to_uri(&net).expect("uri"); + // Padded past the 10-byte test threshold, so it opens on the fast path. + ws.set_document(net_uri.clone(), format!("module net;\nendmodule\n{}", " ".repeat(20))); + assert!(ws.document(&net_uri).expect("open").large, "premise: the fast path"); + + let rewrite = will_rename(&ws, &[tree.rename("rtl/net.v", "rtl/netlist.v")]); + assert!(rewrite.warnings.is_empty(), "{:?}", rewrite.warnings); + assert_eq!(only_file(&rewrite), (uri_of(&top), vec!["netlist.v".to_string()])); + } + #[test] fn a_cross_directory_rename_re_spells_through_an_incdir() { let tree = Tree::new("crossdir"); diff --git a/crates/lucisv_server/src/large.rs b/crates/lucisv_server/src/large.rs new file mode 100644 index 0000000..07b90d3 --- /dev/null +++ b/crates/lucisv_server/src/large.rs @@ -0,0 +1,897 @@ +//! The large-file fast path: what a buffer nobody lexed can still answer. +//! +//! A buffer over `lucisv.largeFile.threshold` is opened by +//! [`crate::state::Document::large`] — one newline scan, no lex, no parse, no +//! semantics, no index. This module is everything that then reads such a +//! buffer *on demand*: +//! +//! * [`window`] lexes one viewport's worth of source for +//! `textDocument/semanticTokens/range`, which is what paints the file; +//! * [`definition`] and [`references`] scan the buffer once per request for a +//! name. +//! +//! Nothing here is exact, and the rules it approximates by are stated in +//! `docs/features/large-file-mode/README.md`. The contract is only that an +//! answer costs a bounded amount of work and never a pass over the whole +//! file — except the two scans, which are one linear pass and are measured. + +use vlog_parser::token::Token; +use vlog_parser::{tokenize, LineIndex, TextRange}; + +use crate::state::Document; + +/// How far back [`inside_block_comment`] looks for the marker that decides +/// whether a window opens inside `/* ... */`. +/// +/// 64 KiB. A block comment longer than this is a licence header nobody is +/// scrolled to the middle of, and the cost of the decision has to stay flat in +/// the file's size: this is the one backwards read the fast path does, and it +/// is a `memchr`-shaped search over a fixed slice however big the file is. +const BACKSCAN: u32 = 64 * 1024; + +/// The most source one window may lex, 1 MiB. +/// +/// A client is free to ask for `semanticTokens/range` over the whole document +/// — VS Code's own `_provideDocumentRangeSemanticTokens` command does exactly +/// that — and answering it over 100 MB would be the whole-file pass this mode +/// exists to avoid. A viewport plus the pages above and below it is a few tens +/// of kilobytes, so the cap is three orders of magnitude clear of anything an +/// editor asks for while scrolling. +const MAX_WINDOW: u32 = 1024 * 1024; + +/// How many times [`lex`] may shrink a window that does not lex before giving +/// up on it. Each attempt drops the lines from the failure onwards, and the +/// failure moves backwards every time, so this is a belt-and-braces bound +/// rather than a number anything real reaches. +const SHRINK_ATTEMPTS: usize = 4; + +/// The most occurrences `textDocument/references` reports on a large buffer. +/// A name in a netlist can occur a hundred thousand times, and a reference +/// list nobody can read costs the editor more than it gives. +pub const REFERENCE_LIMIT: usize = 1000; + +/// One window of a large buffer, lexed. +/// +/// Both fields are in **document** offsets: the caller never sees the slice +/// the lexer actually ran on. +pub struct Window { + /// What the lexer made of the window. Empty when the window could not be + /// lexed at all, which is not an error — it is a window whose text is one + /// unterminated construct. + pub tokens: Vec, + /// Block-comment text the lexer was never shown: the tail of a comment the + /// window opens inside, and the head of one it ends inside. Colouring + /// these is the whole reason the fast path looks backwards at all. + pub comments: Vec, +} + +/// Lex the lines `range` touches, and nothing else. +/// +/// The window is snapped out to whole lines, capped at [`MAX_WINDOW`], and +/// then treated as a self-contained piece of source. The two things that +/// makes wrong, and what is done about each: +/// +/// * **A comment the window opens inside.** Decided by a bounded backwards +/// scan ([`inside_block_comment`]); the tail of the comment is returned as a +/// comment span and the lexer starts after it. +/// * **A construct the window ends inside.** The lexer is all-or-nothing, so +/// an unterminated comment or string at the far edge would cost the whole +/// window; [`lex`] shrinks the window to the last line that does lex, and +/// what is left over is coloured as a comment when it opens one. +pub fn window(doc: &Document, range: lsp_types::Range) -> Window { + let text = &doc.text; + let (start, end) = bounds(&doc.line_index, text.len() as u32, range); + let mut comments = Vec::new(); + let mut from = start; + if inside_block_comment(text, start) { + let Some(rest) = text.get(start as usize..end as usize) else { + return Window { tokens: Vec::new(), comments }; + }; + match rest.find("*/") { + // The comment ends inside the window: colour its tail and lex + // from the first byte after it. + Some(at) => { + from = start + at as u32 + 2; + comments.push(TextRange::new(start, from)); + } + // The whole window is inside one comment. Nothing to lex at all, + // which is the cheapest window there is. + None => { + comments.push(TextRange::new(start, end)); + return Window { tokens: Vec::new(), comments }; + } + } + } + let Some(slice) = text.get(from as usize..end as usize) else { + return Window { tokens: Vec::new(), comments }; + }; + let (mut tokens, lexed) = lex(slice); + for token in &mut tokens { + rebase(token, from); + } + if let Some(tail) = trailing_comment(slice, lexed) { + comments.push(TextRange::new(from + tail.start, from + tail.end)); + } + Window { tokens, comments } +} + +/// The byte range one `Range` asks about, snapped out to whole lines and +/// capped. +/// +/// Both ends land on a character boundary: a line start and a line end always +/// do, and the cap is floored onto one. +fn bounds(index: &LineIndex, len: u32, range: lsp_types::Range) -> (u32, u32) { + let last = index.line_count(); + let first_line = (range.start.line + 1).min(last); + let last_line = (range.end.line + 1).clamp(first_line, last); + let start = index.line_range(first_line).map_or(0, |line| line.start); + let mut end = index.line_range(last_line).map_or(len, |line| line.end); + if end.saturating_sub(start) > MAX_WINDOW { + // Snapped to the line the cap lands in where that helps, and cut + // mid-line where it does not: a single line longer than the cap is + // exactly the netlist shape the cap is for. A token cut in half at the + // far edge still colours as what it started as. + let capped = start + MAX_WINDOW; + end = match index.line_range(index.line_col(capped).0) { + Some(line) if line.end <= capped => line.end, + _ => capped, + }; + } + (start, end.max(start)) +} + +/// Whether the byte at `at` is inside a `/* ... */` comment, as far as a +/// backwards scan of at most [`BACKSCAN`] bytes can tell. +/// +/// **Deliberately approximate.** It reads the last `/*` or `*/` before `at` +/// and believes it: a `/*` written inside a string or after a `//` fools it, +/// and so does a comment whose opener is further back than the budget, in +/// which case the answer is "code". Both mis-colour a screen and neither can +/// corrupt anything, which is the trade the whole mode is built on. +fn inside_block_comment(text: &str, at: u32) -> bool { + let at = at as usize; + let mut from = at.saturating_sub(BACKSCAN as usize); + while from < at && !text.is_char_boundary(from) { + from += 1; + } + let Some(hay) = text.get(from..at) else { return false }; + match (hay.rfind("/*"), hay.rfind("*/")) { + (Some(open), Some(close)) => open > close, + (Some(_), None) => true, + _ => false, + } +} + +/// Lex as much of `slice` as lexes, reporting how many bytes that was. +/// +/// The lexer is all-or-nothing (`docs/features/error-recovery/README.md`), and +/// a window cut out of the middle of a file ends wherever the viewport ended — +/// so an unterminated comment or string at the far edge is the *normal* case +/// here, not a broken file. Its error names the line it gave up on, so the +/// retry drops that line and everything after it. +fn lex(slice: &str) -> (Vec, u32) { + let mut end = slice.len(); + for _ in 0..SHRINK_ATTEMPTS { + let Some(head) = slice.get(..end) else { return (Vec::new(), 0) }; + match tokenize(head) { + Ok(tokens) => return (tokens, end as u32), + Err(problem) => match line_start(head, problem.line) { + // Line 1 failed: there is nothing left to keep. + Some(0) | None => return (Vec::new(), 0), + Some(shorter) => end = shorter, + }, + } + } + (Vec::new(), 0) +} + +/// The byte offset of a 1-based line of `text`, or `None` when it has no such +/// line. Used only on the failure path, so it walks rather than indexing. +fn line_start(text: &str, line: u32) -> Option { + if line <= 1 { + return Some(0); + } + let mut seen = 1; + for (at, byte) in text.bytes().enumerate() { + if byte == b'\n' { + seen += 1; + if seen == line { + return Some(at + 1); + } + } + } + None +} + +/// The block comment the leftovers of a shrunk window open, if they open one. +/// +/// A banner comment crossing the bottom of the viewport is the shape this is +/// for: the lexer refused the window because of it, and colouring the rest of +/// the window as comment is both what it is and what the *next* window (once +/// the user scrolls) will say too. +fn trailing_comment(slice: &str, lexed: u32) -> Option { + let rest = slice.get(lexed as usize..)?; + let open = rest.find("/*")?; + // A `/*` that is closed inside the leftovers was not what stopped the + // lexer, so this is not the shape above and guessing would be wrong. + if rest[open..].contains("*/") { + return None; + } + Some(TextRange::new(lexed + open as u32, lexed + rest.len() as u32)) +} + +/// Move a token, and the comments hanging off it, from window offsets to +/// document offsets. +fn rebase(token: &mut Token, by: u32) { + token.span = shift(token.span, by); + for comment in &mut token.leading { + comment.span = shift(comment.span, by); + } + if let Some(comment) = &mut token.trailing { + comment.span = shift(comment.span, by); + } +} + +fn shift(span: TextRange, by: u32) -> TextRange { + TextRange::new(span.start + by, span.end + by) +} + +// ---------------------------------------------------------------------- +// the two scans +// ---------------------------------------------------------------------- + +/// The keywords that make the identifier after them a declaration, as far as +/// the fast path is concerned. +/// +/// A heuristic, and a small one on purpose: it is read backwards from an +/// occurrence, not parsed, so a declaration written any other way (a port +/// listed in an ANSI header after its direction and type, a `typedef`'s new +/// name, an instance name) is simply not found and the request answers +/// nothing. Every word here is a real keyword — pinned by a test against +/// `vlog_parser::KEYWORDS`, so a typo cannot sit here quietly. +const DECLARATORS: [&str; 22] = [ + "module", + "macromodule", + "interface", + "package", + "program", + "primitive", + "class", + "function", + "task", + "input", + "output", + "inout", + "wire", + "reg", + "logic", + "bit", + "integer", + "int", + "real", + "genvar", + "parameter", + "localparam", +]; + +/// The identifier `offset` sits in, if it sits in one. +pub fn word_at(text: &str, offset: u32) -> Option { + let bytes = text.as_bytes(); + let at = (offset as usize).min(bytes.len()); + let mut start = at; + while start > 0 && is_word(bytes[start - 1]) { + start -= 1; + } + let mut end = at; + while end < bytes.len() && is_word(bytes[end]) { + end += 1; + } + // A cursor in whitespace between two words has an empty range, and an + // empty name would match everywhere. + (start < end).then(|| TextRange::new(start as u32, end as u32)) +} + +/// Where the name at `offset` looks declared: the first occurrence of it +/// preceded by a declaring keyword, or nothing. +/// +/// One linear pass over the buffer, which is what a request on a file nothing +/// has indexed costs. The measurement is in the feature README. +pub fn definition(doc: &Document, offset: u32) -> Option { + let name = word_at(&doc.text, offset)?; + let name = doc.text.get(name.as_range())?; + occurrences(&doc.text, name).find(|at| declares(&doc.text, *at)) +} + +/// Every occurrence of the name at `offset`, capped at [`REFERENCE_LIMIT`]. +/// +/// Occurrences of the *text*, whole-word: this buffer has no scopes, so a +/// local `i` in one module and a local `i` in another are one answer. That is +/// the honest thing a text scan can say, and it is what the README calls +/// checking-light. +pub fn references(doc: &Document, offset: u32, include_declaration: bool) -> Vec { + let Some(name) = word_at(&doc.text, offset) else { return Vec::new() }; + let Some(text) = doc.text.get(name.as_range()) else { return Vec::new() }; + let declaration = (!include_declaration).then(|| definition(doc, offset)).flatten(); + occurrences(&doc.text, text) + .filter(|found| Some(*found) != declaration) + .take(REFERENCE_LIMIT) + .collect() +} + +/// Every whole-word occurrence of `name` in `text`, in order. +fn occurrences<'a>(text: &'a str, name: &'a str) -> impl Iterator + 'a { + let bytes = text.as_bytes(); + text.match_indices(name).filter_map(move |(at, _)| { + let before = at.checked_sub(1).map(|i| bytes[i]); + let after = bytes.get(at + name.len()).copied(); + let bounded = !before.is_some_and(is_word) && !after.is_some_and(is_word); + bounded.then(|| TextRange::new(at as u32, (at + name.len()) as u32)) + }) +} + +/// Whether the word before this occurrence declares it. +fn declares(text: &str, occurrence: TextRange) -> bool { + let bytes = text.as_bytes(); + let mut end = occurrence.start as usize; + while end > 0 && bytes[end - 1].is_ascii_whitespace() { + end -= 1; + } + let mut start = end; + while start > 0 && is_word(bytes[start - 1]) { + start -= 1; + } + text.get(start..end).is_some_and(|word| DECLARATORS.contains(&word)) +} + +/// Whether a byte can be part of an identifier. `$` is in, for the system +/// tasks; the escaped-identifier form (`\name `) is not modelled at all. +fn is_word(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$' +} + +#[cfg(test)] +mod tests { + use super::*; + use lsp_types::{Position, Range}; + use std::path::PathBuf; + + /// A fast-path document over `text`. + fn large(text: &str) -> Document { + Document::large(Some(PathBuf::from("/rtl/net.v")), text.to_string()) + } + + fn range(from: u32, to: u32) -> Range { + Range { + start: Position { line: from, character: 0 }, + end: Position { line: to, character: 0 }, + } + } + + /// The text of every token a window produced, in order. + fn words(doc: &Document, window: &Window) -> Vec { + window + .tokens + .iter() + .filter(|t| t.kind != vlog_parser::token::TokenKind::Eof) + .map(|t| doc.text[t.span.as_range()].to_string()) + .collect() + } + + // ------------------------------------------------------------------ + // the window + // ------------------------------------------------------------------ + + #[test] + fn a_window_lexes_its_own_lines_and_reports_document_offsets() { + let doc = large("module a;\nwire b;\nwire c;\nendmodule\n"); + let window = window(&doc, range(1, 2)); + assert_eq!(words(&doc, &window), ["wire", "b", ";", "wire", "c", ";"]); + // The spans are the document's, not the slice's: the first token is + // `wire` on line 1, which starts at byte 10. + assert_eq!(window.tokens[0].span.start, 10); + } + + #[test] + fn a_window_starting_mid_line_is_snapped_back_to_the_line_start() { + let doc = large("module a;\nwire b;\n"); + let mid = Range { + start: Position { line: 1, character: 4 }, + end: Position { line: 1, character: 6 }, + }; + assert_eq!(words(&doc, &window(&doc, mid)), ["wire", "b", ";"]); + } + + #[test] + fn a_window_past_the_end_of_the_file_is_empty_and_does_not_panic() { + let doc = large("module a;\nendmodule\n"); + assert!(words(&doc, &window(&doc, range(900, 999))).is_empty()); + } + + #[test] + fn a_window_opening_inside_a_block_comment_colours_the_tail_and_lexes_the_rest() { + let doc = large("/* a\n b\n c */ wire d;\nwire e;\n"); + // Lines 1..3: the window opens on ` b`, which is inside the comment + // opened on line 0, so the tail up to `*/` is a comment span and the + // lexer only saw what followed it. + let window = window(&doc, range(1, 3)); + assert_eq!(window.comments.len(), 1); + let comment = &doc.text[window.comments[0].as_range()]; + assert!(comment.ends_with("*/"), "{comment:?}"); + assert!(comment.starts_with(" b"), "{comment:?}"); + assert_eq!(words(&doc, &window), ["wire", "d", ";", "wire", "e", ";"]); + } + + #[test] + fn a_window_wholly_inside_a_block_comment_is_one_comment_and_no_tokens() { + let mut text = String::from("/* opener\n"); + for _ in 0..40 { + text.push_str(" still a comment\n"); + } + text.push_str("*/\nwire a;\n"); + let doc = large(&text); + let window = window(&doc, range(10, 20)); + assert!(window.tokens.is_empty()); + assert_eq!(window.comments.len(), 1); + } + + #[test] + fn the_backward_scan_gives_up_beyond_its_budget_and_assumes_code() { + // A block comment opened further back than BACKSCAN: the decision + // cannot be made, and the documented answer is "code". + let mut text = String::from("/* opener\n"); + text.push_str(&" filler filler filler filler\n".repeat(4000)); + assert!(text.len() as u32 > BACKSCAN, "the premise: past the budget"); + text.push_str("wire a;\n"); + let doc = large(&text); + let last = doc.line_index.line_count() - 2; + let window = window(&doc, range(last, last)); + assert!(window.comments.is_empty(), "no comment was detected"); + assert_eq!(words(&doc, &window), ["wire", "a", ";"], "it lexed as code"); + } + + #[test] + fn a_window_ending_inside_a_block_comment_keeps_the_lines_that_lex() { + let doc = large("wire a;\nwire b;\n/* an unterminated banner\n"); + let window = window(&doc, range(0, 2)); + assert_eq!(words(&doc, &window), ["wire", "a", ";", "wire", "b", ";"]); + assert_eq!(window.comments.len(), 1, "the banner is coloured as a comment"); + assert!(doc.text[window.comments[0].as_range()].starts_with("/*")); + } + + #[test] + fn a_window_ending_inside_a_string_keeps_the_lines_that_lex() { + let doc = large("wire a;\n$display(\"unterminated\n"); + let window = window(&doc, range(0, 1)); + assert_eq!(words(&doc, &window), ["wire", "a", ";"]); + assert!(window.comments.is_empty(), "an unterminated string is not a comment"); + } + + #[test] + fn a_window_whose_first_line_cannot_lex_answers_nothing_rather_than_guessing() { + let doc = large("$display(\"unterminated\nwire a;\n"); + let window = window(&doc, range(0, 0)); + assert!(window.tokens.is_empty()); + assert!(window.comments.is_empty()); + } + + #[test] + fn a_window_is_capped_however_much_the_client_asks_for() { + // Every line is 8 bytes, so 200_000 lines is 1.6 MB — a client asking + // for the whole document must still lex at most MAX_WINDOW of it. + let text = "wire a;\n".repeat(200_000); + assert!(text.len() as u32 > MAX_WINDOW, "the premise"); + let doc = large(&text); + let window = window(&doc, range(0, doc.line_index.line_count())); + let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0); + assert!(last <= MAX_WINDOW, "lexed past the cap: {last}"); + assert!(last > MAX_WINDOW - 64, "and up to it: {last}"); + } + + #[test] + fn one_line_longer_than_the_cap_is_cut_rather_than_lexed_whole() { + let mut text = String::from("wire "); + text.push_str(&"a".repeat(MAX_WINDOW as usize + 1000)); + text.push_str(";\n"); + let doc = large(&text); + let window = window(&doc, range(0, 0)); + // It still answers, and it did not read the whole line. + let last = window.tokens.iter().map(|t| t.span.end).max().unwrap_or(0); + assert!(last <= MAX_WINDOW, "{last}"); + } + + #[test] + fn an_empty_buffer_answers_an_empty_window() { + let doc = large(""); + let window = window(&doc, range(0, 10)); + assert!(window.tokens.is_empty() || words(&doc, &window).is_empty()); + assert!(window.comments.is_empty()); + } + + /// QA attack: a buffer of nothing but newlines. Every line is empty, so + /// every byte offset the code touches (line starts, line ends, the + /// backward scan's window) coincides with several others — the shape most + /// likely to trip an off-by-one into an out-of-range slice. + #[test] + fn a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens() { + let doc = large(&"\n".repeat(5_000)); + for (from, to) in [(0, 1), (0, 5000), (4998, 4999), (2500, 2500)] { + let window = window(&doc, range(from, to)); + // Only the EOF token, which every `tokenize` call ends with even + // over blank input — no real token, and no panic getting there. + assert!(words(&doc, &window).is_empty(), "nothing to lex: {from}..{to}"); + } + } + + /// QA attack: a CRLF netlist. `LineIndex` keeps the `\r` as an ordinary + /// byte of its line (`convert.rs`'s own rule), so a window boundary lands + /// right before a `\r` rather than a `\n` — this pins that the window + /// still lexes the same tokens CRLF or not, and that the trailing `\r` on + /// each line does not get coloured as part of the token before it. + #[test] + fn a_crlf_netlist_windows_the_same_as_its_lf_twin() { + let lf = "module m;\r\n wire sig_a;\r\n wire sig_b;\r\nendmodule\r\n"; + let doc = large(lf); + let window = window(&doc, range(1, 2)); + assert_eq!(words(&doc, &window), ["wire", "sig_a", ";", "wire", "sig_b", ";"]); + // No token swallowed the `\r`: every token's text is exactly itself. + for token in &window.tokens { + let text = &doc.text[token.span.as_range()]; + assert!(!text.contains('\r'), "a token ate the line ending: {text:?}"); + } + } + + // ------------------------------------------------------------------ + // the shrink helper on its own + // ------------------------------------------------------------------ + + #[test] + fn lex_reports_how_much_of_the_slice_it_used() { + let (tokens, used) = lex("wire a;\n"); + assert!(!tokens.is_empty()); + assert_eq!(used, 8); + let (tokens, used) = lex("wire a;\n/* open"); + assert!(!tokens.is_empty()); + assert_eq!(used, 8, "the comment line was dropped"); + } + + #[test] + fn line_start_counts_lines_from_one() { + assert_eq!(line_start("a\nb\nc", 1), Some(0)); + assert_eq!(line_start("a\nb\nc", 2), Some(2)); + assert_eq!(line_start("a\nb\nc", 3), Some(4)); + assert_eq!(line_start("a\nb\nc", 4), None); + } + + // ------------------------------------------------------------------ + // definition and references + // ------------------------------------------------------------------ + + const NETLIST: &str = "module top;\n wire sig_a;\n wire sig_b;\n sub u0 (.a(sig_a), \ + .b(sig_b));\n assign sig_a = sig_b;\nendmodule\n"; + + /// The offset of the `n`-th occurrence of `needle`. + fn at(text: &str, needle: &str, n: usize) -> u32 { + text.match_indices(needle).nth(n).expect("occurrence").0 as u32 + } + + #[test] + fn a_declaration_is_found_by_the_keyword_before_it() { + let doc = large(NETLIST); + let found = definition(&doc, at(NETLIST, "sig_a", 2)).expect("a declaration"); + assert_eq!(found.start, at(NETLIST, "sig_a", 0), "the `wire sig_a;` line"); + assert_eq!(&NETLIST[found.as_range()], "sig_a"); + } + + #[test] + fn a_name_no_keyword_introduces_has_no_definition() { + let doc = large(NETLIST); + assert!(definition(&doc, at(NETLIST, "u0", 0)).is_none(), "an instance name"); + } + + #[test] + fn a_cursor_that_is_not_on_a_word_answers_nothing() { + let doc = large(NETLIST); + let space = NETLIST.find(" wire").expect("indent") as u32; + assert!(definition(&doc, space).is_none()); + assert!(references(&doc, space, true).is_empty()); + } + + #[test] + fn references_are_whole_word_and_in_order() { + let doc = large(NETLIST); + let found = references(&doc, at(NETLIST, "sig_a", 0), true); + assert_eq!(found.len(), 3, "declaration, connection, assignment"); + assert!(found.windows(2).all(|pair| pair[0].start < pair[1].start)); + // `sig_a` is not found inside `sig_ab`. + let doc = large("wire sig_ab;\nwire sig_a;\n"); + assert_eq!(references(&doc, at(&doc.text, "sig_a", 1), true).len(), 1); + } + + #[test] + fn excluding_the_declaration_drops_exactly_the_declaration() { + let doc = large(NETLIST); + let with = references(&doc, at(NETLIST, "sig_a", 1), true); + let without = references(&doc, at(NETLIST, "sig_a", 1), false); + assert_eq!(without.len(), with.len() - 1); + assert!(!without.contains(&with[0])); + } + + #[test] + fn the_reference_list_is_capped() { + let text = format!("wire sig;\n{}", "assign x = sig;\n".repeat(REFERENCE_LIMIT + 500)); + let doc = large(&text); + assert_eq!(references(&doc, 5, true).len(), REFERENCE_LIMIT); + } + + // ------------------------------------------------------------------ + // the 100 MB probes + // ------------------------------------------------------------------ + + /// A netlist-shaped buffer of about `bytes` bytes. + /// + /// Instantiation lines, which is what a synthesized netlist really is, with + /// a declaration and a comment every so often so the scans have something + /// to find and the windows have something to colour. + fn netlist(bytes: usize) -> String { + let mut text = String::with_capacity(bytes + 4096); + text.push_str("module netlist_top;\n wire needle;\n"); + let mut n = 0u64; + while text.len() < bytes { + text.push_str(&format!( + " sky130_fd_sc_hd__inv_2 _{n}_ (.A(net{n}), .Y(net{}));\n", + n + 1 + )); + if n.is_multiple_of(500) { + text.push_str(" /* a banner comment, so the windows are not all code */\n"); + text.push_str(" wire net_local;\n"); + } + n += 1; + } + // A second declaration at the far end: a scan for it is the worst + // case, since the answer is the last thing in the file. + text.push_str(" wire tail_needle;\nendmodule\n"); + text + } + + /// **The measurement the feature README quotes.** Ignored by default: it + /// builds a 100 MB buffer, which is not something `cargo test` should do + /// on every run. Run it as + /// `cargo test -p lucisv_server --release -- --ignored --nocapture + /// large::tests::the_hundred_megabyte_probes`. + /// + /// The bounds asserted are deliberately loose — an order of magnitude over + /// what the numbers actually are on the machine this was written on — so + /// the probe fails on a regression in *kind* (someone made the open path + /// scan the file twice, someone made the window lex the document) rather + /// than on a slow CI box. + #[test] + #[ignore = "synthesizes a 100 MB buffer; run with --release --ignored --nocapture"] + fn the_hundred_megabyte_probes() { + use std::time::Instant; + let text = netlist(100 * 1024 * 1024); + let bytes = text.len(); + + let clock = Instant::now(); + let doc = Document::large(Some(PathBuf::from("/rtl/netlist.v")), text); + let open = clock.elapsed(); + + let lines = doc.line_index.line_count(); + let middle = lines / 2; + let viewport = Range { + start: Position { line: middle, character: 0 }, + end: Position { line: middle + 60, character: 0 }, + }; + // Twice: the first call is where any accidental one-off whole-file + // work would hide. + let clock = Instant::now(); + let first = window(&doc, viewport); + let first_window = clock.elapsed(); + let clock = Instant::now(); + let again = window(&doc, viewport); + let second_window = clock.elapsed(); + assert_eq!(first.tokens.len(), again.tokens.len()); + assert!(!first.tokens.is_empty(), "the window really did lex something"); + + // The worst case for both scans: the name is declared in the *last* + // line of the file, so the answer is only found after a whole pass. + let tail = doc.text.rfind("tail_needle").expect("the tail declaration") as u32; + let clock = Instant::now(); + let found = definition(&doc, tail); + let definition_scan = clock.elapsed(); + assert!(found.is_some()); + + let clock = Instant::now(); + let refs = references(&doc, tail, true); + let reference_scan = clock.elapsed(); + assert!(!refs.is_empty()); + + // And the shape that is worst for the search itself: a short name + // that occurs as a *prefix* of a million others, so the whole-word + // filter runs on every one of them. + let common = doc.text.find("net1)").expect("a net use") as u32; + let clock = Instant::now(); + let many = references(&doc, common, true); + let capped_scan = clock.elapsed(); + + eprintln!( + "100 MB probe: {bytes} bytes, {lines} lines\n \ + open (line index only): {open:?}\n \ + semanticTokens/range window (60 lines): {first_window:?} then {second_window:?}\n \ + definition scan (declared in the last line): {definition_scan:?}\n \ + references scan (2 hits, whole file): {reference_scan:?}\n \ + references scan (short name, {} hits among a million prefixes): {capped_scan:?}", + many.len() + ); + + assert!(open.as_millis() < 5_000, "opening cost {open:?}"); + assert!(first_window.as_millis() < 200, "the first window cost {first_window:?}"); + assert!(second_window.as_millis() < 200, "the second window cost {second_window:?}"); + assert!( + definition_scan.as_millis() < 1_000, + "the definition scan cost {definition_scan:?}" + ); + assert!(reference_scan.as_millis() < 1_000, "the reference scan cost {reference_scan:?}"); + assert!(capped_scan.as_millis() < 1_000, "the worst-case scan cost {capped_scan:?}"); + } + + /// What the fast path is worth, measured rather than asserted: the same + /// buffer through [`Document::new`] and through [`Document::large`]. + /// + /// Ten megabytes rather than a hundred, because the point is the *ratio* + /// and because a 100 MB full analysis is minutes and gigabytes — which is + /// itself the finding, and is why the threshold exists. + #[test] + #[ignore = "analyzes a 10 MB buffer in full; run with --release --ignored --nocapture"] + fn the_full_pipeline_probe_says_what_the_fast_path_saves() { + use std::time::Instant; + let text = netlist(10 * 1024 * 1024); + let clock = Instant::now(); + let fast = Document::large(None, text.clone()); + let fast_open = clock.elapsed(); + + let clock = Instant::now(); + let full = Document::new(None, text, &vlog_semantic::WorkspaceIndex::default()); + let full_open = clock.elapsed(); + + eprintln!( + "10 MB open: fast path {fast_open:?} ({} tokens), full pipeline {full_open:?} \ + ({} tokens) — {:.0}x", + fast.tokens.len(), + full.tokens.len(), + full_open.as_secs_f64() / fast_open.as_secs_f64().max(f64::MIN_POSITIVE) + ); + assert!(fast_open < full_open, "the fast path is the fast one"); + } + + #[test] + fn every_declarator_is_a_real_keyword() { + for word in DECLARATORS { + assert!( + vlog_parser::KEYWORDS.contains(&word), + "{word} is not a keyword the lexer knows" + ); + } + } + + /// **QA finding 1 (2026-08-27), fixed and now a gate.** A single line far + /// longer than [`BACKSCAN`], packed with thousands of short tokens rather + /// than one long one — a wide bus concatenation or a one-line generated + /// port list, both ordinary netlist shapes. `window()` itself only ever + /// touches [`MAX_WINDOW`] bytes, so the *lexer* side was always bounded by + /// construction. But colouring the window also converts every token's byte + /// span to a UTF-16 LSP position (`tokens::flatten`), and that conversion + /// used to scan from the **start of the token's line** every time: on an + /// ordinary file a few dozen bytes of work, on a window that is all one + /// line O(line length) per token, i.e. **O(tokens²)**. Measured at + /// 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** across the four sizes below + /// (release) — 4x the time for 2x the tokens, the signature of a quadratic + /// wall rather than the "bounded, however big the file is" cost the + /// feature README promises. + /// + /// `tokens::flatten` now converts through `Positions::walker` + /// (`convert.rs`), which measures each line once however many offsets fall + /// on it. The same four sizes are **1.7 / 3.3 / 6.4 / 13.2 ms** — 2x for + /// 2x, and 596x faster at the top. + /// + /// The bound is wall-clock, loose, and in debug (this test runs in the + /// normal suite): ~4x the measured debug cost of the largest size, which + /// the quadratic version overshoots by more than two orders of magnitude. + /// A regression in *kind* fails it; a slow CI box does not. + #[test] + fn a_window_of_many_tokens_on_one_line_colours_in_linear_time() { + use std::time::Instant; + for count in [5_000u32, 10_000, 20_000, 40_000] { + // One line: `module m; wire a0,a1,...,last;` — realistic in shape + // (a wide declaration), synthetic only in how wide. + let mut text = String::from("module m; wire "); + for n in 0..count { + text.push_str(&format!("a{n},")); + } + text.push_str("last;\nendmodule\n"); + let doc = large(&text); + let clock = Instant::now(); + let window = window(&doc, range(0, 1)); + let lex_elapsed = clock.elapsed(); + assert!(!window.tokens.is_empty()); + let clock2 = Instant::now(); + let data = crate::tokens::semantic_tokens_in_window(&doc, range(0, 1)); + let colour_elapsed = clock2.elapsed(); + eprintln!( + "{count} tokens, {}-byte line: lex {lex_elapsed:?}, colour {colour_elapsed:?}, \ + {} tokens answered", + text.len(), + data.len() / 5 + ); + assert!(!data.is_empty(), "the window really did colour something"); + assert!( + colour_elapsed.as_millis() < COLOUR_BUDGET_MS, + "colouring {count} tokens on one line cost {colour_elapsed:?} — \ + the quadratic conversion is back" + ); + } + } + + /// The wall-clock ceiling the test above holds the colourer to, in a + /// **debug** build: 4.5x the slowest of the four sizes as measured on the + /// machine this was written on (77 ms at 40,000 tokens, ±0.5 ms over + /// four runs), where the quadratic version this replaced would need tens + /// of seconds. + const COLOUR_BUDGET_MS: u128 = 350; + + /// **QA finding 1 (2026-08-27), fixed and now a gate**, on the *other* + /// fast-path consumer of `Positions`: `references`' hits still have to + /// become `lsp_types::Location`s (`Server::large_scan`, `server.rs`), one + /// `Positions::range` each. `large::references` itself was always linear; + /// the wall was entirely in turning up to [`REFERENCE_LIMIT`] hits on one + /// gigantic line into positions — 206 ms → 789 ms → 3.15 s → **12.6 s** + /// for 100 → 800 hits (release), against a scan of 0.9 → 6.4 ms. + /// + /// `large_scan` now walks the hits with one `Positions::walker`, which + /// they are already in ascending order for. This runs at an eighth of the + /// original probe's line lengths so it can live in the normal suite; the + /// bound is debug wall-clock and ~4x the measured cost, which a return of + /// the per-hit rescan overshoots by two orders of magnitude. + #[test] + fn references_on_one_giant_line_locate_their_hits_in_linear_time() { + use std::time::Instant; + for width in [100u32, 200, 400, 800] { + // One line: `wire sig;` filler `sig` filler `sig` ... — `width` + // occurrences of the needle spread over one line, all comfortably + // under REFERENCE_LIMIT so the cap is not what is being timed. + let mut text = String::from("wire sig;"); + for _ in 0..width { + text.push_str(&" filler_word ".repeat(250)); + text.push_str("sig"); + } + text.push('\n'); + let doc = large(&text); + let clock = Instant::now(); + let hits = references(&doc, 5, true); + let scan_elapsed = clock.elapsed(); + assert_eq!(hits.len() as u32, width + 1, "the declaration plus every use"); + let positions = doc.positions(); + let clock2 = Instant::now(); + // Exactly what `Server::large_scan` does with them. + let mut walker = positions.walker(); + for hit in &hits { + std::hint::black_box(walker.range(*hit)); + } + let locate_elapsed = clock2.elapsed(); + eprintln!( + "{width} hits on one {}-byte line: scan {scan_elapsed:?}, locate {locate_elapsed:?}", + text.len() + ); + assert!( + locate_elapsed.as_millis() < LOCATE_BUDGET_MS, + "locating {width} hits on one line cost {locate_elapsed:?} — \ + the per-hit line rescan is back" + ); + } + } + + /// The wall-clock ceiling for the locator above, in a **debug** build: + /// 4.7x the slowest of the four sizes as measured on the machine this was + /// written on (32 ms at 800 hits on a 2.6 MB line, ±0.2 ms over four + /// runs). + const LOCATE_BUDGET_MS: u128 = 150; +} diff --git a/crates/lucisv_server/src/main.rs b/crates/lucisv_server/src/main.rs index 643960c..13cb59a 100644 --- a/crates/lucisv_server/src/main.rs +++ b/crates/lucisv_server/src/main.rs @@ -21,6 +21,7 @@ mod includes; mod index_cache; mod inlay; mod inline; +mod large; mod lens; mod linked; mod lint; @@ -89,6 +90,7 @@ fn main() -> Result<(), Box> { code_lens_refresh: code_lens_refresh_support(¶ms), show_document: show_document_support(¶ms), configuration: configuration_support(¶ms), + token_server_cancel: token_server_cancel_support(¶ms), }; connection.initialize_finish(id, initialize_value(ranges_formatting)?)?; @@ -424,6 +426,26 @@ fn apply_edit_support(params: &InitializeParams) -> bool { .unwrap_or(false) } +/// Whether the client lets the *server* cancel a semantic-tokens request — +/// `textDocument.semanticTokens.serverCancelSupport`. +/// +/// The large-file fast path declines `semanticTokens/full`, and this decides +/// with which error code: `ServerCancelled` for a client that says it +/// understands one (the spec restricts that code to requests "that explicitly +/// support being server cancellable", and this capability is how a client +/// says so), `ContentModified` for one that does not. Both leave +/// `vscode-languageclient` throwing a `CancellationError`, which is what keeps +/// the range provider alive — see +/// `docs/features/large-file-mode/README.md`. +fn token_server_cancel_support(params: &InitializeParams) -> bool { + params.capabilities.text_document.as_ref().is_some_and(|text_document| { + text_document + .semantic_tokens + .as_ref() + .is_some_and(|tokens| tokens.server_cancel_support == Some(true)) + }) +} + /// Whether the client pulls diagnostics (LSP 3.17). /// /// Sending the capability at all is what says so; its two fields are about diff --git a/crates/lucisv_server/src/server.rs b/crates/lucisv_server/src/server.rs index e50ddd6..2725399 100644 --- a/crates/lucisv_server/src/server.rs +++ b/crates/lucisv_server/src/server.rs @@ -69,7 +69,7 @@ use crate::settings::ClientSettings; use crate::state::{IndexEvent, Workspace}; use crate::{ code_action, completion, diagnostics, file_ops, folding, format, hierarchy, hover, includes, - inlay, inline, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, + inlay, inline, large, lens, linked, nav, on_type, pairs, ports, rename, selection, settings, signature, symbols, sync, tokens, type_def, type_hierarchy, watch, }; @@ -107,6 +107,11 @@ pub struct ClientAbilities { /// for settings. A client that said nothing is only ever *pushed* /// settings, which is what every client got before this was read. pub configuration: bool, + /// Whether the client understands a server-cancelled semantic-tokens + /// request (`textDocument.semanticTokens.serverCancelSupport`). Decides + /// which error code declines `semanticTokens/full` on a large buffer — + /// see `docs/features/large-file-mode/README.md`. + pub token_server_cancel: bool, } /// Everything the server owns. @@ -352,6 +357,17 @@ impl Server { fn request(&mut self, request: Request) -> Response { let id = request.id.clone(); let method = request.method.clone(); + // The large-file fast path answers first, and for most methods it + // answers "nothing" before any handler is entered. Everything it lets + // through is either cheap on an empty analysis or is the one request + // that does real work on a large buffer — see + // `docs/features/large-file-mode/README.md` for the whole table. + if let Some(answer) = self.large_file_answer(&method, &request.params) { + return match answer { + Ok(value) => Response::new_ok(id, value), + Err(failure) => failure.into_response(id), + }; + } let result = match method.as_str() { Formatting::METHOD => decode(request).and_then(|p| self.formatting(p)), RangeFormatting::METHOD => decode(request).and_then(|p| self.range_formatting(p)), @@ -483,15 +499,21 @@ impl Server { // The visible lines only, for the first paint of a large file. // Self-contained and unremembered: a range answer is not what a // later delta is computed against, so it carries no `resultId`. + // + // On a buffer over `lucisv.largeFile.threshold` this is the *only* + // colouring request that answers, and it lexes the window rather + // than filtering the document's tokens — there are none. SemanticTokensRangeRequest::METHOD => { decode(request).and_then(|p: SemanticTokensRangeParams| { - match self.workspace.document(&p.text_document.uri) { - Some(doc) => to_value(SemanticTokensRangeResult::Tokens(SemanticTokens { - result_id: None, - data: tokens::semantic_tokens_in_range(doc, p.range), - })), - None => Ok(Value::Null), - } + let data = match self.workspace.document(&p.text_document.uri) { + Some(doc) if doc.large => tokens::semantic_tokens_in_window(doc, p.range), + Some(doc) => tokens::semantic_tokens_in_range(doc, p.range), + None => return Ok(Value::Null), + }; + to_value(SemanticTokensRangeResult::Tokens(SemanticTokens { + result_id: None, + data, + })) }) } DocumentSymbolRequest::METHOD => decode(request).and_then(|p: DocumentSymbolParams| { @@ -715,6 +737,147 @@ impl Server { } } + // ------------------------------------------------------------------ + // the large-file fast path + // ------------------------------------------------------------------ + + /// What a buffer over `lucisv.largeFile.threshold` answers `method`, or + /// `None` when the normal dispatch may run. + /// + /// Four groups, and the reason each is what it is: + /// + /// * **`semanticTokens/full` and `/full/delta` are declined with an + /// error.** Answering them with an empty set would be worse than not + /// answering: VS Code marks a model whose *document* provider returned + /// anything at all as having complete semantic tokens, and its viewport + /// contribution then never asks for a range again — the file would lose + /// all colour. An error leaves the model incomplete, so the range + /// provider keeps painting. The evidence for both halves is in + /// `docs/features/large-file-mode/README.md`. + /// * **The formatting requests refuse out loud.** A user pressed a key and + /// is owed a reason; silence there reads as a broken formatter. The + /// exceptions are the two the user did not press: `onTypeFormatting` + /// (a keystroke, and it never speaks) and `willSaveWaitUntil` (every + /// save), which decline the way they already decline. + /// * **`definition` and `references` scan the buffer.** The only two + /// answers a text scan can honestly give, and the whole reason the + /// buffer's text is still in memory. + /// * **Everything else answers nothing, fast** — and most of it is not + /// listed here at all: a fast-path `Document` holds the analysis of an + /// *empty* file, so those handlers already answer empty without knowing + /// this mode exists. Named below are only the ones that would otherwise + /// read the text itself. + fn large_file_answer( + &mut self, + method: &str, + params: &Value, + ) -> Option> { + // One boolean before anything is parsed: this runs ahead of every + // request, and a session with no large buffer in it — which is every + // session but one — must not pay a URI parse for the privilege. + if !self.workspace.has_large_documents() { + return None; + } + let uri = document_uri(params)?; + if !self.workspace.document(&uri).is_some_and(|doc| doc.large) { + return None; + } + let answer = match method { + SemanticTokensFullRequest::METHOD | SemanticTokensFullDeltaRequest::METHOD => { + Err(self.tokens_declined()) + } + Formatting::METHOD | RangeFormatting::METHOD | format::RANGES_FORMATTING => { + self.edits(Err(TOO_LARGE.to_string())) + } + // Silent, both of them: one fires on every keystroke and one on + // every save. + OnTypeFormatting::METHOD => to_value(Vec::::new()), + WillSaveWaitUntil::METHOD => Ok(Value::Null), + // A rename would rewrite every *other* file and leave this one + // untouched — the buffer is not in the index and not in + // `sources()` — so it is refused rather than half-applied. + // `prepareRename` declines quietly, so the box never opens. + PrepareRenameRequest::METHOD => Ok(Value::Null), + Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())), + // These three read the buffer's text rather than its analysis: the + // include scan, the `` `include`` line lookup a hover does, and + // the fix application a code action tries. + HoverRequest::METHOD => Ok(Value::Null), + DocumentLinkRequest::METHOD => to_value(Vec::::new()), + CodeActionRequest::METHOD => to_value(Vec::::new()), + GotoDefinition::METHOD => self.large_definition(&uri, params), + References::METHOD => self.large_references(&uri, params), + _ => return None, + }; + Some(answer) + } + + /// The error `semanticTokens/full` is declined with. + /// + /// `ServerCancelled` for a client that advertised `serverCancelSupport`, + /// which is the code the spec reserves for exactly this and the code + /// `vscode-languageclient` turns into a `CancellationError`; + /// `ContentModified` for one that did not, which the same client turns + /// into the same `CancellationError` (semantic tokens are on its + /// `retryOnContentModified` list) and which every 3.16 client already + /// understands. + fn tokens_declined(&self) -> Failure { + let code = match self.abilities.token_server_cancel { + true => lsp_server::ErrorCode::ServerCancelled, + false => lsp_server::ErrorCode::ContentModified, + }; + Failure::Declined(code, TOO_LARGE.to_string()) + } + + /// `textDocument/definition` on a large buffer: the first occurrence of + /// the name under the cursor that a declaring keyword introduces. + fn large_definition(&self, uri: &Uri, params: &Value) -> Result { + let locations = self + .large_scan(uri, params, |doc, offset| { + large::definition(doc, offset).into_iter().collect() + }) + .unwrap_or_default(); + to_value(GotoDefinitionResponse::Array(locations)) + } + + /// `textDocument/references` on a large buffer: every whole-word + /// occurrence of the name under the cursor, capped. + fn large_references(&self, uri: &Uri, params: &Value) -> Result { + let include = params + .get("context") + .and_then(|context| context.get("includeDeclaration")) + .and_then(Value::as_bool) + .unwrap_or(true); + let locations = self + .large_scan(uri, params, |doc, offset| large::references(doc, offset, include)) + .unwrap_or_default(); + to_value(locations) + } + + /// Run one of the fast path's scans at the position `params` names, and + /// turn its spans into locations in the same file. + fn large_scan( + &self, + uri: &Uri, + params: &Value, + scan: impl Fn(&crate::state::Document, u32) -> Vec, + ) -> Option> { + let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?; + let doc = self.workspace.document(uri)?; + let positions = doc.positions(); + let offset = positions.offset(position); + // Both scans answer in ascending order, so one monotonic cursor + // measures each line once — a thousand hits on one netlist line would + // otherwise re-measure that line a thousand times over. + let mut walker = positions.walker(); + Some( + scan(doc, offset) + .into_iter() + .map(|span| Location { uri: uri.clone(), range: walker.range(span) }) + .collect(), + ) + } + fn formatting(&mut self, params: DocumentFormattingParams) -> Result { let uri = params.text_document.uri; let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) }; @@ -1542,8 +1705,38 @@ impl Server { /// has moved on, and a config problem is worth saying once more. fn set_document(&mut self, uri: Uri, text: String) { self.config_warnings.remove(&uri); - self.workspace.set_document(uri, text); + let was_large = self.workspace.document(&uri).is_some_and(|doc| doc.large); + self.workspace.set_document(uri.clone(), text); self.generation += 1; + self.announce_fast_path(&uri, was_large); + } + + /// Say once, in the output channel, that a buffer is on the large-file + /// fast path. + /// + /// Once per *entry* into the mode, not once per notification: a keystroke + /// in a 100 MB buffer must not log a line, and a buffer edited past the + /// threshold mid-session must. Nothing is said on the way back out — + /// leaving the mode restores every answer, which is not news. + fn announce_fast_path(&self, uri: &Uri, was_large: bool) { + let Some(doc) = self.workspace.document(uri).filter(|doc| doc.large && !was_large) else { + return; + }; + let what = match doc.path.as_deref() { + Some(path) => path.display().to_string(), + None => uri.as_str().to_string(), + }; + let size = doc.text.len(); + self.notify( + LogMessage::METHOD, + LogMessageParams { + typ: MessageType::INFO, + message: format!( + "lucisv: large-file fast path: {what} ({size} bytes) — \ + syntax highlighting only, nothing is parsed or indexed" + ), + }, + ); } /// Publish everything known about a buffer — parse errors and lint @@ -1850,6 +2043,11 @@ enum Failure { /// The request was well-formed and the server declined it, with a reason /// meant for the user — LSP's `RequestFailed`. Request(String), + /// The server chose not to compute an answer it could have computed, with + /// a code that tells the client to keep what it has and ask again rather + /// than to treat this as the answer. The large-file fast path declines + /// `semanticTokens/full` this way; nothing else uses it. + Declined(lsp_server::ErrorCode, String), } impl Failure { @@ -1866,11 +2064,30 @@ impl Failure { Failure::Request(message) => { (lsp_server::ErrorCode::RequestFailed as i32, format!("lucisv: {message}")) } + Failure::Declined(code, message) => (code as i32, format!("lucisv: {message}")), }; Response::new_err(id, code, message) } } +/// The sentence every large-buffer refusal carries. One string, because a +/// user who meets it twice should not have to work out whether they are the +/// same thing. +const TOO_LARGE: &str = + "this buffer is over lucisv.largeFile.threshold and is open on the large-file fast path"; + +/// The `textDocument.uri` a request names, read out of the raw params. +/// +/// Before the typed decode on purpose: the fast-path gate has to know which +/// buffer a request is about without knowing which of thirty parameter types +/// it carries, and every document-scoped request in LSP spells it exactly +/// here. A request with no `textDocument` (the hierarchy resolutions, the +/// workspace-wide ones, `executeCommand`) is not gated at all, which is +/// correct: none of them can reach a buffer's text. +fn document_uri(params: &Value) -> Option { + params.get("textDocument")?.get("uri")?.as_str()?.parse().ok() +} + fn decode(request: Request) -> Result { serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string())) } @@ -6691,4 +6908,439 @@ mod tests { ); assert_eq!(session.server.workspace.client_settings().indent, Some(4)); } + + // ------------------------------------------------------------------ + // the large-file fast path (`docs/features/large-file-mode/README.md`) + // ------------------------------------------------------------------ + + /// A session whose fast path starts at 100 bytes, so a test buffer can be + /// three lines long instead of four megabytes. + fn fast_path_settings() -> ClientSettings { + ClientSettings { large_file_threshold: 100, ..Default::default() } + } + + /// A source file that is real Verilog and over the test threshold. + fn big_source() -> String { + let mut text = String::from("module top;\n wire sig_a;\n"); + for i in 0..20 { + text.push_str(&format!(" assign sig_a = w{i};\n")); + } + text.push_str("endmodule\n"); + assert!(text.len() > 100, "the premise: over the test threshold"); + text + } + + /// A session with one large buffer open, and its URI. + /// + /// Every call gets its own tree: this is the one `Tree::new` name shared + /// by roughly a dozen tests (every large-file-mode test that does not + /// need bespoke source text), which — unlike the rest of this module's + /// trees, each named for the one test that uses it — would otherwise + /// collide on the same `/tmp` directory under `cargo test`'s default + /// parallelism and race each other's `remove_dir_all`/`create_dir_all`. + /// The counter is what makes the shared literal safe to share. + fn fast_path_session(abilities: ClientAbilities) -> (Tree, Session, Uri) { + static CALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = CALLS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tree = Tree::new(&format!("largefile{n}")); + let path = tree.path.join("net.v"); + tree.write("net.v", &big_source()); + let mut session = + Session::started(vec![tree.path.clone()], abilities, fast_path_settings()); + let uri = session.open(&path, &big_source()); + let _ = session.drain(); + (tree, session, uri) + } + + /// The params a document-scoped request carries, at a position on the + /// `sig_a` declaration. + fn at_sig_a(uri: &Uri) -> Value { + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 9 }, + }) + } + + #[test] + fn a_buffer_over_the_threshold_opens_on_the_fast_path_and_says_so_once() { + let (_tree, mut session, uri) = { + let tree = Tree::new("largeannounce"); + let path = tree.path.join("net.v"); + tree.write("net.v", &big_source()); + let mut session = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + fast_path_settings(), + ); + let uri = session.open(&path, &big_source()); + (tree, session, uri) + }; + let lines: Vec = session + .logged() + .into_iter() + .map(|(_, message)| message) + .filter(|message| message.contains("large-file fast path")) + .collect(); + assert_eq!(lines.len(), 1, "once per entry into the mode: {lines:?}"); + assert!(lines[0].contains("net.v"), "{}", lines[0]); + assert!(lines[0].contains("bytes"), "{}", lines[0]); + + // A keystroke in it does not say it again. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": big_source() }], + }), + ); + assert!( + !session.logged().iter().any(|(_, m)| m.contains("large-file fast path")), + "the line is per entry, not per notification" + ); + } + + #[test] + fn a_large_buffer_is_diagnosed_as_empty_and_clears_what_it_left_behind() { + let tree = Tree::new("largesquiggles"); + let path = tree.path.join("grow.v"); + let mut session = Session::started( + vec![tree.path.clone()], + ClientAbilities::default(), + fast_path_settings(), + ); + // Small and broken: a real diagnostic is drawn. + let uri = session.open(&path, "module m;\n wire ;\nendmodule\n"); + let drawn = session.published(); + assert_eq!(drawn.len(), 1); + assert!(!drawn[0].diagnostics.is_empty(), "premise: squiggles were drawn"); + + // The same buffer, edited past the threshold: one publish, empty, so + // the squiggles go away rather than being left frozen on screen. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": format!("module m;\n wire ;\n{}", " ".repeat(200)) }], + }), + ); + let cleared = session.published(); + assert_eq!(cleared.len(), 1, "one publish, as every change makes"); + assert!(cleared[0].diagnostics.is_empty(), "and it is empty: {cleared:?}"); + } + + #[test] + fn semantic_tokens_range_paints_a_large_buffer() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + let data = session.result( + SemanticTokensRangeRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { + "start": { "line": 1, "character": 0 }, + "end": { "line": 3, "character": 0 }, + }, + }), + ); + let tokens = data["data"].as_array().expect("a token array").clone(); + assert!(!tokens.is_empty(), "the window was lexed: {data}"); + assert!(data["resultId"].is_null(), "a range answer is not delta material"); + // First token: `wire` on line 1, five numbers per token. + assert_eq!(tokens.len() % 5, 0); + assert_eq!(tokens[0], 1, "delta_line — the first line of the window"); + } + + #[test] + fn semantic_tokens_full_is_declined_rather_than_answered_empty() { + // The whole reason: VS Code marks a model whose document provider + // answered *anything* as complete and never asks its range provider + // again. An error leaves it incomplete, so the viewport keeps + // painting. `serverCancelSupport` decides which code says so. + let cancels = ClientAbilities { token_server_cancel: true, ..Default::default() }; + let (_tree, mut session, uri) = fast_path_session(cancels); + let params = serde_json::json!({ "textDocument": { "uri": uri } }); + for method in [SemanticTokensFullRequest::METHOD, SemanticTokensFullDeltaRequest::METHOD] { + let mut params = params.clone(); + params["previousResultId"] = serde_json::json!("1"); + let error = session.request(method, params).response_result.expect_err("declined"); + assert_eq!(error.code, lsp_server::ErrorCode::ServerCancelled as i32, "{method}"); + assert!(error.message.contains("largeFile.threshold"), "{}", error.message); + } + + // A client that never advertised it gets the code every 3.16 client + // already understands. + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + let error = session + .request( + SemanticTokensFullRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ) + .response_result + .expect_err("declined"); + assert_eq!(error.code, lsp_server::ErrorCode::ContentModified as i32); + } + + #[test] + fn formatting_a_large_buffer_refuses_out_loud_and_edits_nothing() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + let edits = session.result( + Formatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ); + assert_eq!(edits, serde_json::json!([]), "no edit, ever"); + let shown = session.shown(); + assert_eq!(shown.len(), 1, "the user pressed a key and is owed a reason: {shown:?}"); + assert_eq!(shown[0].0, MessageType::ERROR); + assert!(shown[0].1.contains("largeFile.threshold"), "{}", shown[0].1); + } + + #[test] + fn the_two_formatting_requests_the_user_did_not_press_stay_silent() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + let edits = session.result( + OnTypeFormatting::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 1, "character": 9 }, + "ch": ";", + "options": { "tabSize": 2, "insertSpaces": true }, + }), + ); + assert_eq!(edits, serde_json::json!([])); + let saved = session.result( + WillSaveWaitUntil::METHOD, + serde_json::json!({ "textDocument": { "uri": uri }, "reason": 1 }), + ); + assert_eq!(saved, Value::Null); + assert!(session.shown().is_empty(), "neither fires on a key the user pressed"); + } + + #[test] + fn a_rename_is_refused_rather_than_applied_to_every_file_but_this_one() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + assert_eq!( + session.result(PrepareRenameRequest::METHOD, at_sig_a(&uri)), + Value::Null, + "the box never opens" + ); + let mut params = at_sig_a(&uri); + params["newName"] = serde_json::json!("sig_b"); + let error = session.request(Rename::METHOD, params).response_result.expect_err("refused"); + assert_eq!(error.code, lsp_server::ErrorCode::RequestFailed as i32); + assert!(error.message.contains("largeFile.threshold"), "{}", error.message); + } + + #[test] + fn definition_and_references_answer_from_one_scan_of_the_buffer() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + // The cursor is on the `sig_a` of `wire sig_a;`, and every `sig_a` in + // the file is one answer. + let found = session.result(GotoDefinition::METHOD, at_sig_a(&uri)); + let locations = found.as_array().expect("an array"); + assert_eq!(locations.len(), 1, "{found}"); + assert_eq!(locations[0]["range"]["start"]["line"], 1); + assert_eq!(locations[0]["uri"].as_str(), Some(uri.as_str())); + + let mut params = at_sig_a(&uri); + params["context"] = serde_json::json!({ "includeDeclaration": true }); + let all = session.result(References::METHOD, params.clone()); + assert_eq!(all.as_array().expect("an array").len(), 21, "the wire and its 20 uses"); + params["context"] = serde_json::json!({ "includeDeclaration": false }); + let uses = session.result(References::METHOD, params); + assert_eq!(uses.as_array().expect("an array").len(), 20, "minus the declaration"); + } + + /// **The dispatch table.** Every document-scoped request, and what a + /// buffer on the fast path answers it. The point is that the list is + /// complete and pinned: a handler added later that reads a large buffer's + /// *text* will fail here rather than in a user's editor. + #[test] + fn every_other_request_a_large_buffer_gets_answers_nothing_at_all() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + let document = serde_json::json!({ "textDocument": { "uri": uri } }); + let position = at_sig_a(&uri); + let range = serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { + "start": { "line": 0, "character": 0 }, + "end": { "line": 3, "character": 0 }, + }, + }); + let empty = serde_json::json!([]); + // (method, params, expected answer) + let table: Vec<(&str, Value, Value)> = vec![ + (HoverRequest::METHOD, position.clone(), Value::Null), + (GotoTypeDefinition::METHOD, position.clone(), empty.clone()), + (LinkedEditingRange::METHOD, position.clone(), Value::Null), + (DocumentLinkRequest::METHOD, document.clone(), empty.clone()), + (DocumentHighlightRequest::METHOD, position.clone(), Value::Null), + (FoldingRangeRequest::METHOD, document.clone(), empty.clone()), + (DocumentSymbolRequest::METHOD, document.clone(), empty.clone()), + (CodeLensRequest::METHOD, document.clone(), empty.clone()), + (InlayHintRequest::METHOD, range.clone(), empty.clone()), + ( + CodeActionRequest::METHOD, + { + let mut params = range.clone(); + params["context"] = serde_json::json!({ "diagnostics": [] }); + params + }, + empty.clone(), + ), + (Completion::METHOD, position.clone(), Value::Null), + (SignatureHelpRequest::METHOD, position.clone(), Value::Null), + ( + InlineCompletionRequest::METHOD, + { + let mut params = position.clone(); + params["context"] = + serde_json::json!({ "triggerKind": 2, "selectedCompletionInfo": null }); + params + }, + Value::Null, + ), + (CallHierarchyPrepare::METHOD, position.clone(), Value::Null), + (TypeHierarchyPrepare::METHOD, position.clone(), Value::Null), + // The one custom method: an object with both lists empty, which is + // what "this buffer has no scopes" already looks like. + ( + pairs::SCOPE_PAIRS_METHOD, + document.clone(), + serde_json::json!({ "pairs": [], "unmatched": [] }), + ), + ]; + for (method, params, expected) in table { + assert_eq!(session.result(method, params), expected, "{method}"); + } + // `selectionRange` is the one request that answers something: the + // whole document is a legal expand-selection step even with nothing + // parsed, and it costs one span. + let mut selection = document.clone(); + selection["positions"] = serde_json::json!([{ "line": 1, "character": 9 }]); + let chain = session.result(SelectionRangeRequest::METHOD, selection); + assert_eq!(chain.as_array().expect("one chain per position").len(), 1); + assert!(chain[0]["parent"].is_null(), "one step, the file: {chain}"); + // Nothing above said a word to the user. + assert!(session.shown().is_empty()); + } + + #[test] + fn a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer() { + let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() }; + let (_tree, mut session, uri) = fast_path_session(pulling); + let report = session.result( + DocumentDiagnosticRequest::METHOD, + serde_json::json!({ "textDocument": { "uri": uri } }), + ); + assert_eq!(report["items"], serde_json::json!([]), "{report}"); + } + + /// `workspace/diagnostic` walks every open buffer (`workspace_report` + /// above), a large one included — it is not skipped, it is present with + /// an empty **full** report, the same answer `diagnostics::all` gives + /// `textDocument/diagnostic`. Pinned because the workspace-scoped sweep is + /// a different code path from the per-document one already covered by + /// `a_pull_diagnostics_client_gets_an_empty_report_for_a_large_buffer`. + #[test] + fn a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report() { + let pulling = ClientAbilities { pull_diagnostics: true, ..Default::default() }; + let (_tree, mut session, uri) = fast_path_session(pulling); + let report = session.result( + WorkspaceDiagnosticRequest::METHOD, + serde_json::json!({ "identifier": diagnostics::SOURCE, "previousResultIds": [] }), + ); + let items = report["items"].as_array().expect("items"); + assert_eq!(items.len(), 1, "{report:#?}"); + assert_eq!(items[0]["uri"].as_str(), Some(uri.as_str())); + assert_eq!(items[0]["kind"], "full", "present, not skipped: {report:#?}"); + assert_eq!(items[0]["items"], serde_json::json!([]), "{report:#?}"); + } + + #[test] + fn the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change() { + let tree = Tree::new("largethreshold"); + let path = tree.path.join("net.v"); + tree.write("net.v", &big_source()); + // Default settings: the buffer is nowhere near 4 MiB, so it is + // analyzed in full. + let mut session = Session::new(vec![tree.path.clone()], false); + let uri = session.open(&path, &big_source()); + assert!(!session.server.workspace.document(&uri).expect("open").large); + + // Pushed. The buffer already open does not change mode on the spot — + // the decision is taken where a document is built. + session.notify( + DidChangeConfiguration::METHOD, + serde_json::json!({ "settings": { "lucisv": { "largeFile": { "threshold": 100 } } } }), + ); + assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100); + assert!( + !session.server.workspace.document(&uri).expect("open").large, + "the open buffer keeps the mode it was built in" + ); + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ "text": big_source() }], + }), + ); + assert!( + session.server.workspace.document(&uri).expect("open").large, + "and takes the fast path at its next change" + ); + + // Pulled: the same value through the other door. + let mut session = Session::with( + vec![tree.path.clone()], + ClientAbilities { configuration: true, ..Default::default() }, + ); + let (id, _) = configuration_request(&session); + session.answer(id, serde_json::json!([{ "largeFile": { "threshold": 100 } }])); + assert_eq!(session.server.workspace.client_settings().large_file_threshold, 100); + let uri = session.open(&path, &big_source()); + assert!(session.server.workspace.document(&uri).expect("open").large); + } + + #[test] + fn an_edit_to_a_large_buffer_moves_its_lines_and_the_next_window_agrees() { + let (_tree, mut session, uri) = fast_path_session(ClientAbilities::default()); + // Insert a line at the top. `sig_a`'s declaration moves from line 1 + // to line 2, which is only true if the line index was rebuilt. + session.notify( + DidChangeTextDocument::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri, "version": 2 }, + "contentChanges": [{ + "range": { + "start": { "line": 0, "character": 0 }, + "end": { "line": 0, "character": 0 }, + }, + "text": "// a new first line\n", + }], + }), + ); + let data = session.result( + SemanticTokensRangeRequest::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "range": { + "start": { "line": 2, "character": 0 }, + "end": { "line": 3, "character": 0 }, + }, + }), + ); + let tokens = data["data"].as_array().expect("tokens"); + assert_eq!(tokens[0], 2, "the window's own line, after the insertion"); + let found = session.result( + GotoDefinition::METHOD, + serde_json::json!({ + "textDocument": { "uri": uri }, + "position": { "line": 2, "character": 9 }, + }), + ); + assert_eq!(found[0]["range"]["start"]["line"], 2, "{found}"); + } } diff --git a/crates/lucisv_server/src/settings.rs b/crates/lucisv_server/src/settings.rs index 274f01e..b048d52 100644 --- a/crates/lucisv_server/src/settings.rs +++ b/crates/lucisv_server/src/settings.rs @@ -34,6 +34,13 @@ const INDENT_RANGE: RangeInclusive = 1..=8; /// `docs/features/indexing-ux/README.md`. pub const DEFAULT_MAX_FILE_SIZE: u64 = 1024 * 1024; +/// `lucisv.largeFile.threshold`'s default: 4 MiB. A buffer bigger than this is +/// opened on the fast path — line index only, no lex, no parse, no index — and +/// coloured a viewport at a time. `0` turns the fast path off, so every buffer +/// is analyzed in full however big it is; see +/// `docs/features/large-file-mode/README.md`. +pub const DEFAULT_LARGE_FILE_THRESHOLD: u64 = 4 * 1024 * 1024; + /// What `lucisv.index.scope` chooses: how wide the workspace walk goes. /// /// The default is deliberately the narrow one. A large project is the case @@ -124,6 +131,12 @@ pub struct ClientSettings { /// editor's own storage folder — or this platform's cache directory — /// decides; see `index_cache::cache_dir` for the ladder. pub index_cache_path: Option, + /// `lucisv.largeFile.threshold`: the size in bytes above which an **open + /// buffer** is served by the fast path instead of being analyzed. `0` + /// disables the fast path. Unlike `index.maxFileSize`, which is about + /// files on disk that nobody asked for, this one is about the file on + /// screen — see `docs/features/large-file-mode/README.md`. + pub large_file_threshold: u64, } /// The settings a client that said nothing is treated as having asked for. @@ -146,6 +159,7 @@ impl Default for ClientSettings { index_scope_depth: 0, index_persist: true, index_cache_path: None, + large_file_threshold: DEFAULT_LARGE_FILE_THRESHOLD, } } } @@ -172,6 +186,9 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // or is not an object at all — leaves both of its keys at their defaults, // which is what `Value::get` on a non-object already returns. let index = lucisv.get("index"); + // `lucisv.largeFile.threshold` nests exactly as `index.*` does, for the + // same reason: VS Code turns every dotted segment into an object. + let large_file = lucisv.get("largeFile"); ClientSettings { line_length: bounded(lucisv.get("lineLength"), LINE_LENGTH_RANGE), indent: bounded(lucisv.get("indent"), INDENT_RANGE), @@ -201,6 +218,13 @@ pub fn from_payload(settings: &Value) -> ClientSettings { // hit is verified against the file's own bytes. index_persist: flag(index.and_then(|i| i.get("persist"))).unwrap_or(true), index_cache_path: path(index.and_then(|i| i.get("cachePath"))), + // The safe direction again: a wrong-typed threshold leaves the fast + // path armed at its default. A junk value that read as `0` would turn + // it off, and the first 100 MB netlist opened after that would hang + // the editor for minutes — which is the whole thing this exists to + // prevent. + large_file_threshold: count(large_file.and_then(|f| f.get("threshold"))) + .unwrap_or(DEFAULT_LARGE_FILE_THRESHOLD), } } diff --git a/crates/lucisv_server/src/state.rs b/crates/lucisv_server/src/state.rs index c5de810..7e41913 100644 --- a/crates/lucisv_server/src/state.rs +++ b/crates/lucisv_server/src/state.rs @@ -50,6 +50,13 @@ pub struct Document { pub defines: DefineTable, /// The workspace layer's answers for this file's external candidates. pub external: ExternalResolutions, + /// Whether this buffer was opened on the **large-file fast path**: every + /// field above except `text` and `line_index` is the empty analysis of an + /// empty file, because nothing lexed it. Handlers that would scan the text + /// itself check this flag; the ones that read the analysis need not, since + /// there is nothing in it to find. See + /// `docs/features/large-file-mode/README.md`. + pub large: bool, } impl Document { @@ -71,7 +78,44 @@ impl Document { let semantics = analyze(&tree, &text); let external = resolve_external(&semantics, index); let line_index = LineIndex::new(&text); - Document { path, text, line_index, tokens, tree, diagnostics, semantics, defines, external } + let large = false; + Document { + path, + text, + line_index, + tokens, + tree, + diagnostics, + semantics, + defines, + external, + large, + } + } + + /// Take a buffer on the **fast path**: index its lines and nothing else. + /// + /// One newline scan is the whole cost of opening a 100 MB netlist. The + /// derived fields are the analysis of the *empty* file rather than of this + /// one — built by parsing `""`, which costs nothing and needs no new API + /// from `vlog_parser` — so every handler that reads the analysis finds + /// exactly nothing and answers empty without knowing this path exists. + pub fn large(path: Option, text: String) -> Document { + let (tree, _) = parse_source_tolerant(""); + let semantics = analyze(&tree, ""); + let line_index = LineIndex::new(&text); + Document { + path, + text, + line_index, + tokens: Vec::new(), + tree, + diagnostics: Vec::new(), + semantics, + defines: DefineTable::default(), + external: ExternalResolutions::default(), + large: true, + } } /// This document's position converter. @@ -346,6 +390,13 @@ impl Workspace { /// formatting request, so they need no invalidation at all — and neither /// does `index.logFiles`, which changes only how loudly the *next* rescan /// narrates itself. + /// + /// `largeFile.threshold` asks for no rescan either, and deliberately: it + /// is consulted where a `Document` is *built*, so a change to it reaches + /// each open buffer at that buffer's next `didOpen`/`didChange` and not + /// before. A rescan now would index by the mode each buffer is still in, + /// which is the mode the index already reflects + /// (`docs/features/large-file-mode/README.md`). pub fn set_client_settings(&mut self, settings: ClientSettings) -> bool { let rescan = self.client.exclude != settings.exclude || self.client.filelist != settings.filelist @@ -408,6 +459,13 @@ impl Workspace { /// Also the one place a directory enters the folder scope: a buffer with a /// path puts its own directory on the list `scope_dirs` raises. An /// `untitled:` buffer has no path and contributes none. + /// + /// And the one place the **large-file fast path** is chosen: a text over + /// `lucisv.largeFile.threshold` is line-indexed and nothing more. Because + /// the decision lives here it is re-taken on every `didOpen`, `didChange` + /// and text-carrying `didSave`, which is what makes a buffer edited past + /// the threshold — or back under it — change mode at that moment and not + /// before (`docs/features/large-file-mode/README.md`). pub fn set_document(&mut self, uri: Uri, text: String) { let path = uri_to_path(&uri); if let Some(dir) = path.as_deref().and_then(Path::parent) { @@ -416,10 +474,30 @@ impl Workspace { self.opened_dirs.sort(); } } - let doc = Document::new(path, text, &self.index); + let doc = match self.is_large(&text) { + true => Document::large(path, text), + false => Document::new(path, text, &self.index), + }; self.docs.insert(uri, doc); } + /// Whether a buffer of this text takes the fast path. `0` disables it, and + /// the comparison is strict, so a buffer of exactly the threshold is still + /// analyzed in full. + fn is_large(&self, text: &str) -> bool { + let threshold = self.client.large_file_threshold; + threshold != 0 && text.len() as u64 > threshold + } + + /// Whether any open buffer is on the large-file fast path. + /// + /// The gate in `server.rs` runs before every request, and this is what + /// keeps that from costing a URI parse per request in the session where + /// nothing is large — which is every session but one. + pub fn has_large_documents(&self) -> bool { + self.docs.values().any(|doc| doc.large) + } + pub fn close_document(&mut self, uri: &Uri) { self.docs.remove(uri); } @@ -588,7 +666,10 @@ impl Workspace { /// rules — `None` when it contributes nothing at all. fn current_text(&self, path: &Path) -> Option { if let Some(doc) = self.docs.values().find(|doc| doc.path.as_deref() == Some(path)) { - return Some(doc.text.clone()); + // A fast-path buffer contributes nothing, exactly as it does in + // `collect_sources` — indexing it is the parse the fast path + // exists to skip. + return (!doc.large).then(|| doc.text.clone()); } if oversize(path, self.client.max_file_size).is_some() { return None; @@ -649,10 +730,21 @@ impl Workspace { } // Open buffers override what is on disk, and contribute themselves // when they are not on disk at all. + // + // Except a buffer on the large-file fast path, which overrides disk + // with *nothing*: indexing it means parsing the hundred megabytes the + // fast path exists not to parse. Removing the path rather than leaving + // the disk copy in is the honest half of that — the alternative would + // be an index describing a file the user is looking at by bytes it no + // longer has. See `docs/features/large-file-mode/README.md` for the + // interaction with `lucisv.index.maxFileSize`, whose "an open buffer is + // never capped" rule this is the one exception to. for doc in self.docs.values() { let Some(path) = doc.path.clone() else { continue }; texts.retain(|(p, _)| p != &path); - texts.push((path, doc.text.clone())); + if !doc.large { + texts.push((path, doc.text.clone())); + } } Sources { texts, incdirs: scope.incdirs, warnings: scope.warnings } } @@ -881,6 +973,107 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + // ------------------------------------------------------------------ + // the large-file fast path + // ------------------------------------------------------------------ + + /// A workspace whose fast path starts at `threshold` bytes. + fn thresholded(threshold: u64) -> Workspace { + let mut ws = Workspace::default(); + ws.set_client_settings(ClientSettings { + large_file_threshold: threshold, + ..ClientSettings::default() + }); + ws + } + + /// A buffer of exactly `bytes` bytes that is also real Verilog. + fn filler(bytes: usize) -> String { + let mut text = String::from("module m;\n"); + while text.len() + 9 <= bytes { + text.push_str(" wire a;\n"); + } + while text.len() < bytes { + text.push(' '); + } + text + } + + #[test] + fn the_threshold_is_strict_at_the_boundary() { + let sizes = [99, 100, 101]; + let large: Vec = sizes + .iter() + .map(|&size| { + let mut ws = thresholded(100); + ws.set_document(uri("file:///rtl/big.v"), filler(size)); + ws.document(&uri("file:///rtl/big.v")).expect("open").large + }) + .collect(); + assert_eq!(large, [false, false, true], "under, at, over"); + } + + #[test] + fn a_threshold_of_zero_turns_the_fast_path_off_entirely() { + let mut ws = thresholded(0); + ws.set_document(uri("file:///rtl/big.v"), filler(200_000)); + let doc = ws.document(&uri("file:///rtl/big.v")).expect("open"); + assert!(!doc.large); + assert!(!doc.tokens.is_empty(), "it really was lexed"); + } + + #[test] + fn a_fast_path_buffer_holds_the_analysis_of_an_empty_file() { + let mut ws = thresholded(100); + ws.set_document(uri("file:///rtl/big.v"), filler(500)); + let doc = ws.document(&uri("file:///rtl/big.v")).expect("open"); + assert!(doc.large); + assert!(doc.tokens.is_empty(), "nothing was lexed"); + assert!(doc.diagnostics.is_empty(), "nothing was parsed"); + assert!(doc.semantics.symbols().is_empty(), "nothing was analyzed"); + assert!(doc.defines.entries().is_empty(), "no defines were collected"); + // But the two things the fast path *does* build are real. + assert_eq!(doc.text.len(), 500); + assert!(doc.line_index.line_count() > 1); + } + + #[test] + fn a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind() { + let tree = Tree::new("largefile"); + tree.write("pkg.sv", "package p;\n localparam ON_DISK = 1;\nendpackage\n"); + let path = tree.path.join("pkg.sv"); + + let mut ws = thresholded(100); + ws.open_whole_workspace(vec![tree.path.clone()]); + assert_eq!(ws.index().member("p", "ON_DISK").len(), 1, "premise: disk was indexed"); + + // The same file, opened as a buffer the fast path takes. + let mut text = String::from("package p;\n localparam IN_BUFFER = 1;\nendpackage\n"); + text.push_str(&" ".repeat(200)); + ws.set_document(crate::uri::path_to_uri(&path).expect("uri"), text); + ws.rebuild_index(); + assert_eq!(ws.index().member("p", "IN_BUFFER").len(), 0, "the buffer was not parsed"); + assert_eq!( + ws.index().member("p", "ON_DISK").len(), + 0, + "and the disk copy the buffer supersedes is not indexed in its place" + ); + } + + #[test] + fn a_buffer_edited_past_the_threshold_changes_mode_and_back() { + let mut ws = thresholded(200); + let file = uri("file:///rtl/grow.v"); + ws.set_document(file.clone(), "module m;\nendmodule\n".into()); + assert!(!ws.document(&file).expect("open").large); + ws.set_document(file.clone(), filler(1_000)); + assert!(ws.document(&file).expect("open").large, "grew past the threshold"); + ws.set_document(file.clone(), "module m;\nendmodule\n".into()); + let doc = ws.document(&file).expect("open"); + assert!(!doc.large, "and shrank back under it"); + assert!(!doc.tokens.is_empty(), "with a full analysis again"); + } + /// A scratch workspace root. Removed on drop. struct Tree { path: PathBuf, diff --git a/crates/lucisv_server/src/tokens.rs b/crates/lucisv_server/src/tokens.rs index 50f6d99..829776b 100644 --- a/crates/lucisv_server/src/tokens.rs +++ b/crates/lucisv_server/src/tokens.rs @@ -121,18 +121,35 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec Vec { + let window = crate::large::window(doc, range); + let mut pieces = Vec::new(); + // The comment spans the lexer never saw go in first; `flatten` sorts, so + // the order they are collected in cannot reach the wire. + for span in &window.comments { + pieces.push(Piece { span: *span, ty: Highlight::Comment, modifiers: 0 }); + } + for token in &window.tokens { + collect(token, &doc.semantics, &mut pieces); + } + encode(&within(flatten(pieces, doc), range)) +} + /// Classify the whole buffer, split at line boundaries, in wire order. fn absolute(doc: &Document) -> Vec { let mut pieces = Vec::new(); for token in &doc.tokens { - collect_trivia(token, &mut pieces); - if let Some(ty) = classify(token, &doc.semantics) { - pieces.push(Piece { - span: token.span, - ty, - modifiers: modifiers(token, &doc.semantics), - }); - } + collect(token, &doc.semantics, &mut pieces); } flatten(pieces, doc) } @@ -151,13 +168,22 @@ fn within(tokens: Vec, range: Range) -> Vec { tokens.into_iter().filter(|t| t.from() < range.end && range.start < t.to()).collect() } +/// One token's pieces: its comments and the token itself. +/// /// Comments live as trivia on the token that follows (or, for a trailing /// comment, precedes) them — including on the EOF token, which is what makes -/// a comment at the end of the file reachable. -fn collect_trivia(token: &Token, out: &mut Vec) { +/// a comment at the end of the file reachable. They are pushed **in source +/// order** — leading comments, the token, then the trailing comment that sits +/// after it on the same line — because [`flatten`] converts the offsets with a +/// single forward cursor. Ordering is otherwise invisible: `flatten` sorts, +/// and no two pieces here can start at the same byte. +fn collect(token: &Token, semantics: &Semantics, out: &mut Vec) { for comment in &token.leading { out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 }); } + if let Some(ty) = classify(token, semantics) { + out.push(Piece { span: token.span, ty, modifiers: modifiers(token, semantics) }); + } if let Some(comment) = &token.trailing { out.push(Piece { span: comment.span, ty: Highlight::Comment, modifiers: 0 }); } @@ -233,11 +259,18 @@ fn symbol_type(kind: SymbolKind) -> Highlight { /// multi-line macro invocation. fn flatten(pieces: Vec, doc: &Document) -> Vec { let positions = doc.positions(); + // The pieces arrive in source order (see [`collect`]), so one monotonic + // cursor measures each line once however many tokens sit on it. The + // per-call converter re-measures from the line's start every time, which + // is quadratic on a netlist's single million-byte line — seconds per + // viewport, measured. Out-of-order pieces (the fast path's window-edge + // comments) are answered identically, just without the saving. + let mut walker = positions.walker(); let mut flat: Vec = Vec::new(); for piece in pieces { for line_span in split_lines(&doc.text, piece.span) { - let start = positions.position(line_span.start); - let end = positions.position(line_span.end); + let start = walker.position(line_span.start); + let end = walker.position(line_span.end); if end.character <= start.character { continue; } @@ -435,6 +468,44 @@ mod tests { assert_eq!(comments[1].0, 3); } + /// QA (fix-round re-verification): `collect_trivia` became `collect`, + /// folding two callers' duplicated classify-and-push into one function + /// that pushes a token's own piece *between* its leading comments and its + /// trailing one. A single token flanked by both is the shape that + /// exercises every branch of that function on one token, and `flatten`'s + /// stable sort means the exact byte offsets have to be right regardless + /// of the order `collect` happened to push them in. + #[test] + fn a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces() { + let text = "/* lead */\nwire /* mid */ a;\n"; + let out = decoded(text); + let comment = |n: usize| { + out.iter() + .filter(|&&(.., t, _)| t == Highlight::Comment as u32) + .nth(n) + .copied() + .unwrap_or_else(|| panic!("comment {n} missing in {out:?}")) + }; + // Line 0: "/* lead */" is 10 bytes, all ASCII. + assert_eq!(comment(0), (0, 0, 10, Highlight::Comment as u32, 0)); + // Line 1: "wire /* mid */ a;" — `wire` at 0..4, the comment at 5..14 + // (9 bytes), `a` at 15. + let keyword = out + .iter() + .find(|&&(l, c, _, t, _)| l == 1 && c == 0 && t == Highlight::Keyword as u32) + .copied() + .expect("the `wire` keyword"); + assert_eq!(keyword, (1, 0, 4, Highlight::Keyword as u32, 0)); + assert_eq!(comment(1), (1, 5, 9, Highlight::Comment as u32, 0)); + let ident = out + .iter() + .find(|&&(l, c, _, t, _)| l == 1 && c == 15 && t == Highlight::Variable as u32) + .copied() + .expect("the `a` identifier"); + // `a` is a real declaration in this fragment's full semantics. + assert_eq!(ident, (1, 15, 1, Highlight::Variable as u32, DECLARATION)); + } + #[test] fn no_token_ever_spans_a_line_break() { let text = "/* a\n b\n c */\nmodule m;\nendmodule\n"; @@ -594,6 +665,213 @@ mod tests { assert!(windows_checked > 20, "the corpus really is checked out: {windows_checked}"); } + // ------------------------------------------------------------------ + // the large-file fast path's window + // ------------------------------------------------------------------ + + /// The classes a plain identifier can take once `Semantics` has spoken. + /// A fast-path buffer has no `Semantics`, so every one of them is + /// `variable` there — the one difference between the two paths, and the + /// one this normalization folds away so the rest can be compared. + fn coarse(ty: u32) -> u32 { + let refined = [ + Highlight::Namespace, + Highlight::Class, + Highlight::Type, + Highlight::EnumMember, + Highlight::Parameter, + Highlight::Variable, + Highlight::Property, + Highlight::Function, + ]; + match refined.iter().any(|&r| r as u32 == ty) { + true => Highlight::Variable as u32, + false => ty, + } + } + + /// Decoded tokens with the identifier refinement folded away. + fn coarsely(data: &[SemanticToken]) -> Vec<(u32, u32, u32, u32)> { + decode(data).into_iter().map(|(l, c, len, ty, _)| (l, c, len, coarse(ty))).collect() + } + + /// Whether any construct in `doc` crosses `offset` — a block comment, a + /// continued `` `define``, a multi-line macro call. A window boundary + /// inside one of those is exactly where the fast path is *documented* to + /// disagree, so the agreement property excludes them rather than + /// pretending they do not exist. + fn crosses(doc: &Document, offset: u32) -> bool { + doc.tokens.iter().any(|token| { + let spans = token + .leading + .iter() + .map(|c| c.span) + .chain(token.trailing.iter().map(|c| c.span)) + .chain(std::iter::once(token.span)); + spans.into_iter().any(|span| span.start < offset && offset < span.end) + }) + } + + /// **The agreement anchor.** For a window no multi-line construct reaches + /// into, the fast path's answer is the full pipeline's answer — same + /// spans, same lengths, same classes. Run over real corpus files, in the + /// forty-line windows an editor asks for. + #[test] + fn the_window_lexer_answers_what_the_full_pipeline_answers() { + 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"), + corpus.join("common_cells/src/rr_arb_tree.sv"), + ]; + let (mut compared, mut skipped) = (0, 0); + for path in files { + let Ok(text) = std::fs::read_to_string(&path) else { + eprintln!("{} not checked out — skipping", path.display()); + continue; + }; + let full = Document::new(Some(path.clone()), text.clone(), &WorkspaceIndex::default()); + let fast = Document::large(Some(path.clone()), text); + assert!(!full.tokens.is_empty(), "{}: the premise", path.display()); + assert!(fast.tokens.is_empty(), "the fast path lexed nothing at open"); + let lines = full.line_index.line_count(); + let mut from = 0; + while from < lines { + let to = (from + 40).min(lines); + let window = range((from, 0), (to, 0)); + // The two boundaries in bytes: the start of the first line and + // the end of the last line the window lexes. + let start = full.line_index.line_range(from + 1).map_or(0, |l| l.start); + let end = + full.line_index.line_range(to + 1).map_or(full.text.len() as u32, |l| l.end); + if crosses(&full, start) || crosses(&full, end) { + skipped += 1; + from = to; + continue; + } + assert_eq!( + coarsely(&semantic_tokens_in_window(&fast, window)), + coarsely(&semantic_tokens_in_range(&full, window)), + "{}: lines {from}..{to}", + path.display() + ); + compared += 1; + from = to; + } + } + assert!(compared > 50, "the corpus really is checked out: {compared} (skipped {skipped})"); + // The excluded windows are a small minority; if they ever became the + // majority the property would be vacuous. + assert!(skipped * 4 < compared, "too many windows excluded: {skipped} of {compared}"); + } + + #[test] + fn a_window_of_a_fast_path_buffer_is_self_contained_like_a_range_answer() { + let text = "module m;\n wire a;\n wire b;\nendmodule\n"; + let doc = Document::large(None, text.to_string()); + let data = semantic_tokens_in_window(&doc, range((2, 0), (3, 0))); + let first = data.first().expect("line 2 has tokens"); + assert_eq!(first.delta_line, 2, "encoded from the start of the document"); + assert_eq!(first.delta_start, 2, "the `wire` keyword's own column"); + assert!(decode(&data).iter().all(|&(line, ..)| line == 2)); + } + + #[test] + fn a_fast_path_identifier_is_a_plain_variable_with_no_declaration_modifier() { + // The one documented difference: nothing analyzed the buffer, so the + // module name is not a `class` and carries no `declaration` bit. + let text = "module top;\nendmodule\n"; + let doc = Document::large(None, text.to_string()); + let data = decode(&semantic_tokens_in_window(&doc, range((0, 0), (1, 0)))); + let name = data.iter().find(|&&(l, c, ..)| l == 0 && c == 7).expect("`top`"); + assert_eq!(name.3, Highlight::Variable as u32); + assert_eq!(name.4, 0); + } + + #[test] + fn a_fast_path_window_never_carries_a_token_from_outside_the_range() { + let text = "module m;\n wire a;\n wire b;\n wire c;\nendmodule\n"; + let doc = Document::large(None, text.to_string()); + let inside = decode(&semantic_tokens_in_window(&doc, range((2, 0), (3, 0)))); + assert!(!inside.is_empty(), "premise: line 2 has tokens"); + assert!(inside.iter().all(|&(line, ..)| line == 2), "{inside:?}"); + } + + /// QA (fix-round re-verification): the load-bearing claim behind the + /// walker's restart-on-backwards-offset behaviour is that a window's tail + /// comment genuinely arrives at `flatten` *after* every token in byte + /// order but is pushed into `pieces` *before* them (`semantic_tokens_in_window` + /// pushes `window.comments` ahead of the token loop). This reproduces that + /// exact shape through the real request path — a long declaration line + /// followed by a banner comment that never closes — and checks two + /// things: that the comment really is a byte-order tail relative to every + /// token (the premise the walker's reset exists for), and that every + /// token's and the comment's own position, once decoded off the wire, + /// matches what `Positions::position` would say for the same offset — + /// i.e. the single mid-window restart the out-of-order comment forces + /// does not corrupt anything that comes after it. + #[test] + fn a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly() { + let mut text = String::from("wire "); + for n in 0..500 { + text.push_str(&format!("a{n},")); + } + text.push_str("last;\n"); + let declaration_line_len = text.len() as u32; + text.push_str("/* a banner that never closes\n"); + let doc = Document::large(None, text.clone()); + + // The final `within` filter re-checks the *exact* requested LSP + // range (not the whole-line window `large::window` snapped to), so + // the end has to reach past the comment's own start on line 1 for it + // to survive onto the wire at all. + let window_range = range((0, 0), (1, 50)); + let window = crate::large::window(&doc, window_range); + assert!(!window.tokens.is_empty(), "premise: the declaration line lexed"); + assert_eq!(window.comments.len(), 1, "premise: the banner is one tail comment"); + let comment_span = window.comments[0]; + let last_token_end = window.tokens.iter().map(|t| t.span.end).max().expect("a token"); + assert!( + comment_span.start >= declaration_line_len, + "premise: the comment opens on the second line, after every token byte-wise" + ); + assert!( + comment_span.start >= last_token_end, + "premise: the out-of-order shape this test targets — the comment \ + collected before the tokens in `pieces` has the higher byte offset" + ); + + let positions = doc.positions(); + let decoded = decode(&semantic_tokens_in_window(&doc, window_range)); + assert!(decoded.iter().any(|&(_, _, _, ty, _)| ty == Highlight::Comment as u32)); + // Punctuation (`,`, `;`) is deliberately not classified at all, so it + // never reaches `pieces` — only the tokens `classify` keeps are + // expected on the wire. + for token in window.tokens.iter().filter(|t| classify(t, &doc.semantics).is_some()) { + let expected = positions.position(token.span.start); + let found = decoded + .iter() + .find(|&&(line, start, ..)| line == expected.line && start == expected.character); + assert!( + found.is_some(), + "token at byte {} expected at {expected:?}, not found in {decoded:?}", + token.span.start + ); + } + let comment_expected = positions.position(comment_span.start); + assert!( + decoded.iter().any(|&(line, start, _, ty, _)| line == comment_expected.line + && start == comment_expected.character + && ty == Highlight::Comment as u32), + "comment at byte {} expected at {comment_expected:?}, not found in {decoded:?}", + comment_span.start + ); + } + // ------------------------------------------------------------------ // `semanticTokens/full/delta` // ------------------------------------------------------------------ diff --git a/crates/lucisv_server/tests/e2e.rs b/crates/lucisv_server/tests/e2e.rs index e0f1804..5fccde8 100644 --- a/crates/lucisv_server/tests/e2e.rs +++ b/crates/lucisv_server/tests/e2e.rs @@ -4482,3 +4482,113 @@ fn a_second_session_over_the_same_storage_path_indexes_from_the_cache() { let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&storage); } + +/// A 5 MB netlist — over the shipped `lucisv.largeFile.threshold` of 4 MiB, +/// so this needs no settings push to reach the fast path. +fn big_netlist() -> String { + let mut text = String::from("module netlist_top;\n wire needle;\n"); + let mut n = 0u64; + while text.len() < 5 * 1024 * 1024 { + text.push_str(&format!(" inv_2 _{n}_ (.A(net{n}), .Y(needle));\n")); + n += 1; + } + text.push_str("endmodule\n"); + text +} + +#[test] +fn a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire() { + // The one thing the handler tests cannot show: that a buffer far too big + // to analyze goes through the real binary, over real framing, at the + // shipped default threshold — and that what comes back is colour for the + // window, an answer for the scans, an error for the format, and a decline + // for `semanticTokens/full`. + let dir = temp_dir("largefile"); + let file = dir.join("netlist.v"); + let text = big_netlist(); + std::fs::write(&file, &text).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(&text).expect("json") + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":2,"method":"textDocument/semanticTokens/range","params":{{"textDocument":{{"uri":"{uri}"}},"range":{{"start":{{"line":1,"character":0}},"end":{{"line":3,"character":0}}}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":3,"method":"textDocument/semanticTokens/full","params":{{"textDocument":{{"uri":"{uri}"}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":4,"method":"textDocument/definition","params":{{"textDocument":{{"uri":"{uri}"}},"position":{{"line":1,"character":9}}}}}}"# + )), + frame(&format!( + r#"{{"jsonrpc":"2.0","id":5,"method":"textDocument/formatting","params":{{"textDocument":{{"uri":"{uri}"}},"options":{{"tabSize":2,"insertSpaces":true}}}}}}"# + )), + frame(r#"{"jsonrpc":"2.0","id":9,"method":"shutdown","params":null}"#), + frame(r#"{"jsonrpc":"2.0","method":"exit","params":null}"#), + ] + .concat(); + + let clock = std::time::Instant::now(); + let messages = talk(&session); + let elapsed = clock.elapsed(); + + // The window painted, in the file's own coordinates. + let ranged = messages.iter().find(|m| m["id"] == 2).expect("range response"); + let window = token_numbers(&ranged["result"]["data"]); + assert!(!window.is_empty(), "the viewport was coloured: {ranged:#?}"); + assert_eq!(window.len() % 5, 0, "five numbers per token"); + assert_eq!(window[0], 1, "starting on the window's own first line"); + + // `full` is declined, not answered — see the feature README for why an + // empty answer would cost the file all of its colour. + let full = messages.iter().find(|m| m["id"] == 3).expect("full response"); + assert!(full["result"].is_null(), "no result at all: {full:#?}"); + assert_eq!(full["error"]["code"], -32801, "ContentModified for a client that said nothing"); + assert!( + full["error"]["message"].as_str().unwrap_or("").contains("largeFile.threshold"), + "{full:#?}" + ); + + // The scan answered, in this file. + let definition = messages.iter().find(|m| m["id"] == 4).expect("definition response"); + let locations = definition["result"].as_array().expect("an array"); + assert_eq!(locations.len(), 1, "{definition:#?}"); + assert_eq!(locations[0]["range"]["start"]["line"], 1); + + // Formatting refuses, out loud, and edits nothing. + let formatting = messages.iter().find(|m| m["id"] == 5).expect("formatting response"); + assert_eq!(formatting["result"], serde_json::json!([]), "{formatting:#?}"); + let shown: Vec = messages + .iter() + .filter(|m| m["method"] == "window/showMessage") + .filter_map(|m| m["params"]["message"].as_str().map(str::to_string)) + .collect(); + assert_eq!(shown.len(), 1, "{shown:?}"); + assert!(shown[0].contains("cannot format"), "{shown:?}"); + + // And the fast path announced itself once. + let announced: Vec = messages + .iter() + .filter(|m| m["method"] == "window/logMessage") + .filter_map(|m| m["params"]["message"].as_str().map(str::to_string)) + .filter(|line| line.starts_with("lucisv: large-file fast path:")) + .collect(); + assert_eq!(announced.len(), 1, "{announced:?}"); + + // The whole session — 5 MB across a pipe and back — in a debug build. + // 0.4 s on the machine this was written on, and the bound is twenty-five + // times that: the point is that nothing here parses five megabytes of + // Verilog, which in a debug build is minutes. + assert!(elapsed.as_secs() < 10, "the session took {elapsed:?}"); + eprintln!("5 MB fast-path session: {elapsed:?}"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/docs/features/indexing-ux/README.md b/docs/features/indexing-ux/README.md index 248013c..071048d 100644 --- a/docs/features/indexing-ux/README.md +++ b/docs/features/indexing-ux/README.md @@ -38,6 +38,14 @@ are answerable without a debugger. All three settings ride both settings doors `collect_sources` reads the scope's files (capped) and *then* folds every open buffer in over the top (uncapped) — the same override that has always made a buffer beat disk. + **Amended 2026-08-27 by large-file-mode, and this is the one exception:** a + buffer over `lucisv.largeFile.threshold` (4 MiB by default) was never lexed + or parsed at all, so it contributes *nothing* to the index — and it takes + the disk copy of its own path out with it, rather than leaving the index + describing bytes the buffer no longer has. The two settings do not overlap + in intent: this one is about files nobody asked for, that one is about the + file on screen. The interaction table is in + `docs/features/large-file-mode/README.md`. - **The cap is enforced with `fs::metadata` before the read.** The whole saving is that a 200 MB netlist is never read into memory; a cap applied after `read_to_string` would be a cap that costs what it saves. A file whose diff --git a/docs/features/large-file-mode/README.md b/docs/features/large-file-mode/README.md new file mode 100644 index 0000000..63b5fdc --- /dev/null +++ b/docs/features/large-file-mode/README.md @@ -0,0 +1,1035 @@ +# large-file-mode + +## Goal + +Open a 100 MB netlist instantly. A buffer bigger than +`lucisv.largeFile.threshold` (4 MiB by default) is **never lexed, parsed, +analyzed, linted or indexed**; the whole cost of opening it is one newline +scan to build its `LineIndex` — **41 ms for 100 MB**, measured. What the user +still gets is colour: `textDocument/semanticTokens/range` lexes **only the +window it asks about** (**0.25 ms** for a 60-line viewport, whatever the file's +size), plus go-to-definition and find-references inside that one file by text +scan (**10 ms** and **11 ms** over 100 MB, worst case). Everything else answers +empty, fast, and says so out loud in the one place silence would be confusing. +This is a *checking-light* highlighter: it approximates, every approximation is +written down below, and none of them can corrupt anything — the fast path never +produces an edit. + +## The research question, and its answer + +**Q: on a large buffer, what should `semanticTokens/full` and `full/delta` +answer, given that the capability is advertised globally and cannot be +withdrawn per file?** + +**A: they must answer an ERROR.** Anything else costs the file all of its +colour. The evidence, all of it readable in this repo or on this machine: + +1. **VS Code asks its range provider only while the document provider has not + delivered.** `ViewportSemanticTokensContribution._tokenizeViewportNow` opens + with `if (model.tokenization.hasCompleteSemanticTokens()) return;` + (`/Applications/Visual Studio Code.app/Contents/Resources/app/out/vs/workbench/workbench.desktop.main.js`, + VS Code **1.134.0**, commit `110a328`). The two providers are registered + independently by `vscode-languageclient` — `registerDocumentSemanticTokensProvider` + and `registerDocumentRangeSemanticTokensProvider`, both from + `options.full` / `options.range` + (`editors/vscode/node_modules/vscode-languageclient/lib/common/semanticTokens.js:170-175`) + — so advertising both is not the problem; *answering* full is. +2. **An empty answer, a `null` answer and an empty-delta answer all mark the + model complete.** In the same bundle, `_setDocumentSemanticTokens` ends + every non-error path in `setSemanticTokens(…, true)` — including + `if (!t) { this._model.tokenization.setSemanticTokens(null, !0); … }`, which + is the `null`/no-result path. Complete ⇒ the viewport contribution above + returns immediately ⇒ **no range request is ever sent again** ⇒ a 100 MB + file is grey. +3. **An error leaves the model untouched, and does not spin.** The rejection + handler of the same class calls `onUnexpectedError` only for errors that are + *not* cancellations, never calls `_setDocumentSemanticTokens`, and + re-schedules the fetch **only** if the content changed during the request or + the provider set changed (`(r.length>0||this._providersChangedDuringRequest) + && … schedule(…)`). So an error costs one request per real edit — exactly + what a successful answer would have cost — and never a retry loop. +4. **Both candidate error codes reach VS Code as a cancellation, which is the + silent kind.** `client.js:1487-1507` turns `ServerCancelled` **and** + `ContentModified` into a `CancellationError` for semantic tokens, the latter + because all three semantic-token methods are in + `BaseLanguageClient.RequestsToCancelOnContentModified` (`client.js:1514-1518`, + also sent to us as `general.staleRequestSupport.retryOnContentModified`). + `isCancellationError` is what suppresses the console noise in point 3. +5. **Which code: `ServerCancelled` when the client says it understands one.** + `lsp-types`' own doc for the capability we read + (`textDocument.semanticTokens.serverCancelSupport`) is *"Whether the client + allows the server to actively cancel a semantic token request, e.g. supports + returning LSPErrorCodes.ServerCancelled"*, and `vscode-languageclient` sets + it to `true` (`semanticTokens.js:65`). A client that did not advertise it + gets `ContentModified` (-32801), which every 3.16 client already understands + and which the same handler treats identically. The spec's + `retriggerRequest: false` escape hatch exists **only** for diagnostics + (`protocol.diagnostic.d.ts:77` — there is no semantic-token equivalent), so + there is nothing better to say. + +**Answering `full` from the fast lexer over the whole file was measured and +rejected**: 10 MB of netlist through the real pipeline is 930 ms and 2.6 M +tokens (`the_full_pipeline_probe_says_what_the_fast_path_saves`), so 100 MB is +~10 s and ~26 M tokens — and the *wire* cost alone would be 26 M × 5 numbers of +JSON. The window path answers the same 60 lines in 0.25 ms. + +**Two limits of VS Code itself, worth knowing before anyone tests this by +hand** (same bundle, `TextModel`): + +| VS Code limit | value | consequence | +|---|---|---| +| `_MODEL_SYNC_LIMIT` | 50 MB | a bigger file is **never sent to any extension** (`isTooLargeForSyncing`), so lucisv is not asked about it at all — no `didOpen`, no colour, nothing. Editors without that rule (the Neovim client) still reach the fast path at any size. | +| `LARGE_FILE_SIZE_THRESHOLD` | 20 MB | above it (or 300 k lines) `largeFileOptimizations` turns the **TextMate grammar off**, so between 20 MB and 50 MB our viewport semantic tokens are the *only* colour on screen. | + +So in VS Code the fast path is what serves 4 MB – 50 MB, and it is the whole of +the colouring above 20 MB. The 100 MB case is real for Neovim and for the +measurements; VS Code declines it before we see it. + +## The mode + +`Workspace::set_document` — the one place a `Document` is built — chooses: + +``` +text.len() > lucisv.largeFile.threshold → Document::large(path, text) +``` + +`Document::large` builds a `LineIndex` and *nothing else*. Its `tokens`, +`tree`, `diagnostics`, `semantics`, `defines` and `external` are the analysis +of the **empty** file (built by parsing `""`, which costs nothing and needs no +new API from `vlog_parser`), and its `large` flag is set. That is the whole +trick: every handler that reads the analysis finds exactly nothing and answers +empty *without knowing this mode exists*, and only the handlers that would read +the **text** need to be told. + +Because the decision lives in `set_document`, it is re-taken on every +`didOpen`, every `didChange` and every text-carrying `didSave`. A buffer edited +past the threshold switches to the fast path at that moment; one edited back +under it is analyzed again in full. **A changed `lucisv.largeFile.threshold` +therefore takes effect at each buffer's next change, not immediately** — the +simplest rule that has no re-analysis storm in it, and the one the tests pin. + +## The dispatch table + +Every request a document-scoped client can send, and what a buffer on the fast +path answers. The gate (`Server::large_file_answer`) reads +`params.textDocument.uri` out of the raw JSON *before* the typed decode, so one +lookup covers thirty parameter types; a request with no `textDocument` is not +gated at all, which is correct because none of them can reach a buffer's text. + +| request | answer | why | +|---|---|---| +| `semanticTokens/range` | **the window, lexed** | the whole point; see below | +| `semanticTokens/full` | **error** `ServerCancelled` / `ContentModified` | anything else kills the range provider — the research above | +| `semanticTokens/full/delta` | same error | a delta against an answer that was never given is meaningless | +| `definition` | **the declaration heuristic** | one linear scan, 10 ms/100 MB | +| `references` | **the occurrence scan**, capped at 1000 | one linear scan, 11 ms/100 MB | +| `formatting`, `rangeFormatting`, `rangesFormatting` | `[]` **plus an ERROR message** | the user pressed a key; silence would read as a broken formatter. No edit is ever produced, so invariant #1 is untouched | +| `onTypeFormatting` | `[]`, silent | fires on every keystroke; it never speaks, as it never has | +| `willSaveWaitUntil` | `null`, silent | fires on every save; declining is already its cheap path | +| `rename` | error `RequestFailed` | a rename would rewrite every *other* file and leave this one alone — the buffer is in neither the index nor `sources()`. Refusing is the only honest answer | +| `prepareRename` | `null` | so the rename box never opens on a rename that would be refused | +| `hover` | `null` | it would otherwise resolve `` `include``s, which scans the text | +| `documentLink` | `[]` | same: `includes::scan` is a line scan of the whole buffer | +| `codeAction` | `[]` | it would otherwise run the fix applier over the text | +| `publishDiagnostics` / `textDocument/diagnostic` | **empty, once** | nothing was parsed, so there is nothing to say — and the empty publish is what clears squiggles a buffer that just grew past the threshold left on screen | +| `documentSymbol`, `foldingRange`, `documentHighlight`, `codeLens`, `inlayHint`, `completion`, `signatureHelp`, `inlineCompletion`, `typeDefinition`, `linkedEditingRange`, `prepareCallHierarchy`, `prepareTypeHierarchy`, `lucisv/scopePairs` | empty / `null` | not gated at all: they read the analysis, and the analysis is empty. Pinned by `every_other_request_a_large_buffer_gets_answers_nothing_at_all` so a future handler that reads the *text* fails there rather than in a user's editor | +| `selectionRange` | one step: the whole document | the one request that answers something. Expand-selection to the file is true with nothing parsed, and costs one span | +| everything workspace-scoped (`workspace/symbol`, the hierarchy resolutions, `executeCommand`, `willRenameFiles`) | as always | they work off the index, which does not hold this file | + +A `window/logMessage` is sent **once per entry into the mode**: +`large-file fast path: ( bytes) — syntax highlighting only, +nothing is parsed or indexed`. Not once per notification (a keystroke in a +100 MB buffer must not log), and nothing is said on the way back out. + +## The window lexer + +`large::window(doc, range)` is the only thing that reads a large buffer's text +for colour. + +1. **Snap to lines.** The window is the first line of `range.start` through the + last line of `range.end`, so the lexer never starts inside a token. +2. **Cap.** At most `MAX_WINDOW` = 1 MiB. A client is free to ask for the whole + document — VS Code's own `_provideDocumentRangeSemanticTokens` command does + — and that would be the whole-file pass this mode exists to avoid. A + viewport plus the pages above and below is a few tens of kilobytes, three + orders of magnitude clear. A single line longer than the cap is cut + mid-line; a token cut in half still colours as what it started as. +3. **Am I inside a block comment?** A backward scan of at most `BACKSCAN` = + 64 KiB takes the last `/*` or `*/` before the window and believes it. If the + opener wins, the tail up to the window's first `*/` is coloured as a comment + and the lexer starts after it; if there is no `*/` in the window at all, the + whole window is one comment and nothing is lexed. +4. **Lex the rest with the real lexer.** `vlog_parser::tokenize` on the window + slice — the *same* function the full pipeline uses, which is what makes the + agreement property below possible. Spans are rebased from window offsets to + document offsets afterwards, comments on tokens included. +5. **The far edge.** The lexer is all-or-nothing, and a window ends wherever + the viewport ended, so an unterminated comment or string at the bottom is + the normal case. The lex error names the line it gave up on; the window is + shrunk to that line's start and retried (at most 4 times). What is left over + is coloured as a comment when it opens one that never closes — the banner + comment crossing the bottom of the screen, which is both what it is and what + the next window will say once the user scrolls. +6. **Classify with the shared code.** `tokens::semantic_tokens_in_window` feeds + the window's tokens through the *same* `classify`, the same line splitting, + the same overlap filter and the same encoder as + `semantic_tokens_in_range`. Only the source of the tokens differs. + +**The agreement anchor.** `the_window_lexer_answers_what_the_full_pipeline_answers` +runs both paths over real corpus files in forty-line windows and asserts they +produce identical spans, lengths and classes — excluding windows a multi-line +construct reaches into (computed from the full pipeline's own token spans, and +asserted to stay a small minority of windows), and folding away the one +documented difference below. + +### What it gets wrong, honestly + +- **A plain identifier is always `variable`, with no `declaration` modifier.** + There is no `Semantics` to refine it with, so a module name is not a `class` + and a parameter is not a `parameter`. Keywords, numbers, strings, comments, + directives, macro uses, `$system` tasks and attributes are all exactly what + the full pipeline says. +- **A `/*` inside a string or after a `//` fools the backward scan**, and so + does a block comment whose opener is more than 64 KiB back — the documented + answer there is "code", so a multi-megabyte block comment mis-highlights. + Checking-light, by the owner's own framing: a wrong colour on a screen is not + a wrong answer about the source. +- **A construct spanning the window's start** (a continued `` `define``, a + multi-line macro call) is lexed as ordinary code on the window's first line. +- **A window whose *first* line does not lex answers nothing at all** rather + than guessing, and the next window (or the next keystroke) fixes it. +- **No nesting is tracked.** The owner asked for a cap of ~16 layers; a token + classifier has no scope state to cap, so the cap is satisfied by there being + no depth-tracking at all. The requests that *would* need nesting — + `foldingRange`, `lucisv/scopePairs`, `selectionRange`'s inner steps — answer + empty on a large buffer, which is the same guarantee stated as an absence. + +## definition and references + +One linear pass over the buffer per request, no state kept. + +- The identifier under the cursor is read off the text (`[A-Za-z0-9_$]`). +- **definition**: the first whole-word occurrence whose preceding word is one + of 22 declaring keywords (`module`, `wire`, `logic`, `input`, `parameter`, + …; every one asserted to be a real `vlog_parser::KEYWORDS` entry). A + declaration written any other way — an ANSI port after its direction *and* + type, a `typedef`'s new name, an instance name — is simply not found, and the + request answers `[]`. +- **references**: every whole-word occurrence, capped at **1000** + (`REFERENCE_LIMIT`); `includeDeclaration: false` drops exactly the one the + heuristic above picks. There are no scopes here, so two locals called `i` in + two modules are one answer. That is what a text scan can honestly say. + +Shipped because they measured fast: the owner's condition was "only if it costs +nothing perceptible", and the fallback was to drop them. See the numbers below. + +## Measurements + +`cargo test -p lucisv_server --release -- --ignored --nocapture large::tests`, +on the machine this was written on (Apple silicon, release build), over a +**104,857,674-byte / 1,570,802-line** synthesized netlist: + +| operation | cost | +|---|---| +| open (`didOpen` → `Document::large`, i.e. the line index) | **40.7 ms** | +| `semanticTokens/range`, 60-line viewport, first call | **0.247 ms** | +| the same window again | **0.152 ms** | +| `definition`, name declared in the file's **last** line (worst case) | **9.96 ms** | +| `references`, whole-file scan, 2 hits | **10.9 ms** | +| `references`, short name that prefixes a million others (worst case) | **36.6 ms** | + +Comparison, on 10 MB because 100 MB through the full pipeline is minutes and +gigabytes: `Document::large` **7.1 ms** vs `Document::new` **930 ms** — **130×**, +for 2.6 M tokens that are never built. + +### The long-line shape (QA finding 1, fixed 2026-08-27) + +A netlist is not only big, it is *wide*: a bus declaration or a generated port +list can put tens of thousands of tokens on **one** line. Converting each of +their byte offsets to a UTF-16 column used to re-measure that line from its +start (`Positions::position`), which is O(tokens²) for a window and +O(hits × line) for a scan's answer. `convert.rs` now offers a monotonic cursor, +`Positions::walker`, and the two fast-path converters use it. Release build, +same machine, same probes — now running in the normal suite rather than +`#[ignore]`d: + +| probe | before | after | +|---|---|---| +| colour a window of 5,000 tokens on one 29 KB line | 107.8 ms | **1.6 ms** | +| … 10,000 tokens, 59 KB | 439.3 ms | **4.2 ms** | +| … 20,000 tokens, 129 KB | 1.85 s | **8.6 ms** | +| … 40,000 tokens, 269 KB | **7.86 s** | **14.4 ms** — 546× | +| locate 100 `references` hits on one 2.6 MB line | 206 ms | **2.1 ms** | +| … 200 hits, 5.2 MB | 789 ms | **4.3 ms** | +| … 400 hits, 10.4 MB | 3.15 s | **8.3 ms** | +| … 800 hits, 20.8 MB | **12.6 s** | **16.6 ms** — 759× | + +Both columns now double when the input doubles, which is the shape the mode +promises. The scans themselves were always linear and are unchanged (1.0 ms and +6.9 ms for the two ends of the second block). + +The same conversion is what `semanticTokens/full` uses on an **ordinary** +buffer, so this was never only a fast-path bug: a 129 KB single-line file under +the threshold answered `semanticTokens/full` in **2.06 s** before and **232 ms** +after (the remainder is `Semantics::symbol_at`, a different shape and not this +round's). + +End to end, through the real binary in a **debug** build, 5 MB over stdio +(`a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire`): the whole +session — initialize, didOpen, a range request, a declined full request, a +definition, a formatting refusal, shutdown — **0.40 s**. + +## Interaction with the index (`lucisv.index.maxFileSize`) + +The two size settings mean different things and now interact in one place: + +| | `lucisv.index.maxFileSize` (1 MiB) | `lucisv.largeFile.threshold` (4 MiB) | +|---|---|---| +| what it governs | files the **walk** finds on disk | the buffer the user **opened** | +| what it costs | one `stat`, no read | one newline scan, no lex | +| `0` means | no cap | fast path off | + +| the file is… | before this round | now | +|---|---|---| +| walked, over `maxFileSize` | not read at all | unchanged | +| open, under `largeFile.threshold` | analyzed, indexed (uncapped) | unchanged | +| **open, over `largeFile.threshold`** | analyzed and indexed however big — the "an open buffer is never capped" rule | **not analyzed, not indexed, and its path is removed from the index** rather than being served by the stale disk copy | + +The last row is the amendment recorded in +`docs/features/indexing-ux/README.md`. Removing the path (rather than letting +the disk copy stand) keeps the old promise — *the index never disagrees with +the buffer the user is looking at* — in the only way still available: if we +cannot describe what is on screen, we describe nothing. Every cross-file answer +is therefore blind to a fast-path file: it is out of scope, exactly as a file +over the walk cap always was. + +Opening one still **widens the folder scope** the ordinary way — the file's own +directory joins the walk, and the index is rebuilt for it. That is the +directory's business rather than the file's, and the netlist itself is left out +of the resulting index twice over (by the walk cap, and by the rule above). + +`didChange` on a large buffer costs what it always did — `sync::apply_changes` +rebuilds the buffer (O(file) per batch, and edits in a netlist are rare) and +`LineIndex::new` rescans it. No lex, no parse, no diagnostics, no index touch. + +## Assumptions + +- **`text.len()` is the size test**, not the file's size on disk: the buffer is + what is being analyzed, and an `untitled:` buffer has no file. The comparison + is strict, so a buffer of exactly the threshold is analyzed in full. +- **The client asks for ranges.** A client that advertises no `range` support + and only ever asks for `full` gets no colour at all on a large buffer. Every + client this repo ships for (VS Code through `vscode-languageclient`, Neovim's + built-in LSP) asks for ranges. +- **The buffer's text stays in memory.** 100 MB of `String` is the price of + answering anything at all; the editor holds a copy too. +- **The threshold is not consulted anywhere but `set_document`.** A setting + changed while a buffer is open leaves that buffer in the mode it was built + in until its next change. +- **VS Code ≥ 1.134 behaves as the bundle read here says.** The two facts + relied on — "complete tokens stop the viewport provider" and "an error is not + a complete answer" — have been in VS Code for years, and the range provider + would have to *gain* independence for the choice to become wrong rather than + merely unnecessary. Re-check trigger: a VS Code release note saying the + viewport contribution runs alongside document semantic tokens. + +## Handshakes + +**Consumed from `vlog_parser`:** `tokenize` (on a window slice — a `&str` is a +`&str`, and the all-or-nothing failure is handled by shrinking rather than by +asking the lexer to change), `LexError { line }` (the shrink target), +`LineIndex::{new, line_count, line_col, line_range}`, `TextRange`, +`token::{Token, TokenKind, Comment}` with **mutable** `span` fields (the +rebasing), and `KEYWORDS` (the declarator assertion). + +**Consumed from `vlog_semantic`:** nothing new. `Document::large` builds an +empty `Semantics` by analyzing the empty file. + +**Consumed from `convert.rs` (added by this feature's fix round):** +`Positions::walker() -> PositionWalker`, a cursor that converts a +non-decreasing sequence of byte offsets in amortized O(1) each. It answers +exactly what `Positions::position` answers for every offset — including +backwards ones, which restart the measurement rather than failing — so it is an +addition, not a change: every existing caller of `position`/`range` is +untouched and byte-identical. Two callers adopt it, both converting sequences +that are already ascending: `tokens::flatten` (the window colourer, and with it +the ordinary `semanticTokens/full`) and `Server::large_scan` (the +definition/references hits). This closes QA's handshake request below. + +**Promised to the rest of the crate:** `Document::large` is a `Document` in +every structural sense — every field is present and valid, just empty — so no +handler needs to change to keep compiling or to keep answering. The one new +obligation is on **future** handlers: *if you read `doc.text` rather than +`doc.tokens`/`doc.tree`, you must check `doc.large`.* The dispatch-table test +is where that obligation is enforced. + +**Requested of other modules — none.** No engine changed in this round. + +## Status / TODO + +- [x] Research: what VS Code does with `semanticTokens/full` when `range` is + also advertised. Answered above, pinned with file-and-line evidence from + VS Code 1.134.0's own bundle and from the pinned `vscode-languageclient`. +- [x] `lucisv.largeFile.threshold` in `settings.rs` (both doors: pushed and + pulled) and in `editors/vscode/package.json`. +- [x] `Document::large`, the mode decision in `Workspace::set_document`, and + the index exclusion in `collect_sources`/`current_text`. +- [x] `large.rs`: the window lexer, the backward block-comment scan, the + shrink-on-failure rule, the two scans. +- [x] `tokens::semantic_tokens_in_window`, sharing classification and encoding + with the normal range answer. +- [x] The dispatch table in `Server::large_file_answer`, plus + `Failure::Declined` for the two semantic-token refusals. +- [x] Diagnostics: empty for a large buffer, in `diagnostics::all`, so push and + pull agree. +- [x] The `window/logMessage`, once per entry into the mode. +- [x] Same-file definition/references — **shipped**: 10 ms and 11 ms over + 100 MB against the owner's 150 ms budget. +- [x] Tests: **43 new** — 23 in `large.rs` (21 plus the 2 `#[ignore]`d probes), + 4 in `tokens.rs` (including the corpus agreement anchor), 5 in + `state.rs`, 12 in `server.rs` (the dispatch table among them), 1 e2e + against the real binary. +- [x] The measurements, quoted above. +- [x] **QA finding 1 (long lines) fixed**: `Positions::walker` in `convert.rs`, + adopted by `tokens::flatten` and `Server::large_scan`. QA's two + `#[ignore]`d probes are now gates in the normal suite, with wall-clock + bounds; walker/per-call equivalence is pinned by a fixed-seed property + test over multi-byte, CRLF, empty-line and single-giant-line fixtures. +- [ ] **Not done, deliberately:** no `semanticTokens/full` answer of any kind + for a large buffer, so a client that cannot ask for ranges gets no + colour. Revisit only if such a client turns up. +- [ ] **Not done:** the fast path does not know about `didClose`-then-reopen + caching. Reopening a 100 MB file costs the 41 ms line scan again, which + is not worth a cache. + +## Work log + +### 2026-08-27 — dev agent + +- **Research first, as instructed.** The full/delta answer was settled before + any code was written, from three sources in this repo or on this machine: + the pinned `vscode-languageclient@9.0.1` sources under + `editors/vscode/node_modules`, the `vscode-languageserver-protocol` type + docs beside them, and the installed VS Code 1.134.0's own bundled + `workbench.desktop.main.js`. The last one is what turned "I believe VS Code + skips the viewport when the document provider answered" into a quotable + line of code; it also produced the two VS Code limits (50 MB sync, 20 MB + grammar) that reframe what this feature is *for* in that editor. All of it + is written up in "The research question" above. +- **`Document::large` builds the empty analysis rather than making every + field an `Option`.** The alternative — an enum, or `Option` and + friends — would have touched every one of the thirty-odd handlers that read + those fields, for no behaviour they do not already have: they all answer + empty on an empty analysis. This is the "fights the codebase least" choice + the lead asked for, and it is why the dispatch table has ten rows that are + *not* special-cased. +- **The gate reads the URI out of the raw JSON.** `Server::large_file_answer` + runs before the typed decode and looks at `params["textDocument"]["uri"]`. + One lookup, thirty parameter types, and a request without that key is not + gated — which is exactly the set of requests that cannot reach a buffer's + text anyway. +- **`Failure::Declined(code, message)`** is the one new protocol shape: an + error that is not `RequestFailed`. Two codes, chosen by the client's own + `serverCancelSupport` capability, both of which the pinned client turns into + a `CancellationError`. +- **The window lexer runs the real lexer**, per the lead's design. The two + things that made that workable were (a) the window is snapped to line + boundaries so no token is torn at the start, and (b) `LexError` carries the + line it failed on, so the far edge is one shrink-and-retry rather than a + hand-rolled scanner. Writing a comment/string scanner of our own was + considered and rejected: it is language knowledge, which this crate is not + allowed to hold (`docs/features/lucisv-server/README.md`'s own rule), and it + would have broken the agreement property with the full pipeline. +- **Deviation, argued: no nesting cap.** The design asked for scope tracking + capped at 16 levels. A token classifier keeps no scope state, so there was + nothing to cap; the requests that would need it answer empty. Recorded under + "What it gets wrong" rather than implemented as a knob nothing reads. +- **Deviation, small: `willSaveWaitUntil` is silent** where the design put it + with the noisy formatting refusals. It fires on every save of every buffer + and already has `null` as its documented decline; a popup per save would be + the noise the on-type rule exists to avoid. The three requests the user + actually pressed a key for still speak. +- **definition/references shipped**, against the owner's explicit fallback: + the worst-case scans are 10 ms and 37 ms over 100 MB, an order of magnitude + under the 150 ms budget. +- **The index interaction** turned out to have a second half the design did + not name: a large buffer must not merely *fail to override* the disk copy, + it must remove that path from the sources, or the index would describe a + file by bytes the buffer no longer has. Amended `indexing-ux`'s README + accordingly and pinned it with + `a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind`. +- Gates, all clean: `cargo fmt --all -- --check`; `cargo clippy --all-targets` + (0 warnings); `cargo test --workspace` (**2343 passed, 0 failed**, 11 + ignored — the 2 new probes among them); `cargo test -p vlog_formatter` (180 + passed); `node smoke.js ../../target/release/lucisv-server` (OK). No new + dependencies, and no engine crate was touched. +- **Note for the lead:** the working tree also carries a change to + `crates/vlog_parser/src/defines.rs` (`Define`/`DefineTable` gain + `PartialEq`/`Eq`, plus `DefineTable::from_entries`) that this round did not + make and did not need. It was already there when this work started — it + looks like index-persistence's, uncommitted — and it has been left exactly + as found. + +### 2026-08-27 — dev agent, fix round (QA finding 1) + +- **The finding, restated in one line:** the mode's core promise is a bounded + cost regardless of file size, and it did not hold for a buffer that is *wide* + rather than tall — 40,000 tokens on one 269 KB line cost 7.86 s to colour, + 800 references on one 20 MB line cost 12.6 s to locate. Both quadratic, both + realistic netlist shapes. +- **The fix is an addition to `convert.rs`, not a rewrite.** `PositionWalker`, + handed out by `Positions::walker()`, carries three numbers forward — the line + it is on, how far into that line it has measured, and the UTF-16 units it + counted getting there — so a sequence of non-decreasing offsets measures each + line's bytes **once** instead of once per offset. `Positions::position` is + byte-for-byte what it was, and every one of its ~40 callers is untouched. +- **Out-of-order input is a restart, not a panic.** The walker is used only on + ascending sequences, but "ascending" is a caller's promise and a promise is + not an invariant. A backwards offset resets the cursor to that line's start + and re-measures — the exact work `Positions::position` would have done — so + the walker is *total* and its answer is always the per-call answer. That + choice is also what keeps the window colourer fast: the fast path's + window-edge comment spans genuinely do arrive out of order (a tail comment + sits after every token in the window but is collected before them), and + without the reset every token after one would have fallen back to the slow + path and nothing would have been fixed. +- **Equivalence is pinned, not asserted.** `convert.rs` gains a fixed-seed LCG + property test (`the_walker_agrees_with_the_per_call_converter_on_every_shape`) + that walks randomized ascending offset sequences — two strides, a 4-byte + crawl and one that crosses the fixture in 20 steps — over seven fixtures: + empty, plain ASCII, mixed 2/3/4-byte characters with CRLF, all-CRLF with a + blank line, 50 bare newlines, a 14 KB single line, and a wide line of + accented identifiers. Plus `..._at_every_byte_of_a_gnarly_buffer` (every byte + including mid-character and both halves of every `\r\n`), a 500-offset + *jumbled* sequence, and `range`. Every one compares against + `Positions::position` rather than against a hand-written expectation. +- **Adopted in three places, all one line each.** `tokens::flatten` (the window + colourer), `Server::large_scan` (definition/references hits), and — for free, + because they share `flatten` — the ordinary `semanticTokens/full` and + `/range`. See the audit note below. +- **`collect_trivia` became `collect`**, which now pushes a token's own piece + between its leading comments and its trailing one, i.e. in source order. The + two callers each had the same four lines of "classify and push" after calling + it; folding those in removed the duplication and made the piece stream + ascending, which is what lets one cursor serve a whole window. Ordering is + invisible downstream (`flatten` sorts, stably, and no two pieces from one + token can start at the same byte), and the corpus agreement anchor plus the + 55 existing semantic-token tests are the proof: unchanged and green. +- **The `tokens.rs` audit the lead asked for — it was never only a fast-path + bug.** `absolute()` (`semanticTokens/full` and `/range` on an *ordinary* + buffer) flattens through the same function, so any file with a long line hit + the same wall well under the 4 MiB threshold. Measured directly: a 129 KB + buffer that is one line of 20,000 tokens answered `semanticTokens/full` in + **2.06 s** before and **232 ms** after. It qualified under the lead's + same-one-line-adoption rule — the fix is literally the same two lines inside + `flatten` — so it is fixed here rather than filed. The residual 232 ms is + `Semantics::symbol_at` being called once per identifier, a different shape + in a different crate; not this round's, and not filed as a finding because it + is the normal path's ordinary per-token semantic lookup, not a regression. +- **Swept the other `Positions` callers for the same shape; none qualify.** + `diagnostics.rs`, `lint.rs`, `lens.rs`, `pairs.rs`, `linked.rs`, + `includes.rs`, `hierarchy.rs` and `selection.rs` each convert a handful of + spans per request (one per diagnostic, lens, pair or chain step), bounded by + something the user can see rather than by the file's width; `format.rs`, + `rename.rs`, `hover.rs` and `completion.rs` convert one or two. None loops + over a per-token or per-hit sequence. `sync.rs` and `ports.rs` use `offset`, + which is O(column) by nature and has no walker (a client sends one position, + not a sequence). +- **QA's two `#[ignore]`d probes are now gates.** Renamed to + `a_window_of_many_tokens_on_one_line_colours_in_linear_time` and + `references_on_one_giant_line_locate_their_hits_in_linear_time`, they run in + the normal suite with wall-clock bounds in **debug**: 350 ms against a + measured 77 ms (40,000 tokens), and 150 ms against a measured 32 ms (800 + hits). Both margins are ~4.5x the measurement, which was stable to ±0.5 ms + over four runs; the quadratic version they replace overshoots them by two + orders of magnitude, so they fail on a regression in *kind* and not on a slow + box. The references probe runs at an eighth of QA's line lengths (2.6 MB + rather than 20.8 MB) so it costs the suite 0.05 s rather than 2 s; the same + test at QA's original geometry was measured by hand at **16.6 ms** against + its 12.6 s, and both geometries are quoted in the table above. +- **Deviation from the lead's "touch only" list, argued:** `server.rs` is on + the diff. The definition/references hit-to-`Location` conversion the + acceptance criteria name is `Server::large_scan`, which lives there and + nowhere else; the change is three lines (take a walker, use it in the `map`) + and touches no other handler. Leaving it out would have left half of finding + 1 unfixed. +- Gates, all clean: `cargo fmt --all -- --check`; `cargo clippy --all-targets` + (0 warnings); `cargo test --workspace` (**2354 passed, 0 failed**, 11 + ignored — up from 2347/13 by the two flipped probes and the five new walker + tests); `cargo test -p vlog_formatter` (green); `node smoke.js + ../../target/release/lucisv-server` (OK). The corpus agreement anchor + (`the_window_lexer_answers_what_the_full_pipeline_answers`) ran against the + real corpus, not skipped. No new dependencies; no engine crate touched. + +## QA log + +### 2026-08-27 — QA agent + +**Gates, re-run clean after the fixes below:** `cargo fmt --all -- --check`; +`cargo clippy --all-targets` (0 warnings); `cargo test --workspace` (**2347 +passed, 0 failed, 13 ignored**, up from the dev's 2343/11 by the six tests +added below); `cargo test -p vlog_formatter` (114 passed); `node smoke.js +../../target/release/lucisv-server` (OK). The three release-mode probes in +`large.rs` re-run three times each: `open` 39.9–40.9 ms, `semanticTokens/range` +0.15–0.24 ms, `definition` 9.5–10.0 ms, `references` 11.2 ms / +36.7–36.9 ms (worst case) — all within the README's numbers, not flaky. + +**1. The research verdict — verified, not just re-read.** Checked out first +because everything else rests on it. + +- `editors/vscode/node_modules/vscode-languageclient/lib/common/semanticTokens.js:65` + really is `capability.serverCancelSupport = true`, and the cited + `:170-175` really does bracket both `registerDocumentSemanticTokensProvider` + (line 171) and `registerDocumentRangeSemanticTokensProvider` (line 174), + registered independently as claimed — exact, not approximate. +- `client.js`'s rejection handler (found near line 1487, matches) does exactly + what §3–4 of the README claim: `ServerCancelled` is turned into a + `CancellationError`/`LSPCancellationError` **unconditionally**; + `ContentModified` only for methods in `RequestsToCancelOnContentModified`, + which the same file lists as the three semantic-token methods, confirmed a + few lines below. Both polarities pinned in code, not just prose. +- **The load-bearing behavioural claim — re-derived against the actual + installed bundle, not trusted on the dev's word.** VS Code 1.134.0, commit + `110a328`, is genuinely installed at the path cited + (`code --version` confirms both). Pulled the real minified source of + `_tokenizeViewportNow` out of the 18 MB bundle: it opens with + `if(e.tokenization.hasCompleteSemanticTokens())return;` — the exact claim in + point 1, not a paraphrase. Pulled `_setDocumentSemanticTokens`: the `!t` + branch is `this._model.tokenization.setSemanticTokens(null,!0),a();return` + — the null/complete path in point 2, byte-for-byte. Pulled the promise + rejection handler one call up: `l&&(Hi(l)||typeof l.message=="string"&&...) + ||pt(l)` (skip `onUnexpectedError` for a cancellation or a "busy" message), + then `(r.length>0||this._providersChangedDuringRequest)&&(!...isScheduled()&& + ...schedule(...))` — exactly point 3's "reschedules only if content changed + or the provider set changed." **Verdict: not a misread. The behavioural + claim (error → range keeps painting) is directly confirmed in the shipped + binary, independent of the dev's own reading.** + +**2. The window lexer — the documented edges hold; the undocumented one does +not.** + +- Corpus agreement test (`the_window_lexer_answers_what_the_full_pipeline_answers`) + passes as shipped. +- Verified clean: window starting inside a block comment beyond `BACKSCAN` + (existing test), a window boundary inside a string/comment at the far edge + (existing tests), an empty window, a window past EOF, a single line longer + than `MAX_WINDOW` (existing test) — all bounded, no panics. +- Added and verified clean: a 5,000-line buffer of nothing but newlines (every + boundary coincides with every other — `a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens`, + `large.rs`) and a CRLF netlist (`a_crlf_netlist_windows_the_same_as_its_lf_twin`, + `large.rs`) — same tokens as the LF twin, no token swallows a `\r`. +- UTF-16 rebasing: `large::rebase`/`shift` operate purely on byte offsets, so + they are encoding-agnostic by construction; the actual byte→UTF-16 + conversion is deferred to the whole document's `Positions` (`convert.rs`), + unmodified by this round. Correct **and** the mechanism of finding #1 below + — see there. + +> **FIXED 2026-08-27** by the dev fix round logged above — `Positions::walker` +> in `convert.rs`, adopted by `tokens::flatten` and `Server::large_scan`. The +> finding stands as written; the numbers below are the *before* column of the +> table in "The long-line shape" above. Both probes now run in the normal suite +> as gates rather than `#[ignore]`d demonstrations, under the names +> `a_window_of_many_tokens_on_one_line_colours_in_linear_time` and +> `references_on_one_giant_line_locate_their_hits_in_linear_time`. The +> handshake request at the end of this log is satisfied. + +**FINDING 1 (HIGH) — the "bounded, however big the file is" guarantee is false +for a realistic shape: many tokens on one very long line.** Not a corruption +risk (invariants #1–#3 hold: nothing is ever miscompiled, this is a *speed* +claim), but it defeats the feature's entire premise — a keystroke can hang the +editor for the exact class of file this mode targets. + +Root cause: `Positions::position` (`crates/lucisv_server/src/convert.rs:27`, +**pre-existing, not part of this round's diff**) converts a byte offset to a +UTF-16 column by re-scanning **from the start of the token's line** every +call. On ordinary source (short lines) this is free. `large::window` bounds +the *bytes lexed* to `MAX_WINDOW` (1 MiB) but does nothing about how many +*tokens* land inside that one window, and when they all sit on one line, every +one of them pays for a scan whose length grows with how far into the line it +is — O(tokens²) for the window as a whole, over `tokens::flatten` +(`tokens.rs:265`). Same mechanism, same author (`Positions::range`), also hits +`Server::large_scan` (`server.rs:859`), which converts every `definition`/ +`references` hit the same way — so a name repeated many times on one long +line is slow to *locate* even though `large::references`' own scan +(`large.rs`) is genuinely linear. + +Measured (release build), two probes, both `#[ignore]`d (they are +demonstrations, not gates — no timing assertion, so they can never become an +accidental xfail; run with `--release --ignored --nocapture`): + +- `qa_a_single_multi_line_bus_still_shows_quadratic_cost_in_the_window_colourer` + (`large.rs`): one line, `wire a0,a1,...,aN;`. Lexing stays linear (1.3 ms → + 9.7 ms as tokens go 5,000 → 40,000, an 8x growth for 7x work); colouring the + same window goes 107.8 ms → 439.3 ms → 1.85 s → **7.86 s** — roughly 4x time + for every 2x tokens, the signature of O(n²), on a line still well inside the + 1 MiB `MAX_WINDOW` cap (269 KB at 40,000 tokens). +- `qa_references_on_one_giant_line_is_fast_but_locating_the_hits_is_not` + (`large.rs`): `references` on one line with 100/200/400/800 hits (all under + `REFERENCE_LIMIT`). The scan itself: 2.0 ms → 6.3 ms (sublinear). Turning + those hits into `Location`s the way `Server::large_scan` does: 206 ms → + 789 ms → 3.15 s → **12.6 s**. + +Both are realistic shapes for the domain this feature targets — a wide bus +declaration, a long sensitivity list, a signal repeated across a generated +one-line block — not adversarial inputs. Extrapolating the first probe's curve +to the full 1 MiB `MAX_WINDOW` (roughly 4x the 40,000-token sample) lands +around a minute of blocked colouring for a single scroll. + +**This is shared code (`convert.rs`) reached through a new path +(`large.rs`/`tokens::semantic_tokens_in_window`/`Server::large_scan`), so it +is filed here rather than fixed in this round** — CLAUDE.md's scope rule cuts +the other way for a fix (it would touch `Positions`, used by every +non-fast-path request too, and deserves its own design and its own tests +rather than a QA-agent patch under time pressure). Recorded as a handshake +request below. Not a blocker for the parts of this round that do not touch +`Positions` on multi-hit-per-line input, but it should block calling the +*colouring and navigation* halves of this feature done until addressed or +consciously accepted. + +**3. Threshold crossing.** Grow-past (`a_buffer_edited_past_the_threshold_changes_mode_and_back`, +existing) and the diagnostics-clear-on-cross test both verified clean. Shrink- +back verified in the same existing test. `threshold=0` verified via the +existing `a_threshold_of_zero_turns_the_fast_path_off_entirely` (branch logic +read, not run at 100 MB literally, as instructed). Settings-mid-session +semantics (`the_threshold_arrives_by_push_and_by_pull_and_takes_effect_on_the_next_change`) +verified clean, both doors. + +**4. Index-sources removal.** `Workspace::current_text`/`collect_sources` +correctly exclude a `doc.large` buffer's path in both places (state.rs diff +read line by line). The existing +`a_fast_path_buffer_contributes_nothing_to_the_index_and_leaves_no_disk_copy_behind` +test proves the index actually shrinks on a full rebuild. + +- **Reappearance on `didClose` — traced, not separately tested, and correct + by construction:** once the buffer closes, `Workspace::docs` no longer holds + it, so `current_text`/`collect_sources` fall through to the normal + disk-read path (`oversize` + `fs::read_to_string`) exactly as for any file + that was never open. No code path specific to "was large" needs to reset + anything, because nothing recorded that fact outside the (now gone) + `Document`. +- **The incremental path (`Workspace::update_one`, state.rs:611) — traced and + correct, not just the full-rebuild path the dev's test covers.** It also + calls `current_text`, so a file crossing into the fast path takes the + `None` branch and calls `index.remove_file`/`candidates.remove_file`/ + `includes.remove_file` on the incremental path too, not only on + `rebuild_index()`. No separate finding, but worth recording since the + dev's own test only exercises the whole-rebuild path. +- **Persistent `IndexCache` — traced, no stale-serve possible.** + `IndexCache::facts_for(path, text)` (`index_cache.rs:135`) is only ever + called from `update_one`/the whole-rebuild path with **the file's current + text**, and only when that file is still in `sources()`. A fast-path buffer + is never in `sources()`, so `facts_for` is simply never called for its path + while it is open — not "served stale facts and happens to be right", but + never asked at all. A cache entry from *before* the file grew past the + threshold is inert dead weight (harmless) rather than a stale-serve risk. +- **`willRenameFiles` renaming the large file itself — untested by the dev, + traced, then pinned.** Added + `renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it` + (`file_ops.rs`): the renamed file's own `` `include``s are out of scope + (consistent with the index-exclusion rule, since `will_rename` sweeps + `ws.sources()`), but an *unrelated* small file's `` `include`` of the large + file is still correctly resolved and rewritten, because + `IncludeGraph::resolve` walks the real filesystem (`Path::is_file`) rather + than the source list the fast-path buffer was excluded from. Verified + correct; was simply unverified before this pass. +- **`workspace/diagnostic` including the large buffer's entry — untested by + the dev, traced, then pinned.** Added + `a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report` + (`server.rs`): `Workspace::workspace_report` iterates every open URI + unconditionally and calls `diagnostics::all`, which already special-cases + `doc.large`, so the buffer is **present** with an empty **full** report + (not absent, not "unchanged"). Correct; was simply unverified. + +**5. Definition/references heuristics.** `DECLARATORS` covers `genvar` and +`localparam` (both present); `assign` LHS, ANSI-port-after-type, `typedef` +names and instance names are confirmed *not* found, matching the README's own +"what it gets wrong" list exactly — README is honest here. The 1000-cap is +silent (no truncation flag; the protocol has none to use). Word-boundary +correctness (`sig_a` not matched inside `sig_ab`) and identifier extraction +are exercised by the existing tests; no gaps found beyond finding 1 above +(which is about *locating* the hits, not finding them). + +**6. Dispatch-table completeness.** Enumerated every `::METHOD =>` arm in +`server.rs`'s `request()` (37 document/workspace-scoped request methods) and +cross-checked against `large_file_answer` and the +`every_other_request_a_large_buffer_gets_answers_nothing_at_all` table. +`CallHierarchyIncomingCalls`/`OutgoingCalls` and +`TypeHierarchySupertypes`/`Subtypes` take an opaque item (its own `uri` field, +not a nested `textDocument`), so `document_uri`'s +`params["textDocument"]["uri"]` lookup never matches them regardless of +`doc.large` — consistent with the README filing them under "everything +workspace-scoped ... works off the index." Two real gaps found and closed +(see §4's last two bullets: `willRenameFiles` on the file itself, and +`workspace/diagnostic`). No other gaps found in the sweep. + +**7. Performance honesty (beyond finding 1).** All five `--ignored` numbers +in the README reproduced within the stated order of magnitude across three +release runs (see gates above), not cherry-picked. The debug e2e bound +(`a_five_megabyte_buffer_opens_on_the_fast_path_over_the_wire`, `< 10 s` +against a measured ~0.4 s) is not flaky across 3 runs. + +**8. CLAUDE.md compliance.** No `unwrap`/`expect`/`panic!` introduced in +library code paths in the reviewed diff (the new `.expect(...)` calls are all +in `#[cfg(test)]`). Doc comments present on new public items, with one +exception found and fixed (below). `docs/features/large-file-mode/README.md` +has each required section exactly once. The `indexing-ux` amendment +(`docs/features/indexing-ux/README.md`) accurately describes the exception in +one paragraph, cross-referenced correctly. The corpus agreement test is +skip-guarded (`if !corpus.is_dir() { ...; return; }`). `verify.rs` untouched +by this diff (`git diff --stat` confirms no such file listed) — nothing in +this feature can produce an edit, so this was expected, not just checked. + +**Small fixes made directly, noted here:** + +- **`crates/lucisv_server/src/main.rs`** — the new `token_server_cancel_support` + function was inserted *between* the existing doc comment for + `pull_diagnostics_support` and the function it documented, leaving a stray, + wrong doc comment ("Whether the client pulls diagnostics...") sitting above + the wrong function and `pull_diagnostics_support` itself undocumented. + Reordered so each doc comment sits over its own function again; no + behavioural change. +- **`crates/lucisv_server/src/server.rs`** — `fast_path_session`, introduced + this round and shared by roughly a dozen tests, called + `Tree::new("largefile")` with the **same literal name** every time, unlike + every other tree in this file (each named for the one test that uses it). + Under `cargo test`'s default thread-per-test parallelism this is a real + race: one test's `Tree::new` (`remove_dir_all` then `create_dir_all`) can + wipe the directory a concurrent test just wrote its source file into, + observed as a genuine, reproducible failure + (`formatting_a_large_buffer_refuses_out_loud_and_edits_nothing` → + `write: Os { code: 2, ... NotFound }`) when running `server::tests` in + isolation with 8+ threads, even though the full-workspace run the dev + quoted happened not to hit it. Fixed with a per-call atomic counter so the + shared literal is safe to share; re-ran `server::tests` at + `--test-threads=16` eight times after the fix with no failures (zero + failures in nine total isolated runs before vs. after is not itself proof, + but the fix removes the actual race — two tests can no longer resolve to + the same directory). + +**Tests added (6; 2 of the 6 are `#[ignore]`d measurement probes for finding +1, matching this codebase's own convention for the 100 MB/10 MB probes — the +other 4 run in the normal suite and are part of the 2347/13 count above):** + +- `large.rs`: `a_buffer_of_only_newlines_does_not_panic_and_answers_no_tokens`, + `a_crlf_netlist_windows_the_same_as_its_lf_twin`, + `qa_a_single_multi_line_bus_still_shows_quadratic_cost_in_the_window_colourer` + (`#[ignore]`d), `qa_references_on_one_giant_line_is_fast_but_locating_the_hits_is_not` + (`#[ignore]`d). +- `server.rs`: `a_large_buffer_is_present_in_workspace_diagnostics_with_an_empty_full_report`. +- `file_ops.rs`: `renaming_a_large_open_buffer_still_rewrites_other_files_includes_to_it`. + +**C. Beyond the assigned list.** The only new shape tried beyond §2's +newlines/CRLF tests: a `semanticTokens/range` request racing a `didChange` — +not applicable as a race at all. `Server::run`'s main loop +(`server.rs`, the `match` in `run`/`request`/`notification`) processes exactly +one `Message` per iteration to completion before reading the next; the +transport is a single in-process channel drained synchronously. A range +request and a `didChange` notification can therefore never interleave — +whichever is read first is fully handled (including, for a request, its +response sent) before the next message is even parsed. Verified by reading +the loop structure, not by a new test, since there is no concurrency for a +test to exercise. + +**Verdict: not committable as-is.** Everything the dev built is correct where +tested, three real gaps were closed (one race-condition test fix, one stray +doc-comment fix, two missing-coverage tests that turned out to confirm +correct behaviour) and are safe to take as-is. **Finding 1 is the blocker**: +the feature's core promise — bounded cost regardless of file size — does not +hold for a realistic single-long-line shape, in both the request this feature +exists to serve (`semanticTokens/range`) and the two it shipped as a stretch +goal (`definition`/`references`). Recommend: either fix `Positions::position` +to convert UTF-16 columns without an O(column) rescan (e.g. carry a running +byte→UTF-16 offset while iterating pieces already sorted by position, since +`tokens::flatten` already sorts before `encode` — a per-line cache would also +work and touches less), or explicitly document the long-line case as a known +gap the way "no nesting cap" already is, with the owner's sign-off that a +minute-long freeze on a wide bus declaration is acceptable. Either is a +one-round follow-up, not a redesign; nothing else in this feature needs to +wait on it. + +**Handshake request (for whoever owns `convert.rs`)** — *satisfied 2026-08-27 +by `Positions::walker`; a forward cursor rather than the per-line cache +suggested here, which needs no invalidation and is the same cost.* +`Positions::position` +converts a byte offset to a UTF-16 column in O(offset within its line). Every +caller that converts a *single* position pays this once, unnoticeably; a +caller that converts many positions **on the same line** (this round's window +colourer and reference/definition locator, both new) pays it once per +position, which is O(n²) in the number of positions on that line. A per-line +cache (byte offset → UTF-16 units so far, valid for one line, invalidated +across a line boundary) would make every existing caller no slower and this +round's two callers linear. + +### 2026-08-27 — QA agent, fix-round re-verification (finding 1) + +Scope: re-verify the dev's fix for finding 1 above, not redesign it. Read the +fix-round work log and `convert.rs`/`tokens.rs`/`server.rs` before touching +anything. + +**Gates, re-run clean:** `cargo fmt --all -- --check`; `cargo clippy +--all-targets` (0 warnings); `cargo test --workspace` — **2354 passed, 0 +failed, 11 ignored**, matching the dev's own count exactly (verified by +summing every crate's `test result:` line, not just trusting the log); `cargo +test -p vlog_formatter` (**180 passed**, matches); `node smoke.js +../../target/release/lucisv-server` (OK, release binary rebuilt fresh for +this). All four ran again after the tests I added below, still clean: 1152 +passed in `lucisv_server` (up from the dev's 1149 by my 3 new tests), 11 +ignored, 2357 total workspace. + +**1. Repro geometries, by hand, release build.** +`a_window_of_many_tokens_on_one_line_colours_in_linear_time` at its own +40,000-token/268,921-byte line: **12.85 ms** colouring (dev claimed 14.4 ms — +same order, same machine-noise band). The reference-locate gate runs at 1/8 +line length by design, so I temporarily widened its filler +(`.repeat(250)` → `.repeat(2000)`, reverted immediately after) to reproduce +the dev's original 800-hit/20.8 MB geometry directly: **16.8 ms** to locate +(dev claimed 16.6 ms) — both numbers reproduce within noise, three-plus +orders of magnitude under the pre-fix 7.86 s / 12.6 s. Not cherry-picked: the +in-between sizes in both gates' own output also show clean linear doubling. + +**2. Flipped debug gates, 3× each, for bound stability.** `linear_time` +filter, three separate `cargo test` invocations: colour-40k **75.6 / 76.0 / +78.8 ms** against the 350 ms bound (~4.5–4.6× margin, consistent with the +dev's 77 ms); locate-800 **31.9 / 32.1 / 32.2 ms** against the 150 ms bound +(~4.6–4.7× margin, consistent with the dev's 32 ms). No flakiness, no +near-miss. + +**3. The walker's restart semantics — verified O(line-restart), not +O(document).** Read `PositionWalker::position` (`convert.rs:153`): a restart +(`line != self.line || offset < self.cursor`) resets `cursor`/`units` to that +line's own start and re-measures only `line_start..offset` — bounded by the +*target line's* length, never by anything before it or by the document as a +whole. Constructed the pathological shape the task asked for: two 20 KB +lines far apart in one document, offsets ping-ponged between them +(`a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly`, +added to `convert.rs`, permanent, passes) — every call still matches +`Positions::position` exactly, i.e. correctness survives the worst +restart pattern there is. Separately hand-measured (not committed — a +throwaway `#[test]`, run and removed) that per-call cost under ping-pong +scales with *that line's* length, not the iteration count or the document: +~44 µs/call at a 50 KB line, ~370 µs at 500 KB (~8.4× for 10×), ~1.49 ms at +2 MB (~4× for 4×) — linear in line length as expected, and critically it +does not grow across the 2000-iteration run, so ping-pong degrades to +"per-call cost, every call" and never to anything worse than calling +`Positions::position` directly for each offset. Verdict: the restart claim +holds exactly as described. + +**4. The load-bearing claim — window-edge tail comments really do arrive +out of order, and positions after the reset are still right.** No existing +test exercised this exact path (`large::window`'s tail-comment case through +`tokens::semantic_tokens_in_window`/`flatten`, as opposed to `window()` +alone, which the dev's own tests already covered). Added +`a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly` +(`tokens.rs`): a long declaration line followed by a banner comment that +never closes. Confirmed the premise first — the comment's byte span starts +at or after every token's end, yet `semantic_tokens_in_window` pushes +`window.comments` into `pieces` *before* the token loop — so the walker's +very first call in this request is on the *highest*-offset piece, then +immediately falls back to the lowest. Then confirmed every token's and the +comment's own decoded wire position matches `Positions::position` for the +same byte offset, i.e. the one forced restart does not leave the cursor in a +state that miscolours anything that follows. This is a real, reachable +request shape (a banner comment crossing the bottom of a scrolled viewport, +exactly what "The far edge" in the README above describes), not a +constructed-only corner case — the reset path is exercised by ordinary +scrolling, not dead code. + +**5. `collect_trivia` → `collect` — invisibility confirmed, one gap in +coverage closed.** Traced `Token::leading: Vec` (pushed by the +lexer in ascending source order) and `trailing: Option` (at most +one): a single token's own three possible pieces (leading comments, itself, +trailing comment) are structurally non-overlapping spans, so "no two pieces +from one token start at the same byte" holds by construction, not by luck. +`flatten`'s final `flat.sort_by_key(|t| (t.line, t.start))` means the +*collection* order can only affect the walker's amortized-cost path, never +the output — confirmed by reading, not just asserted. No existing test had a +single token carrying **both** a leading and a trailing comment at once +(the exact shape the refactor's doc comment calls out); added +`a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces` +(`tokens.rs`) — hand-computed byte→UTF-16 positions for all three pieces +(a leading block comment, the `wire` keyword, a same-line block comment, and +the declared identifier after it) all match exactly, first pass after fixing +one wrong expectation in my own draft (the identifier really is a +declaration under full semantics, which I'd first guessed as a plain use). + +**6. Ordinary-path regression safety.** The corpus agreement anchor +(`the_window_lexer_answers_what_the_full_pipeline_answers`) re-ran against +the real corpus in **3.59 s**, not skipped — matches the dev's "ran, not +skipped" claim. Spot-reproduced the 129 KB single-line ordinary-buffer claim +directly (a throwaway probe, run and removed): a 128,921-byte one-line +buffer's `semantic_tokens` (the `full` answer) took **231.8 ms**, against +the dev's claimed 232 ms — reproduces essentially exactly. + +**7. Equivalence tests' honesty — checked, not assumed.** The "gnarly +buffer" fixture (`"// é ✓ 🎉\r\nmodule mü;\n\r\n wire ✓a;\r\nendmodule"`) +genuinely contains a 2-byte character (`é`), a 3-byte character (`✓`) and a +genuine 4-byte astral character (`🎉`, 2 UTF-16 units) — checked byte-by-byte +in Python, not eyeballed — plus two `\r\n` occurrences and a bare `\r\n` +empty line, and the every-byte sweep (`0..=len+2`) walks across both bytes +of each by construction. The 500-offset "jumbled" sequence in +`a_walker_handed_offsets_out_of_order_still_answers_the_per_call_position` +is genuinely non-monotonic — replayed the LCG by hand: 238 of 499 consecutive +pairs go backwards, and the full sequence is nowhere near sorted — not an +accidentally-ascending draw. All 5 new walker-equivalence tests (plus my 3rd +new one, the ping-pong test) re-run individually: pass. + +**8. CLAUDE.md compliance on the fix diff.** No `unwrap`/`expect`/`panic!` +outside `#[cfg(test)]` in `convert.rs`, `tokens.rs` or `server.rs` (swept +with an awk filter that stops counting at the test-module boundary, not a +blind grep). `Positions::walker`, `PositionWalker` and its `position`/`range` +methods all carry doc comments already. `verify.rs` untouched +(`git diff --stat` lists no such path). The seven required README sections +each appear exactly once. My additions above are noted here in the QA log, +not written into the dev's Work log or the FIXED annotation, which are left +exactly as the dev wrote them. + +**Tests added (3, all permanent, all passing, none timing-asserted):** +`convert.rs`: +`a_walker_ping_ponged_between_two_far_apart_lines_still_answers_correctly`. +`tokens.rs`: +`a_window_edge_tail_comment_arrives_out_of_order_and_still_positions_correctly`, +`a_token_with_both_a_leading_and_a_trailing_comment_positions_all_three_pieces`. +(Two additional throwaway timing probes — the ping-pong per-call-cost check +and the ordinary-buffer 232 ms spot-check — were written, run, and removed; +they are not in the diff.) + +**Verdict: committable.** The fix does what the work log claims: an addition +to `convert.rs` (`position()` byte-unchanged, confirmed by reading, not +diffing — the pre-fix file was never committed to compare against, so this +QA round reasoned from the code's current behavior on the ~40 existing +callers' own passing tests rather than a `git diff`), adopted at exactly the +three sites named, closing finding 1 in both directions (window colouring +and definition/references location) with measurements that reproduce by +hand within noise. The restart path is real, load-bearing, exercised by an +ordinary request shape, and correct under the worst pattern I could +construct for it. No new corruption risk: nothing in this diff touches +`verify.rs` or produces an edit. Recommend closing finding 1. + +## Review + +### 2026-08-27 — lead + +Reviewed both rounds' diffs, work logs and QA logs; re-ran all gates +myself (2357 workspace tests, 0 failed), clean. This round did the two +things the owner asked hardest for: the open is now one newline scan +(40.7 ms for a 104 MB netlist) and the research question was settled +against the shipped VS Code binary rather than guessed — QA re-derived +the tokens-complete behavior from the bundle independently, which is +what lets the error-on-full answer stand as fact rather than folklore. +Definition and references shipped on measurement, well inside the +owner's budget, and the dispatch table's fall-through-as-empty-file +design means new handlers inherit a sane large-buffer answer by +default instead of by remembering. + +The rejection cycle earned its keep twice over. QA's long-line finding +was exactly the shape netlists take, and the fix's walker — with its +restart semantics proven load-bearing by a real request shape, not +defensive decoration — turned out to fix ordinary files' semantic +tokens too (2.06 s to 232 ms on a one-line buffer), a pre-existing +cost nobody had ever measured. The dev's index-sources removal (the +half my brief missed: a large buffer must remove its path, not merely +fail to override it) and QA's coverage of it against the persistent +cache close the coherence story across all three index rounds. The +residual symbol_at cost on pathological ordinary files is noted, not +filed — it is the normal path's ordinary per-token work. Accepted as +shipped, and with it the owner's large-workarea wave is complete. diff --git a/docs/features/lucisv-server/README.md b/docs/features/lucisv-server/README.md index d45e977..6ccb1e9 100644 --- a/docs/features/lucisv-server/README.md +++ b/docs/features/lucisv-server/README.md @@ -25,8 +25,8 @@ 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. 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` | `vlog_parser::tokenize` + `Semantics` | Delta-encoded, split at line boundaries. Stamped with a `resultId` since 2026-08-26, so a delta can name it. **Declined with an error on a buffer over `lucisv.largeFile.threshold`** (2026-08-27): VS Code marks a model whose document provider answered *anything* as complete and then never asks its range provider again, so an empty answer would cost a 100 MB file all of its colour — see `docs/features/large-file-mode/README.md` | +| `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`. On a buffer over `lucisv.largeFile.threshold` this is the **only** request that colours anything, and it lexes the window itself (0.25 ms for a viewport of a 100 MB file) rather than filtering a token stream that was never built | | `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` | @@ -295,6 +295,23 @@ current content before it is used, and a stale, corrupt or foreign record costs one parse and can change no answer. Rules, the record format and the crash-safety argument: `docs/features/index-persistence/README.md`. +**A buffer over `lucisv.largeFile.threshold` (4 MiB by default) is never +analyzed at all, since 2026-08-27** (large-file-mode). `Workspace::set_document` +— the one place a `Document` is built — puts it on a fast path that indexes its +*lines* and stops: no lex, no parse, no semantics, no diagnostics, no index +entry. 41 ms for 100 MB, against the 930 ms 10 MB costs through the full +pipeline. Its `Document` holds the analysis of the **empty file**, so every +handler that reads the analysis answers empty without knowing the mode exists; +only the handlers that would read the **text** are gated, in one table in +`Server::large_file_answer`. What still works is colour — `semanticTokens/range` +lexes the requested window and nothing else — plus same-file `definition` and +`references` by one linear scan. `semanticTokens/full` is answered with an +*error*, which is the one shape that leaves VS Code's viewport provider +painting. A file on the fast path leaves the workspace index entirely, which is +the one exception to "an open buffer is never capped". The rules, the +approximations, the dispatch table and the measurements: +`docs/features/large-file-mode/README.md`. + **Walked files over `lucisv.index.maxFileSize` (1 MiB by default) are not read at all** — the size is taken from `fs::metadata` before the read, so a generated netlist costs one `stat` rather than minutes of parsing. The cap is @@ -706,6 +723,11 @@ list to `vlog_parser::KEYWORDS`. Rationale and inventory: 3.18 items **parked** with their evidence and re-check triggers: snippet `WorkspaceEdit` edits and `workspace/textDocumentContent`, neither of which the pinned `vscode-languageclient@9.0.1` can consume. +- [x] The **large-file fast path** — delivered by **large-file-mode** + (2026-08-27): a buffer over `lucisv.largeFile.threshold` is line-indexed + and nothing else, coloured a viewport at a time by + `semanticTokens/range`, and answers everything else empty. + `docs/features/large-file-mode/README.md`. - [ ] **Not done:** editor packaging (the VS Code extension and the `lspconfig` snippet are their own TODO.md §6 item). diff --git a/editors/vscode/package.json b/editors/vscode/package.json index 32a62d4..4cc61f9 100644 --- a/editors/vscode/package.json +++ b/editors/vscode/package.json @@ -271,6 +271,12 @@ "type": "string", "default": "", "markdownDescription": "Where to keep the index cache `#lucisv.index.persist#` writes — absolute, or relative to the first workspace folder. Empty (the default) means the extension's own per-workspace storage folder, which VS Code cleans up when the workspace is forgotten. Set this to share one cache between checkouts of the same tree, or to keep it somewhere faster. The directory is created on demand and marks itself ignored with a `.gitignore`. Takes effect on the next workspace scan." + }, + "lucisv.largeFile.threshold": { + "type": "number", + "default": 4194304, + "minimum": 0, + "markdownDescription": "Size in bytes above which an **opened file** is put on the fast path: it is line-counted and nothing else — never parsed, never analyzed, never indexed — so a 100 MB netlist opens instantly instead of hanging the editor. What you still get is **syntax colouring of what is on screen**, painted a screenful at a time, plus go-to-definition and find-references within that file by text search. Everything else — diagnostics, formatting, symbols, folding, rename, hover, completion — answers nothing at all for such a file, and formatting says so rather than doing nothing quietly. A file on the fast path is left out of the workspace index entirely, so its symbols do not exist for the rest of the project. Set to `0` to analyze every file you open however big it is. Takes effect the next time the file is opened or edited. Not to be confused with `#lucisv.index.maxFileSize#`, which is about files nobody opened." } } }