Skip to content
Merged
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
25 changes: 21 additions & 4 deletions bindings/js/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,22 @@ especially for array parameters. Codes must be signed 32-bit integers (for
example, `0x80004005 | 0`). These factories do not change the existing `i32()`
or `fromI32Values()` behavior. Read results with `toNumber()` or `toI32Vec()`.

WinRT enums retain their metadata-declared `Int32` or `UInt32` backing type.
`DynWinRtType.enumType(name, names, values)` still defaults to `Int32`. For a
`UInt32` flags enum, pass `DynWinRtType.u32()` as the fourth argument; generated
bindings do this automatically. `enumValue()`, `getEnumValue()`, `getEnumInt()`,
and `toNumber()` preserve unsigned values up to `0xffffffff`. Unsigned enum
arrays and struct fields use the U32 accessors, while signed enums keep their
I32 accessors. The backing type also participates in generic interface IIDs,
including `IReference<T>` and collection IIDs. Regenerate wrappers and update
the runtime together when adopting this support.

Generated inputs for metadata-declared `UInt32` flags also accept the signed
32-bit bit patterns produced by JavaScript bitwise operators: for example,
`-1` is normalized to `0xffffffff`. This applies only to generated flags-enum
inputs. Plain UInt32 values, non-flags enums, and low-level factories remain
strict and reject negative, fractional, non-finite, or out-of-range values.

### Classic COM

Classic COM is a preview under active development. It uses a separate subpath
Expand Down Expand Up @@ -407,10 +423,11 @@ vectors on x64 and ARM64. Large map keys/values are rejected even for empty maps

Structs and typed enums require exact type identity, not a matching byte size
or shape. Scalars require the matching value variant, except U16 inputs for
Char16, I32 inputs for enum/HRESULT, and range-checked I32 inputs for
I8/U8/Char16. For example, I32 `255` is accepted for U8; I32 `257` throws instead
of wrapping. Reference inputs are retained and queried for the declared IID;
an incompatible interface throws, while a null reference remains null.
Char16, I32 inputs for signed enum/HRESULT, U32 inputs for unsigned enum, and
range-checked I32 inputs for I8/U8/Char16. For example, I32 `255` is accepted for
U8; I32 `257` throws instead of wrapping. Reference inputs are retained and
queried for the declared IID; an incompatible interface throws, while a null
reference remains null.

For admitted POD structs, vector `IndexOf` and map key operations compare
metadata-declared fields by value, including nested fields, and ignore padding.
Expand Down
44 changes: 44 additions & 0 deletions bindings/js/__test__/collection-factories.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,50 @@ test('generated collection input and output contracts agree with native roundtri
t.diagnostic(JSON.stringify(checkCollectionContracts(generated, require(runtimeRoot))))
})

test('generated SDK flags preserve unsigned values through native calls and callbacks', () => {
const unused = () => {
throw new Error('Unused complete SDK interface slot')
}
let attributes = -1
const received = []
const owner = generated.IStorageItem.implement({
renameAsyncOverloadDefaultOptions: unused,
renameAsync: unused,
deleteAsyncOverloadDefaultOptions: unused,
deleteAsync: unused,
getBasicPropertiesAsync: unused,
getName: unused,
getPath: unused,
getAttributes: () => attributes,
getDateCreated: unused,
isOfType: (value) => {
received.push(value)
return true
},
})
try {
assert.equal(owner.value.attributes, 0xffffffff)
for (const [input, expected] of [
[-0x80000000, 0x80000000],
[-1, 0xffffffff],
[0x80000000, 0x80000000],
[0xffffffff, 0xffffffff],
]) {
assert.equal(owner.value.isOfType(input), true)
assert.equal(received.at(-1), expected)
}
const before = received.length
for (const invalid of [-0x80000001, 0x100000000, 1.5, NaN, Infinity]) {
assert.throws(() => owner.value.isOfType(invalid))
}
assert.equal(received.length, before)
attributes = -0x80000001
assert.throws(() => owner.value.attributes)
} finally {
owner.dispose()
}
})

