Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/rust/jsg-test/tests/function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,32 @@ fn call_with_args() {
});
}

/// `Local<Function>::call` passes every argument, in order, and only those.
#[test]
fn call_passes_the_arguments_in_order() {
let harness = crate::Harness::new();
harness.run_in_context(|lock, ctx| {
let value = ctx
.eval_raw(lock, "(function() { return [...arguments].join(); })")
.unwrap();
let func = v8::Local::<v8::Function>::try_from(value).unwrap();

let result = func.call(lock, None, &[])?;
assert_eq!(String::from_js(lock, result)?, "");
let args = [
1_i32.to_js(lock)?,
2_i32.to_js(lock)?,
3_i32.to_js(lock)?,
4_i32.to_js(lock)?,
];
let result = func.call(lock, None, &args)?;
assert_eq!(String::from_js(lock, result)?, "1,2,3,4");
let result = func.call(lock, None, &args[1..3])?;
assert_eq!(String::from_js(lock, result)?, "2,3");
Ok(())
});
}

/// `Local<Function>::call` returning a string via `FromJS`.
#[test]
fn call_returns_string() {
Expand Down
86 changes: 86 additions & 0 deletions src/rust/jsg-test/tests/function_new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,11 @@ impl ThrowingCreator {
let throws: v8::Local<v8::Function> = throws.try_into().unwrap();
let err = throws.call(lock, None, &[]).unwrap_err();
assert!(err.is_pending());
assert!(
v8::Function::from_callback(lock, empty_callback)
.unwrap_err()
.is_pending()
);
let err = v8::Function::new(lock, (), |lock, (), _args| Ok(lock.undefined())).unwrap_err();
self.saw_pending.set(err.is_pending());
Err(err)
Expand Down Expand Up @@ -438,3 +443,84 @@ fn data_of_reachable_function_is_dropped_with_its_isolate() {
assert_eq!(TEARDOWN_DATA_DROPS.load(Ordering::SeqCst), 1);
assert_eq!(TEARDOWN_LEAF_DROPS.load(Ordering::SeqCst), 1);
}

/// A V8 function callback that does nothing.
#[expect(
unsafe_code,
reason = "a V8 function callback, which reads nothing of its arguments"
)]
unsafe extern "C" fn empty_callback(_info: *mut v8::ffi::FunctionCallbackInfo) {}

#[test]
fn function_from_an_extern_callback_returns_undefined() {
crate::Harness::new().run_in_context(|lock, ctx| {
let empty = v8::Function::from_callback(lock, empty_callback).unwrap();
ctx.set_global(lock, "empty", v8::Local::<v8::Value>::from(empty));
assert_eq!(
ctx.eval::<String>(lock, "String(empty(1, 2))").unwrap(),
"undefined"
);
Ok(())
});
}

#[test]
fn function_from_a_closure_callback_gets_its_arguments() {
crate::Harness::new().run_in_context(|lock, ctx| {
let second = v8::Function::from_callback(
lock,
jsg::function_callback(|_lock, args| {
let value = args.get(1);
args.set_return_value(value);
}),
)
.unwrap();
ctx.set_global(lock, "second", v8::Local::<v8::Value>::from(second));
assert_eq!(
ctx.eval::<String>(lock, "second('a', 'b', 'c')").unwrap(),
"b"
);
Ok(())
});
}

/// The function has no signature and an empty name and `length`, and `new` calls it too.
#[test]
fn function_from_a_callback_has_the_shape_of_a_plain_v8_function() {
crate::Harness::new().run_in_context(|lock, ctx| {
let empty = v8::Function::from_callback(lock, empty_callback).unwrap();
ctx.set_global(lock, "empty", v8::Local::<v8::Value>::from(empty));
let code = "[typeof empty, JSON.stringify(empty.name), empty.length, \
typeof new empty(), String(empty.call(42))].join()";
assert_eq!(
ctx.eval::<String>(lock, code).unwrap(),
"function,\"\",0,object,undefined"
);
Ok(())
});
}

#[test]
fn panic_in_a_from_callback_closure_is_an_internal_error() {
crate::Harness::new().run_in_context(|lock, ctx| {
let panics = v8::Function::from_callback(
lock,
jsg::function_callback(|_lock, _args| {
panic!("intentional panic in a function callback");
}),
)
.unwrap();
ctx.set_global(lock, "panics", v8::Local::<v8::Value>::from(panics));
let err = ctx
.eval::<bool>(lock, "panics()")
.unwrap_err()
.unwrap_jsg_err(lock);
assert!(err.message.contains("internal error"), "{}", err.message);
assert!(
!err.message.contains("intentional panic"),
"{}",
err.message
);
Ok(())
});
}
20 changes: 20 additions & 0 deletions src/rust/jsg/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -999,6 +999,26 @@ or a JavaScript exception is pending, `Function::new` creates nothing and return
propagating. As with the functions C++ JSG wraps, the function's `name` is empty, its `length` is
0, and it can be called with `new`.

