'extensible objects' in a Lisp interpreter

This question does not have a right/wrong answer. I am mainly looking for advice of the form "look at how crate XYZ solved it / look at this technique."

I have a basic Lisp interpreter running in Rust. It has something like a

pub struct LispValue {
  Symbol(String),
  I32(i32),
  F32(f32),
  ...
}

Now for handling Rust <-> Lisp interop, I want a flexible way to add Rust types defined OUTSIDE of the lisp crates to be added. Current idea is to do something like:

pub struct LispValue {
  ...
  RustEnum(Rc<dyn RustEnumT>),
  RustStruct(Rc<dyn RustStructT>),
}

The goal here is I want to define a RustEnumT and a RustStructT which allows the runtime to dynamically query the object things like:

  • what fields do you have (Struct)
  • get that field (Struct)
  • what arms do you have (Enum)
    ...

This way, the LispValue can be 'extended' with Rust structs/enums that are not defined in the Lisp crate itself.

I am sure others have run into this problem before. What are written-in-Rust-interpreters have clean / clever solutions to this problem ?

Lua has a similar concept where you can make native objects accessible to Lua code. It doesn't quite do what you suggested by letting you look at the fields/arms of the type, but instead lets the type define a method that gets called every time you access a field on the native object, and it can return whatever it wants.

pub struct LuaValue {
  ...
  ExternalValue(Rc<dyn LuaExternalValueT>)
}

pub trait LuaExternalValueT {
  fn get_field(s: &str) -> Option<LuaValue>
}

^-- something like this ?

Yeah sorta. To be more precise, they aren't called fields but instead values in a table/map, but fundamentally it's the same idea. They also have a way to call the external value as if it was a function object, and maybe other things - I don't remember.

I know very little Lua, but IIRC they also have 'metatables' Programming in Lua : 13.4.1 which also makes it easy to dynamically query for all the keys.

EDIT: Sorry, should be GitHub - lonng/lua-rs: Pure Rust implementation of Lua compiler.

Is https://crates.io/crates/lua-rs the most mature pure-rust lua impl? (I'm trying to minimize external C dependencies to ensure everything builds nicely on wasm32 too.)

I don't know.

That is not a pure Rust Lua implementation.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.