1use core::ops::Range;
13
14use lsp_types::{
15 CompletionItemKind, DiagnosticSeverity, Position, PositionEncodingKind, SemanticToken,
16 SemanticTokenType, SemanticTokensLegend,
17};
18use pikopiko::language::{ItemKind, LineIndex, Token, TokenKind};
19use pikopiko::{Severity, Span};
20
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum Encoding {
24 #[default]
26 Utf16,
27 Utf8,
29}
30
31impl Encoding {
32 pub fn negotiate(offered: Option<&[PositionEncodingKind]>) -> Encoding {
35 match offered {
36 Some(o) if o.contains(&PositionEncodingKind::UTF8) => Encoding::Utf8,
37 _ => Encoding::Utf16,
38 }
39 }
40
41 pub fn kind(self) -> PositionEncodingKind {
43 match self {
44 Encoding::Utf16 => PositionEncodingKind::UTF16,
45 Encoding::Utf8 => PositionEncodingKind::UTF8,
46 }
47 }
48
49 fn width(self, c: char) -> u32 {
50 match self {
51 Encoding::Utf16 => c.len_utf16() as u32,
52 Encoding::Utf8 => c.len_utf8() as u32,
53 }
54 }
55}
56
57pub fn position(text: &str, index: &LineIndex, byte: usize, enc: Encoding) -> Position {
59 let byte = byte.min(text.len());
60 let (line, _) = index.line_col(text, byte);
61 let start = index.line_range(text, line).map_or(0, |r| r.start);
62 let character = text[start..byte.max(start)]
63 .chars()
64 .map(|c| enc.width(c))
65 .sum();
66 Position {
67 line: line - 1,
68 character,
69 }
70}
71
72pub fn byte(text: &str, index: &LineIndex, pos: Position, enc: Encoding) -> usize {
75 let Some(r) = index.line_range(text, pos.line + 1) else {
76 return text.len();
77 };
78 let mut col = 0;
79 for (o, c) in text[r.clone()].char_indices() {
80 if col >= pos.character {
81 return r.start + o;
82 }
83 col += enc.width(c);
84 }
85 r.end
86}
87
88pub fn range(
90 text: &str,
91 index: &LineIndex,
92 bytes: Range<usize>,
93 enc: Encoding,
94) -> lsp_types::Range {
95 lsp_types::Range {
96 start: position(text, index, bytes.start, enc),
97 end: position(text, index, bytes.end, enc),
98 }
99}
100
101pub fn span_range(text: &str, index: &LineIndex, span: Span, enc: Encoding) -> lsp_types::Range {
103 let bytes = index.range_of(text, span).unwrap_or(text.len()..text.len());
104 range(text, index, bytes, enc)
105}
106
107pub fn severity(s: Severity) -> DiagnosticSeverity {
109 match s {
110 Severity::Error => DiagnosticSeverity::ERROR,
111 Severity::Warning => DiagnosticSeverity::WARNING,
112 }
113}
114
115pub fn completion_kind(k: ItemKind) -> CompletionItemKind {
117 match k {
118 ItemKind::Command => CompletionItemKind::KEYWORD,
119 ItemKind::Tone => CompletionItemKind::VALUE,
120 ItemKind::Envelope
121 | ItemKind::Vibrato
122 | ItemKind::Detune
123 | ItemKind::Arp
124 | ItemKind::Duty
125 | ItemKind::Wave => CompletionItemKind::CONSTANT,
126 ItemKind::Off => CompletionItemKind::KEYWORD,
127 ItemKind::Macro => CompletionItemKind::FUNCTION,
128 ItemKind::Library | ItemKind::File => CompletionItemKind::FILE,
129 ItemKind::Shot => CompletionItemKind::EVENT,
130 ItemKind::Mark => CompletionItemKind::REFERENCE,
131 ItemKind::Directive => CompletionItemKind::KEYWORD,
132 }
133}
134
135pub fn token_types(kind: TokenKind) -> (SemanticTokenType, Option<&'static str>) {
137 match kind {
138 TokenKind::Comment => (SemanticTokenType::COMMENT, None),
139 TokenKind::Directive => (SemanticTokenType::KEYWORD, None),
140 TokenKind::Track => (SemanticTokenType::NAMESPACE, None),
141 TokenKind::Note => (SemanticTokenType::STRING, Some("note")),
142 TokenKind::Rest => (SemanticTokenType::STRING, Some("rest")),
143 TokenKind::Command => (SemanticTokenType::FUNCTION, None),
144 TokenKind::Param => (SemanticTokenType::PROPERTY, None),
145 TokenKind::Macro => (SemanticTokenType::MACRO, None),
146 TokenKind::Envelope => (SemanticTokenType::TYPE, Some("envelope")),
147 TokenKind::Loop => (SemanticTokenType::OPERATOR, Some("loop")),
148 TokenKind::Tie => (SemanticTokenType::OPERATOR, Some("tie")),
149 TokenKind::Number => (SemanticTokenType::NUMBER, None),
150 TokenKind::Shot => (SemanticTokenType::EVENT, Some("shot")),
151 }
152}
153
154#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct TokenLegend {
161 pub legend: SemanticTokensLegend,
162}
163
164impl TokenLegend {
165 pub fn new(client_types: Option<&[SemanticTokenType]>) -> Self {
166 let token_types = TokenKind::ALL
167 .iter()
168 .map(|&k| {
169 let (standard, custom) = token_types(k);
170 match (custom, client_types) {
171 (Some(c), Some(types)) if types.iter().any(|t| t.as_str() == c) => {
172 SemanticTokenType::new(c)
173 }
174 _ => standard,
175 }
176 })
177 .collect();
178 TokenLegend {
179 legend: SemanticTokensLegend {
180 token_types,
181 token_modifiers: Vec::new(),
182 },
183 }
184 }
185
186 pub fn index(kind: TokenKind) -> u32 {
188 TokenKind::ALL.iter().position(|&k| k == kind).unwrap_or(0) as u32
189 }
190}
191
192pub fn semantic_tokens(
195 text: &str,
196 index: &LineIndex,
197 tokens: &[Token],
198 enc: Encoding,
199) -> Vec<SemanticToken> {
200 let mut out = Vec::with_capacity(tokens.len());
201 let (mut prev_line, mut prev_col) = (0, 0);
202 for t in tokens {
203 let r = range(text, index, t.bytes.clone(), enc);
204 let length = r.end.character.saturating_sub(r.start.character);
205 let delta_line = r.start.line - prev_line;
206 let delta_start = if delta_line == 0 {
207 r.start.character - prev_col
208 } else {
209 r.start.character
210 };
211 out.push(SemanticToken {
212 delta_line,
213 delta_start,
214 length,
215 token_type: TokenLegend::index(t.kind),
216 token_modifiers_bitset: 0,
217 });
218 prev_line = r.start.line;
219 prev_col = r.start.character;
220 }
221 out
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 #[test]
229 fn positions_in_utf16_and_utf8() {
230 let t = "A 😀c4\nB d";
232 let ix = LineIndex::new(t);
233 let c = t.find('c').unwrap();
234 assert_eq!(position(t, &ix, c, Encoding::Utf16), Position::new(0, 4));
235 assert_eq!(position(t, &ix, c, Encoding::Utf8), Position::new(0, 6));
236 assert_eq!(byte(t, &ix, Position::new(0, 4), Encoding::Utf16), c);
237 assert_eq!(byte(t, &ix, Position::new(0, 6), Encoding::Utf8), c);
238 assert_eq!(
239 byte(t, &ix, Position::new(1, 2), Encoding::Utf16),
240 t.len() - 1
241 );
242 assert_eq!(
244 byte(t, &ix, Position::new(0, 99), Encoding::Utf16),
245 t.find('\n').unwrap()
246 );
247 assert_eq!(byte(t, &ix, Position::new(9, 0), Encoding::Utf16), t.len());
248 assert_eq!(
249 span_range(t, &ix, Span::new(1, 4, 2), Encoding::Utf16),
250 lsp_types::Range::new(Position::new(0, 4), Position::new(0, 6))
251 );
252 }
253
254 #[test]
255 fn legend_uses_custom_types_only_when_offered() {
256 let std_only = TokenLegend::new(None);
257 assert_eq!(std_only.legend.token_types.len(), TokenKind::ALL.len());
258 assert_eq!(
259 std_only.legend.token_types[TokenLegend::index(TokenKind::Note) as usize],
260 SemanticTokenType::STRING
261 );
262 let offered = [SemanticTokenType::new("note"), SemanticTokenType::COMMENT];
263 let custom = TokenLegend::new(Some(&offered));
264 assert_eq!(
265 custom.legend.token_types[TokenLegend::index(TokenKind::Note) as usize].as_str(),
266 "note"
267 );
268 assert_eq!(
269 custom.legend.token_types[TokenLegend::index(TokenKind::Rest) as usize],
270 SemanticTokenType::STRING
271 );
272 }
273
274 #[test]
275 fn semantic_tokens_are_relative() {
276 let t = "A c4 d\n; x";
277 let ix = LineIndex::new(t);
278 let toks = pikopiko::language::tokens(t);
279 let s = semantic_tokens(t, &ix, &toks, Encoding::Utf16);
280 let v: Vec<_> = s
281 .iter()
282 .map(|s| (s.delta_line, s.delta_start, s.length))
283 .collect();
284 assert_eq!(v, vec![(0, 0, 1), (0, 2, 2), (0, 3, 1), (1, 0, 3)]);
285 }
286}