grift_eval 1.4.0

Lisp evaluator for the Grift Scheme language
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
//! Helper macros for the Lisp evaluator.
//!
//! This module contains macros for:
//! - Argument extraction from Lisp lists
//! - Builtin predicate and operation helpers
//! - Native function registration

// ============================================================================
// Helper Macros for Code Deduplication
// ============================================================================

/// Macro to extract arguments from a Lisp list using car/cdr.
///
/// This macro extracts multiple arguments from a list, shadowing the `args`
/// variable after each extraction.
///
/// # Example
/// 
/// `extract_args!(self, args, a, b, c)` extracts three arguments from `args`.
#[macro_export]
macro_rules! extract_args {
    ($self:expr, $args:ident, $var:ident) => {
        let $var = $self.lisp.car($args)?;
    };
    ($self:expr, $args:ident, $var:ident, $($rest:ident),+) => {
        let $var = $self.lisp.car($args)?;
        #[allow(unused_variables)]
        let $args = $self.lisp.cdr($args)?;
        $crate::extract_args!($self, $args, $($rest),+)
    };
}

/// Macro for unary predicate builtins.
///
/// Many builtins follow the pattern of extracting one argument and returning
/// a boolean based on some predicate on the value.
///
/// # Example
/// 
/// `builtin_unary_pred!(self, args, |v| v.is_nil())` extracts one argument
/// and returns a boolean result of the predicate.
#[macro_export]
macro_rules! builtin_unary_pred {
    ($self:expr, $args:expr, $check:expr) => {{
        let arg = $self.lisp.car($args)?;
        let val = $self.lisp.get(arg)?;
        $self.lisp.boolean($check(val)).map_err(Into::into)
    }};
}

/// Macro for numeric predicate builtins.
///
/// Extracts one numeric argument (integer or float) and returns a boolean based on the predicate.
/// For integer arguments, passes isize to int_check. For float arguments, passes fsize to float_check.
///
/// # Example
/// 
/// `builtin_numeric_pred!(self, args, call_expr, |n| n == 0, |f| f == 0.0)` 
#[macro_export]
macro_rules! builtin_numeric_pred {
    ($self:expr, $args:expr, $call_expr:expr, |$n:ident| $int_check:expr, |$f:ident| $float_check:expr) => {{
        let arg = $self.lisp.car($args)?;
        match $self.lisp.get(arg)? {
            Value::Number($n) => $self.lisp.boolean($int_check).map_err(Into::into),
            Value::Float($f) => $self.lisp.boolean($float_check).map_err(Into::into),
            v => Err($self.type_error($call_expr, "number", v.type_name())),
        }
    }};
    ($self:expr, $args:expr, $call_expr:expr, |$n:ident| $check:expr) => {{
        let $n = $self.get_int($self.lisp.car($args)?, $call_expr)?;
        $self.lisp.boolean($check).map_err(Into::into)
    }};
}

/// Macro for rounding operations.
///
/// For integers, these are identity operations. For floats, applies the float operation.
///
/// # Example
/// 
/// `builtin_rounding_op!(self, args, call_expr, |f| float_floor(f))` 
#[macro_export]
macro_rules! builtin_rounding_op {
    ($self:expr, $args:expr, $call_expr:expr, $float_op:expr) => {{
        let arg = $self.lisp.car($args)?;
        match $self.lisp.get(arg)? {
            Value::Number(n) => $self.lisp.number(n).map_err(Into::into),
            Value::Float(f) => {
                let result = $float_op(f);
                $self.lisp.float(result).map_err(Into::into)
            }
            v => Err($self.type_error($call_expr, "number", v.type_name())),
        }
    }};
}

/// Macro for binary integer operations with division-by-zero check.
///
/// Extracts two integer arguments, checks for division by zero, and applies the operation.
/// Only works on exact integers (no float promotion).
///
/// # Example
/// 
/// `builtin_div_op!(self, args, call_expr, |a, b| a / b)` performs integer division.
#[macro_export]
macro_rules! builtin_div_op {
    ($self:expr, $args:expr, $call_expr:expr, $op:expr) => {{
        let a = $self.get_int($self.lisp.car($args)?, $call_expr)?;
        let b = $self.get_int($self.lisp.car($self.lisp.cdr($args)?)?, $call_expr)?;
        if b == 0 {
            return Err($self.make_error($crate::ErrorKind::DivisionByZero, $call_expr));
        }
        $self.lisp.number($op(a, b)).map_err(Into::into)
    }};
}

