Files
lucisv/crates/lucisv_server/src/convert.rs
T
lucioandClaude Fable 5 651e58bfb3 The design-hierarchy sidebar: codex's feature, integrated
An instance-oriented hierarchy view in the Activity Bar —
lucisv/moduleHierarchy snapshots (schema 2: uri table, flat ranges,
derived ids; 11.6 MB -> 2.3 MB on opentitan) plus
lucisv/moduleHierarchyChanged invalidation, gated on the extension's
initializationOptions. Format 5 carries decl spans, instance
occurrences and client positions for file-scope declarations
(+1.7-1.9 % store), so a snapshot reads no files at all: handler
145-167 -> 17-20 ms settled, a save with the sidebar open 366 ->
141 ms. complete is !scanning && !must_wait, pinned. Owner UI rounds:
no hover preview, all levels collapsed by default with stable ids
across refreshes, and search over a resident flat model (freeze
diagnosed: materialized expanded tree x undebounced double
fuzzyScore x whole-tree clone per keystroke) — prebuilt lowercased
index, bitmask prefilter, top-K counting, 200-row cap with an honest
remainder, single-digit ms over a 120k-entry fixture.
LineIndex::utf16_position unifies the index's and the wire's position
math under a cross-crate agreement test.

Implementation: codex. Integration fixes + owner items: Opus dev.
QA: lead (measurement pass) + Sonnet (SHIP, independent oracles).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-29 03:39:06 -07:00

521 lines
21 KiB
Rust

