Skip to main content

logicaffeine_lsp/
line_index.rs

1use lsp_types::Position;
2
3/// Maps between byte offsets and LSP `Position` (line, character).
4///
5/// LSP positions use zero-based line and UTF-16 code unit offsets.
6/// Our source strings use byte offsets. This struct pre-computes
7/// line start byte offsets for efficient bidirectional conversion.
8#[derive(Debug, Clone)]
9pub struct LineIndex {
10    /// Byte offset of each line start. `line_starts[0]` is always 0.
11    line_starts: Vec<usize>,
12    /// The full source text (needed for UTF-16 offset computation).
13    source: String,
14}
15
16impl LineIndex {
17    pub fn new(source: &str) -> Self {
18        let mut line_starts = vec![0];
19        for (i, b) in source.bytes().enumerate() {
20            if b == b'\n' {
21                line_starts.push(i + 1);
22            }
23        }
24        LineIndex {
25            line_starts,
26            source: source.to_string(),
27        }
28    }
29
30    /// Largest char boundary `<= i` (clamped to the source length). Keeps a
31    /// COMPUTED offset (e.g. `span.start + name.len()`) from slicing mid-char and
32    /// panicking — position math must be total over every `usize`.
33    fn floor_char_boundary(&self, i: usize) -> usize {
34        let mut i = i.min(self.source.len());
35        while i > 0 && !self.source.is_char_boundary(i) {
36            i -= 1;
37        }
38        i
39    }
40
41    /// Convert a byte offset to an LSP `Position`.
42    ///
43    /// Returns `(line, character)` where character is a UTF-16 code unit offset.
44    pub fn position(&self, byte_offset: usize) -> Position {
45        let byte_offset = self.floor_char_boundary(byte_offset);
46
47        let line = self
48            .line_starts
49            .partition_point(|&start| start <= byte_offset)
50            .saturating_sub(1);
51
52        let line_start = self.line_starts[line];
53        let line_text = &self.source[line_start..byte_offset];
54        let character = line_text.encode_utf16().count() as u32;
55
56        Position {
57            line: line as u32,
58            character,
59        }
60    }
61
62    /// Byte offset of the end of `line`'s CONTENT — just before its `\n` (and a
63    /// preceding `\r`), or `source.len()` for the last line. Used to clip a
64    /// multi-line token span to a single line for the semantic-token encoder.
65    pub fn line_end_offset(&self, line: usize) -> usize {
66        let end = match self.line_starts.get(line + 1) {
67            Some(&next) => next.saturating_sub(1), // the '\n'
68            None => self.source.len(),
69        };
70        if end > 0 && self.source.as_bytes().get(end - 1) == Some(&b'\r') {
71            end - 1
72        } else {
73            end
74        }
75    }
76
77    /// Return the byte offset of the start of `line` (0-indexed).
78    /// Returns `source.len()` if `line` is out of bounds.
79    pub fn line_start_offset(&self, line: usize) -> usize {
80        self.line_starts
81            .get(line)
82            .copied()
83            .unwrap_or(self.source.len())
84    }
85
86    /// Compute the UTF-16 length of a byte range in the source. Offsets are
87    /// snapped to char boundaries so a computed range can never panic the slice.
88    pub fn utf16_length(&self, byte_start: usize, byte_end: usize) -> u32 {
89        let start = self.floor_char_boundary(byte_start);
90        let end = self.floor_char_boundary(byte_end);
91        if start >= end {
92            return 0;
93        }
94        self.source[start..end].encode_utf16().count() as u32
95    }
96
97    /// Convert an LSP `Position` to a byte offset.
98    pub fn offset(&self, position: Position) -> usize {
99        let line = position.line as usize;
100        if line >= self.line_starts.len() {
101            return self.source.len();
102        }
103
104        let line_start = self.line_starts[line];
105        // Scan only the line's CONTENT (terminator excluded): LSP clamps a
106        // character past the line to the line length, so an out-of-range Position
107        // must resolve to this line's end, not cross the `\n` into the next line.
108        let content_end = self.line_end_offset(line);
109
110        let line_text = &self.source[line_start..content_end];
111        let mut utf16_offset = 0u32;
112        let target = position.character;
113
114        for (byte_idx, ch) in line_text.char_indices() {
115            if utf16_offset >= target {
116                return line_start + byte_idx;
117            }
118            utf16_offset += ch.len_utf16() as u32;
119        }
120
121        content_end
122    }
123}
124
125#[cfg(test)]
126#[path = "../../logicaffeine_tests/unit/logicaffeine_lsp/line_index/tests.rs"]
127mod tests;