rust-analyzer/lib/line-index/src/lib.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

228 lines
7.5 KiB
Rust
Raw Normal View History

2023-05-04 02:18:41 +00:00
//! See [`LineIndex`].
2023-05-04 23:21:42 +00:00
#![deny(missing_debug_implementations, missing_docs, rust_2018_idioms)]
2023-05-04 02:18:41 +00:00
#[cfg(test)]
mod tests;
2023-05-04 23:28:15 +00:00
use nohash_hasher::IntMap;
2023-05-04 23:21:29 +00:00
pub use text_size::{TextRange, TextSize};
2018-08-10 18:13:39 +00:00
2023-05-06 07:52:11 +00:00
/// `(line, column)` information in the native, UTF-8 encoding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LineCol {
2023-05-04 02:18:41 +00:00
/// Zero-based.
2018-08-10 18:13:39 +00:00
pub line: u32,
2023-05-04 02:18:41 +00:00
/// Zero-based UTF-8 offset.
2021-02-12 18:24:10 +00:00
pub col: u32,
2018-11-15 16:34:05 +00:00
}
2023-05-04 02:18:41 +00:00
/// A kind of wide character encoding.
2023-05-06 07:52:11 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2023-05-06 00:35:20 +00:00
#[non_exhaustive]
pub enum WideEncoding {
2023-05-04 02:18:41 +00:00
/// UTF-16.
Utf16,
2023-05-04 02:18:41 +00:00
/// UTF-32.
Utf32,
}
2023-05-06 00:35:20 +00:00
impl WideEncoding {
2023-05-06 07:52:11 +00:00
/// Returns the number of code units it takes to encode `text` in this encoding.
2023-05-06 00:35:20 +00:00
pub fn measure(&self, text: &str) -> usize {
match self {
WideEncoding::Utf16 => text.encode_utf16().count(),
WideEncoding::Utf32 => text.chars().count(),
}
}
}
2023-05-06 07:52:11 +00:00
/// `(line, column)` information in wide encodings.
///
/// See [`WideEncoding`] for the kinds of wide encodings available.
2023-05-04 23:34:24 +00:00
//
// Deliberately not a generic type and different from `LineCol`.
2023-05-06 07:52:11 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct WideLineCol {
2023-05-04 02:18:41 +00:00
/// Zero-based.
pub line: u32,
2023-05-04 02:18:41 +00:00
/// Zero-based.
pub col: u32,
}
2023-05-06 07:52:11 +00:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2023-05-04 23:20:53 +00:00
struct WideChar {
2023-05-06 07:52:11 +00:00
/// Start offset of a character inside a line, zero-based.
2023-05-04 23:20:53 +00:00
start: TextSize,
2023-05-06 07:52:11 +00:00
/// End offset of a character inside a line, zero-based.
2023-05-04 23:20:53 +00:00
end: TextSize,
2018-11-15 16:34:05 +00:00
}
impl WideChar {
/// Returns the length in 8-bit UTF-8 code units.
2020-04-24 21:40:41 +00:00
fn len(&self) -> TextSize {
2018-11-15 16:34:05 +00:00
self.end - self.start
}
/// Returns the length in UTF-16 or UTF-32 code units.
2023-05-06 08:03:18 +00:00
fn wide_len(&self, enc: WideEncoding) -> u32 {
match enc {
WideEncoding::Utf16 => {
if self.len() == TextSize::from(4) {
2
} else {
1
}
}
WideEncoding::Utf32 => 1,
}
}
2018-08-10 18:13:39 +00:00
}
2023-05-06 07:51:25 +00:00
/// Maps flat [`TextSize`] offsets to/from `(line, column)` representation.
#[derive(Debug, Clone, PartialEq, Eq)]
2023-05-06 00:25:10 +00:00
pub struct LineIndex {
2023-05-06 08:46:33 +00:00
/// Offset the beginning of each line (except the first, which always has offset 0).
2023-05-06 09:08:47 +00:00
///
/// Invariant: Always non-empty and the last element holds the length of the original text.
2023-05-06 00:25:10 +00:00
newlines: Box<[TextSize]>,
/// List of non-ASCII characters on each line.
line_wide_chars: IntMap<u32, Box<[WideChar]>>,
}
2018-08-10 18:13:39 +00:00
impl LineIndex {
2023-05-04 02:18:41 +00:00
/// Returns a `LineIndex` for the `text`.
2018-08-10 18:13:39 +00:00
pub fn new(text: &str) -> LineIndex {
2023-05-06 22:09:34 +00:00
let mut newlines = Vec::<TextSize>::with_capacity(16);
let mut line_wide_chars = IntMap::<u32, Box<[WideChar]>>::default();
2023-05-06 07:56:30 +00:00
2023-05-06 22:09:34 +00:00
let mut wide_chars = Vec::<WideChar>::new();
2023-05-06 07:56:30 +00:00
let mut cur_row = TextSize::from(0);
let mut cur_col = TextSize::from(0);
2023-05-06 22:09:34 +00:00
let mut line = 0u32;
2018-11-15 16:34:05 +00:00
2018-08-10 18:13:39 +00:00
for c in text.chars() {
2020-04-24 22:17:50 +00:00
let c_len = TextSize::of(c);
2023-05-04 23:38:35 +00:00
cur_row += c_len;
2018-08-10 18:13:39 +00:00
if c == '\n' {
2023-05-04 23:38:35 +00:00
newlines.push(cur_row);
2018-11-15 16:34:05 +00:00
2023-05-06 07:56:30 +00:00
// Save any wide characters seen in the previous line
if !wide_chars.is_empty() {
2023-05-06 07:56:30 +00:00
let cs = std::mem::take(&mut wide_chars).into_boxed_slice();
line_wide_chars.insert(line, cs);
2018-11-15 16:34:05 +00:00
}
// Prepare for processing the next line
2023-05-06 07:56:30 +00:00
cur_col = TextSize::from(0);
2018-11-15 16:34:05 +00:00
line += 1;
continue;
2018-08-10 18:13:39 +00:00
}
2018-11-15 16:34:05 +00:00
2020-04-24 22:17:50 +00:00
if !c.is_ascii() {
2023-05-04 23:38:35 +00:00
wide_chars.push(WideChar { start: cur_col, end: cur_col + c_len });
2018-11-15 16:34:05 +00:00
}
2023-05-04 23:38:35 +00:00
cur_col += c_len;
2018-11-15 16:34:05 +00:00
}
2023-05-06 09:08:47 +00:00
newlines.push(TextSize::of(text));
2023-05-06 07:56:30 +00:00
// Save any wide characters seen in the last line
if !wide_chars.is_empty() {
line_wide_chars.insert(line, wide_chars.into_boxed_slice());
}
LineIndex { newlines: newlines.into_boxed_slice(), line_wide_chars }
2018-08-10 18:13:39 +00:00
}
2023-05-04 02:18:41 +00:00
/// Transforms the `TextSize` into a `LineCol`.
2023-05-06 07:56:30 +00:00
///
/// # Panics
///
/// If the offset is invalid.
pub fn line_col(&self, offset: TextSize) -> LineCol {
2023-05-06 08:04:41 +00:00
self.try_line_col(offset).expect("invalid offset")
}
2023-05-06 08:05:28 +00:00
/// Transforms the `TextSize` into a `LineCol`, or returns `None` if the `offset` was invalid,
2023-05-06 09:08:47 +00:00
/// e.g. if it extends past the end of the text or points to the middle of a multi-byte
/// character.
2023-05-06 08:04:41 +00:00
pub fn try_line_col(&self, offset: TextSize) -> Option<LineCol> {
2023-05-06 09:08:47 +00:00
if offset > *self.newlines.last().unwrap() {
return None;
}
2023-05-06 08:46:33 +00:00
let line = self.newlines.partition_point(|&it| it <= offset);
let start = self.start_offset(line)?;
2023-05-06 08:37:25 +00:00
let col = offset - start;
2023-05-06 08:05:28 +00:00
let ret = LineCol { line: line as u32, col: col.into() };
self.line_wide_chars
.get(&ret.line)
.into_iter()
.flat_map(|it| it.iter())
2023-05-06 22:06:51 +00:00
.all(|it| col <= it.start || it.end <= col)
2023-05-06 08:05:28 +00:00
.then_some(ret)
}
2023-05-04 02:18:41 +00:00
/// Transforms the `LineCol` into a `TextSize`.
pub fn offset(&self, line_col: LineCol) -> Option<TextSize> {
2023-05-06 08:46:33 +00:00
self.start_offset(line_col.line as usize).map(|start| start + TextSize::from(line_col.col))
}
fn start_offset(&self, line: usize) -> Option<TextSize> {
match line.checked_sub(1) {
None => Some(TextSize::from(0)),
Some(it) => self.newlines.get(it).copied(),
}
}
2018-11-15 16:34:05 +00:00
2023-05-04 02:18:41 +00:00
/// Transforms the `LineCol` with the given `WideEncoding` into a `WideLineCol`.
2023-05-06 07:57:57 +00:00
pub fn to_wide(&self, enc: WideEncoding, line_col: LineCol) -> Option<WideLineCol> {
2023-05-06 08:03:18 +00:00
let mut col = line_col.col;
2023-05-06 07:59:56 +00:00
if let Some(wide_chars) = self.line_wide_chars.get(&line_col.line) {
for c in wide_chars.iter() {
2023-05-06 08:02:37 +00:00
if u32::from(c.end) <= line_col.col {
2023-05-06 22:05:03 +00:00
col = col.checked_sub(u32::from(c.len()) - c.wide_len(enc))?;
2018-11-15 16:34:05 +00:00
} else {
// From here on, all utf16 characters come *after* the character we are mapping,
// so we don't need to take them into account
break;
}
}
}
2023-05-06 08:03:18 +00:00
Some(WideLineCol { line: line_col.line, col })
2018-11-15 16:34:05 +00:00
}
2023-05-06 07:59:56 +00:00
/// Transforms the `WideLineCol` with the given `WideEncoding` into a `LineCol`.
pub fn to_utf8(&self, enc: WideEncoding, line_col: WideLineCol) -> Option<LineCol> {
let mut col = line_col.col;
if let Some(wide_chars) = self.line_wide_chars.get(&line_col.line) {
for c in wide_chars.iter() {
if col > u32::from(c.start) {
2023-05-06 22:05:03 +00:00
col = col.checked_add(u32::from(c.len()) - c.wide_len(enc))?;
2018-11-15 16:34:05 +00:00
} else {
// From here on, all utf16 characters come *after* the character we are mapping,
// so we don't need to take them into account
break;
}
}
}
2023-05-06 22:05:38 +00:00
Some(LineCol { line: line_col.line, col })
2023-05-06 07:59:56 +00:00
}
/// Returns an iterator over the ranges for the lines.
pub fn lines(&self, range: TextRange) -> impl Iterator<Item = TextRange> + '_ {
let lo = self.newlines.partition_point(|&it| it < range.start());
let hi = self.newlines.partition_point(|&it| it <= range.end());
let all = std::iter::once(range.start())
.chain(self.newlines[lo..hi].iter().copied())
.chain(std::iter::once(range.end()));
2018-11-15 16:34:05 +00:00
2023-05-06 07:59:56 +00:00
all.clone()
.zip(all.skip(1))
.map(|(lo, hi)| TextRange::new(lo, hi))
.filter(|it| !it.is_empty())
2018-08-10 18:13:39 +00:00
}
}