tulisp 0.29.0

An embeddable lisp interpreter.
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
//! Association-list (alist) primitives.
//!
//! An alist is a list of cons pairs, e.g. `((name . "Alice") (age . 30))`.
//! See [the Emacs Lisp manual] for the canonical reference.
//!
//! [the Emacs Lisp manual]: https://www.gnu.org/software/emacs/manual/html_node/elisp/Association-Lists.html

use crate::{
    Error, TulispContext, TulispObject,
    eval::{DummyEval, funcall},
    list,
};

/// Makes an alist from the given arguments.
pub fn alist_from<const N: usize>(input: [(TulispObject, TulispObject); N]) -> TulispObject {
    let mut builder = crate::cons::ListBuilder::new();
    for (key, value) in input.into_iter() {
        builder.push(TulispObject::cons(key, value));
    }
    builder.build()
}

/// Returns the first association for key in alist, comparing key against the
/// alist elements using testfn if it is a function, and equal otherwise.
pub fn assoc(
    ctx: &mut TulispContext,
    key: &TulispObject,
    alist: &TulispObject,
    testfn: Option<TulispObject>,
) -> Result<TulispObject, Error> {
    if !alist.listp() {
        return Err(Error::type_mismatch(format!(
            "expected alist. got: {}",
            alist
        )));
    }
    if let Some(testfn) = testfn {
        let pred = ctx.eval(&testfn)?;

        let testfn = |_1: &TulispObject, _2: &TulispObject| -> Result<bool, Error> {
            funcall::<DummyEval>(ctx, &pred, &list!(,_1.clone() ,_2.clone()).unwrap())
                .map(|x| x.is_truthy())
        };
        assoc_find(key, alist, testfn)
    } else {
        let testfn = |_1: &TulispObject, _2: &TulispObject| Ok(_1.equal(_2));
        assoc_find(key, alist, testfn)
    }
}

/// Finds the first association (key . value) by comparing key with alist
/// elements, and, if found, returns the value of that association.
pub fn alist_get(
    ctx: &mut TulispContext,
    key: &TulispObject,
    alist: &TulispObject,
    default_value: Option<TulispObject>,
    remove: Option<TulispObject>,
    testfn: Option<TulispObject>,
) -> Result<TulispObject, Error> {
    // The REMOVE arg makes `(setf (alist-get …) nil)` delete an
    // entry; since `setf` isn't implemented yet, accepting a non-nil
    // REMOVE silently would miss the user's intent. Error explicitly
    // rather than ignoring.
    if let Some(remove) = remove
        && remove.is_truthy()
    {
        return Err(Error::not_implemented(
            "alist-get: REMOVE argument is not implemented (no `setf` support yet)".to_string(),
        ));
    }
    let x = assoc(ctx, key, alist, testfn)?;
    if x.is_truthy() {
        x.cdr()
    } else {
        Ok(default_value.unwrap_or_else(TulispObject::nil))
    }
}

fn assoc_find(
    key: &TulispObject,
    alist: &TulispObject,
    mut testfn: impl FnMut(&TulispObject, &TulispObject) -> Result<bool, Error>,
) -> Result<TulispObject, Error> {
    // Floyd's tortoise / hare: hare advances two cells per step,
    // testing each one; tortoise advances one. If they ever land on
    // the same cell, the alist is circular (e.g. built via `setcdr`)
    // and we'd otherwise infloop. Mirrors `lists::length`.
    let mut slow = alist.clone();
    let mut fast = alist.clone();
    loop {
        for _ in 0..2 {
            if !fast.consp() {
                return Ok(TulispObject::nil());
            }
            let entry = fast.car()?;
            // Match Emacs: silently skip non-cons elements rather than
            // erroring on `caar`. So `(assoc 'b '(1 (b . 2)))` finds
            // the pair instead of crashing on the leading `1`.
            if entry.consp() {
                let entry_key = entry.car()?;
                if testfn(&entry_key, key)? {
                    return Ok(entry);
                }
            }
            fast = fast.cdr()?;
        }
        slow = slow.cdr()?;
        if slow.eq_ptr(&fast) {
            return Err(Error::out_of_range("Circular alist".to_string()));
        }
    }
}

