Skip to main content

xur_std/
io.rs

1//! `std::io`: printing.
2
3use facet::Facet;
4use xur_runtime::registry::XurType;
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    m.named_raw_function_returns_xur("print", &["format", "args"], XurType::UNIT, |cx, args| {
58        print(cx, args, "")
59    })
60    .named_raw_function_returns_xur("println", &["format", "args"], XurType::UNIT, |cx, args| {
61        print(cx, args, "\n")
62    })
63    .named_raw_function_returns_xur("eprint", &["format", "args"], XurType::UNIT, |cx, args| {
64        eprint(cx, args, "")
65    })
66    .named_raw_function_returns_xur(
67        "eprintln",
68        &["format", "args"],
69        XurType::UNIT,
70        |cx, args| eprint(cx, args, "\n"),
71    );
72    registry
73        .module("std::io::c")
74        .named_function("red", &["text"], |s: String| format!("\x1b[31m{s}\x1b[0m"))
75        .named_function("green", &["text"], |s: String| {
76            format!("\x1b[32m{s}\x1b[0m")
77        })
78        .named_function("yellow", &["text"], |s: String| {
79            format!("\x1b[33m{s}\x1b[0m")
80        })
81        .named_function("blue", &["text"], |s: String| format!("\x1b[34m{s}\x1b[0m"))
82        .named_function("magenta", &["text"], |s: String| {
83            format!("\x1b[35m{s}\x1b[0m")
84        })
85        .named_function("cyan", &["text"], |s: String| format!("\x1b[36m{s}\x1b[0m"))
86        .named_function("bold", &["text"], |s: String| format!("\x1b[1m{s}\x1b[0m"))
87        .named_function("dim", &["text"], |s: String| format!("\x1b[2m{s}\x1b[0m"));
88}
89
90/// `print(format, args...)`: each `{}` in `format` is replaced by the next
91/// argument; `{{` and `}}` write literal braces.
92fn print(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
93    let Some((Value::Str(template), args)) = args.split_first() else {
94        return Err(RuntimeError::new(
95            "expected a format string as the first argument",
96        ));
97    };
98    let mut text = if args.is_empty() {
99        template.to_string()
100    } else {
101        format(cx, template, args)?
102    };
103    text.push_str(end);
104    cx.print(&text)?;
105    Ok(Value::Unit)
106}
107
108fn eprint(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
109    let Some((Value::Str(template), args)) = args.split_first() else {
110        return Err(RuntimeError::new(
111            "expected a format string as the first argument",
112        ));
113    };
114    let mut text = if args.is_empty() {
115        template.to_string()
116    } else {
117        format(cx, template, args)?
118    };
119    text.push_str(end);
120    cx.eprint(&text)?;
121    Ok(Value::Unit)
122}
123
124#[cfg(test)]
125mod tests {
126    use xur_runtime::Value;
127    use xur_runtime::testing::{TestCx, fn_id};
128
129    use crate::registry;
130
131    #[test]
132    fn println_formats_its_arguments() {
133        let registry = registry();
134        let mut cx = TestCx::new(&registry, crate::PRELUDE);
135        let println = fn_id(&registry, "std::io::println");
136        let args = [
137            Value::str("{} + {} = {{{}}}"),
138            Value::int(1),
139            Value::int(2),
140            Value::int(3),
141        ];
142        assert_eq!(cx.call(println, &args), Ok(Value::Unit));
143        assert_eq!(cx.output(), "1 + 2 = {3}\n");
144    }
145}