/// Macro for unary numeric operations (supports both int and float).
///
/// Extracts one argument. If integer, applies int_op and returns Number.
/// If float, applies float_op and returns Float.
///
/// # Example
/// 
/// `builtin_unary_num!(self, args, call_expr, |n: isize| n.abs(), |f: fsize| f.abs())` 
#[macro_export]
macro_rules! builtin_unary_num {
    ($self:expr, $args:expr, $call_expr:expr, |$n:ident : isize| $int_op:expr, |$f:ident : fsize| $float_op:expr) => {{
        let arg = $self.lisp.car($args)?;
        match $self.lisp.get(arg)? {
            Value::Number($n) => $self.lisp.number($int_op).map_err(Into::into),
            Value::Float($f) => $self.lisp.float($float_op).map_err(Into::into),
            v => Err($self.type_error($call_expr, "number", v.type_name())),
        }
    }};
}

/// Macro for unary integer operations.
///
/// Extracts one integer argument, applies a transformation, and returns a number.
/// Also accepts floats, truncating to integer first.
///
/// # Example
/// 
/// `builtin_unary_int!(self, args, call_expr, |n| n.abs())` returns absolute value.
#[macro_export]
macro_rules! builtin_unary_int {
    ($self:expr, $args:expr, $call_expr:expr, $op:expr) => {{
        let n = $self.get_int($self.lisp.car($args)?, $call_expr)?;
        $self.lisp.number($op(n)).map_err(Into::into)
    }};
}

/// Macro for unary char-to-integer conversion.
///
/// Extracts one character argument and returns its Unicode code point as a number.
#[macro_export]
macro_rules! builtin_char_to_int {
    ($self:expr, $args:expr, $call_expr:expr) => {{
        let c = $self.get_char($self.lisp.car($args)?, $call_expr)?;
        $self.lisp.number(c as isize).map_err(Into::into)
    }};
}

/// Macro for unary character transformation.
///
/// Extracts one character argument, applies ASCII transformation, and returns a char.
///
/// # Example
/// 
/// `builtin_char_transform!(self, args, call_expr, 'a', 'z', b'a', b'A')` does uppercase.
#[macro_export]
macro_rules! builtin_char_transform {
    ($self:expr, $args:expr, $call_expr:expr, $from_low:expr, $from_high:expr, $from_base:expr, $to_base:expr) => {{
        let c = $self.get_char($self.lisp.car($args)?, $call_expr)?;
        let result = if c >= $from_low && c <= $from_high {
            ((c as u8) - $from_base + $to_base) as char
        } else {
            c
        };
        $self.lisp.char(result).map_err(Into::into)
    }};
}

/// Macro for binary numeric comparison (returns boolean).
///
/// Supports mixed int/float comparisons with automatic promotion.
/// Used in apply_binary_builtin for comparison operations.
#[macro_export]
macro_rules! binary_int_cmp {
    ($self:expr, $a:expr, $b:expr, $call_expr:expr, $cmp:expr) => {{
        let val_a = $self.lisp.get($a)?;
        let val_b = $self.lisp.get($b)?;
        let result = match (val_a, val_b) {
            (Value::Number(x), Value::Number(y)) => $cmp(x as $crate::fsize, y as $crate::fsize),
            (Value::Number(x), Value::Float(y)) => $cmp(x as $crate::fsize, y),
            (Value::Float(x), Value::Number(y)) => $cmp(x, y as $crate::fsize),
            (Value::Float(x), Value::Float(y)) => $cmp(x, y),
            (v, _) if !v.is_number() => return Err($self.type_error($call_expr, "number", v.type_name())),
            (_, v) => return Err($self.type_error($call_expr, "number", v.type_name())),
        };
        $self.lisp.boolean(result).map_err(Into::into)
    }};
}

/// Macro for binary numeric arithmetic (returns number).
///
/// Supports mixed int/float arithmetic with automatic promotion to float.
/// Used in apply_binary_builtin for arithmetic operations.
#[macro_export]
macro_rules! binary_int_op {
    ($self:expr, $a:expr, $b:expr, $call_expr:expr, $int_op:expr, $float_op:expr) => {{
        let val_a = $self.lisp.get($a)?;
        let val_b = $self.lisp.get($b)?;
        match (val_a, val_b) {
            (Value::Number(x), Value::Number(y)) => {
                match $int_op(x, y) {
                    Some(n) => $self.lisp.number(n).map_err(Into::into),
                    None => Err($self.make_error($crate::ErrorKind::DivisionByZero, $call_expr)),
                }
            }
            (Value::Number(x), Value::Float(y)) => {
                $self.lisp.float($float_op(x as $crate::fsize, y)).map_err(Into::into)
            }
            (Value::Float(x), Value::Number(y)) => {
                $self.lisp.float($float_op(x, y as $crate::fsize)).map_err(Into::into)
            }
            (Value::Float(x), Value::Float(y)) => {
                $self.lisp.float($float_op(x, y)).map_err(Into::into)
            }
            (v, _) if !v.is_number() => Err($self.type_error($call_expr, "number", v.type_name())),
            (_, v) => Err($self.type_error($call_expr, "number", v.type_name())),
        }
    }};
}

