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
//! Standard functions for the interpreter.

use num_traits::{Num, One, Pow, Zero};

use core::ops;

use crate::{
    alloc::{vec, Vec},
    AuxErrorInfo, CallContext, EvalError, EvalResult, Function, NativeFn, SpannedEvalError,
    SpannedValue, Value,
};
use arithmetic_parser::Grammar;

fn extract_number<'a, T: Grammar>(
    ctx: &CallContext<'_, 'a>,
    value: SpannedValue<'a, T>,
    error_msg: &str,
) -> Result<T::Lit, SpannedEvalError<'a>> {
    match value.extra {
        Value::Number(value) => Ok(value),
        _ => Err(ctx
            .call_site_error(EvalError::native(error_msg))
            .with_span(&value, AuxErrorInfo::InvalidArg)),
    }
}

fn extract_array<'a, T: Grammar>(
    ctx: &CallContext<'_, 'a>,
    value: SpannedValue<'a, T>,
    error_msg: &str,
) -> Result<Vec<Value<'a, T>>, SpannedEvalError<'a>> {
    if let Value::Tuple(array) = value.extra {
        Ok(array)
    } else {
        let err = EvalError::native(error_msg);
        Err(ctx
            .call_site_error(err)
            .with_span(&value, AuxErrorInfo::InvalidArg))
    }
}

fn extract_fn<'a, T: Grammar>(
    ctx: &CallContext<'_, 'a>,
    value: SpannedValue<'a, T>,
    error_msg: &str,
) -> Result<Function<'a, T>, SpannedEvalError<'a>> {
    if let Value::Function(function) = value.extra {
        Ok(function)
    } else {
        let err = EvalError::native(error_msg);
        Err(ctx
            .call_site_error(err)
            .with_span(&value, AuxErrorInfo::InvalidArg))
    }
}

/// Assertion function.
///
/// # Type
///
/// ```text
/// fn(bool)
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, EvalError, Interpreter};
/// # use assert_matches::assert_matches;
/// let program = r#"
///     assert(1 + 2 == 3); # this assertion is fine
///     assert(3^2 == 10); # this one will fail
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter.insert_native_fn("assert", fns::Assert);
/// let err = interpreter.evaluate(&block).unwrap_err();
/// assert_eq!(err.main_span().fragment, "assert(3^2 == 10)");
/// assert_matches!(
///     err.source(),
///     EvalError::NativeCall(ref msg) if msg == "Assertion failed"
/// );
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Assert;

impl<T: Grammar> NativeFn<T> for Assert {
    fn evaluate<'a>(
        &self,
        args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 1)?;
        match args[0].extra {
            Value::Bool(true) => Ok(Value::void()),
            Value::Bool(false) => {
                let err = EvalError::native("Assertion failed");
                Err(ctx.call_site_error(err))
            }
            _ => {
                let err = EvalError::native("`assert` requires a single boolean argument");
                Err(ctx
                    .call_site_error(err)
                    .with_span(&args[0], AuxErrorInfo::InvalidArg))
            }
        }
    }
}

/// `if` function that eagerly evaluates "if" / "else" terms.
///
/// # Type
///
/// ```text
/// fn<T>(bool, T, T) -> T
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns::If, Interpreter, Value};
/// let program = "x = 3; if(x == 2, -1, x + 1)";
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter.insert_native_fn("if", If);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Number(4.0));
/// ```
///
/// You can also use the lazy evaluation by returning a function and evaluating it
/// afterwards:
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns::If, Interpreter, Value};
/// let program = "x = 3; if(x == 2, || -1, || x + 1)()";
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter.insert_native_fn("if", If);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Number(4.0));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct If;

impl<T> NativeFn<T> for If
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 3)?;
        let else_val = args.pop().unwrap().extra;
        let then_val = args.pop().unwrap().extra;

        match &args[0].extra {
            Value::Bool(condition) => Ok(if *condition { then_val } else { else_val }),

            _ => {
                let err = EvalError::native("`if` requires first arg to be boolean");
                Err(ctx
                    .call_site_error(err)
                    .with_span(&args[0], AuxErrorInfo::InvalidArg))
            }
        }
    }
}

/// Loop function that evaluates the provided closure one or more times.
///
/// # Type
///
/// ```text
/// fn<T, R>(T, fn(T) -> (false, R) | (true, T)) -> R
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, Interpreter, Value};
/// let program = r#"
///     factorial = |x| {
///         loop((x, 1), |(i, acc)| {
///             continue = cmp(i, 1) != -1; # i >= 1
///             (continue, if(continue, (i - 1, acc * i), acc))
///         })
///     };
///     factorial(5) == 120 && factorial(10) == 3628800
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter
///     .insert_native_fn("cmp", fns::Compare)
///     .insert_native_fn("if", fns::If)
///     .insert_native_fn("loop", fns::Loop);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Bool(true));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Loop;

