cljrs-stdlib 0.1.235

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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
//! 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;
#[cfg(not(target_arch = "wasm32"))]
use cljrs_gc::GcConfig;

// io and edn use std::fs which is not available on wasm32-unknown-unknown
#[cfg(not(target_arch = "wasm32"))]
mod edn;
#[cfg(not(target_arch = "wasm32"))]
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");
#[cfg(not(target_arch = "wasm32"))]
const CLOJURE_RUST_IO_SRC: &str = include_str!("clojure/rust/io.cljrs");
#[cfg(not(target_arch = "wasm32"))]
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");
const CLOJURE_SPEC_ALPHA_SRC: &str = include_str!("clojure/spec/alpha.cljrs");
const CLOJURE_SPEC_GEN_ALPHA_SRC: &str = include_str!("clojure/spec/gen/alpha.cljrs");
const CLOJURE_SPEC_TEST_ALPHA_SRC: &str = include_str!("clojure/spec/test/alpha.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 and clojure.edn use std::fs, unavailable on wasm32.
    #[cfg(not(target_arch = "wasm32"))]
    {
        io::register(globals, "clojure.rust.io");
        globals.register_builtin_source("clojure.rust.io", CLOJURE_RUST_IO_SRC);

        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);

    // clojure.spec.alpha ─ pure Clojure, no native helpers.
    globals.register_builtin_source("clojure.spec.alpha", CLOJURE_SPEC_ALPHA_SRC);

    // clojure.spec.gen.alpha ─ pure Clojure, throwing generator stubs.
    globals.register_builtin_source("clojure.spec.gen.alpha", CLOJURE_SPEC_GEN_ALPHA_SRC);

    // clojure.spec.test.alpha ─ pure Clojure, instrument/unstrument.
    globals.register_builtin_source("clojure.spec.test.alpha", CLOJURE_SPEC_TEST_ALPHA_SRC);
}

/// Create a `GlobalEnv` with all built-ins and stdlib registered, **without**
/// the IR lowering hook.
///
/// Use this in the AOT test harness and any other execution context where
/// IR generation is not needed.  It avoids populating the global `IR_CACHE`
/// with entries for test-namespace functions (entries that would never be
/// evicted and would accumulate to hundreds of MB over 233 namespaces).
///
/// GC config and root tracer are still registered identically to `standard_env`.
#[cfg(not(target_arch = "wasm32"))]
pub fn standard_env_no_ir() -> Arc<GlobalEnv> {
    let globals = cljrs_eval::standard_env_minimal_no_ir();
    register(&globals);

    cljrs_gc::HEAP.set_config_from_env();
    let roots_gc = globals.clone();
    cljrs_gc::HEAP.register_root_tracer(move |visitor| {
        use cljrs_gc::GcVisitor as _;
        let namespaces = roots_gc.namespaces.read().unwrap();
        for ns_ptr in namespaces.values() {
            visitor.visit(ns_ptr);
        }
    });

    globals
}

/// 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.
#[cfg(not(target_arch = "wasm32"))]
pub fn standard_env() -> Arc<GlobalEnv> {
    let globals = cljrs_eval::standard_env_minimal();
    register(&globals);

    // Configure GC with default limits and register namespace bindings as roots.
    // Without this, the GC never fires (no config → no soft-limit check).
    // standard_env_with_paths_and_config() overrides the config but reuses this tracer.
    cljrs_gc::HEAP.set_config_from_env();
    let roots_gc = globals.clone();
    cljrs_gc::HEAP.register_root_tracer(move |visitor| {
        use cljrs_gc::GcVisitor as _;
        let namespaces = roots_gc.namespaces.read().unwrap();
        for ns_ptr in namespaces.values() {
            visitor.visit(ns_ptr);
        }
    });

    // Enable IR lowering (pure Rust — nothing to load; honors CLJRS_NO_IR).
    cljrs_eval::mark_compiler_ready(&globals);

    globals
}