/// Macro for binary division operations with zero check.
///
/// Supports mixed int/float division with automatic promotion.
/// Used in apply_binary_builtin for div/mod/rem operations.
#[macro_export]
macro_rules! binary_div_op {
    ($self:expr, $a:expr, $b:expr, $call_expr:expr, $int_op:expr, $float_op:expr) => {{
        let val_a = $self.lisp.get($a)?;
        let val_b = $self.lisp.get($b)?;
        match (val_a, val_b) {
            (Value::Number(x), Value::Number(y)) => {
                if y == 0 {
                    return Err($self.make_error($crate::ErrorKind::DivisionByZero, $call_expr));
                }
                $self.lisp.number($int_op(x, y)).map_err(Into::into)
            }
            (Value::Number(x), Value::Float(y)) => {
                if y == 0.0 {
                    return Err($self.make_error($crate::ErrorKind::DivisionByZero, $call_expr));
                }
                $self.lisp.float($float_op(x as $crate::fsize, y)).map_err(Into::into)
            }
            (Value::Float(x), Value::Number(y)) => {
                if y == 0 {
                    return Err($self.make_error($crate::ErrorKind::DivisionByZero, $call_expr));
                }
                $self.lisp.float($float_op(x, y as $crate::fsize)).map_err(Into::into)
            }
            (Value::Float(x), Value::Float(y)) => {
                if y == 0.0 {
                    return Err($self.make_error($crate::ErrorKind::DivisionByZero, $call_expr));
                }
                $self.lisp.float($float_op(x, y)).map_err(Into::into)
            }
            (v, _) if !v.is_number() => Err($self.type_error($call_expr, "number", v.type_name())),
            (_, v) => Err($self.type_error($call_expr, "number", v.type_name())),
        }
    }};
}

// ============================================================================
// Macro for Native Function Definition
// ============================================================================

