Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsSymbol primitive #761

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,10 @@ event-queue-api = []
# Feature flag to include procedural macros
proc-macros = ["neon-macros"]

# Feature flag to enable the `JsSymbol` API of RFC 38
# https://github.com/neon-bindings/rfcs/pull/38
symbol-api = []

[package.metadata.docs.rs]
features = ["docs-only", "event-handler-api", "proc-macros", "try-catch-api"]

Expand Down
9 changes: 9 additions & 0 deletions crates/neon-runtime/src/napi/bindings/functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,13 @@ mod napi1 {

fn get_property(env: Env, object: Value, key: Value, result: *mut Value) -> Status;

fn get_named_property(
env: Env,
object: Value,
utf8name: *const c_char,
result: *mut Value,
) -> Status;

fn set_element(env: Env, object: Value, index: u32, value: Value) -> Status;

fn get_element(env: Env, object: Value, index: u32, result: *mut Value) -> Status;
Expand Down Expand Up @@ -198,6 +205,8 @@ mod napi1 {
) -> Status;

fn run_script(env: Env, script: Value, result: *mut Value) -> Status;

fn create_symbol(env: Env, description: Value, result: *mut Value) -> Status;
}
);
}
Expand Down
17 changes: 15 additions & 2 deletions crates/neon-runtime/src/napi/object.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::mem::MaybeUninit;

use crate::napi::bindings as napi;
use crate::raw::{Env, Local};
use std::mem::MaybeUninit;
use std::os::raw::c_char;

