pikopiko 0.1.0

MML parser, compiler and chiptune player for games, with diagnostics designed for tools and AI.
Documentation
//! MML の整形(空白と折り返しだけ。意味は変えない)。
//!
//! 手で書いた曲と AI が書いた曲で、空白・改行・コメントの書き方が揃わないと、差分が読みにくく
//! 取扱説明書の見本もそろわない。[`format`] は、**書かれた文字を並べ直すだけ**で、展開した後の曲
//! (イベント・テンポ・音色・マーカーなど)が整形の前後で同じになることを約束する。
//!
//! 約束の守り方:書き換えは次の 3 つの段階に分け、そのたびに整形後のテキストを同じ設定で
//! コンパイルし、**ソース位置を除いた**曲が元と等しいことを確かめる。等しくなければその段階を
//! 取り消す(誤った整形を返すより、整形しない方を選ぶ)。
//!
//! 1. 行末の空白・タブ・改行コード(`\r\n`)、行の前後の空白を整える。連続する空行は 1 行にし、
//!    先頭の空行は消し、末尾は改行 1 つにする。
//! 2. トラック行(行頭が大文字 `A`〜`Z` で、空白が続く行)の、トラック名と中身の間と、中身の
//!    コマンドの間の連続する空白を 1 つにする(`'…'` の中と `;` 以降のコメントは触らない)。
//! 3. 1 行が `width` 文字を超えるトラック行を、空白のところで折り返す。続きの行には同じトラック名を
//!    付ける(同じトラック名の行は上から順につながるので意味は変わらない)。コメント付きの行、
//!    `'…'` と `{…}` の中は折り返さない。折り返しは行ごとに試して、曲が変わる行は折り返さない。
//!
//! 4. ([`FormatOptions::normalize`] が真のときだけ)省略記法 `mp` `mpof` `ep` `epof` `en` `enof` を
//!    `@` の形(`@vib 名前`・`@vib off` など)に書き換える。行ごとに試し、曲が変わる行は戻す。
//!    classic 方言の標準方言への変換は未実装。
//!
//! 指令行・マクロ定義・エンベロープ定義などの行の中身には触れない(値の空白に意味があるため)。
//! 元のテキストに誤りがあるときは、その診断を `Err` で返す。

use crate::{compile_with, CompileOptions, Diagnostic, Song, Span};

/// [`format()`] の設定。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FormatOptions {
    /// 折り返す幅(文字数)。既定は 100。0 なら折り返さない。
    pub width: usize,
    /// 省略記法を `@` の形にそろえる(既定は偽)。
    pub normalize: bool,
}

impl Default for FormatOptions {
    fn default() -> Self {
        Self {
            width: 100,
            normalize: false,
        }
    }
}

/// `src` を整形したテキストを返す(説明はモジュールの先頭)。
///
/// 整形しても変わらないテキストは、そのまま同じものが返る(冪等)。
pub fn format(
    src: &str,
    fmt: &FormatOptions,
    opts: &CompileOptions<'_>,
) -> Result<String, Vec<Diagnostic>> {
    let (song, diags) = compile_with(src, opts);
    let Some(original) = song else {
        return Err(diags.into_iter().filter(|d| d.is_error()).collect());
    };
    let reference = strip(&original);
    let same = |text: &str| -> bool {
        compile_with(text, opts)
            .0
            .is_some_and(|s| strip(&s) == reference)
    };

    // 段階 1・2
    let mut best = src.to_string();
    let tidied = tidy(src);
    if same(&tidied) {
        best = tidied;
    }
    let spaced = tidy_with_spaces(&best);
    if same(&spaced) {
        best = spaced;
    }
    // 段階 4(正規化)。折り返しの前にやる(語が増えるため)
    if fmt.normalize {
        best = normalize_lines(&best, &same);
    }
    // 段階 3
    if fmt.width > 0 {
        best = wrap_lines(&best, fmt.width, &same);
    }
    Ok(best)
}