/// Register a native Rust function as a Lisp builtin with automatic argument extraction.
///
/// This macro generates wrapper code that extracts typed arguments from
/// the Lisp argument list and calls your function. It transforms any Rust
/// function into a Lisp builtin that can be called from Lisp code.
///
/// # Basic Syntax
///
/// ```rust
/// use grift_eval::register_native;
///
/// // Define a function that adds two numbers
/// register_native!(add_two, (a: isize, b: isize) -> isize, {
///     a + b
/// });
///
/// // Define a function with no return value
/// register_native!(print_num, (n: isize) -> (), {
///     // In a real impl, you'd print n
///     ()
/// });
/// ```
///
/// # Stateful Functions
///
/// The macro can also be used for functions that access global static variables:
///
/// ```rust
/// use grift_eval::register_native;
/// use core::sync::atomic::{AtomicUsize, Ordering};
///
/// static MY_COUNTER: AtomicUsize = AtomicUsize::new(0);
///
/// register_native!(
///     native_increment,
///     () -> isize,
///     {
///         MY_COUNTER.fetch_add(1, Ordering::Relaxed) as isize
///     }
/// );
/// ```
///
/// # Limitations: Lisp Context Access
///
/// Due to Rust macro hygiene, the `lisp` and `args` identifiers are NOT directly
/// accessible inside the macro body. The macro is designed for simple functions
/// that work with extracted typed arguments and return simple types.
///
/// For functions that need full access to the Lisp context (creating values,
/// processing variadic arguments, etc.), define a regular function instead:
///
/// ```rust
/// use grift_eval::{Lisp, ArenaIndex, ArenaResult, FromLisp};
/// use grift_arena::ArenaResult as PwnResult;
///
/// fn my_custom_fn<const N: usize>(
///     lisp: &Lisp<N>,
///     args: ArenaIndex,
/// ) -> ArenaResult<ArenaIndex> {
///     // Full access to lisp and args
///     let a = isize::from_lisp(lisp, lisp.car(args)?)?;
///     let rest = lisp.cdr(args)?;
///     let b = isize::from_lisp(lisp, lisp.car(rest)?)?;
///     lisp.cons(lisp.number(a)?, lisp.number(b)?)
/// }
/// ```
///
/// # @with_lisp Variant
///
/// The `@with_lisp` variant allows the extracted arguments to shadow the `args`
/// variable, leaving the remaining argument list available.
///
/// # Generated Code
///
/// The macro generates a function with signature:
/// `fn name<const N: usize>(lisp: &Lisp<N>, args: ArenaIndex) -> ArenaResult<ArenaIndex>`
#[macro_export]
macro_rules! register_native {
    // ========================================================================
    // Standard variants - access statics directly in the body
    // ========================================================================

    // No arguments
    ($name:ident, () -> $ret:ty, $body:block) => {
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            _args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let _ = lisp;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Single argument
    ($name:ident, ($arg1:ident : $ty1:ty) -> $ret:ty, $body:block) => {
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, _rest): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Two arguments
    ($name:ident, ($arg1:ident : $ty1:ty, $arg2:ident : $ty2:ty) -> $ret:ty, $body:block) => {
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, rest): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let ($arg2, _rest): ($ty2, _) = $crate::extract_arg(lisp, rest)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Three arguments
    ($name:ident, ($arg1:ident : $ty1:ty, $arg2:ident : $ty2:ty, $arg3:ident : $ty3:ty) -> $ret:ty, $body:block) => {
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, rest): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let ($arg2, rest): ($ty2, _) = $crate::extract_arg(lisp, rest)?;
            let ($arg3, _rest): ($ty3, _) = $crate::extract_arg(lisp, rest)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Four arguments
    ($name:ident, ($arg1:ident : $ty1:ty, $arg2:ident : $ty2:ty, $arg3:ident : $ty3:ty, $arg4:ident : $ty4:ty) -> $ret:ty, $body:block) => {
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, rest): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let ($arg2, rest): ($ty2, _) = $crate::extract_arg(lisp, rest)?;
            let ($arg3, rest): ($ty3, _) = $crate::extract_arg(lisp, rest)?;
            let ($arg4, _rest): ($ty4, _) = $crate::extract_arg(lisp, rest)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // ========================================================================
    // @with_lisp variants - provide access to 'lisp' and 'args' in the 
    // function body for complex operations requiring the Lisp context.
    // ========================================================================

    // No arguments, with lisp access
    ($name:ident @with_lisp, () -> $ret:ty, $body:block) => {
        #[allow(unused_variables)]
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Single argument, with lisp access
    ($name:ident @with_lisp, ($arg1:ident : $ty1:ty) -> $ret:ty, $body:block) => {
        #[allow(unused_variables)]
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, args): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Two arguments, with lisp access
    ($name:ident @with_lisp, ($arg1:ident : $ty1:ty, $arg2:ident : $ty2:ty) -> $ret:ty, $body:block) => {
        #[allow(unused_variables)]
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, args): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let ($arg2, args): ($ty2, _) = $crate::extract_arg(lisp, args)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Three arguments, with lisp access
    ($name:ident @with_lisp, ($arg1:ident : $ty1:ty, $arg2:ident : $ty2:ty, $arg3:ident : $ty3:ty) -> $ret:ty, $body:block) => {
        #[allow(unused_variables)]
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, args): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let ($arg2, args): ($ty2, _) = $crate::extract_arg(lisp, args)?;
            let ($arg3, args): ($ty3, _) = $crate::extract_arg(lisp, args)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };

    // Four arguments, with lisp access
    ($name:ident @with_lisp, ($arg1:ident : $ty1:ty, $arg2:ident : $ty2:ty, $arg3:ident : $ty3:ty, $arg4:ident : $ty4:ty) -> $ret:ty, $body:block) => {
        #[allow(unused_variables)]
        pub fn $name<const N: usize>(
            lisp: &$crate::Lisp<N>,
            args: $crate::ArenaIndex,
        ) -> $crate::ArenaResult<$crate::ArenaIndex> {
            let ($arg1, args): ($ty1, _) = $crate::extract_arg(lisp, args)?;
            let ($arg2, args): ($ty2, _) = $crate::extract_arg(lisp, args)?;
            let ($arg3, args): ($ty3, _) = $crate::extract_arg(lisp, args)?;
            let ($arg4, args): ($ty4, _) = $crate::extract_arg(lisp, args)?;
            let result: $ret = $body;
            $crate::ToLisp::to_lisp(&result, lisp)
        }
    };
}