pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! # pikopiko
//!
//! MMLテキストを解析してチップチューンを鳴らす pure Rust ライブラリ。
//! コアはオーディオ出力やスレッドを知らない。音を出すには、利用側で
//! [`Player::render`] をオーディオコールバックから呼ぶ。
//!
//! ```
//! use std::sync::Arc;
//!
//! let song = pikopiko::compile("A t150 l8 o4 cdefgab>c").expect("MMLに誤りがある");
//! let mut player = pikopiko::Player::new(Arc::new(song), 48_000);
//! let mut buf = [[0.0f32; 2]; 512];
//! player.render(&mut buf); // オーディオコールバックの中で呼ぶ
//! ```
//!
//! 文法は [`SPEC`](`docs/spec.md`)、使い方は取扱説明書(`docs/guide/`)を参照。
//!
//! ## Overview (English)
//!
//! pikopiko is a pure Rust library that parses MML (Music Macro Language) text and plays
//! chiptune and synth music. The core knows nothing about audio output or threads: to make
//! sound, call [`Player::render`] from your audio callback, as in the example above.
//!
//! - The grammar is in [`SPEC_EN`] (`docs/en/spec.md`; [`SPEC`] is the Japanese original).
//! - The user guide is in English at
//!   [`docs/en/guide/`](https://github.com/lovelygenerator/pikopiko/blob/main/docs/en/guide/README.md).
//! - Diagnostics, synth descriptions and the CLI / MCP messages are available in English and
//!   Japanese (see [`lang`]).
//! - The documentation comments of the public API below are written in Japanese. The user guide
//!   and the grammar specification are the English entry points.

#![forbid(unsafe_code)]
// docs.rs では、機能が要る項目に「必要な機能」を表示する
#![cfg_attr(docsrs, feature(doc_cfg))]

// 用途別のモジュール。直下に用途ごとのディレクトリを置き、どこに何があるかを名前で分かるようにする。
// 翻訳(作る)→ 再生(鳴らす)・書き出し(別の形にする)という流れに沿って分け、作曲支援と報告は
// その横に置く。音源は `synth`、画面の言語は `lang`。
pub mod compiler;
pub mod composer;
pub mod export;
pub mod language;
pub mod player;
pub mod report;
pub mod synth;
/// ランタイム(`pikopiko-runtime`)。音量エンベロープ(`runtime::envelope`)・音程エフェクト
/// (`runtime::pitch`)・イベント列バイナリ(`runtime::binary`)などを、`pikopiko` と同じ版で使える
/// (使う側が `pikopiko-runtime` を別に依存に書かなくてよい)。
pub use pikopiko_runtime as runtime;
/// 訳せる文(エラーの文など)の口(`pikopiko_runtime::text`)。
pub use pikopiko_runtime::text;
/// このクレートの文の表(`locales/*.ftl`。診断の文・言葉・エラーの文)。
pub(crate) mod text_table {
    use crate::text::{Catalog, Seg};
    include!(concat!(env!("OUT_DIR"), "/text.rs"));
}
pub mod lang;

use compiler::{include, parser, song};

pub use compiler::ast::Ast;
pub use compiler::diagnostic::{Diagnostic, Severity, Span};
pub use compiler::dialect::Dialect;
pub use compiler::song::{ChordKeys, Event, EventKind, Marker, Meter, Song, SongMeta};
pub use player::voice::{SynthVoice, Voice};
pub use player::{
    render_to_vec, render_to_vec_looped, render_to_vec_looped_with, render_to_vec_with, Command,
    JumpAt, Notice, NoticeMask, Player, SfxChannels, SfxError, SfxId, TrackActivity,
    MAX_REGISTERED_SFX, NOTICE_CAPACITY,
};
pub use report::info::{
    describe, describe_with, key_name, secs_to_ticks, ticks_to_secs, KeyInfo, MarkerInfo, SongInfo,
    TrackInfo,
};
pub use synth::{Synth, SynthConfig, SynthSpec};

// crates.io のパッケージにはクレートの外のファイルが入らないので、`docs/spec.md` と `docs/en/spec.md` の
// 写しを `spec/` に置く(`scripts/release.sh sync` で写し、`tests/spec_copy.rs` が同じ中身かを見張る)。

