pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! `#` で始まる指示(`#synth`・`#title`・`#frame`・`#meter`・`#include` など)を読む。
//!
//! 知っている指示の一覧は `DIRECTIVES`、同じ指示が二度書かれたかなどの状態は `DirectiveState` に持つ。
//! 古い書き方(`#chip`)は診断で新しい書き方を案内する。
//!
//! 入口の [`directive`] は行を語に分け、本文より後に書かれていないかを確かめてから、指示ごとの
//! メソッド(`DirectiveState::dialect` など)に振り分ける。指示を足すときは、振り分けの `match` に
//! 1 行と、そのメソッドを足す。

use super::*;

pub(super) struct DirectiveState<'a> {
    pub(super) body_started: bool,
    pub(super) dialect: &'a mut Dialect,
    pub(super) dialect_set: &'a mut Option<Span>,
    pub(super) synth: &'a mut Option<SynthDirective>,
    pub(super) meta: &'a mut crate::compiler::song::SongMeta,
    pub(super) meta_set: &'a mut Vec<(&'static str, Span)>,
    pub(super) frame: &'a mut Option<(u8, Span)>,
    pub(super) meter: &'a mut Option<((u8, u8), Span)>,
    pub(super) swing: &'a mut Option<(crate::compiler::ast::Swing, Span)>,
    pub(super) diags: &'a mut Vec<Diagnostic>,
}

/// 指令の名前の一覧(診断の文に使う)。
pub(super) const DIRECTIVES: &str =
    "#dialect, #synth, #frame, #meter, #swing, #include, #title, #composer, #copyright, #artist, #comment";

/// 空白で区切った語と、その位置(列は 1 始まり)。
type Words = Vec<(String, Span)>;

/// 指令の行(`#dialect`、`#synth`)を処理する。
pub(super) fn directive(chars: &[char], start: usize, line: u32, st: &mut DirectiveState<'_>) {
    let mut words = split_words(chars, start, line);
    let (head, head_span) = words.remove(0);
    let mut name = head[1..].to_string();
    // 曲の情報はゆるい方言では大文字小文字を区別しない(`#TITLE` など)
    if st.dialect.case_insensitive {
        let lower = name.to_ascii_lowercase();
        if crate::compiler::song::SongMeta::NAMES.contains(&lower.as_str()) {
            name = lower;
        }
    }
    let name = name.as_str();
    let known = matches!(name, "dialect" | "synth" | "frame" | "meter" | "swing")
        || crate::compiler::song::SongMeta::NAMES.contains(&name);
    if st.body_started && known {
        st.diags.push(Diagnostic::error(
            codes::DIRECTIVE_NOT_AT_TOP,
            head_span,
            msg!("E0217-position", name = name),
        ));
        return;
    }
    match name {
        "dialect" => st.dialect(head_span, &words),
        "synth" => st.synth(head_span, &words),
        "meter" => st.meter(head_span, &words),
        "frame" => st.frame(head_span, &words),
        "swing" => st.swing(head_span, &words),
        _ if crate::compiler::song::SongMeta::NAMES.contains(&name) => {
            st.meta(chars, name, head_span)
        }
        "chip" => {
            // 音源を選ぶ指令は `#synth`。以前の名前は、黙って既定の音源で鳴らさないよう
            // どの方言でも誤りにして、書き換え先を候補に出す
            st.diags.push(
                Diagnostic::error(
                    codes::UNKNOWN_DIRECTIVE,
                    head_span,
                    msg!("E0215-renamed", name = name, new = "synth"),
                )
                .with_suggestion("#synth"),
            );
        }
        _ => st.unknown(name, head_span),
    }
}

/// 行を空白で区切った語にする(先頭は `#名前`)。
fn split_words(chars: &[char], start: usize, line: u32) -> Words {
    let mut words: Words = Vec::new();
    let mut i = start;
    while i < chars.len() {
        if chars[i].is_whitespace() {
            i += 1;
            continue;
        }
        let b = i;
        while i < chars.len() && !chars[i].is_whitespace() {
            i += 1;
        }
        words.push((
            chars[b..i].iter().collect(),
            Span::new(line, b as u32 + 1, (i - b) as u32),
        ));
    }
    words
}