A function that needs no state can skip the `Wrappable`: `v8::Function::from_callback(lock,
callback)` creates one that V8 calls `callback` for directly, like C++ `v8::Function::New()` with
a plain callback, so a call costs no more than V8's own. Its data is `undefined` and it has no
signature, so `this` can be any value; like a `Function::new` function, its `name` is empty, its
`length` is 0 and it can be called with `new`. It fails as `Function::new` does. Build `callback`
with `jsg::function_callback` from a closure that captures nothing: the closure gets a lock per
call and sets its result with `set_return_value`, and a panic in it throws an internal error and
terminates execution. An `extern "C"` callback also works, but it gets no lock and no panic
handling, so a panic in it aborts the process.

```rust
let second = v8::Function::from_callback(
lock,
jsg::function_callback(|_lock, args| {
let value = args.get(1);
args.set_return_value(value);
}),
)?;
```

### Conventions of the `v8` module

The `v8` module takes handles and returns handles. Converting between a Rust value and a
Expand Down
12 changes: 6 additions & 6 deletions src/rust/jsg/ffi.c++
Original file line number Diff line number Diff line change
Expand Up @@ -648,17 +648,17 @@ MaybeLocal local_function_call(
auto context = isolate->GetCurrentContext();
auto fn = local_as_ref_from_ffi<v8::Function>(function);
auto receiver = local_as_ref_from_ffi<v8::Value>(recv);

v8::LocalVector<v8::Value> v8Args(isolate, args.size());
for (size_t i = 0; i < args.size(); i++) {
v8Args[i] = local_as_ref_from_ffi<v8::Value>(args[i]);
}
// A Local has the layout of a v8::Local (see ffi-inl.h), so the arguments pass as they are,
// without a copy. V8 takes them as non-const but only reads them.
KJ_REQUIRE(args.size() <= INT_MAX, "too many arguments for a JavaScript call", args.size());
Comment thread
bartlomieju marked this conversation as resolved.
Resolved
auto* v8Args = const_cast<v8::Local<v8::Value>*>(
args.empty() ? nullptr : &local_as_ref_from_ffi<v8::Value>(args[0]));

// No TryCatch: what the function throws stays pending and propagates once the Rust caller
// returns to JavaScript, as with C++ JSG. V8 then still reports it where it was thrown, and
// predicts whether JavaScript catches it (which DevTools' "pause on uncaught exceptions" uses)
// by walking the whole stack.
return maybe_local_to_ffi(fn->Call(context, receiver, v8Args.size(), v8Args.data()));
return maybe_local_to_ffi(fn->Call(context, receiver, static_cast<int>(args.size()), v8Args));
}

MaybeLocal function_new(Isolate* isolate, size_t callback, const Local& data) {
Expand Down
33 changes: 33 additions & 0 deletions src/rust/jsg/v8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2446,6 +2446,39 @@ impl Function {
Ok(function)
}

/// Creates a JavaScript function that V8 calls `callback` for, with no data, like C++
/// `v8::Function::New()` with a plain callback.
///
/// Unlike [`Function::new`], a call doesn't reach data through a Wrappable, so it costs no
/// more than V8's call of `callback`. The function carries no state: its data is
/// `undefined`. It has no signature, so `this` can be any value, it can be called with `new`,
/// and, as with [`Function::new`], its name is empty and its `length` is 0.
///
/// [`crate::function_callback`] turns a Rust closure that captures nothing into a callback,
/// which opens a [`crate::CallbackScope`] and turns a panic into an internal error that
/// terminates execution. A callback can also be an `extern "C"` function that V8 calls
/// directly. It gets no lock and no panic handling of its own, so a panic in it aborts the
/// process.
///
/// Fails as [`Function::new`] does.
pub fn from_callback<'s>(
Comment thread
bartlomieju marked this conversation as resolved.
Resolved
lock: &mut Lock<'s>,
callback: crate::RawFunctionCallback,
) -> crate::Result<Local<'s, Self>> {
let undefined = lock.undefined();
// SAFETY: isolate is valid and locked, with a context entered and a HandleScope open
// (guaranteed by Lock); `callback` is a V8 function callback and `undefined` a handle in
// the lock's scope, in which the function is created.
unsafe {
Local::from_ffi_maybe(ffi::function_new(
lock.isolate().as_ffi(),
callback as usize,
undefined.raw(),
))
}
.ok_or_else(Error::pending)
}

/// Creates one function per callback, all with the same data: one Wrappable owns `data`,
/// and its opaque wrapper is the V8 data of every function, so the garbage collector traces
/// `data` once, whichever of the functions are reachable, and drops it once none is.
Expand Down
Loading