/// Like [`standard_env()`] but also sets user source paths for `require`.
#[cfg(not(target_arch = "wasm32"))]
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.
#[cfg(not(target_arch = "wasm32"))]
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());
    // Override the default GC config set by standard_env() with the custom limits.
    // The root tracer is already registered by standard_env().
    cljrs_gc::HEAP.set_config(gc_config);
    globals
}

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

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

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

    #[allow(clippy::result_large_err)]
    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")
        );
        // regex match (issue #188)
        assert_eq!(
            run("(str/replace \"--host\" #\"^--\" \"\")", &mut env).unwrap(),
            Value::string("host")
        );
        assert_eq!(
            run("(str/replace \"aaa\" #\"a\" \"b\")", &mut env).unwrap(),
            Value::string("bbb")
        );
        assert_eq!(
            run("(str/replace-first \"aaa\" #\"a\" \"b\")", &mut env).unwrap(),
            Value::string("baa")
        );
        assert_eq!(
            run("(str/replace-first \"--host\" #\"^--\" \"\")", &mut env).unwrap(),
            Value::string("host")
        );
    }

    #[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_join_char_elements() {
        let (_, mut env) = make_env();
        run("(require '[clojure.string :as str])", &mut env).unwrap();
        // Characters must render as their string value, not reader syntax.
        assert_eq!(
            run(r"(str/join [\8 \0])", &mut env).unwrap(),
            Value::string("80")
        );
        assert_eq!(
            run(r"(str/join \- [\8 \0])", &mut env).unwrap(),
            Value::string("8-0")
        );
        // nil elements are treated as empty string (same as (str nil) = "").
        assert_eq!(
            run(r#"(str/join "-" [nil "a" nil])"#, &mut env).unwrap(),
            Value::string("-a-")
        );
    }

    #[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();
    }

    // ── clojure.spec.alpha (M1: skeleton + predicate specs + and/or) ─────────

    /// Runs `body` on a thread with a 16MB stack (macro-heavy `spec` loading
    /// triggers eager IR lowering, which recurses deeply — see
    /// `test_clojure_test_lazy_load` above for the same pattern).
    fn run_with_big_stack<F: FnOnce() + Send + 'static>(body: F) {
        std::thread::Builder::new()
            .stack_size(16 * 1024 * 1024)
            .spawn(body)
            .unwrap()
            .join()
            .unwrap();
    }

    #[test]
    fn test_spec_def_and_valid_conform() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_eq!(
                run("(s/def ::x even?)", &mut env).unwrap(),
                Value::keyword(Keyword::qualified("user", "x"))
            );
            assert_eq!(
                run("(s/valid? ::x 4)", &mut env).unwrap(),
                Value::Bool(true)
            );
            assert_eq!(
                run("(s/valid? ::x 3)", &mut env).unwrap(),
                Value::Bool(false)
            );
            assert_eq!(run("(s/conform ::x 4)", &mut env).unwrap(), Value::Long(4));
            assert_eq!(
                run("(s/invalid? (s/conform ::x 3))", &mut env).unwrap(),
                Value::Bool(true)
            );
        });
    }

    #[test]
    fn test_spec_set_and_keyword_ref() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::color #{:red :green})", &mut env).unwrap();
            assert_eq!(
                run("(s/valid? ::color :red)", &mut env).unwrap(),
                Value::Bool(true)
            );
            assert_eq!(
                run("(s/valid? ::color :blue)", &mut env).unwrap(),
                Value::Bool(false)
            );

            // keyword-registry-ref spec: ::y re-resolves ::x live.
            run("(s/def ::x even?)", &mut env).unwrap();
            run("(s/def ::y ::x)", &mut env).unwrap();
            assert_eq!(
                run("(s/valid? ::y 4)", &mut env).unwrap(),
                Value::Bool(true)
            );
            assert_eq!(
                run("(s/valid? ::y 3)", &mut env).unwrap(),
                Value::Bool(false)
            );
        });
    }

    #[test]
    fn test_spec_forward_reference() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // ::a refers to ::b before ::b is defined.
            run("(s/def ::a ::b)", &mut env).unwrap();
            run("(s/def ::b string?)", &mut env).unwrap();
            assert_eq!(
                run(r#"(s/conform ::a "hi")"#, &mut env).unwrap(),
                Value::string("hi")
            );
            assert_eq!(
                run("(s/invalid? (s/conform ::a 5))", &mut env).unwrap(),
                Value::Bool(true)
            );
        });
    }

    #[test]
    fn test_spec_and_or() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_eq!(
                run("(s/valid? (s/and int? even?) 4)", &mut env).unwrap(),
                Value::Bool(true)
            );
            assert_eq!(
                run("(s/valid? (s/and int? even?) 3)", &mut env).unwrap(),
                Value::Bool(false)
            );
            let v = run("(s/conform (s/or :i int? :s string?) 5)", &mut env).unwrap();
            match v {
                Value::Vector(vec) => {
                    let items = vec.get().iter().cloned().collect::<Vec<_>>();
                    assert_eq!(items.len(), 2);
                    assert_eq!(items[0], Value::keyword(Keyword::simple("i")));
                    assert_eq!(items[1], Value::Long(5));
                }
                other => panic!("expected [:i 5], got {other:?}"),
            }
        });
    }

    #[test]
    fn test_spec_spec_and_registry_introspection() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // Bare predicates are directly usable but not `spec?`; our own
            // record-based compound specs are.
            assert_eq!(run("(s/spec? even?)", &mut env).unwrap(), Value::Nil);
            let is_spec = run("(s/spec? (s/and int? even?))", &mut env).unwrap();
            assert!(
                !matches!(is_spec, Value::Nil),
                "expected a truthy spec object"
            );

            run("(s/def ::x even?)", &mut env).unwrap();
            assert!(!matches!(
                run("(s/get-spec ::x)", &mut env).unwrap(),
                Value::Nil
            ));
            assert!(matches!(
                run("(s/get-spec ::does-not-exist)", &mut env).unwrap(),
                Value::Nil
            ));

            run("(s/def ::pos-even (s/and int? even? pos?))", &mut env).unwrap();
            let form_v = run("(s/form ::pos-even)", &mut env).unwrap();
            assert_eq!(format!("{form_v}"), "(and int? even? pos?)");
            let describe_v = run("(s/describe ::pos-even)", &mut env).unwrap();
            assert_eq!(format!("{describe_v}"), "(and int? even? pos?)");
        });
    }

    #[test]
    fn test_spec_conform_unregistered_keyword_throws() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            let err = run("(s/conform ::does-not-exist 1)", &mut env).unwrap_err();
            let msg = format!("{err}");
            assert!(
                msg.contains("Unable to resolve spec"),
                "expected 'Unable to resolve spec' in error, got: {msg}"
            );
        });
    }

    // ── clojure.spec.alpha (M2: explain + keys/merge) ────────────────────────

    /// Asserts that a Clojure expression evaluates to exactly `true`/`false`.
    #[track_caller]
    fn assert_bool(src: &str, expected: bool, env: &mut Env) {
        assert_eq!(
            run(src, env).unwrap(),
            Value::Bool(expected),
            "expression: {src}"
        );
    }

    #[test]
    fn test_spec_keys_req_opt() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::a int?) (s/def ::b string?)", &mut env).unwrap();
            run("(s/def ::m (s/keys :req [::a] :opt [::b]))", &mut env).unwrap();
            assert_bool("(s/valid? ::m {::a 1})", true, &mut env);
            assert_bool("(s/valid? ::m {::a 1 ::b \"x\"})", true, &mut env);
            assert_bool("(s/valid? ::m {::b \"x\"})", false, &mut env); // missing req
            assert_bool("(s/valid? ::m {::a \"no\"})", false, &mut env); // bad req value
            assert_bool("(s/valid? ::m {::a 1 ::b 2})", false, &mut env); // bad opt value
            assert_bool("(s/valid? ::m 42)", false, &mut env); // not a map
            // undeclared-but-registered key is still validated (upstream semantics)
            assert_bool(
                "(s/valid? (s/keys :req [::a]) {::a 1 ::b :not-a-string})",
                false,
                &mut env,
            );
            // connectives in :req
            run("(s/def ::c boolean?)", &mut env).unwrap();
            run(
                "(s/def ::conn (s/keys :req [(or ::a (and ::b ::c))]))",
                &mut env,
            )
            .unwrap();
            assert_bool("(s/valid? ::conn {::a 1})", true, &mut env);
            assert_bool("(s/valid? ::conn {::b \"x\" ::c true})", true, &mut env);
            assert_bool("(s/valid? ::conn {::b \"x\"})", false, &mut env);
            assert_bool("(s/valid? ::conn {})", false, &mut env);
        });
    }

    #[test]
    fn test_spec_keys_un_variants() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::a int?) (s/def ::b string?)", &mut env).unwrap();
            run(
                "(s/def ::mu (s/keys :req-un [::a] :opt-un [::b]))",
                &mut env,
            )
            .unwrap();
            assert_bool("(s/valid? ::mu {:a 1})", true, &mut env);
            assert_bool("(s/valid? ::mu {:a 1 :b \"x\"})", true, &mut env);
            assert_bool("(s/valid? ::mu {:b \"x\"})", false, &mut env); // missing req-un
            assert_bool("(s/valid? ::mu {:a \"no\"})", false, &mut env); // bad value
            assert_bool("(s/valid? ::mu {:a 1 :b 2})", false, &mut env); // bad opt-un value
            assert_bool("(= {:a 1} (s/conform ::mu {:a 1}))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_keys_record() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(defrecord Point [x y])", &mut env).unwrap();
            run("(s/def ::x number?) (s/def ::y number?)", &mut env).unwrap();
            run("(s/def ::point (s/keys :req-un [::x ::y]))", &mut env).unwrap();
            assert_bool("(s/valid? ::point (->Point 1 2))", true, &mut env);
            assert_bool("(s/valid? ::point (->Point \"a\" 2))", false, &mut env);
            // conform on a record returns a record (assoc preserves type tag)
            assert_bool(
                "(record? (s/conform ::point (->Point 1 2)))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_explain_data_shape() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::a int?) (s/def ::b string?)", &mut env).unwrap();
            run("(s/def ::m (s/keys :req [::a] :opt [::b]))", &mut env).unwrap();

            // Missing-req problem: (contains? % :user/a)-style pred, path/in [].
            run("(def ed1 (s/explain-data ::m {::b \"x\"}))", &mut env).unwrap();
            assert_bool(
                "(pos? (count (:clojure.spec.alpha/problems ed1)))",
                true,
                &mut env,
            );
            let pred = run(
                "(pr-str (:pred (first (:clojure.spec.alpha/problems ed1))))",
                &mut env,
            )
            .unwrap();
            assert_eq!(pred, Value::string("(contains? % :user/a)"));
            assert_bool(
                "(= [] (:path (first (:clojure.spec.alpha/problems ed1))))",
                true,
                &mut env,
            );

            // Bad-value problem: path/in extended by the key, via extended by
            // both the named keys spec and the failing key's spec.
            run("(def ed2 (s/explain-data ::m {::a \"no\"}))", &mut env).unwrap();
            run(
                "(def p2 (first (:clojure.spec.alpha/problems ed2)))",
                &mut env,
            )
            .unwrap();
            assert_bool("(= [::a] (:path p2))", true, &mut env);
            assert_bool("(= [::a] (:in p2))", true, &mut env);
            assert_bool("(= [::m ::a] (:via p2))", true, &mut env);
            assert_bool("(= \"no\" (:val p2))", true, &mut env);

            // Valid value → nil.
            assert_bool("(nil? (s/explain-data ::m {::a 4}))", true, &mut env);

            // Whole-map value and spec recorded on the explain-data map.
            assert_bool(
                "(= {::a \"no\"} (:clojure.spec.alpha/value ed2))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_merge() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::a int?) (s/def ::b string?)", &mut env).unwrap();
            run("(s/def ::ma (s/keys :req [::a]))", &mut env).unwrap();
            run("(s/def ::mb (s/keys :req [::b]))", &mut env).unwrap();
            run("(s/def ::mab (s/merge ::ma ::mb))", &mut env).unwrap();
            assert_bool("(s/valid? ::mab {::a 1 ::b \"x\"})", true, &mut env);
            assert_bool("(s/valid? ::mab {::a 1})", false, &mut env);
            assert_bool(
                "(= {::a 1 ::b \"x\"} (s/conform ::mab {::a 1 ::b \"x\"}))",
                true,
                &mut env,
            );
            assert_bool(
                "(pos? (count (:clojure.spec.alpha/problems
                               (s/explain-data ::mab {::a 1}))))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_explain_str_and_printer() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::a int?)", &mut env).unwrap();
            run("(s/def ::m (s/keys :req [::a]))", &mut env).unwrap();
            let estr = match run("(s/explain-str ::m {::a \"no\"})", &mut env).unwrap() {
                Value::Str(s) => s.get().clone(),
                other => panic!("expected string from explain-str, got {other:?}"),
            };
            assert!(
                estr.contains("failed") && estr.contains("int?"),
                "unexpected explain-str output: {estr}"
            );
            let ok = run("(s/explain-str ::m {::a 1})", &mut env).unwrap();
            assert_eq!(ok, Value::string("Success!\n"));
        });
    }

    #[test]
    fn test_spec_keys_unform_roundtrip() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(s/def ::id (s/or :i int? :s string?))", &mut env).unwrap();
            run("(s/def ::rm (s/keys :req-un [::id]))", &mut env).unwrap();
            // conform tags the or-valued key; unform untags it.
            assert_bool("(= {:id [:i 5]} (s/conform ::rm {:id 5}))", true, &mut env);
            assert_bool(
                "(= {:id 5} (s/unform ::rm (s/conform ::rm {:id 5})))",
                true,
                &mut env,
            );
        });
    }

    // ── clojure.spec.alpha (M3: regex engine — cat/alt/*/+/?/&) ─────────────

    #[test]
    fn test_spec_regex_cat_and_nesting() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_bool(
                "(= {:a 1 :b \"x\"} (s/conform (s/cat :a int? :b string?) [1 \"x\"]))",
                true,
                &mut env,
            );
            // Nested regex splices into the same flat sequence.
            assert_bool(
                "(= {:a 1 :b [\"x\" \"y\"]}
                    (s/conform (s/cat :a int? :b (s/* string?)) [1 \"x\" \"y\"]))",
                true,
                &mut env,
            );
            // Wrong element type / too short / too long are all invalid.
            assert_bool(
                "(s/invalid? (s/conform (s/cat :a int? :b string?) [1 2]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/cat :a int? :b string?) [1]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/cat :a int?) [1 2]))",
                true,
                &mut env,
            );
            // Non-sequential input is invalid, not an error.
            assert_bool("(s/invalid? (s/conform (s/cat :a int?) 5))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_regex_alt_star_plus_maybe() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // alt tags its branch.
            assert_bool(
                "(= [:i 5] (s/conform (s/alt :i int? :s string?) [5]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/alt :i int? :s string?) [:kw]))",
                true,
                &mut env,
            );
            // * matches empty and many; fails on a bad element.
            assert_bool("(= [] (s/conform (s/* int?) []))", true, &mut env);
            assert_bool("(s/valid? (s/* int?) [])", true, &mut env);
            assert_bool("(= [1 2 3] (s/conform (s/* int?) [1 2 3]))", true, &mut env);
            assert_bool(
                "(s/invalid? (s/conform (s/* int?) [1 :a 3]))",
                true,
                &mut env,
            );
            // + requires at least one.
            assert_bool("(= [1] (s/conform (s/+ int?) [1]))", true, &mut env);
            assert_bool("(s/invalid? (s/conform (s/+ int?) []))", true, &mut env);
            // ? is optional: value when present, nil when absent.
            assert_bool("(= 5 (s/conform (s/? int?) [5]))", true, &mut env);
            assert_bool("(nil? (s/conform (s/? int?) []))", true, &mut env);
            assert_bool("(s/valid? (s/? int?) [])", true, &mut env);
            assert_bool("(s/invalid? (s/conform (s/? int?) [1 2]))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_regex_amp_and_regex_inside_and() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(def even-count? (fn [xs] (even? (count xs))))", &mut env).unwrap();
            // & applies post-predicates to the conformed regex result.
            assert_bool(
                "(= [1 2] (s/conform (s/& (s/* int?) even-count?) [1 2]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/& (s/* int?) even-count?) [1 2 3]))",
                true,
                &mut env,
            );
            // A regex op nested in s/and conforms the whole seq first, then
            // threads the conformed value through the remaining preds.
            run("(def all-even? (fn [xs] (every? even? xs)))", &mut env).unwrap();
            assert_bool(
                "(= [2 4] (s/conform (s/and (s/* int?) all-even?) [2 4]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/valid? (s/and (s/* int?) all-even?) [1 2])",
                false,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_regex_keyword_ref_children() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // A keyword ref to a NON-regex spec consumes exactly one element.
            run("(s/def ::a int?)", &mut env).unwrap();
            assert_bool(
                "(= {:x 1 :y \"x\"} (s/conform (s/cat :x ::a :y string?) [1 \"x\"]))",
                true,
                &mut env,
            );
            // A keyword ref to a REGEX spec splices (upstream reg-resolve!
            // semantics).
            run("(s/def ::r (s/* int?))", &mut env).unwrap();
            assert_bool(
                "(= {:nums [1 2] :tail \"x\"}
                    (s/conform (s/cat :nums ::r :tail string?) [1 2 \"x\"]))",
                true,
                &mut env,
            );
            // s/spec wrapping forces a nested one-element boundary instead.
            assert_bool(
                "(= {:nums [1 2] :tail \"x\"}
                    (s/conform (s/cat :nums (s/spec (s/* int?)) :tail string?)
                               [[1 2] \"x\"]))",
                true,
                &mut env,
            );
            // Registered regex works at top level via the keyword.
            assert_bool("(= [1 2 3] (s/conform ::r [1 2 3]))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_regex_explain_reasons() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // Premature end of input → "Insufficient input" at the missing key.
            run(
                "(def p-insuff (first (:clojure.spec.alpha/problems
                                       (s/explain-data (s/cat :a int? :b string?) [1]))))",
                &mut env,
            )
            .unwrap();
            assert_bool(
                "(= \"Insufficient input\" (:reason p-insuff))",
                true,
                &mut env,
            );
            assert_bool("(= [:b] (:path p-insuff))", true, &mut env);
            // Leftover input → "Extra input" with :in pointing at the index.
            run(
                "(def p-extra (first (:clojure.spec.alpha/problems
                                      (s/explain-data (s/cat :a int?) [1 2]))))",
                &mut env,
            )
            .unwrap();
            assert_bool("(= \"Extra input\" (:reason p-extra))", true, &mut env);
            assert_bool("(= [1] (:in p-extra))", true, &mut env);
            // Element failure mid-sequence: path names the cat key, in the index.
            run(
                "(def p-elem (first (:clojure.spec.alpha/problems
                                     (s/explain-data (s/cat :a int? :b string?) [1 :bad]))))",
                &mut env,
            )
            .unwrap();
            assert_bool("(= [:b] (:path p-elem))", true, &mut env);
            assert_bool("(= [1] (:in p-elem))", true, &mut env);
            assert_bool("(= :bad (:val p-elem))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_regex_unform_roundtrips() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(def even-count? (fn [xs] (even? (count xs))))", &mut env).unwrap();
            for (spec, input) in [
                ("(s/cat :a int? :b string?)", "[1 \"x\"]"),
                ("(s/cat :a int? :b (s/* string?))", "[1 \"x\" \"y\"]"),
                ("(s/alt :i int? :s string?)", "[5]"),
                ("(s/* int?)", "[1 2 3]"),
                ("(s/* int?)", "[]"),
                ("(s/+ int?)", "[1 2]"),
                ("(s/? int?)", "[5]"),
                ("(s/? int?)", "[]"),
                ("(s/& (s/* int?) even-count?)", "[1 2]"),
            ] {
                assert_bool(
                    &format!(
                        "(let [re {spec}] (= {input} (vec (s/unform re (s/conform re {input})))))"
                    ),
                    true,
                    &mut env,
                );
            }
        });
    }

    #[test]
    fn test_spec_plain_map_is_not_a_spec() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            let err = run("(s/conform {:a 1} 5)", &mut env).unwrap_err();
            let msg = format!("{err}");
            assert!(
                msg.contains("not a valid spec"),
                "expected 'not a valid spec' in error, got: {msg}"
            );
        });
    }

    // ── clojure.spec.alpha (M4: collections + leaf specs) ────────────────────

    #[test]
    fn test_spec_coll_of_options() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // happy / sad
            assert_bool(
                "(= [1 2 3] (s/conform (s/coll-of int?) [1 2 3]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/coll-of int?) [1 \"x\"]))",
                true,
                &mut env,
            );
            // :kind
            assert_bool(
                "(s/invalid? (s/conform (s/coll-of int? :kind vector?) '(1 2 3)))",
                true,
                &mut env,
            );
            // :min-count / :max-count
            assert_bool(
                "(s/invalid? (s/conform (s/coll-of int? :min-count 3) [1 2]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/coll-of int? :max-count 2) [1 2 3]))",
                true,
                &mut env,
            );
            // :distinct
            assert_bool(
                "(= [1 2 3] (s/conform (s/coll-of int? :distinct true) [1 2 3]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/coll-of int? :distinct true) [1 1 2]))",
                true,
                &mut env,
            );
            // :into
            assert_bool(
                "(= #{1 2 3} (s/conform (s/coll-of int? :into #{}) [1 2 3]))",
                true,
                &mut env,
            );
            // default (no :into) preserves order for list input; explicit
            // :into '() conjes raw (reverses) — see EverySpec doc comment.
            assert_bool(
                "(= '(1 2 3) (s/conform (s/coll-of int?) '(1 2 3)))",
                true,
                &mut env,
            );
            assert_bool(
                "(= '(3 2 1) (s/conform (s/coll-of int? :into '()) '(1 2 3)))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_map_of_key_handling() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            // default: keys must be valid but ORIGINAL keys are kept
            assert_bool(
                "(= {:a 1 :b 2} (s/conform (s/map-of keyword? int?) {:a 1 :b 2}))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/map-of keyword? int?) {:a \"x\"}))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/map-of keyword? int?) {\"not-kw\" 1}))",
                true,
                &mut env,
            );
            // :conform-keys true swaps in the conformed key
            assert_bool(
                r#"(= {"a" 1} (s/conform (s/map-of (s/conformer name) int? :conform-keys true) {:a 1}))"#,
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_every_vs_coll_of_conform_difference() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(def elem (s/or :i int? :s string?))", &mut env).unwrap();
            // coll-of conforms every element (tagged vectors)
            assert_bool(
                "(= [[:i 1] [:s \"x\"]] (s/conform (s/coll-of elem) [1 \"x\"]))",
                true,
                &mut env,
            );
            // every only validates — returns x unchanged
            assert_bool(
                "(= [1 \"x\"] (s/conform (s/every elem) [1 \"x\"]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/every elem) [1 :bad]))",
                true,
                &mut env,
            );
            // every-kv validates both k/v but never rebuilds
            assert_bool(
                "(= {:a 1} (s/conform (s/every-kv keyword? int?) {:a 1}))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/every-kv keyword? int?) {:a \"x\"}))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_tuple_conform_and_explain() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_bool(
                "(= [1 \"x\"] (s/conform (s/tuple int? string?) [1 \"x\"]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/tuple int? string?) [1]))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform (s/tuple int? string?) 5))",
                true,
                &mut env,
            );
            run(
                "(def tp (first (:clojure.spec.alpha/problems (s/explain-data (s/tuple int? string?) [1 :bad]))))",
                &mut env,
            )
            .unwrap();
            assert_bool("(= [1] (:path tp))", true, &mut env);
            assert_bool("(= [1] (:in tp))", true, &mut env);
            assert_bool("(= :bad (:val tp))", true, &mut env);
            // round-trip unform
            assert_bool(
                "(= [1 \"x\"] (s/unform (s/tuple int? string?) (s/conform (s/tuple int? string?) [1 \"x\"])))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_nilable_both_branches_and_explain_shape() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_bool("(= nil (s/conform (s/nilable int?) nil))", true, &mut env);
            assert_bool("(= 5 (s/conform (s/nilable int?) 5))", true, &mut env);
            assert_bool(
                "(s/invalid? (s/conform (s/nilable int?) \"x\"))",
                true,
                &mut env,
            );
            run(
                "(def np (:clojure.spec.alpha/problems (s/explain-data (s/nilable int?) \"x\")))",
                &mut env,
            )
            .unwrap();
            assert_bool("(= 2 (count np))", true, &mut env);
            assert_bool(
                "(some (fn [p] (= [:clojure.spec.alpha/nil] (:path p))) np)",
                true,
                &mut env,
            );
            assert_bool(
                "(some (fn [p] (= [:clojure.spec.alpha/pred] (:path p))) np)",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_multi_spec_conform_and_no_method() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(defmulti event-type :type)", &mut env).unwrap();
            run("(s/def :evt/type keyword?)", &mut env).unwrap();
            run("(s/def :evt/a (s/keys :req-un [:evt/type]))", &mut env).unwrap();
            run("(defmethod event-type :a [_] :evt/a)", &mut env).unwrap();
            run(
                "(s/def :evt/event (s/multi-spec event-type :type))",
                &mut env,
            )
            .unwrap();
            assert_bool(
                "(= {:type :a} (s/conform :evt/event {:type :a}))",
                true,
                &mut env,
            );
            assert_bool(
                "(s/invalid? (s/conform :evt/event {:type :unknown}))",
                true,
                &mut env,
            );
            run(
                "(def mp (first (:clojure.spec.alpha/problems (s/explain-data :evt/event {:type :unknown}))))",
                &mut env,
            )
            .unwrap();
            assert_bool("(= \"no method\" (:reason mp))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_conformer_transforms_and_threads_through_and() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_bool(
                "(= 10 (s/conform (s/conformer #(* 2 %)) 5))",
                true,
                &mut env,
            );
            // threads the transformed value through the rest of s/and
            assert_bool(
                "(= 10 (s/conform (s/and int? (s/conformer #(* 2 %))) 5))",
                true,
                &mut env,
            );
            assert_bool(
                "(= 5 (s/unform (s/conformer #(* 2 %) #(/ % 2)) 10))",
                true,
                &mut env,
            );
            // no unf given -> unform is identity
            assert_bool(
                "(= 10 (s/unform (s/conformer #(* 2 %)) 10))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_int_in_and_double_in_bounds() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_bool("(s/valid? (s/int-in 0 10) 5)", true, &mut env);
            assert_bool("(s/valid? (s/int-in 0 10) 10)", false, &mut env); // end exclusive
            assert_bool("(s/valid? (s/int-in 0 10) 5.0)", false, &mut env); // not an int?
            assert_bool(
                "(s/valid? (s/double-in :min 0.0 :max 10.0) 5.0)",
                true,
                &mut env,
            );
            assert_bool(
                "(s/valid? (s/double-in :min 0.0 :max 10.0) 20.0)",
                false,
                &mut env,
            );
            // NaN produced via arithmetic (NOT the ##NaN reader literal — that
            // literal hangs this runtime indefinitely on eval, a pre-existing
            // bug unrelated to spec.alpha; see M4 report).
            run("(def nan (/ 0.0 0.0))", &mut env).unwrap();
            run("(def pos-inf (/ 1.0 0.0))", &mut env).unwrap();
            assert_bool("(s/valid? (s/double-in :NaN? false) nan)", false, &mut env);
            assert_bool("(s/valid? (s/double-in) nan)", true, &mut env);
            assert_bool(
                "(s/valid? (s/double-in :infinite? false) pos-inf)",
                false,
                &mut env,
            );
            assert_bool("(s/valid? (s/double-in) pos-inf)", true, &mut env);
            // nonconforming: validates but returns x unconformed
            assert_bool(
                "(= [1 \"x\"] (s/conform (s/nonconforming (s/cat :a int? :b string?)) [1 \"x\"]))",
                true,
                &mut env,
            );
            // inst-in: not implemented, throws clearly
            let err = run("(s/inst-in 0 1)", &mut env).unwrap_err();
            let msg = format!("{err}");
            assert!(
                msg.contains("not implemented"),
                "expected 'not implemented' in error, got: {msg}"
            );
        });
    }

    // ── clojure.spec.alpha / .test.alpha / .gen.alpha (M5: fdef/instrument) ──

    #[test]
    fn test_spec_fdef_registers_qualified_symbol_and_get_spec() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(defn my-add [a b] (+ a b))", &mut env).unwrap();
            assert_bool(
                "(= 'user/my-add (s/fdef my-add :args (s/cat :a int? :b int?) :ret int?))",
                true,
                &mut env,
            );
            assert_bool("(s/fspec? (s/get-spec 'user/my-add))", true, &mut env);
            assert_bool("(some? (:args (s/get-spec 'user/my-add)))", true, &mut env);
            // syntax-quote auto-qualification against the current ns resolves
            // to the same registry entry as the explicit qualified symbol.
            assert_bool(
                "(= (s/get-spec 'user/my-add) (s/get-spec `my-add))",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_instrument_valid_and_invalid_calls() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(require '[clojure.spec.test.alpha :as stest])", &mut env).unwrap();
            run("(defn my-add [a b] (+ a b))", &mut env).unwrap();
            run(
                "(s/fdef my-add :args (s/cat :a int? :b int?) :ret int?)",
                &mut env,
            )
            .unwrap();
            run("(stest/instrument 'user/my-add)", &mut env).unwrap();
            // valid call still returns the normal value through the wrapper.
            assert_eq!(run("(my-add 2 3)", &mut env).unwrap(), Value::Long(5));
            // invalid call throws with the expected message and ex-data.
            run(
                r#"(def caught
                     (try (my-add 2 "x") :did-not-throw
                          (catch Exception e {:msg (ex-message e) :data (ex-data e)})))"#,
                &mut env,
            )
            .unwrap();
            assert_bool(
                r#"(= "Call to user/my-add did not conform to spec." (:msg caught))"#,
                true,
                &mut env,
            );
            assert_bool(
                "(= :instrument (:clojure.spec.alpha/failure (:data caught)))",
                true,
                &mut env,
            );
            assert_bool(
                "(contains? (:data caught) :clojure.spec.test.alpha/caller)",
                true,
                &mut env,
            );
        });
    }

    #[test]
    fn test_spec_unstrument_restores_raw_fn() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(require '[clojure.spec.test.alpha :as stest])", &mut env).unwrap();
            run("(defn my-pair [a b] [a b])", &mut env).unwrap();
            run("(s/fdef my-pair :args (s/cat :a int? :b int?))", &mut env).unwrap();
            run("(stest/instrument 'user/my-pair)", &mut env).unwrap();
            assert!(run("(my-pair 1 \"x\")", &mut env).is_err());
            run("(stest/unstrument 'user/my-pair)", &mut env).unwrap();
            // no longer wrapped -- the raw fn has no type constraints, so an
            // "invalid by spec" call now succeeds instead of throwing.
            assert_bool("(= [1 \"x\"] (my-pair 1 \"x\"))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_instrument_affects_call_sites_evaluated_before_instrument() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(require '[clojure.spec.test.alpha :as stest])", &mut env).unwrap();
            run("(defn my-mul [a b] (* a b))", &mut env).unwrap();
            run("(s/fdef my-mul :args (s/cat :a int? :b int?))", &mut env).unwrap();
            // Warm up this call site (and any inline-cached/lowered code for
            // it) BEFORE instrumenting.
            assert_eq!(run("(my-mul 2 3)", &mut env).unwrap(), Value::Long(6));
            run("(stest/instrument 'user/my-mul)", &mut env).unwrap();
            // A stale inline cache pointing at the pre-instrument var root
            // would silently skip the spec check here.
            assert!(run("(my-mul 2 \"x\")", &mut env).is_err());
        });
    }

    #[test]
    fn test_spec_instrumentable_syms_and_idempotent_double_instrument() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(require '[clojure.spec.test.alpha :as stest])", &mut env).unwrap();
            run("(defn my-pair2 [a b] [a b])", &mut env).unwrap();
            run("(s/fdef my-pair2 :args (s/cat :a int? :b int?))", &mut env).unwrap();
            assert_bool(
                "(boolean (some #{'user/my-pair2} (stest/instrumentable-syms)))",
                true,
                &mut env,
            );
            run("(stest/instrument 'user/my-pair2)", &mut env).unwrap();
            run("(stest/instrument 'user/my-pair2)", &mut env).unwrap(); // idempotent
            assert!(run("(my-pair2 1 \"x\")", &mut env).is_err());
            // A SINGLE unstrument must fully restore -- if double-instrument
            // had double-wrapped, one layer would still be active and the
            // call below would still throw.
            run("(stest/unstrument 'user/my-pair2)", &mut env).unwrap();
            assert_bool("(= [1 \"x\"] (my-pair2 1 \"x\"))", true, &mut env);
        });
    }

    #[test]
    fn test_spec_with_instrument_disabled_bypasses_checks() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(require '[clojure.spec.test.alpha :as stest])", &mut env).unwrap();
            run("(defn my-pair3 [a b] [a b])", &mut env).unwrap();
            run("(s/fdef my-pair3 :args (s/cat :a int? :b int?))", &mut env).unwrap();
            run("(stest/instrument 'user/my-pair3)", &mut env).unwrap();
            assert!(run("(my-pair3 1 \"x\")", &mut env).is_err());
            assert_bool(
                "(stest/with-instrument-disabled (= [1 \"x\"] (my-pair3 1 \"x\")))",
                true,
                &mut env,
            );
            // instrumentation resumes outside the dynamic extent.
            assert!(run("(my-pair3 1 \"x\")", &mut env).is_err());
        });
    }

    #[test]
    fn test_spec_assert_happy_sad_and_check_asserts_toggle() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            assert_eq!(run("(s/assert even? 4)", &mut env).unwrap(), Value::Long(4));
            assert!(run("(s/assert even? 5)", &mut env).is_err());
            run("(s/check-asserts false)", &mut env).unwrap();
            // a freshly (re-)macroexpanded s/assert form reads
            // *compile-asserts* at macroexpansion time and passes an invalid
            // value through unchecked.
            assert_eq!(run("(s/assert even? 5)", &mut env).unwrap(), Value::Long(5));
            run("(s/check-asserts true)", &mut env).unwrap();
            assert!(run("(s/assert even? 5)", &mut env).is_err());
        });
    }

    #[test]
    fn test_spec_gen_and_check_throw_not_implemented_and_gen_ns_loads() {
        run_with_big_stack(|| {
            let (_, mut env) = make_env();
            run("(require '[clojure.spec.alpha :as s])", &mut env).unwrap();
            run("(require '[clojure.spec.test.alpha :as stest])", &mut env).unwrap();
            run("(require '[clojure.spec.gen.alpha :as gen])", &mut env).unwrap();
            for src in [
                "(s/gen even?)",
                "(s/exercise even?)",
                "(s/exercise-fn 'user/foo)",
                "(stest/check)",
                "(stest/check 'user/foo)",
                "(stest/check-fn (fn [x] x) even?)",
                "(gen/generate :whatever)",
                "(gen/sample :whatever)",
                "(gen/elements [1 2 3])",
            ] {
                assert!(run(src, &mut env).is_err(), "expected {src} to throw");
            }
        });
    }
}