/// ソース位置を零にした曲(比較のため)。ショットの中の曲も同じにする。
fn strip(song: &Song) -> Song {
    let mut s = song.clone();
    for e in &mut s.events {
        e.span = Span::default();
    }
    for shot in &mut s.shots {
        *shot.song = strip(&shot.song);
    }
    s
}

/// 行を「コード」と「`;` 以降のコメント」に分ける(コメントは `;` を含む)。
fn split_comment(line: &str) -> (&str, &str) {
    match line.find(';') {
        Some(i) => line.split_at(i),
        None => (line, ""),
    }
}

/// トラック行なら、トラック名の部分(`AB` など)の長さを返す。
fn track_name_len(code: &str) -> Option<usize> {
    let n = code.chars().take_while(|c| c.is_ascii_uppercase()).count();
    let rest = &code[n..];
    (n > 0 && rest.starts_with([' ', '\t'])).then_some(n)
}

/// 段階 1:行末の空白・改行コード・空行を整える。
fn tidy(src: &str) -> String {
    let mut out = String::new();
    let mut blank = 0;
    for raw in src.lines() {
        let line = raw.trim_end();
        if line.is_empty() {
            blank += 1;
            continue;
        }
        if blank > 0 && !out.is_empty() {
            out.push('\n');
        }
        blank = 0;
        out.push_str(line);
        out.push('\n');
    }
    out
}

/// 段階 2:トラック行の空白を 1 つにする。
fn tidy_with_spaces(src: &str) -> String {
    let mut out = String::new();
    for line in src.split_inclusive('\n') {
        let body = line.strip_suffix('\n').unwrap_or(line);
        out.push_str(&squeeze_line(body));
        if line.ends_with('\n') {
            out.push('\n');
        }
    }
    out
}

fn squeeze_line(line: &str) -> String {
    let (code, comment) = split_comment(line);
    let Some(n) = track_name_len(code) else {
        return line.to_string();
    };
    let (name, body) = code.split_at(n);
    let mut s = String::from(name);
    let mut in_quote = false;
    let mut pending_space = false;
    let mut started = false;
    for c in body.chars() {
        if c == '\'' {
            in_quote = !in_quote;
        }
        if !in_quote && c.is_whitespace() {
            pending_space = true;
            continue;
        }
        if pending_space {
            s.push(' ');
            pending_space = false;
        }
        started = true;
        s.push(c);
    }
    if !comment.is_empty() {
        // コードとコメントの間は空白 2 つ(コードがなければコメントだけの行)
        if started {
            s.push_str("  ");
        }
        s.push_str(comment.trim_end());
    }
    s
}

/// 折り返せる位置(コードの中の、空白を置いたバイト位置)を返す。`'…'` と `{…}` の中は除く。
fn break_points(body: &str) -> Vec<usize> {
    let mut v = Vec::new();
    let (mut quote, mut brace) = (false, 0i32);
    for (i, c) in body.char_indices() {
        match c {
            '\'' => quote = !quote,
            '{' if !quote => brace += 1,
            '}' if !quote => brace -= 1,
            ' ' if !quote && brace == 0 => v.push(i),
            _ => {}
        }
    }
    v
}

/// 段階 3:長いトラック行を折り返す。行ごとに試し、`same` が偽になる行は戻す。
fn wrap_lines(src: &str, width: usize, same: &dyn Fn(&str) -> bool) -> String {
    let lines: Vec<String> = src.lines().map(str::to_string).collect();
    let mut current = lines.clone();
    for i in 0..lines.len() {
        let line = &lines[i];
        if line.chars().count() <= width || line.contains(';') {
            continue;
        }
        let Some(n) = track_name_len(line) else {
            continue;
        };
        let name = &line[..n];
        let body = &line[n + 1..];
        let points = break_points(body);
        // 貪欲に詰める:幅(名前と空白の分を含む)を超える手前の空白で切る
        let head = n + 1;
        let mut pieces: Vec<&str> = Vec::new();
        let mut start = 0;
        let mut last_ok: Option<usize> = None;
        for &p in &points {
            if head + body[start..p].chars().count() > width {
                if let Some(l) = last_ok.take() {
                    pieces.push(&body[start..l]);
                    start = l + 1;
                    if head + body[start..p].chars().count() > width {
                        last_ok = Some(p);
                        continue;
                    }
                }
            }
            last_ok = Some(p);
        }
        pieces.push(&body[start..]);
        if pieces.len() < 2 {
            continue;
        }
        let wrapped = pieces
            .iter()
            .map(|p| format!("{name} {p}"))
            .collect::<Vec<_>>()
            .join("\n");
        let saved = current[i].clone();
        current[i] = wrapped;
        let mut text = current.join("\n");
        text.push('\n');
        if !same(&text) {
            current[i] = saved;
        }
    }
    let mut text = current.join("\n");
    if !text.is_empty() {
        text.push('\n');
    }
    text
}

