Skip to content

perf(napi): share class accessor trampolines - #3364

Merged
Brooooooklyn merged 10 commits into
napi-rs:mainfrom
intellild:codex/class-accessor-trampoline
Jul 2, 2026
Merged

Brooooooklyn merged 10 commits into
napi-rs:mainfrom
intellild:codex/class-accessor-trampoline

Conversation

@intellild

@intellild intellild commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This PR reduces duplicated generated glue for class getters/setters by moving the common N-API callback work into shared runtime trampolines.

Rspack's optimized build size moved from +19.94KB to -208.06KB after this change:

web-infra-dev/rspack#14643

Why this reduces binary size

Before this change, every generated class accessor emitted its own full extern "C" callback wrapper. For example, a getter roughly expanded to:

extern "C" fn get_foo(
  env: napi::bindgen_prelude::sys::napi_env,
  cb: napi::bindgen_prelude::sys::napi_callback_info,
) -> napi::bindgen_prelude::sys::napi_value {
  unsafe {
    napi::bindgen_prelude::CallbackInfo::<0>::new(env, cb, None, false)
      .and_then(|mut cb| {
        let this_ptr = cb.unwrap_raw::<Foo>()?;
        let this: &Foo = Box::leak(Box::from_raw(this_ptr));

        let ret = this.foo();
        napi::bindgen_prelude::ToNapiValue::to_napi_value(env, ret)
      })
      // converted into the final napi_value here
  }
}

A setter had the same callback setup and argument extraction:

extern "C" fn set_foo(env, cb) -> napi_value {
  unsafe {
    napi::bindgen_prelude::CallbackInfo::<1>::new(env, cb, None, false)
      .and_then(|mut cb| {
        let this_ptr = cb.unwrap_raw::<Foo>()?;
        let this: &mut Foo = Box::leak(Box::from_raw(this_ptr));
        let arg0 = <T as napi::bindgen_prelude::FromNapiValue>::from_napi_value(
          env,
          cb.get_arg(0),
        )?;

        this.set_foo(arg0);
        <() as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, ())
      })
      // converted into the final napi_value here
  }
}

Most of that code is identical for every accessor:

  • napi_get_cb_info through CallbackInfo::new
  • extracting this
  • reading setter arguments
  • returning through the same N-API callback shape

The only accessor-specific part is the typed body:

let ret = this.foo();
ToNapiValue::to_napi_value(env, ret)

or:

let arg0 = FromNapiValue::from_napi_value(env, value)?;
this.set_foo(arg0);
ToNapiValue::to_napi_value(env, ())

This PR changes generated accessors to keep only that typed body and register a shared trampoline instead:

unsafe fn get_foo(
  env: napi::bindgen_prelude::sys::napi_env,
  this: napi::bindgen_prelude::sys::napi_value,
) -> napi::Result<napi::bindgen_prelude::sys::napi_value> {
  let this_ptr = napi::bindgen_prelude::class_accessor_unwrap_this::<Foo>(env, this)?;
  let this: &Foo = Box::leak(Box::from_raw(this_ptr));

  let ret = this.foo();
  napi::bindgen_prelude::ToNapiValue::to_napi_value(env, ret)
}

Registration now points every accessor at the shared runtime callback and passes the typed body through a descriptor:

static ACCESSOR_DESCRIPTOR: napi::bindgen_prelude::ClassAccessorDescriptor =
  napi::bindgen_prelude::ClassAccessorDescriptor {
    getter: Some(get_foo),
    setter: Some(set_foo),
  };

napi::bindgen_prelude::Property::new()
  .with_utf8_name("foo")
  .unwrap()
  .with_getter(napi::bindgen_prelude::class_getter_trampoline)
  .with_setter(napi::bindgen_prelude::class_setter_trampoline)
  .with_data(&ACCESSOR_DESCRIPTOR as *const _ as *mut _)

The runtime trampoline is emitted once in napi, not once per accessor:

pub unsafe extern "C" fn class_getter_trampoline(env, cb_info) -> napi_value {
  // napi_get_cb_info
  // load this
  // load ClassAccessorDescriptor from data
  // call descriptor.getter(env, this)
}

So the generated text section no longer grows with a full callback wrapper for every getter/setter. It grows mostly with the accessor-specific typed body, which is the part that cannot be shared.

This also covers struct field accessors generated from #[napi(getter, setter)], which had the same repeated callback wrapper shape.

Benchmark

Ran yarn workspace bench bench class-accessor.bench.ts three times on main and this branch. Results are 3-run averages in ops/s. There is no obvious performance change; the differences are basically measurement noise.

case main avg this branch avg change
#[napi] impl getter/setter 15,205.78 ops/s 15,570.95 ops/s +2.40%
#[napi(getter, setter)] field 15,104.07 ops/s 15,501.80 ops/s +2.63%
JavaScript getter/setter baseline 4,114,124.45 ops/s 4,063,479.42 ops/s -1.23%

