1use proc_macro2::{Ident, Literal, TokenStream};
2use quote::ToTokens;
3
4use crate::{codegen::js_mod_to_token_stream, BindgenResult, NapiConst, TryToTokens};
5
6impl TryToTokens for NapiConst {
7 fn try_to_tokens(&self, tokens: &mut TokenStream) -> BindgenResult<()> {
8 let register: TokenStream = self.gen_module_register();
9 (quote! {
10 #register
11 })
12 .to_tokens(tokens);
13
14 Ok(())
15 }
16}
17
18impl NapiConst {
19 fn gen_module_register(&self) -> TokenStream {
20 let name_ident = &self.name;
21 let js_name_lit = Literal::string(&format!("{}\0", self.name));
22 let register_name = &self.register_name;
23 let type_name = &self.type_name;
24 let cb_name = Ident::new(
25 &format!("__register__const__{}_callback__", register_name),
26 self.name.span(),
27 );
28 let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());
29
30 quote! {
31 #[allow(non_snake_case)]
32 #[allow(clippy::all)]
33 unsafe fn #cb_name(env: napi::sys::napi_env) -> napi::Result<napi::sys::napi_value> {
34 <#type_name as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, #name_ident)
35 }
36 #[allow(non_snake_case)]
37 #[allow(clippy::all)]
38 #[cfg(all(not(test), not(feature = "noop"), not(target_family = "wasm")))]
39 #[napi::bindgen_prelude::ctor]
40 fn #register_name() {
41 napi::bindgen_prelude::register_module_export(#js_mod_ident, #js_name_lit, #cb_name);
42 }
43
44 #[allow(non_snake_case)]
45 #[allow(clippy::all)]
46 #[cfg(all(not(test), not(feature = "noop"), target_family = "wasm"))]
47 #[no_mangle]
48 unsafe extern "C" fn #register_name() {
49 napi::bindgen_prelude::register_module_export(#js_mod_ident, #js_name_lit, #cb_name);
50 }
51 }
52 }
53}
54