/// Mutates the `out` argument to refer to a `napi_value` containing a newly created JavaScript Object.
pub unsafe fn new(out: &mut Local, env: Env) {
Expand Down Expand Up @@ -131,3 +131,16 @@ pub unsafe fn set(out: &mut bool, env: Env, object: Local, key: Local, val: Loca

*out
}

/// Returns an `Option<Local>` representing the value of the property of `object` named by
/// the `key` value, where `key` is a pointer to a null-terminated byte string. Returns `None` if
/// the value couldn't be retrieved.
pub unsafe fn get_named(env: Env, object: Local, key: *const u8) -> Option<Local> {
let mut local = MaybeUninit::uninit();
if napi::get_named_property(env, object, key as *const _, local.as_mut_ptr())
!= napi::Status::Ok
{
return None;
}
Some(local.assume_init())
}
12 changes: 12 additions & 0 deletions crates/neon-runtime/src/napi/primitive.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::napi::bindings as napi;
use crate::raw::{Env, Local};
use std::mem::MaybeUninit;

/// Mutates the `out` argument provided to refer to the global `undefined` object.
pub unsafe fn undefined(out: &mut Local, env: Env) {
Expand Down Expand Up @@ -43,3 +44,14 @@ pub unsafe fn number_value(env: Env, p: Local) -> f64 {
);
value
}

/// Returns a newly created `Local` containing a JavaScript symbol.
/// Panics if `desc` is not a `Local` representing a `ValueType::String` or a null pointer.
pub unsafe fn symbol(env: Env, desc: Local) -> Local {
let mut local = MaybeUninit::uninit();
assert_eq!(
napi::create_symbol(env, desc, local.as_mut_ptr()),
napi::Status::Ok
);
local.assume_init()
}
5 changes: 5 additions & 0 deletions crates/neon-runtime/src/napi/tag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ pub unsafe fn is_string(env: Env, val: Local) -> bool {
is_type(env, val, napi::ValueType::String)
}

/// Is `val` a JavaScript symbol?
pub unsafe fn is_symbol(env: Env, val: Local) -> bool {
is_type(env, val, napi::ValueType::Symbol)
}

pub unsafe fn is_object(env: Env, val: Local) -> bool {
is_type(env, val, napi::ValueType::Object)
}
Expand Down
11 changes: 11 additions & 0 deletions src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ use crate::types::boxed::{Finalize, JsBox};
#[cfg(feature = "napi-5")]
use crate::types::date::{DateError, JsDate};
use crate::types::error::JsError;
#[cfg(all(feature = "napi-1", feature = "symbol-api"))]
use crate::types::symbol::JsSymbol;
use crate::types::{
JsArray, JsBoolean, JsFunction, JsNull, JsNumber, JsObject, JsString, JsUndefined, JsValue,
StringResult, Value,
Expand Down Expand Up @@ -438,6 +440,15 @@ pub trait Context<'a>: ContextInternal<'a> {
JsString::try_new(self, s)
}

/// Convenience method for creating a `JsSymbol` value.
///
/// If the string exceeds the limits of the JS engine, this method panics.
#[cfg(all(feature = "napi-1", feature = "symbol-api"))]
fn symbol<S: AsRef<str>>(&mut self, description: S) -> Handle<'a, JsSymbol> {
let desc = self.string(description);
JsSymbol::with_description(self, desc)
}

/// Convenience method for creating a `JsNull` value.
fn null(&mut self) -> Handle<'a, JsNull> {
#[cfg(feature = "legacy-runtime")]
Expand Down
2 changes: 2 additions & 0 deletions src/prelude.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ pub use crate::register_module;
pub use crate::result::{JsResult, JsResultExt, NeonResult};
#[cfg(feature = "legacy-runtime")]
pub use crate::task::Task;
#[cfg(all(feature = "napi-1", feature = "symbol-api"))]
pub use crate::types::symbol::JsSymbol;
pub use crate::types::{
BinaryData, JsArray, JsArrayBuffer, JsBoolean, JsBuffer, JsError, JsFunction, JsNull, JsNumber,
JsObject, JsString, JsUndefined, JsValue, Value,
Expand Down
7 changes: 6 additions & 1 deletion src/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@
//! of custom objects that own Rust data structures.
//! - **Primitive types:** These are the built-in JavaScript datatypes that are not
//! object types: [`JsNumber`](JsNumber), [`JsBoolean`](JsBoolean),
//! [`JsString`](JsString), [`JsNull`](JsNull), and [`JsUndefined`](JsUndefined).
//! [`JsString`](JsString), [`JsNull`](JsNull), [`JsSymbol`](JsSymbol),
//! and [`JsUndefined`](JsUndefined).
//!
//! [types]: https://raw.githubusercontent.com/neon-bindings/neon/main/doc/types.jpg
//! [unknown]: https://mariusschulz.com/blog/the-unknown-type-in-typescript#the-unknown-type
Expand All @@ -80,6 +81,8 @@ pub(crate) mod date;
pub(crate) mod error;

pub(crate) mod internal;
#[cfg(all(feature = "napi-1", feature = "symbol-api"))]
pub(crate) mod symbol;
chrisbajorin marked this conversation as resolved.
Show resolved Hide resolved
pub(crate) mod utf8;

use self::internal::{FunctionCallback, ValueInternal};
Expand All @@ -105,6 +108,8 @@ pub use self::boxed::JsBox;
#[cfg(feature = "napi-5")]
pub use self::date::{DateError, DateErrorKind, JsDate};
pub use self::error::JsError;
#[cfg(all(feature = "napi-1", feature = "symbol-api"))]
pub use self::symbol::JsSymbol;

pub(crate) fn build<'a, T: Managed, F: FnOnce(&mut raw::Local) -> bool>(
env: Env,
Expand Down
81 changes: 81 additions & 0 deletions src/types/symbol.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use crate::context::Context;
use crate::handle::{Handle, Managed};
use crate::types::internal::ValueInternal;
use crate::types::{Env, JsString, Value};

use neon_runtime::raw;

/// A JavaScript symbol primitive value.
#[repr(C)]
#[derive(Clone, Copy)]
pub struct JsSymbol(raw::Local);

impl JsSymbol {
/// Create a new symbol.
/// Equivalent to calling `Symbol()` in JavaScript
pub fn new<'a, C: Context<'a>>(cx: &mut C) -> Handle<'a, JsSymbol> {
JsSymbol::new_internal(cx.env(), None)
}

/// Create a new symbol with a description.
/// Equivalent to calling `Symbol(description)` in JavaScript
pub fn with_description<'a, C: Context<'a>>(
cx: &mut C,
desc: Handle<'a, JsString>,
) -> Handle<'a, JsSymbol> {
JsSymbol::new_internal(cx.env(), Some(desc))
}

/// Get the optional symbol description, where `None` represents an undefined description.
pub fn description<'a, C: Context<'a>>(self, cx: &mut C) -> Option<Handle<'a, JsString>> {
Copy link
Member

Choose a reason for hiding this comment

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

I'd prefer if this were built into Node-API, but looks like it isn't. The best I can tell reading the ECMAScript spec, this property is guaranteed to exist and it's impossible to overwrite. @dherman is that correct?

Copy link
Author

Choose a reason for hiding this comment

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

FYI, when I first wrote up the RFC, node@10 was still in maintenance LTS, and symbol.prototype.description was unsupported. With this implementation, if I downgrade to 10.24, the description tests fail both the node and rust getter with:

  1) JsSymbol
       should return a JsSymbol with a description built in Rust:
     AssertionError: expected undefined to equal 'neon:description'
      at Context.<anonymous> (lib/symbols.js:8:16)

  2) JsSymbol
       should read the description property in Rust:
     AssertionError: expected undefined to equal 'neon:description'
      at Context.<anonymous> (lib/symbols.js:18:16)

