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]>
217 lines
8.4 KiB
Rust
217 lines
8.4 KiB
Rust
//! Offset ↔ line:column conversion for one source file.
|
|
//!
|
|
//! The lexer records line/col as it goes, which is all a parse diagnostic
|
|
//! needs. A language server needs the opposite direction too — an editor sends
|
|
//! positions and expects byte ranges back — so this builds the table once and
|
|
//! answers both. It is the analog of ruff's `ruff_source_file::LineIndex`.
|
|
|
|
use crate::span::TextRange;
|
|
|
|
/// Byte offsets of the start of every line in one source text.
|
|
///
|
|
/// Lines and columns are **1-based**; a column is a **UTF-8 byte** offset
|
|
/// within its line, the same unit [`TextRange`] uses, so `col - 1` bytes
|
|
/// separate the line start from the position.
|
|
#[derive(Debug, Clone)]
|
|
pub struct LineIndex {
|
|
/// `line_starts[n]` is the offset of line `n + 1`. Never empty.
|
|
line_starts: Vec<u32>,
|
|
len: u32,
|
|
}
|
|
|
|
impl LineIndex {
|
|
/// Build the index for `text`.
|
|
pub fn new(text: &str) -> Self {
|
|
let mut line_starts = vec![0u32];
|
|
for (i, b) in text.bytes().enumerate() {
|
|
if b == b'\n' {
|
|
line_starts.push(i as u32 + 1);
|
|
}
|
|
}
|
|
LineIndex { line_starts, len: text.len() as u32 }
|
|
}
|
|
|
|
/// How many lines the text has. A trailing newline opens a last, empty
|
|
/// line, so `"a\n"` has two.
|
|
pub fn line_count(&self) -> u32 {
|
|
self.line_starts.len() as u32
|
|
}
|
|
|
|
/// The 1-based line and column of a byte offset. An offset past the end
|
|
/// of the text is clamped to the end.
|
|
pub fn line_col(&self, offset: u32) -> (u32, u32) {
|
|
let offset = offset.min(self.len);
|
|
// The last line whose start is <= offset.
|
|
let line = self.line_starts.partition_point(|&s| s <= offset);
|
|
(line as u32, offset - self.line_starts[line - 1] + 1)
|
|
}
|
|
|
|
/// The **0-based** line and **UTF-16** column of a byte offset — the units
|
|
/// a language-server `Position` counts in, as opposed to
|
|
/// [`line_col`](Self::line_col)'s 1-based bytes. `text` must be the text
|
|
/// this index was built from.
|
|
///
|
|
/// An offset inside a multi-byte character is floored to that character's
|
|
/// start, and the `\r` of a CRLF line ending is not part of its line's
|
|
/// content. It lives here, beside the table it reads, because two callers
|
|
/// need the same answer: a server converting a span for the wire, and the
|
|
/// semantic index recording a declaration's position so no one has to.
|
|
pub fn utf16_position(&self, text: &str, offset: u32) -> (u32, u32) {
|
|
let mut floored = (offset as usize).min(text.len());
|
|
while floored > 0 && !text.is_char_boundary(floored) {
|
|
floored -= 1;
|
|
}
|
|
let (line, _) = self.line_col(floored as u32);
|
|
let start = self.line_range(line).map_or(0, |r| r.start) as usize;
|
|
let slice = text.get(start..floored).unwrap_or("");
|
|
// LSP line content excludes the whole `\r\n`; this index keeps the
|
|
// `\r` as an ordinary byte of its line, so drop it here.
|
|
let slice = slice.strip_suffix('\r').unwrap_or(slice);
|
|
(line - 1, utf16_len(slice))
|
|
}
|
|
|
|
/// The byte offset of a 1-based line and column, or `None` if the text
|
|
/// has no such line. A column past the end of its line is clamped to the
|
|
/// line's end, so the result never lands on another line.
|
|
pub fn offset(&self, line: u32, col: u32) -> Option<u32> {
|
|
if line == 0 || line > self.line_count() {
|
|
return None;
|
|
}
|
|
let start = self.line_starts[line as usize - 1];
|
|
let end = self.line_end(line);
|
|
Some((start + col.max(1) - 1).min(end))
|
|
}
|
|
|
|
/// The byte range of a 1-based line, excluding its terminating newline.
|
|
pub fn line_range(&self, line: u32) -> Option<TextRange> {
|
|
if line == 0 || line > self.line_count() {
|
|
return None;
|
|
}
|
|
Some(TextRange::new(self.line_starts[line as usize - 1], self.line_end(line)))
|
|
}
|
|
|
|
/// Offset of the end of a line, excluding its `\n`. Assumes `line` is in
|
|
/// range.
|
|
fn line_end(&self, line: u32) -> u32 {
|
|
match self.line_starts.get(line as usize) {
|
|
// The next line starts one past this line's `\n`.
|
|
Some(&next) => next - 1,
|
|
None => self.len,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// How many UTF-16 code units a string occupies — the unit LSP counts in.
|
|
///
|
|
/// ASCII is answered by the length, which is what source text almost always
|
|
/// is; the decoding loop is for the rest.
|
|
fn utf16_len(s: &str) -> u32 {
|
|
if s.is_ascii() {
|
|
return s.len() as u32;
|
|
}
|
|
s.chars().map(|c| c.len_utf16() as u32).sum()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn empty_file() {
|
|
let idx = LineIndex::new("");
|
|
assert_eq!(idx.line_count(), 1);
|
|
assert_eq!(idx.line_col(0), (1, 1));
|
|
assert_eq!(idx.offset(1, 1), Some(0));
|
|
assert_eq!(idx.offset(2, 1), None);
|
|
assert_eq!(idx.line_range(1), Some(TextRange::new(0, 0)));
|
|
}
|
|
|
|
#[test]
|
|
fn no_trailing_newline() {
|
|
let src = "module m;\nendmodule";
|
|
let idx = LineIndex::new(src);
|
|
assert_eq!(idx.line_count(), 2);
|
|
assert_eq!(idx.line_col(0), (1, 1));
|
|
assert_eq!(idx.line_col(9), (1, 10)); // the `;`
|
|
assert_eq!(idx.line_col(10), (2, 1)); // `e` of endmodule
|
|
assert_eq!(idx.offset(2, 1), Some(10));
|
|
assert_eq!(idx.line_range(2), Some(TextRange::new(10, src.len() as u32)));
|
|
}
|
|
|
|
#[test]
|
|
fn trailing_newline_opens_an_empty_last_line() {
|
|
let idx = LineIndex::new("a\n");
|
|
assert_eq!(idx.line_count(), 2);
|
|
assert_eq!(idx.line_col(2), (2, 1));
|
|
assert_eq!(idx.offset(2, 1), Some(2));
|
|
assert_eq!(idx.line_range(2), Some(TextRange::new(2, 2)));
|
|
}
|
|
|
|
#[test]
|
|
fn crlf_puts_the_carriage_return_in_the_line() {
|
|
// `\r` is an ordinary byte of the line it ends; only `\n` breaks.
|
|
let src = "ab\r\ncd\r\n";
|
|
let idx = LineIndex::new(src);
|
|
assert_eq!(idx.line_count(), 3);
|
|
assert_eq!(idx.line_col(2), (1, 3)); // the `\r`
|
|
assert_eq!(idx.line_col(4), (2, 1)); // `c`
|
|
assert_eq!(idx.offset(2, 1), Some(4));
|
|
assert_eq!(idx.line_range(1), Some(TextRange::new(0, 3)));
|
|
}
|
|
|
|
#[test]
|
|
fn multibyte_utf8_columns_are_byte_offsets() {
|
|
// `λ` and `äöü` are 2 bytes each per char.
|
|
let src = "// λ comment\nwire ω; // äöü\n";
|
|
let idx = LineIndex::new(src);
|
|
let lambda = src.find('λ').unwrap() as u32;
|
|
assert_eq!(idx.line_col(lambda), (1, 4));
|
|
assert_eq!(idx.offset(1, 4), Some(lambda));
|
|
let omega = src.find('ω').unwrap() as u32;
|
|
assert_eq!(idx.line_col(omega), (2, 6));
|
|
// Round-trip every byte offset in the file, multi-byte or not.
|
|
for off in 0..=src.len() as u32 {
|
|
let (l, c) = idx.line_col(off);
|
|
assert_eq!(idx.offset(l, c), Some(off), "round trip at byte {off}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn utf16_positions_are_zero_based_and_count_code_units() {
|
|
let src = "module m;\n// 🎉 é\nendmodule";
|
|
let idx = LineIndex::new(src);
|
|
assert_eq!(idx.utf16_position(src, 0), (0, 0));
|
|
assert_eq!(idx.utf16_position(src, 7), (0, 7));
|
|
assert_eq!(idx.utf16_position(src, 10), (1, 0));
|
|
let party = src.find('🎉').unwrap() as u32;
|
|
assert_eq!(idx.utf16_position(src, party), (1, 3));
|
|
// Four UTF-8 bytes, two UTF-16 units — the surrogate pair.
|
|
assert_eq!(idx.utf16_position(src, party + 4), (1, 5));
|
|
// An offset inside the pair floors to its start.
|
|
for inside in 1..4 {
|
|
assert_eq!(idx.utf16_position(src, party + inside), (1, 3));
|
|
}
|
|
assert_eq!(idx.utf16_position(src, src.len() as u32 + 99), (2, 9));
|
|
}
|
|
|
|
#[test]
|
|
fn a_crlf_is_not_part_of_its_lines_utf16_content() {
|
|
let src = "ab\r\ncd\r\n";
|
|
let idx = LineIndex::new(src);
|
|
assert_eq!(idx.utf16_position(src, 2), (0, 2), "at the `\\r`");
|
|
assert_eq!(idx.utf16_position(src, 3), (0, 2), "at the `\\n`, past the `\\r`");
|
|
assert_eq!(idx.utf16_position(src, 4), (1, 0));
|
|
}
|
|
|
|
#[test]
|
|
fn out_of_range_positions_are_clamped() {
|
|
let src = "abc\nde";
|
|
let idx = LineIndex::new(src);
|
|
assert_eq!(idx.line_col(999), (2, 3), "past the end clamps to the end");
|
|
assert_eq!(idx.offset(1, 99), Some(3), "a long column stops before the newline");
|
|
assert_eq!(idx.offset(2, 99), Some(6));
|
|
assert_eq!(idx.offset(0, 1), None);
|
|
assert_eq!(idx.offset(3, 1), None);
|
|
}
|
|
}
|