ch32rv 0.40.0

Flashing and debugging tool for WCH CH32 RISC-V microcontrollers
//! en: Started with OpenOCD's arguments, ch32rv is OpenOCD's GDB server (docs/cli.ja.md §4.6):
//! an IDE that only knows how to start OpenOCD (arduino-cli `debug`, Arduino IDE 2 through
//! cortex-debug) runs ch32rv in its place. The arguments are turned into a `ch32rv gdb` command
//! line before clap sees them:
//!
//! - `-c "gdb_port pipe"`: RSP on stdin/stdout (`--pipe`); `-c "gdb_port N"`: TCP port N, with
//!   OpenOCD's `Info : Listening on port N for gdb connections` line; `-c "bindto HOST"`: the
//!   address to listen on (default 127.0.0.1). Other commands (`telnet_port`, `tcl_port`, `init`,
//!   cortex-debug's own) are ignored.
//! - `-f` / `--file` values of the form `ch32rv:chip=<chip>`, `ch32rv:probe=<address>`,
//!   `ch32rv:speed=<speed>` name the chip, the probe and the speed (an empty value, or one
//!   arduino-cli left unexpanded like `{debug.port}`, is none: the only probe there is). Other files (OpenOCD scripts, cortex-debug's helpers) are not read.
//! - `-s` / `--search`, `-d<N>`, `-l` / `--log_output` are taken and ignored.
//!
//! ja: OpenOCD の引数で起動すると、OpenOCD の GDB server として動く。OpenOCD しか起動できない IDE
//! (arduino-cli の debug、cortex-debug 経由の Arduino IDE 2)が代わりに ch32rv を起動する。引数は clap の
//! 前に `ch32rv gdb` のコマンド行へ読み替える。`-c "gdb_port pipe"` は stdin/stdout、`-c "gdb_port N"`
//! は TCP の N(OpenOCD の待ち受けの行を出す)、`-f` の `ch32rv:chip=` / `ch32rv:probe=` /
//! `ch32rv:speed=` で chip と probe と速度。ほかの `-c` とファイルは読まない。

use std::ffi::OsString;

/// en: The options that start an OpenOCD command line (never a ch32rv one: ch32rv's commands come
/// first, and its only short options are `-v` / `-q`). ja: OpenOCD のコマンド行の始まりの option。
fn starts_openocd(first: &str) -> bool {
    matches!(
        first,
        "-f" | "--file" | "-s" | "--search" | "-c" | "--command" | "-l" | "--log_output"
    ) || (first.starts_with("-d") && first[2..].chars().all(|c| c.is_ascii_digit()))
}

