pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! ホバー:位置にある字句の説明(コマンド・パラメータ・マクロ・音色などの意味と値の範囲、定義の
//! 場所、音符なら鳴る位置)を、Markdown の文にする。
//!
//! 文は `locales/language-*.ftl`(`hover-…`)と音源の説明の表から、表示の言語で引く。使う側の
//! `.ftl` での上書きは [`HoverContext::text`] で受ける(`pikopiko::lang::I18n::override_text` を
//! 渡せば、診断などと同じ決まりで上書きが効く)。数・MML の書き方・名前は言語によらない。

use core::fmt::Write as _;

use super::navigate::{definition_at, split_command, DefKind};
use super::position::Location;
use super::tokens::{Token, TokenKind};
use super::Analysis;
use crate::synth::{text_key, OptionKind, SynthSpec};

/// 鳴る位置の一覧に出す数の上限(長い曲で文が伸びすぎないように)。
const MAX_TIMES: usize = 8;

/// ホバーの文を作るのに要るもの。
#[derive(Clone, Copy)]
pub struct HoverContext<'a> {
    /// 表示の言語(`en`・`ja`。対応しない言語は英語)。
    pub lang: &'a str,
    /// 音源の一覧(音色・パラメータの説明を引く。解析に使ったものと同じにする)。
    pub synths: &'a [&'a SynthSpec],
    /// 使う側の文の上書き:キーを受け取り、上書きの文があれば返す。なければ `None`。
    pub text: &'a dyn Fn(&str) -> Option<String>,
}

impl core::fmt::Debug for HoverContext<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("HoverContext")
            .field("lang", &self.lang)
            .field("synths", &self.synths)
            .finish()
    }
}

/// ホバーの結果。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hover {
    /// 説明している字句の位置(本文)。
    pub location: Location,
    /// 説明の文(Markdown)。1 行目は字句そのもの(コード)。
    pub markdown: String,
}

impl HoverContext<'_> {
    /// 本体の表の文(`hover-…`)。
    fn core(&self, key: &str) -> String {
        if let Some(t) = (self.text)(key) {
            return t;
        }
        match crate::text::find(crate::text_table::CATALOGS, self.lang, key) {
            Some(segs) => {
                let mut out = String::new();
                let _ = crate::text::write_segs(&mut out, segs, &mut |_, _| Ok(()));
                out
            }
            None => String::new(),
        }
    }

    /// 音源の表の文(キーは [`text_key`] の形)。
    fn synth(&self, spec: &SynthSpec, key: &str) -> String {
        (self.text)(key).unwrap_or_else(|| spec.text(key, self.lang).to_string())
    }
}

/// `byte` にある字句の説明。説明のない字句(コメント・空白など)では `None`。
pub(super) fn hover(a: &Analysis, byte: usize, ctx: &HoverContext<'_>) -> Option<Hover> {
    let token = a.token_at(byte)?;
    let text = &a.source[token.bytes.clone()];
    let mut md = format!("`{text}`\n\n");
    let spec = a.synth_spec(ctx.synths);
    match token.kind {
        TokenKind::Comment => return None,
        TokenKind::Directive => {
            let key = match text {
                "#dialect" => "hover-directive-dialect",
                "#synth" => "hover-directive-synth",
                "#meter" => "hover-directive-meter",
                "#swing" => "hover-directive-swing",
                "#frame" => "hover-directive-frame",
                "#include" => "hover-directive-include",
                "#sample" => "hover-directive-sample",
                "#title" | "#composer" | "#copyright" | "#artist" | "#comment" => {
                    "hover-directive-meta"
                }
                _ => return None,
            };
            md.push_str(&ctx.core(key));
            if text == "#synth" {
                if let Some(spec) = spec {
                    let _ = write!(
                        md,
                        "\n\n`{}`: {}",
                        spec.name,
                        ctx.synth(spec, &text_key::synth(spec.name))
                    );
                }
            }
        }
        TokenKind::Track => md.push_str(&ctx.core("hover-track")),
        TokenKind::Note | TokenKind::Rest => {
            md.push_str(&ctx.core(if token.kind == TokenKind::Note {
                "hover-note"
            } else {
                "hover-rest"
            }));
            if token.kind == TokenKind::Note {
                sounds_at(a, token, ctx, &mut md);
            }
        }
        TokenKind::Command => command(text, spec, ctx, &mut md)?,
        TokenKind::Param => param(a, token, text, spec, ctx, &mut md)?,
        TokenKind::Macro => {
            md.push_str(&ctx.core(DefKind::Macro.hover_key()));
            let name = &text[1..];
            if let Some(spec) = spec {
                let desc = ctx.synth(spec, &text_key::library(spec.name, name));
                if !desc.is_empty() {
                    let _ = write!(md, "\n\n{desc}");
                }
            }
            defined_at(a, byte, ctx, &mut md);
        }
        TokenKind::Envelope => {
            // `mpof` などの解除も、その種類の説明にする
            let (cmd, _) = split_command(text);
            let kind = DefKind::of_command(cmd.strip_suffix("of").unwrap_or(cmd))?;
            md.push_str(&ctx.core(kind.hover_key()));
            defined_at(a, byte, ctx, &mut md);
        }
        TokenKind::Loop => md.push_str(&ctx.core(match text.as_bytes()[0] {
            b'[' => "hover-loop-start",
            b']' => "hover-loop-end",
            b'|' => "hover-loop-break",
            _ => "hover-loop-point",
        })),
        TokenKind::Tie => md.push_str(&ctx.core(if text == "^" {
            "hover-tie"
        } else {
            "hover-slur"
        })),
        TokenKind::Number => {
            if !text.starts_with('%') {
                return None;
            }
            md.push_str(&ctx.core("hover-tick-length"));
        }
        TokenKind::Shot => {
            md.push_str(&ctx.core(DefKind::Shot.hover_key()));
            defined_at(a, byte, ctx, &mut md);
        }
    }
    Some(Hover {
        location: Location {
            span: token.span,
            bytes: Some(token.bytes.clone()),
        },
        markdown: md.trim_end().to_string(),
    })
}