/// MML文法仕様(`docs/spec.md` の全文、日本語)。生成AIにそのまま渡せる。日本語版が正本。
pub const SPEC: &str = include_str!("../spec/ja.md");

/// MML文法仕様の英語版(`docs/en/spec.md` の全文)。[`SPEC`] の翻訳で、食い違ったら日本語版が正しい。
pub const SPEC_EN: &str = include_str!("../spec/en.md");

/// 言語タグ(`en`・`ja` など)に合う文法仕様。日本語なら [`SPEC`]、それ以外は [`SPEC_EN`]。
pub fn spec_for(lang: &str) -> &'static str {
    if is_japanese(lang) {
        SPEC
    } else {
        SPEC_EN
    }
}

/// 言語タグが日本語(`ja`、`ja-JP`、`ja_JP.UTF-8` など)か。AI に渡す文の言語を選ぶのに使う。
pub fn is_japanese(lang: &str) -> bool {
    let lang = lang.trim();
    lang == "ja" || lang.starts_with("ja-") || lang.starts_with("ja_") || lang.starts_with("ja.")
}

/// 4分音符あたりのtick数(10080。7 連符・9 連符も整数の tick で表せる)。
pub const PPQ: u32 = pikopiko_runtime::defaults::PPQ;
/// 全音符のtick数(= 4 × PPQ = 40320)。音長 `n`(n 分音符)は、これを割り切れる数でなければならない。
pub const WHOLE_TICKS: u32 = 4 * PPQ;
/// MML に書く tick(表記上の tick)の全音符の数。`c%120` の `120` はこの単位で、内部の tick は
/// [`NOTATION_SCALE`] 倍になる。内部の PPQ を変えても、MML に書く数は変わらない。
pub const NOTATION_WHOLE: u32 = 1920;
/// 表記上の tick 1 つあたりの内部の tick 数(= 21)。
pub const NOTATION_SCALE: u32 = WHOLE_TICKS / NOTATION_WHOLE;
/// 音長 `n`(n 分音符)に書ける最大の数。
pub const MAX_LENGTH_NUMBER: u32 = NOTATION_WHOLE;
/// tick で書く音長(`c%120`)の最大(表記上の tick。全音符 255 個分)。
pub const MAX_TICK_LENGTH: u32 = NOTATION_WHOLE * 255;

/// 解析と展開の設定。
///
/// フィールドは増えることがあるので、作るときは `..Default::default()` で残りを埋める。
#[derive(Clone, Copy)]
pub struct CompileOptions<'a> {
    /// 既定の方言。曲の先頭に `#dialect` があればそちらを使う。
    pub dialect: Dialect,
    /// `#synth` で選べる音源。独自の音源を足すときは、内蔵の [`synth::BUILTIN`] と合わせて渡す。
    pub synths: &'a [&'a SynthSpec],
    /// `#include "パス"` の読み込みの口([`include::Files`]、[`include::Sources`] など)。
    /// `None`(既定)なら `#include` は E0601。
    pub include: Option<&'a dyn include::Include>,
    /// 曲の本文の前に読む共有の定義(並べた順に `#include` したのと同じ扱い)。
    pub prelude: &'a [include::Source<'a>],
}

impl Default for CompileOptions<'_> {
    fn default() -> Self {
        CompileOptions {
            dialect: Dialect::PIKOPIKO,
            synths: synth::BUILTIN,
            include: None,
            prelude: &[],
        }
    }
}

impl core::fmt::Debug for CompileOptions<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CompileOptions")
            .field("dialect", &self.dialect)
            .field("synths", &self.synths)
            .field("include", &self.include.map(|_| "…"))
            .field("prelude", &self.prelude)
            .finish()
    }
}

/// MMLを構文解析する(方言 `pikopiko`)。エラーがあっても部分的なASTとすべての診断を返す。
pub fn parse(src: &str) -> (Ast, Vec<Diagnostic>) {
    parser::parse(src, &Dialect::PIKOPIKO)
}

/// 方言を指定して構文解析する。`#include` は読めない(E0601)。
pub fn parse_with(src: &str, dialect: &Dialect) -> (Ast, Vec<Diagnostic>) {
    parser::parse(src, dialect)
}

