Starlight-JS / starlight

JS engine in Rust
https://teletype.in/@starlight-js
Mozilla Public License 2.0
511 stars 9 forks source link

Question about functions #37

Closed andrieshiemstra closed 3 years ago

andrieshiemstra commented 3 years ago

Hi,

I'm working on creating callbacks (JsFunctions from Fn closures) from rust.

With quickjs and spidermonkey i register those in a map with a anique id and then create a function with some metadata

In quickjs there is JS_NewCFunctionData which calls a function with a data JSObject. In spidermonkey i just add a variable to the Function object which is passed to the native function (like as arguments.callee)

Currently with starlight i'd have to bind the function to a second JsValue so i can access the metadata JsValue as this.

All three methods work, but are cumbersome.

Would it be ok if i added a fifth option to functions::FuncType something like this?

Closure<JsClosureFunction>

struct JsClosureFunction {
    pub(crate) closure: Fn(&mut Runtime, arguments: &Arguments) -> Result<JsValue, JsValue>
}

Or do you have an other suggestion?

playXE commented 3 years ago

Sounds reasonable but I don't know how these closures can be serialized then or panic should be triggered when someone tries to serialize runtime with native closure instance?

playXE commented 3 years ago

If you're going to add new type for functions then you have to modify these files: function.rs: https://github.com/Starlight-JS/starlight/blob/dev/crates/starlight/src/vm/function.rs#L162 to add support for invoking native closures. serializer.rs: https://github.com/Starlight-JS/starlight/blob/dev/crates/starlight/src/gc/snapshot/serializer.rs#L423 - should panic when native closure is serialized.

playXE commented 3 years ago

Closed since #47