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    /// Writing to a file whose folder isn't there, carrying the folder
22    /// (make it first with `std::fs::create_dir_all`).
23    DirectoryDoesNotExist(String),
24    /// Any other I/O error, carrying its message.
25    Other(String),
26}
27
28/// What a filesystem attaches to a `std::io::Error` when the folder a file
29/// goes in doesn't exist; [`Error`] turns it into `DirectoryDoesNotExist`.
30#[derive(Debug)]
31pub struct MissingDirectory(pub String);
32
33impl std::fmt::Display for MissingDirectory {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        write!(f, "directory {} does not exist", self.0)
36    }
37}
38
39impl std::error::Error for MissingDirectory {}
40
41/// The error for writing into `dir` when it doesn't exist.
42pub fn missing_directory(dir: impl Into<String>) -> std::io::Error {
43    std::io::Error::new(std::io::ErrorKind::NotFound, MissingDirectory(dir.into()))
44}
45
46/// Checks that the folder `path` goes in exists (none for a bare file name).
47pub fn parent_exists(path: &str) -> Result<(), Error> {
48    match std::path::Path::new(path).parent() {
49        Some(dir) if !dir.as_os_str().is_empty() && !dir.is_dir() => {
50            Err(Error::DirectoryDoesNotExist(dir.display().to_string()))
51        }
52        _ => Ok(()),
53    }
54}
55
56impl From<std::io::Error> for Error {
57    fn from(e: std::io::Error) -> Self {
58        use std::io::ErrorKind;
59        if let Some(missing) = e
60            .get_ref()
61            .and_then(|r| r.downcast_ref::<MissingDirectory>())
62        {
63            return Error::DirectoryDoesNotExist(missing.0.clone());
64        }
65        match e.kind() {
66            ErrorKind::NotFound => Error::NotFound,
67            ErrorKind::PermissionDenied => Error::PermissionDenied,
68            ErrorKind::AlreadyExists => Error::AlreadyExists,
69            ErrorKind::InvalidInput | ErrorKind::InvalidData => Error::InvalidInput,
70            ErrorKind::UnexpectedEof => Error::UnexpectedEof,
71            ErrorKind::Interrupted => Error::Interrupted,
72            _ => Error::Other(e.to_string()),
73        }
74    }
75}
76
77impl std::fmt::Display for Error {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        match self {
80            Error::NotFound => f.write_str("not found"),
81            Error::PermissionDenied => f.write_str("permission denied"),
82            Error::AlreadyExists => f.write_str("already exists"),
83            Error::InvalidInput => f.write_str("invalid input"),
84            Error::UnexpectedEof => f.write_str("unexpected end of file"),
85            Error::Interrupted => f.write_str("interrupted"),
86            Error::DirectoryDoesNotExist(dir) => write!(
87                f,
88                "directory {dir} does not exist (make it with std::fs::create_dir_all)"
89            ),
90            Error::Other(m) => f.write_str(m),
91        }
92    }
93}
94
95pub(crate) fn register(registry: &Registry) {
96    let mut m = registry.module("std::io");
97    m.ty::<Error>("Error");
98    let sig = || RawSig::new().param("format", "str").rest("args", "any");
99    m.raw_function_sig("print", sig(), |cx, args| print(cx, args, ""))
100        .raw_function_sig("println", sig(), |cx, args| print(cx, args, "\n"))
101        .raw_function_sig("eprint", sig(), |cx, args| eprint(cx, args, ""))
102        .raw_function_sig("eprintln", sig(), |cx, args| eprint(cx, args, "\n"));
103    registry
104        .module("std::io::c")
105        .named_function("red", &["text"], |s: String| format!("\x1b[31m{s}\x1b[0m"))
106        .named_function("green", &["text"], |s: String| {
107            format!("\x1b[32m{s}\x1b[0m")
108        })
109        .named_function("yellow", &["text"], |s: String| {
110            format!("\x1b[33m{s}\x1b[0m")
111        })
112        .named_function("blue", &["text"], |s: String| format!("\x1b[34m{s}\x1b[0m"))
113        .named_function("magenta", &["text"], |s: String| {
114            format!("\x1b[35m{s}\x1b[0m")
115        })
116        .named_function("cyan", &["text"], |s: String| format!("\x1b[36m{s}\x1b[0m"))
117        .named_function("bold", &["text"], |s: String| format!("\x1b[1m{s}\x1b[0m"))
118        .named_function("dim", &["text"], |s: String| format!("\x1b[2m{s}\x1b[0m"));
119}
120
121/// `print(format, args...)`: each `{}` in `format` is replaced by the next
122/// argument; `{{` and `}}` write literal braces.
123fn print(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
124    let Some((Value::Str(template), args)) = args.split_first() else {
125        return Err(RuntimeError::new(
126            "expected a format string as the first argument",
127        ));
128    };
129    let mut text = if args.is_empty() {
130        template.to_string()
131    } else {
132        format(cx, template, args)?
133    };
134    text.push_str(end);
135    cx.print(&text)?;
136    Ok(Value::Unit)
137}
138
139fn eprint(cx: &mut dyn Context, args: &[Value], end: &str) -> RunResult<Value> {
140    let Some((Value::Str(template), args)) = args.split_first() else {
141        return Err(RuntimeError::new(
142            "expected a format string as the first argument",
143        ));
144    };
145    let mut text = if args.is_empty() {
146        template.to_string()
147    } else {
148        format(cx, template, args)?
149    };
150    text.push_str(end);
151    cx.eprint(&text)?;
152    Ok(Value::Unit)
153}
154
155#[cfg(test)]
156mod tests {
157    use xur_runtime::Value;
158    use xur_runtime::testing::{TestCx, fn_id};
159
160    use crate::registry;
161
162    #[test]
163    fn println_formats_its_arguments() {
164        let registry = registry();
165        let mut cx = TestCx::new(&registry, crate::PRELUDE);
166        let println = fn_id(&registry, "std::io::println");
167        let args = [
168            Value::str("{} + {} = {{{}}}"),
169            Value::int(1),
170            Value::int(2),
171            Value::int(3),
172        ];
173        assert_eq!(cx.call(println, &args), Ok(Value::Unit));
174        assert_eq!(cx.output(), "1 + 2 = {3}\n");
175    }
176}
177
178#[cfg(test)]
179mod missing_folder_tests {
180    use super::*;
181
182    #[test]
183    fn a_missing_folder_is_its_own_error() {
184        let e = Error::from(missing_directory("/out"));
185        assert!(matches!(&e, Error::DirectoryDoesNotExist(d) if d == "/out"));
186        assert!(e.to_string().contains("directory /out does not exist"));
187        // Any other not-found stays NotFound.
188        let other = std::io::Error::new(std::io::ErrorKind::NotFound, "x");
189        assert!(matches!(Error::from(other), Error::NotFound));
190
191        let dir = std::env::temp_dir().join("xur-io-missing-folder-test");
192        let _ = std::fs::remove_dir_all(&dir);
193        let file = dir.join("x.bin");
194        assert!(matches!(
195            parent_exists(&file.to_string_lossy()),
196            Err(Error::DirectoryDoesNotExist(_))
197        ));
198        assert!(parent_exists("bare-name.txt").is_ok());
199    }
200}