/// 省略記法の語と、`@` の形での書き方。
const ABBREVIATIONS: &[(&str, &str)] = &[
    ("mpof", "@vib off"),
    ("epof", "@detune off"),
    ("enof", "@arp off"),
    ("mp", "@vib"),
    ("ep", "@detune"),
    ("en", "@arp"),
];

/// トラック行のコード部分の省略記法を `@` の形にする。変えたところがなければ `None`。
/// 英小文字の連なり(語)を見て、語が省略記法そのものか、音符・休符の文字(`a`〜`g`・`r`)1 つに
/// 省略記法が続く形(`cmp slow`=`c` と `mp slow`)のときだけ書き換える。`'…'` の中、`$`・`@`・`%`・`!`
/// の直後の名前、英数字や `_` に続く語は触らない。
fn normalize_code(code: &str) -> Option<String> {
    let chars: Vec<char> = code.chars().collect();
    let mut out = String::new();
    let mut changed = false;
    let mut in_quote = false;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];
        if c == '\'' {
            in_quote = !in_quote;
        }
        if in_quote || !c.is_ascii_lowercase() {
            out.push(c);
            i += 1;
            continue;
        }
        let start = i;
        while i < chars.len() && chars[i].is_ascii_lowercase() {
            i += 1;
        }
        let word: String = chars[start..i].iter().collect();
        let prev = start.checked_sub(1).map(|p| chars[p]);
        let named = prev
            .is_some_and(|p| matches!(p, '$' | '@' | '%' | '!' | '_') || p.is_ascii_alphanumeric());
        let next_ok = chars
            .get(i)
            .is_none_or(|n| !(n.is_ascii_alphanumeric() || *n == '_'));
        let replaced = if named || !next_ok {
            None
        } else {
            ABBREVIATIONS.iter().find_map(|(short, long)| {
                if word == *short {
                    Some((String::new(), *long))
                } else {
                    let head = word.strip_suffix(short)?;
                    (head.len() == 1 && "abcdefgr".contains(head))
                        .then(|| (format!("{head} "), *long))
                }
            })
        };
        match replaced {
            Some((head, long)) => {
                out.push_str(&head);
                out.push_str(long);
                changed = true;
            }
            None => out.push_str(&word),
        }
    }
    changed.then_some(out)
}

/// 段階 4:トラック行の省略記法を `@` の形にする。行ごとに試し、`same` が偽になる行は戻す。
fn normalize_lines(src: &str, same: &dyn Fn(&str) -> bool) -> String {
    let lines: Vec<String> = src.lines().map(str::to_string).collect();
    let mut current = lines.clone();
    let join = |v: &[String]| {
        let mut t = v.join("\n");
        if !t.is_empty() {
            t.push('\n');
        }
        t
    };
    for i in 0..lines.len() {
        let (code, comment) = split_comment(&lines[i]);
        if track_name_len(code).is_none() {
            continue;
        }
        let Some(new_code) = normalize_code(code) else {
            continue;
        };
        let saved = current[i].clone();
        current[i] = format!("{new_code}{comment}");
        if !same(&join(&current)) {
            current[i] = saved;
        }
    }
    join(&current)
}