cljrs-stdlib 0.1.14

Built-in standard library namespaces for clojurust (clojure.string, clojure.set, clojure.test, …)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Built-in standard library namespaces for clojurust.
//!
//! Registers `clojure.string`, `clojure.set`, and `clojure.test` into a
//! [`GlobalEnv`] so they are available via `(require ...)` without needing
//! source files on disk.
//!
//! ## Entry points
//!
//! - [`standard_env()`] — full environment for the `cljrs` binary
//! - [`standard_env_with_paths()`] — same, plus user source paths
//! - [`register()`] — add stdlib to an existing env (e.g. for testing)

use std::sync::Arc;

use cljrs_eval::GlobalEnv;
use cljrs_gc::GcConfig;

mod core_async;
mod edn;
pub mod io;
mod set;
mod string;
// ── Embedded sources ──────────────────────────────────────────────────────────

const CLOJURE_TEST_SRC: &str = include_str!("clojure/test.cljrs");
const CLOJURE_STRING_SRC: &str = include_str!("clojure/string.cljrs");
const CLOJURE_SET_SRC: &str = include_str!("clojure/set.cljrs");
const CLOJURE_TEMPLATE_SRC: &str = include_str!("clojure/template.cljrs");
const CLOJURE_RUST_IO_SRC: &str = include_str!("clojure/rust/io.cljrs");
const CLOJURE_EDN_SRC: &str = include_str!("clojure/edn.cljrs");
const CLOJURE_WALK_SRC: &str = include_str!("clojure/walk.cljrs");
const CLOJURE_DATA_SRC: &str = include_str!("clojure/data.cljrs");
const COLJURE_ZIP_SRC: &str = include_str!("clojure/zip.cljrs");

// ── Macro: register a batch of native fns into a namespace ───────────────────

/// Register a slice of `(name, arity, fn)` triples as `NativeFunction` values
/// in `$globals` under namespace `$ns`.
macro_rules! register_fns {
    ($globals:expr, $ns:expr, [ $( ($name:expr, $arity:expr, $func:expr) ),* $(,)? ]) => {{
        use cljrs_gc::GcPtr;
        use cljrs_value::{NativeFn, Value};
        let ns: &str = $ns;
        $(
            {
                let nf = NativeFn::new($name, $arity, $func);
                $globals.intern(ns, std::sync::Arc::from($name), Value::NativeFunction(GcPtr::new(nf)));
            }
        )*
    }};
}

pub(crate) use register_fns;

// ── Public API ────────────────────────────────────────────────────────────────

/// Register all built-in stdlib namespaces into `globals`.
///
/// This is idempotent: calling it again does not re-evaluate sources
/// (already-loaded guard in `load_ns` prevents that), but it will
/// overwrite native fn registrations in the namespace tables.
/// In practice, call it once right after `standard_env_minimal()`.
pub fn register(globals: &Arc<GlobalEnv>) {
    // clojure.string ─ pre-register native fns, then register source for
    // the lazy (ns clojure.string) form to run on first require.
    string::register(globals, "clojure.string");
    globals.register_builtin_source("clojure.string", CLOJURE_STRING_SRC);

    // clojure.set ─ same pattern.
    set::register(globals, "clojure.set");
    globals.register_builtin_source("clojure.set", CLOJURE_SET_SRC);

    // clojure.template ─ pure Clojure, no native helpers.
    globals.register_builtin_source("clojure.template", CLOJURE_TEMPLATE_SRC);

    // clojure.test ─ pure Clojure, no native helpers.
    globals.register_builtin_source("clojure.test", CLOJURE_TEST_SRC);

    // clojure.rust.io ─ I/O resources.
    io::register(globals, "clojure.rust.io");
    globals.register_builtin_source("clojure.rust.io", CLOJURE_RUST_IO_SRC);

    // clojure.edn ─ EDN reader.
    edn::register(globals, "clojure.edn");
    globals.register_builtin_source("clojure.edn", CLOJURE_EDN_SRC);

    // clojure.walk ─ pure Clojure, no native helpers.
    globals.register_builtin_source("clojure.walk", CLOJURE_WALK_SRC);

    // clojure.data ─ pure Clojure, no native helpers.
    globals.register_builtin_source("clojure.data", CLOJURE_DATA_SRC);

    // clojure.zip
    globals.register_builtin_source("clojure.zip", COLJURE_ZIP_SRC);
}

/// Prebuilt IR bundle for clojure.core (generated at build time).
/// When the `prebuild-ir` feature is enabled, this contains serialized IR
/// for all lowerable functions; otherwise it's an empty slice.
#[cfg(feature = "prebuild-ir")]
static PREBUILT_IR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/core_ir.bin"));

