Documentation
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
use std::convert::From;
use std::ffi::c_void;
use std::ffi::CString;
use std::ptr;
#[cfg(feature = "napi5")]
use std::rc::Rc;

use bitflags::bitflags;

#[cfg(feature = "napi5")]
use crate::bindgen_runtime::{FromNapiValue, This};
use crate::{bindgen_runtime::ToNapiValue, sys, Callback, Env, JsValue, Result};

#[cfg(feature = "napi5")]
#[derive(Copy, Clone)]
pub struct PropertyClosures {
  pub setter_closure: *mut c_void,
  pub getter_closure: *mut c_void,
  /// Still filled, but no longer used to drop the closure: the boxed callback
  /// data owns it now. Kept so this public struct does not change.
  pub setter_drop_fn: Option<unsafe fn(*mut c_void)>,
  /// See `setter_drop_fn`.
  pub getter_drop_fn: Option<unsafe fn(*mut c_void)>,
}

#[cfg(feature = "napi5")]
impl Default for PropertyClosures {
  fn default() -> Self {
    Self {
      setter_closure: ptr::null_mut(),
      getter_closure: ptr::null_mut(),
      setter_drop_fn: None,
      getter_drop_fn: None,
    }
  }
}

/// Owns one boxed accessor closure and drops it with the last reference.
#[cfg(feature = "napi5")]
pub(crate) struct OwnedClosure {
  ptr: *mut c_void,
  drop_fn: unsafe fn(*mut c_void),
}

#[cfg(feature = "napi5")]
impl Drop for OwnedClosure {
  fn drop(&mut self) {
    unsafe { (self.drop_fn)(self.ptr) };
  }
}

/// The callback data `Property::raw` boxes. `closures` comes first, so the
/// trampolines can read the data as a `PropertyClosures`.
#[cfg(feature = "napi5")]
#[repr(C)]
pub(crate) struct PropertyClosuresData {
  closures: PropertyClosures,
  _owners: [Option<Rc<OwnedClosure>>; 2],
}

/// A symbol key, resolved in the current environment when the property is
/// defined.
#[derive(Clone)]
enum SymbolKey {
  /// A `Symbol.for` registry key.
  #[cfg(feature = "napi9")]
  For(String),
  /// The name of a well-known symbol, such as `iterator` for `Symbol.iterator`.
  WellKnown(&'static str),
}

#[derive(Clone)]
pub struct Property {
  utf8_name: Option<CString>,
  symbol: Option<SymbolKey>,
  name: sys::napi_value,
  getter: sys::napi_callback,
  setter: sys::napi_callback,
  method: sys::napi_callback,
  attrs: PropertyAttributes,
  value: sys::napi_value,
  data: *mut c_void,
  pub(crate) is_ctor: bool,
  #[cfg(feature = "napi5")]
  pub(crate) closures: PropertyClosures,
  #[cfg(feature = "napi5")]
  getter_owner: Option<Rc<OwnedClosure>>,
  #[cfg(feature = "napi5")]
  setter_owner: Option<Rc<OwnedClosure>>,
}

impl Default for Property {
  fn default() -> Self {
    Property {
      utf8_name: Default::default(),
      symbol: None,
      name: ptr::null_mut(),
      getter: Default::default(),
      setter: Default::default(),
      method: Default::default(),
      attrs: Default::default(),
      value: ptr::null_mut(),
      data: ptr::null_mut(),
      is_ctor: Default::default(),
      #[cfg(feature = "napi5")]
      closures: PropertyClosures::default(),
      #[cfg(feature = "napi5")]
      getter_owner: None,
      #[cfg(feature = "napi5")]
      setter_owner: None,
    }
  }
}

bitflags! {
  #[derive(Debug, Copy, Clone)]
  pub struct PropertyAttributes: i32 {
    const Default = sys::PropertyAttributes::default;
    const Writable = sys::PropertyAttributes::writable;
    const Enumerable = sys::PropertyAttributes::enumerable;
    const Configurable = sys::PropertyAttributes::configurable;
    const Static = sys::PropertyAttributes::static_;
  }
}

impl Default for PropertyAttributes {
  fn default() -> Self {
    PropertyAttributes::Configurable | PropertyAttributes::Enumerable | PropertyAttributes::Writable
  }
}

impl From<PropertyAttributes> for sys::napi_property_attributes {
  fn from(value: PropertyAttributes) -> Self {
    value.bits()
  }
}

impl Property {
  pub fn new() -> Self {
    Default::default()
  }