neon_runtime::tag::is_string(env, local) returns false in the description function, so it returns None.

Copy link
Member

Choose a reason for hiding this comment

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

The good news is we no longer support Node 10 and can make that simplification.

let env = cx.env().to_raw();
const DESCRIPTION_KEY: &[u8] = b"description\0";
unsafe {
neon_runtime::object::get_named(env, self.to_raw(), DESCRIPTION_KEY.as_ptr()).and_then(
|local| {
if neon_runtime::tag::is_string(env, local) {
Some(Handle::new_internal(JsString(local)))
} else {
None
}
},
)
}
}

pub(crate) fn new_internal<'a>(
env: Env,
desc: Option<Handle<'a, JsString>>,
) -> Handle<'a, JsSymbol> {
unsafe {
let desc_local = match desc {
None => std::ptr::null_mut(),
Some(h) => h.to_raw(),
};
let sym_local = neon_runtime::primitive::symbol(env.to_raw(), desc_local);
Handle::new_internal(JsSymbol(sym_local))
}
}
}

impl Value for JsSymbol {}

impl Managed for JsSymbol {
fn to_raw(self) -> raw::Local {
self.0
}

fn from_raw(_: Env, h: raw::Local) -> Self {
JsSymbol(h)
}
}

impl ValueInternal for JsSymbol {
fn name() -> String {
"symbol".to_string()
}

fn is_typeof<Other: Value>(env: Env, other: Other) -> bool {
unsafe { neon_runtime::tag::is_symbol(env.to_raw(), other.to_raw()) }
}
}
2 changes: 1 addition & 1 deletion test/napi/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@ crate-type = ["cdylib"]
version = "*"
path = "../.."
default-features = false
features = ["default-panic-hook", "napi-6", "try-catch-api", "event-queue-api"]
features = ["default-panic-hook", "napi-6", "try-catch-api", "event-queue-api", "symbol-api"]
9 changes: 9 additions & 0 deletions test/napi/lib/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ describe('JsObject', function() {
assert.deepEqual({number: 9000, string: 'hello node'}, addon.return_js_object_with_mixed_content());
});

it('return a JsObject with a symbol property key', function () {
const obj = addon.return_js_object_with_symbol_property_key();
const propertySymbols = Object.getOwnPropertySymbols(obj);
assert.equal(propertySymbols.length, 1);
const [sym] = propertySymbols;
assert.typeOf(sym, "symbol");
assert.equal(obj[sym], sym);
})