Validation

  • cargo fmt
  • cargo check -p napi -p napi-derive-backend
  • cargo test -p napi-derive-backend
  • cargo check -p napi-examples

by OpenAI Codex

Summary by CodeRabbit

  • New Features

    • Added support for class property accessors backed by native getter/setter bindings.
    • Improved handling of class instance access in generated bindings, including safer callback context handling.
    • Added benchmark coverage for comparing native class accessors with a JavaScript baseline.
  • Bug Fixes

    • Fixed property binding behavior so custom data and closure-backed properties are handled more reliably.
    • Improved error handling when native accessors or callbacks panic, returning cleaner runtime errors.

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds runtime class accessor trampolines and descriptor types, updates backend codegen to emit accessor-specific entrypoints and wiring, changes property descriptors to carry raw data while filtering closure registration from precomputed descriptors, and adds benchmark bindings for accessor paths.

Changes

Class accessor trampoline mechanism

Layer / File(s) Summary
Accessor descriptor and trampolines
crates/napi/src/bindgen_runtime/class_accessor.rs, crates/napi/src/bindgen_runtime/mod.rs
Defines ClassAccessorDescriptor and ClassAccessorCallbackInfo<N>, adds an unwrap helper, implements getter/setter trampolines, and re-exports the new module.
Accessor codegen and registration
crates/backend/src/codegen/fn.rs, crates/backend/src/codegen/struct.rs
Generates dedicated accessor entrypoints for non-async class getters/setters, updates cb.this() token emission, builds per-field accessor descriptors, wires trampoline-based registration with .with_data(...), and emits descriptor statics in the helper module.
Property data and closure collection
crates/napi/src/js_values/object_property.rs, crates/napi/src/bindgen_runtime/js_values/object.rs, crates/napi/src/js_values/mod.rs
Adds Property::data and with_data, updates raw() to use the stored data pointer, and changes property descriptor/closure collection to use precomputed descriptors and only include closure-backed entries.
Accessor benchmarks
bench/src/lib.rs, bench/src/class_accessor.rs, bench/class-accessor.bench.ts
Adds benchmark exports for field-based and impl-based class accessors and defines Rust and JS benchmark cases that exercise those access paths.

Estimated code review effort: 4 (Complex) | ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: shared class accessor trampolines for N-API accessors.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@intellild

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/napi/src/bindgen_runtime/js_values/object.rs (1)

466-474: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Build property descriptors once before collecting closure finalizers.

Property::raw() allocates closure data, so calling it here and again for napi_define_properties registers the finalizer for a different allocation than the descriptor passed to N-API.

Proposed fix
-    let properties_iter = properties.iter().map(|property| property.raw());
+    let property_descriptors = properties
+      .iter()
+      .map(|property| property.raw())
+      .collect::<Vec<sys::napi_property_descriptor>>();
     let env = self.value().env;
     #[cfg(feature = "napi5")]
     {
       if !properties.is_empty() {
         let mut closures = properties
           .iter()
+          .zip(property_descriptors.iter())
           .filter(|property| property.has_closure_data())
-          .map(|property| property.raw().data)
+          .map(|(_, descriptor)| descriptor.data)
           .filter(|data| !data.is_null())
           .collect::<Vec<*mut std::ffi::c_void>>();
@@
         self.value().value,
         properties.len(),
-        properties_iter
-          .collect::<Vec<sys::napi_property_descriptor>>()
-          .as_ptr(),
+        property_descriptors.as_ptr(),
       )
     })

Also applies to: 501-503

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/napi/src/bindgen_runtime/js_values/object.rs` around lines 466 - 474,
Build the property descriptors once and reuse them for both closure finalizer
collection and the N-API property definition call. In the object properties flow
around properties.iter(), self.value().env, and the napi5 closure-data branch,
stop calling Property::raw() multiple times on the same Property; instead
materialize the descriptors a single time, then use that same descriptor set for
collecting closure data and for napi_define_properties so the finalizer matches
the exact allocation passed to N-API. Apply the same refactor to the later
properties handling section referenced by the same Property::raw() usage.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/backend/src/codegen/fn.rs`:
- Around line 168-175: `gen_fn_return` currently generates self-returning
accessor code against `ClassAccessorCallbackInfo`, but `cb.this` is no longer
accessible because that field is private. Update the accessor path in
`gen_fn_return` (or the accessor callback generation around
`ClassAccessorCallbackInfo::new`) so `&Self`/`&mut Self` returns use the public
`cb.this()` API, or otherwise expose an equivalent accessor-specific field on
the callback info type.

In `@crates/napi/src/js_values/mod.rs`:
- Around line 613-619: Reuse the same raw property descriptors for both
finalizers and napi_define_properties in the js_values module. In the code
around properties_iter and the napi5 closure handling, avoid calling
property.raw().data separately for the closure-data path if those descriptors
are later passed into N-API; instead, build the raw descriptors once and use
that shared data for both the finalizer setup and the define-properties call.
Apply the same change to the other affected object-path block mentioned in the
comment so both paths use a single raw descriptor allocation.

