seq-compiler 3.0.6

Compiler for the Seq programming language
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
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
//! Built-in word signatures for Seq
//!
//! Defines the stack effects for all runtime built-in operations.
//!
//! Uses declarative macros to minimize boilerplate. The `builtin!` macro
//! supports a Forth-like notation: `(a Type1 Type2 -- a Type3)` where:
//! - `a` is the row variable (representing "rest of stack")
//! - Concrete types: `Int`, `String`, `Float`
//! - Type variables: single uppercase letters like `T`, `U`, `V`

use crate::types::{Effect, SideEffect, StackType, Type};
use std::collections::HashMap;
use std::sync::LazyLock;

/// Convert a type token to a Type expression
macro_rules! ty {
    (Int) => {
        Type::Int
    };
    (Bool) => {
        Type::Bool
    };
    (String) => {
        Type::String
    };
    (Float) => {
        Type::Float
    };
    (Symbol) => {
        Type::Symbol
    };
    (Channel) => {
        Type::Channel
    };
    // Single uppercase letter = type variable
    (T) => {
        Type::Var("T".to_string())
    };
    (U) => {
        Type::Var("U".to_string())
    };
    (V) => {
        Type::Var("V".to_string())
    };
    (W) => {
        Type::Var("W".to_string())
    };
    (K) => {
        Type::Var("K".to_string())
    };
    (M) => {
        Type::Var("M".to_string())
    };
    (Q) => {
        Type::Var("Q".to_string())
    };
    // Multi-char type variables (T1, T2, etc.)
    (T1) => {
        Type::Var("T1".to_string())
    };
    (T2) => {
        Type::Var("T2".to_string())
    };
    (T3) => {
        Type::Var("T3".to_string())
    };
    (T4) => {
        Type::Var("T4".to_string())
    };
    (V2) => {
        Type::Var("V2".to_string())
    };
    (M2) => {
        Type::Var("M2".to_string())
    };
    (Acc) => {
        Type::Var("Acc".to_string())
    };
}

/// Build a stack type from row variable 'a' plus pushed types
macro_rules! stack {
    // Just the row variable
    (a) => {
        StackType::RowVar("a".to_string())
    };
    // Row variable with one type pushed
    (a $t1:tt) => {
        StackType::RowVar("a".to_string()).push(ty!($t1))
    };
    // Row variable with two types pushed
    (a $t1:tt $t2:tt) => {
        StackType::RowVar("a".to_string())
            .push(ty!($t1))
            .push(ty!($t2))
    };
    // Row variable with three types pushed
    (a $t1:tt $t2:tt $t3:tt) => {
        StackType::RowVar("a".to_string())
            .push(ty!($t1))
            .push(ty!($t2))
            .push(ty!($t3))
    };
    // Row variable with four types pushed
    (a $t1:tt $t2:tt $t3:tt $t4:tt) => {
        StackType::RowVar("a".to_string())
            .push(ty!($t1))
            .push(ty!($t2))
            .push(ty!($t3))
            .push(ty!($t4))
    };
    // Row variable with five types pushed
    (a $t1:tt $t2:tt $t3:tt $t4:tt $t5:tt) => {
        StackType::RowVar("a".to_string())
            .push(ty!($t1))
            .push(ty!($t2))
            .push(ty!($t3))
            .push(ty!($t4))
            .push(ty!($t5))
    };
    // Row variable 'b' (used in some signatures)
    (b) => {
        StackType::RowVar("b".to_string())
    };
    (b $t1:tt) => {
        StackType::RowVar("b".to_string()).push(ty!($t1))
    };
    (b $t1:tt $t2:tt) => {
        StackType::RowVar("b".to_string())
            .push(ty!($t1))
            .push(ty!($t2))
    };
}

/// Define a builtin signature with Forth-like stack effect notation
///
/// Usage: `builtin!(sigs, "name", (a Type1 Type2 -- a Type3));`
macro_rules! builtin {
    // (a -- a)
    ($sigs:ident, $name:expr, (a -- a)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a), stack!(a)));
    };
    // (a -- a T)
    ($sigs:ident, $name:expr, (a -- a $o1:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a), stack!(a $o1)));
    };
    // (a -- a T U)
    ($sigs:ident, $name:expr, (a -- a $o1:tt $o2:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a), stack!(a $o1 $o2)));
    };
    // (a T -- a)
    ($sigs:ident, $name:expr, (a $i1:tt -- a)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1), stack!(a)));
    };
    // (a T -- a U)
    ($sigs:ident, $name:expr, (a $i1:tt -- a $o1:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1), stack!(a $o1)));
    };
    // (a T -- a U V)
    ($sigs:ident, $name:expr, (a $i1:tt -- a $o1:tt $o2:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1), stack!(a $o1 $o2)));
    };
    // (a T U -- a)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a)));
    };
    // (a T U -- a V)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1)));
    };
    // (a T U -- a V W)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt $o2:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1 $o2)));
    };
    // (a T U -- a V W X)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt $o2:tt $o3:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1 $o2 $o3)));
    };
    // (a T U -- a V W X Y)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt $o2:tt $o3:tt $o4:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1 $o2 $o3 $o4)));
    };
    // (a T U V -- a)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a)));
    };
    // (a T U V -- a W)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a $o1:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a $o1)));
    };
    // (a T U V -- a W X)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a $o1:tt $o2:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a $o1 $o2)));
    };
    // (a T U V -- a W X Y)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a $o1:tt $o2:tt $o3:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a $o1 $o2 $o3)));
    };
    // (a T U V W -- a X)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt $i4:tt -- a $o1:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3 $i4), stack!(a $o1)));
    };
    // (a T U V W X -- a Y)
    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt $i4:tt $i5:tt -- a $o1:tt)) => {
        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3 $i4 $i5), stack!(a $o1)));
    };
}

/// Define multiple builtins with the same signature
/// Note: Can't use a generic macro due to tt repetition issues, so we use specific helpers
macro_rules! builtins_int_int_to_int {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a Int Int -- a Int));
        )+
    };
}

macro_rules! builtins_int_int_to_bool {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a Int Int -- a Bool));
        )+
    };
}

macro_rules! builtins_bool_bool_to_bool {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a Bool Bool -- a Bool));
        )+
    };
}

macro_rules! builtins_int_to_int {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a Int -- a Int));
        )+
    };
}

macro_rules! builtins_string_to_string {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a String -- a String));
        )+
    };
}

macro_rules! builtins_float_float_to_float {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a Float Float -- a Float));
        )+
    };
}

macro_rules! builtins_float_float_to_bool {
    ($sigs:ident, $($name:expr),+ $(,)?) => {
        $(
            builtin!($sigs, $name, (a Float Float -- a Bool));
        )+
    };
}

/// Get the stack effect signature for a built-in word
pub fn builtin_signature(name: &str) -> Option<Effect> {
    let signatures = builtin_signatures();
    signatures.get(name).cloned()
}