it('gets a 16-byte, zeroed ArrayBuffer', function() {
var b = addon.return_array_buffer();
assert.equal(b.byteLength, 16);
Expand Down
42 changes: 42 additions & 0 deletions test/napi/lib/symbols.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const addon = require('..');
const { assert } = require('chai');

describe('JsSymbol', function () {
it('should return a JsSymbol with a description built with the context helper in Rust', function () {
const sym = addon.return_js_symbol_from_context_helper();
assert.typeOf(sym, 'symbol');
assert.equal(sym.description, 'neon:context_helper');
});

it('should return a JsSymbol with a description built in Rust', function () {
const description = 'neon:description'
const sym = addon.return_js_symbol_with_description(description);
assert.typeOf(sym, 'symbol');
assert.equal(sym.description, description);
});

it('should return a JsSymbol without a description built in Rust', function () {
const sym = addon.return_js_symbol();
assert.typeOf(sym, 'symbol');
assert.equal(sym.description, undefined);
});

it('should read the description property in Rust', function () {
const sym = Symbol('neon:description');
const description = addon.read_js_symbol_description(sym);
assert.equal(description, 'neon:description');
});

it('should read an undefined description property in Rust', function () {
const sym = Symbol();
const description = addon.read_js_symbol_description(sym);
assert.equal(description, undefined);
});

it('accepts and returns symbols', function () {
const symDesc = Symbol('neon:description');
const symNoDesc = Symbol();
assert.equal(addon.accept_and_return_js_symbol(symDesc), symDesc);
assert.equal(addon.accept_and_return_js_symbol(symNoDesc), symNoDesc);
});
});
13 changes: 13 additions & 0 deletions test/napi/lib/types.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,15 @@ describe('type checks', function() {
assert(!addon.is_string(new String('1')));
});

it('is_symbol', function () {
assert(addon.is_symbol(Symbol()));
assert(addon.is_symbol(Symbol("unique symbol")));
assert(addon.is_symbol(Symbol.for('neon:description')));
assert(addon.is_symbol(Symbol.iterator));
assert(!addon.is_symbol(undefined));
assert(!addon.is_symbol("anything other than symbol"));
});

it('is_undefined', function () {
assert(addon.is_undefined(undefined));
assert(!addon.is_undefined(null));
Expand All @@ -84,5 +93,9 @@ describe('type checks', function() {
assert(addon.strict_equals(o1, o1));
assert(!addon.strict_equals(o1, o2));
assert(!addon.strict_equals(o1, 17));
let s1 = Symbol();
let s2 = Symbol();
assert(addon.strict_equals(s1, s1));
assert(!addon.strict_equals(s1, s2));
});
});
7 changes: 7 additions & 0 deletions test/napi/src/js/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ pub fn return_js_object_with_string(mut cx: FunctionContext) -> JsResult<JsObjec
Ok(js_object)
}

pub fn return_js_object_with_symbol_property_key(mut cx: FunctionContext) -> JsResult<JsObject> {
let js_object = cx.empty_object();
let s = cx.symbol("neon:description");
js_object.set(&mut cx, s, s)?;
Ok(js_object)
}

pub fn return_array_buffer(mut cx: FunctionContext) -> JsResult<JsArrayBuffer> {
let b: Handle<JsArrayBuffer> = cx.array_buffer(16)?;
Ok(b)
Expand Down
27 changes: 27 additions & 0 deletions test/napi/src/js/symbols.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use neon::prelude::*;

pub fn return_js_symbol_from_context_helper(mut cx: FunctionContext) -> JsResult<JsSymbol> {
Ok(cx.symbol("neon:context_helper"))
}

pub fn return_js_symbol_with_description(mut cx: FunctionContext) -> JsResult<JsSymbol> {
let description: Handle<JsString> = cx.argument(0)?;
Ok(JsSymbol::with_description(&mut cx, description))
}

pub fn return_js_symbol(mut cx: FunctionContext) -> JsResult<JsSymbol> {
chrisbajorin marked this conversation as resolved.
Show resolved Hide resolved
Ok(JsSymbol::new(&mut cx))
}

pub fn read_js_symbol_description(mut cx: FunctionContext) -> JsResult<JsValue> {
let symbol: Handle<JsSymbol> = cx.argument(0)?;
symbol
.description(&mut cx)
.map(|v| Ok(v.upcast()))
.unwrap_or_else(|| Ok(cx.undefined().upcast()))
}

pub fn accept_and_return_js_symbol(mut cx: FunctionContext) -> JsResult<JsSymbol> {
let sym: Handle<JsSymbol> = cx.argument(0)?;
Ok(sym)
}
6 changes: 6 additions & 0 deletions test/napi/src/js/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ pub fn is_object(mut cx: FunctionContext) -> JsResult<JsBoolean> {
Ok(cx.boolean(result))
}

pub fn is_symbol(mut cx: FunctionContext) -> JsResult<JsBoolean> {
let val: Handle<JsValue> = cx.argument(0)?;
let result = val.is_a::<JsSymbol, _>(&mut cx);
Ok(cx.boolean(result))
}

pub fn is_undefined(mut cx: FunctionContext) -> JsResult<JsBoolean> {
let val: Handle<JsValue> = cx.argument(0)?;
let is_string = val.is_a::<JsUndefined, _>(&mut cx);
Expand Down
Loading