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
5 changes: 3 additions & 2 deletions src/rust/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>`, `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<T>`, 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 |
Expand All @@ -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<T>` is `T | undefined`; `Nullable<T>` is `T | null` (coerces `undefined` to `Null`, but method arguments remain required). Prefer `NullOrUndefined<T>` to `Option<Nullable<T>>` for three distinct `Some(T)`, `Null`, and `Undefined` states; omitted arguments become `Undefined`. `Lenient<T>` additionally preserves shallow mismatches as `Unconvertable`; converting it to `NullOrUndefined<T>` 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<Self>` 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<Self, E>` (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!(<T: jsg::HoldsNoGcReferences> Foo<T>)` 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<Self>` 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<Self, E>` (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!(<T: jsg::HoldsNoGcReferences> Foo<T>)` 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::<R>`, a `kj::Maybe<bool>` 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 `<rust_name>_member()` (constant names lowercased); ordinary property factories are `<getter_name>_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<Self>`) 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 `<name>_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<GlobalSlot>`, 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<Self>` 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<T>` and `RefCell<T>` 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
Expand Down
64 changes: 64 additions & 0 deletions src/rust/jsg-compile-tests/callable-shape.rs
Original file line number Diff line number Diff line change
@@ -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<Self>`, 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<Self>` 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<Self>) {
//~^ 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) {}
}
84 changes: 84 additions & 0 deletions src/rust/jsg-compile-tests/ok-callable-shapes.rs
Original file line number Diff line number Diff line change
@@ -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<bool>,
) -> Result<String, jsg::Error> {
let _ = (lock, b);
Ok(a)
}
}

#[jsg_resource]
pub struct WithThis;

#[jsg_resource]
impl WithThis {
#[jsg_callable]
pub fn call(this: jsg::Rc<Self>, lock: &mut jsg::Lock) -> jsg::Rc<Self> {
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());
}
}
}
31 changes: 30 additions & 1 deletion src/rust/jsg-macros/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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` /
Expand Down Expand Up @@ -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<Self>` 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 `<name>_callable_callback()` and, through
`#[jsg_resource]`, the factory `<name>_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 —
Expand Down
Loading
Loading