Skip to main content

xur_std/
lib.rs

1//! Xur's standard library, `std`.
2//!
3//! It is registered like any other native module, so embedders can run
4//! programs with a different standard library, or register more modules
5//! alongside it. Each submodule registers itself.
6
7mod any;
8mod fmt;
9mod fs;
10mod io;
11mod list;
12mod math;
13mod net;
14mod num;
15mod str;
16mod sync;
17mod thread;
18
19use xur_runtime::{Context, Registry, RunResult, RuntimeError, Value};
20
21/// A registry holding only `std`.
22pub fn registry() -> Registry {
23    let registry = Registry::new();
24    register(&registry);
25    registry
26}
27
28/// Registers `std` and its submodules in `registry`.
29pub fn register(registry: &Registry) {
30    registry
31        .module("std")
32        .raw_function("import", import)
33        .raw_function("panic", panic);
34    io::register(registry);
35    fs::register(registry);
36    thread::register(registry);
37    sync::register(registry);
38    net::register(registry);
39    any::register(registry);
40    math::register(registry);
41    list::register(registry);
42    str::register(registry);
43    num::register(registry);
44}
45
46/// `std::import(path)`: loads a module, which may be computed at runtime.
47fn import(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
48    match args {
49        [Value::Str(path)] => cx.import(path),
50        _ => Err(RuntimeError::new(
51            "`std::import` takes a single path string",
52        )),
53    }
54}
55
56/// `Some(value)` or `None`, as Xur values.
57fn option(cx: &dyn Context, value: Option<Value>) -> Value {
58    let lang = cx.lang();
59    match value {
60        Some(value) => Value::adt(lang.some, vec![value]),
61        None => Value::adt(lang.none, Vec::new()),
62    }
63}
64
65/// How Rust errors appear in Xur: as the `Err` of a `Result`, by message.
66fn error_text(error: impl std::fmt::Display) -> String {
67    error.to_string()
68}
69
70/// `std::panic(format, args...)`: stops the program with a runtime error,
71/// formatted like `println`.
72fn panic(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
73    let Some((Value::Str(template), args)) = args.split_first() else {
74        return Err(RuntimeError::new("`panic` takes a format string"));
75    };
76    Err(RuntimeError::new(fmt::format(cx, template, args)?))
77}