  /// Replaces any key set earlier on this `Property`.
  pub fn with_utf8_name(mut self, name: &str) -> Result<Self> {
    self.utf8_name = Some(CString::new(name)?);
    self.name = ptr::null_mut();
    self.symbol = None;
    Ok(self)
  }

  /// Stores a global symbol key, resolved in the current environment when the
  /// property is defined. Replaces any key set earlier on this `Property`.
  /// Requires the `napi9` feature or a higher Node-API feature.
  ///
  /// Used by `#[napi(symbol_for)]` codegen. Not public API and not covered by
  /// semver.
  #[cfg(feature = "napi9")]
  #[doc(hidden)]
  pub fn with_symbol_name(mut self, name: &str) -> Self {
    self.utf8_name = None;
    self.name = ptr::null_mut();
    self.symbol = Some(SymbolKey::For(name.to_owned()));
    self
  }

  /// Stores the name of a well-known symbol, such as `iterator` for
  /// `Symbol.iterator`. The symbol is read from `globalThis.Symbol` in the
  /// current environment when the property is defined. Replaces any key set
  /// earlier on this `Property`.
  ///
  /// Used by `#[napi(well_known_symbol)]` codegen. Not public API and not
  /// covered by semver.
  #[doc(hidden)]
  pub fn with_well_known_symbol(mut self, name: &'static str) -> Self {
    self.utf8_name = None;
    self.name = ptr::null_mut();
    self.symbol = Some(SymbolKey::WellKnown(name));
    self
  }

  /// Replaces any key set earlier on this `Property`.
  pub fn with_name<T: ToNapiValue>(mut self, env: &Env, name: T) -> Result<Self> {
    self.name = unsafe { T::to_napi_value(env.0, name)? };
    self.utf8_name = None;
    self.symbol = None;
    Ok(self)
  }

  pub fn with_method(mut self, callback: Callback) -> Self {
    self.method = Some(callback);
    self
  }

  pub fn with_getter(mut self, callback: Callback) -> Self {
    self.getter = Some(callback);
    self
  }

  #[cfg(feature = "napi5")]
  pub fn with_getter_closure<R, F>(mut self, callback: F) -> Self
  where
    F: 'static + Fn(Env, This) -> Result<R>,
    R: ToNapiValue,
  {
    let boxed_callback = Box::new(callback);
    let closure_data_ptr: *mut F = Box::into_raw(boxed_callback);
    let drop_fn = |ptr: *mut c_void| unsafe {
      drop(Box::from_raw(ptr as *mut F));
    };
    self.closures.getter_closure = closure_data_ptr.cast();
    self.closures.getter_drop_fn = Some(drop_fn);
    self.getter_owner = Some(Rc::new(OwnedClosure {
      ptr: closure_data_ptr.cast(),
      drop_fn,
    }));

    let fun = crate::trampoline_getter::<R, F>;
    self.getter = Some(fun);
    self
  }

  pub fn with_setter(mut self, callback: Callback) -> Self {
    self.setter = Some(callback);
    self
  }

  #[cfg(feature = "napi5")]
  pub fn with_setter_closure<F, V>(mut self, callback: F) -> Self
  where
    F: 'static + Fn(crate::Env, This, V) -> Result<()>,
    V: FromNapiValue,
  {
    let boxed_callback = Box::new(callback);
    let closure_data_ptr: *mut F = Box::into_raw(boxed_callback);
    let drop_fn = |ptr: *mut c_void| unsafe {
      drop(Box::from_raw(ptr as *mut F));
    };
    self.closures.setter_closure = closure_data_ptr.cast();
    self.closures.setter_drop_fn = Some(drop_fn);
    self.setter_owner = Some(Rc::new(OwnedClosure {
      ptr: closure_data_ptr.cast(),
      drop_fn,
    }));

    let fun = crate::trampoline_setter::<V, F>;
    self.setter = Some(fun);
    self
  }

