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

Ergonomic function-calling API #829

Merged
merged 8 commits into from
Dec 3, 2021
Merged

Ergonomic function-calling API #829

merged 8 commits into from
Dec 3, 2021

Conversation

dherman
Copy link
Collaborator

@dherman dherman commented Nov 24, 2021

This PR implements an ergonomic function-calling API using an options object and method chaining. It offers two new methods, JsFunction::call_with() and JsFunction::construct_with(), along with an Arguments trait that enables lightweight syntax for heterogeneously-typed arguments expressed as Rust tuples. It also uses type inference to downcast the result of the function call to an expected type. All together, this makes calling JS functions from Rust much more ergonomic.

Before:

let this = cx.undefined();
let args = vec![
    cx.number(17).upcast(),
    cx.string("hello").upcast()
];
let v: Handle<JsArray> = f.call(&mut cx, this, args)?
    .downcast_or_throw()?;

After:

let v: Handle<JsArray> = f
    .call_with(&cx)
    .args((cx.number(17), cx.string("hello"))
    .apply(&mut cx)?;

Previous attempts:

Also related:

@dherman dherman changed the base branch from main to next/0.10 November 24, 2021 21:57
@dherman dherman force-pushed the arguments-options-api branch from 0e6b8e5 to 856410d Compare December 1, 2021 08:12
@dherman dherman requested a review from kjvalencik December 1, 2021 08:13
src/types/function/mod.rs Outdated Show resolved Hide resolved
src/types/function/mod.rs Outdated Show resolved Hide resolved
src/types/function/mod.rs Outdated Show resolved Hide resolved
- Use undefined instead of null for default this
- Overloaded result type for `construct_with()`
- Tests for all of the above
@dherman dherman requested a review from kjvalencik December 3, 2021 19:06
@dherman dherman merged commit dae093f into next/0.10 Dec 3, 2021
@dherman dherman deleted the arguments-options-api branch December 3, 2021 23:09
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

Successfully merging this pull request may close these issues.

2 participants