caternary 0.5.0

Caternary is a stack-based language and runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
//! Quotation combinators for caternary.
//!
//! Combinators are operators that execute quotations (bracketed code) from the stack.
//! They enable higher-order programming patterns like `CALL`, `DIP`, `BI`, etc.
//!
//! To use combinators, your stack element type `T` must implement `Quotable`, which
//! allows extracting the underlying tokens from a quotation value.

use crate::EvalError;
use crate::Evaluator;
use crate::Token;
use crate::evaluator::operator_error;

/// A trait for stack element types that can contain quotations.
///
/// Quotations are bracketed code that can be executed by combinators. This trait
/// allows combinators to extract the tokens from a quotation value on the stack.
pub trait Quotable: From<Token> + Clone {
    /// Attempts to extract the tokens from a quotation value.
    ///
    /// Returns `Some(tokens)` if this value is a quotation (bracket), or `None` otherwise.
    fn as_quotation(&self) -> Option<&[Token]>;

    /// Converts this value back to tokens for use in quotation construction.
    ///
    /// Used by `CURRY` to embed a value into a quotation. Returns a vector of
    /// tokens that, when evaluated, would produce this value on the stack.
    fn to_tokens(&self) -> Vec<Token>;

    /// Returns true if this value represents a truthy condition.
    ///
    /// Used by conditional combinators like `IF`, `WHEN`, `UNLESS`.
    /// The default implementation returns `true` for all values.
    fn is_truthy(&self) -> bool {
        true
    }

    /// Attempts to extract this value as a sequence of elements.
    ///
    /// Returns `Some(elements)` if this value is a sequence, or `None` otherwise.
    /// Used by sequence combinators like `MAP`, `FILTER`, `FOLD`, `EACH`.
    fn as_sequence(&self) -> Option<Vec<Self>>;

    /// Creates a sequence value from a vector of elements.
    ///
    /// Used by sequence combinators to construct result sequences.
    fn from_sequence(elements: Vec<Self>) -> Self;
}

fn stack_underflow(expected: usize, found: usize) -> EvalError {
    operator_error(format!(
        "stack underflow: need at least {expected} values, found {found}"
    ))
}

fn require_len<T>(stack: &[T], expected: usize) -> Result<(), EvalError> {
    if stack.len() < expected {
        return Err(stack_underflow(expected, stack.len()));
    }
    Ok(())
}

fn not_a_quotation() -> EvalError {
    operator_error("expected a quotation (bracketed code)")
}

fn not_a_sequence() -> EvalError {
    operator_error("expected a sequence")
}

/// Pops a quotation from the stack, returning its tokens.
fn pop_quotation<T: Quotable>(stack: &mut Vec<T>) -> Result<Vec<Token>, EvalError> {
    let val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    val.as_quotation()
        .map(|tokens| tokens.to_vec())
        .ok_or_else(not_a_quotation)
}

// ============================================================================
// Core Combinators
// ============================================================================

/// `CALL`: Execute a quotation.
///
/// Stack effect: `( [Q] -- ... )`
///
/// Pops a quotation from the stack and executes it.
fn call<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    let quotation = pop_quotation(stack)?;
    eval.eval_with_stack(&quotation, stack)
}

/// `DIP`: Execute a quotation while hiding the top element.
///
/// Stack effect: `( x [Q] -- ... x )`
///
/// Pops a quotation and the element below it, executes the quotation,
/// then pushes the hidden element back.
fn dip<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let hidden = stack.pop().unwrap();
    eval.eval_with_stack(&quotation, stack)?;
    stack.push(hidden);
    Ok(())
}

/// `KEEP`: Execute a quotation on a value, keeping the original value.
///
/// Stack effect: `( x [Q] -- ... x )`
///
/// Like `DIP` but the quotation receives a copy of x, and x is restored after.
fn keep<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let x = stack.last().unwrap().clone();
    eval.eval_with_stack(&quotation, stack)?;
    stack.push(x);
    Ok(())
}

/// `BI`: Apply two quotations to a single value.
///
/// Stack effect: `( x [P] [Q] -- P(x) Q(x) )`
///
/// Pops two quotations and a value, applies each quotation to a copy of the value.
fn bi<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 3)?;
    let q = pop_quotation(stack)?;
    let p = pop_quotation(stack)?;
    let x = stack.pop().unwrap();

    stack.push(x.clone());
    eval.eval_with_stack(&p, stack)?;

    stack.push(x);
    eval.eval_with_stack(&q, stack)?;

    Ok(())
}

/// `BI*`: Apply two quotations to two values respectively.
///
/// Stack effect: `( x y [P] [Q] -- P(x) Q(y) )`
///
/// Pops two quotations and two values, applies P to x and Q to y.
fn bi_star<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 4)?;
    let q = pop_quotation(stack)?;
    let p = pop_quotation(stack)?;
    let y = stack.pop().unwrap();
    let x = stack.pop().unwrap();

    stack.push(x);
    eval.eval_with_stack(&p, stack)?;

    stack.push(y);
    eval.eval_with_stack(&q, stack)?;

    Ok(())
}

/// `BI@`: Apply one quotation to two values.
///
/// Stack effect: `( x y [Q] -- Q(x) Q(y) )`
///
/// Pops a quotation and two values, applies the quotation to each.
fn bi_at<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 3)?;
    let q = pop_quotation(stack)?;
    let y = stack.pop().unwrap();
    let x = stack.pop().unwrap();

    stack.push(x);
    eval.eval_with_stack(&q, stack)?;

    stack.push(y);
    eval.eval_with_stack(&q, stack)?;

    Ok(())
}

/// `CLEAVE`: Apply multiple quotations to a single value.
///
/// Stack effect: `( x [[P] [Q] ...] -- P(x) Q(x) ... )`
///
/// Pops a list of quotations and a value, applies each quotation to a copy of the value.
fn cleave<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotations_val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    let quotations = quotations_val
        .as_quotation()
        .ok_or_else(not_a_quotation)?
        .to_vec();
    let x = stack.pop().unwrap();

    for token in quotations {
        if let Token::Bracket(q) = token {
            stack.push(x.clone());
            eval.eval_with_stack(&q, stack)?;
        } else {
            return Err(operator_error("CLEAVE expects a list of quotations"));
        }
    }

    Ok(())
}

/// `SPREAD`: Apply quotations from a list to corresponding stack values.
///
/// Stack effect: `( x y z [[P] [Q] [R]] -- P(x) Q(y) R(z) )`
///
/// Pops a list of quotations, then pops that many values, applies each quotation
/// to its corresponding value.
fn spread<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 1)?;
    let quotations_val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    let quotations = quotations_val
        .as_quotation()
        .ok_or_else(not_a_quotation)?
        .to_vec();

    let n = quotations.len();
    require_len(stack, n)?;

    let mut values: Vec<T> = Vec::with_capacity(n);
    for _ in 0..n {
        values.push(stack.pop().unwrap());
    }
    values.reverse();

    for (val, token) in values.into_iter().zip(quotations) {
        if let Token::Bracket(q) = token {
            stack.push(val);
            eval.eval_with_stack(&q, stack)?;
        } else {
            return Err(operator_error("SPREAD expects a list of quotations"));
        }
    }

    Ok(())
}

/// `COMPOSE`: Concatenate two quotations.
///
/// Stack effect: `( [P] [Q] -- [P Q] )`
///
/// Creates a new quotation that executes P followed by Q.
fn compose<T: Quotable>(stack: &mut Vec<T>, _eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let q = pop_quotation(stack)?;
    let p = pop_quotation(stack)?;

    let mut combined = p;
    combined.extend(q);

    stack.push(T::from(Token::Bracket(combined)));
    Ok(())
}

/// `CURRY`: Partially apply a value to a quotation.
///
/// Stack effect: `( x [Q] -- [x Q] )`
///
/// Creates a new quotation that pushes x, then executes Q.
fn curry<T: Quotable>(stack: &mut Vec<T>, _eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let q = pop_quotation(stack)?;
    let x_val = stack.pop().unwrap();

    let mut combined = x_val.to_tokens();
    combined.extend(q);

    stack.push(T::from(Token::Bracket(combined)));
    Ok(())
}

// ============================================================================
// Conditional Combinators
// ============================================================================