---

Outside diff comments:
In `@crates/napi/src/bindgen_runtime/js_values/object.rs`:
- Around line 466-474: Build the property descriptors once and reuse them for
both closure finalizer collection and the N-API property definition call. In the
object properties flow around properties.iter(), self.value().env, and the napi5
closure-data branch, stop calling Property::raw() multiple times on the same
Property; instead materialize the descriptors a single time, then use that same
descriptor set for collecting closure data and for napi_define_properties so the
finalizer matches the exact allocation passed to N-API. Apply the same refactor
to the later properties handling section referenced by the same Property::raw()
usage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 320fe217-ea20-4ccf-b5d3-a3ae92a7e5e5

📥 Commits

Reviewing files that changed from the base of the PR and between f72afd5 and a28a3b5.

📒 Files selected for processing (7)
  • crates/backend/src/codegen/fn.rs
  • crates/backend/src/codegen/struct.rs
  • crates/napi/src/bindgen_runtime/class_accessor.rs
  • crates/napi/src/bindgen_runtime/js_values/object.rs
  • crates/napi/src/bindgen_runtime/mod.rs
  • crates/napi/src/js_values/mod.rs
  • crates/napi/src/js_values/object_property.rs

Comment thread crates/backend/src/codegen/fn.rs Resolved
Comment thread crates/napi/src/js_values/mod.rs Resolved
@intellild

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
crates/backend/src/codegen/fn.rs (1)

130-175: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep accessor argument conversions inside catch_unwind.

Lines 173-174 run #arg_conversions before Line 175’s #function_call, but the catch_unwind branch only wraps #native_call. For generated accessors, a panic during unwrap_raw/FromNapiValue conversion can still escape through the class accessor trampoline instead of becoming a napi::Error.

Proposed restructuring
+      let function_call_inner = quote! {
+        let __wrapped_env = napi::bindgen_prelude::Env::from(env);
+        #(`#arg_conversions`)*
+        `#native_call`
+      };
+
       let function_call = if self.catch_unwind {
         quote! {
           {
-            std::panic::catch_unwind(|| { `#native_call` })
+            std::panic::catch_unwind(|| { `#function_call_inner` })
               .map_err(|e| {
                 let message = {
                   if let Some(string) = e.downcast_ref::<String>() {
@@
       } else {
         quote! {
-          `#native_call`
+          `#function_call_inner`
         }
       };
@@
             let mut cb = napi::bindgen_prelude::ClassAccessorCallbackInfo::<`#args_len`>::new(
               env,
               this,
               __napi_accessor_args,
             );
-            let __wrapped_env = napi::bindgen_prelude::Env::from(env);
-            #(`#arg_conversions`)*
             `#function_call`
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/backend/src/codegen/fn.rs` around lines 130 - 175, The class accessor
trampoline in fn.rs only wraps `#native_call` in std::panic::catch_unwind, so
`#arg_conversions` can still panic before the guard. Move the argument conversion
work for `#intermediate_ident` inside the catch_unwind scope used by
function_call, or otherwise wrap both `#accessor_args/`#arg_conversions and the
native call together, so any panic from unwrap_raw or FromNapiValue is converted
into napi::Error.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@crates/backend/src/codegen/fn.rs`:
- Around line 130-175: The class accessor trampoline in fn.rs only wraps
`#native_call` in std::panic::catch_unwind, so `#arg_conversions` can still panic
before the guard. Move the argument conversion work for `#intermediate_ident`
inside the catch_unwind scope used by function_call, or otherwise wrap both
`#accessor_args/`#arg_conversions and the native call together, so any panic from
unwrap_raw or FromNapiValue is converted into napi::Error.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: dd235256-b841-4c6d-b781-a589471256cd

📥 Commits

Reviewing files that changed from the base of the PR and between a28a3b5 and 1890259.

📒 Files selected for processing (4)
  • crates/backend/src/codegen/fn.rs
  • crates/backend/src/codegen/struct.rs
  • crates/napi/src/bindgen_runtime/js_values/object.rs
  • crates/napi/src/js_values/mod.rs
🚧 Files skipped from review as they are similar to previous changes (2)
  • crates/napi/src/js_values/mod.rs
  • crates/napi/src/bindgen_runtime/js_values/object.rs

@intellild

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@intellild
intellild marked this pull request as ready for review July 1, 2026 09:14
@intellild
intellild marked this pull request as draft July 1, 2026 11:05
@intellild
intellild marked this pull request as ready for review July 1, 2026 11:25
@Brooooooklyn

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 5575e4ad54

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@Brooooooklyn

Copy link
Copy Markdown
Member

@intellild please fix clippy error

@Brooooooklyn
Brooooooklyn merged commit 324c550 into napi-rs:main Jul 2, 2026
55 checks passed
@github-actions github-actions Bot mentioned this pull request Jul 2, 2026
@intellild
intellild deleted the codex/class-accessor-trampoline branch July 2, 2026 05:53
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