Skip to main content

xur_std/
io.rs

1//! `std::io`: printing.
2
3use facet::Facet;
4use xur_runtime::registry::RawSig;
5use xur_runtime::{Context, Registry, RunResult, RuntimeError, Value};
6
7use crate::fmt::format;
8
9/// A recoverable I/O error. Shared across the I/O modules (`std::fs`,
10/// `std::net`, `std::path`, …) so a script handles one error type; match it as
11/// `Err(io::Error::NotFound)` etc. Build one with `io::Error::from(std::io::Error)`.
12#[derive(Clone, Facet)]
13#[repr(C)]
14pub enum Error {
15    NotFound,
16    PermissionDenied,
17    AlreadyExists,
18    InvalidInput,
19    UnexpectedEof,
20    Interrupted,
21    /// Any other I/O error, carrying its message.
22    Other(String),
23}
24
25impl From<std::io::Error> for Error {
26    fn from(e: std::io::Error) -> Self {
27        use std::io::ErrorKind;
28        match e.kind() {
29            ErrorKind::NotFound => Error::NotFound,
30            ErrorKind::PermissionDenied => Error::PermissionDenied,
31            ErrorKind::AlreadyExists => Error::AlreadyExists,
32            ErrorKind::InvalidInput | ErrorKind::InvalidData => Error::InvalidInput,
33            ErrorKind::UnexpectedEof => Error::UnexpectedEof,
34            ErrorKind::Interrupted => Error::Interrupted,
35            _ => Error::Other(e.to_string()),
36        }
37    }
38}
39
40impl std::fmt::Display for Error {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Error::NotFound => f.write_str("not found"),
44            Error::PermissionDenied => f.write_str("permission denied"),
45            Error::AlreadyExists => f.write_str("already exists"),
46            Error::InvalidInput => f.write_str("invalid input"),
47            Error::UnexpectedEof => f.write_str("unexpected end of file"),
48            Error::Interrupted => f.write_str("interrupted"),
49            Error::Other(m) => f.write_str(m),
50        }
51    }
52}
53
54pub(crate) fn register(registry: &Registry) {
55    let mut m = registry.module("std::io");
56    m.ty::<Error>("Error");
57    let sig = || RawSig::new().param("format", "str").rest("args", "any");
58    m.raw_function_sig("print", sig(), |cx, args| print(cx, args, ""))
59        .raw_function_sig("println", sig(), |cx, args| print(cx, args, "\n"))
60        .raw_function_sig("eprint", sig(), |cx, args| eprint(cx, args, ""))
61        .raw_function_sig("eprintln", sig(), |cx, args| eprint(cx, args, "\n"));
62    registry
63        .module("std::io::c")
64        .named_function("red", &["text"], |s: String| format!("\x1b[31m{s}\x1b[0m"))
65        .named_function("green", &["text"], |s: String| {
66            format!("\x1b[32m{s}\x1b[0m")
67        })
68        .named_function("yellow", &["text"], |s: String| {
69            format!("\x1b[33m{s}\x1b[0m")
70        })
71        .named_function("blue", &["text"], |s: String| format!("\x1b[34m{s}\x1b[0m"))
72        .named_function("magenta", &["text"], |s: String| {
73            format!("\x1b[35m{s}\x1b[0m")
74        })
75        .named_function("cyan", &["text"], |s: String| format!("\x1b[36m{s}\x1b[0m"))
76        .named_function("bold", &["text"], |s: String| format!("\x1b[1m{s}\x1b[0m"))
77        .named_function("dim", &["text"], |s: String| format!("\x1b[2m{s}\x1b[0m"));
78}
79
80/// `print(format, args...)`: each `{}` in `format` is replaced by the next
81/// argument; `{{` and `}}` write literal braces.
82fn print(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
83    let Some((Value::Str(template), args)) = args.split_first() else {
84        return Err(RuntimeError::new(
85            "expected a format string as the first argument",
86        ));
87    };
88    let mut text = if args.is_empty() {
89        template.to_string()
90    } else {
91        format(cx, template, args)?
92    };
93    text.push_str(end);
94    cx.print(&text)?;
95    Ok(Value::Unit)
96}
97
98fn eprint(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
99    let Some((Value::Str(template), args)) = args.split_first() else {
100        return Err(RuntimeError::new(
101            "expected a format string as the first argument",
102        ));
103    };
104    let mut text = if args.is_empty() {
105        template.to_string()
106    } else {
107        format(cx, template, args)?
108    };
109    text.push_str(end);
110    cx.eprint(&text)?;
111    Ok(Value::Unit)
112}
113
114#[cfg(test)]
115mod tests {
116    use xur_runtime::Value;
117    use xur_runtime::testing::{TestCx, fn_id};
118
119    use crate::registry;
120
121    #[test]
122    fn println_formats_its_arguments() {
123        let registry = registry();
124        let mut cx = TestCx::new(&registry, crate::PRELUDE);
125        let println = fn_id(&registry, "std::io::println");
126        let args = [
127            Value::str("{} + {} = {{{}}}"),
128            Value::int(1),
129            Value::int(2),
130            Value::int(3),
131        ];
132        assert_eq!(cx.call(println, &args), Ok(Value::Unit));
133        assert_eq!(cx.output(), "1 + 2 = {3}\n");
134    }
135}