Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplifying Function Binding #3799

Open
ahaoboy opened this issue Apr 9, 2024 · 4 comments
Open

Simplifying Function Binding #3799

ahaoboy opened this issue Apr 9, 2024 · 4 comments

Comments

@ahaoboy
Copy link
Contributor

ahaoboy commented Apr 9, 2024

Is it possible to use macros to convert normal rust functions to boa form, normal rust functions are more general and easier to test

fn add(a: i32, b: i32) -> i32 {
    a + b
}
fn __boa_add(_: &JsValue, args: &[JsValue], context: &mut Context) -> JsResult<JsValue> {
    let a = args[0].to_i32(context).unwrap();
    let b = args[1].to_i32(context).unwrap();
    Ok(boa_engine::JsValue::Integer(a + b))
}
@jedel1043
Copy link
Member

See #3770 for the main discussion, and @hansl is currently working on precisely this. (Which we are really grateful for!)

@ahaoboy
Copy link
Contributor Author

ahaoboy commented Apr 9, 2024

There are some differences, I need to add the rust function to js in a way similar to rquickjs.

fn add(a: i32, b: i32) -> i32 {
    a + b
}

global
  .set(
      "add",
      Function::new(ctx.clone(), add )
          .unwrap()
          .with_name("add")
          .unwrap(),
  )

I wanted a way to add rust functions directly using register_global_property

fn add(a: i32, b: i32) -> i32 {
    a + b
}

 context
    .register_global_property(js_string!( "add" ),
    add,
    Attribute::all())
    .unwrap();

In mpv-boa, I've implemented a similar macros , but it's not perfect and still requires the use of macros to generate a boa-style function

@hansl
Copy link
Contributor

hansl commented Apr 9, 2024

With my PR that example should work almost right out. I think the only thing might be missing a Into<JsValue> for NativeFunction and an add.into_js_function_copied() when passing that to register_global_property. I think we could make the interface of register_global_property better for functions, but overall this should work with minimal boilerplate with the boa_interop crate.

@hansl
Copy link
Contributor

hansl commented Apr 9, 2024

Oh the PR is not in yet; #3773

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants