Skip to main content

pikopiko_cli/lsp/
convert.rs

1//! 言語サービスの層(`pikopiko::language`)の自前の型と、LSP の型(`lsp-types`)の変換の口。
2//!
3//! 言語サーバー `pikopiko-lsp` が使い、`lsp-types` の型で受け取るエディタの部品などの使う側も
4//! そのまま呼べるよう公開する。口は少なく薄く保つ(位置・範囲・トークンの種類・診断の重さ程度):
5//! 本体は自前の型の言語サービスの層にあるので、`lsp-types` の版がずれた使う側は自分で変換できる。
6//! 対応する `lsp-types` の版は [`lsp_types`](このモジュールが出し直したもの)の版。
7//!
8//! 位置の数え方:LSP の位置は 0 始まりの行と、行の中の列(既定は UTF-16 の単位。クライアントが
9//! 対応を知らせれば UTF-8 のバイト)。コアは 1 始まりの行・文字単位の列とバイト位置なので、
10//! ここで行の中を数え直して換算する([`Encoding`])。
11
12use 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/// LSP の列の単位。
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
23pub enum Encoding {
24    /// UTF-16 の単位(LSP の既定)。
25    #[default]
26    Utf16,
27    /// UTF-8 のバイト。
28    Utf8,
29}
30
31impl Encoding {
32    /// クライアントが対応を知らせた単位(`general.positionEncodings`)から選ぶ。UTF-8 があれば
33    /// UTF-8(換算が要らない)、なければ UTF-16。
34    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    /// サーバーの能力として返す値。
42    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
57/// バイト位置 → LSP の位置。
58pub 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
72/// LSP の位置 → バイト位置。行の外は行の終わり、テキストの外はテキストの終わり。文字の途中を
73/// 指す列(UTF-16 のサロゲートの間など)は、その文字の後ろ。
74pub 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
88/// バイト範囲 → LSP の範囲。
89pub 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
101/// [`Span`](そのテキストの中の位置として。`source` は見ない)→ LSP の範囲。
102pub 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
107/// 診断の重さ。
108pub fn severity(s: Severity) -> DiagnosticSeverity {
109    match s {
110        Severity::Error => DiagnosticSeverity::ERROR,
111        Severity::Warning => DiagnosticSeverity::WARNING,
112    }
113}
114
115/// 補完の候補の種類。
116pub 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
135/// トークンの種類の、近い標準の種類と、独自の種類(なければ `None`)。
136pub 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/// セマンティックトークンの凡例と、トークンの種類 → 凡例の番号の表。
155///
156/// 凡例は [`TokenKind::ALL`] の順に 1 つずつ。独自の種類は、クライアントが知らせた種類
157/// (`textDocument.semanticTokens.tokenTypes`)にあれば使い、なければ近い標準の種類にする。
158/// `client_types` が `None`(知らせなかった)なら標準の種類だけ。
159#[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    /// 種類の凡例の番号([`TokenKind::ALL`] の添字)。
187    pub fn index(kind: TokenKind) -> u32 {
188        TokenKind::ALL.iter().position(|&k| k == kind).unwrap_or(0) as u32
189    }
190}
191
192/// トークン → セマンティックトークン(LSP の相対位置の並び)。トークンは先頭から順で、1 行に
193/// 収まっていること(`pikopiko::language::tokens` の約束)。
194pub 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        // `😀` は UTF-16 で 2、UTF-8 で 4
231        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        // 外は端
243        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}