Large-file fast path: 100 MB netlists open in 40 ms
Owner-requested round, the last of the large-workarea wave. Above lucisv.largeFile.threshold (4 MiB default, 0 disables) a buffer opens as a line index and nothing else — no lex, no parse, no semantics, and its path removed from the index sources so nothing describes it by stale disk bytes. Viewport highlighting lexes only the requested window (snap to a line boundary, budget-bounded backward comment scan, imperfection documented); semanticTokens/full answers the spec's cancellation errors because the shipped VS Code binary marks tokens complete on ANY non-error answer and never asks for ranges again — settled by reading the bundle, verified independently by QA, pinned with the client-library citations. Same-file definition/references shipped on measurement (worst 37 ms vs the 150 ms budget); every other handler answers as the empty file by construction; formatting alone says why aloud. Two client facts recorded: VS Code never syncs files over 50 MB, and above 20 MB our viewport tokens are the only color. QA rejected the first cut on the round's true shape — thousands of tokens on one long line went quadratic through per-call UTF-16 conversion (7.86 s to color one 269 KB line). The fix adds a monotonic PositionWalker to convert.rs (restart-on-backwards proven load-bearing by the out-of-order tail-comment shape), adopted at three sites for 546x/759x on the probes — and it fixed ordinary files' semantic tokens too (2.06 s to 232 ms on a one-line buffer), a cost the normal path had always paid. Probes are now normally-running gates with 4.5x margins, walker-vs-per-call equivalence swept over gnarly fixtures and adversarial ping-pong. 51 tests added across both rounds (dev 43+5, QA 6+3, minus overlaps), 2 ignored probes. Completes the owner's large-workarea requests. docs/features/large-file-mode/README.md Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
5e98b1a669
commit
bc606dd6bd
15 files changed
+3550
-27
No files matched your search
@@ -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: <path> (<bytes> 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.
|
||||
|
||||
@@ -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<String> {
|
||||
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| {
|
||||
|
||||
@@ -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<Diagnostic> {
|
||||
// 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));
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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<Token>,
|
||||
/// 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<TextRange>,
|
||||
}
|
||||
|
||||
/// 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<Token>, 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<usize> {
|
||||
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<TextRange> {
|
||||
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<TextRange> {
|
||||
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<TextRange> {
|
||||
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<TextRange> {
|
||||
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<Item = TextRange> + '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<String> {
|
||||
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;
|
||||
}
|
||||
@@ -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<dyn Error + Sync + Send>> {
|
||||
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
|
||||
|
||||
@@ -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<Result<Value, Failure>> {
|
||||
// One boolean before anything is parsed: this runs ahead of every
|
||||
// request, and a session with no large buffer in it — which is every
|
||||
// session but one — must not pay a URI parse for the privilege.
|
||||
if !self.workspace.has_large_documents() {
|
||||
return None;
|
||||
}
|
||||
let uri = document_uri(params)?;
|
||||
if !self.workspace.document(&uri).is_some_and(|doc| doc.large) {
|
||||
return None;
|
||||
}
|
||||
let answer = match method {
|
||||
SemanticTokensFullRequest::METHOD | SemanticTokensFullDeltaRequest::METHOD => {
|
||||
Err(self.tokens_declined())
|
||||
}
|
||||
Formatting::METHOD | RangeFormatting::METHOD | format::RANGES_FORMATTING => {
|
||||
self.edits(Err(TOO_LARGE.to_string()))
|
||||
}
|
||||
// Silent, both of them: one fires on every keystroke and one on
|
||||
// every save.
|
||||
OnTypeFormatting::METHOD => to_value(Vec::<lsp_types::TextEdit>::new()),
|
||||
WillSaveWaitUntil::METHOD => Ok(Value::Null),
|
||||
// A rename would rewrite every *other* file and leave this one
|
||||
// untouched — the buffer is not in the index and not in
|
||||
// `sources()` — so it is refused rather than half-applied.
|
||||
// `prepareRename` declines quietly, so the box never opens.
|
||||
PrepareRenameRequest::METHOD => Ok(Value::Null),
|
||||
Rename::METHOD => Err(Failure::Request(TOO_LARGE.to_string())),
|
||||
// These three read the buffer's text rather than its analysis: the
|
||||
// include scan, the `` `include`` line lookup a hover does, and
|
||||
// the fix application a code action tries.
|
||||
HoverRequest::METHOD => Ok(Value::Null),
|
||||
DocumentLinkRequest::METHOD => to_value(Vec::<lsp_types::DocumentLink>::new()),
|
||||
CodeActionRequest::METHOD => to_value(Vec::<lsp_types::CodeActionOrCommand>::new()),
|
||||
GotoDefinition::METHOD => self.large_definition(&uri, params),
|
||||
References::METHOD => self.large_references(&uri, params),
|
||||
_ => return None,
|
||||
};
|
||||
Some(answer)
|
||||
}
|
||||
|
||||
/// The error `semanticTokens/full` is declined with.
|
||||
///
|
||||
/// `ServerCancelled` for a client that advertised `serverCancelSupport`,
|
||||
/// which is the code the spec reserves for exactly this and the code
|
||||
/// `vscode-languageclient` turns into a `CancellationError`;
|
||||
/// `ContentModified` for one that did not, which the same client turns
|
||||
/// into the same `CancellationError` (semantic tokens are on its
|
||||
/// `retryOnContentModified` list) and which every 3.16 client already
|
||||
/// understands.
|
||||
fn tokens_declined(&self) -> Failure {
|
||||
let code = match self.abilities.token_server_cancel {
|
||||
true => lsp_server::ErrorCode::ServerCancelled,
|
||||
false => lsp_server::ErrorCode::ContentModified,
|
||||
};
|
||||
Failure::Declined(code, TOO_LARGE.to_string())
|
||||
}
|
||||
|
||||
/// `textDocument/definition` on a large buffer: the first occurrence of
|
||||
/// the name under the cursor that a declaring keyword introduces.
|
||||
fn large_definition(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
||||
let locations = self
|
||||
.large_scan(uri, params, |doc, offset| {
|
||||
large::definition(doc, offset).into_iter().collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
to_value(GotoDefinitionResponse::Array(locations))
|
||||
}
|
||||
|
||||
/// `textDocument/references` on a large buffer: every whole-word
|
||||
/// occurrence of the name under the cursor, capped.
|
||||
fn large_references(&self, uri: &Uri, params: &Value) -> Result<Value, Failure> {
|
||||
let include = params
|
||||
.get("context")
|
||||
.and_then(|context| context.get("includeDeclaration"))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
let locations = self
|
||||
.large_scan(uri, params, |doc, offset| large::references(doc, offset, include))
|
||||
.unwrap_or_default();
|
||||
to_value(locations)
|
||||
}
|
||||
|
||||
/// Run one of the fast path's scans at the position `params` names, and
|
||||
/// turn its spans into locations in the same file.
|
||||
fn large_scan(
|
||||
&self,
|
||||
uri: &Uri,
|
||||
params: &Value,
|
||||
scan: impl Fn(&crate::state::Document, u32) -> Vec<vlog_parser::TextRange>,
|
||||
) -> Option<Vec<Location>> {
|
||||
let position: Position = serde_json::from_value(params.get("position")?.clone()).ok()?;
|
||||
let doc = self.workspace.document(uri)?;
|
||||
let positions = doc.positions();
|
||||
let offset = positions.offset(position);
|
||||
// Both scans answer in ascending order, so one monotonic cursor
|
||||
// measures each line once — a thousand hits on one netlist line would
|
||||
// otherwise re-measure that line a thousand times over.
|
||||
let mut walker = positions.walker();
|
||||
Some(
|
||||
scan(doc, offset)
|
||||
.into_iter()
|
||||
.map(|span| Location { uri: uri.clone(), range: walker.range(span) })
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn formatting(&mut self, params: DocumentFormattingParams) -> Result<Value, Failure> {
|
||||
let uri = params.text_document.uri;
|
||||
let Some(doc) = self.workspace.document(&uri) else { return Ok(Value::Null) };
|
||||
@@ -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<Uri> {
|
||||
params.get("textDocument")?.get("uri")?.as_str()?.parse().ok()
|
||||
}
|
||||
|
||||
fn decode<P: DeserializeOwned>(request: Request) -> Result<P, Failure> {
|
||||
serde_json::from_value(request.params).map_err(|e| Failure::InvalidParams(e.to_string()))
|
||||
}
|
||||
@@ -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<String> = session
|
||||
.logged()
|
||||
.into_iter()
|
||||
.map(|(_, message)| message)
|
||||
.filter(|message| message.contains("large-file fast path"))
|
||||
.collect();
|
||||
assert_eq!(lines.len(), 1, "once per entry into the mode: {lines:?}");
|
||||
assert!(lines[0].contains("net.v"), "{}", lines[0]);
|
||||
assert!(lines[0].contains("bytes"), "{}", lines[0]);
|
||||
|
||||
// A keystroke in it does not say it again.
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,13 @@ const INDENT_RANGE: RangeInclusive<u64> = 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<String>,
|
||||
/// `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),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<PathBuf>, 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<String> {
|
||||
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<bool> = 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,
|
||||
|
||||
@@ -121,18 +121,35 @@ pub fn semantic_tokens_in_range(doc: &Document, range: Range) -> Vec<SemanticTok
|
||||
encode(&within(absolute(doc), range))
|
||||
}
|
||||
|
||||
/// The tokens a range covers of a buffer nothing has lexed — the large-file
|
||||
/// fast path's answer to `semanticTokens/range`.
|
||||
///
|
||||
/// Identical to [`semantic_tokens_in_range`] in everything the client can see:
|
||||
/// the same classification, the same line splitting, the same encoding from
|
||||
/// the start of the document, the same overlap filter. The only difference is
|
||||
/// where the tokens come from — `large::window` lexes the window instead of
|
||||
/// the document's own (empty) token stream — and that a plain identifier can
|
||||
/// only ever be `variable`, because there is no `Semantics` to refine it with.
|
||||
/// See `docs/features/large-file-mode/README.md`.
|
||||
pub fn semantic_tokens_in_window(doc: &Document, range: Range) -> Vec<SemanticToken> {
|
||||
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<Absolute> {
|
||||
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<Absolute>, range: Range) -> Vec<Absolute> {
|
||||
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<Piece>) {
|
||||
/// 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<Piece>) {
|
||||
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<Piece>, doc: &Document) -> Vec<Absolute> {
|
||||
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<Absolute> = 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`
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
@@ -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<String> = 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<String> = 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);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 `[email protected]` 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).
|
||||
|
||||
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user