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