1use proc_macro2::TokenStream;
2use quote::{ToTokens, quote};
3use syn::{
4 Attribute, FnArg, ImplItem, ItemFn, ItemImpl, Meta, Pat, ReturnType, Signature, parse2,
5 spanned::Spanned,
6};
7
8use crate::{
9 attrs::{self, Args},
10 wire::{crosses_bare, from_wire_type, split_result, to_wire_type},
11};
12
13struct Shim {
15 moved: Args,
17 in_impl: bool,
20 export_name: syn::Ident,
22}
23
24fn build_shim(sig: &Signature, item_attrs: &[Attribute], shim: &Shim) -> syn::Result<TokenStream> {
26 let Shim {
27 moved,
28 in_impl,
29 export_name,
30 } = shim;
31
32 let callee = &sig.ident;
34
35 if !sig.generics.params.is_empty() {
36 return Err(syn::Error::new(
37 sig.generics.span(),
38 "#[wasm_export] does not support generic methods; wasm_bindgen cannot export them",
39 ));
40 }
41
42 let mut bindgen_args = moved.clone();
46 let named = moved.iter().any(|meta| meta.path().is_ident("js_name"));
47 let is_constructor = moved.iter().any(|meta| meta.path().is_ident("constructor"));
48 if !named && !is_constructor {
49 let name = export_name.to_string();
50 bindgen_args.push(Meta::NameValue(syn::parse_quote!(js_name = #name)));
51 }
52 let forwarded = if *in_impl {
56 quote!(#[wasm_bindgen(#bindgen_args)])
57 } else {
58 quote!(#[::bitwarden_ffi::_macro::wasm_bindgen(#bindgen_args)])
59 };
60
61 let mut receiver: Option<TokenStream> = None;
63 let mut params: Vec<TokenStream> = Vec::new();
64 let mut conversions: Vec<TokenStream> = Vec::new();
65 let mut call_args: Vec<TokenStream> = Vec::new();
66
67 for (i, input) in sig.inputs.iter().enumerate() {
68 match input {
69 FnArg::Receiver(recv) => receiver = Some(recv.to_token_stream()),
70 FnArg::Typed(pat_type) => {
71 let name = match &*pat_type.pat {
74 Pat::Ident(pat) => pat.ident.clone(),
75 _ => syn::Ident::new(&format!("__arg{i}"), pat_type.pat.span()),
76 };
77 let ty = &*pat_type.ty;
78
79 if crosses_bare(ty) {
80 params.push(quote!(#name: #ty));
81 } else {
82 let wire = from_wire_type(ty);
83 params.push(quote!(#name: #wire));
84 conversions.push(quote! {
85 let #name = <#ty as ::bitwarden_ffi::FromWasm>::from_wire(#name)
86 .map_err(::bitwarden_ffi::TsError::Conversion)?;
87 });
88 }
89 call_args.push(quote!(#name));
90 }
91 }
92 }
93
94 let is_async = sig.asyncness.is_some();
95 let await_tok = is_async.then(|| quote!(.await));
96 let async_tok = is_async.then(|| quote!(async));
97 let call = match (&receiver, in_impl) {
98 (Some(_), _) => quote!(self.#callee(#(#call_args),*)#await_tok),
99 (None, true) => quote!(Self::#callee(#(#call_args),*)#await_tok),
100 (None, false) => quote!(#callee(#(#call_args),*)#await_tok),
101 };
102
103 let ret_ty = match &sig.output {
104 ReturnType::Default => None,
105 ReturnType::Type(_, ty) => Some(&**ty),
106 };
107 let result_parts = ret_ty.and_then(split_result);
108 let returned = result_parts.map(|(ok, _)| ok).or(ret_ty);
110 let convert_return = returned.is_some_and(|ty| !crosses_bare(ty));
111
112 let all_params: Vec<TokenStream> = receiver.iter().cloned().chain(params).collect();
113 let carried = item_attrs
116 .iter()
117 .filter(|attr| attr.path().is_ident("doc") || attr.path().is_ident("cfg"));
118 let shim_ident = syn::Ident::new(&format!("__wasm_ts_{export_name}"), export_name.span());
119
120 let error = match result_parts {
126 Some((_, err_ty)) => quote!(::bitwarden_ffi::TsError<#err_ty>),
127 None => quote!(::bitwarden_ffi::TsError),
128 };
129 let produce = match result_parts {
130 Some(_) => quote!(#call.map_err(::bitwarden_ffi::TsError::Inner)?),
131 None => call,
132 };
133 let (output, tail) = match returned.filter(|_| convert_return) {
134 Some(ty) => (
135 to_wire_type(ty),
136 quote! {
137 <#ty as ::bitwarden_ffi::ToWasm>::to_wire(__out)
138 .map_err(::bitwarden_ffi::TsError::Conversion)
139 },
140 ),
141 None => (
143 returned.map_or_else(|| quote!(()), |ty| quote!(#ty)),
144 quote!(::core::result::Result::Ok(__out)),
145 ),
146 };
147
148 Ok(quote! {
149 #(#carried)*
150 #forwarded
151 #[doc(hidden)]
152 #[allow(deprecated)]
155 pub #async_tok fn #shim_ident(#(#all_params),*)
156 -> ::core::result::Result<#output, #error>
157 {
158 #(#conversions)*
159 let __out = #produce;
160 #tail
161 }
162 })
163}
164
165pub(crate) fn wasm_export(attr: TokenStream, item: TokenStream) -> TokenStream {
168 match parse2::<ItemImpl>(item.clone()) {
169 Ok(impl_block) => wasm_export_impl(attr, impl_block),
170 Err(impl_err) => match parse2::<ItemFn>(item) {
173 Ok(function) => wasm_export_fn(attr, function),
174 Err(_) => impl_err.to_compile_error(),
175 },
176 }
177}
178
179fn wasm_export_impl(attr: TokenStream, mut impl_block: ItemImpl) -> TokenStream {
181 let forwarded = match attrs::parse_args(attr) {
182 Ok(args) => args,
183 Err(err) => return err.to_compile_error(),
184 };
185
186 if let Err(err) = check_exportable(&impl_block.generics, &impl_block.attrs, "impl blocks") {
187 return err.to_compile_error();
188 }
189
190 let self_ty = impl_block.self_ty.clone();
191 let mut shims = Vec::new();
192
193 for item in &mut impl_block.items {
194 let ImplItem::Fn(method) = item else { continue };
195
196 let export_name = match apply_wasm_only(&mut method.attrs, &mut method.sig) {
199 Ok(name) => name,
200 Err(err) => return err.to_compile_error(),
201 };
202
203 if !matches!(method.vis, syn::Visibility::Public(_)) {
207 continue;
208 }
209
210 match take_shim(
211 &mut method.attrs,
212 &method.sig,
213 true,
214 export_name,
215 Args::new(),
216 ) {
217 Ok(shim) => shims.push(shim),
218 Err(err) => return err.to_compile_error(),
219 }
220 }
221
222 if shims.is_empty() {
223 return impl_block.into_token_stream();
224 }
225
226 let bindgen_args = (!forwarded.is_empty()).then(|| quote!((#forwarded)));
227 let cfgs = impl_block
229 .attrs
230 .iter()
231 .filter(|attr| attr.path().is_ident("cfg"))
232 .cloned()
233 .collect::<Vec<_>>();
234
235 quote! {
236 #impl_block
237
238 #(#cfgs)*
239 #[cfg(feature = "wasm")]
240 #[::bitwarden_ffi::_macro::wasm_bindgen #bindgen_args]
241 impl #self_ty {
242 #(#shims)*
243 }
244 }
245}
246
247fn wasm_export_fn(attr: TokenStream, mut function: ItemFn) -> TokenStream {
249 let forwarded = match attrs::parse_args(attr) {
250 Ok(args) => args,
251 Err(err) => return err.to_compile_error(),
252 };
253
254 if let Err(err) = check_exportable(&function.sig.generics, &function.attrs, "functions") {
255 return err.to_compile_error();
256 }
257
258 let export_name = match apply_wasm_only(&mut function.attrs, &mut function.sig) {
259 Ok(name) => name,
260 Err(err) => return err.to_compile_error(),
261 };
262
263 if !matches!(function.vis, syn::Visibility::Public(_)) {
264 return function.into_token_stream();
265 }
266
267 let shim = match take_shim(
269 &mut function.attrs,
270 &function.sig,
271 false,
272 export_name,
273 forwarded,
274 ) {
275 Ok(shim) => shim,
276 Err(err) => return err.to_compile_error(),
277 };
278
279 quote! {
280 #function
281
282 #[cfg(feature = "wasm")]
283 #shim
284 }
285}
286
287fn take_shim(
291 item_attrs: &mut Vec<Attribute>,
292 sig: &Signature,
293 in_impl: bool,
294 export_name: syn::Ident,
295 mut moved: Args,
296) -> syn::Result<TokenStream> {
297 item_attrs.retain(|attr| match attrs::wasm_bindgen_args(attr) {
299 Some(args) => {
300 moved.extend(args);
301 false
302 }
303 None => true,
304 });
305
306 build_shim(
307 sig,
308 item_attrs,
309 &Shim {
310 moved,
311 in_impl,
312 export_name,
313 },
314 )
315}
316
317fn check_exportable(
321 generics: &syn::Generics,
322 item_attrs: &[Attribute],
323 kind: &str,
324) -> syn::Result<()> {
325 if !generics.params.is_empty() {
326 return Err(syn::Error::new(
327 generics.span(),
328 format!(
329 "#[wasm_export] does not support generic {kind}; wasm_bindgen cannot export them"
330 ),
331 ));
332 }
333
334 if let Some(attr) = attrs::find_wasm_bindgen(item_attrs) {
335 return Err(syn::Error::new_spanned(
336 attr,
337 "#[wasm_export] replaces #[wasm_bindgen]; pass its arguments to #[wasm_export] \
338 instead, as in #[wasm_export(js_class = Foo)]",
339 ));
340 }
341
342 Ok(())
343}
344
345fn apply_wasm_only(attrs: &mut Vec<Attribute>, sig: &mut Signature) -> syn::Result<syn::Ident> {
352 let export_name = sig.ident.clone();
353 let idx = attrs.iter().position(|a| a.path().is_ident("wasm_only"));
354 let Some(idx) = idx else {
355 return Ok(export_name);
356 };
357 let note = wasm_only_note(&attrs.remove(idx))?;
358
359 attrs.push(syn::parse_quote!(#[doc(hidden)]));
360 attrs.push(syn::parse_quote!(#[deprecated(note = #note)]));
361 attrs.push(syn::parse_quote!(#[allow(deprecated)]));
362 sig.ident = syn::Ident::new(&format!("__wasm_only_{export_name}"), sig.ident.span());
363
364 Ok(export_name)
365}
366
367fn wasm_only_note(attr: &Attribute) -> syn::Result<String> {
369 const DEFAULT: &str = "This is a WASM-only binding. Calling it from Rust is not allowed.";
370 if attr.meta.require_path_only().is_ok() {
371 return Ok(DEFAULT.to_owned());
372 }
373
374 let mut note = None;
375 attr.parse_nested_meta(|meta| {
376 if meta.path.is_ident("note") {
377 note = Some(meta.value()?.parse::<syn::LitStr>()?.value());
378 Ok(())
379 } else {
380 Err(meta.error("unknown attribute, expected `note`"))
381 }
382 })?;
383 Ok(note.unwrap_or_else(|| DEFAULT.to_owned()))
384}
385
386#[cfg(test)]
387mod tests {
388 use super::*;
389
390 fn expand(attr: TokenStream, item: TokenStream) -> String {
393 wasm_export(attr, item).to_string().replace(' ', "")
394 }
395
396 #[test]
397 fn leaves_the_original_block_as_written_and_generates_a_shim_block() {
398 let out = expand(
399 TokenStream::new(),
400 quote! {
401 impl Canvas {
402 pub fn translate(&self, point: Point) -> Point { point }
403 }
404 },
405 );
406
407 assert!(!out.contains("compile_error!"), "{out}");
408 assert!(
410 out.contains("pubfntranslate(&self,point:Point)->Point{point}"),
411 "{out}"
412 );
413 assert!(
414 out.contains("#[::bitwarden_ffi::_macro::wasm_bindgen]implCanvas{"),
415 "{out}"
416 );
417 assert!(out.contains("fn__wasm_ts_translate"), "{out}");
418 }
419
420 #[test]
421 fn projects_parameters_and_returns_onto_their_wire_types() {
422 let out = expand(
423 TokenStream::new(),
424 quote! {
425 impl Canvas {
426 pub fn translate(&self, point: Point) -> Result<Point, MoveError> { Ok(point) }
427 }
428 },
429 );
430
431 assert!(out.contains("js_name=\"translate\""), "{out}");
432 assert!(
433 out.contains("<Pointas::bitwarden_ffi::FromWasm>::Wire"),
434 "{out}"
435 );
436 assert!(
437 out.contains("<Pointas::bitwarden_ffi::ToWasm>::Wire"),
438 "{out}"
439 );
440 assert!(out.contains("::bitwarden_ffi::TsError<MoveError>"), "{out}");
441 }
442
443 #[test]
444 fn projects_a_handle_type_the_same_way() {
445 let out = expand(
448 TokenStream::new(),
449 quote! {
450 impl VaultClient {
451 pub fn ciphers(&self) -> CiphersClient { todo!() }
452 }
453 },
454 );
455
456 assert!(
457 out.contains("<CiphersClientas::bitwarden_ffi::ToWasm>::Wire"),
458 "{out}"
459 );
460 }
461
462 #[test]
463 fn projects_the_impls_own_type_like_any_other() {
464 let out = expand(
468 TokenStream::new(),
469 quote! {
470 impl Canvas {
471 pub fn new() -> Self { Canvas }
472 }
473 },
474 );
475
476 assert!(
477 out.contains("<Selfas::bitwarden_ffi::ToWasm>::Wire"),
478 "{out}"
479 );
480 }
481
482 #[test]
483 fn defaults_the_error_for_an_infallible_method() {
484 let out = expand(
485 TokenStream::new(),
486 quote! {
487 impl Canvas {
488 pub fn width(&self) -> u32 { 0 }
489 }
490 },
491 );
492
493 assert!(out.contains("::bitwarden_ffi::TsError>"), "{out}");
494 assert!(!out.contains("TsError<"), "{out}");
495 }
496
497 #[test]
498 fn leaves_reference_parameters_alone() {
499 let out = expand(
501 TokenStream::new(),
502 quote! {
503 impl Canvas {
504 pub fn draw(&self, backend: &JsBackend) -> u32 { 0 }
505 }
506 },
507 );
508
509 assert!(out.contains("backend:&JsBackend"), "{out}");
510 assert!(!out.contains("<&JsBackendas"), "{out}");
511 }
512
513 #[test]
514 fn awaits_an_async_method() {
515 let out = expand(
516 TokenStream::new(),
517 quote! {
518 impl Canvas {
519 pub async fn save(&self, point: Point) -> Point { point }
520 }
521 },
522 );
523
524 assert!(out.contains("pubasyncfn__wasm_ts_save"), "{out}");
525 assert!(out.contains("self.save(point).await"), "{out}");
526 }
527
528 #[test]
529 fn calls_an_associated_function_through_self() {
530 let out = expand(
531 TokenStream::new(),
532 quote! {
533 impl Canvas {
534 pub fn blank(width: u32) -> Canvas { todo!() }
535 }
536 },
537 );
538
539 assert!(out.contains("Self::blank(width)"), "{out}");
540 }
541
542 #[test]
543 fn forwards_its_arguments_to_the_generated_block() {
544 let out = expand(
545 quote!(js_class = IpcClient),
546 quote! {
547 impl JsIpcClient {
548 pub fn is_running(&self) -> bool { true }
549 }
550 },
551 );
552
553 assert!(
554 out.contains("#[::bitwarden_ffi::_macro::wasm_bindgen(js_class=IpcClient)]"),
555 "{out}"
556 );
557 }
558
559 #[test]
560 fn moves_a_method_attribute_onto_its_shim() {
561 let out = expand(
563 TokenStream::new(),
564 quote! {
565 impl PolicyClient {
566 #[cfg_attr(feature = "wasm", wasm_bindgen(js_name = "get_enforced"))]
567 pub fn get_enforced(&self) {}
568 }
569 },
570 );
571
572 assert_eq!(out.matches("js_name=").count(), 1, "{out}");
573 assert!(out.contains("js_name=\"get_enforced\""), "{out}");
574 assert!(
575 !out.contains("cfg_attr(feature=\"wasm\",wasm_bindgen"),
576 "{out}"
577 );
578 }
579
580 #[test]
581 fn leaves_a_constructor_for_wasm_bindgen_to_name() {
582 let out = expand(
584 TokenStream::new(),
585 quote! {
586 impl JsIpcClient {
587 #[wasm_bindgen(constructor)]
588 pub fn new() -> JsIpcClient { todo!() }
589 }
590 },
591 );
592
593 assert!(!out.contains("js_name"), "{out}");
594 assert!(out.contains("fn__wasm_ts_new"), "{out}");
595 }
596
597 #[test]
598 fn carries_a_cfg_from_the_impl_block_onto_the_shim_block() {
599 let out = expand(
601 TokenStream::new(),
602 quote! {
603 #[cfg(target_arch = "wasm32")]
604 impl Canvas {
605 pub fn translate(&self, point: Point) -> Point { point }
606 }
607 },
608 );
609
610 assert_eq!(
611 out.matches("#[cfg(target_arch=\"wasm32\")]").count(),
612 2,
613 "{out}"
614 );
615 }
616
617 #[test]
618 fn carries_a_cfg_and_docs_from_a_method_onto_its_shim() {
619 let out = expand(
620 TokenStream::new(),
621 quote! {
622 impl Canvas {
623 #[cfg(feature = "geometry")]
625 pub fn translate(&self, point: Point) -> Point { point }
626 }
627 },
628 );
629
630 assert_eq!(
631 out.matches("#[cfg(feature=\"geometry\")]").count(),
632 2,
633 "{out}"
634 );
635 assert_eq!(out.matches("Translatesthepoint.").count(), 2, "{out}");
636 }
637
638 #[test]
639 fn renames_a_wasm_only_method_and_keeps_its_js_name_on_the_shim() {
640 let out = expand(
641 TokenStream::new(),
642 quote! {
643 impl JsIpcClient {
644 #[wasm_only]
645 pub fn is_running(&self) -> bool { true }
646 }
647 },
648 );
649
650 assert!(out.contains("fn__wasm_only_is_running"), "{out}");
651 assert!(out.contains("self.__wasm_only_is_running()"), "{out}");
652 assert!(out.contains("js_name=\"is_running\""), "{out}");
653 assert!(out.contains("#[doc(hidden)]"), "{out}");
654 assert!(
655 out.contains(
656 "#[deprecated(note=\"ThisisaWASM-onlybinding.CallingitfromRustisnotallowed.\")]"
657 ),
658 "{out}"
659 );
660 }
661
662 #[test]
663 fn carries_a_custom_note() {
664 let out = expand(
665 TokenStream::new(),
666 quote! {
667 impl JsIpcClient {
668 #[wasm_only(note = "Use `IpcClient::start`.")]
669 pub fn start(&self) {}
670 }
671 },
672 );
673
674 assert!(
675 out.contains("#[deprecated(note=\"Use`IpcClient::start`.\")]"),
676 "{out}"
677 );
678 }
679
680 #[test]
681 fn renames_a_private_wasm_only_method_without_shimming_it() {
682 let out = expand(
683 TokenStream::new(),
684 quote! {
685 impl JsIpcClient {
686 #[wasm_only]
687 fn internal(&self) {}
688 }
689 },
690 );
691
692 assert!(out.contains("fn__wasm_only_internal"), "{out}");
693 assert!(!out.contains("__wasm_ts_"), "{out}");
694 }
695
696 #[test]
697 fn leaves_a_private_generic_method_alone() {
698 let out = expand(
700 TokenStream::new(),
701 quote! {
702 impl Canvas {
703 pub fn width(&self) -> u32 { 0 }
704 fn draw<T: Shape>(&self, shape: T) {}
705 }
706 },
707 );
708
709 assert!(!out.contains("compile_error!"), "{out}");
710 assert!(!out.contains("__wasm_ts_draw"), "{out}");
711 }
712
713 #[test]
714 fn generates_no_block_when_nothing_is_public() {
715 let out = expand(
716 TokenStream::new(),
717 quote! {
718 impl Canvas {
719 fn internal(&self) {}
720 }
721 },
722 );
723
724 assert!(!out.contains("wasm_bindgen"), "{out}");
725 }
726
727 #[test]
728 fn rejects_a_generic_impl_block() {
729 let out = expand(
732 TokenStream::new(),
733 quote! {
734 impl<T> Canvas<T> {
735 pub fn translate(&self, point: Point) -> Point { point }
736 }
737 },
738 );
739
740 assert!(out.contains("compile_error!"), "{out}");
741 assert!(out.contains("doesnotsupportgenericimplblocks"), "{out}");
742 }
743
744 #[test]
745 fn rejects_a_generic_method() {
746 let out = expand(
747 TokenStream::new(),
748 quote! {
749 impl Canvas {
750 pub fn draw<T: Shape>(&self, shape: T) {}
751 }
752 },
753 );
754
755 assert!(out.contains("compile_error!"), "{out}");
756 assert!(out.contains("doesnotsupportgenericmethods"), "{out}");
757 }
758
759 #[test]
760 fn rejects_a_block_that_still_carries_wasm_bindgen() {
761 let out = expand(
764 TokenStream::new(),
765 quote! {
766 #[wasm_bindgen(js_class = IpcClient)]
767 impl JsIpcClient {
768 pub fn is_running(&self) -> bool { true }
769 }
770 },
771 );
772
773 assert!(out.contains("compile_error!"), "{out}");
774 assert!(out.contains("replaces#[wasm_bindgen]"), "{out}");
775 }
776
777 #[test]
778 fn shims_a_free_function() {
779 let out = expand(
782 quote!(js_name = doThing),
783 quote! {
784 pub fn do_thing(point: Point) -> Point { point }
785 },
786 );
787
788 assert!(!out.contains("compile_error!"), "{out}");
789 assert!(out.contains("pubfndo_thing(point:Point)->Point"), "{out}");
790 assert!(
791 out.contains("#[::bitwarden_ffi::_macro::wasm_bindgen(js_name=doThing)]"),
792 "{out}"
793 );
794 assert!(out.contains("fn__wasm_ts_do_thing"), "{out}");
795 assert!(out.contains("do_thing(point)"), "{out}");
796 }
797
798 #[test]
799 fn leaves_a_private_free_function_unshimmed() {
800 let out = expand(
801 TokenStream::new(),
802 quote! {
803 fn do_thing(point: Point) -> Point { point }
804 },
805 );
806
807 assert!(!out.contains("__wasm_ts_"), "{out}");
808 }
809
810 #[test]
811 fn rejects_a_generic_free_function() {
812 let out = expand(
813 TokenStream::new(),
814 quote! {
815 pub fn do_thing<T>(value: T) {}
816 },
817 );
818
819 assert!(out.contains("compile_error!"), "{out}");
820 assert!(out.contains("doesnotsupportgenericfunctions"), "{out}");
821 }
822
823 #[test]
824 fn rejects_an_item_that_is_neither() {
825 let out = expand(TokenStream::new(), quote! { pub struct Canvas; });
826
827 assert!(out.contains("compile_error!"), "{out}");
828 }
829}