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