impl Loop {
    const ITER_ERROR: &'static str =
        "iteration function should return a 2-element tuple with first bool value";
}

impl<T> NativeFn<T> for Loop
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let iter = args.pop().unwrap();
        let iter = match iter.extra {
            Value::Function(iter) => iter,
            _ => {
                let err =
                    EvalError::native("Second argument of `loop` should be an iterator function");
                return Err(ctx
                    .call_site_error(err)
                    .with_span(&iter, AuxErrorInfo::InvalidArg));
            }
        };

        let mut arg = args.pop().unwrap();
        loop {
            match iter.evaluate(vec![arg], ctx)? {
                Value::Tuple(mut tuple) => {
                    let (ret_or_next_arg, flag) = if tuple.len() == 2 {
                        (tuple.pop().unwrap(), tuple.pop().unwrap())
                    } else {
                        let err = EvalError::native(Self::ITER_ERROR);
                        break Err(ctx.call_site_error(err));
                    };

                    match (flag, ret_or_next_arg) {
                        (Value::Bool(false), ret) => break Ok(ret),
                        (Value::Bool(true), next_arg) => {
                            arg = ctx.apply_call_span(next_arg);
                        }
                        _ => {
                            let err = EvalError::native(Self::ITER_ERROR);
                            break Err(ctx.call_site_error(err));
                        }
                    }
                }
                _ => {
                    let err = EvalError::native(Self::ITER_ERROR);
                    break Err(ctx.call_site_error(err));
                }
            }
        }
    }
}

/// Map function that evaluates the provided function on each item of the tuple.
///
/// # Type
///
/// ```text
/// fn<T, U>([T], fn(T) -> U) -> [U]
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, Interpreter, Value};
/// let program = r#"
///     xs = (1, -2, 3, -0.3);
///     map(xs, |x| if(cmp(x, 0) == 1, x, 0)) == (1, 0, 3, 0)
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter
///     .insert_native_fn("cmp", fns::Compare)
///     .insert_native_fn("if", fns::If)
///     .insert_native_fn("map", fns::Map);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Bool(true));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Map;

impl<T> NativeFn<T> for Map
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let map_fn = extract_fn(
            ctx,
            args.pop().unwrap(),
            "`map` requires second arg to be a mapping function",
        )?;
        let array = extract_array(
            ctx,
            args.pop().unwrap(),
            "`map` requires first arg to be a tuple",
        )?;

        let mapped: Result<Vec<_>, _> = array
            .into_iter()
            .map(|value| {
                let spanned = ctx.apply_call_span(value);
                map_fn.evaluate(vec![spanned], ctx)
            })
            .collect();
        mapped.map(Value::Tuple)
    }
}

/// Filter function that evaluates the provided function on each item of the tuple and retains
/// only elements for which the function returned `true`.
///
/// # Type
///
/// ```text
/// fn<T>([T], fn(T) -> bool) -> [T]
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, Interpreter, Value};
/// let program = r#"
///     xs = (1, -2, 3, -7, -0.3);
///     filter(xs, |x| cmp(x, -1) == 1) == (1, 3, -0.3)
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter
///     .insert_native_fn("cmp", fns::Compare)
///     .insert_native_fn("filter", fns::Filter);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Bool(true));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Filter;

impl<T> NativeFn<T> for Filter
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let filter_fn = extract_fn(
            ctx,
            args.pop().unwrap(),
            "`filter` requires second arg to be a filter function",
        )?;
        let array = extract_array(
            ctx,
            args.pop().unwrap(),
            "`filter` requires first arg to be a tuple",
        )?;

        let mut filtered = vec![];
        for value in array {
            let spanned = ctx.apply_call_span(value.clone());
            match filter_fn.evaluate(vec![spanned], ctx)? {
                Value::Bool(true) => filtered.push(value),
                Value::Bool(false) => { /* do nothing */ }
                _ => {
                    let err = EvalError::native(
                        "`filter` requires filtering function to return booleans",
                    );
                    return Err(ctx.call_site_error(err));
                }
            }
        }
        Ok(Value::Tuple(filtered))
    }
}

/// Reduce (aka fold) function that reduces the provided tuple to a single value.
///
/// # Type
///
/// ```text
/// fn<T, Acc>([T], Acc, fn(Acc, T) -> Acc) -> Acc
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, Interpreter, Value};
/// let program = r#"
///     xs = (1, -2, 3, -7);
///     fold(xs, 1, |acc, x| acc * x) == 42
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter
///     .insert_native_fn("fold", fns::Fold);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Bool(true));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Fold;