/// `IF`: Conditional execution.
///
/// Stack effect: `( ? [T] [F] -- ... )`
///
/// Pops a condition and two quotations. Executes T if condition is truthy, F otherwise.
fn if_combinator<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 3)?;
    let false_branch = pop_quotation(stack)?;
    let true_branch = pop_quotation(stack)?;
    let condition = stack.pop().unwrap();

    if condition.is_truthy() {
        eval.eval_with_stack(&true_branch, stack)
    } else {
        eval.eval_with_stack(&false_branch, stack)
    }
}

/// `WHEN`: Execute quotation if condition is truthy.
///
/// Stack effect: `( ? [Q] -- ... )`
///
/// Pops a condition and a quotation. Executes Q only if condition is truthy.
fn when<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let condition = stack.pop().unwrap();

    if condition.is_truthy() {
        eval.eval_with_stack(&quotation, stack)
    } else {
        Ok(())
    }
}

/// `UNLESS`: Execute quotation if condition is falsy.
///
/// Stack effect: `( ? [Q] -- ... )`
///
/// Pops a condition and a quotation. Executes Q only if condition is falsy.
fn unless<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let condition = stack.pop().unwrap();

    if !condition.is_truthy() {
        eval.eval_with_stack(&quotation, stack)
    } else {
        Ok(())
    }
}

// ============================================================================
// Sequence Combinators
// ============================================================================

/// `MAP`: Transform each element of a sequence.
///
/// Stack effect: `( seq [Q] -- seq' )`
///
/// Applies Q to each element of the sequence, collecting results.
fn map<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let seq_val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    let seq = seq_val.as_sequence().ok_or_else(not_a_sequence)?;

    let mut results = Vec::with_capacity(seq.len());
    for elem in seq {
        let before = stack.len();
        stack.push(elem);
        eval.eval_with_stack(&quotation, stack)?;
        if stack.len() != before + 1 {
            return Err(operator_error(
                "MAP quotation must consume one element and leave one result",
            ));
        }
        let result = stack
            .pop()
            .ok_or_else(|| operator_error("MAP quotation must leave one value on stack"))?;
        results.push(result);
    }

    stack.push(T::from_sequence(results));
    Ok(())
}

/// `FILTER`: Select elements matching a predicate.
///
/// Stack effect: `( seq [pred] -- seq' )`
///
/// Applies pred to each element, keeping only those where pred returns truthy.
fn filter<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let seq_val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    let seq = seq_val.as_sequence().ok_or_else(not_a_sequence)?;

    let mut results = Vec::new();
    for elem in seq {
        let before = stack.len();
        stack.push(elem.clone());
        eval.eval_with_stack(&quotation, stack)?;
        if stack.len() != before + 1 {
            return Err(operator_error(
                "FILTER quotation must consume one element and leave one predicate value",
            ));
        }
        let predicate_result = stack
            .pop()
            .ok_or_else(|| operator_error("FILTER quotation must leave one value on stack"))?;
        if predicate_result.is_truthy() {
            results.push(elem);
        }
    }

    stack.push(T::from_sequence(results));
    Ok(())
}

/// `FOLD`: Reduce a sequence with an accumulator.
///
/// Stack effect: `( seq init [Q] -- result )`
///
/// Starting with init, applies Q to (accumulator, element) for each element.
/// Q should leave the new accumulator on the stack.
fn fold<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 3)?;
    let quotation = pop_quotation(stack)?;
    let init = stack.pop().unwrap();
    let seq_val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    let seq = seq_val.as_sequence().ok_or_else(not_a_sequence)?;

    stack.push(init);
    for elem in seq {
        let before = stack.len();
        stack.push(elem);
        eval.eval_with_stack(&quotation, stack)?;
        if stack.len() != before {
            return Err(operator_error(
                "FOLD quotation must consume accumulator+element and leave one accumulator",
            ));
        }
    }

    Ok(())
}

/// `EACH`: Execute a quotation for each element (for side effects).
///
/// Stack effect: `( seq [Q] -- )`
///
/// Applies Q to each element, discarding results.
fn each<T: Quotable>(stack: &mut Vec<T>, eval: &Evaluator<T>) -> Result<(), EvalError> {
    require_len(stack, 2)?;
    let quotation = pop_quotation(stack)?;
    let seq_val = stack.pop().ok_or_else(|| stack_underflow(1, 0))?;
    let seq = seq_val.as_sequence().ok_or_else(not_a_sequence)?;

    for elem in seq {
        let before = stack.len();
        stack.push(elem);
        eval.eval_with_stack(&quotation, stack)?;
        if stack.len() != before {
            return Err(operator_error(
                "EACH quotation must consume one element and leave no extra values",
            ));
        }
    }

    Ok(())
}

