1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
use std::collections::HashMap;
use std::sync::atomic::{AtomicU32, Ordering};

use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::ToTokens;

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

static NAPI_IMPL_ID: AtomicU32 = AtomicU32::new(0);
const TYPED_ARRAY_TYPE: &[&str] = &[
  "Int8Array",
  "Uint8Array",
  "Uint8ClampedArray",
  "Int16Array",
  "Uint16Array",
  "Int32Array",
  "Uint32Array",
  "Float32Array",
  "Float64Array",
  "BigInt64Array",
  "BigUint64Array",
];

// Generate trait implementations for given Struct.
fn gen_napi_value_map_impl(name: &Ident, to_napi_val_impl: TokenStream) -> TokenStream {
  let name_str = name.to_string();
  let js_name_str = format!("{}\0", name_str);
  let validate = quote! {
    unsafe fn validate(env: napi::sys::napi_env, napi_val: napi::sys::napi_value) -> napi::Result<napi::sys::napi_value> {
      if let Some(ctor_ref) = napi::bindgen_prelude::get_class_constructor(#js_name_str) {
        let mut ctor = std::ptr::null_mut();
        napi::check_status!(
          napi::sys::napi_get_reference_value(env, ctor_ref, &mut ctor),
          "Failed to get constructor reference of class `{}`",
          #name_str
        )?;
        let mut is_instance_of = false;
        napi::check_status!(
          napi::sys::napi_instanceof(env, napi_val, ctor, &mut is_instance_of),
          "Failed to get external value of class `{}`",
          #name_str
        )?;
        if is_instance_of {
          Ok(std::ptr::null_mut())
        } else {
          Err(napi::Error::new(
            napi::Status::InvalidArg,
            format!("Value is not instanceof class `{}`", #name_str)
          ))
        }
      } else {
        Err(napi::Error::new(
          napi::Status::InvalidArg,
          format!("Failed to get constructor of class `{}`", #name_str)
        ))
      }
    }
  };
  quote! {
    impl napi::bindgen_prelude::TypeName for #name {
      fn type_name() -> &'static str {
        #name_str
      }

      fn value_type() -> napi::ValueType {
        napi::ValueType::Function
      }
    }

    impl napi::bindgen_prelude::TypeName for &#name {
      fn type_name() -> &'static str {
        #name_str
      }

      fn value_type() -> napi::ValueType {
        napi::ValueType::Object
      }
    }

    impl napi::bindgen_prelude::TypeName for &mut #name {
      fn type_name() -> &'static str {
        #name_str
      }

      fn value_type() -> napi::ValueType {
        napi::ValueType::Object
      }
    }

    #to_napi_val_impl

    impl napi::bindgen_prelude::FromNapiRef for #name {
      unsafe fn from_napi_ref(
        env: napi::bindgen_prelude::sys::napi_env,
        napi_val: napi::bindgen_prelude::sys::napi_value
      ) -> napi::bindgen_prelude::Result<&'static Self> {
        let mut wrapped_val: *mut std::ffi::c_void = std::ptr::null_mut();

        napi::bindgen_prelude::check_status!(
          napi::bindgen_prelude::sys::napi_unwrap(env, napi_val, &mut wrapped_val),
          "Failed to recover `{}` type from napi value",
          #name_str,
        )?;

        Ok(&*(wrapped_val as *const #name))
      }
    }

    impl napi::bindgen_prelude::FromNapiMutRef for #name {
      unsafe fn from_napi_mut_ref(
        env: napi::bindgen_prelude::sys::napi_env,
        napi_val: napi::bindgen_prelude::sys::napi_value
      ) -> napi::bindgen_prelude::Result<&'static mut Self> {
        let mut wrapped_val: *mut std::ffi::c_void = std::ptr::null_mut();

        napi::bindgen_prelude::check_status!(
          napi::bindgen_prelude::sys::napi_unwrap(env, napi_val, &mut wrapped_val),
          "Failed to recover `{}` type from napi value",
          #name_str,
        )?;

        Ok(&mut *(wrapped_val as *mut #name))
      }
    }

    impl napi::bindgen_prelude::FromNapiValue for &#name {
      unsafe fn from_napi_value(
        env: napi::bindgen_prelude::sys::napi_env,
        napi_val: napi::bindgen_prelude::sys::napi_value
      ) -> napi::bindgen_prelude::Result<Self> {
        napi::bindgen_prelude::FromNapiRef::from_napi_ref(env, napi_val)
      }
    }

    impl napi::bindgen_prelude::FromNapiValue for &mut #name {
      unsafe fn from_napi_value(
        env: napi::bindgen_prelude::sys::napi_env,
        napi_val: napi::bindgen_prelude::sys::napi_value
      ) -> napi::bindgen_prelude::Result<Self> {
        napi::bindgen_prelude::FromNapiMutRef::from_napi_mut_ref(env, napi_val)
      }
    }

    impl napi::bindgen_prelude::ValidateNapiValue for &#name {
      #validate
    }

    impl napi::bindgen_prelude::ValidateNapiValue for &mut #name {
      #validate
    }
  }
}