impl<T> NativeFn<T> for Fold
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 3)?;
        let fold_fn = extract_fn(
            ctx,
            args.pop().unwrap(),
            "`fold` requires third arg to be a folding function",
        )?;
        let acc = args.pop().unwrap().extra;
        let array = extract_array(
            ctx,
            args.pop().unwrap(),
            "`fold` requires first arg to be a tuple",
        )?;

        array.into_iter().try_fold(acc, |acc, value| {
            let spanned_args = vec![ctx.apply_call_span(acc), ctx.apply_call_span(value)];
            fold_fn.evaluate(spanned_args, ctx)
        })
    }
}

/// Function that appends a value onto a tuple.
///
/// # Type
///
/// ```text
/// fn<T>([T], T) -> [T]
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, Interpreter, Value};
/// let program = r#"
///     repeat = |x, times| loop(
///         (0, ()),
///         |(i, acc)| {
///             continue = cmp(i, times) == -1;
///             ret = if(continue, (i + 1, push(acc, x)), acc);
///             (continue, ret)
///         },
///     );
///     repeat(-2, 3) == (-2, -2, -2) && repeat((7,), 4) == ((7,), (7,), (7,), (7,))
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter
///     .insert_native_fn("cmp", fns::Compare)
///     .insert_native_fn("if", fns::If)
///     .insert_native_fn("loop", fns::Loop)
///     .insert_native_fn("push", fns::Push);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Bool(true));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Push;

impl<T> NativeFn<T> for Push
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let elem = args.pop().unwrap().extra;
        let mut array = extract_array(
            ctx,
            args.pop().unwrap(),
            "`fold` requires first arg to be a tuple",
        )?;

        array.push(elem);
        Ok(Value::Tuple(array))
    }
}

/// Function that merges two tuples.
///
/// # Type
///
/// ```text
/// fn<T>([T], [T]) -> [T]
/// ```
///
/// # Examples
///
/// ```
/// # use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};
/// # use arithmetic_eval::{fns, Interpreter, Value};
/// let program = r#"
///     ## Merges all arguments (which should be tuples) into a single tuple.
///     super_merge = |...xs| fold(xs, (), merge);
///     super_merge((1, 2), (3,), (), (4, 5, 6)) == (1, 2, 3, 4, 5, 6)
/// "#;
/// let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
///
/// let mut interpreter = Interpreter::new();
/// interpreter
///     .insert_native_fn("fold", fns::Fold)
///     .insert_native_fn("merge", fns::Merge);
/// let ret = interpreter.evaluate(&block).unwrap();
/// assert_eq!(ret, Value::Bool(true));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Merge;

impl<T> NativeFn<T> for Merge
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit>,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let second = extract_array(
            ctx,
            args.pop().unwrap(),
            "`merge` requires second arg to be a tuple",
        )?;
        let mut first = extract_array(
            ctx,
            args.pop().unwrap(),
            "`merge` requires first arg to be a tuple",
        )?;

        first.extend_from_slice(&second);
        Ok(Value::Tuple(first))
    }
}

/// Comparator function on two arguments. Returns `-1` if the first argument is lesser than
/// the second, `1` if the first argument is greater, and `0` in other cases.
///
/// # Type
///
/// ```text
/// fn(Num, Num) -> Num
/// ```
#[derive(Debug, Clone, Copy)]
pub struct Compare;

const COMPARE_ERROR_MSG: &str = "Compare requires 2 primitive arguments";

impl<T> NativeFn<T> for Compare
where
    T: Grammar,
    T::Lit: Num + ops::Neg<Output = T::Lit> + Pow<T::Lit, Output = T::Lit> + PartialOrd,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let y = args.pop().unwrap();
        let x = args.pop().unwrap();

        let x = extract_number(ctx, x, COMPARE_ERROR_MSG)?;
        let y = extract_number(ctx, y, COMPARE_ERROR_MSG)?;

        Ok(Value::Number(if x < y {
            -<T::Lit as One>::one()
        } else if x > y {
            <T::Lit as One>::one()
        } else {
            <T::Lit as Zero>::zero()
        }))
    }
}

/// Unary function wrapper.
#[derive(Debug, Clone, Copy)]
pub struct Unary<F> {
    function: F,
}

impl<F> Unary<F> {
    /// Creates a new function.
    pub const fn new(function: F) -> Self {
        Self { function }
    }
}

impl<F, T> NativeFn<T> for Unary<F>
where
    T: Grammar,
    F: Fn(T::Lit) -> T::Lit,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 1)?;
        let arg = args.pop().unwrap();

        match arg.extra {
            Value::Number(x) => {
                let output = (self.function)(x);
                Ok(Value::Number(output))
            }
            _ => {
                let err = EvalError::native("Unary function requires one primitive argument");
                Err(ctx
                    .call_site_error(err)
                    .with_span(&arg, AuxErrorInfo::InvalidArg))
            }
        }
    }
}

const BINARY_FN_MSG: &str = "Binary function requires two primitive arguments";

