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 assert;
9mod bytes;
10#[cfg(feature = "cli")]
11mod cli;
12mod fmt;
13mod fs;
14mod io;
15mod json;
16mod list;
17mod log;
18mod map;
19mod math;
20mod mem;
21mod net;
22mod num;
23mod path;
24mod process;
25mod ptr;
26pub mod re;
27mod record;
28mod reflect;
29mod str;
30mod sync;
31mod thread;
32mod xur;
33
34pub use xur::{set_argv, set_invoked_by};
35
36include!(concat!(env!("OUT_DIR"), "/prelude.rs"));
37
38use xur_runtime::{Context, Registry, RunResult, RuntimeError, Value};
39
40/// A registry holding only `std`.
41pub fn registry() -> Registry {
42    let registry = Registry::new();
43    register(&registry);
44    registry
45}
46
47/// Registers `std` and its submodules in `registry`.
48pub fn register(registry: &Registry) {
49    registry
50        .module("std")
51        .named_raw_function("import", &["path"], import)
52        .named_raw_function("try_import", &["path"], try_import)
53        .named_raw_function("panic", &["format", "args"], panic)
54        .named_raw_function("argv", &[], argv);
55    registry
56        .module("std::fmt")
57        .named_raw_function("format", &["template", "args"], format);
58    io::register(registry);
59    fs::register(registry);
60    process::register(registry);
61    thread::register(registry);
62    sync::register(registry);
63    net::register(registry);
64    any::register(registry);
65    assert::register(registry);
66    reflect::register(registry);
67    json::register(registry);
68    re::register(registry);
69    math::register(registry);
70    mem::register(registry);
71    list::register(registry);
72    log::register(registry);
73    map::register(registry);
74    bytes::register(registry);
75    str::register(registry);
76    num::register(registry);
77    path::register(registry);
78    ptr::register(registry);
79    record::register(registry);
80    xur::register(registry);
81    #[cfg(feature = "cli")]
82    cli::register(registry);
83}
84
85/// `std::import(path)`: loads a module, which may be computed at runtime.
86fn import(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
87    match args {
88        [Value::Str(path)] => cx.import(path),
89        _ => Err(RuntimeError::new(
90            "`std::import` takes a single path string",
91        )),
92    }
93}
94
95/// `std::try_import(path)`: like `import`, but returns `Result<module, str>`
96/// instead of stopping the program.
97fn try_import(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
98    match args {
99        [Value::Str(path)] => {
100            let lang = *cx.lang();
101            match cx.import(path) {
102                Ok(module) => Ok(Value::adt(lang.ok, vec![module])),
103                Err(error) => Ok(Value::adt(lang.err, vec![Value::str(&error.message)])),
104            }
105        }
106        _ => Err(RuntimeError::new(
107            "`std::try_import` takes a single path string",
108        )),
109    }
110}
111
112/// `Some(value)` or `None`, as Xur values.
113fn option(cx: &dyn Context, value: Option<Value>) -> Value {
114    let lang = cx.lang();
115    match value {
116        Some(value) => Value::adt(lang.some, vec![value]),
117        None => Value::adt(lang.none, Vec::new()),
118    }
119}
120
121/// `Ok(value)` or `Err(message)`, as Xur values.
122fn result(cx: &dyn Context, value: Result<Value, String>) -> Value {
123    let lang = cx.lang();
124    match value {
125        Ok(value) => Value::adt(lang.ok, vec![value]),
126        Err(message) => Value::adt(lang.err, vec![Value::str(&message)]),
127    }
128}
129
130/// How Rust errors appear in Xur: as the `Err` of a `Result`, by message.
131fn error_text(error: impl std::fmt::Display) -> String {
132    error.to_string()
133}
134
135/// `std::fmt::format(template, args...)`: returns a formatted string.
136fn format(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
137    let Some((Value::Str(template), args)) = args.split_first() else {
138        return Err(RuntimeError::new("`format` takes a format string"));
139    };
140    Ok(Value::str(&fmt::format(cx, template, args)?))
141}
142
143/// `std::argv()`: the program's argument list as set by `set_argv`.
144fn argv(_cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
145    if !args.is_empty() {
146        return Err(RuntimeError::new("`std::argv` takes no arguments"));
147    }
148    let items = xur::ARGV.get().cloned().unwrap_or_default();
149    Ok(Value::list(items))
150}
151
152/// `std::panic(format, args...)`: stops the program with a runtime error,
153/// formatted like `println`.
154fn panic(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
155    let Some((Value::Str(template), args)) = args.split_first() else {
156        return Err(RuntimeError::new("`panic` takes a format string"));
157    };
158    Err(RuntimeError::new(fmt::format(cx, template, args)?))
159}