/// Create a `GlobalEnv` with all built-ins and stdlib registered.
///
/// Prefer this over `cljrs_eval::standard_env()` in the `cljrs` binary so that
/// stdlib namespaces are loaded lazily (only on first `require`) instead of
/// eagerly at startup.
pub fn standard_env() -> Arc<GlobalEnv> {
    let globals = cljrs_eval::standard_env_minimal();
    register(&globals);

    // Try loading prebuilt IR first (skips compiler loading entirely).
    #[cfg(feature = "prebuild-ir")]
    {
        match cljrs_ir::deserialize_bundle(PREBUILT_IR) {
            Ok(bundle) if !bundle.is_empty() => {
                // Register compiler sources (needed for any functions not in the
                // prebuilt bundle, and for user code that triggers IR lowering).
                cljrs_eval::register_compiler_sources(&globals);

                let loaded = cljrs_eval::load_prebuilt_ir(&globals, &bundle);
                cljrs_logging::feat_debug!(
                    "ir",
                    "loaded {loaded} prebuilt IR arities from bundle ({} entries)",
                    bundle.len()
                );

                // Still load the compiler on a background thread so new user
                // functions can be eagerly lowered at definition time.
                let g = globals.clone();
                let _ = std::thread::Builder::new()
                    .stack_size(16 * 1024 * 1024)
                    .spawn(move || {
                        let mut env = cljrs_eval::Env::new(g.clone(), "user");
                        cljrs_eval::ensure_compiler_loaded(&g, &mut env);
                    });

                return globals;
            }
            _ => {
                // Empty or corrupt bundle — fall through to runtime lowering.
            }
        }
    }

    // Fallback: register and load compiler namespaces so IR lowering is
    // available at runtime. Loading runs on a thread with a large stack
    // because the Clojure compiler sources are deeply recursive.
    cljrs_eval::register_compiler_sources(&globals);
    {
        let g = globals.clone();
        let _ = std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(move || {
                let mut env = cljrs_eval::Env::new(g.clone(), "user");
                cljrs_eval::ensure_compiler_loaded(&g, &mut env);
            })
            .and_then(|h| h.join().map_err(|_| std::io::Error::other("join failed")));
    }

    globals
}

/// Like [`standard_env()`] but also sets user source paths for `require`.
pub fn standard_env_with_paths(source_paths: Vec<std::path::PathBuf>) -> Arc<GlobalEnv> {
    let globals = standard_env();
    globals.set_source_paths(source_paths);
    globals
}

