seqc/
builtins.rs

1//! Built-in word signatures for Seq
2//!
3//! Defines the stack effects for all runtime built-in operations.
4//!
5//! Uses declarative macros to minimize boilerplate. The `builtin!` macro
6//! supports a Forth-like notation: `(a Type1 Type2 -- a Type3)` where:
7//! - `a` is the row variable (representing "rest of stack")
8//! - Concrete types: `Int`, `String`, `Float`
9//! - Type variables: single uppercase letters like `T`, `U`, `V`
10
11use crate::types::{Effect, SideEffect, StackType, Type};
12use std::collections::HashMap;
13use std::sync::LazyLock;
14
15/// Convert a type token to a Type expression
16macro_rules! ty {
17    (Int) => {
18        Type::Int
19    };
20    (Bool) => {
21        Type::Bool
22    };
23    (String) => {
24        Type::String
25    };
26    (Float) => {
27        Type::Float
28    };
29    (Symbol) => {
30        Type::Symbol
31    };
32    (Channel) => {
33        Type::Channel
34    };
35    // Single uppercase letter = type variable
36    (T) => {
37        Type::Var("T".to_string())
38    };
39    (U) => {
40        Type::Var("U".to_string())
41    };
42    (V) => {
43        Type::Var("V".to_string())
44    };
45    (W) => {
46        Type::Var("W".to_string())
47    };
48    (K) => {
49        Type::Var("K".to_string())
50    };
51    (M) => {
52        Type::Var("M".to_string())
53    };
54    (Q) => {
55        Type::Var("Q".to_string())
56    };
57    // Multi-char type variables (T1, T2, etc.)
58    (T1) => {
59        Type::Var("T1".to_string())
60    };
61    (T2) => {
62        Type::Var("T2".to_string())
63    };
64    (T3) => {
65        Type::Var("T3".to_string())
66    };
67    (T4) => {
68        Type::Var("T4".to_string())
69    };
70    (V2) => {
71        Type::Var("V2".to_string())
72    };
73    (M2) => {
74        Type::Var("M2".to_string())
75    };
76    (Acc) => {
77        Type::Var("Acc".to_string())
78    };
79}
80
81/// Build a stack type from row variable 'a' plus pushed types
82macro_rules! stack {
83    // Just the row variable
84    (a) => {
85        StackType::RowVar("a".to_string())
86    };
87    // Row variable with one type pushed
88    (a $t1:tt) => {
89        StackType::RowVar("a".to_string()).push(ty!($t1))
90    };
91    // Row variable with two types pushed
92    (a $t1:tt $t2:tt) => {
93        StackType::RowVar("a".to_string())
94            .push(ty!($t1))
95            .push(ty!($t2))
96    };
97    // Row variable with three types pushed
98    (a $t1:tt $t2:tt $t3:tt) => {
99        StackType::RowVar("a".to_string())
100            .push(ty!($t1))
101            .push(ty!($t2))
102            .push(ty!($t3))
103    };
104    // Row variable with four types pushed
105    (a $t1:tt $t2:tt $t3:tt $t4:tt) => {
106        StackType::RowVar("a".to_string())
107            .push(ty!($t1))
108            .push(ty!($t2))
109            .push(ty!($t3))
110            .push(ty!($t4))
111    };
112    // Row variable with five types pushed
113    (a $t1:tt $t2:tt $t3:tt $t4:tt $t5:tt) => {
114        StackType::RowVar("a".to_string())
115            .push(ty!($t1))
116            .push(ty!($t2))
117            .push(ty!($t3))
118            .push(ty!($t4))
119            .push(ty!($t5))
120    };
121    // Row variable 'b' (used in some signatures)
122    (b) => {
123        StackType::RowVar("b".to_string())
124    };
125    (b $t1:tt) => {
126        StackType::RowVar("b".to_string()).push(ty!($t1))
127    };
128    (b $t1:tt $t2:tt) => {
129        StackType::RowVar("b".to_string())
130            .push(ty!($t1))
131            .push(ty!($t2))
132    };
133}
134
135/// Define a builtin signature with Forth-like stack effect notation
136///
137/// Usage: `builtin!(sigs, "name", (a Type1 Type2 -- a Type3));`
138macro_rules! builtin {
139    // (a -- a)
140    ($sigs:ident, $name:expr, (a -- a)) => {
141        $sigs.insert($name.to_string(), Effect::new(stack!(a), stack!(a)));
142    };
143    // (a -- a T)
144    ($sigs:ident, $name:expr, (a -- a $o1:tt)) => {
145        $sigs.insert($name.to_string(), Effect::new(stack!(a), stack!(a $o1)));
146    };
147    // (a -- a T U)
148    ($sigs:ident, $name:expr, (a -- a $o1:tt $o2:tt)) => {
149        $sigs.insert($name.to_string(), Effect::new(stack!(a), stack!(a $o1 $o2)));
150    };
151    // (a T -- a)
152    ($sigs:ident, $name:expr, (a $i1:tt -- a)) => {
153        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1), stack!(a)));
154    };
155    // (a T -- a U)
156    ($sigs:ident, $name:expr, (a $i1:tt -- a $o1:tt)) => {
157        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1), stack!(a $o1)));
158    };
159    // (a T -- a U V)
160    ($sigs:ident, $name:expr, (a $i1:tt -- a $o1:tt $o2:tt)) => {
161        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1), stack!(a $o1 $o2)));
162    };
163    // (a T U -- a)
164    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a)) => {
165        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a)));
166    };
167    // (a T U -- a V)
168    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt)) => {
169        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1)));
170    };
171    // (a T U -- a V W)
172    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt $o2:tt)) => {
173        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1 $o2)));
174    };
175    // (a T U -- a V W X)
176    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt $o2:tt $o3:tt)) => {
177        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1 $o2 $o3)));
178    };
179    // (a T U -- a V W X Y)
180    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt -- a $o1:tt $o2:tt $o3:tt $o4:tt)) => {
181        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2), stack!(a $o1 $o2 $o3 $o4)));
182    };
183    // (a T U V -- a)
184    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a)) => {
185        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a)));
186    };
187    // (a T U V -- a W)
188    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a $o1:tt)) => {
189        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a $o1)));
190    };
191    // (a T U V -- a W X)
192    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a $o1:tt $o2:tt)) => {
193        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a $o1 $o2)));
194    };
195    // (a T U V -- a W X Y)
196    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt -- a $o1:tt $o2:tt $o3:tt)) => {
197        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3), stack!(a $o1 $o2 $o3)));
198    };
199    // (a T U V W -- a X)
200    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt $i4:tt -- a $o1:tt)) => {
201        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3 $i4), stack!(a $o1)));
202    };
203    // (a T U V W X -- a Y)
204    ($sigs:ident, $name:expr, (a $i1:tt $i2:tt $i3:tt $i4:tt $i5:tt -- a $o1:tt)) => {
205        $sigs.insert($name.to_string(), Effect::new(stack!(a $i1 $i2 $i3 $i4 $i5), stack!(a $o1)));
206    };
207}
208
209/// Define multiple builtins with the same signature
210/// Note: Can't use a generic macro due to tt repetition issues, so we use specific helpers
211macro_rules! builtins_int_int_to_int {
212    ($sigs:ident, $($name:expr),+ $(,)?) => {
213        $(
214            builtin!($sigs, $name, (a Int Int -- a Int));
215        )+
216    };
217}
218
219macro_rules! builtins_int_int_to_bool {
220    ($sigs:ident, $($name:expr),+ $(,)?) => {
221        $(
222            builtin!($sigs, $name, (a Int Int -- a Bool));
223        )+
224    };
225}
226
227macro_rules! builtins_bool_bool_to_bool {
228    ($sigs:ident, $($name:expr),+ $(,)?) => {
229        $(
230            builtin!($sigs, $name, (a Bool Bool -- a Bool));
231        )+
232    };
233}
234
235macro_rules! builtins_int_to_int {
236    ($sigs:ident, $($name:expr),+ $(,)?) => {
237        $(
238            builtin!($sigs, $name, (a Int -- a Int));
239        )+
240    };
241}
242
243macro_rules! builtins_string_to_string {
244    ($sigs:ident, $($name:expr),+ $(,)?) => {
245        $(
246            builtin!($sigs, $name, (a String -- a String));
247        )+
248    };
249}
250
251macro_rules! builtins_float_float_to_float {
252    ($sigs:ident, $($name:expr),+ $(,)?) => {
253        $(
254            builtin!($sigs, $name, (a Float Float -- a Float));
255        )+
256    };
257}
258
259macro_rules! builtins_float_float_to_bool {
260    ($sigs:ident, $($name:expr),+ $(,)?) => {
261        $(
262            builtin!($sigs, $name, (a Float Float -- a Bool));
263        )+
264    };
265}
266
267/// Get the stack effect signature for a built-in word
268pub fn builtin_signature(name: &str) -> Option<Effect> {
269    let signatures = builtin_signatures();
270    signatures.get(name).cloned()
271}
272
273/// Get all built-in word signatures
274pub fn builtin_signatures() -> HashMap<String, Effect> {
275    let mut sigs = HashMap::new();
276
277    // =========================================================================
278    // I/O Operations
279    // =========================================================================
280
281    builtin!(sigs, "io.write", (a String -- a)); // Write without newline
282    builtin!(sigs, "io.write-line", (a String -- a));
283    builtin!(sigs, "io.read-line", (a -- a String Bool)); // Returns line + success flag
284    builtin!(sigs, "io.read-line+", (a -- a String Int)); // Returns line + status (legacy)
285    builtin!(sigs, "io.read-n", (a Int -- a String Int)); // Read N bytes, returns bytes + status
286
287    // =========================================================================
288    // Command-line Arguments
289    // =========================================================================
290
291    builtin!(sigs, "args.count", (a -- a Int));
292    builtin!(sigs, "args.at", (a Int -- a String));
293
294    // =========================================================================
295    // File Operations
296    // =========================================================================
297
298    builtin!(sigs, "file.slurp", (a String -- a String Bool)); // returns (content success) - errors are values
299    builtin!(sigs, "file.exists?", (a String -- a Bool));
300
301    // file.for-each-line+: Complex quotation type - defined manually
302    sigs.insert(
303        "file.for-each-line+".to_string(),
304        Effect::new(
305            StackType::RowVar("a".to_string())
306                .push(Type::String)
307                .push(Type::Quotation(Box::new(Effect::new(
308                    StackType::RowVar("a".to_string()).push(Type::String),
309                    StackType::RowVar("a".to_string()),
310                )))),
311            StackType::RowVar("a".to_string())
312                .push(Type::String)
313                .push(Type::Bool),
314        ),
315    );
316
317    // =========================================================================
318    // Type Conversions
319    // =========================================================================
320
321    builtin!(sigs, "int->string", (a Int -- a String));
322    builtin!(sigs, "int->float", (a Int -- a Float));
323    builtin!(sigs, "float->int", (a Float -- a Int));
324    builtin!(sigs, "float->string", (a Float -- a String));
325    builtin!(sigs, "string->int", (a String -- a Int Bool)); // value + success flag
326    builtin!(sigs, "string->float", (a String -- a Float Bool)); // value + success flag
327    builtin!(sigs, "char->string", (a Int -- a String));
328    builtin!(sigs, "symbol->string", (a Symbol -- a String));
329    builtin!(sigs, "string->symbol", (a String -- a Symbol));
330
331    // =========================================================================
332    // Integer Arithmetic ( a Int Int -- a Int )
333    // =========================================================================
334
335    builtins_int_int_to_int!(
336        sigs,
337        "i.add",
338        "i.subtract",
339        "i.multiply",
340        "i.divide",
341        "i.modulo"
342    );
343    builtins_int_int_to_int!(sigs, "i.+", "i.-", "i.*", "i./", "i.%");
344
345    // =========================================================================
346    // Integer Comparison ( a Int Int -- a Bool )
347    // =========================================================================
348
349    builtins_int_int_to_bool!(sigs, "i.=", "i.<", "i.>", "i.<=", "i.>=", "i.<>");
350    builtins_int_int_to_bool!(sigs, "i.eq", "i.lt", "i.gt", "i.lte", "i.gte", "i.neq");
351
352    // =========================================================================
353    // Boolean Operations ( a Bool Bool -- a Bool )
354    // =========================================================================
355
356    builtins_bool_bool_to_bool!(sigs, "and", "or");
357    builtin!(sigs, "not", (a Bool -- a Bool));
358
359    // =========================================================================
360    // Bitwise Operations
361    // =========================================================================
362
363    builtins_int_int_to_int!(sigs, "band", "bor", "bxor", "shl", "shr");
364    builtins_int_to_int!(sigs, "bnot", "popcount", "clz", "ctz");
365    builtin!(sigs, "int-bits", (a -- a Int));
366
367    // =========================================================================
368    // Stack Operations (Polymorphic)
369    // =========================================================================
370
371    builtin!(sigs, "dup", (a T -- a T T));
372    builtin!(sigs, "drop", (a T -- a));
373    builtin!(sigs, "swap", (a T U -- a U T));
374    builtin!(sigs, "over", (a T U -- a T U T));
375    builtin!(sigs, "rot", (a T U V -- a U V T));
376    builtin!(sigs, "nip", (a T U -- a U));
377    builtin!(sigs, "tuck", (a T U -- a U T U));
378    builtin!(sigs, "2dup", (a T U -- a T U T U));
379    builtin!(sigs, "3drop", (a T U V -- a));
380
381    // pick and roll: Type approximations (see detailed comments below)
382    // pick: ( ..a T Int -- ..a T T ) - copies value at depth n to top
383    builtin!(sigs, "pick", (a T Int -- a T T));
384    // roll: ( ..a T Int -- ..a T ) - rotates n+1 items, bringing depth n to top
385    builtin!(sigs, "roll", (a T Int -- a T));
386
387    // =========================================================================
388    // Channel Operations (CSP-style concurrency)
389    // Errors are values, not crashes - all ops return success flags
390    // =========================================================================
391
392    builtin!(sigs, "chan.make", (a -- a Channel));
393    builtin!(sigs, "chan.send", (a T Channel -- a Bool)); // returns success flag
394    builtin!(sigs, "chan.receive", (a Channel -- a T Bool)); // returns value and success flag
395    builtin!(sigs, "chan.close", (a Channel -- a));
396    builtin!(sigs, "chan.yield", (a - -a));
397
398    // =========================================================================
399    // Quotation/Control Flow Operations
400    // =========================================================================
401
402    // call: Polymorphic - accepts Quotation or Closure
403    // Uses type variable Q to represent "something callable"
404    sigs.insert(
405        "call".to_string(),
406        Effect::new(
407            StackType::RowVar("a".to_string()).push(Type::Var("Q".to_string())),
408            StackType::RowVar("b".to_string()),
409        ),
410    );
411
412    // cond: Multi-way conditional (variable arity)
413    sigs.insert(
414        "cond".to_string(),
415        Effect::new(
416            StackType::RowVar("a".to_string()),
417            StackType::RowVar("b".to_string()),
418        ),
419    );
420
421    // times: ( a Quotation Int -- a ) where Quotation has effect ( a -- a )
422    sigs.insert(
423        "times".to_string(),
424        Effect::new(
425            StackType::RowVar("a".to_string())
426                .push(Type::Quotation(Box::new(Effect::new(
427                    StackType::RowVar("a".to_string()),
428                    StackType::RowVar("a".to_string()),
429                ))))
430                .push(Type::Int),
431            StackType::RowVar("a".to_string()),
432        ),
433    );
434
435    // while: ( a CondQuot BodyQuot -- a )
436    // CondQuot: ( a -- a Bool ), BodyQuot: ( a -- a )
437    sigs.insert(
438        "while".to_string(),
439        Effect::new(
440            StackType::RowVar("a".to_string())
441                .push(Type::Quotation(Box::new(Effect::new(
442                    StackType::RowVar("a".to_string()),
443                    StackType::RowVar("a".to_string()).push(Type::Bool),
444                ))))
445                .push(Type::Quotation(Box::new(Effect::new(
446                    StackType::RowVar("a".to_string()),
447                    StackType::RowVar("a".to_string()),
448                )))),
449            StackType::RowVar("a".to_string()),
450        ),
451    );
452
453    // until: ( a BodyQuot CondQuot -- a )
454    // BodyQuot: ( a -- a ), CondQuot: ( a -- a Bool )
455    sigs.insert(
456        "until".to_string(),
457        Effect::new(
458            StackType::RowVar("a".to_string())
459                .push(Type::Quotation(Box::new(Effect::new(
460                    StackType::RowVar("a".to_string()),
461                    StackType::RowVar("a".to_string()),
462                ))))
463                .push(Type::Quotation(Box::new(Effect::new(
464                    StackType::RowVar("a".to_string()),
465                    StackType::RowVar("a".to_string()).push(Type::Bool),
466                )))),
467            StackType::RowVar("a".to_string()),
468        ),
469    );
470
471    // strand.spawn: ( a Quotation -- a Int ) - spawn a concurrent strand
472    // The quotation can have any stack effect - it runs independently
473    sigs.insert(
474        "strand.spawn".to_string(),
475        Effect::new(
476            StackType::RowVar("a".to_string()).push(Type::Quotation(Box::new(Effect::new(
477                StackType::RowVar("spawn_in".to_string()),
478                StackType::RowVar("spawn_out".to_string()),
479            )))),
480            StackType::RowVar("a".to_string()).push(Type::Int),
481        ),
482    );
483
484    // strand.weave: ( a Quotation -- a handle ) - create a woven strand (generator)
485    // The quotation receives (WeaveCtx, first_resume_value) and must thread WeaveCtx through.
486    // Returns a handle (WeaveCtx) for use with strand.resume.
487    sigs.insert(
488        "strand.weave".to_string(),
489        Effect::new(
490            StackType::RowVar("a".to_string()).push(Type::Quotation(Box::new(Effect::new(
491                StackType::RowVar("weave_in".to_string()),
492                StackType::RowVar("weave_out".to_string()),
493            )))),
494            StackType::RowVar("a".to_string()).push(Type::Var("handle".to_string())),
495        ),
496    );
497
498    // strand.resume: ( a handle b -- a handle b Bool ) - resume weave with value
499    // Takes handle and value to send, returns (handle, yielded_value, has_more)
500    sigs.insert(
501        "strand.resume".to_string(),
502        Effect::new(
503            StackType::RowVar("a".to_string())
504                .push(Type::Var("handle".to_string()))
505                .push(Type::Var("b".to_string())),
506            StackType::RowVar("a".to_string())
507                .push(Type::Var("handle".to_string()))
508                .push(Type::Var("b".to_string()))
509                .push(Type::Bool),
510        ),
511    );
512
513    // yield: ( a ctx b -- a ctx b | Yield b ) - yield value and receive resume value
514    // The WeaveCtx must be passed explicitly and threaded through.
515    // The Yield effect indicates this word produces yield semantics.
516    sigs.insert(
517        "yield".to_string(),
518        Effect::with_effects(
519            StackType::RowVar("a".to_string())
520                .push(Type::Var("ctx".to_string()))
521                .push(Type::Var("b".to_string())),
522            StackType::RowVar("a".to_string())
523                .push(Type::Var("ctx".to_string()))
524                .push(Type::Var("b".to_string())),
525            vec![SideEffect::Yield(Box::new(Type::Var("b".to_string())))],
526        ),
527    );
528
529    // strand.weave-cancel: ( a handle -- a ) - cancel a weave and release its resources
530    // Use this to clean up a weave that won't be resumed to completion.
531    // This prevents resource leaks from abandoned weaves.
532    sigs.insert(
533        "strand.weave-cancel".to_string(),
534        Effect::new(
535            StackType::RowVar("a".to_string()).push(Type::Var("handle".to_string())),
536            StackType::RowVar("a".to_string()),
537        ),
538    );
539
540    // =========================================================================
541    // TCP Operations
542    // =========================================================================
543
544    builtin!(sigs, "tcp.listen", (a Int -- a Int));
545    builtin!(sigs, "tcp.accept", (a Int -- a Int));
546    builtin!(sigs, "tcp.read", (a Int -- a String));
547    builtin!(sigs, "tcp.write", (a String Int -- a));
548    builtin!(sigs, "tcp.close", (a Int -- a));
549
550    // =========================================================================
551    // OS Operations
552    // =========================================================================
553
554    builtin!(sigs, "os.getenv", (a String -- a String Bool));
555    builtin!(sigs, "os.home-dir", (a -- a String Bool));
556    builtin!(sigs, "os.current-dir", (a -- a String Bool));
557    builtin!(sigs, "os.path-exists", (a String -- a Bool));
558    builtin!(sigs, "os.path-is-file", (a String -- a Bool));
559    builtin!(sigs, "os.path-is-dir", (a String -- a Bool));
560    builtin!(sigs, "os.path-join", (a String String -- a String));
561    builtin!(sigs, "os.path-parent", (a String -- a String Bool));
562    builtin!(sigs, "os.path-filename", (a String -- a String Bool));
563    builtin!(sigs, "os.exit", (a Int -- a)); // Never returns, but typed as identity
564    builtin!(sigs, "os.name", (a -- a String));
565    builtin!(sigs, "os.arch", (a -- a String));
566
567    // =========================================================================
568    // String Operations
569    // =========================================================================
570
571    builtin!(sigs, "string.concat", (a String String -- a String));
572    builtin!(sigs, "string.length", (a String -- a Int));
573    builtin!(sigs, "string.byte-length", (a String -- a Int));
574    builtin!(sigs, "string.char-at", (a String Int -- a Int));
575    builtin!(sigs, "string.substring", (a String Int Int -- a String));
576    builtin!(sigs, "string.find", (a String String -- a Int));
577    builtin!(sigs, "string.split", (a String String -- a V)); // Returns Variant (list)
578    builtin!(sigs, "string.contains", (a String String -- a Bool));
579    builtin!(sigs, "string.starts-with", (a String String -- a Bool));
580    builtin!(sigs, "string.empty?", (a String -- a Bool));
581    builtin!(sigs, "string.equal?", (a String String -- a Bool));
582
583    // Symbol operations
584    builtin!(sigs, "symbol.=", (a Symbol Symbol -- a Bool));
585
586    // String transformations
587    builtins_string_to_string!(
588        sigs,
589        "string.trim",
590        "string.chomp",
591        "string.to-upper",
592        "string.to-lower",
593        "string.json-escape"
594    );
595
596    // =========================================================================
597    // Encoding Operations
598    // =========================================================================
599
600    builtin!(sigs, "encoding.base64-encode", (a String -- a String));
601    builtin!(sigs, "encoding.base64-decode", (a String -- a String Bool));
602    builtin!(sigs, "encoding.base64url-encode", (a String -- a String));
603    builtin!(sigs, "encoding.base64url-decode", (a String -- a String Bool));
604    builtin!(sigs, "encoding.hex-encode", (a String -- a String));
605    builtin!(sigs, "encoding.hex-decode", (a String -- a String Bool));
606
607    // =========================================================================
608    // Crypto Operations
609    // =========================================================================
610
611    builtin!(sigs, "crypto.sha256", (a String -- a String));
612    builtin!(sigs, "crypto.hmac-sha256", (a String String -- a String));
613    builtin!(sigs, "crypto.constant-time-eq", (a String String -- a Bool));
614    builtin!(sigs, "crypto.random-bytes", (a Int -- a String));
615    builtin!(sigs, "crypto.uuid4", (a -- a String));
616    builtin!(sigs, "crypto.aes-gcm-encrypt", (a String String -- a String Bool));
617    builtin!(sigs, "crypto.aes-gcm-decrypt", (a String String -- a String Bool));
618    builtin!(sigs, "crypto.pbkdf2-sha256", (a String String Int -- a String Bool));
619    builtin!(sigs, "crypto.ed25519-keypair", (a -- a String String));
620    builtin!(sigs, "crypto.ed25519-sign", (a String String -- a String Bool));
621    builtin!(sigs, "crypto.ed25519-verify", (a String String String -- a Bool));
622
623    // =========================================================================
624    // HTTP Client Operations
625    // =========================================================================
626
627    builtin!(sigs, "http.get", (a String -- a M));
628    builtin!(sigs, "http.post", (a String String String -- a M));
629    builtin!(sigs, "http.put", (a String String String -- a M));
630    builtin!(sigs, "http.delete", (a String -- a M));
631
632    // =========================================================================
633    // Regular Expression Operations
634    // =========================================================================
635
636    builtin!(sigs, "regex.match?", (a String String -- a Bool));
637    builtin!(sigs, "regex.find", (a String String -- a String Bool));
638    builtin!(sigs, "regex.find-all", (a String String -- a V));
639    builtin!(sigs, "regex.replace", (a String String String -- a String));
640    builtin!(sigs, "regex.replace-all", (a String String String -- a String));
641    builtin!(sigs, "regex.captures", (a String String -- a V Bool));
642    builtin!(sigs, "regex.split", (a String String -- a V));
643    builtin!(sigs, "regex.valid?", (a String -- a Bool));
644
645    // =========================================================================
646    // Compression Operations
647    // =========================================================================
648
649    builtin!(sigs, "compress.gzip", (a String -- a String Bool));
650    builtin!(sigs, "compress.gzip-level", (a String Int -- a String Bool));
651    builtin!(sigs, "compress.gunzip", (a String -- a String Bool));
652    builtin!(sigs, "compress.zstd", (a String -- a String Bool));
653    builtin!(sigs, "compress.zstd-level", (a String Int -- a String Bool));
654    builtin!(sigs, "compress.unzstd", (a String -- a String Bool));
655
656    // =========================================================================
657    // Variant Operations
658    // =========================================================================
659
660    builtin!(sigs, "variant.field-count", (a V -- a Int));
661    builtin!(sigs, "variant.tag", (a V -- a Symbol));
662    builtin!(sigs, "variant.field-at", (a V Int -- a T));
663    builtin!(sigs, "variant.append", (a V T -- a V2));
664    builtin!(sigs, "variant.last", (a V -- a T));
665    builtin!(sigs, "variant.init", (a V -- a V2));
666
667    // Type-safe variant constructors with fixed arity (symbol tags for SON support)
668    builtin!(sigs, "variant.make-0", (a Symbol -- a V));
669    builtin!(sigs, "variant.make-1", (a T1 Symbol -- a V));
670    builtin!(sigs, "variant.make-2", (a T1 T2 Symbol -- a V));
671    builtin!(sigs, "variant.make-3", (a T1 T2 T3 Symbol -- a V));
672    builtin!(sigs, "variant.make-4", (a T1 T2 T3 T4 Symbol -- a V));
673
674    // Aliases for dynamic variant construction (SON-friendly names)
675    builtin!(sigs, "wrap-0", (a Symbol -- a V));
676    builtin!(sigs, "wrap-1", (a T1 Symbol -- a V));
677    builtin!(sigs, "wrap-2", (a T1 T2 Symbol -- a V));
678    builtin!(sigs, "wrap-3", (a T1 T2 T3 Symbol -- a V));
679    builtin!(sigs, "wrap-4", (a T1 T2 T3 T4 Symbol -- a V));
680
681    // =========================================================================
682    // List Operations (Higher-order combinators for Variants)
683    // =========================================================================
684
685    // List construction and access
686    builtin!(sigs, "list.make", (a -- a V));
687    builtin!(sigs, "list.push", (a V T -- a V));
688    builtin!(sigs, "list.get", (a V Int -- a T Bool));
689    builtin!(sigs, "list.set", (a V Int T -- a V Bool));
690
691    builtin!(sigs, "list.length", (a V -- a Int));
692    builtin!(sigs, "list.empty?", (a V -- a Bool));
693
694    // list.map: ( a Variant Quotation -- a Variant )
695    // Quotation: ( b T -- b U )
696    sigs.insert(
697        "list.map".to_string(),
698        Effect::new(
699            StackType::RowVar("a".to_string())
700                .push(Type::Var("V".to_string()))
701                .push(Type::Quotation(Box::new(Effect::new(
702                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
703                    StackType::RowVar("b".to_string()).push(Type::Var("U".to_string())),
704                )))),
705            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
706        ),
707    );
708
709    // list.filter: ( a Variant Quotation -- a Variant )
710    // Quotation: ( b T -- b Bool )
711    sigs.insert(
712        "list.filter".to_string(),
713        Effect::new(
714            StackType::RowVar("a".to_string())
715                .push(Type::Var("V".to_string()))
716                .push(Type::Quotation(Box::new(Effect::new(
717                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
718                    StackType::RowVar("b".to_string()).push(Type::Bool),
719                )))),
720            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
721        ),
722    );
723
724    // list.fold: ( a Variant init Quotation -- a result )
725    // Quotation: ( b Acc T -- b Acc )
726    sigs.insert(
727        "list.fold".to_string(),
728        Effect::new(
729            StackType::RowVar("a".to_string())
730                .push(Type::Var("V".to_string()))
731                .push(Type::Var("Acc".to_string()))
732                .push(Type::Quotation(Box::new(Effect::new(
733                    StackType::RowVar("b".to_string())
734                        .push(Type::Var("Acc".to_string()))
735                        .push(Type::Var("T".to_string())),
736                    StackType::RowVar("b".to_string()).push(Type::Var("Acc".to_string())),
737                )))),
738            StackType::RowVar("a".to_string()).push(Type::Var("Acc".to_string())),
739        ),
740    );
741
742    // list.each: ( a Variant Quotation -- a )
743    // Quotation: ( b T -- b )
744    sigs.insert(
745        "list.each".to_string(),
746        Effect::new(
747            StackType::RowVar("a".to_string())
748                .push(Type::Var("V".to_string()))
749                .push(Type::Quotation(Box::new(Effect::new(
750                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
751                    StackType::RowVar("b".to_string()),
752                )))),
753            StackType::RowVar("a".to_string()),
754        ),
755    );
756
757    // =========================================================================
758    // Map Operations (Dictionary with O(1) lookup)
759    // =========================================================================
760
761    builtin!(sigs, "map.make", (a -- a M));
762    builtin!(sigs, "map.get", (a M K -- a V Bool)); // returns (value success) - errors are values, not crashes
763    builtin!(sigs, "map.set", (a M K V -- a M2));
764    builtin!(sigs, "map.has?", (a M K -- a Bool));
765    builtin!(sigs, "map.remove", (a M K -- a M2));
766    builtin!(sigs, "map.keys", (a M -- a V));
767    builtin!(sigs, "map.values", (a M -- a V));
768    builtin!(sigs, "map.size", (a M -- a Int));
769    builtin!(sigs, "map.empty?", (a M -- a Bool));
770
771    // =========================================================================
772    // Float Arithmetic ( a Float Float -- a Float )
773    // =========================================================================
774
775    builtins_float_float_to_float!(sigs, "f.add", "f.subtract", "f.multiply", "f.divide");
776    builtins_float_float_to_float!(sigs, "f.+", "f.-", "f.*", "f./");
777
778    // =========================================================================
779    // Float Comparison ( a Float Float -- a Bool )
780    // =========================================================================
781
782    builtins_float_float_to_bool!(sigs, "f.=", "f.<", "f.>", "f.<=", "f.>=", "f.<>");
783    builtins_float_float_to_bool!(sigs, "f.eq", "f.lt", "f.gt", "f.lte", "f.gte", "f.neq");
784
785    // =========================================================================
786    // Test Framework
787    // =========================================================================
788
789    builtin!(sigs, "test.init", (a String -- a));
790    builtin!(sigs, "test.finish", (a - -a));
791    builtin!(sigs, "test.has-failures", (a -- a Bool));
792    builtin!(sigs, "test.assert", (a Bool -- a));
793    builtin!(sigs, "test.assert-not", (a Bool -- a));
794    builtin!(sigs, "test.assert-eq", (a Int Int -- a));
795    builtin!(sigs, "test.assert-eq-str", (a String String -- a));
796    builtin!(sigs, "test.fail", (a String -- a));
797    builtin!(sigs, "test.pass-count", (a -- a Int));
798    builtin!(sigs, "test.fail-count", (a -- a Int));
799
800    // Time operations
801    builtin!(sigs, "time.now", (a -- a Int));
802    builtin!(sigs, "time.nanos", (a -- a Int));
803    builtin!(sigs, "time.sleep-ms", (a Int -- a));
804
805    // SON serialization
806    builtin!(sigs, "son.dump", (a T -- a String));
807    builtin!(sigs, "son.dump-pretty", (a T -- a String));
808
809    // Stack introspection (for REPL)
810    // stack.dump prints all values and clears the stack
811    sigs.insert(
812        "stack.dump".to_string(),
813        Effect::new(
814            StackType::RowVar("a".to_string()), // Consumes any stack
815            StackType::RowVar("b".to_string()), // Returns empty stack (different row var)
816        ),
817    );
818
819    sigs
820}
821
822/// Get documentation for a built-in word
823pub fn builtin_doc(name: &str) -> Option<&'static str> {
824    BUILTIN_DOCS.get(name).copied()
825}
826
827/// Get all built-in word documentation (cached with LazyLock for performance)
828pub fn builtin_docs() -> &'static HashMap<&'static str, &'static str> {
829    &BUILTIN_DOCS
830}
831
832/// Lazily initialized documentation for all built-in words
833static BUILTIN_DOCS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
834    let mut docs = HashMap::new();
835
836    // I/O Operations
837    docs.insert(
838        "io.write",
839        "Write a string to stdout without a trailing newline.",
840    );
841    docs.insert(
842        "io.write-line",
843        "Write a string to stdout followed by a newline.",
844    );
845    docs.insert(
846        "io.read-line",
847        "Read a line from stdin. Returns (line, success).",
848    );
849    docs.insert(
850        "io.read-line+",
851        "Read a line from stdin. Returns (line, status_code).",
852    );
853    docs.insert(
854        "io.read-n",
855        "Read N bytes from stdin. Returns (bytes, status_code).",
856    );
857
858    // Command-line Arguments
859    docs.insert("args.count", "Get the number of command-line arguments.");
860    docs.insert("args.at", "Get the command-line argument at index N.");
861
862    // File Operations
863    docs.insert(
864        "file.slurp",
865        "Read entire file contents. Returns (content, success).",
866    );
867    docs.insert("file.exists?", "Check if a file exists at the given path.");
868    docs.insert(
869        "file.for-each-line+",
870        "Execute a quotation for each line in a file.",
871    );
872
873    // Type Conversions
874    docs.insert(
875        "int->string",
876        "Convert an integer to its string representation.",
877    );
878    docs.insert(
879        "int->float",
880        "Convert an integer to a floating-point number.",
881    );
882    docs.insert("float->int", "Truncate a float to an integer.");
883    docs.insert(
884        "float->string",
885        "Convert a float to its string representation.",
886    );
887    docs.insert(
888        "string->int",
889        "Parse a string as an integer. Returns (value, success).",
890    );
891    docs.insert(
892        "string->float",
893        "Parse a string as a float. Returns (value, success).",
894    );
895    docs.insert(
896        "char->string",
897        "Convert a Unicode codepoint to a single-character string.",
898    );
899    docs.insert(
900        "symbol->string",
901        "Convert a symbol to its string representation.",
902    );
903    docs.insert("string->symbol", "Intern a string as a symbol.");
904
905    // Integer Arithmetic
906    docs.insert("i.add", "Add two integers.");
907    docs.insert("i.subtract", "Subtract second integer from first.");
908    docs.insert("i.multiply", "Multiply two integers.");
909    docs.insert("i.divide", "Integer division (truncates toward zero).");
910    docs.insert("i.modulo", "Integer modulo (remainder after division).");
911    docs.insert("i.+", "Add two integers.");
912    docs.insert("i.-", "Subtract second integer from first.");
913    docs.insert("i.*", "Multiply two integers.");
914    docs.insert("i./", "Integer division (truncates toward zero).");
915    docs.insert("i.%", "Integer modulo (remainder after division).");
916
917    // Integer Comparison
918    docs.insert("i.=", "Test if two integers are equal.");
919    docs.insert("i.<", "Test if first integer is less than second.");
920    docs.insert("i.>", "Test if first integer is greater than second.");
921    docs.insert(
922        "i.<=",
923        "Test if first integer is less than or equal to second.",
924    );
925    docs.insert(
926        "i.>=",
927        "Test if first integer is greater than or equal to second.",
928    );
929    docs.insert("i.<>", "Test if two integers are not equal.");
930    docs.insert("i.eq", "Test if two integers are equal.");
931    docs.insert("i.lt", "Test if first integer is less than second.");
932    docs.insert("i.gt", "Test if first integer is greater than second.");
933    docs.insert(
934        "i.lte",
935        "Test if first integer is less than or equal to second.",
936    );
937    docs.insert(
938        "i.gte",
939        "Test if first integer is greater than or equal to second.",
940    );
941    docs.insert("i.neq", "Test if two integers are not equal.");
942
943    // Boolean Operations
944    docs.insert("and", "Logical AND of two booleans.");
945    docs.insert("or", "Logical OR of two booleans.");
946    docs.insert("not", "Logical NOT of a boolean.");
947
948    // Bitwise Operations
949    docs.insert("band", "Bitwise AND of two integers.");
950    docs.insert("bor", "Bitwise OR of two integers.");
951    docs.insert("bxor", "Bitwise XOR of two integers.");
952    docs.insert("bnot", "Bitwise NOT (complement) of an integer.");
953    docs.insert("shl", "Shift left by N bits.");
954    docs.insert("shr", "Shift right by N bits (arithmetic).");
955    docs.insert("popcount", "Count the number of set bits.");
956    docs.insert("clz", "Count leading zeros.");
957    docs.insert("ctz", "Count trailing zeros.");
958    docs.insert("int-bits", "Push the bit width of integers (64).");
959
960    // Stack Operations
961    docs.insert("dup", "Duplicate the top stack value.");
962    docs.insert("drop", "Remove the top stack value.");
963    docs.insert("swap", "Swap the top two stack values.");
964    docs.insert("over", "Copy the second value to the top.");
965    docs.insert("rot", "Rotate the top three values (third to top).");
966    docs.insert("nip", "Remove the second value from the stack.");
967    docs.insert("tuck", "Copy the top value below the second.");
968    docs.insert("2dup", "Duplicate the top two values.");
969    docs.insert("3drop", "Remove the top three values.");
970    docs.insert("pick", "Copy the value at depth N to the top.");
971    docs.insert("roll", "Rotate N+1 items, bringing depth N to top.");
972
973    // Channel Operations
974    docs.insert(
975        "chan.make",
976        "Create a new channel for inter-strand communication.",
977    );
978    docs.insert(
979        "chan.send",
980        "Send a value on a channel. Returns success flag.",
981    );
982    docs.insert(
983        "chan.receive",
984        "Receive a value from a channel. Returns (value, success).",
985    );
986    docs.insert("chan.close", "Close a channel.");
987    docs.insert("chan.yield", "Yield control to the scheduler.");
988
989    // Control Flow
990    docs.insert("call", "Call a quotation or closure.");
991    docs.insert(
992        "cond",
993        "Multi-way conditional: test clauses until one succeeds.",
994    );
995    docs.insert("times", "Execute a quotation N times.");
996    docs.insert("while", "Loop while condition is true: [cond] [body] while");
997    docs.insert("until", "Loop until condition is true: [body] [cond] until");
998
999    // Concurrency
1000    docs.insert(
1001        "strand.spawn",
1002        "Spawn a concurrent strand. Returns strand ID.",
1003    );
1004    docs.insert(
1005        "strand.weave",
1006        "Create a generator/coroutine. Returns handle.",
1007    );
1008    docs.insert(
1009        "strand.resume",
1010        "Resume a weave with a value. Returns (handle, value, has_more).",
1011    );
1012    docs.insert(
1013        "yield",
1014        "Yield a value from a weave and receive resume value.",
1015    );
1016    docs.insert(
1017        "strand.weave-cancel",
1018        "Cancel a weave and release its resources.",
1019    );
1020
1021    // TCP Operations
1022    docs.insert(
1023        "tcp.listen",
1024        "Start listening on a port. Returns socket ID.",
1025    );
1026    docs.insert(
1027        "tcp.accept",
1028        "Accept a connection. Returns client socket ID.",
1029    );
1030    docs.insert("tcp.read", "Read data from a socket. Returns string.");
1031    docs.insert("tcp.write", "Write data to a socket.");
1032    docs.insert("tcp.close", "Close a socket.");
1033
1034    // OS Operations
1035    docs.insert(
1036        "os.getenv",
1037        "Get environment variable. Returns (value, exists).",
1038    );
1039    docs.insert(
1040        "os.home-dir",
1041        "Get user's home directory. Returns (path, success).",
1042    );
1043    docs.insert(
1044        "os.current-dir",
1045        "Get current working directory. Returns (path, success).",
1046    );
1047    docs.insert("os.path-exists", "Check if a path exists.");
1048    docs.insert("os.path-is-file", "Check if path is a regular file.");
1049    docs.insert("os.path-is-dir", "Check if path is a directory.");
1050    docs.insert("os.path-join", "Join two path components.");
1051    docs.insert(
1052        "os.path-parent",
1053        "Get parent directory. Returns (path, success).",
1054    );
1055    docs.insert(
1056        "os.path-filename",
1057        "Get filename component. Returns (name, success).",
1058    );
1059    docs.insert("os.exit", "Exit the program with a status code.");
1060    docs.insert(
1061        "os.name",
1062        "Get the operating system name (e.g., \"macos\", \"linux\").",
1063    );
1064    docs.insert(
1065        "os.arch",
1066        "Get the CPU architecture (e.g., \"aarch64\", \"x86_64\").",
1067    );
1068
1069    // String Operations
1070    docs.insert("string.concat", "Concatenate two strings.");
1071    docs.insert("string.length", "Get the character length of a string.");
1072    docs.insert("string.byte-length", "Get the byte length of a string.");
1073    docs.insert(
1074        "string.char-at",
1075        "Get Unicode codepoint at character index.",
1076    );
1077    docs.insert(
1078        "string.substring",
1079        "Extract substring from start index with length.",
1080    );
1081    docs.insert(
1082        "string.find",
1083        "Find substring. Returns index or -1 if not found.",
1084    );
1085    docs.insert("string.split", "Split string by delimiter. Returns a list.");
1086    docs.insert("string.contains", "Check if string contains a substring.");
1087    docs.insert(
1088        "string.starts-with",
1089        "Check if string starts with a prefix.",
1090    );
1091    docs.insert("string.empty?", "Check if string is empty.");
1092    docs.insert("string.equal?", "Check if two strings are equal.");
1093    docs.insert("string.trim", "Remove leading and trailing whitespace.");
1094    docs.insert("string.chomp", "Remove trailing newline.");
1095    docs.insert("string.to-upper", "Convert to uppercase.");
1096    docs.insert("string.to-lower", "Convert to lowercase.");
1097    docs.insert("string.json-escape", "Escape special characters for JSON.");
1098    docs.insert("symbol.=", "Check if two symbols are equal.");
1099
1100    // Encoding Operations
1101    docs.insert(
1102        "encoding.base64-encode",
1103        "Encode a string to Base64 (standard alphabet with padding).",
1104    );
1105    docs.insert(
1106        "encoding.base64-decode",
1107        "Decode a Base64 string. Returns (decoded, success).",
1108    );
1109    docs.insert(
1110        "encoding.base64url-encode",
1111        "Encode to URL-safe Base64 (no padding). Suitable for JWTs and URLs.",
1112    );
1113    docs.insert(
1114        "encoding.base64url-decode",
1115        "Decode URL-safe Base64. Returns (decoded, success).",
1116    );
1117    docs.insert(
1118        "encoding.hex-encode",
1119        "Encode a string to lowercase hexadecimal.",
1120    );
1121    docs.insert(
1122        "encoding.hex-decode",
1123        "Decode a hexadecimal string. Returns (decoded, success).",
1124    );
1125
1126    // Crypto Operations
1127    docs.insert(
1128        "crypto.sha256",
1129        "Compute SHA-256 hash of a string. Returns 64-char hex digest.",
1130    );
1131    docs.insert(
1132        "crypto.hmac-sha256",
1133        "Compute HMAC-SHA256 signature. ( message key -- signature )",
1134    );
1135    docs.insert(
1136        "crypto.constant-time-eq",
1137        "Timing-safe string comparison. Use for comparing signatures/tokens.",
1138    );
1139    docs.insert(
1140        "crypto.random-bytes",
1141        "Generate N cryptographically secure random bytes as hex string.",
1142    );
1143    docs.insert("crypto.uuid4", "Generate a random UUID v4 string.");
1144    docs.insert(
1145        "crypto.aes-gcm-encrypt",
1146        "Encrypt with AES-256-GCM. ( plaintext hex-key -- ciphertext success )",
1147    );
1148    docs.insert(
1149        "crypto.aes-gcm-decrypt",
1150        "Decrypt AES-256-GCM ciphertext. ( ciphertext hex-key -- plaintext success )",
1151    );
1152    docs.insert(
1153        "crypto.pbkdf2-sha256",
1154        "Derive key from password. ( password salt iterations -- hex-key success ) Min 1000 iterations, 100000+ recommended.",
1155    );
1156    docs.insert(
1157        "crypto.ed25519-keypair",
1158        "Generate Ed25519 keypair. ( -- public-key private-key ) Both as 64-char hex strings.",
1159    );
1160    docs.insert(
1161        "crypto.ed25519-sign",
1162        "Sign message with Ed25519 private key. ( message private-key -- signature success ) Signature is 128-char hex.",
1163    );
1164    docs.insert(
1165        "crypto.ed25519-verify",
1166        "Verify Ed25519 signature. ( message signature public-key -- valid )",
1167    );
1168
1169    // HTTP Client Operations
1170    docs.insert(
1171        "http.get",
1172        "HTTP GET request. ( url -- response-map ) Map has status, body, ok, error.",
1173    );
1174    docs.insert(
1175        "http.post",
1176        "HTTP POST request. ( url body content-type -- response-map )",
1177    );
1178    docs.insert(
1179        "http.put",
1180        "HTTP PUT request. ( url body content-type -- response-map )",
1181    );
1182    docs.insert(
1183        "http.delete",
1184        "HTTP DELETE request. ( url -- response-map )",
1185    );
1186
1187    // Regular Expression Operations
1188    docs.insert(
1189        "regex.match?",
1190        "Check if pattern matches anywhere in string. ( text pattern -- bool )",
1191    );
1192    docs.insert(
1193        "regex.find",
1194        "Find first match. ( text pattern -- matched success )",
1195    );
1196    docs.insert(
1197        "regex.find-all",
1198        "Find all matches. ( text pattern -- list )",
1199    );
1200    docs.insert(
1201        "regex.replace",
1202        "Replace first match. ( text pattern replacement -- result )",
1203    );
1204    docs.insert(
1205        "regex.replace-all",
1206        "Replace all matches. ( text pattern replacement -- result )",
1207    );
1208    docs.insert(
1209        "regex.captures",
1210        "Extract capture groups. ( text pattern -- groups success )",
1211    );
1212    docs.insert(
1213        "regex.split",
1214        "Split string by pattern. ( text pattern -- list )",
1215    );
1216    docs.insert(
1217        "regex.valid?",
1218        "Check if pattern is valid regex. ( pattern -- bool )",
1219    );
1220
1221    // Compression Operations
1222    docs.insert(
1223        "compress.gzip",
1224        "Compress string with gzip. Returns base64-encoded data. ( data -- compressed success )",
1225    );
1226    docs.insert(
1227        "compress.gzip-level",
1228        "Compress with gzip at level 1-9. ( data level -- compressed success )",
1229    );
1230    docs.insert(
1231        "compress.gunzip",
1232        "Decompress gzip data. ( base64-data -- decompressed success )",
1233    );
1234    docs.insert(
1235        "compress.zstd",
1236        "Compress string with zstd. Returns base64-encoded data. ( data -- compressed success )",
1237    );
1238    docs.insert(
1239        "compress.zstd-level",
1240        "Compress with zstd at level 1-22. ( data level -- compressed success )",
1241    );
1242    docs.insert(
1243        "compress.unzstd",
1244        "Decompress zstd data. ( base64-data -- decompressed success )",
1245    );
1246
1247    // Variant Operations
1248    docs.insert(
1249        "variant.field-count",
1250        "Get the number of fields in a variant.",
1251    );
1252    docs.insert(
1253        "variant.tag",
1254        "Get the tag (constructor name) of a variant.",
1255    );
1256    docs.insert("variant.field-at", "Get the field at index N.");
1257    docs.insert(
1258        "variant.append",
1259        "Append a value to a variant (creates new).",
1260    );
1261    docs.insert("variant.last", "Get the last field of a variant.");
1262    docs.insert("variant.init", "Get all fields except the last.");
1263    docs.insert("variant.make-0", "Create a variant with 0 fields.");
1264    docs.insert("variant.make-1", "Create a variant with 1 field.");
1265    docs.insert("variant.make-2", "Create a variant with 2 fields.");
1266    docs.insert("variant.make-3", "Create a variant with 3 fields.");
1267    docs.insert("variant.make-4", "Create a variant with 4 fields.");
1268    docs.insert("wrap-0", "Create a variant with 0 fields (alias).");
1269    docs.insert("wrap-1", "Create a variant with 1 field (alias).");
1270    docs.insert("wrap-2", "Create a variant with 2 fields (alias).");
1271    docs.insert("wrap-3", "Create a variant with 3 fields (alias).");
1272    docs.insert("wrap-4", "Create a variant with 4 fields (alias).");
1273
1274    // List Operations
1275    docs.insert("list.make", "Create an empty list.");
1276    docs.insert("list.push", "Push a value onto a list. Returns new list.");
1277    docs.insert("list.get", "Get value at index. Returns (value, success).");
1278    docs.insert("list.set", "Set value at index. Returns (list, success).");
1279    docs.insert("list.length", "Get the number of elements in a list.");
1280    docs.insert("list.empty?", "Check if a list is empty.");
1281    docs.insert(
1282        "list.map",
1283        "Apply quotation to each element. Returns new list.",
1284    );
1285    docs.insert("list.filter", "Keep elements where quotation returns true.");
1286    docs.insert("list.fold", "Reduce list with accumulator and quotation.");
1287    docs.insert(
1288        "list.each",
1289        "Execute quotation for each element (side effects).",
1290    );
1291
1292    // Map Operations
1293    docs.insert("map.make", "Create an empty map.");
1294    docs.insert("map.get", "Get value for key. Returns (value, success).");
1295    docs.insert("map.set", "Set key to value. Returns new map.");
1296    docs.insert("map.has?", "Check if map contains a key.");
1297    docs.insert("map.remove", "Remove a key. Returns new map.");
1298    docs.insert("map.keys", "Get all keys as a list.");
1299    docs.insert("map.values", "Get all values as a list.");
1300    docs.insert("map.size", "Get the number of key-value pairs.");
1301    docs.insert("map.empty?", "Check if map is empty.");
1302
1303    // Float Arithmetic
1304    docs.insert("f.add", "Add two floats.");
1305    docs.insert("f.subtract", "Subtract second float from first.");
1306    docs.insert("f.multiply", "Multiply two floats.");
1307    docs.insert("f.divide", "Divide first float by second.");
1308    docs.insert("f.+", "Add two floats.");
1309    docs.insert("f.-", "Subtract second float from first.");
1310    docs.insert("f.*", "Multiply two floats.");
1311    docs.insert("f./", "Divide first float by second.");
1312
1313    // Float Comparison
1314    docs.insert("f.=", "Test if two floats are equal.");
1315    docs.insert("f.<", "Test if first float is less than second.");
1316    docs.insert("f.>", "Test if first float is greater than second.");
1317    docs.insert("f.<=", "Test if first float is less than or equal.");
1318    docs.insert("f.>=", "Test if first float is greater than or equal.");
1319    docs.insert("f.<>", "Test if two floats are not equal.");
1320    docs.insert("f.eq", "Test if two floats are equal.");
1321    docs.insert("f.lt", "Test if first float is less than second.");
1322    docs.insert("f.gt", "Test if first float is greater than second.");
1323    docs.insert("f.lte", "Test if first float is less than or equal.");
1324    docs.insert("f.gte", "Test if first float is greater than or equal.");
1325    docs.insert("f.neq", "Test if two floats are not equal.");
1326
1327    // Test Framework
1328    docs.insert(
1329        "test.init",
1330        "Initialize the test framework with a test name.",
1331    );
1332    docs.insert("test.finish", "Finish testing and print results.");
1333    docs.insert("test.has-failures", "Check if any tests have failed.");
1334    docs.insert("test.assert", "Assert that a boolean is true.");
1335    docs.insert("test.assert-not", "Assert that a boolean is false.");
1336    docs.insert("test.assert-eq", "Assert that two integers are equal.");
1337    docs.insert("test.assert-eq-str", "Assert that two strings are equal.");
1338    docs.insert("test.fail", "Mark a test as failed with a message.");
1339    docs.insert("test.pass-count", "Get the number of passed assertions.");
1340    docs.insert("test.fail-count", "Get the number of failed assertions.");
1341
1342    // Time Operations
1343    docs.insert("time.now", "Get current Unix timestamp in seconds.");
1344    docs.insert(
1345        "time.nanos",
1346        "Get high-resolution monotonic time in nanoseconds.",
1347    );
1348    docs.insert("time.sleep-ms", "Sleep for N milliseconds.");
1349
1350    // Serialization
1351    docs.insert("son.dump", "Serialize any value to SON format (compact).");
1352    docs.insert(
1353        "son.dump-pretty",
1354        "Serialize any value to SON format (pretty-printed).",
1355    );
1356
1357    // Stack Introspection
1358    docs.insert(
1359        "stack.dump",
1360        "Print all stack values and clear the stack (REPL).",
1361    );
1362
1363    docs
1364});
1365
1366#[cfg(test)]
1367mod tests {
1368    use super::*;
1369
1370    #[test]
1371    fn test_builtin_signature_write_line() {
1372        let sig = builtin_signature("io.write-line").unwrap();
1373        // ( ..a String -- ..a )
1374        let (rest, top) = sig.inputs.clone().pop().unwrap();
1375        assert_eq!(top, Type::String);
1376        assert_eq!(rest, StackType::RowVar("a".to_string()));
1377        assert_eq!(sig.outputs, StackType::RowVar("a".to_string()));
1378    }
1379
1380    #[test]
1381    fn test_builtin_signature_i_add() {
1382        let sig = builtin_signature("i.add").unwrap();
1383        // ( ..a Int Int -- ..a Int )
1384        let (rest, top) = sig.inputs.clone().pop().unwrap();
1385        assert_eq!(top, Type::Int);
1386        let (rest2, top2) = rest.pop().unwrap();
1387        assert_eq!(top2, Type::Int);
1388        assert_eq!(rest2, StackType::RowVar("a".to_string()));
1389
1390        let (rest3, top3) = sig.outputs.clone().pop().unwrap();
1391        assert_eq!(top3, Type::Int);
1392        assert_eq!(rest3, StackType::RowVar("a".to_string()));
1393    }
1394
1395    #[test]
1396    fn test_builtin_signature_dup() {
1397        let sig = builtin_signature("dup").unwrap();
1398        // Input: ( ..a T )
1399        assert_eq!(
1400            sig.inputs,
1401            StackType::Cons {
1402                rest: Box::new(StackType::RowVar("a".to_string())),
1403                top: Type::Var("T".to_string())
1404            }
1405        );
1406        // Output: ( ..a T T )
1407        let (rest, top) = sig.outputs.clone().pop().unwrap();
1408        assert_eq!(top, Type::Var("T".to_string()));
1409        let (rest2, top2) = rest.pop().unwrap();
1410        assert_eq!(top2, Type::Var("T".to_string()));
1411        assert_eq!(rest2, StackType::RowVar("a".to_string()));
1412    }
1413
1414    #[test]
1415    fn test_all_builtins_have_signatures() {
1416        let sigs = builtin_signatures();
1417
1418        // Verify all expected builtins have signatures
1419        assert!(sigs.contains_key("io.write-line"));
1420        assert!(sigs.contains_key("io.read-line"));
1421        assert!(sigs.contains_key("int->string"));
1422        assert!(sigs.contains_key("i.add"));
1423        assert!(sigs.contains_key("dup"));
1424        assert!(sigs.contains_key("swap"));
1425        assert!(sigs.contains_key("chan.make"));
1426        assert!(sigs.contains_key("chan.send"));
1427        assert!(sigs.contains_key("chan.receive"));
1428        assert!(
1429            sigs.contains_key("string->float"),
1430            "string->float should be a builtin"
1431        );
1432    }
1433
1434    #[test]
1435    fn test_all_docs_have_signatures() {
1436        let sigs = builtin_signatures();
1437        let docs = builtin_docs();
1438
1439        for name in docs.keys() {
1440            assert!(
1441                sigs.contains_key(*name),
1442                "Builtin '{}' has documentation but no signature",
1443                name
1444            );
1445        }
1446    }
1447
1448    #[test]
1449    fn test_all_signatures_have_docs() {
1450        let sigs = builtin_signatures();
1451        let docs = builtin_docs();
1452
1453        for name in sigs.keys() {
1454            assert!(
1455                docs.contains_key(name.as_str()),
1456                "Builtin '{}' has signature but no documentation",
1457                name
1458            );
1459        }
1460    }
1461}