pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! 言語サービスの層(`pikopiko::language`)の自前の型と、LSP の型(`lsp-types`)の変換の口。
//!
//! 言語サーバー `pikopiko-lsp` が使い、`lsp-types` の型で受け取るエディタの部品などの使う側も
//! そのまま呼べるよう公開する。口は少なく薄く保つ(位置・範囲・トークンの種類・診断の重さ程度):
//! 本体は自前の型の言語サービスの層にあるので、`lsp-types` の版がずれた使う側は自分で変換できる。
//! 対応する `lsp-types` の版は [`lsp_types`](このモジュールが出し直したもの)の版。
//!
//! 位置の数え方:LSP の位置は 0 始まりの行と、行の中の列(既定は UTF-16 の単位。クライアントが
//! 対応を知らせれば UTF-8 のバイト)。コアは 1 始まりの行・文字単位の列とバイト位置なので、
//! ここで行の中を数え直して換算する([`Encoding`])。

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};

/// LSP の列の単位。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Encoding {
    /// UTF-16 の単位(LSP の既定)。
    #[default]
    Utf16,
    /// UTF-8 のバイト。
    Utf8,
}

impl Encoding {
    /// クライアントが対応を知らせた単位(`general.positionEncodings`)から選ぶ。UTF-8 があれば
    /// UTF-8(換算が要らない)、なければ UTF-16。
    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,
        }
    }
}

/// バイト位置 → LSP の位置。
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,
    }
}

/// LSP の位置 → バイト位置。行の外は行の終わり、テキストの外はテキストの終わり。文字の途中を
/// 指す列(UTF-16 のサロゲートの間など)は、その文字の後ろ。
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
}

/// バイト範囲 → LSP の範囲。
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),
    }
}

/// [`Span`](そのテキストの中の位置として。`source` は見ない)→ LSP の範囲。
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,
    }
}

/// トークンの種類の、近い標準の種類と、独自の種類(なければ `None`)。
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")),
    }
}

/// セマンティックトークンの凡例と、トークンの種類 → 凡例の番号の表。
///
/// 凡例は [`TokenKind::ALL`] の順に 1 つずつ。独自の種類は、クライアントが知らせた種類
/// (`textDocument.semanticTokens.tokenTypes`)にあれば使い、なければ近い標準の種類にする。
/// `client_types` が `None`(知らせなかった)なら標準の種類だけ。
#[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(),
            },
        }
    }

    /// 種類の凡例の番号([`TokenKind::ALL`] の添字)。
    pub fn index(kind: TokenKind) -> u32 {
        TokenKind::ALL.iter().position(|&k| k == kind).unwrap_or(0) as u32
    }
}

/// トークン → セマンティックトークン(LSP の相対位置の並び)。トークンは先頭から順で、1 行に
/// 収まっていること(`pikopiko::language::tokens` の約束)。
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() {
        // `😀` は UTF-16 で 2、UTF-8 で 4
        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)]);
    }
}