/// Conversion between a Rust struct and a Lisp alist.
///
/// Values in the alist are treated as already-evaluated lisp objects
/// and passed through to the field types' `TryFrom<TulispObject>`
/// impls without further evaluation:
///
/// ```ignore
/// let cfg = MyType::from_alist(&mut ctx, &obj)?;
/// ```
///
/// Unlike [`Plistable`](crate::Plistable), there is no `Alist<T>`
/// wrapper for use as a [`defun`](crate::TulispContext::defun)
/// argument — alists arrive as a single value, not as a flat
/// keyword-argument list, so they are passed through normal
/// [`TulispObject`] argument types and converted via [`from_alist`]
/// inside the function body:
///
/// ```ignore
/// ctx.defun("apply-config", |obj: TulispObject| -> Result<(), Error> {
///     let cfg = Config::from_alist(/* ctx? */, &obj)?;
///     // ...
/// });
/// ```
///
/// (Because `from_alist` takes a `&mut TulispContext` to intern field
/// keys, you'll need a closure form that includes ctx as the first
/// parameter — see [`TulispContext::defun`].)
///
/// The [`AsAlist!`](macro@crate::AsAlist) macro generates both
/// `from_alist` and `into_alist` from a struct definition.
///
/// [`from_alist`]: Self::from_alist
pub trait Alistable {
    /// Deserialize an already-evaluated lisp alist (a list of dotted
    /// pairs) into `Self`. Each value is passed through as-is, with no
    /// further evaluation.
    fn from_alist(ctx: &mut TulispContext, obj: &TulispObject) -> Result<Self, Error>
    where
        Self: Sized;

    /// Serialize `self` into a Lisp alist of dotted pairs.
    fn into_alist(self, ctx: &mut TulispContext) -> TulispObject;
}