/// 設定(方言、`#include` の読み込みの口、共有の定義)を指定して構文解析する。
pub fn parse_with_options(src: &str, opts: &CompileOptions<'_>) -> (Ast, Vec<Diagnostic>) {
    parser::parse_root(src, &opts.dialect, opts.prelude, opts.include, opts.synths)
}

/// 解析と展開をまとめて行う。エラーがあれば `None`。警告は診断に含まれる。
pub fn compile_with_diagnostics(src: &str) -> (Option<Song>, Vec<Diagnostic>) {
    compile_with(src, &CompileOptions::default())
}

/// 設定を指定して解析と展開を行う。
pub fn compile_with(src: &str, opts: &CompileOptions<'_>) -> (Option<Song>, Vec<Diagnostic>) {
    let (_, song, diags) = compile_parts(src, opts);
    (song, diags)
}

/// [`compile_with`] の中身:構文解析の結果(AST)も返す。言語サービスの層([`language`])が、
/// 同じ 1 回の解析から定義の位置と曲を引くのに使う。
pub(crate) fn compile_parts(
    src: &str,
    opts: &CompileOptions<'_>,
) -> (Ast, Option<Song>, Vec<Diagnostic>) {
    let (ast, mut diags) = parse_with_options(src, opts);
    let (song, exp) = song::expand(&ast, opts.synths);
    diags.extend(exp);
    parser::fill_files(&mut diags, &ast.sources);
    diags.sort_by_key(|d| (d.span.source, d.span.line, d.span.col));
    diags.dedup_by(|a, b| a.is_repeat_of(b));
    if diags.iter().any(|d| d.is_error()) {
        return (ast, None, diags);
    }
    (ast, song, diags)
}

/// 解析と展開をまとめて行う。エラーが1つでもあれば、すべての診断(警告を含む)を返す。
pub fn compile(src: &str) -> Result<Song, Vec<Diagnostic>> {
    match compile_with_diagnostics(src) {
        (Some(song), _) => Ok(song),
        (None, diags) => Err(diags),
    }
}

/// `candidates` から `name` に近いものを探す。打ち間違いの修正候補用。
///
/// 近さは編集距離(隣どうしの入れ替えも 1 と数える)で、2 以内かつ長い方の名前の半分以内のもの。
/// 半分の制限は、短い名前どうしが「綴りが近いだけ」で候補になるのを防ぐため(`va` にしかない
/// `%pw` を `basic` に書いたとき、意味の違う `%pan` を案内しない)。`cutof` → `cutoff`・`pna` →
/// `pan` のような本当の打ち間違いは残る。同じ距離なら名前の順で最初のもの(決定的にするため)。
pub(crate) fn nearest<'a>(name: &str, candidates: &[&'a str]) -> Option<&'a str> {
    candidates
        .iter()
        .map(|c| (edit_distance(c, name), *c))
        .filter(|(d, c)| *d <= 2 && *d * 2 <= c.chars().count().max(name.chars().count()))
        .min()
        .map(|(_, c)| c)
}

/// 2つの文字列の編集距離(挿入・削除・置き換えと、隣どうしの入れ替えをそれぞれ 1 と数える。
/// 打ち間違いの候補探し用)。
fn edit_distance(a: &str, b: &str) -> usize {
    let a: Vec<char> = a.chars().collect();
    let b: Vec<char> = b.chars().collect();
    // d[i][j]:a の先頭 i 文字と b の先頭 j 文字の距離(入れ替えを見るため 2 行前まで持つ)
    let mut d = vec![vec![0usize; b.len() + 1]; a.len() + 1];
    for (i, row) in d.iter_mut().enumerate() {
        row[0] = i;
    }
    for (j, v) in d[0].iter_mut().enumerate() {
        *v = j;
    }
    for i in 1..=a.len() {
        for j in 1..=b.len() {
            let cost = usize::from(a[i - 1] != b[j - 1]);
            let mut v = (d[i - 1][j] + 1)
                .min(d[i][j - 1] + 1)
                .min(d[i - 1][j - 1] + cost);
            if i > 1 && j > 1 && a[i - 1] == b[j - 2] && a[i - 2] == b[j - 1] {
                v = v.min(d[i - 2][j - 2] + 1);
            }
            d[i][j] = v;
        }
    }
    d[a.len()][b.len()]
}