/// Get all built-in word signatures
pub fn builtin_signatures() -> HashMap<String, Effect> {
    let mut sigs = HashMap::new();

    // =========================================================================
    // I/O Operations
    // =========================================================================

    builtin!(sigs, "io.write", (a String -- a)); // Write without newline
    builtin!(sigs, "io.write-line", (a String -- a));
    builtin!(sigs, "io.read-line", (a -- a String Bool)); // Returns line + success flag
    builtin!(sigs, "io.read-line+", (a -- a String Int)); // DEPRECATED: use io.read-line instead
    builtin!(sigs, "io.read-n", (a Int -- a String Int)); // Read N bytes, returns bytes + status

    // =========================================================================
    // Command-line Arguments
    // =========================================================================

    builtin!(sigs, "args.count", (a -- a Int));
    builtin!(sigs, "args.at", (a Int -- a String));

    // =========================================================================
    // File Operations
    // =========================================================================

    builtin!(sigs, "file.slurp", (a String -- a String Bool)); // returns (content success) - errors are values
    builtin!(sigs, "file.exists?", (a String -- a Bool));

    // file.for-each-line+: Complex quotation type - defined manually
    sigs.insert(
        "file.for-each-line+".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string())
                .push(Type::String)
                .push(Type::Quotation(Box::new(Effect::new(
                    StackType::RowVar("a".to_string()).push(Type::String),
                    StackType::RowVar("a".to_string()),
                )))),
            StackType::RowVar("a".to_string())
                .push(Type::String)
                .push(Type::Bool),
        ),
    );

    // =========================================================================
    // Type Conversions
    // =========================================================================

    builtin!(sigs, "int->string", (a Int -- a String));
    builtin!(sigs, "int->float", (a Int -- a Float));
    builtin!(sigs, "float->int", (a Float -- a Int));
    builtin!(sigs, "float->string", (a Float -- a String));
    builtin!(sigs, "string->int", (a String -- a Int Bool)); // value + success flag
    builtin!(sigs, "string->float", (a String -- a Float Bool)); // value + success flag
    builtin!(sigs, "char->string", (a Int -- a String));
    builtin!(sigs, "symbol->string", (a Symbol -- a String));
    builtin!(sigs, "string->symbol", (a String -- a Symbol));

    // =========================================================================
    // Integer Arithmetic ( a Int Int -- a Int )
    // =========================================================================

    builtins_int_int_to_int!(sigs, "i.add", "i.subtract", "i.multiply");
    builtins_int_int_to_int!(sigs, "i.+", "i.-", "i.*");

    // Division operations return ( a Int Int -- a Int Bool ) for error handling
    builtin!(sigs, "i.divide", (a Int Int -- a Int Bool));
    builtin!(sigs, "i.modulo", (a Int Int -- a Int Bool));
    builtin!(sigs, "i./", (a Int Int -- a Int Bool));
    builtin!(sigs, "i.%", (a Int Int -- a Int Bool));

    // =========================================================================
    // Integer Comparison ( a Int Int -- a Bool )
    // =========================================================================

    builtins_int_int_to_bool!(sigs, "i.=", "i.<", "i.>", "i.<=", "i.>=", "i.<>");
    builtins_int_int_to_bool!(sigs, "i.eq", "i.lt", "i.gt", "i.lte", "i.gte", "i.neq");

    // =========================================================================
    // Boolean Operations ( a Bool Bool -- a Bool )
    // =========================================================================

    builtins_bool_bool_to_bool!(sigs, "and", "or");
    builtin!(sigs, "not", (a Bool -- a Bool));

    // =========================================================================
    // Bitwise Operations
    // =========================================================================

    builtins_int_int_to_int!(sigs, "band", "bor", "bxor", "shl", "shr");
    builtins_int_to_int!(sigs, "bnot", "popcount", "clz", "ctz");
    builtin!(sigs, "int-bits", (a -- a Int));

    // =========================================================================
    // Stack Operations (Polymorphic)
    // =========================================================================

    builtin!(sigs, "dup", (a T -- a T T));
    builtin!(sigs, "drop", (a T -- a));
    builtin!(sigs, "swap", (a T U -- a U T));
    builtin!(sigs, "over", (a T U -- a T U T));
    builtin!(sigs, "rot", (a T U V -- a U V T));
    builtin!(sigs, "nip", (a T U -- a U));
    builtin!(sigs, "tuck", (a T U -- a U T U));
    builtin!(sigs, "2dup", (a T U -- a T U T U));
    builtin!(sigs, "3drop", (a T U V -- a));

    // pick and roll: Type approximations (see detailed comments below)
    // pick: ( ..a T Int -- ..a T T ) - copies value at depth n to top
    builtin!(sigs, "pick", (a T Int -- a T T));
    // roll: ( ..a T Int -- ..a T ) - rotates n+1 items, bringing depth n to top
    builtin!(sigs, "roll", (a T Int -- a T));

    // =========================================================================
    // Channel Operations (CSP-style concurrency)
    // Errors are values, not crashes - all ops return success flags
    // =========================================================================

    builtin!(sigs, "chan.make", (a -- a Channel));
    builtin!(sigs, "chan.send", (a T Channel -- a Bool)); // returns success flag
    builtin!(sigs, "chan.receive", (a Channel -- a T Bool)); // returns value and success flag
    builtin!(sigs, "chan.close", (a Channel -- a));
    builtin!(sigs, "chan.yield", (a - -a));

    // =========================================================================
    // Quotation/Control Flow Operations
    // =========================================================================

    // call: Polymorphic - accepts Quotation or Closure
    // Uses type variable Q to represent "something callable"
    sigs.insert(
        "call".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string()).push(Type::Var("Q".to_string())),
            StackType::RowVar("b".to_string()),
        ),
    );

    // cond: Multi-way conditional (variable arity)
    sigs.insert(
        "cond".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string()),
            StackType::RowVar("b".to_string()),
        ),
    );

    // strand.spawn: ( a Quotation -- a Int ) - spawn a concurrent strand
    // The quotation can have any stack effect - it runs independently
    sigs.insert(
        "strand.spawn".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string()).push(Type::Quotation(Box::new(Effect::new(
                StackType::RowVar("spawn_in".to_string()),
                StackType::RowVar("spawn_out".to_string()),
            )))),
            StackType::RowVar("a".to_string()).push(Type::Int),
        ),
    );

    // strand.weave: ( a Quotation -- a handle ) - create a woven strand (generator)
    // The quotation receives (WeaveCtx, first_resume_value) and must thread WeaveCtx through.
    // Returns a handle (WeaveCtx) for use with strand.resume.
    sigs.insert(
        "strand.weave".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string()).push(Type::Quotation(Box::new(Effect::new(
                StackType::RowVar("weave_in".to_string()),
                StackType::RowVar("weave_out".to_string()),
            )))),
            StackType::RowVar("a".to_string()).push(Type::Var("handle".to_string())),
        ),
    );

    // strand.resume: ( a handle b -- a handle b Bool ) - resume weave with value
    // Takes handle and value to send, returns (handle, yielded_value, has_more)
    sigs.insert(
        "strand.resume".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string())
                .push(Type::Var("handle".to_string()))
                .push(Type::Var("b".to_string())),
            StackType::RowVar("a".to_string())
                .push(Type::Var("handle".to_string()))
                .push(Type::Var("b".to_string()))
                .push(Type::Bool),
        ),
    );

    // yield: ( a ctx b -- a ctx b | Yield b ) - yield value and receive resume value
    // The WeaveCtx must be passed explicitly and threaded through.
    // The Yield effect indicates this word produces yield semantics.
    sigs.insert(
        "yield".to_string(),
        Effect::with_effects(
            StackType::RowVar("a".to_string())
                .push(Type::Var("ctx".to_string()))
                .push(Type::Var("b".to_string())),
            StackType::RowVar("a".to_string())
                .push(Type::Var("ctx".to_string()))
                .push(Type::Var("b".to_string())),
            vec![SideEffect::Yield(Box::new(Type::Var("b".to_string())))],
        ),
    );

    // strand.weave-cancel: ( a handle -- a ) - cancel a weave and release its resources
    // Use this to clean up a weave that won't be resumed to completion.
    // This prevents resource leaks from abandoned weaves.
    sigs.insert(
        "strand.weave-cancel".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string()).push(Type::Var("handle".to_string())),
            StackType::RowVar("a".to_string()),
        ),
    );

    // =========================================================================
    // TCP Operations
    // =========================================================================

    // TCP operations return Bool for error handling
    builtin!(sigs, "tcp.listen", (a Int -- a Int Bool));
    builtin!(sigs, "tcp.accept", (a Int -- a Int Bool));
    builtin!(sigs, "tcp.read", (a Int -- a String Bool));
    builtin!(sigs, "tcp.write", (a String Int -- a Bool));
    builtin!(sigs, "tcp.close", (a Int -- a Bool));

    // =========================================================================
    // OS Operations
    // =========================================================================

    builtin!(sigs, "os.getenv", (a String -- a String Bool));
    builtin!(sigs, "os.home-dir", (a -- a String Bool));
    builtin!(sigs, "os.current-dir", (a -- a String Bool));
    builtin!(sigs, "os.path-exists", (a String -- a Bool));
    builtin!(sigs, "os.path-is-file", (a String -- a Bool));
    builtin!(sigs, "os.path-is-dir", (a String -- a Bool));
    builtin!(sigs, "os.path-join", (a String String -- a String));
    builtin!(sigs, "os.path-parent", (a String -- a String Bool));
    builtin!(sigs, "os.path-filename", (a String -- a String Bool));
    builtin!(sigs, "os.exit", (a Int -- a)); // Never returns, but typed as identity
    builtin!(sigs, "os.name", (a -- a String));
    builtin!(sigs, "os.arch", (a -- a String));

    // =========================================================================
    // Signal Handling (Unix signals)
    // =========================================================================

    builtin!(sigs, "signal.trap", (a Int -- a));
    builtin!(sigs, "signal.received?", (a Int -- a Bool));
    builtin!(sigs, "signal.pending?", (a Int -- a Bool));
    builtin!(sigs, "signal.default", (a Int -- a));
    builtin!(sigs, "signal.ignore", (a Int -- a));
    builtin!(sigs, "signal.clear", (a Int -- a));
    // Signal constants (platform-correct values)
    builtin!(sigs, "signal.SIGINT", (a -- a Int));
    builtin!(sigs, "signal.SIGTERM", (a -- a Int));
    builtin!(sigs, "signal.SIGHUP", (a -- a Int));
    builtin!(sigs, "signal.SIGPIPE", (a -- a Int));
    builtin!(sigs, "signal.SIGUSR1", (a -- a Int));
    builtin!(sigs, "signal.SIGUSR2", (a -- a Int));
    builtin!(sigs, "signal.SIGCHLD", (a -- a Int));
    builtin!(sigs, "signal.SIGALRM", (a -- a Int));
    builtin!(sigs, "signal.SIGCONT", (a -- a Int));

    // =========================================================================
    // Terminal Operations (raw mode, character I/O, dimensions)
    // =========================================================================

    builtin!(sigs, "terminal.raw-mode", (a Bool -- a));
    builtin!(sigs, "terminal.read-char", (a -- a Int));
    builtin!(sigs, "terminal.read-char?", (a -- a Int));
    builtin!(sigs, "terminal.width", (a -- a Int));
    builtin!(sigs, "terminal.height", (a -- a Int));
    builtin!(sigs, "terminal.flush", (a - -a));

    // =========================================================================
    // String Operations
    // =========================================================================

    builtin!(sigs, "string.concat", (a String String -- a String));
    builtin!(sigs, "string.length", (a String -- a Int));
    builtin!(sigs, "string.byte-length", (a String -- a Int));
    builtin!(sigs, "string.char-at", (a String Int -- a Int));
    builtin!(sigs, "string.substring", (a String Int Int -- a String));
    builtin!(sigs, "string.find", (a String String -- a Int));
    builtin!(sigs, "string.split", (a String String -- a V)); // Returns Variant (list)
    builtin!(sigs, "string.contains", (a String String -- a Bool));
    builtin!(sigs, "string.starts-with", (a String String -- a Bool));
    builtin!(sigs, "string.empty?", (a String -- a Bool));
    builtin!(sigs, "string.equal?", (a String String -- a Bool));

    // Symbol operations
    builtin!(sigs, "symbol.=", (a Symbol Symbol -- a Bool));

    // String transformations
    builtins_string_to_string!(
        sigs,
        "string.trim",
        "string.chomp",
        "string.to-upper",
        "string.to-lower",
        "string.json-escape"
    );

    // =========================================================================
    // Encoding Operations
    // =========================================================================

    builtin!(sigs, "encoding.base64-encode", (a String -- a String));
    builtin!(sigs, "encoding.base64-decode", (a String -- a String Bool));
    builtin!(sigs, "encoding.base64url-encode", (a String -- a String));
    builtin!(sigs, "encoding.base64url-decode", (a String -- a String Bool));
    builtin!(sigs, "encoding.hex-encode", (a String -- a String));
    builtin!(sigs, "encoding.hex-decode", (a String -- a String Bool));

    // =========================================================================
    // Crypto Operations
    // =========================================================================

    builtin!(sigs, "crypto.sha256", (a String -- a String));
    builtin!(sigs, "crypto.hmac-sha256", (a String String -- a String));
    builtin!(sigs, "crypto.constant-time-eq", (a String String -- a Bool));
    builtin!(sigs, "crypto.random-bytes", (a Int -- a String));
    builtin!(sigs, "crypto.random-int", (a Int Int -- a Int));
    builtin!(sigs, "crypto.uuid4", (a -- a String));
    builtin!(sigs, "crypto.aes-gcm-encrypt", (a String String -- a String Bool));
    builtin!(sigs, "crypto.aes-gcm-decrypt", (a String String -- a String Bool));
    builtin!(sigs, "crypto.pbkdf2-sha256", (a String String Int -- a String Bool));
    builtin!(sigs, "crypto.ed25519-keypair", (a -- a String String));
    builtin!(sigs, "crypto.ed25519-sign", (a String String -- a String Bool));
    builtin!(sigs, "crypto.ed25519-verify", (a String String String -- a Bool));

    // =========================================================================
    // HTTP Client Operations
    // =========================================================================

    builtin!(sigs, "http.get", (a String -- a M));
    builtin!(sigs, "http.post", (a String String String -- a M));
    builtin!(sigs, "http.put", (a String String String -- a M));
    builtin!(sigs, "http.delete", (a String -- a M));

    // =========================================================================
    // Regular Expression Operations
    // =========================================================================

    // Regex operations return Bool for error handling (invalid regex)
    builtin!(sigs, "regex.match?", (a String String -- a Bool));
    builtin!(sigs, "regex.find", (a String String -- a String Bool));
    builtin!(sigs, "regex.find-all", (a String String -- a V Bool));
    builtin!(sigs, "regex.replace", (a String String String -- a String Bool));
    builtin!(sigs, "regex.replace-all", (a String String String -- a String Bool));
    builtin!(sigs, "regex.captures", (a String String -- a V Bool));
    builtin!(sigs, "regex.split", (a String String -- a V Bool));
    builtin!(sigs, "regex.valid?", (a String -- a Bool));

    // =========================================================================
    // Compression Operations
    // =========================================================================

    builtin!(sigs, "compress.gzip", (a String -- a String Bool));
    builtin!(sigs, "compress.gzip-level", (a String Int -- a String Bool));
    builtin!(sigs, "compress.gunzip", (a String -- a String Bool));
    builtin!(sigs, "compress.zstd", (a String -- a String Bool));
    builtin!(sigs, "compress.zstd-level", (a String Int -- a String Bool));
    builtin!(sigs, "compress.unzstd", (a String -- a String Bool));

    // =========================================================================
    // Variant Operations
    // =========================================================================

    builtin!(sigs, "variant.field-count", (a V -- a Int));
    builtin!(sigs, "variant.tag", (a V -- a Symbol));
    builtin!(sigs, "variant.field-at", (a V Int -- a T));
    builtin!(sigs, "variant.append", (a V T -- a V2));
    builtin!(sigs, "variant.last", (a V -- a T));
    builtin!(sigs, "variant.init", (a V -- a V2));

    // Type-safe variant constructors with fixed arity (symbol tags for SON support)
    builtin!(sigs, "variant.make-0", (a Symbol -- a V));
    builtin!(sigs, "variant.make-1", (a T1 Symbol -- a V));
    builtin!(sigs, "variant.make-2", (a T1 T2 Symbol -- a V));
    builtin!(sigs, "variant.make-3", (a T1 T2 T3 Symbol -- a V));
    builtin!(sigs, "variant.make-4", (a T1 T2 T3 T4 Symbol -- a V));
    // variant.make-5 through variant.make-12 defined manually (macro only supports up to 5 inputs)
    for n in 5..=12 {
        let mut input = StackType::RowVar("a".to_string());
        for i in 1..=n {
            input = input.push(Type::Var(format!("T{}", i)));
        }
        input = input.push(Type::Symbol);
        let output = StackType::RowVar("a".to_string()).push(Type::Var("V".to_string()));
        sigs.insert(format!("variant.make-{}", n), Effect::new(input, output));
    }

    // Aliases for dynamic variant construction (SON-friendly names)
    builtin!(sigs, "wrap-0", (a Symbol -- a V));
    builtin!(sigs, "wrap-1", (a T1 Symbol -- a V));
    builtin!(sigs, "wrap-2", (a T1 T2 Symbol -- a V));
    builtin!(sigs, "wrap-3", (a T1 T2 T3 Symbol -- a V));
    builtin!(sigs, "wrap-4", (a T1 T2 T3 T4 Symbol -- a V));
    // wrap-5 through wrap-12 defined manually
    for n in 5..=12 {
        let mut input = StackType::RowVar("a".to_string());
        for i in 1..=n {
            input = input.push(Type::Var(format!("T{}", i)));
        }
        input = input.push(Type::Symbol);
        let output = StackType::RowVar("a".to_string()).push(Type::Var("V".to_string()));
        sigs.insert(format!("wrap-{}", n), Effect::new(input, output));
    }

    // =========================================================================
    // List Operations (Higher-order combinators for Variants)
    // =========================================================================

    // List construction and access
    builtin!(sigs, "list.make", (a -- a V));
    builtin!(sigs, "list.push", (a V T -- a V));
    builtin!(sigs, "list.get", (a V Int -- a T Bool));
    builtin!(sigs, "list.set", (a V Int T -- a V Bool));

    builtin!(sigs, "list.length", (a V -- a Int));
    builtin!(sigs, "list.empty?", (a V -- a Bool));

    // list.map: ( a Variant Quotation -- a Variant )
    // Quotation: ( b T -- b U )
    sigs.insert(
        "list.map".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string())
                .push(Type::Var("V".to_string()))
                .push(Type::Quotation(Box::new(Effect::new(
                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
                    StackType::RowVar("b".to_string()).push(Type::Var("U".to_string())),
                )))),
            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
        ),
    );

    // list.filter: ( a Variant Quotation -- a Variant )
    // Quotation: ( b T -- b Bool )
    sigs.insert(
        "list.filter".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string())
                .push(Type::Var("V".to_string()))
                .push(Type::Quotation(Box::new(Effect::new(
                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
                    StackType::RowVar("b".to_string()).push(Type::Bool),
                )))),
            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
        ),
    );

    // list.fold: ( a Variant init Quotation -- a result )
    // Quotation: ( b Acc T -- b Acc )
    sigs.insert(
        "list.fold".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string())
                .push(Type::Var("V".to_string()))
                .push(Type::Var("Acc".to_string()))
                .push(Type::Quotation(Box::new(Effect::new(
                    StackType::RowVar("b".to_string())
                        .push(Type::Var("Acc".to_string()))
                        .push(Type::Var("T".to_string())),
                    StackType::RowVar("b".to_string()).push(Type::Var("Acc".to_string())),
                )))),
            StackType::RowVar("a".to_string()).push(Type::Var("Acc".to_string())),
        ),
    );

    // list.each: ( a Variant Quotation -- a )
    // Quotation: ( b T -- b )
    sigs.insert(
        "list.each".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string())
                .push(Type::Var("V".to_string()))
                .push(Type::Quotation(Box::new(Effect::new(
                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
                    StackType::RowVar("b".to_string()),
                )))),
            StackType::RowVar("a".to_string()),
        ),
    );

    // =========================================================================
    // Map Operations (Dictionary with O(1) lookup)
    // =========================================================================

    builtin!(sigs, "map.make", (a -- a M));
    builtin!(sigs, "map.get", (a M K -- a V Bool)); // returns (value success) - errors are values, not crashes
    builtin!(sigs, "map.set", (a M K V -- a M2));
    builtin!(sigs, "map.has?", (a M K -- a Bool));
    builtin!(sigs, "map.remove", (a M K -- a M2));
    builtin!(sigs, "map.keys", (a M -- a V));
    builtin!(sigs, "map.values", (a M -- a V));
    builtin!(sigs, "map.size", (a M -- a Int));
    builtin!(sigs, "map.empty?", (a M -- a Bool));

    // =========================================================================
    // Float Arithmetic ( a Float Float -- a Float )
    // =========================================================================

    builtins_float_float_to_float!(sigs, "f.add", "f.subtract", "f.multiply", "f.divide");
    builtins_float_float_to_float!(sigs, "f.+", "f.-", "f.*", "f./");

    // =========================================================================
    // Float Comparison ( a Float Float -- a Bool )
    // =========================================================================

    builtins_float_float_to_bool!(sigs, "f.=", "f.<", "f.>", "f.<=", "f.>=", "f.<>");
    builtins_float_float_to_bool!(sigs, "f.eq", "f.lt", "f.gt", "f.lte", "f.gte", "f.neq");

    // =========================================================================
    // Test Framework
    // =========================================================================

    builtin!(sigs, "test.init", (a String -- a));
    builtin!(sigs, "test.finish", (a - -a));
    builtin!(sigs, "test.has-failures", (a -- a Bool));
    builtin!(sigs, "test.assert", (a Bool -- a));
    builtin!(sigs, "test.assert-not", (a Bool -- a));
    builtin!(sigs, "test.assert-eq", (a Int Int -- a));
    builtin!(sigs, "test.assert-eq-str", (a String String -- a));
    builtin!(sigs, "test.fail", (a String -- a));
    builtin!(sigs, "test.pass-count", (a -- a Int));
    builtin!(sigs, "test.fail-count", (a -- a Int));

    // Time operations
    builtin!(sigs, "time.now", (a -- a Int));
    builtin!(sigs, "time.nanos", (a -- a Int));
    builtin!(sigs, "time.sleep-ms", (a Int -- a));

    // SON serialization
    builtin!(sigs, "son.dump", (a T -- a String));
    builtin!(sigs, "son.dump-pretty", (a T -- a String));

    // Stack introspection (for REPL)
    // stack.dump prints all values and clears the stack
    sigs.insert(
        "stack.dump".to_string(),
        Effect::new(
            StackType::RowVar("a".to_string()), // Consumes any stack
            StackType::RowVar("b".to_string()), // Returns empty stack (different row var)
        ),
    );

    sigs
}