/// Derive [`Alistable`] for a struct.
///
/// # Syntax
///
/// ```text
/// AsAlist! {
///     [attributes]
///     [pub] struct Name {
///         [field_vis] field[<"key-name">]: Type [{= default}],
///         ...
///     }
/// }
/// ```
///
/// - Each field maps to a symbol key in the alist. By default the key
///   is `stringify!(field)`. Use `field<"custom-name">` to override.
/// - A field with `{= expr}` is optional; if absent from the alist the
///   default expression is used.
/// - A field without a default is required; a missing key is an error.
///
/// # Example
///
/// ```rust
/// use tulisp::{TulispContext, Alistable, AsAlist};
///
/// AsAlist! {
///     struct Person {
///         name: String,
///         age: i64 {= 0},
///     }
/// }
///
/// let mut ctx = TulispContext::new();
/// ctx.eval_string(r#"(setq alice '((name . "Alice") (age . 30)))"#).unwrap();
/// let alice_obj = ctx.eval_string("alice").unwrap();
/// let alice = Person::from_alist(&mut ctx, &alice_obj).unwrap();
/// assert_eq!(alice.name, "Alice");
/// assert_eq!(alice.age, 30);
/// ```
#[macro_export]
macro_rules! AsAlist {
    (@key-name
        $field:ident<$field_key:literal>) => {
        $field_key
    };
    (@key-name $field:ident) => {
        stringify!($field)
    };

    (@missing-field $key_name:expr, $default:expr) => {
        Ok($default)
    };
    (@missing-field $key_name:expr,) => {
        Err($crate::Error::alist_error(concat!("Missing ", $key_name, " field")))
    };

    (@extract-field $value:ident, None) => {
        if $value.null() {
            None
        } else {
            Some($value.try_into()?)
        }
    };

    (@extract-field $value:ident, Some($e: expr)) => {
        if $value.null() {
            None
        } else {
            Some($value.try_into()?)
        }
    };

    (@extract-field $value:ident, $e: expr) => {
        $value.try_into()?
    };

    (@extract-field $value:ident) => {
        $value.try_into()?
    };

    (
        $( #[$meta:meta] )*
        $vis:vis struct $struct_name:ident {
            $(
                $( #[$($field_meta:tt)+] )*
                $field_vis:vis $field:ident$(<$field_key:literal>)? : $type:ty
                $({= $($default:tt)+ })?
            ),+ $(,)?
        }
    ) => {

        $( #[$meta] )*
        $vis struct $struct_name {

            $($( #[$($field_meta)+] )* $field_vis $field: $type),+
        }

        impl $crate::Alistable for $struct_name {
            fn from_alist(
                ctx: &mut TulispContext, alist: &$crate::TulispObject
            ) -> Result<Self, $crate::Error> {
                #[derive(Default)]
                struct Builder {
                    $($field: Option<$type>),+
                }

                impl Builder {
                    fn build(self) -> Result<$struct_name, $crate::Error> {
                        Ok($struct_name {
                            $($field: if let Some(f) = self.$field { f } else {
                                $crate::AsAlist!(
                                    @missing-field
                                    $crate::AsAlist!(@key-name $field $(<$field_key>)?),
                                    $( $($default)+ )?
                                )?}),+
                        })
                    }
                }

                let symbols = $crate::intern!(ctx => {
                    $($field: $crate::AsAlist!(@key-name $field $(<$field_key>)?)),+
                });

                let mut builder = Builder::default();

                for entry in alist.base_iter() {
                    if !entry.consp() {
                        return Err($crate::Error::alist_error(format!(
                            "Alist entry is not a cons pair: {}",
                            entry
                        )));
                    }
                    let key = entry.car()?;
                    let value = entry.cdr()?;
                    $(if key.eq(&symbols.$field) {
                        builder.$field = Some($crate::AsAlist!(@extract-field value $(, $($default)+)?));
                    } else)+ {
                        return Err($crate::Error::alist_error(format!(
                            "Unexpected key in alist: {}",
                            key
                        )));
                    }
                }

                builder.build()
            }

            fn into_alist(self, ctx: &mut TulispContext) -> $crate::TulispObject {
                let symbols = $crate::intern!(ctx => {
                    $($field: $crate::AsAlist!(@key-name $field $(<$field_key>)?)),+
                });

                $crate::alist::alist_from([
                    $((symbols.$field.clone(), self.$field.into())),+
                ])
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use super::{alist_from, alist_get};
    use crate::{Alistable, Error, TulispContext};

    #[test]
    fn test_alist() -> Result<(), Error> {
        let mut ctx = TulispContext::new();
        let a = ctx.intern("a");
        let b = ctx.intern("b");
        let c = ctx.intern("c");
        let d = ctx.intern("d");
        let list = alist_from([
            (a.clone(), 20.into()),
            (b.clone(), 30.into()),
            (c.clone(), 40.into()),
        ]);
        assert!(alist_get(&mut ctx, &b, &list, None, None, None)?.equal(&30.into()));
        assert!(alist_get(&mut ctx, &d, &list, None, None, None)?.null());
        Ok(())
    }

    AsAlist! {
        #[derive(Default, Debug)]
        struct Person {
            /// The person's first name
            name<"first-name">: String,

            /// The person's age
            age: i64,

            /// The person's addresses
            addr: Vec<String>,

            /// The person's education (optional)
            education<"edu">: Option<String> {= None},

            /// The person's current place (optional, default is "Home")
            place: Option<String> {= Some("Home".to_string())},

            /// Optional, default 42.
            answer: i64 {= 42},
        }
    }

    #[test]
    fn test_alistable_from_lisp_value_no_eval() -> Result<(), Error> {
        let mut ctx = TulispContext::new();
        ctx.eval_string(
            r#"(setq x '((first-name . "Bob")
                         (age . 25)
                         (addr . ("Main St" "Oak Ave"))
                         (place . "Office")))"#,
        )?;
        let x = ctx.eval_string("x")?;

        let p = Person::from_alist(&mut ctx, &x)?;
        assert_eq!(p.name, "Bob");
        assert_eq!(p.age, 25);
        assert_eq!(p.addr, vec!["Main St".to_string(), "Oak Ave".to_string()]);
        assert_eq!(p.place.as_deref(), Some("Office"));
        // `edu` is omitted — its default kicks in.
        assert_eq!(p.education, None);
        Ok(())
    }

    #[test]
    fn test_alistable_round_trip() -> Result<(), Error> {
        let mut ctx = TulispContext::new();
        let p = Person {
            name: "Carol".into(),
            age: 40,
            addr: vec!["Pine St".into()],
            education: None,
            place: Some("Home".into()),
            answer: 42,
        };
        let obj = p.into_alist(&mut ctx);
        let q = Person::from_alist(&mut ctx, &obj)?;
        assert_eq!(q.name, "Carol");
        assert_eq!(q.age, 40);
        assert_eq!(q.addr, vec!["Pine St".to_string()]);
        // None serializes as nil; the macro now reads nil back as None
        // for optional fields rather than erroring on `try_into::<T>`.
        assert_eq!(q.education, None);
        assert_eq!(q.place.as_deref(), Some("Home"));
        assert_eq!(q.answer, 42);
        Ok(())
    }

    #[test]
    fn test_alistable_explicit_nil_is_none() -> Result<(), Error> {
        // Optional fields explicitly set to nil in the alist resolve
        // to None, regardless of what default the field declared.
        let mut ctx = TulispContext::new();
        ctx.eval_string(
            r#"(setq x '((first-name . "Bob")
                          (age . 25)
                          (addr . nil)
                          (place . nil)))"#,
        )?;
        let x = ctx.eval_string("x")?;
        let p = Person::from_alist(&mut ctx, &x)?;
        assert_eq!(p.place, None);
        // `edu` is absent → its `None` default kicks in.
        assert_eq!(p.education, None);
        Ok(())
    }

    #[test]
    fn test_alistable_missing_required_field() {
        let mut ctx = TulispContext::new();
        ctx.eval_string(r#"(setq x '((first-name . "Bob") (addr)))"#)
            .unwrap();
        let x = ctx.eval_string("x").unwrap();
        let err = Person::from_alist(&mut ctx, &x).unwrap_err();
        let msg = err.format(&ctx);
        assert!(msg.contains("Missing age field"), "got: {msg}");
    }

    #[test]
    fn test_alistable_unexpected_key() {
        let mut ctx = TulispContext::new();
        ctx.eval_string(r#"(setq x '((first-name . "Bob") (age . 5) (addr) (other . 1)))"#)
            .unwrap();
        let x = ctx.eval_string("x").unwrap();
        let err = Person::from_alist(&mut ctx, &x).unwrap_err();
        let msg = err.format(&ctx);
        assert!(msg.contains("Unexpected key in alist"), "got: {msg}");
    }

    #[test]
    fn test_assoc_detects_cycle() {
        // Build a circular alist via setcdr: the cdr of the last cons
        // points back to the head, so a naive walk never terminates.
        let mut ctx = TulispContext::new();
        ctx.eval_string(
            r#"
            (setq x (list (cons 'a 1) (cons 'b 2) (cons 'c 3)))
            (setcdr (cdr (cdr x)) x)
            "#,
        )
        .unwrap();
        let x = ctx.eval_string("x").unwrap();
        let key = ctx.intern("missing");
        let err = super::assoc(&mut ctx, &key, &x, None).unwrap_err();
        let msg = err.format(&ctx);
        assert!(msg.contains("Circular alist"), "got: {msg}");
    }
}