Skip to main content

catallaxy_stdlib/
lib.rs

1//! Native implementations of the Catallaxy standard library.
2//!
3//! Each native receives the calling thread's [`Vm`] and its arguments (the receiver first for
4//! methods). A missing optional argument arrives as the empty marker; use [`opt`].
5
6mod coll;
7mod conc;
8mod core;
9pub mod fiber;
10mod sys;
11
12use std::io::Write;
13use std::sync::OnceLock;
14
15use catallaxy_runtime::class::class_of;
16use catallaxy_runtime::object::{kind_of, str_of};
17use catallaxy_runtime::ops;
18use catallaxy_runtime::ownership;
19use catallaxy_runtime::{panic, ObjKind, RtResult, Trap, Value};
20use catallaxy_vm::{NativeFn, Vm};
21use parking_lot::Mutex;
22
23/// Command-line arguments passed to the program (after the script path).
24pub static ARGS: OnceLock<Vec<String>> = OnceLock::new();
25
26static STDOUT: Mutex<Option<std::io::BufWriter<std::io::Stdout>>> = Mutex::new(None);
27
28/// Writes to the buffered standard output.
29pub fn write_out(s: &str) {
30    let mut g = STDOUT.lock();
31    let w = g.get_or_insert_with(|| std::io::BufWriter::with_capacity(1 << 16, std::io::stdout()));
32    let _ = w.write_all(s.as_bytes());
33}
34
35/// Flushes buffered standard output (at exit, before reading input, before errors).
36pub fn flush() {
37    if let Some(w) = STDOUT.lock().as_mut() {
38        let _ = w.flush();
39    }
40}
41
42static EXTENSIONS: std::sync::LazyLock<parking_lot::RwLock<rustc_hash::FxHashMap<String, NativeFn>>> =
43    std::sync::LazyLock::new(Default::default);
44
45/// Registers a native function implemented by a Rust extension crate. Catallaxy code declares it
46/// with `native fn name(...) -> T` (a top-level `native fn` uses its plain name; a `native fn` in
47/// a class `C` uses `C.name`). Must be called before the program is loaded.
48pub fn register_native(name: &str, f: NativeFn) {
49    EXTENSIONS.write().insert(name.to_string(), f);
50}
51
52/// Looks up a native implementation by name: the standard library, then extensions.
53pub fn lookup(name: &str) -> Option<NativeFn> {
54    core::lookup(name)
55        .or_else(|| coll::lookup(name))
56        .or_else(|| conc::lookup(name))
57        .or_else(|| sys::lookup(name))
58        .or_else(|| EXTENSIONS.read().get(name).copied())
59}
60
61// ---- argument helpers ------------------------------------------------------------------------
62
63pub(crate) fn opt(v: Value) -> Option<Value> {
64    if v.is_empty_marker() {
65        None
66    } else {
67        Some(v)
68    }
69}
70
71pub(crate) fn arg(args: &[Value], i: usize) -> Option<Value> {
72    args.get(i).copied().and_then(opt)
73}
74
75pub(crate) fn s<'a>(v: Value) -> RtResult<&'a str> {
76    match str_of(v) {
77        Some(s) => Ok(s),
78        None => panic(format!("TypeError: expected String, got {}", class_of(v).name)),
79    }
80}
81
82pub(crate) fn int(v: Value) -> RtResult<i64> {
83    if v.is_small_int() {
84        return Ok(v.as_small_int());
85    }
86    if ops::is_int(v) {
87        return match ops::int_as_i64(v) {
88            Some(i) => Ok(i),
89            None => panic("RangeError: integer too large"),
90        };
91    }
92    panic(format!("TypeError: expected Int, got {}", class_of(v).name))
93}
94
95pub(crate) fn float(v: Value) -> RtResult<f64> {
96    if v.is_float() {
97        Ok(v.as_f64())
98    } else if ops::is_int(v) {
99        Ok(ops::int_to_f64(v))
100    } else {
101        panic(format!("TypeError: expected Float, got {}", class_of(v).name))
102    }
103}
104
105pub(crate) fn new_str(vm: &mut Vm, s: &str) -> Value {
106    vm.m.alloc_str(s)
107}
108
109pub(crate) fn new_list(vm: &mut Vm, items: Vec<Value>) -> Value {
110    vm.m.alloc_list(items)
111}
112
113/// A snapshot of a list's items (with ownership checks).
114pub(crate) fn list_items(vm: &Vm, l: Value) -> RtResult<Vec<Value>> {
115    if kind_of(l) != ObjKind::List {
116        return panic(format!("TypeError: expected List, got {}", class_of(l).name));
117    }
118    Ok(ownership::read_list(&vm.m, l)?.to_vec())
119}
120
121pub(crate) fn to_s(vm: &mut Vm, v: Value) -> RtResult<String> {
122    ops::to_s(vm, v)
123}
124
125pub(crate) fn ok(vm: &mut Vm, v: Value) -> Value {
126    catallaxy_vm::slow::make_result(vm, true, v)
127}
128
129pub(crate) fn err(vm: &mut Vm, msg: &str) -> Value {
130    let s = new_str(vm, msg);
131    catallaxy_vm::slow::make_result(vm, false, s)
132}
133
134pub(crate) fn exit_trap(code: i32) -> Trap {
135    Trap::Exit(code)
136}
137
138/// Runs a blocking operation with the thread in native state.
139pub(crate) fn blocking<R>(vm: &Vm, f: impl FnOnce() -> R) -> R {
140    flush();
141    catallaxy_gc::blocking(&vm.m.rec, f)
142}