use crate::lsp::{Encoding, SemanticToken};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum TokenKind {
Keyword,
Function,
Type,
String,
Constant,
Comment,
Macro,
Namespace,
}
impl TokenKind {
pub fn from_name(name: &str) -> Option<Self> {
Some(match name {
"keyword" | "modifier" | "selfKeyword" | "selfTypeKeyword" => Self::Keyword,
"function" | "method" | "member" => Self::Function,
"type" | "class" | "struct" | "enum" | "interface" | "union" | "typeParameter"
| "typeAlias" | "builtinType" | "concept" => Self::Type,
"string" | "char" | "character" | "regexp" | "escapeSequence" | "formatSpecifier" => {
Self::String
}
"number" | "boolean" | "enumMember" | "const" | "constParameter" => Self::Constant,
"comment" => Self::Comment,
"macro" | "decorator" | "attribute" | "derive" | "builtinAttribute" | "lifetime"
| "label" => Self::Macro,
"namespace" | "module" => Self::Namespace,
_ => return None,
})
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Token {
pub start: usize,
pub end: usize,
pub kind: TokenKind,
}
#[derive(Default)]
pub struct Highlights {
lines: Vec<Vec<Token>>,
}
impl Highlights {
pub fn new(tokens: &[SemanticToken], lines: &[String], encoding: Encoding) -> Self {
let mut table = vec![Vec::new(); lines.len()];
for token in tokens {
let Some(line) = lines.get(token.line) else {
continue;
};
let start = encoding.to_chars(line, token.start);
let end = encoding.to_chars(line, token.start + token.length);
if start < end {
table[token.line].push(Token {
start,
end,
kind: token.kind,
});
}
}
Self { lines: table }
}
pub fn on(&self, y: usize) -> &[Token] {
self.lines.get(y).map_or(&[], Vec::as_slice)
}
pub fn inserted(&mut self, x: usize, y: usize) {
for token in self.lines.get_mut(y).into_iter().flatten() {
if token.start >= x {
token.start += 1;
token.end += 1;
} else if token.end >= x {
token.end += 1;
}
}
}
pub fn deleted(&mut self, x: usize, y: usize) {
if let Some(tokens) = self.lines.get_mut(y) {
for token in tokens.iter_mut() {
if token.start > x {
token.start -= 1;
token.end -= 1;
} else if token.end > x {
token.end -= 1;
}
}
tokens.retain(|token| token.start < token.end);
}
}
pub fn split(&mut self, x: usize, y: usize) {
let Some(tokens) = self.lines.get_mut(y) else {
return;
};
let mut below = Vec::new();
for token in tokens.iter_mut() {
if token.end > x {
below.push(Token {
start: token.start.saturating_sub(x),
end: token.end - x,
kind: token.kind,
});
token.end = token.end.min(x);
}
}
tokens.retain(|token| token.start < token.end);
self.lines.insert(y + 1, below);
}
pub fn joined(&mut self, y: usize, len: usize) {
if y + 1 < self.lines.len() {
let below = self.lines.remove(y + 1);
self.lines[y].extend(below.into_iter().map(|token| Token {
start: token.start + len,
end: token.end + len,
kind: token.kind,
}));
}
}
}