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
617    // =========================================================================
618    // HTTP Client Operations
619    // =========================================================================
620
621    builtin!(sigs, "http.get", (a String -- a M));
622    builtin!(sigs, "http.post", (a String String String -- a M));
623    builtin!(sigs, "http.put", (a String String String -- a M));
624    builtin!(sigs, "http.delete", (a String -- a M));
625
626    // =========================================================================
627    // Variant Operations
628    // =========================================================================
629
630    builtin!(sigs, "variant.field-count", (a V -- a Int));
631    builtin!(sigs, "variant.tag", (a V -- a Symbol));
632    builtin!(sigs, "variant.field-at", (a V Int -- a T));
633    builtin!(sigs, "variant.append", (a V T -- a V2));
634    builtin!(sigs, "variant.last", (a V -- a T));
635    builtin!(sigs, "variant.init", (a V -- a V2));
636
637    // Type-safe variant constructors with fixed arity (symbol tags for SON support)
638    builtin!(sigs, "variant.make-0", (a Symbol -- a V));
639    builtin!(sigs, "variant.make-1", (a T1 Symbol -- a V));
640    builtin!(sigs, "variant.make-2", (a T1 T2 Symbol -- a V));
641    builtin!(sigs, "variant.make-3", (a T1 T2 T3 Symbol -- a V));
642    builtin!(sigs, "variant.make-4", (a T1 T2 T3 T4 Symbol -- a V));
643
644    // Aliases for dynamic variant construction (SON-friendly names)
645    builtin!(sigs, "wrap-0", (a Symbol -- a V));
646    builtin!(sigs, "wrap-1", (a T1 Symbol -- a V));
647    builtin!(sigs, "wrap-2", (a T1 T2 Symbol -- a V));
648    builtin!(sigs, "wrap-3", (a T1 T2 T3 Symbol -- a V));
649    builtin!(sigs, "wrap-4", (a T1 T2 T3 T4 Symbol -- a V));
650
651    // =========================================================================
652    // List Operations (Higher-order combinators for Variants)
653    // =========================================================================
654
655    // List construction and access
656    builtin!(sigs, "list.make", (a -- a V));
657    builtin!(sigs, "list.push", (a V T -- a V));
658    builtin!(sigs, "list.get", (a V Int -- a T Bool));
659    builtin!(sigs, "list.set", (a V Int T -- a V Bool));
660
661    builtin!(sigs, "list.length", (a V -- a Int));
662    builtin!(sigs, "list.empty?", (a V -- a Bool));
663
664    // list.map: ( a Variant Quotation -- a Variant )
665    // Quotation: ( b T -- b U )
666    sigs.insert(
667        "list.map".to_string(),
668        Effect::new(
669            StackType::RowVar("a".to_string())
670                .push(Type::Var("V".to_string()))
671                .push(Type::Quotation(Box::new(Effect::new(
672                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
673                    StackType::RowVar("b".to_string()).push(Type::Var("U".to_string())),
674                )))),
675            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
676        ),
677    );
678
679    // list.filter: ( a Variant Quotation -- a Variant )
680    // Quotation: ( b T -- b Bool )
681    sigs.insert(
682        "list.filter".to_string(),
683        Effect::new(
684            StackType::RowVar("a".to_string())
685                .push(Type::Var("V".to_string()))
686                .push(Type::Quotation(Box::new(Effect::new(
687                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
688                    StackType::RowVar("b".to_string()).push(Type::Bool),
689                )))),
690            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
691        ),
692    );
693
694    // list.fold: ( a Variant init Quotation -- a result )
695    // Quotation: ( b Acc T -- b Acc )
696    sigs.insert(
697        "list.fold".to_string(),
698        Effect::new(
699            StackType::RowVar("a".to_string())
700                .push(Type::Var("V".to_string()))
701                .push(Type::Var("Acc".to_string()))
702                .push(Type::Quotation(Box::new(Effect::new(
703                    StackType::RowVar("b".to_string())
704                        .push(Type::Var("Acc".to_string()))
705                        .push(Type::Var("T".to_string())),
706                    StackType::RowVar("b".to_string()).push(Type::Var("Acc".to_string())),
707                )))),
708            StackType::RowVar("a".to_string()).push(Type::Var("Acc".to_string())),
709        ),
710    );
711
712    // list.each: ( a Variant Quotation -- a )
713    // Quotation: ( b T -- b )
714    sigs.insert(
715        "list.each".to_string(),
716        Effect::new(
717            StackType::RowVar("a".to_string())
718                .push(Type::Var("V".to_string()))
719                .push(Type::Quotation(Box::new(Effect::new(
720                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
721                    StackType::RowVar("b".to_string()),
722                )))),
723            StackType::RowVar("a".to_string()),
724        ),
725    );
726
727    // =========================================================================
728    // Map Operations (Dictionary with O(1) lookup)
729    // =========================================================================
730
731    builtin!(sigs, "map.make", (a -- a M));
732    builtin!(sigs, "map.get", (a M K -- a V Bool)); // returns (value success) - errors are values, not crashes
733    builtin!(sigs, "map.set", (a M K V -- a M2));
734    builtin!(sigs, "map.has?", (a M K -- a Bool));
735    builtin!(sigs, "map.remove", (a M K -- a M2));
736    builtin!(sigs, "map.keys", (a M -- a V));
737    builtin!(sigs, "map.values", (a M -- a V));
738    builtin!(sigs, "map.size", (a M -- a Int));
739    builtin!(sigs, "map.empty?", (a M -- a Bool));
740
741    // =========================================================================
742    // Float Arithmetic ( a Float Float -- a Float )
743    // =========================================================================
744
745    builtins_float_float_to_float!(sigs, "f.add", "f.subtract", "f.multiply", "f.divide");
746    builtins_float_float_to_float!(sigs, "f.+", "f.-", "f.*", "f./");
747
748    // =========================================================================
749    // Float Comparison ( a Float Float -- a Bool )
750    // =========================================================================
751
752    builtins_float_float_to_bool!(sigs, "f.=", "f.<", "f.>", "f.<=", "f.>=", "f.<>");
753    builtins_float_float_to_bool!(sigs, "f.eq", "f.lt", "f.gt", "f.lte", "f.gte", "f.neq");
754
755    // =========================================================================
756    // Test Framework
757    // =========================================================================
758
759    builtin!(sigs, "test.init", (a String -- a));
760    builtin!(sigs, "test.finish", (a - -a));
761    builtin!(sigs, "test.has-failures", (a -- a Bool));
762    builtin!(sigs, "test.assert", (a Bool -- a));
763    builtin!(sigs, "test.assert-not", (a Bool -- a));
764    builtin!(sigs, "test.assert-eq", (a Int Int -- a));
765    builtin!(sigs, "test.assert-eq-str", (a String String -- a));
766    builtin!(sigs, "test.fail", (a String -- a));
767    builtin!(sigs, "test.pass-count", (a -- a Int));
768    builtin!(sigs, "test.fail-count", (a -- a Int));
769
770    // Time operations
771    builtin!(sigs, "time.now", (a -- a Int));
772    builtin!(sigs, "time.nanos", (a -- a Int));
773    builtin!(sigs, "time.sleep-ms", (a Int -- a));
774
775    // SON serialization
776    builtin!(sigs, "son.dump", (a T -- a String));
777    builtin!(sigs, "son.dump-pretty", (a T -- a String));
778
779    // Stack introspection (for REPL)
780    // stack.dump prints all values and clears the stack
781    sigs.insert(
782        "stack.dump".to_string(),
783        Effect::new(
784            StackType::RowVar("a".to_string()), // Consumes any stack
785            StackType::RowVar("b".to_string()), // Returns empty stack (different row var)
786        ),
787    );
788
789    sigs
790}
791
792/// Get documentation for a built-in word
793pub fn builtin_doc(name: &str) -> Option<&'static str> {
794    BUILTIN_DOCS.get(name).copied()
795}
796
797/// Get all built-in word documentation (cached with LazyLock for performance)
798pub fn builtin_docs() -> &'static HashMap<&'static str, &'static str> {
799    &BUILTIN_DOCS
800}
801
802/// Lazily initialized documentation for all built-in words
803static BUILTIN_DOCS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
804    let mut docs = HashMap::new();
805
806    // I/O Operations
807    docs.insert(
808        "io.write",
809        "Write a string to stdout without a trailing newline.",
810    );
811    docs.insert(
812        "io.write-line",
813        "Write a string to stdout followed by a newline.",
814    );
815    docs.insert(
816        "io.read-line",
817        "Read a line from stdin. Returns (line, success).",
818    );
819    docs.insert(
820        "io.read-line+",
821        "Read a line from stdin. Returns (line, status_code).",
822    );
823    docs.insert(
824        "io.read-n",
825        "Read N bytes from stdin. Returns (bytes, status_code).",
826    );
827
828    // Command-line Arguments
829    docs.insert("args.count", "Get the number of command-line arguments.");
830    docs.insert("args.at", "Get the command-line argument at index N.");
831
832    // File Operations
833    docs.insert(
834        "file.slurp",
835        "Read entire file contents. Returns (content, success).",
836    );
837    docs.insert("file.exists?", "Check if a file exists at the given path.");
838    docs.insert(
839        "file.for-each-line+",
840        "Execute a quotation for each line in a file.",
841    );
842
843    // Type Conversions
844    docs.insert(
845        "int->string",
846        "Convert an integer to its string representation.",
847    );
848    docs.insert(
849        "int->float",
850        "Convert an integer to a floating-point number.",
851    );
852    docs.insert("float->int", "Truncate a float to an integer.");
853    docs.insert(
854        "float->string",
855        "Convert a float to its string representation.",
856    );
857    docs.insert(
858        "string->int",
859        "Parse a string as an integer. Returns (value, success).",
860    );
861    docs.insert(
862        "string->float",
863        "Parse a string as a float. Returns (value, success).",
864    );
865    docs.insert(
866        "char->string",
867        "Convert a Unicode codepoint to a single-character string.",
868    );
869    docs.insert(
870        "symbol->string",
871        "Convert a symbol to its string representation.",
872    );
873    docs.insert("string->symbol", "Intern a string as a symbol.");
874
875    // Integer Arithmetic
876    docs.insert("i.add", "Add two integers.");
877    docs.insert("i.subtract", "Subtract second integer from first.");
878    docs.insert("i.multiply", "Multiply two integers.");
879    docs.insert("i.divide", "Integer division (truncates toward zero).");
880    docs.insert("i.modulo", "Integer modulo (remainder after division).");
881    docs.insert("i.+", "Add two integers.");
882    docs.insert("i.-", "Subtract second integer from first.");
883    docs.insert("i.*", "Multiply two integers.");
884    docs.insert("i./", "Integer division (truncates toward zero).");
885    docs.insert("i.%", "Integer modulo (remainder after division).");
886
887    // Integer Comparison
888    docs.insert("i.=", "Test if two integers are equal.");
889    docs.insert("i.<", "Test if first integer is less than second.");
890    docs.insert("i.>", "Test if first integer is greater than second.");
891    docs.insert(
892        "i.<=",
893        "Test if first integer is less than or equal to second.",
894    );
895    docs.insert(
896        "i.>=",
897        "Test if first integer is greater than or equal to second.",
898    );
899    docs.insert("i.<>", "Test if two integers are not equal.");
900    docs.insert("i.eq", "Test if two integers are equal.");
901    docs.insert("i.lt", "Test if first integer is less than second.");
902    docs.insert("i.gt", "Test if first integer is greater than second.");
903    docs.insert(
904        "i.lte",
905        "Test if first integer is less than or equal to second.",
906    );
907    docs.insert(
908        "i.gte",
909        "Test if first integer is greater than or equal to second.",
910    );
911    docs.insert("i.neq", "Test if two integers are not equal.");
912
913    // Boolean Operations
914    docs.insert("and", "Logical AND of two booleans.");
915    docs.insert("or", "Logical OR of two booleans.");
916    docs.insert("not", "Logical NOT of a boolean.");
917
918    // Bitwise Operations
919    docs.insert("band", "Bitwise AND of two integers.");
920    docs.insert("bor", "Bitwise OR of two integers.");
921    docs.insert("bxor", "Bitwise XOR of two integers.");
922    docs.insert("bnot", "Bitwise NOT (complement) of an integer.");
923    docs.insert("shl", "Shift left by N bits.");
924    docs.insert("shr", "Shift right by N bits (arithmetic).");
925    docs.insert("popcount", "Count the number of set bits.");
926    docs.insert("clz", "Count leading zeros.");
927    docs.insert("ctz", "Count trailing zeros.");
928    docs.insert("int-bits", "Push the bit width of integers (64).");
929
930    // Stack Operations
931    docs.insert("dup", "Duplicate the top stack value.");
932    docs.insert("drop", "Remove the top stack value.");
933    docs.insert("swap", "Swap the top two stack values.");
934    docs.insert("over", "Copy the second value to the top.");
935    docs.insert("rot", "Rotate the top three values (third to top).");
936    docs.insert("nip", "Remove the second value from the stack.");
937    docs.insert("tuck", "Copy the top value below the second.");
938    docs.insert("2dup", "Duplicate the top two values.");
939    docs.insert("3drop", "Remove the top three values.");
940    docs.insert("pick", "Copy the value at depth N to the top.");
941    docs.insert("roll", "Rotate N+1 items, bringing depth N to top.");
942
943    // Channel Operations
944    docs.insert(
945        "chan.make",
946        "Create a new channel for inter-strand communication.",
947    );
948    docs.insert(
949        "chan.send",
950        "Send a value on a channel. Returns success flag.",
951    );
952    docs.insert(
953        "chan.receive",
954        "Receive a value from a channel. Returns (value, success).",
955    );
956    docs.insert("chan.close", "Close a channel.");
957    docs.insert("chan.yield", "Yield control to the scheduler.");
958
959    // Control Flow
960    docs.insert("call", "Call a quotation or closure.");
961    docs.insert(
962        "cond",
963        "Multi-way conditional: test clauses until one succeeds.",
964    );
965    docs.insert("times", "Execute a quotation N times.");
966    docs.insert("while", "Loop while condition is true: [cond] [body] while");
967    docs.insert("until", "Loop until condition is true: [body] [cond] until");
968
969    // Concurrency
970    docs.insert(
971        "strand.spawn",
972        "Spawn a concurrent strand. Returns strand ID.",
973    );
974    docs.insert(
975        "strand.weave",
976        "Create a generator/coroutine. Returns handle.",
977    );
978    docs.insert(
979        "strand.resume",
980        "Resume a weave with a value. Returns (handle, value, has_more).",
981    );
982    docs.insert(
983        "yield",
984        "Yield a value from a weave and receive resume value.",
985    );
986    docs.insert(
987        "strand.weave-cancel",
988        "Cancel a weave and release its resources.",
989    );
990
991    // TCP Operations
992    docs.insert(
993        "tcp.listen",
994        "Start listening on a port. Returns socket ID.",
995    );
996    docs.insert(
997        "tcp.accept",
998        "Accept a connection. Returns client socket ID.",
999    );
1000    docs.insert("tcp.read", "Read data from a socket. Returns string.");
1001    docs.insert("tcp.write", "Write data to a socket.");
1002    docs.insert("tcp.close", "Close a socket.");
1003
1004    // OS Operations
1005    docs.insert(
1006        "os.getenv",
1007        "Get environment variable. Returns (value, exists).",
1008    );
1009    docs.insert(
1010        "os.home-dir",
1011        "Get user's home directory. Returns (path, success).",
1012    );
1013    docs.insert(
1014        "os.current-dir",
1015        "Get current working directory. Returns (path, success).",
1016    );
1017    docs.insert("os.path-exists", "Check if a path exists.");
1018    docs.insert("os.path-is-file", "Check if path is a regular file.");
1019    docs.insert("os.path-is-dir", "Check if path is a directory.");
1020    docs.insert("os.path-join", "Join two path components.");
1021    docs.insert(
1022        "os.path-parent",
1023        "Get parent directory. Returns (path, success).",
1024    );
1025    docs.insert(
1026        "os.path-filename",
1027        "Get filename component. Returns (name, success).",
1028    );
1029    docs.insert("os.exit", "Exit the program with a status code.");
1030    docs.insert(
1031        "os.name",
1032        "Get the operating system name (e.g., \"macos\", \"linux\").",
1033    );
1034    docs.insert(
1035        "os.arch",
1036        "Get the CPU architecture (e.g., \"aarch64\", \"x86_64\").",
1037    );
1038
1039    // String Operations
1040    docs.insert("string.concat", "Concatenate two strings.");
1041    docs.insert("string.length", "Get the character length of a string.");
1042    docs.insert("string.byte-length", "Get the byte length of a string.");
1043    docs.insert(
1044        "string.char-at",
1045        "Get Unicode codepoint at character index.",
1046    );
1047    docs.insert(
1048        "string.substring",
1049        "Extract substring from start index with length.",
1050    );
1051    docs.insert(
1052        "string.find",
1053        "Find substring. Returns index or -1 if not found.",
1054    );
1055    docs.insert("string.split", "Split string by delimiter. Returns a list.");
1056    docs.insert("string.contains", "Check if string contains a substring.");
1057    docs.insert(
1058        "string.starts-with",
1059        "Check if string starts with a prefix.",
1060    );
1061    docs.insert("string.empty?", "Check if string is empty.");
1062    docs.insert("string.equal?", "Check if two strings are equal.");
1063    docs.insert("string.trim", "Remove leading and trailing whitespace.");
1064    docs.insert("string.chomp", "Remove trailing newline.");
1065    docs.insert("string.to-upper", "Convert to uppercase.");
1066    docs.insert("string.to-lower", "Convert to lowercase.");
1067    docs.insert("string.json-escape", "Escape special characters for JSON.");
1068    docs.insert("symbol.=", "Check if two symbols are equal.");
1069
1070    // Encoding Operations
1071    docs.insert(
1072        "encoding.base64-encode",
1073        "Encode a string to Base64 (standard alphabet with padding).",
1074    );
1075    docs.insert(
1076        "encoding.base64-decode",
1077        "Decode a Base64 string. Returns (decoded, success).",
1078    );
1079    docs.insert(
1080        "encoding.base64url-encode",
1081        "Encode to URL-safe Base64 (no padding). Suitable for JWTs and URLs.",
1082    );
1083    docs.insert(
1084        "encoding.base64url-decode",
1085        "Decode URL-safe Base64. Returns (decoded, success).",
1086    );
1087    docs.insert(
1088        "encoding.hex-encode",
1089        "Encode a string to lowercase hexadecimal.",
1090    );
1091    docs.insert(
1092        "encoding.hex-decode",
1093        "Decode a hexadecimal string. Returns (decoded, success).",
1094    );
1095
1096    // Crypto Operations
1097    docs.insert(
1098        "crypto.sha256",
1099        "Compute SHA-256 hash of a string. Returns 64-char hex digest.",
1100    );
1101    docs.insert(
1102        "crypto.hmac-sha256",
1103        "Compute HMAC-SHA256 signature. ( message key -- signature )",
1104    );
1105    docs.insert(
1106        "crypto.constant-time-eq",
1107        "Timing-safe string comparison. Use for comparing signatures/tokens.",
1108    );
1109    docs.insert(
1110        "crypto.random-bytes",
1111        "Generate N cryptographically secure random bytes as hex string.",
1112    );
1113    docs.insert("crypto.uuid4", "Generate a random UUID v4 string.");
1114
1115    // HTTP Client Operations
1116    docs.insert(
1117        "http.get",
1118        "HTTP GET request. ( url -- response-map ) Map has status, body, ok, error.",
1119    );
1120    docs.insert(
1121        "http.post",
1122        "HTTP POST request. ( url body content-type -- response-map )",
1123    );
1124    docs.insert(
1125        "http.put",
1126        "HTTP PUT request. ( url body content-type -- response-map )",
1127    );
1128    docs.insert(
1129        "http.delete",
1130        "HTTP DELETE request. ( url -- response-map )",
1131    );
1132
1133    // Variant Operations
1134    docs.insert(
1135        "variant.field-count",
1136        "Get the number of fields in a variant.",
1137    );
1138    docs.insert(
1139        "variant.tag",
1140        "Get the tag (constructor name) of a variant.",
1141    );
1142    docs.insert("variant.field-at", "Get the field at index N.");
1143    docs.insert(
1144        "variant.append",
1145        "Append a value to a variant (creates new).",
1146    );
1147    docs.insert("variant.last", "Get the last field of a variant.");
1148    docs.insert("variant.init", "Get all fields except the last.");
1149    docs.insert("variant.make-0", "Create a variant with 0 fields.");
1150    docs.insert("variant.make-1", "Create a variant with 1 field.");
1151    docs.insert("variant.make-2", "Create a variant with 2 fields.");
1152    docs.insert("variant.make-3", "Create a variant with 3 fields.");
1153    docs.insert("variant.make-4", "Create a variant with 4 fields.");
1154    docs.insert("wrap-0", "Create a variant with 0 fields (alias).");
1155    docs.insert("wrap-1", "Create a variant with 1 field (alias).");
1156    docs.insert("wrap-2", "Create a variant with 2 fields (alias).");
1157    docs.insert("wrap-3", "Create a variant with 3 fields (alias).");
1158    docs.insert("wrap-4", "Create a variant with 4 fields (alias).");
1159
1160    // List Operations
1161    docs.insert("list.make", "Create an empty list.");
1162    docs.insert("list.push", "Push a value onto a list. Returns new list.");
1163    docs.insert("list.get", "Get value at index. Returns (value, success).");
1164    docs.insert("list.set", "Set value at index. Returns (list, success).");
1165    docs.insert("list.length", "Get the number of elements in a list.");
1166    docs.insert("list.empty?", "Check if a list is empty.");
1167    docs.insert(
1168        "list.map",
1169        "Apply quotation to each element. Returns new list.",
1170    );
1171    docs.insert("list.filter", "Keep elements where quotation returns true.");
1172    docs.insert("list.fold", "Reduce list with accumulator and quotation.");
1173    docs.insert(
1174        "list.each",
1175        "Execute quotation for each element (side effects).",
1176    );
1177
1178    // Map Operations
1179    docs.insert("map.make", "Create an empty map.");
1180    docs.insert("map.get", "Get value for key. Returns (value, success).");
1181    docs.insert("map.set", "Set key to value. Returns new map.");
1182    docs.insert("map.has?", "Check if map contains a key.");
1183    docs.insert("map.remove", "Remove a key. Returns new map.");
1184    docs.insert("map.keys", "Get all keys as a list.");
1185    docs.insert("map.values", "Get all values as a list.");
1186    docs.insert("map.size", "Get the number of key-value pairs.");
1187    docs.insert("map.empty?", "Check if map is empty.");
1188
1189    // Float Arithmetic
1190    docs.insert("f.add", "Add two floats.");
1191    docs.insert("f.subtract", "Subtract second float from first.");
1192    docs.insert("f.multiply", "Multiply two floats.");
1193    docs.insert("f.divide", "Divide first float by second.");
1194    docs.insert("f.+", "Add two floats.");
1195    docs.insert("f.-", "Subtract second float from first.");
1196    docs.insert("f.*", "Multiply two floats.");
1197    docs.insert("f./", "Divide first float by second.");
1198
1199    // Float Comparison
1200    docs.insert("f.=", "Test if two floats are equal.");
1201    docs.insert("f.<", "Test if first float is less than second.");
1202    docs.insert("f.>", "Test if first float is greater than second.");
1203    docs.insert("f.<=", "Test if first float is less than or equal.");
1204    docs.insert("f.>=", "Test if first float is greater than or equal.");
1205    docs.insert("f.<>", "Test if two floats are not equal.");
1206    docs.insert("f.eq", "Test if two floats are equal.");
1207    docs.insert("f.lt", "Test if first float is less than second.");
1208    docs.insert("f.gt", "Test if first float is greater than second.");
1209    docs.insert("f.lte", "Test if first float is less than or equal.");
1210    docs.insert("f.gte", "Test if first float is greater than or equal.");
1211    docs.insert("f.neq", "Test if two floats are not equal.");
1212
1213    // Test Framework
1214    docs.insert(
1215        "test.init",
1216        "Initialize the test framework with a test name.",
1217    );
1218    docs.insert("test.finish", "Finish testing and print results.");
1219    docs.insert("test.has-failures", "Check if any tests have failed.");
1220    docs.insert("test.assert", "Assert that a boolean is true.");
1221    docs.insert("test.assert-not", "Assert that a boolean is false.");
1222    docs.insert("test.assert-eq", "Assert that two integers are equal.");
1223    docs.insert("test.assert-eq-str", "Assert that two strings are equal.");
1224    docs.insert("test.fail", "Mark a test as failed with a message.");
1225    docs.insert("test.pass-count", "Get the number of passed assertions.");
1226    docs.insert("test.fail-count", "Get the number of failed assertions.");
1227
1228    // Time Operations
1229    docs.insert("time.now", "Get current Unix timestamp in seconds.");
1230    docs.insert(
1231        "time.nanos",
1232        "Get high-resolution monotonic time in nanoseconds.",
1233    );
1234    docs.insert("time.sleep-ms", "Sleep for N milliseconds.");
1235
1236    // Serialization
1237    docs.insert("son.dump", "Serialize any value to SON format (compact).");
1238    docs.insert(
1239        "son.dump-pretty",
1240        "Serialize any value to SON format (pretty-printed).",
1241    );
1242
1243    // Stack Introspection
1244    docs.insert(
1245        "stack.dump",
1246        "Print all stack values and clear the stack (REPL).",
1247    );
1248
1249    docs
1250});
1251
1252#[cfg(test)]
1253mod tests {
1254    use super::*;
1255
1256    #[test]
1257    fn test_builtin_signature_write_line() {
1258        let sig = builtin_signature("io.write-line").unwrap();
1259        // ( ..a String -- ..a )
1260        let (rest, top) = sig.inputs.clone().pop().unwrap();
1261        assert_eq!(top, Type::String);
1262        assert_eq!(rest, StackType::RowVar("a".to_string()));
1263        assert_eq!(sig.outputs, StackType::RowVar("a".to_string()));
1264    }
1265
1266    #[test]
1267    fn test_builtin_signature_i_add() {
1268        let sig = builtin_signature("i.add").unwrap();
1269        // ( ..a Int Int -- ..a Int )
1270        let (rest, top) = sig.inputs.clone().pop().unwrap();
1271        assert_eq!(top, Type::Int);
1272        let (rest2, top2) = rest.pop().unwrap();
1273        assert_eq!(top2, Type::Int);
1274        assert_eq!(rest2, StackType::RowVar("a".to_string()));
1275
1276        let (rest3, top3) = sig.outputs.clone().pop().unwrap();
1277        assert_eq!(top3, Type::Int);
1278        assert_eq!(rest3, StackType::RowVar("a".to_string()));
1279    }
1280
1281    #[test]
1282    fn test_builtin_signature_dup() {
1283        let sig = builtin_signature("dup").unwrap();
1284        // Input: ( ..a T )
1285        assert_eq!(
1286            sig.inputs,
1287            StackType::Cons {
1288                rest: Box::new(StackType::RowVar("a".to_string())),
1289                top: Type::Var("T".to_string())
1290            }
1291        );
1292        // Output: ( ..a T T )
1293        let (rest, top) = sig.outputs.clone().pop().unwrap();
1294        assert_eq!(top, Type::Var("T".to_string()));
1295        let (rest2, top2) = rest.pop().unwrap();
1296        assert_eq!(top2, Type::Var("T".to_string()));
1297        assert_eq!(rest2, StackType::RowVar("a".to_string()));
1298    }
1299
1300    #[test]
1301    fn test_all_builtins_have_signatures() {
1302        let sigs = builtin_signatures();
1303
1304        // Verify all expected builtins have signatures
1305        assert!(sigs.contains_key("io.write-line"));
1306        assert!(sigs.contains_key("io.read-line"));
1307        assert!(sigs.contains_key("int->string"));
1308        assert!(sigs.contains_key("i.add"));
1309        assert!(sigs.contains_key("dup"));
1310        assert!(sigs.contains_key("swap"));
1311        assert!(sigs.contains_key("chan.make"));
1312        assert!(sigs.contains_key("chan.send"));
1313        assert!(sigs.contains_key("chan.receive"));
1314        assert!(
1315            sigs.contains_key("string->float"),
1316            "string->float should be a builtin"
1317        );
1318    }
1319
1320    #[test]
1321    fn test_all_docs_have_signatures() {
1322        let sigs = builtin_signatures();
1323        let docs = builtin_docs();
1324
1325        for name in docs.keys() {
1326            assert!(
1327                sigs.contains_key(*name),
1328                "Builtin '{}' has documentation but no signature",
1329                name
1330            );
1331        }
1332    }
1333
1334    #[test]
1335    fn test_all_signatures_have_docs() {
1336        let sigs = builtin_signatures();
1337        let docs = builtin_docs();
1338
1339        for name in sigs.keys() {
1340            assert!(
1341                docs.contains_key(name.as_str()),
1342                "Builtin '{}' has signature but no documentation",
1343                name
1344            );
1345        }
1346    }
1347}