diff --git a/src/rust/AGENTS.md b/src/rust/AGENTS.md index 4ed1567df70..b2599c1fecc 100644 --- a/src/rust/AGENTS.md +++ b/src/rust/AGENTS.md @@ -15,7 +15,7 @@ _Snapshot — the set drifts as crates come and go; `bazel query //src/rust/...` | Crate | Purpose | | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `jsg/` | Rust JSG bindings: `Lock`, `Rc`, `Resource`, `Struct`, `Type`, `Realm`, `FeatureFlags`, module registration; V8 handle types in `jsg::v8` (`Local`, `Global`, `TracedGlobal` over marker types that mirror V8's classes, from `Value` and `Number` to the typed arrays, and `BackingStore`); JS functions from Rust closures (`v8::Function::new`); typed promises (`jsg::Promise<'s, T>`, counterpart of C++ `jsg::Promise`, with `PromiseResolver`, `TracedPromise`, `TracedPromiseResolver` and `Lock::eval_now`; a returned promise keeps its resource alive through `ToJS::to_js_with_creator`, which containers forward); async context frames (`AsyncContextFrame`, `TracedAsyncContextFrame`); structured serialization in `jsg::Serializer`'s format (`ser`) | -| `jsg-macros/` | Proc macros: `#[jsg_struct]`, `#[jsg_method]`, `#[jsg_resource]`, `#[jsg_oneof]`, `#[jsg_static_constant]`, `#[jsg_constructor]`, `#[jsg_property]`, `#[jsg_inspect_property]`, `#[jsg_wildcard_property]` | +| `jsg-macros/` | Proc macros: `#[jsg_struct]`, `#[jsg_method]`, `#[jsg_resource]`, `#[jsg_oneof]`, `#[jsg_static_constant]`, `#[jsg_constructor]`, `#[jsg_property]`, `#[jsg_inspect_property]`, `#[jsg_wildcard_property]`, `#[jsg_callable]` | | `jsg-test/` | Test harness (`Harness`) for JSG Rust bindings | | `api/` | Rust-implemented Node.js APIs; registers modules via `register_nodejs_modules()` | | `encoding/` | WHATWG legacy text decoders via `encoding_rs`; an opaque streaming `Decoder` emits UTF-16 over the CXX bridge | @@ -35,10 +35,11 @@ _Snapshot — the set drifts as crates come and go; `bazel query //src/rust/...` - **Namespace**: `workerd::rust::*` for crates in this directory, except `python-parser` → `edgeworker::rust::python_parser`; a crate living beside C++ uses that C++'s namespace (e.g. `workerd::server::cli`) - **Errors**: `thiserror` for library crates; `jsg::Error` with `ExceptionType` for JSG-facing crates - **JSG nullish values**: `Option` is `T | undefined`; `Nullable` is `T | null` (coerces `undefined` to `Null`, but method arguments remain required). Prefer `NullOrUndefined` to `Option>` for three distinct `Some(T)`, `Null`, and `Undefined` states; omitted arguments become `Undefined`. `Lenient` additionally preserves shallow mismatches as `Unconvertable`; converting it to `NullOrUndefined` maps those to `Undefined`, and `Lenient::to_parts()` also returns the original JS value. See [Rust JSG nullish values](jsg/README.md#nullablet-and-nullorundefinedt). -- **JSG resources**: `#[jsg_resource]` on struct + impl block; `#[jsg_method]` auto-converts `snake_case` → `camelCase`; methods with `&self` become instance methods, methods without a receiver become static methods, and any other receiver is a compile error (JavaScript can re-enter a resource, so state that methods change goes in `Cell`/`RefCell` fields, or in `jsg::Cell`/`jsg::RefCell` fields when it holds a `jsg::Rc` or a `TracedGlobal`, whose `take`/`replace`/`borrow_mut` take the lock and make the contents strong; never hold a `RefCell` borrow across a call that can run JavaScript); a method or accessor can take `this: jsg::Rc` as its first parameter instead of `&self` to get a `jsg::Rc` of its resource (like `JSG_THIS`) to hand to a callback; don't share the resource's state with a callback through an `std::rc::Rc` (see `jsg/README.md` §Reaching the resource from a callback); a `#[jsg_method]` is registered with the type's `v8::Signature`, so its `&self` callback resolves the receiver without the `WORKERD_RUST_WRAPPABLE_TAG` marker check (`WrappableRc::resolve_method_receiver`); callbacks without a signature (accessors, inspect properties, wildcard interceptors) use `resolve_receiver`, which reads the marker before unwrapping so that it accepts any value; an eligible `#[jsg_method]` also gets a V8 Fast API callback (types in `jsg/fast_api.rs`) and must not call into V8; a `#[jsg_constructor]` returns `Self` or `Result` (an `Err` is thrown) and throws `TypeError` when called without `new`; `#[jsg_static_constant]` on `const` items exposes read-only numeric constants on both constructor and prototype (name kept as-is, no camelCase); `#[jsg_resource(nested_types(Foo, Name = Bar))]` on the impl block puts other resources' constructors on the prototype (`JSG_NESTED_TYPE`); resources integrate with GC via `Traced` + `GarbageCollected`: every named field is traced via `Traced::trace(&self.field, visitor)` and all non-traceable types use no-op `Traced` impls; `Traced::trace` has no default, so a type with nothing to trace uses `jsg::jsg_traced!` (also `jsg_traced!( Foo)` for a generic type that holds a `T`), which also implements `jsg::HoldsNoGcReferences` +- **JSG resources**: `#[jsg_resource]` on struct + impl block; `#[jsg_method]` auto-converts `snake_case` → `camelCase`; methods with `&self` become instance methods, methods without a receiver become static methods, and any other receiver is a compile error (JavaScript can re-enter a resource, so state that methods change goes in `Cell`/`RefCell` fields, or in `jsg::Cell`/`jsg::RefCell` fields when it holds a `jsg::Rc` or a `TracedGlobal`, whose `take`/`replace`/`borrow_mut` take the lock and make the contents strong; never hold a `RefCell` borrow across a call that can run JavaScript); a method or accessor can take `this: jsg::Rc` as its first parameter instead of `&self` to get a `jsg::Rc` of its resource (like `JSG_THIS`) to hand to a callback; don't share the resource's state with a callback through an `std::rc::Rc` (see `jsg/README.md` §Reaching the resource from a callback); a `#[jsg_method]` is registered with the type's `v8::Signature`, so its `&self` callback resolves the receiver without the `WORKERD_RUST_WRAPPABLE_TAG` marker check (`WrappableRc::resolve_method_receiver`); callbacks without a signature (accessors, inspect properties, wildcard interceptors, `#[jsg_callable]` call handlers) use `resolve_receiver`, which reads the marker before unwrapping so that it accepts any value; an eligible `#[jsg_method]` also gets a V8 Fast API callback (types in `jsg/fast_api.rs`) and must not call into V8; a `#[jsg_constructor]` returns `Self` or `Result` (an `Err` is thrown) and throws `TypeError` when called without `new`; `#[jsg_static_constant]` on `const` items exposes read-only numeric constants on both constructor and prototype (name kept as-is, no camelCase); `#[jsg_resource(nested_types(Foo, Name = Bar))]` on the impl block puts other resources' constructors on the prototype (`JSG_NESTED_TYPE`); resources integrate with GC via `Traced` + `GarbageCollected`: every named field is traced via `Traced::trace(&self.field, visitor)` and all non-traceable types use no-op `Traced` impls; `Traced::trace` has no default, so a type with nothing to trace uses `jsg::jsg_traced!` (also `jsg_traced!( Foo)` for a generic type that holds a `T`), which also implements `jsg::HoldsNoGcReferences` - **Resources created by C++**: C++ creates a Rust resource through an `extern "Rust"` function of the crate that defines it, which returns the wrapper through `jsg::v8::run_ffi_callback`; C++ holds the wrapper (a `jsg::JsRef`), since it has no typed reference to a Rust resource, and checks a value's type through one that returns `jsg::resource::ffi_is::`, a `kj::Maybe` that is none when an exception is pending. See `jsg/README.md` §Creating resources from C++. - **Custom JSG registration**: `#[jsg_resource(custom_members)]` on an impl generates member factories but leaves `impl Resource` to the author. `Resource::members(registry, flags)` uses ordinary Rust to select members, order, and property placement, and also drives RTTI under the export's flags. Factories are `_member()` (constant names lowercased); ordinary property factories are `_member(PropertyPlacement)` (`Prototype`, `Instance` or `LazyInstance`) and include the paired setter. See `jsg-macros/README.md` §Custom member registration. - **JSG properties**: three property macros on `#[jsg_resource]` impl blocks — `#[jsg_property(prototype|instance|lazy_instance [, name = "..."] [, readonly])]` (`prototype` registers an accessor on the prototype, equivalent to `JSG_PROTOTYPE_PROPERTY`; `instance` registers an own data property via V8 `SetNativeDataProperty`, equivalent to `JSG_INSTANCE_PROPERTY`; `lazy_instance` registers an own data property via V8 `SetLazyDataProperty` whose getter runs once, on first access, equivalent to `JSG_LAZY_INSTANCE_PROPERTY`: it has no setter, is writable unless `readonly` (`JSG_LAZY_READONLY_INSTANCE_PROPERTY`); declaration order sets `Object.keys()` order for automatic registration; `readonly` is a compile-time check preventing a paired setter; `name = "..."` overrides the JS name; prefer `prototype` in almost all cases), `#[jsg_inspect_property]` (registered under a unique symbol, invisible to normal enumeration and string-key lookup, surfaced by `node:util` `inspect()`, equivalent to `JSG_INSPECT_PROPERTY`), and `#[jsg_wildcard_property]` (answers string-named properties the object and its prototypes lack, at most one per type, equivalent to `JSG_WILDCARD_PROPERTY`; see `jsg/README.md`); setter auto-detected from `set_` prefix; read-only when no setter present; getter/setter `.length` and `.name` are set correctly when `spec_compliant_property_attributes` compat flag is enabled +- **Callable resources**: `#[jsg_callable]` on a `&self` (or `this: jsg::Rc`) method makes instances callable as functions, equivalent to `JSG_CALLABLE` (V8 `SetCallAsFunctionHandler` on the instance template); at most one per type; runs with or without `new`, always with the instance as `this`; factory `_callable_member()`, so the method may also be a `#[jsg_method]`; RTTI describes it as the structure's `callable` signature, as C++ does; see `jsg/README.md` §Callable resources - **`jsg::v8::Global` / `TracedGlobal`**: persistent handles. A `Global` is for handles Rust owns outside resources: GC never visits it, so it is always strong, holds its handle inline (no box), has no `Traced` impl (it cannot be a resource field), and is `Send` and `Sync`. A `TracedGlobal` is for resource fields, which GC traces to collect cycles; it is `Send` (not `Sync`). Either may be dropped on any thread. Under the isolate lock its strong handle is reset at once; without the lock it is queued and reset at the next `IsolateBase::Lock`, through `IsolateBase::applyDeferredActions()`; once the `Realm` is dropped (under the lock, before `Dispose`) the handles are left to `Dispose`. See `jsg/isolate_state.rs`. Hand-written FFI that resets a V8 handle directly must hold the lock. Rust never resets a `TracedGlobal`'s traced reference: every GC visit, and the detaching visit on the way out of a `jsg::` cell, lets go of it and makes the strong handle strong again (`ClearWeak`) before C++ installs a new one if needed, and a drop just lets go of it; V8 frees untraced nodes at the next full GC. See `GcVisitor::visit_traced_global`. A `TracedGlobal` keeps its handles in a `Box`, since V8 holds the address of a weak handle's slot; the slot of a `TracedGlobal` dropped after the `Realm` is kept until the isolate is disposed - **JSG parameters**: function `.length` is the Web IDL required-argument count under `spec_compliant_property_attributes` (`this: jsg::Rc` and a leading `&mut Lock` are not counted; counting stops at the first type whose `FromJS::is_optional()` returns true), so put optional parameters last - **`Traced`**: core tracing trait in `jsg::wrappable`, with `trace`, which GC calls and which also detaches a value from its owner (`GcVisitor::is_detaching`: every GC reference in it becomes strong and forgets its parent, so it stays valid outside a traced field); built-ins include no-op impls for primitives/value types and delegating impls for wrappers/collections (`Option`, `Nullable`, `NullOrUndefined`, `Lenient`, `Vec`, `jsg::Dict`, maps/sets, `Cell`, `RefCell`, `jsg::Cell`, `jsg::RefCell`, `jsg::Rc`, `jsg::Weak`, `jsg::v8::TracedGlobal`); `jsg::v8::Global` deliberately has none. `std::cell::Cell` and `RefCell` are `Traced` only for `T: jsg::HoldsNoGcReferences` (no `jsg::Rc` or `TracedGlobal` inside; wrappers and collections forward it, and `#[jsg_struct]`/`#[jsg_oneof]` derive it when every field or variant has it, unless `custom_holds_no_gc_references` leaves it to the author, as for two structs that contain each other); a `jsg::Rc` or `TracedGlobal` that is moved out of a field lives in a `jsg::Cell` or `jsg::RefCell` (`jsg/cell.rs`), which detach it before it leaves the cell diff --git a/src/rust/jsg-compile-tests/callable-shape.rs b/src/rust/jsg-compile-tests/callable-shape.rs new file mode 100644 index 00000000000..9e2f632389b --- /dev/null +++ b/src/rust/jsg-compile-tests/callable-shape.rs @@ -0,0 +1,64 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// A resource type is callable at most one way, through a method that takes `&self` or +// `this: jsg::Rc`, and `#[jsg_callable]` takes no arguments. + +use jsg_macros::jsg_callable; +use jsg_macros::jsg_resource; + +#[jsg_resource] +pub struct Twice; + +#[jsg_resource] +impl Twice { + #[jsg_callable] + pub fn first(&self) {} + + #[jsg_callable] + pub fn second(&self) {} + //~^ ERROR a resource type has at most one #[jsg_callable] +} + +#[jsg_resource] +pub struct Static; + +#[jsg_resource] +impl Static { + #[jsg_callable] + pub fn call() {} + //~^ ERROR a #[jsg_callable] method takes `&self`, or `this: jsg::Rc` in its place +} + +#[jsg_resource] +pub struct Mutable; + +#[jsg_resource] +impl Mutable { + #[jsg_callable] + pub fn call(&mut self) {} + //~^ ERROR a resource method takes `&self` +} + +#[jsg_resource] +pub struct MisplacedThis; + +#[jsg_resource] +impl MisplacedThis { + #[jsg_callable] + pub fn call(lock: &mut jsg::Lock, this: jsg::Rc) { + //~^ ERROR `this` must be the first parameter + let _ = (lock, this); + } +} + +#[jsg_resource] +pub struct Arguments; + +#[jsg_resource] +impl Arguments { + #[jsg_callable(name = "x")] + //~^ ERROR #[jsg_callable] takes no arguments + pub fn call(&self) {} +} diff --git a/src/rust/jsg-compile-tests/ok-callable-shapes.rs b/src/rust/jsg-compile-tests/ok-callable-shapes.rs new file mode 100644 index 00000000000..5f008263268 --- /dev/null +++ b/src/rust/jsg-compile-tests/ok-callable-shapes.rs @@ -0,0 +1,84 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +// A callable method has the shapes of a `#[jsg_method]`, and may also be one, with the +// attributes in either order. Custom registration may choose between several callables. + +use jsg::MemberRegistry; +use jsg::Resource; +use jsg::feature_flags::compatibility_flags; +use jsg_macros::jsg_callable; +use jsg_macros::jsg_method; +use jsg_macros::jsg_resource; + +#[jsg_resource] +pub struct WithLock; + +#[jsg_resource] +impl WithLock { + #[jsg_callable] + pub fn call( + &self, + lock: &mut jsg::Lock, + a: String, + b: Option, + ) -> Result { + let _ = (lock, b); + Ok(a) + } +} + +#[jsg_resource] +pub struct WithThis; + +#[jsg_resource] +impl WithThis { + #[jsg_callable] + pub fn call(this: jsg::Rc, lock: &mut jsg::Lock) -> jsg::Rc { + let _ = lock; + this + } +} + +#[jsg_resource] +pub struct CallableFirst; + +#[jsg_resource] +impl CallableFirst { + #[jsg_callable] + #[jsg_method] + pub fn call(&self) {} +} + +#[jsg_resource] +pub struct MethodFirst; + +#[jsg_resource] +impl MethodFirst { + #[jsg_method] + #[jsg_callable] + pub fn call(&self) {} +} + +#[jsg_resource] +pub struct Versioned; + +#[jsg_resource(custom_members)] +impl Versioned { + #[jsg_callable] + pub fn call_old(&self) {} + + #[jsg_callable] + pub fn call_new(&self) {} +} + +impl Resource for Versioned { + fn members(registry: &mut impl MemberRegistry, flags: compatibility_flags::Reader<'_>) { + if flags.get_node_js_compat() { + registry.add(Self::call_new_callable_member()); + } else { + registry.add(Self::call_old_callable_member()); + } + } +} diff --git a/src/rust/jsg-macros/README.md b/src/rust/jsg-macros/README.md index b454dcc478c..cffcff3662a 100644 --- a/src/rust/jsg-macros/README.md +++ b/src/rust/jsg-macros/README.md @@ -154,7 +154,7 @@ The optional `ts_root` argument marks a TypeScript generation root. **On an impl block** — emits `jsg::Resource::members(registry, flags)`, registering every `#[jsg_method]`, `#[jsg_constructor]`, `#[jsg_property]`, `#[jsg_inspect_property]`, -`#[jsg_wildcard_property]`, and `#[jsg_static_constant]` item. It also generates member factories used by both automatic +`#[jsg_wildcard_property]`, `#[jsg_callable]`, and `#[jsg_static_constant]` item. It also generates member factories used by both automatic and custom registration. Use `#[jsg_resource(nested_types(Foo, Name = Bar))]` to expose other resource types' constructors on the prototype (equivalent to `JSG_NESTED_TYPE(Foo)` and @@ -244,6 +244,7 @@ the **Rust declaration**, independently of any JavaScript `name = "..."` overrid | Property getter `get_value` with an optional paired setter | `Self::get_value_member(placement)` | | Inspect getter `debug_info` | `Self::debug_info_member()` | | Wildcard property `get_var` | `Self::get_var_member()` | +| Callable `call` | `Self::call_callable_member()` | An ordinary property factory accepts `jsg::PropertyPlacement::{Prototype, Instance, LazyInstance}` and selects the matching V8 getter and setter callbacks. The attribute's `prototype` / `instance` / @@ -460,6 +461,34 @@ impl Env { // 'HOME' in env // true ``` +## `#[jsg_callable]` + +Makes the instances of a `#[jsg_resource]` type callable as functions, running the method. +Equivalent to C++ `JSG_CALLABLE`. + +The method takes `&self`, or `this: jsg::Rc` in its place, and otherwise has the shape of +a `#[jsg_method]`. The attribute takes no arguments. A type is callable at most one way; with +automatic registration a second `#[jsg_callable]` is a compile error, and a custom `members` list +that includes two fails at runtime. The macro generates `_callable_callback()` and, through +`#[jsg_resource]`, the factory `_callable_member()`, which differ from a `#[jsg_method]`'s, +so a method may also be a `#[jsg_method]`. See [Callable resources](../jsg/README.md#callable-resources) +for how they behave. + +```rust +use jsg_macros::{jsg_callable, jsg_resource}; + +#[jsg_resource] +struct Greeter { greeting: String } + +#[jsg_resource] +impl Greeter { + #[jsg_callable] + pub fn greet(&self, name: String) -> String { format!("{}, {name}", self.greeting) } +} +// JS: greeter('world') // "Hello, world" +// typeof greeter // "function" +``` + ## `#[jsg_oneof]` Generates `jsg::Type`, `jsg::FromJS`, `jsg::Traced` and `jsg::TypeInfo` for a union enum — diff --git a/src/rust/jsg-macros/lib.rs b/src/rust/jsg-macros/lib.rs index c066fa254a5..073031e1cc0 100644 --- a/src/rust/jsg-macros/lib.rs +++ b/src/rust/jsg-macros/lib.rs @@ -15,6 +15,7 @@ //! | `#[jsg_property]` | fn inside impl | Register a resource accessor property (getter/setter) | //! | `#[jsg_inspect_property]` | fn inside impl | Register a debug-inspect-only symbol property | //! | `#[jsg_wildcard_property]` | fn inside impl | Answer reads of any property the object does not have | +//! | `#[jsg_callable]` | fn inside impl | Make instances callable as functions | //! | `#[jsg_struct]` | struct | Expose a Rust struct as a plain JavaScript object | //! | `#[jsg_oneof]` | enum | Accept one of several JavaScript types (`kj::OneOf`) | //! @@ -400,19 +401,58 @@ fn callback_with_instance( let method_name = method_attr.map(|attr| { extract_name_attribute(attr).unwrap_or_else(|| snake_to_camel(&fn_name.to_string())) }); - let fn_vis = &input_fn.vis; + let callbacks = match generate_callbacks( + &input_fn, + callback_names(fn_name, kind, instance_kind), + method_name.as_deref(), + receiver_check, + ) { + Ok(callbacks) => callbacks, + Err(error) => return error.into(), + }; + // The method keeps its other attributes, so that a `#[jsg_callable]` after the attribute + // being expanded still expands. + let method = reemit_method(&input_fn); + quote! { + #method + #callbacks + } + .into() +} + +/// Re-emits `input_fn` with its other attributes. The body is wrapped in braces spanned at the +/// macro call, as the methods have always been emitted, so that clippy treats the method as +/// macro output and does not lint the signature against its generated callbacks. +fn reemit_method(input_fn: &ItemFn) -> proc_macro2::TokenStream { + let ItemFn { + attrs, + vis, + sig, + block, + } = input_fn; + quote! { #(#attrs)* #vis #sig { #block } } +} + +/// Generates the callbacks named in `callback_kinds`, each calling `input_fn`, or returns the +/// method with an error and stubs of the callbacks (see [`reject`]). `method_name` is a method's +/// JS name; its errors match C++ JSG's. +fn generate_callbacks( + input_fn: &ItemFn, + callback_kinds: impl Iterator + Clone, + method_name: Option<&str>, + receiver_check: ReceiverCheck, +) -> Result { + let fn_name = &input_fn.sig.ident; let fn_sig = &input_fn.sig; - let fn_block = &input_fn.block; // Methods with a `&self` receiver, or a `this: jsg::Rc` parameter in its place, become // instance methods on the prototype. Methods with neither become static methods on the // constructor. - let callback_kinds = callback_names(fn_name, kind, instance_kind); - if let Some(error) = receiver_error(&input_fn, callback_kinds.clone()) { - return error.into(); + if let Some(error) = receiver_error(input_fn, callback_kinds.clone()) { + return Err(error); } - if let Some(error) = this_error(&input_fn, callback_kinds.clone()) { - return error.into(); + if let Some(error) = this_error(input_fn, callback_kinds.clone()) { + return Err(error); } let has_self = fn_sig.receiver().is_some(); let has_this = this_param(fn_sig).is_some(); @@ -452,7 +492,7 @@ fn callback_with_instance( let js_index = i - injected_params; let arg = syn::Ident::new(&format!("arg{js_index}"), fn_name.span()); - let unwrap = unwrap_argument(ty, &arg, js_index, method_name.as_deref()); + let unwrap = unwrap_argument(ty, &arg, js_index, method_name); // For reference types (like &str), FromJS returns an owned type (String), // so we need to borrow it when passing to the function. let is_ref = matches!(ty.as_ref(), syn::Type::Reference(_)); @@ -491,11 +531,7 @@ fn callback_with_instance( } }); - quote! { - #fn_vis #fn_sig { #fn_block } - #(#callbacks)* - } - .into() + Ok(quote! { #(#callbacks)* }) } /// The statements that convert the call's `result` and return it to JavaScript, or throw what @@ -795,8 +831,8 @@ fn reject( /// /// **On an impl block** — emits `jsg::Resource::members(registry, flags)` registering every /// `#[jsg_method]`, `#[jsg_property]`, `#[jsg_inspect_property]`, `#[jsg_wildcard_property]`, -/// `#[jsg_constructor]`, and `#[jsg_static_constant]` item, plus member factories, which also -/// describe their members for RTTI. +/// `#[jsg_callable]`, `#[jsg_constructor]`, and `#[jsg_static_constant]` item, plus member +/// factories, which also describe their members for RTTI. /// With `custom_members`, emits only the factories; implement `jsg::Resource` yourself /// to select members using ordinary Rust control flow and compatibility flags. /// @@ -947,6 +983,76 @@ pub fn jsg_wildcard_property(attr: TokenStream, item: TokenStream) -> TokenStrea wildcard::expand(attr, item) } +// ============================================================================= +// #[jsg_callable] +// ============================================================================= + +/// The name that errors from converting the arguments of a `#[jsg_callable]` method give the +/// method, as C++ JSG's `registerCallable()` does. +const CALLED_AS_FUNCTION: &str = "(called as function)"; + +/// Makes the instances of a `#[jsg_resource]` type callable as functions, running the method. +/// +/// Equivalent to C++ JSG's `JSG_CALLABLE`. The method takes `&self`, or `this: jsg::Rc` as +/// its first parameter in place of it, and otherwise has the shape of a `#[jsg_method]`: an +/// optional `&mut jsg::Lock`, then the JavaScript arguments. It runs whether the instance is +/// called with or without `new`, and always with the instance as `this`, so a callable taken off +/// the object it was read from still calls the instance. A type is callable at most one way. +/// The method may also be a `#[jsg_method]`, to be callable both ways. +/// See `src/rust/jsg/README.md` for how callable resources behave. +#[proc_macro_attribute] +pub fn jsg_callable(attr: TokenStream, item: TokenStream) -> TokenStream { + // Registration as Member::Callable is handled by #[jsg_resource] on the enclosing impl block. + let input_fn = parse_macro_input!(item as ItemFn); + let fn_name = &input_fn.sig.ident; + let callback_names = std::iter::once((Callback::Function, callable_callback_name(fn_name))); + let error = if attr.is_empty() { + let has_receiver = + input_fn.sig.receiver().is_some() || input_fn.sig.inputs.iter().any(is_named_this); + (!has_receiver).then(|| { + syn::Error::new_spanned( + fn_name, + "a #[jsg_callable] method takes `&self`, or `this: jsg::Rc` in its place: \ + it runs on the instance that is called", + ) + }) + } else { + Some(syn::Error::new_spanned( + proc_macro2::TokenStream::from(attr), + "#[jsg_callable] takes no arguments", + )) + }; + if let Some(error) = error { + return reject(&input_fn, callback_names, &error).into(); + } + // A call handler has no `v8::Signature`. V8 passes the instance that is called as `this`, + // but the callback still checks the receiver, as an accessor's does. + let callbacks = generate_callbacks( + &input_fn, + callback_names, + Some(CALLED_AS_FUNCTION), + ReceiverCheck::Marker, + ); + // The method keeps its other attributes, so that a `#[jsg_method]` after this one expands. + match callbacks { + Ok(callbacks) => { + let method = reemit_method(&input_fn); + quote! { + #method + #callbacks + } + } + Err(error) => error, + } + .into() +} + +/// The name of the callback that `#[jsg_callable]` generates for `fn_name`. It differs from the +/// callback of a `#[jsg_method]`, so that a method can be both. +fn callable_callback_name(fn_name: &syn::Ident) -> syn::Ident { + syn::Ident::new(&format!("{fn_name}_callable_callback"), fn_name.span()) +} + // ============================================================================= // #[jsg_oneof] // ============================================================================= diff --git a/src/rust/jsg-macros/resource-test.rs b/src/rust/jsg-macros/resource-test.rs index 97663cf2cf7..32eed9bbceb 100644 --- a/src/rust/jsg-macros/resource-test.rs +++ b/src/rust/jsg-macros/resource-test.rs @@ -795,3 +795,85 @@ fn property_descriptions_follow_the_requested_placement() { .unwrap(); assert!(inspect.description.is_none()); } + +#[test] +fn callable_factory_registers_and_describes_the_callable_callback() { + let input: ItemImpl = parse_quote! { + impl Sample { + #[jsg_callable] + fn call(&self, value: String) -> bool { true } + } + }; + let (registrations, error) = + collect_callable_registrations(&input, RegistrationMode::Automatic); + assert!(error.is_none()); + let [registration] = registrations.as_slice() else { + panic!("expected one registration"); + }; + assert_eq!(registration.factory_name, "call_callable_member"); + let factory = registration.factory().to_string(); + assert!( + factory + .contains("jsg :: Member :: Callable { callback : Self :: call_callable_callback () }"), + "{factory}" + ); + assert!( + factory.contains("jsg :: rtti :: Member :: Callable"), + "{factory}" + ); + let expanded = expand_resource_impl(quote!(), &input).to_string(); + assert!( + expanded.contains("Self :: call_callable_member ()"), + "{expanded}" + ); +} + +// A method can be both a method and the callable, since their factories and callbacks differ. +#[test] +fn method_can_also_be_the_callable() { + let input: ItemImpl = parse_quote! { + impl Sample { + #[jsg_callable] + #[jsg_method] + fn call(&self) {} + } + }; + let expanded = expand_resource_impl(quote!(), &input); + let file: syn::File = syn::parse2(expanded.clone()).unwrap(); + assert!( + !file + .items + .iter() + .any(|item| matches!(item, syn::Item::Macro(_))), + "{expanded}" + ); + let expanded = expanded.to_string(); + assert!(expanded.contains("Self :: call_member ()"), "{expanded}"); + assert!( + expanded.contains("Self :: call_callable_member ()"), + "{expanded}" + ); +} + +#[test] +fn second_callable_is_rejected_only_with_automatic_registration() { + let input: ItemImpl = parse_quote! { + impl Sample { + #[jsg_callable] + fn first(&self) {} + #[jsg_callable] + fn second(&self) {} + } + }; + let (registrations, error) = + collect_callable_registrations(&input, RegistrationMode::Automatic); + assert_eq!(registrations.len(), 2); + let error = error.unwrap().to_string(); + assert!( + error.contains("a resource type has at most one #[jsg_callable]"), + "{error}" + ); + let (registrations, error) = collect_callable_registrations(&input, RegistrationMode::Custom); + assert_eq!(registrations.len(), 2); + assert!(error.is_none()); +} diff --git a/src/rust/jsg-macros/resource.rs b/src/rust/jsg-macros/resource.rs index 7ac14ef6db2..f50318a06a3 100644 --- a/src/rust/jsg-macros/resource.rs +++ b/src/rust/jsg-macros/resource.rs @@ -325,24 +325,77 @@ fn collect_method_registrations(impl_block: &ItemImpl) -> Vec (Vec, Option) { + collect_at_most_one( + impl_block, + mode, + "jsg_wildcard_property", + member_factory_name, + |method| { + let rust_name = &method.sig.ident; + let getter_callback = crate::wildcard::getter_callback_name(rust_name); + let query_callback = crate::wildcard::query_callback_name(rust_name); + let member = quote! { + jsg::Member::WildcardProperty { + getter_callback: Self::#getter_callback(), + query_callback: Self::#query_callback(), + } + }; + // C++ RTTI does not describe wildcard properties either. + (member, None) + }, + ) +} + +/// Scans `impl_block` for `#[jsg_callable]` methods. As with wildcard properties, a resource +/// type is callable at most one way. The factory is `{name}_callable_member`, so that a method +/// can also be a `#[jsg_method]`, whose factory is `{name}_member`. +fn collect_callable_registrations( + impl_block: &ItemImpl, + mode: RegistrationMode, +) -> (Vec, Option) { + let factory_name = |rust_name: &syn::Ident| { + syn::Ident::new(&format!("{rust_name}_callable_member"), rust_name.span()) + }; + collect_at_most_one(impl_block, mode, "jsg_callable", factory_name, |method| { + let callback = crate::callable_callback_name(&method.sig.ident); + let member = quote! { jsg::Member::Callable { callback: Self::#callback() } }; + let args = describe_args(method, Callable::Method); + let result = describe_result(method); + let description = quote! { + jsg::rtti::Member::Callable { + args: vec![#(#args),*], + result: #result, + } + }; + (member, Some(description)) + }) +} + +/// Registers each method of `impl_block` annotated with `#[attr]`, a member a resource type has +/// at most one of, in a factory named by `factory_name`; `registration` gives the member and its +/// RTTI description. With automatic registration a second such method is a compile error, +/// which is returned alongside the registrations so that the type is still registered and adds +/// no errors of its own. Custom registration may choose between several by compatibility flag; +/// registering more than one at once fails at runtime. +fn collect_at_most_one( + impl_block: &ItemImpl, + mode: RegistrationMode, + attr: &str, + factory_name: impl Fn(&syn::Ident) -> syn::Ident, + registration: impl Fn( + &syn::ImplItemFn, + ) -> (proc_macro2::TokenStream, Option), ) -> (Vec, Option) { let methods: Vec<_> = impl_block .items .iter() .filter_map(|item| match item { - syn::ImplItem::Fn(method) - if method - .attrs - .iter() - .any(|a| is_attr(a, "jsg_wildcard_property")) => - { + syn::ImplItem::Fn(method) if method.attrs.iter().any(|a| is_attr(a, attr)) => { Some(method) } _ => None, @@ -354,8 +407,10 @@ fn collect_wildcard_registrations( .map(|second| { syn::Error::new_spanned( &second.sig.ident, - "a resource type has at most one #[jsg_wildcard_property]; use \ - `custom_members` to choose between several by compatibility flag", + format!( + "a resource type has at most one #[{attr}]; use `custom_members` to choose \ + between several by compatibility flag" + ), ) .to_compile_error() }); @@ -363,16 +418,13 @@ fn collect_wildcard_registrations( .iter() .map(|method| { let rust_name = &method.sig.ident; - let getter_callback = crate::wildcard::getter_callback_name(rust_name); - let query_callback = crate::wildcard::query_callback_name(rust_name); - let member = quote! { - jsg::Member::WildcardProperty { - getter_callback: Self::#getter_callback(), - query_callback: Self::#query_callback(), - } - }; - // C++ RTTI does not describe wildcard properties either. - MemberRegistration::new(rust_name, member, None) + let (member, description) = registration(method); + MemberRegistration::with_factory_name( + rust_name, + factory_name(rust_name), + member, + description, + ) }) .collect(); (registrations, error) @@ -653,6 +705,8 @@ fn generate_resource_bindings( registrations.extend(collect_constant_registrations(impl_block)); let (wildcard, wildcard_error) = collect_wildcard_registrations(impl_block, mode); registrations.extend(wildcard); + let (callable, callable_error) = collect_callable_registrations(impl_block, mode); + registrations.extend(callable); validate_factory_names(impl_block, ®istrations).map_err(|err| err.to_compile_error())?; let factories = registrations.iter().map(MemberRegistration::factory); let automatic = registrations.iter().map(|r| &r.automatic); @@ -678,6 +732,7 @@ fn generate_resource_bindings( Ok(quote! { #wildcard_error + #callable_error #[automatically_derived] impl #self_ty { diff --git a/src/rust/jsg-test/tests/callable.rs b/src/rust/jsg-test/tests/callable.rs new file mode 100644 index 00000000000..54fd595af71 --- /dev/null +++ b/src/rust/jsg-test/tests/callable.rs @@ -0,0 +1,379 @@ +// Copyright (c) 2026 Cloudflare, Inc. +// Licensed under the Apache 2.0 license found in the LICENSE file or at: +// https://opensource.org/licenses/Apache-2.0 + +//! `#[jsg_callable]` behaves as C++ JSG's `JSG_CALLABLE`. The first test mirrors the +//! "Test `JSG_CALLABLE`" test in `src/workerd/jsg/jsg-test.c++` case for case. + +use std::cell::Cell; + +use jsg::ExceptionType; +use jsg::MemberRegistry; +use jsg::Resource; +use jsg::feature_flags::compatibility_flags; +use jsg_macros::jsg_callable; +use jsg_macros::jsg_constructor; +use jsg_macros::jsg_method; +use jsg_macros::jsg_resource; +use jsg_macros::jsg_wildcard_property; + +/// `MyCallable` of the C++ test. +#[jsg_resource] +struct MyCallable; + +#[jsg_resource] +impl MyCallable { + #[jsg_constructor] + fn constructor() -> Self { + Self + } + + #[jsg_callable] + #[jsg_method] + fn foo(&self) -> bool { + let _ = self; + true + } +} + +/// Adds its arguments to a running total, which it returns. +#[jsg_resource] +struct Counter { + total: Cell, +} + +#[jsg_resource] +impl Counter { + #[jsg_callable] + fn add(&self, lock: &mut jsg::Lock, amount: f64, times: Option) -> f64 { + let _ = lock; + self.total + .set(amount.mul_add(times.unwrap_or(1.0), self.total.get())); + self.total.get() + } + + #[jsg_method] + fn total(&self) -> f64 { + self.total.get() + } +} + +fn counter() -> jsg::Rc { + jsg::Rc::new(Counter { + total: Cell::new(0.0), + }) +} + +/// Returns itself when called, and fails when called with `"fail"`. +#[jsg_resource] +struct Itself; + +#[jsg_resource] +impl Itself { + #[jsg_callable] + fn call(this: jsg::Rc, arg: Option) -> Result, jsg::Error> { + if arg.as_deref() == Some("fail") { + return Err(jsg::Error::new_range_error("failed")); + } + Ok(this) + } +} + +/// Like an RPC stub: has every property, and calling it, or a property, records the path. +#[jsg_resource] +struct Stub { + path: String, +} + +#[jsg_resource] +impl Stub { + #[jsg_callable] + fn call(&self, arg: String) -> String { + format!("{}({arg})", self.path) + } + + #[jsg_wildcard_property] + #[expect( + clippy::unnecessary_wraps, + reason = "a wildcard property returns an Option" + )] + fn get(&self, name: &str) -> Option> { + Some(jsg::Rc::new(Self { + path: format!("{}.{name}", self.path), + })) + } +} + +/// Is callable one of two ways, depending on a compatibility flag. +#[jsg_resource] +struct Versioned; + +#[jsg_resource(custom_members)] +impl Versioned { + #[jsg_callable] + fn call_old(&self) -> String { + let _ = self; + "old".to_owned() + } + + #[jsg_callable] + fn call_new(&self) -> String { + let _ = self; + "new".to_owned() + } +} + +impl Resource for Versioned { + fn members(registry: &mut impl MemberRegistry, flags: compatibility_flags::Reader<'_>) { + if flags.get_cache_option_enabled() { + registry.add(Self::call_new_callable_member()); + } else { + registry.add(Self::call_old_callable_member()); + } + } +} + +/// Not callable. +#[jsg_resource] +struct Plain; + +#[jsg_resource] +impl Plain { + #[jsg_method] + fn foo(&self) -> bool { + let _ = self; + true + } +} + +fn with_globals(f: impl for<'s, 'c> FnOnce(&mut jsg::Lock<'s>, &crate::EvalContext<'c>)) { + let harness = crate::Harness::new(); + harness.run_in_context(|lock, ctx| { + let my_callable = jsg::resource::function_template_of::(lock).unwrap(); + ctx.set_global(lock, "MyCallable", my_callable); + ctx.set_global(lock, "getCallable", jsg::Rc::new(MyCallable)); + ctx.set_global(lock, "counter", counter()); + ctx.set_global(lock, "itself", jsg::Rc::new(Itself)); + ctx.set_global( + lock, + "stub", + jsg::Rc::new(Stub { + path: "stub".to_owned(), + }), + ); + ctx.set_global(lock, "plain", jsg::Rc::new(Plain)); + f(lock, ctx); + Ok(()) + }); +} + +fn expect_eval(lock: &mut jsg::Lock<'_>, ctx: &crate::EvalContext<'_>, code: &str, expected: &str) { + let result: String = ctx.eval(lock, code).unwrap(); + assert_eq!(result, expected, "{code}"); +} + +fn expect_error( + lock: &mut jsg::Lock<'_>, + ctx: &crate::EvalContext<'_>, + code: &str, + name: ExceptionType, +) -> String { + let err = ctx + .eval::(lock, code) + .unwrap_err() + .unwrap_jsg_err(lock); + assert_eq!(err.name, name, "{code}: {}", err.message); + err.message +} + +// ============================================================================= +// jsg-test.c++ "Test JSG_CALLABLE" +// ============================================================================= + +// `getCallable` is a global instance here rather than a method returning one. +#[test] +fn callable_resource() { + with_globals(|lock, ctx| { + expect_eval( + lock, + ctx, + "let obj = getCallable; String(obj.foo())", + "true", + ); + expect_eval(lock, ctx, "String(getCallable())", "true"); + expect_eval(lock, ctx, "String(new MyCallable()())", "true"); + // Calling with `new` runs the method too. + expect_eval(lock, ctx, "String(new getCallable())", "true"); + }); +} + +// ============================================================================= +// The callable object +// ============================================================================= + +// V8 reports an object with a call handler as a function, but it is still an instance of the +// resource type, with the type's prototype rather than `Function.prototype`. +#[test] +fn callable_is_a_function_and_an_instance() { + with_globals(|lock, ctx| { + expect_eval(lock, ctx, "typeof getCallable", "function"); + expect_eval( + lock, + ctx, + "String(getCallable instanceof MyCallable)", + "true", + ); + expect_eval( + lock, + ctx, + "String(Object.getPrototypeOf(getCallable) === MyCallable.prototype)", + "true", + ); + expect_eval( + lock, + ctx, + "String(getCallable instanceof Function)", + "false", + ); + expect_eval(lock, ctx, "typeof getCallable.call", "undefined"); + expect_eval( + lock, + ctx, + "String(Reflect.apply(getCallable, null, []))", + "true", + ); + }); +} + +#[test] +fn resource_without_jsg_callable_is_not_callable() { + with_globals(|lock, ctx| { + expect_eval(lock, ctx, "typeof plain", "object"); + let message = expect_error(lock, ctx, "plain()", ExceptionType::TypeError); + assert!(message.contains("is not a function"), "{message}"); + }); +} + +#[test] +fn custom_members_choose_how_it_is_callable() { + for (enabled, expected) in [(false, "old"), (true, "new")] { + let harness = + crate::Harness::with_flags(|mut flags| flags.set_cache_option_enabled(enabled)); + harness.run_in_context(|lock, ctx| { + ctx.set_global(lock, "v", jsg::Rc::new(Versioned)); + expect_eval(lock, ctx, "v()", expected); + Ok(()) + }); + } +} + +// ============================================================================= +// `this` +// ============================================================================= + +// V8 runs the call handler with the callable as `this`, however the call names it, so a +// callable taken off an object still calls the instance. +#[test] +fn this_is_always_the_callable() { + with_globals(|lock, ctx| { + expect_eval(lock, ctx, "String(itself() === itself)", "true"); + expect_eval( + lock, + ctx, + "const o = { f: itself }; String(o.f() === itself)", + "true", + ); + expect_eval( + lock, + ctx, + "String(Reflect.apply(itself, {}, []) === itself)", + "true", + ); + expect_eval(lock, ctx, "String(new itself() === itself)", "true"); + expect_eval( + lock, + ctx, + "String(Object.create(itself).constructor === itself.constructor)", + "true", + ); + }); +} + +// An object that inherits from the callable is not callable itself. +#[test] +fn inheriting_object_is_not_callable() { + with_globals(|lock, ctx| { + expect_eval(lock, ctx, "typeof Object.create(itself)", "object"); + expect_error( + lock, + ctx, + "Object.create(itself)()", + ExceptionType::TypeError, + ); + }); +} + +// ============================================================================= +// Arguments and results +// ============================================================================= + +#[test] +fn arguments_are_converted_as_for_a_method() { + with_globals(|lock, ctx| { + expect_eval(lock, ctx, "String(counter(2))", "2"); + expect_eval(lock, ctx, "String(counter(3, 2))", "8"); + expect_eval(lock, ctx, "String(counter.total())", "8"); + // Extra arguments are ignored. + expect_eval(lock, ctx, "String(counter(1, 1, 'extra'))", "9"); + }); +} + +// Errors name the method as C++ JSG's `JSG_CALLABLE` does. +#[test] +fn argument_errors_name_the_call() { + with_globals(|lock, ctx| { + assert_eq!( + expect_error(lock, ctx, "counter()", ExceptionType::TypeError), + "Failed to execute '(called as function)' on 'Counter': parameter 1 is not of type \ + 'number'." + ); + assert_eq!( + expect_error(lock, ctx, "stub(Symbol())", ExceptionType::TypeError), + "Cannot convert a Symbol value to a string" + ); + expect_eval(lock, ctx, "String(counter.total())", "0"); + }); +} + +#[test] +fn error_is_thrown() { + with_globals(|lock, ctx| { + assert_eq!( + expect_error(lock, ctx, "itself('fail')", ExceptionType::RangeError), + "failed" + ); + expect_eval(lock, ctx, "String(itself() === itself)", "true"); + }); +} + +// ============================================================================= +// With a wildcard property +// ============================================================================= + +// A callable resource with a wildcard property has the shape of a JS RPC stub: properties of +// any name, each callable in turn. +#[test] +fn callable_with_wildcard_property() { + with_globals(|lock, ctx| { + expect_eval(lock, ctx, "stub('x')", "stub(x)"); + expect_eval(lock, ctx, "stub.foo('x')", "stub.foo(x)"); + expect_eval(lock, ctx, "stub.foo.bar('y')", "stub.foo.bar(y)"); + expect_eval(lock, ctx, "typeof stub.foo", "function"); + expect_eval( + lock, + ctx, + "const m = stub.method; m('torn off')", + "stub.method(torn off)", + ); + }); +} diff --git a/src/rust/jsg-test/tests/mod.rs b/src/rust/jsg-test/tests/mod.rs index b53a3c09a2d..6069650eb51 100644 --- a/src/rust/jsg-test/tests/mod.rs +++ b/src/rust/jsg-test/tests/mod.rs @@ -8,6 +8,7 @@ mod async_context; mod boolean; mod buffer_types; mod builtin_module; +mod callable; mod cell; mod coercion_safety; mod collections_gc; diff --git a/src/rust/jsg/README.md b/src/rust/jsg/README.md index 46c48e66d6f..473141217b6 100644 --- a/src/rust/jsg/README.md +++ b/src/rust/jsg/README.md @@ -1298,6 +1298,44 @@ A wildcard property behaves as in C++ JSG: - A wildcard property named `then` makes the object a thenable, which `await` would call. Return `None` for `then` unless that is intended. +## Callable resources + +`#[jsg_callable]`, the equivalent of C++ JSG's `JSG_CALLABLE`, makes the instances of a resource +type callable as functions: + +```rust +#[jsg_resource] +impl Statement { + // `statement(1, 2)` runs the method. + #[jsg_callable] + pub fn run(&self, lock: &mut jsg::Lock, a: f64, b: Option) -> String { + /* ... */ + } +} +``` + +A callable resource behaves as in C++ JSG: + +- The method takes `&self`, or `this: jsg::Rc` in its place, and otherwise has the shape + of a `#[jsg_method]`: an optional `lock: &mut jsg::Lock`, then the JavaScript arguments, which + are converted as a method's are. An argument error names the method `(called as function)`. + A type is callable at most one way, though `custom_members` may choose between several by + compatibility flag. The method may also be a `#[jsg_method]`, to be callable both ways. +- The method runs whether the instance is called with or without `new`. +- `this` is always the instance, however the call names it: a callable read from another object + (`const f = obj.method; f()`), or called with `Reflect.apply()` and another receiver, still runs + on the instance. The resource cannot tell how it was called. +- `typeof` is `"function"`, but the instance is an ordinary instance of the resource type: its + prototype is the type's prototype, not `Function.prototype`, so it has no `call`, `apply` or + `bind`, and `instanceof Function` is false. +- Only the instance is callable: an object that inherits from it, as `Object.create(obj)` does, + is not. +- With a [wildcard property](#wildcard-properties) as well, every property can be callable, which + is how C++ JSG's RPC stubs are built. +- RTTI describes the method as the type's call signature (the `callable` of its structure), as + C++ RTTI describes a `JSG_CALLABLE`. The TypeScript generator does not read it, so C++ types + declare their call signatures with `JSG_TS_OVERRIDE`. + ## Static Constants To expose numeric constants on a resource class (equivalent to `JSG_STATIC_CONSTANT` in C++), use `#[jsg_static_constant]` on `const` items inside a `#[jsg_resource]` impl block: diff --git a/src/rust/jsg/ffi.c++ b/src/rust/jsg/ffi.c++ index e32abd15603..b45ef0dbcd3 100644 --- a/src/rust/jsg/ffi.c++ +++ b/src/rust/jsg/ffi.c++ @@ -1575,6 +1575,14 @@ Global create_resource_template(Isolate* isolate, const ResourceDescriptor& desc setWildcardProperty(instance, wildcard, registerExternalRef); } + // Mirrors registerCallable() (resource.h): the call handler goes on the instance, not the + // prototype, and V8 runs it with the instance as `this`. + KJ_IF_SOME(callable, descriptor.callable) { + instance->SetCallAsFunctionHandler( + reinterpret_cast(reinterpret_cast(callable))); + registerExternalRef(callable); + } + auto result = scope.Escape(constructor); return to_ffi(v8::Global(isolate, result)); } diff --git a/src/rust/jsg/lib.rs b/src/rust/jsg/lib.rs index 567508ec132..c8255cf5fa9 100644 --- a/src/rust/jsg/lib.rs +++ b/src/rust/jsg/lib.rs @@ -1169,6 +1169,12 @@ pub enum Member { getter_callback: RawWildcardGetterCallback, query_callback: RawWildcardQueryCallback, }, + /// Makes every instance callable as a function, like C++ JSG's `JSG_CALLABLE`: calling the + /// instance, with or without `new`, runs `callback` with the instance as `this`, however the + /// call names it. A type has at most one. + Callable { + callback: RawFunctionCallback, + }, /// Another resource type's constructor, as a property of this type's /// prototype named `name`, like C++ JSG's `JSG_NESTED_TYPE`. Nested types /// are installed after every other member, whatever their position. diff --git a/src/rust/jsg/resource.rs b/src/rust/jsg/resource.rs index 1a6e4798328..287ab3ac1f0 100644 --- a/src/rust/jsg/resource.rs +++ b/src/rust/jsg/resource.rs @@ -527,6 +527,7 @@ fn get_resource_descriptor( static_methods: Vec::new(), static_constants: Vec::new(), wildcard_property: KjMaybe::None, + callable: KjMaybe::None, }; let mut members = TemplateMembers(Vec::new()); @@ -634,6 +635,14 @@ fn get_resource_descriptor( query_callback: query_callback as usize, }); } + Member::Callable { callback } => { + assert!( + descriptor.callable.is_none(), + "{} is callable more than one way", + R::class_name() + ); + descriptor.callable = KjMaybe::Some(callback as usize); + } Member::NestedType { name, nested_type } => nested_types.push((name, nested_type)), } } diff --git a/src/rust/jsg/rtti-test.rs b/src/rust/jsg/rtti-test.rs index a3af838184c..a9b1fdd4877 100644 --- a/src/rust/jsg/rtti-test.rs +++ b/src/rust/jsg/rtti-test.rs @@ -407,6 +407,83 @@ fn bridge_contexts_take_canonical_flags() { ); } +struct CallableNode; + +impl TypeInfo for CallableNode { + fn describe(cx: &mut Context) -> Type { + cx.structure::("CallableNode", true, |_| { + vec![ + Member::Callable { + args: vec![Parameter { + name: "value", + ty: Type::String, + }], + result: Type::Boolean, + }, + Member::Constant { + name: "LIMIT", + value: crate::ConstantValue::Number(1.0), + }, + ] + }) + } +} + +// As C++ RTTI writes a `JSG_CALLABLE`, the signature is the structure's `callable`, not one of +// its members. +#[test] +fn callable_is_the_structures_callable_signature() { + let mut cx = Context::default(); + CallableNode::describe(&mut cx); + let message = read_context(&cx); + let root = message + .get_root::() + .unwrap(); + let structure = root + .get_groups() + .unwrap() + .get(0) + .get_structures() + .unwrap() + .get(0); + assert!(structure.has_callable()); + let callable = structure.get_callable().unwrap(); + assert!(matches!( + callable.get_return_type().unwrap().which().unwrap(), + rtti_capnp::type_::Boolt(()) + )); + let args = callable.get_args().unwrap(); + assert_eq!(args.len(), 1); + assert!(matches!( + args.get(0).which().unwrap(), + rtti_capnp::type_::String(_) + )); + let members = structure.get_members().unwrap(); + assert_eq!(members.len(), 1); + assert!(matches!( + members.get(0).which().unwrap(), + rtti_capnp::member::Constant(_) + )); +} + +#[test] +fn structure_without_callable_has_none() { + let mut cx = Context::default(); + Node::describe(&mut cx); + let message = read_context(&cx); + let root = message + .get_root::() + .unwrap(); + let structure = root + .get_groups() + .unwrap() + .get(0) + .get_structures() + .unwrap() + .get(0); + assert!(!structure.has_callable()); +} + #[test] fn handles_are_described_as_their_values() { let mut cx = Context::default(); diff --git a/src/rust/jsg/rtti.rs b/src/rust/jsg/rtti.rs index 4db47a7fe22..d2b2e96baf9 100644 --- a/src/rust/jsg/rtti.rs +++ b/src/rust/jsg/rtti.rs @@ -96,6 +96,12 @@ pub enum Member { name: &'static str, value: crate::ConstantValue, }, + /// The signature of calling an instance as a function. It is not a member of the encoded + /// structure but its `callable` field, as C++ RTTI writes a `JSG_CALLABLE`. + Callable { + args: Vec, + result: Type, + }, } struct Structure { @@ -238,9 +244,19 @@ impl Context { } nesting.push(index); builder.set_ts_root(structure.root); - let mut members = builder.init_members(length(structure.members.len())); - for (i, member) in structure.members.iter().enumerate() { - member.write(self, members.reborrow().get(length(i)), nesting); + let (callables, members): (Vec<_>, Vec<_>) = structure + .members + .iter() + .partition(|member| matches!(member, Member::Callable { .. })); + // Template creation rejects a type that is callable more than one way. + if let Some(Member::Callable { args, result }) = callables.first() { + let mut callable = builder.reborrow().init_callable(); + result.write(callable.reborrow().init_return_type()); + write_args(args, callable.init_args(length(args.len()))); + } + let mut builders = builder.init_members(length(members.len())); + for (i, member) in members.into_iter().enumerate() { + member.write(self, builders.reborrow().get(length(i)), nesting); } nesting.pop(); } @@ -405,6 +421,9 @@ impl Member { crate::ConstantValue::Number(value) => constant.set_number_value(*value), } } + Self::Callable { .. } => { + unreachable!("Context::write_structure writes a callable as the structure's") + } } } } diff --git a/src/rust/jsg/v8.rs b/src/rust/jsg/v8.rs index a89d1843924..466d420efe1 100644 --- a/src/rust/jsg/v8.rs +++ b/src/rust/jsg/v8.rs @@ -807,6 +807,8 @@ pub mod ffi { pub static_methods: Vec, pub static_constants: Vec, pub wildcard_property: KjMaybe, + /// The `v8::FunctionCallback` that runs when an instance is called as a function. + pub callable: KjMaybe, } // Resources