//! Byte offsets ↔ LSP positions.
//!
//! Everything below the protocol speaks UTF-8 byte offsets; LSP `Position`
//! speaks UTF-16 code units within a line. The two agree only on ASCII, which
//! is why getting this wrong survives to production. The exact rules — mid-
//! character clamping, surrogate halves, CRLF — are in
//! `docs/features/lucisv-server/README.md`.
use lsp_types::{Position, Range};
use vlog_parser::{LineIndex, TextRange};
/// One document's text and line table, paired so positions can be converted
/// in both directions. Borrows; there is no cached copy to invalidate.
pub struct Positions<'a> {
text: &'a str,
index: &'a LineIndex,
}
impl<'a> Positions<'a> {
/// Pair a document's text with the line index built from it.
pub fn new(text: &'a str, index: &'a LineIndex) -> Self {
Positions { text, index }
}
/// The LSP position of a byte offset. An offset inside a multi-byte
/// character is floored to that character's start.
///
/// The conversion itself lives on [`LineIndex`], so that the semantic
/// index — which records the same positions for a declaration while its
/// file is scanned — cannot answer differently from the wire.
pub fn position(&self, offset: u32) -> Position {
let (line, character) = self.index.utf16_position(self.text, offset);
Position { line, character }
}
/// 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 {
return self.text.len() as u32;
};
let end = self.line_content_end(line);
let mut units = 0u32;
let mut offset = line.start;
for ch in self.text.get(line.start as usize..end as usize).unwrap_or("").chars() {
if units >= pos.character {
break;
}
units += ch.len_utf16() as u32;
offset += ch.len_utf8() as u32;
}
offset
}
/// The LSP range of a byte range.
pub fn range(&self, span: TextRange) -> Range {
Range { start: self.position(span.start), end: self.position(span.end) }
}
/// The whole document, as a range — what a full-document edit replaces.
pub fn whole_document(&self) -> Range {
self.range(TextRange::new(0, self.text.len() as u32))
}
/// Widen a byte range to the whole lines it touches, for a hover snippet.
pub fn whole_lines(&self, span: TextRange) -> &'a str {
let (first, _) = self.index.line_col(span.start);
let (last, _) = self.index.line_col(span.end);
let start = self.index.line_range(first).map_or(0, |r| r.start);
let end = self.index.line_range(last).map_or(self.text.len() as u32, |r| r.end);
self.text.get(start as usize..end as usize).unwrap_or("")
}
/// A range an editor can actually draw, for a diagnostic whose span is
/// empty — a zero-width range underlines nothing.
///
/// An empty span becomes the whole line it sits on. A lex error reports
/// at the point the lexer gave up, which for an unterminated comment or
/// string is end-of-file — usually the empty line a trailing newline
/// opens — so an empty line falls back to the one before it, where the
/// text the user has to fix actually is.
pub fn diagnostic_range(&self, span: TextRange) -> Range {
if !span.is_empty() {
return self.range(span);
}
let (line, _) = self.index.line_col(span.start);
let mut target = self.index.line_range(line).unwrap_or(span);
if target.is_empty() && line > 1 {
target = self.index.line_range(line - 1).unwrap_or(target);
}
self.range(target)
}
/// The end of a line's content: its `\r`, if it has one, is not content.
fn line_content_end(&self, line: TextRange) -> u32 {
match self.text.get(line.start as usize..line.end as usize) {
Some(s) if s.ends_with('\r') => line.end - 1,
_ => line.end,
}
}
/// The largest character boundary at or below `offset`, clamped into the
/// text. Slicing anywhere else panics, and an offset can land mid-
/// character whenever a client's position rounding meets a surrogate pair.
fn floor_boundary(&self, offset: u32) -> u32 {
let mut offset = offset.min(self.text.len() as u32) as usize;
while offset > 0 && !self.text.is_char_boundary(offset) {
offset -= 1;
}
offset as u32
}
}
/// 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()
}
#[cfg(test)]
mod tests {
use super::*;
fn positions(text: &str) -> (LineIndex, String) {
(LineIndex::new(text), text.to_string())
}
/// Build a `Positions` and run `f` on it — the index has to outlive it.
fn with<T>(text: &str, f: impl FnOnce(&Positions<'_>) -> T) -> T {
let (index, owned) = positions(text);
f(&Positions::new(&owned, &index))
}
fn pos(line: u32, character: u32) -> Position {
Position { line, character }
}
#[test]
fn ascii_offsets_are_columns() {
with("module m;\nendmodule\n", |p| {
assert_eq!(p.position(0), pos(0, 0));
assert_eq!(p.position(7), pos(0, 7));
assert_eq!(p.position(10), pos(1, 0));
assert_eq!(p.offset(pos(0, 7)), 7);
assert_eq!(p.offset(pos(1, 0)), 10);
});
}
#[test]
fn a_two_byte_character_is_one_utf16_unit() {
// "// é x" — `é` is 2 UTF-8 bytes, 1 UTF-16 unit.
with("// é x\nwire a;\n", |p| {
assert_eq!(p.position(3), pos(0, 3)); // at the `é`
assert_eq!(p.position(5), pos(0, 4)); // after it: 4 units, 5 bytes
assert_eq!(p.offset(pos(0, 4)), 5);
assert_eq!(p.offset(pos(0, 6)), 7); // end of line content
});
}
#[test]
fn a_three_byte_character_is_still_one_utf16_unit() {
with("// ✓ ok\n", |p| {
assert_eq!(p.position(6), pos(0, 4)); // `✓` is 3 bytes, 1 unit
assert_eq!(p.offset(pos(0, 4)), 6);
});
}
#[test]
fn an_astral_character_is_two_utf16_units() {
// `🎉` is one `char`, 4 UTF-8 bytes, 2 UTF-16 units — the surrogate
// pair every naive implementation gets wrong.
with("// 🎉 done\n", |p| {
assert_eq!(p.position(3), pos(0, 3));
assert_eq!(p.position(7), pos(0, 5)); // 3 + 2 units, 3 + 4 bytes
assert_eq!(p.offset(pos(0, 5)), 7);
});
}
#[test]
fn a_position_inside_a_surrogate_pair_rounds_forward() {
// Character 4 is the low half of `🎉`'s pair: there is no byte there,
// so the whole character is consumed rather than sliced.
with("// 🎉 done\n", |p| {
assert_eq!(p.offset(pos(0, 4)), 7);
assert!("// 🎉 done\n".is_char_boundary(7));
});
}
#[test]
fn an_offset_inside_a_character_floors_to_its_start() {
with("// 🎉\n", |p| {
// Bytes 4, 5, 6 are continuation bytes of `🎉`, which starts at 3.
for offset in 3..=6 {
assert_eq!(p.position(offset), pos(0, 3), "offset {offset}");
}
});
}
#[test]
fn crlf_terminators_are_not_line_content() {
// "module m;" is bytes 0..9; `\r` is 9, `\n` is 10, line 2 starts at 11.
let text = "module m;\r\nendmodule\r\n";
with(text, |p| {
assert_eq!(p.position(8), pos(0, 8), "the `;`");
assert_eq!(p.position(9), pos(0, 9), "the `\\r` is at end-of-content");
assert_eq!(p.position(10), pos(0, 9), "and so is the `\\n`");
assert_eq!(p.position(11), pos(1, 0));
// A character past the content clamps before the `\r`.
assert_eq!(p.offset(pos(0, 99)), 9);
assert_eq!(p.offset(pos(1, 0)), 11);
});
}
#[test]
fn a_crlf_terminator_is_the_one_place_the_round_trip_collapses() {
// Both bytes of a `\r\n` are "the end of the line's content", and LSP
// has one position for that, so byte → position → byte is not the
// identity on the `\n`. Stated as a test so it stays a known,
// deliberate collapse rather than a surprise.
with("ab\r\ncd\n", |p| {
assert_eq!(p.position(2), p.position(3));
assert_eq!(p.offset(p.position(3)), 2, "rounds back to the `\\r`");
});
}
#[test]
fn out_of_range_positions_clamp() {
let text = "wire a;\n";
with(text, |p| {
assert_eq!(p.offset(pos(99, 0)), text.len() as u32);
assert_eq!(p.offset(pos(0, 99)), 7);
assert_eq!(p.position(9_999), p.position(text.len() as u32));
});
}
#[test]
fn every_character_boundary_round_trips() {
// Mixed widths, CRLF, an astral character and a trailing partial line.
let text = "// é ✓ 🎉\r\nmodule mü;\n wire ✓a;\r\nendmodule";
with(text, |p| {
for (offset, _) in text.char_indices() {
// The `\n` of a `\r\n` is the documented exception: it shares
// its position with the `\r` before it.
if text.as_bytes().get(offset.wrapping_sub(1)) == Some(&b'\r') {
continue;
}
let offset = offset as u32;
assert_eq!(p.offset(p.position(offset)), offset, "at byte {offset}");
}
let end = text.len() as u32;
assert_eq!(p.offset(p.position(end)), end);
});
}
#[test]
fn an_empty_span_becomes_a_visible_range() {
with("wire a;\nendmodule\n", |p| {
let r = p.diagnostic_range(TextRange::empty(2));
assert_eq!(r.start, pos(0, 0), "the whole line it sits on");
assert_eq!(r.end, pos(0, 7));
// A non-empty span is passed through unchanged.
assert_eq!(p.diagnostic_range(TextRange::new(0, 4)), p.range(TextRange::new(0, 4)));
});
}
#[test]
fn an_empty_span_at_end_of_file_falls_back_to_the_line_before() {
// A trailing newline opens an empty last line, which is where a lex
// error lands; underlining nothing there helps nobody.
let text = "module m;\n wire a; /* oops\n";
with(text, |p| {
let r = p.diagnostic_range(TextRange::empty(text.len() as u32));
assert_eq!(r.start.line, 1);
assert!(r.start.character < r.end.character, "must be drawable");
});
}
#[test]
fn whole_lines_widens_a_span_to_its_lines() {
with("module m;\n wire a;\nendmodule\n", |p| {
assert_eq!(p.whole_lines(TextRange::new(14, 15)), " wire a;");
assert_eq!(p.whole_lines(TextRange::new(7, 14)), "module m;\n wire a;");
});
}
// ------------------------------------------------------------------
// 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| {
assert_eq!(p.position(0), pos(0, 0));
assert_eq!(p.offset(pos(0, 0)), 0);
assert_eq!(p.whole_document(), Range { start: pos(0, 0), end: pos(0, 0) });
});
}
}