pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 曲どうしで定義を共有する仕組み(`#include "パス"` と、API で渡す共有の定義)。
//!
//! コアはファイルを読まない。読み込みは [`Include`] を実装したものを
//! [`crate::CompileOptions::include`] に渡して行う。ファイルから読むなら [`Files`]、
//! 名前と本文の組から引くなら(ファイルを読まない環境、テスト)[`Sources`]。
//!
//! 読み込まれる側に書けるのは定義だけ(マクロ `$名前 = …`、`@env` `@vib` `@detune` `@arp` の定義)と、
//! コメント・空行・入れ子の `#include`。
//!
//! ```
//! use pikopiko::compiler::include::{Source, Sources};
//! use pikopiko::{compile_with, CompileOptions};
//!
//! let lib = Sources::new([("lib.mml", "@env pluck = 15 12 9 6 3 0\n$riff = c d e")]);
//! let opts = CompileOptions { include: Some(&lib), ..Default::default() };
//! let (song, diags) = compile_with("#include \"lib.mml\"\nA @env pluck $riff", &opts);
//! assert!(song.is_some(), "{diags:?}");
//!
//! // ファイルを持たず、定義の文字列を前置きとして渡すこともできる
//! let prelude = [Source { name: "common", text: "$riff = c d e" }];
//! let opts = CompileOptions { prelude: &prelude, ..Default::default() };
//! assert!(compile_with("A $riff", &opts).0.is_some());
//! ```

use crate::compiler::diagnostic::Message;
use crate::msg;
use std::path::{Path, PathBuf};

/// 読み込んだもの。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Included {
    /// 読み込んだものの名前。同じものを 2 回読んだか・循環しているかの判定と、診断の表示に使う。
    /// 入れ子の `#include` では、読み込む側の名前として [`Include::load`] の `from` に渡る。
    pub name: String,
    /// 本文(MML)。
    pub text: String,
}

/// `#include` の読み込みの口。
pub trait Include {
    /// `path`(`#include "…"` に書いた文字列)を読む。`from` は読み込む側の名前
    /// (曲の本文なら `None`)。失敗したときは理由の文を返す(診断 E0601 の文になる。
    /// ほかの言語に訳せるよう [`crate::msg!`] で作る。文字列も渡せる)。
    fn load(&self, path: &str, from: Option<&str>) -> Result<Included, Message>;

    /// `#include "@名前/種類"` の `名前/種類`(`@` の後ろ)を、利用者の音色集から読む。組み込みの音色集
    /// (音源の `tone_files`)にない名前のときだけ呼ばれる(組み込みが優先)。その名前の音色集を持たない
    /// 口は `None`(既定)を返し、持つ口は読めたか・読めない理由を返す。音色集は標準の方言で書く。
    fn load_library(&self, _name: &str) -> Option<Result<Included, Message>> {
        None
    }

    /// `#sample` の録音(WAV のバイト列)を読む。`path` は曲に書いた文字列。既定は読めない環境(E0601)。
    fn load_bytes(&self, path: &str) -> Result<std::sync::Arc<[u8]>, Message> {
        Err(msg!("E0601-sample-unavailable", path = path))
    }

    /// `#include "` の入力補助が出す、読み込めるファイルの名前(`dir` はそこまで打った
    /// フォルダー部分で、空か `/` で終わる。基準は曲の本文の置き場所)。`.mml` のファイルとフォルダー
    /// (`名前/`)を返す。既定は空(読める一覧を持たない口)。補完は決定的であるため、コアは
    /// ファイルを直接は読まず、この口に任せる。
    fn list(&self, _dir: &str) -> Vec<String> {
        Vec::new()
    }

    /// `#include "@` の入力補助が出す、組み込み以外の音色集のファイル(利用者の音色集。`@名前/種類`)と、
    /// 中の音色の名前。`load_library` が読める名前の一覧に当たる。既定は空。
    fn libraries(&self) -> Vec<(String, Vec<String>)> {
        Vec::new()
    }
}

/// [`crate::CompileOptions::prelude`] に渡す、共有の定義の文字列。
/// 曲の本文の前に、並べた順に `#include` したのと同じ扱いで読む。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Source<'a> {
    /// 診断の表示に使う名前。
    pub name: &'a str,
    pub text: &'a str,
}