/// Binary function wrapper.
#[derive(Debug, Clone, Copy)]
pub struct Binary<F> {
    function: F,
}

impl<F> Binary<F> {
    /// Creates a new function.
    pub const fn new(function: F) -> Self {
        Self { function }
    }
}

impl<F, T> NativeFn<T> for Binary<F>
where
    T: Grammar,
    F: Fn(T::Lit, T::Lit) -> T::Lit,
{
    fn evaluate<'a>(
        &self,
        mut args: Vec<SpannedValue<'a, T>>,
        ctx: &mut CallContext<'_, 'a>,
    ) -> EvalResult<'a, T> {
        ctx.check_args_count(&args, 2)?;
        let y = args.pop().unwrap();
        let x = args.pop().unwrap();

        let x = extract_number(ctx, x, BINARY_FN_MSG)?;
        let y = extract_number(ctx, y, BINARY_FN_MSG)?;
        let output = (self.function)(x, y);
        Ok(Value::Number(output))
    }
}

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

    use arithmetic_parser::{grammars::F32Grammar, GrammarExt, Span};

    use core::f32;

    #[test]
    fn if_basic() {
        let mut interpreter = Interpreter::new();
        interpreter
            .insert_native_fn("if", If)
            .insert_native_fn("cmp", Compare);

        let program = r#"
            x = 1.0;
            if(cmp(x, 2) == -1, x + 5, 3 - x)
        "#;
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let ret = interpreter.evaluate(&block).unwrap();
        assert_eq!(ret, Value::Number(6.0));

        let program = r#"
            x = 4.5;
            if(cmp(x, 2) == -1, || x + 5, || 3 - x)()
        "#;
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let ret = interpreter.evaluate(&block).unwrap();
        assert_eq!(ret, Value::Number(-1.5));
    }

    #[test]
    fn loop_basic() {
        let mut interpreter = Interpreter::new();
        interpreter
            .insert_native_fn("loop", Loop)
            .insert_native_fn("if", If)
            .insert_native_fn("cmp", Compare);

        let program = r#"
            # Finds the greatest power of 2 lesser or equal to the value.
            discrete_log2 = |x| {
                loop(0, |i| {
                    continue = cmp(2^i, x) != 1;
                    (continue, if(continue, i + 1, i - 1))
                })
            };
            discrete_log2(9)
        "#;
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let ret = interpreter.evaluate(&block).unwrap();
        assert_eq!(ret, Value::Number(3.0));

        let program = "(discrete_log2(1), discrete_log2(2), \
            discrete_log2(4), discrete_log2(6.5), discrete_log2(1000))";
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let ret = interpreter.evaluate(&block).unwrap();
        assert_eq!(
            ret,
            Value::Tuple(vec![
                Value::Number(0.0),
                Value::Number(1.0),
                Value::Number(2.0),
                Value::Number(2.0),
                Value::Number(9.0),
            ])
        );
    }

    #[test]
    fn max_value_with_fold() {
        let mut interpreter = Interpreter::new();
        interpreter
            .insert_var("Inf", Value::Number(f32::INFINITY))
            .insert_native_fn("cmp", Compare)
            .insert_native_fn("if", If)
            .insert_native_fn("fold", Fold);

        let program = r#"
            max_value = |...xs| {
                fold(xs, -Inf, |acc, x| if(cmp(x, acc) == 1, x, acc))
            };
            max_value(1, -2, 7, 2, 5) == 7 && max_value(3, -5, 9) == 9
        "#;
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let ret = interpreter.evaluate(&block).unwrap();
        assert_eq!(ret, Value::Bool(true));
    }

    #[test]
    fn reverse_list_with_fold() {
        let mut interpreter = Interpreter::new();
        interpreter
            .insert_native_fn("merge", Merge)
            .insert_native_fn("fold", Fold);

        let program = r#"
            reverse = |xs| {
                fold(xs, (), |acc, x| merge((x,), acc))
            };
            xs = (-4, 3, 0, 1);
            xs.reverse() == (1, 0, 3, -4)
        "#;
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let ret = interpreter.evaluate(&block).unwrap();
        assert_eq!(ret, Value::Bool(true));

        let program = "xs.reverse()";
        let block = F32Grammar::parse_statements(Span::new(program)).unwrap();
        let mut module = interpreter.compile(&block).unwrap();

        const SAMPLES: &[(&[f32], &[f32])] = &[
            (&[1.0, 2.0, 3.0], &[3.0, 2.0, 1.0]),
            (&[], &[]),
            (&[1.0], &[1.0]),
        ];

        for &(input, expected) in SAMPLES {
            let input = input.iter().copied().map(Value::Number).collect();
            let expected = expected.iter().copied().map(Value::Number).collect();
            module.set_import("xs", Value::Tuple(input));
            assert_eq!(module.run().unwrap(), Value::Tuple(expected));
        }
    }
}