impl TryToTokens for NapiStruct {
  fn try_to_tokens(&self, tokens: &mut TokenStream) -> BindgenResult<()> {
    let napi_value_map_impl = self.gen_napi_value_map_impl();

    let class_helper_mod = if self.kind == NapiStructKind::Object {
      quote! {}
    } else {
      self.gen_helper_mod()
    };

    (quote! {
      #napi_value_map_impl
      #class_helper_mod
    })
    .to_tokens(tokens);

    Ok(())
  }
}

impl NapiStruct {
  fn gen_helper_mod(&self) -> TokenStream {
    let mod_name = Ident::new(&format!("__napi_helper__{}", self.name), Span::call_site());

    let ctor = if self.kind == NapiStructKind::Constructor {
      self.gen_default_ctor()
    } else {
      quote! {}
    };

    let mut getters_setters = self.gen_default_getters_setters();
    getters_setters.sort_by(|a, b| a.0.cmp(&b.0));
    let register = self.gen_register();

    let getters_setters_token = getters_setters.into_iter().map(|(_, token)| token);

    quote! {
      #[allow(clippy::all)]
      #[allow(non_snake_case)]
      mod #mod_name {
        use std::ptr;
        use super::*;

        #ctor
        #(#getters_setters_token)*
        #register
      }
    }
  }

  fn gen_default_ctor(&self) -> TokenStream {
    let name = &self.name;
    let js_name_str = &self.js_name;
    let fields_len = self.fields.len();
    let mut fields = vec![];

    for (i, field) in self.fields.iter().enumerate() {
      let ty = &field.ty;
      match &field.name {
        syn::Member::Named(ident) => fields
          .push(quote! { #ident: <#ty as napi::bindgen_prelude::FromNapiValue>::from_napi_value(env, cb.get_arg(#i))? }),
        syn::Member::Unnamed(_) => {
          fields.push(quote! { <#ty as napi::bindgen_prelude::FromNapiValue>::from_napi_value(env, cb.get_arg(#i))? });
        }
      }
    }

    let construct = if self.is_tuple {
      quote! { #name (#(#fields),*) }
    } else {
      quote! { #name {#(#fields),*} }
    };

    let is_empty_struct_hint = fields_len == 0;

    let constructor = if self.implement_iterator {
      quote! { unsafe { cb.construct_generator::<#is_empty_struct_hint, #name>(#js_name_str, #construct) } }
    } else {
      quote! { unsafe { cb.construct::<#is_empty_struct_hint, #name>(#js_name_str, #construct) } }
    };

    quote! {
      extern "C" fn constructor(
        env: napi::bindgen_prelude::sys::napi_env,
        cb: napi::bindgen_prelude::sys::napi_callback_info
      ) -> napi::bindgen_prelude::sys::napi_value {
        napi::bindgen_prelude::CallbackInfo::<#fields_len>::new(env, cb, None, false)
          .and_then(|cb| #constructor)
          .unwrap_or_else(|e| {
            unsafe { napi::bindgen_prelude::JsError::from(e).throw_into(env) };
            std::ptr::null_mut::<napi::bindgen_prelude::sys::napi_value__>()
          })
      }
    }
  }

  fn gen_napi_value_map_impl(&self) -> TokenStream {
    match self.kind {
      NapiStructKind::None => gen_napi_value_map_impl(
        &self.name,
        self.gen_to_napi_value_ctor_impl_for_non_default_constructor_struct(),
      ),
      NapiStructKind::Constructor => {
        gen_napi_value_map_impl(&self.name, self.gen_to_napi_value_ctor_impl())
      }
      NapiStructKind::Object => self.gen_to_napi_value_obj_impl(),
    }
  }

  fn gen_to_napi_value_ctor_impl_for_non_default_constructor_struct(&self) -> TokenStream {
    let name = &self.name;
    let js_name_raw = &self.js_name;
    let js_name_str = format!("{}\0", js_name_raw);
    let iterator_implementation = self.gen_iterator_property(name);
    let finalize_trait = if self.use_custom_finalize {
      quote! {}
    } else {
      quote! { impl napi::bindgen_prelude::ObjectFinalize for #name {} }
    };
    let instance_of_impl = self.gen_instance_of_impl(name, &js_name_str);
    quote! {
      impl napi::bindgen_prelude::ToNapiValue for #name {
        unsafe fn to_napi_value(
          env: napi::sys::napi_env,
          val: #name
        ) -> napi::Result<napi::bindgen_prelude::sys::napi_value> {
          if let Some(ctor_ref) = napi::__private::get_class_constructor(#js_name_str) {
            let mut wrapped_value = Box::into_raw(Box::new(val));
            if wrapped_value as usize == 0x1 {
              wrapped_value = Box::into_raw(Box::new(0u8)).cast();
            }
            let instance_value = #name::new_instance(env, wrapped_value.cast(), ctor_ref)?;
            #iterator_implementation
            Ok(instance_value)
          } else {
            Err(napi::bindgen_prelude::Error::new(
              napi::bindgen_prelude::Status::InvalidArg, format!("Failed to get constructor of class `{}` in `ToNapiValue`", #js_name_raw))
            )
          }
        }
      }

      #finalize_trait
      #instance_of_impl
      impl #name {
        pub fn into_reference(val: #name, env: napi::Env) -> napi::Result<napi::bindgen_prelude::Reference<#name>> {
          if let Some(ctor_ref) = napi::bindgen_prelude::get_class_constructor(#js_name_str) {
            unsafe {
              let mut wrapped_value = Box::into_raw(Box::new(val));
              if wrapped_value as usize == 0x1 {
                wrapped_value = Box::into_raw(Box::new(0u8)).cast();
              }
              let instance_value = #name::new_instance(env.raw(), wrapped_value.cast(), ctor_ref)?;
              {
                let env = env.raw();
                #iterator_implementation
              }
              napi::bindgen_prelude::Reference::<#name>::from_value_ptr(wrapped_value.cast(), env.raw())
            }
          } else {
            Err(napi::bindgen_prelude::Error::new(
              napi::bindgen_prelude::Status::InvalidArg, format!("Failed to get constructor of class `{}`", #js_name_raw))
            )
          }
        }

        pub fn into_instance(self, env: napi::Env) -> napi::Result<napi::bindgen_prelude::ClassInstance<#name>> {
          if let Some(ctor_ref) = napi::bindgen_prelude::get_class_constructor(#js_name_str) {
            unsafe {
              let wrapped_value = Box::leak(Box::new(self));
              let instance_value = #name::new_instance(env.raw(), wrapped_value as *mut _ as *mut std::ffi::c_void, ctor_ref)?;

              Ok(napi::bindgen_prelude::ClassInstance::<#name>::new(instance_value, wrapped_value))
            }
          } else {
            Err(napi::bindgen_prelude::Error::new(
              napi::bindgen_prelude::Status::InvalidArg, format!("Failed to get constructor of class `{}`", #js_name_raw))
            )
          }
        }

        unsafe fn new_instance(
          env: napi::sys::napi_env,
          wrapped_value: *mut std::ffi::c_void,
          ctor_ref: napi::sys::napi_ref,
        ) -> napi::Result<napi::bindgen_prelude::sys::napi_value> {
          let mut ctor = std::ptr::null_mut();
          napi::check_status!(
            napi::sys::napi_get_reference_value(env, ctor_ref, &mut ctor),
            "Failed to get constructor reference of class `{}`",
            #js_name_raw
          )?;

          let mut result = std::ptr::null_mut();
          napi::__private::___CALL_FROM_FACTORY.with(|inner| inner.store(true, std::sync::atomic::Ordering::Relaxed));
          napi::check_status!(
            napi::sys::napi_new_instance(env, ctor, 0, std::ptr::null_mut(), &mut result),
            "Failed to construct class `{}`",
            #js_name_raw
          )?;
          napi::__private::___CALL_FROM_FACTORY.with(|inner| inner.store(false, std::sync::atomic::Ordering::Relaxed));
          let mut object_ref = std::ptr::null_mut();
          let initial_finalize: Box<dyn FnOnce()> = Box::new(|| {});
          let finalize_callbacks_ptr = std::rc::Rc::into_raw(std::rc::Rc::new(std::cell::Cell::new(Box::into_raw(initial_finalize))));
          napi::check_status!(
            napi::sys::napi_wrap(
              env,
              result,
              wrapped_value,
              Some(napi::bindgen_prelude::raw_finalize_unchecked::<#name>),
              std::ptr::null_mut(),
              &mut object_ref,
            ),
            "Failed to wrap native object of class `{}`",
            #js_name_raw
          )?;
          napi::bindgen_prelude::Reference::<#name>::add_ref(env, wrapped_value, (wrapped_value, object_ref, finalize_callbacks_ptr));
          Ok(result)
        }
      }
    }
  }

  fn gen_iterator_property(&self, name: &Ident) -> TokenStream {
    if !self.implement_iterator {
      return quote! {};
    }
    quote! {
      napi::__private::create_iterator::<#name>(env, instance_value, wrapped_value);
    }
  }

  fn gen_to_napi_value_ctor_impl(&self) -> TokenStream {
    let name = &self.name;
    let js_name_without_null = &self.js_name;
    let js_name_str = format!("{}\0", &self.js_name);
    let instance_of_impl = self.gen_instance_of_impl(name, &js_name_str);

    let mut field_conversions = vec![];
    let mut field_destructions = vec![];

    for field in self.fields.iter() {
      let ty = &field.ty;

      match &field.name {
        syn::Member::Named(ident) => {
          // alias here prevents field name shadowing
          let alias_ident = format_ident!("{}_", ident);
          field_destructions.push(quote! { #ident: #alias_ident });
          field_conversions.push(
            quote! { <#ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, #alias_ident)? },
          );
        }
        syn::Member::Unnamed(i) => {
          field_destructions.push(quote! { arg #i });
          field_conversions.push(
            quote! { <#ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, arg #i)? },
          );
        }
      }
    }

    let destructed_fields = if self.is_tuple {
      quote! {
        Self (#(#field_destructions),*)
      }
    } else {
      quote! {
        Self {#(#field_destructions),*}
      }
    };

    let finalize_trait = if self.use_custom_finalize {
      quote! {}
    } else {
      quote! { impl napi::bindgen_prelude::ObjectFinalize for #name {} }
    };

    quote! {
      impl napi::bindgen_prelude::ToNapiValue for #name {
        unsafe fn to_napi_value(
          env: napi::bindgen_prelude::sys::napi_env,
          val: #name,
        ) -> napi::bindgen_prelude::Result<napi::bindgen_prelude::sys::napi_value> {
          if let Some(ctor_ref) = napi::bindgen_prelude::get_class_constructor(#js_name_str) {
            let mut ctor = std::ptr::null_mut();

            napi::bindgen_prelude::check_status!(
              napi::bindgen_prelude::sys::napi_get_reference_value(env, ctor_ref, &mut ctor),
              "Failed to get constructor reference of class `{}`",
              #js_name_without_null
            )?;

            let mut instance_value = std::ptr::null_mut();
            let #destructed_fields = val;
            let args = vec![#(#field_conversions),*];

            napi::bindgen_prelude::check_status!(
              napi::bindgen_prelude::sys::napi_new_instance(env, ctor, args.len(), args.as_ptr(), &mut instance_value),
              "Failed to construct class `{}`",
              #js_name_without_null
            )?;

            Ok(instance_value)
          } else {
            Err(napi::bindgen_prelude::Error::new(
              napi::bindgen_prelude::Status::InvalidArg, format!("Failed to get constructor of class `{}`", #js_name_str))
            )
          }
        }
      }
      #instance_of_impl
      #finalize_trait
    }
  }

  fn gen_to_napi_value_obj_impl(&self) -> TokenStream {
    let name = &self.name;
    let name_str = self.name.to_string();

    let mut obj_field_setters = vec![];
    let mut obj_field_getters = vec![];
    let mut field_destructions = vec![];

    for field in self.fields.iter() {
      let field_js_name = &field.js_name;
      let ty = &field.ty;
      let is_optional_field = if let syn::Type::Path(syn::TypePath {
        path: syn::Path { segments, .. },
        ..
      }) = &ty
      {
        if let Some(last_path) = segments.last() {
          last_path.ident == "Option"
        } else {
          false
        }
      } else {
        false
      };
      match &field.name {
        syn::Member::Named(ident) => {
          let alias_ident = format_ident!("{}_", ident);
          field_destructions.push(quote! { #ident: #alias_ident });
          if is_optional_field {
            obj_field_setters.push(match self.use_nullable {
              false => quote! {
                if #alias_ident.is_some() {
                  obj.set(#field_js_name, #alias_ident)?;
                }
              },
              true => quote! {
                if let Some(#alias_ident) = #alias_ident {
                  obj.set(#field_js_name, #alias_ident)?;
                } else {
                  obj.set(#field_js_name, napi::bindgen_prelude::Null)?;
                }
              },
            });
          } else {
            obj_field_setters.push(quote! { obj.set(#field_js_name, #alias_ident)?; });
          }
          if is_optional_field && !self.use_nullable {
            obj_field_getters.push(quote! {
              let #alias_ident: #ty = obj.get(#field_js_name).map_err(|mut err| {
                err.reason = format!("{} on {}.{}", err.reason, #name_str, #field_js_name);
                err
              })?;
            });
          } else {
            obj_field_getters.push(quote! {
              let #alias_ident: #ty = obj.get(#field_js_name).map_err(|mut err| {
                err.reason = format!("{} on {}.{}", err.reason, #name_str, #field_js_name);
                err
              })?.ok_or_else(|| napi::bindgen_prelude::Error::new(
                napi::bindgen_prelude::Status::InvalidArg,
                format!("Missing field `{}`", #field_js_name),
              ))?;
            });
          }
        }
        syn::Member::Unnamed(i) => {
          field_destructions.push(quote! { arg #i });
          if is_optional_field {
            obj_field_setters.push(match self.use_nullable {
              false => quote! {
                if arg #1.is_some() {
                  obj.set(#field_js_name, arg #i)?;
                }
              },
              true => quote! {
                if let Some(arg #i) = arg #i {
                  obj.set(#field_js_name, arg #i)?;
                } else {
                  obj.set(#field_js_name, napi::bindgen_prelude::Null)?;
                }
              },
            });
          } else {
            obj_field_setters.push(quote! { obj.set(#field_js_name, arg #1)?; });
          }
          if is_optional_field && !self.use_nullable {
            obj_field_getters.push(quote! { let arg #i: #ty = obj.get(#field_js_name)?; });
          } else {
            obj_field_getters.push(quote! {
              let arg #i: #ty = obj.get(#field_js_name)?.ok_or_else(|| napi::bindgen_prelude::Error::new(
                napi::bindgen_prelude::Status::InvalidArg,
                format!("Missing field `{}`", #field_js_name),
              ))?;
            });
          }
        }
      }
    }

    let destructed_fields = if self.is_tuple {
      quote! {
        Self (#(#field_destructions),*)
      }
    } else {
      quote! {
        Self {#(#field_destructions),*}
      }
    };

    let to_napi_value = if self.object_to_js {
      quote! {
        impl napi::bindgen_prelude::ToNapiValue for #name {
          unsafe fn to_napi_value(env: napi::bindgen_prelude::sys::napi_env, val: #name) -> napi::bindgen_prelude::Result<napi::bindgen_prelude::sys::napi_value> {
            let env_wrapper = napi::bindgen_prelude::Env::from(env);
            let mut obj = env_wrapper.create_object()?;

            let #destructed_fields = val;
            #(#obj_field_setters)*

            napi::bindgen_prelude::Object::to_napi_value(env, obj)
          }
        }
      }
    } else {
      quote! {}
    };

    let from_napi_value = if self.object_from_js {
      quote! {
        impl napi::bindgen_prelude::FromNapiValue for #name {
          unsafe fn from_napi_value(
            env: napi::bindgen_prelude::sys::napi_env,
            napi_val: napi::bindgen_prelude::sys::napi_value
          ) -> napi::bindgen_prelude::Result<Self> {
            let env_wrapper = napi::bindgen_prelude::Env::from(env);
            let mut obj = napi::bindgen_prelude::Object::from_napi_value(env, napi_val)?;

            #(#obj_field_getters)*

            let val = #destructed_fields;

            Ok(val)
          }
        }
      }
    } else {
      quote! {}
    };

    quote! {
      impl napi::bindgen_prelude::TypeName for #name {
        fn type_name() -> &'static str {
          #name_str
        }

        fn value_type() -> napi::ValueType {
          napi::ValueType::Object
        }
      }

      #to_napi_value

      #from_napi_value

      impl napi::bindgen_prelude::ValidateNapiValue for #name {}
    }
  }

  fn gen_default_getters_setters(&self) -> Vec<(String, TokenStream)> {
    let mut getters_setters = vec![];
    let struct_name = &self.name;

    for field in self.fields.iter() {
      let field_ident = &field.name;
      let field_name = match &field.name {
        syn::Member::Named(ident) => ident.to_string(),
        syn::Member::Unnamed(i) => format!("field{}", i.index),
      };
      let ty = &field.ty;

      let getter_name = Ident::new(
        &format!("get_{}", rm_raw_prefix(&field_name)),
        Span::call_site(),
      );
      let setter_name = Ident::new(
        &format!("set_{}", rm_raw_prefix(&field_name)),
        Span::call_site(),
      );

      if field.getter {
        let default_to_napi_value_convert = quote! {
          let val = obj.#field_ident.to_owned();
          unsafe { <#ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, val) }
        };
        let to_napi_value_convert = if let syn::Type::Path(syn::TypePath {
          path: syn::Path { segments, .. },
          ..
        }) = ty
        {
          if let Some(syn::PathSegment { ident, .. }) = segments.last() {
            if TYPED_ARRAY_TYPE.iter().any(|name| ident == name) || ident == "Buffer" {
              quote! {
                let val = &mut obj.#field_ident;
                unsafe { <&mut #ty as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, val) }
              }
            } else {
              default_to_napi_value_convert
            }
          } else {
            default_to_napi_value_convert
          }
        } else {
          default_to_napi_value_convert
        };
        getters_setters.push((
          field.js_name.clone(),
          quote! {
            extern "C" fn #getter_name(
              env: napi::bindgen_prelude::sys::napi_env,
              cb: napi::bindgen_prelude::sys::napi_callback_info
            ) -> napi::bindgen_prelude::sys::napi_value {
              napi::bindgen_prelude::CallbackInfo::<0>::new(env, cb, Some(0), false)
                .and_then(|mut cb| unsafe { cb.unwrap_borrow_mut::<#struct_name>() })
                .and_then(|obj| {
                  #to_napi_value_convert
                })
                .unwrap_or_else(|e| {
                  unsafe { napi::bindgen_prelude::JsError::from(e).throw_into(env) };
                  std::ptr::null_mut::<napi::bindgen_prelude::sys::napi_value__>()
                })
            }
          },
        ));
      }

      if field.setter {
        getters_setters.push((
          field.js_name.clone(),
          quote! {
            extern "C" fn #setter_name(
              env: napi::bindgen_prelude::sys::napi_env,
              cb: napi::bindgen_prelude::sys::napi_callback_info
            ) -> napi::bindgen_prelude::sys::napi_value {
              napi::bindgen_prelude::CallbackInfo::<1>::new(env, cb, Some(1), false)
                .and_then(|mut cb_info| unsafe {
                  cb_info.unwrap_borrow_mut::<#struct_name>()
                    .and_then(|obj| {
                      <#ty as napi::bindgen_prelude::FromNapiValue>::from_napi_value(env, cb_info.get_arg(0))
                        .and_then(move |val| {
                          obj.#field_ident = val;
                          <() as napi::bindgen_prelude::ToNapiValue>::to_napi_value(env, ())
                        })
                    })
                })
                .unwrap_or_else(|e| {
                  unsafe { napi::bindgen_prelude::JsError::from(e).throw_into(env) };
                  std::ptr::null_mut::<napi::bindgen_prelude::sys::napi_value__>()
                })
            }
          },
        ));
      }
    }

    getters_setters
  }

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

    if self.kind == NapiStructKind::Constructor {
      props.push(quote! { napi::bindgen_prelude::Property::new("constructor").unwrap().with_ctor(constructor) });
    }

    for field in self.fields.iter() {
      let field_name = match &field.name {
        syn::Member::Named(ident) => ident.to_string(),
        syn::Member::Unnamed(i) => format!("field{}", i.index),
      };

      if !field.getter {
        continue;
      }

      let js_name = &field.js_name;
      let mut attribute = super::PROPERTY_ATTRIBUTE_DEFAULT;
      if field.writable {
        attribute |= super::PROPERTY_ATTRIBUTE_WRITABLE;
      }
      if field.enumerable {
        attribute |= super::PROPERTY_ATTRIBUTE_ENUMERABLE;
      }
      if field.configurable {
        attribute |= super::PROPERTY_ATTRIBUTE_CONFIGURABLE;
      }

      let mut prop = quote! {
        napi::bindgen_prelude::Property::new(#js_name)
          .unwrap()
          .with_property_attributes(napi::bindgen_prelude::PropertyAttributes::from_bits(#attribute).unwrap())
      };

      if field.getter {
        let getter_name = Ident::new(
          &format!("get_{}", rm_raw_prefix(&field_name)),
          Span::call_site(),
        );
        (quote! { .with_getter(#getter_name) }).to_tokens(&mut prop);
      }

      if field.writable && field.setter {
        let setter_name = Ident::new(
          &format!("set_{}", rm_raw_prefix(&field_name)),
          Span::call_site(),
        );
        (quote! { .with_setter(#setter_name) }).to_tokens(&mut prop);
      }

      props.push(prop);
    }
    let js_mod_ident = js_mod_to_token_stream(self.js_mod.as_ref());
    quote! {
      #[allow(non_snake_case)]
      #[allow(clippy::all)]
      #[cfg(all(not(test), not(feature = "noop"), not(target_family = "wasm")))]
      #[napi::bindgen_prelude::ctor]
      fn #struct_register_name() {
        napi::__private::register_class(#name_str, #js_mod_ident, #js_name, vec![#(#props),*]);
      }

      #[allow(non_snake_case)]
      #[allow(clippy::all)]
      #[cfg(all(not(test), not(feature = "noop"), target_family = "wasm"))]
      #[no_mangle]
      extern "C" fn #struct_register_name() {
        napi::__private::register_class(#name_str, #js_mod_ident, #js_name, vec![#(#props),*]);
      }
    }
  }

  fn gen_instance_of_impl(&self, name: &Ident, js_name: &str) -> TokenStream {
    quote! {
      impl #name {
        pub fn instance_of<V: napi::NapiRaw>(env: napi::Env, value: V) -> napi::Result<bool> {
          if let Some(ctor_ref) = napi::bindgen_prelude::get_class_constructor(#js_name) {
            let mut ctor = std::ptr::null_mut();
            napi::check_status!(
              unsafe { napi::sys::napi_get_reference_value(env.raw(), ctor_ref, &mut ctor) },
              "Failed to get constructor reference of class `{}`",
              #js_name
            )?;
            let mut is_instance_of = false;
            napi::check_status!(
              unsafe { napi::sys::napi_instanceof(env.raw(), value.raw(), ctor, &mut is_instance_of) },
              "Failed to run instanceof for class `{}`",
              #js_name
            )?;
            Ok(is_instance_of)
          } else {
            Err(napi::Error::new(napi::Status::GenericFailure, format!("Failed to get constructor of class `{}`", #js_name)))
          }
        }
      }
    }
  }
}

impl TryToTokens for NapiImpl {
  fn try_to_tokens(&self, tokens: &mut TokenStream) -> BindgenResult<()> {
    self.gen_helper_mod()?.to_tokens(tokens);

    Ok(())
  }
}

impl NapiImpl {
  fn gen_helper_mod(&self) -> BindgenResult<TokenStream> {
    let name_str = self.name.to_string();
    let js_name = format!("{}\0", self.js_name);
    let mod_name = Ident::new(
      &format!(
        "__napi_impl_helper__{}__{}",
        name_str,
        NAPI_IMPL_ID.fetch_add(1, Ordering::SeqCst)
      ),
      Span::call_site(),
    );

    let register_name = &self.register_name;

    let mut methods = vec![];
    let mut props = HashMap::new();

    for item in self.items.iter() {
      let js_name = Literal::string(&item.js_name);
      let item_str = item.name.to_string();
      let intermediate_name = get_intermediate_ident(&item_str);
      methods.push(item.try_to_token_stream()?);

      let mut attribute = super::PROPERTY_ATTRIBUTE_DEFAULT;
      if item.writable {
        attribute |= super::PROPERTY_ATTRIBUTE_WRITABLE;
      }
      if item.enumerable {
        attribute |= super::PROPERTY_ATTRIBUTE_ENUMERABLE;
      }
      if item.configurable {
        attribute |= super::PROPERTY_ATTRIBUTE_CONFIGURABLE;
      }

      let prop = props.entry(&item.js_name).or_insert_with(|| {
        quote! {
          napi::bindgen_prelude::Property::new(#js_name).unwrap().with_property_attributes(napi::bindgen_prelude::PropertyAttributes::from_bits(#attribute).unwrap())
        }
      });

      let appendix = match item.kind {
        FnKind::Constructor => quote! { .with_ctor(#intermediate_name) },
        FnKind::Getter => quote! { .with_getter(#intermediate_name) },
        FnKind::Setter => quote! { .with_setter(#intermediate_name) },
        _ => {
          if item.fn_self.is_some() {
            quote! { .with_method(#intermediate_name) }
          } else {
            quote! { .with_method(#intermediate_name).with_property_attributes(napi::bindgen_prelude::PropertyAttributes::Static) }
          }
        }
      };

      appendix.to_tokens(prop);
    }

    let mut props: Vec<_> = props.into_iter().collect();
    props.sort_by_key(|(_, prop)| prop.to_string());
    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());
    Ok(quote! {
      #[allow(non_snake_case)]
      #[allow(clippy::all)]
      mod #mod_name {
        use super::*;
        #(#methods)*

        #[cfg(all(not(test), not(feature = "noop"), not(target_family = "wasm")))]
        #[napi::bindgen_prelude::ctor]
        fn #register_name() {
          napi::__private::register_class(#name_str, #js_mod_ident, #js_name, vec![#(#props),*]);
        }

        #[cfg(all(not(test), not(feature = "noop"), target_family = "wasm"))]
        #[no_mangle]
        extern "C" fn #register_name() {
          napi::__private::register_class(#name_str, #js_mod_ident, #js_name, vec![#(#props_wasm),*]);
        }
      }
    })
  }
}

pub fn rm_raw_prefix(s: &str) -> &str {
  if let Some(stripped) = s.strip_prefix("r#") {
    stripped
  } else {
    s
  }
}