pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! 定義の読み込み(`#include`):読み込むファイルの文字列を探し(`include_text`)、その中の定義
//! (マクロ・エンベロープ・効果の定義など)だけを本文の前に読む(`include_directive`)。
//!
//! 読み込んだものの位置は `Span::source` で本文と分け、誤りには読み込んだファイルの名前を付ける。
//! 同じファイルを二度読む・ループする読み込みは診断にする。
//!
//! `@` で始まる名前(`#include "@va/bass"`)はファイルではなく、音源の組み込みの音色集
//! (`SynthSpec::tone_files`)から読む(`library_text`)。読み込みの口(`Include`)を渡さなくても
//! 使えるので、ファイルを読まない環境(MCP など)でも同じ曲が通る。組み込みにない名前は、読み込みの口の
//! `load_library`(利用者の音色集)に任せる。

use super::*;

/// 読み込んだテキストを定義だけのものとして読み、`defs` に足す。位置は読み込んだものの番号にする。
pub(super) fn include_text(
    name: String,
    text: &str,
    dialect: &Dialect,
    inc: &mut Includes<'_>,
    defs: &mut Defs,
    diags: &mut Vec<Diagnostic>,
) {
    inc.sources.push(name.clone());
    let id = inc.sources.len().min(u16::MAX as usize) as u16;
    inc.stack.push(name);
    let (sub, mut d) = parse_impl(text, dialect, Mode::Included, inc, std::mem::take(defs));
    inc.stack.pop();
    let set = |sp: &mut Span| {
        if sp.source == 0 {
            sp.source = id;
        }
    };
    for x in &mut d {
        set(&mut x.span);
    }
    diags.extend(d);
    let Ast {
        mut macros,
        mut envelopes,
        mut vibratos,
        mut detunes,
        mut arps,
        mut duties,
        mut waves,
        mut shots,
        ..
    } = sub;
    for m in &mut macros {
        set(&mut m.span);
        m.nodes.iter_mut().for_each(|n| n.set_source(id));
    }
    envelopes.iter_mut().for_each(|e| set(&mut e.span));
    vibratos.iter_mut().for_each(|e| set(&mut e.span));
    detunes.iter_mut().for_each(|e| set(&mut e.span));
    arps.iter_mut().for_each(|e| set(&mut e.span));
    duties.iter_mut().for_each(|e| set(&mut e.span));
    waves.iter_mut().for_each(|e| set(&mut e.span));
    for s in &mut shots {
        set(&mut s.span);
        set(&mut s.synth_span);
        s.nodes.iter_mut().for_each(|n| n.set_source(id));
    }
    *defs = Defs {
        macros,
        envelopes,
        vibratos,
        detunes,
        arps,
        duties,
        waves,
        shots,
    };
}

/// `#include "パス"` の行を処理する。
pub(super) fn include_directive(
    chars: &[char],
    head_end: usize,
    head_span: Span,
    dialect: &Dialect,
    inc: &mut Includes<'_>,
    defs: &mut Defs,
    diags: &mut Vec<Diagnostic>,
) {
    let rest: String = chars[head_end.min(chars.len())..].iter().collect();
    let rest = rest.trim();
    let path = rest
        .strip_prefix('"')
        .and_then(|r| r.strip_suffix('"'))
        .filter(|p| !p.is_empty() && !p.contains('"'));
    let Some(path) = path else {
        diags.push(
            Diagnostic::error(
                codes::BAD_DIRECTIVE_VALUE,
                head_span,
                msg!("E0228-include-path"),
            )
            .with_suggestion("#include \"common.mml\""),
        );
        return;
    };
    // 組み込みの音色集は読み込みの口を使わない。音色集は標準の方言で書いてあるので、
    // 読み込む側の方言に関わらず標準の方言で読む
    let library = path.strip_prefix('@');
    if inc.stack.len() >= crate::compiler::include::MAX_DEPTH {
        diags.push(Diagnostic::error(
            codes::INCLUDE_CYCLE,
            head_span,
            msg!("E0602-too-deep", max = crate::compiler::include::MAX_DEPTH),
        ));
        return;
    }
    let loaded = match (library, inc.loader) {
        (Some(name), loader) => match library_text(name, inc.synths) {
            Ok(text) => Ok((path.to_string(), text.to_string(), Dialect::PIKOPIKO)),
            // 組み込みにない名前は、利用者の音色集(読み込みの口が持つもの)を探す
            Err(e) => match loader.and_then(|l| l.load_library(name)) {
                Some(r) => r.map(|l| (l.name, l.text, Dialect::PIKOPIKO)),
                None => Err(e),
            },
        },
        (None, Some(loader)) => loader
            .load(path, inc.stack.last().map(String::as_str))
            .map(|l| (l.name, l.text, *dialect)),
        (None, None) => Err(msg!("E0601-unavailable", path = path)),
    };
    let (name, text, dialect) = match loaded {
        Ok(l) => l,
        Err(e) => {
            diags.push(Diagnostic::error(codes::INCLUDE_FAILED, head_span, e));
            return;
        }
    };
    if inc.stack.contains(&name) {
        diags.push(Diagnostic::error(
            codes::INCLUDE_CYCLE,
            head_span,
            msg!("E0602-self", path = path),
        ));
        return;
    }
    // 同じものは 1 回だけ読む(菱形の読み込みで定義が重複しないように)
    if inc.sources.contains(&name) {
        return;
    }
    include_text(name, &text, &dialect, inc, defs, diags);
}

