//! 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, 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 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 { 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 { 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, } } } #[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 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); } }