Repository navigation
perf(napi): share class accessor trampolines - #3364
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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. ChangesClass accessor trampoline mechanism
Estimated code review effort: 4 (Complex) | ~60 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
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 winBuild property descriptors once before collecting closure finalizers.
Property::raw()allocates closure data, so calling it here and again fornapi_define_propertiesregisters 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
📒 Files selected for processing (7)
crates/backend/src/codegen/fn.rscrates/backend/src/codegen/struct.rscrates/napi/src/bindgen_runtime/class_accessor.rscrates/napi/src/bindgen_runtime/js_values/object.rscrates/napi/src/bindgen_runtime/mod.rscrates/napi/src/js_values/mod.rscrates/napi/src/js_values/object_property.rs
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
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 winKeep accessor argument conversions inside
catch_unwind.Lines 173-174 run
#arg_conversionsbefore Line 175’s#function_call, but thecatch_unwindbranch only wraps#native_call. For generated accessors, a panic duringunwrap_raw/FromNapiValueconversion can still escape through the class accessor trampoline instead of becoming anapi::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
📒 Files selected for processing (4)
crates/backend/src/codegen/fn.rscrates/backend/src/codegen/struct.rscrates/napi/src/bindgen_runtime/js_values/object.rscrates/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
|
@coderabbitai review |
✅ Action performedReview finished.
|
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@intellild please fix clippy error |
… into codex/class-accessor-trampoline
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.94KBto-208.06KBafter 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:A setter had the same callback setup and argument extraction:
Most of that code is identical for every accessor:
napi_get_cb_infothroughCallbackInfo::newthisThe only accessor-specific part is the typed body:
or:
This PR changes generated accessors to keep only that typed body and register a shared trampoline instead:
Registration now points every accessor at the shared runtime callback and passes the typed body through a descriptor:
The runtime trampoline is emitted once in
napi, not once per accessor: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.tsthree times onmainand this branch. Results are 3-run averages inops/s. There is no obvious performance change; the differences are basically measurement noise.#[napi] implgetter/setter#[napi(getter, setter)]fieldValidation
cargo fmtcargo check -p napi -p napi-derive-backendcargo test -p napi-derive-backendcargo check -p napi-examplesby OpenAI Codex
Summary by CodeRabbit
New Features
Bug Fixes