use core::ops::Range;
use lsp_types::{
CompletionItemKind, DiagnosticSeverity, Position, PositionEncodingKind, SemanticToken,
SemanticTokenType, SemanticTokensLegend,
};
use pikopiko::language::{ItemKind, LineIndex, Token, TokenKind};
use pikopiko::{Severity, Span};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Encoding {
#[default]
Utf16,
Utf8,
}
impl Encoding {
pub fn negotiate(offered: Option<&[PositionEncodingKind]>) -> Encoding {
match offered {
Some(o) if o.contains(&PositionEncodingKind::UTF8) => Encoding::Utf8,
_ => Encoding::Utf16,
}
}
pub fn kind(self) -> PositionEncodingKind {
match self {
Encoding::Utf16 => PositionEncodingKind::UTF16,
Encoding::Utf8 => PositionEncodingKind::UTF8,
}
}
fn width(self, c: char) -> u32 {
match self {
Encoding::Utf16 => c.len_utf16() as u32,
Encoding::Utf8 => c.len_utf8() as u32,
}
}
}
pub fn position(text: &str, index: &LineIndex, byte: usize, enc: Encoding) -> Position {
let byte = byte.min(text.len());
let (line, _) = index.line_col(text, byte);
let start = index.line_range(text, line).map_or(0, |r| r.start);
let character = text[start..byte.max(start)]
.chars()
.map(|c| enc.width(c))
.sum();
Position {
line: line - 1,
character,
}
}
pub fn byte(text: &str, index: &LineIndex, pos: Position, enc: Encoding) -> usize {
let Some(r) = index.line_range(text, pos.line + 1) else {
return text.len();
};
let mut col = 0;
for (o, c) in text[r.clone()].char_indices() {
if col >= pos.character {
return r.start + o;
}
col += enc.width(c);
}
r.end
}
pub fn range(
text: &str,
index: &LineIndex,
bytes: Range<usize>,
enc: Encoding,
) -> lsp_types::Range {
lsp_types::Range {
start: position(text, index, bytes.start, enc),
end: position(text, index, bytes.end, enc),
}
}
pub fn span_range(text: &str, index: &LineIndex, span: Span, enc: Encoding) -> lsp_types::Range {
let bytes = index.range_of(text, span).unwrap_or(text.len()..text.len());
range(text, index, bytes, enc)
}
pub fn severity(s: Severity) -> DiagnosticSeverity {
match s {
Severity::Error => DiagnosticSeverity::ERROR,
Severity::Warning => DiagnosticSeverity::WARNING,
}
}
pub fn completion_kind(k: ItemKind) -> CompletionItemKind {
match k {
ItemKind::Command => CompletionItemKind::KEYWORD,
ItemKind::Tone => CompletionItemKind::VALUE,
ItemKind::Envelope
| ItemKind::Vibrato
| ItemKind::Detune
| ItemKind::Arp
| ItemKind::Duty
| ItemKind::Wave => CompletionItemKind::CONSTANT,
ItemKind::Off => CompletionItemKind::KEYWORD,
ItemKind::Macro => CompletionItemKind::FUNCTION,
ItemKind::Library | ItemKind::File => CompletionItemKind::FILE,
ItemKind::Shot => CompletionItemKind::EVENT,
ItemKind::Mark => CompletionItemKind::REFERENCE,
ItemKind::Directive => CompletionItemKind::KEYWORD,
}
}
pub fn token_types(kind: TokenKind) -> (SemanticTokenType, Option<&'static str>) {
match kind {
TokenKind::Comment => (SemanticTokenType::COMMENT, None),
TokenKind::Directive => (SemanticTokenType::KEYWORD, None),
TokenKind::Track => (SemanticTokenType::NAMESPACE, None),
TokenKind::Note => (SemanticTokenType::STRING, Some("note")),
TokenKind::Rest => (SemanticTokenType::STRING, Some("rest")),
TokenKind::Command => (SemanticTokenType::FUNCTION, None),
TokenKind::Param => (SemanticTokenType::PROPERTY, None),
TokenKind::Macro => (SemanticTokenType::MACRO, None),
TokenKind::Envelope => (SemanticTokenType::TYPE, Some("envelope")),
TokenKind::Loop => (SemanticTokenType::OPERATOR, Some("loop")),
TokenKind::Tie => (SemanticTokenType::OPERATOR, Some("tie")),
TokenKind::Number => (SemanticTokenType::NUMBER, None),
TokenKind::Shot => (SemanticTokenType::EVENT, Some("shot")),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TokenLegend {
pub legend: SemanticTokensLegend,
}
impl TokenLegend {
pub fn new(client_types: Option<&[SemanticTokenType]>) -> Self {
let token_types = TokenKind::ALL
.iter()
.map(|&k| {
let (standard, custom) = token_types(k);
match (custom, client_types) {
(Some(c), Some(types)) if types.iter().any(|t| t.as_str() == c) => {
SemanticTokenType::new(c)
}
_ => standard,
}
})
.collect();
TokenLegend {
legend: SemanticTokensLegend {
token_types,
token_modifiers: Vec::new(),
},
}
}
pub fn index(kind: TokenKind) -> u32 {
TokenKind::ALL.iter().position(|&k| k == kind).unwrap_or(0) as u32
}
}
pub fn semantic_tokens(
text: &str,
index: &LineIndex,
tokens: &[Token],
enc: Encoding,
) -> Vec<SemanticToken> {
let mut out = Vec::with_capacity(tokens.len());
let (mut prev_line, mut prev_col) = (0, 0);
for t in tokens {
let r = range(text, index, t.bytes.clone(), enc);
let length = r.end.character.saturating_sub(r.start.character);
let delta_line = r.start.line - prev_line;
let delta_start = if delta_line == 0 {
r.start.character - prev_col
} else {
r.start.character
};
out.push(SemanticToken {
delta_line,
delta_start,
length,
token_type: TokenLegend::index(t.kind),
token_modifiers_bitset: 0,
});
prev_line = r.start.line;
prev_col = r.start.character;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn positions_in_utf16_and_utf8() {
let t = "A 😀c4\nB d";
let ix = LineIndex::new(t);
let c = t.find('c').unwrap();
assert_eq!(position(t, &ix, c, Encoding::Utf16), Position::new(0, 4));
assert_eq!(position(t, &ix, c, Encoding::Utf8), Position::new(0, 6));
assert_eq!(byte(t, &ix, Position::new(0, 4), Encoding::Utf16), c);
assert_eq!(byte(t, &ix, Position::new(0, 6), Encoding::Utf8), c);
assert_eq!(
byte(t, &ix, Position::new(1, 2), Encoding::Utf16),
t.len() - 1
);
assert_eq!(
byte(t, &ix, Position::new(0, 99), Encoding::Utf16),
t.find('\n').unwrap()
);
assert_eq!(byte(t, &ix, Position::new(9, 0), Encoding::Utf16), t.len());
assert_eq!(
span_range(t, &ix, Span::new(1, 4, 2), Encoding::Utf16),
lsp_types::Range::new(Position::new(0, 4), Position::new(0, 6))
);
}
#[test]
fn legend_uses_custom_types_only_when_offered() {
let std_only = TokenLegend::new(None);
assert_eq!(std_only.legend.token_types.len(), TokenKind::ALL.len());
assert_eq!(
std_only.legend.token_types[TokenLegend::index(TokenKind::Note) as usize],
SemanticTokenType::STRING
);
let offered = [SemanticTokenType::new("note"), SemanticTokenType::COMMENT];
let custom = TokenLegend::new(Some(&offered));
assert_eq!(
custom.legend.token_types[TokenLegend::index(TokenKind::Note) as usize].as_str(),
"note"
);
assert_eq!(
custom.legend.token_types[TokenLegend::index(TokenKind::Rest) as usize],
SemanticTokenType::STRING
);
}
#[test]
fn semantic_tokens_are_relative() {
let t = "A c4 d\n; x";
let ix = LineIndex::new(t);
let toks = pikopiko::language::tokens(t);
let s = semantic_tokens(t, &ix, &toks, Encoding::Utf16);
let v: Vec<_> = s
.iter()
.map(|s| (s.delta_line, s.delta_start, s.length))
.collect();
assert_eq!(v, vec![(0, 0, 1), (0, 2, 2), (0, 3, 1), (1, 0, 3)]);
}
}