/// Get documentation for a built-in word
pub fn builtin_doc(name: &str) -> Option<&'static str> {
    BUILTIN_DOCS.get(name).copied()
}

/// Get all built-in word documentation (cached with LazyLock for performance)
pub fn builtin_docs() -> &'static HashMap<&'static str, &'static str> {
    &BUILTIN_DOCS
}

/// Lazily initialized documentation for all built-in words
static BUILTIN_DOCS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
    let mut docs = HashMap::new();

    // I/O Operations
    docs.insert(
        "io.write",
        "Write a string to stdout without a trailing newline.",
    );
    docs.insert(
        "io.write-line",
        "Write a string to stdout followed by a newline.",
    );
    docs.insert(
        "io.read-line",
        "Read a line from stdin. Returns (line, success).",
    );
    docs.insert(
        "io.read-line+",
        "DEPRECATED: Use io.read-line instead. Read a line from stdin. Returns (line, status_code).",
    );
    docs.insert(
        "io.read-n",
        "Read N bytes from stdin. Returns (bytes, status_code).",
    );

    // Command-line Arguments
    docs.insert("args.count", "Get the number of command-line arguments.");
    docs.insert("args.at", "Get the command-line argument at index N.");

    // File Operations
    docs.insert(
        "file.slurp",
        "Read entire file contents. Returns (content, success).",
    );
    docs.insert("file.exists?", "Check if a file exists at the given path.");
    docs.insert(
        "file.for-each-line+",
        "Execute a quotation for each line in a file.",
    );

    // Type Conversions
    docs.insert(
        "int->string",
        "Convert an integer to its string representation.",
    );
    docs.insert(
        "int->float",
        "Convert an integer to a floating-point number.",
    );
    docs.insert("float->int", "Truncate a float to an integer.");
    docs.insert(
        "float->string",
        "Convert a float to its string representation.",
    );
    docs.insert(
        "string->int",
        "Parse a string as an integer. Returns (value, success).",
    );
    docs.insert(
        "string->float",
        "Parse a string as a float. Returns (value, success).",
    );
    docs.insert(
        "char->string",
        "Convert a Unicode codepoint to a single-character string.",
    );
    docs.insert(
        "symbol->string",
        "Convert a symbol to its string representation.",
    );
    docs.insert("string->symbol", "Intern a string as a symbol.");

    // Integer Arithmetic
    docs.insert("i.add", "Add two integers.");
    docs.insert("i.subtract", "Subtract second integer from first.");
    docs.insert("i.multiply", "Multiply two integers.");
    docs.insert("i.divide", "Integer division (truncates toward zero).");
    docs.insert("i.modulo", "Integer modulo (remainder after division).");
    docs.insert("i.+", "Add two integers.");
    docs.insert("i.-", "Subtract second integer from first.");
    docs.insert("i.*", "Multiply two integers.");
    docs.insert("i./", "Integer division (truncates toward zero).");
    docs.insert("i.%", "Integer modulo (remainder after division).");

    // Integer Comparison
    docs.insert("i.=", "Test if two integers are equal.");
    docs.insert("i.<", "Test if first integer is less than second.");
    docs.insert("i.>", "Test if first integer is greater than second.");
    docs.insert(
        "i.<=",
        "Test if first integer is less than or equal to second.",
    );
    docs.insert(
        "i.>=",
        "Test if first integer is greater than or equal to second.",
    );
    docs.insert("i.<>", "Test if two integers are not equal.");
    docs.insert("i.eq", "Test if two integers are equal.");
    docs.insert("i.lt", "Test if first integer is less than second.");
    docs.insert("i.gt", "Test if first integer is greater than second.");
    docs.insert(
        "i.lte",
        "Test if first integer is less than or equal to second.",
    );
    docs.insert(
        "i.gte",
        "Test if first integer is greater than or equal to second.",
    );
    docs.insert("i.neq", "Test if two integers are not equal.");

    // Boolean Operations
    docs.insert("and", "Logical AND of two booleans.");
    docs.insert("or", "Logical OR of two booleans.");
    docs.insert("not", "Logical NOT of a boolean.");

    // Bitwise Operations
    docs.insert("band", "Bitwise AND of two integers.");
    docs.insert("bor", "Bitwise OR of two integers.");
    docs.insert("bxor", "Bitwise XOR of two integers.");
    docs.insert("bnot", "Bitwise NOT (complement) of an integer.");
    docs.insert("shl", "Shift left by N bits.");
    docs.insert("shr", "Shift right by N bits (arithmetic).");
    docs.insert("popcount", "Count the number of set bits.");
    docs.insert("clz", "Count leading zeros.");
    docs.insert("ctz", "Count trailing zeros.");
    docs.insert("int-bits", "Push the bit width of integers (64).");

    // Stack Operations
    docs.insert("dup", "Duplicate the top stack value.");
    docs.insert("drop", "Remove the top stack value.");
    docs.insert("swap", "Swap the top two stack values.");
    docs.insert("over", "Copy the second value to the top.");
    docs.insert("rot", "Rotate the top three values (third to top).");
    docs.insert("nip", "Remove the second value from the stack.");
    docs.insert("tuck", "Copy the top value below the second.");
    docs.insert("2dup", "Duplicate the top two values.");
    docs.insert("3drop", "Remove the top three values.");
    docs.insert("pick", "Copy the value at depth N to the top.");
    docs.insert("roll", "Rotate N+1 items, bringing depth N to top.");

    // Channel Operations
    docs.insert(
        "chan.make",
        "Create a new channel for inter-strand communication.",
    );
    docs.insert(
        "chan.send",
        "Send a value on a channel. Returns success flag.",
    );
    docs.insert(
        "chan.receive",
        "Receive a value from a channel. Returns (value, success).",
    );
    docs.insert("chan.close", "Close a channel.");
    docs.insert("chan.yield", "Yield control to the scheduler.");

    // Control Flow
    docs.insert("call", "Call a quotation or closure.");
    docs.insert(
        "cond",
        "Multi-way conditional: test clauses until one succeeds.",
    );

    // Concurrency
    docs.insert(
        "strand.spawn",
        "Spawn a concurrent strand. Returns strand ID.",
    );
    docs.insert(
        "strand.weave",
        "Create a generator/coroutine. Returns handle.",
    );
    docs.insert(
        "strand.resume",
        "Resume a weave with a value. Returns (handle, value, has_more).",
    );
    docs.insert(
        "yield",
        "Yield a value from a weave and receive resume value.",
    );
    docs.insert(
        "strand.weave-cancel",
        "Cancel a weave and release its resources.",
    );

    // TCP Operations
    docs.insert(
        "tcp.listen",
        "Start listening on a port. Returns (socket_id, success).",
    );
    docs.insert(
        "tcp.accept",
        "Accept a connection. Returns (client_id, success).",
    );
    docs.insert(
        "tcp.read",
        "Read data from a socket. Returns (string, success).",
    );
    docs.insert("tcp.write", "Write data to a socket. Returns success.");
    docs.insert("tcp.close", "Close a socket. Returns success.");

    // OS Operations
    docs.insert(
        "os.getenv",
        "Get environment variable. Returns (value, exists).",
    );
    docs.insert(
        "os.home-dir",
        "Get user's home directory. Returns (path, success).",
    );
    docs.insert(
        "os.current-dir",
        "Get current working directory. Returns (path, success).",
    );
    docs.insert("os.path-exists", "Check if a path exists.");
    docs.insert("os.path-is-file", "Check if path is a regular file.");
    docs.insert("os.path-is-dir", "Check if path is a directory.");
    docs.insert("os.path-join", "Join two path components.");
    docs.insert(
        "os.path-parent",
        "Get parent directory. Returns (path, success).",
    );
    docs.insert(
        "os.path-filename",
        "Get filename component. Returns (name, success).",
    );
    docs.insert("os.exit", "Exit the program with a status code.");
    docs.insert(
        "os.name",
        "Get the operating system name (e.g., \"macos\", \"linux\").",
    );
    docs.insert(
        "os.arch",
        "Get the CPU architecture (e.g., \"aarch64\", \"x86_64\").",
    );

    // Signal Handling
    docs.insert(
        "signal.trap",
        "Trap a signal: set internal flag on receipt instead of default action.",
    );
    docs.insert(
        "signal.received?",
        "Check if signal was received and clear the flag. Returns Bool.",
    );
    docs.insert(
        "signal.pending?",
        "Check if signal is pending without clearing the flag. Returns Bool.",
    );
    docs.insert(
        "signal.default",
        "Restore the default handler for a signal.",
    );
    docs.insert(
        "signal.ignore",
        "Ignore a signal entirely (useful for SIGPIPE in servers).",
    );
    docs.insert(
        "signal.clear",
        "Clear the pending flag for a signal without checking it.",
    );
    docs.insert("signal.SIGINT", "SIGINT constant (Ctrl+C interrupt).");
    docs.insert("signal.SIGTERM", "SIGTERM constant (termination request).");
    docs.insert("signal.SIGHUP", "SIGHUP constant (hangup detected).");
    docs.insert("signal.SIGPIPE", "SIGPIPE constant (broken pipe).");
    docs.insert(
        "signal.SIGUSR1",
        "SIGUSR1 constant (user-defined signal 1).",
    );
    docs.insert(
        "signal.SIGUSR2",
        "SIGUSR2 constant (user-defined signal 2).",
    );
    docs.insert("signal.SIGCHLD", "SIGCHLD constant (child status changed).");
    docs.insert("signal.SIGALRM", "SIGALRM constant (alarm clock).");
    docs.insert("signal.SIGCONT", "SIGCONT constant (continue if stopped).");

    // Terminal Operations
    docs.insert(
        "terminal.raw-mode",
        "Enable/disable raw terminal mode. In raw mode: no line buffering, no echo, Ctrl+C read as byte 3.",
    );
    docs.insert(
        "terminal.read-char",
        "Read a single byte from stdin (blocking). Returns 0-255 on success, -1 on EOF/error.",
    );
    docs.insert(
        "terminal.read-char?",
        "Read a single byte from stdin (non-blocking). Returns 0-255 if available, -1 otherwise.",
    );
    docs.insert(
        "terminal.width",
        "Get terminal width in columns. Returns 80 if unknown.",
    );
    docs.insert(
        "terminal.height",
        "Get terminal height in rows. Returns 24 if unknown.",
    );
    docs.insert(
        "terminal.flush",
        "Flush stdout. Use after writing escape sequences or partial lines.",
    );

    // String Operations
    docs.insert("string.concat", "Concatenate two strings.");
    docs.insert("string.length", "Get the character length of a string.");
    docs.insert("string.byte-length", "Get the byte length of a string.");
    docs.insert(
        "string.char-at",
        "Get Unicode codepoint at character index.",
    );
    docs.insert(
        "string.substring",
        "Extract substring from start index with length.",
    );
    docs.insert(
        "string.find",
        "Find substring. Returns index or -1 if not found.",
    );
    docs.insert("string.split", "Split string by delimiter. Returns a list.");
    docs.insert("string.contains", "Check if string contains a substring.");
    docs.insert(
        "string.starts-with",
        "Check if string starts with a prefix.",
    );
    docs.insert("string.empty?", "Check if string is empty.");
    docs.insert("string.equal?", "Check if two strings are equal.");
    docs.insert("string.trim", "Remove leading and trailing whitespace.");
    docs.insert("string.chomp", "Remove trailing newline.");
    docs.insert("string.to-upper", "Convert to uppercase.");
    docs.insert("string.to-lower", "Convert to lowercase.");
    docs.insert("string.json-escape", "Escape special characters for JSON.");
    docs.insert("symbol.=", "Check if two symbols are equal.");

    // Encoding Operations
    docs.insert(
        "encoding.base64-encode",
        "Encode a string to Base64 (standard alphabet with padding).",
    );
    docs.insert(
        "encoding.base64-decode",
        "Decode a Base64 string. Returns (decoded, success).",
    );
    docs.insert(
        "encoding.base64url-encode",
        "Encode to URL-safe Base64 (no padding). Suitable for JWTs and URLs.",
    );
    docs.insert(
        "encoding.base64url-decode",
        "Decode URL-safe Base64. Returns (decoded, success).",
    );
    docs.insert(
        "encoding.hex-encode",
        "Encode a string to lowercase hexadecimal.",
    );
    docs.insert(
        "encoding.hex-decode",
        "Decode a hexadecimal string. Returns (decoded, success).",
    );

    // Crypto Operations
    docs.insert(
        "crypto.sha256",
        "Compute SHA-256 hash of a string. Returns 64-char hex digest.",
    );
    docs.insert(
        "crypto.hmac-sha256",
        "Compute HMAC-SHA256 signature. ( message key -- signature )",
    );
    docs.insert(
        "crypto.constant-time-eq",
        "Timing-safe string comparison. Use for comparing signatures/tokens.",
    );
    docs.insert(
        "crypto.random-bytes",
        "Generate N cryptographically secure random bytes as hex string.",
    );
    docs.insert(
        "crypto.random-int",
        "Generate uniform random integer in [min, max). ( min max -- Int ) Uses rejection sampling to avoid modulo bias.",
    );
    docs.insert("crypto.uuid4", "Generate a random UUID v4 string.");
    docs.insert(
        "crypto.aes-gcm-encrypt",
        "Encrypt with AES-256-GCM. ( plaintext hex-key -- ciphertext success )",
    );
    docs.insert(
        "crypto.aes-gcm-decrypt",
        "Decrypt AES-256-GCM ciphertext. ( ciphertext hex-key -- plaintext success )",
    );
    docs.insert(
        "crypto.pbkdf2-sha256",
        "Derive key from password. ( password salt iterations -- hex-key success ) Min 1000 iterations, 100000+ recommended.",
    );
    docs.insert(
        "crypto.ed25519-keypair",
        "Generate Ed25519 keypair. ( -- public-key private-key ) Both as 64-char hex strings.",
    );
    docs.insert(
        "crypto.ed25519-sign",
        "Sign message with Ed25519 private key. ( message private-key -- signature success ) Signature is 128-char hex.",
    );
    docs.insert(
        "crypto.ed25519-verify",
        "Verify Ed25519 signature. ( message signature public-key -- valid )",
    );

    // HTTP Client Operations
    docs.insert(
        "http.get",
        "HTTP GET request. ( url -- response-map ) Map has status, body, ok, error.",
    );
    docs.insert(
        "http.post",
        "HTTP POST request. ( url body content-type -- response-map )",
    );
    docs.insert(
        "http.put",
        "HTTP PUT request. ( url body content-type -- response-map )",
    );
    docs.insert(
        "http.delete",
        "HTTP DELETE request. ( url -- response-map )",
    );

    // Regular Expression Operations
    docs.insert(
        "regex.match?",
        "Check if pattern matches anywhere in string. ( text pattern -- bool )",
    );
    docs.insert(
        "regex.find",
        "Find first match. ( text pattern -- matched success )",
    );
    docs.insert(
        "regex.find-all",
        "Find all matches. ( text pattern -- list success )",
    );
    docs.insert(
        "regex.replace",
        "Replace first match. ( text pattern replacement -- result success )",
    );
    docs.insert(
        "regex.replace-all",
        "Replace all matches. ( text pattern replacement -- result success )",
    );
    docs.insert(
        "regex.captures",
        "Extract capture groups. ( text pattern -- groups success )",
    );
    docs.insert(
        "regex.split",
        "Split string by pattern. ( text pattern -- list success )",
    );
    docs.insert(
        "regex.valid?",
        "Check if pattern is valid regex. ( pattern -- bool )",
    );

    // Compression Operations
    docs.insert(
        "compress.gzip",
        "Compress string with gzip. Returns base64-encoded data. ( data -- compressed success )",
    );
    docs.insert(
        "compress.gzip-level",
        "Compress with gzip at level 1-9. ( data level -- compressed success )",
    );
    docs.insert(
        "compress.gunzip",
        "Decompress gzip data. ( base64-data -- decompressed success )",
    );
    docs.insert(
        "compress.zstd",
        "Compress string with zstd. Returns base64-encoded data. ( data -- compressed success )",
    );
    docs.insert(
        "compress.zstd-level",
        "Compress with zstd at level 1-22. ( data level -- compressed success )",
    );
    docs.insert(
        "compress.unzstd",
        "Decompress zstd data. ( base64-data -- decompressed success )",
    );

    // Variant Operations
    docs.insert(
        "variant.field-count",
        "Get the number of fields in a variant.",
    );
    docs.insert(
        "variant.tag",
        "Get the tag (constructor name) of a variant.",
    );
    docs.insert("variant.field-at", "Get the field at index N.");
    docs.insert(
        "variant.append",
        "Append a value to a variant (creates new).",
    );
    docs.insert("variant.last", "Get the last field of a variant.");
    docs.insert("variant.init", "Get all fields except the last.");
    docs.insert("variant.make-0", "Create a variant with 0 fields.");
    docs.insert("variant.make-1", "Create a variant with 1 field.");
    docs.insert("variant.make-2", "Create a variant with 2 fields.");
    docs.insert("variant.make-3", "Create a variant with 3 fields.");
    docs.insert("variant.make-4", "Create a variant with 4 fields.");
    docs.insert("variant.make-5", "Create a variant with 5 fields.");
    docs.insert("variant.make-6", "Create a variant with 6 fields.");
    docs.insert("variant.make-7", "Create a variant with 7 fields.");
    docs.insert("variant.make-8", "Create a variant with 8 fields.");
    docs.insert("variant.make-9", "Create a variant with 9 fields.");
    docs.insert("variant.make-10", "Create a variant with 10 fields.");
    docs.insert("variant.make-11", "Create a variant with 11 fields.");
    docs.insert("variant.make-12", "Create a variant with 12 fields.");
    docs.insert("wrap-0", "Create a variant with 0 fields (alias).");
    docs.insert("wrap-1", "Create a variant with 1 field (alias).");
    docs.insert("wrap-2", "Create a variant with 2 fields (alias).");
    docs.insert("wrap-3", "Create a variant with 3 fields (alias).");
    docs.insert("wrap-4", "Create a variant with 4 fields (alias).");
    docs.insert("wrap-5", "Create a variant with 5 fields (alias).");
    docs.insert("wrap-6", "Create a variant with 6 fields (alias).");
    docs.insert("wrap-7", "Create a variant with 7 fields (alias).");
    docs.insert("wrap-8", "Create a variant with 8 fields (alias).");
    docs.insert("wrap-9", "Create a variant with 9 fields (alias).");
    docs.insert("wrap-10", "Create a variant with 10 fields (alias).");
    docs.insert("wrap-11", "Create a variant with 11 fields (alias).");
    docs.insert("wrap-12", "Create a variant with 12 fields (alias).");

    // List Operations
    docs.insert("list.make", "Create an empty list.");
    docs.insert("list.push", "Push a value onto a list. Returns new list.");
    docs.insert("list.get", "Get value at index. Returns (value, success).");
    docs.insert("list.set", "Set value at index. Returns (list, success).");
    docs.insert("list.length", "Get the number of elements in a list.");
    docs.insert("list.empty?", "Check if a list is empty.");
    docs.insert(
        "list.map",
        "Apply quotation to each element. Returns new list.",
    );
    docs.insert("list.filter", "Keep elements where quotation returns true.");
    docs.insert("list.fold", "Reduce list with accumulator and quotation.");
    docs.insert(
        "list.each",
        "Execute quotation for each element (side effects).",
    );

    // Map Operations
    docs.insert("map.make", "Create an empty map.");
    docs.insert("map.get", "Get value for key. Returns (value, success).");
    docs.insert("map.set", "Set key to value. Returns new map.");
    docs.insert("map.has?", "Check if map contains a key.");
    docs.insert("map.remove", "Remove a key. Returns new map.");
    docs.insert("map.keys", "Get all keys as a list.");
    docs.insert("map.values", "Get all values as a list.");
    docs.insert("map.size", "Get the number of key-value pairs.");
    docs.insert("map.empty?", "Check if map is empty.");

    // Float Arithmetic
    docs.insert("f.add", "Add two floats.");
    docs.insert("f.subtract", "Subtract second float from first.");
    docs.insert("f.multiply", "Multiply two floats.");
    docs.insert("f.divide", "Divide first float by second.");
    docs.insert("f.+", "Add two floats.");
    docs.insert("f.-", "Subtract second float from first.");
    docs.insert("f.*", "Multiply two floats.");
    docs.insert("f./", "Divide first float by second.");

    // Float Comparison
    docs.insert("f.=", "Test if two floats are equal.");
    docs.insert("f.<", "Test if first float is less than second.");
    docs.insert("f.>", "Test if first float is greater than second.");
    docs.insert("f.<=", "Test if first float is less than or equal.");
    docs.insert("f.>=", "Test if first float is greater than or equal.");
    docs.insert("f.<>", "Test if two floats are not equal.");
    docs.insert("f.eq", "Test if two floats are equal.");
    docs.insert("f.lt", "Test if first float is less than second.");
    docs.insert("f.gt", "Test if first float is greater than second.");
    docs.insert("f.lte", "Test if first float is less than or equal.");
    docs.insert("f.gte", "Test if first float is greater than or equal.");
    docs.insert("f.neq", "Test if two floats are not equal.");

    // Test Framework
    docs.insert(
        "test.init",
        "Initialize the test framework with a test name.",
    );
    docs.insert("test.finish", "Finish testing and print results.");
    docs.insert("test.has-failures", "Check if any tests have failed.");
    docs.insert("test.assert", "Assert that a boolean is true.");
    docs.insert("test.assert-not", "Assert that a boolean is false.");
    docs.insert("test.assert-eq", "Assert that two integers are equal.");
    docs.insert("test.assert-eq-str", "Assert that two strings are equal.");
    docs.insert("test.fail", "Mark a test as failed with a message.");
    docs.insert("test.pass-count", "Get the number of passed assertions.");
    docs.insert("test.fail-count", "Get the number of failed assertions.");

    // Time Operations
    docs.insert("time.now", "Get current Unix timestamp in seconds.");
    docs.insert(
        "time.nanos",
        "Get high-resolution monotonic time in nanoseconds.",
    );
    docs.insert("time.sleep-ms", "Sleep for N milliseconds.");

    // Serialization
    docs.insert("son.dump", "Serialize any value to SON format (compact).");
    docs.insert(
        "son.dump-pretty",
        "Serialize any value to SON format (pretty-printed).",
    );

    // Stack Introspection
    docs.insert(
        "stack.dump",
        "Print all stack values and clear the stack (REPL).",
    );

    docs
});

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_builtin_signature_write_line() {
        let sig = builtin_signature("io.write-line").unwrap();
        // ( ..a String -- ..a )
        let (rest, top) = sig.inputs.clone().pop().unwrap();
        assert_eq!(top, Type::String);
        assert_eq!(rest, StackType::RowVar("a".to_string()));
        assert_eq!(sig.outputs, StackType::RowVar("a".to_string()));
    }

    #[test]
    fn test_builtin_signature_i_add() {
        let sig = builtin_signature("i.add").unwrap();
        // ( ..a Int Int -- ..a Int )
        let (rest, top) = sig.inputs.clone().pop().unwrap();
        assert_eq!(top, Type::Int);
        let (rest2, top2) = rest.pop().unwrap();
        assert_eq!(top2, Type::Int);
        assert_eq!(rest2, StackType::RowVar("a".to_string()));

        let (rest3, top3) = sig.outputs.clone().pop().unwrap();
        assert_eq!(top3, Type::Int);
        assert_eq!(rest3, StackType::RowVar("a".to_string()));
    }

    #[test]
    fn test_builtin_signature_dup() {
        let sig = builtin_signature("dup").unwrap();
        // Input: ( ..a T )
        assert_eq!(
            sig.inputs,
            StackType::Cons {
                rest: Box::new(StackType::RowVar("a".to_string())),
                top: Type::Var("T".to_string())
            }
        );
        // Output: ( ..a T T )
        let (rest, top) = sig.outputs.clone().pop().unwrap();
        assert_eq!(top, Type::Var("T".to_string()));
        let (rest2, top2) = rest.pop().unwrap();
        assert_eq!(top2, Type::Var("T".to_string()));
        assert_eq!(rest2, StackType::RowVar("a".to_string()));
    }

    #[test]
    fn test_all_builtins_have_signatures() {
        let sigs = builtin_signatures();

        // Verify all expected builtins have signatures
        assert!(sigs.contains_key("io.write-line"));
        assert!(sigs.contains_key("io.read-line"));
        assert!(sigs.contains_key("int->string"));
        assert!(sigs.contains_key("i.add"));
        assert!(sigs.contains_key("dup"));
        assert!(sigs.contains_key("swap"));
        assert!(sigs.contains_key("chan.make"));
        assert!(sigs.contains_key("chan.send"));
        assert!(sigs.contains_key("chan.receive"));
        assert!(
            sigs.contains_key("string->float"),
            "string->float should be a builtin"
        );
        assert!(
            sigs.contains_key("signal.trap"),
            "signal.trap should be a builtin"
        );
    }

    #[test]
    fn test_all_docs_have_signatures() {
        let sigs = builtin_signatures();
        let docs = builtin_docs();

        for name in docs.keys() {
            assert!(
                sigs.contains_key(*name),
                "Builtin '{}' has documentation but no signature",
                name
            );
        }
    }

    #[test]
    fn test_all_signatures_have_docs() {
        let sigs = builtin_signatures();
        let docs = builtin_docs();

        for name in sigs.keys() {
            assert!(
                docs.contains_key(name.as_str()),
                "Builtin '{}' has signature but no documentation",
                name
            );
        }
    }
}