impl DirectiveState<'_> {
    /// `#dialect 名前`:以降の行の読み方を変える。
    fn dialect(&mut self, head_span: Span, words: &Words) {
        if let Some(prev) = self.dialect_set {
            self.diags.push(Diagnostic::error(
                codes::DUPLICATE_DIRECTIVE,
                head_span,
                msg!("E0218-dialect", line = prev.line),
            ));
            return;
        }
        let names: Vec<&str> = Dialect::BUILTIN.iter().map(|d| d.name).collect();
        let Some((arg, arg_span)) = words.first() else {
            self.diags.push(
                Diagnostic::error(
                    codes::UNKNOWN_DIALECT,
                    head_span,
                    msg!("E0216-missing", names = names.join(", ")),
                )
                .with_suggestion("#dialect pikopiko"),
            );
            return;
        };
        match Dialect::builtin(arg) {
            Some(d) => {
                *self.dialect = d;
                *self.dialect_set = Some(head_span);
            }
            None => {
                let mut d = Diagnostic::error(
                    codes::UNKNOWN_DIALECT,
                    *arg_span,
                    msg!("E0216-unknown", name = arg, names = names.join(", ")),
                );
                if let Some(n) = crate::nearest(arg, &names) {
                    d = d.with_suggestion(n);
                }
                self.diags.push(d);
            }
        }
    }

    /// `#synth 名前 キー=値 …`:音源とオプション。名前とオプションの検査は展開(`#synth` の決定)で行う。
    fn synth(&mut self, head_span: Span, words: &Words) {
        if self.synth.is_some() {
            self.diags.push(Diagnostic::error(
                codes::DUPLICATE_DIRECTIVE,
                head_span,
                msg!("E0218-synth"),
            ));
            return;
        }
        let Some((arg, arg_span)) = words.first().cloned() else {
            self.diags.push(
                Diagnostic::error(codes::UNKNOWN_SYNTH, head_span, msg!("E0501-missing"))
                    .with_suggestion("#synth basic"),
            );
            return;
        };
        let options = words[1..]
            .iter()
            .map(|(w, sp)| match w.split_once('=') {
                Some((k, v)) => (k.to_string(), v.to_string(), *sp),
                None => (w.clone(), String::new(), *sp),
            })
            .collect();
        *self.synth = Some(SynthDirective {
            name: arg,
            name_span: arg_span,
            options,
            span: head_span,
        });
    }

    /// `#meter 拍の数/拍の音符`:拍子(拍・小節の通知とマーカーへの移動に使う)。
    fn meter(&mut self, head_span: Span, words: &Words) {
        if let Some((_, prev)) = self.meter {
            self.diags.push(Diagnostic::error(
                codes::DUPLICATE_DIRECTIVE,
                head_span,
                msg!("E0218-meter", line = prev.line),
            ));
            return;
        }
        let value = words.first().and_then(|(w, _)| {
            let (n, d) = w.split_once('/')?;
            let n: u8 = n.parse().ok()?;
            let d: u8 = d.parse().ok()?;
            ((1..=32).contains(&n) && matches!(d, 1 | 2 | 4 | 8 | 16 | 32)).then_some((n, d))
        });
        match value {
            Some(v) if words.len() == 1 => *self.meter = Some((v, head_span)),
            _ => {
                let span = words.first().map(|(_, s)| *s).unwrap_or(head_span);
                self.diags.push(
                    Diagnostic::error(codes::BAD_DIRECTIVE_VALUE, span, msg!("E0228-meter"))
                        .with_suggestion("#meter 3/4"),
                );
            }
        }
    }

    /// `#swing 8 62`:曲全体のスウィング(粒度 8 か 16、前の音の割合 50〜75%)。
    /// トラックごとに `@swing` で変えられる。
    fn swing(&mut self, head_span: Span, words: &Words) {
        if let Some((_, prev)) = self.swing {
            self.diags.push(Diagnostic::error(
                codes::DUPLICATE_DIRECTIVE,
                head_span,
                msg!("E0218-swing", line = prev.line),
            ));
            return;
        }
        let value = match words.as_slice() {
            [(u, _), (p, _)] => match (u.parse::<u8>(), p.parse::<u8>()) {
                (Ok(unit), Ok(percent))
                    if crate::compiler::ast::Swing::UNITS.contains(&unit)
                        && crate::compiler::ast::Swing::PERCENT.contains(&percent) =>
                {
                    Some(crate::compiler::ast::Swing { unit, percent })
                }
                _ => None,
            },
            _ => None,
        };
        match value {
            Some(v) => *self.swing = Some((v, head_span)),
            None => {
                let span = words.first().map(|(_, s)| *s).unwrap_or(head_span);
                self.diags.push(
                    Diagnostic::error(codes::BAD_DIRECTIVE_VALUE, span, msg!("E0228-swing"))
                        .with_suggestion("#swing 8 62"),
                );
            }
        }
    }

    /// `#frame 50`:エンベロープなどの 1 フレームの長さ(1 秒あたりのフレーム数)。
    fn frame(&mut self, head_span: Span, words: &Words) {
        if let Some((_, prev)) = self.frame {
            self.diags.push(Diagnostic::error(
                codes::DUPLICATE_DIRECTIVE,
                head_span,
                msg!("E0218-frame", line = prev.line),
            ));
            return;
        }
        let rates = pikopiko_runtime::envelope::FRAME_RATES;
        let value = words
            .first()
            .and_then(|(w, _)| w.parse::<u8>().ok())
            .filter(|v| rates.contains(v));
        match value {
            Some(v) if words.len() == 1 => *self.frame = Some((v, head_span)),
            _ => {
                let span = words.first().map(|(_, s)| *s).unwrap_or(head_span);
                self.diags.push(
                    Diagnostic::error(codes::BAD_DIRECTIVE_VALUE, span, msg!("E0228-frame"))
                        .with_suggestion("#frame 50"),
                );
            }
        }
    }

    /// 曲の情報(`#title` など)。値は語に分けず、指令の名前の後ろから行末まで。
    /// `#comment` だけは何度でも書け、改行でつなぐ。
    fn meta(&mut self, chars: &[char], name: &str, head_span: Span) {
        let key = crate::compiler::song::SongMeta::NAMES
            .iter()
            .find(|n| **n == name)
            .copied()
            .unwrap_or("title");
        // 値は指令の名前の後ろから行末まで(前後の空白を除く)
        let head_end = (head_span.col - 1 + head_span.len) as usize;
        let value: String = chars[head_end.min(chars.len())..]
            .iter()
            .collect::<String>()
            .trim()
            .to_string();
        if value.is_empty() {
            self.diags.push(Diagnostic::error(
                codes::BAD_DIRECTIVE_VALUE,
                head_span,
                msg!("E0228-value-missing", key = key),
            ));
            return;
        }
        if key != "comment" {
            if let Some((_, prev)) = self.meta_set.iter().find(|(k, _)| *k == key) {
                self.diags.push(Diagnostic::error(
                    codes::DUPLICATE_DIRECTIVE,
                    head_span,
                    msg!("E0218-twice", key = key, line = prev.line),
                ));
                return;
            }
        }
        self.meta_set.push((key, head_span));
        if let Some(slot) = self.meta.slot(key) {
            match slot {
                Some(prev) => {
                    prev.push('\n');
                    prev.push_str(&value);
                }
                None => *slot = Some(value),
            }
        }
    }

    /// 知らない指令。ゆるい方言ではほかのツール用の指令として警告だけにし、厳密な方言では誤り。
    fn unknown(&mut self, name: &str, head_span: Span) {
        if self.dialect.case_insensitive {
            // ゆるい方言では、ほかのツール用の指令(#TITLE など)を読み飛ばす
            self.diags.push(Diagnostic::warning(
                codes::IGNORED_DIRECTIVE,
                head_span,
                msg!("W0102-unknown", name = name, names = DIRECTIVES),
            ));
        } else {
            self.diags.push(Diagnostic::error(
                codes::UNKNOWN_DIRECTIVE,
                head_span,
                msg!("E0215-unknown", name = name, names = DIRECTIVES),
            ));
        }
    }
}