// ============================================================================
// Registration
// ============================================================================

/// Register quotation combinators on an evaluator.
///
/// This registers the core combinators: `CALL`, `DIP`, `KEEP`, `BI`, `BI*`, `BI@`,
/// `CLEAVE`, `SPREAD`, `COMPOSE`, `CURRY`.
pub fn register_combinators<T>(evaluator: &mut Evaluator<T>)
where
    T: Quotable,
{
    evaluator.define("CALL", call::<T>);
    evaluator.define("DIP", dip::<T>);
    evaluator.define("KEEP", keep::<T>);
    evaluator.define("BI", bi::<T>);
    evaluator.define("BI*", bi_star::<T>);
    evaluator.define("BI@", bi_at::<T>);
    evaluator.define("CLEAVE", cleave::<T>);
    evaluator.define("SPREAD", spread::<T>);
    evaluator.define("COMPOSE", compose::<T>);
    evaluator.define("CURRY", curry::<T>);
}

/// Register conditional combinators on an evaluator.
///
/// This registers: `IF`, `WHEN`, `UNLESS`.
pub fn register_conditionals<T>(evaluator: &mut Evaluator<T>)
where
    T: Quotable,
{
    evaluator.define("IF", if_combinator::<T>);
    evaluator.define("WHEN", when::<T>);
    evaluator.define("UNLESS", unless::<T>);
}

