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    // strand.spawn: ( a Quotation -- a Int ) - spawn a concurrent strand
422    // The quotation can have any stack effect - it runs independently
423    sigs.insert(
424        "strand.spawn".to_string(),
425        Effect::new(
426            StackType::RowVar("a".to_string()).push(Type::Quotation(Box::new(Effect::new(
427                StackType::RowVar("spawn_in".to_string()),
428                StackType::RowVar("spawn_out".to_string()),
429            )))),
430            StackType::RowVar("a".to_string()).push(Type::Int),
431        ),
432    );
433
434    // strand.weave: ( a Quotation -- a handle ) - create a woven strand (generator)
435    // The quotation receives (WeaveCtx, first_resume_value) and must thread WeaveCtx through.
436    // Returns a handle (WeaveCtx) for use with strand.resume.
437    sigs.insert(
438        "strand.weave".to_string(),
439        Effect::new(
440            StackType::RowVar("a".to_string()).push(Type::Quotation(Box::new(Effect::new(
441                StackType::RowVar("weave_in".to_string()),
442                StackType::RowVar("weave_out".to_string()),
443            )))),
444            StackType::RowVar("a".to_string()).push(Type::Var("handle".to_string())),
445        ),
446    );
447
448    // strand.resume: ( a handle b -- a handle b Bool ) - resume weave with value
449    // Takes handle and value to send, returns (handle, yielded_value, has_more)
450    sigs.insert(
451        "strand.resume".to_string(),
452        Effect::new(
453            StackType::RowVar("a".to_string())
454                .push(Type::Var("handle".to_string()))
455                .push(Type::Var("b".to_string())),
456            StackType::RowVar("a".to_string())
457                .push(Type::Var("handle".to_string()))
458                .push(Type::Var("b".to_string()))
459                .push(Type::Bool),
460        ),
461    );
462
463    // yield: ( a ctx b -- a ctx b | Yield b ) - yield value and receive resume value
464    // The WeaveCtx must be passed explicitly and threaded through.
465    // The Yield effect indicates this word produces yield semantics.
466    sigs.insert(
467        "yield".to_string(),
468        Effect::with_effects(
469            StackType::RowVar("a".to_string())
470                .push(Type::Var("ctx".to_string()))
471                .push(Type::Var("b".to_string())),
472            StackType::RowVar("a".to_string())
473                .push(Type::Var("ctx".to_string()))
474                .push(Type::Var("b".to_string())),
475            vec![SideEffect::Yield(Box::new(Type::Var("b".to_string())))],
476        ),
477    );
478
479    // strand.weave-cancel: ( a handle -- a ) - cancel a weave and release its resources
480    // Use this to clean up a weave that won't be resumed to completion.
481    // This prevents resource leaks from abandoned weaves.
482    sigs.insert(
483        "strand.weave-cancel".to_string(),
484        Effect::new(
485            StackType::RowVar("a".to_string()).push(Type::Var("handle".to_string())),
486            StackType::RowVar("a".to_string()),
487        ),
488    );
489
490    // =========================================================================
491    // TCP Operations
492    // =========================================================================
493
494    builtin!(sigs, "tcp.listen", (a Int -- a Int));
495    builtin!(sigs, "tcp.accept", (a Int -- a Int));
496    builtin!(sigs, "tcp.read", (a Int -- a String));
497    builtin!(sigs, "tcp.write", (a String Int -- a));
498    builtin!(sigs, "tcp.close", (a Int -- a));
499
500    // =========================================================================
501    // OS Operations
502    // =========================================================================
503
504    builtin!(sigs, "os.getenv", (a String -- a String Bool));
505    builtin!(sigs, "os.home-dir", (a -- a String Bool));
506    builtin!(sigs, "os.current-dir", (a -- a String Bool));
507    builtin!(sigs, "os.path-exists", (a String -- a Bool));
508    builtin!(sigs, "os.path-is-file", (a String -- a Bool));
509    builtin!(sigs, "os.path-is-dir", (a String -- a Bool));
510    builtin!(sigs, "os.path-join", (a String String -- a String));
511    builtin!(sigs, "os.path-parent", (a String -- a String Bool));
512    builtin!(sigs, "os.path-filename", (a String -- a String Bool));
513    builtin!(sigs, "os.exit", (a Int -- a)); // Never returns, but typed as identity
514    builtin!(sigs, "os.name", (a -- a String));
515    builtin!(sigs, "os.arch", (a -- a String));
516
517    // =========================================================================
518    // Terminal Operations (raw mode, character I/O, dimensions)
519    // =========================================================================
520
521    builtin!(sigs, "terminal.raw-mode", (a Bool -- a));
522    builtin!(sigs, "terminal.read-char", (a -- a Int));
523    builtin!(sigs, "terminal.read-char?", (a -- a Int));
524    builtin!(sigs, "terminal.width", (a -- a Int));
525    builtin!(sigs, "terminal.height", (a -- a Int));
526    builtin!(sigs, "terminal.flush", (a - -a));
527
528    // =========================================================================
529    // String Operations
530    // =========================================================================
531
532    builtin!(sigs, "string.concat", (a String String -- a String));
533    builtin!(sigs, "string.length", (a String -- a Int));
534    builtin!(sigs, "string.byte-length", (a String -- a Int));
535    builtin!(sigs, "string.char-at", (a String Int -- a Int));
536    builtin!(sigs, "string.substring", (a String Int Int -- a String));
537    builtin!(sigs, "string.find", (a String String -- a Int));
538    builtin!(sigs, "string.split", (a String String -- a V)); // Returns Variant (list)
539    builtin!(sigs, "string.contains", (a String String -- a Bool));
540    builtin!(sigs, "string.starts-with", (a String String -- a Bool));
541    builtin!(sigs, "string.empty?", (a String -- a Bool));
542    builtin!(sigs, "string.equal?", (a String String -- a Bool));
543
544    // Symbol operations
545    builtin!(sigs, "symbol.=", (a Symbol Symbol -- a Bool));
546
547    // String transformations
548    builtins_string_to_string!(
549        sigs,
550        "string.trim",
551        "string.chomp",
552        "string.to-upper",
553        "string.to-lower",
554        "string.json-escape"
555    );
556
557    // =========================================================================
558    // Encoding Operations
559    // =========================================================================
560
561    builtin!(sigs, "encoding.base64-encode", (a String -- a String));
562    builtin!(sigs, "encoding.base64-decode", (a String -- a String Bool));
563    builtin!(sigs, "encoding.base64url-encode", (a String -- a String));
564    builtin!(sigs, "encoding.base64url-decode", (a String -- a String Bool));
565    builtin!(sigs, "encoding.hex-encode", (a String -- a String));
566    builtin!(sigs, "encoding.hex-decode", (a String -- a String Bool));
567
568    // =========================================================================
569    // Crypto Operations
570    // =========================================================================
571
572    builtin!(sigs, "crypto.sha256", (a String -- a String));
573    builtin!(sigs, "crypto.hmac-sha256", (a String String -- a String));
574    builtin!(sigs, "crypto.constant-time-eq", (a String String -- a Bool));
575    builtin!(sigs, "crypto.random-bytes", (a Int -- a String));
576    builtin!(sigs, "crypto.random-int", (a Int Int -- a Int));
577    builtin!(sigs, "crypto.uuid4", (a -- a String));
578    builtin!(sigs, "crypto.aes-gcm-encrypt", (a String String -- a String Bool));
579    builtin!(sigs, "crypto.aes-gcm-decrypt", (a String String -- a String Bool));
580    builtin!(sigs, "crypto.pbkdf2-sha256", (a String String Int -- a String Bool));
581    builtin!(sigs, "crypto.ed25519-keypair", (a -- a String String));
582    builtin!(sigs, "crypto.ed25519-sign", (a String String -- a String Bool));
583    builtin!(sigs, "crypto.ed25519-verify", (a String String String -- a Bool));
584
585    // =========================================================================
586    // HTTP Client Operations
587    // =========================================================================
588
589    builtin!(sigs, "http.get", (a String -- a M));
590    builtin!(sigs, "http.post", (a String String String -- a M));
591    builtin!(sigs, "http.put", (a String String String -- a M));
592    builtin!(sigs, "http.delete", (a String -- a M));
593
594    // =========================================================================
595    // Regular Expression Operations
596    // =========================================================================
597
598    builtin!(sigs, "regex.match?", (a String String -- a Bool));
599    builtin!(sigs, "regex.find", (a String String -- a String Bool));
600    builtin!(sigs, "regex.find-all", (a String String -- a V));
601    builtin!(sigs, "regex.replace", (a String String String -- a String));
602    builtin!(sigs, "regex.replace-all", (a String String String -- a String));
603    builtin!(sigs, "regex.captures", (a String String -- a V Bool));
604    builtin!(sigs, "regex.split", (a String String -- a V));
605    builtin!(sigs, "regex.valid?", (a String -- a Bool));
606
607    // =========================================================================
608    // Compression Operations
609    // =========================================================================
610
611    builtin!(sigs, "compress.gzip", (a String -- a String Bool));
612    builtin!(sigs, "compress.gzip-level", (a String Int -- a String Bool));
613    builtin!(sigs, "compress.gunzip", (a String -- a String Bool));
614    builtin!(sigs, "compress.zstd", (a String -- a String Bool));
615    builtin!(sigs, "compress.zstd-level", (a String Int -- a String Bool));
616    builtin!(sigs, "compress.unzstd", (a String -- a String Bool));
617
618    // =========================================================================
619    // Variant Operations
620    // =========================================================================
621
622    builtin!(sigs, "variant.field-count", (a V -- a Int));
623    builtin!(sigs, "variant.tag", (a V -- a Symbol));
624    builtin!(sigs, "variant.field-at", (a V Int -- a T));
625    builtin!(sigs, "variant.append", (a V T -- a V2));
626    builtin!(sigs, "variant.last", (a V -- a T));
627    builtin!(sigs, "variant.init", (a V -- a V2));
628
629    // Type-safe variant constructors with fixed arity (symbol tags for SON support)
630    builtin!(sigs, "variant.make-0", (a Symbol -- a V));
631    builtin!(sigs, "variant.make-1", (a T1 Symbol -- a V));
632    builtin!(sigs, "variant.make-2", (a T1 T2 Symbol -- a V));
633    builtin!(sigs, "variant.make-3", (a T1 T2 T3 Symbol -- a V));
634    builtin!(sigs, "variant.make-4", (a T1 T2 T3 T4 Symbol -- a V));
635
636    // Aliases for dynamic variant construction (SON-friendly names)
637    builtin!(sigs, "wrap-0", (a Symbol -- a V));
638    builtin!(sigs, "wrap-1", (a T1 Symbol -- a V));
639    builtin!(sigs, "wrap-2", (a T1 T2 Symbol -- a V));
640    builtin!(sigs, "wrap-3", (a T1 T2 T3 Symbol -- a V));
641    builtin!(sigs, "wrap-4", (a T1 T2 T3 T4 Symbol -- a V));
642
643    // =========================================================================
644    // List Operations (Higher-order combinators for Variants)
645    // =========================================================================
646
647    // List construction and access
648    builtin!(sigs, "list.make", (a -- a V));
649    builtin!(sigs, "list.push", (a V T -- a V));
650    builtin!(sigs, "list.get", (a V Int -- a T Bool));
651    builtin!(sigs, "list.set", (a V Int T -- a V Bool));
652
653    builtin!(sigs, "list.length", (a V -- a Int));
654    builtin!(sigs, "list.empty?", (a V -- a Bool));
655
656    // list.map: ( a Variant Quotation -- a Variant )
657    // Quotation: ( b T -- b U )
658    sigs.insert(
659        "list.map".to_string(),
660        Effect::new(
661            StackType::RowVar("a".to_string())
662                .push(Type::Var("V".to_string()))
663                .push(Type::Quotation(Box::new(Effect::new(
664                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
665                    StackType::RowVar("b".to_string()).push(Type::Var("U".to_string())),
666                )))),
667            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
668        ),
669    );
670
671    // list.filter: ( a Variant Quotation -- a Variant )
672    // Quotation: ( b T -- b Bool )
673    sigs.insert(
674        "list.filter".to_string(),
675        Effect::new(
676            StackType::RowVar("a".to_string())
677                .push(Type::Var("V".to_string()))
678                .push(Type::Quotation(Box::new(Effect::new(
679                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
680                    StackType::RowVar("b".to_string()).push(Type::Bool),
681                )))),
682            StackType::RowVar("a".to_string()).push(Type::Var("V2".to_string())),
683        ),
684    );
685
686    // list.fold: ( a Variant init Quotation -- a result )
687    // Quotation: ( b Acc T -- b Acc )
688    sigs.insert(
689        "list.fold".to_string(),
690        Effect::new(
691            StackType::RowVar("a".to_string())
692                .push(Type::Var("V".to_string()))
693                .push(Type::Var("Acc".to_string()))
694                .push(Type::Quotation(Box::new(Effect::new(
695                    StackType::RowVar("b".to_string())
696                        .push(Type::Var("Acc".to_string()))
697                        .push(Type::Var("T".to_string())),
698                    StackType::RowVar("b".to_string()).push(Type::Var("Acc".to_string())),
699                )))),
700            StackType::RowVar("a".to_string()).push(Type::Var("Acc".to_string())),
701        ),
702    );
703
704    // list.each: ( a Variant Quotation -- a )
705    // Quotation: ( b T -- b )
706    sigs.insert(
707        "list.each".to_string(),
708        Effect::new(
709            StackType::RowVar("a".to_string())
710                .push(Type::Var("V".to_string()))
711                .push(Type::Quotation(Box::new(Effect::new(
712                    StackType::RowVar("b".to_string()).push(Type::Var("T".to_string())),
713                    StackType::RowVar("b".to_string()),
714                )))),
715            StackType::RowVar("a".to_string()),
716        ),
717    );
718
719    // =========================================================================
720    // Map Operations (Dictionary with O(1) lookup)
721    // =========================================================================
722
723    builtin!(sigs, "map.make", (a -- a M));
724    builtin!(sigs, "map.get", (a M K -- a V Bool)); // returns (value success) - errors are values, not crashes
725    builtin!(sigs, "map.set", (a M K V -- a M2));
726    builtin!(sigs, "map.has?", (a M K -- a Bool));
727    builtin!(sigs, "map.remove", (a M K -- a M2));
728    builtin!(sigs, "map.keys", (a M -- a V));
729    builtin!(sigs, "map.values", (a M -- a V));
730    builtin!(sigs, "map.size", (a M -- a Int));
731    builtin!(sigs, "map.empty?", (a M -- a Bool));
732
733    // =========================================================================
734    // Float Arithmetic ( a Float Float -- a Float )
735    // =========================================================================
736
737    builtins_float_float_to_float!(sigs, "f.add", "f.subtract", "f.multiply", "f.divide");
738    builtins_float_float_to_float!(sigs, "f.+", "f.-", "f.*", "f./");
739
740    // =========================================================================
741    // Float Comparison ( a Float Float -- a Bool )
742    // =========================================================================
743
744    builtins_float_float_to_bool!(sigs, "f.=", "f.<", "f.>", "f.<=", "f.>=", "f.<>");
745    builtins_float_float_to_bool!(sigs, "f.eq", "f.lt", "f.gt", "f.lte", "f.gte", "f.neq");
746
747    // =========================================================================
748    // Test Framework
749    // =========================================================================
750
751    builtin!(sigs, "test.init", (a String -- a));
752    builtin!(sigs, "test.finish", (a - -a));
753    builtin!(sigs, "test.has-failures", (a -- a Bool));
754    builtin!(sigs, "test.assert", (a Bool -- a));
755    builtin!(sigs, "test.assert-not", (a Bool -- a));
756    builtin!(sigs, "test.assert-eq", (a Int Int -- a));
757    builtin!(sigs, "test.assert-eq-str", (a String String -- a));
758    builtin!(sigs, "test.fail", (a String -- a));
759    builtin!(sigs, "test.pass-count", (a -- a Int));
760    builtin!(sigs, "test.fail-count", (a -- a Int));
761
762    // Time operations
763    builtin!(sigs, "time.now", (a -- a Int));
764    builtin!(sigs, "time.nanos", (a -- a Int));
765    builtin!(sigs, "time.sleep-ms", (a Int -- a));
766
767    // SON serialization
768    builtin!(sigs, "son.dump", (a T -- a String));
769    builtin!(sigs, "son.dump-pretty", (a T -- a String));
770
771    // Stack introspection (for REPL)
772    // stack.dump prints all values and clears the stack
773    sigs.insert(
774        "stack.dump".to_string(),
775        Effect::new(
776            StackType::RowVar("a".to_string()), // Consumes any stack
777            StackType::RowVar("b".to_string()), // Returns empty stack (different row var)
778        ),
779    );
780
781    sigs
782}
783
784/// Get documentation for a built-in word
785pub fn builtin_doc(name: &str) -> Option<&'static str> {
786    BUILTIN_DOCS.get(name).copied()
787}
788
789/// Get all built-in word documentation (cached with LazyLock for performance)
790pub fn builtin_docs() -> &'static HashMap<&'static str, &'static str> {
791    &BUILTIN_DOCS
792}
793
794/// Lazily initialized documentation for all built-in words
795static BUILTIN_DOCS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
796    let mut docs = HashMap::new();
797
798    // I/O Operations
799    docs.insert(
800        "io.write",
801        "Write a string to stdout without a trailing newline.",
802    );
803    docs.insert(
804        "io.write-line",
805        "Write a string to stdout followed by a newline.",
806    );
807    docs.insert(
808        "io.read-line",
809        "Read a line from stdin. Returns (line, success).",
810    );
811    docs.insert(
812        "io.read-line+",
813        "Read a line from stdin. Returns (line, status_code).",
814    );
815    docs.insert(
816        "io.read-n",
817        "Read N bytes from stdin. Returns (bytes, status_code).",
818    );
819
820    // Command-line Arguments
821    docs.insert("args.count", "Get the number of command-line arguments.");
822    docs.insert("args.at", "Get the command-line argument at index N.");
823
824    // File Operations
825    docs.insert(
826        "file.slurp",
827        "Read entire file contents. Returns (content, success).",
828    );
829    docs.insert("file.exists?", "Check if a file exists at the given path.");
830    docs.insert(
831        "file.for-each-line+",
832        "Execute a quotation for each line in a file.",
833    );
834
835    // Type Conversions
836    docs.insert(
837        "int->string",
838        "Convert an integer to its string representation.",
839    );
840    docs.insert(
841        "int->float",
842        "Convert an integer to a floating-point number.",
843    );
844    docs.insert("float->int", "Truncate a float to an integer.");
845    docs.insert(
846        "float->string",
847        "Convert a float to its string representation.",
848    );
849    docs.insert(
850        "string->int",
851        "Parse a string as an integer. Returns (value, success).",
852    );
853    docs.insert(
854        "string->float",
855        "Parse a string as a float. Returns (value, success).",
856    );
857    docs.insert(
858        "char->string",
859        "Convert a Unicode codepoint to a single-character string.",
860    );
861    docs.insert(
862        "symbol->string",
863        "Convert a symbol to its string representation.",
864    );
865    docs.insert("string->symbol", "Intern a string as a symbol.");
866
867    // Integer Arithmetic
868    docs.insert("i.add", "Add two integers.");
869    docs.insert("i.subtract", "Subtract second integer from first.");
870    docs.insert("i.multiply", "Multiply two integers.");
871    docs.insert("i.divide", "Integer division (truncates toward zero).");
872    docs.insert("i.modulo", "Integer modulo (remainder after division).");
873    docs.insert("i.+", "Add two integers.");
874    docs.insert("i.-", "Subtract second integer from first.");
875    docs.insert("i.*", "Multiply two integers.");
876    docs.insert("i./", "Integer division (truncates toward zero).");
877    docs.insert("i.%", "Integer modulo (remainder after division).");
878
879    // Integer Comparison
880    docs.insert("i.=", "Test if two integers are equal.");
881    docs.insert("i.<", "Test if first integer is less than second.");
882    docs.insert("i.>", "Test if first integer is greater than second.");
883    docs.insert(
884        "i.<=",
885        "Test if first integer is less than or equal to second.",
886    );
887    docs.insert(
888        "i.>=",
889        "Test if first integer is greater than or equal to second.",
890    );
891    docs.insert("i.<>", "Test if two integers are not equal.");
892    docs.insert("i.eq", "Test if two integers are equal.");
893    docs.insert("i.lt", "Test if first integer is less than second.");
894    docs.insert("i.gt", "Test if first integer is greater than second.");
895    docs.insert(
896        "i.lte",
897        "Test if first integer is less than or equal to second.",
898    );
899    docs.insert(
900        "i.gte",
901        "Test if first integer is greater than or equal to second.",
902    );
903    docs.insert("i.neq", "Test if two integers are not equal.");
904
905    // Boolean Operations
906    docs.insert("and", "Logical AND of two booleans.");
907    docs.insert("or", "Logical OR of two booleans.");
908    docs.insert("not", "Logical NOT of a boolean.");
909
910    // Bitwise Operations
911    docs.insert("band", "Bitwise AND of two integers.");
912    docs.insert("bor", "Bitwise OR of two integers.");
913    docs.insert("bxor", "Bitwise XOR of two integers.");
914    docs.insert("bnot", "Bitwise NOT (complement) of an integer.");
915    docs.insert("shl", "Shift left by N bits.");
916    docs.insert("shr", "Shift right by N bits (arithmetic).");
917    docs.insert("popcount", "Count the number of set bits.");
918    docs.insert("clz", "Count leading zeros.");
919    docs.insert("ctz", "Count trailing zeros.");
920    docs.insert("int-bits", "Push the bit width of integers (64).");
921
922    // Stack Operations
923    docs.insert("dup", "Duplicate the top stack value.");
924    docs.insert("drop", "Remove the top stack value.");
925    docs.insert("swap", "Swap the top two stack values.");
926    docs.insert("over", "Copy the second value to the top.");
927    docs.insert("rot", "Rotate the top three values (third to top).");
928    docs.insert("nip", "Remove the second value from the stack.");
929    docs.insert("tuck", "Copy the top value below the second.");
930    docs.insert("2dup", "Duplicate the top two values.");
931    docs.insert("3drop", "Remove the top three values.");
932    docs.insert("pick", "Copy the value at depth N to the top.");
933    docs.insert("roll", "Rotate N+1 items, bringing depth N to top.");
934
935    // Channel Operations
936    docs.insert(
937        "chan.make",
938        "Create a new channel for inter-strand communication.",
939    );
940    docs.insert(
941        "chan.send",
942        "Send a value on a channel. Returns success flag.",
943    );
944    docs.insert(
945        "chan.receive",
946        "Receive a value from a channel. Returns (value, success).",
947    );
948    docs.insert("chan.close", "Close a channel.");
949    docs.insert("chan.yield", "Yield control to the scheduler.");
950
951    // Control Flow
952    docs.insert("call", "Call a quotation or closure.");
953    docs.insert(
954        "cond",
955        "Multi-way conditional: test clauses until one succeeds.",
956    );
957
958    // Concurrency
959    docs.insert(
960        "strand.spawn",
961        "Spawn a concurrent strand. Returns strand ID.",
962    );
963    docs.insert(
964        "strand.weave",
965        "Create a generator/coroutine. Returns handle.",
966    );
967    docs.insert(
968        "strand.resume",
969        "Resume a weave with a value. Returns (handle, value, has_more).",
970    );
971    docs.insert(
972        "yield",
973        "Yield a value from a weave and receive resume value.",
974    );
975    docs.insert(
976        "strand.weave-cancel",
977        "Cancel a weave and release its resources.",
978    );
979
980    // TCP Operations
981    docs.insert(
982        "tcp.listen",
983        "Start listening on a port. Returns socket ID.",
984    );
985    docs.insert(
986        "tcp.accept",
987        "Accept a connection. Returns client socket ID.",
988    );
989    docs.insert("tcp.read", "Read data from a socket. Returns string.");
990    docs.insert("tcp.write", "Write data to a socket.");
991    docs.insert("tcp.close", "Close a socket.");
992
993    // OS Operations
994    docs.insert(
995        "os.getenv",
996        "Get environment variable. Returns (value, exists).",
997    );
998    docs.insert(
999        "os.home-dir",
1000        "Get user's home directory. Returns (path, success).",
1001    );
1002    docs.insert(
1003        "os.current-dir",
1004        "Get current working directory. Returns (path, success).",
1005    );
1006    docs.insert("os.path-exists", "Check if a path exists.");
1007    docs.insert("os.path-is-file", "Check if path is a regular file.");
1008    docs.insert("os.path-is-dir", "Check if path is a directory.");
1009    docs.insert("os.path-join", "Join two path components.");
1010    docs.insert(
1011        "os.path-parent",
1012        "Get parent directory. Returns (path, success).",
1013    );
1014    docs.insert(
1015        "os.path-filename",
1016        "Get filename component. Returns (name, success).",
1017    );
1018    docs.insert("os.exit", "Exit the program with a status code.");
1019    docs.insert(
1020        "os.name",
1021        "Get the operating system name (e.g., \"macos\", \"linux\").",
1022    );
1023    docs.insert(
1024        "os.arch",
1025        "Get the CPU architecture (e.g., \"aarch64\", \"x86_64\").",
1026    );
1027
1028    // Terminal Operations
1029    docs.insert(
1030        "terminal.raw-mode",
1031        "Enable/disable raw terminal mode. In raw mode: no line buffering, no echo, Ctrl+C read as byte 3.",
1032    );
1033    docs.insert(
1034        "terminal.read-char",
1035        "Read a single byte from stdin (blocking). Returns 0-255 on success, -1 on EOF/error.",
1036    );
1037    docs.insert(
1038        "terminal.read-char?",
1039        "Read a single byte from stdin (non-blocking). Returns 0-255 if available, -1 otherwise.",
1040    );
1041    docs.insert(
1042        "terminal.width",
1043        "Get terminal width in columns. Returns 80 if unknown.",
1044    );
1045    docs.insert(
1046        "terminal.height",
1047        "Get terminal height in rows. Returns 24 if unknown.",
1048    );
1049    docs.insert(
1050        "terminal.flush",
1051        "Flush stdout. Use after writing escape sequences or partial lines.",
1052    );
1053
1054    // String Operations
1055    docs.insert("string.concat", "Concatenate two strings.");
1056    docs.insert("string.length", "Get the character length of a string.");
1057    docs.insert("string.byte-length", "Get the byte length of a string.");
1058    docs.insert(
1059        "string.char-at",
1060        "Get Unicode codepoint at character index.",
1061    );
1062    docs.insert(
1063        "string.substring",
1064        "Extract substring from start index with length.",
1065    );
1066    docs.insert(
1067        "string.find",
1068        "Find substring. Returns index or -1 if not found.",
1069    );
1070    docs.insert("string.split", "Split string by delimiter. Returns a list.");
1071    docs.insert("string.contains", "Check if string contains a substring.");
1072    docs.insert(
1073        "string.starts-with",
1074        "Check if string starts with a prefix.",
1075    );
1076    docs.insert("string.empty?", "Check if string is empty.");
1077    docs.insert("string.equal?", "Check if two strings are equal.");
1078    docs.insert("string.trim", "Remove leading and trailing whitespace.");
1079    docs.insert("string.chomp", "Remove trailing newline.");
1080    docs.insert("string.to-upper", "Convert to uppercase.");
1081    docs.insert("string.to-lower", "Convert to lowercase.");
1082    docs.insert("string.json-escape", "Escape special characters for JSON.");
1083    docs.insert("symbol.=", "Check if two symbols are equal.");
1084
1085    // Encoding Operations
1086    docs.insert(
1087        "encoding.base64-encode",
1088        "Encode a string to Base64 (standard alphabet with padding).",
1089    );
1090    docs.insert(
1091        "encoding.base64-decode",
1092        "Decode a Base64 string. Returns (decoded, success).",
1093    );
1094    docs.insert(
1095        "encoding.base64url-encode",
1096        "Encode to URL-safe Base64 (no padding). Suitable for JWTs and URLs.",
1097    );
1098    docs.insert(
1099        "encoding.base64url-decode",
1100        "Decode URL-safe Base64. Returns (decoded, success).",
1101    );
1102    docs.insert(
1103        "encoding.hex-encode",
1104        "Encode a string to lowercase hexadecimal.",
1105    );
1106    docs.insert(
1107        "encoding.hex-decode",
1108        "Decode a hexadecimal string. Returns (decoded, success).",
1109    );
1110
1111    // Crypto Operations
1112    docs.insert(
1113        "crypto.sha256",
1114        "Compute SHA-256 hash of a string. Returns 64-char hex digest.",
1115    );
1116    docs.insert(
1117        "crypto.hmac-sha256",
1118        "Compute HMAC-SHA256 signature. ( message key -- signature )",
1119    );
1120    docs.insert(
1121        "crypto.constant-time-eq",
1122        "Timing-safe string comparison. Use for comparing signatures/tokens.",
1123    );
1124    docs.insert(
1125        "crypto.random-bytes",
1126        "Generate N cryptographically secure random bytes as hex string.",
1127    );
1128    docs.insert(
1129        "crypto.random-int",
1130        "Generate uniform random integer in [min, max). ( min max -- Int ) Uses rejection sampling to avoid modulo bias.",
1131    );
1132    docs.insert("crypto.uuid4", "Generate a random UUID v4 string.");
1133    docs.insert(
1134        "crypto.aes-gcm-encrypt",
1135        "Encrypt with AES-256-GCM. ( plaintext hex-key -- ciphertext success )",
1136    );
1137    docs.insert(
1138        "crypto.aes-gcm-decrypt",
1139        "Decrypt AES-256-GCM ciphertext. ( ciphertext hex-key -- plaintext success )",
1140    );
1141    docs.insert(
1142        "crypto.pbkdf2-sha256",
1143        "Derive key from password. ( password salt iterations -- hex-key success ) Min 1000 iterations, 100000+ recommended.",
1144    );
1145    docs.insert(
1146        "crypto.ed25519-keypair",
1147        "Generate Ed25519 keypair. ( -- public-key private-key ) Both as 64-char hex strings.",
1148    );
1149    docs.insert(
1150        "crypto.ed25519-sign",
1151        "Sign message with Ed25519 private key. ( message private-key -- signature success ) Signature is 128-char hex.",
1152    );
1153    docs.insert(
1154        "crypto.ed25519-verify",
1155        "Verify Ed25519 signature. ( message signature public-key -- valid )",
1156    );
1157
1158    // HTTP Client Operations
1159    docs.insert(
1160        "http.get",
1161        "HTTP GET request. ( url -- response-map ) Map has status, body, ok, error.",
1162    );
1163    docs.insert(
1164        "http.post",
1165        "HTTP POST request. ( url body content-type -- response-map )",
1166    );
1167    docs.insert(
1168        "http.put",
1169        "HTTP PUT request. ( url body content-type -- response-map )",
1170    );
1171    docs.insert(
1172        "http.delete",
1173        "HTTP DELETE request. ( url -- response-map )",
1174    );
1175
1176    // Regular Expression Operations
1177    docs.insert(
1178        "regex.match?",
1179        "Check if pattern matches anywhere in string. ( text pattern -- bool )",
1180    );
1181    docs.insert(
1182        "regex.find",
1183        "Find first match. ( text pattern -- matched success )",
1184    );
1185    docs.insert(
1186        "regex.find-all",
1187        "Find all matches. ( text pattern -- list )",
1188    );
1189    docs.insert(
1190        "regex.replace",
1191        "Replace first match. ( text pattern replacement -- result )",
1192    );
1193    docs.insert(
1194        "regex.replace-all",
1195        "Replace all matches. ( text pattern replacement -- result )",
1196    );
1197    docs.insert(
1198        "regex.captures",
1199        "Extract capture groups. ( text pattern -- groups success )",
1200    );
1201    docs.insert(
1202        "regex.split",
1203        "Split string by pattern. ( text pattern -- list )",
1204    );
1205    docs.insert(
1206        "regex.valid?",
1207        "Check if pattern is valid regex. ( pattern -- bool )",
1208    );
1209
1210    // Compression Operations
1211    docs.insert(
1212        "compress.gzip",
1213        "Compress string with gzip. Returns base64-encoded data. ( data -- compressed success )",
1214    );
1215    docs.insert(
1216        "compress.gzip-level",
1217        "Compress with gzip at level 1-9. ( data level -- compressed success )",
1218    );
1219    docs.insert(
1220        "compress.gunzip",
1221        "Decompress gzip data. ( base64-data -- decompressed success )",
1222    );
1223    docs.insert(
1224        "compress.zstd",
1225        "Compress string with zstd. Returns base64-encoded data. ( data -- compressed success )",
1226    );
1227    docs.insert(
1228        "compress.zstd-level",
1229        "Compress with zstd at level 1-22. ( data level -- compressed success )",
1230    );
1231    docs.insert(
1232        "compress.unzstd",
1233        "Decompress zstd data. ( base64-data -- decompressed success )",
1234    );
1235
1236    // Variant Operations
1237    docs.insert(
1238        "variant.field-count",
1239        "Get the number of fields in a variant.",
1240    );
1241    docs.insert(
1242        "variant.tag",
1243        "Get the tag (constructor name) of a variant.",
1244    );
1245    docs.insert("variant.field-at", "Get the field at index N.");
1246    docs.insert(
1247        "variant.append",
1248        "Append a value to a variant (creates new).",
1249    );
1250    docs.insert("variant.last", "Get the last field of a variant.");
1251    docs.insert("variant.init", "Get all fields except the last.");
1252    docs.insert("variant.make-0", "Create a variant with 0 fields.");
1253    docs.insert("variant.make-1", "Create a variant with 1 field.");
1254    docs.insert("variant.make-2", "Create a variant with 2 fields.");
1255    docs.insert("variant.make-3", "Create a variant with 3 fields.");
1256    docs.insert("variant.make-4", "Create a variant with 4 fields.");
1257    docs.insert("wrap-0", "Create a variant with 0 fields (alias).");
1258    docs.insert("wrap-1", "Create a variant with 1 field (alias).");
1259    docs.insert("wrap-2", "Create a variant with 2 fields (alias).");
1260    docs.insert("wrap-3", "Create a variant with 3 fields (alias).");
1261    docs.insert("wrap-4", "Create a variant with 4 fields (alias).");
1262
1263    // List Operations
1264    docs.insert("list.make", "Create an empty list.");
1265    docs.insert("list.push", "Push a value onto a list. Returns new list.");
1266    docs.insert("list.get", "Get value at index. Returns (value, success).");
1267    docs.insert("list.set", "Set value at index. Returns (list, success).");
1268    docs.insert("list.length", "Get the number of elements in a list.");
1269    docs.insert("list.empty?", "Check if a list is empty.");
1270    docs.insert(
1271        "list.map",
1272        "Apply quotation to each element. Returns new list.",
1273    );
1274    docs.insert("list.filter", "Keep elements where quotation returns true.");
1275    docs.insert("list.fold", "Reduce list with accumulator and quotation.");
1276    docs.insert(
1277        "list.each",
1278        "Execute quotation for each element (side effects).",
1279    );
1280
1281    // Map Operations
1282    docs.insert("map.make", "Create an empty map.");
1283    docs.insert("map.get", "Get value for key. Returns (value, success).");
1284    docs.insert("map.set", "Set key to value. Returns new map.");
1285    docs.insert("map.has?", "Check if map contains a key.");
1286    docs.insert("map.remove", "Remove a key. Returns new map.");
1287    docs.insert("map.keys", "Get all keys as a list.");
1288    docs.insert("map.values", "Get all values as a list.");
1289    docs.insert("map.size", "Get the number of key-value pairs.");
1290    docs.insert("map.empty?", "Check if map is empty.");
1291
1292    // Float Arithmetic
1293    docs.insert("f.add", "Add two floats.");
1294    docs.insert("f.subtract", "Subtract second float from first.");
1295    docs.insert("f.multiply", "Multiply two floats.");
1296    docs.insert("f.divide", "Divide first float by second.");
1297    docs.insert("f.+", "Add two floats.");
1298    docs.insert("f.-", "Subtract second float from first.");
1299    docs.insert("f.*", "Multiply two floats.");
1300    docs.insert("f./", "Divide first float by second.");
1301
1302    // Float Comparison
1303    docs.insert("f.=", "Test if two floats are equal.");
1304    docs.insert("f.<", "Test if first float is less than second.");
1305    docs.insert("f.>", "Test if first float is greater than second.");
1306    docs.insert("f.<=", "Test if first float is less than or equal.");
1307    docs.insert("f.>=", "Test if first float is greater than or equal.");
1308    docs.insert("f.<>", "Test if two floats are not equal.");
1309    docs.insert("f.eq", "Test if two floats are equal.");
1310    docs.insert("f.lt", "Test if first float is less than second.");
1311    docs.insert("f.gt", "Test if first float is greater than second.");
1312    docs.insert("f.lte", "Test if first float is less than or equal.");
1313    docs.insert("f.gte", "Test if first float is greater than or equal.");
1314    docs.insert("f.neq", "Test if two floats are not equal.");
1315
1316    // Test Framework
1317    docs.insert(
1318        "test.init",
1319        "Initialize the test framework with a test name.",
1320    );
1321    docs.insert("test.finish", "Finish testing and print results.");
1322    docs.insert("test.has-failures", "Check if any tests have failed.");
1323    docs.insert("test.assert", "Assert that a boolean is true.");
1324    docs.insert("test.assert-not", "Assert that a boolean is false.");
1325    docs.insert("test.assert-eq", "Assert that two integers are equal.");
1326    docs.insert("test.assert-eq-str", "Assert that two strings are equal.");
1327    docs.insert("test.fail", "Mark a test as failed with a message.");
1328    docs.insert("test.pass-count", "Get the number of passed assertions.");
1329    docs.insert("test.fail-count", "Get the number of failed assertions.");
1330
1331    // Time Operations
1332    docs.insert("time.now", "Get current Unix timestamp in seconds.");
1333    docs.insert(
1334        "time.nanos",
1335        "Get high-resolution monotonic time in nanoseconds.",
1336    );
1337    docs.insert("time.sleep-ms", "Sleep for N milliseconds.");
1338
1339    // Serialization
1340    docs.insert("son.dump", "Serialize any value to SON format (compact).");
1341    docs.insert(
1342        "son.dump-pretty",
1343        "Serialize any value to SON format (pretty-printed).",
1344    );
1345
1346    // Stack Introspection
1347    docs.insert(
1348        "stack.dump",
1349        "Print all stack values and clear the stack (REPL).",
1350    );
1351
1352    docs
1353});
1354
1355#[cfg(test)]
1356mod tests {
1357    use super::*;
1358
1359    #[test]
1360    fn test_builtin_signature_write_line() {
1361        let sig = builtin_signature("io.write-line").unwrap();
1362        // ( ..a String -- ..a )
1363        let (rest, top) = sig.inputs.clone().pop().unwrap();
1364        assert_eq!(top, Type::String);
1365        assert_eq!(rest, StackType::RowVar("a".to_string()));
1366        assert_eq!(sig.outputs, StackType::RowVar("a".to_string()));
1367    }
1368
1369    #[test]
1370    fn test_builtin_signature_i_add() {
1371        let sig = builtin_signature("i.add").unwrap();
1372        // ( ..a Int Int -- ..a Int )
1373        let (rest, top) = sig.inputs.clone().pop().unwrap();
1374        assert_eq!(top, Type::Int);
1375        let (rest2, top2) = rest.pop().unwrap();
1376        assert_eq!(top2, Type::Int);
1377        assert_eq!(rest2, StackType::RowVar("a".to_string()));
1378
1379        let (rest3, top3) = sig.outputs.clone().pop().unwrap();
1380        assert_eq!(top3, Type::Int);
1381        assert_eq!(rest3, StackType::RowVar("a".to_string()));
1382    }
1383
1384    #[test]
1385    fn test_builtin_signature_dup() {
1386        let sig = builtin_signature("dup").unwrap();
1387        // Input: ( ..a T )
1388        assert_eq!(
1389            sig.inputs,
1390            StackType::Cons {
1391                rest: Box::new(StackType::RowVar("a".to_string())),
1392                top: Type::Var("T".to_string())
1393            }
1394        );
1395        // Output: ( ..a T T )
1396        let (rest, top) = sig.outputs.clone().pop().unwrap();
1397        assert_eq!(top, Type::Var("T".to_string()));
1398        let (rest2, top2) = rest.pop().unwrap();
1399        assert_eq!(top2, Type::Var("T".to_string()));
1400        assert_eq!(rest2, StackType::RowVar("a".to_string()));
1401    }
1402
1403    #[test]
1404    fn test_all_builtins_have_signatures() {
1405        let sigs = builtin_signatures();
1406
1407        // Verify all expected builtins have signatures
1408        assert!(sigs.contains_key("io.write-line"));
1409        assert!(sigs.contains_key("io.read-line"));
1410        assert!(sigs.contains_key("int->string"));
1411        assert!(sigs.contains_key("i.add"));
1412        assert!(sigs.contains_key("dup"));
1413        assert!(sigs.contains_key("swap"));
1414        assert!(sigs.contains_key("chan.make"));
1415        assert!(sigs.contains_key("chan.send"));
1416        assert!(sigs.contains_key("chan.receive"));
1417        assert!(
1418            sigs.contains_key("string->float"),
1419            "string->float should be a builtin"
1420        );
1421    }
1422
1423    #[test]
1424    fn test_all_docs_have_signatures() {
1425        let sigs = builtin_signatures();
1426        let docs = builtin_docs();
1427
1428        for name in docs.keys() {
1429            assert!(
1430                sigs.contains_key(*name),
1431                "Builtin '{}' has documentation but no signature",
1432                name
1433            );
1434        }
1435    }
1436
1437    #[test]
1438    fn test_all_signatures_have_docs() {
1439        let sigs = builtin_signatures();
1440        let docs = builtin_docs();
1441
1442        for name in sigs.keys() {
1443            assert!(
1444                docs.contains_key(name.as_str()),
1445                "Builtin '{}' has signature but no documentation",
1446                name
1447            );
1448        }
1449    }
1450}