test('generated string map factory converts both keys and values', (t) => {
const keep = own(t)
const keys = ['first', '\u03bb', '\ud83d\ude00']
Expand Down
2 changes: 1 addition & 1 deletion bindings/js/__test__/fixtures/collection-contracts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function unused() {

const numberExpected = {
code: 'NumberExpected',
message: 'Failed to convert napi value String into rust type `u32`',
message: 'Failed to convert napi value String into rust type `f64`',
}

export function checkCollectionContracts(g, runtime) {
Expand Down
22 changes: 22 additions & 0 deletions bindings/js/__test__/winrt-implementation.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ test('async and generator dispatchers are rejected before publication', (t) => {

test('scalar and enum ABI aliases survive synchronous callbacks without JS numeric coercion', (t) => {
const enumType = DynWinRtType.enumType('Tests.NodeReverseEnum', ['Answer'], [42])
const flagsType = DynWinRtType.enumType('Tests.NodeReverseFlags', ['All'], [0xffffffff], DynWinRtType.u32())
const cases: Array<{
type: DynWinRtType
value: DynWinRtValue
Expand Down Expand Up @@ -271,21 +272,42 @@ test('scalar and enum ABI aliases survive synchronous callbacks without JS numer
{ type: DynWinRtType.f32(), value: DynWinRtValue.f32(1.25), read: (v) => v.toF64(), expected: 1.25 },
{ type: DynWinRtType.f64(), value: DynWinRtValue.f64(-9.5), read: (v) => v.toF64(), expected: -9.5 },
{ type: enumType, value: DynWinRtValue.enumValue(enumType, 42), read: (v) => v.getEnumInt(), expected: 42 },
{
type: flagsType,
value: DynWinRtValue.enumValue(flagsType, 0xffffffff),
read: (v) => v.getEnumInt(),
expected: 0xffffffff,
},
{ type: flagsType, value: DynWinRtValue.u32(0x80000000), read: (v) => v.toNumber(), expected: 0x80000000 },
]
const methods = cases.map(({ type }, index) => ({
name: `Echo${index}`,
vtableIndex: index + 6,
signature: new DynWinRtMethodSig().addIn(type).addOut(type),
}))
const setterSlot = methods.length + 6
methods.push({
name: 'SetUInt32',
vtableIndex: setterSlot,
signature: new DynWinRtMethodSig().addIn(DynWinRtType.u32()),
})
const { type, plan } = fixture('2799ac23-bcd8-4086-b6f0-1f33b3af84be', methods, 'Tests.IWinRtScalars')
const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => {
if (slot === setterSlot) {
t.is(args[0].toNumber(), 0xffffffff)
return []
}
t.is(cases[slot - 6].read(args[0]), cases[slot - 6].expected)
return [args[0]]
})
const view = viewOf(owner, type.iid())
cases.forEach(({ value, read, expected }, index) => {
t.is(read(type.method(index + 6).invoke(view, [value])), expected)
})
type.method(setterSlot).setU32(view, 0xffffffff)
for (const invalid of [-1, 2 ** 32, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
t.throws(() => type.method(setterSlot).setU32(view, invalid))
}
owner.dispose()
view.release()
})
Expand Down
56 changes: 56 additions & 0 deletions bindings/js/__test__/winrt-marshalling.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,62 @@ function own(t: ExecutionContext, value: InstanceType<typeof DynWinRtValue>) {
return value
}

test('unsigned enums retain SDK IIDs and high-bit values across native storage', (t) => {
const flags = DynWinRtType.enumType(
'Windows.Gaming.Input.GamepadButtons',
['High', 'All'],
[0x80000000, 0xffffffff],
DynWinRtType.u32(),
)
const vector = DynWinRtType.parameterized(WinGuid.parse('913337e9-11a1-4345-a3a2-4e7f956e222d'), [flags])
const reference = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [flags])
t.is(vector.iid().toString().toLowerCase(), '2da67b4c-03d3-57c7-8257-6c30837177ac')
t.is(reference.iid().toString().toLowerCase(), '9b7e3bfb-85a9-5b98-81b3-1af4a060a6f5')
t.is(DynWinRtType.getEnumValue('Windows.Gaming.Input.GamepadButtons', 'All'), 0xffffffff)
const getter = DynWinRtType.registerInterface('EnumContracts.IReferenceFlags', reference.iid())
.addMethod('get_Value', new DynWinRtMethodSig().addOut(flags))
.method(6)

const values = [0, 0x80000000, 0xffffffff].map((value) => own(t, DynWinRtValue.enumValue(flags, value)))
for (const [index, expected] of [0, 0x80000000, 0xffffffff].entries()) {
t.is(values[index].toNumber(), expected)
t.is(values[index].getEnumInt(), expected)
const boxed = own(t, DynWinRtValue.boxReference(values[index], flags))
const view = own(t, boxed.cast(reference.iid()))
t.is(own(t, getter.invoke(view, [])).toNumber(), expected)
t.throws(() => getter.getI32(view))
}
t.is(values[2].getEnumName(), 'All')
const array = DynWinRtArray.fromObjectValues(values, flags)
t.deepEqual(array.toU32Vec(), [0, 0x80000000, 0xffffffff])
t.throws(() => array.toI32Vec())
const record = DynWinRtStruct.create(DynWinRtType.structType('EnumContracts.FlagRecord', [flags]))
record.setU32(0, 0xffffffff)
t.is(record.getU32(0), 0xffffffff)
t.throws(() => record.getI32(0))

for (const value of [-1, 2 ** 32, 1.5, NaN, Infinity]) {
t.throws(() => DynWinRtValue.enumValue(flags, value))
}
t.throws(() => DynWinRtValue.enumValue(DynWinRtType.u32(), 1))
t.throws(() => DynWinRtType.enumType('Windows.Gaming.Input.GamepadButtons'), { message: /backing type/ })
t.throws(() => DynWinRtType.enumType('EnumContracts.Bad', [], [], DynWinRtType.u64()))
t.throws(() => DynWinRtType.enumType('EnumContracts.Range', ['Bad'], [-1], DynWinRtType.u32()))
t.throws(() => DynWinRtType.enumType('EnumContracts.Length', ['Missing'], []))

const signed = DynWinRtType.enumType('EnumContracts.Signed', ['Negative'], [-1])
const negative = own(t, DynWinRtValue.enumValue(signed, -1))
t.is(negative.toNumber(), -1)
t.is(negative.getEnumInt(), -1)
t.is(DynWinRtType.getEnumValue('EnumContracts.Signed', 'Negative'), -1)
t.throws(() => DynWinRtValue.enumValue(signed, 0x80000000))

for (const invalid of [-1, 2 ** 32, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
t.throws(() => DynWinRtValue.u32(invalid))
t.throws(() => DynWinRtArray.fromU32Values([0, invalid]))
}
})

function registerMethodAt(
name: string,
iid: InstanceType<typeof WinGuid>,
Expand Down
2 changes: 1 addition & 1 deletion bindings/js/src/com.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4744,7 +4744,7 @@ impl DynCom {
}

#[napi]
pub fn u32(value: u32) -> DynWinRTValue {
pub fn u32(value: f64) -> napi::Result<DynWinRTValue> {
DynWinRTValue::u32(value)
}

Expand Down
41 changes: 26 additions & 15 deletions bindings/js/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,10 @@ impl DynWinRTValue {
Self::hresult(value)
}
#[napi]
pub fn u32(value: u32) -> DynWinRTValue {
DynWinRTValue::new(dynwinrt::WinRTValue::U32(value))
pub fn u32(value: f64) -> napi::Result<DynWinRTValue> {
Ok(DynWinRTValue::new(dynwinrt::WinRTValue::U32(js_u32(
value, "u32",
)?)))
}
#[napi]
pub fn i64(value: Either<BigInt, f64>) -> napi::Result<DynWinRTValue> {
Expand All @@ -175,13 +177,19 @@ impl DynWinRTValue {
pub fn f64(value: f64) -> DynWinRTValue {
DynWinRTValue::new(dynwinrt::WinRTValue::F64(value))
}
/// Create an enum value from an i32. The type_handle must be an enum type.
/// Create an enum value within the enum's declared i32 or u32 range.
#[napi]
pub fn enum_value(enum_type: &DynWinRTType, value: i32) -> DynWinRTValue {
DynWinRTValue::new(dynwinrt::WinRTValue::Enum {
value,
type_handle: enum_type.0.clone(),
})
pub fn enum_value(enum_type: &DynWinRTType, value: f64) -> napi::Result<DynWinRTValue> {
let value = if enum_type.0.underlying_kind() == dynwinrt::TypeKind::U32 {
i64::from(js_u32(value, "enumValue")?)
} else {
i64::from(js_i32(value, "enumValue")?)
};
enum_type
.0
.enum_value(value)
.map(DynWinRTValue::new)
.map_err(|error| napi::Error::from_reason(error.message()))
}

#[napi]
Expand All @@ -194,13 +202,10 @@ impl DynWinRTValue {
.map_err(|e| napi::Error::from_reason(e.message()))
}

/// Get the i32 value of an enum. Returns None if not an enum.
/// Get the signed or unsigned numeric value of an enum. Returns None if not an enum.
#[napi]
pub fn get_enum_int(&self) -> Option<i32> {
match &self.winrt {
dynwinrt::WinRTValue::Enum { value, .. } => Some(*value),
_ => None,
}
pub fn get_enum_int(&self) -> Option<f64> {
self.winrt.as_enum_number().map(|value| value as f64)
}

/// Get the member name of an enum value. Returns None if not an enum or no matching member.
Expand Down Expand Up @@ -427,7 +432,13 @@ impl DynWinRTValue {
dynwinrt::WinRTValue::I32(i) => f64::from(*i),
dynwinrt::WinRTValue::U32(i) => f64::from(*i),
dynwinrt::WinRTValue::HResult(hr) => f64::from(hr.0),
dynwinrt::WinRTValue::Enum { value, .. } => f64::from(*value),
dynwinrt::WinRTValue::Enum { value, type_handle } => {
if type_handle.underlying_kind() == dynwinrt::TypeKind::U32 {
f64::from(*value as u32)
} else {
f64::from(*value)
}
}
_ => {
return Err(napi::Error::from_reason(format!(
"Cannot convert {:?} to number",
Expand Down
27 changes: 16 additions & 11 deletions bindings/js/src/winrt_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ where
T: Copy,
{
let actual = array.element_type.kind();
if !expected(actual) {
if !expected(array.element_type.underlying_kind()) {
return Err(napi::Error::from_reason(format!(
"{method} cannot read an array with element type {actual:?}",
)));
Expand Down Expand Up @@ -185,12 +185,7 @@ impl DynWinRTArray {
collect_typed_array(
&self.0,
"toI32Vec",
|kind| {
matches!(
kind,
dynwinrt::TypeKind::I32 | dynwinrt::TypeKind::Enum(_) | dynwinrt::TypeKind::HResult
)
},
|kind| matches!(kind, dynwinrt::TypeKind::I32 | dynwinrt::TypeKind::HResult),
|value: i32| value,
|value| match value {
dynwinrt::WinRTValue::I32(value) | dynwinrt::WinRTValue::Enum { value, .. } => Some(value),
Expand All @@ -209,6 +204,11 @@ impl DynWinRTArray {
|value: u32| value,
|value| match value {
dynwinrt::WinRTValue::U32(value) => Some(value),
dynwinrt::WinRTValue::Enum { value, type_handle }
if type_handle.underlying_kind() == dynwinrt::TypeKind::U32 =>
{
Some(value as u32)
}
_ => None,
},
)
Expand Down Expand Up @@ -355,10 +355,15 @@ impl DynWinRTArray {
}

#[napi]
pub fn from_u32_values(values: Vec<u32>) -> DynWinRTArray {
let wvals: Vec<dynwinrt::WinRTValue> =
values.into_iter().map(dynwinrt::WinRTValue::U32).collect();
DynWinRTArray::new(dynwinrt::ArrayData::from_values(TABLE.u32_type(), &wvals))
pub fn from_u32_values(values: Vec<f64>) -> napi::Result<DynWinRTArray> {
let wvals = values
.into_iter()
.map(|value| js_u32(value, "fromU32Values").map(dynwinrt::WinRTValue::U32))
.collect::<napi::Result<Vec<_>>>()?;
Ok(DynWinRTArray::new(dynwinrt::ArrayData::from_values(
TABLE.u32_type(),
&wvals,
)))
}

#[napi]
Expand Down
3 changes: 2 additions & 1 deletion bindings/js/src/winrt_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,8 @@ impl DynWinRTMethodHandle {
}

#[napi]
pub fn set_u32(&self, obj: &DynWinRTValue, value: u32) -> napi::Result<()> {
pub fn set_u32(&self, obj: &DynWinRTValue, value: f64) -> napi::Result<()> {
let value = crate::js_numbers::js_u32(value, "setU32")?;
let raw = obj
.winrt()
.as_object()
Expand Down
12 changes: 3 additions & 9 deletions bindings/js/src/winrt_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl DynWinRTStruct {
handle.field_count(),
)));
}
let actual = handle.field_type(index).kind();
let actual = handle.field_type(index).underlying_kind();
if !accepts(actual) {
return Err(napi::Error::from_reason(format!(
"{method}: field {index} has type {actual:?}, expected {expected}",
Expand Down Expand Up @@ -163,20 +163,14 @@ impl DynWinRTStruct {
#[napi]
pub fn get_i32(&self, index: f64) -> napi::Result<i32> {
let index = self.checked_field_index(index, "getI32", "i32, enum, or HRESULT", |kind| {
matches!(
kind,
dynwinrt::TypeKind::I32 | dynwinrt::TypeKind::Enum(_) | dynwinrt::TypeKind::HResult
)
matches!(kind, dynwinrt::TypeKind::I32 | dynwinrt::TypeKind::HResult)
})?;
Ok(self.0.get_field::<i32>(index))
}
#[napi]
pub fn set_i32(&mut self, index: f64, value: f64) -> napi::Result<()> {
let index = self.checked_field_index(index, "setI32", "i32, enum, or HRESULT", |kind| {
matches!(
kind,
dynwinrt::TypeKind::I32 | dynwinrt::TypeKind::Enum(_) | dynwinrt::TypeKind::HResult
)
matches!(kind, dynwinrt::TypeKind::I32 | dynwinrt::TypeKind::HResult)
})?;
self.0.set_field(index, js_i32(value, "setI32")?);
Ok(())
Expand Down
Loading
Loading