/// Register sequence combinators on an evaluator.
///
/// This registers: `MAP`, `FILTER`, `FOLD`, `EACH`.
pub fn register_sequence_combinators<T>(evaluator: &mut Evaluator<T>)
where
    T: Quotable,
{
    evaluator.define("MAP", map::<T>);
    evaluator.define("FILTER", filter::<T>);
    evaluator.define("FOLD", fold::<T>);
    evaluator.define("EACH", each::<T>);
}

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

    #[derive(Debug, Clone, PartialEq)]
    enum Value {
        Int(i64),
        Bool(bool),
        Word(String),
        Quotation(Vec<Token>),
        Sequence(Vec<Value>),
    }

    impl From<Token> for Value {
        fn from(token: Token) -> Self {
            match token {
                Token::Word(w) => {
                    if let Ok(n) = w.parse::<i64>() {
                        Value::Int(n)
                    } else if w == "true" {
                        Value::Bool(true)
                    } else if w == "false" {
                        Value::Bool(false)
                    } else {
                        Value::Word(w)
                    }
                }
                Token::Bracket(tokens) => Value::Quotation(tokens),
            }
        }
    }

    impl Quotable for Value {
        fn as_quotation(&self) -> Option<&[Token]> {
            match self {
                Value::Quotation(tokens) => Some(tokens),
                _ => None,
            }
        }

        fn to_tokens(&self) -> Vec<Token> {
            match self {
                Value::Int(n) => vec![Token::Word(n.to_string())],
                Value::Bool(b) => vec![Token::Word(b.to_string())],
                Value::Word(w) => vec![Token::Word(w.clone())],
                Value::Quotation(tokens) => vec![Token::Bracket(tokens.clone())],
                Value::Sequence(elems) => {
                    let inner: Vec<Token> = elems.iter().flat_map(|e| e.to_tokens()).collect();
                    vec![Token::Bracket(inner)]
                }
            }
        }

        fn is_truthy(&self) -> bool {
            match self {
                Value::Bool(b) => *b,
                Value::Int(n) => *n != 0,
                _ => true,
            }
        }

        fn as_sequence(&self) -> Option<Vec<Self>> {
            match self {
                Value::Sequence(elems) => Some(elems.clone()),
                Value::Quotation(tokens) => {
                    Some(tokens.iter().map(|t| Value::from(t.clone())).collect())
                }
                _ => None,
            }
        }

        fn from_sequence(elements: Vec<Self>) -> Self {
            Value::Sequence(elements)
        }
    }

    fn make_eval() -> Evaluator<Value> {
        let mut eval = Evaluator::new();
        register_stack_builtins(&mut eval);
        register_combinators(&mut eval);
        register_conditionals(&mut eval);
        register_sequence_combinators(&mut eval);

        eval.define("ADD", |stack: &mut Vec<Value>, _eval| {
            let b = stack.pop().ok_or_else(|| stack_underflow(2, stack.len()))?;
            let a = stack.pop().ok_or_else(|| stack_underflow(2, stack.len()))?;
            match (a, b) {
                (Value::Int(a), Value::Int(b)) => stack.push(Value::Int(a + b)),
                _ => {
                    return Err(operator_error("ADD requires two integers"));
                }
            }
            Ok(())
        });

        eval.define("MUL", |stack: &mut Vec<Value>, _eval| {
            let b = stack.pop().ok_or_else(|| stack_underflow(2, stack.len()))?;
            let a = stack.pop().ok_or_else(|| stack_underflow(2, stack.len()))?;
            match (a, b) {
                (Value::Int(a), Value::Int(b)) => stack.push(Value::Int(a * b)),
                _ => {
                    return Err(operator_error("MUL requires two integers"));
                }
            }
            Ok(())
        });

        eval.define("GT", |stack: &mut Vec<Value>, _eval| {
            let b = stack.pop().ok_or_else(|| stack_underflow(2, stack.len()))?;
            let a = stack.pop().ok_or_else(|| stack_underflow(2, stack.len()))?;
            match (a, b) {
                (Value::Int(a), Value::Int(b)) => stack.push(Value::Bool(a > b)),
                _ => {
                    return Err(operator_error("GT requires two integers"));
                }
            }
            Ok(())
        });

        eval.define("EVEN", |stack: &mut Vec<Value>, _eval| {
            let a = stack.pop().ok_or_else(|| stack_underflow(1, stack.len()))?;
            match a {
                Value::Int(n) => stack.push(Value::Bool(n % 2 == 0)),
                _ => {
                    return Err(operator_error("EVEN requires an integer"));
                }
            }
            Ok(())
        });

        eval.define("ECHO", |stack: &mut Vec<Value>, _eval| {
            let value = stack.pop().ok_or_else(|| stack_underflow(1, stack.len()))?;
            stack.push(value);
            Ok(())
        });

        eval
    }

    // ========================================================================
    // CALL tests
    // ========================================================================

    #[test]
    fn call_executes_quotation() {
        let eval = make_eval();
        let tokens = parse("1 2 [ADD] CALL").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(3)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn call_nested_quotations() {
        let eval = make_eval();
        let tokens = parse("1 2 [[ADD] CALL] CALL").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(3)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn echo_preserves_shell_quoted_word() {
        let eval = make_eval();
        let tokens = parse(r#""hello world" ECHO"#).unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Word("hello world".to_string())]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn call_executes_compact_quotation_with_shell_quoted_word() {
        let eval = make_eval();
        let tokens = parse(r#"["hello world" ECHO]CALL"#).unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Word("hello world".to_string())]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // DIP tests
    // ========================================================================

    #[test]
    fn dip_hides_top() {
        let eval = make_eval();
        let tokens = parse("1 2 3 [ADD] DIP").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(3), Value::Int(3)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn dip_restores_hidden_value() {
        let eval = make_eval();
        let tokens = parse("10 20 [DUP] DIP").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(10), Value::Int(10), Value::Int(20)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // KEEP tests
    // ========================================================================

    #[test]
    fn keep_preserves_value() {
        let eval = make_eval();
        let tokens = parse("5 [DUP MUL] KEEP").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(25), Value::Int(5)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // BI tests
    // ========================================================================

    #[test]
    fn bi_applies_two_quotations() {
        let eval = make_eval();
        let tokens = parse("5 [DUP ADD] [DUP MUL] BI").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(10), Value::Int(25)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // BI* tests
    // ========================================================================

    #[test]
    fn bi_star_applies_to_two_values() {
        let eval = make_eval();
        let tokens = parse("3 4 [DUP MUL] [DUP ADD] BI*").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(9), Value::Int(8)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // BI@ tests
    // ========================================================================

    #[test]
    fn bi_at_applies_same_quotation() {
        let eval = make_eval();
        let tokens = parse("3 4 [DUP MUL] BI@").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(9), Value::Int(16)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // CLEAVE tests
    // ========================================================================

    #[test]
    fn cleave_applies_multiple_quotations() {
        let eval = make_eval();
        let tokens = parse("5 [[DUP ADD] [DUP MUL] [1 ADD]] CLEAVE").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(10), Value::Int(25), Value::Int(6)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // SPREAD tests
    // ========================================================================

    #[test]
    fn spread_distributes_quotations() {
        let eval = make_eval();
        let tokens = parse("1 2 3 [[DUP ADD] [DUP MUL] [1 ADD]] SPREAD").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(2), Value::Int(4), Value::Int(4)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // COMPOSE tests
    // ========================================================================

    #[test]
    fn compose_concatenates_quotations() {
        let eval = make_eval();
        let tokens = parse("[1 ADD] [2 MUL] COMPOSE 5 SWAP CALL").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(12)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // CURRY tests
    // ========================================================================

    #[test]
    fn curry_partial_application() {
        let eval = make_eval();
        let tokens = parse("10 [ADD] CURRY 5 SWAP CALL").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(15)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // IF tests
    // ========================================================================

    #[test]
    fn if_true_branch() {
        let eval = make_eval();
        let tokens = parse("true [1] [2] IF").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(1)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn if_false_branch() {
        let eval = make_eval();
        let tokens = parse("false [1] [2] IF").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(2)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn if_with_comparison() {
        let eval = make_eval();
        let tokens = parse("5 3 GT [yes] [no] IF").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Word("yes".to_string())]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // WHEN tests
    // ========================================================================

    #[test]
    fn when_true_executes() {
        let eval = make_eval();
        let tokens = parse("true [42] WHEN").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(42)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn when_false_skips() {
        let eval = make_eval();
        let tokens = parse("false [42] WHEN").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert!(result.is_empty());
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // UNLESS tests
    // ========================================================================

    #[test]
    fn unless_false_executes() {
        let eval = make_eval();
        let tokens = parse("false [42] UNLESS").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(42)]);
        println!("Stack: {result:?}");
    }

    #[test]
    fn unless_true_skips() {
        let eval = make_eval();
        let tokens = parse("true [42] UNLESS").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert!(result.is_empty());
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // MAP tests
    // ========================================================================

    #[test]
    fn map_transforms_sequence() {
        let eval = make_eval();
        let tokens = parse("[1 2 3] [DUP MUL] MAP").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(
            result,
            vec![Value::Sequence(vec![
                Value::Int(1),
                Value::Int(4),
                Value::Int(9)
            ])]
        );
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // FILTER tests
    // ========================================================================

    #[test]
    fn filter_selects_matching() {
        let eval = make_eval();
        let tokens = parse("[1 2 3 4 5 6] [EVEN] FILTER").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(
            result,
            vec![Value::Sequence(vec![
                Value::Int(2),
                Value::Int(4),
                Value::Int(6)
            ])]
        );
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // FOLD tests
    // ========================================================================

    #[test]
    fn fold_accumulates() {
        let eval = make_eval();
        let tokens = parse("[1 2 3 4 5] 0 [ADD] FOLD").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(15)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // EACH tests
    // ========================================================================

    #[test]
    fn each_iterates() {
        let eval = make_eval();
        let tokens = parse("0 [1 2 3] [ADD] EACH").unwrap();
        let result = eval.eval(&tokens).unwrap();
        assert_eq!(result, vec![Value::Int(6)]);
        println!("Stack: {result:?}");
    }

    // ========================================================================
    // Error handling tests
    // ========================================================================

    #[test]
    fn call_non_quotation_fails() {
        let eval = make_eval();
        let tokens = parse("42 CALL").unwrap();
        let result = eval.eval(&tokens);
        assert!(result.is_err());
        println!("Error: {result:?}");
    }

    #[test]
    fn dip_underflow_fails() {
        let eval = make_eval();
        let tokens = parse("[ADD] DIP").unwrap();
        let result = eval.eval(&tokens);
        assert!(result.is_err());
        println!("Error: {result:?}");
    }
}