/// `Command` の字句(`o4`・`@3`・`@bar` など)の説明。
fn command(
    text: &str,
    spec: Option<&SynthSpec>,
    ctx: &HoverContext<'_>,
    md: &mut String,
) -> Option<()> {
    let b = text.as_bytes();
    let second = b.get(1).copied();
    let key = match b[0].to_ascii_lowercase() {
        b'o' => "hover-octave",
        b'>' => "hover-octave-up",
        b'<' => "hover-octave-down",
        b'l' => "hover-length",
        b't' if text.contains(',') => "hover-tempo-ramp",
        b't' => "hover-tempo",
        b'v' if matches!(second, Some(b'+' | b'-')) => "hover-volume-relative",
        b'v' => "hover-volume",
        b'k' => "hover-transpose",
        b'q' if second == Some(b'%') => "hover-gate-cut",
        b'q' => "hover-gate",
        b'{' | b'}' => "hover-portamento",
        b'\'' => "hover-chord",
        b'@' => match &text[1..] {
            "bar" => "hover-bar",
            "swing" => "hover-swing",
            n if n.is_empty() || n.bytes().all(|c| c.is_ascii_digit()) => {
                md.push_str(&ctx.core("hover-tone"));
                if let (Some(spec), Ok(id)) = (spec, n.parse::<u8>()) {
                    let desc = ctx.synth(spec, &text_key::tone(spec.name, id));
                    if !desc.is_empty() {
                        let _ = write!(md, "\n\n`{}` `@{id}`: {desc}", spec.name);
                    }
                }
                return Some(());
            }
            n => DefKind::of_command(n)?.hover_key(),
        },
        _ => return None,
    };
    md.push_str(&ctx.core(key));
    Some(())
}

/// `Param` の字句(`%cutoff=100`、指令の `キー=値`)の説明と値の範囲。
fn param(
    a: &Analysis,
    token: &Token,
    text: &str,
    spec: Option<&SynthSpec>,
    ctx: &HoverContext<'_>,
    md: &mut String,
) -> Option<()> {
    let line = a.line_text(token.span.line);
    let spec = spec?;
    if let Some(rest) = text.strip_prefix('%') {
        let name = rest.split('=').next().unwrap_or("");
        md.push_str(&ctx.core("hover-param"));
        let desc = ctx.synth(spec, &text_key::param(spec.name, name));
        if !desc.is_empty() {
            let _ = write!(md, "\n\n`{}` `%{name}`: {desc}", spec.name);
        }
        if let Some(p) = spec.params.iter().find(|p| p.name == name) {
            let _ = write!(
                md,
                "\n\n{}: {}–{} / {}: {}",
                ctx.core("hover-range"),
                p.min,
                p.max,
                ctx.core("hover-default"),
                p.default
            );
        }
        return Some(());
    }
    // 指令の `キー=値`:`#synth` のオプションだけ説明する
    if !line.trim_start().starts_with("#synth") {
        return None;
    }
    let name = text.split('=').next().unwrap_or("");
    let o = spec.options.iter().find(|o| o.name == name)?;
    let desc = ctx.synth(spec, &text_key::option(spec.name, name));
    let _ = write!(md, "`{}` `{name}`: {desc}", spec.name);
    let range = match o.kind {
        OptionKind::Range { min, max } => format!("{min}–{max}"),
        OptionKind::Choice(c) => c.join(" / "),
    };
    let _ = write!(
        md,
        "\n\n{}: {range} / {}: {}",
        ctx.core("hover-range"),
        ctx.core("hover-default"),
        o.default
    );
    Some(())
}

/// 定義の場所(本文なら行の中身、読み込んだものならその名前と行)を足す。
fn defined_at(a: &Analysis, byte: usize, ctx: &HoverContext<'_>, md: &mut String) {
    let Some(def) = definition_at(a, byte) else {
        return;
    };
    let Some(loc) = def.location() else {
        return;
    };
    let label = ctx.core("hover-defined-at");
    if loc.span.source == 0 {
        let _ = write!(
            md,
            "\n\n{label} ({}): `{}`",
            loc.span.line,
            a.line_text(loc.span.line).trim()
        );
    } else {
        let name = a.source_name(loc.span.source).unwrap_or("");
        let _ = write!(md, "\n\n{label}: `{name}` ({})", loc.span.line);
    }
}

/// 音符が鳴る位置(トラックと tick)を足す。
fn sounds_at(a: &Analysis, token: &Token, ctx: &HoverContext<'_>, md: &mut String) {
    let times = a.notes_at(token.bytes.start);
    if times.is_empty() {
        return;
    }
    let _ = write!(md, "\n\n{}:", ctx.core("hover-sounds-at"));
    for n in times.iter().take(MAX_TIMES) {
        let _ = write!(md, " `{}` {}", n.track_name, n.tick);
    }
    if times.len() > MAX_TIMES {
        let _ = write!(md, " … ({})", times.len());
    }
}