Skip to main content

TulispConvertible

Trait TulispConvertible 

Source
pub trait TulispConvertible {
    // Required methods
    fn from_tulisp(value: &TulispObject) -> Result<Self, Error>
       where Self: Sized;
    fn into_tulisp(self) -> TulispObject;
}
Expand description

Bidirectional conversion between Rust types and TulispObject.

This trait is the bridge between Rust and Lisp values. Every argument type and return type used with TulispContext::defun must implement it.

§Built-in implementations

Rust typeLisp type
i64integer
f64float
boolt / nil
Stringstring
Numberinteger or float
Vec<T>list
TulispObjectany (pass-through)
Shared<dyn TulispAny>any (to support custom types that implement TulispConvertible)

§Implementing for custom types

For structs that map to Lisp plists, use the AsPlist! macro instead of implementing this trait by hand.

For arbitrary Rust types that have no natural Lisp representation, store the value as an opaque TulispAny object using Shared::new. Any type that implements Clone, Display, and Any qualifies (the blanket impl of TulispAny covers all of these automatically).

use std::fmt;
use tulisp::{TulispConvertible, TulispObject, Shared, Error};

#[derive(Clone)]
struct Point { x: i64, y: i64 }

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(Point {} {})", self.x, self.y)
    }
}

impl TulispConvertible for Point {
    fn from_tulisp(value: &TulispObject) -> Result<Self, Error> {
        value
            .as_any()
            .ok()
            .and_then(|v| v.downcast_ref::<Point>().cloned())
            .ok_or_else(|| Error::type_mismatch("Expected Point"))
    }
    fn into_tulisp(self) -> TulispObject {
        Shared::new(self).into()
    }
}

let mut ctx = tulisp::TulispContext::new();
ctx.defun("make-point", |x: i64, y: i64| Point { x, y });
ctx.defun("point-x", |p: Point| p.x);
assert_eq!(ctx.eval_string("(point-x (make-point 3 4))").unwrap().to_string(), "3");

Required Methods§

Source

fn from_tulisp(value: &TulispObject) -> Result<Self, Error>
where Self: Sized,

Converts a Lisp value into this Rust type.

Returns an error if the value has the wrong Lisp type.

Source

fn into_tulisp(self) -> TulispObject

Converts this Rust value into a Lisp value.

Implementations on Foreign Types§

Source§

impl TulispConvertible for bool

Source§

impl TulispConvertible for f64

Source§

impl TulispConvertible for i64

Source§

impl TulispConvertible for String

Source§

impl<T> TulispConvertible for Vec<T>

Implementors§