  pub fn with_property_attributes(mut self, attributes: PropertyAttributes) -> Self {
    self.attrs = attributes;
    self
  }

  pub fn with_value<'env, T: JsValue<'env>>(mut self, value: &T) -> Self {
    self.value = T::raw(value);
    self
  }

  pub fn with_napi_value<T: ToNapiValue>(mut self, env: &Env, value: T) -> Result<Self> {
    self.value = unsafe { T::to_napi_value(env.0, value)? };
    Ok(self)
  }

  #[doc(hidden)]
  pub fn with_data(mut self, data: *mut c_void) -> Self {
    self.data = data;
    self
  }

  #[cfg(all(feature = "napi5", not(feature = "noop")))]
  pub(crate) fn has_owned_closure(&self) -> bool {
    self.getter_owner.is_some() || self.setter_owner.is_some()
  }

  #[cfg(feature = "napi5")]
  pub(crate) fn has_closure_data(&self) -> bool {
    self.data.is_null()
      && (!self.closures.getter_closure.is_null() || !self.closures.setter_closure.is_null())
  }

  pub(crate) fn raw(&self, env: sys::napi_env) -> Result<sys::napi_property_descriptor> {
    // Only the symbol key is shared across environments, never a napi_value.
    // The lookup runs before this property's closure data is allocated.
    let name = match &self.symbol {
      None => self.name,
      #[cfg(feature = "napi9")]
      Some(SymbolKey::For(symbol_name)) => {
        let mut symbol = ptr::null_mut();
        crate::check_status!(unsafe {
          sys::node_api_symbol_for(
            env,
            symbol_name.as_ptr().cast(),
            symbol_name.len() as isize,
            &mut symbol,
          )
        })?;
        symbol
      }
      Some(SymbolKey::WellKnown(name)) => well_known_symbol(env, name)?,
    };
    #[cfg(feature = "napi5")]
    let data = if !self.data.is_null() {
      self.data
    } else if self.closures.getter_closure.is_null() && self.closures.setter_closure.is_null() {
      // No closures to allocate, avoid memory leak
      ptr::null_mut()
    } else {
      // Only allocate when we actually have closures
      Box::into_raw(Box::new(PropertyClosuresData {
        closures: self.closures,
        _owners: [self.getter_owner.clone(), self.setter_owner.clone()],
      }))
      .cast()
    };

    Ok(sys::napi_property_descriptor {
      utf8name: match self.utf8_name {
        Some(ref name) => name.as_ptr(),
        None => ptr::null(),
      },
      name,
      method: self.method,
      getter: self.getter,
      setter: self.setter,
      value: self.value,
      attributes: self.attrs.into(),
      #[cfg(not(feature = "napi5"))]
      data: self.data,
      #[cfg(feature = "napi5")]
      data,
    })
  }