/// `#sample スロット "パス" [元の高さ]` の行を処理する。録音は読み込みの口([`Include::load_bytes`])で読む。
pub(super) fn sample_directive(
    chars: &[char],
    head_end: usize,
    head_span: Span,
    inc: &Includes<'_>,
    samples: &mut Vec<crate::synth::SampleAsset>,
    diags: &mut Vec<Diagnostic>,
) {
    let rest: String = chars[head_end.min(chars.len())..].iter().collect();
    let rest = rest.trim();
    let bad = |diags: &mut Vec<Diagnostic>| {
        diags.push(
            Diagnostic::error(codes::BAD_DIRECTIVE_VALUE, head_span, msg!("E0228-sample"))
                .with_suggestion("#sample 0 \"kick.wav\" 60"),
        );
    };
    let Some((slot, after)) = rest.split_once(char::is_whitespace) else {
        return bad(diags);
    };
    let after = after.trim();
    let Some(body) = after.strip_prefix('"') else {
        return bad(diags);
    };
    let Some((path, tail)) = body.split_once('"') else {
        return bad(diags);
    };
    let Ok(slot) = slot.parse::<u8>() else {
        return bad(diags);
    };
    let tail = tail.trim();
    let root_key = if tail.is_empty() {
        None
    } else {
        match tail.parse::<u8>() {
            Ok(k) if k <= 127 => Some(k),
            _ => return bad(diags),
        }
    };
    if path.is_empty() {
        return bad(diags);
    }
    if slot >= crate::synth::SAMPLE_SLOTS {
        diags.push(Diagnostic::error(
            codes::BAD_DIRECTIVE_VALUE,
            head_span,
            msg!("E0228-sample-slot", max = crate::synth::SAMPLE_SLOTS - 1),
        ));
        return;
    }
    let Some(loader) = inc.loader else {
        diags.push(Diagnostic::error(
            codes::INCLUDE_FAILED,
            head_span,
            msg!("E0601-sample-unavailable", path = path),
        ));
        return;
    };
    match loader.load_bytes(path) {
        Ok(data) => {
            // 同じスロットに書き直したら、あとの指定が優先
            samples.retain(|s| s.slot != slot);
            samples.push(crate::synth::SampleAsset {
                slot,
                path: path.to_string(),
                root_key,
                data,
                span: head_span,
            });
        }
        Err(e) => diags.push(Diagnostic::error(codes::INCLUDE_FAILED, head_span, e)),
    }
}

/// 組み込みの音色集 `音源/名前`(`@` の後ろ)の本文。見つからなければ理由の文(E0601)。
fn library_text(name: &str, synths: &[&SynthSpec]) -> Result<&'static str, Message> {
    let path = format!("@{name}");
    let (synth, file) = name.split_once('/').unwrap_or((name, ""));
    let with_files: Vec<&SynthSpec> = synths
        .iter()
        .copied()
        .filter(|s| !s.tone_files.is_empty())
        .collect();
    let Some(spec) = with_files.iter().find(|s| s.matches(synth)) else {
        if with_files.is_empty() {
            return Err(msg!("E0601-library-none", path = path));
        }
        let names: Vec<String> = with_files
            .iter()
            .map(|s| format!("@{}", s.library_prefix()))
            .collect();
        return Err(msg!(
            "E0601-library-synth",
            path = path,
            names = names.join(", ")
        ));
    };
    match spec.tone_file(file) {
        Some(f) => Ok(f.text),
        None => {
            let names: Vec<String> = spec
                .tone_files
                .iter()
                .map(|f| format!("@{}/{}", spec.library_prefix(), f.name))
                .collect();
            Err(msg!(
                "E0601-library-file",
                path = path,
                names = names.join(", ")
            ))
        }
    }
}