xur-std 0.1.11

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

use facet::Facet;
use xur_runtime::registry::RawSig;
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,
    /// Writing to a file whose folder isn't there, carrying the folder
    /// (make it first with `std::fs::create_dir_all`).
    DirectoryDoesNotExist(String),
    /// Any other I/O error, carrying its message.
    Other(String),
}

/// What a filesystem attaches to a `std::io::Error` when the folder a file
/// goes in doesn't exist; [`Error`] turns it into `DirectoryDoesNotExist`.
#[derive(Debug)]
pub struct MissingDirectory(pub String);

impl std::fmt::Display for MissingDirectory {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "directory {} does not exist", self.0)
    }
}

impl std::error::Error for MissingDirectory {}

/// The error for writing into `dir` when it doesn't exist.
pub fn missing_directory(dir: impl Into<String>) -> std::io::Error {
    std::io::Error::new(std::io::ErrorKind::NotFound, MissingDirectory(dir.into()))
}

/// Checks that the folder `path` goes in exists (none for a bare file name).
pub fn parent_exists(path: &str) -> Result<(), Error> {
    match std::path::Path::new(path).parent() {
        Some(dir) if !dir.as_os_str().is_empty() && !dir.is_dir() => {
            Err(Error::DirectoryDoesNotExist(dir.display().to_string()))
        }
        _ => Ok(()),
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        use std::io::ErrorKind;
        if let Some(missing) = e
            .get_ref()
            .and_then(|r| r.downcast_ref::<MissingDirectory>())
        {
            return Error::DirectoryDoesNotExist(missing.0.clone());
        }
        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::DirectoryDoesNotExist(dir) => write!(
                f,
                "directory {dir} does not exist (make it with std::fs::create_dir_all)"
            ),
            Error::Other(m) => f.write_str(m),
        }
    }
}

pub(crate) fn register(registry: &Registry) {
    let mut m = registry.module("std::io");
    m.ty::<Error>("Error");
    let sig = || RawSig::new().param("format", "str").rest("args", "any");
    m.raw_function_sig("print", sig(), |cx, args| print(cx, args, ""))
        .raw_function_sig("println", sig(), |cx, args| print(cx, args, "\n"))
        .raw_function_sig("eprint", sig(), |cx, args| eprint(cx, args, ""))
        .raw_function_sig("eprintln", sig(), |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");
    }
}

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

    #[test]
    fn a_missing_folder_is_its_own_error() {
        let e = Error::from(missing_directory("/out"));
        assert!(matches!(&e, Error::DirectoryDoesNotExist(d) if d == "/out"));
        assert!(e.to_string().contains("directory /out does not exist"));
        // Any other not-found stays NotFound.
        let other = std::io::Error::new(std::io::ErrorKind::NotFound, "x");
        assert!(matches!(Error::from(other), Error::NotFound));

        let dir = std::env::temp_dir().join("xur-io-missing-folder-test");
        let _ = std::fs::remove_dir_all(&dir);
        let file = dir.join("x.bin");
        assert!(matches!(
            parent_exists(&file.to_string_lossy()),
            Err(Error::DirectoryDoesNotExist(_))
        ));
        assert!(parent_exists("bare-name.txt").is_ok());
    }
}