  pub fn with_ctor(mut self, callback: Callback) -> Self {
    self.method = Some(callback);
    self.is_ctor = true;
    self
  }
}

/// Reads `globalThis.Symbol[name]`, and fails instead of returning a value
/// that is not a symbol, so a missing symbol is never used as a property key.
fn well_known_symbol(env: sys::napi_env, name: &str) -> Result<sys::napi_value> {
  let mut global = ptr::null_mut();
  crate::check_status!(
    unsafe { sys::napi_get_global(env, &mut global) },
    "Get global object failed"
  )?;
  let mut symbol_ctor = ptr::null_mut();
  crate::check_status!(
    unsafe { sys::napi_get_named_property(env, global, c"Symbol".as_ptr(), &mut symbol_ctor) },
    "Get global Symbol failed"
  )?;
  let not_available = || {
    crate::Error::new(
      crate::Status::GenericFailure,
      format!("Symbol.{name} is not available in this runtime"),
    )
  };
  // Reading a property of `undefined` or `null` would throw a JS exception,
  // which hides the error below.
  let mut value_type = 0;
  crate::check_status!(unsafe { sys::napi_typeof(env, symbol_ctor, &mut value_type) })?;
  if value_type != sys::ValueType::napi_function && value_type != sys::ValueType::napi_object {
    return Err(not_available());
  }
  let mut key = ptr::null_mut();
  crate::check_status!(unsafe {
    sys::napi_create_string_utf8(env, name.as_ptr().cast(), name.len() as isize, &mut key)
  })?;
  let mut symbol = ptr::null_mut();
  crate::check_status!(
    unsafe { sys::napi_get_property(env, symbol_ctor, key, &mut symbol) },
    "Get Symbol.{} failed",
    name
  )?;
  crate::check_status!(unsafe { sys::napi_typeof(env, symbol, &mut value_type) })?;
  if value_type != sys::ValueType::napi_symbol {
    return Err(not_available());
  }
  Ok(symbol)
}

/// Builds the symbol-keyed `Property` for `#[napi(symbol_for = "...")]`.
/// Checked against the features of this crate, so a missing `napi9` gives a
/// clear error instead of a missing method.
#[cfg(feature = "napi9")]
#[doc(hidden)]
#[macro_export]
macro_rules! symbol_for_property {
  ($name:expr) => {
    $crate::bindgen_prelude::Property::new().with_symbol_name($name)
  };
}

#[cfg(not(feature = "napi9"))]
#[doc(hidden)]
#[macro_export]
macro_rules! symbol_for_property {
  ($name:expr) => {{
    compile_error!("`symbol_for` requires the `napi9` feature of the `napi` crate");
    $crate::bindgen_prelude::Property::new()
  }};
}

#[cfg(all(test, feature = "napi9"))]
mod tests {
  use super::*;

  // Name conversion is stubbed so the builder can be tested without a JS
  // environment. The opaque value is only compared, never dereferenced.
  struct TestName;

  impl ToNapiValue for TestName {
    unsafe fn to_napi_value(_env: sys::napi_env, _value: Self) -> Result<sys::napi_value> {
      Ok(ptr::dangling_mut())
    }
  }

  fn old_keys(env: &Env) -> [Property; 4] {
    [
      Property::new().with_utf8_name("old").unwrap(),
      Property::new().with_name(env, TestName).unwrap(),
      Property::new().with_symbol_name("old"),
      Property::new().with_well_known_symbol("dispose"),
    ]
  }

  #[test]
  fn utf8_name_replaces_other_names() {
    let env = Env::from_raw(ptr::null_mut());
    for property in old_keys(&env) {
      let property = property.with_utf8_name("new").unwrap();
      assert_eq!(property.utf8_name.as_ref().unwrap().as_bytes(), b"new");
      assert!(property.symbol.is_none());
      assert!(property.name.is_null());
    }
  }

  #[test]
  fn value_name_replaces_other_names() {
    let env = Env::from_raw(ptr::null_mut());
    for property in old_keys(&env) {
      let property = property.with_name(&env, TestName).unwrap();
      assert!(property.utf8_name.is_none());
      assert!(property.symbol.is_none());
      assert_eq!(property.name, ptr::dangling_mut());
    }
  }

  #[test]
  fn symbol_name_replaces_other_names() {
    let env = Env::from_raw(ptr::null_mut());
    for property in old_keys(&env) {
      let property = property.with_symbol_name("new");
      assert!(matches!(&property.symbol, Some(SymbolKey::For(name)) if name == "new"));
      assert!(property.utf8_name.is_none());
      assert!(property.name.is_null());
    }
  }

  #[test]
  fn well_known_symbol_replaces_other_names() {
    let env = Env::from_raw(ptr::null_mut());
    for property in old_keys(&env) {
      let property = property.with_well_known_symbol("iterator");
      assert!(matches!(
        property.symbol,
        Some(SymbolKey::WellKnown("iterator"))
      ));
      assert!(property.utf8_name.is_none());
      assert!(property.name.is_null());
    }
  }

  #[cfg(not(feature = "noop"))]
  #[test]
  #[should_panic(expected = "register_class does not accept closure-backed properties")]
  fn register_class_rejects_closure_properties() {
    struct ClosureClass;
    let property = Property::new()
      .with_utf8_name("value")
      .unwrap()
      .with_getter_closure(|_env, _this| Ok(1u32));
    crate::bindgen_runtime::register_class(
      std::any::TypeId::of::<ClosureClass>(),
      None,
      "ClosureClass",
      vec![property],
      false,
    );
  }
}