pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! サブコマンドの中身(`check` `info` `render` `play` `build` `synths` `library`(`--check` は `library_check`) `tone` `dx7`)。
//!
//! サブコマンドごとに 1 つのファイルにし、入口(`main.rs` の `run`)から呼ぶ関数だけを出す。
//! このファイルには、いくつかのサブコマンドで使う部品(検査 `compile`・診断の表示
//! `print_diagnostics`・音源を作る `create_synth`・書き出しと JSON のエラーの文)を置く。
//! 表示の文は `main.rs` の `t`・`ta`(`locales/<言語>/cli.ftl`)で作り、`to_string()` の文は出さない。

use super::*;

mod build;
mod check;
mod dx7;
mod fmt;
mod info;
mod library;
mod library_check;
mod play;
mod render;
mod synths;
mod tone;

pub(super) use build::build;
pub(super) use check::check;
pub(super) use dx7::dx7;
pub(super) use fmt::fmt;
pub(super) use info::info;
pub(super) use library::library;
pub(super) use library_check::library_check;
pub(super) use play::play;
pub(super) use render::render;
pub(super) use synths::synths;
pub(super) use tone::{tone, ToneArgs, ToneReference};

pub(super) fn counts(d: &[Diagnostic]) -> (usize, usize) {
    let e = d.iter().filter(|d| d.severity == Severity::Error).count();
    (e, d.len() - e)
}

/// 曲が選んだ音源の実体を作る(`pikopiko::synth::all()` の中から)。
pub(super) fn create_synth(song: &pikopiko::Song, sample_rate: u32) -> Box<dyn pikopiko::Synth> {
    pikopiko::synth::create(
        pikopiko::synth::all(),
        &song.synth,
        sample_rate,
        song.tracks.len(),
    )
}

pub(super) fn compile(src: &str, o: &Opts) -> (Option<pikopiko::Song>, Vec<Diagnostic>) {
    // `#include` は入力ファイルのフォルダーから(標準入力なら今いるフォルダーから)
    let files = match o.file.as_deref() {
        Some(p) if p != "-" => pikopiko::compiler::include::Files::beside(p),
        _ => pikopiko::compiler::include::Files::new("."),
    };
    // 利用者の音色集(`#include "@名前/種類"`)は、ファイルの読み込みの口に包んで渡す
    let with_libs = pikopiko::synth::tones::user::WithLibraries::new(Some(&files), &o.libs);
    let opts = CompileOptions {
        dialect: o.dialect,
        synths: pikopiko::synth::all(),
        include: Some(&with_libs),
        ..Default::default()
    };
    compile_with(src, &opts)
}

/// rustc 風に、該当行と位置の印を付けて表示する。
///
/// メッセージは表示の言語で(文のキーと値から、その言語の表で作る)。
/// 修正候補は MML の書き方なので、どの言語でも出す。
pub(super) fn print_diagnostics(src: &str, path: &str, diags: &[Diagnostic]) {
    let lines: Vec<&str> = src.lines().collect();
    let tr = i18n();
    let suggestion_label = t("cli-diag-suggestion");
    for d in diags {
        let message = tr.diagnostic(d);
        let suggestion = d.suggestion.as_ref();
        let sev = match d.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
        };
        eprintln!("{sev}[{}]: {message}", d.code);
        // 読み込んだもの(`#include`)の中の診断は、そのファイルの位置を出す(行の抜き出しはしない)
        if let Some(file) = &d.file {
            eprintln!("  --> {}:{}:{}", file, d.span.line, d.span.col);
            if let Some(s) = suggestion {
                eprintln!("   = {suggestion_label}: {s}");
            }
            eprintln!();
            continue;
        }
        eprintln!("  --> {}:{}:{}", path, d.span.line, d.span.col);
        if let Some(line) = lines.get((d.span.line as usize).wrapping_sub(1)) {
            let prefix: String = line
                .chars()
                .take(d.span.col.saturating_sub(1) as usize)
                .map(|c| {
                    if c == '\t' {
                        '\t'
                    } else if c.is_ascii() {
                        ' '
                    } else {
                        ' '
                    }
                })
                .collect();
            eprintln!("   | {line}");
            eprintln!("   | {prefix}{}", "^".repeat(d.span.len.max(1) as usize));
        }
        if let Some(s) = suggestion {
            eprintln!("   = {suggestion_label}: {s}");
        }
        eprintln!();
    }
}

pub(super) fn write_error(path: &str, e: std::io::Error) -> String {
    ta(
        "cli-err-write-file",
        &[("path", path.into()), ("error", i18n().io_error(&e).into())],
    )
}

/// JSON にできなかった(このプログラムの型からは起きない)。serde_json の文(英語)は出さない。
pub(super) fn json_error(_: serde_json::Error) -> String {
    t("cli-err-json")
}