/// ファイルから読む。パスは読み込む側のファイルのあるフォルダーからの相対(絶対パスも可)。
/// 曲の本文から読むときの基準は [`Files::new`] で渡すフォルダー。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Files {
    base: PathBuf,
}

impl Files {
    /// `base` は曲の本文のあるフォルダー(本文がファイルでなければ、今いるフォルダーなど)。
    pub fn new(base: impl Into<PathBuf>) -> Self {
        Files { base: base.into() }
    }

    /// 曲のファイルのパスから作る(そのファイルのあるフォルダーを基準にする)。
    pub fn beside(file: impl AsRef<Path>) -> Self {
        let dir = file
            .as_ref()
            .parent()
            .map(Path::to_path_buf)
            .unwrap_or_default();
        Files::new(dir)
    }

    /// 基準のフォルダー。
    pub fn base(&self) -> &Path {
        &self.base
    }
}

impl Include for Files {
    fn list(&self, dir: &str) -> Vec<String> {
        let Ok(rd) = std::fs::read_dir(self.base.join(dir)) else {
            return Vec::new();
        };
        let mut names: Vec<String> = rd
            .flatten()
            .filter_map(|e| {
                let name = e.file_name().into_string().ok()?;
                let is_dir = e.file_type().ok()?.is_dir();
                if is_dir {
                    Some(format!("{name}/"))
                } else if name.ends_with(".mml") {
                    Some(name)
                } else {
                    None
                }
            })
            .collect();
        names.sort();
        names
    }

    fn load_bytes(&self, path: &str) -> Result<std::sync::Arc<[u8]>, Message> {
        let full = self.base.join(path);
        std::fs::read(&full).map(Into::into).map_err(|e| {
            msg!(
                "E0601-read-failed",
                path = full.display().to_string(),
                error = e.to_string()
            )
        })
    }

    fn load(&self, path: &str, from: Option<&str>) -> Result<Included, Message> {
        let dir = match from {
            Some(f) => Path::new(f)
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_default(),
            None => self.base.clone(),
        };
        let full = dir.join(path);
        let text = std::fs::read_to_string(&full).map_err(|e| {
            msg!(
                "E0601-read-failed",
                path = full.display().to_string(),
                error = e.to_string()
            )
        })?;
        // 同じファイルを別の書き方で指しても同じものと分かるよう、正規化したパスを名前にする
        let name = std::fs::canonicalize(&full)
            .unwrap_or(full)
            .to_string_lossy()
            .into_owned();
        Ok(Included { name, text })
    }
}

/// 名前と本文の組から引く(ファイルを読まない)。`#include "名前"` の名前とそのまま比べる。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Sources {
    entries: Vec<(String, String)>,
}

impl Sources {
    pub fn new<N: Into<String>, T: Into<String>>(
        entries: impl IntoIterator<Item = (N, T)>,
    ) -> Self {
        Sources {
            entries: entries
                .into_iter()
                .map(|(n, t)| (n.into(), t.into()))
                .collect(),
        }
    }

    /// 足す(同じ名前があれば置き換える)。
    pub fn insert(&mut self, name: impl Into<String>, text: impl Into<String>) {
        let name = name.into();
        let text = text.into();
        match self.entries.iter_mut().find(|(n, _)| *n == name) {
            Some(e) => e.1 = text,
            None => self.entries.push((name, text)),
        }
    }

    /// 名前の一覧(足した順)。
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.entries.iter().map(|(n, _)| n.as_str())
    }

    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

impl Include for Sources {
    fn load(&self, path: &str, _from: Option<&str>) -> Result<Included, Message> {
        self.entries
            .iter()
            .find(|(n, _)| n == path)
            .map(|(n, t)| Included {
                name: n.clone(),
                text: t.clone(),
            })
            .ok_or_else(|| {
                let names: Vec<&str> = self.names().collect();
                if names.is_empty() {
                    msg!("E0601-not-given-none", path = path)
                } else {
                    msg!("E0601-not-given", path = path, names = names.join(", "))
                }
            })
    }
}

/// 入れ子の `#include` の深さの上限。
pub const MAX_DEPTH: usize = 8;