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;
10mod cell;
11#[cfg(feature = "cli")]
12mod cli;
13#[cfg(feature = "datetime")]
14mod datetime;
15#[cfg(feature = "rust_decimal")]
16pub mod decimal;
17#[cfg(feature = "env")]
18mod env;
19mod features;
20pub mod fmt;
21#[cfg(feature = "fs")]
22mod fs;
23#[cfg(feature = "egui-widgets")]
24pub mod gui;
25#[cfg(feature = "hash")]
26mod hash;
27#[cfg(feature = "http")]
28mod http;
29pub mod io;
30#[cfg(feature = "json")]
31mod json;
32mod list;
33#[cfg(feature = "log")]
34mod log;
35mod map;
36mod math;
37mod mem;
38mod native_enum_test;
39#[cfg(feature = "net")]
40mod net;
41mod num;
42mod path;
43#[cfg(feature = "process")]
44mod process;
45#[cfg(feature = "ptr")]
46mod ptr;
47#[cfg(feature = "random")]
48mod random;
49pub mod re;
50mod record;
51mod reflect;
52#[cfg(feature = "regex")]
53mod regex;
54mod str;
55mod sync;
56#[cfg(feature = "thread")]
57mod thread;
58#[cfg(feature = "time")]
59mod time;
60mod xur;
61
62pub use features::module_feature;
63pub use xur::{set_argv, set_invoked_by};
64
65include!(concat!(env!("OUT_DIR"), "/prelude.rs"));
66
67use xur_runtime::registry::{ElemHint, XurType};
68use xur_runtime::{Context, Registry, RunResult, RuntimeError, Value};
69
70/// A registry holding only `std`.
71pub fn registry() -> Registry {
72    let registry = Registry::new();
73    register(&registry);
74    registry
75}
76
77/// Registers `std` and its submodules in `registry`.
78pub fn register(registry: &Registry) {
79    registry
80        .module("std")
81        .named_raw_function("import", &["path"], import)
82        .named_raw_function_returns_xur(
83            "try_import",
84            &["path"],
85            XurType::Named("Result", &[ElemHint::Name("module"), ElemHint::Name("str")]),
86            try_import,
87        )
88        .named_raw_function_returns_xur("panic", &["format", "args"], XurType::UNIT, panic)
89        .named_raw_function_returns_xur("argv", &[], XurType::list::<String>(), argv);
90    registry
91        .module("std::fmt")
92        .named_raw_function_returns::<String>("format", &["template", "args"], format);
93    io::register(registry);
94    #[cfg(feature = "fs")]
95    fs::register(registry);
96    #[cfg(feature = "process")]
97    process::register(registry);
98    #[cfg(feature = "thread")]
99    thread::register(registry);
100    sync::register(registry);
101    #[cfg(feature = "net")]
102    net::register(registry);
103    any::register(registry);
104    assert::register(registry);
105    reflect::register(registry);
106    #[cfg(feature = "egui-widgets")]
107    gui::register(registry);
108    #[cfg(feature = "http")]
109    http::register(registry);
110    #[cfg(feature = "json")]
111    json::register(registry);
112    re::register(registry);
113    math::register(registry);
114    mem::register(registry);
115    native_enum_test::register(registry);
116    list::register(registry);
117    #[cfg(feature = "log")]
118    log::register(registry);
119    map::register(registry);
120    bytes::register(registry);
121    cell::register(registry);
122    str::register(registry);
123    num::register(registry);
124    path::register(registry);
125    #[cfg(feature = "ptr")]
126    ptr::register(registry);
127    record::register(registry);
128    #[cfg(feature = "regex")]
129    regex::register(registry);
130    #[cfg(feature = "datetime")]
131    datetime::register(registry);
132    #[cfg(feature = "time")]
133    time::register(registry);
134    #[cfg(feature = "env")]
135    env::register(registry);
136    #[cfg(feature = "random")]
137    random::register(registry);
138    #[cfg(feature = "hash")]
139    hash::register(registry);
140    xur::register(registry);
141    #[cfg(feature = "cli")]
142    cli::register(registry);
143    #[cfg(feature = "rust_decimal")]
144    decimal::register(registry);
145}
146
147/// `std::import(path)`: loads a module, which may be computed at runtime.
148fn import(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
149    match args {
150        [Value::Str(path)] => cx.import(path),
151        _ => Err(RuntimeError::new(
152            "`std::import` takes a single path string",
153        )),
154    }
155}
156
157/// `std::try_import(path)`: like `import`, but returns `Result<module, str>`
158/// instead of stopping the program.
159fn try_import(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
160    match args {
161        [Value::Str(path)] => {
162            let lang = *cx.lang();
163            match cx.import(path) {
164                Ok(module) => Ok(Value::adt(lang.ok, vec![module])),
165                Err(error) => Ok(Value::adt(lang.err, vec![Value::str(&error.message)])),
166            }
167        }
168        _ => Err(RuntimeError::new(
169            "`std::try_import` takes a single path string",
170        )),
171    }
172}
173
174/// `Some(value)` or `None`, as Xur values.
175fn option(cx: &dyn Context, value: Option<Value>) -> Value {
176    let lang = cx.lang();
177    match value {
178        Some(value) => Value::adt(lang.some, vec![value]),
179        None => Value::adt(lang.none, Vec::new()),
180    }
181}
182
183/// `Ok(value)` or `Err(message)`, as Xur values.
184fn result(cx: &dyn Context, value: Result<Value, String>) -> Value {
185    let lang = cx.lang();
186    match value {
187        Ok(value) => Value::adt(lang.ok, vec![value]),
188        Err(message) => Value::adt(lang.err, vec![Value::str(&message)]),
189    }
190}
191
192/// How Rust errors appear in Xur: as the `Err` of a `Result`, by message.
193fn error_text(error: impl std::fmt::Display) -> String {
194    error.to_string()
195}
196
197/// `std::fmt::format(template, args...)`: returns a formatted string.
198fn format(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
199    let Some((Value::Str(template), args)) = args.split_first() else {
200        return Err(RuntimeError::new("`format` takes a format string"));
201    };
202    Ok(Value::str(&fmt::format(cx, template, args)?))
203}
204
205/// `std::argv()`: the program's argument list as set by `set_argv`.
206fn argv(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
207    if !args.is_empty() {
208        return Err(RuntimeError::new("`std::argv` takes no arguments"));
209    }
210    let Some((script, rest)) = xur::ARGV.get() else {
211        return Ok(Value::list(Vec::new()));
212    };
213    let mut items: Vec<Value> = Vec::with_capacity(1 + rest.len());
214    items.push(option(cx, script.clone()));
215    items.extend(rest.iter().map(|a| Value::str(a)));
216    Ok(Value::list(items))
217}
218
219/// `std::panic(format, args...)`: stops the program with a runtime error,
220/// formatted like `println`.
221fn panic(cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
222    let Some((Value::Str(template), args)) = args.split_first() else {
223        return Err(RuntimeError::new("`panic` takes a format string"));
224    };
225    Err(RuntimeError::new(fmt::format(cx, template, args)?))
226}