/// en: The `ch32rv gdb` command line for an OpenOCD one, or None when `argv` is not OpenOCD's.
/// ja: OpenOCD のコマンド行を `ch32rv gdb` のものへ。OpenOCD のものでなければ None。
pub(crate) fn translate(argv: &[OsString]) -> Option<Vec<OsString>> {
    let args: Vec<String> = argv
        .iter()
        .skip(1)
        .map(|a| a.to_string_lossy().into_owned())
        .collect();
    let named_openocd = argv.first().is_some_and(|a| {
        std::path::Path::new(a)
            .file_stem()
            .is_some_and(|s| s.to_string_lossy().eq_ignore_ascii_case("openocd"))
    });
    if !named_openocd && !args.first().is_some_and(|a| starts_openocd(a)) {
        return None;
    }
    let mut commands = Vec::new();
    let mut files = Vec::new();
    let mut it = args.into_iter();
    while let Some(a) = it.next() {
        match a.as_str() {
            "-c" | "--command" => commands.extend(it.next()),
            "-f" | "--file" => files.extend(it.next()),
            "-s" | "--search" | "-l" | "--log_output" => {
                it.next();
            }
            _ => {} // -d<N> and anything else OpenOCD would take
        }
    }
    let mut port = String::from("3333");
    let mut host = String::from("127.0.0.1");
    for c in commands.iter().flat_map(|c| c.split([';', '\n'])) {
        let words: Vec<&str> = c.split_whitespace().collect();
        match words.as_slice() {
            ["gdb_port", p] => port = (*p).to_owned(),
            ["bindto", h] => host = (*h).to_owned(),
            _ => {}
        }
    }
    let mut out: Vec<OsString> = vec![
        argv.first().cloned().unwrap_or_else(|| "ch32rv".into()),
        "--non-interactive".into(),
    ];
    for f in &files {
        let Some(kv) = f.strip_prefix("ch32rv:") else {
            continue;
        };
        let Some((k, v)) = kv.split_once('=') else {
            continue;
        };
        let v = v.trim();
        // en: Empty, or a property arduino-cli left unexpanded (`{debug.port}` without `-p`): none.
        // ja: 空か、arduino-cli が展開しなかったプロパティ(`-p` 無しの `{debug.port}`)は指定なし。
        if v.is_empty() || (v.starts_with('{') && v.ends_with('}')) {
            continue;
        }
        match k.trim() {
            "chip" => out.extend(["--chip".into(), v.into()]),
            "probe" => out.extend(["--probe".into(), v.into()]),
            "speed" => out.extend(["--speed".into(), v.into()]),
            _ => {}
        }
    }
    out.extend(["gdb".into(), "--openocd".into()]);
    if port == "pipe" {
        out.push("--pipe".into());
    } else {
        let addr = if host.contains(':') {
            format!("[{host}]:{port}")
        } else {
            format!("{host}:{port}")
        };
        out.extend(["--listen".into(), addr.into()]);
    }
    Some(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn t(args: &[&str]) -> Option<Vec<String>> {
        let argv: Vec<OsString> = args.iter().map(OsString::from).collect();
        translate(&argv).map(|v| {
            v.into_iter()
                .map(|a| a.to_string_lossy().into_owned())
                .collect()
        })
    }

    #[test]
    fn arduino_cli_pipe() {
        // arduino-cli: target extended-remote | "<path>" -s .. --file .. -c "gdb_port pipe" ..
        let v = t(&[
            "/x/ch32rv",
            "-s",
            "/core/debug",
            "--file",
            "/core/debug/ch32rv.cfg",
            "--file",
            "ch32rv:chip=CH32V203C8T6",
            "--file",
            "ch32rv:probe=",
            "-c",
            "gdb_port pipe",
            "-c",
            "telnet_port 0",
        ])
        .unwrap_or_default();
        assert_eq!(
            v,
            [
                "/x/ch32rv",
                "--non-interactive",
                "--chip",
                "CH32V203C8T6",
                "gdb",
                "--openocd",
                "--pipe"
            ]
        );
    }

    #[test]
    fn cortex_debug_tcp() {
        let v = t(&[
            "ch32rv.exe",
            "-f",
            "C:/ext/support/openocd-helpers.tcl",
            "-c",
            "gdb_port 50000",
            "-c",
            "tcl_port 50001",
            "-c",
            "telnet_port 50002",
            "-s",
            "C:/core/debug",
            "-f",
            "C:/core/debug/ch32rv.cfg",
            "-f",
            "ch32rv:chip=CH32X035G8U6",
            "-f",
            "ch32rv:probe=oep://0070070d9394/weact",
            "-c",
            "CDLiveWatchSetup",
        ])
        .unwrap_or_default();
        assert_eq!(
            v,
            [
                "ch32rv.exe",
                "--non-interactive",
                "--chip",
                "CH32X035G8U6",
                "--probe",
                "oep://0070070d9394/weact",
                "gdb",
                "--openocd",
                "--listen",
                "127.0.0.1:50000"
            ]
        );
    }

    #[test]
    fn not_openocd() {
        assert_eq!(t(&["ch32rv", "flash", "a.elf"]), None);
        assert_eq!(t(&["ch32rv", "-v", "probe", "list"]), None);
        assert_eq!(t(&["ch32rv"]), None);
        // Named openocd: OpenOCD's defaults.
        let v = t(&["/usr/bin/openocd"]).unwrap_or_default();
        assert_eq!(v[2..], ["gdb", "--openocd", "--listen", "127.0.0.1:3333"]);
        let v = t(&["ch32rv", "-d3", "-c", "gdb_port 4444; bindto 0.0.0.0"]).unwrap_or_default();
        assert!(
            v.ends_with(&["--listen".to_owned(), "0.0.0.0:4444".to_owned()]),
            "{v:?}"
        );
        // A property arduino-cli left unexpanded (no `-p`: `{debug.port}`) is no value.
        let v = t(&[
            "ch32rv",
            "-f",
            "ch32rv:probe={debug.port}",
            "-c",
            "gdb_port pipe",
        ])
        .unwrap_or_default();
        assert!(!v.iter().any(|a| a == "--probe"), "{v:?}");
    }
}