xur-std 0.1.4

The standard library of the Xur language
Documentation
//! `std::io`: printing.

use facet::Facet;
use xur_runtime::registry::XurType;
use xur_runtime::{Context, Registry, RunResult, RuntimeError, Value};

use crate::fmt::format;

/// A recoverable I/O error. Shared across the I/O modules (`std::fs`,
/// `std::net`, `std::path`, …) so a script handles one error type; match it as
/// `Err(io::Error::NotFound)` etc. Build one with `io::Error::from(std::io::Error)`.
#[derive(Clone, Facet)]
#[repr(C)]
pub enum Error {
    NotFound,
    PermissionDenied,
    AlreadyExists,
    InvalidInput,
    UnexpectedEof,
    Interrupted,
    /// Any other I/O error, carrying its message.
    Other(String),
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        use std::io::ErrorKind;
        match e.kind() {
            ErrorKind::NotFound => Error::NotFound,
            ErrorKind::PermissionDenied => Error::PermissionDenied,
            ErrorKind::AlreadyExists => Error::AlreadyExists,
            ErrorKind::InvalidInput | ErrorKind::InvalidData => Error::InvalidInput,
            ErrorKind::UnexpectedEof => Error::UnexpectedEof,
            ErrorKind::Interrupted => Error::Interrupted,
            _ => Error::Other(e.to_string()),
        }
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::NotFound => f.write_str("not found"),
            Error::PermissionDenied => f.write_str("permission denied"),
            Error::AlreadyExists => f.write_str("already exists"),
            Error::InvalidInput => f.write_str("invalid input"),
            Error::UnexpectedEof => f.write_str("unexpected end of file"),
            Error::Interrupted => f.write_str("interrupted"),
            Error::Other(m) => f.write_str(m),
        }
    }
}

pub(crate) fn register(registry: &Registry) {
    let mut m = registry.module("std::io");
    m.ty::<Error>("Error");
    m.named_raw_function_returns_xur("print", &["format", "args"], XurType::UNIT, |cx, args| {
        print(cx, args, "")
    })
    .named_raw_function_returns_xur("println", &["format", "args"], XurType::UNIT, |cx, args| {
        print(cx, args, "\n")
    })
    .named_raw_function_returns_xur("eprint", &["format", "args"], XurType::UNIT, |cx, args| {
        eprint(cx, args, "")
    })
    .named_raw_function_returns_xur(
        "eprintln",
        &["format", "args"],
        XurType::UNIT,
        |cx, args| eprint(cx, args, "\n"),
    );
    registry
        .module("std::io::c")
        .named_function("red", &["text"], |s: String| format!("\x1b[31m{s}\x1b[0m"))
        .named_function("green", &["text"], |s: String| {
            format!("\x1b[32m{s}\x1b[0m")
        })
        .named_function("yellow", &["text"], |s: String| {
            format!("\x1b[33m{s}\x1b[0m")
        })
        .named_function("blue", &["text"], |s: String| format!("\x1b[34m{s}\x1b[0m"))
        .named_function("magenta", &["text"], |s: String| {
            format!("\x1b[35m{s}\x1b[0m")
        })
        .named_function("cyan", &["text"], |s: String| format!("\x1b[36m{s}\x1b[0m"))
        .named_function("bold", &["text"], |s: String| format!("\x1b[1m{s}\x1b[0m"))
        .named_function("dim", &["text"], |s: String| format!("\x1b[2m{s}\x1b[0m"));
}

/// `print(format, args...)`: each `{}` in `format` is replaced by the next
/// argument; `{{` and `}}` write literal braces.
fn print(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
    let Some((Value::Str(template), args)) = args.split_first() else {
        return Err(RuntimeError::new(
            "expected a format string as the first argument",
        ));
    };
    let mut text = if args.is_empty() {
        template.to_string()
    } else {
        format(cx, template, args)?
    };
    text.push_str(end);
    cx.print(&text)?;
    Ok(Value::Unit)
}

fn eprint(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
    let Some((Value::Str(template), args)) = args.split_first() else {
        return Err(RuntimeError::new(
            "expected a format string as the first argument",
        ));
    };
    let mut text = if args.is_empty() {
        template.to_string()
    } else {
        format(cx, template, args)?
    };
    text.push_str(end);
    cx.eprint(&text)?;
    Ok(Value::Unit)
}

#[cfg(test)]
mod tests {
    use xur_runtime::Value;
    use xur_runtime::testing::{TestCx, fn_id};

    use crate::registry;

    #[test]
    fn println_formats_its_arguments() {
        let registry = registry();
        let mut cx = TestCx::new(&registry, crate::PRELUDE);
        let println = fn_id(&registry, "std::io::println");
        let args = [
            Value::str("{} + {} = {{{}}}"),
            Value::int(1),
            Value::int(2),
            Value::int(3),
        ];
        assert_eq!(cx.call(println, &args), Ok(Value::Unit));
        assert_eq!(cx.output(), "1 + 2 = {3}\n");
    }
}