/// Like [`standard_env_with_paths()`] but also sets GC configuration.
pub fn standard_env_with_paths_and_config(
    source_paths: Vec<std::path::PathBuf>,
    gc_config: Arc<GcConfig>,
) -> Arc<GlobalEnv> {
    let globals = standard_env();
    globals.set_source_paths(source_paths);
    globals.set_gc_config(gc_config.clone());
    // Configure the global GC heap with the same limits
    cljrs_gc::HEAP.set_config(gc_config);
    // Register GlobalEnv namespaces as GC roots so automatic collection
    // can trace all live values reachable from namespace bindings.
    let roots_globals = globals.clone();
    cljrs_gc::HEAP.register_root_tracer(move |visitor| {
        use cljrs_gc::GcVisitor as _;
        let namespaces = roots_globals.namespaces.read().unwrap();
        for (_name, ns_ptr) in namespaces.iter() {
            visitor.visit(ns_ptr);
        }
    });
    globals
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use cljrs_eval::{Env, EvalResult, eval};
    use cljrs_reader::Parser;
    use cljrs_value::Value;

    fn make_env() -> (Arc<GlobalEnv>, Env) {
        let globals = standard_env();
        let env = Env::new(globals.clone(), "user");
        (globals, env)
    }

    fn run(src: &str, env: &mut Env) -> EvalResult {
        let mut parser = Parser::new(src.to_string(), "<test>".to_string());
        let forms = parser.parse_all().expect("parse error");
        let mut result = Value::Nil;
        for form in forms {
            result = eval(&form, env)?;
        }
        Ok(result)
    }

    // ── clojure.string ────────────────────────────────────────────────────────

    #[test]
    fn test_string_upper_lower() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        assert_eq!(
            run("(str/upper-case \"hello\")", &mut env).unwrap(),
            Value::string("HELLO")
        );
        assert_eq!(
            run("(str/lower-case \"WORLD\")", &mut env).unwrap(),
            Value::string("world")
        );
    }

    #[test]
    fn test_string_trim() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        assert_eq!(
            run("(str/trim \"  hello  \")", &mut env).unwrap(),
            Value::string("hello")
        );
        assert_eq!(
            run("(str/triml \"  hi\")", &mut env).unwrap(),
            Value::string("hi")
        );
        assert_eq!(
            run("(str/trimr \"hi  \")", &mut env).unwrap(),
            Value::string("hi")
        );
    }

    #[test]
    fn test_string_predicates() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        assert_eq!(
            run("(str/blank? \"  \")", &mut env).unwrap(),
            Value::Bool(true)
        );
        assert_eq!(
            run("(str/blank? \"x\")", &mut env).unwrap(),
            Value::Bool(false)
        );
        assert_eq!(
            run("(str/starts-with? \"hello\" \"hel\")", &mut env).unwrap(),
            Value::Bool(true)
        );
        assert_eq!(
            run("(str/ends-with? \"hello\" \"llo\")", &mut env).unwrap(),
            Value::Bool(true)
        );
        assert_eq!(
            run("(str/includes? \"hello\" \"ell\")", &mut env).unwrap(),
            Value::Bool(true)
        );
    }

    #[test]
    fn test_string_replace() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        assert_eq!(
            run("(str/replace \"aabbcc\" \"bb\" \"XX\")", &mut env).unwrap(),
            Value::string("aaXXcc")
        );
        assert_eq!(
            run("(str/replace-first \"aabbcc\" \"a\" \"X\")", &mut env).unwrap(),
            Value::string("Xabbcc")
        );
    }

    #[test]
    fn test_string_split_join() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        let v = run("(str/split \"a,b,c\" \",\")", &mut env).unwrap();
        assert!(matches!(v, Value::Vector(_)));
        assert_eq!(
            run("(str/join \"-\" [\"a\" \"b\" \"c\"])", &mut env).unwrap(),
            Value::string("a-b-c")
        );
    }

    #[test]
    fn test_string_capitalize() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        assert_eq!(
            run("(str/capitalize \"hello world\")", &mut env).unwrap(),
            Value::string("Hello world")
        );
    }

    #[test]
    fn test_string_split_lines() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        let v = run("(str/split-lines \"a\\nb\\nc\")", &mut env).unwrap();
        assert!(matches!(v, Value::Vector(_)));
    }

    // ── clojure.set ───────────────────────────────────────────────────────────

    #[test]
    fn test_set_union() {
        let (_, mut env) = make_env();
        run("(require '[clojure.set :as s])", &mut env).unwrap();
        let v = run("(s/union #{1 2} #{2 3})", &mut env).unwrap();
        match v {
            Value::Set(s) => assert_eq!(s.count(), 3),
            other => panic!("expected set, got {other:?}"),
        }
    }

    #[test]
    fn test_set_intersection() {
        let (_, mut env) = make_env();
        run("(require '[clojure.set :as s])", &mut env).unwrap();
        let v = run("(s/intersection #{1 2 3} #{2 3 4})", &mut env).unwrap();
        match v {
            Value::Set(s) => assert_eq!(s.count(), 2),
            other => panic!("expected set, got {other:?}"),
        }
    }

    #[test]
    fn test_set_difference() {
        let (_, mut env) = make_env();
        run("(require '[clojure.set :as s])", &mut env).unwrap();
        let v = run("(s/difference #{1 2 3} #{2 3})", &mut env).unwrap();
        match v {
            Value::Set(s) => assert_eq!(s.count(), 1),
            other => panic!("expected set, got {other:?}"),
        }
    }

    #[test]
    fn test_set_subset_superset() {
        let (_, mut env) = make_env();
        run("(require '[clojure.set :as s])", &mut env).unwrap();
        assert_eq!(
            run("(s/subset? #{1 2} #{1 2 3})", &mut env).unwrap(),
            Value::Bool(true)
        );
        assert_eq!(
            run("(s/superset? #{1 2 3} #{1 2})", &mut env).unwrap(),
            Value::Bool(true)
        );
    }

    #[test]
    fn test_set_map_invert() {
        let (_, mut env) = make_env();
        run("(require '[clojure.set :as s])", &mut env).unwrap();
        let v = run("(s/map-invert {:a 1 :b 2})", &mut env).unwrap();
        assert!(matches!(v, Value::Map(_)));
    }

    // ── clojure.test (via stdlib registry) ───────────────────────────────────

    #[test]
    fn test_clojure_test_lazy_load() {
        // Run on a thread with adequate stack: the `is` macro expansion
        // triggers eager IR lowering, which calls the Clojure compiler
        // (deeply recursive — needs more than the default 2MB test thread stack).
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(|| {
                let (_, mut env) = make_env();
                // clojure.test is NOT pre-loaded in standard_env_minimal();
                // it should load lazily from the registry.
                run(
                    "(require '[clojure.test :refer [is deftest run-tests]])",
                    &mut env,
                )
                .unwrap();
                let v = run("(is (= 1 1))", &mut env).unwrap();
                assert_eq!(v, Value::Bool(true));
            })
            .unwrap()
            .join()
            .unwrap();
    }
}