Skip to content

Commit

Permalink
fix(napi-derive,cli): register function cross crates
Browse files Browse the repository at this point in the history
  • Loading branch information
Brooooooklyn committed Dec 10, 2023
1 parent 589d959 commit 6a73868
Show file tree
Hide file tree
Showing 14 changed files with 531 additions and 761 deletions.
45 changes: 25 additions & 20 deletions cli/src/api/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -609,18 +609,27 @@ class Builder {
const intermediateWasiRegisterFile = this.envs.WASI_REGISTER_TMP_PATH
const wasiRegisterFunctions =
this.target.arch === 'wasm32'
? JSON.parse(
await readFileAsync(intermediateWasiRegisterFile, 'utf8').catch(
(err) => {
console.warn(
`Read ${colors.yellowBright(
intermediateWasiRegisterFile,
)} failed, reason: ${err.message}`,
)
return `[]`
},
),
)
? await (async function readIntermediateWasiRegisterFile() {
const fileContent = await readFileAsync(
intermediateWasiRegisterFile,
'utf8',
).catch((err) => {
console.warn(
`Read ${colors.yellowBright(
intermediateWasiRegisterFile,
)} failed, reason: ${err.message}`,
)
return ``
})
return fileContent
.split('\n')
.map((l) => l.trim())
.filter((l) => l.length)
.map((line) => {
const [_, fn] = line.split(':')
return fn.trim()
})
})()
: []
const jsOutput = await this.writeJsBinding(idents)
const wasmOutput = await this.writeWasiBinding(
Expand Down Expand Up @@ -780,18 +789,14 @@ class Builder {
const { name, dir } = parse(distFileName)
const newPath = join(dir, `${this.config.binaryName}.wasi.cjs`)
const workerPath = join(dir, 'wasi-worker.mjs')
const declareCodes = `const { ${idents.join(
', ',
)} } = __napiModule.exports\n`
const exportsCode = idents
.map((ident) => `module.exports.${ident} = ${ident}`)
.map(
(ident) => `module.exports.${ident} = __napiModule.exports.${ident}`,
)
.join(',\n')
await writeFileAsync(
newPath,
createWasiBinding(name, wasiRegisterFunctions) +
declareCodes +
exportsCode +
'\n',
createWasiBinding(name, wasiRegisterFunctions) + exportsCode + '\n',
'utf8',
)
await writeFileAsync(workerPath, WASI_WORKER_TEMPLATE, 'utf8')
Expand Down
2 changes: 1 addition & 1 deletion cli/src/api/load-wasi-template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule
function __napi_rs_initialize_modules(__napiInstance) {
${wasiRegisterFunctions
.map((name) => ` __napiInstance.exports['${name}']()`)
.map((name) => ` __napiInstance.exports['${name}']?.()`)
.join('\n')}
}
`
5 changes: 5 additions & 0 deletions crates/backend/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub struct NapiFn {
pub configurable: bool,
pub catch_unwind: bool,
pub unsafe_: bool,
pub register_name: Ident,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -86,6 +87,7 @@ pub struct NapiStruct {
pub comments: Vec<String>,
pub implement_iterator: bool,
pub use_custom_finalize: bool,
pub register_name: Ident,
}

#[derive(Debug, Clone, PartialEq, Eq)]
Expand Down Expand Up @@ -121,6 +123,7 @@ pub struct NapiImpl {
pub iterator_return_type: Option<Type>,
pub js_mod: Option<String>,
pub comments: Vec<String>,
pub register_name: Ident,
}

#[derive(Debug, Clone)]
Expand All @@ -131,6 +134,7 @@ pub struct NapiEnum {
pub js_mod: Option<String>,
pub comments: Vec<String>,
pub skip_typescript: bool,
pub register_name: Ident,
}

#[derive(Debug, Clone)]
Expand Down Expand Up @@ -164,6 +168,7 @@ pub struct NapiConst {
pub js_mod: Option<String>,
pub comments: Vec<String>,
pub skip_typescript: bool,
pub register_name: Ident,
}

#[derive(Debug, Clone)]
Expand Down
17 changes: 0 additions & 17 deletions crates/backend/src/codegen.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
use std::sync::atomic::AtomicUsize;

use proc_macro2::{Ident, Span, TokenStream};

use crate::BindgenResult;
Expand All @@ -14,12 +12,6 @@ pub const PROPERTY_ATTRIBUTE_WRITABLE: i32 = 1 << 0;
pub const PROPERTY_ATTRIBUTE_ENUMERABLE: i32 = 1 << 1;
pub const PROPERTY_ATTRIBUTE_CONFIGURABLE: i32 = 1 << 2;

static REGISTER_INDEX: AtomicUsize = AtomicUsize::new(0);

thread_local! {
pub static REGISTER_IDENTS: std::cell::RefCell<Vec<String>> = std::cell::RefCell::new(Vec::new());
}

pub trait TryToTokens {
fn try_to_tokens(&self, tokens: &mut TokenStream) -> BindgenResult<()>;

Expand All @@ -36,15 +28,6 @@ fn get_intermediate_ident(name: &str) -> Ident {
Ident::new(&new_name, Span::call_site())
}

fn get_register_ident(name: &str) -> Ident {
let new_name = format!(
"__napi_register__{}_{}",
name,
REGISTER_INDEX.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
);
Ident::new(&new_name, Span::call_site())
}

fn js_mod_to_token_stream(js_mod: Option<&String>) -> TokenStream {
js_mod
.map(|i| {
Expand Down
14 changes: 4 additions & 10 deletions crates/backend/src/codegen/const.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use proc_macro2::{Ident, Literal, TokenStream};
use quote::ToTokens;

use crate::{
codegen::{get_register_ident, js_mod_to_token_stream},
BindgenResult, NapiConst, TryToTokens,
};
use crate::{codegen::js_mod_to_token_stream, BindgenResult, NapiConst, TryToTokens};

impl TryToTokens for NapiConst {
fn try_to_tokens(&self, tokens: &mut TokenStream) -> BindgenResult<()> {
Expand All @@ -20,19 +17,16 @@ impl TryToTokens for NapiConst {

impl NapiConst {
fn gen_module_register(&self) -> TokenStream {
let name_str = self.name.to_string();
let name_ident = self.name.clone();
let name_ident = &self.name;
let js_name_lit = Literal::string(&format!("{}\0", self.name));
let register_name = get_register_ident(&name_str);
let register_name = &self.register_name;
let type_name = &self.type_name;
let cb_name = Ident::new(
&format!("__register__const__{}_callback__", register_name),
self.name.span(),
);
let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());
crate::codegen::REGISTER_IDENTS.with(|c| {
c.borrow_mut().push(register_name.to_string());
});

quote! {
#[allow(non_snake_case)]
#[allow(clippy::all)]
Expand Down
11 changes: 2 additions & 9 deletions crates/backend/src/codegen/enum.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::ToTokens;

use crate::{
codegen::{get_register_ident, js_mod_to_token_stream},
BindgenResult, NapiEnum, TryToTokens,
};
use crate::{codegen::js_mod_to_token_stream, BindgenResult, NapiEnum, TryToTokens};

impl TryToTokens for NapiEnum {
fn try_to_tokens(&self, tokens: &mut TokenStream) -> BindgenResult<()> {
Expand Down Expand Up @@ -103,7 +100,7 @@ impl NapiEnum {
fn gen_module_register(&self) -> TokenStream {
let name_str = self.name.to_string();
let js_name_lit = Literal::string(&format!("{}\0", &self.js_name));
let register_name = get_register_ident(&name_str);
let register_name = &self.register_name;

let mut define_properties = vec![];

Expand Down Expand Up @@ -134,10 +131,6 @@ impl NapiEnum {

let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());

crate::codegen::REGISTER_IDENTS.with(|c| {
c.borrow_mut().push(register_name.to_string());
});

quote! {
#[allow(non_snake_case)]
#[allow(clippy::all)]
Expand Down
8 changes: 3 additions & 5 deletions crates/backend/src/codegen/fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use quote::ToTokens;
use syn::spanned::Spanned;

use crate::{
codegen::{get_intermediate_ident, get_register_ident, js_mod_to_token_stream},
codegen::{get_intermediate_ident, js_mod_to_token_stream},
BindgenResult, CallbackArg, Diagnostic, FnKind, FnSelf, NapiFn, NapiFnArgKind, TryToTokens,
};

Expand Down Expand Up @@ -567,13 +567,11 @@ impl NapiFn {
let name_str = self.name.to_string();
let js_name = format!("{}\0", &self.js_name);
let name_len = self.js_name.len();
let module_register_name = get_register_ident(&name_str);
let module_register_name = &self.register_name;
let intermediate_ident = get_intermediate_ident(&name_str);
let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());
let cb_name = Ident::new(&format!("{}_js_function", name_str), Span::call_site());
crate::codegen::REGISTER_IDENTS.with(|c| {
c.borrow_mut().push(module_register_name.to_string());
});

quote! {
#[allow(non_snake_case)]
#[allow(clippy::all)]
Expand Down
12 changes: 3 additions & 9 deletions crates/backend/src/codegen/struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::ToTokens;

use crate::{
codegen::{get_intermediate_ident, get_register_ident, js_mod_to_token_stream},
codegen::{get_intermediate_ident, js_mod_to_token_stream},
BindgenResult, FnKind, NapiImpl, NapiStruct, NapiStructKind, TryToTokens,
};

Expand Down Expand Up @@ -717,7 +717,7 @@ impl NapiStruct {

fn gen_register(&self) -> TokenStream {
let name_str = self.name.to_string();
let struct_register_name = get_register_ident(&format!("{}_struct", name_str));
let struct_register_name = &self.register_name;
let js_name = format!("{}\0", self.js_name);
let mut props = vec![];

Expand Down Expand Up @@ -772,9 +772,6 @@ impl NapiStruct {
props.push(prop);
}
let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());
crate::codegen::REGISTER_IDENTS.with(|c| {
c.borrow_mut().push(struct_register_name.to_string());
});
quote! {
#[allow(non_snake_case)]
#[allow(clippy::all)]
Expand Down Expand Up @@ -842,7 +839,7 @@ impl NapiImpl {
Span::call_site(),
);

let register_name = get_register_ident(&format!("{}_impl", name_str));
let register_name = &self.register_name;

let mut methods = vec![];
let mut props = HashMap::new();
Expand Down Expand Up @@ -891,9 +888,6 @@ impl NapiImpl {
let props = props.into_iter().map(|(_, prop)| prop);
let props_wasm = props.clone();
let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());
crate::codegen::REGISTER_IDENTS.with(|c| {
c.borrow_mut().push(register_name.to_string());
});
Ok(quote! {
#[allow(non_snake_case)]
#[allow(clippy::all)]
Expand Down
8 changes: 8 additions & 0 deletions crates/backend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ macro_rules! napi_ast_impl {
}
}
}

impl Napi {
pub fn register_name(&self) -> String {
match self.item {
$( NapiItem::$v(ref ast) => ast.register_name.to_string() ),*
}
}
}
};
}

Expand Down
Loading

1 comment on commit 6a73868

@github-actions
Copy link

Choose a reason for hiding this comment

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

Benchmark

Benchmark suite Current: 6a73868 Previous: 589d959 Ratio
noop#napi-rs 85112250 ops/sec (±2.02%) 86551753 ops/sec (±0.3%) 1.02
noop#JavaScript 823471418 ops/sec (±0.07%) 822661730 ops/sec (±0.09%) 1.00
Plus number#napi-rs 24677092 ops/sec (±0.35%) 24047360 ops/sec (±0.27%) 0.97
Plus number#JavaScript 822752850 ops/sec (±0.09%) 821877453 ops/sec (±0.12%) 1.00
Create buffer#napi-rs 656337 ops/sec (±13.03%) 661045 ops/sec (±12.15%) 1.01
Create buffer#JavaScript 3764338 ops/sec (±2.3%) 3426355 ops/sec (±2.89%) 0.91
createArray#createArrayJson 55747 ops/sec (±0.56%) 53388 ops/sec (±0.73%) 0.96
createArray#create array for loop 10311 ops/sec (±0.35%) 10296 ops/sec (±0.47%) 1.00
createArray#create array with serde trait 10226 ops/sec (±0.49%) 10207 ops/sec (±0.65%) 1.00
getArrayFromJs#get array from json string 23231 ops/sec (±0.74%) 23653 ops/sec (±0.53%) 1.02
getArrayFromJs#get array from serde 13344 ops/sec (±0.41%) 11689 ops/sec (±0.41%) 0.88
getArrayFromJs#get array with for loop 16239 ops/sec (±0.69%) 16636 ops/sec (±0.5%) 1.02
Get Set property#Get Set from native#u32 573904 ops/sec (±12.89%) 564982 ops/sec (±12.28%) 0.98
Get Set property#Get Set from JavaScript#u32 541456 ops/sec (±2.32%) 546365 ops/sec (±2.3%) 1.01
Get Set property#Get Set from native#string 565145 ops/sec (±11.88%) 547550 ops/sec (±11.62%) 0.97
Get Set property#Get Set from JavaScript#string 520484 ops/sec (±1.97%) 511606 ops/sec (±1.99%) 0.98
Async task#spawn task 26765 ops/sec (±0.87%) 26688 ops/sec (±0.66%) 1.00
Async task#ThreadSafeFunction 9538 ops/sec (±0.67%) 9357 ops/sec (±1.16%) 0.98
Async task#Tokio future to Promise 32175 ops/sec (±0.99%) 32918 ops/sec (±0.7%) 1.02
Query#query * 100 3953 ops/sec (±0.5%) 3936 ops/sec (±1.32%) 1.00
Query#query * 1 28029 ops/sec (±1.49%) 28384 ops/sec (±1.19%) 1.01

This comment was automatically generated by workflow using github-action-benchmark.

Please sign in to comment.