From 7deb7bf82b841874189456ed1964230ec273d90c Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Tue, 8 Sep 2026 21:39:06 +0800 Subject: [PATCH 1/8] feat: add standalone WinRT interface implementations Add metadata-validated WinRT reverse-call plans, standalone multi-interface IInspectable objects, and synchronous owner-thread handlers for Node.js and Python. Generate typed implementation factories and independently owned views, preserve callback lifetime and output ownership, and cover real native vtable calls, properties, events, arrays, and multi-output results. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 14 + bindings/js/Cargo.toml | 2 +- bindings/js/README.md | 82 ++ .../__test__/winrt-event-lifetime-child.mjs | 124 ++ .../__test__/winrt-implementation-child.mjs | 142 ++ .../__test__/winrt-implementation-worker.mjs | 27 + .../js/__test__/winrt-implementation.spec.ts | 889 ++++++++++++ bindings/js/package.json | 3 +- bindings/js/scripts/generate-entrypoints.mjs | 12 +- bindings/js/src/lib.rs | 71 +- bindings/js/src/winrt_delegate_method.rs | 130 ++ bindings/js/src/winrt_implementation.rs | 543 +++++++ .../js/src/winrt_implementation_test_hooks.rs | 196 +++ bindings/py/README.md | 113 ++ bindings/py/dynwinrt.pyi | 91 ++ bindings/py/src/delegate_method.rs | 78 + bindings/py/src/errors.rs | 3 + bindings/py/src/implementation.py | 73 + bindings/py/src/implementation.rs | 642 ++++++++ bindings/py/src/lib.rs | 5 + bindings/py/src/runtime.rs | 22 +- bindings/py/tests/test_implementation.py | 1292 +++++++++++++++++ bindings/py/tests/test_typing_package.py | 18 + crates/dynwinrt/Cargo.toml | 5 + crates/dynwinrt/src/array.rs | 35 +- crates/dynwinrt/src/call.rs | 1 + crates/dynwinrt/src/lib.rs | 5 + .../dynwinrt/src/metadata_table/value_data.rs | 31 + crates/dynwinrt/src/native_call.rs | 27 +- crates/dynwinrt/src/signature.rs | 38 + .../src/winrt_implementation/identity.rs | 207 +++ .../dynwinrt/src/winrt_implementation/mod.rs | 583 ++++++++ .../dynwinrt/src/winrt_implementation/plan.rs | 268 ++++ .../src/winrt_implementation/tests.rs | 1175 +++++++++++++++ .../src/winrt_implementation/values.rs | 607 ++++++++ .../winrt-interface-implementations.md | 179 +++ .../winrt-interface-implementations.md | 271 ++++ samples/js/README.md | 1 + samples/js/interface-implementation/README.md | 41 + samples/js/interface-implementation/app.mjs | 80 + .../js/interface-implementation/generate.ps1 | 28 + .../package-lock.json | 47 + .../js/interface-implementation/package.json | 11 + samples/python/README.md | 1 + .../python/interface-implementation/README.md | 41 + .../python/interface-implementation/app.py | 116 ++ .../interface-implementation/generate.ps1 | 28 + .../python/interface-implementation/run.ps1 | 16 + tests/e2e/e2e_test.ps1 | 44 +- tests/e2e/implementation_test.ps1 | 145 ++ tests/e2e/runners/implementation_js.mjs | 666 +++++++++ tests/e2e/runners/implementation_js.test.mjs | 39 + tests/e2e/runners/implementation_py.py | 1035 +++++++++++++ .../runners/test_implementation_runners.py | 85 ++ .../typecheck/python_implementation_api.py | 284 ++++ tests/e2e/typecheck/ts_implementation_api.ts | 193 +++ .../src/codegen/winrt/javascript/generator.rs | 9 + .../winrt/javascript/implementation.rs | 850 +++++++++++ .../src/codegen/winrt/javascript/ir.rs | 23 + .../src/codegen/winrt/javascript/method.rs | 1 + .../src/codegen/winrt/javascript/mod.rs | 8 + .../codegen/winrt/javascript/project/mod.rs | 25 +- .../winrt/javascript/render/declarations.rs | 3 + .../winrt/javascript/render/javascript/mod.rs | 12 +- .../src/codegen/winrt/javascript/signature.rs | 12 +- .../codegen/winrt/python/generator/index.rs | 9 + .../codegen/winrt/python/generator/types.rs | 21 +- .../codegen/winrt/python/implementation.rs | 978 +++++++++++++ .../src/codegen/winrt/python/mod.rs | 1 + .../src/codegen/winrt/python/naming.rs | 100 +- .../src/codegen/winrt/python/signature.rs | 4 +- .../src/codegen/winrt/python/stubs.rs | 36 +- .../codegen/winrt/shared/implementation.rs | 797 ++++++++++ .../src/codegen/winrt/shared/imports.rs | 8 + .../src/codegen/winrt/shared/mod.rs | 1 + .../src/codegen/winrt/shared/structs.rs | 8 +- tools/dynwinrt-codegen/src/main.rs | 59 +- tools/dynwinrt-codegen/src/meta.rs | 434 ++++++ .../tests/python_identity_cache_test.rs | 2 +- .../tests/python_inheritance_typing_test.rs | 2 +- .../uri/windows/foundation/IStringable.d.ts | 15 +- .../uri/windows/foundation/IStringable.js | 94 +- ...iRuntimeClassWithAbsoluteCanonicalUri.d.ts | 16 +- ...UriRuntimeClassWithAbsoluteCanonicalUri.js | 101 +- .../foundation/IWwwFormUrlDecoderEntry.d.ts | 16 +- .../foundation/IWwwFormUrlDecoderEntry.js | 101 +- ...FormUrlDecoderEntry_g498f64075ebd0fce.d.ts | 5 + ...wwFormUrlDecoderEntry_g498f64075ebd0fce.js | 4 + .../tests/snapshots/uri_py/__init__.py | 3 + ...i_iterator_i_www_form_url_decoder_entry.py | 13 +- .../tests/snapshots/uri_py/i_stringable.py | 138 +- ...ntime_class_with_absolute_canonical_uri.py | 146 +- .../uri_py/i_www_form_url_decoder_entry.py | 146 +- .../tests/snapshots/uri_pyi/__init__.pyi | 3 + ..._iterator_i_www_form_url_decoder_entry.pyi | 1 + .../tests/snapshots/uri_pyi/i_stringable.pyi | 18 +- ...time_class_with_absolute_canonical_uri.pyi | 19 +- .../uri_pyi/i_www_form_url_decoder_entry.pyi | 19 +- .../dynwinrt-codegen/tests/tsc_check_test.rs | 29 + .../tests/winrt_implementation_test.rs | 1246 ++++++++++++++++ 100 files changed, 16368 insertions(+), 73 deletions(-) create mode 100644 bindings/js/__test__/winrt-event-lifetime-child.mjs create mode 100644 bindings/js/__test__/winrt-implementation-child.mjs create mode 100644 bindings/js/__test__/winrt-implementation-worker.mjs create mode 100644 bindings/js/__test__/winrt-implementation.spec.ts create mode 100644 bindings/js/src/winrt_delegate_method.rs create mode 100644 bindings/js/src/winrt_implementation.rs create mode 100644 bindings/js/src/winrt_implementation_test_hooks.rs create mode 100644 bindings/py/src/delegate_method.rs create mode 100644 bindings/py/src/implementation.py create mode 100644 bindings/py/src/implementation.rs create mode 100644 bindings/py/tests/test_implementation.py create mode 100644 crates/dynwinrt/src/winrt_implementation/identity.rs create mode 100644 crates/dynwinrt/src/winrt_implementation/mod.rs create mode 100644 crates/dynwinrt/src/winrt_implementation/plan.rs create mode 100644 crates/dynwinrt/src/winrt_implementation/tests.rs create mode 100644 crates/dynwinrt/src/winrt_implementation/values.rs create mode 100644 docs/architecture/winrt-interface-implementations.md create mode 100644 docs/guides/windows/winrt-interface-implementations.md create mode 100644 samples/js/interface-implementation/README.md create mode 100644 samples/js/interface-implementation/app.mjs create mode 100644 samples/js/interface-implementation/generate.ps1 create mode 100644 samples/js/interface-implementation/package-lock.json create mode 100644 samples/js/interface-implementation/package.json create mode 100644 samples/python/interface-implementation/README.md create mode 100644 samples/python/interface-implementation/app.py create mode 100644 samples/python/interface-implementation/generate.ps1 create mode 100644 samples/python/interface-implementation/run.ps1 create mode 100644 tests/e2e/implementation_test.ps1 create mode 100644 tests/e2e/runners/implementation_js.mjs create mode 100644 tests/e2e/runners/implementation_js.test.mjs create mode 100644 tests/e2e/runners/implementation_py.py create mode 100644 tests/e2e/runners/test_implementation_runners.py create mode 100644 tests/e2e/typecheck/python_implementation_api.py create mode 100644 tests/e2e/typecheck/ts_implementation_api.ts create mode 100644 tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs create mode 100644 tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation.rs create mode 100644 tools/dynwinrt-codegen/tests/winrt_implementation_test.rs diff --git a/README.md b/README.md index c6e7f72e..40a2ae07 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,20 @@ names, native Python values, asyncio-compatible awaitables, and type stubs. - [Python codegen package guide](tools/dynwinrt-codegen/python/README.md) - [Python runtime guide](bindings/py/README.md) +### Implementing WinRT interfaces + +Node.js and Python can supply synchronous handlers for complete non-generic +WinRT interfaces. Generated `.implementation(...)` descriptors compose multiple +interfaces into a standalone IInspectable object, and `.implement(...)` creates +its owner. Public typed interface views can be passed to ordinary native +consumers without a WinUI composable base or OS registration. + +The first release is non-agile and owner-thread-only. Reference release and +object-wide callback disposal are separate operations. See +[WinRT interface implementations](docs/guides/windows/winrt-interface-implementations.md) +for both language APIs, supported method/property/event/array/output contracts, +ownership, and the separate IBackgroundTask deployment concerns. + ### WinUI `Application + Window` When `Microsoft.UI.Xaml.Application` is selected, codegen emits helpers for diff --git a/bindings/js/Cargo.toml b/bindings/js/Cargo.toml index a9be7a15..af793983 100644 --- a/bindings/js/Cargo.toml +++ b/bindings/js/Cargo.toml @@ -12,7 +12,7 @@ repository = "https://github.com/microsoft/dynwinrt" crate-type = ["cdylib"] [features] -test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager"] +test-hooks = ["windows/Win32_System_Wmi", "windows/Win32_Media_DeviceManager", "windows/ApplicationModel_Background"] [dependencies] napi = { version = "3", features = ["napi7"] } diff --git a/bindings/js/README.md b/bindings/js/README.md index 9319224f..c85fe057 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -69,6 +69,86 @@ contains duplicate short names, each canonical module keeps its native symbol name while the root barrel uses a namespace-qualified name, such as `AIFoundationEmbeddingVector` or `SemanticSearchEmbeddingVector`. +### Standalone WinRT interface implementations + +Metadata-generated standalone WinRT interfaces expose `implementation(handlers)` +and `implement(handlers, ...additionalDescriptors)`. The latter returns a +`DynWinRtImplementation` owner; use the public +`GeneratedInterface.fromImplementation(owner)` factory to create an +independently owned typed view. Low-level users must select an interface with +`value.cast(iid)` before invoking that interface's method handles: `toValue()` +returns the canonical `IInspectable`, not an arbitrary interface's vtable. +These are local, synchronous, non-agile WinRT objects, not COM class +registrations or OS background-task registrations. + +The npm root also exports the low-level primitives for metadata-driven callers: + +```ts +DynWinRtInterfacePlan.create(name, interfaceType, [ + { name: 'ToString', vtableIndex: 6, signature }, +], requiredIids) + +DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { + return [DynWinRtValue.hstring('implemented in JavaScript')] +}, runtimeClassName) +``` + +Plans must describe each complete interface, including every contiguous native +slot starting at 6. Required interfaces need separate plans. The dispatcher +receives `DynWinRtValue[]` and must return an array of **all** outputs in signature +order (`[]` for void). Fill-array inputs are capacities; their returned arrays +must have exactly that length. Async functions, promises, and thenable results +are unsupported. Dispatch errors fail the native call; `takeError()` returns and +clears the latest diagnostic, or `null` when there is none. + +`release()` and owner garbage collection drop only the owner's native reference. +Separately retained native values keep their callbacks alive. `disconnect()` +closes every view while retaining the owner reference; `dispose()` disconnects +and releases it, and both are idempotent. Disposing during a callback allows that +active invocation to finish safely. `isClosed` describes object-wide callback +disconnection, not merely whether this owner was released. + +**Always dispose deterministically when handlers capture their owner or a native +view.** Such cross-runtime cycles cannot be collected by JavaScript alone. +Disposal breaks native callback roots; final reference cleanup runs on a later +event-loop turn. Cleanup TSFNs do not keep Node alive. Environment shutdown +disconnects all live implementations before releasing handler references, and +callbacks from other threads fail rather than touching the JS environment. + +Native delegates received by an implementation can be invoked with +`value.invokeDelegate(iid, signature, args)`. For repeated calls, cache a +`DynWinRtDelegateMethod.create(iid, signature)` and use its `invoke(value, args)` +method instead. Both query the metadata's concrete delegate IID, retain the +managed values for the call, and return all outputs in signature order (`[]` for void). Delegate +`Invoke` occupies `IUnknown` slot 3; do not register it as an ordinary slot-6 +WinRT interface method. The IID and full signature must come from delegate +metadata, including concrete type arguments for generic delegates. This helper +uses only the WinRT call planner and performs no COM registration. +Its arguments follow the existing outbound `invokeAll()` contract: a fill-array +input is a preallocated, correctly typed `DynWinRtArray.toValue()`, not a U32 +capacity value. Only reverse-entry implementation handlers receive capacities. +Generated callable delegate bridges must allocate this outbound storage before +invoking the helper. + +`DynWinRtDelegate.release()` deterministically drops the creator's native +reference, without disconnecting references retained by a native event source. +Event registration code must release its temporary `toValue()` result and the +creator in `finally` after the add call, on success and failure. A successful +event source owns the delegate independently until removal. Retaining a creator +in the same closure context as its native callback can otherwise form a +cross-runtime cycle and keep the delegate's referenced TSFN alive after +unsubscribe. Releasing the creator twice is harmless; `toValue()` after release +throws. This does not unref active event callbacks or force process exit. + +For metadata whose native type is HRESULT, use `DynWinRtValue.fromHResult(code)` +(also available as `hresult(code)`) +or `DynWinRtArray.fromHresultValues(codes)` to preserve its semantic type, +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()`. + +### Classic COM + Classic COM is a preview under active development. It uses a separate subpath from the same package, keeping the WinRT root API unchanged: @@ -91,6 +171,8 @@ See the repository's codegen, current coverage and limitations, GUID/IID/CLSID, lifetime, Automation, and `/com/unsafe` examples. +### Generated WinRT values + Unambiguous public WinRT activation metadata is projected as JavaScript constructors. Parameterized and composable activations support idiomatic forms such as `new Uri(base, relative)` and `new StackPanel()`. The generated static factory diff --git a/bindings/js/__test__/winrt-event-lifetime-child.mjs b/bindings/js/__test__/winrt-event-lifetime-child.mjs new file mode 100644 index 00000000..fc7b1d0b --- /dev/null +++ b/bindings/js/__test__/winrt-event-lifetime-child.mjs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { + DynWinRtDelegate, + DynWinRtImplementation, + DynWinRtInterfacePlan, + DynWinRtMethodSig, + DynWinRtStruct, + DynWinRtType, + DynWinRtValue, + WinGuid, + roInitialize, +} from '../dist/winrt.js' + +roInitialize(1) +const mode = process.argv[2] +const referenceIid = WinGuid.parse('fbc4dd29-245b-11e4-af98-689423260cf8') +const closableIid = WinGuid.parse('30d5a829-7fa4-4026-83bb-d75bae4ea99e') +const delegateType = DynWinRtType.parameterized( + WinGuid.parse('9de1c534-6ae1-11e0-84e1-18a905bcc53f'), + [DynWinRtType.interface(referenceIid), DynWinRtType.object()], +) +const delegateIid = delegateType.iid() +const delegateArgs = [DynWinRtType.interface(referenceIid), DynWinRtType.object()] +const invokeSignature = new DynWinRtMethodSig().addIn(delegateArgs[0]).addIn(delegateArgs[1]) +const tokenType = DynWinRtType.structType('Windows.Foundation.EventRegistrationToken', [DynWinRtType.i64()]) +const methods = [ + { name: 'get_Capacity', vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(DynWinRtType.u32()) }, + { name: 'add_Closed', vtableIndex: 7, signature: new DynWinRtMethodSig().addIn(delegateType).addOut(tokenType) }, + { name: 'remove_Closed', vtableIndex: 8, signature: new DynWinRtMethodSig().addIn(tokenType) }, +] +let referenceType = DynWinRtType.registerInterface('Windows.Foundation.IMemoryBufferReference', referenceIid) +for (const method of methods) referenceType = referenceType.addMethod(method.name, method.signature) +const closeSignature = new DynWinRtMethodSig() +const closableType = DynWinRtType.registerInterface('Windows.Foundation.IClosable', closableIid) + .addMethod('Close', closeSignature) +const referencePlan = DynWinRtInterfacePlan.create( + 'Windows.Foundation.IMemoryBufferReference', referenceType, methods, [closableIid], +) +const closePlan = DynWinRtInterfacePlan.create('Windows.Foundation.IClosable', closableType, [ + { name: 'Close', vtableIndex: 6, signature: closeSignature }, +]) + +let retained +let sender +let delivered = 0 +let removed = 0 +const owner = DynWinRtImplementation.create([referencePlan, closePlan], (index, slot, args) => { + if (index === 1) { + retained?.invokeDelegate(delegateIid, invokeSignature, [sender, DynWinRtValue.nullValue()]) + return [] + } + if (slot === 6) return [DynWinRtValue.u32(4096)] + if (slot === 7) { + if (mode === 'add-failure') throw new Error('expected subscription rejection') + retained = args[0] + const token = DynWinRtStruct.create(tokenType) + token.setI64(0, 1n) + return [token.toValue()] + } + assert.equal(args[0].asStruct().getI64(0), 1n) + retained.release() + retained = undefined + removed++ + return [] +}) +const canonical = owner.toValue() +sender = canonical.cast(referenceIid) +const closer = canonical.cast(closableIid) +canonical.release() + +function onClosed(callback) { + // Mirror generated events: sibling closures share the context containing + // wrapped, handler, and the returned unsubscribe closure. + const wrapped = (nativeSender, args) => callback(nativeSender, args) + const handler = DynWinRtDelegate.create(delegateIid, delegateArgs, wrapped) + let value + let token + try { + value = handler.toValue() + token = referenceType.method(7).invoke(sender, [value]) + } finally { + value?.release() + handler.release() + } + return () => { + void handler + referenceType.method(8).invoke(sender, [token]) + } +} + +try { + if (mode === 'add-failure') { + assert.throws(() => onClosed(() => {}), /expected subscription rejection/) + assert.equal(retained, undefined) + } else { + assert.ok(mode === 'remove' || mode === 'once') + const unsubscribe = onClosed((nativeSender, args) => { + assert.equal(referenceType.method(6).invoke(nativeSender, []).toNumber(), 4096) + assert.equal(args.isNull(), true) + delivered++ + if (mode === 'once') unsubscribe() + }) + // Keeping the unsubscribe function reachable must not keep an unsubscribed + // native delegate alive. No GC or forced process exit is used in this test. + globalThis.retainedUnsubscribe = unsubscribe + owner.release() + closableType.method(6).invokeAll(closer, []) + assert.equal(delivered, 1) + if (mode === 'remove') unsubscribe() + assert.equal(removed, 1) + assert.equal(retained, undefined) + closableType.method(6).invokeAll(closer, []) + assert.equal(delivered, 1) + } +} finally { + retained?.release() + sender.release() + closer.release() + owner.dispose() +} +console.log(`generated-event-lifetime-ok:${mode}`) diff --git a/bindings/js/__test__/winrt-implementation-child.mjs b/bindings/js/__test__/winrt-implementation-child.mjs new file mode 100644 index 00000000..dbe78d43 --- /dev/null +++ b/bindings/js/__test__/winrt-implementation-child.mjs @@ -0,0 +1,142 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict' +import { once } from 'node:events' +import { createRequire } from 'node:module' +import { setImmediate as tick } from 'node:timers/promises' +import { Worker } from 'node:worker_threads' + +const runtimePath = process.env.DYNWINRT_TEST_RUNTIME +const runtime = createRequire(import.meta.url)(runtimePath) +const { + DynWinRtImplementation: Implementation, + DynWinRtInterfacePlan: Plan, + DynWinRtType: Type, + DynWinRtMethodSig: Signature, + DynWinRtValue: Value, + WinGuid, +} = runtime +runtime.roInitialize(1) + +const mode = process.argv[2] +const iid = WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3') +const signature = new Signature().addOut(Type.hstring()) +const plan = Plan.create('Windows.Foundation.IStringable', Type.interface(iid), [ + { name: 'ToString', vtableIndex: 6, signature }, +]) +const callbackFor = (sentinel) => () => [Value.hstring(sentinel.text)] +const stats = () => runtime.winrtImplementationTestStats() + +async function collect(reference) { + for (let i = 0; i < 100; i++) { + await tick() + global.gc() + await tick() + if (reference.deref() === undefined) return true + } + return false +} + +if (mode === 'retention') { + function retain() { + const sentinel = { text: 'native-retained callback' } + const owner = Implementation.create([plan], callbackFor(sentinel)) + const value = owner.toValue() + runtime.winrtImplementationTestRetain(value) + value.release() + return { owner: new WeakRef(owner), sentinel: new WeakRef(sentinel) } + } + const references = retain() + assert.equal(await collect(references.owner), true, 'the JS owner should be collectable') + assert.notEqual(references.sentinel.deref(), undefined, 'a native reference retains the callback') + assert.equal(runtime.winrtImplementationTestInvokeRetained().text, 'native-retained callback') + assert.equal(runtime.winrtImplementationTestInvokeRetained(true).hresult, 0x8001010e | 0) + runtime.winrtImplementationTestReleaseRetained(true) + assert.equal(await collect(references.sentinel), true, 'foreign final release frees callback roots on the JS thread') + assert.equal(stats().liveControls, 0) + assert.equal(stats().finalizedCallbacks, 1) +} else if (mode === 'cycle') { + function createCycle() { + const sentinel = { text: 'cycle' } + const owner = Implementation.create([plan], () => { + assert.equal(owner.isClosed, false) + return [Value.hstring(sentinel.text)] + }) + return { owner: new WeakRef(owner), sentinel: new WeakRef(sentinel) } + } + const references = createCycle() + for (let i = 0; i < 5; i++) { + await tick() + global.gc() + } + assert.notEqual(references.owner.deref(), undefined, 'a callback that captures its owner is a cross-runtime cycle') + assert.equal(stats().liveControls, 1) + references.owner.deref().dispose() + assert.equal(await collect(references.owner), true, 'dispose breaks the owner/callback cycle') + assert.equal(await collect(references.sentinel), true) + assert.equal(stats().liveControls, 0) +} else if (mode === 'reentrant-release') { + const owner = Implementation.create([plan], () => { + runtime.winrtImplementationTestReleaseRetained() + return [Value.hstring('completed after release')] + }) + const value = owner.toValue() + runtime.winrtImplementationTestRetain(value) + value.release() + owner.release() + assert.equal(runtime.winrtImplementationTestInvokeRetained().text, 'completed after release') + assert.equal(owner.isClosed, true) + for (let i = 0; i < 5; i++) await tick() + assert.equal(stats().liveControls, 0) +} else if (mode === 'delegate-release' || mode === 'delegate-value-release') { + const delegateIid = WinGuid.parse('749139bd-84a7-4abd-b17d-871a77c5c39f') + const signature = new Signature().addIn(Type.i32()) + const method = runtime.DynWinRtDelegateMethod.create(delegateIid, signature) + const callbackForValue = (box, sentinel) => (argument) => { + assert.equal(argument.toNumber(), 42) + sentinel.called = true + box.value.release() + } + function createDelegate() { + const box = {} + const sentinel = { called: false } + const delegate = runtime.DynWinRtDelegate.create(delegateIid, [Type.i32()], callbackForValue(box, sentinel)) + box.value = delegate.toValue() + return { owner: new WeakRef(delegate), sentinel: new WeakRef(sentinel), box } + } + const references = createDelegate() + assert.equal(await collect(references.owner), true) + assert.equal(runtime.tsfnTestRegisteredHandleCount(), 1) + const outputs = + mode === 'delegate-release' + ? method.invoke(references.box.value, [Value.i32(42)]) + : references.box.value.invokeDelegate(delegateIid, signature, [Value.i32(42)]) + assert.deepEqual(outputs, []) + assert.equal(references.box.value.isNull(), true) + assert.equal(await collect(references.sentinel), true, 'the invocation pin releases the final native reference') + assert.equal(runtime.tsfnTestRegisteredHandleCount(), 0) +} else if (mode === 'shutdown') { + const before = stats() + for (const terminate of [false, true]) { + const worker = new Worker(new URL('./winrt-implementation-worker.mjs', import.meta.url), { + workerData: { runtimePath, terminate }, + }) + const exited = once(worker, 'exit') + const [message] = await once(worker, 'message') + assert.equal(message, 'retained') + if (terminate) await worker.terminate() + await exited + const result = runtime.winrtImplementationTestInvokeRetained() + assert.notEqual(result.hresult, 0, 'a stale environment must never be invoked') + assert.equal(result.text ?? null, null) + runtime.winrtImplementationTestReleaseRetained(true) + } + assert.equal(stats().environmentDisconnects, before.environmentDisconnects + 2) + assert.equal(stats().finalizedCallbacks, before.finalizedCallbacks + 2) +} else if (mode === 'natural-exit') { + globalThis.retainedImplementation = Implementation.create([plan], callbackFor({ text: 'exit' })) +} else { + throw new Error(`Unknown child mode: ${mode}`) +} +console.log(`winrt-${mode}-ok`) diff --git a/bindings/js/__test__/winrt-implementation-worker.mjs b/bindings/js/__test__/winrt-implementation-worker.mjs new file mode 100644 index 00000000..692c0091 --- /dev/null +++ b/bindings/js/__test__/winrt-implementation-worker.mjs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { createRequire } from 'node:module' +import { parentPort, workerData } from 'node:worker_threads' + +const runtime = createRequire(import.meta.url)(workerData.runtimePath) +runtime.roInitialize(1) +const iid = runtime.WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3') +const plan = runtime.DynWinRtInterfacePlan.create( + 'Windows.Foundation.IStringable', + runtime.DynWinRtType.interface(iid), + [ + { + name: 'ToString', + vtableIndex: 6, + signature: new runtime.DynWinRtMethodSig().addOut(runtime.DynWinRtType.hstring()), + }, + ], +) +const owner = runtime.DynWinRtImplementation.create([plan], () => [runtime.DynWinRtValue.hstring('worker')]) +const value = owner.toValue() +runtime.winrtImplementationTestRetain(value) +value.release() +owner.release() +parentPort.postMessage('retained') +if (workerData.terminate) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 10_000) diff --git a/bindings/js/__test__/winrt-implementation.spec.ts b/bindings/js/__test__/winrt-implementation.spec.ts new file mode 100644 index 00000000..164a695e --- /dev/null +++ b/bindings/js/__test__/winrt-implementation.spec.ts @@ -0,0 +1,889 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import test from 'ava' +import { AsyncLocalStorage } from 'node:async_hooks' +import { spawnSync } from 'node:child_process' +import { createRequire } from 'node:module' +import { fileURLToPath } from 'node:url' + +import { + DynWinRtArray, + DynWinRtDelegate, + DynWinRtDelegateMethod, + DynWinRtImplementation, + DynWinRtInterfacePlan, + DynWinRtMethodSig, + DynWinRtStruct, + DynWinRtType, + DynWinRtValue, + WinGuid, + roInitialize, + type DynWinRtImplementationDescriptor, + type DynWinRtImplementationMethod, +} from '../dist/winrt.js' +import * as com from '../dist/com.js' + +roInitialize(1) + +const stringableIid = WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3') +const closableIid = WinGuid.parse('30d5a829-7fa4-4026-83bb-d75bae4ea99e') +const stringSig = new DynWinRtMethodSig().addOut(DynWinRtType.hstring()) +const voidSig = new DynWinRtMethodSig() +const stringMethods = [{ name: 'ToString', vtableIndex: 6, signature: stringSig }] +const stringType = DynWinRtType.registerInterface('Windows.Foundation.IStringable', stringableIid).addMethod( + 'ToString', + stringSig, +) +const closeType = DynWinRtType.registerInterface('Windows.Foundation.IClosable', closableIid).addMethod( + 'Close', + voidSig, +) +const stringPlan = DynWinRtInterfacePlan.create('Windows.Foundation.IStringable', stringType, stringMethods) +const closePlan = DynWinRtInterfacePlan.create('Windows.Foundation.IClosable', closeType, [ + { name: 'Close', vtableIndex: 6, signature: voidSig }, +]) +const toString = stringType.method(6) +const close = closeType.method(6) +const textResult = () => [DynWinRtValue.hstring('standalone')] + +function viewOf(owner: DynWinRtImplementation, iid = stringableIid) { + const identity = owner.toValue() + try { + return identity.cast(iid) + } finally { + identity.release() + } +} + +function fixture(iid: string, methods: DynWinRtImplementationMethod[], name = 'Tests.IWinRtFixture') { + let type = DynWinRtType.registerInterface(name, WinGuid.parse(iid)) + for (const method of methods) type = type.addMethod(method.name, method.signature) + return { type, plan: DynWinRtInterfacePlan.create(name, type, methods) } +} + +test('standalone interface plans and implementations are WinRT-root-only exports', (t) => { + t.is(typeof DynWinRtImplementation.create, 'function') + t.is(typeof DynWinRtInterfacePlan.create, 'function') + t.false('DynWinRtImplementation' in com) + t.false('DynWinRtInterfacePlan' in com) + t.false('DynWinRtDelegateMethod' in com) + const descriptor: DynWinRtImplementationDescriptor = { + plan: stringPlan, + dispatch: (_slot, _args) => textResult(), + } + const owner = DynWinRtImplementation.create([descriptor.plan], (_index, slot, args) => + descriptor.dispatch(slot, args), + ) + const value = viewOf(owner) + t.is(toString.getString(value), 'standalone') + owner.dispose() + value.release() +}) + +test('plans reject incomplete slots, wrong descriptor types, unsupported roots and nested arrays', (t) => { + for (const vtableIndex of [-1, 0, 3, 7, 6.5, NaN, Infinity, 2 ** 32]) { + t.throws(() => + DynWinRtInterfacePlan.create('Bad', stringType, [{ name: 'ToString', vtableIndex, signature: stringSig }]), + ) + } + t.throws(() => DynWinRtInterfacePlan.create('', stringType, stringMethods), { message: /name/i }) + t.throws(() => DynWinRtInterfacePlan.create('Bad', DynWinRtType.i32(), []), { message: /non-generic/i }) + t.throws(() => DynWinRtInterfacePlan.create('Bad', DynWinRtType.delegate(stringableIid), [])) + t.throws(() => + DynWinRtInterfacePlan.create('Bad', DynWinRtType.parameterized(stringableIid, [DynWinRtType.i32()]), []), + ) + t.throws( + () => + DynWinRtInterfacePlan.create('Bad', stringType, [ + { name: 'ToString', vtableIndex: 6, signature: DynWinRtType.i32() as unknown as DynWinRtMethodSig }, + ]), + { message: /DynWinRtMethodSig/i }, + ) + const nested = DynWinRtType.arrayType(DynWinRtType.arrayType(DynWinRtType.i32())) + t.throws( + () => + DynWinRtInterfacePlan.create('Bad', stringType, [ + { name: 'ToString', vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(nested) }, + ]), + { message: /nested|array/i }, + ) + t.throws(() => + DynWinRtInterfacePlan.create('Bad', stringType, [ + { name: 'ToString', vtableIndex: 6, signature: new DynWinRtMethodSig().addOutFill(DynWinRtType.i32()) }, + ]), + ) + t.throws(() => DynWinRtImplementation.create([], textResult), { message: /at least one/i }) + t.throws(() => DynWinRtImplementation.create([stringPlan, stringPlan], textResult), { message: /duplicate/i }) + t.throws(() => DynWinRtImplementation.create([stringType as unknown as DynWinRtInterfacePlan], textResult)) + t.throws(() => DynWinRtImplementation.create([stringPlan], textResult, 'invalid\0name')) +}) + +test('required interfaces are independent views and are validated together', (t) => { + const required = DynWinRtInterfacePlan.create('RequiredStringable', stringType, stringMethods, [closableIid]) + t.throws(() => DynWinRtImplementation.create([required], textResult), { message: /requires.*separate/i }) + const duplicate = DynWinRtInterfacePlan.create('RequiredStringable', stringType, stringMethods, [ + closableIid, + closableIid, + ]) + t.throws(() => DynWinRtImplementation.create([duplicate, closePlan], textResult), { message: /duplicate/i }) + let closes = 0 + const owner = DynWinRtImplementation.create([required, closePlan], (index, slot, args) => { + t.is(slot, 6) + t.deepEqual(args, []) + if (index === 0) return textResult() + t.is(index, 1) + closes++ + return [] + }) + const first = viewOf(owner) + const second = viewOf(owner) + const closeView = viewOf(owner, closableIid) + t.is(toString.getString(first), 'standalone') + t.deepEqual(close.invokeAll(closeView, []), []) + closeView.release() + t.is(closes, 1) + first.release() + t.is(toString.getString(second), 'standalone') + owner.dispose() + t.throws(() => toString.getString(second)) + second.release() +}) + +test('plans snapshot descriptors rather than observing later JS mutation', (t) => { + const methods = [{ name: 'ToString', vtableIndex: 6, signature: stringSig }] + const plan = DynWinRtInterfacePlan.create('ImmutableStringable', stringType, methods) + methods[0].signature = voidSig + methods[0].vtableIndex = 99 + methods.length = 0 + const owner = DynWinRtImplementation.create([plan], textResult) + const value = viewOf(owner) + t.is(toString.invoke(value, []).toString(), 'standalone') + value.release() + owner.dispose() +}) + +test('exceptions and invalid outputs fail synchronously and leave no pending JS exception', (t) => { + let fail = true + const owner = DynWinRtImplementation.create([stringPlan], () => { + if (fail) throw new Error('reverse callback sentinel') + return textResult() + }) + const value = viewOf(owner) + t.throws(() => toString.getString(value)) + t.regex(owner.takeError()!, /reverse callback sentinel/) + t.is(owner.takeError(), null) + fail = false + t.is(toString.getString(value), 'standalone') + owner.dispose() + value.release() + + const invalid: Array<() => unknown> = [ + () => undefined, + () => null, + () => [42], + () => [DynWinRtType.i32()], + () => [], + () => [DynWinRtValue.i32(42)], + () => Promise.resolve(textResult()), + // oxlint-disable-next-line unicorn/no-thenable -- Deliberately rejected callback result. + () => ({ then() {} }), + () => + Object.defineProperty([], '0', { + get() { + throw new Error('output getter sentinel') + }, + }), + () => + // oxlint-disable-next-line unicorn/no-thenable -- A throwing then getter must not leak an exception. + Object.defineProperty([], 'then', { + get() { + throw new Error('then getter sentinel') + }, + }), + ] + for (const callback of invalid) { + const bad = DynWinRtImplementation.create([stringPlan], callback as () => DynWinRtValue[]) + const view = viewOf(bad) + t.throws(() => toString.getString(view)) + t.truthy(bad.takeError()) + t.is(bad.takeError(), null) + bad.dispose() + view.release() + } +}) + +test('async and generator dispatchers are rejected before publication', (t) => { + t.throws( + () => { + // @ts-expect-error Async dispatchers are deliberately not part of the contract. + return DynWinRtImplementation.create([stringPlan], async () => textResult()) + }, + { message: /synchronous/ }, + ) + function* generator() { + yield textResult() + } + t.throws(() => DynWinRtImplementation.create([stringPlan], generator as unknown as () => DynWinRtValue[]), { + message: /synchronous/, + }) +}) + +test('scalar and enum ABI aliases survive synchronous callbacks without JS numeric coercion', (t) => { + const enumType = DynWinRtType.enumType('Tests.NodeReverseEnum', ['Answer'], [42]) + const cases: Array<{ + type: DynWinRtType + value: DynWinRtValue + read(value: DynWinRtValue): unknown + expected: unknown + }> = [ + { type: DynWinRtType.boolType(), value: DynWinRtValue.boolValue(true), read: (v) => v.toBool(), expected: true }, + { type: DynWinRtType.i8Type(), value: DynWinRtValue.i8Value(-12), read: (v) => v.toNumber(), expected: -12 }, + { type: DynWinRtType.u8(), value: DynWinRtValue.u8Value(250), read: (v) => v.toNumber(), expected: 250 }, + { type: DynWinRtType.i16(), value: DynWinRtValue.i16(-1234), read: (v) => v.toNumber(), expected: -1234 }, + { type: DynWinRtType.u16(), value: DynWinRtValue.u16(65535), read: (v) => v.toNumber(), expected: 65535 }, + { type: DynWinRtType.char16(), value: DynWinRtValue.u16(0xd800), read: (v) => v.toNumber(), expected: 0xd800 }, + { + type: DynWinRtType.i32(), + value: DynWinRtValue.i32(-2147483648), + read: (v) => v.toNumber(), + expected: -2147483648, + }, + { type: DynWinRtType.u32(), value: DynWinRtValue.u32(4294967295), read: (v) => v.toNumber(), expected: 4294967295 }, + { + type: DynWinRtType.hresult(), + value: DynWinRtValue.i32(0x80004005 | 0), + read: (v) => v.toNumber(), + expected: 0x80004005 | 0, + }, + { + type: DynWinRtType.i64(), + value: DynWinRtValue.i64(-9223372036854775808n), + read: (v) => v.toI64Bigint(), + expected: -9223372036854775808n, + }, + { + type: DynWinRtType.u64(), + value: DynWinRtValue.u64(18446744073709551615n), + read: (v) => v.toU64Bigint(), + expected: 18446744073709551615n, + }, + { 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 }, + ] + const methods = cases.map(({ type }, index) => ({ + name: `Echo${index}`, + vtableIndex: index + 6, + signature: new DynWinRtMethodSig().addIn(type).addOut(type), + })) + const { type, plan } = fixture('2799ac23-bcd8-4086-b6f0-1f33b3af84be', methods, 'Tests.IWinRtScalars') + const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => { + 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) + }) + owner.dispose() + view.release() +}) + +test('recursive structs and arrays retain their HSTRING and interface fields', (t) => { + const innerType = DynWinRtType.structType('Tests.NodeReverseInner', [ + DynWinRtType.hstring(), + DynWinRtType.interface(stringableIid), + ]) + const outerType = DynWinRtType.structType('Tests.NodeReverseOuter', [innerType, DynWinRtType.i32()]) + const arrayType = DynWinRtType.arrayType(outerType) + const { type, plan } = fixture( + '6968bfa2-e195-4d07-9726-3442ee1d1133', + [{ name: 'Copy', vtableIndex: 6, signature: new DynWinRtMethodSig().addIn(arrayType).addOut(arrayType) }], + 'Tests.IWinRtStructArrays', + ) + const referenced = DynWinRtImplementation.create([stringPlan], textResult) + const object = viewOf(referenced) + const inner = DynWinRtStruct.create(innerType) + inner.setHstring(0, 'nested string') + inner.setObject(1, object) + const outer = DynWinRtStruct.create(outerType) + outer.setStruct(0, inner) + outer.setI32(1, 19) + const owner = DynWinRtImplementation.create([plan], (_index, _slot, args) => [args[0]]) + const view = viewOf(owner, type.iid()) + const input = DynWinRtArray.fromObjectValues([outer.toValue()], outerType).toValue() + const result = type.method(6).invoke(view, [input]) + input.release() + const copied = result.asArray().get(0).asStruct() + const copiedInner = copied.getStruct(0) + t.is(copied.getI32(1), 19) + t.is(copiedInner.getHstring(0), 'nested string') + const copiedObject = copiedInner.getObject(1) + t.is(toString.getString(copiedObject), 'standalone') + copiedObject.release() + result.release() + owner.dispose() + view.release() + referenced.dispose() + object.release() +}) + +test('managed WinRT reference categories are nullable and closed generic values stay owned', (t) => { + const referenceType = DynWinRtType.parameterized(WinGuid.parse('61c17706-2d65-11e0-9ae8-d48564015472'), [ + DynWinRtType.i32(), + ]) + const types = [ + DynWinRtType.object(), + DynWinRtType.interface(stringableIid), + DynWinRtType.runtimeClass('Tests.NodeReverseRuntimeClass', stringType), + DynWinRtType.delegate(WinGuid.parse('de77ae11-536d-4f38-9354-22f9414a82ec')), + DynWinRtType.iAsyncAction(), + DynWinRtType.iAsyncOperation(DynWinRtType.i32()), + DynWinRtType.iAsyncActionWithProgress(DynWinRtType.u32()), + DynWinRtType.iAsyncOperationWithProgress(DynWinRtType.i32(), DynWinRtType.u32()), + referenceType, + ] + const { type, plan } = fixture( + 'f8e75843-5f9b-4af9-b3ea-d123e9c841a0', + types.map((item, index) => ({ + name: `Echo${index}`, + vtableIndex: index + 6, + signature: new DynWinRtMethodSig().addIn(item).addOut(item), + })), + 'Tests.IWinRtReferences', + ) + const owner = DynWinRtImplementation.create([plan], (_index, _slot, args) => [args[0]]) + const view = viewOf(owner, type.iid()) + types.forEach((_item, index) => { + t.true( + type + .method(index + 6) + .invoke(view, [DynWinRtValue.nullValue()]) + .isNull(), + ) + }) + const boxed = DynWinRtValue.boxReference(DynWinRtValue.i32(123), DynWinRtType.i32()) + const result = type.method(types.length + 5).invoke(view, [boxed]) + boxed.release() + const getter = DynWinRtType.registerInterface('Tests.IReferenceI32', referenceType.iid()) + .addMethod('get_Value', new DynWinRtMethodSig().addOut(DynWinRtType.i32())) + .method(6) + const reference = result.cast(referenceType.iid()) + result.release() + t.is(getter.getI32(reference), 123) + reference.release() + owner.dispose() + view.release() +}) + +test('synchronous dispatch preserves its Node async context', (t) => { + const storage = new AsyncLocalStorage() + const owner = storage.run('creation context', () => + DynWinRtImplementation.create([stringPlan], () => [DynWinRtValue.hstring(storage.getStore() ?? 'missing')]), + ) + const value = viewOf(owner) + t.is( + storage.run('caller context', () => toString.getString(value)), + 'creation context', + ) + value.release() + owner.dispose() +}) + +test('metadata-described delegate callers use slot 3 and reject invalid targets and arguments', (t) => { + const iid = WinGuid.parse('74ca6c7f-502c-4b4b-bb77-7c2025a73fc8') + const signature = new DynWinRtMethodSig().addIn(DynWinRtType.i32()) + const method = DynWinRtDelegateMethod.create(iid, signature) + const received: number[] = [] + const delegate = DynWinRtDelegate.create(iid, [DynWinRtType.i32()], (value) => { + received.push(value.toNumber()) + }) + const value = delegate.toValue() + t.deepEqual(method.invoke(value, [DynWinRtValue.i32(41)]), []) + t.deepEqual(received, [41]) + t.throws(() => method.invoke(value, []), { message: /count/i }) + t.throws(() => method.invoke(value, [DynWinRtValue.hstring('wrong')])) + t.throws(() => method.invoke(value, [DynWinRtType.i32() as unknown as DynWinRtValue])) + t.throws(() => method.invoke(DynWinRtValue.nullValue(), [DynWinRtValue.i32(1)])) + t.throws(() => DynWinRtDelegateMethod.create(WinGuid.parse('00000000-0000-0000-c000-000000000046'), signature), { + message: /infrastructure/, + }) + t.throws(() => DynWinRtDelegateMethod.create(iid, DynWinRtType.i32() as unknown as DynWinRtMethodSig)) + const unsupported = DynWinRtDelegateMethod.create(WinGuid.parse('22bf990d-2be0-4239-8c44-c3959b1b6011'), signature) + t.throws(() => unsupported.invoke(value, [DynWinRtValue.i32(1)]), { message: /QueryInterface/ }) + t.deepEqual(received, [41]) + t.deepEqual(method.invoke(value, [DynWinRtValue.i32(42)]), []) + value.release() + t.throws(() => method.invoke(value, [DynWinRtValue.i32(43)]), { message: /live managed Object/ }) +}) + +test('delegate owner release is idempotent and preserves independently retained native values', (t) => { + const iid = WinGuid.parse('312a69d6-444a-4d3a-ab56-f7e85b23e654') + const signature = new DynWinRtMethodSig().addIn(DynWinRtType.i32()) + let received = 0 + const owner = DynWinRtDelegate.create(iid, [DynWinRtType.i32()], (value) => { + received = value.toNumber() + }) + const retained = owner.toValue() + owner.release() + owner.release() + t.throws(() => owner.toValue(), { message: /released/ }) + t.deepEqual(retained.invokeDelegate(iid, signature, [DynWinRtValue.i32(42)]), []) + t.is(received, 42) + retained.release() +}) + +for (const mode of ['remove', 'once', 'add-failure']) { + test.serial(`generated event ownership exits naturally after ${mode}`, (t) => { + const child = spawnSync(process.execPath, [ + fileURLToPath(new URL('./winrt-event-lifetime-child.mjs', import.meta.url)), mode, + ], { encoding: 'utf8', timeout: 10_000, windowsHide: true }) + t.is(child.status, 0, `${child.error ?? ''}\n${child.stdout}\n${child.stderr}`) + t.regex(child.stdout, new RegExp(`generated-event-lifetime-ok:${mode}`)) + }) +} + +for (const api of ['prepared', 'value'] as const) { + test(`delegate ${api} callers pin managed values through nested invocation and reentrant release`, (t) => { + const iid = WinGuid.parse('00c1b0c2-2f1c-4e9f-a167-373bc6149513') + const signature = new DynWinRtMethodSig().addIn(DynWinRtType.i32()) + const method = DynWinRtDelegateMethod.create(iid, signature) + const invoke = (value: DynWinRtValue, args: DynWinRtValue[]) => + api === 'prepared' ? method.invoke(value, args) : value.invokeDelegate(iid, signature, args) + let value: DynWinRtValue + const received: number[] = [] + const delegate = DynWinRtDelegate.create(iid, [DynWinRtType.i32()], (arg) => { + const number = arg.toNumber() + received.push(number) + if (number === 1) { + t.deepEqual(invoke(value, [DynWinRtValue.i32(2)]), []) + } else { + value.release() + } + }) + value = delegate.toValue() + t.deepEqual(invoke(value, [DynWinRtValue.i32(1)]), []) + t.deepEqual(received, [1, 2]) + t.true(value.isNull()) + t.throws(() => invoke(value, [DynWinRtValue.i32(3)]), { message: /live managed Object/ }) + }) +} + +test('release, disconnect and dispose have distinct idempotent lifetime semantics', (t) => { + const owner = DynWinRtImplementation.create([stringPlan], textResult) + const value = viewOf(owner) + owner.release() + owner.release() + t.false(owner.isClosed) + t.throws(() => owner.toValue(), { message: /released/i }) + t.is(toString.getString(value), 'standalone') + owner.disconnect() + t.true(owner.isClosed) + t.throws(() => toString.getString(value)) + owner.dispose() + owner.dispose() + value.release() + + const unique = DynWinRtImplementation.create([stringPlan], textResult) + unique.release() + t.true(unique.isClosed) +}) + +test('reentrant calls, owner release and disposal do not deadlock or destroy active callback roots', (t) => { + let depth = 0 + let view: DynWinRtValue + const owner = DynWinRtImplementation.create([stringPlan], () => { + if (depth++ === 0) { + const inner = toString.getString(view) + owner.dispose() + return [DynWinRtValue.hstring(`outer:${inner}`)] + } + owner.release() + return [DynWinRtValue.hstring('inner')] + }) + view = viewOf(owner) + t.is(toString.getString(view), 'outer:inner') + t.true(owner.isClosed) + t.throws(() => toString.getString(view)) + view.release() +}) + +test('custom property, event, GUID, struct and multiple-output signatures cross actual vtables', (t) => { + const tokenType = DynWinRtType.structType('Windows.Foundation.EventRegistrationToken', [DynWinRtType.i64()]) + const eventIid = WinGuid.parse('ac0a9714-89f6-4e72-9c44-ac29b89b671c') + const pointType = DynWinRtType.structType('Tests.NodeReversePoint', [DynWinRtType.f64(), DynWinRtType.f64()]) + const methods = [ + { name: 'get_Value', vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(DynWinRtType.i32()) }, + { name: 'put_Value', vtableIndex: 7, signature: new DynWinRtMethodSig().addIn(DynWinRtType.i32()) }, + { + name: 'add_Changed', + vtableIndex: 8, + signature: new DynWinRtMethodSig().addIn(DynWinRtType.delegate(eventIid)).addOut(tokenType), + }, + { name: 'remove_Changed', vtableIndex: 9, signature: new DynWinRtMethodSig().addIn(tokenType) }, + { + name: 'Transform', + vtableIndex: 10, + signature: new DynWinRtMethodSig() + .addIn(pointType) + .addIn(DynWinRtType.guidType()) + .addOut(pointType) + .addOut(DynWinRtType.guidType()) + .addOut(DynWinRtType.boolType()), + }, + ] + const { type, plan } = fixture('281144a6-d56b-4cbf-abcc-87bbd1fcf5e3', methods) + const eventSignature = new DynWinRtMethodSig().addIn(DynWinRtType.i32()) + let current = 5 + let handler: DynWinRtValue | undefined + const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => { + if (slot === 6) return [DynWinRtValue.i32(current)] + if (slot === 7) { + current = args[0].toNumber() + if (handler) handler.invokeDelegate(eventIid, eventSignature, [DynWinRtValue.i32(current)]) + return [] + } + if (slot === 8) { + handler = args[0].cast(eventIid) + const token = DynWinRtStruct.create(tokenType) + token.setI64(0, 123n) + return [token.toValue()] + } + if (slot === 9) { + t.is(args[0].asStruct().getI64(0), 123n) + handler!.release() + handler = undefined + return [] + } + t.is(slot, 10) + const point = args[0].asStruct() + const result = DynWinRtStruct.create(pointType) + result.setF64(0, point.getF64(0) + 1) + result.setF64(1, point.getF64(1) + 2) + return [result.toValue(), args[1], DynWinRtValue.boolValue(true)] + }) + const value = viewOf(owner, type.iid()) + type.method(7).setI32(value, 17) + t.is(type.method(6).getI32(value), 17) + const changes: number[] = [] + const delegate = DynWinRtDelegate.create(eventIid, [DynWinRtType.i32()], (value) => { + changes.push(value.toNumber()) + }) + const delegateValue = delegate.toValue() + const token = type.method(8).invoke(value, [delegateValue]) + t.truthy(handler) + type.method(7).setI32(value, 18) + t.deepEqual(changes, [18]) + type.method(9).invoke(value, [token]) + t.is(handler, undefined) + type.method(7).setI32(value, 19) + t.deepEqual(changes, [18]) + const point = DynWinRtStruct.create(pointType) + point.setF64(0, 3) + point.setF64(1, 9) + const outputs = type.method(10).invokeAll(value, [point.toValue(), DynWinRtValue.guid(stringableIid)]) + t.is(outputs[0].asStruct().getF64(0), 4) + t.is(outputs[0].asStruct().getF64(1), 11) + t.is(outputs[1].toGuid().toString(), stringableIid.toString()) + t.true(outputs[2].toBool()) + delegateValue.release() + value.release() + owner.dispose() +}) + +test('pass, receive and fill arrays preserve argument order, capacities and reference elements', (t) => { + const i32Array = DynWinRtType.arrayType(DynWinRtType.i32()) + const stringArray = DynWinRtType.arrayType(DynWinRtType.hstring()) + const objectArray = DynWinRtType.arrayType(DynWinRtType.interface(stringableIid)) + const methods = [ + { name: 'Pass', vtableIndex: 6, signature: new DynWinRtMethodSig().addIn(i32Array).addOut(i32Array) }, + { name: 'Receive', vtableIndex: 7, signature: new DynWinRtMethodSig().addOut(stringArray) }, + { + name: 'Fill', + vtableIndex: 8, + signature: new DynWinRtMethodSig() + .addIn(DynWinRtType.i32()) + .addOutFill(i32Array) + .addIn(DynWinRtType.i32()) + .addOut(DynWinRtType.i32()), + }, + { name: 'References', vtableIndex: 9, signature: new DynWinRtMethodSig().addIn(objectArray).addOut(objectArray) }, + ] + const { type, plan } = fixture('92735c9b-4c5b-425a-9ff3-2b01e9927556', methods, 'Tests.IWinRtArrays') + let invalidFill = false + const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => { + if (slot === 6) + return [ + DynWinRtArray.fromI32Values( + args[0] + .asArray() + .toI32Vec() + .map((v) => v * 2), + ).toValue(), + ] + if (slot === 7) return [DynWinRtArray.fromStringValues(['', 'native', '🌍']).toValue()] + if (slot === 9) return [args[0]] + t.deepEqual( + args.map((arg) => arg.toNumber()), + [10, 3, 20], + ) + return [DynWinRtArray.fromI32Values(invalidFill ? [7] : [7, 8, 9]).toValue(), DynWinRtValue.i32(30)] + }) + const value = viewOf(owner, type.iid()) + t.deepEqual( + type + .method(6) + .invoke(value, [DynWinRtArray.fromI32Values([1, -2]).toValue()]) + .asArray() + .toI32Vec(), + [2, -4], + ) + t.deepEqual( + type + .method(6) + .invoke(value, [DynWinRtArray.fromI32Values([]).toValue()]) + .asArray() + .toI32Vec(), + [], + ) + t.deepEqual(type.method(7).invoke(value, []).asArray().toStringVec(), ['', 'native', '🌍']) + const fill = DynWinRtArray.fromI32Values([0, 0, 0]).toValue() + const fillArgs = [DynWinRtValue.i32(10), fill, DynWinRtValue.i32(20)] + const outputs = type.method(8).invokeAll(value, fillArgs) + t.deepEqual(outputs[0].asArray().toI32Vec(), [7, 8, 9]) + t.is(outputs[1].toNumber(), 30) + invalidFill = true + t.throws(() => type.method(8).invokeAll(value, fillArgs)) + t.regex(owner.takeError()!, /capacity|length|fill/i) + const referenceOwner = DynWinRtImplementation.create([stringPlan], textResult) + const reference = viewOf(referenceOwner) + const inputs = DynWinRtArray.fromObjectValues( + [reference, DynWinRtValue.nullValue()], + DynWinRtType.interface(stringableIid), + ) + const references = type.method(9).invoke(value, [inputs.toValue()]).asArray().toValues() + t.is(toString.getString(references[0]), 'standalone') + t.true(references[1].isNull()) + referenceOwner.dispose() + reference.release() + references.forEach((item) => item.release()) + owner.dispose() + value.release() +}) + +test('semantic HRESULT values and arrays round-trip through pass, receive and fill contracts', (t) => { + const codes = [0, 1, 0x80004005 | 0, -2147483648, 2147483647] + const elementType = DynWinRtType.hresult() + const arrayType = DynWinRtType.arrayType(elementType) + const { type, plan } = fixture( + '9dd1d5b0-e3f4-4c79-a9c5-3f182d570d7b', + [ + { name: 'Pass', vtableIndex: 6, signature: new DynWinRtMethodSig().addIn(arrayType).addOut(arrayType) }, + { name: 'Receive', vtableIndex: 7, signature: new DynWinRtMethodSig().addOut(arrayType) }, + { name: 'Fill', vtableIndex: 8, signature: new DynWinRtMethodSig().addOutFill(arrayType) }, + { name: 'Echo', vtableIndex: 9, signature: new DynWinRtMethodSig().addIn(elementType).addOut(elementType) }, + { name: 'Consume', vtableIndex: 10, signature: new DynWinRtMethodSig().addIn(elementType) }, + ], + 'Tests.IWinRtHResultArrays', + ) + const consumed: number[] = [] + const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => { + if (slot === 10) { + consumed.push(args[0].toNumber()) + return [] + } + if (slot === 6 || slot === 9) return [args[0]] + if (slot === 8) t.is(args[0].toNumber(), codes.length) + return [DynWinRtArray.fromHresultValues(codes).toValue()] + }) + const view = viewOf(owner, type.iid()) + const input = DynWinRtArray.fromHresultValues(codes).toValue() + t.deepEqual(type.method(6).invoke(view, [input]).asArray().toI32Vec(), codes) + const genericInput = DynWinRtArray.fromObjectValues( + codes.map((code) => DynWinRtValue.fromHResult(code)), + elementType, + ).toValue() + t.deepEqual(type.method(6).invoke(view, [genericInput]).asArray().toI32Vec(), codes) + t.deepEqual(type.method(7).invoke(view, []).asArray().toI32Vec(), codes) + const fill = DynWinRtArray.fromHresultValues(codes.map(() => 0)).toValue() + t.deepEqual(type.method(8).invoke(view, [fill]).asArray().toI32Vec(), codes) + for (const code of codes) { + t.is( + type + .method(9) + .invoke(view, [DynWinRtValue.hresult(code)]) + .toNumber(), + code, + ) + t.deepEqual(type.method(10).invokeAll(view, [DynWinRtValue.fromHResult(code)]), []) + } + t.deepEqual(consumed, codes) + t.deepEqual(DynWinRtArray.fromHresultValues([]).toI32Vec(), []) + for (const invalid of [NaN, Infinity, 0.5, -2147483649, 2147483648]) { + t.throws(() => DynWinRtValue.hresult(invalid)) + t.throws(() => DynWinRtValue.fromHResult(invalid)) + t.throws(() => DynWinRtArray.fromHresultValues([0, invalid])) + } + input.release() + genericInput.release() + fill.release() + view.release() + owner.dispose() +}) + +test('non-null async elements stay awaitable after pass, receive and fill array calls', async (t) => { + const activationIid = WinGuid.parse('00000035-0000-0000-c000-000000000046') + const outputIid = WinGuid.parse('905a0fe6-bc53-11df-8c49-001e4fc686da') + const asyncType = DynWinRtType.iAsyncOperation(DynWinRtType.boolType()) + const arrayType = DynWinRtType.arrayType(asyncType) + const activation = DynWinRtType.registerInterface('IActivationFactory', activationIid) + .addMethod('ActivateInstance', new DynWinRtMethodSig().addOut(DynWinRtType.object())) + .method(6) + const outputType = DynWinRtType.registerInterface('Windows.Storage.Streams.IOutputStream', outputIid) + .addMethod( + 'WriteAsync', + new DynWinRtMethodSig() + .addIn(DynWinRtType.interface(WinGuid.parse('905a0fe0-bc53-11df-8c49-001e4fc686da'))) + .addOut(DynWinRtType.iAsyncOperationWithProgress(DynWinRtType.u32(), DynWinRtType.u32())), + ) + .addMethod('FlushAsync', new DynWinRtMethodSig().addOut(asyncType)) + const { type, plan } = fixture( + 'ebdb96e6-790a-4b55-927c-eb6e570471b5', + [ + { name: 'Pass', vtableIndex: 6, signature: new DynWinRtMethodSig().addIn(arrayType).addOut(arrayType) }, + { name: 'Receive', vtableIndex: 7, signature: new DynWinRtMethodSig().addOut(arrayType) }, + { name: 'Fill', vtableIndex: 8, signature: new DynWinRtMethodSig().addOutFill(arrayType) }, + ], + 'Tests.IWinRtAsyncArrays', + ) + const rawFactory = DynWinRtValue.activationFactory('Windows.Storage.Streams.InMemoryRandomAccessStream') + let factory: DynWinRtValue + try { + factory = rawFactory.cast(activationIid) + } finally { + rawFactory.release() + } + let stream: DynWinRtValue + try { + stream = activation.invoke(factory, []) + } finally { + factory.release() + } + let output: DynWinRtValue + try { + output = stream.cast(outputIid) + } finally { + stream.release() + } + const makeArray = () => { + const operation = outputType.method(7).invoke(output, []) + try { + return DynWinRtArray.fromObjectValues([operation], asyncType).toValue() + } finally { + operation.release() + } + } + const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => { + if (slot === 6) return [args[0]] + if (slot === 8) t.is(args[0].toNumber(), 1) + return [makeArray()] + }) + const view = viewOf(owner, type.iid()) + try { + for (const slot of [6, 7, 8]) { + const input = + slot === 6 + ? makeArray() + : slot === 8 + ? DynWinRtArray.fromObjectValues([DynWinRtValue.nullValue()], asyncType).toValue() + : undefined + let result: DynWinRtValue + try { + result = type.method(slot).invoke(view, input ? [input] : []) + } finally { + input?.release() + } + const element = result.asArray().get(0) + result.release() + try { + t.true((await element.toPromise()).toBool()) + } finally { + element.release() + } + } + } finally { + view.release() + owner.dispose() + const closable = output.cast(closableIid) + try { + close.invokeAll(closable, []) + } finally { + closable.release() + output.release() + } + } +}) + +interface NativeHooks { + winrtImplementationTestBackgroundInstance(): DynWinRtValue + winrtImplementationTestBackgroundProgress(value: DynWinRtValue): number +} +const hooks = createRequire(import.meta.url)('../dist/index.js') as Partial + +if (!hooks.winrtImplementationTestBackgroundInstance) { + test.skip('native retention and SDK fixtures require the test-hooks Cargo feature', () => {}) +} else { + test('IBackgroundTask receives and can retain a complete native IBackgroundTaskInstance fixture', (t) => { + const taskIid = WinGuid.parse('7d13d534-fd12-43ce-8c22-ea1ff13c06df') + const instanceIid = WinGuid.parse('865bda7a-21d8-4573-8f32-928a1b0641f6') + const signature = new DynWinRtMethodSig().addIn(DynWinRtType.interface(instanceIid)) + const taskType = DynWinRtType.registerInterface( + 'Windows.ApplicationModel.Background.IBackgroundTask', + taskIid, + ).addMethod('Run', signature) + const plan = DynWinRtInterfacePlan.create('Windows.ApplicationModel.Background.IBackgroundTask', taskType, [ + { name: 'Run', vtableIndex: 6, signature }, + ]) + let retained: DynWinRtValue | undefined + const owner = DynWinRtImplementation.create([plan], (_index, slot, args) => { + t.is(slot, 6) + retained = args[0] + t.is(hooks.winrtImplementationTestBackgroundProgress!(retained), 42) + return [] + }) + const value = viewOf(owner, taskIid) + const instance = hooks.winrtImplementationTestBackgroundInstance!() + t.deepEqual(taskType.method(6).invokeAll(value, [instance]), []) + instance.release() + t.is(hooks.winrtImplementationTestBackgroundProgress!(retained!), 42) + retained!.release() + owner.dispose() + value.release() + }) + + for (const mode of [ + 'retention', + 'cycle', + 'reentrant-release', + 'delegate-release', + 'delegate-value-release', + 'shutdown', + 'natural-exit', + ]) { + test.serial(`native callback lifecycle: ${mode}`, (t) => { + const child = spawnSync( + process.execPath, + ['--expose-gc', fileURLToPath(new URL('./winrt-implementation-child.mjs', import.meta.url)), mode], + { + env: { ...process.env, DYNWINRT_TEST_RUNTIME: fileURLToPath(new URL('../dist/index.js', import.meta.url)) }, + encoding: 'utf8', + timeout: 20_000, + windowsHide: true, + }, + ) + t.is(child.status, 0, `${child.error ?? ''}\n${child.stdout}\n${child.stderr}`) + t.regex(child.stdout, new RegExp(`winrt-${mode}-ok`)) + }) + } +} diff --git a/bindings/js/package.json b/bindings/js/package.json index ec793dfd..f48e7e1b 100644 --- a/bindings/js/package.json +++ b/bindings/js/package.json @@ -92,8 +92,9 @@ "lint": "oxlint", "test": "npm run test:types && ava", "test:generated-unsafe": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/generated-unsafe-companion.e2e.ts", + "test:winrt-implementation": "npm run build:test-hooks && npm run build:entrypoints && ava __test__/winrt-implementation.spec.ts", "test:types": "npm run test:types:index && npm run test:types:raw", - "test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts", + "test:types:index": "tsc --noEmit --strict --target ESNext --module NodeNext --moduleResolution NodeNext __test__/index.spec.ts __test__/winrt-implementation.spec.ts", "test:types:raw": "tsc --noEmit --project __test__/types/tsconfig.json", "test:tsfn": "npm run build:test-hooks && ava __test__/tsfn.spec.ts", "version": "napi version" diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index b73dedeb..68c15d7c 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -207,10 +207,16 @@ const rawComDeclarations = [ '}', ] -writeFacade( - 'winrt', - nativeExports.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom'), +const winrtExports = nativeExports.filter( + (name) => !name.startsWith('DynCom') && name !== 'initializeCom', ) +writeFacade('winrt', winrtExports, [...winrtExports, 'DynWinRtImplementationMethod'], [], [ + '/** A generated interface plan and its synchronous, metadata-ordered dispatcher. */', + 'export interface DynWinRtImplementationDescriptor {', + " readonly plan: import('./index.js').DynWinRtInterfacePlan", + " readonly dispatch: (vtableIndex: number, args: import('./index.js').DynWinRtValue[]) => import('./index.js').DynWinRtValue[]", + '}', +]) writeFacade( 'com', nativeExports.filter((name) => comExports.has(name)), diff --git a/bindings/js/src/lib.rs b/bindings/js/src/lib.rs index e502de76..2229b08f 100644 --- a/bindings/js/src/lib.rs +++ b/bindings/js/src/lib.rs @@ -33,8 +33,16 @@ mod async_promise; mod generated_unsafe_test_hooks; mod managed_tsfn; mod scheduled_start; +mod winrt_delegate_method; +pub use winrt_delegate_method::DynWinRtDelegateMethod; +mod winrt_implementation; +pub use winrt_implementation::{ + DynWinRtImplementation, DynWinRtImplementationMethod, DynWinRtInterfacePlan, +}; #[cfg(feature = "test-hooks")] mod tsfn_test_hooks; +#[cfg(feature = "test-hooks")] +mod winrt_implementation_test_hooks; /// Shared MetadataTable — created once, used everywhere. static TABLE: std::sync::LazyLock> = @@ -1417,6 +1425,18 @@ impl DynWinRTValue { pub fn i32(value: i32) -> DynWinRTValue { DynWinRTValue::new(dynwinrt::WinRTValue::I32(value)) } + /// Create a semantic HRESULT value from a signed 32-bit status code. + #[napi] + pub fn hresult(value: f64) -> napi::Result { + Ok(DynWinRTValue::new(dynwinrt::WinRTValue::HResult( + windows::core::HRESULT(js_i32(value, "hresult")?), + ))) + } + /// Alias for hresult(), preserving the exact native HRESULT value type. + #[napi(js_name = "fromHResult")] + pub fn from_hresult(value: f64) -> napi::Result { + Self::hresult(value) + } #[napi] pub fn u32(value: u32) -> DynWinRTValue { DynWinRTValue::new(dynwinrt::WinRTValue::U32(value)) @@ -1658,6 +1678,22 @@ impl DynWinRTValue { Ok(result) } + /// Invoke a metadata-described WinRT delegate at IUnknown slot 3. + /// Returns every output in signature order ([] for void), retaining the target + /// and arguments across native calls. FillArray inputs require typed Array + /// storage, just like outbound invokeAll; they are not U32 capacities. + #[napi(strict)] + pub fn invoke_delegate( + &self, + #[napi(ts_arg_type = "WinGuid")] iid: Unknown<'_>, + #[napi(ts_arg_type = "DynWinRtMethodSig")] signature: Unknown<'_>, + #[napi(ts_arg_type = "DynWinRtValue[]")] args: Vec>, + ) -> napi::Result> { + self.ensure_existing_com_apartment()?; + let target = self.0.clone(); + winrt_delegate_method::invoke_delegate_value(target, iid, signature, args) + } + #[napi] pub fn to_number(&self) -> napi::Result { Ok(match &self.0 { @@ -2068,6 +2104,22 @@ impl DynWinRTArray { DynWinRTArray(dynwinrt::ArrayData::from_values(TABLE.i32_type(), &wvals)) } + /// Build an array whose native element type is HRESULT, not I32. + #[napi] + pub fn from_hresult_values(values: Vec) -> napi::Result { + let values = values + .into_iter() + .map(|value| { + js_i32(value, "fromHresultValues") + .map(|value| dynwinrt::WinRTValue::HResult(windows::core::HRESULT(value))) + }) + .collect::>>()?; + Ok(DynWinRTArray(dynwinrt::ArrayData::from_values( + TABLE.hresult(), + &values, + ))) + } + #[napi] pub fn from_u32_values(values: Vec) -> DynWinRTArray { let wvals: Vec = @@ -3107,10 +3159,23 @@ impl DynWinRtDelegate { Ok(DynWinRtDelegate(value)) } - /// Get the delegate as a DynWinRtValue for passing to WinRT methods. + /// Drop this owner's native reference without disconnecting native holders. + /// Event registration code should release both this owner and its temporary + /// toValue() result after the native event source has retained the delegate. #[napi] - pub fn to_value(&self) -> DynWinRTValue { - DynWinRTValue::new(self.0.clone()) + pub fn release(&mut self) { + self.0 = dynwinrt::WinRTValue::Null; + } + + /// Get an independently owned value for passing the delegate to WinRT. + #[napi] + pub fn to_value(&self) -> napi::Result { + if matches!(self.0, dynwinrt::WinRTValue::Null) { + return Err(napi::Error::from_reason( + "WinRT delegate owner has been released", + )); + } + Ok(DynWinRTValue::new(self.0.clone())) } } diff --git a/bindings/js/src/winrt_delegate_method.rs b/bindings/js/src/winrt_delegate_method.rs new file mode 100644 index 00000000..33dac32f --- /dev/null +++ b/bindings/js/src/winrt_delegate_method.rs @@ -0,0 +1,130 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use napi::{ + bindgen_prelude::{FromNapiValue, Unknown}, + JsValue, +}; +use napi_derive::napi; +use windows::core::{IInspectable, IUnknown, Interface, GUID}; + +use crate::{winrt_implementation::require_instance, DynWinRTMethodSig, DynWinRTValue, WinGUID}; + +type DelegateCall = + dyn Fn(&IUnknown, &[dynwinrt::WinRTValue]) -> windows::core::Result>; + +/// A prepared caller for a metadata-described WinRT delegate's Invoke method. +/// Delegates derive from IUnknown, so Invoke is slot 3, not IInspectable slot 6. +/// Supply the full delegate signature and its concrete IID (including generic +/// type arguments). This does not register an interface or use the COM planner. +#[napi] +pub struct DynWinRtDelegateMethod { + iid: GUID, + call: Box, +} + +fn clone_arguments(args: Vec>) -> napi::Result> { + args + .into_iter() + .map(|value| { + require_instance::(&value, "DynWinRtValue")?; + Ok( + unsafe { <&DynWinRTValue>::from_napi_value(value.value().env, value.raw()) }? + .0 + .clone(), + ) + }) + .collect() +} + +pub(crate) fn invoke_delegate_value( + target: dynwinrt::WinRTValue, + iid: Unknown<'_>, + signature: Unknown<'_>, + args: Vec>, +) -> napi::Result> { + let caller = DynWinRtDelegateMethod::create(iid, signature)?; + let args = clone_arguments(args)?; + caller.invoke_native(target, &args) +} + +impl DynWinRtDelegateMethod { + fn invoke_native( + &self, + target: dynwinrt::WinRTValue, + args: &[dynwinrt::WinRTValue], + ) -> napi::Result> { + if target.as_object().is_none() { + return Err(napi::Error::from_reason( + "Delegate invocation requires a live managed Object value", + )); + } + let view = target.cast(&self.iid).map_err(|error| { + napi::Error::from_reason(format!( + "Delegate QueryInterface failed: {}", + error.message() + )) + })?; + let object = view.as_object().ok_or_else(|| { + napi::Error::from_reason("Delegate QueryInterface did not return a managed Object") + })?; + (self.call)(&object, args) + .map(|values| values.into_iter().map(DynWinRTValue::new).collect()) + .map_err(|error| napi::Error::from_reason(error.message())) + } +} + +#[napi] +impl DynWinRtDelegateMethod { + #[napi(factory, strict)] + pub fn create( + #[napi(ts_arg_type = "WinGuid")] iid: Unknown<'_>, + #[napi(ts_arg_type = "DynWinRtMethodSig")] signature: Unknown<'_>, + ) -> napi::Result { + require_instance::(&iid, "WinGuid")?; + require_instance::(&signature, "DynWinRtMethodSig")?; + let iid = unsafe { <&WinGUID>::from_napi_value(iid.value().env, iid.raw()) }?.0; + if [ + GUID::zeroed(), + IUnknown::IID, + IInspectable::IID, + windows::core::imp::IAgileObject::IID, + windows::core::imp::IMarshal::IID, + windows::core::imp::IWeakReference::IID, + windows::core::imp::IWeakReferenceSource::IID, + ] + .contains(&iid) + { + return Err(napi::Error::from_reason( + "A WinRT delegate caller requires a delegate IID, not an infrastructure IID", + )); + } + let signature = + unsafe { <&DynWinRTMethodSig>::from_napi_value(signature.value().env, signature.raw()) }?; + let method = signature.0.clone().build(3); + Ok(Self { + iid, + // Keep the native facade's unnameable prepared Method type opaque. + call: Box::new(move |object, args| method.call_dynamic(object.as_raw(), args)), + }) + } + + /// Query the delegate IID and synchronously invoke its native Invoke method. + /// Returns all outputs in signature order; void delegates return []. + /// Target and arguments are retained across QI and reentrant native calls. + /// Like outbound invokeAll, FillArray inputs must be preallocated typed Array + /// values. U32 capacities apply only to reverse interface handler inputs. + #[napi(strict)] + pub fn invoke( + &self, + #[napi(ts_arg_type = "DynWinRtValue")] value: Unknown<'_>, + #[napi(ts_arg_type = "DynWinRtValue[]")] args: Vec>, + ) -> napi::Result> { + require_instance::(&value, "DynWinRtValue")?; + let value = unsafe { <&DynWinRTValue>::from_napi_value(value.value().env, value.raw()) }?; + value.ensure_existing_com_apartment()?; + let target = value.0.clone(); + let args = clone_arguments(args)?; + self.invoke_native(target, &args) + } +} diff --git a/bindings/js/src/winrt_implementation.rs b/bindings/js/src/winrt_implementation.rs new file mode 100644 index 00000000..08fe0e26 --- /dev/null +++ b/bindings/js/src/winrt_implementation.rs @@ -0,0 +1,543 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + ptr, + rc::Rc, + sync::{ + atomic::{AtomicU64, Ordering}, + Arc, + }, +}; + +use dynwinrt::{ + WinRTValue, WinRtImplementation, WinRtImplementationPlan, WinRtInterfaceDefinition, + WinRtMethodDefinition, WinRtThreadingPolicy, +}; +use napi::{ + bindgen_prelude::{FromNapiValue, Function, JavaScriptClassExt, ToNapiValue, Unknown}, + sys, Env, JsValue, +}; +use napi_derive::napi; +use windows::core::HRESULT; + +use crate::{managed_tsfn::ManagedTsfn, DynWinRTMethodSig, DynWinRTType, DynWinRTValue, WinGUID}; + +static NEXT_IMPLEMENTATION_ID: AtomicU64 = AtomicU64::new(1); +#[cfg(feature = "test-hooks")] +pub(crate) static FINALIZED_CALLBACKS: AtomicU64 = AtomicU64::new(0); +#[cfg(feature = "test-hooks")] +pub(crate) static ENV_DISCONNECTS: AtomicU64 = AtomicU64::new(0); + +thread_local! { + // N-API owns these controllers on the environment thread. Callback closures + // never capture them: foreign native destruction only releases a cleanup TSFN. + static ENVIRONMENTS: RefCell>> = RefCell::new(HashMap::new()); +} + +struct Environment { + closed: Cell, + implementations: RefCell>>, +} + +struct ImplementationState { + native: RefCell, +} + +fn environment(env: Env) -> napi::Result> { + let key = env.raw() as usize; + if let Some(environment) = ENVIRONMENTS.with(|entries| entries.borrow().get(&key).cloned()) { + if environment.closed.get() { + return Err(napi::Error::from_reason( + "Cannot create a WinRT implementation while the Node environment is closing", + )); + } + return Ok(environment); + } + let environment = Rc::new(Environment { + closed: Cell::new(false), + implementations: RefCell::new(HashMap::new()), + }); + // Installed after ManagedTsfn's hook. Node runs cleanup hooks in reverse + // registration order, so native controls disconnect before TSFN teardown. + let _hook = env.add_env_cleanup_hook((key, environment.clone()), |(key, environment)| { + environment.closed.set(true); + ENVIRONMENTS.with(|entries| entries.borrow_mut().remove(&key)); + let states = environment + .implementations + .borrow_mut() + .drain() + .map(|(_, state)| state) + .collect::>(); + for state in states { + if let Err(error) = state.native.borrow_mut().dispose() { + eprintln!("[dynwinrt] WinRT implementation environment cleanup: {error}"); + } + #[cfg(feature = "test-hooks")] + ENV_DISCONNECTS.fetch_add(1, Ordering::Relaxed); + } + })?; + ENVIRONMENTS.with(|entries| entries.borrow_mut().insert(key, environment.clone())); + Ok(environment) +} + +fn forget_implementation(env_key: usize, id: u64) { + let environment = ENVIRONMENTS.with(|entries| entries.borrow().get(&env_key).cloned()); + if let Some(environment) = environment { + let removed = environment.implementations.borrow_mut().remove(&id); + drop(removed); + } +} + +fn binding_error(error: windows::core::Error) -> napi::Error { + napi::Error::from_reason(error.message()) +} + +pub(crate) fn require_instance( + value: &Unknown<'_>, + name: &str, +) -> napi::Result<()> { + // JavaScriptClassExt uses the registered JS name (DynWinRt*). napi-rs's + // ValidateNapiValue derives instead look up the legacy Rust DynWinRT* name. + if T::instance_of(&Env::from_raw(value.value().env), value)? { + Ok(()) + } else { + Err(napi::Error::from_reason(format!( + "Expected a {name} instance" + ))) + } +} + +/// One complete method contract, including every output in ABI parameter order. +#[napi(object, object_to_js = false)] +pub struct DynWinRtImplementationMethod<'env> { + pub name: String, + pub vtable_index: f64, + #[napi(ts_type = "DynWinRtMethodSig")] + pub signature: Unknown<'env>, +} + +/// A standalone WinRT interface descriptor. Creation never registers a COM class +/// or changes the outbound WinRT method registry. +#[napi] +pub struct DynWinRtInterfacePlan(WinRtInterfaceDefinition); + +#[napi] +impl DynWinRtInterfacePlan { + #[napi(factory, strict)] + pub fn create( + name: String, + #[napi(ts_arg_type = "DynWinRtType")] interface_type: Unknown<'_>, + methods: Vec>, + #[napi(ts_arg_type = "WinGuid[]")] required_iids: Option>>, + ) -> napi::Result { + require_instance::(&interface_type, "DynWinRtType")?; + let interface_type = unsafe { + <&DynWinRTType>::from_napi_value(interface_type.value().env, interface_type.raw()) + }?; + let methods = methods + .into_iter() + .map(|method| { + let env = method.signature.value().env; + let raw = method.signature.raw(); + require_instance::(&method.signature, "DynWinRtMethodSig")?; + let signature = unsafe { <&DynWinRTMethodSig>::from_napi_value(env, raw) }?; + Ok(WinRtMethodDefinition { + name: method.name, + vtable_index: crate::js_u32(method.vtable_index, "vtableIndex")? as usize, + signature: signature.0.clone(), + }) + }) + .collect::>>()?; + let required_iids = required_iids + .unwrap_or_default() + .into_iter() + .map(|iid| { + let env = iid.value().env; + let raw = iid.raw(); + require_instance::(&iid, "WinGuid")?; + Ok(unsafe { <&WinGUID>::from_napi_value(env, raw) }?.0) + }) + .collect::>>()?; + let definition = WinRtInterfaceDefinition { + name, + interface_type: interface_type.type_handle(), + required_iids, + methods, + }; + WinRtImplementationPlan::validate_interface(&definition).map_err(binding_error)?; + Ok(Self(definition)) + } +} + +/// Owns one reference to a synchronous, non-agile WinRT implementation. +/// +/// release()/GC drops this owner's reference only. Native references keep the +/// callback alive. dispose() disconnects every view and breaks callback cycles. +/// Call dispose() explicitly when a handler captures its owner or a native view; +/// those cross-runtime cycles are not visible to JavaScript's garbage collector. +#[napi] +pub struct DynWinRtImplementation { + state: Rc, +} + +impl Drop for DynWinRtImplementation { + fn drop(&mut self) { + self.state.native.borrow_mut().release(); + } +} + +#[napi] +impl DynWinRtImplementation { + #[napi(factory, strict)] + pub fn create( + env: Env, + #[napi(ts_arg_type = "DynWinRtInterfacePlan[]")] interfaces: Vec>, + #[napi( + ts_arg_type = "(interfaceIndex: number, vtableIndex: number, args: DynWinRtValue[]) => DynWinRtValue[]" + )] + callback: Function<'_, (), Unknown<'_>>, + runtime_class_name: Option, + ) -> napi::Result { + let definitions = interfaces + .into_iter() + .map(|interface| { + let raw = interface.raw(); + require_instance::(&interface, "DynWinRtInterfacePlan")?; + Ok( + unsafe { <&DynWinRtInterfacePlan>::from_napi_value(env.raw(), raw) }? + .0 + .clone(), + ) + }) + .collect::>>()?; + let plan = WinRtImplementationPlan::new(definitions, WinRtThreadingPolicy::OwnerThread) + .map_err(binding_error)?; + reject_async_function(env.raw(), callback.raw())?; + + let id = NEXT_IMPLEMENTATION_ID.fetch_add(1, Ordering::Relaxed); + let env_key = env.raw() as usize; + let (callback_ref, async_context, finalize_resources) = + crate::create_direct_callback_resources( + env.raw(), + callback.raw(), + b"dynwinrt.winrtImplementation", + )?; + let finalizer = Box::new(move |env| { + forget_implementation(env_key, id); + finalize_resources(env); + #[cfg(feature = "test-hooks")] + FINALIZED_CALLBACKS.fetch_add(1, Ordering::Relaxed); + }); + let tsfn = ManagedTsfn::create( + env.raw(), + callback.raw(), + 1, + true, + |(), _| Ok(Vec::new()), + Some(finalizer), + )?; + let environment = environment(env)?; + let direct = crate::DirectJsCallback { + env: env.raw(), + callback_ref, + async_context, + lifecycle: tsfn.lifecycle(), + }; + let callback: dynwinrt::WinRtImplementationCallback = + Arc::new(move |interface_index, vtable_index, values| { + // This TSFN is only a lifetime/finalizer bridge. Native enforces the + // owner thread before entry; method dispatch is never queued. + let _resources = &tsfn; + invoke_callback(&direct, interface_index, vtable_index, values).map_err(|error| { + windows::core::Error::new( + HRESULT(0x80004005u32 as i32), + format!("WinRT implementation callback failed: {}", error.reason), + ) + }) + }); + let native = WinRtImplementation::new(plan, callback, runtime_class_name.as_deref()) + .map_err(binding_error)?; + let state = Rc::new(ImplementationState { + native: RefCell::new(native), + }); + environment + .implementations + .borrow_mut() + .insert(id, state.clone()); + Ok(Self { state }) + } + + /// Returns a separately owned canonical IInspectable value. + #[napi] + pub fn to_value(&self) -> napi::Result { + self + .state + .native + .borrow() + .to_value() + .map(DynWinRTValue::new) + .map_err(binding_error) + } + + /// Drops only this owner's native reference. Retained views remain callable. + #[napi] + pub fn release(&self) { + self.state.native.borrow_mut().release(); + } + + /// Disconnects callbacks on every view, retaining this owner's reference. + #[napi] + pub fn disconnect(&self) -> napi::Result<()> { + self + .state + .native + .borrow() + .disconnect() + .map_err(binding_error) + } + + /// Disconnects all views, releases the owner, and breaks callback roots. + /// Repeated calls are harmless; an active callback may finish before cleanup. + #[napi] + pub fn dispose(&self) -> napi::Result<()> { + self + .state + .native + .borrow_mut() + .dispose() + .map_err(binding_error) + } + + #[napi(getter)] + pub fn is_closed(&self) -> bool { + self.state.native.borrow().is_closed() + } + + /// Returns and clears the latest native dispatch/validation error. + #[napi] + pub fn take_error(&self) -> Option { + self.state.native.borrow().take_error() + } +} + +fn reject_async_function(env: sys::napi_env, callback: sys::napi_value) -> napi::Result<()> { + let mut constructor = ptr::null_mut(); + crate::napi_status("napi_get_named_property(callback constructor)", unsafe { + sys::napi_get_named_property(env, callback, c"constructor".as_ptr(), &mut constructor) + })?; + let mut typ = sys::ValueType::napi_undefined; + crate::napi_status("napi_typeof(callback constructor)", unsafe { + sys::napi_typeof(env, constructor, &mut typ) + })?; + if typ == sys::ValueType::napi_function { + let mut name = ptr::null_mut(); + crate::napi_status( + "napi_get_named_property(callback constructor name)", + unsafe { sys::napi_get_named_property(env, constructor, c"name".as_ptr(), &mut name) }, + )?; + let name = unsafe { String::from_napi_value(env, name) }?; + if name == "AsyncFunction" || name == "AsyncGeneratorFunction" || name == "GeneratorFunction" { + return Err(napi::Error::from_reason( + "WinRT implementation handlers must be synchronous functions, not async/generator functions", + )); + } + } + Ok(()) +} + +fn parse_outputs(env: sys::napi_env, result: sys::napi_value) -> napi::Result> { + let mut promise = false; + crate::napi_status("napi_is_promise(WinRT result)", unsafe { + sys::napi_is_promise(env, result, &mut promise) + })?; + let mut typ = sys::ValueType::napi_undefined; + crate::napi_status("napi_typeof(WinRT result)", unsafe { + sys::napi_typeof(env, result, &mut typ) + })?; + if matches!( + typ, + sys::ValueType::napi_object | sys::ValueType::napi_function + ) { + let mut then = ptr::null_mut(); + crate::napi_status("napi_get_named_property(WinRT result then)", unsafe { + sys::napi_get_named_property(env, result, c"then".as_ptr(), &mut then) + })?; + let mut then_type = sys::ValueType::napi_undefined; + crate::napi_status("napi_typeof(WinRT result then)", unsafe { + sys::napi_typeof(env, then, &mut then_type) + })?; + promise |= then_type == sys::ValueType::napi_function; + } + if promise { + return Err(napi::Error::from_reason( + "WinRT implementation handlers must return synchronous DynWinRtValue[] results, not a Promise/thenable", + )); + } + let mut array = false; + crate::napi_status("napi_is_array(WinRT outputs)", unsafe { + sys::napi_is_array(env, result, &mut array) + })?; + if !array { + return Err(napi::Error::from_reason( + "WinRT implementation handlers must return a DynWinRtValue[] (use [] for void)", + )); + } + let mut length = 0; + crate::napi_status("napi_get_array_length(WinRT outputs)", unsafe { + sys::napi_get_array_length(env, result, &mut length) + })?; + let mut outputs = Vec::with_capacity(length as usize); + for index in 0..length { + let mut raw = ptr::null_mut(); + crate::napi_status("napi_get_element(WinRT output)", unsafe { + sys::napi_get_element(env, result, index, &mut raw) + })?; + let value = unsafe { Unknown::from_napi_value(env, raw) }?; + require_instance::(&value, "DynWinRtValue").map_err(|error| { + napi::Error::from_reason(format!( + "WinRT output {index} must be a DynWinRtValue: {}", + error.reason + )) + })?; + outputs.push( + unsafe { <&DynWinRTValue>::from_napi_value(env, raw) }? + .0 + .clone(), + ); + } + Ok(outputs) +} + +fn callback_error(env: sys::napi_env, error: napi::Error) -> napi::Error { + let mut pending = false; + if unsafe { sys::napi_is_exception_pending(env, &mut pending) } != sys::Status::napi_ok + || !pending + { + return error; + } + let mut exception = ptr::null_mut(); + if unsafe { sys::napi_get_and_clear_last_exception(env, &mut exception) } != sys::Status::napi_ok + { + return error; + } + let mut message = ptr::null_mut(); + if unsafe { sys::napi_coerce_to_string(env, exception, &mut message) } == sys::Status::napi_ok { + if let Ok(message) = unsafe { String::from_napi_value(env, message) } { + return napi::Error::from_reason(message); + } + } + // Even an exception's toString() may throw. Never leak a pending exception + // through the foreign HRESULT boundary. + let mut ignored = ptr::null_mut(); + unsafe { sys::napi_get_and_clear_last_exception(env, &mut ignored) }; + napi::Error::from_reason(format!( + "JavaScript handler threw an exception (message unavailable): {}", + error.reason + )) +} + +struct CallbackHandleScope { + env: sys::napi_env, + scope: Option, +} + +impl CallbackHandleScope { + fn open(env: sys::napi_env) -> napi::Result { + let mut scope = ptr::null_mut(); + crate::napi_status("napi_open_handle_scope(WinRT callback)", unsafe { + sys::napi_open_handle_scope(env, &mut scope) + })?; + Ok(Self { + env, + scope: Some(scope), + }) + } + + fn close(&mut self) -> napi::Result<()> { + if let Some(scope) = self.scope.take() { + crate::napi_status("napi_close_handle_scope(WinRT callback)", unsafe { + sys::napi_close_handle_scope(self.env, scope) + })?; + } + Ok(()) + } +} + +impl Drop for CallbackHandleScope { + fn drop(&mut self) { + // Native catches Rust panics; close the N-API scope during unwinding too. + if let Err(error) = self.close() { + eprintln!("[dynwinrt] WinRT callback handle scope cleanup: {error}"); + } + } +} + +fn invoke_callback( + direct: &crate::DirectJsCallback, + interface_index: usize, + vtable_index: usize, + values: &[WinRTValue], +) -> napi::Result> { + if direct.lifecycle.is_closing() { + return Err(napi::Error::from_reason( + "WinRT implementation's Node environment is closing", + )); + } + let env = direct.env; + let mut scope = CallbackHandleScope::open(env)?; + let result = (|| { + let mut function = ptr::null_mut(); + crate::napi_status("napi_get_reference_value(WinRT callback)", unsafe { + sys::napi_get_reference_value(env, direct.callback_ref, &mut function) + })?; + let js_values = values + .iter() + .cloned() + .map(DynWinRTValue::new) + .collect::>(); + let args = unsafe { + [ + u32::to_napi_value(env, interface_index as u32)?, + u32::to_napi_value(env, vtable_index as u32)?, + Vec::::to_napi_value(env, js_values)?, + ] + }; + let mut receiver = ptr::null_mut(); + crate::napi_status("napi_get_global(WinRT callback)", unsafe { + sys::napi_get_global(env, &mut receiver) + })?; + let mut result = ptr::null_mut(); + crate::napi_status("napi_make_callback(WinRT implementation)", unsafe { + sys::napi_make_callback( + env, + direct.async_context, + receiver, + function, + args.len(), + args.as_ptr(), + &mut result, + ) + })?; + parse_outputs(env, result) + })() + .map_err(|error| callback_error(env, error)); + let close = scope.close(); + match result { + Err(error) => Err(error), + Ok(outputs) => close.map(|()| outputs), + } +} + +#[cfg(feature = "test-hooks")] +pub(crate) fn live_control_count() -> u32 { + ENVIRONMENTS.with(|entries| { + entries + .borrow() + .values() + .map(|env| env.implementations.borrow().len() as u32) + .sum() + }) +} diff --git a/bindings/js/src/winrt_implementation_test_hooks.rs b/bindings/js/src/winrt_implementation_test_hooks.rs new file mode 100644 index 00000000..f954098f --- /dev/null +++ b/bindings/js/src/winrt_implementation_test_hooks.rs @@ -0,0 +1,196 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::sync::{ + atomic::{AtomicU32, Ordering}, + Arc, Mutex, +}; + +use dynwinrt::{ + MethodSignature, WinRTValue, WinRtImplementation, WinRtImplementationPlan, + WinRtInterfaceDefinition, WinRtMethodDefinition, WinRtThreadingPolicy, +}; +use napi_derive::napi; +use windows::{ + core::{self as windows_core, Interface}, + ApplicationModel::Background::{ + BackgroundTaskCanceledEventHandler, BackgroundTaskDeferral, BackgroundTaskRegistration, + IBackgroundTaskInstance, + }, + Foundation::IStringable, +}; + +use crate::{winrt_implementation, DynWinRTValue}; + +static RETAINED: Mutex> = Mutex::new(None); + +#[napi(object)] +pub struct WinRtImplementationTestCall { + pub hresult: i32, + pub text: Option, +} + +#[napi(object)] +pub struct WinRtImplementationTestStats { + pub live_controls: u32, + pub finalized_callbacks: u32, + pub environment_disconnects: u32, +} + +#[napi] +pub fn winrt_implementation_test_stats() -> WinRtImplementationTestStats { + WinRtImplementationTestStats { + live_controls: winrt_implementation::live_control_count(), + finalized_callbacks: winrt_implementation::FINALIZED_CALLBACKS.load(Ordering::Relaxed) as u32, + environment_disconnects: winrt_implementation::ENV_DISCONNECTS.load(Ordering::Relaxed) as u32, + } +} + +#[napi] +pub fn winrt_implementation_test_retain(value: &DynWinRTValue) -> napi::Result<()> { + value + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("Expected an object"))? + .cast::() + .map_err(|error| napi::Error::from_reason(error.message()))?; + let previous = RETAINED.lock().unwrap().replace(value.0.clone()); + drop(previous); + Ok(()) +} + +fn call_retained(value: WinRTValue) -> WinRtImplementationTestCall { + let result = value + .as_object() + .unwrap() + .cast::() + .and_then(|view| view.ToString()); + match result { + Ok(text) => WinRtImplementationTestCall { + hresult: 0, + text: Some(text.to_string()), + }, + Err(error) => WinRtImplementationTestCall { + hresult: error.code().0, + text: None, + }, + } +} + +#[napi] +pub fn winrt_implementation_test_invoke_retained( + foreign_thread: Option, +) -> napi::Result { + let value = RETAINED + .lock() + .unwrap() + .clone() + .ok_or_else(|| napi::Error::from_reason("No retained WinRT implementation"))?; + if foreign_thread.unwrap_or(false) { + std::thread::spawn(move || call_retained(value)) + .join() + .map_err(|_| napi::Error::from_reason("Retained invocation thread panicked")) + } else { + Ok(call_retained(value)) + } +} + +#[napi] +pub fn winrt_implementation_test_release_retained( + foreign_thread: Option, +) -> napi::Result<()> { + let value = RETAINED.lock().unwrap().take(); + if foreign_thread.unwrap_or(false) { + std::thread::spawn(move || drop(value)) + .join() + .map_err(|_| napi::Error::from_reason("Retained release thread panicked"))?; + } else { + drop(value); + } + Ok(()) +} + +#[napi] +pub fn winrt_implementation_test_background_instance() -> napi::Result { + // The complete nine-slot contract matches the SDK IBackgroundTaskInstance_Vtbl. + // This fixture never registers an OS task. The SDK projection below is an + // independent native caller, not a reinterpreted pointer or a vtable alias. + let table = &*crate::TABLE; + let signature = || MethodSignature::new(table); + let methods = [ + ("InstanceId", signature().add_out(table.guid_type())), + ( + "Task", + signature().add_out(table.interface(BackgroundTaskRegistration::IID)), + ), + ("Progress", signature().add_out(table.u32_type())), + ("SetProgress", signature().add_in(table.u32_type())), + ("TriggerDetails", signature().add_out(table.object())), + ( + "Canceled", + signature() + .add_in(table.delegate(BackgroundTaskCanceledEventHandler::IID)) + .add_out(table.i64_type()), + ), + ("RemoveCanceled", signature().add_in(table.i64_type())), + ("SuspendedCount", signature().add_out(table.u32_type())), + ( + "GetDeferral", + signature().add_out(table.interface(BackgroundTaskDeferral::IID)), + ), + ] + .into_iter() + .enumerate() + .map(|(index, (name, signature))| WinRtMethodDefinition { + name: name.into(), + vtable_index: index + 6, + signature, + }) + .collect(); + let definition = WinRtInterfaceDefinition { + name: "Windows.ApplicationModel.Background.IBackgroundTaskInstance".into(), + interface_type: table.interface(IBackgroundTaskInstance::IID), + required_iids: Vec::new(), + methods, + }; + let result = (|| { + let plan = WinRtImplementationPlan::new(vec![definition], WinRtThreadingPolicy::OwnerThread)?; + let progress = AtomicU32::new(42); + let owner = WinRtImplementation::new( + plan, + Arc::new(move |_, slot, values| match slot { + 6 => Ok(vec![WinRTValue::Guid(windows_core::GUID::from_u128( + 0x72be118a_a19e_466a_a7d6_634a79e197b7, + ))]), + 8 => Ok(vec![WinRTValue::U32(progress.load(Ordering::Relaxed))]), + 9 => { + if let WinRTValue::U32(value) = values[0] { + progress.store(value, Ordering::Relaxed); + } + Ok(Vec::new()) + } + 13 => Ok(vec![WinRTValue::U32(0)]), + _ => Err(windows_core::Error::new( + windows_core::HRESULT(0x80004001u32 as i32), + "Fixture has no OS task registration, cancellation source, trigger, or deferral", + )), + }), + None, + )?; + owner.to_value() + })(); + result + .map(DynWinRTValue::new) + .map_err(|error| napi::Error::from_reason(error.message())) +} + +#[napi] +pub fn winrt_implementation_test_background_progress(value: &DynWinRTValue) -> napi::Result { + value + .0 + .as_object() + .ok_or_else(|| napi::Error::from_reason("Expected an object"))? + .cast::() + .and_then(|instance| instance.Progress()) + .map_err(|error| napi::Error::from_reason(error.message())) +} diff --git a/bindings/py/README.md b/bindings/py/README.md index 71347ff0..ae115921 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -190,6 +190,119 @@ Generated runtime classes that implement `IClosable` support `with` and an idempotent `close()` method. Prefer deterministic cleanup instead of relying on Python garbage collection. +## Standalone WinRT interface implementations + +Generated, supported non-generic WinRT interfaces provide `.implementation()` +and `.implement()` factories. They create standalone, `IInspectable`-rooted +objects; they do not activate or register an OS class, compose a WinUI control, +or implement Classic COM interfaces. Use the public `from_implementation()` +factory to obtain a typed view without transferring the owner's reference: + +```python +from dynwinrt import release_projected +from generated.windows.foundation import IClosable, IStringable + +class Label: + def to_string(self) -> str: + return "Python-backed WinRT object" + + def close(self) -> None: + pass + +handler = Label() +with IStringable.implement( + handler, IClosable.implementation(handler) +) as owner: + label = IStringable.from_implementation(owner) + try: + print(label.to_string()) + finally: + release_projected(label) +``` + +The generated handler protocols describe snake-case methods and their input +and output types. Additional interface descriptors provide separate native +views sharing the same object identity. Every required interface must be +included; an incomplete implementation is rejected before publication. +`release_projected(view)` releases a view independently without disposing or +releasing its controller. + +The low-level runtime surface is: + +- `DynWinRTImplementationMethod(name, vtable_index, signature)`: an immutable + method definition using the existing `DynWinRTMethodSig`. +- `DynWinRTInterfacePlan.create(name, interface_type, methods, + required_iids=())`: an immutable, validated interface definition. Methods + occupy every slot starting at slot 6; required-interface membership is + checked when composing the complete implementation. +- `DynWinRTImplementationDescriptor(plan, dispatch)`: a generated interface + plan and synchronous `dispatch(vtable_index, args)` callable. +- `DynWinRTImplementation.create(interfaces, callback, + runtime_class_name=None)`: the native owner. Its callback receives + `(interface_index, vtable_index, list[DynWinRTValue])` and must return a + `list[DynWinRTValue]` in signature output order, with any logical return last. + A void callback returns `[]`, not `None`. + +Prefer generated plans rather than hand-authoring native signatures. The +runtime validates scalar, GUID, HSTRING, complete struct, managed-reference, +and pass/receive/fill-array contracts. For fill arrays the **callback** receives +a `UInt32` capacity and must return an array of exactly that length. Existing +outbound `DynWinRTMethodHandle` calls still take a preallocated array value for +a fill-array argument. `DynWinRTValue.from_hresult()` constructs an exact +signed HRESULT value, including for typed HRESULT arrays. + +Callbacks are synchronous and run only on the creating native thread, with a +fresh copy of the `contextvars` context captured at creation. Reentrant calls +are supported. Async callables and coroutine/awaitable results are rejected; +no event loop is scheduled or blocked. Already-created native WinRT async +values can be passed through like other managed native values. Arbitrary +generic interface implementations, cross-thread dispatch, and Python +subinterpreters are not supported. + +Callable wrappers for received native delegates can prepare a reusable +`DynWinRTDelegateMethod.create(iid, signature)` and call +`method.invoke(value, args)`. The convenience +`value.invoke_delegate(iid, signature, args)` remains available and uses the +same invocation path. The IID and signature must describe the same WinRT +delegate's `Invoke` method, including computed closed-generic IIDs. This calls +slot 3 on the delegate's `IUnknown` root and returns all outputs as a list +(`[]` for void). It borrows the Python value, owns a native pin through the +call, and propagates failed HRESULTs. Arguments use the existing outbound +`invoke_all()` contract, including preallocated fill-array values; these +helpers do not infer signatures or turn arbitrary objects into delegates. + +### Implementation lifetime and callback failures + +`to_value()` returns an independently owned native reference. `release()` +drops only the owner's reference; callbacks remain alive while native +consumers retain other references, even after the Python owner wrapper is +gone. `disconnect()` disables all views and releases captured Python handlers +without dropping the owner's native reference. `dispose()` disconnects and +releases, and is repeat-safe. The owner context manager calls `dispose()`. +An in-flight callback can finish safely when it calls any of these methods; +subsequent calls after disconnection fail with `RO_E_CLOSED`. + +GC tracing is deliberately conservative: captured Python references are +reported as owner edges only when that owner is the sole native reference. +This collects ordinary handler/self/owner cycles without treating native +consumers as collectable Python references. Cycles that retain a native alias, +or that have requested native weak references, may require **explicit +`dispose()`**. Callback invocation and `to_value()` require the creating thread; +foreign-thread `to_value()` raises `OSError` with `RPC_E_WRONG_THREAD`. +Owner release, disposal, and garbage collection can run on another Python +thread without leaking the owner's native reference. This does not make +arbitrary wrapped Windows objects agile. Prefer deterministic cleanup; +unexpected GC cleanup failures are reported to `sys.unraisablehook`. +Interpreter shutdown separately closes the callback gate and drops +captured handlers; late native calls cannot enter a finalized interpreter. + +Python callback exceptions and invalid Python output containers are reported +to `sys.unraisablehook` and fail the native call with +`PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION` (`0xA0EE4005`). Native output-contract +mismatches also fail rather than returning fabricated values. `take_error()` +returns and clears the latest native callback diagnostic; `is_closed` is a +read-only property. + ## Experimental WinUI support When the required WinUI metadata is generated, `Application.create()` installs diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 0b8a8184..ec0a8da1 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -27,6 +27,11 @@ __all__ = [ "DynWinRTType", "DynWinRTMethodSig", "DynWinRTMethodHandle", + "DynWinRTImplementationMethod", + "DynWinRTInterfacePlan", + "DynWinRTImplementation", + "DynWinRTImplementationDescriptor", + "DynWinRTDelegateMethod", "DynWinRTOverrideInterface", "DynWinRTXamlRegistration", "DynWinRTValue", @@ -231,6 +236,84 @@ class DynWinRTMethodSig: def add_out_fill(self, typ: DynWinRTType) -> DynWinRTMethodSig: ... +@final +class DynWinRTDelegateMethod: + @staticmethod + def create( + iid: WinGUID, signature: DynWinRTMethodSig + ) -> DynWinRTDelegateMethod: ... + def invoke( + self, value: DynWinRTValue, args: Sequence[DynWinRTValue] + ) -> List[DynWinRTValue]: ... + + +@final +class DynWinRTImplementationMethod: + def __new__( + cls, name: str, vtable_index: int, signature: DynWinRTMethodSig + ) -> DynWinRTImplementationMethod: ... + @property + def name(self) -> str: ... + @property + def vtable_index(self) -> int: ... + @property + def signature(self) -> DynWinRTMethodSig: ... + + +@final +class DynWinRTInterfacePlan: + @staticmethod + def create( + name: str, + interface_type: DynWinRTType, + methods: Sequence[DynWinRTImplementationMethod], + required_iids: Sequence[WinGUID] = ..., + ) -> DynWinRTInterfacePlan: ... + @property + def name(self) -> str: ... + @property + def interface_type(self) -> DynWinRTType: ... + @property + def methods(self) -> List[DynWinRTImplementationMethod]: ... + @property + def required_iids(self) -> List[WinGUID]: ... + + +@final +class DynWinRTImplementationDescriptor: + def __init__( + self, + plan: DynWinRTInterfacePlan, + dispatch: Callable[[int, List[DynWinRTValue]], List[DynWinRTValue]], + ) -> None: ... + @property + def plan(self) -> DynWinRTInterfacePlan: ... + def dispatch( + self, vtable_index: int, args: List[DynWinRTValue] + ) -> List[DynWinRTValue]: ... + + +@final +class DynWinRTImplementation: + @staticmethod + def create( + interfaces: Sequence[DynWinRTInterfacePlan], + callback: Callable[[int, int, List[DynWinRTValue]], List[DynWinRTValue]], + runtime_class_name: Optional[str] = ..., + ) -> DynWinRTImplementation: ... + def to_value(self) -> DynWinRTValue: ... + def release(self) -> None: ... + def dispose(self) -> None: ... + def disconnect(self) -> None: ... + @property + def is_closed(self) -> bool: ... + def take_error(self) -> Optional[str]: ... + def __enter__(self) -> DynWinRTImplementation: ... + def __exit__( + self, _exc_type: object, _exc_value: object, _traceback: object + ) -> Literal[False]: ... + + @final class DynWinRTOverrideInterface: def __new__( @@ -303,6 +386,8 @@ class DynWinRTValue: @staticmethod def from_i32(value: int) -> DynWinRTValue: ... @staticmethod + def from_hresult(value: int) -> DynWinRTValue: ... + @staticmethod def from_u32(value: int) -> DynWinRTValue: ... @staticmethod def from_i64(value: int) -> DynWinRTValue: ... @@ -356,6 +441,12 @@ class DynWinRTValue: def as_raw(self) -> int: ... def identity_raw(self) -> int: ... def cast(self, iid: WinGUID) -> DynWinRTValue: ... + def invoke_delegate( + self, + iid: WinGUID, + signature: DynWinRTMethodSig, + args: Sequence[DynWinRTValue], + ) -> List[DynWinRTValue]: ... def activate(self) -> DynWinRTValue: ... def call_0( self, method_index: int, return_type: DynWinRTType diff --git a/bindings/py/src/delegate_method.rs b/bindings/py/src/delegate_method.rs new file mode 100644 index 00000000..fbfc14bb --- /dev/null +++ b/bindings/py/src/delegate_method.rs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use pyo3::exceptions::PyTypeError; +use pyo3::prelude::*; +use windows::core::{GUID, IInspectable, IUnknown, Interface}; + +use crate::errors::{map_dynwinrt_error, map_windows_error}; +use crate::runtime::{DynWinRTMethodSig, DynWinRTValue, WinGUID}; + +type DelegateCall = + dyn Fn(&IUnknown, &[dynwinrt::WinRTValue]) -> windows::core::Result>; + +struct PreparedDelegateCall(Box); + +// Constructed only below, capturing a fully built WinRT Method: immutable +// MethodInfo and a prepared libffi CIF, with no Python or target references. +// ffi_call reads that CIF; argument/output storage is local to each invocation. +// Its owned metadata/CIF allocations can also be destroyed on any thread. +unsafe impl Send for PreparedDelegateCall {} +unsafe impl Sync for PreparedDelegateCall {} + +#[pyclass(frozen, module = "dynwinrt")] +pub struct DynWinRTDelegateMethod { + iid: GUID, + call: PreparedDelegateCall, +} + +#[pymethods] +impl DynWinRTDelegateMethod { + /// Prepare a metadata-described WinRT delegate Invoke signature once. + #[staticmethod] + pub(crate) fn create(iid: &WinGUID, signature: &DynWinRTMethodSig) -> PyResult { + if iid.0 == GUID::zeroed() || iid.0 == IUnknown::IID || iid.0 == IInspectable::IID { + return Err(PyTypeError::new_err( + "delegate invocation requires a metadata-described delegate IID", + )); + } + let method = signature.0.clone().build(3); + Ok(Self { + iid: iid.0, + call: PreparedDelegateCall(Box::new(move |object, args| { + method.call_dynamic(object.as_raw(), args) + })), + }) + } + + /// Return all outputs in signature order, or [] for a void Invoke method. + pub(crate) fn invoke( + &self, + value: &Bound<'_, DynWinRTValue>, + args: Vec, + ) -> PyResult> { + // Keep native pins, not a Python value borrow, across reentrant Invoke. + let value = value.try_borrow()?.0.clone(); + let delegate = value.cast(&self.iid).map_err(map_dynwinrt_error)?; + let dynwinrt::WinRTValue::Object(object) = &delegate else { + return Err(PyTypeError::new_err( + "delegate invocation requires a managed WinRT delegate value", + )); + }; + let args = args.into_iter().map(|arg| arg.0).collect::>(); + (self.call.0)(object, &args) + .map(|outputs| outputs.into_iter().map(DynWinRTValue).collect()) + .map_err(map_windows_error) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prepared_delegate_method_is_send_sync() { + fn assert_send_sync() {} + assert_send_sync::(); + } +} diff --git a/bindings/py/src/errors.rs b/bindings/py/src/errors.rs index b43293ab..f80ea216 100644 --- a/bindings/py/src/errors.rs +++ b/bindings/py/src/errors.rs @@ -5,6 +5,9 @@ use pyo3::exceptions::asyncio::CancelledError as PyCancelledError; use pyo3::exceptions::{PyIndexError, PyOSError, PyRuntimeError}; use pyo3::prelude::*; +#[cfg(test)] +pub(crate) static UNRAISABLE_HOOK_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + pub(crate) fn map_windows_error(error: windows::core::Error) -> PyErr { windows_error(error, None) } diff --git a/bindings/py/src/implementation.py b/bindings/py/src/implementation.py new file mode 100644 index 00000000..6055a8a5 --- /dev/null +++ b/bindings/py/src/implementation.py @@ -0,0 +1,73 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import inspect as _implementation_inspect + + +def _dynwinrt_require_sync_implementation_callable(callback): + if not callable(callback): + raise TypeError("WinRT implementation callback must be callable") + call = getattr(callback, "__call__", None) + if any( + _implementation_inspect.iscoroutinefunction(candidate) + or _implementation_inspect.isasyncgenfunction(candidate) + for candidate in (callback, call) + ): + raise TypeError( + "WinRT implementation callbacks must be synchronous; " + "async callables are not supported" + ) + + +def _dynwinrt_validate_implementation_result(result): + if ( + _implementation_inspect.isawaitable(result) + or _implementation_inspect.isasyncgen(result) + ): + if _implementation_inspect.iscoroutine(result): + result.close() + raise TypeError( + "WinRT implementation callbacks must return synchronously; " + "coroutine and awaitable results are not supported" + ) + if not isinstance(result, list) or any( + not isinstance(value, DynWinRTValue) for value in result + ): + raise TypeError( + "WinRT implementation callbacks must return a list of DynWinRTValue " + "outputs in signature order (use [] for a void method)" + ) + return result + + +def _dynwinrt_checked_implementation_callback(callback): + _dynwinrt_require_sync_implementation_callable(callback) + + def invoke(interface_index, vtable_index, args): + return _dynwinrt_validate_implementation_result( + callback(interface_index, vtable_index, args) + ) + + return invoke + + +class DynWinRTImplementationDescriptor: + """One generated interface plan and its synchronous projected dispatcher.""" + + __slots__ = ("_plan", "_dispatch", "__weakref__") + + def __init__(self, plan, dispatch): + if not isinstance(plan, DynWinRTInterfacePlan): + raise TypeError("plan must be a DynWinRTInterfacePlan") + _dynwinrt_require_sync_implementation_callable(dispatch) + self._plan = plan + self._dispatch = dispatch + + @property + def plan(self): + return self._plan + + def dispatch(self, vtable_index, args): + return _dynwinrt_validate_implementation_result( + self._dispatch(vtable_index, args) + ) diff --git a/bindings/py/src/implementation.rs b/bindings/py/src/implementation.rs new file mode 100644 index 00000000..238eef3f --- /dev/null +++ b/bindings/py/src/implementation.rs @@ -0,0 +1,642 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::ffi::CString; +use std::sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, Ordering}, +}; + +use dynwinrt::{ + WinRtImplementation, WinRtImplementationCallback, WinRtImplementationPlan, + WinRtInterfaceDefinition, WinRtMethodDefinition, WinRtThreadingPolicy, +}; +use pyo3::exceptions::PyRuntimeError; +use pyo3::prelude::*; +use pyo3::pyclass::{PyTraverseError, PyVisit}; +use pyo3::types::PyList; +use windows::core::{Error, HRESULT}; + +use crate::errors::map_windows_error; +use crate::runtime::{ + DynWinRTMethodSig, DynWinRTType, DynWinRTValue, PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION, WinGUID, + wrap_python_callback_context, +}; + +const RO_E_CLOSED: HRESULT = HRESULT(0x80000013_u32 as i32); +const E_FAIL: HRESULT = HRESULT(0x80004005_u32 as i32); + +fn closed_error() -> Error { + Error::new( + RO_E_CLOSED, + "Python WinRT implementation callbacks are disconnected or the interpreter is shutting down", + ) +} + +#[pyclass(frozen, from_py_object, module = "dynwinrt")] +#[derive(Clone)] +pub struct DynWinRTImplementationMethod(WinRtMethodDefinition); + +#[pymethods] +impl DynWinRTImplementationMethod { + #[new] + fn new(name: String, vtable_index: usize, signature: &DynWinRTMethodSig) -> Self { + Self(WinRtMethodDefinition { + name, + vtable_index, + signature: signature.0.clone(), + }) + } + + #[getter] + fn name(&self) -> &str { + &self.0.name + } + + #[getter] + fn vtable_index(&self) -> usize { + self.0.vtable_index + } + + #[getter] + fn signature(&self) -> DynWinRTMethodSig { + DynWinRTMethodSig(self.0.signature.clone()) + } +} + +#[pyclass(frozen, from_py_object, module = "dynwinrt")] +#[derive(Clone)] +pub struct DynWinRTInterfacePlan(WinRtInterfaceDefinition); + +#[pymethods] +impl DynWinRTInterfacePlan { + #[staticmethod] + #[pyo3( + signature = (name, interface_type, methods, required_iids=Vec::new()), + text_signature = "(name, interface_type, methods, required_iids=())" + )] + fn create( + name: String, + interface_type: &DynWinRTType, + methods: Vec, + required_iids: Vec, + ) -> PyResult { + let definition = WinRtInterfaceDefinition { + name, + interface_type: interface_type.0.clone(), + required_iids: required_iids.into_iter().map(|iid| iid.0).collect(), + methods: methods.into_iter().map(|method| method.0).collect(), + }; + WinRtImplementationPlan::validate_interface(&definition).map_err(map_windows_error)?; + Ok(Self(definition)) + } + + #[getter] + fn name(&self) -> &str { + &self.0.name + } + + #[getter] + fn interface_type(&self) -> DynWinRTType { + DynWinRTType(self.0.interface_type.clone()) + } + + #[getter] + fn methods(&self) -> Vec { + self.0 + .methods + .iter() + .cloned() + .map(DynWinRTImplementationMethod) + .collect() + } + + #[getter] + fn required_iids(&self) -> Vec { + self.0.required_iids.iter().copied().map(WinGUID).collect() + } +} + +#[derive(Default)] +struct InterpreterState { + stopping: AtomicBool, + callbacks: Mutex>>, +} + +impl InterpreterState { + fn register(&self, callback: &Arc) -> PyResult<()> { + let mut callbacks = self.callbacks.lock().map_err(|_| { + PyRuntimeError::new_err("WinRT implementation shutdown registry is poisoned") + })?; + if self.stopping.load(Ordering::Acquire) { + return Err(PyRuntimeError::new_err( + "cannot create a WinRT implementation while the interpreter is shutting down", + )); + } + callbacks.retain(|callback| callback.strong_count() != 0); + callbacks.push(Arc::downgrade(callback)); + Ok(()) + } + + fn shutdown(&self) { + self.stopping.store(true, Ordering::Release); + let callbacks = { + let mut registry = self + .callbacks + .lock() + .unwrap_or_else(|error| error.into_inner()); + std::mem::take(&mut *registry) + }; + for callback in callbacks { + if let Some(callback) = callback.upgrade() { + callback.clear(); + } + } + } +} + +#[pyclass(frozen, name = "_DynWinRTImplementationRuntime")] +struct ImplementationRuntime(Arc); + +#[pymethods] +impl ImplementationRuntime { + fn shutdown(&self) { + self.0.shutdown(); + } +} + +struct CallbackCell { + // Exactly one Python reference is shared by the native callback and the GC + // visitor. The owner and shutdown registry hold only Weak references here. + callback: Mutex>>, + interpreter: Arc, +} + +impl CallbackCell { + fn clear(&self) { + let callback = self + .callback + .lock() + .unwrap_or_else(|error| error.into_inner()) + .take(); + // Decref may execute a handler's finalizer and reenter dispose(). + drop(callback); + } + + fn invoke( + &self, + interface_index: usize, + vtable_index: usize, + args: &[dynwinrt::WinRTValue], + ) -> windows::core::Result> { + if self.interpreter.stopping.load(Ordering::Acquire) { + return Err(closed_error()); + } + Python::try_attach(|py| { + if self.interpreter.stopping.load(Ordering::Acquire) { + return Err(closed_error()); + } + let callback = self + .callback + .lock() + .map_err(|_| Error::new(E_FAIL, "Python WinRT callback state is poisoned"))? + .as_ref() + .map(|callback| callback.clone_ref(py)) + .ok_or_else(closed_error)?; + let result = (|| -> PyResult> { + let inputs = args + .iter() + .map(|value| Py::new(py, DynWinRTValue(value.clone()))) + .collect::>>()?; + let inputs = PyList::new(py, inputs)?; + let outputs = callback.call1(py, (interface_index, vtable_index, inputs))?; + Ok(outputs + .extract::>(py)? + .into_iter() + .map(|value| value.0) + .collect()) + })(); + result.map_err(|error| { + let message = format!( + "Python WinRT implementation callback at interface {interface_index}, \ + slot {vtable_index}: {error}" + ); + error.write_unraisable(py, Some(callback.bind(py))); + Error::new(PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION, message) + }) + }) + .unwrap_or_else(|| Err(closed_error())) + } +} + +#[pyclass(weakref, module = "dynwinrt")] +pub struct DynWinRTImplementation { + native: Mutex>, + callback: Weak, + interpreter: Arc, +} + +struct NativeLease<'a> { + slot: &'a Mutex>, + value: Option, +} + +impl Drop for NativeLease<'_> { + fn drop(&mut self) { + let mut slot = self.slot.lock().unwrap_or_else(|error| error.into_inner()); + debug_assert!(slot.is_none()); + *slot = self.value.take(); + } +} + +impl DynWinRTImplementation { + fn with_native( + &self, + action: impl FnOnce(&mut WinRtImplementation) -> PyResult, + ) -> PyResult { + let value = self + .native + .lock() + .map_err(|_| PyRuntimeError::new_err("WinRT implementation owner state is poisoned"))? + .take() + .ok_or_else(|| { + PyRuntimeError::new_err("WinRT implementation owner has an active native operation") + })?; + let mut lease = NativeLease { + slot: &self.native, + value: Some(value), + }; + // Restore the controller even on unwind, without holding a binding + // state lock across native AddRef/Release, disconnection, or destruction. + action(lease.value.as_mut().expect("the lease owns the controller")) + } + + fn disconnect_native(&self, release: bool, only_if_unique: bool) -> PyResult<()> { + // Keep the cell alive until the controller is restored. Dropping the + // captured handler can then reenter this owner through a finalizer. + // An in-flight native callback retains its own root until it returns. + let callback = self.callback.upgrade(); + self.with_native(|native| { + if only_if_unique && !native.has_unique_native_reference() { + return Ok(()); + } + if release { + native.dispose().map_err(map_windows_error)?; + } else { + native.disconnect().map_err(map_windows_error)?; + } + Ok(()) + })?; + drop(callback); + Ok(()) + } +} + +#[pymethods] +impl DynWinRTImplementation { + #[staticmethod] + #[pyo3(signature = (interfaces, callback, runtime_class_name=None))] + fn create( + py: Python<'_>, + interfaces: Vec, + callback: Py, + runtime_class_name: Option<&str>, + ) -> PyResult { + // PyGILState attachment targets the main interpreter. Do not accept a + // subinterpreter-owned callable and later attach to the wrong one. + if unsafe { pyo3::ffi::PyInterpreterState_Get() != pyo3::ffi::PyInterpreterState_Main() } { + return Err(PyRuntimeError::new_err( + "WinRT interface implementations do not support Python subinterpreters", + )); + } + let module = py.import("dynwinrt.dynwinrt")?; + let runtime = module.getattr("_dynwinrt_implementation_runtime")?; + let interpreter = runtime + .extract::>()? + .0 + .clone(); + if interpreter.stopping.load(Ordering::Acquire) { + return Err(PyRuntimeError::new_err( + "cannot create a WinRT implementation while the interpreter is shutting down", + )); + } + let plan = WinRtImplementationPlan::new( + interfaces + .into_iter() + .map(|interface| interface.0) + .collect(), + WinRtThreadingPolicy::OwnerThread, + ) + .map_err(map_windows_error)?; + let callback = module + .getattr("_dynwinrt_checked_implementation_callback")? + .call1((callback,))? + .unbind(); + let callback = Arc::new(CallbackCell { + callback: Mutex::new(Some(wrap_python_callback_context(py, callback)?)), + interpreter: interpreter.clone(), + }); + let native_callback = callback.clone(); + let native_callback: WinRtImplementationCallback = + Arc::new(move |interface, slot, args| native_callback.invoke(interface, slot, args)); + let native = WinRtImplementation::new(plan, native_callback, runtime_class_name) + .map_err(map_windows_error)?; + interpreter.register(&callback)?; + Ok(Self { + native: Mutex::new(Some(native)), + callback: Arc::downgrade(&callback), + interpreter, + }) + } + + fn to_value(&self) -> PyResult { + self.with_native(|native| { + native + .to_value() + .map(DynWinRTValue) + .map_err(map_windows_error) + }) + } + + /// Drop this owner's native reference without disconnecting retained views. + fn release(&self) -> PyResult<()> { + let callback = self.callback.upgrade(); + self.with_native(|native| { + native.release(); + Ok(()) + })?; + drop(callback); + Ok(()) + } + + /// Disconnect every native view and release this owner's reference. + fn dispose(&self) -> PyResult<()> { + self.disconnect_native(true, false) + } + + fn disconnect(&self) -> PyResult<()> { + self.disconnect_native(false, false) + } + + #[getter] + fn is_closed(&self) -> PyResult { + Ok(self.interpreter.stopping.load(Ordering::Acquire) + || self.with_native(|native| Ok(native.is_closed()))?) + } + + fn take_error(&self) -> PyResult> { + self.with_native(|native| Ok(native.take_error())) + } + + fn __enter__(slf: PyRef<'_, Self>) -> PyResult> { + if slf.is_closed()? { + return Err(map_windows_error(closed_error())); + } + // A released owner may still have live native aliases. + slf.with_native(|native| native.to_value().map_err(map_windows_error))?; + Ok(slf) + } + + fn __exit__( + &self, + _exc_type: &Bound<'_, PyAny>, + _exc_value: &Bound<'_, PyAny>, + _traceback: &Bound<'_, PyAny>, + ) -> PyResult { + self.dispose()?; + Ok(false) + } + + fn __traverse__(&self, visit: PyVisit<'_>) -> Result<(), PyTraverseError> { + // Native aliases are external roots, not Python-owned graph edges. + // try_lock also avoids GC deadlocks during reentrant native cleanup. + if let Ok(slot) = self.native.try_lock() { + if let Some(native) = slot.as_ref() { + if native.has_unique_native_reference() { + if let Some(callback) = self.callback.upgrade() { + if let Ok(captured) = callback.callback.try_lock() { + if let Some(captured) = captured.as_ref() { + visit.call(captured)?; + } + } + } + } + } + } + Ok(()) + } + + fn __clear__(slf: &Bound<'_, Self>) { + // Recheck: a finalizer may have retained a native alias since traverse. + let result = (|| -> PyResult<()> { slf.try_borrow()?.disconnect_native(true, true) })(); + if let Err(error) = result { + error.write_unraisable(slf.py(), Some(slf.as_any())); + } + } +} + +pub(crate) fn init(module: &Bound<'_, PyModule>) -> PyResult<()> { + module.add_class::()?; + module.add_class::()?; + module.add_class::()?; + let runtime = Py::new( + module.py(), + ImplementationRuntime(Arc::new(InterpreterState::default())), + )?; + module.py().import("atexit")?.call_method1( + "register", + (runtime.bind(module.py()).getattr("shutdown")?,), + )?; + module.add("_dynwinrt_implementation_runtime", runtime)?; + let source = CString::new(include_str!("implementation.py")).expect("Python source has no NUL"); + module.py().run(&source, Some(&module.dict()), None)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::{Barrier, mpsc}; + use std::time::Duration; + + use pyo3::types::PyDict; + use windows::core::Interface; + + use super::*; + + #[test] + fn gc_cleanup_reports_unexpected_owner_errors_as_unraisable() { + fn assert_send_sync() {} + assert_send_sync::(); + + let _serial = crate::errors::UNRAISABLE_HOOK_TEST_LOCK.lock().unwrap(); + Python::initialize(); + Python::attach(|py| { + let table = dynwinrt::MetadataTable::new(); + let plan = WinRtImplementationPlan::new( + vec![WinRtInterfaceDefinition { + name: "Windows.Foundation.IClosable".into(), + interface_type: table.interface(windows::Foundation::IClosable::IID), + required_iids: vec![], + methods: vec![WinRtMethodDefinition { + name: "Close".into(), + vtable_index: 6, + signature: dynwinrt::MethodSignature::new(&table), + }], + }], + WinRtThreadingPolicy::OwnerThread, + ) + .unwrap(); + let native = + WinRtImplementation::new(plan, Arc::new(|_, _, _| Ok(vec![])), None).unwrap(); + let owner = Bound::new( + py, + DynWinRTImplementation { + native: Mutex::new(Some(native)), + callback: Weak::new(), + interpreter: Arc::new(InterpreterState::default()), + }, + ) + .unwrap(); + let poisoned = catch_unwind(AssertUnwindSafe(|| { + let owner = owner.borrow(); + let _guard = owner.native.lock().unwrap(); + panic!("inject a poisoned owner lock"); + })); + assert!(poisoned.is_err()); + + let captured = PyList::empty(py); + let sys = py.import("sys").unwrap(); + let previous_hook = sys.getattr("unraisablehook").unwrap(); + sys.setattr("unraisablehook", captured.getattr("append").unwrap()) + .unwrap(); + DynWinRTImplementation::__clear__(&owner); + sys.setattr("unraisablehook", previous_hook).unwrap(); + + assert_eq!(captured.len(), 1); + let record = captured.get_item(0).unwrap(); + let error = record.getattr("exc_value").unwrap(); + assert!(error.is_instance_of::()); + assert!(error.str().unwrap().to_str().unwrap().contains("poisoned")); + assert!(record.getattr("object").unwrap().is(&owner)); + + owner.borrow().native.clear_poison(); + owner.borrow().dispose().unwrap(); + }); + } + + #[test] + fn dispose_preserves_already_dispatched_callback_waiting_to_enter_python() { + Python::initialize(); + Python::attach(|py| { + let table = dynwinrt::MetadataTable::new(); + let iid = windows::Foundation::IStringable::IID; + let signature = dynwinrt::MethodSignature::new(&table).add_out(table.hstring()); + let typ = table + .register_interface("Windows.Foundation.IStringable", iid) + .add_method("ToString", signature.clone()); + let plan = WinRtImplementationPlan::new( + vec![WinRtInterfaceDefinition { + name: "Windows.Foundation.IStringable".into(), + interface_type: typ.clone(), + required_iids: vec![], + methods: vec![WinRtMethodDefinition { + name: "ToString".into(), + vtable_index: 6, + signature, + }], + }], + WinRtThreadingPolicy::OwnerThread, + ) + .unwrap(); + let globals = PyDict::new(py); + globals + .set_item( + "result", + DynWinRTValue(dynwinrt::WinRTValue::HString("finished".into())), + ) + .unwrap(); + let function = py + .eval(c"lambda *args: [result]", Some(&globals), None) + .unwrap(); + let function_ref = py + .import("weakref") + .unwrap() + .call_method1("ref", (&function,)) + .unwrap(); + let interpreter = Arc::new(InterpreterState::default()); + let cell = Arc::new(CallbackCell { + callback: Mutex::new(Some(function.unbind())), + interpreter: interpreter.clone(), + }); + let (entered, receiver) = mpsc::channel(); + let proceed = Arc::new(Barrier::new(2)); + let callback_cell = cell.clone(); + let callback_proceed = proceed.clone(); + let native = WinRtImplementation::new( + plan, + Arc::new(move |interface, slot, args| { + entered.send(()).unwrap(); + callback_proceed.wait(); + callback_cell.invoke(interface, slot, args) + }), + None, + ) + .unwrap(); + let owner = Bound::new( + py, + DynWinRTImplementation { + native: Mutex::new(Some(native)), + callback: Arc::downgrade(&cell), + interpreter, + }, + ) + .unwrap(); + drop(cell); + let view = owner + .call_method0("to_value") + .unwrap() + .call_method1("cast", (WinGUID(iid),)) + .unwrap(); + let method = Bound::new(py, DynWinRTType(typ)) + .unwrap() + .call_method1("method", (6,)) + .unwrap(); + let worker_owner = owner.clone().unbind(); + let worker = std::thread::spawn(move || { + receiver.recv_timeout(Duration::from_secs(10)).unwrap(); + Python::attach(|py| { + worker_owner.bind(py).call_method0("dispose").unwrap(); + }); + proceed.wait(); + }); + + let result = method.call_method1("invoke_detached", (&view, PyList::empty(py))); + py.detach(|| worker.join()).unwrap(); + let result = result.unwrap(); + assert_eq!( + result + .call_method0("to_string") + .unwrap() + .extract::() + .unwrap(), + "finished" + ); + assert!(owner.borrow().is_closed().unwrap()); + assert!(function_ref.call0().unwrap().is_none()); + let error = method + .call_method1("invoke", (&view, PyList::empty(py))) + .unwrap_err(); + assert_eq!( + error + .value(py) + .getattr("winerror") + .unwrap() + .extract::() + .unwrap(), + RO_E_CLOSED.0 + ); + view.call_method0("release").unwrap(); + }); + } +} diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index bb9092c4..034b0a9b 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -4,7 +4,9 @@ use pyo3::prelude::*; mod async_runtime; +mod delegate_method; mod errors; +mod implementation; mod runtime; mod values; @@ -560,12 +562,14 @@ def _dynwinrt_dispatch_progress(dispatch_state, value): m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; + super::implementation::init(m)?; m.py().run( c" _Coroutine.register(_DynWinRTAsync) @@ -598,6 +602,7 @@ for _name in ( 'WinRTAsyncWithProgress', 'WinRTCoroutine', 'WinRTCoroutineWithProgress', + 'DynWinRTImplementationDescriptor', 'ProjectedLifetimeScope', 'projected_lifetime_scope', 'project_as', diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 091b4d90..b48ad59b 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -15,7 +15,10 @@ use crate::errors::{map_dynwinrt_error, map_dynwinrt_error_with_context, map_win static TABLE: std::sync::LazyLock> = std::sync::LazyLock::new(|| dynwinrt::MetadataTable::new()); -fn wrap_python_callback_context(py: Python<'_>, callback: Py) -> PyResult> { +pub(crate) fn wrap_python_callback_context( + py: Python<'_>, + callback: Py, +) -> PyResult> { Ok(py .import("dynwinrt.dynwinrt")? .getattr("_dynwinrt_wrap_delegate_callback")? @@ -1257,6 +1260,10 @@ impl DynWinRTValue { DynWinRTValue(dynwinrt::WinRTValue::I32(value)) } #[staticmethod] + fn from_hresult(value: i32) -> DynWinRTValue { + DynWinRTValue(dynwinrt::WinRTValue::HResult(windows::core::HRESULT(value))) + } + #[staticmethod] fn from_u32(value: u32) -> DynWinRTValue { DynWinRTValue(dynwinrt::WinRTValue::U32(value)) } @@ -1603,6 +1610,16 @@ impl DynWinRTValue { .map_err(map_dynwinrt_error) } + /// Invoke metadata-described Invoke on an IUnknown-rooted WinRT delegate. + fn invoke_delegate( + slf: &Bound<'_, Self>, + iid: &WinGUID, + signature: &DynWinRTMethodSig, + args: Vec, + ) -> PyResult> { + crate::delegate_method::DynWinRTDelegateMethod::create(iid, signature)?.invoke(slf, args) + } + /// Call IActivationFactory::ActivateInstance (vtable[6]) to create a default instance. /// Use on the result of activation_factory() for classes with parameterless constructors. fn activate(&self) -> PyResult { @@ -2259,7 +2276,7 @@ impl DynWinRTStruct { #[pyclass] pub struct DynWinRtDelegate(dynwinrt::WinRTValue); -const PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION: windows::core::HRESULT = +pub(crate) const PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION: windows::core::HRESULT = windows::core::HRESULT(0xA0EE4005_u32 as i32); fn create_python_delegate( @@ -2546,6 +2563,7 @@ mod tests { #[test] fn python_delegate_reports_unraisable_callback_errors() { + let _serial = crate::errors::UNRAISABLE_HOOK_TEST_LOCK.lock().unwrap(); Python::initialize(); Python::attach(|py| { let locals = PyDict::new(py); diff --git a/bindings/py/tests/test_implementation.py b/bindings/py/tests/test_implementation.py new file mode 100644 index 00000000..3f4ac603 --- /dev/null +++ b/bindings/py/tests/test_implementation.py @@ -0,0 +1,1292 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Standalone WinRT implementations, called through real native vtables.""" + +from contextlib import contextmanager +from contextvars import ContextVar +import gc +from pathlib import Path +import subprocess +import sys +import textwrap +import threading +from uuid import uuid4 +import warnings +import weakref + +import pytest + +from dynwinrt import ( + DynWinRTArray, + DynWinRTDelegateMethod, + DynWinRTImplementation, + DynWinRTImplementationDescriptor, + DynWinRTImplementationMethod, + DynWinRTInterfacePlan, + DynWinRTMethodSig, + DynWinRTStruct, + DynWinRTType, + DynWinRTValue, + DynWinRtDelegate, + RoApartment, + WinGUID, +) + + +STRINGABLE_IID = WinGUID.parse("96369f54-8eb6-48f0-abce-c1b211e627c3") +CLOSABLE_IID = WinGUID.parse("30d5a829-7fa4-4026-83bb-d75bae4ea99e") +BACKGROUND_TASK_IID = WinGUID.parse("7d13d534-fd12-43ce-8c22-ea1ff13c06df") +BACKGROUND_INSTANCE_IID = WinGUID.parse("865bda7a-21d8-4573-8f32-928a1b0641f6") +CANCELED_HANDLER_IID = WinGUID.parse("a6c4bac0-51f8-4c57-ac3f-156dd1680c4f") +PYTHON_EXCEPTION = -1594998779 # 0xA0EE4005 +CLOSED = -2147483629 # RO_E_CLOSED +INVALID_ARGUMENT = -2147024809 +WRONG_THREAD = -2147417842 # RPC_E_WRONG_THREAD + + +@pytest.fixture(scope="module", autouse=True) +def apartment(): + with RoApartment(1): + yield + + +def _interface(name, methods, *, iid=None, required_iids=()): + iid = iid or WinGUID.parse(str(uuid4())) + typ = DynWinRTType.register_interface(name, iid) + definitions = [] + for index, (method_name, signature) in enumerate(methods, 6): + typ = typ.add_method(method_name, signature) + definitions.append(DynWinRTImplementationMethod(method_name, index, signature)) + plan = DynWinRTInterfacePlan.create(name, typ, definitions, required_iids) + return plan, typ + + +def _stringable(): + return _interface( + "Windows.Foundation.IStringable", + [("ToString", DynWinRTMethodSig().add_out(DynWinRTType.hstring()))], + iid=STRINGABLE_IID, + ) + + +def _closable(): + return _interface( + "Windows.Foundation.IClosable", + [("Close", DynWinRTMethodSig())], + iid=CLOSABLE_IID, + ) + + +def _view(owner, typ): + value = owner.to_value() + try: + return value.cast(typ.iid()) + finally: + value.release() + + +def test_stringable_closable_descriptors_and_owned_views(): + string_plan, string_type = _stringable() + close_plan, close_type = _closable() + calls = [] + + def stringify(slot, args): + calls.append(("string", slot, args)) + return [DynWinRTValue.from_hstring("Python \0 WinRT \U0001f600")] + + def close(slot, args): + calls.append(("close", slot, args)) + return [] + + descriptors = ( + DynWinRTImplementationDescriptor(string_plan, stringify), + DynWinRTImplementationDescriptor(close_plan, close), + ) + with DynWinRTImplementation.create( + tuple(descriptor.plan for descriptor in descriptors), + lambda interface, slot, args: descriptors[interface].dispatch(slot, args), + "DynWinRT.Tests.PythonStandalone", + ) as owner: + string_view = _view(owner, string_type) + close_view = _view(owner, close_type) + try: + assert string_type.method(6).get_string(string_view) == "Python \0 WinRT \U0001f600" + assert close_type.method(6).invoke_all(close_view, []) == [] + assert string_view.identity_raw() == close_view.identity_raw() + assert string_view.as_raw() != close_view.as_raw() + assert calls == [("string", 6, []), ("close", 6, [])] + assert not owner.is_closed + assert owner.take_error() is None + finally: + string_view.release() + close_view.release() + assert owner.is_closed + owner.dispose() + + +def test_background_task_receives_retained_borrowed_instance(): + registration_type = DynWinRTType.runtime_class( + "Windows.ApplicationModel.Background.BackgroundTaskRegistration", + DynWinRTType.interface(WinGUID.parse("10654cc2-a26e-43bf-8c12-1fb40dbfbfa0")), + ) + deferral_type = DynWinRTType.runtime_class( + "Windows.ApplicationModel.Background.BackgroundTaskDeferral", + DynWinRTType.interface(WinGUID.parse("93cc156d-af27-4dd3-846e-24ee40cadd25")), + ) + # Every IBackgroundTaskInstance slot has its SDK ABI, including unused ones. + instance_plan, instance_type = _interface( + "Windows.ApplicationModel.Background.IBackgroundTaskInstance", + [ + ("get_InstanceId", DynWinRTMethodSig().add_out(DynWinRTType.guid_type())), + ("get_Task", DynWinRTMethodSig().add_out(registration_type)), + ("get_Progress", DynWinRTMethodSig().add_out(DynWinRTType.u32_type())), + ("put_Progress", DynWinRTMethodSig().add_in(DynWinRTType.u32_type())), + ("get_TriggerDetails", DynWinRTMethodSig().add_out(DynWinRTType.object())), + ("add_Canceled", DynWinRTMethodSig() + .add_in(DynWinRTType.delegate(CANCELED_HANDLER_IID)) + .add_out(DynWinRTType.i64_type())), + ("remove_Canceled", DynWinRTMethodSig().add_in(DynWinRTType.i64_type())), + ("get_SuspendedCount", DynWinRTMethodSig().add_out(DynWinRTType.u32_type())), + ("GetDeferral", DynWinRTMethodSig().add_out(deferral_type)), + ], + iid=BACKGROUND_INSTANCE_IID, + ) + progress = [0] + instance_id = WinGUID.parse(str(uuid4())) + + def instance_dispatch(interface, slot, args): + assert interface == 0 + if slot == 6: + return [DynWinRTValue.from_guid(instance_id)] + if slot == 8: + return [DynWinRTValue.from_u32(progress[0])] + if slot == 9: + progress[0] = args[0].to_u32() + return [] + raise NotImplementedError("fixture does not register tasks or acquire OS deferrals") + + task_plan, task_type = _interface( + "Windows.ApplicationModel.Background.IBackgroundTask", + [("Run", DynWinRTMethodSig().add_in(instance_type))], + iid=BACKGROUND_TASK_IID, + ) + retained = [] + + def run(_interface, slot, args): + assert slot == 6 and len(args) == 1 + assert instance_type.method(6).invoke(args[0], []).to_guid().to_string() == instance_id.to_string() + instance_type.method(9).invoke_all(args[0], [DynWinRTValue.from_u32(73)]) + retained.append(args[0]) + return [] + + with DynWinRTImplementation.create([instance_plan], instance_dispatch) as instance_owner: + with DynWinRTImplementation.create([task_plan], run) as task_owner: + instance = _view(instance_owner, instance_type) + task = _view(task_owner, task_type) + try: + assert task_type.method(6).invoke_all(task, [instance]) == [] + instance.release() + instance_owner.release() + assert progress == [73] + assert instance_type.method(8).invoke(retained[0], []).to_u32() == 73 + finally: + instance.release() + task.release() + for value in retained: + value.release() + retained.clear() + + +SCALARS = { + "bool": ("bool_type", "from_bool", [True, False], "to_bool"), + "i8": ("i8_type", "from_i8", [-128, 127], "to_int"), + "u8": ("u8_type", "from_u8", [0, 255], "to_int"), + "i16": ("i16_type", "from_i16", [-32768, 32767], "to_int"), + "u16": ("u16_type", "from_u16", [0, 65535], "to_int"), + "char16": ("char16", "from_u16", [0xD834, 65], "to_int"), + "i32": ("i32_type", "from_i32", [-(2**31), 2**31 - 1], "to_int"), + "u32": ("u32_type", "from_u32", [0, 2**32 - 1], "to_int"), + "i64": ("i64_type", "from_i64", [-(2**63), 2**63 - 1], "to_i64"), + "u64": ("u64_type", "from_u64", [0, 2**64 - 1], "to_u64"), + "f32": ("f32_type", "from_f32", [1.25, -2.5], "to_f64"), + "f64": ("f64_type", "from_f64", [1.25e100, -2.5e-100], "to_f64"), + "hresult": ("hresult", "from_hresult", [-2147467259, 0], "to_number"), + "hstring": ("hstring", "from_hstring", ["hello\0world", "\U0001f600"], "to_string"), +} +SHAPES = (*SCALARS, "guid", "enum", "struct", "object", "interface", + "runtime_class", "delegate", "generic", "async") + + +@contextmanager +def _values(shape): + owners = [] + try: + if shape in SCALARS: + type_name, constructor, values, reader = SCALARS[shape] + typ = getattr(DynWinRTType, type_name)() + values = [getattr(DynWinRTValue, constructor)(value) for value in values] + normalize = lambda value: getattr(value, reader)() + elif shape == "guid": + typ = DynWinRTType.guid_type() + values = [DynWinRTValue.from_guid(WinGUID.parse(str(uuid4()))) for _ in range(2)] + normalize = lambda value: value.to_guid().to_string() + elif shape == "enum": + typ = DynWinRTType.enum_type(f"Tests.Enum{uuid4().hex}", ["Low", "High"], [-1, 42]) + values = [DynWinRTValue.enum_value(typ, value) for value in (-1, 42)] + normalize = lambda value: value.to_number() + elif shape == "struct": + inner_type = DynWinRTType.struct_type( + f"Tests.Inner{uuid4().hex}", [DynWinRTType.f32_type(), DynWinRTType.i64_type()] + ) + typ = DynWinRTType.struct_type( + f"Tests.Packet{uuid4().hex}", + [DynWinRTType.hstring(), DynWinRTType.guid_type(), inner_type], + ) + values = [] + for index in range(2): + inner = DynWinRTStruct.create(inner_type) + inner.set_f32(0, 1.25 + index) + inner.set_i64(1, -(2**60) + index) + packet = DynWinRTStruct.create(typ) + packet.set_hstring(0, f"owned\0string {index}") + packet.set_guid(1, WinGUID.parse(str(uuid4()))) + packet.set_struct(2, inner) + values.append(packet.to_value()) + + def normalize(value): + packet = value.as_struct() + inner = packet.get_struct(2) + return (packet.get_hstring(0), packet.get_guid(1).to_string(), + inner.get_f32(0), inner.get_i64(1)) + elif shape in ("object", "interface", "runtime_class"): + plan, interface_type = _stringable() + owner = DynWinRTImplementation.create( + [plan], lambda *_args: [DynWinRTValue.from_hstring("retained")] + ) + owners.append(owner) + typ = { + "object": DynWinRTType.object(), + "interface": interface_type, + "runtime_class": DynWinRTType.runtime_class("Tests.Stringable", interface_type), + }[shape] + values = [owner.to_value(), DynWinRTValue.null_value()] + normalize = lambda value: None if value.is_null() else value.identity_raw() + elif shape == "delegate": + typ = DynWinRTType.delegate(CANCELED_HANDLER_IID) + delegate = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, + [DynWinRTType.interface(BACKGROUND_INSTANCE_IID), DynWinRTType.i32_type()], + lambda *_args: None, + ) + values = [delegate.to_value(), DynWinRTValue.null_value()] + normalize = lambda value: None if value.is_null() else value.identity_raw() + elif shape == "generic": + typ = DynWinRTType.parameterized( + WinGUID.parse("913337e9-11a1-4345-a3a2-4e7f956e222d"), + [DynWinRTType.i32_type()], + ) + values = [ + DynWinRTValue.create_vector([DynWinRTValue.from_i32(12)], DynWinRTType.i32_type()), + DynWinRTValue.null_value(), + ] + normalize = lambda value: None if value.is_null() else value.identity_raw() + elif shape == "async": + file_type = DynWinRTType.runtime_class( + "Windows.Storage.StorageFile", + DynWinRTType.interface(WinGUID.parse("fa3f6186-4214-428c-a64c-14c9ac7315ea")), + ) + typ = DynWinRTType.i_async_operation(file_type) + statics_iid = WinGUID.parse("5984c710-daf2-43c8-8bb4-a4d3eacfd03f") + statics = DynWinRTType.register_interface("IStorageFileStatics", statics_iid) + statics = statics.add_method( + "GetFileFromPathAsync", + DynWinRTMethodSig().add_in(DynWinRTType.hstring()).add_out(typ), + ) + factory = DynWinRTValue.activation_factory("Windows.Storage.StorageFile") + factory_view = factory.cast(statics_iid) + try: + operation = statics.method(6).invoke( + factory_view, [DynWinRTValue.from_hstring(str(Path(__file__).resolve()))] + ) + finally: + factory_view.release() + factory.release() + operation.wait().release() + values = [operation, DynWinRTValue.null_value()] + + def normalize(value): + if value.is_null(): + return None + result = value.wait() + try: + return not result.is_null() + finally: + result.release() + else: + raise AssertionError(shape) + yield typ, values, normalize + finally: + for owner in owners: + owner.dispose() + + +@pytest.mark.parametrize("shape", SHAPES) +def test_native_value_passthrough(shape): + with _values(shape) as (typ, values, normalize): + plan, interface_type = _interface( + f"Tests.Echo{uuid4().hex}", + [("Echo", DynWinRTMethodSig().add_in(typ).add_out(typ))], + ) + received = [] + + def dispatch(interface, slot, args): + assert (interface, slot) == (0, 6) + received.append(normalize(args[0])) + return [args[0]] + + with DynWinRTImplementation.create([plan], dispatch) as owner: + view = _view(owner, interface_type) + try: + expected = [normalize(value) for value in values] + actual = [ + normalize(interface_type.method(6).invoke(view, [value])) + for value in values + ] + assert actual == expected + assert received == expected + finally: + view.release() + + +@pytest.mark.parametrize("shape", SHAPES) +@pytest.mark.parametrize("direction", ["pass", "receive", "fill"]) +def test_native_arrays(shape, direction): + with _values(shape) as (typ, values, normalize): + array_type = DynWinRTType.array_type(typ) + signature = DynWinRTMethodSig() + if direction == "pass": + signature = signature.add_in(array_type).add_out(array_type) + elif direction == "receive": + signature = signature.add_out(array_type) + else: + signature = signature.add_out_fill(array_type) + plan, interface_type = _interface( + f"Tests.Arrays{uuid4().hex}", [("Transform", signature)] + ) + expected = [normalize(value) for value in values] + + def dispatch(_interface, _slot, args): + if direction == "pass": + assert [normalize(value) for value in args[0].as_array().to_values()] == expected + return [args[0]] + if direction == "fill": + assert args[0].to_u32() == len(values) + else: + assert args == [] + return [DynWinRTArray.from_values(values, typ).to_value()] + + with DynWinRTImplementation.create([plan], dispatch) as owner: + view = _view(owner, interface_type) + try: + if direction == "pass": + args = [DynWinRTArray.from_values(values, typ).to_value()] + elif direction == "fill": + args = [DynWinRTArray.from_values(values, typ).to_value()] + else: + args = [] + result = interface_type.method(6).invoke(view, args) + assert [normalize(value) for value in result.as_array().to_values()] == expected + finally: + view.release() + + +@pytest.mark.parametrize("direction", ["pass", "receive", "fill"]) +def test_empty_arrays_and_output_order(direction): + element_type = DynWinRTType.hstring() + array_type = DynWinRTType.array_type(element_type) + signature = DynWinRTMethodSig().add_in(DynWinRTType.i32_type()) + if direction == "pass": + signature = signature.add_in(array_type).add_out(array_type) + elif direction == "receive": + signature = signature.add_out(array_type) + else: + signature = signature.add_out_fill(array_type) + signature = signature.add_in(DynWinRTType.hstring()).add_out(DynWinRTType.guid_type()) + signature = signature.add_out(DynWinRTType.i64_type()) + plan, typ = _interface(f"Tests.OutputOrder{uuid4().hex}", [("Multiple", signature)]) + guid = WinGUID.parse(str(uuid4())) + + def dispatch(_interface, _slot, args): + assert args[0].to_int() == 17 + assert args[-1].to_string() == "last input" + if direction == "pass": + assert len(args[1].as_array()) == 0 + elif direction == "fill": + assert args[1].to_u32() == 0 + else: + assert len(args) == 2 + return [DynWinRTArray.from_values([], element_type).to_value(), + DynWinRTValue.from_guid(guid), DynWinRTValue.from_i64(2**60)] + + with DynWinRTImplementation.create([plan], dispatch) as owner: + view = _view(owner, typ) + try: + args = [DynWinRTValue.from_i32(17)] + if direction == "pass": + args.append(DynWinRTArray.from_values([], element_type).to_value()) + elif direction == "fill": + args.append(DynWinRTArray.from_values([], element_type).to_value()) + args.append(DynWinRTValue.from_hstring("last input")) + outputs = typ.method(6).invoke_all(view, args) + assert len(outputs) == 3 + assert len(outputs[0].as_array()) == 0 + assert outputs[1].to_guid().to_string() == guid.to_string() + assert outputs[2].to_i64() == 2**60 + finally: + view.release() + + +def test_properties_and_event_subscription_signatures(): + token_type = DynWinRTType.struct_type( + "Windows.Foundation.EventRegistrationToken", [DynWinRTType.i64_type()] + ) + token = DynWinRTStruct.create(token_type) + token.set_i64(0, 101) + plan, typ = _interface( + f"Tests.PropertiesAndEvents{uuid4().hex}", + [ + ("get_Count", DynWinRTMethodSig().add_out(DynWinRTType.i32_type())), + ("put_Count", DynWinRTMethodSig().add_in(DynWinRTType.i32_type())), + ("add_Canceled", DynWinRTMethodSig() + .add_in(DynWinRTType.delegate(CANCELED_HANDLER_IID)).add_out(token_type)), + ("remove_Canceled", DynWinRTMethodSig().add_in(token_type)), + ], + ) + count = [0] + listeners = [] + + def dispatch(_interface, slot, args): + if slot == 6: + return [DynWinRTValue.from_i32(count[0])] + if slot == 7: + count[0] = args[0].to_int() + return [] + if slot == 8: + listeners.append(args[0]) + return [token.to_value()] + assert slot == 9 and args[0].as_struct().get_i64(0) == 101 + listeners.pop().release() + return [] + + delegate = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, + [DynWinRTType.interface(BACKGROUND_INSTANCE_IID), DynWinRTType.i32_type()], + lambda *_args: None, + ) + with DynWinRTImplementation.create([plan], dispatch) as owner: + view = _view(owner, typ) + try: + typ.method(7).invoke_all(view, [DynWinRTValue.from_i32(42)]) + assert typ.method(6).get_i32(view) == 42 + result = typ.method(8).invoke(view, [delegate.to_value()]) + assert result.as_struct().get_i64(0) == 101 + assert len(listeners) == 1 + typ.method(9).invoke_all(view, [result]) + assert listeners == [] + finally: + view.release() + + +def _canceled_delegate_types(): + return [ + DynWinRTType.interface(BACKGROUND_INSTANCE_IID), + DynWinRTType.enum_type( + "Windows.ApplicationModel.Background.BackgroundTaskCancellationReason" + ), + ] + + +def _canceled_delegate_signature(): + signature = DynWinRTMethodSig() + for typ in _canceled_delegate_types(): + signature = signature.add_in(typ) + return signature + + +@pytest.fixture(params=["convenience", "cached"]) +def invoke_canceled_delegate(request): + signature = _canceled_delegate_signature() + if request.param == "cached": + return DynWinRTDelegateMethod.create(CANCELED_HANDLER_IID, signature).invoke + return lambda value, args: value.invoke_delegate(CANCELED_HANDLER_IID, signature, args) + + +def test_implementation_handler_invokes_and_retains_incoming_delegate(invoke_canceled_delegate): + plan, typ = _interface( + f"Tests.DelegateInvocation{uuid4().hex}", + [("Subscribe", DynWinRTMethodSig() + .add_in(DynWinRTType.delegate(CANCELED_HANDLER_IID)))], + ) + observed = [] + retained = [] + + def canceled(sender, reason): + assert sender.is_null() + observed.append(reason.to_number()) + + def dispatch(_interface, _slot, args): + retained.append(args[0]) + return invoke_canceled_delegate( + args[0], + [DynWinRTValue.null_value(), DynWinRTValue.from_i32(3)], + ) + + delegate_value = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, _canceled_delegate_types(), canceled + ).to_value() + with DynWinRTImplementation.create([plan], dispatch) as owner: + view = _view(owner, typ) + try: + assert typ.method(6).invoke_all(view, [delegate_value]) == [] + delegate_value.release() + assert invoke_canceled_delegate( + retained[0], + [DynWinRTValue.null_value(), DynWinRTValue.from_i32(4)], + ) == [] + assert observed == [3, 4] + finally: + delegate_value.release() + view.release() + for value in retained: + value.release() + retained.clear() + + +def test_delegate_invocation_pins_value_across_reentrant_release(invoke_canceled_delegate): + holder = {} + called = [] + + def canceled(_sender, reason): + holder["value"].release() + called.append(reason.to_number()) + + holder["value"] = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, _canceled_delegate_types(), canceled + ).to_value() + assert invoke_canceled_delegate( + holder["value"], + [DynWinRTValue.null_value(), DynWinRTValue.from_i32(5)], + ) == [] + assert called == [5] + assert holder["value"].is_null() + + +def test_delegate_invocation_errors_propagate(monkeypatch, invoke_canceled_delegate): + errors = [] + monkeypatch.setattr(sys, "unraisablehook", errors.append) + + def canceled(_sender, _reason): + raise ValueError("native delegate callback failed") + + value = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, _canceled_delegate_types(), canceled + ).to_value() + try: + with pytest.raises(OSError) as caught: + invoke_canceled_delegate( + value, + [DynWinRTValue.null_value(), DynWinRTValue.from_i32(6)], + ) + assert caught.value.winerror == PYTHON_EXCEPTION + assert len(errors) == 1 + assert isinstance(errors[0].exc_value, ValueError) + for iid in ( + "00000000-0000-0000-0000-000000000000", + "00000000-0000-0000-c000-000000000046", + "af86e2e0-b12d-4c6a-9c5a-d7aa65101e90", + ): + with pytest.raises(TypeError, match="delegate IID"): + value.invoke_delegate(WinGUID.parse(iid), _canceled_delegate_signature(), []) + with pytest.raises(TypeError, match="delegate IID"): + DynWinRTDelegateMethod.create(WinGUID.parse(iid), _canceled_delegate_signature()) + finally: + value.release() + errors.clear() + + +def test_failed_delegate_query_releases_temporary_native_references(invoke_canceled_delegate): + owner, owner_ref, handler_ref, typ = _owner_cycle() + value = _view(owner, typ) + with pytest.raises(OSError) as caught: + invoke_canceled_delegate(value, []) + assert caught.value.winerror == -2147467262 # E_NOINTERFACE + assert typ.method(6).invoke(value, []).to_string() == "cycle" + value.release() + del caught, value, owner + gc.collect() + assert owner_ref() is None and handler_ref() is None + + +def test_cached_delegate_method_reuses_metadata_without_retaining_targets(): + signature = _canceled_delegate_signature() + method = DynWinRTDelegateMethod.create(CANCELED_HANDLER_IID, signature) + del signature + observed = [] + + class Handler: + def __init__(self, name): + self.name = name + + def canceled(self, sender, reason): + assert sender.is_null() + observed.append((self.name, reason.to_number())) + + for name in ("first", "second"): + handler = Handler(name) + reference = weakref.ref(handler) + value = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, _canceled_delegate_types(), handler.canceled + ).to_value() + del handler + try: + assert method.invoke( + value, [DynWinRTValue.null_value(), DynWinRTValue.from_i32(7)] + ) == [] + with pytest.raises(OSError): + method.invoke(value, []) + finally: + value.release() + assert reference() is None + assert observed == [("first", 7), ("second", 7)] + with pytest.raises(RuntimeError): + method.invoke(DynWinRTValue.null_value(), []) + + +def test_cached_delegate_method_shares_prepared_cif_across_python_threads(): + method = DynWinRTDelegateMethod.create( + CANCELED_HANDLER_IID, _canceled_delegate_signature() + ) + barrier = threading.Barrier(2) + observed = [] + errors = [] + + def run(code): + try: + def canceled(sender, reason): + assert sender.is_null() + barrier.wait(timeout=10) + observed.append(reason.to_number()) + assert reason.to_number() == code + + value = DynWinRtDelegate.create( + CANCELED_HANDLER_IID, _canceled_delegate_types(), canceled + ).to_value() + try: + assert method.invoke( + value, [DynWinRTValue.null_value(), DynWinRTValue.from_i32(code)] + ) == [] + finally: + value.release() + except BaseException as error: + errors.append(f"{type(error).__name__}: {error}") + + threads = [threading.Thread(target=run, args=(code,), daemon=True) for code in (17, 29)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=15) + assert not thread.is_alive() + assert errors == [] + assert sorted(observed) == [17, 29] + + +def test_python_exceptions_reach_native_caller_and_unraisable_hook(monkeypatch): + plan, typ = _stringable() + errors = [] + monkeypatch.setattr(sys, "unraisablehook", errors.append) + + def fail(*_args): + raise ValueError("intentional callback failure") + + with DynWinRTImplementation.create([plan], fail) as owner: + view = _view(owner, typ) + try: + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == PYTHON_EXCEPTION + assert len(errors) == 1 + assert isinstance(errors[0].exc_value, ValueError) + assert "intentional callback failure" in owner.take_error() + assert owner.take_error() is None + finally: + view.release() + errors.clear() + + +@pytest.mark.parametrize("result", [None, (), ["not a value"], 12]) +def test_invalid_python_output_containers_fail(monkeypatch, result): + plan, typ = _stringable() + errors = [] + monkeypatch.setattr(sys, "unraisablehook", errors.append) + with DynWinRTImplementation.create([plan], lambda *_args: result) as owner: + view = _view(owner, typ) + try: + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == PYTHON_EXCEPTION + assert isinstance(errors[0].exc_value, TypeError) + assert "list of DynWinRTValue" in owner.take_error() + finally: + view.release() + errors.clear() + + +@pytest.mark.parametrize("result", [[], [DynWinRTValue.from_i32(1)], + [DynWinRTValue.from_hstring("one"), + DynWinRTValue.from_hstring("two")]]) +def test_native_output_shape_mismatch_fails(result): + plan, typ = _stringable() + with DynWinRTImplementation.create([plan], lambda *_args: result) as owner: + view = _view(owner, typ) + try: + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == INVALID_ARGUMENT + assert owner.take_error() + finally: + view.release() + + +def test_fill_array_capacity_must_match_exactly(): + array_type = DynWinRTType.array_type(DynWinRTType.i32_type()) + plan, typ = _interface( + f"Tests.BadFill{uuid4().hex}", [("Fill", DynWinRTMethodSig().add_out_fill(array_type))] + ) + with DynWinRTImplementation.create( + [plan], lambda *_args: [DynWinRTArray.from_i32_values([1]).to_value()] + ) as owner: + view = _view(owner, typ) + try: + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, [DynWinRTArray.from_i32_values([0, 0]).to_value()]) + assert caught.value.winerror == INVALID_ARGUMENT + assert owner.take_error() + finally: + view.release() + + +def test_plan_validation_and_immutable_definitions(): + signature = DynWinRTMethodSig().add_out(DynWinRTType.hstring()) + method = DynWinRTImplementationMethod("ToString", 6, signature) + methods = [method] + plan = DynWinRTInterfacePlan.create("IStringable", DynWinRTType.interface(STRINGABLE_IID), methods) + methods.clear() + assert plan.name == "IStringable" and len(plan.methods) == 1 + assert method.name == "ToString" and method.vtable_index == 6 + assert isinstance(method.signature, DynWinRTMethodSig) + with pytest.raises(AttributeError): + method.vtable_index = 9 + with pytest.raises(AttributeError): + plan.name = "changed" + for slot in (3, 7): + with pytest.raises(OSError): + DynWinRTInterfacePlan.create( + "BadSlots", plan.interface_type, + [DynWinRTImplementationMethod("Bad", slot, signature)], + ) + with pytest.raises(OSError): + DynWinRTInterfacePlan.create("BadRoot", DynWinRTType.object(), [method]) + with pytest.raises(OSError): + DynWinRTInterfacePlan.create( + "Generic", DynWinRTType.parameterized( + WinGUID.parse("913337e9-11a1-4345-a3a2-4e7f956e222d"), + [DynWinRTType.i32_type()], + ), [method], + ) + with pytest.raises(OSError): + DynWinRTInterfacePlan.create( + "NestedArray", DynWinRTType.interface(WinGUID.parse(str(uuid4()))), + [DynWinRTImplementationMethod("Bad", 6, DynWinRTMethodSig().add_in( + DynWinRTType.array_type(DynWinRTType.array_type(DynWinRTType.i32_type())) + ))], + ) + with pytest.raises(OSError): + DynWinRTImplementation.create([], lambda *_args: []) + with pytest.raises(OSError): + DynWinRTImplementation.create([plan, plan], lambda *_args: []) + + +def test_required_interfaces_are_validated_as_a_complete_set(): + close_plan, close_type = _closable() + string_plan, _ = _stringable() + required = DynWinRTInterfacePlan.create( + string_plan.name, string_plan.interface_type, string_plan.methods, (CLOSABLE_IID,) + ) + with pytest.raises(OSError, match="requires"): + DynWinRTImplementation.create([required], lambda *_args: []) + with DynWinRTImplementation.create( + [required, close_plan], + lambda interface, _slot, _args: [] if interface else [DynWinRTValue.from_hstring("valid")], + ) as owner: + view = _view(owner, close_type) + try: + assert close_type.method(6).invoke_all(view, []) == [] + finally: + view.release() + + +def test_async_callables_are_rejected_before_publication(): + plan, _ = _stringable() + + async def coroutine(*_args): + return [] + + async def async_generator(*_args): + yield [] + + class AsyncCallable: + async def __call__(self, *_args): + return [] + + for callback in (coroutine, async_generator, AsyncCallable()): + with pytest.raises(TypeError, match="synchronous"): + DynWinRTImplementation.create([plan], callback) + with pytest.raises(TypeError, match="synchronous"): + DynWinRTImplementationDescriptor(plan, callback) + with pytest.raises(TypeError, match="callable"): + DynWinRTImplementation.create([plan], None) + + +@pytest.mark.parametrize("kind", ["coroutine", "awaitable"]) +def test_async_results_are_rejected_without_await_or_warning(monkeypatch, kind): + plan, typ = _stringable() + errors = [] + monkeypatch.setattr(sys, "unraisablehook", errors.append) + + async def coroutine(): + raise AssertionError("coroutine must not run") + + class Awaitable: + def __await__(self): + raise AssertionError("awaitable must not be scheduled") + + def callback(*_args): + return coroutine() if kind == "coroutine" else Awaitable() + + with warnings.catch_warnings(record=True) as recorded: + warnings.simplefilter("always", RuntimeWarning) + with DynWinRTImplementation.create([plan], callback) as owner: + view = _view(owner, typ) + try: + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == PYTHON_EXCEPTION + assert isinstance(errors[0].exc_value, TypeError) + assert "synchronously" in owner.take_error() + finally: + view.release() + errors.clear() + gc.collect() + assert not any("was never awaited" in str(item.message) for item in recorded) + + +def test_contextvars_and_same_thread_detached_reentrancy(): + plan, typ = _stringable() + context = ContextVar("python_winrt_reverse_context", default="outside") + token = context.set("construction") + calls = [] + depth = [0] + view = None + + def callback(*_args): + calls.append(context.get()) + context.set("handler mutation") + if depth[0] == 0: + depth[0] += 1 + assert typ.method(6).invoke(view, []).to_string() == "nested" + depth[0] -= 1 + return [DynWinRTValue.from_hstring("nested")] + + try: + with DynWinRTImplementation.create([plan], callback) as owner: + context.set("call site") + view = _view(owner, typ) + try: + assert typ.method(6).invoke_detached(view, []).to_string() == "nested" + assert calls == ["construction", "construction"] + assert context.get() == "call site" + finally: + view.release() + finally: + context.reset(token) + + +@pytest.mark.parametrize("operation", ["release", "disconnect", "dispose"]) +def test_reentrant_lifetime_operations(operation): + plan, typ = _stringable() + owner = None + + def callback(*_args): + getattr(owner, operation)() + return [DynWinRTValue.from_hstring("completed in-flight call")] + + owner = DynWinRTImplementation.create([plan], callback) + view = _view(owner, typ) + try: + assert typ.method(6).invoke(view, []).to_string() == "completed in-flight call" + if operation == "release": + assert not owner.is_closed + assert typ.method(6).invoke(view, []).to_string() == "completed in-flight call" + else: + assert owner.is_closed + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == CLOSED + owner.dispose() + owner.dispose() + finally: + view.release() + + +def test_disposal_breaks_handler_cycle_and_allows_finalizer_reentrancy(): + plan, typ = _stringable() + finalized = [] + + class Handler: + def dispatch(self, *_args): + return [DynWinRTValue.from_hstring("live")] + + def __del__(self): + owner = self.owner() + if owner is not None: + owner.dispose() + finalized.append("handler") + + handler = Handler() + owner = DynWinRTImplementation.create([plan], handler.dispatch) + handler.owner = weakref.ref(owner) + reference = weakref.ref(handler) + view = _view(owner, typ) + del handler + owner.dispose() + assert reference() is None + assert finalized == ["handler"] + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == CLOSED + view.release() + + +def test_native_reference_retains_callback_after_owner_wrapper_disappears(): + plan, typ = _stringable() + + class Handler: + def dispatch(self, *_args): + return [DynWinRTValue.from_hstring("native retained")] + + handler = Handler() + owner = DynWinRTImplementation.create([plan], handler.dispatch) + view = _view(owner, typ) + handler_ref, owner_ref = weakref.ref(handler), weakref.ref(owner) + del handler, owner + gc.collect() + assert owner_ref() is None and handler_ref() is not None + assert typ.method(6).invoke(view, []).to_string() == "native retained" + view.release() + gc.collect() + assert handler_ref() is None + + +def test_final_native_release_drops_callback_even_if_released_owner_is_alive(): + plan, typ = _stringable() + + class Handler: + def dispatch(self, *_args): + return [DynWinRTValue.from_hstring("live")] + + handler = Handler() + owner = DynWinRTImplementation.create([plan], handler.dispatch) + view = _view(owner, typ) + reference = weakref.ref(handler) + del handler + owner.release() + owner.release() + assert not owner.is_closed and reference() is not None + with pytest.raises(OSError) as caught: + owner.to_value() + assert caught.value.winerror == CLOSED + view.release() + assert owner.is_closed and reference() is None + + +def _run_python_thread(callback): + errors = [] + + def run(): + try: + callback() + except BaseException as error: + errors.append(f"{type(error).__name__}: {error}") + + thread = threading.Thread(target=run, daemon=True) + thread.start() + thread.join(timeout=10) + assert not thread.is_alive(), "worker did not finish native owner cleanup" + assert errors == [] + + +@pytest.mark.parametrize("cycle", [False, True], ids=["last-owner-drop", "owner-cycle-gc"]) +def test_foreign_python_thread_releases_last_owner_and_handler_captures(cycle): + plan, _typ = _stringable() + entered = [] + + class Handler: + def dispatch(self, *_args): + entered.append(threading.get_ident()) + raise AssertionError("cleanup must not enter a callback") + + gc_enabled = gc.isenabled() + gc.disable() + try: + handler = Handler() + owner = DynWinRTImplementation.create([plan], handler.dispatch) + if cycle: + handler.owner = owner + owner_ref, handler_ref = weakref.ref(owner), weakref.ref(handler) + handoff = [owner] + del owner, handler + + def drop_on_worker(): + handoff.clear() + gc.collect() + # Flush any decrefs deferred by PyO3's native destruction path. + DynWinRTType.i32_type() + gc.collect() + assert owner_ref() is None and handler_ref() is None + + _run_python_thread(drop_on_worker) + assert owner_ref() is None and handler_ref() is None + assert entered == [] + finally: + if gc_enabled: + gc.enable() + + +def test_foreign_python_thread_to_value_reports_core_wrong_thread_error(): + plan, _typ = _stringable() + entered = [] + + def callback(*_args): + entered.append(True) + raise AssertionError("wrong-thread access must not enter a callback") + + with DynWinRTImplementation.create([plan], callback) as owner: + errors = [] + + def access_on_worker(): + assert not owner.is_closed + try: + owner.to_value() + except OSError as error: + errors.append(error.winerror) + else: + raise AssertionError("foreign thread obtained a native view") + + _run_python_thread(access_on_worker) + assert errors == [WRONG_THREAD] + assert entered == [] + value = owner.to_value() + value.release() + assert not owner.is_closed + + +def test_foreign_python_gc_preserves_externally_retained_native_root(): + gc_enabled = gc.isenabled() + gc.disable() + try: + owner, owner_ref, handler_ref, typ = _owner_cycle() + view = _view(owner, typ) + del owner + _run_python_thread(gc.collect) + assert owner_ref() is not None and handler_ref() is not None + assert not owner_ref().is_closed + view.release() + + def collect_on_worker(): + gc.collect() + DynWinRTType.i32_type() + gc.collect() + + _run_python_thread(collect_on_worker) + assert owner_ref() is None and handler_ref() is None + finally: + if gc_enabled: + gc.enable() + + +def _owner_cycle(): + plan, typ = _stringable() + + class Handler: + def dispatch(self, *_args): + return [DynWinRTValue.from_hstring("cycle")] + + handler = Handler() + owner = DynWinRTImplementation.create([plan], handler.dispatch) + handler.owner = owner + return owner, weakref.ref(owner), weakref.ref(handler), typ + + +def test_gc_collects_owner_only_python_native_cycle_once(): + owner, owner_ref, handler_ref, _typ = _owner_cycle() + assert gc.is_tracked(owner) + del owner + gc.collect() + assert owner_ref() is None + assert handler_ref() is None + + +def test_gc_does_not_trace_external_native_root_as_python_only_edge(): + owner, owner_ref, handler_ref, typ = _owner_cycle() + view = _view(owner, typ) + del owner + gc.collect() + assert owner_ref() is not None and handler_ref() is not None + assert typ.method(6).invoke(view, []).to_string() == "cycle" + view.release() + gc.collect() + assert owner_ref() is None and handler_ref() is None + + +def test_retained_native_self_cycle_requires_explicit_dispose(): + owner, owner_ref, handler_ref, typ = _owner_cycle() + handler_ref().native_alias = _view(owner, typ) + del owner + gc.collect() + assert owner_ref() is not None and handler_ref() is not None + owner_ref().dispose() + gc.collect() + assert owner_ref() is None and handler_ref() is None + + +def test_context_manager_preserves_user_exception_and_disconnects_aliases(): + plan, typ = _stringable() + owner = DynWinRTImplementation.create( + [plan], lambda *_args: [DynWinRTValue.from_hstring("live")] + ) + view = _view(owner, typ) + try: + with pytest.raises(ValueError, match="body failure"): + with owner: + raise ValueError("body failure") + assert owner.is_closed + with pytest.raises(OSError) as caught: + typ.method(6).invoke(view, []) + assert caught.value.winerror == CLOSED + with pytest.raises(OSError): + owner.to_value() + with pytest.raises(OSError): + owner.__enter__() + finally: + view.release() + + +@pytest.mark.parametrize("during_callback", [False, True]) +def test_interpreter_shutdown_closes_retained_native_callbacks(during_callback): + script = r''' + import atexit + import sys + state = {} + + def late_native_call(): + owner, view, method = state["native"] + assert owner.is_closed + try: + method.invoke(view, []) + except OSError as error: + assert error.winerror == -2147483629, error + else: + raise AssertionError("callback entered after shutdown") + try: + method.invoke(state["native_only"], []) + except OSError as error: + assert error.winerror == -2147483629, error + else: + raise AssertionError("ownerless callback entered after shutdown") + assert state["calls"] == 1 + try: + state["factory"]() + except RuntimeError as error: + assert "shutting down" in str(error) + else: + raise AssertionError("created implementation during shutdown") + owner.dispose() + view.release() + state["native_only"].release() + print("late native callback safely rejected", flush=True) + + atexit.register(late_native_call) + from dynwinrt import (DynWinRTImplementation, DynWinRTImplementationMethod, + DynWinRTInterfacePlan, DynWinRTType, DynWinRTValue, + DynWinRTMethodSig, WinGUID, ro_initialize) + ro_initialize(1) + iid = WinGUID.parse("96369f54-8eb6-48f0-abce-c1b211e627c3") + sig = DynWinRTMethodSig().add_out(DynWinRTType.hstring()) + typ = DynWinRTType.register_interface("IStringable", iid).add_method("ToString", sig) + plan = DynWinRTInterfacePlan.create( + "IStringable", typ, [DynWinRTImplementationMethod("ToString", 6, sig)] + ) + state["calls"] = 0 + def callback(*args): + state["calls"] += 1 + if sys.argv[1] == "1": + from dynwinrt.dynwinrt import _dynwinrt_implementation_runtime + _dynwinrt_implementation_runtime.shutdown() + return [DynWinRTValue.from_hstring("before shutdown")] + state["factory"] = lambda: DynWinRTImplementation.create([plan], callback) + owner = state["factory"]() + view = owner.to_value().cast(iid) + method = typ.method(6) + state["native"] = owner, view, method + second_owner = state["factory"]() + state["native_only"] = second_owner.to_value().cast(iid) + second_owner.release() + del second_owner + assert method.invoke(view, []).to_string() == "before shutdown" + ''' + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(script), str(int(during_callback))], + capture_output=True, text=True, timeout=30, check=False, + ) + assert result.returncode == 0, result.stderr + assert "late native callback safely rejected" in result.stdout + assert not result.stderr + + +def test_subinterpreters_are_rejected_without_native_callback_publication(): + script = r''' + import dynwinrt + try: + import _interpreters as interpreters + except ImportError: + import _xxsubinterpreters as interpreters + interpreter = interpreters.create() + try: + try: + result = interpreters.run_string(interpreter, "import dynwinrt") + except BaseException as error: + message = str(error) + else: + message = getattr(result, "formatted", str(result)) + assert "subinterpreter" in message.lower(), message + finally: + interpreters.destroy(interpreter) + print("subinterpreter import rejected") + ''' + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(script)], + capture_output=True, text=True, timeout=30, check=False, + ) + assert result.returncode == 0, result.stderr + assert "subinterpreter import rejected" in result.stdout diff --git a/bindings/py/tests/test_typing_package.py b/bindings/py/tests/test_typing_package.py index 9d0c4551..8db79e90 100644 --- a/bindings/py/tests/test_typing_package.py +++ b/bindings/py/tests/test_typing_package.py @@ -2,6 +2,7 @@ # Licensed under the MIT License. from pathlib import Path +import inspect import dynwinrt @@ -11,3 +12,20 @@ def test_wheel_contains_typing_metadata(): assert (package_dir / "__init__.pyi").is_file() assert (package_dir / "py.typed").is_file() + + +def test_wheel_exports_typed_implementation_surface(): + stub = (Path(dynwinrt.__file__).parent / "__init__.pyi").read_text(encoding="utf-8") + for name in ( + "DynWinRTImplementationMethod", + "DynWinRTInterfacePlan", + "DynWinRTImplementationDescriptor", + "DynWinRTImplementation", + "DynWinRTDelegateMethod", + ): + assert name in dynwinrt.__all__ + assert hasattr(dynwinrt, name) + assert f"class {name}:" in stub + signature = inspect.signature(dynwinrt.DynWinRTInterfacePlan.create) + assert signature.parameters["required_iids"].default == () + assert "def from_hresult(" in stub diff --git a/crates/dynwinrt/Cargo.toml b/crates/dynwinrt/Cargo.toml index 4dc84fe7..57cc00d8 100644 --- a/crates/dynwinrt/Cargo.toml +++ b/crates/dynwinrt/Cargo.toml @@ -50,6 +50,11 @@ features = [ criterion = { version = "0.5", features = ["html_reports"] } futures = "0.3.31" tokio = { version = "1.49.0", features = ["macros", "rt"] } + +[dev-dependencies.windows] +version = ">=0.59, <=0.62" +features = ["ApplicationModel_Background"] + [[bench]] name = "bench" harness = false diff --git a/crates/dynwinrt/src/array.rs b/crates/dynwinrt/src/array.rs index 571882ec..b8be501a 100644 --- a/crates/dynwinrt/src/array.rs +++ b/crates/dynwinrt/src/array.rs @@ -164,6 +164,13 @@ impl ArrayData { } } + pub(crate) fn from_owned_values(element_type: TypeHandle, values: Vec) -> Self { + Self { + element_type, + buffer: ArrayBuffer::Values(values), + } + } + /// Wrap a CoTaskMem-allocated buffer (ReceiveArray or FillArray pattern). /// ArrayData takes ownership and will CoTaskMemFree on drop. pub(crate) fn from_cotaskmem( @@ -240,10 +247,8 @@ impl ArrayData { /// For Values arrays, returns a clone of the stored value. /// For CoTaskMem arrays, reads from raw bytes (AddRef / DuplicateString as needed). pub fn get(&self, index: usize) -> WinRTValue { - let len = self.len(); - self.try_get(index).unwrap_or_else(|_| { - panic!("ArrayData::get index {} out of bounds (len {})", index, len) - }) + self.try_get(index) + .unwrap_or_else(|error| panic!("ArrayData::get failed: {}", error.message())) } /// Fallible element access that reports invalid indices instead of panicking. @@ -252,17 +257,17 @@ impl ArrayData { if index >= len { return Err(crate::result::Error::IndexOutOfBounds { index, len }); } - Ok(match &self.buffer { - ArrayBuffer::Values(v) => v[index].clone(), + match &self.buffer { + ArrayBuffer::Values(v) => Ok(v[index].clone()), ArrayBuffer::CoTaskMem { ptr, .. } => self.get_from_raw(index, *ptr as *const u8), - }) + } } /// Read element from a raw byte buffer (CoTaskMem path). - fn get_from_raw(&self, index: usize, base: *const u8) -> WinRTValue { + fn get_from_raw(&self, index: usize, base: *const u8) -> crate::result::Result { let elem_size = self.element_type.element_size(); unsafe { - match self.element_type.kind() { + Ok(match self.element_type.kind() { TypeKind::Bool => WinRTValue::Bool(*base.add(index * elem_size) != 0), TypeKind::I8 => WinRTValue::I8(*(base.add(index * elem_size) as *const i8)), TypeKind::U8 => WinRTValue::U8(*base.add(index * elem_size)), @@ -300,8 +305,12 @@ impl ArrayData { WinRTValue::Null } else { // from_raw takes ownership, but we want a clone — so AddRef first - let obj = IUnknown::from_raw_borrowed(&raw).unwrap(); - WinRTValue::Object(obj.clone()) + let obj = IUnknown::from_raw_borrowed(&raw).unwrap().clone(); + if self.element_type.is_async() { + self.element_type.from_out(obj.into_raw())? + } else { + WinRTValue::Object(obj) + } } } TypeKind::Struct(_) => { @@ -314,8 +323,8 @@ impl ArrayData { } WinRTValue::Struct(vd) } - other => panic!("ArrayData::get unsupported element type: {:?}", other), - } + other => return Err(crate::result::Error::UnsupportedCollectionElement(other)), + }) } } diff --git a/crates/dynwinrt/src/call.rs b/crates/dynwinrt/src/call.rs index 4eca2706..9e1d12ae 100644 --- a/crates/dynwinrt/src/call.rs +++ b/crates/dynwinrt/src/call.rs @@ -475,6 +475,7 @@ macro_rules! dispatch_scalar { WinRTValue::I16(v) => $call(*v), WinRTValue::U16(v) => $call(*v), WinRTValue::I32(v) => $call(*v), + WinRTValue::HResult(v) => $call(v.0), WinRTValue::Enum { value: v, .. } => $call(*v), WinRTValue::U32(v) => $call(*v), WinRTValue::I64(v) => $call(*v), diff --git a/crates/dynwinrt/src/lib.rs b/crates/dynwinrt/src/lib.rs index 938dc270..a7c799ec 100644 --- a/crates/dynwinrt/src/lib.rs +++ b/crates/dynwinrt/src/lib.rs @@ -17,6 +17,7 @@ mod roapi; mod signature; mod value; mod winapp; +mod winrt_implementation; mod xaml_application; mod array; @@ -59,6 +60,10 @@ pub use crate::roapi::ro_get_activation_factory_2; pub use crate::signature::{InterfaceSignature, MethodSignature}; pub use crate::value::{ArrayOfIUnknownData, AsyncInfo, WinRTValue}; pub use crate::winapp::{WinAppSdkContext, initialize_winappsdk}; +pub use crate::winrt_implementation::{ + WinRtImplementation, WinRtImplementationCallback, WinRtImplementationPlan, + WinRtInterfaceDefinition, WinRtMethodDefinition, WinRtThreadingPolicy, +}; pub use crate::xaml_application::{ XamlRuntimeClassActivator, XamlRuntimeClassRegistration, create_xaml_application, register_xaml_runtime_class, diff --git a/crates/dynwinrt/src/metadata_table/value_data.rs b/crates/dynwinrt/src/metadata_table/value_data.rs index 6e9942ab..b6e32395 100644 --- a/crates/dynwinrt/src/metadata_table/value_data.rs +++ b/crates/dynwinrt/src/metadata_table/value_data.rs @@ -126,6 +126,25 @@ impl std::fmt::Debug for ValueTypeData { } impl ValueTypeData { + pub(crate) fn try_new(handle: &TypeHandle) -> windows_core::Result { + let layout = handle.layout(); + let ptr = if layout.size() == 0 { + std::ptr::null_mut() + } else { + let ptr = unsafe { std::alloc::alloc_zeroed(layout) }; + if ptr.is_null() { + return Err(windows_core::Error::from_hresult(windows_core::HRESULT( + 0x8007000Eu32 as i32, + ))); + } + ptr + }; + Ok(Self { + type_handle: handle.clone(), + ptr, + }) + } + pub(crate) fn new(handle: &TypeHandle) -> Self { let layout = handle.layout(); let ptr = if layout.size() > 0 { @@ -225,6 +244,18 @@ impl ValueTypeData { } } + /// Transfer already-prepared field ownership without calling native code. + /// `result` must be uninitialized storage for this exact struct layout. + pub(crate) unsafe fn move_to_abi(self, result: *mut c_void) { + let size = self.type_handle.size_of(); + if size != 0 { + unsafe { + std::ptr::copy_nonoverlapping(self.ptr, result.cast(), size); + std::ptr::write_bytes(self.ptr, 0, size); + } + } + } + pub fn get_field(&self, index: usize) -> T { let h = &self.type_handle; let offset = h.field_offset(index); diff --git a/crates/dynwinrt/src/native_call.rs b/crates/dynwinrt/src/native_call.rs index 004e422d..6a87108f 100644 --- a/crates/dynwinrt/src/native_call.rs +++ b/crates/dynwinrt/src/native_call.rs @@ -735,6 +735,10 @@ impl MethodReturn { } impl AbiMethodSignature { + pub(crate) fn parameters(&self) -> &[Parameter] { + &self.parameters + } + pub(crate) fn new(table: &Arc) -> Self { AbiMethodSignature { out_count: 0, @@ -1124,6 +1128,18 @@ fn coerce_input_object( }) } +pub(crate) fn array_element_types_match(expected: &TypeHandle, actual: &TypeHandle) -> bool { + match (expected.kind(), actual.kind()) { + (TypeKind::Struct(_), TypeKind::Struct(_)) | (TypeKind::Enum(_), TypeKind::Enum(_)) => { + expected == actual + } + (TypeKind::Enum(_), TypeKind::I32) + | (TypeKind::Char16, TypeKind::U16) + | (TypeKind::U16, TypeKind::Char16) => true, + (expected, actual) => expected == actual, + } +} + fn coerce_input_array( expected: &TypeHandle, value: &WinRTValue, @@ -1144,14 +1160,7 @@ fn coerce_input_array( ) })?; let is_object_array = expected_object_iid(&element_type).is_some(); - let element_type_matches = match (element_type.kind(), array.element_type.kind()) { - (TypeKind::Struct(_), TypeKind::Struct(_)) => array.element_type == element_type, - (TypeKind::Enum(_), TypeKind::Enum(_)) => array.element_type == element_type, - (TypeKind::Enum(_), TypeKind::I32) - | (TypeKind::Char16, TypeKind::U16) - | (TypeKind::U16, TypeKind::Char16) => true, - (expected, actual) => expected == actual, - }; + let element_type_matches = array_element_types_match(&element_type, &array.element_type); if !is_object_array && !element_type_matches { return Err(windows_core::Error::new( windows_core::HRESULT(0x80070057u32 as i32), @@ -1214,7 +1223,7 @@ fn validate_input_struct(expected: &TypeHandle, value: &WinRTValue) -> windows_c Ok(()) } -fn coerce_scalar_input( +pub(crate) fn coerce_scalar_input( expected: &TypeHandle, value: &WinRTValue, ) -> windows_core::Result> { diff --git a/crates/dynwinrt/src/signature.rs b/crates/dynwinrt/src/signature.rs index 58317bbe..dce8fcab 100644 --- a/crates/dynwinrt/src/signature.rs +++ b/crates/dynwinrt/src/signature.rs @@ -20,6 +20,13 @@ use crate::{ #[derive(Debug, Clone)] pub struct MethodSignature(AbiMethodSignature); +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum WinRtParameterDirection { + In, + Out, + FillArray, +} + impl MethodSignature { pub fn new(table: &Arc) -> Self { Self(AbiMethodSignature::new(table)) @@ -44,6 +51,37 @@ impl MethodSignature { pub fn build(self, index: usize) -> Method { Method(self.0.build(index)) } + + pub(crate) fn implementation_parameters( + &self, + ) -> windows_core::Result> { + use crate::native_call::ParamKind; + + self.0 + .parameters() + .iter() + .map(|parameter| { + let direction = match parameter.kind { + ParamKind::In => WinRtParameterDirection::In, + ParamKind::Out => WinRtParameterDirection::Out, + ParamKind::OutFillArray => WinRtParameterDirection::FillArray, + ParamKind::OptionalOut | ParamKind::InOut => { + return Err(windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "WinRT implementations require WinRT input/output contracts", + )); + } + }; + let typ = parameter.typ.as_winrt().ok_or_else(|| { + windows_core::Error::new( + windows_core::HRESULT(0x80070057u32 as i32), + "WinRT implementations cannot contain Classic COM parameter types", + ) + })?; + Ok((typ.clone(), direction)) + }) + .collect() + } } #[derive(Debug)] diff --git a/crates/dynwinrt/src/winrt_implementation/identity.rs b/crates/dynwinrt/src/winrt_implementation/identity.rs new file mode 100644 index 00000000..28e434e1 --- /dev/null +++ b/crates/dynwinrt/src/winrt_implementation/identity.rs @@ -0,0 +1,207 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use core::ffi::c_void; +use std::{ + mem::ManuallyDrop, + panic::{AssertUnwindSafe, catch_unwind}, + ptr, + sync::{Arc, Weak}, +}; + +use windows::Win32::System::WinRT::{ + IWeakReference, IWeakReference_Vtbl, IWeakReferenceSource_Vtbl, +}; +use windows_core::{GUID, HRESULT, IUnknown, Interface}; + +use super::{E_FAIL, E_NOINTERFACE, E_POINTER, Host, S_OK}; + +// One native +1 is one Arc strong reference. Using Arc/Weak keeps failed weak +// resolution on the same destruction path as ordinary Release, including a +// concurrent final Release while QueryInterface rejects the requested IID. +pub(super) unsafe fn borrowed(this: *mut c_void) -> ManuallyDrop> { + ManuallyDrop::new(unsafe { Arc::from_raw(this.cast::()) }) +} + +pub(super) unsafe fn pin(this: *mut c_void) -> Arc { + unsafe { + Arc::increment_strong_count(this.cast::()); + Arc::from_raw(this.cast::()) + } +} + +pub(super) unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let owner = unsafe { borrowed::(this) }; + unsafe { Arc::increment_strong_count(this.cast::()) }; + Arc::strong_count(&owner) as u32 +} + +pub(super) unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let owner = unsafe { Arc::from_raw(this.cast::()) }; + let remaining = Arc::strong_count(&owner) - 1; + if catch_unwind(AssertUnwindSafe(|| drop(owner))).is_err() { + eprintln!("[dynwinrt] Panic while releasing a WinRT implementation reference"); + } + remaining as u32 +} + +#[repr(C)] +pub(super) struct WeakSource { + vtable: *const IWeakReferenceSource_Vtbl, + pub owner: *mut Host, +} + +impl WeakSource { + pub fn new() -> Self { + Self { + vtable: &Self::VTABLE, + owner: ptr::null_mut(), + } + } + + const VTABLE: IWeakReferenceSource_Vtbl = IWeakReferenceSource_Vtbl { + base__: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query, + AddRef: Self::add_ref, + Release: Self::release, + }, + GetWeakReference: Self::get_weak_reference, + }; + + unsafe fn owner(this: *mut c_void) -> *mut c_void { + unsafe { (*this.cast::()).owner.cast() } + } + + unsafe extern "system" fn query( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + unsafe { Host::query_interface(Self::owner(this), iid, result) } + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + unsafe { add_ref::(Self::owner(this)) } + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + unsafe { release::(Self::owner(this)) } + } + + unsafe extern "system" fn get_weak_reference( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + unsafe { result.write(ptr::null_mut()) }; + match catch_unwind(AssertUnwindSafe(|| { + let owner = unsafe { borrowed::(Self::owner(this)) }; + let weak = Arc::new(NativeWeakReference { + vtable: &NativeWeakReference::VTABLE, + owner: Arc::downgrade(&owner), + #[cfg(test)] + after_upgrade: std::sync::Mutex::new(None), + }); + unsafe { result.write(Arc::into_raw(weak).cast_mut().cast()) }; + })) { + Ok(()) => S_OK, + Err(_) => E_FAIL, + } + } +} + +#[repr(C)] +pub(super) struct NativeWeakReference { + vtable: *const IWeakReference_Vtbl, + owner: Weak, + #[cfg(test)] + after_upgrade: std::sync::Mutex>>, +} + +// This separate weak-reference identity contains no apartment-bound values. +// It only upgrades an atomic Weak and calls thread-safe Host identity methods. +unsafe impl Send for NativeWeakReference {} +unsafe impl Sync for NativeWeakReference {} + +impl NativeWeakReference { + const VTABLE: IWeakReference_Vtbl = IWeakReference_Vtbl { + base__: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query, + AddRef: add_ref::, + Release: release::, + }, + Resolve: Self::resolve, + }; + + unsafe extern "system" fn query( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + unsafe { result.write(ptr::null_mut()) }; + if iid.is_null() { + return E_POINTER; + } + let iid = unsafe { &*iid }; + if *iid == IUnknown::IID + || *iid == IWeakReference::IID + || *iid == windows_core::imp::IAgileObject::IID + { + unsafe { + add_ref::(this); + result.write(this); + } + S_OK + } else if *iid == windows_core::imp::IMarshal::IID { + // Encapsulated pinned windows-core helper; only this independent + // weak-reference object is agile, never its implemented target. + unsafe { + add_ref::(this); + windows_core::imp::marshaler(IUnknown::from_raw(this), result) + } + } else { + E_NOINTERFACE + } + } + + unsafe extern "system" fn resolve( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + unsafe { result.write(ptr::null_mut()) }; + if iid.is_null() { + return E_POINTER; + } + catch_unwind(AssertUnwindSafe(|| { + let weak = unsafe { &*this.cast::() }; + let Some(owner) = weak.owner.upgrade() else { + return S_OK; + }; + #[cfg(test)] + { + let hook = weak.after_upgrade.lock().unwrap().take(); + if let Some(hook) = hook { + hook(); + } + } + // `owner` releases through Arc on every return path, including + // E_NOINTERFACE when this pin became the final strong reference. + unsafe { Host::query_interface(Arc::as_ptr(&owner).cast_mut().cast(), iid, result) } + })) + .unwrap_or(E_FAIL) + } + + #[cfg(test)] + pub fn after_upgrade(&self, hook: impl FnOnce() + Send + 'static) { + *self.after_upgrade.lock().unwrap() = Some(Box::new(hook)); + } +} diff --git a/crates/dynwinrt/src/winrt_implementation/mod.rs b/crates/dynwinrt/src/winrt_implementation/mod.rs new file mode 100644 index 00000000..0a724e30 --- /dev/null +++ b/crates/dynwinrt/src/winrt_implementation/mod.rs @@ -0,0 +1,583 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Standalone, metadata-planned WinRT interface implementations. +//! +//! These objects are non-agile. Only IUnknown/IInspectable identity operations +//! are available independently of the creating thread. Method callbacks are +//! synchronous and must return every declared output before ownership is +//! published to the native caller. + +use core::ffi::c_void; +use std::{ + panic::{AssertUnwindSafe, catch_unwind}, + ptr, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + thread::{self, ThreadId}, +}; + +use windows::Win32::System::Com::CoTaskMemAlloc; +use windows::Win32::System::WinRT::IWeakReferenceSource; +use windows_core::{GUID, HRESULT, HSTRING, IInspectable, IUnknown, Interface}; + +use crate::{ + WinRTValue, + com_helpers::{E_FAIL, E_NOINTERFACE, E_POINTER, IInspectableVtbl, S_OK}, + native_callback::{CallbackAbiType, CallbackSignature}, +}; + +mod identity; +mod plan; +mod values; + +pub use plan::{ + WinRtImplementationPlan, WinRtInterfaceDefinition, WinRtMethodDefinition, WinRtThreadingPolicy, +}; + +const E_INVALIDARG: HRESULT = HRESULT(0x80070057u32 as i32); +const E_OUTOFMEMORY: HRESULT = HRESULT(0x8007000Eu32 as i32); +const RPC_E_WRONG_THREAD: HRESULT = HRESULT(0x8001010Eu32 as i32); +const RO_E_CLOSED: HRESULT = HRESULT(0x80000013u32 as i32); + +fn error(code: HRESULT, message: impl AsRef) -> windows_core::Error { + windows_core::Error::new(code, message.as_ref()) +} + +fn invalid_argument(message: impl AsRef) -> windows_core::Error { + error(E_INVALIDARG, message) +} + +fn reserved_iid(iid: &GUID) -> bool { + *iid == GUID::zeroed() + || *iid == IUnknown::IID + || *iid == IInspectable::IID + || *iid == windows_core::imp::IAgileObject::IID + || *iid == windows_core::imp::IMarshal::IID + || *iid == windows_core::imp::IWeakReferenceSource::IID + || *iid == windows_core::imp::IWeakReference::IID +} + +/// Returns outputs in signature order (including the projected return value). +/// Incoming references have already been retained for the callback. +pub type WinRtImplementationCallback = + Arc windows_core::Result> + Send + Sync>; + +struct Control { + owner_thread: ThreadId, + closed: AtomicBool, + callback: Mutex>, + last_error: Mutex>, +} + +impl Control { + fn callback(&self) -> windows_core::Result { + if thread::current().id() != self.owner_thread { + return Err(error( + RPC_E_WRONG_THREAD, + "WinRT implementation callbacks require the creating thread; no cross-apartment dispatcher is installed", + )); + } + self.callback + .lock() + .map_err(|_| error(E_FAIL, "WinRT implementation callback state is poisoned"))? + .clone() + .ok_or_else(|| { + error( + RO_E_CLOSED, + "WinRT implementation callbacks are disconnected", + ) + }) + } + + fn disconnect(&self) -> windows_core::Result<()> { + let callback = { + let mut slot = self + .callback + .lock() + .map_err(|_| error(E_FAIL, "WinRT implementation callback state is poisoned"))?; + self.closed.store(true, Ordering::Release); + slot.take() + }; + // A handler/finalizer may reenter this object when its last root drops. + drop(callback); + Ok(()) + } + + fn record_error(&self, message: String) { + match self.last_error.lock() { + Ok(mut slot) => *slot = Some(message), + Err(_) => eprintln!("[dynwinrt] WinRT callback error state is poisoned: {message}"), + } + } +} + +/// Owns one native reference to an implemented WinRT object. +/// +/// Dropping or releasing this owner does not disconnect other native owners. +/// `dispose` deliberately disconnects the whole object and breaks callback +/// cycles; an already-dispatched callback retains its resources until return. +pub struct WinRtImplementation { + identity: Option, + control: Arc, +} + +// The only IUnknown stored here is our canonical, atomically owned Host, never +// an arbitrary apartment-bound object. Control state and callback destruction +// are thread-safe. Moving/releasing a controller does not grant callback +// agility: to_value and native dispatch still enforce the owner thread. +unsafe impl Send for WinRtImplementation {} +unsafe impl Sync for WinRtImplementation {} + +impl WinRtImplementation { + pub fn new( + plan: WinRtImplementationPlan, + callback: WinRtImplementationCallback, + runtime_class_name: Option<&str>, + ) -> windows_core::Result { + if runtime_class_name.is_some_and(|name| name.contains('\0')) { + return Err(invalid_argument( + "WinRT runtime class names cannot contain NUL", + )); + } + let control = Arc::new(Control { + owner_thread: thread::current().id(), + closed: AtomicBool::new(false), + callback: Mutex::new(Some(callback)), + last_error: Mutex::new(None), + }); + let identity = Host::create( + plan, + control.clone(), + HSTRING::from(runtime_class_name.unwrap_or("")), + )?; + Ok(Self { + identity: Some(identity), + control, + }) + } + + pub fn to_value(&self) -> windows_core::Result { + if thread::current().id() != self.control.owner_thread { + return Err(error( + RPC_E_WRONG_THREAD, + "WinRT implementation owner belongs to another thread", + )); + } + self.identity + .as_ref() + .map(|identity| WinRTValue::Object(identity.clone())) + .ok_or_else(|| error(RO_E_CLOSED, "WinRT implementation owner has been released")) + } + + pub fn release(&mut self) { + self.identity = None; + } + + pub fn disconnect(&self) -> windows_core::Result<()> { + self.control.disconnect() + } + + pub fn dispose(&mut self) -> windows_core::Result<()> { + self.disconnect()?; + self.release(); + Ok(()) + } + + pub fn is_closed(&self) -> bool { + self.control.closed.load(Ordering::Acquire) + } + + pub fn take_error(&self) -> Option { + match self.control.last_error.lock() { + Ok(mut slot) => slot.take(), + Err(_) => Some("WinRT callback error state is poisoned".into()), + } + } + + /// Conservative GC hint: false when any other native owner may exist. + /// Native weak-reference machinery may also make this return false. + pub fn has_unique_native_reference(&self) -> bool { + self.identity.as_ref().is_some_and(|identity| { + // This controller always owns the canonical Host identity. + let host = unsafe { identity::borrowed::(identity.as_raw()) }; + !host.weak_requested.load(Ordering::Acquire) && Arc::strong_count(&host) == 1 + }) + } +} + +#[repr(C)] +struct View { + vtable: *const *const c_void, + owner: *mut Host, + index: usize, + _storage: Box<[*const c_void]>, +} + +#[repr(C)] +struct Host { + vtable: *const IInspectableVtbl, + control: Arc, + plan: WinRtImplementationPlan, + name: HSTRING, + iids: Box<[GUID]>, + // The individually boxed views and vtables never move after publication. + #[allow(clippy::vec_box)] + views: Vec>, + weak_source: Box, + weak_requested: AtomicBool, +} + +// All native storage is immutable after publication, refcounts are atomic, and +// callback/control state is synchronized. This does NOT grant WinRT agility: +// dispatch rejects foreign threads before accessing language resources. +unsafe impl Send for Host {} +unsafe impl Sync for Host {} + +impl Drop for Host { + fn drop(&mut self) { + match catch_unwind(AssertUnwindSafe(|| self.control.disconnect())) { + Ok(Ok(())) => {} + Ok(Err(error)) => eprintln!("[dynwinrt] WinRT implementation destruction: {error}"), + Err(_) => eprintln!("[dynwinrt] Panic while destroying WinRT implementation callbacks"), + } + } +} + +impl Host { + const VTABLE: IInspectableVtbl = IInspectableVtbl { + base: windows_core::IUnknown_Vtbl { + QueryInterface: Self::query_interface, + AddRef: Self::add_ref, + Release: Self::release, + }, + get_iids: Self::get_iids, + get_runtime_class_name: Self::get_runtime_class_name, + get_trust_level: Self::get_trust_level, + }; + + fn create( + plan: WinRtImplementationPlan, + control: Arc, + name: HSTRING, + ) -> windows_core::Result { + match plan.threading { + WinRtThreadingPolicy::OwnerThread => {} + } + let mut views = Vec::with_capacity(plan.interfaces.len()); + for (index, interface) in plan.interfaces.iter().enumerate() { + let mut slots = vec![ + Self::view_query_interface as *const () as *const c_void, + Self::view_add_ref as *const () as *const c_void, + Self::view_release as *const () as *const c_void, + Self::view_get_iids as *const () as *const c_void, + Self::view_get_runtime_class_name as *const () as *const c_void, + Self::view_get_trust_level as *const () as *const c_void, + ]; + for method in &interface.methods { + let code = match Self::static_code(method.slot, &method.signature) { + Some(code) => code, + None => crate::native_callback::callback_code( + method.slot, + method.signature.clone(), + Self::dispatch_libffi, + ) + .map_err(|message| { + error( + E_FAIL, + format!( + "{}::{} (slot {}): cannot prepare WinRT callback: {message}", + interface.name, method.name, method.slot + ), + ) + })?, + }; + slots.push(code); + } + let storage = slots.into_boxed_slice(); + views.push(Box::new(View { + vtable: storage.as_ptr(), + owner: ptr::null_mut(), + index, + _storage: storage, + })); + } + let iids = plan + .interfaces + .iter() + .map(|interface| interface.iid) + .collect(); + let mut host = Arc::new(Self { + vtable: &Self::VTABLE, + control, + plan, + name, + iids, + views, + weak_source: Box::new(identity::WeakSource::new()), + weak_requested: AtomicBool::new(false), + }); + let owner = Arc::as_ptr(&host).cast_mut(); + let unpublished = + Arc::get_mut(&mut host).expect("unpublished WinRT host is uniquely owned"); + for view in &mut unpublished.views { + view.owner = owner; + } + unpublished.weak_source.owner = owner; + Ok(unsafe { IUnknown::from_raw(Arc::into_raw(host).cast_mut().cast()) }) + } + + unsafe extern "system" fn query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + unsafe { result.write(ptr::null_mut()) }; + if iid.is_null() { + return E_POINTER; + } + let host = unsafe { &*this.cast::() }; + let iid = unsafe { &*iid }; + let view = if *iid == IUnknown::IID || *iid == IInspectable::IID { + this + } else if let Some(index) = host.iids.iter().position(|candidate| candidate == iid) { + ptr::from_ref(host.views[index].as_ref()).cast_mut().cast() + } else if *iid == IWeakReferenceSource::IID { + host.weak_requested.store(true, Ordering::Release); + ptr::from_ref(host.weak_source.as_ref()).cast_mut().cast() + } else { + return E_NOINTERFACE; + }; + unsafe { identity::add_ref::(this) }; + unsafe { result.write(view) }; + S_OK + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + unsafe { identity::add_ref::(this) } + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + unsafe { identity::release::(this) } + } + + unsafe extern "system" fn get_iids( + this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + if !count.is_null() { + unsafe { count.write(0) }; + } + if !result.is_null() { + unsafe { result.write(ptr::null_mut()) }; + } + if count.is_null() || result.is_null() { + return E_POINTER; + } + let host = unsafe { &*this.cast::() }; + let Ok(length) = u32::try_from(host.iids.len()) else { + return E_OUTOFMEMORY; + }; + let Some(bytes) = host.iids.len().checked_mul(size_of::()) else { + return E_OUTOFMEMORY; + }; + let allocation = unsafe { CoTaskMemAlloc(bytes).cast::() }; + if allocation.is_null() { + return E_OUTOFMEMORY; + } + unsafe { + ptr::copy_nonoverlapping(host.iids.as_ptr(), allocation, host.iids.len()); + count.write(length); + result.write(allocation); + } + S_OK + } + + unsafe extern "system" fn get_runtime_class_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + unsafe { result.write(ptr::null_mut()) }; + match catch_unwind(AssertUnwindSafe(|| { + let host = unsafe { &*this.cast::() }; + unsafe { result.cast::().write(host.name.clone()) }; + })) { + Ok(()) => S_OK, + Err(_) => E_FAIL, + } + } + + unsafe extern "system" fn get_trust_level(_this: *mut c_void, result: *mut i32) -> HRESULT { + if result.is_null() { + return E_POINTER; + } + unsafe { result.write(0) }; + S_OK + } + + unsafe fn owner(this: *mut c_void) -> *mut c_void { + unsafe { (*this.cast::()).owner.cast() } + } + + unsafe extern "system" fn view_query_interface( + this: *mut c_void, + iid: *const GUID, + result: *mut *mut c_void, + ) -> HRESULT { + unsafe { Self::query_interface(Self::owner(this), iid, result) } + } + + unsafe extern "system" fn view_add_ref(this: *mut c_void) -> u32 { + unsafe { Self::add_ref(Self::owner(this)) } + } + + unsafe extern "system" fn view_release(this: *mut c_void) -> u32 { + unsafe { Self::release(Self::owner(this)) } + } + + unsafe extern "system" fn view_get_iids( + this: *mut c_void, + count: *mut u32, + result: *mut *mut GUID, + ) -> HRESULT { + unsafe { Self::get_iids(Self::owner(this), count, result) } + } + + unsafe extern "system" fn view_get_runtime_class_name( + this: *mut c_void, + result: *mut *mut c_void, + ) -> HRESULT { + unsafe { Self::get_runtime_class_name(Self::owner(this), result) } + } + + unsafe extern "system" fn view_get_trust_level(this: *mut c_void, result: *mut i32) -> HRESULT { + unsafe { Self::get_trust_level(Self::owner(this), result) } + } + + unsafe fn dispatch(slot: usize, args: *const *const c_void) -> HRESULT { + if args.is_null() || unsafe { (*args).is_null() } { + return E_POINTER; + } + let this = unsafe { (*args).cast::<*mut c_void>().read_unaligned() }; + if this.is_null() { + return E_POINTER; + } + let (control, context, invocation) = { + let view = unsafe { &*this.cast::() }; + let host = unsafe { identity::pin::(view.owner.cast()) }; + let control = host.control.clone(); + let Some(interface) = host.plan.interfaces.get(view.index) else { + return E_INVALIDARG; + }; + let Some(method) = slot + .checked_sub(6) + .and_then(|index| interface.methods.get(index)) + else { + return E_INVALIDARG; + }; + let context = format!("{}::{} (slot {slot})", interface.name, method.name); + let invocation = catch_unwind(AssertUnwindSafe(|| -> windows_core::Result<()> { + // Failure outputs are initialized even for disconnected and + // wrong-thread calls, before any language/runtime entry. + let outputs = unsafe { method.initialize_outputs(args)? }; + let callback = control.callback()?; + let inputs = unsafe { method.inputs(args)? }; + let values = callback(view.index, slot, &inputs)?; + let prepared = method.prepare_outputs(outputs, &values)?; + // Every fallible conversion and reference acquisition is done. + for output in prepared { + unsafe { output.commit() }; + } + Ok(()) + })) + .unwrap_or_else(|_| Err(error(E_FAIL, "Rust panic in WinRT implementation callback"))); + (control, context, invocation) + }; + match invocation { + Ok(()) => S_OK, + Err(cause) => { + control.record_error(format!( + "{context}: 0x{:08X}: {}", + cause.code().0 as u32, + cause.message() + )); + cause.into() + } + } + } + + unsafe fn dispatch_libffi( + slot: usize, + _signature: &CallbackSignature, + args: *const *const c_void, + result: *mut c_void, + ) { + if !result.is_null() { + let hr = unsafe { Self::dispatch(slot, args) }; + unsafe { result.cast::().write(hr.0) }; + } + } + + unsafe extern "system" fn no_args(this: *mut c_void) -> HRESULT { + let args = [ptr::from_ref(&this).cast()]; + unsafe { Self::dispatch(SLOT, args.as_ptr()) } + } + + unsafe extern "system" fn one_pointer( + this: *mut c_void, + value: *mut c_void, + ) -> HRESULT { + let args = [ptr::from_ref(&this).cast(), ptr::from_ref(&value).cast()]; + unsafe { Self::dispatch(SLOT, args.as_ptr()) } + } + + unsafe extern "system" fn two_pointers( + this: *mut c_void, + first: *mut c_void, + second: *mut c_void, + ) -> HRESULT { + let args = [ + ptr::from_ref(&this).cast(), + ptr::from_ref(&first).cast(), + ptr::from_ref(&second).cast(), + ]; + unsafe { Self::dispatch(SLOT, args.as_ptr()) } + } + + fn static_slot(signature: &CallbackSignature) -> Option<*const c_void> { + match signature.parameters() { + [] => Some(Self::no_args:: as *const () as *const c_void), + [CallbackAbiType::Pointer] => { + Some(Self::one_pointer:: as *const () as *const c_void) + } + [CallbackAbiType::Pointer, CallbackAbiType::Pointer] => { + Some(Self::two_pointers:: as *const () as *const c_void) + } + _ => None, + } + } + + fn static_code(slot: usize, signature: &CallbackSignature) -> Option<*const c_void> { + macro_rules! slots { + ($($slot:literal),+ $(,)?) => { + match slot { + $($slot => Self::static_slot::<$slot>(signature),)+ + _ => None, + } + }; + } + slots!(6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/dynwinrt/src/winrt_implementation/plan.rs b/crates/dynwinrt/src/winrt_implementation/plan.rs new file mode 100644 index 00000000..4ed3bf2e --- /dev/null +++ b/crates/dynwinrt/src/winrt_implementation/plan.rs @@ -0,0 +1,268 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::HashSet; + +use libffi::middle::Type; +use windows_core::{GUID, Interface}; + +use crate::{ + MethodSignature, TypeHandle, TypeKind, + native_callback::{CallbackAbiType, CallbackSignature}, + signature::WinRtParameterDirection, +}; + +use super::{invalid_argument, reserved_iid, values::ValuePlan}; + +/// The first release deliberately does not marshal language callbacks. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WinRtThreadingPolicy { + OwnerThread, +} + +/// One complete WinRT method contract, including all output parameters. +#[derive(Debug, Clone)] +pub struct WinRtMethodDefinition { + pub name: String, + pub vtable_index: usize, + pub signature: MethodSignature, +} + +/// Metadata for one independently queryable, IInspectable-rooted interface. +/// +/// WinRT required interfaces have their own vtables; their methods must not be +/// appended to this interface or aliased to an incompatible vtable prefix. +#[derive(Debug, Clone)] +pub struct WinRtInterfaceDefinition { + pub name: String, + pub interface_type: TypeHandle, + pub required_iids: Vec, + pub methods: Vec, +} + +#[derive(Debug, Clone)] +pub(super) struct ParameterPlan { + pub abi_index: usize, + pub direction: WinRtParameterDirection, + pub value: ValuePlan, + pub array: bool, +} + +#[derive(Debug, Clone)] +pub(super) struct MethodPlan { + pub name: String, + pub slot: usize, + pub parameters: Vec, + pub signature: CallbackSignature, + pub input_count: usize, + pub output_count: usize, +} + +#[derive(Debug, Clone)] +pub(super) struct InterfacePlan { + pub name: String, + pub iid: GUID, + pub methods: Vec, +} + +/// Immutable, validated WinRT reverse-call contracts shared by all bindings. +#[derive(Debug, Clone)] +pub struct WinRtImplementationPlan { + pub(super) interfaces: Vec, + pub(super) threading: WinRtThreadingPolicy, +} + +impl WinRtImplementationPlan { + pub fn new( + definitions: Vec, + threading: WinRtThreadingPolicy, + ) -> windows_core::Result { + if definitions.is_empty() { + return Err(invalid_argument( + "A WinRT implementation requires at least one interface", + )); + } + let mut iids = HashSet::new(); + for definition in &definitions { + let TypeKind::Interface(iid) = definition.interface_type.kind() else { + return Err(invalid_argument(format!( + "{}: only non-generic IInspectable-rooted interfaces can be implemented", + definition.name + ))); + }; + if definition.name.is_empty() { + return Err(invalid_argument("WinRT interface names cannot be empty")); + } + if reserved_iid(&iid) { + return Err(invalid_argument(format!( + "{}: IID {iid:?} is reserved for the WinRT object infrastructure", + definition.name + ))); + } + if !iids.insert(iid) { + return Err(invalid_argument(format!( + "Duplicate WinRT implementation IID {iid:?}" + ))); + } + } + let mut required = Vec::with_capacity(definitions.len()); + for definition in &definitions { + let mut seen = HashSet::new(); + let mut indices = Vec::new(); + for iid in &definition.required_iids { + if *iid == windows_core::IUnknown::IID || *iid == windows_core::IInspectable::IID { + continue; + } + if !seen.insert(*iid) { + return Err(invalid_argument(format!( + "{}: duplicate required interface IID {iid:?}", + definition.name + ))); + } + let Some(index) = definitions.iter().position(|candidate| { + candidate.interface_type.kind() == TypeKind::Interface(*iid) + }) else { + return Err(invalid_argument(format!( + "{} requires a separate implementation of interface {iid:?}", + definition.name + ))); + }; + indices.push(index); + } + required.push(indices); + } + fn visit(index: usize, graph: &[Vec], state: &mut [u8]) -> bool { + match state[index] { + 1 => return false, + 2 => return true, + _ => {} + } + state[index] = 1; + for &base in &graph[index] { + if !visit(base, graph, state) { + return false; + } + } + state[index] = 2; + true + } + let mut state = vec![0; definitions.len()]; + for (index, definition) in definitions.iter().enumerate() { + if !visit(index, &required, &mut state) { + return Err(invalid_argument(format!( + "{}: cyclic WinRT required-interface relationships", + definition.name + ))); + } + } + let interfaces = definitions + .into_iter() + .map(|definition| { + let mut methods = Vec::with_capacity(definition.methods.len()); + for (index, method) in definition.methods.into_iter().enumerate() { + if method.vtable_index != index + 6 { + return Err(invalid_argument(format!( + "{}: WinRT methods must occupy every contiguous slot starting at 6; \ + expected slot {}, found {}", + definition.name, + index + 6, + method.vtable_index + ))); + } + if method.name.is_empty() { + return Err(invalid_argument(format!( + "{}: method at slot {} has no metadata name", + definition.name, method.vtable_index + ))); + } + methods.push(MethodPlan::new(method).map_err(|error| { + invalid_argument(format!("{}: {}", definition.name, error.message())) + })?); + } + Ok(InterfacePlan { + name: definition.name, + iid: definition + .interface_type + .iid() + .expect("validated interface IID"), + methods, + }) + }) + .collect::>>()?; + Ok(Self { + interfaces, + threading, + }) + } + + /// Validate a single descriptor without requiring its companion views yet. + pub fn validate_interface(definition: &WinRtInterfaceDefinition) -> windows_core::Result<()> { + let mut standalone = definition.clone(); + standalone.required_iids.clear(); + Self::new(vec![standalone], WinRtThreadingPolicy::OwnerThread).map(|_| ()) + } +} + +impl MethodPlan { + fn new(definition: WinRtMethodDefinition) -> windows_core::Result { + let mut parameters = Vec::new(); + let mut native = Vec::new(); + let mut input_count = 0; + let mut output_count = 0; + for (index, (typ, direction)) in definition + .signature + .implementation_parameters()? + .into_iter() + .enumerate() + { + let array = typ.is_array(); + if direction == WinRtParameterDirection::FillArray && !array { + return Err(invalid_argument(format!( + "{} parameter {index}: FillArray requires a WinRT array type", + definition.name + ))); + } + let value = ValuePlan::new(if array { typ.array_element_type() } else { typ }) + .map_err(|error| { + invalid_argument(format!( + "{} parameter {index}: {}", + definition.name, + error.message() + )) + })?; + let abi_index = native.len() + 1; + if array { + native.push(if direction == WinRtParameterDirection::Out { + (CallbackAbiType::Pointer, Type::pointer()) + } else { + (CallbackAbiType::U32, Type::u32()) + }); + native.push((CallbackAbiType::Pointer, Type::pointer())); + } else if direction == WinRtParameterDirection::Out { + native.push((CallbackAbiType::Pointer, Type::pointer())); + } else { + native.push(value.callback_abi()); + } + if direction != WinRtParameterDirection::Out { + input_count += 1; + } + if direction != WinRtParameterDirection::In { + output_count += 1; + } + parameters.push(ParameterPlan { + abi_index, + direction, + value, + array, + }); + } + Ok(Self { + name: definition.name, + slot: definition.vtable_index, + parameters, + signature: CallbackSignature::hresult(native), + input_count, + output_count, + }) + } +} diff --git a/crates/dynwinrt/src/winrt_implementation/tests.rs b/crates/dynwinrt/src/winrt_implementation/tests.rs new file mode 100644 index 00000000..43b28ca3 --- /dev/null +++ b/crates/dynwinrt/src/winrt_implementation/tests.rs @@ -0,0 +1,1175 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::sync::atomic::{AtomicPtr, AtomicUsize}; + +use windows::{ + ApplicationModel::Background::{ + BackgroundTaskCanceledEventHandler, BackgroundTaskDeferral, BackgroundTaskRegistration, + IBackgroundTask, IBackgroundTaskInstance, IBackgroundTaskInstance_Impl, + }, + Foundation::{ + IClosable, IMemoryBufferReference, IReference, IStringable, MemoryBuffer, + TypedEventHandler, Uri, + }, + Win32::System::Com::CoTaskMemFree, +}; + +use crate::{ArrayData, MetadataTable, MethodSignature, TypeKind}; + +use super::*; + +const IID_FIXTURE: GUID = GUID::from_u128(0x4ab7eea7_29a1_4f48_a6da_22894e210ec0); +const IID_OTHER: GUID = GUID::from_u128(0x443bc92c_8c7f_4ab0_a8b1_60a765bddb49); + +fn definition( + table: &Arc, + name: &str, + iid: GUID, + signatures: Vec, +) -> WinRtInterfaceDefinition { + WinRtInterfaceDefinition { + name: name.into(), + interface_type: table.interface(iid), + required_iids: vec![], + methods: signatures + .into_iter() + .enumerate() + .map(|(index, signature)| WinRtMethodDefinition { + name: format!("Method{index}"), + vtable_index: 6 + index, + signature, + }) + .collect(), + } +} + +fn create( + definitions: Vec, + callback: impl Fn(usize, usize, &[WinRTValue]) -> windows_core::Result> + + Send + + Sync + + 'static, +) -> WinRtImplementation { + WinRtImplementation::new( + WinRtImplementationPlan::new(definitions, WinRtThreadingPolicy::OwnerThread).unwrap(), + Arc::new(callback), + Some("DynWinRt.Tests.Standalone"), + ) + .unwrap() +} + +fn query(owner: &WinRtImplementation, iid: &GUID) -> IUnknown { + owner + .to_value() + .unwrap() + .cast(iid) + .unwrap() + .as_object() + .unwrap() +} + +fn stringable_definition(table: &Arc) -> WinRtInterfaceDefinition { + definition( + table, + "Windows.Foundation.IStringable", + IStringable::IID, + vec![MethodSignature::new(table).add_out(table.hstring())], + ) +} + +#[test] +fn standalone_inspectable_has_canonical_identity_public_iids_and_weak_references() { + let table = MetadataTable::new(); + let closes = Arc::new(AtomicUsize::new(0)); + let callback_closes = closes.clone(); + let mut owner = create( + vec![ + stringable_definition(&table), + definition( + &table, + "Windows.Foundation.IClosable", + IClosable::IID, + vec![MethodSignature::new(&table)], + ), + ], + move |interface, slot, inputs| { + assert_eq!(slot, 6); + assert!(inputs.is_empty()); + if interface == 0 { + Ok(vec![WinRTValue::HString("standalone".into())]) + } else { + callback_closes.fetch_add(1, Ordering::SeqCst); + Ok(vec![]) + } + }, + ); + let canonical = owner.to_value().unwrap().as_object().unwrap(); + let stringable: IStringable = canonical.cast().unwrap(); + let closable: IClosable = canonical.cast().unwrap(); + assert_ne!(stringable.as_raw(), closable.as_raw()); + assert_eq!(stringable.cast::().unwrap(), canonical); + assert_eq!(closable.cast::().unwrap(), canonical); + let inspectable: IInspectable = closable.cast().unwrap(); + assert_eq!(inspectable.as_raw(), canonical.as_raw()); + assert_eq!( + inspectable.GetRuntimeClassName().unwrap(), + "DynWinRt.Tests.Standalone" + ); + assert_eq!(inspectable.GetTrustLevel().unwrap(), 0); + let mut count = 0; + let mut iids = ptr::null_mut(); + unsafe { + (inspectable.vtable().GetIids)(inspectable.as_raw(), &mut count, &mut iids) + .ok() + .unwrap(); + assert_eq!(count, 2); + assert_eq!( + &*ptr::slice_from_raw_parts(iids, count as usize), + &[IStringable::IID, IClosable::IID] + ); + CoTaskMemFree(Some(iids.cast())); + } + assert!(canonical.cast::().is_err()); + assert!(canonical.cast::().is_err()); + assert_eq!(stringable.ToString().unwrap(), "standalone"); + closable.Close().unwrap(); + assert_eq!(closes.load(Ordering::SeqCst), 1); + let weak = stringable.downgrade().unwrap(); + owner.release(); + assert_eq!(weak.upgrade().unwrap().ToString().unwrap(), "standalone"); + drop(inspectable); + drop(canonical); + drop(closable); + drop(stringable); + assert!(weak.upgrade().is_none()); + assert!(owner.is_closed()); +} + +#[test] +fn release_and_dispose_have_distinct_native_retention_semantics() { + let table = MetadataTable::new(); + let mut owner = create(vec![stringable_definition(&table)], |_, _, _| { + Ok(vec![WinRTValue::HString("retained".into())]) + }); + assert!(owner.has_unique_native_reference()); + let retained: IStringable = query(&owner, &IStringable::IID).cast().unwrap(); + assert!(!owner.has_unique_native_reference()); + owner.release(); + assert!(!owner.is_closed()); + assert_eq!(retained.ToString().unwrap(), "retained"); + assert_eq!(owner.to_value().unwrap_err().code(), RO_E_CLOSED); + owner.dispose().unwrap(); + owner.dispose().unwrap(); + assert!(owner.is_closed()); + assert_eq!(retained.ToString().unwrap_err().code(), RO_E_CLOSED); + assert!(owner.take_error().unwrap().contains("disconnected")); + assert!(owner.take_error().is_none()); +} + +#[test] +fn foreign_thread_callbacks_reject_before_language_entry_and_zero_outputs() { + let table = MetadataTable::new(); + let calls = Arc::new(AtomicUsize::new(0)); + let callback_calls = calls.clone(); + let owner = create(vec![stringable_definition(&table)], move |_, _, _| { + callback_calls.fetch_add(1, Ordering::SeqCst); + Ok(vec![WinRTValue::HString("owner thread".into())]) + }); + let value = owner.to_value().unwrap(); + thread::spawn(move || { + let object = value.as_object().unwrap(); + let stringable: IStringable = object.cast().unwrap(); + let mut output = ptr::null_mut(); + let hr = unsafe { (stringable.vtable().ToString)(stringable.as_raw(), &mut output) }; + assert_eq!(hr, RPC_E_WRONG_THREAD); + assert!(output.is_null()); + assert_eq!( + object + .cast::() + .unwrap() + .GetTrustLevel() + .unwrap(), + 0 + ); + }) + .join() + .unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(owner.take_error().unwrap().contains("creating thread")); + let stringable: IStringable = query(&owner, &IStringable::IID).cast().unwrap(); + assert_eq!(stringable.ToString().unwrap(), "owner thread"); +} + +#[test] +fn callback_errors_and_panics_are_hresult_failures() { + let table = MetadataTable::new(); + for panic in [false, true] { + let owner = create(vec![stringable_definition(&table)], move |_, _, _| { + if panic { + panic!("controlled callback panic"); + } + Err(error(E_INVALIDARG, "controlled callback exception")) + }); + let stringable: IStringable = query(&owner, &IStringable::IID).cast().unwrap(); + let mut output = ptr::null_mut(); + let hr = unsafe { (stringable.vtable().ToString)(stringable.as_raw(), &mut output) }; + assert_eq!(hr, if panic { E_FAIL } else { E_INVALIDARG }); + assert!(output.is_null()); + let message = owner.take_error().unwrap(); + assert!(message.contains(if panic { + "Rust panic" + } else { + "controlled callback exception" + })); + } +} + +struct DropCounter(Arc); + +impl Drop for DropCounter { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} + +#[test] +fn final_reentrant_release_keeps_static_and_dynamic_dispatch_alive() { + let table = MetadataTable::new(); + for dynamic in [false, true] { + let destroyed = Arc::new(AtomicUsize::new(0)); + let counter = DropCounter(destroyed.clone()); + let raw_reference = Arc::new(AtomicPtr::new(ptr::null_mut::())); + let callback_raw = raw_reference.clone(); + let signature = if dynamic { + MethodSignature::new(&table) + .add_in(table.f64_type()) + .add_out(table.hstring()) + } else { + MethodSignature::new(&table).add_out(table.hstring()) + }; + let mut owner = create( + vec![definition( + &table, + "Test.IReentrant", + IID_FIXTURE, + vec![signature.clone()], + )], + move |_, _, inputs| { + assert_eq!(inputs.len(), usize::from(dynamic)); + let raw = callback_raw.swap(ptr::null_mut(), Ordering::SeqCst); + assert!(!raw.is_null()); + drop(unsafe { IUnknown::from_raw(raw) }); + assert_eq!(counter.0.load(Ordering::SeqCst), 0); + Ok(vec![WinRTValue::HString("completed after Release".into())]) + }, + ); + let raw = query(&owner, &IID_FIXTURE).into_raw(); + raw_reference.store(raw, Ordering::SeqCst); + owner.release(); + let outputs = signature + .build(6) + .call_dynamic( + raw, + if dynamic { + &[WinRTValue::F64(42.5)] + } else { + &[] + }, + ) + .unwrap(); + assert_eq!(outputs[0].as_hstring().unwrap(), "completed after Release"); + assert_eq!(destroyed.load(Ordering::SeqCst), 1); + assert!(owner.is_closed()); + } +} + +#[test] +fn reentrant_disconnection_allows_current_callback_to_finish() { + let table = MetadataTable::new(); + let control = Arc::new(Mutex::new(None::>)); + let callback_control = control.clone(); + let owner = create(vec![stringable_definition(&table)], move |_, _, _| { + let control = callback_control + .lock() + .unwrap() + .as_ref() + .unwrap() + .upgrade() + .unwrap(); + control.disconnect().unwrap(); + Ok(vec![WinRTValue::HString("already entered".into())]) + }); + *control.lock().unwrap() = Some(Arc::downgrade(&owner.control)); + let stringable: IStringable = query(&owner, &IStringable::IID).cast().unwrap(); + assert_eq!(stringable.ToString().unwrap(), "already entered"); + assert_eq!(stringable.ToString().unwrap_err().code(), RO_E_CLOSED); +} + +#[test] +fn multi_output_conversion_is_atomic_and_releases_prepared_references() { + let table = MetadataTable::new(); + let destroyed = Arc::new(AtomicUsize::new(0)); + let counter = DropCounter(destroyed.clone()); + let mut returned = create(vec![stringable_definition(&table)], move |_, _, _| { + let _ = &counter; + Ok(vec![WinRTValue::HString("child".into())]) + }); + let returned_value = returned.to_value().unwrap(); + let pending = Arc::new(Mutex::new(Some(returned_value))); + returned.release(); + let signature = MethodSignature::new(&table) + .add_out(table.interface(IStringable::IID)) + .add_out(table.hstring()) + .add_out(table.u32_type()); + let callback_pending = pending.clone(); + let owner = create( + vec![definition( + &table, + "Test.IAtomicOutputs", + IID_FIXTURE, + vec![signature], + )], + move |_, _, _| { + Ok(vec![ + callback_pending.lock().unwrap().take().unwrap(), + WinRTValue::HString("prepared string".into()), + WinRTValue::Bool(true), + ]) + }, + ); + let object = query(&owner, &IID_FIXTURE); + let function: unsafe extern "system" fn( + *mut c_void, + *mut *mut c_void, + *mut *mut c_void, + *mut u32, + ) -> HRESULT = + unsafe { std::mem::transmute(*(*(object.as_raw().cast::<*const *const c_void>())).add(6)) }; + let mut reference = ptr::null_mut(); + let mut string = ptr::null_mut(); + let mut number = 99; + assert_eq!( + unsafe { function(object.as_raw(), &mut reference, &mut string, &mut number) }, + E_INVALIDARG + ); + assert!(reference.is_null()); + assert!(string.is_null()); + assert_eq!(number, 0); + assert_eq!(destroyed.load(Ordering::SeqCst), 1); + assert!(owner.take_error().unwrap().contains("expected u4")); +} + +#[test] +fn primitives_guid_structs_and_nullable_references_cross_native_vtables() { + let table = MetadataTable::new(); + let point = table.struct_type("Test.Point", &[table.f32_type(), table.f32_type()]); + let holder = table.struct_type( + "Test.Holder", + &[point.clone(), table.hstring(), table.object()], + ); + let uri = Uri::CreateUri(&HSTRING::from("https://example.com/borrowed")).unwrap(); + let mut point_value = point.default_value(); + point_value.set_field(0, 3.5f32); + point_value.set_field(1, -8.25f32); + let mut holder_value = holder.default_value(); + holder_value.set_field_struct(0, &point_value); + holder_value + .set_field_hstring(1, "retained field".into()) + .unwrap(); + holder_value + .set_field_object(2, Some(&uri.cast().unwrap())) + .unwrap(); + let enum_type = table.enum_type("Test.Mode", vec![("A".into(), 3)]); + let shapes = vec![ + (table.bool_type(), WinRTValue::Bool(true)), + (table.i8_type(), WinRTValue::I8(-7)), + (table.u8_type(), WinRTValue::U8(250)), + (table.i16_type(), WinRTValue::I16(-300)), + (table.char16_type(), WinRTValue::U16(0x263a)), + (table.i32_type(), WinRTValue::I32(-42)), + (table.hresult(), WinRTValue::HResult(E_FAIL)), + (table.u32_type(), WinRTValue::U32(4_000_000_000)), + (table.i64_type(), WinRTValue::I64(i64::MIN + 10)), + (table.u64_type(), WinRTValue::U64(u64::MAX - 10)), + (table.f32_type(), WinRTValue::F32(3.125)), + (table.f64_type(), WinRTValue::F64(-1.75)), + (table.guid_type(), WinRTValue::Guid(IID_FIXTURE)), + (table.hstring(), WinRTValue::HString("owned string".into())), + (enum_type, WinRTValue::I32(3)), + (holder.clone(), WinRTValue::Struct(holder_value)), + (table.object(), WinRTValue::Object(uri.cast().unwrap())), + (table.object(), WinRTValue::Null), + ]; + for (typ, value) in shapes { + let signature = MethodSignature::new(&table) + .add_in(typ.clone()) + .add_out(typ.clone()); + let captured = Arc::new(Mutex::new(None)); + let callback_captured = captured.clone(); + let owner = create( + vec![definition( + &table, + "Test.IEcho", + IID_FIXTURE, + vec![signature.clone()], + )], + move |_, _, inputs| { + *callback_captured.lock().unwrap() = Some(inputs[0].clone()); + Ok(vec![inputs[0].clone()]) + }, + ); + let object = query(&owner, &IID_FIXTURE); + let outputs = signature + .build(6) + .call_dynamic(object.as_raw(), &[value]) + .unwrap(); + let retained = captured.lock().unwrap().take().unwrap(); + match (typ.kind(), &outputs[0], retained) { + (TypeKind::Struct(_), WinRTValue::Struct(output), WinRTValue::Struct(retained)) => { + assert_eq!(output.get_field_hstring(1).unwrap(), "retained field"); + assert_eq!(retained.get_field_struct(0).get_field::(1), -8.25); + assert_eq!( + output + .get_field_object(2) + .unwrap() + .unwrap() + .cast::() + .unwrap() + .Host() + .unwrap(), + "example.com" + ); + } + (TypeKind::Object, WinRTValue::Null, WinRTValue::Null) => {} + (TypeKind::Object, WinRTValue::Object(output), WinRTValue::Object(retained)) => { + assert_eq!( + output.cast::().unwrap(), + retained.cast::().unwrap() + ); + } + (_, output, retained) => assert_eq!(format!("{output:?}"), format!("{retained:?}")), + } + } +} + +#[test] +fn pass_receive_and_fill_arrays_preserve_element_ownership() { + let table = MetadataTable::new(); + let record = table.struct_type("Test.ArrayRecord", &[table.hstring(), table.u64_type()]); + let mut record_value = record.default_value(); + record_value + .set_field_hstring(0, "array record".into()) + .unwrap(); + record_value.set_field(1, u64::MAX - 3); + let object = Uri::CreateUri(&HSTRING::from("https://example.com/array")).unwrap(); + let cases = [ + ( + table.u8_type(), + vec![WinRTValue::U8(1), WinRTValue::U8(255)], + ), + ( + table.f64_type(), + vec![WinRTValue::F64(0.25), WinRTValue::F64(-2.5)], + ), + ( + table.guid_type(), + vec![WinRTValue::Guid(IID_FIXTURE), WinRTValue::Guid(IID_OTHER)], + ), + ( + table.hstring(), + vec![ + WinRTValue::HString("first".into()), + WinRTValue::HString("second".into()), + ], + ), + ( + table.object(), + vec![WinRTValue::Object(object.cast().unwrap()), WinRTValue::Null], + ), + (record, vec![WinRTValue::Struct(record_value)]), + ]; + for (element, values) in cases { + for empty in [false, true] { + let input = ArrayData::from_values(element.clone(), if empty { &[] } else { &values }); + let fill = ArrayData::from_values(element.clone(), if empty { &[] } else { &values }); + let array_type = table.array(&element); + let signature = MethodSignature::new(&table) + .add_in(array_type.clone()) + .add_out(array_type.clone()) + .add_out_fill(array_type); + let owner = create( + vec![definition( + &table, + "Test.IArrays", + IID_FIXTURE, + vec![signature.clone()], + )], + |_, _, inputs| { + let [WinRTValue::Array(array), WinRTValue::U32(capacity)] = inputs else { + panic!("expected array plus fill capacity"); + }; + assert_eq!(array.len(), *capacity as usize); + Ok(vec![ + WinRTValue::Array(array.clone()), + WinRTValue::Array(array.clone()), + ]) + }, + ); + let view = query(&owner, &IID_FIXTURE); + let result = signature + .build(6) + .call_dynamic( + view.as_raw(), + &[WinRTValue::Array(input), WinRTValue::Array(fill)], + ) + .unwrap(); + assert_eq!(result.len(), 2); + for output in result { + let WinRTValue::Array(array) = output else { + panic!("array output expected") + }; + assert_eq!(array.len(), if empty { 0 } else { values.len() }); + for index in 0..array.len() { + match (array.get(index), &values[index]) { + (WinRTValue::Struct(output), WinRTValue::Struct(expected)) => { + assert_eq!( + output.get_field_hstring(0).unwrap(), + expected.get_field_hstring(0).unwrap() + ); + assert_eq!(output.get_field::(1), expected.get_field::(1)); + } + (WinRTValue::Object(output), WinRTValue::Object(expected)) => { + assert_eq!( + output.cast::().unwrap(), + expected.cast::().unwrap() + ); + } + (output, expected) => { + assert_eq!(format!("{output:?}"), format!("{expected:?}")) + } + } + } + } + } + } +} + +#[test] +fn invalid_outputs_never_publish_partial_arrays() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_out(table.array(&table.hstring())) + .add_out(table.u32_type()); + let owner = create( + vec![definition( + &table, + "Test.IFailedArray", + IID_FIXTURE, + vec![signature], + )], + move |_, _, _| { + Ok(vec![ + WinRTValue::Array(ArrayData::from_values( + table.hstring(), + &[WinRTValue::HString("first".into()), WinRTValue::Bool(true)], + )), + WinRTValue::U32(4), + ]) + }, + ); + let view = query(&owner, &IID_FIXTURE); + let function: unsafe extern "system" fn( + *mut c_void, + *mut u32, + *mut *mut c_void, + *mut u32, + ) -> HRESULT = + unsafe { std::mem::transmute(*(*(view.as_raw().cast::<*const *const c_void>())).add(6)) }; + let mut length = 99; + let mut data = ptr::null_mut(); + let mut number = 99; + let hr = unsafe { function(view.as_raw(), &mut length, &mut data, &mut number) }; + assert_eq!(hr, E_INVALIDARG); + assert_eq!(length, 0); + assert!(data.is_null()); + assert_eq!(number, 0); +} + +#[test] +fn null_output_slots_are_rejected_after_initializing_other_outputs() { + let table = MetadataTable::new(); + let signature = MethodSignature::new(&table) + .add_out(table.i32_type()) + .add_out(table.u64_type()); + let owner = create( + vec![definition( + &table, + "Test.INullOutputs", + IID_FIXTURE, + vec![signature], + )], + |_, _, _| panic!("null outputs must fail before dispatch"), + ); + let view = query(&owner, &IID_FIXTURE); + let function: unsafe extern "system" fn(*mut c_void, *mut i32, *mut u64) -> HRESULT = + unsafe { std::mem::transmute(*(*(view.as_raw().cast::<*const *const c_void>())).add(6)) }; + let mut output = u64::MAX; + assert_eq!( + unsafe { function(view.as_raw(), ptr::null_mut(), &mut output) }, + E_POINTER + ); + assert_eq!(output, 0); +} + +#[test] +fn invalid_and_incomplete_descriptors_fail_before_publication() { + let table = MetadataTable::new(); + let validate = |definition: WinRtInterfaceDefinition| { + WinRtImplementationPlan::new(vec![definition], WinRtThreadingPolicy::OwnerThread) + }; + let mut missing_slot = stringable_definition(&table); + missing_slot.methods[0].vtable_index = 7; + assert!( + validate(missing_slot) + .unwrap_err() + .message() + .contains("contiguous slot") + ); + let mut required = stringable_definition(&table); + required.required_iids.push(IClosable::IID); + assert!( + validate(required) + .unwrap_err() + .message() + .contains("requires a separate") + ); + let mut cycle = stringable_definition(&table); + cycle.required_iids.push(IStringable::IID); + assert!(validate(cycle).unwrap_err().message().contains("cyclic")); + let mut generic = stringable_definition(&table); + generic.interface_type = table.generic(crate::metadata_table::IVECTOR, 1); + assert!( + validate(generic) + .unwrap_err() + .message() + .contains("non-generic") + ); + for typ in [ + table.generic(crate::metadata_table::IVECTOR, 1), + table.array(&table.array(&table.u8_type())), + table.struct_type("Test.Empty", &[]), + table.interface(GUID::zeroed()), + ] { + assert!( + validate(definition( + &table, + "Test.IUnsupported", + IID_FIXTURE, + vec![MethodSignature::new(&table).add_in(typ)], + )) + .is_err() + ); + } + assert!( + validate(definition( + &table, + "Test.IBadFill", + IID_FIXTURE, + vec![MethodSignature::new(&table).add_out_fill(table.u8_type())], + )) + .unwrap_err() + .message() + .contains("FillArray") + ); + for iid in [ + GUID::zeroed(), + IUnknown::IID, + IInspectable::IID, + windows_core::imp::IAgileObject::IID, + windows_core::imp::IMarshal::IID, + ] { + assert!(validate(definition(&table, "Test.IReserved", iid, vec![])).is_err()); + } + assert!( + WinRtImplementationPlan::new( + vec![stringable_definition(&table), stringable_definition(&table)], + WinRtThreadingPolicy::OwnerThread, + ) + .unwrap_err() + .message() + .contains("Duplicate") + ); + assert!( + values::ValuePlan::new(table.guid_type()) + .unwrap() + .array_bytes(usize::MAX) + .is_err() + ); +} + +#[test] +fn required_interfaces_use_independent_complete_vtables() { + let table = MetadataTable::new(); + let mut first = stringable_definition(&table); + first.required_iids.push(IClosable::IID); + let owner = create( + vec![ + first, + definition( + &table, + "Windows.Foundation.IClosable", + IClosable::IID, + vec![MethodSignature::new(&table)], + ), + ], + |index, _, _| { + if index == 0 { + Ok(vec![WinRTValue::HString("required views".into())]) + } else { + Ok(vec![]) + } + }, + ); + let first: IStringable = query(&owner, &IStringable::IID).cast().unwrap(); + let required: IClosable = first.cast().unwrap(); + assert_ne!(first.as_raw(), required.as_raw()); + assert_eq!(first.ToString().unwrap(), "required views"); + required.Close().unwrap(); + assert_eq!( + first.cast::().unwrap(), + required.cast::().unwrap() + ); +} + +#[test] +fn struct_outputs_require_exact_type_identity() { + let table = MetadataTable::new(); + let expected = table.struct_type("Test.Expected", &[table.f64_type()]); + let actual = table.struct_type("Test.Actual", &[table.f64_type()]); + let value = WinRTValue::Struct(actual.default_value()); + let signature = MethodSignature::new(&table).add_out(expected); + let owner = create( + vec![definition( + &table, + "Test.IStructOutput", + IID_FIXTURE, + vec![signature.clone()], + )], + move |_, _, _| Ok(vec![value.clone()]), + ); + let view = query(&owner, &IID_FIXTURE); + assert_eq!( + signature + .build(6) + .call_dynamic(view.as_raw(), &[]) + .unwrap_err() + .code(), + E_INVALIDARG + ); +} + +#[test] +fn immutable_winrt_plans_and_host_state_are_send_sync() { + fn assert_send_sync() {} + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); +} + +#[windows_core::implement(IBackgroundTaskInstance)] +struct BackgroundInstance { + progress: Arc, +} + +impl IBackgroundTaskInstance_Impl for BackgroundInstance_Impl { + fn InstanceId(&self) -> windows_core::Result { + Ok(IID_FIXTURE) + } + + fn Task(&self) -> windows_core::Result { + Err(error( + crate::com_helpers::E_NOTIMPL, + "Fixture has no OS task registration", + )) + } + + fn Progress(&self) -> windows_core::Result { + Ok(self.progress.load(Ordering::SeqCst) as u32) + } + + fn SetProgress(&self, value: u32) -> windows_core::Result<()> { + self.progress.store(value as usize, Ordering::SeqCst); + Ok(()) + } + + fn TriggerDetails(&self) -> windows_core::Result { + Err(error( + crate::com_helpers::E_NOTIMPL, + "Fixture has no OS trigger", + )) + } + + fn Canceled( + &self, + _: windows_core::Ref, + ) -> windows_core::Result { + Err(error( + crate::com_helpers::E_NOTIMPL, + "Fixture has no cancellation source", + )) + } + + fn RemoveCanceled(&self, _: i64) -> windows_core::Result<()> { + Err(error( + crate::com_helpers::E_NOTIMPL, + "Fixture has no cancellation source", + )) + } + + fn SuspendedCount(&self) -> windows_core::Result { + Ok(0) + } + + fn GetDeferral(&self) -> windows_core::Result { + Err(error( + crate::com_helpers::E_NOTIMPL, + "Fixture does not create OS deferrals", + )) + } +} + +#[test] +fn background_task_uses_the_same_generic_host_and_real_native_caller() { + let table = MetadataTable::new(); + let retained = Arc::new(Mutex::new(None::)); + let callback_retained = retained.clone(); + let owner = create( + vec![definition( + &table, + "Windows.ApplicationModel.Background.IBackgroundTask", + IBackgroundTask::IID, + vec![ + MethodSignature::new(&table).add_in(table.interface(IBackgroundTaskInstance::IID)), + ], + )], + move |_, _, inputs| { + let task: IBackgroundTaskInstance = inputs[0].as_object().unwrap().cast()?; + assert_eq!(task.InstanceId()?, IID_FIXTURE); + task.SetProgress(73)?; + *callback_retained.lock().unwrap() = Some(inputs[0].clone()); + Ok(vec![]) + }, + ); + let progress = Arc::new(AtomicUsize::new(0)); + let instance: IBackgroundTaskInstance = BackgroundInstance { + progress: progress.clone(), + } + .into(); + let task: IBackgroundTask = query(&owner, &IBackgroundTask::IID).cast().unwrap(); + task.Run(&instance).unwrap(); + drop(instance); + assert_eq!(progress.load(Ordering::SeqCst), 73); + let retained: IBackgroundTaskInstance = retained + .lock() + .unwrap() + .take() + .unwrap() + .as_object() + .unwrap() + .cast() + .unwrap(); + assert_eq!(retained.Progress().unwrap(), 73); +} + +#[test] +fn properties_and_event_accessors_bridge_native_delegate_values() { + type ClosedHandler = TypedEventHandler; + let table = MetadataTable::new(); + let mut reference = definition( + &table, + "Windows.Foundation.IMemoryBufferReference", + IMemoryBufferReference::IID, + vec![ + MethodSignature::new(&table).add_out(table.u32_type()), + MethodSignature::new(&table) + .add_in(table.delegate(ClosedHandler::IID)) + .add_out(table.i64_type()), + MethodSignature::new(&table).add_in(table.i64_type()), + ], + ); + reference.required_iids.push(IClosable::IID); + let current_handler = Arc::new(Mutex::new(None::)); + let callback_handler = current_handler.clone(); + let sender = MemoryBuffer::Create(24).unwrap().CreateReference().unwrap(); + let callback_sender = WinRTValue::Object(sender.cast().unwrap()); + let owner = create( + vec![ + reference, + definition( + &table, + "Windows.Foundation.IClosable", + IClosable::IID, + vec![MethodSignature::new(&table)], + ), + ], + move |interface, slot, inputs| { + if interface == 1 { + let handler = callback_handler.lock().unwrap().clone(); + if let Some(handler) = handler { + let handler: ClosedHandler = handler.as_object().unwrap().cast()?; + let sender: IMemoryBufferReference = + callback_sender.as_object().unwrap().cast()?; + handler.Invoke(&sender, None)?; + } + return Ok(vec![]); + } + match slot { + 6 => Ok(vec![WinRTValue::U32(64)]), + 7 => { + *callback_handler.lock().unwrap() = Some(inputs[0].clone()); + Ok(vec![WinRTValue::I64(42)]) + } + 8 => { + assert!(matches!(inputs, [WinRTValue::I64(42)])); + *callback_handler.lock().unwrap() = None; + Ok(vec![]) + } + _ => Err(error( + crate::com_helpers::E_NOTIMPL, + "Unexpected fixture slot", + )), + } + }, + ); + let reference: IMemoryBufferReference = + query(&owner, &IMemoryBufferReference::IID).cast().unwrap(); + assert_eq!(reference.Capacity().unwrap(), 64); + let received = Arc::new(AtomicUsize::new(0)); + let callback_received = received.clone(); + let handler = ClosedHandler::new(move |sender, _| { + callback_received.fetch_add( + sender.as_ref().unwrap().Capacity()? as usize, + Ordering::SeqCst, + ); + Ok(()) + }); + let token = reference.Closed(&handler).unwrap(); + drop(handler); + reference.Close().unwrap(); + assert_eq!(received.load(Ordering::SeqCst), 24); + reference.RemoveClosed(token).unwrap(); + reference.Close().unwrap(); + assert_eq!(received.load(Ordering::SeqCst), 24); + assert!(current_handler.lock().unwrap().is_none()); +} + +#[test] +fn closed_generic_nullable_values_pass_without_implementing_generic_interfaces() { + let table = MetadataTable::new(); + let generic = table.generic(crate::metadata_table::IREFERENCE, 1); + let reference = table.parameterized(&generic, &[table.u32_type()]); + let signature = MethodSignature::new(&table) + .add_in(reference.clone()) + .add_out(reference); + let owner = create( + vec![definition( + &table, + "Test.IOptionalValue", + IID_FIXTURE, + vec![signature.clone()], + )], + |_, _, inputs| Ok(vec![inputs[0].clone()]), + ); + let view = query(&owner, &IID_FIXTURE); + let method = signature.build(6); + let boxed = crate::box_ireference(WinRTValue::U32(19), table.u32_type()).unwrap(); + let outputs = method.call_dynamic(view.as_raw(), &[boxed]).unwrap(); + let value: IReference = outputs[0].as_object().unwrap().cast().unwrap(); + assert_eq!(value.Value().unwrap(), 19); + assert!(matches!( + method + .call_dynamic(view.as_raw(), &[WinRTValue::Null]) + .unwrap()[0], + WinRTValue::Null + )); +} + +#[test] +fn established_projection_aliases_are_checked_and_preserved_in_outputs() { + let table = MetadataTable::new(); + for (typ, number) in [ + (table.i8_type(), -127), + (table.u8_type(), 255), + (table.char16_type(), 0x263a), + ] { + let plan = values::ValuePlan::new(typ).unwrap(); + assert!(plan.prepare(&WinRTValue::I32(number)).is_ok()); + assert!(plan.prepare(&WinRTValue::I32(i32::MAX)).is_err()); + } + + let other_table = MetadataTable::new(); + let enum_type = table.enum_type("Test.ArrayAliasEnum", vec![]); + for (expected, actual, values) in [ + ( + table.u32_type(), + other_table.u32_type(), + vec![WinRTValue::U32(8)], + ), + ( + table.u16_type(), + table.char16_type(), + vec![WinRTValue::U16(65)], + ), + ( + table.char16_type(), + table.u16_type(), + vec![WinRTValue::U16(66)], + ), + (enum_type, table.i32_type(), vec![WinRTValue::I32(3)]), + ] { + let signature = MethodSignature::new(&table).add_out(table.array(&expected)); + let result = WinRTValue::Array(ArrayData::from_values(actual, &values)); + let owner = create( + vec![definition( + &table, + "Test.IArrayAlias", + IID_FIXTURE, + vec![signature.clone()], + )], + move |_, _, _| Ok(vec![result.clone()]), + ); + let view = query(&owner, &IID_FIXTURE); + assert!(signature.build(6).call_dynamic(view.as_raw(), &[]).is_ok()); + } +} + +#[test] +fn failed_weak_resolve_racing_final_release_destroys_the_host() { + use windows::Win32::System::WinRT::{IWeakReference, IWeakReferenceSource}; + + let table = MetadataTable::new(); + let destroyed = Arc::new(AtomicUsize::new(0)); + let counter = DropCounter(destroyed.clone()); + let mut owner = create(vec![stringable_definition(&table)], move |_, _, _| { + let _ = &counter; + Ok(vec![WinRTValue::HString("weak target".into())]) + }); + let source: IWeakReferenceSource = owner + .to_value() + .unwrap() + .as_object() + .unwrap() + .cast() + .unwrap(); + let canonical = source.cast::().unwrap(); + assert_eq!(canonical, owner.to_value().unwrap().as_object().unwrap()); + drop(canonical); + let weak = unsafe { source.GetWeakReference().unwrap() }; + drop(source); + let upgraded = Arc::new(std::sync::Barrier::new(2)); + let resume = Arc::new(std::sync::Barrier::new(2)); + let hook_upgraded = upgraded.clone(); + let hook_resume = resume.clone(); + let native = unsafe { &*weak.as_raw().cast::() }; + native.after_upgrade(move || { + hook_upgraded.wait(); + hook_resume.wait(); + }); + let worker_weak = WinRTValue::Object(weak.cast().unwrap()); + let worker = thread::spawn(move || { + let weak: IWeakReference = worker_weak.as_object().unwrap().cast().unwrap(); + let mut result = ptr::null_mut(); + let hr = unsafe { (weak.vtable().Resolve)(weak.as_raw(), &IClosable::IID, &mut result) }; + assert_eq!(hr, E_NOINTERFACE); + assert!(result.is_null()); + }); + upgraded.wait(); + owner.release(); + assert_eq!(destroyed.load(Ordering::SeqCst), 0); + resume.wait(); + worker.join().unwrap(); + assert_eq!(destroyed.load(Ordering::SeqCst), 1); + assert!(owner.is_closed()); + let mut result = ptr::null_mut(); + assert_eq!( + unsafe { (weak.vtable().Resolve)(weak.as_raw(), &IStringable::IID, &mut result) }, + S_OK + ); + assert!(result.is_null()); + assert!(weak.cast::().is_ok()); + assert!(weak.cast::().is_err()); +} + +#[test] +fn async_array_values_keep_their_declared_async_type_in_all_directions() { + use windows::Storage::StorageFile; + + let table = MetadataTable::new(); + let file_type = table.runtime_class( + "Windows.Storage.StorageFile".into(), + &table.interface(StorageFile::IID), + ); + let operation = StorageFile::GetFileFromPathAsync(&HSTRING::from( + std::env::current_exe().unwrap().to_string_lossy().as_ref(), + )) + .unwrap(); + let async_type = table.async_operation(&file_type); + let generic_type = table.parameterized( + &table.generic(crate::metadata_table::IASYNC_OPERATION, 1), + &[file_type], + ); + let value = WinRTValue::Async(crate::AsyncInfo { + info: operation.cast().unwrap(), + async_type: async_type.clone(), + }); + for element in [async_type, generic_type] { + for direction in 0..3 { + let array_type = table.array(&element); + let signature = match direction { + 0 => MethodSignature::new(&table) + .add_in(array_type.clone()) + .add_out(array_type), + 1 => MethodSignature::new(&table).add_out(array_type), + _ => MethodSignature::new(&table).add_out_fill(array_type), + }; + let array = WinRTValue::Array(ArrayData::from_values( + element.clone(), + &[value.clone(), WinRTValue::Null], + )); + let returned = array.clone(); + let owner = create( + vec![definition( + &table, + "Test.IAsyncArray", + IID_FIXTURE, + vec![signature.clone()], + )], + move |_, _, inputs| { + if direction == 0 { + let WinRTValue::Array(values) = &inputs[0] else { + panic!("expected array") + }; + assert!(matches!(values.get(0), WinRTValue::Async(_))); + } + Ok(vec![returned.clone()]) + }, + ); + let view = query(&owner, &IID_FIXTURE); + let inputs = if direction == 1 { vec![] } else { vec![array] }; + let outputs = signature + .build(6) + .call_dynamic(view.as_raw(), &inputs) + .unwrap(); + let WinRTValue::Array(values) = &outputs[0] else { + panic!("expected array") + }; + let WinRTValue::Async(result) = values.get(0) else { + panic!("native array element lost its async type"); + }; + assert_eq!(result.iid(), element.iid().unwrap()); + assert!(matches!(values.get(1), WinRTValue::Null)); + } + } +} diff --git a/crates/dynwinrt/src/winrt_implementation/values.rs b/crates/dynwinrt/src/winrt_implementation/values.rs new file mode 100644 index 00000000..8d3bda12 --- /dev/null +++ b/crates/dynwinrt/src/winrt_implementation/values.rs @@ -0,0 +1,607 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use core::ffi::c_void; +use std::ptr; + +use libffi::middle::Type; +use windows::Win32::System::Com::{CoTaskMemAlloc, CoTaskMemFree}; +use windows_core::{GUID, HRESULT, HSTRING, IInspectable, IUnknown, Interface}; + +use crate::{ + ArrayData, TypeHandle, TypeKind, ValueTypeData, WinRTValue, native_callback::CallbackAbiType, + signature::WinRtParameterDirection, +}; + +use super::{ + E_OUTOFMEMORY, E_POINTER, error, invalid_argument, + plan::{MethodPlan, ParameterPlan}, +}; + +#[derive(Debug, Clone)] +pub(super) struct ValuePlan { + pub typ: TypeHandle, + pub size: usize, + pub align: usize, + iid: Option, + fields: Vec<(usize, ValuePlan)>, +} + +impl ValuePlan { + pub fn new(typ: TypeHandle) -> windows_core::Result { + Self::with_depth(typ, 0) + } + + fn with_depth(typ: TypeHandle, depth: usize) -> windows_core::Result { + if depth > 64 { + return Err(invalid_argument("WinRT struct nesting exceeds 64 levels")); + } + match typ.kind() { + TypeKind::Array(_) => { + return Err(invalid_argument( + "Nested arrays and array-valued struct fields are not WinRT callback values", + )); + } + TypeKind::Generic { .. } => { + return Err(invalid_argument( + "Open generic types cannot appear in a WinRT callback", + )); + } + TypeKind::OutValue(_) | TypeKind::ArrayOfIUnknown => { + return Err(invalid_argument( + "Legacy ABI-only types do not describe a complete WinRT callback contract", + )); + } + _ => {} + } + typ.table() + .try_closed_signature_string_kind(typ.kind()) + .map_err(|cause| invalid_argument(cause.message()))?; + let iid = if typ.kind().is_com_pointer() { + let iid = if typ.kind() == TypeKind::Object { + IInspectable::IID + } else { + typ.iid().ok_or_else(|| { + invalid_argument("WinRT callback reference has no resolved IID") + })? + }; + if iid == GUID::zeroed() { + return Err(invalid_argument( + "WinRT callback reference has an empty IID", + )); + } + Some(iid) + } else { + None + }; + let size = typ.size_of(); + let align = typ.align_of(); + if size == 0 || align == 0 || !align.is_power_of_two() || size % align != 0 { + return Err(invalid_argument( + "WinRT callback value has an incomplete ABI layout", + )); + } + let mut fields = Vec::new(); + if matches!(typ.kind(), TypeKind::Struct(_)) { + let mut end = 0; + for index in 0..typ.field_count() { + let field = Self::with_depth(typ.field_type(index), depth + 1)?; + let offset = typ.field_offset(index); + let field_end = offset + .checked_add(field.size) + .ok_or_else(|| invalid_argument("WinRT struct field layout overflows"))?; + if offset < end || offset % field.align != 0 || field_end > size { + return Err(invalid_argument("WinRT struct field layout is incomplete")); + } + end = field_end; + fields.push((offset, field)); + } + if fields.is_empty() { + return Err(invalid_argument( + "Empty WinRT structs cannot be passed by value", + )); + } + } + Ok(Self { + typ, + size, + align, + iid, + fields, + }) + } + + pub fn callback_abi(&self) -> (CallbackAbiType, Type) { + let abi = match self.typ.kind() { + TypeKind::I8 => CallbackAbiType::I8, + TypeKind::Bool | TypeKind::U8 => CallbackAbiType::U8, + TypeKind::I16 => CallbackAbiType::I16, + TypeKind::U16 | TypeKind::Char16 => CallbackAbiType::U16, + TypeKind::I32 | TypeKind::Enum(_) | TypeKind::HResult => CallbackAbiType::I32, + TypeKind::U32 => CallbackAbiType::U32, + TypeKind::I64 => CallbackAbiType::I64, + TypeKind::U64 => CallbackAbiType::U64, + TypeKind::F32 => CallbackAbiType::F32, + TypeKind::F64 => CallbackAbiType::F64, + TypeKind::Guid => CallbackAbiType::Guid, + TypeKind::Struct(_) => { + CallbackAbiType::NativeStruct(self.typ.signature_string(), self.size) + } + _ => CallbackAbiType::Pointer, + }; + (abi, self.typ.libffi_type()) + } + + pub fn array_bytes(&self, length: usize) -> windows_core::Result { + length + .checked_mul(self.size) + .filter(|size| *size <= isize::MAX as usize) + .ok_or_else(|| { + invalid_argument("WinRT array byte length overflows the native address size") + }) + } + + pub unsafe fn read_borrowed(&self, source: *const c_void) -> windows_core::Result { + if source.is_null() { + return Err(error(E_POINTER, "Null WinRT callback value storage")); + } + macro_rules! scalar { + ($ty:ty, $variant:ident) => { + WinRTValue::$variant(unsafe { source.cast::<$ty>().read_unaligned() }) + }; + } + Ok(match self.typ.kind() { + TypeKind::Bool => WinRTValue::Bool(unsafe { source.cast::().read() } != 0), + TypeKind::I8 => scalar!(i8, I8), + TypeKind::U8 => scalar!(u8, U8), + TypeKind::I16 => scalar!(i16, I16), + TypeKind::U16 | TypeKind::Char16 => scalar!(u16, U16), + TypeKind::I32 => scalar!(i32, I32), + TypeKind::U32 => scalar!(u32, U32), + TypeKind::I64 => scalar!(i64, I64), + TypeKind::U64 => scalar!(u64, U64), + TypeKind::F32 => scalar!(f32, F32), + TypeKind::F64 => scalar!(f64, F64), + TypeKind::Guid => scalar!(GUID, Guid), + TypeKind::HResult => scalar!(HRESULT, HResult), + TypeKind::Enum(_) => WinRTValue::Enum { + value: unsafe { source.cast::().read_unaligned() }, + type_handle: self.typ.clone(), + }, + TypeKind::HString => { + let raw = unsafe { source.cast::<*mut c_void>().read_unaligned() }; + let borrowed = unsafe { &*ptr::from_ref(&raw).cast::() }; + WinRTValue::HString(borrowed.clone()) + } + TypeKind::Struct(_) => { + WinRTValue::Struct(unsafe { self.prepare_borrowed_struct(source)? }) + } + kind if kind.is_com_pointer() => { + let raw = unsafe { source.cast::<*mut c_void>().read_unaligned() }; + if raw.is_null() { + WinRTValue::Null + } else { + let borrowed = unsafe { IUnknown::from_raw_borrowed(&raw) } + .ok_or_else(|| error(E_POINTER, "Null WinRT callback interface"))?; + let owned = borrowed.clone(); + if self.typ.is_async() { + self.typ + .from_out(owned.into_raw()) + .map_err(|cause| invalid_argument(cause.message()))? + } else { + WinRTValue::Object(owned) + } + } + } + _ => return Err(invalid_argument("Unsupported WinRT callback value plan")), + }) + } + + pub fn prepare(&self, value: &WinRTValue) -> windows_core::Result { + let coerced = if self.iid.is_none() { + crate::native_call::coerce_scalar_input(&self.typ, value).map_err(|cause| { + error( + cause.code(), + format!("WinRT callback output: {}", cause.message()), + ) + })? + } else { + None + }; + let value = coerced.as_ref().unwrap_or(value); + macro_rules! primitive { + ($value:expr, $variant:ident) => { + Ok(PreparedValue::$variant(*$value)) + }; + } + match (self.typ.kind(), value) { + (TypeKind::Bool, WinRTValue::Bool(value)) => primitive!(value, Bool), + (TypeKind::I8, WinRTValue::I8(value)) => primitive!(value, I8), + (TypeKind::U8, WinRTValue::U8(value)) => primitive!(value, U8), + (TypeKind::I16, WinRTValue::I16(value)) => primitive!(value, I16), + (TypeKind::U16 | TypeKind::Char16, WinRTValue::U16(value)) => primitive!(value, U16), + (TypeKind::I32 | TypeKind::Enum(_) | TypeKind::HResult, WinRTValue::I32(value)) => { + primitive!(value, I32) + } + (TypeKind::Enum(_), WinRTValue::Enum { value, type_handle }) + if *type_handle == self.typ => + { + primitive!(value, I32) + } + (TypeKind::U32, WinRTValue::U32(value)) => primitive!(value, U32), + (TypeKind::I64, WinRTValue::I64(value)) => primitive!(value, I64), + (TypeKind::U64, WinRTValue::U64(value)) => primitive!(value, U64), + (TypeKind::F32, WinRTValue::F32(value)) => primitive!(value, F32), + (TypeKind::F64, WinRTValue::F64(value)) => primitive!(value, F64), + (TypeKind::Guid, WinRTValue::Guid(value)) => primitive!(value, Guid), + (TypeKind::HResult, WinRTValue::HResult(value)) => Ok(PreparedValue::I32(value.0)), + (TypeKind::HString, WinRTValue::HString(value)) => { + Ok(PreparedValue::HString(value.clone())) + } + (TypeKind::Struct(_), WinRTValue::Struct(value)) + if *value.type_handle() == self.typ => + { + Ok(PreparedValue::Struct(unsafe { + self.prepare_borrowed_struct(value.as_ptr().cast())? + })) + } + (kind, WinRTValue::Null) if kind.is_com_pointer() => Ok(PreparedValue::Object(None)), + (kind, value) if kind.is_com_pointer() => { + let object = value.as_object().ok_or_else(|| self.mismatch(value))?; + let mut queried = ptr::null_mut(); + let iid = self.iid.expect("validated WinRT reference IID"); + let hr = unsafe { object.query(&iid, &mut queried) }; + // Own any returned reference immediately, including on failure. + let queried = unsafe { IUnknown::from_raw_borrowed(&queried) } + .map(|_| unsafe { IUnknown::from_raw(queried) }); + hr.ok()?; + queried + .map(|object| PreparedValue::Object(Some(object))) + .ok_or_else(|| error(E_POINTER, "QueryInterface returned a null WinRT output")) + } + _ => Err(self.mismatch(value)), + } + } + + fn mismatch(&self, value: &WinRTValue) -> windows_core::Error { + invalid_argument(format!( + "WinRT callback output expected {}, received {:?}", + self.typ.signature_string(), + value.get_type_kind() + )) + } + + unsafe fn prepare_borrowed_struct( + &self, + source: *const c_void, + ) -> windows_core::Result { + let mut prepared = ValueTypeData::try_new(&self.typ)?; + // Populate only retained fields into zeroed storage. A later failure + // can then drop it without releasing any still-borrowed fields. + for (offset, field) in &self.fields { + let source = unsafe { source.byte_add(*offset) }; + let owned = if matches!(field.typ.kind(), TypeKind::Struct(_)) { + PreparedValue::Struct(unsafe { field.prepare_borrowed_struct(source)? }) + } else { + let value = unsafe { field.read_borrowed(source)? }; + field.prepare(&value)? + }; + unsafe { owned.commit(prepared.as_mut_ptr().add(*offset).cast()) }; + } + Ok(prepared) + } + + unsafe fn read_array( + &self, + source: *const c_void, + length: u32, + ) -> windows_core::Result { + self.array_bytes(length as usize)?; + if source.is_null() && length != 0 { + return Err(error( + E_POINTER, + "Nonempty WinRT input array has a null data pointer", + )); + } + let mut values = Vec::new(); + values + .try_reserve_exact(length as usize) + .map_err(|_| error(E_OUTOFMEMORY, "Cannot allocate WinRT callback array inputs"))?; + for index in 0..length as usize { + values.push(unsafe { self.read_borrowed(source.byte_add(index * self.size))? }); + } + Ok(WinRTValue::Array(ArrayData::from_owned_values( + self.typ.clone(), + values, + ))) + } + + fn prepare_array(&self, value: &WinRTValue) -> windows_core::Result { + let WinRTValue::Array(array) = value else { + return Err(invalid_argument( + "WinRT callback array output must be an Array value", + )); + }; + let compatible = self.iid.is_some() + || crate::native_call::array_element_types_match(&self.typ, &array.element_type); + if !compatible { + return Err(invalid_argument( + "WinRT callback array element type does not match its plan", + )); + } + let length = u32::try_from(array.len()) + .map_err(|_| invalid_argument("WinRT callback array length exceeds UINT32_MAX"))?; + let bytes = self.array_bytes(array.len())?; + let data = if bytes == 0 { + ptr::null_mut() + } else { + let data = unsafe { CoTaskMemAlloc(bytes) }; + if data.is_null() { + return Err(error( + E_OUTOFMEMORY, + "Cannot allocate WinRT callback array output", + )); + } + unsafe { ptr::write_bytes(data, 0, bytes) }; + data + }; + let prepared = PreparedArray { + data, + length, + element_type: self.typ.clone(), + }; + for index in 0..array.len() { + let value = array + .try_get(index) + .map_err(|cause| invalid_argument(cause.message()))?; + let owned = self.prepare(&value)?; + unsafe { owned.commit(data.byte_add(index * self.size)) }; + } + Ok(prepared) + } +} + +pub(super) enum PreparedValue { + Bool(bool), + I8(i8), + U8(u8), + I16(i16), + U16(u16), + I32(i32), + U32(u32), + I64(i64), + U64(u64), + F32(f32), + F64(f64), + Guid(GUID), + HString(HSTRING), + Object(Option), + Struct(ValueTypeData), +} + +impl PreparedValue { + unsafe fn commit(self, target: *mut c_void) { + unsafe { + match self { + Self::Bool(value) => target.cast::().write(u8::from(value)), + Self::I8(value) => target.cast::().write(value), + Self::U8(value) => target.cast::().write(value), + Self::I16(value) => target.cast::().write_unaligned(value), + Self::U16(value) => target.cast::().write_unaligned(value), + Self::I32(value) => target.cast::().write_unaligned(value), + Self::U32(value) => target.cast::().write_unaligned(value), + Self::I64(value) => target.cast::().write_unaligned(value), + Self::U64(value) => target.cast::().write_unaligned(value), + Self::F32(value) => target.cast::().write_unaligned(value), + Self::F64(value) => target.cast::().write_unaligned(value), + Self::Guid(value) => target.cast::().write_unaligned(value), + Self::HString(value) => target.cast::().write_unaligned(value), + Self::Object(value) => target + .cast::<*mut c_void>() + .write_unaligned(value.map_or(ptr::null_mut(), Interface::into_raw)), + Self::Struct(value) => value.move_to_abi(target), + } + } + } +} + +pub(super) struct PreparedArray { + data: *mut c_void, + length: u32, + element_type: TypeHandle, +} + +impl Drop for PreparedArray { + fn drop(&mut self) { + if !self.data.is_null() { + drop(ArrayData::from_cotaskmem( + self.element_type.clone(), + self.data, + self.length as usize, + )); + } + } +} + +pub(super) enum OutputTarget { + Value(*mut c_void), + ReceiveArray { + length: *mut u32, + data: *mut *mut c_void, + }, + FillArray { + capacity: u32, + data: *mut c_void, + }, +} + +pub(super) enum PreparedOutput { + Value(*mut c_void, PreparedValue), + ReceiveArray(*mut u32, *mut *mut c_void, PreparedArray), + FillArray(*mut c_void, PreparedArray), +} + +impl PreparedOutput { + pub unsafe fn commit(self) { + unsafe { + match self { + Self::Value(target, value) => value.commit(target), + Self::ReceiveArray(length, data, mut array) => { + length.write_unaligned(array.length); + data.write_unaligned(array.data); + array.data = ptr::null_mut(); + } + Self::FillArray(target, mut array) => { + let bytes = array.length as usize * array.element_type.size_of(); + if bytes != 0 { + ptr::copy_nonoverlapping(array.data.cast::(), target.cast(), bytes); + CoTaskMemFree(Some(array.data)); + array.data = ptr::null_mut(); + } + } + } + } + } +} + +impl ParameterPlan { + unsafe fn pointer(&self, args: *const *const c_void, offset: usize) -> *mut c_void { + unsafe { + (*args.add(self.abi_index + offset)) + .cast::<*mut c_void>() + .read_unaligned() + } + } + + unsafe fn length(&self, args: *const *const c_void) -> u32 { + unsafe { (*args.add(self.abi_index)).cast::().read_unaligned() } + } +} + +impl MethodPlan { + pub unsafe fn initialize_outputs( + &self, + args: *const *const c_void, + ) -> windows_core::Result> { + let mut outputs = Vec::with_capacity(self.output_count); + let mut failure = None; + for parameter in &self.parameters { + if parameter.direction == WinRtParameterDirection::In { + continue; + } + if !parameter.array { + let target = unsafe { parameter.pointer(args, 0) }; + if target.is_null() { + failure.get_or_insert_with(|| error(E_POINTER, "Null WinRT output pointer")); + } else { + unsafe { ptr::write_bytes(target, 0, parameter.value.size) }; + } + outputs.push(OutputTarget::Value(target)); + } else if parameter.direction == WinRtParameterDirection::Out { + let length = unsafe { parameter.pointer(args, 0).cast::() }; + let data = unsafe { parameter.pointer(args, 1).cast::<*mut c_void>() }; + if !length.is_null() { + unsafe { length.write_unaligned(0) }; + } + if !data.is_null() { + unsafe { data.write_unaligned(ptr::null_mut()) }; + } + if length.is_null() || data.is_null() { + failure.get_or_insert_with(|| { + error(E_POINTER, "Null WinRT ReceiveArray output pointer") + }); + } + outputs.push(OutputTarget::ReceiveArray { length, data }); + } else { + let capacity = unsafe { parameter.length(args) }; + let data = unsafe { parameter.pointer(args, 1) }; + match parameter.value.array_bytes(capacity as usize) { + Ok(bytes) if bytes != 0 && data.is_null() => { + failure.get_or_insert_with(|| { + error(E_POINTER, "Null nonempty WinRT FillArray buffer") + }); + } + Ok(bytes) if bytes != 0 => unsafe { ptr::write_bytes(data, 0, bytes) }, + Ok(_) => {} + Err(error) => { + failure.get_or_insert(error); + } + } + outputs.push(OutputTarget::FillArray { capacity, data }); + } + } + failure.map_or(Ok(outputs), Err) + } + + pub unsafe fn inputs( + &self, + args: *const *const c_void, + ) -> windows_core::Result> { + let mut inputs = Vec::with_capacity(self.input_count); + for parameter in &self.parameters { + if parameter.direction == WinRtParameterDirection::Out { + continue; + } + inputs.push( + if parameter.direction == WinRtParameterDirection::FillArray { + WinRTValue::U32(unsafe { parameter.length(args) }) + } else if parameter.array { + unsafe { + parameter + .value + .read_array(parameter.pointer(args, 1), parameter.length(args))? + } + } else { + unsafe { + parameter + .value + .read_borrowed(*args.add(parameter.abi_index))? + } + }, + ); + } + Ok(inputs) + } + + pub fn prepare_outputs( + &self, + targets: Vec, + values: &[WinRTValue], + ) -> windows_core::Result> { + if values.len() != self.output_count { + return Err(invalid_argument(format!( + "{}: callback returned {} outputs; the WinRT contract requires {}", + self.name, + values.len(), + self.output_count + ))); + } + self.parameters + .iter() + .filter(|parameter| parameter.direction != WinRtParameterDirection::In) + .zip(targets) + .zip(values) + .map(|((parameter, target), value)| match target { + OutputTarget::Value(target) => Ok(PreparedOutput::Value( + target, + parameter.value.prepare(value)?, + )), + OutputTarget::ReceiveArray { length, data } => Ok(PreparedOutput::ReceiveArray( + length, + data, + parameter.value.prepare_array(value)?, + )), + OutputTarget::FillArray { capacity, data } => { + let array = parameter.value.prepare_array(value)?; + if array.length != capacity { + return Err(invalid_argument(format!( + "{}: FillArray output has {} elements; expected capacity {capacity}", + self.name, array.length + ))); + } + Ok(PreparedOutput::FillArray(data, array)) + } + }) + .collect() + } +} diff --git a/docs/architecture/winrt-interface-implementations.md b/docs/architecture/winrt-interface-implementations.md new file mode 100644 index 00000000..0dcd0e2a --- /dev/null +++ b/docs/architecture/winrt-interface-implementations.md @@ -0,0 +1,179 @@ +# Standalone WinRT interface implementations + +The WinRT implementation facility creates real, independently constructible +`IInspectable` objects from runtime metadata. JavaScript and Python implement +their methods. It does not require a composable WinUI base, an aggregated inner +object, a per-interface native adapter, or activation registration. + +## Planning and dispatch + +```text +WinRT InterfaceMeta + MethodMeta + -> shared, validated WinRT implementation projection + -> generated typed handler adapters and interface descriptors + -> WinRtImplementationPlan + -> immutable IInspectable identity and independent interface views + -> private native_callback static thunks / cached libffi closures + -> owner-thread language callback + -> prepared, owned outputs + -> native caller +``` + +`crates/dynwinrt/src/winrt_implementation/plan.rs` consumes WinRT +`MethodSignature` descriptions, not Classic COM contracts. The signature +facade exposes only WinRT input, output, and fill-array directions. The first +interface method is slot **6**, after all six IUnknown/IInspectable methods. +Methods must be contiguous, and the plan records their full parameter +expansion and output order before an object can be published. + +Required WinRT interfaces are separate QueryInterface views. Their methods +are not appended to a derived interface, and incompatible vtable prefixes are +never aliased. The whole-object plan rejects absent requirements, cycles, +duplicate interface IIDs, reserved infrastructure IIDs, invalid slots, and +unsupported types. The public interface set and every view's vtable are frozen +for the object's entire lifetime. + +The existing outbound WinRT and Classic COM planners remain independent. +Private scalar-validation, array-element identity rules, and native callback +storage are shared where their contracts are identical. The WinRT host never +registers its methods in the Classic COM registry. + +## Native object model + +The canonical identity is an IInspectable-rooted allocation. Every interface +view has its own immutable vtable and a pointer to that allocation. All views +share a single atomic reference count. QueryInterface for IUnknown or +IInspectable returns the canonical identity regardless of the source view. + +GetIids allocates the actual implemented public IID list with CoTaskMemAlloc; +the caller owns that allocation. GetRuntimeClassName returns an owned HSTRING +for the supplied descriptive name, or an empty string when none was supplied. +This name does not make a class activatable. GetTrustLevel returns BaseTrust. + +The private identity adapter maps each native `+1` to one `Arc` strong +reference and implements native weak references using `Weak`. Upgrading +a weak reference is atomically synchronized with final destruction. Its +temporary pin and ordinary native Release use the same Arc destruction path, +including when QueryInterface rejects an IID. No state lock is held across +QueryInterface, final destruction, or callback-resource cleanup. This avoids +depending on the pinned windows-core internal weak refcount's temporary +decrement to trigger destruction of this separately allocated dynamic host. + +Native weak references expire after the last strong reference is released. +IWeakReferenceSource is infrastructure, not a user-supplied interface plan. +The target host does not expose IAgileObject or a free-threaded marshaler. The +separate native weak-reference object is agile; its optional marshaler uses a +pinned windows-core helper encapsulated in `identity.rs`. + +## Threading and lifetime + +The only supported callback policy is synchronous, same-owner-thread +dispatch. The native host compares thread identity before entering a language +binding. A foreign-thread call returns `RPC_E_WRONG_THREAD`, even if the caller +has an otherwise valid native reference. Identity, reference counting, +IInspectable metadata queries, and weak-reference operations do not enter +the language runtime. + +Each method invocation acquires an extra native reference before accessing its +dispatch plan. It also snapshots the callback outside the callback-state +mutex. Reentrant disposal or the caller's final Release cannot destroy an +executing callback's object, plan, or language roots. + +Dynamic libffi closures use the existing process-lifetime signature/slot cache. +Their executable pages cannot be freed by a final reentrant Release. Common +no-argument and pointer-only signatures use static thunks. If the process +cannot allocate executable closure memory for another supported signature, +creation fails before publishing any interface. + +The owner/controller holds one native reference. Releasing or collecting it +does not disconnect independently retained native references. Explicit +`dispose` disconnects callbacks object-wide and drops the controller's +reference. Already-dispatched callbacks may finish, including returning their +fully validated outputs; later calls return `RO_E_CLOSED`. + +Language bindings additionally gate dispatch on their environment/interpreter +lifetime. Callback roots belong to the native object, not merely the original +language wrapper. Shutdown disconnects language callback state before its +resources become unavailable. No synchronous callback is approximated by a +fire-and-forget thread-safe-function notification. + +Explicit disposal is also the deterministic escape hatch for a handler that +strongly retains its own native object. Native references are external GC roots: +tracing them as ordinary language-only edges could collect an object that a +native consumer still owns. Python's GC integration is consequently +conservative in the presence of independently retained native references. +See the public guide for the binding-specific ownership rules. + +The Python public implementation-view helper deliberately bypasses the +ordinary wrapper-identity cache, not the native initializer or projected +lifetime tracking. Thus two same-IID views have independently releasable QI +references, while ordinary `from_value` calls retain their existing identity +behavior. + +Generated Node event registration releases the creator's delegate reference +and its call-local value after the native event source retains its own +reference. This prevents an unsubscribe closure's shared lexical environment +from keeping a removed delegate's referenced TSFN alive. It neither globally +unrefs callbacks nor changes cross-thread delegate dispatch. + +## Value and output ownership + +Incoming native interface pointers and HSTRINGs are borrowed. The reverse +marshaller retains or duplicates them before invoking user code, including +references in structs and arrays. The callback may retain these managed +values without retaining a pointer into the caller's stack or array buffer. + +WinRT array directions have distinct plans: + +| Direction | Native ABI | Callback contract | +| --- | --- | --- | +| Input/pass array | `UINT32 length, T* data` | Owned managed array of input elements | +| Output/receive array | `UINT32* length, T** data` | Owned array result; allocation uses CoTaskMem | +| Fill array | `UINT32 capacity, T* data` | Capacity input and exactly that many result elements | + +Before dispatch, every supplied output location is initialized, including +output lengths, pointers, structs, and fill buffers. Null required storage +returns `E_POINTER`; zero-length arrays may have null data pointers. Byte-size +multiplication is checked against the target's address width. + +All outputs are prepared before any is published. Preparation validates exact +struct/enum identity, established scalar/array aliases, array element values, +and the requested interface IID. It acquires owned interface references, +duplicates strings, and constructs zero-initialized, allocator-correct array +buffers. Prepared values are RAII-owned, so a later failed output conversion +releases all earlier preparation. + +Publication only transfers already-prepared ownership. It does not run a +handler or QueryInterface halfway through a multi-output result. Strings are +owned HSTRINGs, references transfer a `+1`, and receive arrays transfer both +their element ownership and their CoTaskMem allocation. Structs retain their +exact metadata layout on 32-bit and 64-bit targets. + +Language exceptions and Rust panics become failing HRESULTs and never +successful placeholder values. The controller retains a contextual diagnostic +containing the interface, slot, HRESULT, and message. Python additionally uses +its unraisable-exception convention at the native callback boundary. + +## Boundaries + +Generic interface implementations, uninstantiated generic types, nested +arrays, unknown layouts, ABI-only pointer/out-value descriptors, asynchronous +language handlers, and cross-thread language dispatch are outside this +release. Existing closed generic, delegate, nullable-reference, and native +async **values** can cross supported method contracts; this does not enable +user-defined generic implementations or automatic awaiting. + +The Python binding rejects subinterpreters because its existing GIL attachment +path targets the main interpreter. Node callback state is scoped to its N-API +environment. These language-runtime gates supplement the native owner-thread +policy rather than replacing it. + +The generated descriptor is a complete metadata contract, not permission to +invent an IID or substitute an unrelated vtable. Low-level descriptor +construction is intended for tools and complete, ABI-correct fixtures. + +IBackgroundTask is an application of this same machinery. Windows triggering, +CLSID activation, COM server hosting, package identity/deployment, and task +registration are separate concerns and are not performed by this facility. + +See [the Node.js and Python usage guide](../guides/windows/winrt-interface-implementations.md). diff --git a/docs/guides/windows/winrt-interface-implementations.md b/docs/guides/windows/winrt-interface-implementations.md new file mode 100644 index 00000000..98797365 --- /dev/null +++ b/docs/guides/windows/winrt-interface-implementations.md @@ -0,0 +1,271 @@ +# Implement WinRT interfaces in Node.js and Python + +Generated WinRT interfaces can create standalone native objects backed by +synchronous JavaScript or Python handlers. The objects support IInspectable, +QueryInterface, and real native vtable calls. They do not need WinUI +composition, a package identity, or background-task registration. + +Use a runtime and code generator from the same version. Generate the complete +interfaces you need, including their required interfaces. The generated +handler declaration describes exactly which methods and results to provide. + +## Construction and typed interface views + +`Interface.implementation(handlers)` describes one implemented interface. +`Interface.implement(handlers, ...additional)` creates a native owner from one +or more descriptors. The returned `DynWinRtImplementation` (Node) or +`DynWinRTImplementation` (Python) is distinct from a typed interface view. + +Use `Interface.fromImplementation(owner)` in Node, or +`Interface.from_implementation(owner)` in Python, to obtain a public typed view. +This keeps the owner valid and creates an independently owned interface +reference. The view is accepted by ordinary generated methods taking that +interface; no type assertion or internal `_fromNative` helper is needed. +Repeated conversions to the same IID return independent views. Python's new +conversion remains tracked by the current projected lifetime scope, but does +not reuse or replace the ordinary `from_value` identity cache. + +### Node.js + +Generate IStringable and IClosable: + +```powershell +cargo run -p dynwinrt-codegen -- generate ` + --class-name "Windows.Foundation.IStringable,Windows.Foundation.IClosable" ` + --output .\generated +``` + +```js +import { roInitialize } from '@microsoft/dynwinrt'; +import { IClosable, IStringable, releaseProjected } from './generated/index.js'; + +roInitialize(1); +const owner = IStringable.implement( + { toString: () => 'Implemented in JavaScript' }, + IClosable.implementation({ close: () => console.log('Native Close call') }), +); +const text = IStringable.fromImplementation(owner); +const closable = IClosable.fromImplementation(owner); +try { + console.log(text.toString()); // Outbound native call, then reverse callback. + owner.release(); // These two interface references remain valid. + closable.close(); +} finally { + owner.dispose(); // Disconnect every retained view's callbacks. + releaseProjected(closable); + releaseProjected(text); +} +``` + +Use the generated `IStringableHandlers` and other handler declarations +to type handler objects in TypeScript. Handlers must be actual synchronous +functions; an `async` function or a returned Promise/thenable is not a WinRT +synchronous result. + +### Python + +Generate the same interfaces with `--lang py`: + +```powershell +cargo run -p dynwinrt-codegen -- generate ` + --class-name "Windows.Foundation.IStringable,Windows.Foundation.IClosable" ` + --lang py --output .\generated +``` + +```python +from dynwinrt import RoApartment, release_projected +from generated.windows.foundation import IClosable, IStringable + +class TextHandler: + def to_string(self) -> str: + return "Implemented in Python" + +class CloseHandler: + def close(self) -> None: + print("Native Close call") + +with RoApartment(1): + owner = IStringable.implement( + TextHandler(), IClosable.implementation(CloseHandler()) + ) + text = IStringable.from_implementation(owner) + closable = IClosable.from_implementation(owner) + try: + print(text.to_string()) # Crosses the native vtable in both directions. + owner.release() + closable.close() + finally: + owner.dispose() + release_projected(closable) + release_projected(text) +``` + +Python handler objects may use ordinary bound methods. Generated `.pyi` +declarations describe their protocol. Coroutine functions and returned +awaitables are rejected, not run in the background or awaited on the callback +thread. The implementation owner's context-manager exit performs **dispose**, +not merely reference release. + +Python implementations currently require the main CPython interpreter; +subinterpreter-owned callbacks are rejected at construction. Captured +`contextvars` follow the existing Python callback-context convention. + +## Supported contracts + +Support is determined from the entire interface, not only from the method an +application intends to call. Missing handlers, unresolved required interfaces, +duplicate views, invalid slots, or unsupported signatures fail before a native +object is published. + +| Contract | Support | +| --- | --- | +| Ordinary methods | Typed inputs, void results, return values, and multiple outputs | +| Properties | Explicit synchronous getter and setter handlers | +| Events | Add/remove handlers, native delegate values, and registration tokens | +| Primitive values | Booleans, integer widths, floating-point values, Char16, enums, HRESULT values | +| GUID and HSTRING | Managed values with native layout/string ownership | +| WinRT structs | Known layouts, including supported nested fields | +| Object/interface/class references | Nullable managed references; output QueryInterface checks the declared IID | +| Closed generic and nullable-reference values | Established value conversions, not generic implementations | +| Arrays | Input, receive, and fill arrays of supported elements | +| Native async objects | Pass-through where the existing projection supports the declared type | + +Handler accessor names and output field names are given in the generated +handler type. Do not infer them from a property's displayed name or a +language object's shape. When a method has multiple logical outputs, the +generated result has named fields; every field must be present and valid. +The ABI order is explicit output parameters in metadata order followed by the +method's logical return value. + +A fill-array handler receives a **capacity**, not a writable borrowed native +buffer. Return exactly that many elements. Receive-array storage and element +references are allocated and transferred by the runtime. An invalid element, +wrong length, missing result field, or failed output QueryInterface fails the +whole call before any output ownership is published. + +Required interfaces have their own handler descriptors and native views. +For example, IMemoryBufferReference requires IClosable. Supply its descriptor +alongside the memory-reference handlers; do not merge an IClosable method into +the memory-reference vtable. + +For its Closed event, the implementation handlers are `getCapacity`, +`addClosed`, and `removeClosed` in Node, or `get_capacity`, `add_closed`, and +`remove_closed` in Python. The add handler receives an owned, typed callable +native delegate. Retain it to deliver the event by calling +`handler(senderView, null)` / `handler(sender_view, None)`. Return a token +`{ value: 1n }` in Node or `EventRegistrationToken(value=1)` in Python. The remove +handler receives that token and should remove and release its stored delegate. +These calls invoke the delegate's native slot 3; they are not direct calls to +the original subscriber's language function. + +Generated Node subscriptions release their creator and temporary delegate +references after the native add method returns. The native event source owns +the subscription reference until removal. Keeping an unsubscribe function +reachable after removal does not keep the native delegate alive. A caller +using `DynWinRtDelegate.create` directly must similarly release its delegate +owner and its separate `toValue()` reference when they are no longer needed. +Neither release disconnects a native-retained reference. + +Existing metadata visibility rules remain in force: an `ExclusiveTo` static +or factory interface is an implementation detail of its runtime class, not a +new public implementation entrypoint. The array examples in the generated +integration suite use public IDataWriter, IPropertyValue, and IDataReader +interfaces rather than exposing private factory interfaces. + +## Ownership, disposal, and errors + +| Operation | Meaning | +| --- | --- | +| `toValue()` / `to_value()` | Create an owned low-level native value for explicit interop | +| Public typed view conversion | Create an owned typed view without consuming the owner | +| `releaseProjected(view)` / `release_projected(view)` | Release that view without disposing the controller or other views | +| `release()` on the implementation owner | Drop only that owner's native reference | +| `disconnect()` | Disconnect callbacks for the whole implemented object | +| `dispose()` | Disconnect the whole object, then release the owner's reference | +| `takeError()` / `take_error()` | Retrieve and clear the last contextual native callback error | + +Native references keep handlers alive after the original wrapper leaves scope. +An independent view or native consumer's reference is not disconnected merely +because the owner was released or collected. Low-level values and typed views +have independent reference ownership and must follow their normal projected +lifetime rules. JavaScript's `releaseProjected` is exported by the generated +package; Python's `release_projected` is exported by `dynwinrt`. + +Explicit disposal is different: every later method call through any retained +view fails with `RO_E_CLOSED`. A callback that had **already entered** before +disposal may finish and return its validated outputs. Its native object, +dispatch storage, and callback roots remain alive until it returns. + +If a handler retains its own owner or native view, the resulting native/language +cycle may require explicit disposal. Python GC integration is conservative +when external native references exist: collecting a still-native-owned handler +would be incorrect. Avoid strong self/native cycles where practical, and use a +`try/finally` or the Python owner context manager for deterministic +disconnection. Environment/interpreter shutdown also closes callback state; +it does not leave callable pointers into a destroyed language runtime. + +Python can collect an owner-only callback cycle when that owner holds the sole +native reference. Native aliases or native weak-reference use are treated +conservatively and may require explicit disposal. Native reference cleanup can +run on another thread without granting permission to invoke handlers there. + +Language exceptions are reported as real failing HRESULTs. The owner's error +accessor provides interface/slot context; Python also reports the original +exception using its native-callback unraisable-exception convention. Outputs +are initialized on failure, and prepared strings, references, and buffers are +released if any output conversion fails. +Ordinary JavaScript handler exceptions map to `E_FAIL` (`0x80004005`); +ordinary Python handler exceptions map to `0xA0EE4005`. In particular, throwing +`NotImplementedError` does not request native `E_NOTIMPL`, and arbitrary +properties attached to a JavaScript Error do not override its HRESULT. + +## Threading + +Create and call implementations on their **owner thread**. They are explicitly +non-agile, including when created in an MTA. Native identity and reference-count +operations remain thread-safe, but a method callback from a foreign thread +fails with `RPC_E_WRONG_THREAD` before entering JavaScript or Python. + +This release does not provide apartment dispatch, cross-thread callback +marshaling, implicit Promise/coroutine conversion, or event-loop blocking to +wait for a synchronous result. Existing native WinRT async objects and +deferrals may be used explicitly through their own APIs. + +## IBackgroundTask and deployment + +IBackgroundTask uses the same general implementation engine as IStringable, +IClosable, and other supported interfaces. A controlled native consumer can +call its Run method with a real IBackgroundTaskInstance interface without +registering an operating-system task. + +The [Node sample](../../../samples/js/interface-implementation/README.md) and +[Python sample](../../../samples/python/interface-implementation/README.md) +provide runnable task-instance fixtures and demonstrate native Run calls, +nested native property callbacks, multiple interface views, and owner release. + +Creating such an object does **not** register a background task or COM server, +make a CLSID activatable, configure a Windows trigger, install a package, or +grant a package identity. Windows background activation and deployment are +separate future work. GetRuntimeClassName is descriptive metadata, not +activation registration. + +Arbitrary user-defined generic interface implementations, nested arrays, +unknown native layouts, and incomplete ownership contracts are not supported. +Where a signature requires a dynamic libffi closure, process restrictions on +executable-memory allocation can also make construction fail. + +For implementation details, see +[the native architecture](../../architecture/winrt-interface-implementations.md). + +The repository's focused generated/native scenarios can be run after building +the matching bindings and generator: + +```powershell +.\tests\e2e\e2e_test.ps1 -SkipBuild -Suite implementations ` + -Lang py,ts -CargoProfile dev -Python .\bindings\py\.venv\Scripts\python.exe +``` + +They exercise real vtables, properties, native event delegates, pass/receive/ +fill arrays, scalar/GUID/struct/reference outputs, named multiple outputs, +independent views, exception recovery, and retention/disposal. Use +`-Suite standard` for the existing WinRT/Classic COM compatibility scenarios. diff --git a/samples/js/README.md b/samples/js/README.md index df820e04..93b6f5ba 100644 --- a/samples/js/README.md +++ b/samples/js/README.md @@ -10,6 +10,7 @@ The JavaScript samples use generated bindings and the | [`windows-hello`](windows-hello/) | Electron, Windows Hello, and HWND-bound Classic COM interop | | [`electron-share-ui`](electron-share-ui/) | Electron Share UI with WinRT and Classic COM | | [`electron-smtc`](electron-smtc/) | Electron system media controls and GSMTC loopback | +| [`interface-implementation`](interface-implementation/) | Standalone JavaScript-backed WinRT interfaces, native IBackgroundTask calls, and multi-interface lifetime | The WinUI samples use WinApp CLI to restore matching Windows App SDK metadata, runtime packages, bootstrap binaries, and generated npm bindings. diff --git a/samples/js/interface-implementation/README.md b/samples/js/interface-implementation/README.md new file mode 100644 index 00000000..c7b65a23 --- /dev/null +++ b/samples/js/interface-implementation/README.md @@ -0,0 +1,41 @@ +# JavaScript-defined standalone WinRT interfaces + +This sample implements IBackgroundTask, IStringable, and IClosable on one +standalone native object. A second implemented object supplies a controlled +IBackgroundTaskInstance. Calling the generated `task.run(instance)` enters the +native WinRT vtable, invokes the JavaScript handler, and makes nested native +property calls on the task instance. + +There is no WinUI base, package identity, OS task registration, COM server, or +background activation. Unused task-instance fixture methods throw rather than +pretending that an OS registration or deferral exists. + +From the repository root, build the matching runtime and generator: + +```powershell +cargo build -p dynwinrt-codegen +Push-Location .\bindings\js +npm ci +npm run build +Pop-Location + +Push-Location .\samples\js\interface-implementation +npm install --ignore-scripts --omit=optional +.\generate.ps1 -Codegen ..\..\..\target\debug\dynwinrt-codegen.exe +npm start +Pop-Location +``` + +The local npm dependency uses the runtime built in this checkout. Generation +auto-detects the Windows SDK; pass `-Winmd` to select another Windows.winmd. + +The owner and typed views have independent references. `owner.release()` +releases only the creator's reference, so the retained views continue to work. +`owner.dispose()` disconnects all future callbacks; the sample confirms a +later native call fails and prints its contextual diagnostic. An already +entered callback is allowed to finish. IClosable.Close is just another +handler-defined method, not a hidden alias for owner disposal. The generated +package's `releaseProjected(view)` independently releases each typed view. + +See [the public guide](../../../docs/guides/windows/winrt-interface-implementations.md) +for the supported contracts and owner-thread/lifetime restrictions. diff --git a/samples/js/interface-implementation/app.mjs b/samples/js/interface-implementation/app.mjs new file mode 100644 index 00000000..e5e0f6ef --- /dev/null +++ b/samples/js/interface-implementation/app.mjs @@ -0,0 +1,80 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict'; +import { roInitialize } from '@microsoft/dynwinrt'; +import { + IBackgroundTask, + IBackgroundTaskInstance, + IClosable, + IStringable, + releaseProjected, +} from './generated/index.js'; + +roInitialize(1); + +function unavailable() { + throw new Error('This local task-instance fixture has no OS registration, trigger, or deferral'); +} + +let progress = 0; +let runs = 0; +let closes = 0; +const instanceOwner = IBackgroundTaskInstance.implement({ + getInstanceId: () => '4ab7eea7-29a1-4f48-a6da-22894e210ec0', + getTask: unavailable, + getProgress: () => progress, + setProgress: value => { progress = value; }, + getTriggerDetails: unavailable, + addCanceled: unavailable, + removeCanceled: unavailable, + getSuspendedCount: () => 0, + getDeferral: unavailable, +}); +const handlers = { + run(instance) { + if (instance === null) throw new TypeError('A task instance is required by this handler'); + instance.progress = instance.progress + 1; + runs += 1; + }, + toString: () => `JavaScript task: ${runs} native Run calls`, + close: () => { closes += 1; }, +}; +const owner = IBackgroundTask.implement( + handlers, + IStringable.implementation(handlers), + IClosable.implementation(handlers), +); +const instance = IBackgroundTaskInstance.fromImplementation(instanceOwner); +const task = IBackgroundTask.fromImplementation(owner); +const text = IStringable.fromImplementation(owner); +const duplicateText = IStringable.fromImplementation(owner); +const closable = IClosable.fromImplementation(owner); + +try { + assert.notStrictEqual(text, duplicateText); + releaseProjected(duplicateText); + // Both the Run call and its progress property calls cross native vtables. + task.run(instance); + assert.equal(instance.progress, 1); + console.log(text.toString()); + + owner.release(); + task.run(instance); + assert.equal(instance.progress, 2); + closable.close(); + assert.equal(closes, 1); + releaseProjected(closable); + assert.equal(owner.isClosed, false); + console.log(text.toString()); + + owner.dispose(); + assert.throws(() => text.toString(), /closed|80000013/i); + const diagnostic = owner.takeError(); + assert.match(diagnostic, /0x80000013/); + console.log(diagnostic); +} finally { + owner.dispose(); + instanceOwner.dispose(); + for (const view of [closable, duplicateText, text, task, instance]) releaseProjected(view); +} diff --git a/samples/js/interface-implementation/generate.ps1 b/samples/js/interface-implementation/generate.ps1 new file mode 100644 index 00000000..98984f98 --- /dev/null +++ b/samples/js/interface-implementation/generate.ps1 @@ -0,0 +1,28 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [string]$Codegen = "dynwinrt-codegen", + [string]$Winmd +) + +$ErrorActionPreference = "Stop" +if (Test-Path -LiteralPath $Codegen -PathType Leaf) { + $Codegen = (Resolve-Path -LiteralPath $Codegen).Path +} else { + $Codegen = (Get-Command $Codegen -ErrorAction Stop).Source +} +$arguments = @( + "generate", + "--class-name", + "Windows.ApplicationModel.Background.IBackgroundTask,Windows.ApplicationModel.Background.IBackgroundTaskInstance,Windows.Foundation.IStringable,Windows.Foundation.IClosable", + "--lang", "js", + "--output", (Join-Path $PSScriptRoot "generated") +) +if ($Winmd) { + $arguments += @("--winmd", (Resolve-Path -LiteralPath $Winmd).Path) +} +& $Codegen @arguments +if ($LASTEXITCODE -ne 0) { + throw "WinRT interface generation failed with exit code $LASTEXITCODE" +} diff --git a/samples/js/interface-implementation/package-lock.json b/samples/js/interface-implementation/package-lock.json new file mode 100644 index 00000000..c169b395 --- /dev/null +++ b/samples/js/interface-implementation/package-lock.json @@ -0,0 +1,47 @@ +{ + "name": "dynwinrt-interface-implementation-sample", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "dynwinrt-interface-implementation-sample", + "dependencies": { + "@microsoft/dynwinrt": "file:../../../bindings/js" + } + }, + "../../../bindings/js": { + "name": "@microsoft/dynwinrt", + "version": "0.1.0", + "license": "MIT", + "devDependencies": { + "@emnapi/core": "^1.5.0", + "@emnapi/runtime": "^1.5.0", + "@napi-rs/cli": "^3.2.0", + "@napi-rs/wasm-runtime": "^1.0.4", + "@oxc-node/core": "^0.0.35", + "@taplo/cli": "^0.7.0", + "@tybys/wasm-util": "^0.10.0", + "@types/node": "^24.13.3", + "ava": "^6.4.1", + "c8": "12.0.0", + "chalk": "^5.6.2", + "emnapi": "^1.5.0", + "husky": "^9.1.7", + "lint-staged": "^16.1.6", + "npm-run-all2": "^8.0.4", + "oxlint": "^1.14.0", + "prettier": "^3.6.2", + "tinybench": "^6.0.0", + "tsx": "^4.21.0", + "typescript": "^5.9.2" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@microsoft/dynwinrt": { + "resolved": "../../../bindings/js", + "link": true + } + } +} diff --git a/samples/js/interface-implementation/package.json b/samples/js/interface-implementation/package.json new file mode 100644 index 00000000..821ffbff --- /dev/null +++ b/samples/js/interface-implementation/package.json @@ -0,0 +1,11 @@ +{ + "name": "dynwinrt-interface-implementation-sample", + "private": true, + "type": "module", + "scripts": { + "start": "node app.mjs" + }, + "dependencies": { + "@microsoft/dynwinrt": "file:../../../bindings/js" + } +} diff --git a/samples/python/README.md b/samples/python/README.md index 05a6967d..58d9fafe 100644 --- a/samples/python/README.md +++ b/samples/python/README.md @@ -10,6 +10,7 @@ checkout, then run each sample's `generate.ps1` before `run.ps1`. | [`ocr-image`](ocr-image/) | Self-contained image creation, bitmap decoding, and Windows OCR | | [`app-lifecycle-single-instance`](app-lifecycle-single-instance/) | Multi-process activation redirection with Windows App SDK AppLifecycle | | [`cryptography`](cryptography/) | SHA-256, `IBuffer`, text encoding, and hex conversion | +| [`interface-implementation`](interface-implementation/) | Standalone Python-backed WinRT interfaces, native IBackgroundTask calls, and multi-interface lifetime | | [`device-watcher`](device-watcher/) | Device enumeration and thread-safe typed event subscriptions | | [`text-to-speech`](text-to-speech/) | `asyncio`, speech synthesis, media playback, and typed events | | [`app-notification`](app-notification/) | Windows App SDK bootstrap, notification builder, display, activation, and cleanup | diff --git a/samples/python/interface-implementation/README.md b/samples/python/interface-implementation/README.md new file mode 100644 index 00000000..cd262b04 --- /dev/null +++ b/samples/python/interface-implementation/README.md @@ -0,0 +1,41 @@ +# Python-defined standalone WinRT interfaces + +This sample implements IBackgroundTask, IStringable, and IClosable on one +standalone native object. Another implemented object supplies a complete +IBackgroundTaskInstance fixture. The generated `task.run(instance)` call +crosses a real native WinRT vtable before the Python handler runs; its progress +property reads/writes make additional native calls into the fixture. + +No composable WinUI class, package identity, OS task registration, COM server, +or trigger is needed. Fixture methods that would need OS registration, +cancellation, or deferrals explicitly raise NotImplementedError. + +Build/install the matching Python runtime from `bindings\py` and build the +generator, then run from the repository root: + +```powershell +cargo build -p dynwinrt-codegen +.\samples\python\interface-implementation\generate.ps1 ` + -Codegen .\target\debug\dynwinrt-codegen.exe +.\samples\python\interface-implementation\run.ps1 ` + -Python .\bindings\py\.venv\Scripts\python.exe +``` + +The selected interpreter must have this checkout's runtime installed. +Generation auto-detects the Windows SDK; `-Winmd` selects an explicit metadata +file. The generated package is imported from the sample directory and does +not need to be installed separately. + +Releasing the implementation owner's reference leaves independently retained +typed views usable. Explicit disposal in `finally` disconnects every view's +future callbacks. Already-entered callbacks may finish. The projected lifetime +scope releases typed wrappers before the apartment exits. The implementation +owner's own context-manager exit, when used, performs **dispose**, not release. +The public `dynwinrt.release_projected(view)` helper independently releases a +typed view without disconnecting its controller or other views. + +Do not use `async def` for these synchronous handlers. Native calls from +another thread fail before entering Python. See +[the public guide](../../../docs/guides/windows/winrt-interface-implementations.md) +for the capability matrix, callback errors, native retention, and cycle/shutdown +semantics. diff --git a/samples/python/interface-implementation/app.py b/samples/python/interface-implementation/app.py new file mode 100644 index 00000000..1f74d32d --- /dev/null +++ b/samples/python/interface-implementation/app.py @@ -0,0 +1,116 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import NoReturn +from uuid import UUID + +from dynwinrt import RoApartment, projected_lifetime_scope, release_projected +from generated.windows.application_model.background import ( + IBackgroundTask, + IBackgroundTaskInstance, +) +from generated.windows.foundation import IClosable, IStringable + + +class TaskInstance: + def __init__(self) -> None: + self.progress = 0 + + def get_instance_id(self) -> UUID: + return UUID("4ab7eea7-29a1-4f48-a6da-22894e210ec0") + + def get_progress(self) -> int: + return self.progress + + def set_progress(self, value: int) -> None: + self.progress = value + + def get_suspended_count(self) -> int: + return 0 + + def get_task(self) -> NoReturn: + raise NotImplementedError("This fixture has no registered OS task") + + def get_trigger_details(self) -> NoReturn: + raise NotImplementedError("This fixture has no OS trigger") + + def add_canceled(self, handler: object) -> NoReturn: + raise NotImplementedError("This fixture has no cancellation source") + + def remove_canceled(self, token: object) -> NoReturn: + raise NotImplementedError("This fixture has no cancellation source") + + def get_deferral(self) -> NoReturn: + raise NotImplementedError("This fixture does not create OS deferrals") + + +class Task: + def __init__(self) -> None: + self.runs = 0 + self.closes = 0 + + def run(self, instance: IBackgroundTaskInstance | None) -> None: + if instance is None: + raise ValueError("A task instance is required by this handler") + instance.progress = instance.progress + 1 + self.runs += 1 + + def to_string(self) -> str: + return f"Python task: {self.runs} native Run calls" + + def close(self) -> None: + self.closes += 1 + + +def main() -> None: + with RoApartment(1), projected_lifetime_scope(): + instance_owner = IBackgroundTaskInstance.implement(TaskInstance()) + handlers = Task() + owner = IBackgroundTask.implement( + handlers, + IStringable.implementation(handlers), + IClosable.implementation(handlers), + ) + instance = IBackgroundTaskInstance.from_implementation(instance_owner) + task = IBackgroundTask.from_implementation(owner) + text = IStringable.from_implementation(owner) + duplicate_text = IStringable.from_implementation(owner) + closable = IClosable.from_implementation(owner) + try: + assert text is not duplicate_text + release_projected(duplicate_text) + # Run and its nested progress property calls traverse native vtables. + task.run(instance) + assert instance.progress == 1 + print(text.to_string()) + owner.release() + task.run(instance) + assert instance.progress == 2 + closable.close() + assert handlers.closes == 1 + release_projected(closable) + assert not owner.is_closed + print(text.to_string()) + owner.dispose() + try: + text.to_string() + except OSError as error: + if error.winerror != -2147483629: # RO_E_CLOSED + raise + diagnostic = owner.take_error() + assert isinstance(diagnostic, str) and "0x80000013" in diagnostic + print(diagnostic) + else: + raise AssertionError("A disposed implementation accepted a native callback") + finally: + owner.dispose() + instance_owner.dispose() + for view in (closable, duplicate_text, text, task, instance): + release_projected(view) + assert owner.is_closed + + +if __name__ == "__main__": + main() diff --git a/samples/python/interface-implementation/generate.ps1 b/samples/python/interface-implementation/generate.ps1 new file mode 100644 index 00000000..33995f2d --- /dev/null +++ b/samples/python/interface-implementation/generate.ps1 @@ -0,0 +1,28 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [string]$Codegen = "dynwinrt-codegen", + [string]$Winmd +) + +$ErrorActionPreference = "Stop" +if (Test-Path -LiteralPath $Codegen -PathType Leaf) { + $Codegen = (Resolve-Path -LiteralPath $Codegen).Path +} else { + $Codegen = (Get-Command $Codegen -ErrorAction Stop).Source +} +$arguments = @( + "generate", + "--class-name", + "Windows.ApplicationModel.Background.IBackgroundTask,Windows.ApplicationModel.Background.IBackgroundTaskInstance,Windows.Foundation.IStringable,Windows.Foundation.IClosable", + "--lang", "py", + "--output", (Join-Path $PSScriptRoot "generated") +) +if ($Winmd) { + $arguments += @("--winmd", (Resolve-Path -LiteralPath $Winmd).Path) +} +& $Codegen @arguments +if ($LASTEXITCODE -ne 0) { + throw "WinRT interface generation failed with exit code $LASTEXITCODE" +} diff --git a/samples/python/interface-implementation/run.ps1 b/samples/python/interface-implementation/run.ps1 new file mode 100644 index 00000000..fa7082fb --- /dev/null +++ b/samples/python/interface-implementation/run.ps1 @@ -0,0 +1,16 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param([string]$Python = "python") + +$ErrorActionPreference = "Stop" +if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot "generated\__init__.py"))) { + throw "Generated bindings were not found. Run generate.ps1 first." +} +if (Test-Path -LiteralPath $Python -PathType Leaf) { + $Python = (Resolve-Path -LiteralPath $Python).Path +} +& $Python (Join-Path $PSScriptRoot "app.py") +if ($LASTEXITCODE -ne 0) { + exit $LASTEXITCODE +} diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index cc4876d8..297d3a89 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -3,7 +3,8 @@ # Licensed under the MIT License. # # E2E test orchestrator: build, generate, run language-specific runners, collect results. -# Test logic lives in runners/py_runner.py, runners/ts_runner.ts, and runners/com/*.mjs. +# Test logic lives in runners/py_runner.py, runners/ts_runner.ts, runners/com/*.mjs, +# and runners/implementation_{py.py,js.mjs}. # # Usage: # .\tests\e2e\e2e_test.ps1 # Full (build + generate + test) @@ -11,6 +12,8 @@ # .\tests\e2e\e2e_test.ps1 -Lang py # Python only # .\tests\e2e\e2e_test.ps1 -Lang ts # TypeScript only # .\tests\e2e\e2e_test.ps1 -Lang com # Classic COM only +# .\tests\e2e\e2e_test.ps1 -SkipBuild -Suite implementations -Lang py,ts -KeepGenerated +# .\tests\e2e\e2e_test.ps1 -SkipBuild -Suite standard # Existing WinRT/COM cases only param( [switch]$SkipBuild, @@ -18,12 +21,18 @@ param( [string]$CargoProfile = "release", [string]$CargoTarget, [string]$Python, + [ValidateSet("all", "standard", "implementations")] + [string]$Suite = "all", [ValidateSet("py", "ts", "com")] [string[]]$Lang = @("py", "ts", "com") ) $ErrorActionPreference = "Stop" $langWasExplicit = $PSBoundParameters.ContainsKey("Lang") +if ($Suite -eq "implementations") { + $Lang = @($Lang | Where-Object { $_ -in @("py", "ts") }) + if ($Lang.Count -eq 0) { throw "The implementations suite requires -Lang py and/or ts." } +} $root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent $specsFile = Join-Path $PSScriptRoot "e2e_specs.json" $e2eDir = Join-Path $PSScriptRoot "e2e_generated" @@ -110,6 +119,15 @@ if ("com" -in $Lang) { } } +# The focused selector shares the existing build/tool selection, but does not +# generate standard WinRT or COM fixtures (or delete their retained results). +if ($Suite -eq "implementations") { + & (Join-Path $PSScriptRoot "implementation_test.ps1") ` + -Lang $Lang -Python $pythonExe -CargoProfile $CargoProfile -CargoTarget $CargoTarget ` + -KeepGenerated:$KeepGenerated + exit $LASTEXITCODE +} + if ($Lang.Count -eq 0) { Write-Error "No languages available"; exit 1 } # -------------------------------------------------------------------------- @@ -157,7 +175,14 @@ if (-not $SkipBuild) { if ($LASTEXITCODE -ne 0) { Write-Error "npm install failed"; exit 1 } $napi = Join-Path $root "bindings\js\node_modules\.bin\napi.cmd" if (-not (Test-Path -LiteralPath $napi)) { Write-Error "NAPI CLI is missing: $napi"; exit 1 } - & $napi build --no-const-enum --platform @cargoProfileArgs @cargoTargetArgs -o dist 2>&1 | Out-Null + # NAPI uses --profile literally as the artifact directory. Cargo's + # built-in dev profile writes to debug, so let NAPI select its default + # debug build rather than looking for a nonexistent target/.../dev DLL. + [string[]]$napiProfileArgs = @( + if ($CargoProfile -eq "release") { "--release" } + elseif ($CargoProfile -ne "dev") { "--profile"; $CargoProfile } + ) + & $napi build --no-const-enum --platform @napiProfileArgs @cargoTargetArgs -o dist 2>&1 | Out-Null if ($LASTEXITCODE -ne 0) { Write-Error "napi build failed"; exit 1 } npm run build:entrypoints --silent if ($LASTEXITCODE -ne 0) { Write-Error "runtime entrypoint generation failed"; exit 1 } @@ -394,6 +419,21 @@ if ("com" -in $Lang) { } } +if ($Suite -eq "all" -and ("py" -in $Lang -or "ts" -in $Lang)) { + Write-Host "`n--- Generated WinRT implementations ---" -ForegroundColor Yellow + $implementationLangs = @($Lang | Where-Object { $_ -in @("py", "ts") }) + & (Join-Path $PSScriptRoot "implementation_test.ps1") ` + -Lang $implementationLangs -Python $pythonExe ` + -CargoProfile $CargoProfile -CargoTarget $CargoTarget -KeepGenerated + if ($LASTEXITCODE -ne 0) { $totalFail++ } else { $totalPass++ } + foreach ($l in $implementationLangs) { + $resultPath = Join-Path $e2eDir "implementations\results_$l.json" + if (Test-Path $resultPath) { + $allResults += Get-Content $resultPath -Raw | ConvertFrom-Json + } + } +} + # -------------------------------------------------------------------------- # Summary # -------------------------------------------------------------------------- diff --git a/tests/e2e/implementation_test.ps1 b/tests/e2e/implementation_test.ps1 new file mode 100644 index 00000000..8209a4f0 --- /dev/null +++ b/tests/e2e/implementation_test.ps1 @@ -0,0 +1,145 @@ +#!/usr/bin/env pwsh +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# +# Generation, strict consumer typechecks, and isolated native-vtable scenarios. +# Use e2e_test.ps1 -Suite implementations for the normal build/skip-build entrypoint. +# This script intentionally never installs tools, activates UI, or registers a task. + +param( + [ValidateSet("py", "ts")] + [string[]]$Lang = @("py", "ts"), + [string]$Python = "python", + [string]$CargoProfile = "release", + [string]$CargoTarget, + [switch]$KeepGenerated +) + +$ErrorActionPreference = "Stop" +$root = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent +$out = Join-Path $PSScriptRoot "e2e_generated\implementations" +$runtime = Join-Path $root "bindings\js\dist\winrt.js" +$failed = 0 +$generationResults = @{} +$typecheckResults = @{} +[string[]]$cargoArgs = @( + if ($CargoProfile -eq "release") { "--release" } + else { "--profile"; $CargoProfile } + if ($CargoTarget) { "--target"; $CargoTarget } +) +$winmd = if ($env:DYNWINRT_WINDOWS_WINMD) { + $env:DYNWINRT_WINDOWS_WINMD +} else { + "C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd" +} +if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) { + throw "WinRT implementation E2E requires Windows.winmd. Set DYNWINRT_WINDOWS_WINMD." +} + +# All are ordinary non-generic interfaces. IBindable* only contributes metadata; +# the test never initializes XAML. IDataReader contributes a real FillArray slot. +$classes = @( + "Windows.ApplicationModel.Background.IBackgroundTask", + "Windows.ApplicationModel.Background.IBackgroundTaskInstance", + "Windows.Foundation.IStringable", + "Windows.Foundation.IClosable", + "Windows.Foundation.IMemoryBufferReference", + "Windows.Globalization.NumberFormatting.INumberParser", + "Windows.Foundation.IPropertyValue", + "Windows.Storage.Streams.IDataWriter", + "Windows.Storage.Streams.IBuffer", + "Windows.Storage.Streams.IDataReader", + "Windows.UI.Xaml.Interop.IBindableVectorView", + "Windows.UI.Xaml.Interop.IBindableIterable", + "Windows.UI.Xaml.Interop.IBindableIterator" +) -join "," + +if (Test-Path -LiteralPath $out) { Remove-Item -LiteralPath $out -Recurse -Force } +New-Item -ItemType Directory -Path $out -Force | Out-Null + +foreach ($language in $Lang) { + Write-Host "`n--- Generate WinRT implementations ($language) ---" -ForegroundColor Yellow + $directory = Join-Path $out $(if ($language -eq "py") { "python_bindings" } else { "js" }) + $codegenLanguage = if ($language -eq "py") { "py" } else { "js" } + $runtimeImport = [IO.Path]::GetRelativePath($directory, $runtime).Replace("\", "/") + $generatedModules = 0 + & cargo run -p dynwinrt-codegen @cargoArgs --quiet -- generate ` + --winmd $winmd --class-name $classes --lang $codegenLanguage ` + --output $directory --import-name $runtimeImport | + ForEach-Object { + if ($_ -like "Generated *") { $generatedModules++ } + else { Write-Host $_ } + } + $generationResults[$language] = $LASTEXITCODE -eq 0 + if ($LASTEXITCODE -ne 0) { + Write-Host " FAIL generation ($language); other selected languages will still run." -ForegroundColor Red + $failed++ + continue + } + Write-Host " Generated $generatedModules modules in $directory" + + # Typecheck failures are not an excuse to skip native execution. Retain both + # diagnostics so an integration run reports the complete blocked matrix. + if ($language -eq "py") { + Write-Host "`n--- Implementation .pyi consumer typecheck ---" -ForegroundColor Yellow + $previousMypyPath = $env:MYPYPATH + try { + # Long generic delegate facade names can exceed MAX_PATH in a + # shared-worktree checkout. Use extended paths, not registry/OS + # changes or suppressed import diagnostics. + $env:MYPYPATH = if ($env:OS -eq "Windows_NT" -and -not $out.StartsWith('\\?\')) { + if ($out.StartsWith('\\')) { '\\?\UNC\' + $out.Substring(2) } + else { '\\?\' + $out } + } else { $out } + & $Python -m mypy --strict (Join-Path $PSScriptRoot "typecheck\python_implementation_api.py") + $typecheckResults[$language] = $LASTEXITCODE -eq 0 + if ($LASTEXITCODE -ne 0) { $failed++ } + } finally { + $env:MYPYPATH = $previousMypyPath + } + Write-Host "`n--- Python implementation native E2E ---" -ForegroundColor Yellow + & $Python (Join-Path $PSScriptRoot "runners\implementation_py.py") ` + --generated $directory --output (Join-Path $out "results_py.json") + if ($LASTEXITCODE -ne 0) { $failed++ } + } else { + Write-Host "`n--- Implementation .d.ts consumer typecheck ---" -ForegroundColor Yellow + $tsc = Join-Path $root "bindings\js\node_modules\typescript\bin\tsc" + if (-not (Test-Path -LiteralPath $tsc)) { + Write-Host " FAIL: TypeScript compiler missing at $tsc (install the existing bindings/js dependencies)." -ForegroundColor Red + $failed++ + $typecheckResults[$language] = $false + } else { + & node $tsc --noEmit --strict --target ES2022 --module Node16 --moduleResolution Node16 ` + --types node --typeRoots (Join-Path $root "bindings\js\node_modules\@types") ` + (Join-Path $PSScriptRoot "typecheck\ts_implementation_api.ts") + $typecheckResults[$language] = $LASTEXITCODE -eq 0 + if ($LASTEXITCODE -ne 0) { $failed++ } + } + Write-Host "`n--- Node implementation native E2E ---" -ForegroundColor Yellow + & node (Join-Path $PSScriptRoot "runners\implementation_js.mjs") ` + --generated $directory --runtime $runtime --output (Join-Path $out "results_ts.json") + if ($LASTEXITCODE -ne 0) { $failed++ } + } +} + +Write-Host "`n=== Generated implementation summary ===" -ForegroundColor Cyan +foreach ($language in $Lang) { + $generationStatus = if ($generationResults[$language]) { "PASS" } else { "FAIL" } + $typecheckStatus = if (-not $typecheckResults.ContainsKey($language)) { "BLOCKED" } + elseif ($typecheckResults[$language]) { "PASS" } else { "FAIL" } + Write-Host " $language`: generation $generationStatus; strict typecheck $typecheckStatus" + $result = Join-Path $out "results_$language.json" + if (Test-Path -LiteralPath $result) { + $report = Get-Content -LiteralPath $result -Raw | ConvertFrom-Json + Write-Host " $($report.language): $($report.passed)/$($report.total) passed ($($report.architecture))" + } else { + Write-Host " $language`: BLOCKED before native runner produced results" -ForegroundColor Red + } +} +if ($failed -ne 0) { + Write-Host "IMPLEMENTATION E2E FAILED; generated files and JSON retained at $out" -ForegroundColor Red + exit 1 +} +Write-Host "IMPLEMENTATION E2E PASSED" -ForegroundColor Green +if (-not $KeepGenerated) { Remove-Item -LiteralPath $out -Recurse -Force } +exit 0 diff --git a/tests/e2e/runners/implementation_js.mjs b/tests/e2e/runners/implementation_js.mjs new file mode 100644 index 00000000..46cf5e64 --- /dev/null +++ b/tests/e2e/runners/implementation_js.mjs @@ -0,0 +1,666 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +/** + * Generated WinRT implementation E2E. Every scenario runs in a fresh process: + * a native crash/hang is a failure, not a reason to lose the rest of the matrix. + * Only generated factories create implementation objects. Native consumers are + * generated outbound methods or independently registered stock method handles; + * no test calls an interface handler directly. + */ +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import { mkdirSync, writeFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const require = createRequire(import.meta.url); +const filename = fileURLToPath(import.meta.url); +const resultPrefix = 'DYNWINRT_IMPLEMENTATION_RESULT='; +const E_FAIL = 0x80004005; +const RO_E_CLOSED = 0x80000013; +const instanceId = '243aab7d-9411-49af-b66d-0123456789ab'; + +function notImplemented() { + throw new Error('Unused standalone E2E fixture method'); +} + +function expectHresult(action, expected) { + let error; + try { action(); } catch (caught) { error = caught; } + assert.ok(error, `Expected native HRESULT 0x${expected.toString(16)}`); + const codes = [error.hresult, error.winerror, error.code].filter(value => typeof value === 'number'); + const text = String(error); + assert.ok( + codes.some(code => (code >>> 0) === expected) || + text.toLowerCase().includes(expected.toString(16)) || + text.includes(String(expected | 0)), + `Expected HRESULT 0x${expected.toString(16)}, got ${error.stack ?? error}`, + ); + return error; +} + +function takeError(owner, pattern) { + const error = owner.takeError(); + assert.ok(error != null, 'Native callback failure must be available through takeError()'); + assert.match(String(error.message ?? error), pattern); + assert.equal(owner.takeError(), null, 'takeError() must drain the stored error'); +} + +function nativeConsumer(runtime, owner, name, iidText, methodName, signature) { + // Both stock interfaces used here have one method at IInspectable slot 6. + // Always QI first: toValue() returns the canonical IInspectable pointer, + // which must NEVER be called as though it were an arbitrary interface view. + const iid = runtime.WinGuid.parse(iidText); + const method = runtime.DynWinRtType.registerInterface(`E2E.${name}Consumer`, iid) + .addMethod(methodName, signature).method(6); + const canonical = owner.toValue(); + let value; + try { value = canonical.cast(iid); } finally { canonical.release(); } + return { invoke: () => method.invoke(value, []), release: () => value.release() }; +} + +function nativeStringable(runtime, owner) { + return nativeConsumer(runtime, owner, 'IStringable', '96369f54-8eb6-48f0-abce-c1b211e627c3', 'ToString', + new runtime.DynWinRtMethodSig().addOut(runtime.DynWinRtType.hstring())); +} + +function taskInstanceHandlers(state) { + // IBackgroundTaskInstance has exactly nine slots, 6 through 14. In + // particular, Canceled is not a made-up success with a fabricated token. + return { + getInstanceId() { state.getIds++; return instanceId; }, + getTask: notImplemented, + getProgress() { state.gets++; return state.progress; }, + setProgress(value) { state.sets++; state.progress = value; }, + getTriggerDetails: notImplemented, + addCanceled: notImplemented, + removeCanceled: notImplemented, + getSuspendedCount: notImplemented, + getDeferral: notImplemented, + }; +} + +function readerHandlers(readBytes) { + // A complete IDataReader plan, not a truncated vtable. Only ReadBytes is + // used by this fixture; every other metadata slot deliberately fails. + return { + getUnconsumedBufferLength: notImplemented, + getUnicodeEncoding: notImplemented, setUnicodeEncoding: notImplemented, + getByteOrder: notImplemented, setByteOrder: notImplemented, + getInputStreamOptions: notImplemented, setInputStreamOptions: notImplemented, + readByte: notImplemented, readBytes, readBuffer: notImplemented, + readBoolean: notImplemented, readGuid: notImplemented, + readInt16: notImplemented, readInt32: notImplemented, readInt64: notImplemented, + readUInt16: notImplemented, readUInt32: notImplemented, readUInt64: notImplemented, + readSingle: notImplemented, readDouble: notImplemented, readString: notImplemented, + readDateTime: notImplemented, readTimeSpan: notImplemented, + loadAsync: notImplemented, detachBuffer: notImplemented, detachStream: notImplemented, + }; +} + +const cases = { + background_task({ g, runtime, own }) { + const state = { progress: 17, gets: 0, sets: 0, getIds: 0 }; + const instanceOwner = own(g.IBackgroundTaskInstance.implement(taskInstanceHandlers(state))); + const instance = g.IBackgroundTaskInstance.fromImplementation(instanceOwner); + let runs = 0; + const taskOwner = own(g.IBackgroundTask.implement({ + run(taskInstance) { + assert.ok(taskInstance instanceof g.IBackgroundTaskInstance); + assert.equal(taskInstance.instanceId.toLowerCase(), instanceId); + taskInstance.progress = taskInstance.progress + 5; + runs++; + }, + })); + const task = g.IBackgroundTask.fromImplementation(taskOwner); + task.run(instance); + assert.deepEqual(state, { progress: 22, gets: 1, sets: 1, getIds: 1 }); + assert.equal(runs, 1); + instanceOwner.release(); + taskOwner.release(); + task.run(instance); + assert.deepEqual(state, { progress: 27, gets: 2, sets: 2, getIds: 2 }); + assert.equal(runs, 2); + const token = runtime.DynWinRtStruct.create(runtime.DynWinRtType.structType( + 'Windows.Foundation.EventRegistrationToken', [runtime.DynWinRtType.i64()], + )); + token.setI64(0, 1n); + for (const action of [ + () => instance.task, + () => instance.triggerDetails, + () => instance.suspendedCount, + () => instance.getDeferral(), + () => instance.onCanceled(() => {}), + () => instance.offCanceled(token.toValue()), + ]) { + expectHresult(action, E_FAIL); + takeError(instanceOwner, /unused standalone/i); + } + }, + + multi_interface_lifetime({ g, own }) { + let closes = 0; + const owner = own(g.IStringable.implement( + { toString: () => 'retained \0 WinRT \u96ea' }, + g.IClosable.implementation({ close() { closes++; } }), + )); + const first = g.IStringable.fromImplementation(owner); + const second = g.IStringable.fromImplementation(owner); + const closable = g.IClosable.fromImplementation(owner); + assert.notEqual(first, second, 'Typed views must not reuse one mutable native holder'); + const retained = owner.toValue(); + try { + // The public lifetime helper releases only this view's QI reference. + g.releaseProjected(first); + assert.equal(second.toString(), 'retained \0 WinRT \u96ea'); + owner.release(); + owner.release(); + assert.equal(owner.isClosed, false, 'release() is not dispose()'); + assert.equal(second.toString(), 'retained \0 WinRT \u96ea'); + closable.close(); + assert.equal(closes, 1); + const nativeRetainedView = g.IStringable.from(retained); + retained.release(); + assert.equal(nativeRetainedView.toString(), 'retained \0 WinRT \u96ea'); + g.releaseProjected(nativeRetainedView); + assert.equal(owner.takeError(), null); + } finally { retained.release(); } + }, + + dispose_disconnects({ g, runtime, own }) { + let calls = 0; + const owner = own(g.IStringable.implement( + { toString() { calls++; return 'before disposal'; } }, + g.IClosable.implementation({ close() { calls++; } }), + )); + const text = nativeStringable(runtime, owner); + const close = nativeConsumer(runtime, owner, 'IClosable', '30d5a829-7fa4-4026-83bb-d75bae4ea99e', 'Close', + new runtime.DynWinRtMethodSig()); + try { + assert.equal(text.invoke().toString(), 'before disposal'); + close.invoke(); + owner.release(); + assert.equal(text.invoke().toString(), 'before disposal'); + assert.equal(owner.isClosed, false); + owner.dispose(); + owner.dispose(); + assert.equal(owner.isClosed, true); + expectHresult(text.invoke, RO_E_CLOSED); + expectHresult(close.invoke, RO_E_CLOSED); + assert.equal(calls, 3, 'Disposed native views must not enter any handler'); + } finally { close.release(); text.release(); } + }, + + reentrant_dispose({ g, runtime, own }) { + let calls = 0; + const owner = own(g.IStringable.implement({ + toString() { calls++; owner.dispose(); return 'active callback finished'; }, + })); + const view = nativeStringable(runtime, owner); + try { + assert.equal(view.invoke().toString(), 'active callback finished'); + assert.equal(owner.isClosed, true); + expectHresult(view.invoke, RO_E_CLOSED); + assert.equal(calls, 1); + } finally { view.release(); } + }, + + callback_error({ g, runtime, own }) { + let fail = true; + const owner = own(g.IStringable.implement({ + toString() { + if (fail) throw new Error('implementation-e2e-js-sentinel'); + return 'recovered'; + }, + })); + const view = nativeStringable(runtime, owner); + try { + expectHresult(view.invoke, E_FAIL); + takeError(owner, /implementation-e2e-js-sentinel/); + fail = false; + assert.equal(view.invoke().toString(), 'recovered'); + assert.equal(owner.isClosed, false); + assert.equal(owner.takeError(), null); + } finally { view.release(); } + }, + + async_handler_rejected({ g }) { + let entered = false; + assert.throws( + () => g.IStringable.implementation({ async toString() { entered = true; return 'bad'; } }), + /async|synchronous/i, + ); + assert.throws( + () => g.IClosable.implementation({ async close() { entered = true; } }), + /async|synchronous/i, + ); + assert.equal(entered, false); + }, + + async_result_rejected({ g, runtime, own }) { + const owner = own(g.IStringable.implement({ toString: () => Promise.resolve('not a WinRT result') })); + const view = nativeStringable(runtime, owner); + try { + expectHresult(view.invoke, E_FAIL); + takeError(owner, /promise|async|synchronous/i); + } finally { view.release(); } + }, + + required_interfaces({ g, own }) { + const handlers = { getCapacity: () => 73, addClosed: notImplemented, removeClosed: notImplemented }; + assert.throws( + () => g.IMemoryBufferReference.implement(handlers), + /required|IClosable|30d5a829/i, + ); + const owner = own(g.IMemoryBufferReference.implement( + handlers, g.IClosable.implementation({ close() {} }), + )); + assert.equal(g.IMemoryBufferReference.fromImplementation(owner).capacity, 73); + g.IClosable.fromImplementation(owner).close(); + assert.throws( + () => g.IStringable.implement({ toString: () => '' }, g.IStringable.implementation({ toString: () => '' })), + /duplicate|already|IID/i, + ); + const onlyStringable = own(g.IStringable.implement({ toString: () => 'not IClosable' })); + expectHresult(() => g.IClosable.fromImplementation(onlyStringable), 0x80004002); + }, + + memory_buffer_event({ g, own }) { + const callbacks = new Map(); + let added = 0; + let removed = 0; + let delivered = 0; + let eventSender; + const owner = own(g.IMemoryBufferReference.implement({ + getCapacity: () => 4096, + addClosed(handler) { + assert.ok(handler != null, 'Closed receives a native delegate'); + assert.equal(typeof handler, 'function', 'Received delegates are typed callable native views'); + callbacks.set(++added, handler); + return { value: BigInt(added) }; + }, + removeClosed(token) { + assert.equal(typeof token.value, 'bigint'); + const received = callbacks.get(Number(token.value)); + assert.ok(received); + assert.equal(callbacks.delete(Number(token.value)), true); + g.releaseProjected(received); + removed++; + }, + }, g.IClosable.implementation({ + close() { + for (const callback of [...callbacks.values()]) { + // This is a generated wrapper over native delegate slot 3, + // not the original JavaScript event callback. + callback(eventSender, null); + } + }, + }))); + eventSender = g.IMemoryBufferReference.fromImplementation(owner); + const close = g.IClosable.fromImplementation(owner); + const unsubscribe = eventSender.onClosed((sender, args) => { + assert.ok(sender instanceof g.IMemoryBufferReference); + assert.equal(sender.capacity, 4096); // Reentrant native property call. + assert.equal(args, null); + delivered++; + }); + assert.equal(added, 1); + owner.release(); + close.close(); + assert.equal(delivered, 1, 'Close must invoke the delegate through its native vtable'); + unsubscribe(); + assert.equal(removed, 1); + close.close(); + assert.equal(delivered, 1); + owner.dispose(); + expectHresult(() => close.close(), RO_E_CLOSED); + }, + + array_contracts({ g, runtime, own }) { + // Public, non-exclusive SDK interfaces: do not expose an ExclusiveTo + // factory interface just to obtain a convenient array fixture. + const state = { bytes: Buffer.alloc(0), text: '', guid: instanceId, signed: 0n, unsigned: 0n, real: 0 }; + const writerHandlers = Object.fromEntries([ + 'getUnstoredBufferLength', 'getUnicodeEncoding', 'setUnicodeEncoding', + 'getByteOrder', 'setByteOrder', 'writeByte', 'writeBufferRange', + 'writeBoolean', 'writeInt16', 'writeInt32', 'writeUInt16', 'writeUInt32', + 'writeSingle', 'writeDateTime', 'writeTimeSpan', 'storeAsync', 'flushAsync', + 'detachStream', + ].map(name => [name, notImplemented])); + Object.assign(writerHandlers, { + writeBytes(value) { + assert.ok(Array.isArray(value), 'PassArray input is a projected number[]'); + state.bytes = Buffer.from(value); + }, + writeBuffer(value) { + assert.ok(value instanceof g.IBuffer); + state.bytes = value.toBuffer(); + }, + writeString(value) { state.text = value; return Buffer.byteLength(value); }, + measureString: value => Buffer.byteLength(value), + writeGuid: value => { state.guid = value; }, + writeInt64: value => { state.signed = value; }, + writeUInt64: value => { state.unsigned = value; }, + writeDouble: value => { state.real = value; }, + detachBuffer: () => g.IBuffer.fromBuffer(state.bytes), + }); + const writerOwner = own(g.IDataWriter.implement(writerHandlers, g.IClosable.implementation({ close() {} }))); + const writer = g.IDataWriter.fromImplementation(writerOwner); + const propertyHandlers = Object.fromEntries([ + 'getType', 'getIsNumericScalar', 'getUInt8', 'getInt16', 'getUInt16', 'getInt32', + 'getUInt32', 'getSingle', 'getChar16', 'getBoolean', 'getDateTime', 'getTimeSpan', + 'getPoint', 'getSize', 'getRect', 'getInt16Array', 'getUInt16Array', 'getInt32Array', + 'getUInt32Array', 'getSingleArray', 'getChar16Array', 'getBooleanArray', + 'getDateTimeArray', 'getTimeSpanArray', 'getSizeArray', 'getRectArray', + ].map(name => [name, notImplemented])); + const objectOwner = own(g.IStringable.implement({ toString: () => 'array object' })); + const object = objectOwner.toValue(); + let invalidElement = false; + Object.assign(propertyHandlers, { + getUInt8Array: () => state.bytes, + getString: () => state.text, + getStringArray: () => invalidElement ? [state.text, 42] : [state.text, '', 'snow \u96ea'], + getGuid: () => state.guid, + getGuidArray: () => [state.guid, instanceId], + getInt64: () => state.signed, + getInt64Array: () => [state.signed, -(1n << 63n)], + getUInt64: () => state.unsigned, + getUInt64Array: () => [state.unsigned, (1n << 64n) - 1n], + getDouble: () => state.real, + getDoubleArray: () => [state.real, -2.5], + getPointArray: () => [{ x: 1.25, y: -3.5 }, { x: 0, y: 2 }], + getInspectableArray: () => [object, null], + }); + const owner = own(g.IPropertyValue.implement(propertyHandlers)); + const view = g.IPropertyValue.fromImplementation(owner); + writerOwner.release(); + owner.release(); + for (const bytes of [Buffer.alloc(0), Buffer.from([0, 1, 127, 128, 255])]) { + writer.writeBytes(bytes); + assert.deepEqual(view.getUInt8Array(), bytes); + const native = writer.detachBuffer(); + assert.ok(native instanceof g.IBuffer); + assert.equal(native.length, bytes.length); + assert.deepEqual(native.toBuffer(), bytes); + writer.writeBuffer(native); + assert.deepEqual(view.getUInt8Array(), bytes); + g.releaseProjected(native); + } + const text = 'generated \0 WinRT \u96ea \ud83d\ude80'; + assert.equal(writer.writeString(text), writer.measureString(text)); + assert.equal(view.getString(), text); + assert.deepEqual(view.getStringArray(), [text, '', 'snow \u96ea']); + writer.writeGuid(instanceId); + assert.equal(view.getGuid().toLowerCase(), instanceId); + assert.deepEqual(view.getGuidArray().map(value => value.toLowerCase()), [instanceId, instanceId]); + writer.writeInt64((1n << 63n) - 1n); + writer.writeUInt64((1n << 64n) - 1n); + writer.writeDouble(1.25); + assert.equal(view.getInt64(), (1n << 63n) - 1n); + assert.equal(view.getUInt64(), (1n << 64n) - 1n); + assert.equal(view.getDouble(), 1.25); + assert.deepEqual(view.getInt64Array(), [(1n << 63n) - 1n, -(1n << 63n)]); + assert.deepEqual(view.getUInt64Array(), [(1n << 64n) - 1n, (1n << 64n) - 1n]); + assert.deepEqual(view.getDoubleArray(), [1.25, -2.5]); + assert.deepEqual(view.getPointArray(), [{ x: 1.25, y: -3.5 }, { x: 0, y: 2 }]); + const objects = view.getInspectableArray(); + assert.equal(objects.length, 2); + const textView = g.IStringable.from(objects[0]); + assert.equal(textView.toString(), 'array object'); + assert.equal(objects[1], null); + g.releaseProjected(textView); + objects.forEach(value => value?.release()); + invalidElement = true; + expectHresult(() => view.getStringArray(), E_FAIL); + takeError(owner, /getStringArray|invalid implementation result/i); + invalidElement = false; + assert.deepEqual(view.getStringArray(), [text, '', 'snow \u96ea']); + assert.equal(owner.takeError(), null); + assert.equal(writerOwner.takeError(), null); + object.release(); + g.releaseProjected(view); + g.releaseProjected(writer); + }, + + fill_array({ g, own }) { + const capacities = []; + const owner = own(g.IDataReader.implement(readerHandlers(capacity => { + assert.equal(typeof capacity, 'number'); + capacities.push(capacity); + return Uint8Array.from({ length: capacity }, (_, index) => (index * 17 + 3) & 255); + }), g.IClosable.implementation({ close() {} }))); + const view = g.IDataReader.fromImplementation(owner); + for (const capacity of [0, 1, 7, 257]) { + const actual = view.readBytes(new Uint8Array(capacity)); + assert.deepEqual(Array.from(actual), Array.from({ length: capacity }, (_, index) => (index * 17 + 3) & 255)); + } + assert.deepEqual(capacities, [0, 1, 7, 257], 'FillArray logical input must be U32 capacity, not an array'); + expectHresult(() => view.readByte(), E_FAIL); + takeError(owner, /unused standalone/i); + }, + + fill_array_wrong_length({ g, own }) { + let wrong = true; + const owner = own(g.IDataReader.implement(readerHandlers(capacity => new Uint8Array(capacity - (wrong ? 1 : 0))), + g.IClosable.implementation({ close() {} }))); + const view = g.IDataReader.fromImplementation(owner); + assert.throws(() => view.readBytes(new Uint8Array(4)), /length|capacity|80070057|invalid/i); + takeError(owner, /capacity|length/i); + wrong = false; + assert.equal(view.readBytes(new Uint8Array(4)).length, 4); + assert.equal(owner.takeError(), null); + }, + + named_outputs({ g, own }) { + let named = true; + const owner = own(g.IBindableVectorView.implement({ + getAt(index) { assert.equal(index, 0); return null; }, + getSize: () => 1, + // Deliberately reverse object field insertion order. Metadata out + // params come first at the ABI, then the method return, by NAME. + indexOf(value) { + return named ? { result: value === null, index: value === null ? 0 : 0xffffffff } : [0, true]; + }, + }, g.IBindableIterable.implementation({ + first() { + let current = true; + const iteratorOwner = own(g.IBindableIterator.implement({ + getCurrent: () => null, + getHasCurrent: () => current, + moveNext() { current = false; return false; }, + })); + return g.IBindableIterator.fromImplementation(iteratorOwner); + }, + }))); + const view = g.IBindableVectorView.fromImplementation(owner); + assert.equal(view.size, 1); + assert.equal(view.getAt(0), null); + // Existing outbound projections preserve their tuple shape. Inbound + // implementation handlers use the new named multi-output shape. + assert.deepEqual(view.indexOf(null), [0, true]); + const other = own(g.IStringable.implement({ toString: () => 'not in the vector' })); + const raw = other.toValue(); + try { assert.deepEqual(view.indexOf(raw), [0xffffffff, false]); } + finally { raw.release(); } + const iterator = g.IBindableIterable.fromImplementation(owner).first(); + assert.equal(iterator.hasCurrent, true); + assert.equal(iterator.current, null); + assert.equal(iterator.moveNext(), false); + assert.equal(iterator.hasCurrent, false); + assert.equal(owner.takeError(), null); + named = false; + expectHresult(() => view.indexOf(null), E_FAIL); + takeError(owner, /named|field/i); + named = true; + assert.deepEqual(view.indexOf(null), [0, true]); + }, + + nullable_reference_results({ g, own }) { + const owner = own(g.INumberParser.implement({ + parseInt(text) { + assert.equal(typeof text, 'string'); + if (!/^-?\d+$/.test(text)) return null; + const value = BigInt(text); + return value >= -(1n << 63n) && value < (1n << 63n) ? value : null; + }, + parseUInt(text) { + assert.equal(typeof text, 'string'); + if (!/^\d+$/.test(text)) return null; + const value = BigInt(text); + return value < (1n << 64n) ? value : null; + }, + parseDouble(text) { + assert.equal(typeof text, 'string'); + const value = Number(text); + return Number.isFinite(value) ? value : null; + }, + })); + const view = g.INumberParser.fromImplementation(owner); + owner.release(); + try { + for (const value of [-(1n << 63n), 0n, (1n << 63n) - 1n]) { + assert.equal(view.parseInt(String(value)), value); + } + for (const value of [0n, (1n << 64n) - 1n]) { + assert.equal(view.parseUInt(String(value)), value); + } + assert.equal(view.parseInt('9223372036854775808'), null); + assert.equal(view.parseUInt('-1'), null); + assert.equal(view.parseUInt('18446744073709551616'), null); + assert.equal(view.parseInt('invalid'), null); + assert.equal(view.parseDouble('2.5'), 2.5); + assert.equal(view.parseDouble('-0.125'), -0.125); + assert.equal(view.parseDouble('invalid'), null); + assert.equal(owner.takeError(), null); + } finally { g.releaseProjected(view); } + }, + + public_view_success_ref_balance({ g, runtime, own }) { + const owner = own(g.IStringable.implement({ toString: () => 'balanced public view' })); + const view = g.IStringable.fromImplementation(owner); + try { + assert.equal(view.toString(), 'balanced public view'); + } finally { g.releaseProjected(view); } + assert.equal(owner.isClosed, false, 'Releasing the view must leave the owner usable'); + const consumer = nativeStringable(runtime, owner); + try { assert.equal(consumer.invoke().toString(), 'balanced public view'); } + finally { consumer.release(); } + owner.release(); + // No GC or dispose before this assertion: there are no intentional + // native aliases left, so a canonical temporary cannot be hidden. + assert.equal(owner.isClosed, true, 'Successful fromImplementation leaked a native reference'); + }, + + public_view_failed_cast_ref_balance({ g, runtime, own }) { + const owner = own(g.IStringable.implement({ toString: () => 'still usable after failed QI' })); + expectHresult(() => g.IClosable.fromImplementation(owner), 0x80004002); + assert.equal(owner.isClosed, false, 'A failed conversion must not dispose the owner'); + const consumer = nativeStringable(runtime, owner); + try { assert.equal(consumer.invoke().toString(), 'still usable after failed QI'); } + finally { consumer.release(); } + owner.release(); + assert.equal(owner.isClosed, true, 'Failed fromImplementation leaked its canonical temporary'); + }, +}; + +export const caseIds = Object.freeze(Object.keys(cases)); + +export function decodeChildResult(id, child) { + const line = (child.stdout ?? '').split(/\r?\n/).findLast(value => value.startsWith(resultPrefix)); + let result = { + id, pass: false, + error: `Native child did not report a result (exit=${child.status}, signal=${child.signal}, error=${child.error ?? 'none'})\n${child.stdout ?? ''}`, + }; + if (line) { + try { + const payload = JSON.parse(line.slice(resultPrefix.length)); + if (payload.id !== id || typeof payload.pass !== 'boolean') throw new Error('Invalid case result envelope'); + result = payload; + } catch (error) { + result.error = `Invalid native child result: ${error}`; + } + } + if (child.status !== 0 && result.pass) { + result = { ...result, pass: false, error: `Native child failed during cleanup (exit=${child.status}, ${child.error ?? ''})` }; + } + return { ...result, exit_code: child.status, stderr: child.stderr ?? '' }; +} + +function options() { + const result = {}; + for (let index = 2; index < process.argv.length; index += 2) { + const key = process.argv[index]; + if (!key.startsWith('--') || !process.argv[index + 1]) throw new Error(`Invalid argument: ${key}`); + result[key.slice(2)] = process.argv[index + 1]; + } + for (const key of ['generated', 'runtime']) { + if (!result[key]) throw new Error(`--${key} is required`); + result[key] = path.resolve(result[key]); + } + if (result.case && !Object.hasOwn(cases, result.case)) throw new Error(`Unknown case: ${result.case}`); + return result; +} + +function runOne(id, args) { + const started = performance.now(); + const owners = []; + let error = null; + try { + const runtime = require(args.runtime); + assert.equal(typeof runtime.DynWinRtImplementation, 'function', 'Build the JS runtime with WinRT implementation support'); + runtime.roInitialize(1); + const g = require(path.join(args.generated, 'index.js')); + cases[id]({ g, runtime, own(value) { owners.push(value); return value; } }); + } catch (caught) { + error = caught.stack ?? String(caught); + } finally { + for (const owner of owners.reverse()) { + try { owner.dispose(); } catch (caught) { error ??= caught.stack ?? String(caught); } + } + } + return { id, pass: error === null, error, duration_ms: Math.round(performance.now() - started) }; +} + +function main() { + const args = options(); + if (args.case) { + const result = runOne(args.case, args); + console.log(resultPrefix + JSON.stringify(result)); + if (!result.pass) process.exitCode = 1; + return; + } + const results = []; + const printedErrors = new Set(); + console.log(`Node ${process.version}, ${process.arch}, ${process.execPath}`); + for (const id of caseIds) { + const child = spawnSync(process.execPath, [ + filename, '--case', id, '--generated', args.generated, '--runtime', args.runtime, + ], { encoding: 'utf8', timeout: 90_000, maxBuffer: 8 * 1024 * 1024, windowsHide: true }); + const result = decodeChildResult(id, child); + results.push(result); + console.log(` ${result.pass ? 'PASS' : 'FAIL'} ${id}`); + if (!result.pass) { + const diagnostic = `${result.error}\n${result.stderr}`; + const key = `${String(result.error).split('\n')[0]}\n${result.stderr}`; + if (!printedErrors.has(key)) { + console.log(diagnostic); + printedErrors.add(key); + } + } + } + const report = { + language: 'ts-implementations', architecture: process.arch, runtime: process.version, + executable: process.execPath, binding: args.runtime, generated: args.generated, + passed: results.filter(result => result.pass).length, total: results.length, results, + }; + console.log(`Node implementation E2E: ${report.passed}/${report.total} passed (${report.architecture})`); + if (args.output) { + mkdirSync(path.dirname(path.resolve(args.output)), { recursive: true }); + writeFileSync(args.output, JSON.stringify(report, null, 2) + '\n'); + } + if (report.passed !== report.total) process.exitCode = 1; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === filename) main(); diff --git a/tests/e2e/runners/implementation_js.test.mjs b/tests/e2e/runners/implementation_js.test.mjs new file mode 100644 index 00000000..d736e8ea --- /dev/null +++ b/tests/e2e/runners/implementation_js.test.mjs @@ -0,0 +1,39 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { caseIds, decodeChildResult } from './implementation_js.mjs'; + +const pass = 'DYNWINRT_IMPLEMENTATION_RESULT={"id":"case","pass":true,"error":null}\n'; + +test('native case result is preserved only for a successful process', () => { + assert.equal(decodeChildResult('case', { stdout: pass, status: 0 }).pass, true); + const failed = decodeChildResult('case', { stdout: pass, status: 3221225477 }); + assert.equal(failed.pass, false); + assert.match(failed.error, /cleanup/); +}); + +test('crash, timeout, missing result, and malformed result are failures', () => { + for (const child of [ + { stdout: '', status: 3221225477 }, + { stdout: '', status: null, error: new Error('ETIMEDOUT') }, + { stdout: 'no marker', status: 0 }, + { stdout: 'DYNWINRT_IMPLEMENTATION_RESULT=invalid', status: 0 }, + { stdout: 'DYNWINRT_IMPLEMENTATION_RESULT={"id":"wrong","pass":true}', status: 0 }, + { stdout: 'DYNWINRT_IMPLEMENTATION_RESULT={"id":"case","pass":"true"}', status: 0 }, + ]) { + assert.equal(decodeChildResult('case', child).pass, false); + } +}); + +test('the whole requested native scenario matrix stays enabled', () => { + assert.equal(caseIds.length, 16); + assert.equal(caseIds[0], 'background_task'); + for (const name of ['memory_buffer_event', 'array_contracts', 'fill_array', 'named_outputs']) { + assert.ok(caseIds.includes(name)); + } + assert.ok(caseIds.includes('public_view_success_ref_balance')); + assert.ok(caseIds.includes('public_view_failed_cast_ref_balance')); + assert.ok(caseIds.includes('nullable_reference_results')); +}); diff --git a/tests/e2e/runners/implementation_py.py b/tests/e2e/runners/implementation_py.py new file mode 100644 index 00000000..4344d187 --- /dev/null +++ b/tests/e2e/runners/implementation_py.py @@ -0,0 +1,1035 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Generated implementations exercised only via real native vtable invocations. + +Each case is a subprocess, so native crashes, cleanup failures, and hangs are +reported without silently dropping the rest of the requested coverage. +""" + +from __future__ import annotations + +import argparse +from contextlib import ExitStack, contextmanager +import gc +import importlib +import importlib.util +import inspect +import json +from pathlib import Path +import platform +import re +import struct +import subprocess +import sys +import time +import traceback +from uuid import UUID +import weakref + + +RESULT_PREFIX = "DYNWINRT_IMPLEMENTATION_RESULT=" +RO_E_CLOSED = 0x80000013 +PYTHON_CALLBACK_ERROR = 0xA0EE4005 # Existing PyWinRT-compatible callback HRESULT. +INSTANCE_ID = UUID("243aab7d-9411-49af-b66d-0123456789ab") + + +def not_implemented(*_args): + raise NotImplementedError("Unused standalone E2E fixture method") + + +def expect_hresult(action, expected): + try: + action() + except OSError as error: + actual = error.winerror & 0xFFFFFFFF + assert actual == expected, ( + f"Expected native HRESULT 0x{expected:08x}, got 0x{actual:08x}: {error}" + ) + return error + raise AssertionError(f"Expected native HRESULT 0x{expected:08x}") + + +def expect_error(action, pattern): + try: + action() + except Exception as error: + assert re.search(pattern, str(error), re.IGNORECASE), str(error) + return error + raise AssertionError(f"Expected an error matching {pattern!r}") + + +def take_error(owner, pattern): + error = owner.take_error() + assert error is not None, "Callback failure must be available through take_error()" + assert re.search(pattern, str(error), re.IGNORECASE), str(error) + assert owner.take_error() is None, "take_error() must drain the stored error" + + +@contextmanager +def native_consumer(dw, owner, name, iid_text, method_name, signature): + # These stock interfaces each have exactly one method at slot 6. A + # canonical IInspectable value is NOT that view: QI before any vtable call. + iid = dw.WinGUID.parse(iid_text) + interface = dw.DynWinRTType.register_interface(f"E2E.{name}Consumer", iid) + method = interface.add_method(method_name, signature).method(6) + canonical = owner.to_value() + try: + value = canonical.cast(iid) + finally: + canonical.release() + try: + yield lambda: method.invoke(value, []) + finally: + value.release() + + +def native_stringable(dw, owner): + return native_consumer( + dw, owner, "IStringable", "96369f54-8eb6-48f0-abce-c1b211e627c3", "ToString", + dw.DynWinRTMethodSig().add_out(dw.DynWinRTType.hstring()), + ) + + +class TaskInstanceHandlers: + # All nine exact IBackgroundTaskInstance methods, in slots 6 through 14. + def __init__(self): + self.progress = 17 + self.gets = self.sets = self.get_ids = 0 + + def get_instance_id(self): + self.get_ids += 1 + return INSTANCE_ID + + get_task = not_implemented + + def get_progress(self): + self.gets += 1 + return self.progress + + def set_progress(self, value): + self.sets += 1 + self.progress = value + + get_trigger_details = not_implemented + add_canceled = not_implemented + remove_canceled = not_implemented + get_suspended_count = not_implemented + get_deferral = not_implemented + + +class ReaderHandlers: + """Complete IDataReader vtable, with only its FillArray method implemented.""" + + get_unconsumed_buffer_length = not_implemented + get_unicode_encoding = not_implemented + set_unicode_encoding = not_implemented + get_byte_order = not_implemented + set_byte_order = not_implemented + get_input_stream_options = not_implemented + set_input_stream_options = not_implemented + read_byte = not_implemented + read_buffer = not_implemented + read_boolean = not_implemented + read_guid = not_implemented + read_int16 = not_implemented + read_int32 = not_implemented + read_int64 = not_implemented + read_uint16 = not_implemented + read_uint32 = not_implemented + read_uint64 = not_implemented + read_single = not_implemented + read_double = not_implemented + read_string = not_implemented + read_date_time = not_implemented + read_time_span = not_implemented + load_async = not_implemented + detach_buffer = not_implemented + detach_stream = not_implemented + + def __init__(self, fill): + self.fill = fill + + def read_bytes(self, capacity): + return self.fill(capacity) + + +class CloseHandlers: + def close(self): + pass + + +def background_task(g, dw, own): + state = TaskInstanceHandlers() + instance_owner = own(g.IBackgroundTaskInstance.implement(state)) + instance = g.IBackgroundTaskInstance.from_implementation(instance_owner) + + class Task: + runs = 0 + + def run(self, task_instance): + assert isinstance(task_instance, g.IBackgroundTaskInstance) + assert task_instance.instance_id == INSTANCE_ID + task_instance.progress = task_instance.progress + 5 + self.runs += 1 + + handlers = Task() + owner = own(g.IBackgroundTask.implement(handlers)) + task = g.IBackgroundTask.from_implementation(owner) + task.run(instance) + assert (state.progress, state.gets, state.sets, state.get_ids) == (22, 1, 1, 1) + assert handlers.runs == 1 + instance_owner.release() + owner.release() + task.run(instance) + assert (state.progress, state.gets, state.sets, state.get_ids) == (27, 2, 2, 2) + assert handlers.runs == 2 + token = dw.DynWinRTStruct.create(dw.DynWinRTType.struct_type( + "Windows.Foundation.EventRegistrationToken", [dw.DynWinRTType.i64_type()] + )) + token.set_i64(0, 1) + for action in ( + lambda: instance.task, + lambda: instance.trigger_details, + lambda: instance.suspended_count, + lambda: instance.get_deferral(), + lambda: instance.on_canceled(lambda *_: None), + lambda: instance.off_canceled(token.to_value()), + ): + error = expect_hresult(action, PYTHON_CALLBACK_ERROR) + assert "NotImplementedError" in str(error) and "Unused standalone" in str(error) + take_error(instance_owner, "unused standalone") + + +def multi_interface_lifetime(g, dw, own): + class Handlers: + closes = 0 + + def to_string(self): + return "retained \0 WinRT \u96ea" + + def close(self): + self.closes += 1 + + handlers = Handlers() + owner = own(g.IStringable.implement(handlers, g.IClosable.implementation(handlers))) + first = g.IStringable.from_implementation(owner) + second = g.IStringable.from_implementation(owner) + closable = g.IClosable.from_implementation(owner) + assert first is not second, "Typed views must not share one mutable native holder" + retained = owner.to_value() + try: + dw.release_projected(first) + assert second.to_string() == "retained \0 WinRT \u96ea" + owner.release() + owner.release() + assert not owner.is_closed, "release() must not disconnect native views" + assert second.to_string() == "retained \0 WinRT \u96ea" + closable.close() + assert handlers.closes == 1 + native_retained_view = g.IStringable.from_value(retained) + retained.release() + assert native_retained_view.to_string() == "retained \0 WinRT \u96ea" + assert owner.take_error() is None + finally: + retained.release() + + scoped_owner = own(g.IStringable.implement(handlers)) + with dw.projected_lifetime_scope(): + native = scoped_owner.to_value() + try: + cached = g.IStringable.from_value(native) + first = g.IStringable.from_implementation(scoped_owner) + second = g.IStringable.from_implementation(scoped_owner) + assert first is not second and first is not cached + assert g.IStringable.from_value(native) is cached, "Existing from_value cache behavior changed" + finally: + native.release() + dw.release_projected(first) + assert second.to_string() == "retained \0 WinRT \u96ea" + expect_error(second.to_string, "object|released|null") + expect_error(cached.to_string, "object|released|null") + assert not scoped_owner.is_closed + recovered = g.IStringable.from_implementation(scoped_owner) + assert recovered.to_string() == "retained \0 WinRT \u96ea" + dw.release_projected(recovered) + scoped_owner.release() + assert scoped_owner.is_closed + + +def gc_referent_ids(owner): + # IDs only: keeping the objects returned by get_referents() would itself + # retain the callback/handler graph and invalidate a collection assertion. + return frozenset(id(value) for value in gc.get_referents(owner)) + + +def generated_owner_cycle(g): + class Handlers: + def to_string(self): + return "public helper GC" + + handlers = Handlers() + owner = g.IStringable.implement(handlers) + handlers.owner = owner + assert gc.is_tracked(owner) + return owner, weakref.ref(owner), weakref.ref(handlers) + + +def collect_owner_cycle(dw, owner_ref, handlers_ref): + for _ in range(3): + gc.collect() + # Flush any PyO3 decrefs deferred by native destruction. This does not + # create a native instance or retain an implementation reference. + dw.DynWinRTType.i32_type() + if owner_ref() is None and handlers_ref() is None: + return + raise AssertionError( + "Owner-only cycle was not collected; a public helper may have leaked " + "its canonical temporary or a QueryInterface reference" + ) + + +def public_view_success_gc(g, dw, own): + # Do not use own(): its bound cleanup method would be a strong Python root. + owner, owner_ref, handlers_ref = generated_owner_cycle(g) + first = second = None + try: + baseline = gc_referent_ids(owner) + assert baseline, "Owner-only callbacks must participate in Python GC" + first = g.IStringable.from_implementation(owner) + second = g.IStringable.from_implementation(owner) + assert first is not second + assert gc_referent_ids(owner) != baseline, ( + "A returned view must own an external native QI reference" + ) + dw.release_projected(first) + first = None + assert not owner.is_closed + assert second.to_string() == "public helper GC" + with native_stringable(dw, owner) as invoke: + assert invoke().to_string() == "public helper GC" + + # Only the view and the native callback -> handler -> owner cycle now + # keep the object alive. GC must not disconnect a retained native view. + del owner + gc.collect() + assert owner_ref() is not None and handlers_ref() is not None + assert second.to_string() == "public helper GC" + dw.release_projected(second) + second = None + + remaining = owner_ref() + if remaining is not None: + assert gc_referent_ids(remaining) == baseline, ( + "Successful from_implementation left an extra native root" + ) + del remaining + collect_owner_cycle(dw, owner_ref, handlers_ref) + finally: + for view in (first, second): + if view is not None: + dw.release_projected(view) + remaining = owner_ref() + if remaining is not None: + remaining.dispose() + + +def public_view_failed_cast_gc(g, dw, own): + owner, owner_ref, handlers_ref = generated_owner_cycle(g) + try: + baseline = gc_referent_ids(owner) + assert baseline, "Owner-only callbacks must participate in Python GC" + for _ in range(8): + caught = expect_hresult( + lambda: g.IClosable.from_implementation(owner), 0x80004002 + ) + # Keep the exception AND its traceback alive during this check. + # Without finally: value.release(), the failed helper's traceback + # can retain value=owner.to_value(), hiding the callback from GC. + assert gc_referent_ids(owner) == baseline, ( + "Failed from_implementation did not release its canonical " + "temporary before propagating E_NOINTERFACE" + ) + del caught + assert not owner.is_closed + with native_stringable(dw, owner) as invoke: + assert invoke().to_string() == "public helper GC" + assert gc_referent_ids(owner) == baseline + del owner + collect_owner_cycle(dw, owner_ref, handlers_ref) + finally: + remaining = owner_ref() + if remaining is not None: + remaining.dispose() + + +def dispose_disconnects(g, dw, own): + class Handlers: + calls = 0 + + def to_string(self): + self.calls += 1 + return "before disposal" + + def close(self): + self.calls += 1 + + handlers = Handlers() + owner = own(g.IStringable.implement(handlers, g.IClosable.implementation(handlers))) + with native_stringable(dw, owner) as text, native_consumer( + dw, owner, "IClosable", "30d5a829-7fa4-4026-83bb-d75bae4ea99e", "Close", dw.DynWinRTMethodSig() + ) as close: + assert text().to_string() == "before disposal" + close() + owner.release() + assert text().to_string() == "before disposal" + assert not owner.is_closed + owner.dispose() + owner.dispose() + assert owner.is_closed + expect_hresult(text, RO_E_CLOSED) + expect_hresult(close, RO_E_CLOSED) + assert handlers.calls == 3 + + +def reentrant_dispose(g, dw, own): + class Handlers: + calls = 0 + + def to_string(self): + self.calls += 1 + owner.dispose() + return "active callback finished" + + handlers = Handlers() + owner = own(g.IStringable.implement(handlers)) + with native_stringable(dw, owner) as invoke: + assert invoke().to_string() == "active callback finished" + assert owner.is_closed + expect_hresult(invoke, RO_E_CLOSED) + assert handlers.calls == 1 + + +def callback_error(g, dw, own): + class Handlers: + fail = True + + def to_string(self): + if self.fail: + raise ValueError("implementation-e2e-python-sentinel") + return "recovered" + + handlers = Handlers() + owner = own(g.IStringable.implement(handlers)) + with native_stringable(dw, owner) as invoke: + expect_hresult(invoke, PYTHON_CALLBACK_ERROR) + take_error(owner, "implementation-e2e-python-sentinel") + handlers.fail = False + assert invoke().to_string() == "recovered" + assert not owner.is_closed + assert owner.take_error() is None + + +def async_handler_rejected(g, dw, own): + class Handlers: + entered = False + + async def to_string(self): + self.entered = True + return "bad" + + handlers = Handlers() + expect_error(lambda: g.IStringable.implementation(handlers), "async|synchronous") + assert not handlers.entered + + class AsyncClose: + entered = False + + async def close(self): + self.entered = True + + close = AsyncClose() + expect_error(lambda: g.IClosable.implementation(close), "async|synchronous") + assert not close.entered + + +def async_result_rejected(g, dw, own): + async def result(): + return "not a WinRT result" + + class Handlers: + pending = None + + def to_string(self): + self.pending = result() + return self.pending + + handlers = Handlers() + owner = own(g.IStringable.implement(handlers)) + try: + with native_stringable(dw, owner) as invoke: + expect_hresult(invoke, PYTHON_CALLBACK_ERROR) + take_error(owner, "coroutine|awaitable|async|synchronous") + assert inspect.getcoroutinestate(handlers.pending) == inspect.CORO_CLOSED, ( + "Rejected coroutine results must be closed, not left to warn at GC" + ) + finally: + if handlers.pending is not None: + handlers.pending.close() + + +def required_interfaces(g, dw, own): + class Reference: + def get_capacity(self): + return 73 + + add_closed = not_implemented + remove_closed = not_implemented + + expect_error( + lambda: g.IMemoryBufferReference.implement(Reference()), + "required|IClosable|30d5a829", + ) + owner = own(g.IMemoryBufferReference.implement( + Reference(), g.IClosable.implementation(CloseHandlers()) + )) + assert g.IMemoryBufferReference.from_implementation(owner).capacity == 73 + g.IClosable.from_implementation(owner).close() + + class Text: + def to_string(self): + return "not IClosable" + + expect_error( + lambda: g.IStringable.implement(Text(), g.IStringable.implementation(Text())), + "duplicate|already|IID", + ) + only_stringable = own(g.IStringable.implement(Text())) + expect_hresult(lambda: g.IClosable.from_implementation(only_stringable), 0x80004002) + + +def memory_buffer_event(g, dw, own): + callbacks = {} + delivered = [] + + class Reference: + added = removed = 0 + + def get_capacity(self): + return 4096 + + def add_closed(self, handler): + assert callable(handler), "Received delegates are typed callable native views" + self.added += 1 + callbacks[self.added] = handler + return g.EventRegistrationToken(value=self.added) + + def remove_closed(self, token): + assert isinstance(token, g.EventRegistrationToken) + del callbacks[token.value] + self.removed += 1 + + def close(self): + for callback in list(callbacks.values()): + # Generated delegate wrapper -> native Invoke slot -> Python + # callback. The original event callback is never called here. + callback(event_sender, None) + + handlers = Reference() + owner = own(g.IMemoryBufferReference.implement( + handlers, g.IClosable.implementation(handlers) + )) + event_sender = g.IMemoryBufferReference.from_implementation(owner) + close = g.IClosable.from_implementation(owner) + + def on_closed(sender, args): + assert isinstance(sender, g.IMemoryBufferReference) + assert sender.capacity == 4096 # Reentrant outbound native getter. + assert args is None + delivered.append(sender.capacity) + + unsubscribe = event_sender.subscribe_closed(on_closed) + assert handlers.added == 1 + owner.release() + close.close() + assert delivered == [4096] + unsubscribe() + assert handlers.removed == 1 + close.close() + assert delivered == [4096] + owner.dispose() + expect_hresult(close.close, RO_E_CLOSED) + + +def array_contracts(g, dw, own): + # Keep ExclusiveTo factory interfaces private. These complete public SDK + # interfaces cover native pass/receive arrays and typed value ownership. + state = {"bytes": b"", "text": "", "guid": INSTANCE_ID, "signed": 0, "unsigned": 0, "real": 0.0} + + class Writer: + get_unstored_buffer_length = not_implemented + get_unicode_encoding = not_implemented + set_unicode_encoding = not_implemented + get_byte_order = not_implemented + set_byte_order = not_implemented + write_byte = not_implemented + write_buffer_range = not_implemented + write_boolean = not_implemented + write_int16 = not_implemented + write_int32 = not_implemented + write_uint16 = not_implemented + write_uint32 = not_implemented + write_single = not_implemented + write_date_time = not_implemented + write_time_span = not_implemented + store_async = not_implemented + flush_async = not_implemented + detach_stream = not_implemented + + def write_bytes(self, value): + assert isinstance(value, list), "PassArray input is a projected list[int]" + state["bytes"] = bytes(value) + + def write_buffer(self, value): + assert isinstance(value, g.IBuffer) + state["bytes"] = value.to_bytes() + + def write_string(self, value): + state["text"] = value + return len(value.encode("utf-8")) + + def measure_string(self, value): + return len(value.encode("utf-8")) + + def write_guid(self, value): + state["guid"] = value + + def write_int64(self, value): + state["signed"] = value + + def write_uint64(self, value): + state["unsigned"] = value + + def write_double(self, value): + state["real"] = value + + def detach_buffer(self): + return g.IBuffer.from_bytes(state["bytes"]) + + class Text: + def to_string(self): + return "array object" + + object_owner = own(g.IStringable.implement(Text())) + raw_object = object_owner.to_value() + + class Properties: + invalid_element = False + get_type = not_implemented + get_is_numeric_scalar = not_implemented + get_uint8 = not_implemented + get_int16 = not_implemented + get_uint16 = not_implemented + get_int32 = not_implemented + get_uint32 = not_implemented + get_single = not_implemented + get_char16 = not_implemented + get_boolean = not_implemented + get_date_time = not_implemented + get_time_span = not_implemented + get_point = not_implemented + get_size = not_implemented + get_rect = not_implemented + get_int16_array = not_implemented + get_uint16_array = not_implemented + get_int32_array = not_implemented + get_uint32_array = not_implemented + get_single_array = not_implemented + get_char16_array = not_implemented + get_boolean_array = not_implemented + get_date_time_array = not_implemented + get_time_span_array = not_implemented + get_size_array = not_implemented + get_rect_array = not_implemented + + def get_uint8_array(self): + return state["bytes"] + + def get_string(self): + return state["text"] + + def get_string_array(self): + return [state["text"], 42] if self.invalid_element else [state["text"], "", "snow \u96ea"] + + def get_guid(self): + return state["guid"] + + def get_guid_array(self): + return [state["guid"], INSTANCE_ID] + + def get_int64(self): + return state["signed"] + + def get_int64_array(self): + return [state["signed"], -(1 << 63)] + + def get_uint64(self): + return state["unsigned"] + + def get_uint64_array(self): + return [state["unsigned"], (1 << 64) - 1] + + def get_double(self): + return state["real"] + + def get_double_array(self): + return [state["real"], -2.5] + + def get_point_array(self): + return [g.Point(x=1.25, y=-3.5), g.Point(x=0.0, y=2.0)] + + def get_inspectable_array(self): + return [raw_object, None] + + writer_owner = own(g.IDataWriter.implement(Writer(), g.IClosable.implementation(CloseHandlers()))) + writer = g.IDataWriter.from_implementation(writer_owner) + properties = Properties() + owner = own(g.IPropertyValue.implement(properties)) + view = g.IPropertyValue.from_implementation(owner) + writer_owner.release() + owner.release() + for data in (b"", bytes([0, 1, 127, 128, 255])): + writer.write_bytes(data) + assert view.get_uint8_array() == data + native = writer.detach_buffer() + assert isinstance(native, g.IBuffer) + assert native.length == len(data) + assert native.to_bytes() == data + writer.write_buffer(native) + assert view.get_uint8_array() == data + dw.release_projected(native) + text = "generated \0 WinRT \u96ea \U0001f680" + assert writer.write_string(text) == writer.measure_string(text) + assert view.get_string() == text + assert view.get_string_array() == [text, "", "snow \u96ea"] + writer.write_guid(INSTANCE_ID) + assert view.get_guid() == INSTANCE_ID + assert view.get_guid_array() == [INSTANCE_ID, INSTANCE_ID] + writer.write_int64((1 << 63) - 1) + writer.write_uint64((1 << 64) - 1) + writer.write_double(1.25) + assert view.get_int64() == (1 << 63) - 1 + assert view.get_uint64() == (1 << 64) - 1 + assert view.get_double() == 1.25 + assert view.get_int64_array() == [(1 << 63) - 1, -(1 << 63)] + assert view.get_uint64_array() == [(1 << 64) - 1, (1 << 64) - 1] + assert view.get_double_array() == [1.25, -2.5] + points = view.get_point_array() + assert [(point.x, point.y) for point in points] == [(1.25, -3.5), (0.0, 2.0)] + objects = view.get_inspectable_array() + assert len(objects) == 2 and objects[1] is None + text_view = g.IStringable.from_value(objects[0]) + assert text_view.to_string() == "array object" + dw.release_projected(text_view) + objects[0].release() + properties.invalid_element = True + expect_hresult(view.get_string_array, PYTHON_CALLBACK_ERROR) + take_error(owner, "get_string_array|invalid implementation result") + properties.invalid_element = False + assert view.get_string_array() == [text, "", "snow \u96ea"] + assert owner.take_error() is None + assert writer_owner.take_error() is None + raw_object.release() + dw.release_projected(view) + dw.release_projected(writer) + + +def fill_array(g, dw, own): + capacities = [] + + def fill(capacity): + assert isinstance(capacity, int), "FillArray input is U32 capacity, not an array" + capacities.append(capacity) + return bytes((index * 17 + 3) & 255 for index in range(capacity)) + + owner = own(g.IDataReader.implement( + ReaderHandlers(fill), g.IClosable.implementation(CloseHandlers()) + )) + view = g.IDataReader.from_implementation(owner) + for capacity in (0, 1, 7, 257): + actual = view.read_bytes(bytearray(capacity)) + assert actual == bytes((index * 17 + 3) & 255 for index in range(capacity)) + assert capacities == [0, 1, 7, 257] + error = expect_hresult(view.read_byte, PYTHON_CALLBACK_ERROR) + assert "NotImplementedError" in str(error) and "Unused standalone" in str(error) + take_error(owner, "unused standalone") + + +def fill_array_wrong_length(g, dw, own): + wrong = True + + def fill(capacity): + return bytes(capacity - int(wrong)) + + owner = own(g.IDataReader.implement( + ReaderHandlers(fill), g.IClosable.implementation(CloseHandlers()) + )) + view = g.IDataReader.from_implementation(owner) + expect_error(lambda: view.read_bytes(bytearray(4)), "length|capacity|invalid|80070057") + take_error(owner, "capacity|length") + wrong = False + assert len(view.read_bytes(bytearray(4))) == 4 + assert owner.take_error() is None + + +def named_outputs(g, dw, own): + class VectorView: + named = True + + def get_at(self, index): + assert index == 0 + return None + + def get_size(self): + return 1 + + def index_of(self, value): + # Reverse dictionary insertion order: lowering must use metadata + # names, with explicit out index first and the return appended. + if self.named: + return {"result": value is None, "index": 0 if value is None else 0xFFFFFFFF} + return (0, True) + + def first(self): + class Iterator: + current = True + + def get_current(self): + return None + + def get_has_current(self): + return self.current + + def move_next(self): + self.current = False + return False + + iterator = own(g.IBindableIterator.implement(Iterator())) + return g.IBindableIterator.from_implementation(iterator) + + handlers = VectorView() + owner = own(g.IBindableVectorView.implement( + handlers, g.IBindableIterable.implementation(handlers) + )) + view = g.IBindableVectorView.from_implementation(owner) + assert view.size == 1 + assert view.get_at(0) is None + # Outbound API retains its existing tuple shape. Only the new inbound + # implementation contract requires named outputs. + assert view.index_of(dw.DynWinRTValue.null_value()) == (0, True) + + class Text: + def to_string(self): + return "not in the vector" + + other = own(g.IStringable.implement(Text())) + raw = other.to_value() + try: + assert view.index_of(raw) == (0xFFFFFFFF, False) + finally: + raw.release() + iterator = g.IBindableIterable.from_implementation(owner).first() + assert iterator.has_current + assert iterator.current is None + assert not iterator.move_next() + assert not iterator.has_current + assert owner.take_error() is None + handlers.named = False + expect_hresult(lambda: view.index_of(dw.DynWinRTValue.null_value()), PYTHON_CALLBACK_ERROR) + take_error(owner, "dict|field") + handlers.named = True + assert view.index_of(dw.DynWinRTValue.null_value()) == (0, True) + + +def nullable_reference_results(g, dw, own): + class Handlers: + def parse_int(self, text): + assert isinstance(text, str) + if re.fullmatch(r"-?\d+", text) is None: + return None + value = int(text) + return value if -(1 << 63) <= value < (1 << 63) else None + + def parse_u_int(self, text): + assert isinstance(text, str) + if re.fullmatch(r"\d+", text) is None: + return None + value = int(text) + return value if value < (1 << 64) else None + + def parse_double(self, text): + assert isinstance(text, str) + try: + return float(text) + except ValueError: + return None + + owner = own(g.INumberParser.implement(Handlers())) + view = g.INumberParser.from_implementation(owner) + owner.release() + try: + for value in (-(1 << 63), 0, (1 << 63) - 1): + assert view.parse_int(str(value)) == value + for value in (0, (1 << 64) - 1): + assert view.parse_u_int(str(value)) == value + assert view.parse_int("9223372036854775808") is None + assert view.parse_u_int("-1") is None + assert view.parse_u_int("18446744073709551616") is None + assert view.parse_int("invalid") is None + assert view.parse_double("2.5") == 2.5 + assert view.parse_double("-0.125") == -0.125 + assert view.parse_double("invalid") is None + assert owner.take_error() is None + finally: + dw.release_projected(view) + + +CASES = { + case.__name__: case for case in ( + background_task, multi_interface_lifetime, dispose_disconnects, + reentrant_dispose, callback_error, async_handler_rejected, + async_result_rejected, required_interfaces, memory_buffer_event, + array_contracts, fill_array, fill_array_wrong_length, named_outputs, + nullable_reference_results, + public_view_success_gc, public_view_failed_cast_gc, + ) +} + +# Python alone exposes the native owner-only cycle to its GC visitor. These +# cases must not have a projected lifetime scope or a retained cleanup callback. +PUBLIC_VIEW_GC_CASES = frozenset({ + "public_view_success_gc", "public_view_failed_cast_gc", +}) + + +def decode_child_result(case_id, stdout, stderr, exit_code): + lines = [line for line in stdout.splitlines() if line.startswith(RESULT_PREFIX)] + result = { + "id": case_id, "pass": False, + "error": f"Native child did not report a result (exit={exit_code})\n{stdout}", + } + if lines: + try: + payload = json.loads(lines[-1][len(RESULT_PREFIX):]) + if payload["id"] != case_id or not isinstance(payload["pass"], bool): + raise ValueError("Invalid case result envelope") + result = payload + except (ValueError, KeyError, TypeError) as error: + result["error"] = f"Invalid native child result: {error}" + if exit_code != 0 and result["pass"]: + result.update({"pass": False, "error": f"Native child failed during cleanup (exit={exit_code})"}) + return {**result, "exit_code": exit_code, "stderr": stderr} + + +def import_search_path(path: Path) -> str: + absolute = str(path.resolve()) + if sys.platform != "win32" or absolute.startswith("\\\\?\\"): + return absolute + if absolute.startswith("\\\\"): + return "\\\\?\\UNC\\" + absolute[2:] + return "\\\\?\\" + absolute + + +def run_one(case_id, generated): + started = time.monotonic() + error = None + try: + import dynwinrt as dw + + assert hasattr(dw, "DynWinRTImplementation"), ( + "Build/install the Python runtime with WinRT implementation support" + ) + # Generated generic facade names can otherwise exceed Windows + # MAX_PATH in this worktree even though codegen emitted valid files. + sys.path.insert(0, import_search_path(generated.parent)) + g = importlib.import_module(generated.name) + with dw.RoApartment(1), ExitStack() as cleanup: + if case_id not in PUBLIC_VIEW_GC_CASES: + cleanup.enter_context(dw.projected_lifetime_scope()) + + def own(owner): + assert case_id not in PUBLIC_VIEW_GC_CASES, ( + "GC cases must not register a strong owner cleanup root" + ) + cleanup.callback(owner.dispose) + return owner + + CASES[case_id](g, dw, own) + gc.collect() + except Exception: + error = traceback.format_exc() + return { + "id": case_id, "pass": error is None, "error": error, + "duration_ms": round((time.monotonic() - started) * 1000), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--generated", type=Path, required=True) + parser.add_argument("--output", type=Path) + parser.add_argument("--case", choices=CASES) + args = parser.parse_args() + generated = args.generated.resolve() + if args.case: + result = run_one(args.case, generated) + print(RESULT_PREFIX + json.dumps(result), flush=True) + return 0 if result["pass"] else 1 + + # platform.machine() alone describes the OS under Windows emulation. The + # executable build tag identifies the actual interpreter architecture. + architecture = f"{platform.machine()} / {struct.calcsize('P') * 8}-bit / {platform.python_compiler()}" + print(f"Python {platform.python_version()}, {architecture}, {sys.executable}") + results = [] + printed_errors = set() + for case_id in CASES: + command = [ + sys.executable, str(Path(__file__).resolve()), + "--case", case_id, "--generated", str(generated), + ] + try: + child = subprocess.run( + command, text=True, capture_output=True, encoding="utf-8", + errors="replace", timeout=90, check=False, + ) + result = decode_child_result(case_id, child.stdout, child.stderr, child.returncode) + except subprocess.TimeoutExpired as error: + result = { + "id": case_id, "pass": False, "error": f"Native child exceeded 90s: {error}", + "exit_code": None, "stderr": str(error.stderr or ""), + } + results.append(result) + print(f" {'PASS' if result['pass'] else 'FAIL'} {case_id}", flush=True) + if not result["pass"]: + diagnostic = f"{result['error']}\n{result['stderr']}" + lines = str(result["error"]).strip().splitlines() + key = (lines[-1] if lines else "", result["stderr"]) + if key not in printed_errors: + print(diagnostic, flush=True) + printed_errors.add(key) + report = { + "language": "py-implementations", "architecture": architecture, + "runtime": sys.version, "executable": sys.executable, + "binding": getattr(importlib.util.find_spec("dynwinrt"), "origin", None), + "generated": str(generated), "passed": sum(result["pass"] for result in results), + "total": len(results), "results": results, + } + print(f"Python implementation E2E: {report['passed']}/{report['total']} passed ({architecture})") + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + return 0 if report["passed"] == report["total"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/e2e/runners/test_implementation_runners.py b/tests/e2e/runners/test_implementation_runners.py new file mode 100644 index 00000000..94ce7066 --- /dev/null +++ b/tests/e2e/runners/test_implementation_runners.py @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import json +import gc +from pathlib import Path +import sys +import unittest +import weakref + +from implementation_py import ( + CASES, PUBLIC_VIEW_GC_CASES, RESULT_PREFIX, TaskInstanceHandlers, + decode_child_result, gc_referent_ids, import_search_path, +) + + +class ImplementationRunnerTests(unittest.TestCase): + def test_success_requires_successful_process_cleanup(self): + stdout = RESULT_PREFIX + json.dumps({"id": "case", "pass": True, "error": None}) + self.assertTrue(decode_child_result("case", stdout, "", 0)["pass"]) + result = decode_child_result("case", stdout, "native failure", 0xC0000005) + self.assertFalse(result["pass"]) + self.assertIn("cleanup", result["error"]) + self.assertEqual(result["stderr"], "native failure") + + def test_missing_or_malformed_marker_is_not_a_skip_or_success(self): + for stdout, exit_code in ( + ("", 0xC0000005), + ("no marker", 0), + (RESULT_PREFIX + "invalid", 0), + (RESULT_PREFIX + '{"id":"wrong","pass":true}', 0), + (RESULT_PREFIX + '{"id":"case","pass":"true"}', 0), + ): + with self.subTest(stdout=stdout, exit_code=exit_code): + self.assertFalse(decode_child_result("case", stdout, "", exit_code)["pass"]) + + def test_complete_matrix_and_nine_method_background_fixture(self): + self.assertEqual(len(CASES), 16) + self.assertEqual(next(iter(CASES)), "background_task") + for case in ("memory_buffer_event", "array_contracts", "fill_array", "named_outputs"): + self.assertIn(case, CASES) + self.assertIn("nullable_reference_results", CASES) + methods = { + name for name, value in vars(TaskInstanceHandlers).items() + if callable(value) and not name.startswith("_") + } + self.assertEqual(methods, { + "get_instance_id", "get_task", "get_progress", "set_progress", + "get_trigger_details", "add_canceled", "remove_canceled", + "get_suspended_count", "get_deferral", + }) + + def test_public_helper_gc_cases_cannot_be_hidden_by_cleanup_roots(self): + self.assertEqual(PUBLIC_VIEW_GC_CASES, { + "public_view_success_gc", "public_view_failed_cast_gc", + }) + self.assertTrue(PUBLIC_VIEW_GC_CASES <= CASES.keys()) + + def test_gc_referent_snapshot_does_not_retain_the_observed_graph(self): + class Graph: + pass + + graph = Graph() + graph.cycle = graph + reference = weakref.ref(graph) + snapshot = gc_referent_ids(graph) + self.assertTrue(snapshot) + del graph + gc.collect() + self.assertIsNone(reference()) + self.assertTrue(all(isinstance(value, int) for value in snapshot)) + + def test_generated_import_root_supports_extended_windows_paths(self): + root = Path(__file__).resolve().parent + search = import_search_path(root) + self.assertTrue(Path(search).is_dir()) + self.assertEqual(import_search_path(Path(search)), search) + if sys.platform == "win32": + self.assertTrue(search.startswith("\\\\?\\")) + else: + self.assertEqual(search, str(root)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/e2e/typecheck/python_implementation_api.py b/tests/e2e/typecheck/python_implementation_api.py new file mode 100644 index 00000000..4ac8c889 --- /dev/null +++ b/tests/e2e/typecheck/python_implementation_api.py @@ -0,0 +1,284 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Strict mypy consumer fixture; never executed as an E2E scenario.""" + +from collections.abc import Callable +from typing import Never, TypedDict +from uuid import UUID + +from dynwinrt import DynWinRTImplementation, DynWinRTValue, release_projected +from python_bindings.windows.application_model.background import ( + IBackgroundTask, IBackgroundTaskInstance, +) +from python_bindings.windows.foundation import ( + EventRegistrationToken, IClosable, IMemoryBufferReference, IPropertyValue, IStringable, Point, +) +from python_bindings.windows.globalization.number_formatting import INumberParser +from python_bindings.windows.storage.streams import IBuffer, IDataReader, IDataWriter +from python_bindings.windows.ui.xaml.interop import ( + IBindableIterable, IBindableIterator, IBindableVectorView, +) + + +def unused(*_args: object, **_kwargs: object) -> Never: + raise NotImplementedError("Typecheck fixture only") + + +class InstanceHandlers: + def get_instance_id(self) -> UUID: + return UUID("243aab7d-9411-49af-b66d-0123456789ab") + + get_task = unused + + def get_progress(self) -> int: + return 0 + + def set_progress(self, value: int) -> None: + pass + + get_trigger_details = unused + add_canceled = unused + remove_canceled = unused + get_suspended_count = unused + get_deferral = unused + + +class TaskHandlers: + def run(self, task_instance: IBackgroundTaskInstance | None) -> None: + if task_instance is not None: + identifier: UUID = task_instance.instance_id + task_instance.progress = len(str(identifier)) + + def to_string(self) -> str: + return "typed owner" + + def close(self) -> None: + pass + + +def check_owner() -> None: + handlers = TaskHandlers() + instance: DynWinRTImplementation = IBackgroundTaskInstance.implement(InstanceHandlers()) + owner: DynWinRTImplementation = IBackgroundTask.implement( + handlers, IStringable.implementation(handlers), IClosable.implementation(handlers) + ) + task: IBackgroundTask = IBackgroundTask.from_implementation(owner) + task.run(IBackgroundTaskInstance.from_implementation(instance)) + text: IStringable = IStringable.from_implementation(owner) + close: IClosable = IClosable.from_implementation(owner) + value: str = text.to_string() + close.close() + release_projected(text) + release_projected(close) + raw: DynWinRTValue = owner.to_value() + closed: bool = owner.is_closed + error: str | None = owner.take_error() + owner.release() + owner.dispose() + _: tuple[str, DynWinRTValue, bool, str | None] = (value, raw, closed, error) + + # Expected-error fixtures also fail if declarations become permissive Any. + IBackgroundTaskInstance.implementation(handlers) # type: ignore[arg-type] + IStringable.from_implementation(raw) # type: ignore[arg-type] + + +class WrongText: + def to_string(self) -> int: + return 17 + + +class AsyncText: + async def to_string(self) -> str: + return "late" + + +def check_invalid_handlers() -> None: + IStringable.implementation(WrongText()) # type: ignore[arg-type] + IStringable.implementation(AsyncText()) # type: ignore[arg-type] + + +class NumberParserHandlers: + def parse_int(self, text: str) -> int | None: + return -(1 << 63) + + def parse_u_int(self, text: str) -> int | None: + return (1 << 64) - 1 + + def parse_double(self, text: str) -> float | None: + return None + + +def check_nullable_reference_outputs() -> None: + owner = INumberParser.implement(NumberParserHandlers()) + parser = INumberParser.from_implementation(owner) + signed: int | None = parser.parse_int("signed") + unsigned: int | None = parser.parse_u_int("unsigned") + real: float | None = parser.parse_double("invalid") + release_projected(parser) + _: tuple[int | None, int | None, float | None] = (signed, unsigned, real) + + +ClosedDelegate = Callable[[IMemoryBufferReference | None, DynWinRTValue | None], None] + + +class ReferenceHandlers: + def __init__(self, sender: IMemoryBufferReference) -> None: + self.sender = sender + + def get_capacity(self) -> int: + return 4096 + + def add_closed(self, handler: ClosedDelegate | None) -> EventRegistrationToken: + if handler is not None: + handler(self.sender, None) + return EventRegistrationToken(value=1) + + def remove_closed(self, token: EventRegistrationToken) -> None: + value: int = token.value + assert value == 1 + + +def check_event(sender: IMemoryBufferReference) -> None: + owner = IMemoryBufferReference.implement( + ReferenceHandlers(sender), IClosable.implementation(TaskHandlers()) + ) + view: IMemoryBufferReference = IMemoryBufferReference.from_implementation(owner) + + def callback(source: IMemoryBufferReference | None, args: DynWinRTValue | None) -> None: + if source is not None: + capacity: int = source.capacity + assert capacity >= 0 + + unsubscribe: Callable[[], None] = view.subscribe_closed(callback) + unsubscribe() + + +class ReaderHandlers: + get_unconsumed_buffer_length = unused + get_unicode_encoding = unused + set_unicode_encoding = unused + get_byte_order = unused + set_byte_order = unused + get_input_stream_options = unused + set_input_stream_options = unused + read_byte = unused + read_buffer = unused + read_boolean = unused + read_guid = unused + read_int16 = unused + read_int32 = unused + read_int64 = unused + read_uint16 = unused + read_uint32 = unused + read_uint64 = unused + read_single = unused + read_double = unused + read_string = unused + read_date_time = unused + read_time_span = unused + load_async = unused + detach_buffer = unused + detach_stream = unused + + def read_bytes(self, capacity: int) -> bytes: + return bytes(capacity) + + +class WriterHandlers: + get_unstored_buffer_length = unused + get_unicode_encoding = set_unicode_encoding = unused + get_byte_order = set_byte_order = unused + write_byte = write_buffer_range = unused + write_boolean = write_guid = unused + write_int16 = write_int32 = write_int64 = unused + write_uint16 = write_uint32 = write_uint64 = unused + write_single = write_double = unused + write_date_time = write_time_span = unused + write_string = measure_string = unused + store_async = flush_async = detach_buffer = detach_stream = unused + + def write_bytes(self, value: list[int]) -> None: + assert bytes(value) == b"\0\xff" + + def write_buffer(self, buffer: IBuffer | None) -> None: + if buffer is not None: + assert isinstance(buffer.to_bytes(), bytes) + + +class PropertyHandlers: + get_type = get_is_numeric_scalar = unused + get_uint8 = get_int16 = get_uint16 = get_int32 = get_uint32 = unused + get_int64 = get_uint64 = get_single = get_double = unused + get_char16 = get_boolean = get_string = get_guid = unused + get_date_time = get_time_span = get_point = get_size = get_rect = unused + get_int16_array = get_uint16_array = get_int32_array = get_uint32_array = unused + get_int64_array = get_uint64_array = get_single_array = get_double_array = unused + get_char16_array = get_boolean_array = get_guid_array = unused + get_date_time_array = get_time_span_array = get_size_array = get_rect_array = unused + + def get_uint8_array(self) -> bytes: + return b"\0\xff" + + def get_string_array(self) -> list[str]: + return ["owned string"] + + def get_inspectable_array(self) -> list[DynWinRTValue | None]: + return [None] + + def get_point_array(self) -> list[Point]: + return [Point(x=1.25, y=-3.5)] + + +def check_arrays() -> None: + reader_owner = IDataReader.implement( + ReaderHandlers(), IClosable.implementation(TaskHandlers()) + ) + reader: IDataReader = IDataReader.from_implementation(reader_owner) + filled: bytes = reader.read_bytes(bytearray(4)) + writer_owner = IDataWriter.implement(WriterHandlers(), IClosable.implementation(TaskHandlers())) + writer: IDataWriter = IDataWriter.from_implementation(writer_owner) + writer.write_bytes(filled) + writer.write_buffer(IBuffer.from_bytes(filled)) + property_owner = IPropertyValue.implement(PropertyHandlers()) + value: IPropertyValue = IPropertyValue.from_implementation(property_owner) + copied: bytes = value.get_uint8_array() + strings: list[str] = value.get_string_array() + points: list[Point] = value.get_point_array() + assert copied and strings and points + + +class IndexOfResult(TypedDict): + index: int + result: bool + + +class VectorHandlers: + def get_at(self, index: int) -> DynWinRTValue | None: + return None + + def get_size(self) -> int: + return 1 + + def index_of(self, value: DynWinRTValue | None) -> IndexOfResult: + return {"result": value is None, "index": 0} + + def first(self) -> IBindableIterator | None: + return None + + +class TupleResultHandlers: + get_at = unused + get_size = unused + + def index_of(self, value: DynWinRTValue | None) -> tuple[int, bool]: + return (0, True) + + +def check_named_outputs() -> None: + handlers = VectorHandlers() + owner = IBindableVectorView.implement(handlers, IBindableIterable.implementation(handlers)) + view: IBindableVectorView = IBindableVectorView.from_implementation(owner) + result: tuple[int, bool] = view.index_of(DynWinRTValue.null_value()) + assert result == (0, True) + IBindableVectorView.implementation(TupleResultHandlers()) # type: ignore[arg-type] diff --git a/tests/e2e/typecheck/ts_implementation_api.ts b/tests/e2e/typecheck/ts_implementation_api.ts new file mode 100644 index 00000000..e5b292ee --- /dev/null +++ b/tests/e2e/typecheck/ts_implementation_api.ts @@ -0,0 +1,193 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// Compile, do not execute. This imports the real generated declarations and +// built runtime declarations, not a permissive hand-written runtime stub. +import { + IBackgroundTask, IBackgroundTaskInstance, IClosable, IStringable, + IMemoryBufferReference, IPropertyValue, IBuffer, IDataReader, IDataWriter, + IBindableIterable, IBindableIterator, IBindableVectorView, INumberParser, + releaseProjected, +} from '../e2e_generated/implementations/js/index.js'; +import { + DynWinRtArray, DynWinRtImplementation, DynWinRtType, DynWinRtValue, +} from '../../../bindings/js/dist/winrt.js'; + +function unused(..._args: unknown[]): never { + throw new Error('Typecheck fixture only'); +} + +const exactHresult: DynWinRtValue = DynWinRtValue.hresult(-2147467263); +const hresults: DynWinRtArray = DynWinRtArray.fromHresultValues([0, -2147467263]); +const genericHresults: DynWinRtArray = DynWinRtArray.fromObjectValues( + [exactHresult], DynWinRtType.hresult(), +); +const hresultCodes: number[] = hresults.toI32Vec(); +void [genericHresults, hresultCodes]; +// @ts-expect-error Exact HRESULT factories accept signed-i32 numbers, not strings. +DynWinRtValue.hresult('0x80004001'); +// @ts-expect-error A batch HRESULT constructor does not accept heterogeneous arrays. +DynWinRtArray.fromHresultValues([0, '0x80004001']); + +const instance = IBackgroundTaskInstance.implement({ + getInstanceId: () => '243aab7d-9411-49af-b66d-0123456789ab', + getTask: unused, + getProgress: () => 0, + setProgress(value) { const progress: number = value; void progress; }, + getTriggerDetails: unused, + addCanceled: unused, + removeCanceled: unused, + getSuspendedCount: unused, + getDeferral: unused, +}); +const owner: DynWinRtImplementation = IBackgroundTask.implement({ + run(value) { + const native: IBackgroundTaskInstance | null = value; + if (native !== null) { + const id: string = native.instanceId; + native.progress = id.length; + } + }, +}, IStringable.implementation({ toString: () => 'typed owner' }), +IClosable.implementation({ close() {} })); +const taskView: IBackgroundTask = IBackgroundTask.fromImplementation(owner); +taskView.run(IBackgroundTaskInstance.fromImplementation(instance)); +const stringView: IStringable = IStringable.fromImplementation(owner); +const closeView: IClosable = IClosable.fromImplementation(owner); +const text: string = stringView.toString(); +closeView.close(); +releaseProjected(stringView); +releaseProjected(closeView); +const raw: DynWinRtValue = owner.toValue(); +const closed: boolean = owner.isClosed; +const error: string | null = owner.takeError(); +owner.release(); +owner.dispose(); +void [text, raw, closed, error]; + +// @ts-expect-error Handler names are ordinary JS camelCase, not Python names. +IStringable.implementation({ to_string: () => 'wrong name' }); +// @ts-expect-error A string-returning native method cannot return a number. +IStringable.implementation({ toString: () => 17 }); +// @ts-expect-error Async results are not WinRT logical outputs. +IStringable.implementation({ toString: async () => 'late' }); +// @ts-expect-error All nine methods are required, not just Run's used getters. +IBackgroundTaskInstance.implementation({ getProgress: () => 0 }); +// @ts-expect-error A typed view takes a root implementation owner. +IStringable.fromImplementation(raw); +// @ts-expect-error Consumers use the typed public view helper, not native constructors. +new IStringable(raw); + +const parserOwner = INumberParser.implement({ + parseInt: () => -(1n << 63n), + parseUInt: () => (1n << 64n) - 1n, + parseDouble: () => null, +}); +const parser = INumberParser.fromImplementation(parserOwner); +const parsedInt: bigint | null = parser.parseInt('signed'); +const parsedUInt: bigint | null = parser.parseUInt('unsigned'); +const parsedDouble: number | null = parser.parseDouble('invalid'); +releaseProjected(parser); +void [parsedInt, parsedUInt, parsedDouble]; + +let sender: IMemoryBufferReference; +const memory = IMemoryBufferReference.implement({ + getCapacity: () => 4096, + addClosed(handler) { + // Received delegates have a typed native invocation surface. + if (handler !== null) handler(sender, null); + return { value: 1n }; + }, + removeClosed(token) { + const nativeToken: bigint = token.value; + void nativeToken; + }, +}, IClosable.implementation({ close() {} })); +sender = IMemoryBufferReference.fromImplementation(memory); +const unsubscribe: () => void = sender.onClosed((source, args) => { + const sourceView: IMemoryBufferReference | null = source; + const eventArgs: unknown = args; + void [sourceView, eventArgs]; +}); +unsubscribe(); +const capacity: number = sender.capacity; +void capacity; + +declare const readerMethods: Parameters[0]; +const reader = IDataReader.implement({ + ...readerMethods, + readBytes(capacity) { + const count: number = capacity; + return new Uint8Array(count); + }, +}, IClosable.implementation({ close() {} })); +const filled: Uint8Array = IDataReader.fromImplementation(reader).readBytes(new Uint8Array(4)); +void filled; +IDataReader.implementation({ + ...readerMethods, + // @ts-expect-error FillArray receives logical U32 capacity, not caller storage. + readBytes: (value: Uint8Array) => value, +}); + +declare const writerMethods: Parameters[0]; +const writerOwner = IDataWriter.implement({ + ...writerMethods, + writeBytes(value) { + const bytes: number[] = value; + void bytes; + }, + writeBuffer(value) { + const buffer: IBuffer | null = value; + void buffer; + }, +}, IClosable.implementation({ close() {} })); +const writerView: IDataWriter = IDataWriter.fromImplementation(writerOwner); +writerView.writeBytes(new Uint8Array([0, 255])); +writerView.writeBuffer(IBuffer.fromBuffer(new Uint8Array([1]))); +declare const propertyMethods: Parameters[0]; +const properties = IPropertyValue.implement({ + ...propertyMethods, + getUInt8Array: () => new Uint8Array([0, 255]), + getStringArray: () => ['owned string'], + getInspectableArray: () => [raw, null], + getPointArray: () => [{ x: 1.25, y: -3.5 }], +}); +const propertyView: IPropertyValue = IPropertyValue.fromImplementation(properties); +const copied: Uint8Array = propertyView.getUInt8Array(); +const strings: string[] = propertyView.getStringArray(); +const points: { x: number; y: number }[] = propertyView.getPointArray(); +const objects: (DynWinRtValue | null)[] = propertyView.getInspectableArray(); +void [copied, strings, points, objects]; +// @ts-expect-error Object array elements project native null references as null. +const nonNullableObjects: DynWinRtValue[] = propertyView.getInspectableArray(); +IPropertyValue.implementation({ + ...propertyMethods, + // @ts-expect-error ReceiveArray elements must match the metadata element type. + getStringArray: () => ['valid', 42], +}); + +const iterator = IBindableIterator.implement({ + getCurrent: () => null, getHasCurrent: () => true, moveNext: () => false, +}); +const iterable = IBindableIterable.implementation({ + first: () => IBindableIterator.fromImplementation(iterator), +}); +const vector = IBindableVectorView.implement({ + getAt: () => null, + getSize: () => 1, + indexOf(value) { + return { result: value === null, index: 0 }; + }, +}, iterable); +const result: [number, boolean] = IBindableVectorView.fromImplementation(vector).indexOf(null); +void result; +IBindableVectorView.implementation({ + getAt: () => null, getSize: () => 1, + // @ts-expect-error Inbound multiple outputs are named, not positional tuples. + indexOf: () => [0, true], +}); +IBindableVectorView.implementation({ + getAt: () => null, getSize: () => 1, + // @ts-expect-error Explicit index out is required in addition to result. + indexOf: () => ({ result: true }), +}); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/generator.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/generator.rs index 86012582..9b97f5d0 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/generator.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/generator.rs @@ -57,6 +57,15 @@ pub fn generate_index( if is_delegate { continue; } + let implementation = + super::implementation::project(&Default::default(), iface, &HashSet::new()); + if !implementation.exports.is_empty() { + out.push_str(&format!( + "export type {{ {} }} from './{}.js';\n", + implementation.exports.join(", "), + iface.name + )); + } let struct_names: Vec<_> = collect_used_structs_from_iface(iface) .iter() .flat_map(|s| ts_pack_export_names(s)) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs new file mode 100644 index 00000000..df6177e2 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs @@ -0,0 +1,850 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! JavaScript projection of validated reverse-call contracts. + +use std::collections::HashSet; + +use crate::codegen::winrt::shared::implementation::{ + ImplementationAbi, ImplementationHandlerKind, ImplementationMethod, ImplementationProjection, + ImplementationType, WinRtImplementationPlan, project_implementation, validate_type, +}; +use crate::codegen::winrt::shared::imports::{NO_DEFERRED, ireference_inner_type}; +use crate::meta::{InterfaceMeta, ParamDirection}; +use crate::types::TypeMeta; + +use super::JavaScriptProjectionContext; +use super::naming::{capitalize, to_camel_case}; +use super::signature::{convert_return, ts_dynwinrt_type}; + +const HELPERS: &str = r#" +function __implementationCheck(value, valid, label) { + if (!valid) throw new TypeError(`${label}: invalid implementation result`); + return value; +} +function __implementationField(value, name, label) { + if (value === null || typeof value !== 'object') throw new TypeError(`${label}: expected a named result object`); + const field = Object.getOwnPropertyDescriptor(value, name); + if (!field || !Object.hasOwn(field, 'value')) throw new TypeError(`${label}: missing data field ${name}`); + return field.value; +} +function __implementationArray(value, label, bytes = false, capacity = undefined) { + if (!Array.isArray(value) && !(bytes && value instanceof Uint8Array)) throw new TypeError(`${label}: expected an array`); + if (capacity !== undefined && value.length !== capacity) throw new RangeError(`${label}: FillArray result must match capacity ${capacity}`); + return Array.from(value); +} +function __implementationReference(value, iid, label) { + if (value === null) return DynWinRtValue.nullValue(); + const raw = value instanceof DynWinRtValue ? value : value?._obj; + if (!(raw instanceof DynWinRtValue)) throw new TypeError(`${label}: expected a managed WinRT value or null`); + return raw.isNull() ? DynWinRtValue.nullValue() : raw.cast(iid); +} +function __implementationSync(value, label) { + if (value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function') { + throw new TypeError(`${label}: implementation callbacks must return synchronously, not a Promise or thenable`); + } + return value; +} +function __implementationHandler(handlers, name, label) { + if (handlers === null || (typeof handlers !== 'object' && typeof handlers !== 'function')) throw new TypeError(`${label}: expected a handler object`); + let owner = handlers; + while (owner && owner !== Object.prototype && owner !== Function.prototype) { + const property = Object.getOwnPropertyDescriptor(owner, name); + if (property) { + const callback = property.value; + if (typeof callback !== 'function') throw new TypeError(`${label}: missing synchronous handler ${name} (accessors are not handlers)`); + if (Object.prototype.toString.call(callback) === '[object AsyncFunction]' || Object.prototype.toString.call(callback) === '[object AsyncGeneratorFunction]') { + throw new TypeError(`${label}.${name}: async handlers are not supported`); + } + return callback.bind(handlers); + } + owner = Object.getPrototypeOf(owner); + } + throw new TypeError(`${label}: missing synchronous handler ${name}`); +} +"#; + +fn quote(value: &str) -> String { + serde_json::to_string(value).expect("string serialization") +} + +fn handler_name(method: &ImplementationMethod) -> String { + let (prefix, raw) = match method.handler_kind { + ImplementationHandlerKind::Method => return to_camel_case(&method.name), + ImplementationHandlerKind::Getter => ("get", "get_"), + ImplementationHandlerKind::Setter => ("set", "put_"), + ImplementationHandlerKind::Add => ("add", "add_"), + ImplementationHandlerKind::Remove => ("remove", "remove_"), + }; + format!( + "{prefix}{}", + capitalize(method.name.strip_prefix(raw).unwrap_or(&method.name)) + ) +} + +fn input_name(name: &str, index: usize, fill: bool) -> String { + let name = if name.is_empty() { + format!("arg{index}") + } else { + to_camel_case(name) + }; + if fill { + format!("{name}Capacity") + } else { + name + } +} + +fn output_names(method: &ImplementationMethod) -> Result, String> { + let names = method + .output_names + .iter() + .map(|name| to_camel_case(name)) + .collect::>(); + if names.iter().collect::>().len() != names.len() { + return Err(format!("{} has colliding output names", method.name)); + } + Ok(names) +} + +struct Projector<'a> { + context: &'a JavaScriptProjectionContext, + known: &'a HashSet, + plan: &'a WinRtImplementationPlan, + prefix: String, +} + +impl Projector<'_> { + fn delegate_index(&self, typ: &TypeMeta) -> Option { + self.plan + .delegates + .iter() + .position(|delegate| delegate.typ.metadata == *typ) + } + + fn native(&self, typ: &ImplementationType) -> String { + match &typ.abi { + ImplementationAbi::Array(element) => { + format!("DynWinRtType.arrayType({})", self.native(element)) + } + ImplementationAbi::Struct(fields) => { + let TypeMeta::Struct { + namespace, name, .. + } = &typ.metadata + else { + unreachable!() + }; + format!( + "DynWinRtType.structType({}, [{}])", + quote(&format!("{namespace}.{name}")), + fields + .iter() + .map(|field| self.native(field)) + .collect::>() + .join(", ") + ) + } + ImplementationAbi::Reference => match &typ.metadata { + TypeMeta::Interface { iid, .. } | TypeMeta::Delegate { iid, .. } => { + let kind = if self.delegate_index(&typ.metadata).is_some() + || matches!(typ.metadata, TypeMeta::Delegate { .. }) + { + "delegate" + } else { + "interface" + }; + format!("DynWinRtType.{kind}(WinGuid.parse({}))", quote(iid)) + } + TypeMeta::RuntimeClass { + namespace, + name, + default_interface, + } => { + let default = validate_type( + default_interface + .as_deref() + .expect("validated default interface"), + false, + ) + .expect("validated type"); + format!( + "DynWinRtType.runtimeClass({}, {})", + quote(&format!( + "{namespace}.{}", + self.context.metadata_type_name(namespace, name) + )), + self.native(&default) + ) + } + TypeMeta::Parameterized { piid, args, .. } => format!( + "DynWinRtType.parameterized(WinGuid.parse({}), [{}])", + quote(piid), + args.iter() + .map(|typ| self + .native(&validate_type(typ, false).expect("validated argument"))) + .collect::>() + .join(", ") + ), + TypeMeta::Object + | TypeMeta::AsyncAction + | TypeMeta::AsyncActionWithProgress(_) + | TypeMeta::AsyncOperation(_) + | TypeMeta::AsyncOperationWithProgress(_, _) => { + ts_dynwinrt_type(self.context, &typ.metadata) + } + _ => unreachable!("validated reference"), + }, + ImplementationAbi::Scalar if typ.metadata == TypeMeta::Char16 => { + "DynWinRtType.char16()".into() + } + ImplementationAbi::Scalar + | ImplementationAbi::HResult + | ImplementationAbi::Enum + | ImplementationAbi::Guid + | ImplementationAbi::HString => ts_dynwinrt_type(self.context, &typ.metadata), + } + } + + fn iid(&self, typ: &ImplementationType) -> String { + if typ.metadata == TypeMeta::Object { + "WinGuid.parse('af86e2e0-b12d-4c6a-9c5a-d7aa65101e90')".into() + } else { + format!("{}.iid()", self.native(typ)) + } + } + + fn annotation(&self, typ: &ImplementationType, writing: bool) -> String { + if let Some(index) = self.delegate_index(&typ.metadata) { + return format!( + "{}Delegate{index}{} | null", + self.prefix, + if writing { " | DynWinRtValue" } else { "" } + ); + } + if let Some(inner) = ireference_inner_type(&typ.metadata) { + return format!( + "{} | null", + self.annotation( + &validate_type(inner, false).expect("validated IReference"), + writing + ) + ); + } + match &typ.abi { + ImplementationAbi::Array(element) => { + let array = format!("({})[]", self.annotation(element, writing)); + if writing && element.metadata == TypeMeta::U8 { + format!("{array} | Uint8Array") + } else { + array + } + } + ImplementationAbi::Struct(fields) => { + let TypeMeta::Struct { + fields: metadata, .. + } = &typ.metadata + else { + unreachable!() + }; + format!( + "{{ {} }}", + metadata + .iter() + .zip(fields) + .map(|(field, typ)| { + format!( + "{}: {}", + to_camel_case(&field.name), + self.annotation(typ, writing) + ) + }) + .collect::>() + .join("; ") + ) + } + ImplementationAbi::HResult => "number".into(), + ImplementationAbi::Enum => match &typ.metadata { + TypeMeta::Enum { name, .. } if self.known.contains(name) => name.clone(), + _ => "number".into(), + }, + ImplementationAbi::Reference => { + let name = match &typ.metadata { + TypeMeta::RuntimeClass { name, .. } | TypeMeta::Interface { name, .. } + if self.known.contains(name) => + { + name.clone() + } + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => { + let concrete = self + .context + .projected_parameterized_name(namespace, name, piid, args); + if self.known.contains(&concrete) { + concrete + } else { + "DynWinRtValue".into() + } + } + _ => "DynWinRtValue".into(), + }; + format!("{name} | null") + } + ImplementationAbi::Scalar | ImplementationAbi::Guid | ImplementationAbi::HString => { + match typ.metadata { + TypeMeta::Bool => "boolean", + TypeMeta::I64 | TypeMeta::U64 => "bigint", + TypeMeta::String | TypeMeta::Guid => "string", + _ => "number", + } + .into() + } + } + } + + fn read(&self, typ: &ImplementationType, value: &str) -> String { + if let Some(index) = self.delegate_index(&typ.metadata) { + return format!("{}Delegate{index}({value})", self.prefix); + } + if let Some(inner) = ireference_inner_type(&typ.metadata) { + let inner = validate_type(inner, false).expect("validated IReference value"); + let native = format!( + "DynWinRtType.registerInterface('__dynwinrt_reverse_reference_' + iid.toString(), iid).addMethod('get_Value', new DynWinRtMethodSig().addOut({})).method(6).invoke(v.cast(iid), [])", + self.native(&inner) + ); + return format!( + "((v) => {{ if (v.isNull()) return null; const iid = {}; return {}; }})({value})", + self.iid(typ), + self.read(&inner, &native) + ); + } + match &typ.abi { + ImplementationAbi::Array(element) => format!( + "{value}.asArray().toValues().map(v => {})", + self.read(element, "v") + ), + ImplementationAbi::Struct(fields) => { + let TypeMeta::Struct { + fields: metadata, .. + } = &typ.metadata + else { + unreachable!() + }; + let members = metadata + .iter() + .zip(fields) + .enumerate() + .map(|(index, (field, typ))| { + let expr = match &typ.abi { + ImplementationAbi::Reference => { + self.read(typ, &format!("s.getObject({index})")) + } + ImplementationAbi::Struct(_) => { + self.read(typ, &format!("s.getStruct({index}).toValue()")) + } + _ => super::structs::struct_field_getter( + self.context, + &typ.metadata, + index, + ), + }; + format!("{}: {expr}", to_camel_case(&field.name)) + }) + .collect::>() + .join(", "); + format!("((s) => ({{ {members} }}))({value}.asStruct())") + } + ImplementationAbi::Reference if typ.metadata.is_async() => { + format!("((v) => v.isNull() ? null : v)({value})") + } + _ => convert_return( + self.context, + value, + Some(&typ.metadata), + false, + self.known, + &NO_DEFERRED, + ), + } + } + + fn check_scalar(&self, typ: &ImplementationType, value: &str, label: &str) -> String { + let integer = |min: &str, max: &str| { + format!("typeof v === 'number' && Number.isInteger(v) && v >= {min} && v <= {max}") + }; + let check = match &typ.metadata { + TypeMeta::Bool => "typeof v === 'boolean'".into(), + TypeMeta::String | TypeMeta::Guid => "typeof v === 'string'".into(), + TypeMeta::I8 => integer("-128", "127"), + TypeMeta::U8 => integer("0", "255"), + TypeMeta::I16 => integer("-32768", "32767"), + TypeMeta::U16 | TypeMeta::Char16 => integer("0", "65535"), + TypeMeta::I32 | TypeMeta::Enum { .. } | TypeMeta::Struct { .. } => integer("-2147483648", "2147483647"), + TypeMeta::U32 => integer("0", "4294967295"), + TypeMeta::I64 => "typeof v === 'bigint' && v >= -9223372036854775808n && v <= 9223372036854775807n".into(), + TypeMeta::U64 => "typeof v === 'bigint' && v >= 0n && v <= 18446744073709551615n".into(), + TypeMeta::F32 => "typeof v === 'number' && (!Number.isFinite(v) || Math.abs(v) <= 3.4028234663852886e38)".into(), + TypeMeta::F64 => "typeof v === 'number'".into(), + _ => unreachable!("validated scalar"), + }; + format!( + "((v) => __implementationCheck(v, {check}, {}))({value})", + quote(label) + ) + } + + fn write( + &self, + typ: &ImplementationType, + value: &str, + label: &str, + capacity: Option<&str>, + ) -> String { + if let Some(inner) = ireference_inner_type(&typ.metadata) { + let inner = validate_type(inner, false).expect("validated IReference"); + return format!( + "((v) => v === null ? DynWinRtValue.nullValue() : (v instanceof DynWinRtValue || v?._obj instanceof DynWinRtValue) ? __implementationReference(v, {}, {}) : DynWinRtValue.boxReference({}, {}))({value})", + self.iid(typ), + quote(label), + self.write(&inner, "v", label, None), + self.native(&inner) + ); + } + match &typ.abi { + ImplementationAbi::Reference => format!( + "__implementationReference({value}, {}, {})", + self.iid(typ), + quote(label) + ), + ImplementationAbi::Array(element) + if matches!(element.abi, ImplementationAbi::HResult) => + { + format!( + "DynWinRtArray.fromHresultValues(__implementationArray({value}, {}, false, {}).map(v => {})).toValue()", + quote(label), + capacity.unwrap_or("undefined"), + self.check_scalar(element, "v", &format!("{label}[]")) + ) + } + ImplementationAbi::Array(element) => format!( + "DynWinRtArray.fromObjectValues(__implementationArray({value}, {}, {}, {}).map(v => {}), {}).toValue()", + quote(label), + element.metadata == TypeMeta::U8, + capacity.unwrap_or("undefined"), + self.write(element, "v", &format!("{label}[]"), None), + self.native(element) + ), + ImplementationAbi::Struct(fields) => { + let TypeMeta::Struct { + fields: metadata, .. + } = &typ.metadata + else { + unreachable!() + }; + let setters = metadata + .iter() + .zip(fields) + .enumerate() + .map(|(index, (field, typ))| { + let field_name = to_camel_case(&field.name); + let label = format!("{label}.{field_name}"); + let access = format!( + "__implementationField(v, {}, {})", + quote(&field_name), + quote(&label) + ); + let setter = match &typ.abi { + ImplementationAbi::Reference => format!( + "s.setObject({index}, {})", + self.write(typ, &access, &label, None) + ), + ImplementationAbi::Struct(_) => format!( + "s.setStruct({index}, {}.asStruct())", + self.write(typ, &access, &label, None) + ), + _ => super::structs::struct_field_setter( + self.context, + &typ.metadata, + index, + &self.check_scalar(typ, &access, &label), + ), + }; + format!("{setter};") + }) + .collect::>() + .join(" "); + format!( + "((v) => {{ const s = DynWinRtStruct.create({}); {setters} return s.toValue(); }})({value})", + self.native(typ) + ) + } + ImplementationAbi::HResult => format!( + "DynWinRtValue.hresult({})", + self.check_scalar(typ, value, label) + ), + ImplementationAbi::Scalar + | ImplementationAbi::Enum + | ImplementationAbi::Guid + | ImplementationAbi::HString => { + let value = self.check_scalar(typ, value, label); + let constructor = match typ.metadata { + TypeMeta::Bool => "boolValue", + TypeMeta::I8 => "i8Value", + TypeMeta::U8 => "u8Value", + TypeMeta::I16 => "i16", + TypeMeta::U16 | TypeMeta::Char16 => "u16", + TypeMeta::I32 => "i32", + TypeMeta::U32 => "u32", + TypeMeta::I64 => "i64", + TypeMeta::U64 => "u64", + TypeMeta::F32 => "f32", + TypeMeta::F64 => "f64", + TypeMeta::String => "hstring", + TypeMeta::Guid => return format!("DynWinRtValue.guid(WinGuid.parse({value}))"), + TypeMeta::Enum { .. } => { + return format!("DynWinRtValue.enumValue({}, {value})", self.native(typ)); + } + _ => unreachable!("validated scalar"), + }; + format!("DynWinRtValue.{constructor}({value})") + } + } + } + + fn signature(&self, method: &ImplementationMethod) -> String { + let mut signature = "new DynWinRtMethodSig()".to_string(); + for parameter in &method.parameters { + let add = match parameter.direction { + ParamDirection::In => "addIn", + ParamDirection::Out => "addOut", + ParamDirection::OutFill => "addOutFill", + }; + signature.push_str(&format!(".{add}({})", self.native(¶meter.typ))); + } + if let Some(typ) = &method.return_type { + signature.push_str(&format!(".addOut({})", self.native(typ))); + } + signature + } + + fn default_value(&self, typ: &ImplementationType) -> String { + match &typ.abi { + ImplementationAbi::Reference => "DynWinRtValue.nullValue()".into(), + ImplementationAbi::Struct(_) => { + format!("DynWinRtStruct.create({}).toValue()", self.native(typ)) + } + ImplementationAbi::Array(_) => unreachable!("nested arrays were rejected"), + ImplementationAbi::Enum => format!("DynWinRtValue.enumValue({}, 0)", self.native(typ)), + _ => self.write( + typ, + match typ.metadata { + TypeMeta::Bool => "false", + TypeMeta::I64 | TypeMeta::U64 => "0n", + TypeMeta::String => "''", + TypeMeta::Guid => "'00000000-0000-0000-0000-000000000000'", + _ => "0", + }, + "delegate fill storage", + None, + ), + } + } + + fn delegate_fill_input(&self, typ: &ImplementationType, capacity: &str) -> String { + let ImplementationAbi::Array(element) = &typ.abi else { + unreachable!("validated FillArray") + }; + format!( + "DynWinRtArray.fromObjectValues(Array.from({{ length: __implementationCheck({capacity}, Number.isInteger({capacity}) && {capacity} >= 0 && {capacity} <= 4294967295, 'delegate capacity') }}, () => {}), {}).toValue()", + self.default_value(element), + self.native(element) + ) + } + + fn parameters(&self, method: &ImplementationMethod, writing: bool) -> Result { + let mut names = HashSet::new(); + let mut params = Vec::new(); + for parameter in &method.parameters { + if let Some(index) = parameter.input_index { + let fill = parameter.direction == ParamDirection::OutFill; + let name = input_name(¶meter.name, index, fill); + if !names.insert(name.clone()) { + return Err(format!( + "{} has colliding handler parameter names", + method.name + )); + } + params.push(format!( + "{name}: {}", + if fill { + "number".into() + } else { + self.annotation(¶meter.typ, writing) + } + )); + } + } + Ok(params.join(", ")) + } + + fn result_type(&self, method: &ImplementationMethod, writing: bool) -> Result { + let types = method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| &p.typ) + .chain(method.return_type.iter()) + .collect::>(); + Ok(match types.as_slice() { + [] => "void".into(), + [typ] => self.annotation(typ, writing), + _ => format!( + "{{ {} }}", + output_names(method)? + .iter() + .zip(types) + .map(|(name, typ)| { format!("{name}: {}", self.annotation(typ, writing)) }) + .collect::>() + .join("; ") + ), + }) + } +} + +pub(super) fn project( + context: &JavaScriptProjectionContext, + iface: &InterfaceMeta, + known: &HashSet, +) -> ImplementationProjection { + let result = project_implementation(iface) + .and_then(|plan| project_validated(context, iface, known, &plan)); + result.unwrap_or_else(|reason| ImplementationProjection { + factory_body: format!( + " static implementation() {{ throw new TypeError({0}); }}\n static implement() {{ throw new TypeError({0}); }}\n", quote(&reason) + ), + factory_declarations: format!( + " /** {} */\n static implementation(handlers: never): never;\n /** {} */\n static implement(handlers: never, ...additional: never[]): never;\n", + reason.replace("*/", "* /"), reason.replace("*/", "* /") + ), + ..Default::default() + }) +} + +fn project_validated( + context: &JavaScriptProjectionContext, + iface: &InterfaceMeta, + known: &HashSet, + plan: &WinRtImplementationPlan, +) -> Result { + let projector = Projector { + context, + known, + plan, + prefix: format!("{}Implementation", iface.name), + }; + let mut support = String::from(HELPERS); + let mut declarations = String::new(); + for (index, delegate) in plan.delegates.iter().enumerate() { + let method = &delegate.invoke; + declarations.push_str(&format!( + "export type {}Delegate{index} = (({}) => {}) & {{ readonly _obj: DynWinRtValue }};\n", + projector.prefix, + projector.parameters(method, true)?, + projector.result_type(method, false)? + )); + let args = method + .parameters + .iter() + .filter_map(|parameter| { + parameter.input_index.map(|index| { + if parameter.direction == ParamDirection::OutFill { + projector.delegate_fill_input(¶meter.typ, &format!("args[{index}]")) + } else { + projector.write( + ¶meter.typ, + &format!("args[{index}]"), + "delegate argument", + None, + ) + } + }) + }) + .collect::>() + .join(", "); + let outputs = method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| &p.typ) + .chain(method.return_type.iter()) + .enumerate() + .map(|(index, typ)| projector.read(typ, &format!("result[{index}]"))) + .collect::>(); + let returned = match outputs.as_slice() { + [] => "undefined".into(), + [value] => value.clone(), + _ => format!( + "{{ {} }}", + output_names(method)? + .iter() + .zip(outputs) + .map(|(name, expr)| format!("{name}: {expr}")) + .collect::>() + .join(", ") + ), + }; + support.push_str(&format!( + "\nfunction {}Delegate{index}(value) {{\n if (value.isNull()) return null;\n const callback = (...args) => {{\n if (args.length !== {}) throw new TypeError('delegate argument count mismatch');\n const result = value.invokeDelegate({}, {}, [{args}]);\n return {returned};\n }};\n Object.defineProperty(callback, '_obj', {{ value }});\n return callback;\n}}\n", + projector.prefix, method.input_count, projector.iid(&delegate.typ), projector.signature(method) + )); + } + declarations.push_str(&format!( + "\n/** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */\nexport interface {}Handlers {{\n", iface.name + )); + let mut handlers = HashSet::new(); + let mut bindings = Vec::new(); + let mut dispatch = String::new(); + let mut descriptors = Vec::new(); + for method in &plan.methods { + let handler = handler_name(method); + if !handlers.insert(handler.clone()) { + return Err(format!( + "{} cannot be implemented: handler name collision for {handler}", + plan.name + )); + } + declarations.push_str(&format!( + " {handler}({}): {};\n", + projector.parameters(method, false)?, + projector.result_type(method, true)? + )); + let slot = method.vtable_index; + bindings.push(format!( + " const h{slot} = __implementationHandler(handlers, {}, {});", + quote(&handler), + quote(&plan.name) + )); + descriptors.push(format!( + "{{ name: {}, vtableIndex: {slot}, signature: {} }}", + quote(&method.name), + projector.signature(method) + )); + let args = method + .parameters + .iter() + .filter_map(|parameter| { + parameter.input_index.map(|index| { + if parameter.direction == ParamDirection::OutFill { + format!("args[{index}].toNumber()") + } else { + projector.read(¶meter.typ, &format!("args[{index}]")) + } + }) + }) + .collect::>() + .join(", "); + let label = format!("{}.{}", plan.name, handler); + dispatch.push_str(&format!( + " case {slot}: {{\n if (args.length !== {}) throw new TypeError('implementation argument count mismatch');\n const result = __implementationSync(h{slot}({args}), {});\n", method.input_count, quote(&label) + )); + let names = output_names(method)?; + let mut outputs = Vec::new(); + for (index, (typ, fill)) in method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| { + ( + &p.typ, + if p.direction == ParamDirection::OutFill { + p.input_index + } else { + None + }, + ) + }) + .chain(method.return_type.iter().map(|typ| (typ, None))) + .enumerate() + { + let value = if method.output_count == 1 { + "result".into() + } else { + format!( + "__implementationField(result, {}, {})", + quote(&names[index]), + quote(&label) + ) + }; + let capacity = fill.map(|index| format!("args[{index}].toNumber()")); + outputs.push(projector.write( + typ, + &value, + &format!("{label}.{}", names[index]), + capacity.as_deref(), + )); + } + if outputs.is_empty() { + dispatch.push_str(&format!( + " if (result !== undefined) throw new TypeError({});\n", + quote(&format!("{label}: void handler must return undefined")) + )); + } + dispatch.push_str(&format!( + " return [{}];\n }}\n", + outputs.join(", ") + )); + } + declarations.push_str("}\n"); + support.push_str(&format!( + "\nlet __implementationPlan;\nfunction __getImplementationPlan() {{\n return (__implementationPlan ??= DynWinRtInterfacePlan.create({}, DynWinRtType.interface(WinGuid.parse({})), [\n {}\n ], [{}]));\n}}\n", + quote(&plan.name), quote(&plan.iid), descriptors.join(",\n "), + plan.required_interfaces.iter().map(|typ| projector.iid(typ)).collect::>().join(", ") + )); + let requirements = if plan.required_interfaces.is_empty() { + String::new() + } else { + format!( + " Required QI views must be supplied as additional descriptors: {}.", + plan.required_interfaces + .iter() + .map(|typ| typ + .metadata + .type_identity() + .definition_name() + .unwrap_or("interface") + .to_string()) + .collect::>() + .join(", ") + ) + }; + if !plan.delegates.is_empty() { + bindings.push(" if (typeof DynWinRtValue.prototype.invokeDelegate !== 'function') throw new TypeError('this interface requires WinRT delegate invocation support in the runtime');".into()); + } + let mut factory_body = format!( + " static implementation(handlers) {{\n{}\n const plan = __getImplementationPlan();\n return Object.freeze({{ plan, dispatch(vtableIndex, args) {{\n if (!Array.isArray(args)) throw new TypeError('implementation arguments must be an array');\n switch (vtableIndex) {{\n{dispatch} default: throw new RangeError('unknown implementation vtable slot');\n }}\n }} }});\n }}\n\n static implement(handlers, ...additional) {{\n const descriptors = [this.implementation(handlers), ...additional];\n for (const descriptor of descriptors) {{\n if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor');\n }}\n const plans = descriptors.map(descriptor => descriptor.plan);\n const dispatchers = descriptors.map(descriptor => descriptor.dispatch);\n return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => {{\n if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index');\n return dispatchers[interfaceIndex](vtableIndex, args);\n }});\n }}\n", + bindings.join("\n") + ); + factory_body.push_str( + "\n static fromImplementation(owner) {\n if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller');\n const value = owner.toValue();\n try {\n return this.from(value);\n } finally {\n value.release();\n }\n }\n", + ); + let factory_declarations = format!( + " /** Validate synchronous handlers and create an independent interface descriptor.{requirements} */\n static implementation(handlers: {}Handlers): DynWinRtImplementationDescriptor;\n /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper.{requirements} */\n static implement(handlers: {}Handlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation;\n /** Query a controller for this interface and return an owned, typed view. */\n static fromImplementation(owner: DynWinRtImplementation): {};\n", + iface.name, iface.name, iface.name + ); + let exports = std::iter::once(format!("{}Handlers", iface.name)) + .chain( + (0..plan.delegates.len()).map(|index| format!("{}Delegate{index}", projector.prefix)), + ) + .collect(); + Ok(ImplementationProjection { + support_code: support, + declarations, + factory_body, + factory_declarations, + supported: true, + exports, + }) +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs index 123acbf4..83ba6086 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/ir.rs @@ -276,6 +276,7 @@ pub struct ProjectedIface { pub has_parameterized_cast: bool, pub members: Vec, pub is_delegate: bool, + pub(crate) implementation: super::super::shared::implementation::ImplementationProjection, } pub struct ProjectedIidConst { @@ -316,6 +317,13 @@ pub struct ProjectedFile { } impl ProjectedFile { + pub fn public_type_exports(&self) -> BTreeSet { + self.ifaces + .iter() + .flat_map(|iface| iface.implementation.exports.iter().cloned()) + .collect() + } + pub fn public_exports(&self) -> BTreeSet { let mut exports = BTreeSet::new(); exports.extend(self.classes.iter().map(|class| class.name.clone())); @@ -377,6 +385,7 @@ pub struct GeneratedModule { pub declarations: Option, pub imports: Vec, pub public_exports: BTreeSet, + pub public_type_exports: BTreeSet, pub primary_export: Option, pub internal_exports: BTreeSet, pub compatibility_aliases: BTreeSet, @@ -392,6 +401,7 @@ impl GeneratedModule { declarations: None, imports: Vec::new(), public_exports: BTreeSet::new(), + public_type_exports: BTreeSet::new(), primary_export: None, internal_exports: BTreeSet::new(), compatibility_aliases: BTreeSet::new(), @@ -411,6 +421,7 @@ impl GenerationPlan { && (previous.javascript != module.javascript || previous.declarations != module.declarations || previous.public_exports != module.public_exports + || previous.public_type_exports != module.public_type_exports || previous.internal_exports != module.internal_exports) { return Err(format!( @@ -466,6 +477,18 @@ impl GenerationPlan { module.canonical_module )); } + if !module.public_type_exports.is_empty() { + output.push_str(&format!( + "export type {{ {} }} from './{}.js';\n", + module + .public_type_exports + .iter() + .cloned() + .collect::>() + .join(", "), + module.canonical_module + )); + } } output } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs index f5c68f45..3b1a120b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/method.rs @@ -307,6 +307,7 @@ pub(crate) fn ts_array_element_type(inner: &TypeMeta, known_types: &HashSet "bigint[]".to_string(), TypeMeta::Struct { name, .. } if name == "HResult" => "number[]".to_string(), TypeMeta::Struct { name, .. } => format!("{}[]", name), + TypeMeta::Object => "Array".to_string(), TypeMeta::RuntimeClass { name, .. } if known_types.contains(name) => format!("{}[]", name), TypeMeta::Interface { name, .. } if known_types.contains(name) => format!("{}[]", name), _ => "DynWinRtValue[]".to_string(), diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs index 20ffc3fe..458d000f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod docs; pub mod generator; +mod implementation; pub mod ir; pub(crate) mod method; pub(crate) mod naming; @@ -1268,6 +1269,13 @@ fn apply_projected_interface_names( for method in &mut interface.methods { apply_projected_method_names(context, method); } + for required in &mut interface.implementation_metadata.required_interfaces { + apply_projected_type_names(context, required); + } + for delegate in &mut interface.implementation_metadata.delegates { + apply_projected_type_names(context, &mut delegate.typ); + apply_projected_method_names(context, &mut delegate.invoke); + } } fn apply_projected_type_ref_name(context: &JavaScriptProjectionContext, reference: &mut TypeRef) { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs index 2c89fd48..a2244373 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs @@ -1255,7 +1255,15 @@ pub fn project_interface( let mut imports = Vec::new(); imports.push(build_runtime_import(context, has_structs)); - let collection_names = collect_used_generics_from_methods(context, &iface.methods); + let mut collection_names = collect_used_generics_from_methods(context, &iface.methods); + for delegate in &iface.implementation_metadata.delegates { + collection_names.extend(collect_used_generics_from_methods( + context, + std::slice::from_ref(&delegate.invoke), + )); + } + collection_names.sort(); + collection_names.dedup(); for cname in &collection_names { if cname != &iface.name && !delegate_names.contains(cname) { imports.push(ProjectedImport { @@ -1451,6 +1459,20 @@ pub fn project_interface( let needs_unwrap = check_needs_unwrap_simple(&members); let doc = build_doc_info(iface.doc.as_deref(), iface.deprecated.as_deref(), None, &[]); + let implementation = super::implementation::project(context, iface, known_types); + if implementation.supported { + imports[0].symbols.extend([ + "DynWinRtInterfacePlan".into(), + "DynWinRtImplementation".into(), + ]); + imports.push(ProjectedImport { + symbols: vec!["DynWinRtImplementationDescriptor".into()], + from: context.runtime_import_name().into(), + runtime_only: false, + dts_only: true, + is_runtime_package: true, + }); + } ProjectedFile { name: iface.name.clone(), @@ -1468,6 +1490,7 @@ pub fn project_interface( has_parameterized_cast, members, is_delegate: false, + implementation, }], delegates: vec![], needs_unwrap_helper: needs_unwrap, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs index 8d96b34d..bd85784c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/declarations.rs @@ -321,6 +321,8 @@ fn render_class_dts(out: &mut String, class: &ProjectedClass, file: &ProjectedFi } fn render_iface_dts(out: &mut String, iface: &ProjectedIface, file: &ProjectedFile) { + out.push_str(&iface.implementation.declarations); + out.push('\n'); // IID const (only exported ones) for iid in &file.iid_consts { if iid.exported { @@ -339,6 +341,7 @@ fn render_iface_dts(out: &mut String, iface: &ProjectedIface, file: &ProjectedFi // Constructor — private (users should use static from() or factory methods) out.push_str(" private constructor();\n"); + out.push_str(&iface.implementation.factory_declarations); // static from() — internal, for advanced cross-interface casting if iface.has_static_from { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs index 07f95436..f9519070 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/render/javascript/mod.rs @@ -305,6 +305,8 @@ fn render_class_js(out: &mut String, class: &ProjectedClass) { } fn render_iface_js(out: &mut String, iface: &ProjectedIface, _file: &ProjectedFile) { + out.push_str(&iface.implementation.support_code); + out.push('\n'); if let Some(ref doc) = iface.doc { out.push_str(&render_jsdoc(doc, "")); } @@ -333,6 +335,8 @@ fn render_iface_js(out: &mut String, iface: &ProjectedIface, _file: &ProjectedFi iface.name, iface.name )); } + out.push('\n'); + out.push_str(&iface.implementation.factory_body); // Members for member in &iface.members { @@ -482,13 +486,15 @@ fn render_member_js(out: &mut String, member: &ProjectedMember, _class_name: &st " const handler = DynWinRtDelegate.create(DynWinRtType.object().iid(), [DynWinRtType.object(), DynWinRtType.object()], wrapped);\n" ); } + out.push_str(" let __handlerValue;\n let __token;\n try {\n __handlerValue = handler.toValue();\n"); out.push_str(&format!( - " const __token = {}.method({}).invoke({}, [handler.toValue()]);\n", + " __token = {}.method({}).invoke({}, [__handlerValue]);\n", event.add_iface_var, event.add_vtable_index, event.add_obj_expr )); + out.push_str(" } finally {\n __handlerValue?.release();\n handler.release();\n }\n"); if let Some(idx) = event.remove_vtable_index { out.push_str(&format!( - " return () => {{ void handler; {}.method({}).invoke({}, [__token]); }};\n", + " return () => {{ {}.method({}).invoke({}, [__token]); }};\n", event.remove_iface_var, idx, event.remove_obj_expr )); } else { @@ -497,7 +503,7 @@ fn render_member_js(out: &mut String, member: &ProjectedMember, _class_name: &st .strip_prefix("on") .unwrap_or(&event.subscribe_name); out.push_str(&format!( - " return () => {{ void handler; this.off{}(__token); }};\n", + " return () => {{ this.off{}(__token); }};\n", cap )); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs index bcb4f1e8..c92095f8 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/signature.rs @@ -434,6 +434,11 @@ pub(crate) fn wrap_arg( TypeMeta::I32 | TypeMeta::Enum { .. } => { format!("DynWinRtArray.fromI32Values({name})") } + TypeMeta::Struct { + name: struct_name, .. + } if struct_name == "HResult" => { + format!("DynWinRtArray.fromHresultValues({name})") + } TypeMeta::U32 => format!("DynWinRtArray.fromU32Values({name})"), TypeMeta::I64 => format!("DynWinRtArray.fromI64Values({name})"), TypeMeta::U64 => format!("DynWinRtArray.fromU64Values({name})"), @@ -457,7 +462,7 @@ pub(crate) fn wrap_arg( TypeMeta::Struct { name: struct_name, .. } if struct_name == "HResult" => { - format!("DynWinRtValue.i32({})", name) + format!("DynWinRtValue.hresult({})", name) } TypeMeta::Struct { name: struct_name, .. @@ -494,7 +499,7 @@ fn wrap_reference_value( ), TypeMeta::Struct { name: struct_name, .. - } if struct_name == "HResult" => format!("DynWinRtValue.i32({})", name), + } if struct_name == "HResult" => format!("DynWinRtValue.hresult({})", name), TypeMeta::Struct { name: struct_name, .. } => format!("_pack{}({}).toValue()", struct_name, name), @@ -538,6 +543,9 @@ fn vector_item_wrap_expr( elem: &TypeMeta, ) -> String { match elem { + TypeMeta::Struct { name, .. } if name == "HResult" => { + format!("DynWinRtValue.hresult({})", var) + } TypeMeta::Struct { name, .. } if name != "HResult" => { format!("_pack{}({}).toValue()", name, var) } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs index b4759582..0aa149d3 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs @@ -53,6 +53,9 @@ pub fn generate_index( module = module, iname = name )); + for helper in super::super::implementation::exports(context, iface) { + out.push_str(&format!("from .{module} import {helper} # noqa: F401\n")); + } } } let mut sorted_enums: Vec<_> = enums.iter().collect(); @@ -119,6 +122,12 @@ pub fn generate_public_index( context.public_qualified_module(&identity), name )); + for helper in super::super::implementation::exports(context, interface) { + out.push_str(&format!( + "from .{} import {helper} # noqa: F401\n", + context.public_qualified_module(&identity), + )); + } } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs index ec56d42a..e1d6ff82 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -84,6 +84,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe if is_delegate { return generate_delegate(iface); } + let implementation = super::super::implementation::project(context, iface); let used_structs = collect_used_structs_from_iface(iface); @@ -91,6 +92,9 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); out.push_str(IMPORT_LINE); + if implementation.supported { + out.push_str(super::super::implementation::IMPORTS); + } let is_element_factory = iface.namespace == "Microsoft.UI.Xaml" && iface.name == "IElementFactory"; if is_element_factory { @@ -121,7 +125,14 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe super::super::collect_runtime_delegate_names(&iface.methods, context); // Import parameterized collection types (skip delegates) - let collection_identities = collect_used_generic_identities_from_methods(&iface.methods); + let mut collection_identities = collect_used_generic_identities_from_methods(&iface.methods); + for delegate in &iface.implementation_metadata.delegates { + collection_identities.extend(collect_used_generic_identities_from_methods( + std::slice::from_ref(&delegate.invoke), + )); + } + collection_identities.sort(); + collection_identities.dedup(); for identity in &collection_identities { let identity = context.normalize_identity(identity); if identity != iface.type_identity() && !delegate_names.contains(&identity) { @@ -245,6 +256,9 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe } } + out.push_str(&implementation.declarations); + out.push_str(&implementation.support_code); + // Wrapper class if let Some(identity) = &observable_vector { let vector_name = context.projected_name(identity); @@ -269,6 +283,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe )); } out.push_str(" _dynwinrt_interface_type = True\n"); + out.push_str(&implementation.factory_body); if !iface.iid.is_empty() || iface.generic_piid.is_some() { out.push_str(&format!( " _dynwinrt_interface_iid = IID_{}\n", @@ -283,7 +298,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe \x20 return _dynwinrt_projected_from_native(cls, args[0], '_set_native')\n\ \x20 return super().__new__(cls)\n\n", ); - out.push_str(" def _set_native(self, obj: DynWinRTValue):\n"); + out.push_str(" def _set_native(self, obj: DynWinRTValue, *, cache=True):\n"); if let Some(identity) = &observable_vector { let vector_name = context.projected_name(identity); out.push_str(&format!( @@ -307,7 +322,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe " _dynwinrt_track_projected(self, '{}.{}')\n", iface.namespace, iface.name )); - out.push_str(" _dynwinrt_cache_projected(self)\n"); + out.push_str(" if cache:\n _dynwinrt_cache_projected(self)\n"); out.push('\n'); out.push_str(" def __init__(self, obj: DynWinRTValue):\n"); out.push_str( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs new file mode 100644 index 00000000..f3271b2f --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs @@ -0,0 +1,978 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Python projection of the same validated reverse-call plan used by JavaScript. + +use std::collections::HashSet; + +use crate::codegen::winrt::shared::implementation::{ + ImplementationAbi, ImplementationHandlerKind, ImplementationMethod, ImplementationProjection, + ImplementationType, WinRtImplementationPlan, project_implementation, validate_type, +}; +use crate::codegen::winrt::shared::imports::ireference_inner_type; +use crate::meta::{InterfaceMeta, ParamDirection}; +use crate::types::TypeMeta; + +use super::naming::{PythonProjectionContext, to_snake_case}; +use super::native_types::{FoundationType, foundation_type}; +use super::signature::{py_convert_return, py_dynwinrt_type, py_runtime_type_symbol}; + +pub(super) const IMPORTS: &str = "\ +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) +"; + +const HELPERS: &str = r#" +import inspect as _implementation_inspect + + +def _implementation_check(value, valid, label): + if not valid: + raise TypeError(f'{label}: invalid implementation result') + return value + + +def _implementation_field(value, name, label): + if not isinstance(value, dict) or name not in value: + raise TypeError(f'{label}: expected a result dict containing {name}') + return value[name] + + +def _implementation_array(value, label, bytes_allowed=False, capacity=None): + if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): + raise TypeError(f'{label}: expected an array') + if capacity is not None and len(value) != capacity: + raise ValueError(f'{label}: FillArray result must match capacity {capacity}') + return list(value) + + +def _implementation_reference(value, iid, label): + if value is None: + return DynWinRTValue.null_value() + raw = getattr(value, '_obj', value) + if not isinstance(raw, DynWinRTValue): + raise TypeError(f'{label}: expected a managed WinRT value or None') + return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) + + +def _implementation_sync(value, label): + if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): + if _implementation_inspect.iscoroutine(value): + value.close() + raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') + return value + + +def _implementation_handler(handlers, name, count, label): + try: + member = _implementation_inspect.getattr_static(handlers, name) + except AttributeError: + raise TypeError(f'{label}: missing synchronous handler {name}') from None + if isinstance(member, property): + raise TypeError(f'{label}: property accessors are not callback handlers: {name}') + callback = getattr(handlers, name) + if not callable(callback): + raise TypeError(f'{label}: missing synchronous handler {name}') + if (_implementation_inspect.iscoroutinefunction(callback) + or _implementation_inspect.isasyncgenfunction(callback) + or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) + or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): + raise TypeError(f'{label}.{name}: async handlers are not supported') + try: + signature = _implementation_inspect.signature(callback) + except ValueError: + pass + else: + try: + signature.bind(*([None] * count)) + except TypeError as error: + raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None + return callback + +"#; + +fn quote(value: &str) -> String { + serde_json::to_string(value).expect("string serialization") +} + +fn handler_name(method: &ImplementationMethod) -> String { + let (prefix, raw) = match method.handler_kind { + ImplementationHandlerKind::Method => return to_snake_case(&method.name), + ImplementationHandlerKind::Getter => ("get_", "get_"), + ImplementationHandlerKind::Setter => ("set_", "put_"), + ImplementationHandlerKind::Add => ("add_", "add_"), + ImplementationHandlerKind::Remove => ("remove_", "remove_"), + }; + format!( + "{prefix}{}", + to_snake_case(method.name.strip_prefix(raw).unwrap_or(&method.name)) + ) +} + +fn input_name(name: &str, index: usize, fill: bool) -> String { + let name = if name.is_empty() { + format!("arg{index}") + } else { + to_snake_case(name) + }; + if fill { + format!("{name}_capacity") + } else { + name + } +} + +fn output_names(method: &ImplementationMethod) -> Result, String> { + let names = method + .output_names + .iter() + .map(|name| to_snake_case(name)) + .collect::>(); + if names.iter().collect::>().len() != names.len() { + return Err(format!("{} has colliding output names", method.name)); + } + Ok(names) +} + +fn collect_structs(typ: &ImplementationType, output: &mut Vec) { + match &typ.abi { + ImplementationAbi::Struct(fields) => { + if !output + .iter() + .any(|candidate| candidate.metadata == typ.metadata) + { + output.push(typ.clone()); + for field in fields { + collect_structs(field, output); + } + } + } + ImplementationAbi::Array(element) => collect_structs(element, output), + ImplementationAbi::Reference => { + if let Some(inner) = ireference_inner_type(&typ.metadata) { + collect_structs( + &validate_type(inner, false).expect("validated IReference"), + output, + ); + } + } + _ => {} + } +} + +struct Projector<'a> { + context: &'a PythonProjectionContext, + plan: &'a WinRtImplementationPlan, + prefix: String, + structs: Vec, +} + +impl Projector<'_> { + fn delegate_index(&self, typ: &TypeMeta) -> Option { + self.plan + .delegates + .iter() + .position(|delegate| delegate.typ.metadata == *typ) + } + + fn native(&self, typ: &ImplementationType) -> String { + match &typ.abi { + ImplementationAbi::Array(element) => { + format!("DynWinRTType.array_type({})", self.native(element)) + } + ImplementationAbi::Struct(fields) => { + let TypeMeta::Struct { + namespace, name, .. + } = &typ.metadata + else { + unreachable!() + }; + format!( + "DynWinRTType.struct_type({}, [{}])", + quote(&format!("{namespace}.{name}")), + fields + .iter() + .map(|field| self.native(field)) + .collect::>() + .join(", ") + ) + } + ImplementationAbi::Reference => match &typ.metadata { + TypeMeta::Interface { iid, .. } | TypeMeta::Delegate { iid, .. } => { + let kind = if self.delegate_index(&typ.metadata).is_some() + || matches!(typ.metadata, TypeMeta::Delegate { .. }) + { + "delegate" + } else { + "interface" + }; + format!("DynWinRTType.{kind}(WinGUID.parse({}))", quote(iid)) + } + TypeMeta::RuntimeClass { + namespace, + name, + default_interface, + } => { + let default = validate_type( + default_interface + .as_deref() + .expect("validated default interface"), + false, + ) + .expect("validated type"); + format!( + "DynWinRTType.runtime_class({}, {})", + quote(&format!("{namespace}.{name}")), + self.native(&default) + ) + } + TypeMeta::Parameterized { piid, args, .. } => format!( + "DynWinRTType.parameterized(WinGUID.parse({}), [{}])", + quote(piid), + args.iter() + .map(|typ| self + .native(&validate_type(typ, false).expect("validated argument"))) + .collect::>() + .join(", ") + ), + TypeMeta::Object + | TypeMeta::AsyncAction + | TypeMeta::AsyncActionWithProgress(_) + | TypeMeta::AsyncOperation(_) + | TypeMeta::AsyncOperationWithProgress(_, _) => py_dynwinrt_type(&typ.metadata), + _ => unreachable!("validated reference"), + }, + ImplementationAbi::Scalar + | ImplementationAbi::HResult + | ImplementationAbi::Enum + | ImplementationAbi::Guid + | ImplementationAbi::HString => py_dynwinrt_type(&typ.metadata), + } + } + + fn iid(&self, typ: &ImplementationType) -> String { + if typ.metadata == TypeMeta::Object { + "WinGUID.parse('af86e2e0-b12d-4c6a-9c5a-d7aa65101e90')".into() + } else { + format!("{}.iid()", self.native(typ)) + } + } + + fn annotation(&self, typ: &ImplementationType, writing: bool) -> String { + if let Some(index) = self.delegate_index(&typ.metadata) { + return format!( + "{}Delegate{index}{} | None", + self.prefix, + if writing { " | DynWinRTValue" } else { "" } + ); + } + if let Some(inner) = ireference_inner_type(&typ.metadata) { + return format!( + "{} | None", + self.annotation( + &validate_type(inner, false).expect("validated IReference"), + writing + ) + ); + } + match &typ.abi { + ImplementationAbi::Array(element) => { + let array = format!("list[{}]", self.annotation(element, writing)); + if writing && element.metadata == TypeMeta::U8 { + format!("{array} | bytes | bytearray") + } else { + array + } + } + ImplementationAbi::Struct(_) => match foundation_type(&typ.metadata) { + Some(FoundationType::DateTime) => "datetime".into(), + Some(FoundationType::TimeSpan) => "timedelta".into(), + None => self.context.reference_name_for_type(&typ.metadata), + }, + ImplementationAbi::HResult => "int".into(), + ImplementationAbi::Enum => { + if self.context.is_known_type(&typ.metadata) { + self.context.reference_name_for_type(&typ.metadata) + } else { + "int".into() + } + } + ImplementationAbi::Reference => { + let name = match &typ.metadata { + TypeMeta::RuntimeClass { .. } + | TypeMeta::Interface { .. } + | TypeMeta::Parameterized { .. } + if self.context.is_known_type(&typ.metadata) => + { + self.context.reference_name_for_type(&typ.metadata) + } + _ => "DynWinRTValue".into(), + }; + format!("{name} | None") + } + ImplementationAbi::Scalar | ImplementationAbi::Guid | ImplementationAbi::HString => { + match typ.metadata { + TypeMeta::Bool => "bool", + TypeMeta::String | TypeMeta::Char16 => "str", + TypeMeta::Guid => "UUID", + TypeMeta::F32 | TypeMeta::F64 => "float", + _ => "int", + } + .into() + } + } + } + + fn struct_symbol(&self, typ: &TypeMeta) -> String { + let TypeMeta::Struct { name, .. } = typ else { + unreachable!() + }; + if self.context.is_packaged() { + py_runtime_type_symbol(self.context, typ, name) + } else { + name.clone() + } + } + + fn read(&self, typ: &ImplementationType, value: &str) -> String { + if let Some(index) = self.delegate_index(&typ.metadata) { + return format!("_{}Delegate{index}({value})", self.prefix); + } + if let Some(inner) = ireference_inner_type(&typ.metadata) { + let inner = validate_type(inner, false).expect("validated IReference value"); + let native = format!( + "DynWinRTType.register_interface('__dynwinrt_reverse_reference_' + str(iid), iid).add_method('get_Value', DynWinRTMethodSig().add_out({})).method(6).invoke(v.cast(iid), [])", + self.native(&inner) + ); + return format!( + "(lambda v: None if v.is_null() else (lambda iid: {})({}))({value})", + self.read(&inner, &native), + self.iid(typ) + ); + } + match &typ.abi { + ImplementationAbi::Array(element) => format!( + "[{} for v in {value}.as_array().to_values()]", + self.read(element, "v") + ), + ImplementationAbi::Struct(fields) if foundation_type(&typ.metadata).is_none() => { + let TypeMeta::Struct { + fields: metadata, .. + } = &typ.metadata + else { + unreachable!() + }; + let fields = metadata + .iter() + .zip(fields) + .enumerate() + .map(|(index, (field, typ))| { + let expr = match &typ.abi { + ImplementationAbi::Reference => { + self.read(typ, &format!("s.get_object({index})")) + } + ImplementationAbi::Struct(_) => { + self.read(typ, &format!("s.get_struct({index}).to_value()")) + } + _ => super::structs::py_struct_field_getter( + self.context, + &typ.metadata, + index, + ), + }; + format!("{}={expr}", to_snake_case(&field.name)) + }) + .collect::>() + .join(", "); + format!( + "(lambda s: {}({fields}))({value}.as_struct())", + self.struct_symbol(&typ.metadata) + ) + } + ImplementationAbi::Reference if typ.metadata.is_async() => { + format!("(lambda v: None if v.is_null() else v)({value})") + } + _ => py_convert_return(value, Some(&typ.metadata), false, self.context), + } + } + + fn check_scalar(&self, typ: &ImplementationType, value: &str, label: &str) -> String { + let integer = |min: &str, max: &str| { + format!("isinstance(v, int) and not isinstance(v, bool) and {min} <= v <= {max}") + }; + let check = match &typ.metadata { + TypeMeta::Bool => "isinstance(v, bool)".into(), + TypeMeta::String => "isinstance(v, str)".into(), + TypeMeta::Char16 => "isinstance(v, str) and len(v) == 1 and ord(v) <= 65535".into(), + TypeMeta::Guid => "isinstance(v, UUID)".into(), + TypeMeta::I8 => integer("-128", "127"), TypeMeta::U8 => integer("0", "255"), + TypeMeta::I16 => integer("-32768", "32767"), TypeMeta::U16 => integer("0", "65535"), + TypeMeta::I32 | TypeMeta::Enum { .. } | TypeMeta::Struct { .. } => integer("-2147483648", "2147483647"), + TypeMeta::U32 => integer("0", "4294967295"), + TypeMeta::I64 => integer("-9223372036854775808", "9223372036854775807"), + TypeMeta::U64 => integer("0", "18446744073709551615"), + TypeMeta::F32 => "isinstance(v, (int, float)) and not isinstance(v, bool) and (not __import__('math').isfinite(v) or abs(v) <= 3.4028234663852886e38)".into(), + TypeMeta::F64 => "isinstance(v, (int, float)) and not isinstance(v, bool)".into(), + _ => unreachable!("validated scalar"), + }; + format!( + "(lambda v: _implementation_check(v, {check}, {}))({value})", + quote(label) + ) + } + + fn write( + &self, + typ: &ImplementationType, + value: &str, + label: &str, + capacity: Option<&str>, + ) -> String { + if let Some(inner) = ireference_inner_type(&typ.metadata) { + let inner = validate_type(inner, false).expect("validated IReference"); + return format!( + "(lambda v: DynWinRTValue.null_value() if v is None else _implementation_reference(v, {}, {}) if isinstance(getattr(v, '_obj', v), DynWinRTValue) else DynWinRTValue.box_reference({}, {}))({value})", + self.iid(typ), + quote(label), + self.write(&inner, "v", label, None), + self.native(&inner) + ); + } + match &typ.abi { + ImplementationAbi::Reference => format!( + "_implementation_reference({value}, {}, {})", + self.iid(typ), + quote(label) + ), + ImplementationAbi::Array(element) + if matches!(element.abi, ImplementationAbi::HResult) => + { + format!( + "DynWinRTArray.from_values([{} for v in _implementation_array({value}, {}, False, {})], {}).to_value()", + self.write(element, "v", &format!("{label}[]"), None), + quote(label), + capacity.unwrap_or("None"), + self.native(element) + ) + } + ImplementationAbi::Array(element) => format!( + "DynWinRTArray.from_object_values([{} for v in _implementation_array({value}, {}, {}, {})], {}).to_value()", + self.write(element, "v", &format!("{label}[]"), None), + quote(label), + if element.metadata == TypeMeta::U8 { + "True" + } else { + "False" + }, + capacity.unwrap_or("None"), + self.native(element) + ), + ImplementationAbi::Struct(_) => { + let index = self + .structs + .iter() + .position(|candidate| candidate == typ) + .expect("collected struct"); + format!("_{}Struct{index}({value}, {})", self.prefix, quote(label)) + } + ImplementationAbi::HResult => format!( + "DynWinRTValue.from_hresult({})", + self.check_scalar(typ, value, label) + ), + ImplementationAbi::Scalar + | ImplementationAbi::Enum + | ImplementationAbi::Guid + | ImplementationAbi::HString => { + let value = self.check_scalar(typ, value, label); + let constructor = match typ.metadata { + TypeMeta::Bool => "from_bool", + TypeMeta::I8 => "from_i8", + TypeMeta::U8 => "from_u8", + TypeMeta::I16 => "from_i16", + TypeMeta::U16 => "from_u16", + TypeMeta::Char16 => return format!("DynWinRTValue.from_u16(ord({value}))"), + TypeMeta::I32 => "from_i32", + TypeMeta::U32 => "from_u32", + TypeMeta::I64 => "from_i64", + TypeMeta::U64 => "from_u64", + TypeMeta::F32 => "from_f32", + TypeMeta::F64 => "from_f64", + TypeMeta::String => "from_hstring", + TypeMeta::Guid => { + return format!("DynWinRTValue.from_guid(_dynwinrt_guid({value}))"); + } + TypeMeta::Enum { .. } => { + return format!( + "DynWinRTValue.enum_value({}, int({value}))", + self.native(typ) + ); + } + _ => unreachable!("validated scalar"), + }; + format!("DynWinRTValue.{constructor}({value})") + } + } + } + + fn signature(&self, method: &ImplementationMethod) -> String { + let mut signature = "DynWinRTMethodSig()".to_string(); + for parameter in &method.parameters { + let add = match parameter.direction { + ParamDirection::In => "add_in", + ParamDirection::Out => "add_out", + ParamDirection::OutFill => "add_out_fill", + }; + signature.push_str(&format!(".{add}({})", self.native(¶meter.typ))); + } + if let Some(typ) = &method.return_type { + signature.push_str(&format!(".add_out({})", self.native(typ))); + } + signature + } + + fn default_value(&self, typ: &ImplementationType) -> String { + match &typ.abi { + ImplementationAbi::Reference => "DynWinRTValue.null_value()".into(), + ImplementationAbi::Struct(_) => { + format!("DynWinRTStruct.create({}).to_value()", self.native(typ)) + } + ImplementationAbi::Array(_) => unreachable!("nested arrays were rejected"), + ImplementationAbi::Enum => format!("DynWinRTValue.enum_value({}, 0)", self.native(typ)), + _ => self.write( + typ, + match typ.metadata { + TypeMeta::Bool => "False", + TypeMeta::String => "''", + TypeMeta::Char16 => "'\\0'", + TypeMeta::Guid => "UUID(int=0)", + _ => "0", + }, + "delegate fill storage", + None, + ), + } + } + + fn delegate_fill_input(&self, typ: &ImplementationType, capacity: &str) -> String { + let ImplementationAbi::Array(element) = &typ.abi else { + unreachable!("validated FillArray") + }; + format!( + "DynWinRTArray.{}([{} for _ in range(_implementation_check({capacity}, isinstance({capacity}, int) and not isinstance({capacity}, bool) and 0 <= {capacity} <= 4294967295, 'delegate capacity'))], {}).to_value()", + if matches!(element.abi, ImplementationAbi::HResult) { + "from_values" + } else { + "from_object_values" + }, + self.default_value(element), + self.native(element) + ) + } + + fn parameters(&self, method: &ImplementationMethod, writing: bool) -> Result { + let mut names = HashSet::new(); + let mut params = Vec::new(); + for parameter in &method.parameters { + if let Some(index) = parameter.input_index { + let fill = parameter.direction == ParamDirection::OutFill; + let mut name = input_name(¶meter.name, index, fill); + if name == "self" { + name.push('_'); + } + if !names.insert(name.clone()) { + return Err(format!( + "{} has colliding handler parameter names", + method.name + )); + } + params.push(format!( + "{name}: {}", + if fill { + "int".into() + } else { + self.annotation(¶meter.typ, writing) + } + )); + } + } + Ok(params.join(", ")) + } + + fn result_name(&self, method: &ImplementationMethod) -> String { + format!("{}{}Result", self.prefix, method.name) + } + + fn result_type(&self, method: &ImplementationMethod, writing: bool) -> String { + let types = method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| &p.typ) + .chain(method.return_type.iter()) + .collect::>(); + match types.as_slice() { + [] => "None".into(), + [typ] => self.annotation(typ, writing), + _ => self.result_name(method), + } + } +} + +pub(super) fn project( + context: &PythonProjectionContext, + iface: &InterfaceMeta, +) -> ImplementationProjection { + project_implementation(iface).and_then(|plan| { + for method in &iface.methods { + let name = if method.is_property_getter { + method.name.strip_prefix("get_").unwrap_or(&method.name) + } else if method.is_property_setter { + method.name.strip_prefix("put_").unwrap_or(&method.name) + } else { &method.name }; + if ["implementation", "implement", "from_implementation"].contains(&to_snake_case(name).as_str()) { + return Err(format!("{} cannot be implemented: factory name conflicts with outbound member {name}", plan.name)); + } + } + project_validated(context, iface, &plan) + }) + .unwrap_or_else(|reason| ImplementationProjection { + factory_body: format!( + " @staticmethod\n def implementation(handlers):\n raise TypeError({0})\n\n @staticmethod\n def implement(handlers, *additional):\n raise TypeError({0})\n\n", quote(&reason) + ), + factory_declarations: format!(" # {}\n", reason.replace('\n', " ")), + ..Default::default() + }) +} + +fn project_validated( + context: &PythonProjectionContext, + iface: &InterfaceMeta, + plan: &WinRtImplementationPlan, +) -> Result { + let mut structs = Vec::new(); + for method in plan + .methods + .iter() + .chain(plan.delegates.iter().map(|delegate| &delegate.invoke)) + { + for typ in method + .parameters + .iter() + .map(|parameter| ¶meter.typ) + .chain(method.return_type.iter()) + { + collect_structs(typ, &mut structs); + } + } + let projector = Projector { + context, + plan, + structs, + prefix: format!("{}Implementation", iface.name), + }; + let mut support = String::from(HELPERS); + let mut declarations = String::new(); + let mut result_names = HashSet::new(); + for (result_name, method) in plan + .methods + .iter() + .map(|method| (projector.result_name(method), method)) + .chain(plan.delegates.iter().enumerate().map(|(index, delegate)| { + ( + format!("{}Delegate{index}Result", projector.prefix), + &delegate.invoke, + ) + })) + { + if method.output_count > 1 { + if !result_names.insert(result_name.clone()) { + return Err(format!( + "{} cannot be implemented: result type name collision {result_name}", + plan.name + )); + } + declarations.push_str(&format!("\nclass {result_name}(TypedDict):\n")); + let types = method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| &p.typ) + .chain(method.return_type.iter()); + for (name, typ) in output_names(method)?.iter().zip(types) { + declarations.push_str(&format!( + " {name}: {}\n", + projector.annotation(typ, true) + )); + } + } + } + for (index, typ) in projector.structs.iter().enumerate() { + support.push_str(&format!( + "\ndef _{}Struct{index}(value, label):\n", + projector.prefix + )); + if let Some(kind) = foundation_type(&typ.metadata) { + let TypeMeta::Struct { name, .. } = &typ.metadata else { + unreachable!() + }; + let annotation = match kind { + FoundationType::DateTime => "datetime", + FoundationType::TimeSpan => "timedelta", + }; + support.push_str(&format!( + " _implementation_check(value, isinstance(value, {annotation}), label)\n return _pack_{}(value).to_value()\n\n", + to_snake_case(name) + )); + continue; + } + support.push_str(&format!( + " _implementation_check(value, isinstance(value, {}), label)\n s = DynWinRTStruct.create({})\n", + projector.struct_symbol(&typ.metadata), projector.native(typ) + )); + let ( + ImplementationAbi::Struct(fields), + TypeMeta::Struct { + fields: metadata, .. + }, + ) = (&typ.abi, &typ.metadata) + else { + unreachable!() + }; + for (index, (field, typ)) in metadata.iter().zip(fields).enumerate() { + let field_name = to_snake_case(&field.name); + let value = format!("value.{field_name}"); + let setter = match &typ.abi { + ImplementationAbi::Reference => format!( + "s.set_object({index}, {})", + projector.write(typ, &value, &field_name, None) + ), + ImplementationAbi::Struct(_) => format!( + "s.set_struct({index}, {}.as_struct())", + projector.write(typ, &value, &field_name, None) + ), + _ => super::structs::py_struct_field_setter( + &typ.metadata, + index, + &projector.check_scalar(typ, &value, &field_name), + ), + }; + support.push_str(&format!(" {setter}\n")); + } + support.push_str(" return s.to_value()\n\n"); + } + for (index, delegate) in plan.delegates.iter().enumerate() { + let method = &delegate.invoke; + let params = projector.parameters(method, true)?; + let comma = if params.is_empty() { "" } else { ", " }; + declarations.push_str(&format!( + "\nclass {}Delegate{index}(Protocol):\n @property\n def _obj(self) -> DynWinRTValue: ...\n def __call__(self{comma}{params}) -> {}: ...\n", + projector.prefix, if method.output_count > 1 { format!("{}Delegate{index}Result", projector.prefix) } else { projector.result_type(method, false) } + )); + let args = method + .parameters + .iter() + .filter_map(|parameter| { + parameter.input_index.map(|index| { + if parameter.direction == ParamDirection::OutFill { + projector.delegate_fill_input(¶meter.typ, &format!("args[{index}]")) + } else { + projector.write( + ¶meter.typ, + &format!("args[{index}]"), + "delegate argument", + None, + ) + } + }) + }) + .collect::>() + .join(", "); + let outputs = method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| &p.typ) + .chain(method.return_type.iter()) + .enumerate() + .map(|(index, typ)| projector.read(typ, &format!("result[{index}]"))) + .collect::>(); + let returned = match outputs.as_slice() { + [] => "None".into(), + [value] => value.clone(), + _ => format!( + "{{ {} }}", + output_names(method)? + .iter() + .zip(outputs) + .map(|(name, expr)| format!("{}: {expr}", quote(name))) + .collect::>() + .join(", ") + ), + }; + support.push_str(&format!( + "\ndef _{}Delegate{index}(value):\n if value.is_null():\n return None\n def callback(*args):\n if len(args) != {}:\n raise TypeError('delegate argument count mismatch')\n result = value.invoke_delegate({}, {}, [{args}])\n return {returned}\n callback._obj = value\n return callback\n\n", + projector.prefix, method.input_count, projector.iid(&delegate.typ), projector.signature(method) + )); + } + declarations.push_str(&format!( + "\nclass {}Handlers(Protocol):\n \"\"\"Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.\"\"\"\n", iface.name + )); + let mut handlers = HashSet::new(); + let mut bindings = Vec::new(); + let mut dispatch = String::new(); + let mut descriptors = Vec::new(); + for method in &plan.methods { + let handler = handler_name(method); + if !handlers.insert(handler.clone()) { + return Err(format!( + "{} cannot be implemented: handler name collision for {handler}", + plan.name + )); + } + let params = projector.parameters(method, false)?; + declarations.push_str(&format!( + " def {handler}(self{}{}) -> {}: ...\n", + if params.is_empty() { "" } else { ", " }, + params, + projector.result_type(method, true) + )); + let slot = method.vtable_index; + bindings.push(format!( + " h{slot} = _implementation_handler(handlers, {}, {}, {})", + quote(&handler), + method.input_count, + quote(&plan.name) + )); + descriptors.push(format!( + "DynWinRTImplementationMethod({}, {slot}, {})", + quote(&method.name), + projector.signature(method) + )); + let args = method + .parameters + .iter() + .filter_map(|parameter| { + parameter.input_index.map(|index| { + if parameter.direction == ParamDirection::OutFill { + format!("args[{index}].to_u32()") + } else { + projector.read(¶meter.typ, &format!("args[{index}]")) + } + }) + }) + .collect::>() + .join(", "); + let label = format!("{}.{}", plan.name, handler); + dispatch.push_str(&format!( + " if vtable_index == {slot}:\n if len(args) != {}:\n raise TypeError('implementation argument count mismatch')\n result = _implementation_sync(h{slot}({args}), {})\n", method.input_count, quote(&label) + )); + let names = output_names(method)?; + let mut outputs = Vec::new(); + for (index, (typ, fill)) in method + .parameters + .iter() + .filter(|p| p.output_index.is_some()) + .map(|p| { + ( + &p.typ, + if p.direction == ParamDirection::OutFill { + p.input_index + } else { + None + }, + ) + }) + .chain(method.return_type.iter().map(|typ| (typ, None))) + .enumerate() + { + let value = if method.output_count == 1 { + "result".into() + } else { + format!( + "_implementation_field(result, {}, {})", + quote(&names[index]), + quote(&label) + ) + }; + let capacity = fill.map(|index| format!("args[{index}].to_u32()")); + outputs.push(projector.write( + typ, + &value, + &format!("{label}.{}", names[index]), + capacity.as_deref(), + )); + } + if outputs.is_empty() { + dispatch.push_str(&format!( + " if result is not None:\n raise TypeError({})\n", + quote(&format!("{label}: void handler must return None")) + )); + } + dispatch.push_str(&format!( + " return [{}]\n", + outputs.join(", ") + )); + } + support.push_str(&format!( + "\n_implementation_plan = None\n\ndef _get_implementation_plan():\n global _implementation_plan\n if _implementation_plan is None:\n _implementation_plan = DynWinRTInterfacePlan.create({}, DynWinRTType.interface(WinGUID.parse({})), [\n {}\n ], [{}])\n return _implementation_plan\n\n", + quote(&plan.name), quote(&plan.iid), descriptors.join(",\n "), + plan.required_interfaces.iter().map(|typ| projector.iid(typ)).collect::>().join(", ") + )); + if !plan.delegates.is_empty() { + bindings.push(" if not callable(getattr(DynWinRTValue, 'invoke_delegate', None)):\n raise TypeError('this interface requires WinRT delegate invocation support in the runtime')".into()); + } + let mut factory_body = format!( + " @staticmethod\n def implementation(handlers: {}Handlers) -> DynWinRTImplementationDescriptor:\n{}\n plan = _get_implementation_plan()\n def dispatch(vtable_index, args):\n if not isinstance(args, list):\n raise TypeError('implementation arguments must be a list')\n{dispatch} raise ValueError('unknown implementation vtable slot')\n return DynWinRTImplementationDescriptor(plan, dispatch)\n\n @classmethod\n def implement(cls, handlers: {}Handlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation:\n descriptors = (cls.implementation(handlers), *additional)\n if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors):\n raise TypeError('invalid implementation descriptor')\n plans = [descriptor.plan for descriptor in descriptors]\n dispatchers = tuple(descriptor.dispatch for descriptor in descriptors)\n def callback(interface_index, vtable_index, args):\n if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers):\n raise ValueError('unknown implementation interface index')\n return dispatchers[interface_index](vtable_index, args)\n return DynWinRTImplementation.create(plans, callback)\n\n", + iface.name, + bindings.join("\n"), + iface.name + ); + factory_body.push_str(&format!( + " @classmethod\n def from_implementation(cls, owner: DynWinRTImplementation) -> '{}':\n \"\"\"Query an independently owned view, tracked by the current lifetime scope.\"\"\"\n if not isinstance(owner, DynWinRTImplementation):\n raise TypeError('from_implementation requires a DynWinRTImplementation controller')\n value = owner.to_value()\n try:\n native = value.cast(IID_{})\n try:\n view = object.__new__(cls)\n cls._set_native(view, native, cache=False)\n return view\n except BaseException:\n native.release()\n raise\n finally:\n value.release()\n\n", + iface.name, iface.name + )); + let requirements = if plan.required_interfaces.is_empty() { + String::new() + } else { + format!( + " # Required QI views must be supplied as additional descriptors: {}.\n", + plan.required_interfaces + .iter() + .map(|typ| typ + .metadata + .type_identity() + .definition_name() + .unwrap_or("interface") + .to_string()) + .collect::>() + .join(", ") + ) + }; + let factory_declarations = format!( + "{requirements} def implementation(cls, handlers: {}Handlers) -> DynWinRTImplementationDescriptor: ...\n def implement(cls, handlers: {}Handlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ...\n def from_implementation(cls, owner: DynWinRTImplementation) -> {}: ...\n\n", + iface.name, iface.name, iface.name + ); + let mut exports = vec![format!("{}Handlers", iface.name)]; + exports.extend( + (0..plan.delegates.len()).map(|index| format!("{}Delegate{index}", projector.prefix)), + ); + exports.extend(result_names); + exports.sort(); + Ok(ImplementationProjection { + support_code: support, + declarations, + factory_body, + factory_declarations, + supported: true, + exports, + }) +} + +pub(super) fn exports(context: &PythonProjectionContext, iface: &InterfaceMeta) -> Vec { + let mut projected = iface.clone(); + projected.name = context.projected_name_for_interface(iface); + project(context, &projected).exports +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs index f8116d7e..78924041 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs @@ -4,6 +4,7 @@ pub(crate) mod collections; mod docs; mod generator; +mod implementation; pub(crate) mod method; pub(crate) mod naming; mod native_types; diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 72caf6d0..26421f42 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -372,10 +372,24 @@ fn qualified_module_name( } fn public_module_name(identity: &PythonTypeIdentity, projected_name: &str) -> String { - shorten_module_component_with_hash_input( - &to_snake_case(projected_name), - &identity.canonical_key(), - ) + let namespace = identity.namespace().unwrap_or_default(); + let qualified = qualified_module_name(identity, namespace, projected_name); + let prefix = python_namespace_segments(namespace).join("__"); + if prefix.is_empty() { + return qualified; + } + // Budget the namespace as well as the basename. Otherwise a readable flat + // module can have a facade path that Windows Python cannot open. + qualified + .strip_prefix(&format!("{prefix}__")) + .filter(|name| !name.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| { + format!( + "type_{:016x}", + stable_module_hash(&identity.canonical_key()) + ) + }) } /// Explicit, immutable naming and lookup state for one Python projection. @@ -890,6 +904,84 @@ mod tests { assert!( context.public_module(&identity).chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH ); + assert_eq!( + context.public_module(&identity), + implementation + .strip_prefix("windows__foundation__") + .unwrap() + ); + assert!( + context.public_qualified_module(&identity).chars().count() + <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + ); + } + + #[test] + fn background_event_delegate_facade_uses_the_qualified_module_budget() { + let identity = TypeIdentity::closed_generic( + TypeIdentityKind::Delegate, + "Windows.Foundation", + "TypedEventHandler", + [ + TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.ApplicationModel.Background", + "BackgroundTaskRegistrationGroup", + ), + TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.ApplicationModel.Activation", + "BackgroundActivatedEventArgs", + ), + ], + ); + let context = PythonProjectionContext::packaged_with_ambiguities( + [identity.clone()], + ["BackgroundActivatedEventArgs".to_string()], + ) + .unwrap(); + let implementation = context.implementation_module(&identity); + let public = context.public_module(&identity); + assert_eq!( + public, + implementation + .strip_prefix("windows__foundation__") + .unwrap() + ); + assert!( + context.public_qualified_module(&identity).len() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + ); + assert!(public.starts_with("typed_event_handler_background_task_registration_group")); + assert_eq!(public, context.public_module(&identity)); + assert_ne!( + public, + context.public_module(&TypeIdentity::closed_generic( + TypeIdentityKind::Delegate, + "Windows.Foundation", + "TypedEventHandler", + [ + TypeIdentity::Primitive { + name: "Object".into() + }, + TypeIdentity::Primitive { + name: "Object".into() + } + ], + )) + ); + } + + #[test] + fn facade_shortening_keeps_a_valid_name_when_namespace_uses_the_budget() { + let identity = TypeIdentity::named( + TypeIdentityKind::Interface, + "VeryLongNamespace".repeat(12), + "IValue", + ); + let context = PythonProjectionContext::packaged([identity.clone()]).unwrap(); + let public = context.public_module(&identity); + assert!(public.starts_with("type_"), "{public}"); + assert_eq!(public.len(), 5 + MODULE_HASH_HEX_LENGTH); } #[test] diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs index 98e25700..a472218a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs @@ -399,7 +399,7 @@ pub(crate) fn py_wrap_arg(name: &str, typ: &TypeMeta) -> String { TypeMeta::Struct { name: struct_name, .. } if struct_name == "HResult" => { - format!("DynWinRTValue.from_i32({})", name) + format!("DynWinRTValue.from_hresult({})", name) } TypeMeta::Struct { name: struct_name, .. @@ -438,7 +438,7 @@ pub(crate) fn py_wrap_native_value(name: &str, typ: &TypeMeta) -> String { TypeMeta::Struct { name: struct_name, .. } if struct_name == "HResult" => { - format!("DynWinRTValue.from_i32({})", name) + format!("DynWinRTValue.from_hresult({})", name) } TypeMeta::Struct { name: struct_name, .. diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 0987b796..45f70aeb 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -211,6 +211,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf out.push_str(&format!("{}_PARAM_TYPES: list[DynWinRTType]\n", iface.name)); return out; } + let implementation = super::implementation::project(context, iface); let used_structs = collect_used_structs_from_iface(iface); @@ -218,6 +219,10 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); out.push_str(IMPORT_LINE); + if implementation.supported { + out.push_str(super::implementation::IMPORTS); + out.push_str("from abc import ABCMeta\n"); + } let collection_kind = interface_kind(iface); let is_protocol = collection_kind.is_none(); out.push_str("from typing import Protocol, Self, TypeVar\n"); @@ -242,7 +247,14 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf let delegate_names = super::collect_referenced_delegate_names(&iface.methods, context); let runtime_delegate_names = super::collect_runtime_delegate_names(&iface.methods, context); - let collection_identities = collect_used_generic_identities_from_methods(&iface.methods); + let mut collection_identities = collect_used_generic_identities_from_methods(&iface.methods); + for delegate in &iface.implementation_metadata.delegates { + collection_identities.extend(collect_used_generic_identities_from_methods( + std::slice::from_ref(&delegate.invoke), + )); + } + collection_identities.sort(); + collection_identities.dedup(); let observable_vector = observable_vector_identity(iface); for identity in &collection_identities { let identity = context.normalize_identity(identity); @@ -348,6 +360,13 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf } } + out.push_str(&implementation.declarations); + let implementation_metaclass = format!("_{}ImplementationFactory", iface.name); + if implementation.supported { + out.push_str(&format!("\nclass {implementation_metaclass}(ABCMeta):\n")); + out.push_str(&implementation.factory_declarations); + } + let collection_base = collection_kind .and_then(abc_name) @@ -380,6 +399,9 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf } let mut seen_bases = HashSet::new(); bases.retain(|base| seen_bases.insert(base.clone())); + if implementation.supported { + bases.push(format!("metaclass={implementation_metaclass}")); + } if bases.is_empty() { out.push_str(&format!("\nclass {}:\n", iface.name)); } else { @@ -393,6 +415,9 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf }, " ", )); + if !implementation.supported { + out.push_str(&implementation.factory_declarations); + } if !is_protocol { out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n"); } @@ -1590,6 +1615,9 @@ pub fn generate_index_stub( module = module, iname = name )); + for helper in super::implementation::exports(context, iface) { + out.push_str(&format!("from .{module} import {helper} as {helper}\n")); + } } } @@ -1659,6 +1687,12 @@ pub fn generate_public_index_stub( name, name )); + for helper in super::implementation::exports(context, interface) { + out.push_str(&format!( + "from .{} import {helper} as {helper}\n", + context.public_qualified_module(&identity), + )); + } } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation.rs new file mode 100644 index 00000000..3f998e35 --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation.rs @@ -0,0 +1,797 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Authoritative, language-neutral reverse WinRT call contracts. +//! +//! Requirements are independent QI views, never inherited vtable prefixes. +//! Parameter order is native metadata order; output order is explicit out +//! parameters followed by the logical return. + +use std::collections::HashSet; + +use crate::meta::{InterfaceMeta, ParamDirection}; +use crate::types::TypeMeta; + +const IUNKNOWN: &str = "00000000-0000-0000-c000-000000000046"; +const IINSPECTABLE: &str = "af86e2e0-b12d-4c6a-9c5a-d7aa65101e90"; + +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum ImplementationAbi { + Scalar, + HResult, + Enum, + Guid, + HString, + Reference, + Struct(Vec), + Array(Box), +} + +/// The metadata is retained for language projection, but only after its full +/// native shape has passed validation. Renderers cannot see this type. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct ImplementationType { + pub metadata: TypeMeta, + pub abi: ImplementationAbi, +} + +#[derive(Clone, Debug)] +pub(crate) struct ImplementationParameter { + pub name: String, + pub typ: ImplementationType, + pub direction: ParamDirection, + pub input_index: Option, + pub output_index: Option, +} + +#[derive(Clone, Debug)] +pub(crate) struct ImplementationMethod { + pub name: String, + pub vtable_index: usize, + pub parameters: Vec, + pub return_type: Option, + pub input_count: usize, + pub output_count: usize, + pub output_names: Vec, + pub handler_kind: ImplementationHandlerKind, +} + +#[derive(Clone, Copy, Debug)] +pub(crate) enum ImplementationHandlerKind { + Method, + Getter, + Setter, + Add, + Remove, +} + +#[derive(Clone, Debug)] +pub(crate) struct WinRtImplementationPlan { + pub name: String, + pub iid: String, + pub required_interfaces: Vec, + pub methods: Vec, + pub delegates: Vec, +} + +#[derive(Clone, Debug)] +pub(crate) struct ImplementationDelegate { + pub typ: ImplementationType, + pub invoke: ImplementationMethod, +} + +fn valid_iid(iid: &str) -> bool { + iid.len() == 36 + && iid.chars().enumerate().all(|(index, ch)| { + if matches!(index, 8 | 13 | 18 | 23) { + ch == '-' + } else { + ch.is_ascii_hexdigit() + } + }) + && iid != "00000000-0000-0000-0000-000000000000" +} + +pub(crate) fn validate_type(typ: &TypeMeta, in_struct: bool) -> Result { + let abi = match typ { + TypeMeta::Bool + | TypeMeta::I8 + | TypeMeta::U8 + | TypeMeta::I16 + | TypeMeta::U16 + | TypeMeta::Char16 + | TypeMeta::I32 + | TypeMeta::U32 + | TypeMeta::I64 + | TypeMeta::U64 + | TypeMeta::F32 + | TypeMeta::F64 => ImplementationAbi::Scalar, + TypeMeta::Guid => ImplementationAbi::Guid, + TypeMeta::String => ImplementationAbi::HString, + TypeMeta::Object | TypeMeta::AsyncAction => ImplementationAbi::Reference, + TypeMeta::Interface { + namespace, + name, + iid, + } + | TypeMeta::Delegate { + namespace, + name, + iid, + } => { + if !valid_iid(iid) { + return Err(format!( + "{namespace}.{name} has an unresolved or invalid IID" + )); + } + if name.contains('`') { + return Err(format!("{namespace}.{name} is an open generic reference")); + } + ImplementationAbi::Reference + } + TypeMeta::RuntimeClass { + namespace, + name, + default_interface, + } => { + let interface = default_interface + .as_deref() + .ok_or_else(|| format!("{namespace}.{name} has no resolved default interface"))?; + let resolved = validate_type(interface, false)?; + if !matches!(resolved.abi, ImplementationAbi::Reference) + || matches!(interface, TypeMeta::Object | TypeMeta::RuntimeClass { .. }) + { + return Err(format!( + "{namespace}.{name} has an invalid default interface" + )); + } + ImplementationAbi::Reference + } + TypeMeta::Parameterized { + namespace, + name, + piid, + args, + } => { + if !valid_iid(piid) || args.is_empty() { + return Err(format!( + "{namespace}.{name} has no resolved closed generic IID" + )); + } + if namespace == "Windows.Foundation" + && name.split('`').next() == Some("IReference") + && !piid.eq_ignore_ascii_case("61c17706-2d65-11e0-9ae8-d48564015472") + { + return Err("IReference metadata has an incompatible PIID".into()); + } + if let Some((_, arity)) = name.rsplit_once('`') { + if arity.parse::().ok() != Some(args.len()) { + return Err(format!( + "{namespace}.{name} has incomplete generic arguments" + )); + } + } + for arg in args { + if matches!(arg, TypeMeta::Array(_)) { + return Err(format!( + "{namespace}.{name} has an unsupported array type argument" + )); + } + validate_type(arg, false)?; + } + if piid.eq_ignore_ascii_case("61c17706-2d65-11e0-9ae8-d48564015472") + && (args.len() != 1 + || matches!( + validate_type(&args[0], false)?.abi, + ImplementationAbi::Reference | ImplementationAbi::Array(_) + )) + { + return Err("IReference requires one supported value type".into()); + } + ImplementationAbi::Reference + } + TypeMeta::AsyncOperation(result) | TypeMeta::AsyncActionWithProgress(result) => { + validate_type(result, false)?; + if matches!(result.as_ref(), TypeMeta::Array(_)) { + return Err("async interfaces cannot have array type arguments".into()); + } + ImplementationAbi::Reference + } + TypeMeta::AsyncOperationWithProgress(result, progress) => { + for arg in [result, progress] { + validate_type(arg, false)?; + if matches!(arg.as_ref(), TypeMeta::Array(_)) { + return Err("async interfaces cannot have array type arguments".into()); + } + } + ImplementationAbi::Reference + } + TypeMeta::Enum { + namespace, + name, + underlying, + .. + } => { + if !matches!(underlying.as_ref(), TypeMeta::I32 | TypeMeta::U32) { + return Err(format!( + "{namespace}.{name} does not have a 32-bit WinRT enum ABI" + )); + } + ImplementationAbi::Enum + } + TypeMeta::Struct { + namespace, + name, + fields, + } if namespace == "Windows.Foundation" && name == "HResult" => { + if fields.len() != 1 || fields[0].typ != TypeMeta::I32 { + return Err("Windows.Foundation.HResult has an incomplete scalar layout".into()); + } + ImplementationAbi::HResult + } + TypeMeta::Struct { + namespace, + name, + fields, + } => { + if fields.is_empty() { + return Err(format!("{namespace}.{name} has no complete struct layout")); + } + let mut names = HashSet::new(); + let mut validated = Vec::new(); + for field in fields { + if field.name.is_empty() || !names.insert(&field.name) { + return Err(format!("{namespace}.{name} has ambiguous struct fields")); + } + validated + .push(validate_type(&field.typ, true).map_err(|reason| { + format!("{namespace}.{name}.{}: {reason}", field.name) + })?); + } + ImplementationAbi::Struct(validated) + } + TypeMeta::Array(element) => { + if in_struct || matches!(element.as_ref(), TypeMeta::Array(_)) { + return Err( + "nested arrays and array struct fields have no supported WinRT layout".into(), + ); + } + ImplementationAbi::Array(Box::new(validate_type(element, false)?)) + } + }; + Ok(ImplementationType { + metadata: typ.clone(), + abi, + }) +} + +pub(crate) fn project_implementation( + iface: &InterfaceMeta, +) -> Result { + let full_name = format!("{}.{}", iface.namespace, iface.name); + let fail = |reason: String| format!("{full_name} cannot be implemented: {reason}"); + if iface.is_delegate() { + return Err(fail( + "delegates use their separate IUnknown-rooted callback API".into(), + )); + } + if iface.generic_piid.is_some() + || iface.generic_name.is_some() + || !iface.generic_args.is_empty() + || iface.implementation_metadata.is_generic_definition + || iface.name.contains('`') + { + return Err(fail( + "generic interface implementations are not supported".into(), + )); + } + if !valid_iid(&iface.iid) { + return Err(fail("interface IID is unresolved or invalid".into())); + } + if [IUNKNOWN, IINSPECTABLE] + .iter() + .any(|iid| iface.iid.eq_ignore_ascii_case(iid)) + { + return Err(fail( + "IUnknown and IInspectable are reserved host interfaces".into(), + )); + } + if !iface.implementation_metadata.diagnostics.is_empty() { + return Err(fail(iface.implementation_metadata.diagnostics.join("; "))); + } + let mut methods = Vec::new(); + for (position, method) in iface.methods.iter().enumerate() { + if method.vtable_index != 6 + position { + return Err(fail(format!( + "{} must occupy WinRT slot {}, not {}; incomplete or non-WinRT vtable", + method.name, + 6 + position, + method.vtable_index + ))); + } + if method.name.is_empty() || method.name.starts_with('.') { + return Err(fail(format!("unsupported method {}", method.name))); + } + let mut parameters = Vec::new(); + let mut input_count = 0; + let mut output_count = 0; + for parameter in &method.params { + let typ = validate_type(¶meter.typ, false).map_err(|reason| { + fail(format!( + "{} parameter {}: {reason}", + method.name, parameter.name + )) + })?; + if parameter.direction == ParamDirection::OutFill + && !matches!(typ.abi, ImplementationAbi::Array(_)) + { + return Err(fail(format!( + "{} parameter {}: FillArray requires an array", + method.name, parameter.name + ))); + } + let input_index = if parameter.direction != ParamDirection::Out { + let index = input_count; + input_count += 1; + Some(index) + } else { + None + }; + let output_index = if parameter.direction != ParamDirection::In { + let index = output_count; + output_count += 1; + Some(index) + } else { + None + }; + parameters.push(ImplementationParameter { + name: parameter.name.clone(), + typ, + direction: parameter.direction.clone(), + input_index, + output_index, + }); + } + let return_type = method + .return_type + .as_ref() + .map(|typ| { + validate_type(typ, false) + .map_err(|reason| fail(format!("{} return: {reason}", method.name))) + }) + .transpose()?; + output_count += usize::from(return_type.is_some()); + let mut output_names = parameters + .iter() + .filter_map(|parameter| { + parameter.output_index.map(|index| { + if parameter.name.is_empty() { + format!("out{index}") + } else { + parameter.name.clone() + } + }) + }) + .collect::>(); + if return_type.is_some() { + let occupied = output_names + .iter() + .map(|name| name.to_lowercase()) + .collect::>(); + let mut result_name = "result".to_string(); + while occupied.contains(&result_name) { + result_name.push('_'); + } + output_names.push(result_name); + } + let kind_count = [ + method.is_property_getter, + method.is_property_setter, + method.is_event_add, + method.is_event_remove, + ] + .into_iter() + .filter(|flag| *flag) + .count(); + if kind_count > 1 { + return Err(fail(format!( + "{} has conflicting method semantics", + method.name + ))); + } + methods.push(ImplementationMethod { + name: method.name.clone(), + vtable_index: method.vtable_index, + parameters, + return_type, + input_count, + output_count, + output_names, + handler_kind: if method.is_property_getter { + ImplementationHandlerKind::Getter + } else if method.is_property_setter { + ImplementationHandlerKind::Setter + } else if method.is_event_add { + ImplementationHandlerKind::Add + } else if method.is_event_remove { + ImplementationHandlerKind::Remove + } else { + ImplementationHandlerKind::Method + }, + }); + } + let mut required_interfaces = Vec::new(); + let mut seen = HashSet::new(); + for typ in iface + .base_interfaces + .iter() + .chain(&iface.implementation_metadata.required_interfaces) + { + let required = validate_type(typ, false) + .map_err(|reason| fail(format!("required interface: {reason}")))?; + if let TypeMeta::Parameterized { + namespace, name, .. + } = typ + { + return Err(fail(format!( + "required generic interface {namespace}.{name} cannot be implemented by standalone factories" + ))); + } + if !matches!( + typ, + TypeMeta::Interface { .. } | TypeMeta::Parameterized { .. } + ) { + return Err(fail( + "required interface has no independent interface view".into(), + )); + } + if let TypeMeta::Interface { iid, .. } = typ { + if [IUNKNOWN, IINSPECTABLE] + .iter() + .any(|reserved| iid.eq_ignore_ascii_case(reserved)) + { + continue; + } + if iid.eq_ignore_ascii_case(&iface.iid) { + return Err(fail("cyclic required interface closure".into())); + } + } + if seen.insert(typ.type_identity()) { + required_interfaces.push(required); + } + } + let mut delegates = Vec::new(); + for delegate in &iface.implementation_metadata.delegates { + let typ = validate_type(&delegate.typ, false).map_err(&fail)?; + // Invoke uses slot 3, but the value and output contracts are identical + // to WinRT methods. It is not a published interface implementation. + let mut method = delegate.invoke.clone(); + method.vtable_index = 6; + let delegate_iface = InterfaceMeta { + namespace: iface.namespace.clone(), + name: "DelegateInvokeContract".into(), + iid: iface.iid.clone(), + methods: vec![method], + ..Default::default() + }; + let mut invoke = project_implementation(&delegate_iface)?.methods.remove(0); + invoke.vtable_index = 3; + delegates.push(ImplementationDelegate { typ, invoke }); + } + Ok(WinRtImplementationPlan { + name: full_name, + iid: iface.iid.clone(), + required_interfaces, + methods, + delegates, + }) +} + +/// Final language projection. ABI validation and all conversions have already +/// happened before a renderer receives these strings. +#[derive(Clone, Debug, Default)] +pub(crate) struct ImplementationProjection { + pub support_code: String, + pub declarations: String, + pub factory_body: String, + pub factory_declarations: String, + pub supported: bool, + pub exports: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::meta::{MethodMeta, ParamMeta}; + use crate::types::FieldMeta; + + fn interface(typ: TypeMeta) -> InterfaceMeta { + InterfaceMeta { + namespace: "Tests".into(), + name: "IContract".into(), + iid: "119ade03-d016-4c34-8813-4c2c3678dada".into(), + methods: vec![MethodMeta { + name: "RoundTrip".into(), + vtable_index: 6, + params: vec![ParamMeta { + name: "value".into(), + typ: typ.clone(), + direction: ParamDirection::In, + }], + return_type: Some(typ), + ..Default::default() + }], + ..Default::default() + } + } + + fn managed() -> TypeMeta { + TypeMeta::Interface { + namespace: "Tests".into(), + name: "IManaged".into(), + iid: "12ace702-8ff7-4e34-95c4-04e13f64c885".into(), + } + } + + #[test] + fn implementation_matrix_validates_scalar_reference_struct_and_array_contracts() { + let structure = TypeMeta::Struct { + namespace: "Tests".into(), + name: "Record".into(), + fields: vec![ + FieldMeta { + name: "Text".into(), + typ: TypeMeta::String, + }, + FieldMeta { + name: "Reference".into(), + typ: managed(), + }, + FieldMeta { + name: "Value".into(), + typ: TypeMeta::Struct { + namespace: "Tests".into(), + name: "Inner".into(), + fields: vec![FieldMeta { + name: "Number".into(), + typ: TypeMeta::U64, + }], + }, + }, + ], + }; + let enum_type = TypeMeta::Enum { + namespace: "Tests".into(), + name: "Choice".into(), + underlying: Box::new(TypeMeta::I32), + members: vec![], + is_flags: false, + doc: None, + deprecated: None, + }; + let types = vec![ + TypeMeta::Bool, + TypeMeta::I8, + TypeMeta::U8, + TypeMeta::I16, + TypeMeta::U16, + TypeMeta::Char16, + TypeMeta::I32, + TypeMeta::U32, + TypeMeta::I64, + TypeMeta::U64, + TypeMeta::F32, + TypeMeta::F64, + TypeMeta::String, + TypeMeta::Guid, + TypeMeta::Object, + TypeMeta::AsyncAction, + TypeMeta::AsyncOperation(Box::new(TypeMeta::String)), + TypeMeta::AsyncActionWithProgress(Box::new(TypeMeta::U32)), + TypeMeta::AsyncOperationWithProgress(Box::new(TypeMeta::Guid), Box::new(TypeMeta::U32)), + enum_type, + managed(), + structure, + TypeMeta::RuntimeClass { + namespace: "Tests".into(), + name: "Managed".into(), + default_interface: Some(Box::new(managed())), + }, + TypeMeta::Parameterized { + namespace: "Windows.Foundation".into(), + name: "IReference`1".into(), + piid: "61c17706-2d65-11e0-9ae8-d48564015472".into(), + args: vec![TypeMeta::I32], + }, + TypeMeta::Struct { + namespace: "Windows.Foundation".into(), + name: "HResult".into(), + fields: vec![FieldMeta { + name: "Value".into(), + typ: TypeMeta::I32, + }], + }, + ]; + for typ in types { + let plan = project_implementation(&interface(typ.clone())) + .unwrap_or_else(|e| panic!("{typ:?}: {e}")); + assert_eq!(plan.methods[0].input_count, 1); + assert_eq!(plan.methods[0].output_count, 1); + project_implementation(&interface(TypeMeta::Array(Box::new(typ)))) + .expect("supported array element"); + } + } + + #[test] + fn implementation_keeps_native_parameter_order_and_explicit_output_order() { + let mut iface = interface(TypeMeta::I32); + iface.methods[0].params = vec![ + ParamMeta { + name: "firstOut".into(), + typ: TypeMeta::String, + direction: ParamDirection::Out, + }, + ParamMeta { + name: "input".into(), + typ: TypeMeta::Bool, + direction: ParamDirection::In, + }, + ParamMeta { + name: "buffer".into(), + typ: TypeMeta::Array(Box::new(TypeMeta::Guid)), + direction: ParamDirection::OutFill, + }, + ParamMeta { + name: "lastInput".into(), + typ: TypeMeta::U64, + direction: ParamDirection::In, + }, + ParamMeta { + name: "lastOut".into(), + typ: managed(), + direction: ParamDirection::Out, + }, + ]; + let plan = project_implementation(&iface).unwrap(); + let method = &plan.methods[0]; + assert_eq!(method.vtable_index, 6); + assert_eq!(method.input_count, 3); + assert_eq!(method.output_count, 4); + assert_eq!( + method.output_names, + ["firstOut", "buffer", "lastOut", "result"] + ); + assert_eq!( + method + .parameters + .iter() + .map(|p| p.input_index) + .collect::>(), + [None, Some(0), Some(1), Some(2), None] + ); + assert_eq!( + method + .parameters + .iter() + .map(|p| p.output_index) + .collect::>(), + [Some(0), None, Some(1), None, Some(2)] + ); + assert_eq!(method.return_type.as_ref().unwrap().metadata, TypeMeta::I32); + } + + #[test] + fn implementation_requirements_are_independent_views_not_vtable_prefixes() { + let mut iface = interface(TypeMeta::String); + iface.base_interfaces.push(managed()); + let ancestor = TypeMeta::Interface { + namespace: "Tests".into(), + name: "IAncestor".into(), + iid: "5c011b9b-e33b-40e7-b787-9442224b9e51".into(), + }; + iface + .implementation_metadata + .required_interfaces + .extend([managed(), ancestor]); + let plan = project_implementation(&iface).unwrap(); + assert_eq!(plan.required_interfaces.len(), 2); + assert_eq!(plan.methods.len(), 1); + assert_eq!(plan.methods[0].vtable_index, 6); + } + + #[test] + fn implementation_rejects_unknown_layouts_iids_and_nested_arrays_as_whole_interfaces() { + let bad = vec![ + ( + TypeMeta::Interface { + namespace: "Tests".into(), + name: "IMissing".into(), + iid: String::new(), + }, + "IID", + ), + ( + TypeMeta::RuntimeClass { + namespace: "Tests".into(), + name: "Missing".into(), + default_interface: None, + }, + "default interface", + ), + ( + TypeMeta::Struct { + namespace: "Tests".into(), + name: "Unknown".into(), + fields: vec![], + }, + "struct layout", + ), + ( + TypeMeta::Array(Box::new(TypeMeta::Array(Box::new(TypeMeta::I32)))), + "nested arrays", + ), + ( + TypeMeta::Parameterized { + namespace: "Tests".into(), + name: "IOpen`2".into(), + piid: "c6c7fcce-aafa-4937-b9e8-6d98dcae7f3d".into(), + args: vec![TypeMeta::I32], + }, + "generic arguments", + ), + ]; + for (typ, expected) in bad { + let mut iface = interface(TypeMeta::String); + iface.methods.push(MethodMeta { + name: "Bad".into(), + vtable_index: 7, + return_type: Some(typ), + ..Default::default() + }); + let error = project_implementation(&iface).unwrap_err(); + assert!(error.contains(expected) && error.contains("Bad"), "{error}"); + } + } + + #[test] + fn implementation_rejects_generic_roots_host_roots_partial_vtables_and_metadata_errors() { + let mut iface = interface(TypeMeta::String); + iface.generic_piid = Some(iface.iid.clone()); + assert!( + project_implementation(&iface) + .unwrap_err() + .contains("generic interface") + ); + iface.generic_piid = None; + iface.methods[0].vtable_index = 3; + assert!( + project_implementation(&iface) + .unwrap_err() + .contains("WinRT slot 6") + ); + iface.methods[0].vtable_index = 6; + iface.iid = IINSPECTABLE.into(); + assert!( + project_implementation(&iface) + .unwrap_err() + .contains("reserved") + ); + iface = interface(TypeMeta::String); + iface + .implementation_metadata + .diagnostics + .push("unknown pointer contract".into()); + assert!( + project_implementation(&iface) + .unwrap_err() + .contains("unknown pointer contract") + ); + iface.implementation_metadata.diagnostics.clear(); + iface.methods[0].params[0].direction = ParamDirection::OutFill; + assert!( + project_implementation(&iface) + .unwrap_err() + .contains("FillArray requires an array") + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs index 20a5fb65..f74873eb 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs @@ -188,6 +188,14 @@ fn collect_methods_type_imports( pub(crate) fn collect_iface_type_imports(iface: &InterfaceMeta) -> HashSet { let mut imports = HashSet::new(); collect_methods_type_imports(&iface.methods, &iface.name, false, &mut imports); + for delegate in &iface.implementation_metadata.delegates { + collect_methods_type_imports( + std::slice::from_ref(&delegate.invoke), + &iface.name, + false, + &mut imports, + ); + } imports } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs index 89ad09a4..df2a0f9b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs @@ -2,5 +2,6 @@ // Licensed under the MIT License. pub(crate) mod docs; +pub(crate) mod implementation; pub(crate) mod imports; pub(crate) mod structs; diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/structs.rs index e61c5b17..8ecaf02a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/structs.rs @@ -91,7 +91,13 @@ pub(crate) fn collect_used_structs_from_class(class: &ClassMeta) -> Vec Vec { let mut seen = HashSet::new(); let mut result = Vec::new(); - for m in &iface.methods { + for m in iface.methods.iter().chain( + iface + .implementation_metadata + .delegates + .iter() + .map(|delegate| &delegate.invoke), + ) { for p in &m.params { collect_used_structs_from_type(&p.typ, &mut seen, &mut result); } diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 07600635..efb6e5f4 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -2301,7 +2301,13 @@ fn load_effective_generation_plan( if line.is_empty() || line.starts_with("//") { continue; } - let (names, module) = parse_root_export_metadata(line).ok_or_else(|| { + let type_only = line.starts_with("export type "); + let metadata_line = if type_only { + line.replacen("export type ", "export ", 1) + } else { + line.to_string() + }; + let (names, module) = parse_root_export_metadata(&metadata_line).ok_or_else(|| { format!( "Invalid retained JavaScript root export metadata in {}: `{line}`", index_path.display() @@ -2317,7 +2323,11 @@ fn load_effective_generation_plan( retained.public_exports.extend(names); plan.insert(retained)?; } else if let Some(retained) = plan.modules.get_mut(&module) { - retained.public_exports.extend(names); + if type_only { + retained.public_type_exports.extend(names); + } else { + retained.public_exports.extend(names); + } } else { return Err(format!( "Retained JavaScript root export metadata references missing canonical module `{module}`" @@ -2410,6 +2420,7 @@ fn emit_javascript_projected_file( use dynwinrt_codegen::codegen::projected::{GeneratedModule, PlannedImport}; let public_exports = projected.public_exports(); + let public_type_exports = projected.public_type_exports(); let internal_exports = projected.internal_exports(); let dependencies = projected .imports @@ -2548,6 +2559,7 @@ fn emit_javascript_projected_file( declarations: Some(dts), imports, public_exports, + public_type_exports, primary_export: (target.identity.kind != javascript::JavaScriptTypeKind::Delegate) .then(|| target.projected_name.clone()), internal_exports, @@ -2906,6 +2918,7 @@ fn generate_js_files( declarations: Some(stub_dts), imports: Vec::new(), public_exports: [target.projected_name.clone()].into_iter().collect(), + public_type_exports: Default::default(), primary_export: Some(target.projected_name.clone()), internal_exports: BTreeSet::new(), compatibility_aliases: target.compatibility_aliases.clone(), @@ -4216,7 +4229,40 @@ fn write_python_facade( .strip_prefix("from .") .and_then(|line| line.split_once(" import ")) .ok_or_else(|| format!("Generated index import for `{type_name}` is invalid"))?; - let exports = exports.split('#').next().unwrap_or(exports).trim(); + let mut exports = exports + .split('#') + .next() + .unwrap_or(exports) + .trim() + .to_string(); + let mut additional_exports = Vec::new(); + for line in implementation_index + .lines() + .filter(|line| line.starts_with("from .")) + .skip(1) + { + let (extra_source, extra) = line + .strip_prefix("from .") + .and_then(|line| line.split_once(" import ")) + .ok_or_else(|| format!("Generated helper import for `{type_name}` is invalid"))?; + if extra_source != source { + return Err(format!( + "Generated helper exports for `{type_name}` must use the same implementation module" + )); + } + let extra = extra.split('#').next().unwrap_or(extra).trim(); + for export in extra.split(',') { + additional_exports.push( + export + .trim() + .split_once(" as ") + .map_or_else(|| export.trim(), |(_, alias)| alias.trim()) + .to_string(), + ); + } + exports.push_str(", "); + exports.push_str(extra); + } let exported_type = exports.split(',').any(|export| { export .trim() @@ -4261,6 +4307,13 @@ fn write_python_facade( } else if !exports.is_empty() { package_exports.push(format!("from .{public_module} import {exports}")); } + for helper in additional_exports { + package_exports.push(if extension == "pyi" { + format!("from .{public_module} import {helper} as {helper}") + } else { + format!("from .{public_module} import {helper}") + }); + } Ok(()) } diff --git a/tools/dynwinrt-codegen/src/meta.rs b/tools/dynwinrt-codegen/src/meta.rs index 730a509d..263de330 100644 --- a/tools/dynwinrt-codegen/src/meta.rs +++ b/tools/dynwinrt-codegen/src/meta.rs @@ -72,12 +72,28 @@ pub struct InterfaceMeta { pub generic_name: Option, /// For parameterized interfaces: the type arguments used to instantiate. pub generic_args: Vec, + /// Reverse-call evidence kept separate from the permissive outbound projection. + pub implementation_metadata: InterfaceImplementationMetadata, /// XML doc summary (populated from sibling .xml). pub doc: Option, /// XML `` text. pub deprecated: Option, } +#[derive(Debug, Clone, Default)] +pub struct InterfaceImplementationMetadata { + pub diagnostics: Vec, + pub required_interfaces: Vec, + pub is_generic_definition: bool, + pub delegates: Vec, +} + +#[derive(Debug, Clone)] +pub struct ImplementationDelegateMeta { + pub typ: TypeMeta, + pub invoke: MethodMeta, +} + impl InterfaceMeta { pub fn is_delegate(&self) -> bool { self.methods.iter().any(|method| method.name == ".ctor") @@ -1537,9 +1553,73 @@ fn parse_interface_methods( generic_args.iter().map(type_meta_to_winmd_type).collect(); let mut methods = Vec::new(); + let mut implementation_metadata = InterfaceImplementationMetadata { + is_generic_definition: def.generic_params().next().is_some() && generic_args.is_empty(), + ..Default::default() + }; + if !def + .flags() + .contains(windows_metadata::TypeAttributes::WindowsRuntime) + { + implementation_metadata + .diagnostics + .push("not a Windows Runtime interface; Classic COM uses a separate planner".into()); + } for (i, method) in def.methods().enumerate() { let vtable_index = 6 + i; let sig = method.signature(&winmd_generics); + if sig.flags != windows_metadata::MethodCallAttributes::HASTHIS { + implementation_metadata.diagnostics.push(format!( + "{} requires a non-generic instance WinRT calling convention", + method.name() + )); + } + if method + .impl_flags() + .contains(windows_metadata::MethodImplAttributes::PreserveSig) + { + implementation_metadata.diagnostics.push(format!( + "{} has a direct native return rather than the WinRT HRESULT convention", + method.name() + )); + } + for (position, typ) in sig.types.iter().enumerate() { + if let Err(reason) = + validate_implementation_metadata_type(typ, index, generic_args, &mut HashSet::new()) + { + implementation_metadata.diagnostics.push(format!( + "{} parameter {}: {reason}", + method.name(), + position + 1 + )); + } else { + collect_implementation_delegates( + typ, + index, + generic_args, + &mut implementation_metadata, + ); + } + } + if sig.return_type != windows_metadata::Type::Void { + if let Err(reason) = validate_implementation_metadata_type( + &sig.return_type, + index, + generic_args, + &mut HashSet::new(), + ) { + implementation_metadata + .diagnostics + .push(format!("{} return: {reason}", method.name())); + } else { + collect_implementation_delegates( + &sig.return_type, + index, + generic_args, + &mut implementation_metadata, + ); + } + } let raw_name = method.name().to_string(); let overload_name = method.find_attribute("OverloadAttribute").and_then(|a| { @@ -1552,6 +1632,14 @@ fn parse_interface_methods( let mut params = Vec::new(); let param_defs: Vec<_> = method.params().filter(|p| p.sequence() > 0).collect(); + if param_defs.len() != sig.types.len() { + implementation_metadata.diagnostics.push(format!( + "{}: incomplete parameter contracts ({} types, {} parameter records)", + method.name(), + sig.types.len(), + param_defs.len() + )); + } let mut clr_sig_types: Vec = Vec::new(); for (j, param_def) in param_defs.iter().enumerate() { if j < sig.types.len() { @@ -1560,6 +1648,24 @@ fn parse_interface_methods( let is_out = param_def .flags() .contains(windows_metadata::ParamAttributes::Out); + if !is_out && matches!(sig.types[j], windows_metadata::Type::ArrayRef(_)) { + implementation_metadata.diagnostics.push(format!( + "{} parameter {}: ReceiveArray requires an Out contract", + method.name(), + param_def.name() + )); + } + if is_out + && param_def + .flags() + .contains(windows_metadata::ParamAttributes::In) + { + implementation_metadata.diagnostics.push(format!( + "{} parameter {}: InOut is not a WinRT implementation contract", + method.name(), + param_def.name() + )); + } let direction = if is_out { if matches!(sig.types[j], windows_metadata::Type::Array(_)) { // [out] Array = FillArray (caller allocates buffer, callee fills) @@ -1656,6 +1762,46 @@ fn parse_interface_methods( }) .map(|(_, base)| base) .collect(); + let mut pending = def + .interface_impls() + .map(|base| base.interface(&winmd_generics)) + .collect::>(); + let mut seen_requirements = HashSet::new(); + while let Some(required) = pending.pop() { + let windows_metadata::Type::Name(named) = &required else { + implementation_metadata + .diagnostics + .push("unknown required interface contract".into()); + continue; + }; + let typ = map_winmd_type_with_generics(&required, index, generic_args); + if matches!(&typ, TypeMeta::Interface { iid, .. } if + iid.eq_ignore_ascii_case("00000000-0000-0000-c000-000000000046") + || iid.eq_ignore_ascii_case("af86e2e0-b12d-4c6a-9c5a-d7aa65101e90")) + { + continue; + } + if !seen_requirements.insert(typ.type_identity()) { + continue; + } + implementation_metadata.required_interfaces.push(typ); + let lookup_name = named.name.split('`').next().unwrap_or(&named.name); + if let Some(required_def) = index.get(&named.namespace, lookup_name).next() { + pending.extend( + required_def + .interface_impls() + .map(|base| base.interface(&named.generics)), + ); + } else { + implementation_metadata.diagnostics.push(format!( + "required interface {}.{} is not present in loaded metadata", + named.namespace, named.name + )); + } + } + implementation_metadata + .required_interfaces + .sort_by_key(|typ| typ.type_identity()); Some(InterfaceMeta { name: output_name.to_string(), namespace: namespace.to_string(), @@ -1665,11 +1811,267 @@ fn parse_interface_methods( generic_piid, generic_name: None, generic_args: generic_args_vec, + implementation_metadata, doc: None, deprecated: None, }) } +fn collect_implementation_delegates( + typ: &windows_metadata::Type, + index: &reader::Index, + generic_args: &[TypeMeta], + output: &mut InterfaceImplementationMetadata, +) { + use windows_metadata::Type; + match typ { + Type::Array(inner) | Type::ArrayRef(inner) => { + collect_implementation_delegates(inner, index, generic_args, output); + } + Type::Name(named) => { + for argument in &named.generics { + collect_implementation_delegates(argument, index, generic_args, output); + } + let lookup_name = named.name.split('`').next().unwrap_or(&named.name); + let Some(def) = index.get(&named.namespace, lookup_name).next() else { + return; + }; + if def + .extends() + .is_some_and(|base| base.namespace() == "System" && base.name() == "ValueType") + { + for field in def.fields() { + collect_implementation_delegates(&field.ty(), index, generic_args, output); + } + return; + } + if !def.extends().is_some_and(|base| { + base.namespace() == "System" + && matches!(base.name(), "Delegate" | "MulticastDelegate") + }) { + return; + } + let delegate_type = map_winmd_type_with_generics(typ, index, generic_args); + if output + .delegates + .iter() + .any(|delegate| delegate.typ == delegate_type) + { + return; + } + let Some(invoke) = def.methods().find(|method| method.name() == "Invoke") else { + output.diagnostics.push(format!( + "{}.{} has no delegate Invoke contract", + named.namespace, named.name + )); + return; + }; + let signature = invoke.signature(&named.generics); + if signature.flags != windows_metadata::MethodCallAttributes::HASTHIS + || invoke + .impl_flags() + .contains(windows_metadata::MethodImplAttributes::PreserveSig) + { + output.diagnostics.push(format!( + "{}.{} Invoke has an unsupported native calling convention", + named.namespace, named.name + )); + } + let parameter_defs = invoke + .params() + .filter(|parameter| parameter.sequence() > 0) + .collect::>(); + if parameter_defs.len() != signature.types.len() { + output.diagnostics.push(format!( + "{}.{} has incomplete delegate parameter contracts", + named.namespace, named.name + )); + return; + } + let params = parameter_defs + .iter() + .zip(&signature.types) + .map(|(parameter, typ)| { + let out = parameter + .flags() + .contains(windows_metadata::ParamAttributes::Out); + if (out + && parameter + .flags() + .contains(windows_metadata::ParamAttributes::In)) + || (!out && matches!(typ, Type::ArrayRef(_))) + { + output.diagnostics.push(format!( + "{}.{} Invoke parameter {} has an unsupported direction contract", + named.namespace, + named.name, + parameter.name() + )); + } + ParamMeta { + name: parameter.name().into(), + typ: map_winmd_type_with_generics(typ, index, generic_args), + direction: if out { + if matches!(typ, Type::Array(_)) { + ParamDirection::OutFill + } else { + ParamDirection::Out + } + } else { + ParamDirection::In + }, + } + }) + .collect(); + let return_type = (signature.return_type != Type::Void) + .then(|| map_winmd_type_with_generics(&signature.return_type, index, generic_args)); + output.delegates.push(ImplementationDelegateMeta { + typ: delegate_type, + invoke: MethodMeta { + name: "Invoke".into(), + raw_name: "Invoke".into(), + vtable_index: 3, + params, + return_type, + ..Default::default() + }, + }); + for typ in signature + .types + .iter() + .chain((signature.return_type != Type::Void).then_some(&signature.return_type)) + { + if let Err(reason) = validate_implementation_metadata_type( + typ, + index, + generic_args, + &mut HashSet::new(), + ) { + output.diagnostics.push(format!( + "{}.{} Invoke: {reason}", + named.namespace, named.name + )); + } else { + collect_implementation_delegates(typ, index, generic_args, output); + } + } + } + _ => {} + } +} + +fn validate_implementation_metadata_type( + typ: &windows_metadata::Type, + index: &reader::Index, + generic_args: &[TypeMeta], + visiting: &mut HashSet<(String, String)>, +) -> Result<(), String> { + use windows_metadata::Type; + match typ { + Type::Bool + | Type::I8 + | Type::U8 + | Type::I16 + | Type::U16 + | Type::I32 + | Type::U32 + | Type::I64 + | Type::U64 + | Type::F32 + | Type::F64 + | Type::Char + | Type::String + | Type::Object => Ok(()), + Type::Generic(position) if (*position as usize) < generic_args.len() => Ok(()), + Type::Generic(_) => Err("open generic type has no closed ABI".into()), + Type::Array(element) | Type::ArrayRef(element) => { + if matches!(element.as_ref(), Type::Array(_) | Type::ArrayRef(_)) { + return Err("nested arrays are not a WinRT array contract".into()); + } + validate_implementation_metadata_type(element, index, generic_args, visiting) + } + Type::Name(named) => { + if named.namespace == "System" && named.name == "Guid" { + return Ok(()); + } + let lookup_name = named.name.split('`').next().unwrap_or(&named.name); + let Some(def) = index.get(&named.namespace, lookup_name).next() else { + return Err(format!( + "unresolved type {}.{}", + named.namespace, named.name + )); + }; + if !def + .flags() + .contains(windows_metadata::TypeAttributes::WindowsRuntime) + { + return Err(format!( + "{}.{} is not a WinRT metadata type", + named.namespace, named.name + )); + } + for argument in &named.generics { + validate_implementation_metadata_type(argument, index, generic_args, visiting)?; + } + if def + .extends() + .is_some_and(|base| base.namespace() == "System" && base.name() == "ValueType") + { + let identity = (named.namespace.clone(), named.name.clone()); + if !visiting.insert(identity.clone()) { + return Err(format!( + "recursive struct layout {}.{}", + named.namespace, named.name + )); + } + if !def + .flags() + .contains(windows_metadata::TypeAttributes::SequentialLayout) + { + return Err(format!( + "non-sequential struct layout {}.{} is unsupported", + named.namespace, named.name + )); + } + if let Some(layout) = def.class_layout() { + if layout.packing_size() != 0 || layout.class_size() != 0 { + return Err(format!( + "non-default struct layout {}.{} is unsupported", + named.namespace, named.name + )); + } + } + for field in def.fields() { + let field_type = field.ty(); + if matches!( + field_type, + Type::Array(_) | Type::ArrayRef(_) | Type::ArrayFixed(_, _) + ) { + return Err(format!( + "array field {}.{}.{} has no WinRT value layout", + named.namespace, + named.name, + field.name() + )); + } + validate_implementation_metadata_type( + &field_type, + index, + generic_args, + visiting, + ) + .map_err(|reason| format!("field {}: {reason}", field.name()))?; + } + visiting.remove(&identity); + } + Ok(()) + } + _ => Err(format!( + "unsupported native type {typ:?}; it cannot be treated as Object" + )), + } +} + /// Produce a .NET-style CLR type name for XML doc signature keys. /// Examples: `System.Int32`, `System.String`, `Windows.Foundation.Uri`, /// `System.String[]`, `Windows.Foundation.Collections.IVector`1`. @@ -2064,6 +2466,38 @@ fn resolve_named_type( mod tests { use super::*; + #[test] + fn implementation_metadata_does_not_erase_unknown_native_shapes_into_object() { + use windows_metadata::Type; + let index = reader::Index::new(Vec::new()); + for typ in [ + Type::Generic(0), + Type::PtrMut(Box::new(Type::I32), 1), + Type::PtrConst(Box::new(Type::Void), 1), + Type::ArrayFixed(Box::new(Type::U8), 4), + Type::Array(Box::new(Type::Array(Box::new(Type::I32)))), + ] { + assert!( + validate_implementation_metadata_type(&typ, &index, &[], &mut HashSet::new()) + .is_err(), + "{typ:?}" + ); + } + assert!( + validate_implementation_metadata_type(&Type::Object, &index, &[], &mut HashSet::new()) + .is_ok() + ); + assert!( + validate_implementation_metadata_type( + &Type::Generic(0), + &index, + &[TypeMeta::I32], + &mut HashSet::new() + ) + .is_ok() + ); + } + #[test] fn make_parameterized_name_single_arg() { let name = make_parameterized_name("IVector`1", &[TypeMeta::String]); diff --git a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs index b9896e2f..b7e6cce9 100644 --- a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs +++ b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs @@ -157,7 +157,7 @@ fn interface_generation_uses_projected_identity_cache() { "missing native-wrap __new__:\n{py}" ); assert!( - py.contains("def _set_native(self, obj: DynWinRTValue):"), + py.contains("def _set_native(self, obj: DynWinRTValue, *, cache=True):"), "missing native initializer:\n{py}" ); assert!( diff --git a/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs b/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs index b39881e1..1f7e2e9b 100644 --- a/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs @@ -228,7 +228,7 @@ fn real_windows_metadata_exposes_xaml_and_stream_typing_relationships() { common::generate_interface(with_content_type, &known_interfaces, &HashSet::new()); assert!( with_content_stub - .contains("class IRandomAccessStreamWithContentType(_IRandomAccessStreamWithContentTypeIdentity, Protocol):"), + .contains("class IRandomAccessStreamWithContentType(_IRandomAccessStreamWithContentTypeIdentity, Protocol, metaclass=_IRandomAccessStreamWithContentTypeImplementationFactory):"), "{with_content_stub}" ); assert!( diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts index ea7ea55f..5c4b2bcf 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts @@ -1,10 +1,23 @@ // Generated by dynwinrt-codegen — do not edit -import { WinGuid } from '@microsoft/dynwinrt'; +import { WinGuid, DynWinRtImplementation } from '@microsoft/dynwinrt'; +import { DynWinRtImplementationDescriptor } from '@microsoft/dynwinrt'; + + +/** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */ +export interface IStringableHandlers { + toString(): string; +} export declare const IID_IStringable: WinGuid; export declare class IStringable { private constructor(); + /** Validate synchronous handlers and create an independent interface descriptor. */ + static implementation(handlers: IStringableHandlers): DynWinRtImplementationDescriptor; + /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper. */ + static implement(handlers: IStringableHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation; + /** Query a controller for this interface and return an owned, typed view. */ + static fromImplementation(owner: DynWinRtImplementation): IStringable; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IStringable; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js index e9f1e4e6..b0734b3f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid } = require('@microsoft/dynwinrt'); +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation } = require('@microsoft/dynwinrt'); const IID_IStringable = WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3'); @@ -14,6 +14,59 @@ const _IStringable = new Proxy({}, { } }); + +function __implementationCheck(value, valid, label) { + if (!valid) throw new TypeError(`${label}: invalid implementation result`); + return value; +} +function __implementationField(value, name, label) { + if (value === null || typeof value !== 'object') throw new TypeError(`${label}: expected a named result object`); + const field = Object.getOwnPropertyDescriptor(value, name); + if (!field || !Object.hasOwn(field, 'value')) throw new TypeError(`${label}: missing data field ${name}`); + return field.value; +} +function __implementationArray(value, label, bytes = false, capacity = undefined) { + if (!Array.isArray(value) && !(bytes && value instanceof Uint8Array)) throw new TypeError(`${label}: expected an array`); + if (capacity !== undefined && value.length !== capacity) throw new RangeError(`${label}: FillArray result must match capacity ${capacity}`); + return Array.from(value); +} +function __implementationReference(value, iid, label) { + if (value === null) return DynWinRtValue.nullValue(); + const raw = value instanceof DynWinRtValue ? value : value?._obj; + if (!(raw instanceof DynWinRtValue)) throw new TypeError(`${label}: expected a managed WinRT value or null`); + return raw.isNull() ? DynWinRtValue.nullValue() : raw.cast(iid); +} +function __implementationSync(value, label) { + if (value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function') { + throw new TypeError(`${label}: implementation callbacks must return synchronously, not a Promise or thenable`); + } + return value; +} +function __implementationHandler(handlers, name, label) { + if (handlers === null || (typeof handlers !== 'object' && typeof handlers !== 'function')) throw new TypeError(`${label}: expected a handler object`); + let owner = handlers; + while (owner && owner !== Object.prototype && owner !== Function.prototype) { + const property = Object.getOwnPropertyDescriptor(owner, name); + if (property) { + const callback = property.value; + if (typeof callback !== 'function') throw new TypeError(`${label}: missing synchronous handler ${name} (accessors are not handlers)`); + if (Object.prototype.toString.call(callback) === '[object AsyncFunction]' || Object.prototype.toString.call(callback) === '[object AsyncGeneratorFunction]') { + throw new TypeError(`${label}.${name}: async handlers are not supported`); + } + return callback.bind(handlers); + } + owner = Object.getPrototypeOf(owner); + } + throw new TypeError(`${label}: missing synchronous handler ${name}`); +} + +let __implementationPlan; +function __getImplementationPlan() { + return (__implementationPlan ??= DynWinRtInterfacePlan.create("Windows.Foundation.IStringable", DynWinRtType.interface(WinGuid.parse("96369f54-8eb6-48f0-abce-c1b211e627c3")), [ + { name: "ToString", vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(DynWinRtType.hstring()) } + ], [])); +} + class IStringable { _obj; @@ -25,6 +78,45 @@ class IStringable { return new IStringable(obj.cast(IID_IStringable)); } + static implementation(handlers) { + const h6 = __implementationHandler(handlers, "toString", "Windows.Foundation.IStringable"); + const plan = __getImplementationPlan(); + return Object.freeze({ plan, dispatch(vtableIndex, args) { + if (!Array.isArray(args)) throw new TypeError('implementation arguments must be an array'); + switch (vtableIndex) { + case 6: { + if (args.length !== 0) throw new TypeError('implementation argument count mismatch'); + const result = __implementationSync(h6(), "Windows.Foundation.IStringable.toString"); + return [DynWinRtValue.hstring(((v) => __implementationCheck(v, typeof v === 'string', "Windows.Foundation.IStringable.toString.result"))(result))]; + } + default: throw new RangeError('unknown implementation vtable slot'); + } + } }); + } + + static implement(handlers, ...additional) { + const descriptors = [this.implementation(handlers), ...additional]; + for (const descriptor of descriptors) { + if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor'); + } + const plans = descriptors.map(descriptor => descriptor.plan); + const dispatchers = descriptors.map(descriptor => descriptor.dispatch); + return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { + if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index'); + return dispatchers[interfaceIndex](vtableIndex, args); + }); + } + + static fromImplementation(owner) { + if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller'); + const value = owner.toValue(); + try { + return this.from(value); + } finally { + value.release(); + } + } + toString() { return _IStringable.method(6).invoke(this._obj, []).toString(); } diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts index 1f605afb..1e775d9b 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts @@ -1,10 +1,24 @@ // Generated by dynwinrt-codegen — do not edit -import { WinGuid } from '@microsoft/dynwinrt'; +import { WinGuid, DynWinRtImplementation } from '@microsoft/dynwinrt'; +import { DynWinRtImplementationDescriptor } from '@microsoft/dynwinrt'; + + +/** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */ +export interface IUriRuntimeClassWithAbsoluteCanonicalUriHandlers { + getAbsoluteCanonicalUri(): string; + getDisplayIri(): string; +} export declare const IID_IUriRuntimeClassWithAbsoluteCanonicalUri: WinGuid; export declare class IUriRuntimeClassWithAbsoluteCanonicalUri { private constructor(); + /** Validate synchronous handlers and create an independent interface descriptor. */ + static implementation(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers): DynWinRtImplementationDescriptor; + /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper. */ + static implement(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation; + /** Query a controller for this interface and return an owned, typed view. */ + static fromImplementation(owner: DynWinRtImplementation): IUriRuntimeClassWithAbsoluteCanonicalUri; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IUriRuntimeClassWithAbsoluteCanonicalUri; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js index 12686c70..82bc2157 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid } = require('@microsoft/dynwinrt'); +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation } = require('@microsoft/dynwinrt'); const IID_IUriRuntimeClassWithAbsoluteCanonicalUri = WinGuid.parse('758d9661-221c-480f-a339-50656673f46f'); @@ -15,6 +15,60 @@ const _IUriRuntimeClassWithAbsoluteCanonicalUri = new Proxy({}, { } }); + +function __implementationCheck(value, valid, label) { + if (!valid) throw new TypeError(`${label}: invalid implementation result`); + return value; +} +function __implementationField(value, name, label) { + if (value === null || typeof value !== 'object') throw new TypeError(`${label}: expected a named result object`); + const field = Object.getOwnPropertyDescriptor(value, name); + if (!field || !Object.hasOwn(field, 'value')) throw new TypeError(`${label}: missing data field ${name}`); + return field.value; +} +function __implementationArray(value, label, bytes = false, capacity = undefined) { + if (!Array.isArray(value) && !(bytes && value instanceof Uint8Array)) throw new TypeError(`${label}: expected an array`); + if (capacity !== undefined && value.length !== capacity) throw new RangeError(`${label}: FillArray result must match capacity ${capacity}`); + return Array.from(value); +} +function __implementationReference(value, iid, label) { + if (value === null) return DynWinRtValue.nullValue(); + const raw = value instanceof DynWinRtValue ? value : value?._obj; + if (!(raw instanceof DynWinRtValue)) throw new TypeError(`${label}: expected a managed WinRT value or null`); + return raw.isNull() ? DynWinRtValue.nullValue() : raw.cast(iid); +} +function __implementationSync(value, label) { + if (value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function') { + throw new TypeError(`${label}: implementation callbacks must return synchronously, not a Promise or thenable`); + } + return value; +} +function __implementationHandler(handlers, name, label) { + if (handlers === null || (typeof handlers !== 'object' && typeof handlers !== 'function')) throw new TypeError(`${label}: expected a handler object`); + let owner = handlers; + while (owner && owner !== Object.prototype && owner !== Function.prototype) { + const property = Object.getOwnPropertyDescriptor(owner, name); + if (property) { + const callback = property.value; + if (typeof callback !== 'function') throw new TypeError(`${label}: missing synchronous handler ${name} (accessors are not handlers)`); + if (Object.prototype.toString.call(callback) === '[object AsyncFunction]' || Object.prototype.toString.call(callback) === '[object AsyncGeneratorFunction]') { + throw new TypeError(`${label}.${name}: async handlers are not supported`); + } + return callback.bind(handlers); + } + owner = Object.getPrototypeOf(owner); + } + throw new TypeError(`${label}: missing synchronous handler ${name}`); +} + +let __implementationPlan; +function __getImplementationPlan() { + return (__implementationPlan ??= DynWinRtInterfacePlan.create("Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri", DynWinRtType.interface(WinGuid.parse("758d9661-221c-480f-a339-50656673f46f")), [ + { name: "get_AbsoluteCanonicalUri", vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(DynWinRtType.hstring()) }, + { name: "get_DisplayIri", vtableIndex: 7, signature: new DynWinRtMethodSig().addOut(DynWinRtType.hstring()) } + ], [])); +} + class IUriRuntimeClassWithAbsoluteCanonicalUri { _obj; @@ -26,6 +80,51 @@ class IUriRuntimeClassWithAbsoluteCanonicalUri { return new IUriRuntimeClassWithAbsoluteCanonicalUri(obj.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri)); } + static implementation(handlers) { + const h6 = __implementationHandler(handlers, "getAbsoluteCanonicalUri", "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri"); + const h7 = __implementationHandler(handlers, "getDisplayIri", "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri"); + const plan = __getImplementationPlan(); + return Object.freeze({ plan, dispatch(vtableIndex, args) { + if (!Array.isArray(args)) throw new TypeError('implementation arguments must be an array'); + switch (vtableIndex) { + case 6: { + if (args.length !== 0) throw new TypeError('implementation argument count mismatch'); + const result = __implementationSync(h6(), "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.getAbsoluteCanonicalUri"); + return [DynWinRtValue.hstring(((v) => __implementationCheck(v, typeof v === 'string', "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.getAbsoluteCanonicalUri.result"))(result))]; + } + case 7: { + if (args.length !== 0) throw new TypeError('implementation argument count mismatch'); + const result = __implementationSync(h7(), "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.getDisplayIri"); + return [DynWinRtValue.hstring(((v) => __implementationCheck(v, typeof v === 'string', "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.getDisplayIri.result"))(result))]; + } + default: throw new RangeError('unknown implementation vtable slot'); + } + } }); + } + + static implement(handlers, ...additional) { + const descriptors = [this.implementation(handlers), ...additional]; + for (const descriptor of descriptors) { + if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor'); + } + const plans = descriptors.map(descriptor => descriptor.plan); + const dispatchers = descriptors.map(descriptor => descriptor.dispatch); + return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { + if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index'); + return dispatchers[interfaceIndex](vtableIndex, args); + }); + } + + static fromImplementation(owner) { + if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller'); + const value = owner.toValue(); + try { + return this.from(value); + } finally { + value.release(); + } + } + get absoluteCanonicalUri() { return (() => { const _m = _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IUriRuntimeClassWithAbsoluteCanonicalUri.method(6).invoke(this._obj, []).toString(); })(); } diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts index 8b5f1328..b6493ef0 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts @@ -1,10 +1,24 @@ // Generated by dynwinrt-codegen — do not edit -import { WinGuid } from '@microsoft/dynwinrt'; +import { WinGuid, DynWinRtImplementation } from '@microsoft/dynwinrt'; +import { DynWinRtImplementationDescriptor } from '@microsoft/dynwinrt'; + + +/** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */ +export interface IWwwFormUrlDecoderEntryHandlers { + getName(): string; + getValue(): string; +} export declare const IID_IWwwFormUrlDecoderEntry: WinGuid; export declare class IWwwFormUrlDecoderEntry { private constructor(); + /** Validate synchronous handlers and create an independent interface descriptor. */ + static implementation(handlers: IWwwFormUrlDecoderEntryHandlers): DynWinRtImplementationDescriptor; + /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper. */ + static implement(handlers: IWwwFormUrlDecoderEntryHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation; + /** Query a controller for this interface and return an owned, typed view. */ + static fromImplementation(owner: DynWinRtImplementation): IWwwFormUrlDecoderEntry; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IWwwFormUrlDecoderEntry; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js index b870de39..8a287ae3 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid } = require('@microsoft/dynwinrt'); +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation } = require('@microsoft/dynwinrt'); const IID_IWwwFormUrlDecoderEntry = WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'); @@ -15,6 +15,60 @@ const _IWwwFormUrlDecoderEntry = new Proxy({}, { } }); + +function __implementationCheck(value, valid, label) { + if (!valid) throw new TypeError(`${label}: invalid implementation result`); + return value; +} +function __implementationField(value, name, label) { + if (value === null || typeof value !== 'object') throw new TypeError(`${label}: expected a named result object`); + const field = Object.getOwnPropertyDescriptor(value, name); + if (!field || !Object.hasOwn(field, 'value')) throw new TypeError(`${label}: missing data field ${name}`); + return field.value; +} +function __implementationArray(value, label, bytes = false, capacity = undefined) { + if (!Array.isArray(value) && !(bytes && value instanceof Uint8Array)) throw new TypeError(`${label}: expected an array`); + if (capacity !== undefined && value.length !== capacity) throw new RangeError(`${label}: FillArray result must match capacity ${capacity}`); + return Array.from(value); +} +function __implementationReference(value, iid, label) { + if (value === null) return DynWinRtValue.nullValue(); + const raw = value instanceof DynWinRtValue ? value : value?._obj; + if (!(raw instanceof DynWinRtValue)) throw new TypeError(`${label}: expected a managed WinRT value or null`); + return raw.isNull() ? DynWinRtValue.nullValue() : raw.cast(iid); +} +function __implementationSync(value, label) { + if (value !== null && (typeof value === 'object' || typeof value === 'function') && typeof value.then === 'function') { + throw new TypeError(`${label}: implementation callbacks must return synchronously, not a Promise or thenable`); + } + return value; +} +function __implementationHandler(handlers, name, label) { + if (handlers === null || (typeof handlers !== 'object' && typeof handlers !== 'function')) throw new TypeError(`${label}: expected a handler object`); + let owner = handlers; + while (owner && owner !== Object.prototype && owner !== Function.prototype) { + const property = Object.getOwnPropertyDescriptor(owner, name); + if (property) { + const callback = property.value; + if (typeof callback !== 'function') throw new TypeError(`${label}: missing synchronous handler ${name} (accessors are not handlers)`); + if (Object.prototype.toString.call(callback) === '[object AsyncFunction]' || Object.prototype.toString.call(callback) === '[object AsyncGeneratorFunction]') { + throw new TypeError(`${label}.${name}: async handlers are not supported`); + } + return callback.bind(handlers); + } + owner = Object.getPrototypeOf(owner); + } + throw new TypeError(`${label}: missing synchronous handler ${name}`); +} + +let __implementationPlan; +function __getImplementationPlan() { + return (__implementationPlan ??= DynWinRtInterfacePlan.create("Windows.Foundation.IWwwFormUrlDecoderEntry", DynWinRtType.interface(WinGuid.parse("125e7431-f678-4e8e-b670-20a9b06c512d")), [ + { name: "get_Name", vtableIndex: 6, signature: new DynWinRtMethodSig().addOut(DynWinRtType.hstring()) }, + { name: "get_Value", vtableIndex: 7, signature: new DynWinRtMethodSig().addOut(DynWinRtType.hstring()) } + ], [])); +} + class IWwwFormUrlDecoderEntry { _obj; @@ -26,6 +80,51 @@ class IWwwFormUrlDecoderEntry { return new IWwwFormUrlDecoderEntry(obj.cast(IID_IWwwFormUrlDecoderEntry)); } + static implementation(handlers) { + const h6 = __implementationHandler(handlers, "getName", "Windows.Foundation.IWwwFormUrlDecoderEntry"); + const h7 = __implementationHandler(handlers, "getValue", "Windows.Foundation.IWwwFormUrlDecoderEntry"); + const plan = __getImplementationPlan(); + return Object.freeze({ plan, dispatch(vtableIndex, args) { + if (!Array.isArray(args)) throw new TypeError('implementation arguments must be an array'); + switch (vtableIndex) { + case 6: { + if (args.length !== 0) throw new TypeError('implementation argument count mismatch'); + const result = __implementationSync(h6(), "Windows.Foundation.IWwwFormUrlDecoderEntry.getName"); + return [DynWinRtValue.hstring(((v) => __implementationCheck(v, typeof v === 'string', "Windows.Foundation.IWwwFormUrlDecoderEntry.getName.result"))(result))]; + } + case 7: { + if (args.length !== 0) throw new TypeError('implementation argument count mismatch'); + const result = __implementationSync(h7(), "Windows.Foundation.IWwwFormUrlDecoderEntry.getValue"); + return [DynWinRtValue.hstring(((v) => __implementationCheck(v, typeof v === 'string', "Windows.Foundation.IWwwFormUrlDecoderEntry.getValue.result"))(result))]; + } + default: throw new RangeError('unknown implementation vtable slot'); + } + } }); + } + + static implement(handlers, ...additional) { + const descriptors = [this.implementation(handlers), ...additional]; + for (const descriptor of descriptors) { + if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor'); + } + const plans = descriptors.map(descriptor => descriptor.plan); + const dispatchers = descriptors.map(descriptor => descriptor.dispatch); + return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { + if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index'); + return dispatchers[interfaceIndex](vtableIndex, args); + }); + } + + static fromImplementation(owner) { + if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller'); + const value = owner.toValue(); + try { + return this.from(value); + } finally { + value.release(); + } + } + get name() { return (() => { const _m = _IWwwFormUrlDecoderEntry.method(6); return typeof _m.getString === 'function' ? _m.getString(this._obj) : _IWwwFormUrlDecoderEntry.method(6).invoke(this._obj, []).toString(); })(); } diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts index 84567886..21f079d3 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.d.ts @@ -2,10 +2,15 @@ import { WinGuid } from '@microsoft/dynwinrt'; import { IWwwFormUrlDecoderEntry } from '../IWwwFormUrlDecoderEntry.js'; + export declare const IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce: WinGuid; export declare class IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce { private constructor(); + /** Windows.Foundation.Collections.IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce cannot be implemented: generic interface implementations are not supported */ + static implementation(handlers: never): never; + /** Windows.Foundation.Collections.IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce cannot be implemented: generic interface implementations are not supported */ + static implement(handlers: never, ...additional: never[]): never; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js index a8096f6f..23ce7967 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/collections/IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.js @@ -23,6 +23,7 @@ const _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce = ne } }); + class IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce { _obj; @@ -34,6 +35,9 @@ class IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce { return new IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce(obj.cast(IID_IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce)); } + static implementation() { throw new TypeError("Windows.Foundation.Collections.IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce cannot be implemented: generic interface implementations are not supported"); } + static implement() { throw new TypeError("Windows.Foundation.Collections.IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce cannot be implemented: generic interface implementations are not supported"); } + get current() { return ((v) => v.isNull() ? null : new (__get_IWwwFormUrlDecoderEntry())(v))((() => { const _m = _IIterator_WindowsFoundationIWwwFormUrlDecoderEntry_g498f64075ebd0fce.method(6); return typeof _m.getObj === 'function' ? _m.getObj(this._obj) : _m.invoke(this._obj, []); })()); } diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py index a64d55f0..f0d74285 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/__init__.py @@ -3,5 +3,8 @@ from .windows__foundation__www_form_url_decoder import WwwFormUrlDecoder # noqa: F401 from .windows__foundation__collections__i_iterator_i_www_form_url_decoder_entry import IID_IIterator_IWwwFormUrlDecoderEntry, IIterator_IWwwFormUrlDecoderEntry # noqa: F401 from .windows__foundation__i_stringable import IID_IStringable, IStringable # noqa: F401 +from .windows__foundation__i_stringable import IStringableHandlers # noqa: F401 from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IID_IUriRuntimeClassWithAbsoluteCanonicalUri, IUriRuntimeClassWithAbsoluteCanonicalUri # noqa: F401 +from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IUriRuntimeClassWithAbsoluteCanonicalUriHandlers # noqa: F401 from .windows__foundation__i_www_form_url_decoder_entry import IID_IWwwFormUrlDecoderEntry, IWwwFormUrlDecoderEntry # noqa: F401 +from .windows__foundation__i_www_form_url_decoder_entry import IWwwFormUrlDecoderEntryHandlers # noqa: F401 diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py index bdd1e396..88b80268 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py @@ -31,17 +31,26 @@ class IIterator_IWwwFormUrlDecoderEntry(_WinRTIteratorMixin): _dynwinrt_interface_type = True + @staticmethod + def implementation(handlers): + raise TypeError("Windows.Foundation.Collections.IIterator_IWwwFormUrlDecoderEntry cannot be implemented: generic interface implementations are not supported") + + @staticmethod + def implement(handlers, *additional): + raise TypeError("Windows.Foundation.Collections.IIterator_IWwwFormUrlDecoderEntry cannot be implemented: generic interface implementations are not supported") + _dynwinrt_interface_iid = IID_IIterator_IWwwFormUrlDecoderEntry def __new__(cls, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue): return _dynwinrt_projected_from_native(cls, args[0], '_set_native') return super().__new__(cls) - def _set_native(self, obj: DynWinRTValue): + def _set_native(self, obj: DynWinRTValue, *, cache=True): self._obj = obj.cast(IID_IIterator_IWwwFormUrlDecoderEntry) self._dynwinrt_native_ready = True _dynwinrt_track_projected(self, 'Windows.Foundation.Collections.IIterator_IWwwFormUrlDecoderEntry') - _dynwinrt_cache_projected(self) + if cache: + _dynwinrt_cache_projected(self) def __init__(self, obj: DynWinRTValue): if getattr(self, '_dynwinrt_native_ready', False): diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py index c4763963..47915c50 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py @@ -14,6 +14,11 @@ _dynwinrt_symbol, _dynwinrt_track_projected, _dynwinrt_uuid, _dynwinrt_vector, _dynwinrt_wrap_values, ) +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) IID_IStringable = WinGUID.parse('96369f54-8eb6-48f0-abce-c1b211e627c3') @@ -22,19 +27,148 @@ .add_method("ToString", DynWinRTMethodSig().add_out(DynWinRTType.hstring())) +class IStringableHandlers(Protocol): + """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" + def to_string(self) -> str: ... + +import inspect as _implementation_inspect + + +def _implementation_check(value, valid, label): + if not valid: + raise TypeError(f'{label}: invalid implementation result') + return value + + +def _implementation_field(value, name, label): + if not isinstance(value, dict) or name not in value: + raise TypeError(f'{label}: expected a result dict containing {name}') + return value[name] + + +def _implementation_array(value, label, bytes_allowed=False, capacity=None): + if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): + raise TypeError(f'{label}: expected an array') + if capacity is not None and len(value) != capacity: + raise ValueError(f'{label}: FillArray result must match capacity {capacity}') + return list(value) + + +def _implementation_reference(value, iid, label): + if value is None: + return DynWinRTValue.null_value() + raw = getattr(value, '_obj', value) + if not isinstance(raw, DynWinRTValue): + raise TypeError(f'{label}: expected a managed WinRT value or None') + return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) + + +def _implementation_sync(value, label): + if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): + if _implementation_inspect.iscoroutine(value): + value.close() + raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') + return value + + +def _implementation_handler(handlers, name, count, label): + try: + member = _implementation_inspect.getattr_static(handlers, name) + except AttributeError: + raise TypeError(f'{label}: missing synchronous handler {name}') from None + if isinstance(member, property): + raise TypeError(f'{label}: property accessors are not callback handlers: {name}') + callback = getattr(handlers, name) + if not callable(callback): + raise TypeError(f'{label}: missing synchronous handler {name}') + if (_implementation_inspect.iscoroutinefunction(callback) + or _implementation_inspect.isasyncgenfunction(callback) + or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) + or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): + raise TypeError(f'{label}.{name}: async handlers are not supported') + try: + signature = _implementation_inspect.signature(callback) + except ValueError: + pass + else: + try: + signature.bind(*([None] * count)) + except TypeError as error: + raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None + return callback + + +_implementation_plan = None + +def _get_implementation_plan(): + global _implementation_plan + if _implementation_plan is None: + _implementation_plan = DynWinRTInterfacePlan.create("Windows.Foundation.IStringable", DynWinRTType.interface(WinGUID.parse("96369f54-8eb6-48f0-abce-c1b211e627c3")), [ + DynWinRTImplementationMethod("ToString", 6, DynWinRTMethodSig().add_out(DynWinRTType.hstring())) + ], []) + return _implementation_plan + + class IStringable: _dynwinrt_interface_type = True + @staticmethod + def implementation(handlers: IStringableHandlers) -> DynWinRTImplementationDescriptor: + h6 = _implementation_handler(handlers, "to_string", 0, "Windows.Foundation.IStringable") + plan = _get_implementation_plan() + def dispatch(vtable_index, args): + if not isinstance(args, list): + raise TypeError('implementation arguments must be a list') + if vtable_index == 6: + if len(args) != 0: + raise TypeError('implementation argument count mismatch') + result = _implementation_sync(h6(), "Windows.Foundation.IStringable.to_string") + return [DynWinRTValue.from_hstring((lambda v: _implementation_check(v, isinstance(v, str), "Windows.Foundation.IStringable.to_string.result"))(result))] + raise ValueError('unknown implementation vtable slot') + return DynWinRTImplementationDescriptor(plan, dispatch) + + @classmethod + def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: + descriptors = (cls.implementation(handlers), *additional) + if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors): + raise TypeError('invalid implementation descriptor') + plans = [descriptor.plan for descriptor in descriptors] + dispatchers = tuple(descriptor.dispatch for descriptor in descriptors) + def callback(interface_index, vtable_index, args): + if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers): + raise ValueError('unknown implementation interface index') + return dispatchers[interface_index](vtable_index, args) + return DynWinRTImplementation.create(plans, callback) + + @classmethod + def from_implementation(cls, owner: DynWinRTImplementation) -> 'IStringable': + """Query an independently owned view, tracked by the current lifetime scope.""" + if not isinstance(owner, DynWinRTImplementation): + raise TypeError('from_implementation requires a DynWinRTImplementation controller') + value = owner.to_value() + try: + native = value.cast(IID_IStringable) + try: + view = object.__new__(cls) + cls._set_native(view, native, cache=False) + return view + except BaseException: + native.release() + raise + finally: + value.release() + _dynwinrt_interface_iid = IID_IStringable def __new__(cls, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue): return _dynwinrt_projected_from_native(cls, args[0], '_set_native') return super().__new__(cls) - def _set_native(self, obj: DynWinRTValue): + def _set_native(self, obj: DynWinRTValue, *, cache=True): self._obj = obj self._dynwinrt_native_ready = True _dynwinrt_track_projected(self, 'Windows.Foundation.IStringable') - _dynwinrt_cache_projected(self) + if cache: + _dynwinrt_cache_projected(self) def __init__(self, obj: DynWinRTValue): if getattr(self, '_dynwinrt_native_ready', False): diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py index cbba7fb1..a152b92d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py @@ -14,6 +14,11 @@ _dynwinrt_symbol, _dynwinrt_track_projected, _dynwinrt_uuid, _dynwinrt_vector, _dynwinrt_wrap_values, ) +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) IID_IUriRuntimeClassWithAbsoluteCanonicalUri = WinGUID.parse('758d9661-221c-480f-a339-50656673f46f') @@ -23,19 +28,156 @@ .add_method("get_DisplayIri", DynWinRTMethodSig().add_out(DynWinRTType.hstring())) +class IUriRuntimeClassWithAbsoluteCanonicalUriHandlers(Protocol): + """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" + def get_absolute_canonical_uri(self) -> str: ... + def get_display_iri(self) -> str: ... + +import inspect as _implementation_inspect + + +def _implementation_check(value, valid, label): + if not valid: + raise TypeError(f'{label}: invalid implementation result') + return value + + +def _implementation_field(value, name, label): + if not isinstance(value, dict) or name not in value: + raise TypeError(f'{label}: expected a result dict containing {name}') + return value[name] + + +def _implementation_array(value, label, bytes_allowed=False, capacity=None): + if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): + raise TypeError(f'{label}: expected an array') + if capacity is not None and len(value) != capacity: + raise ValueError(f'{label}: FillArray result must match capacity {capacity}') + return list(value) + + +def _implementation_reference(value, iid, label): + if value is None: + return DynWinRTValue.null_value() + raw = getattr(value, '_obj', value) + if not isinstance(raw, DynWinRTValue): + raise TypeError(f'{label}: expected a managed WinRT value or None') + return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) + + +def _implementation_sync(value, label): + if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): + if _implementation_inspect.iscoroutine(value): + value.close() + raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') + return value + + +def _implementation_handler(handlers, name, count, label): + try: + member = _implementation_inspect.getattr_static(handlers, name) + except AttributeError: + raise TypeError(f'{label}: missing synchronous handler {name}') from None + if isinstance(member, property): + raise TypeError(f'{label}: property accessors are not callback handlers: {name}') + callback = getattr(handlers, name) + if not callable(callback): + raise TypeError(f'{label}: missing synchronous handler {name}') + if (_implementation_inspect.iscoroutinefunction(callback) + or _implementation_inspect.isasyncgenfunction(callback) + or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) + or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): + raise TypeError(f'{label}.{name}: async handlers are not supported') + try: + signature = _implementation_inspect.signature(callback) + except ValueError: + pass + else: + try: + signature.bind(*([None] * count)) + except TypeError as error: + raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None + return callback + + +_implementation_plan = None + +def _get_implementation_plan(): + global _implementation_plan + if _implementation_plan is None: + _implementation_plan = DynWinRTInterfacePlan.create("Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri", DynWinRTType.interface(WinGUID.parse("758d9661-221c-480f-a339-50656673f46f")), [ + DynWinRTImplementationMethod("get_AbsoluteCanonicalUri", 6, DynWinRTMethodSig().add_out(DynWinRTType.hstring())), + DynWinRTImplementationMethod("get_DisplayIri", 7, DynWinRTMethodSig().add_out(DynWinRTType.hstring())) + ], []) + return _implementation_plan + + class IUriRuntimeClassWithAbsoluteCanonicalUri: _dynwinrt_interface_type = True + @staticmethod + def implementation(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers) -> DynWinRTImplementationDescriptor: + h6 = _implementation_handler(handlers, "get_absolute_canonical_uri", 0, "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri") + h7 = _implementation_handler(handlers, "get_display_iri", 0, "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri") + plan = _get_implementation_plan() + def dispatch(vtable_index, args): + if not isinstance(args, list): + raise TypeError('implementation arguments must be a list') + if vtable_index == 6: + if len(args) != 0: + raise TypeError('implementation argument count mismatch') + result = _implementation_sync(h6(), "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.get_absolute_canonical_uri") + return [DynWinRTValue.from_hstring((lambda v: _implementation_check(v, isinstance(v, str), "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.get_absolute_canonical_uri.result"))(result))] + if vtable_index == 7: + if len(args) != 0: + raise TypeError('implementation argument count mismatch') + result = _implementation_sync(h7(), "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.get_display_iri") + return [DynWinRTValue.from_hstring((lambda v: _implementation_check(v, isinstance(v, str), "Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri.get_display_iri.result"))(result))] + raise ValueError('unknown implementation vtable slot') + return DynWinRTImplementationDescriptor(plan, dispatch) + + @classmethod + def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: + descriptors = (cls.implementation(handlers), *additional) + if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors): + raise TypeError('invalid implementation descriptor') + plans = [descriptor.plan for descriptor in descriptors] + dispatchers = tuple(descriptor.dispatch for descriptor in descriptors) + def callback(interface_index, vtable_index, args): + if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers): + raise ValueError('unknown implementation interface index') + return dispatchers[interface_index](vtable_index, args) + return DynWinRTImplementation.create(plans, callback) + + @classmethod + def from_implementation(cls, owner: DynWinRTImplementation) -> 'IUriRuntimeClassWithAbsoluteCanonicalUri': + """Query an independently owned view, tracked by the current lifetime scope.""" + if not isinstance(owner, DynWinRTImplementation): + raise TypeError('from_implementation requires a DynWinRTImplementation controller') + value = owner.to_value() + try: + native = value.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri) + try: + view = object.__new__(cls) + cls._set_native(view, native, cache=False) + return view + except BaseException: + native.release() + raise + finally: + value.release() + _dynwinrt_interface_iid = IID_IUriRuntimeClassWithAbsoluteCanonicalUri def __new__(cls, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue): return _dynwinrt_projected_from_native(cls, args[0], '_set_native') return super().__new__(cls) - def _set_native(self, obj: DynWinRTValue): + def _set_native(self, obj: DynWinRTValue, *, cache=True): self._obj = obj self._dynwinrt_native_ready = True _dynwinrt_track_projected(self, 'Windows.Foundation.IUriRuntimeClassWithAbsoluteCanonicalUri') - _dynwinrt_cache_projected(self) + if cache: + _dynwinrt_cache_projected(self) def __init__(self, obj: DynWinRTValue): if getattr(self, '_dynwinrt_native_ready', False): diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py index 0e3947bf..6d708ee0 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py @@ -14,6 +14,11 @@ _dynwinrt_symbol, _dynwinrt_track_projected, _dynwinrt_uuid, _dynwinrt_vector, _dynwinrt_wrap_values, ) +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) IID_IWwwFormUrlDecoderEntry = WinGUID.parse('125e7431-f678-4e8e-b670-20a9b06c512d') @@ -23,19 +28,156 @@ .add_method("get_Value", DynWinRTMethodSig().add_out(DynWinRTType.hstring())) +class IWwwFormUrlDecoderEntryHandlers(Protocol): + """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" + def get_name(self) -> str: ... + def get_value(self) -> str: ... + +import inspect as _implementation_inspect + + +def _implementation_check(value, valid, label): + if not valid: + raise TypeError(f'{label}: invalid implementation result') + return value + + +def _implementation_field(value, name, label): + if not isinstance(value, dict) or name not in value: + raise TypeError(f'{label}: expected a result dict containing {name}') + return value[name] + + +def _implementation_array(value, label, bytes_allowed=False, capacity=None): + if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): + raise TypeError(f'{label}: expected an array') + if capacity is not None and len(value) != capacity: + raise ValueError(f'{label}: FillArray result must match capacity {capacity}') + return list(value) + + +def _implementation_reference(value, iid, label): + if value is None: + return DynWinRTValue.null_value() + raw = getattr(value, '_obj', value) + if not isinstance(raw, DynWinRTValue): + raise TypeError(f'{label}: expected a managed WinRT value or None') + return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) + + +def _implementation_sync(value, label): + if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): + if _implementation_inspect.iscoroutine(value): + value.close() + raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') + return value + + +def _implementation_handler(handlers, name, count, label): + try: + member = _implementation_inspect.getattr_static(handlers, name) + except AttributeError: + raise TypeError(f'{label}: missing synchronous handler {name}') from None + if isinstance(member, property): + raise TypeError(f'{label}: property accessors are not callback handlers: {name}') + callback = getattr(handlers, name) + if not callable(callback): + raise TypeError(f'{label}: missing synchronous handler {name}') + if (_implementation_inspect.iscoroutinefunction(callback) + or _implementation_inspect.isasyncgenfunction(callback) + or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) + or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): + raise TypeError(f'{label}.{name}: async handlers are not supported') + try: + signature = _implementation_inspect.signature(callback) + except ValueError: + pass + else: + try: + signature.bind(*([None] * count)) + except TypeError as error: + raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None + return callback + + +_implementation_plan = None + +def _get_implementation_plan(): + global _implementation_plan + if _implementation_plan is None: + _implementation_plan = DynWinRTInterfacePlan.create("Windows.Foundation.IWwwFormUrlDecoderEntry", DynWinRTType.interface(WinGUID.parse("125e7431-f678-4e8e-b670-20a9b06c512d")), [ + DynWinRTImplementationMethod("get_Name", 6, DynWinRTMethodSig().add_out(DynWinRTType.hstring())), + DynWinRTImplementationMethod("get_Value", 7, DynWinRTMethodSig().add_out(DynWinRTType.hstring())) + ], []) + return _implementation_plan + + class IWwwFormUrlDecoderEntry: _dynwinrt_interface_type = True + @staticmethod + def implementation(handlers: IWwwFormUrlDecoderEntryHandlers) -> DynWinRTImplementationDescriptor: + h6 = _implementation_handler(handlers, "get_name", 0, "Windows.Foundation.IWwwFormUrlDecoderEntry") + h7 = _implementation_handler(handlers, "get_value", 0, "Windows.Foundation.IWwwFormUrlDecoderEntry") + plan = _get_implementation_plan() + def dispatch(vtable_index, args): + if not isinstance(args, list): + raise TypeError('implementation arguments must be a list') + if vtable_index == 6: + if len(args) != 0: + raise TypeError('implementation argument count mismatch') + result = _implementation_sync(h6(), "Windows.Foundation.IWwwFormUrlDecoderEntry.get_name") + return [DynWinRTValue.from_hstring((lambda v: _implementation_check(v, isinstance(v, str), "Windows.Foundation.IWwwFormUrlDecoderEntry.get_name.result"))(result))] + if vtable_index == 7: + if len(args) != 0: + raise TypeError('implementation argument count mismatch') + result = _implementation_sync(h7(), "Windows.Foundation.IWwwFormUrlDecoderEntry.get_value") + return [DynWinRTValue.from_hstring((lambda v: _implementation_check(v, isinstance(v, str), "Windows.Foundation.IWwwFormUrlDecoderEntry.get_value.result"))(result))] + raise ValueError('unknown implementation vtable slot') + return DynWinRTImplementationDescriptor(plan, dispatch) + + @classmethod + def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: + descriptors = (cls.implementation(handlers), *additional) + if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors): + raise TypeError('invalid implementation descriptor') + plans = [descriptor.plan for descriptor in descriptors] + dispatchers = tuple(descriptor.dispatch for descriptor in descriptors) + def callback(interface_index, vtable_index, args): + if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers): + raise ValueError('unknown implementation interface index') + return dispatchers[interface_index](vtable_index, args) + return DynWinRTImplementation.create(plans, callback) + + @classmethod + def from_implementation(cls, owner: DynWinRTImplementation) -> 'IWwwFormUrlDecoderEntry': + """Query an independently owned view, tracked by the current lifetime scope.""" + if not isinstance(owner, DynWinRTImplementation): + raise TypeError('from_implementation requires a DynWinRTImplementation controller') + value = owner.to_value() + try: + native = value.cast(IID_IWwwFormUrlDecoderEntry) + try: + view = object.__new__(cls) + cls._set_native(view, native, cache=False) + return view + except BaseException: + native.release() + raise + finally: + value.release() + _dynwinrt_interface_iid = IID_IWwwFormUrlDecoderEntry def __new__(cls, *args, **kwargs): if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue): return _dynwinrt_projected_from_native(cls, args[0], '_set_native') return super().__new__(cls) - def _set_native(self, obj: DynWinRTValue): + def _set_native(self, obj: DynWinRTValue, *, cache=True): self._obj = obj self._dynwinrt_native_ready = True _dynwinrt_track_projected(self, 'Windows.Foundation.IWwwFormUrlDecoderEntry') - _dynwinrt_cache_projected(self) + if cache: + _dynwinrt_cache_projected(self) def __init__(self, obj: DynWinRTValue): if getattr(self, '_dynwinrt_native_ready', False): diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi index af3ad47c..2a61dbc6 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/__init__.pyi @@ -3,5 +3,8 @@ from .windows__foundation__uri import Uri as Uri from .windows__foundation__www_form_url_decoder import WwwFormUrlDecoder as WwwFormUrlDecoder from .windows__foundation__collections__i_iterator_i_www_form_url_decoder_entry import IID_IIterator_IWwwFormUrlDecoderEntry, IIterator_IWwwFormUrlDecoderEntry as IIterator_IWwwFormUrlDecoderEntry from .windows__foundation__i_stringable import IID_IStringable, IStringable as IStringable +from .windows__foundation__i_stringable import IStringableHandlers as IStringableHandlers from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IID_IUriRuntimeClassWithAbsoluteCanonicalUri, IUriRuntimeClassWithAbsoluteCanonicalUri as IUriRuntimeClassWithAbsoluteCanonicalUri +from .windows__foundation__i_uri_runtime_class_with_absolute_canonical_uri import IUriRuntimeClassWithAbsoluteCanonicalUriHandlers as IUriRuntimeClassWithAbsoluteCanonicalUriHandlers from .windows__foundation__i_www_form_url_decoder_entry import IID_IWwwFormUrlDecoderEntry, IWwwFormUrlDecoderEntry as IWwwFormUrlDecoderEntry +from .windows__foundation__i_www_form_url_decoder_entry import IWwwFormUrlDecoderEntryHandlers as IWwwFormUrlDecoderEntryHandlers diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi index 847902d1..d52a5ea8 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi @@ -20,6 +20,7 @@ class _IIterator_IWwwFormUrlDecoderEntryIdentity(Protocol): def _dynwinrt_iid_windows_foundation_collections_iiterator_iwwwformurldecoderentry(self) -> None: ... class IIterator_IWwwFormUrlDecoderEntry(_IIterator_IWwwFormUrlDecoderEntryIdentity, Iterator[IWwwFormUrlDecoderEntry | None]): + # Windows.Foundation.Collections.IIterator_IWwwFormUrlDecoderEntry cannot be implemented: generic interface implementations are not supported def __init__(self, obj: DynWinRTValue) -> None: ... def __iter__(self) -> Iterator[IWwwFormUrlDecoderEntry | None]: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi index e5038c55..8b7a5c61 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi @@ -7,6 +7,12 @@ from ._typing import ( DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, _DynWinRTProjector, ) +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) +from abc import ABCMeta from typing import Protocol, Self, TypeVar _InterfaceT = TypeVar('_InterfaceT') @@ -15,10 +21,20 @@ _InterfaceT = TypeVar('_InterfaceT') IID_IStringable: WinGUID +class IStringableHandlers(Protocol): + """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" + def to_string(self) -> str: ... + +class _IStringableImplementationFactory(ABCMeta): + def implementation(cls, handlers: IStringableHandlers) -> DynWinRTImplementationDescriptor: ... + def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ... + def from_implementation(cls, owner: DynWinRTImplementation) -> IStringable: ... + + class _IStringableIdentity(Protocol): def _dynwinrt_iid_windows_foundation_istringable(self) -> None: ... -class IStringable(_IStringableIdentity, Protocol): +class IStringable(_IStringableIdentity, Protocol, metaclass=_IStringableImplementationFactory): @classmethod def from_value(cls, obj: DynWinRTValue) -> Self: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi index 3b4bf45f..e69f86c8 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi @@ -7,6 +7,12 @@ from ._typing import ( DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, _DynWinRTProjector, ) +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) +from abc import ABCMeta from typing import Protocol, Self, TypeVar _InterfaceT = TypeVar('_InterfaceT') @@ -15,10 +21,21 @@ _InterfaceT = TypeVar('_InterfaceT') IID_IUriRuntimeClassWithAbsoluteCanonicalUri: WinGUID +class IUriRuntimeClassWithAbsoluteCanonicalUriHandlers(Protocol): + """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" + def get_absolute_canonical_uri(self) -> str: ... + def get_display_iri(self) -> str: ... + +class _IUriRuntimeClassWithAbsoluteCanonicalUriImplementationFactory(ABCMeta): + def implementation(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers) -> DynWinRTImplementationDescriptor: ... + def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ... + def from_implementation(cls, owner: DynWinRTImplementation) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... + + class _IUriRuntimeClassWithAbsoluteCanonicalUriIdentity(Protocol): def _dynwinrt_iid_windows_foundation_iuriruntimeclasswithabsolutecanonicaluri(self) -> None: ... -class IUriRuntimeClassWithAbsoluteCanonicalUri(_IUriRuntimeClassWithAbsoluteCanonicalUriIdentity, Protocol): +class IUriRuntimeClassWithAbsoluteCanonicalUri(_IUriRuntimeClassWithAbsoluteCanonicalUriIdentity, Protocol, metaclass=_IUriRuntimeClassWithAbsoluteCanonicalUriImplementationFactory): @classmethod def from_value(cls, obj: DynWinRTValue) -> Self: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi index 90757e21..02a9d22f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi @@ -7,6 +7,12 @@ from ._typing import ( DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, _DynWinRTProjector, ) +from typing import Protocol, TypedDict +from dynwinrt import ( + DynWinRTInterfacePlan, DynWinRTImplementationMethod, + DynWinRTImplementation, DynWinRTImplementationDescriptor, +) +from abc import ABCMeta from typing import Protocol, Self, TypeVar _InterfaceT = TypeVar('_InterfaceT') @@ -15,10 +21,21 @@ _InterfaceT = TypeVar('_InterfaceT') IID_IWwwFormUrlDecoderEntry: WinGUID +class IWwwFormUrlDecoderEntryHandlers(Protocol): + """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" + def get_name(self) -> str: ... + def get_value(self) -> str: ... + +class _IWwwFormUrlDecoderEntryImplementationFactory(ABCMeta): + def implementation(cls, handlers: IWwwFormUrlDecoderEntryHandlers) -> DynWinRTImplementationDescriptor: ... + def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ... + def from_implementation(cls, owner: DynWinRTImplementation) -> IWwwFormUrlDecoderEntry: ... + + class _IWwwFormUrlDecoderEntryIdentity(Protocol): def _dynwinrt_iid_windows_foundation_iwwwformurldecoderentry(self) -> None: ... -class IWwwFormUrlDecoderEntry(_IWwwFormUrlDecoderEntryIdentity, Protocol): +class IWwwFormUrlDecoderEntry(_IWwwFormUrlDecoderEntryIdentity, Protocol, metaclass=_IWwwFormUrlDecoderEntryImplementationFactory): @classmethod def from_value(cls, obj: DynWinRTValue) -> Self: ... diff --git a/tools/dynwinrt-codegen/tests/tsc_check_test.rs b/tools/dynwinrt-codegen/tests/tsc_check_test.rs index 97b0099c..4c78f045 100644 --- a/tools/dynwinrt-codegen/tests/tsc_check_test.rs +++ b/tools/dynwinrt-codegen/tests/tsc_check_test.rs @@ -157,6 +157,8 @@ fn generated_dts_passes_tsc_no_emit() { import { User } from "./windows/system/User.js"; import { ContactDate } from "./windows/application-model/contacts/ContactDate.js"; import { IReference_UInt32 } from "./windows/foundation/IReference_UInt32.js"; +import { IStringable } from "./windows/foundation/IStringable.js"; +import { releaseProjected } from "./lifetime.js"; new Uri("https://example.com"); new Uri("https://example.com/base/", "child"); @@ -165,6 +167,15 @@ new Uri(); // @ts-expect-error User instances can only be returned by the system. new User(); +const owner = IStringable.implement({ toString: () => "public view" }); +const view: IStringable = IStringable.fromImplementation(owner); +function consumeStringable(value: IStringable): string { return value.toString(); } +const text: string = consumeStringable(view); +// @ts-expect-error Native interface constructors remain internal. +new IStringable(owner.toValue()); +releaseProjected(view); +owner.dispose(); + const contactDate = ContactDate.create(); const day: number | null = contactDate.day; contactDate.day = 17; @@ -232,6 +243,24 @@ export declare class DynWinRtMethodSig { addOutFill(t: DynWinRtType): DynWinRtMethodSig; [key: string]: any; } +export declare class DynWinRtInterfacePlan { + private constructor(); + static create(name: string, interfaceType: DynWinRtType, methods: { name: string; vtableIndex: number; signature: DynWinRtMethodSig }[], requiredIids?: WinGuid[]): DynWinRtInterfacePlan; +} +export interface DynWinRtImplementationDescriptor { + readonly plan: DynWinRtInterfacePlan; + readonly dispatch: (vtableIndex: number, args: DynWinRtValue[]) => DynWinRtValue[]; +} +export declare class DynWinRtImplementation { + private constructor(); + static create(interfaces: DynWinRtInterfacePlan[], callback: (interfaceIndex: number, vtableIndex: number, args: DynWinRtValue[]) => DynWinRtValue[], runtimeClassName?: string): DynWinRtImplementation; + toValue(): DynWinRtValue; + release(): void; + dispose(): void; + disconnect(): void; + readonly isClosed: boolean; + takeError(): string | null; +} export declare class DynWinRtValue { toNumber(): number; toI64(): number; diff --git a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs new file mode 100644 index 00000000..85ea416b --- /dev/null +++ b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs @@ -0,0 +1,1246 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +mod common; + +use std::collections::{HashMap, HashSet}; +use std::io::Write; +use std::path::Path; +use std::process::{Command, Stdio}; + +use dynwinrt_codegen::codegen::{javascript, project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::meta::{ + self, ImplementationDelegateMeta, InterfaceImplementationMetadata, InterfaceMeta, MethodMeta, + ParamDirection, ParamMeta, +}; +use dynwinrt_codegen::types::{FieldMeta, TypeMeta}; + +const WINDOWS_WINMD: &str = + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; + +fn generated(iface: &InterfaceMeta) -> [String; 4] { + let known = HashSet::from([iface.name.clone()]); + let projected = project::project_interface( + &Default::default(), + iface, + &known, + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let context = + common::projection_context(&[], std::slice::from_ref(iface), &known, &HashSet::new()); + [ + render_js::render(&projected), + render_dts::render(&projected), + python::generate_interface(&context, iface), + python_stub::generate_interface_stub(&context, iface), + ] +} + +fn fixture() -> InterfaceMeta { + let delegate = TypeMeta::Delegate { + namespace: "Tests".into(), + name: "Callback".into(), + iid: "3fe67b63-0ad2-4b10-8b25-4f5d7696cb03".into(), + }; + let fill_delegate = TypeMeta::Delegate { + namespace: "Tests".into(), + name: "FillCallback".into(), + iid: "6df84c34-56fe-47fd-a7d6-2a10e986efc4".into(), + }; + let reference = TypeMeta::Parameterized { + namespace: "Windows.Foundation".into(), + name: "IReference`1".into(), + piid: "61c17706-2d65-11e0-9ae8-d48564015472".into(), + args: vec![TypeMeta::I32], + }; + let hresult = TypeMeta::Struct { + namespace: "Windows.Foundation".into(), + name: "HResult".into(), + fields: vec![FieldMeta { + name: "Value".into(), + typ: TypeMeta::I32, + }], + }; + InterfaceMeta { + namespace: "Tests".into(), + name: "IContract".into(), + iid: "119ade03-d016-4c34-8813-4c2c3678dada".into(), + methods: vec![ + MethodMeta { + name: "get_Title".into(), + vtable_index: 6, + is_property_getter: true, + return_type: Some(TypeMeta::String), + ..Default::default() + }, + MethodMeta { + name: "put_Title".into(), + vtable_index: 7, + is_property_setter: true, + params: vec![ParamMeta { + name: "value".into(), + typ: TypeMeta::String, + direction: ParamDirection::In, + }], + ..Default::default() + }, + MethodMeta { + name: "Transform".into(), + vtable_index: 8, + params: vec![ + ParamMeta { + name: "label".into(), + typ: TypeMeta::String, + direction: ParamDirection::Out, + }, + ParamMeta { + name: "values".into(), + typ: TypeMeta::Array(Box::new(TypeMeta::I32)), + direction: ParamDirection::In, + }, + ParamMeta { + name: "buffer".into(), + typ: TypeMeta::Array(Box::new(TypeMeta::I32)), + direction: ParamDirection::OutFill, + }, + ], + return_type: Some(TypeMeta::Bool), + ..Default::default() + }, + MethodMeta { + name: "UseCallback".into(), + vtable_index: 9, + params: vec![ParamMeta { + name: "callback".into(), + typ: delegate.clone(), + direction: ParamDirection::In, + }], + return_type: Some(TypeMeta::String), + ..Default::default() + }, + MethodMeta { + name: "GetObject".into(), + vtable_index: 10, + return_type: Some(TypeMeta::Object), + ..Default::default() + }, + MethodMeta { + name: "EchoOptional".into(), + vtable_index: 11, + params: vec![ParamMeta { + name: "value".into(), + typ: reference.clone(), + direction: ParamDirection::In, + }], + return_type: Some(reference), + ..Default::default() + }, + MethodMeta { + name: "UseContract".into(), + vtable_index: 12, + params: vec![ParamMeta { + name: "value".into(), + typ: TypeMeta::Interface { + namespace: "Tests".into(), + name: "IContract".into(), + iid: "119ade03-d016-4c34-8813-4c2c3678dada".into(), + }, + direction: ParamDirection::In, + }], + return_type: Some(TypeMeta::Bool), + ..Default::default() + }, + MethodMeta { + name: "UseFillCallback".into(), + vtable_index: 13, + params: vec![ParamMeta { + name: "callback".into(), + typ: fill_delegate.clone(), + direction: ParamDirection::In, + }], + return_type: Some(TypeMeta::Bool), + ..Default::default() + }, + MethodMeta { + name: "RoundTripHresult".into(), + vtable_index: 14, + params: vec![ParamMeta { + name: "value".into(), + typ: hresult.clone(), + direction: ParamDirection::In, + }], + return_type: Some(hresult.clone()), + ..Default::default() + }, + MethodMeta { + name: "RoundTripHresults".into(), + vtable_index: 15, + params: vec![ParamMeta { + name: "values".into(), + typ: TypeMeta::Array(Box::new(hresult.clone())), + direction: ParamDirection::In, + }], + return_type: Some(TypeMeta::Array(Box::new(hresult))), + ..Default::default() + }, + ], + implementation_metadata: InterfaceImplementationMetadata { + delegates: vec![ + ImplementationDelegateMeta { + typ: delegate, + invoke: MethodMeta { + name: "Invoke".into(), + vtable_index: 3, + params: vec![ParamMeta { + name: "value".into(), + typ: TypeMeta::I32, + direction: ParamDirection::In, + }], + return_type: Some(TypeMeta::String), + ..Default::default() + }, + }, + ImplementationDelegateMeta { + typ: fill_delegate, + invoke: MethodMeta { + name: "Invoke".into(), + vtable_index: 3, + params: vec![ParamMeta { + name: "buffer".into(), + typ: TypeMeta::Array(Box::new(TypeMeta::I32)), + direction: ParamDirection::OutFill, + }], + return_type: Some(TypeMeta::U32), + ..Default::default() + }, + }, + ], + ..Default::default() + }, + ..Default::default() + } +} + +fn run(program: &str, args: &[&str], input: &str) -> String { + let mut child = Command::new(program) + .env("PYTHONUTF8", "1") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("start installed language runner"); + child + .stdin + .take() + .unwrap() + .write_all(input.as_bytes()) + .unwrap(); + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout).unwrap() +} + +#[test] +fn implementation_renderers_preserve_abi_order_and_emit_typed_named_results() { + let [js, dts, py, pyi] = generated(&fixture()); + assert!(js.contains("signature: new DynWinRtMethodSig().addOut(DynWinRtType.hstring()).addIn(DynWinRtType.arrayType(DynWinRtType.i32())).addOutFill(DynWinRtType.arrayType(DynWinRtType.i32())).addOut(DynWinRtType.boolType())"), "{js}"); + assert!(py.contains("DynWinRTImplementationMethod(\"Transform\", 8, DynWinRTMethodSig().add_out(DynWinRTType.hstring()).add_in(DynWinRTType.array_type(DynWinRTType.i32_type())).add_out_fill(DynWinRTType.array_type(DynWinRTType.i32_type())).add_out(DynWinRTType.bool_type()))"), "{py}"); + assert!(dts.contains("transform(values: (number)[], bufferCapacity: number): { label: string; buffer: (number)[]; result: boolean }"), "{dts}"); + assert!(dts.contains("getTitle(): string") && dts.contains("setTitle(value: string): void")); + assert!(pyi.contains("def transform(self, values: list[int], buffer_capacity: int) -> IContractImplementationTransformResult"), "{pyi}"); + assert!(pyi.contains("class IContractImplementationTransformResult(TypedDict):\n label: str\n buffer: list[int]\n result: bool")); + assert!(js.contains("bufferCapacity") || dts.contains("bufferCapacity")); + assert!( + js.contains("FillArray result must match capacity") + && py.contains("FillArray result must match capacity") + ); + assert!(dts.contains("private constructor();")); + assert!(dts.contains("static fromImplementation(owner: DynWinRtImplementation): IContract;")); + assert!( + pyi.contains( + "def from_implementation(cls, owner: DynWinRTImplementation) -> IContract: ..." + ) + ); + assert!(js.contains("const value = owner.toValue();")); + assert!( + js.contains("return this.from(value);\n } finally {\n value.release();") + ); + assert!(py.contains("value = owner.to_value()")); + assert!(py.contains("native = value.cast(IID_IContract)")); + assert!(py.contains("cls._set_native(view, native, cache=False)")); + assert!(py.contains( + "except BaseException:\n native.release()\n raise" + )); + assert!(py.contains("finally:\n value.release()")); +} + +#[test] +fn implementation_result_names_are_chosen_once_before_language_naming() { + let iface = InterfaceMeta { + namespace: "Tests".into(), + name: "IResults".into(), + iid: "119ade03-d016-4c34-8813-4c2c3678dada".into(), + methods: vec![MethodMeta { + name: "Read".into(), + vtable_index: 6, + params: ["RESULT", "result_"] + .into_iter() + .map(|name| ParamMeta { + name: name.into(), + typ: TypeMeta::I32, + direction: ParamDirection::Out, + }) + .collect(), + return_type: Some(TypeMeta::Bool), + ..Default::default() + }], + ..Default::default() + }; + let [js, dts, py, pyi] = generated(&iface); + assert!( + dts.contains("{ rESULT: number; result_: number; result__: boolean }"), + "{dts}" + ); + assert!( + pyi.contains(" result: int\n result_: int\n result__: bool"), + "{pyi}" + ); + assert!(js.contains("__implementationField(result, \"result__\"")); + assert!(py.contains("_implementation_field(result, \"result__\"")); +} + +#[test] +fn implementation_hresult_values_and_arrays_use_exact_factories() { + let [js, _, py, _] = generated(&fixture()); + assert!(js.contains("DynWinRtValue.hresult(")); + assert!(js.contains("DynWinRtArray.fromHresultValues(")); + assert!(py.contains("DynWinRTValue.from_hresult(")); + assert!(py.contains("DynWinRTArray.from_values([DynWinRTValue.from_hresult(")); + assert!( + js.contains("DynWinRtValue.i32("), + "ordinary I32 values must retain their factory" + ); + assert!( + py.contains("DynWinRTValue.from_i32("), + "ordinary I32 values must retain their factory" + ); +} + +#[test] +fn implementation_invalid_contracts_keep_outbound_generation_and_reject_factories() { + let mut cases = Vec::new(); + let mut generic = fixture(); + generic.generic_piid = Some(generic.iid.clone()); + generic.generic_args = vec![TypeMeta::I32]; + cases.push((generic, "generic interface implementations")); + let mut incomplete = fixture(); + incomplete.methods[1].vtable_index = 10; + cases.push((incomplete, "incomplete or non-WinRT vtable")); + let mut missing_iid = fixture(); + missing_iid.iid.clear(); + cases.push((missing_iid, "IID is unresolved")); + let mut unknown = fixture(); + unknown + .implementation_metadata + .diagnostics + .push("unknown pointer contract".into()); + cases.push((unknown, "unknown pointer contract")); + let mut collision = fixture(); + collision.methods[1].name = "GetTitle".into(); + collision.methods[1].is_property_setter = false; + cases.push((collision, "handler name collision")); + for (iface, expected) in cases { + let [js, dts, py, pyi] = generated(&iface); + for output in [&js, &dts, &py, &pyi] { + assert!(output.contains(expected), "{expected}\n{output}"); + } + assert!(js.contains("class IContract") && py.contains("class IContract")); + assert!(dts.contains("handlers: never") && !pyi.contains("def implement(")); + assert!( + !js.contains("DynWinRtImplementation.create") + && !py.contains("DynWinRTImplementation.create") + ); + } +} + +#[test] +fn implementation_stock_winmd_covers_background_strings_closing_properties_events_arrays_and_multiout() + { + if !Path::new(WINDOWS_WINMD).is_file() { + eprintln!("Skipping: Windows.winmd is unavailable"); + return; + } + let foundation = meta::parse_interfaces(WINDOWS_WINMD, "Windows.Foundation"); + let background = meta::parse_interfaces(WINDOWS_WINMD, "Windows.ApplicationModel.Background"); + for (interfaces, name, method) in [ + (&foundation, "IStringable", "ToString"), + (&foundation, "IClosable", "Close"), + (&background, "IBackgroundTask", "Run"), + ] { + let iface = interfaces.iter().find(|iface| iface.name == name).unwrap(); + assert_eq!(iface.methods[0].vtable_index, 6); + let [js, dts, py, pyi] = generated(iface); + assert!( + js.contains("DynWinRtImplementation.create") + && py.contains("DynWinRTImplementation.create"), + "{js}\n{py}" + ); + assert!(js.contains(&format!("name: \"{method}\", vtableIndex: 6"))); + assert!( + dts.contains(&format!("{name}Handlers")) && pyi.contains(&format!("{name}Handlers")) + ); + } + let instance = background + .iter() + .find(|iface| iface.name == "IBackgroundTaskInstance") + .unwrap(); + assert!(!instance.implementation_metadata.delegates.is_empty()); + assert_eq!( + instance.implementation_metadata.delegates[0] + .invoke + .vtable_index, + 3 + ); + let [js, dts, py, pyi] = generated(instance); + assert!( + dts.contains("getProgress") && dts.contains("setProgress") && dts.contains("addCanceled") + ); + assert!( + pyi.contains("get_progress") + && pyi.contains("set_progress") + && pyi.contains("add_canceled") + ); + assert!(js.contains(".invokeDelegate(") && py.contains(".invoke_delegate(")); + let reader = meta::parse_class(WINDOWS_WINMD, "Windows.Storage.Streams", "DataReader") + .unwrap() + .default_interface + .unwrap(); + assert!(reader.methods.iter().any(|method| { + method + .params + .iter() + .any(|p| p.direction == ParamDirection::OutFill) + })); + let [js, _, py, _] = generated(&reader); + assert!( + js.contains("addOutFill") && js.contains("DynWinRtImplementation.create"), + "{js}" + ); + assert!( + py.contains("add_out_fill") && py.contains("DynWinRTImplementation.create"), + "{py}" + ); + let properties = foundation + .iter() + .find(|iface| iface.name == "IPropertyValue") + .unwrap(); + let [js, _, py, _] = generated(properties); + assert!( + js.contains("DynWinRtArray.fromObjectValues") + && js.contains("DynWinRtImplementation.create") + ); + assert!( + py.contains("DynWinRTArray.from_object_values") + && py.contains("DynWinRTImplementation.create") + ); + let transforms = + meta::parse_class(WINDOWS_WINMD, "Windows.UI.Xaml.Media", "GeneralTransform").unwrap(); + let transform = transforms.default_interface.unwrap(); + assert!(transform.methods.iter().any(|method| { + method.return_type.is_some() + && method + .params + .iter() + .any(|param| param.direction == ParamDirection::Out) + })); + let [js, dts, py, pyi] = generated(&transform); + assert!( + js.contains("DynWinRtImplementation.create") + && py.contains("DynWinRTImplementation.create") + ); + assert!(dts.contains("result: boolean") && pyi.contains("result: bool")); + let streams = meta::parse_interfaces(WINDOWS_WINMD, "Windows.Storage.Streams"); + let random_access = streams + .iter() + .find(|interface| interface.name == "IRandomAccessStream") + .unwrap(); + let requirements = &random_access.implementation_metadata.required_interfaces; + for name in ["IInputStream", "IOutputStream", "IClosable"] { + assert!( + requirements.iter().any( + |typ| matches!(typ, TypeMeta::Interface { name: actual, .. } if actual == name) + ), + "{name}: {requirements:?}" + ); + } + assert!( + !random_access + .methods + .iter() + .any(|method| method.name == "ReadAsync" || method.name == "WriteAsync") + ); + let [js, dts, py, pyi] = generated(random_access); + assert!( + js.contains("DynWinRtImplementation.create") + && py.contains("DynWinRTImplementation.create") + ); + assert!(dts.contains("Required QI views") && pyi.contains("Required QI views")); + for iid in [ + "905a0fe2-bc53-11df-8c49-001e4fc686da", + "905a0fe6-bc53-11df-8c49-001e4fc686da", + "30d5a829-7fa4-4026-83bb-d75bae4ea99e", + ] { + assert!(js.contains(iid) && py.contains(iid), "{iid}"); + } +} + +#[test] +fn implementation_javascript_projection_validates_handlers_results_arrays_and_dispatch() { + let [js, _, _, _] = generated(&fixture()); + let test = r#" +const assert = require('node:assert/strict'); +const input = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +// Projection-only doubles: native vtables/ownership are covered by the native and E2E suites. +class Value { + constructor(kind, value) { + this.kind = kind; this.value = value; this.releases = 0; + if (kind === 'object' && value?.owner) value.owner.references++; + } + toString() { return this.value; } toNumber() { return this.value; } toBool() { return this.value; } + asArray() { return this.value; } isNull() { return this.value === null; } + cast(iid) { + if (this.kind !== 'object') throw new TypeError('not an object'); + if (this.value?.owner?.failQueryInterface) throw new TypeError('QueryInterface failure'); + return new Value(this.kind, this.value); + } + release() { + this.releases++; + if (this.kind === 'object' && this.value?.owner) this.value.owner.references--; + this.kind = 'null'; this.value = null; + } + invokeDelegate(iid, signature, args) { + if (iid === '6df84c34-56fe-47fd-a7d6-2a10e986efc4') { + assert.deepEqual(signature.parameters.map(p => p[0]), ['addOutFill', 'addOut']); + assert.equal(args.length, 1); + assert.equal(args[0].kind, 'array'); + assert.deepEqual(args[0].asArray().toValues().map(value => value.value), [0, 0, 0]); + return [ArrayValue.fromObjectValues([Value.i32(7), Value.i32(7), Value.i32(7)]).toValue(), Value.u32(3)]; + } + assert.equal(iid, '3fe67b63-0ad2-4b10-8b25-4f5d7696cb03'); + assert.deepEqual(signature.parameters.map(p => p[0]), ['addIn', 'addOut']); + return [Value.hstring(`delegate:${args[0].value}`)]; + } +} +for (const name of ['i32', 'u32', 'hstring', 'boolValue']) Value[name] = value => new Value(name, value); +Value.hresult = value => { + if (!Number.isInteger(value) || value < -2147483648 || value > 2147483647) throw new RangeError('HRESULT range'); + return new Value('hresult', value); +}; +Value.nullValue = () => new Value('null', null); +Value.boxReference = value => new Value('object', { boxed: value }); +const Type = new Proxy({}, { get(_, key) { return (...args) => ({ + key, args, iid() { return args[0]; }, addMethod() { return this; }, + method(slot) { return { invoke(obj, args) { + if (obj.value.boxed) { assert.equal(slot, 6); return obj.value.boxed; } + return obj.value.owner.callback(0, slot, args)[0] ?? Value.nullValue(); + } }; }, +}); } }); +class Signature { constructor() { this.parameters = []; } } +for (const name of ['addIn', 'addOut', 'addOutFill']) Signature.prototype[name] = function(type) { this.parameters.push([name, type]); return this; }; +class Plan { static create(name, type, methods, required) { return Object.assign(new Plan(), { name, type, methods, required }); } } +let published = 0; +class Implementation { + static create(plans, callback) { published++; return Object.assign(new Implementation(), { plans, callback, references: 1 }); } + toValue() { return (this.lastValue = new Value('object', { owner: this })); } +} +function releaseProjected(view) { view._obj.release(); } +const ArrayValue = { + fromObjectValues(values, type) { + return { toValue: () => new Value('array', { toValues: () => [...values], toI32Vec: () => values.map(value => value.value) }) }; + }, + fromHresultValues(values) { return this.fromObjectValues(values.map(Value.hresult)); }, +}; +const runtime = { DynWinRtValue: Value, DynWinRtType: Type, DynWinRtMethodSig: Signature, DynWinRtInterfacePlan: Plan, DynWinRtImplementation: Implementation, DynWinRtArray: ArrayValue, WinGuid: { parse: value => value } }; +const moduleObject = { exports: {} }; +new Function('require', 'module', 'exports', input)((name) => runtime, moduleObject, moduleObject.exports); +const IContract = moduleObject.exports.IContract; +let title = 'start', seen; +const handlers = { + getTitle() { return title; }, setTitle(value) { title = value; }, + transform(values, bufferCapacity) { seen = [values, bufferCapacity]; return { label: 'ok', buffer: Array(bufferCapacity).fill(values[0] + 1), result: true }; }, + useCallback(callback) { if (callback === null) return 'null'; assert(callback._obj instanceof Value); return callback(7); }, + getObject() { return Value.nullValue(); }, + echoOptional(value) { return value; }, + useContract(value) { return value !== null && value.title === 'public view'; }, + useFillCallback(callback) { + if (callback === null) return false; + const result = callback(3); + assert.deepEqual(result, { buffer: [7, 7, 7], result: 3 }); + return true; + }, + roundTripHresult(value) { return value; }, + roundTripHresults(values) { return values; }, +}; +assert.throws(() => IContract.implement({}), /missing synchronous handler/); +assert.throws(() => IContract.implement({ ...handlers, getTitle: async () => 'bad' }), /async handlers/); +let getterCalls = 0; +assert.throws(() => IContract.implement({ ...handlers, get getTitle() { getterCalls++; return () => 'bad'; } }), /accessors/); +assert.equal(getterCalls, 0); assert.equal(published, 0); +const invokeDelegate = Value.prototype.invokeDelegate; +delete Value.prototype.invokeDelegate; +assert.throws(() => IContract.implement(handlers), /requires WinRT delegate invocation/); +Value.prototype.invokeDelegate = invokeDelegate; +const descriptor = IContract.implementation(handlers); +assert.equal(descriptor.dispatch(6, [])[0].value, 'start'); +descriptor.dispatch(7, [Value.hstring('changed')]); assert.equal(title, 'changed'); +const values = ArrayValue.fromObjectValues([Value.i32(4), Value.i32(5)]).toValue(); +const results = descriptor.dispatch(8, [values, Value.u32(3)]); +assert.deepEqual(seen, [[4, 5], 3]); +assert.deepEqual(results.map(v => v.kind), ['hstring', 'array', 'boolValue']); +assert.deepEqual(results[1].asArray().toValues().map(v => v.value), [5, 5, 5]); +assert.equal(descriptor.dispatch(9, [new Value('object', {})])[0].value, 'delegate:7'); +assert.equal(descriptor.dispatch(9, [new Value('object', null)])[0].value, 'null'); +assert.equal(descriptor.dispatch(10, [])[0].isNull(), true); +assert.equal(descriptor.dispatch(11, [Value.boxReference(Value.i32(8))])[0].value.boxed.value, 8); +assert.equal(descriptor.dispatch(11, [Value.nullValue()])[0].isNull(), true); +assert.equal(descriptor.dispatch(13, [new Value('object', {})])[0].value, true); +const semanticHresult = descriptor.dispatch(14, [Value.hresult(-2147467259)])[0]; +assert.equal(semanticHresult.kind, 'hresult'); +assert.equal(semanticHresult.value, -2147467259); +const hresultArray = descriptor.dispatch(15, [ArrayValue.fromHresultValues([-2147467259, 0]).toValue()])[0]; +assert.deepEqual(hresultArray.asArray().toValues().map(value => [value.kind, value.value]), [['hresult', -2147467259], ['hresult', 0]]); +assert.throws(() => IContract.implementation({ ...handlers, roundTripHresults: () => [2147483648] }).dispatch(15, [hresultArray]), /invalid implementation result/); +assert.throws(() => descriptor.dispatch(3, []), /unknown implementation vtable slot/); +assert.throws(() => descriptor.dispatch(8, []), /argument count/); +assert.throws(() => IContract.implementation({ ...handlers, getTitle: () => ({ then() {} }) }).dispatch(6, []), /thenable/); +assert.throws(() => IContract.implementation({ ...handlers, transform: () => ({ label: 'bad', buffer: [], result: true }) }).dispatch(8, [values, Value.u32(3)]), /match capacity/); +assert.throws(() => IContract.implementation({ ...handlers, transform: () => ({ label: 'bad', buffer: [2147483648], result: true }) }).dispatch(8, [values, Value.u32(1)]), /invalid implementation result/); +assert.throws(() => IContract.implementation({ ...handlers, transform: () => ({ buffer: [1], result: true }) }).dispatch(8, [values, Value.u32(1)]), /missing data field/); +const owner = IContract.implement(handlers); +assert.equal(owner.callback(0, 6, [])[0].value, 'changed'); +assert.throws(() => owner.callback(-1, 6, []), /unknown implementation interface index/); +const view = IContract.fromImplementation(owner); +assert(view instanceof IContract); +assert.equal(owner.lastValue.releases, 1); +assert.equal(owner.references, 2); +assert.equal(view.title, 'changed'); +view.title = 'public view'; +assert.equal(view.useContract(view), true); +assert.equal(view.roundTripHresult(-2147467259), -2147467259); +assert.deepEqual(view.roundTripHresults([-2147467259, 0]), [-2147467259, 0]); +releaseProjected(view); +assert.equal(owner.references, 1); +assert.equal(owner.callback(0, 6, [])[0].value, 'public view'); +owner.failQueryInterface = true; +assert.throws(() => IContract.fromImplementation(owner), /QueryInterface failure/); +assert.equal(owner.lastValue.releases, 1); +assert.equal(owner.references, 1); +owner.failQueryInterface = false; +const originalFrom = IContract.from; +IContract.from = () => { throw new TypeError('projection failure'); }; +assert.throws(() => IContract.fromImplementation(owner), /projection failure/); +assert.equal(owner.lastValue.releases, 1); +assert.equal(owner.references, 1); +IContract.from = originalFrom; +const recovered = IContract.fromImplementation(owner); +assert.equal(recovered.title, 'public view'); +releaseProjected(recovered); +assert.equal(owner.references, 1); +assert.throws(() => IContract.fromImplementation({}), /requires a DynWinRtImplementation controller/); +console.log('JavaScript projection assertions passed'); +"#; + let output = run("node", &["-e", test], &serde_json::to_string(&js).unwrap()); + assert!(output.contains("assertions passed")); +} + +#[test] +fn implementation_javascript_handler_lookup_excludes_builtin_prototypes() { + let sources = ["IStringable", "IUserCallbacks"].map(|name| { + let mut iface = InterfaceMeta { + namespace: "Tests".into(), + name: name.into(), + iid: "119ade03-d016-4c34-8813-4c2c3678dada".into(), + methods: vec![MethodMeta { + name: "ToString".into(), + vtable_index: 6, + return_type: Some(TypeMeta::String), + ..Default::default() + }], + ..Default::default() + }; + if name == "IUserCallbacks" { + iface.methods.push(MethodMeta { + name: "Call".into(), + vtable_index: 7, + return_type: Some(TypeMeta::String), + ..Default::default() + }); + } + serde_json::json!({ "name": name, "source": generated(&iface)[0] }) + }); + let script = r#" +const assert = require('node:assert/strict'); +const sources = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +let plansCreated = 0; +class Signature { addOut() { return this; } } +class Value { static hstring(value) { return value; } } +const runtime = { + DynWinRtType: { interface: iid => iid, hstring: () => 'hstring' }, + DynWinRtMethodSig: Signature, DynWinRtValue: Value, + DynWinRtInterfacePlan: { create() { plansCreated++; return {}; } }, + DynWinRtImplementation: class {}, + WinGuid: { parse: iid => iid }, +}; +for (const { name, source } of sources) { + const module = { exports: {} }; + new Function('require', 'module', 'exports', source)(() => runtime, module, module.exports); + const Interface = module.exports[name]; + const before = plansCreated; + assert.throws(() => Interface.implementation({}), /missing synchronous handler toString/); + assert.throws(() => Interface.implementation(function () {}), /missing synchronous handler toString/); + assert.throws(() => Interface.implementation(Object.create(Function.prototype)), /missing synchronous handler toString/); + assert.equal(plansCreated, before); + class BaseHandlers { + toString() { return this.label; } + call() { return 'user class call'; } + } + class DerivedHandlers extends BaseHandlers { + constructor() { super(); this.label = 'user class string'; } + } + const descriptor = Interface.implementation(new DerivedHandlers()); + assert.deepEqual(descriptor.dispatch(6, []), ['user class string']); + const explicit = function () {}; + explicit.toString = () => 'explicit function handler'; + if (name === 'IUserCallbacks') { + assert.throws(() => Interface.implementation(explicit), /missing synchronous handler call/); + explicit.call = () => 'explicit call handler'; + assert.deepEqual(Interface.implementation(explicit).dispatch(7, []), ['explicit call handler']); + } + assert.deepEqual(Interface.implementation(explicit).dispatch(6, []), ['explicit function handler']); +} +console.log('prototype validation passed'); +"#; + assert!( + run( + "node", + &["-e", script], + &serde_json::to_string(&sources).unwrap() + ) + .contains("prototype validation passed") + ); +} + +#[test] +fn implementation_python_projection_validates_handlers_results_arrays_and_dispatch() { + let [_, _, py, _] = generated(&fixture()); + let test = r#" +import sys, json, types, typing, datetime, uuid, weakref +source = json.load(sys.stdin) +# Projection-only doubles, not native ABI fixtures. +class Value: + def __init__(self, kind, value): + self.kind, self.value, self.releases = kind, value, 0 + if kind == 'object' and hasattr(value, 'owner'): value.owner.references += 1 + def to_string(self): return self.value + def to_number(self): return self.value + def to_u32(self): return self.value + def to_bool(self): return self.value + def as_array(self): return self.value + def is_null(self): return self.value is None + def cast(self, iid): + if self.kind != 'object': raise TypeError('not an object') + if getattr(getattr(self.value, 'owner', None), 'fail_query_interface', False): + raise TypeError('QueryInterface failure') + return Value(self.kind, self.value) + def release(self): + self.releases += 1 + if self.kind == 'object' and hasattr(self.value, 'owner'): self.value.owner.references -= 1 + self.kind, self.value = 'null', None + def invoke_delegate(self, iid, signature, args): + if iid == '6df84c34-56fe-47fd-a7d6-2a10e986efc4': + assert [kind for kind, typ in signature.parameters] == ['OutFill', 'Out'] + assert len(args) == 1 + assert args[0].kind == 'array' + assert [value.value for value in args[0].as_array().to_values()] == [0, 0, 0] + return [Array([Value.from_i32(7), Value.from_i32(7), Value.from_i32(7)]).to_value(), Value.from_u32(3)] + assert iid == '3fe67b63-0ad2-4b10-8b25-4f5d7696cb03' + assert [kind for kind, typ in signature.parameters] == ['In', 'Out'] + return [Value.from_hstring(f'delegate:{args[0].value}')] +for name in ('from_i32', 'from_u32', 'from_hstring', 'from_bool'): + setattr(Value, name, staticmethod(lambda value, name=name: Value(name, value))) +Value.from_hresult = staticmethod(lambda value: Value('hresult', value)) +Value.null_value = staticmethod(lambda: Value('null', None)) +Value.box_reference = staticmethod(lambda value, typ: Value('object', types.SimpleNamespace(boxed=value))) +class NativeType: + def __init__(self, key, args): self.key, self.args = key, args + def iid(self): return self.args[0] + def add_method(self, *args): return self + def method(self, slot): + def invoke(obj, args): + if hasattr(obj.value, 'boxed'): + assert slot == 6 + return obj.value.boxed + outputs = obj.value.owner.callback(0, slot, args) + return outputs[0] if outputs else Value.null_value() + return types.SimpleNamespace(invoke=invoke, get_string=lambda obj: invoke(obj, []).to_string()) +class Types(type): + def __getattr__(cls, name): return lambda *args: NativeType(name, args) +class Type(metaclass=Types): pass +class Signature: + def __init__(self): self.parameters = [] + def add_in(self, typ): self.parameters.append(('In', typ)); return self + def add_out(self, typ): self.parameters.append(('Out', typ)); return self + def add_out_fill(self, typ): self.parameters.append(('OutFill', typ)); return self +class Method: + def __init__(self, name, slot, signature): self.name, self.slot, self.signature = name, slot, signature +class Plan: + @staticmethod + def create(*args): return Plan() +class Descriptor: + def __init__(self, plan, dispatch): self.plan, self.dispatch = plan, dispatch +class Implementation: + published = 0 + @staticmethod + def create(plans, callback): + Implementation.published += 1 + owner = Implementation() + owner.plans, owner.callback = plans, callback + owner.references = 1 + return owner + def to_value(self): + self.last_value = Value('object', types.SimpleNamespace(owner=self)) + return self.last_value +def release_projected(view): view._obj.release() +class Array: + def __init__(self, values): self.values = values + @staticmethod + def from_values(values, typ=None): return Array(values) + @staticmethod + def from_object_values(values, typ=None): return Array(values) + def to_value(self): return Value('array', self) + def to_values(self): return self.values[:] + def to_i32_list(self): return [value.value for value in self.values] +runtime = types.ModuleType('generated._runtime') +runtime.__getattr__ = lambda name: None +def from_native(cls, obj, setter): + instance = object.__new__(cls) + getattr(instance, setter)(obj) + return instance +for name, value in dict( + TYPE_CHECKING=False, Callable=typing.Callable, DynWinRTType=Type, DynWinRTMethodSig=Signature, + DynWinRTValue=Value, DynWinRTArray=Array, WinGUID=types.SimpleNamespace(parse=lambda value: value), + _property=property, _weakref_ref=weakref.ref, UUID=uuid.UUID, + datetime=datetime.datetime, timedelta=datetime.timedelta, + _dynwinrt_projected_from_native=from_native, + _dynwinrt_track_projected=lambda value, *args: value, + _dynwinrt_cache_projected=lambda value: None, + _dynwinrt_symbol=lambda module, name: namespace[name], + _dynwinrt_array=lambda values, wrap, element_type, bytes_allowed: Array([wrap(value) for value in values]).to_value(), +).items(): setattr(runtime, name, value) +binding = types.ModuleType('dynwinrt') +for name, value in dict(DynWinRTInterfacePlan=Plan, DynWinRTImplementationMethod=Method, + DynWinRTImplementation=Implementation, DynWinRTImplementationDescriptor=Descriptor).items(): setattr(binding, name, value) +package = types.ModuleType('generated'); package.__path__ = [] +sys.modules.update({'generated': package, 'generated._runtime': runtime, 'dynwinrt': binding}) +namespace = {'__name__': 'generated.contract', '__package__': 'generated'} +exec(compile(source, 'contract.py', 'exec'), namespace) +Contract = namespace['IContract'] +class Handlers: + def __init__(self): self.title = 'start'; self.seen = None + def get_title(self): return self.title + def set_title(self, value): self.title = value + def transform(self, values, buffer_capacity): + self.seen = (values, buffer_capacity) + return {'label': 'ok', 'buffer': [values[0]+1] * buffer_capacity, 'result': True} + def use_callback(self, callback): + if callback is None: return 'null' + assert isinstance(callback._obj, Value) + return callback(7) + def get_object(self): return Value.null_value() + def echo_optional(self, value): return value + def use_contract(self, value): return value is not None and value.title == 'public view' + def use_fill_callback(self, callback): + if callback is None: return False + result = callback(3) + assert result == {'buffer': [7, 7, 7], 'result': 3} + return True + def round_trip_hresult(self, value): return value + def round_trip_hresults(self, values): return values +def raises(fragment, call): + try: call() + except (TypeError, ValueError) as error: assert fragment in str(error), str(error) + else: raise AssertionError('expected rejection: '+fragment) +raises('missing synchronous handler', lambda: Contract.implement(object())) +class AsyncHandlers(Handlers): + async def get_title(self): return 'bad' +raises('async handlers', lambda: Contract.implement(AsyncHandlers())) +class WrongSignature(Handlers): + def get_title(self, unexpected): return unexpected +raises('handler signature', lambda: Contract.implement(WrongSignature())) +class PropertyHandlers(Handlers): + @property + def get_title(self): raise AssertionError('must not evaluate property') +raises('accessors', lambda: Contract.implement(PropertyHandlers())) +assert Implementation.published == 0 +invoke_delegate = Value.invoke_delegate +del Value.invoke_delegate +raises('requires WinRT delegate invocation', lambda: Contract.implement(Handlers())) +Value.invoke_delegate = invoke_delegate +handlers = Handlers(); descriptor = Contract.implementation(handlers) +assert descriptor.dispatch(6, [])[0].value == 'start' +descriptor.dispatch(7, [Value.from_hstring('changed')]); assert handlers.title == 'changed' +values = Array([Value.from_i32(4), Value.from_i32(5)]).to_value() +outputs = descriptor.dispatch(8, [values, Value.from_u32(3)]) +assert handlers.seen == ([4, 5], 3) +assert [value.kind for value in outputs] == ['from_hstring', 'array', 'from_bool'] +assert [value.value for value in outputs[1].as_array().to_values()] == [5, 5, 5] +assert descriptor.dispatch(9, [Value('object', {})])[0].value == 'delegate:7' +assert descriptor.dispatch(9, [Value('object', None)])[0].value == 'null' +assert descriptor.dispatch(10, [])[0].is_null() +assert descriptor.dispatch(11, [Value.box_reference(Value.from_i32(8), None)])[0].value.boxed.value == 8 +assert descriptor.dispatch(11, [Value.null_value()])[0].is_null() +assert descriptor.dispatch(13, [Value('object', {})])[0].value is True +semantic_hresult = descriptor.dispatch(14, [Value.from_hresult(-2147467259)])[0] +assert semantic_hresult.kind == 'hresult' and semantic_hresult.value == -2147467259 +hresult_array = descriptor.dispatch(15, [Array([Value.from_hresult(-2147467259), Value.from_hresult(0)]).to_value()])[0] +assert [(value.kind, value.value) for value in hresult_array.as_array().to_values()] == [('hresult', -2147467259), ('hresult', 0)] +class InvalidHresults(Handlers): + def round_trip_hresults(self, values): return [2147483648] +raises('invalid implementation result', lambda: Contract.implementation(InvalidHresults()).dispatch(15, [hresult_array])) +raises('unknown implementation vtable slot', lambda: descriptor.dispatch(3, [])) +raises('argument count', lambda: descriptor.dispatch(8, [])) +async def coroutine(): return 'bad' +class CoroutineResult(Handlers): + def get_title(self): return coroutine() +raises('synchronously', lambda: Contract.implementation(CoroutineResult()).dispatch(6, [])) +class ShortBuffer(Handlers): + def transform(self, values, capacity): return {'label':'bad','buffer':[],'result':True} +raises('match capacity', lambda: Contract.implementation(ShortBuffer()).dispatch(8,[values,Value.from_u32(3)])) +class LargeInteger(Handlers): + def transform(self, values, capacity): return {'label':'bad','buffer':[2147483648],'result':True} +raises('invalid implementation result', lambda: Contract.implementation(LargeInteger()).dispatch(8,[values,Value.from_u32(1)])) +owner = Contract.implement(handlers) +assert owner.callback(0,6,[])[0].value == 'changed' +raises('unknown implementation interface index', lambda: owner.callback(-1,6,[])) +view = Contract.from_implementation(owner) +assert isinstance(view, Contract) +assert owner.last_value.releases == 1 +assert owner.references == 2 +assert view.title == 'changed' +view.title = 'public view' +assert view.use_contract(view) +assert view.round_trip_hresult(-2147467259) == -2147467259 +assert view.round_trip_hresults([-2147467259, 0]) == [-2147467259, 0] +release_projected(view) +assert owner.references == 1 +assert owner.callback(0,6,[])[0].value == 'public view' +owner.fail_query_interface = True +raises('QueryInterface failure', lambda: Contract.from_implementation(owner)) +assert owner.last_value.releases == 1 +assert owner.references == 1 +owner.fail_query_interface = False +class FailingView(Contract): + def _set_native(self, value, *, cache=True): + raise TypeError('projection failure') +raises('projection failure', lambda: FailingView.from_implementation(owner)) +assert owner.last_value.releases == 1 +assert owner.references == 1 +recovered = Contract.from_implementation(owner) +assert recovered.title == 'public view' +independent = Contract.from_implementation(owner) +assert independent is not recovered +assert owner.references == 3 +release_projected(independent) +assert recovered.title == 'public view' +release_projected(recovered) +assert owner.references == 1 +raises('requires a DynWinRTImplementation controller', lambda: Contract.from_implementation(object())) +print('Python projection assertions passed') +"#; + let output = run( + "python", + &["-c", test], + &serde_json::to_string(&py).unwrap(), + ); + assert!(output.contains("assertions passed")); +} + +#[test] +fn implementation_helper_types_are_separate_from_javascript_runtime_exports() { + let iface = fixture(); + let projected = project::project_interface( + &Default::default(), + &iface, + &HashSet::new(), + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + assert!( + projected + .public_type_exports() + .contains("IContractHandlers") + ); + assert!(!projected.public_exports().contains("IContractHandlers")); + let index = javascript::generator::generate_index(&[], &[iface], &[]); + assert!(index.contains("export type { IContractHandlers, IContractImplementationDelegate0, IContractImplementationDelegate1 }")); + assert!( + !javascript::generator::esm_index_to_cjs_lazy(&index).contains("exports.IContractHandlers") + ); + let [_, _, _, stub] = generated(&fixture()); + assert!(stub.contains("class _IContractImplementationFactory(ABCMeta):")); + assert!(stub.contains("metaclass=_IContractImplementationFactory")); + let interface_body = stub.split("class IContract(").nth(1).unwrap(); + assert!( + !interface_body.contains("def implementation(") + && !interface_body.contains("def implement(") + ); + assert!(!interface_body.contains("def from_implementation(")); +} + +#[test] +fn implementation_cli_emits_background_instance_public_views() { + if !Path::new(WINDOWS_WINMD).is_file() { + eprintln!("Skipping: Windows.winmd is unavailable"); + return; + } + let scratch = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("target") + .join(format!("cli-public-views-{}", std::process::id())); + let mut artifacts = Vec::new(); + for language in ["js", "py"] { + let output = scratch.join(language); + let generated = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args([ + "generate", + "--class-name", + "Windows.ApplicationModel.Background.IBackgroundTaskInstance", + "--lang", + language, + "--winmd", + WINDOWS_WINMD, + "--output", + ]) + .arg(&output) + .output() + .expect("run the built CLI executable"); + assert!( + generated.status.success(), + "{}", + String::from_utf8_lossy(&generated.stderr) + ); + let base = if language == "js" { + output + .join("windows") + .join("application-model") + .join("background") + } else { + output + }; + let stem = if language == "js" { + "IBackgroundTaskInstance" + } else { + "windows__application_model__background__i_background_task_instance" + }; + let declarations = if language == "js" { "d.ts" } else { "pyi" }; + artifacts.push(( + std::fs::read_to_string(base.join(format!("{stem}.{language}"))).unwrap(), + std::fs::read_to_string(base.join(format!("{stem}.{declarations}"))).unwrap(), + )); + } + std::fs::remove_dir_all(&scratch).unwrap(); + assert!(artifacts[0].0.contains("static fromImplementation(owner)")); + assert!( + artifacts[0] + .0 + .contains("} finally {\n value.release();") + ); + assert!(artifacts[0].1.contains("private constructor();")); + assert!(artifacts[0].1.contains( + "static fromImplementation(owner: DynWinRtImplementation): IBackgroundTaskInstance;" + )); + assert!( + artifacts[1] + .0 + .contains("def from_implementation(cls, owner: DynWinRTImplementation)") + ); + assert!( + artifacts[1] + .0 + .contains("finally:\n value.release()") + ); + assert!(artifacts[1].1.contains( + "def from_implementation(cls, owner: DynWinRTImplementation) -> IBackgroundTaskInstance: ..." + )); +} + +#[test] +fn implementation_public_python_views_type_check_without_internal_constructors() { + if !Path::new(WINDOWS_WINMD).is_file() { + eprintln!("Skipping: Windows.winmd is unavailable"); + return; + } + let available = Command::new("python") + .args(["-m", "mypy", "--version"]) + .output(); + if !available.is_ok_and(|output| output.status.success()) { + assert!( + std::env::var("DYNWINRT_REQUIRE_MYPY").as_deref() != Ok("1"), + "DYNWINRT_REQUIRE_MYPY=1 but the existing mypy runner is unavailable" + ); + eprintln!("Skipping: mypy is unavailable"); + return; + } + let tool_root = Path::new(env!("CARGO_MANIFEST_DIR")); + let scratch = tool_root + .join("target") + .join(format!("public-views-{}", std::process::id())); + std::fs::create_dir_all(&scratch).unwrap(); + let package = scratch.join("views"); + let generated = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args([ + "generate", + "--class-name", + "Windows.ApplicationModel.Background.IBackgroundTask,Windows.ApplicationModel.Background.IBackgroundTaskInstance,Windows.Foundation.IStringable,Windows.Foundation.IClosable", + "--lang", + "py", + "--winmd", + WINDOWS_WINMD, + "--output", + ]) + .arg(&package) + .output() + .expect("run the existing generator"); + assert!( + generated.status.success(), + "{}", + String::from_utf8_lossy(&generated.stderr) + ); + let foundation = package.join("windows").join("foundation"); + let delegate_facade = std::fs::read_dir(&foundation) + .unwrap() + .map(|entry| entry.unwrap().path()) + .find(|path| { + path.extension().is_some_and(|extension| extension == "pyi") + && path + .file_name() + .unwrap() + .to_string_lossy() + .starts_with("typed_event_handler_background_task_registration_group") + }) + .expect("transitive BackgroundTaskRegistrationGroup delegate facade"); + let public_name = delegate_facade + .file_stem() + .unwrap() + .to_string_lossy() + .to_string(); + let relative = delegate_facade + .strip_prefix(&package) + .unwrap() + .with_extension(""); + assert!( + relative.to_string_lossy().len() <= 120, + "public namespace path exceeded the flat-module budget: {}", + relative.display() + ); + let facade = std::fs::read_to_string(&delegate_facade).unwrap(); + let implementation = facade + .lines() + .find_map(|line| { + line.strip_prefix("from ...") + .and_then(|line| line.split_once(" import ")) + .map(|(module, _)| module) + }) + .expect("facade import of its canonical implementation"); + assert_eq!( + implementation.strip_prefix("windows__foundation__"), + Some(public_name.as_str()) + ); + assert!(package.join(format!("{implementation}.pyi")).is_file()); + assert!( + std::fs::read_to_string(foundation.join("__init__.pyi")) + .unwrap() + .contains(&format!("from .{public_name} import ")) + ); + let consumer = scratch.join("consumer.py"); + std::fs::write( + &consumer, + r#" +from views import IStringable, IClosable, IBackgroundTask, IBackgroundTaskInstance +from dynwinrt import release_projected + +class Strings: + def to_string(self) -> str: + return "public view" + +class Closing: + def close(self) -> None: + pass + +def consume_stringable(value: IStringable) -> str: + return value.to_string() + +class Task: + def run(self, instance: IBackgroundTaskInstance | None) -> None: + if instance is not None: + instance.progress = 24 + +def consume_task(value: IBackgroundTask, instance: IBackgroundTaskInstance) -> None: + value.run(instance) + +owner = IStringable.implement(Strings(), IClosable.implementation(Closing())) +view: IStringable = IStringable.from_implementation(owner) +text: str = consume_stringable(view) +release_projected(view) +owner.dispose() +task_owner = IBackgroundTask.implement(Task()) +task_view: IBackgroundTask = IBackgroundTask.from_implementation(task_owner) +release_projected(task_view) +task_owner.dispose() +"#, + ) + .unwrap(); + let binding_stubs = tool_root + .join("..") + .join("..") + .join("bindings") + .join("py") + .canonicalize() + .unwrap(); + let result = Command::new("python") + .args([ + "-m", + "mypy", + "--strict", + "--follow-imports=silent", + "--no-incremental", + "--cache-dir", + ]) + .arg("mypy-cache") + .arg("consumer.py") + .current_dir(&scratch) + .env("PYTHONUTF8", "1") + .env( + "MYPYPATH", + std::env::join_paths([binding_stubs, std::path::PathBuf::from(".")]).unwrap(), + ) + .output() + .expect("run the existing mypy checker"); + std::fs::remove_dir_all(&scratch).unwrap(); + assert!( + result.status.success(), + "{}\n{}", + String::from_utf8_lossy(&result.stdout), + String::from_utf8_lossy(&result.stderr) + ); +} From 738f5891c7e6d1a0c515f7c3fbace1869f474b1b Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 9 Sep 2026 11:53:30 +0800 Subject: [PATCH 2/8] fix: account for implementation coverage across source families Preserve ongoing coverage reporting work before merging current main. Include generated implementation sources, normalize Python subprocess paths, and retain per-family reports without changing coverage gates. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- eng/coverage/coverage.ps1 | 170 +++++++++-------- eng/coverage/coverage.threshold.tests.ps1 | 104 ++++++++++ eng/coverage/python-coveragerc | 12 +- eng/coverage/python_coverage.py | 155 +++++++++++++++ eng/coverage/test_python_coverage.py | 219 ++++++++++++++++++++++ 5 files changed, 578 insertions(+), 82 deletions(-) create mode 100644 eng/coverage/python_coverage.py create mode 100644 eng/coverage/test_python_coverage.py diff --git a/eng/coverage/coverage.ps1 b/eng/coverage/coverage.ps1 index e196176a..5c279323 100644 --- a/eng/coverage/coverage.ps1 +++ b/eng/coverage/coverage.ps1 @@ -35,9 +35,13 @@ $output = if ([IO.Path]::IsPathRooted($OutputDirectory)) { } $rustReport = Join-Path $output "rust" $pythonReport = Join-Path $output "python" +$pythonRuntimeReport = Join-Path $pythonReport "runtime" +$pythonWinrtReport = Join-Path $pythonReport "generated-winrt" +$pythonImplementationReport = Join-Path $pythonReport "generated-implementations" $jsReport = Join-Path $output "javascript" $jsRuntimeReport = Join-Path $jsReport "runtime" $jsWinrtReport = Join-Path $jsReport "generated-winrt" +$jsImplementationReport = Join-Path $jsReport "generated-implementations" $jsComReport = Join-Path $jsReport "generated-classic-com" $jsTemp = Join-Path $output "raw\javascript" $rustRaw = Join-Path $output "raw\rust" @@ -48,7 +52,7 @@ $outputMarkerText = "Managed by eng/coverage/coverage.ps1" $pipelineError = $null $pythonStartup = $null $originalLocation = (Get-Location).Path -$scratchRoot = Join-Path ([IO.Path]::GetTempPath()) "dynwinrt-coverage-$PID-$([guid]::NewGuid().ToString('N'))" +$scratchRoot = Join-Path $output ".scratch-$PID-$([guid]::NewGuid().ToString('N'))" $pythonEnvironment = Join-Path $scratchRoot "python" $jsDist = Join-Path $root "bindings\js\dist" $jsDistBackup = Join-Path $scratchRoot "js-dist" @@ -236,7 +240,7 @@ function Test-LcovSourceCovered { foreach ($record in ($Lcov -split "(?m)^end_of_record\r?\n?")) { if ( $record -match "(?m)^SF:.*$SourcePattern.*$" -and - $record -match "(?m)^LH:(\d+)$" -and + $record -match "(?m)^LH:(\d+)\r?$" -and [int]$matches[1] -gt 0 ) { return $true @@ -283,6 +287,38 @@ function Write-JavaScriptCoverageReport { } } +function Get-JavaScriptCoverageLayers { + param([switch]$All) + [pscustomobject]@{ + Name = "JavaScript runtime" + Path = $jsRuntimeReport + Includes = @("bindings/js/dist/**/*.js") + RequiredSourcePattern = "bindings[\\/]js[\\/]dist[\\/]index\.js" + } + if ($All -or $winrtCoverageExpected) { + [pscustomobject]@{ + Name = "Generated WinRT projections" + Path = $jsWinrtReport + Includes = @("tests/e2e/e2e_generated/ts/**/*.js") + RequiredSourcePattern = "tests[\\/]e2e[\\/]e2e_generated[\\/]ts[\\/]" + } + [pscustomobject]@{ + Name = "Generated WinRT implementations" + Path = $jsImplementationReport + Includes = @("tests/e2e/e2e_generated/implementations/js/**/*.js") + RequiredSourcePattern = "tests[\\/]e2e[\\/]e2e_generated[\\/]implementations[\\/]js[\\/]" + } + } + if ($All -or $comCoverageExpected) { + [pscustomobject]@{ + Name = "Generated Classic COM projections" + Path = $jsComReport + Includes = @("tests/e2e/e2e_generated/com/**/*.js") + RequiredSourcePattern = "tests[\\/]e2e[\\/]e2e_generated[\\/]com[\\/]" + } + } +} + function Write-Reports { Stop-PythonCoverage Remove-Item Env:NODE_V8_COVERAGE -ErrorAction SilentlyContinue @@ -313,13 +349,21 @@ function Write-Reports { } $lcov = Get-Content -LiteralPath (Join-Path $rustReport "lcov.info") -Raw - foreach ($requiredSource in @( + $requiredNativeSources = @( "bindings/js/src/lib.rs", "bindings/py/src/runtime.rs" - )) { + ) + if ($winrtCoverageExpected) { + $requiredNativeSources += @( + "bindings/js/src/winrt_implementation.rs", + "bindings/py/src/implementation.rs", + "crates/dynwinrt/src/winrt_implementation/" + ) + } + foreach ($requiredSource in $requiredNativeSources) { $pattern = [regex]::Escape($requiredSource).Replace("/", "[\\/]") - if ($lcov -notmatch $pattern) { - throw "Rust coverage did not include native binding source: $requiredSource" + if (-not (Test-LcovSourceCovered $lcov $pattern)) { + throw "Rust coverage did not execute native binding source: $requiredSource" } } } else { @@ -328,44 +372,16 @@ function Write-Reports { $pythonData = @(Get-ChildItem -LiteralPath $pythonReport -Filter ".coverage.*" -File -ErrorAction SilentlyContinue) if ($pythonData.Count -gt 0) { - Invoke-Step "Combine Python coverage" { - & $script:pythonExe -m coverage combine --keep $pythonReport + $pythonReportArgs = @( + "--root", $root, + "--output", $pythonReport, + "--config", $pythonConfig + ) + if ($winrtCoverageExpected) { + $pythonReportArgs += "--require-generated" } - $allPythonData = Join-Path $pythonReport "all-data.json" - & $script:pythonExe -m coverage json --ignore-errors -o $allPythonData - if ($LASTEXITCODE -ne 0) { - throw "Inspecting Python coverage data failed" - } - $coverageJson = Get-Content -LiteralPath $allPythonData -Raw | ConvertFrom-Json -AsHashtable - $measuredFiles = @($coverageJson["files"].Keys) - $productFiles = @($measuredFiles | Where-Object { - $_ -match "tests[\\/]e2e[\\/]e2e_generated[\\/]python_bindings" -or - ($_ -match "dynwinrt" -and $_ -notmatch "bindings[\\/]py[\\/]tests") - }) - if ($productFiles.Count -gt 0) { - Invoke-Step "Python HTML coverage report" { - & $script:pythonExe -m coverage html --rcfile $pythonConfig ` - -d (Join-Path $pythonReport "html") - } - Invoke-Step "Python XML coverage report" { - & $script:pythonExe -m coverage xml --rcfile $pythonConfig ` - -o (Join-Path $pythonReport "coverage.xml") - } - Invoke-Step "Python LCOV coverage report" { - & $script:pythonExe -m coverage lcov --rcfile $pythonConfig ` - -o (Join-Path $pythonReport "lcov.info") - } - Invoke-Step "Python JSON coverage summary" { - & $script:pythonExe -m coverage json --rcfile $pythonConfig ` - -o (Join-Path $pythonReport "coverage.json") - } - & $script:pythonExe -m coverage report --rcfile $pythonConfig - } else { - if ($SkipE2E) { - Write-Warning "No generated Python projection files were measured; skipping Python reports" - } else { - throw "No generated Python projection files were measured" - } + Invoke-Step "Python aggregate and per-family coverage reports" { + & $script:pythonExe (Join-Path $PSScriptRoot "python_coverage.py") @pythonReportArgs } } else { throw "No Python coverage data was produced" @@ -373,37 +389,20 @@ function Write-Reports { $jsData = @(Get-ChildItem -LiteralPath $jsTemp -Filter "*.json" -File -ErrorAction SilentlyContinue) if ($jsData.Count -gt 0) { - $aggregateIncludes = @("bindings/js/dist/**/*.js") - if ($winrtCoverageExpected) { - $aggregateIncludes += "tests/e2e/e2e_generated/ts/**/*.js" - } - if ($comCoverageExpected) { - $aggregateIncludes += "tests/e2e/e2e_generated/com/**/*.js" - } + $layers = @(Get-JavaScriptCoverageLayers) + $aggregateIncludes = @($layers | ForEach-Object { $_.Includes }) Write-JavaScriptCoverageReport ` -Name "JavaScript aggregate" ` -ReportDirectory $jsReport ` -Includes $aggregateIncludes ` -RequiredSourcePattern "bindings[\\/]js[\\/]dist[\\/]index\.js" - Write-JavaScriptCoverageReport ` - -Name "JavaScript runtime" ` - -ReportDirectory $jsRuntimeReport ` - -Includes @("bindings/js/dist/**/*.js") ` - -RequiredSourcePattern "bindings[\\/]js[\\/]dist[\\/]index\.js" - if ($winrtCoverageExpected) { + foreach ($layer in $layers) { Write-JavaScriptCoverageReport ` - -Name "Generated WinRT" ` - -ReportDirectory $jsWinrtReport ` - -Includes @("tests/e2e/e2e_generated/ts/**/*.js") ` - -RequiredSourcePattern "tests[\\/]e2e[\\/]e2e_generated[\\/]ts[\\/]" - } - if ($comCoverageExpected) { - Write-JavaScriptCoverageReport ` - -Name "Generated Classic COM" ` - -ReportDirectory $jsComReport ` - -Includes @("tests/e2e/e2e_generated/com/**/*.js") ` - -RequiredSourcePattern "tests[\\/]e2e[\\/]e2e_generated[\\/]com[\\/]" + -Name $layer.Name ` + -ReportDirectory $layer.Path ` + -Includes $layer.Includes ` + -RequiredSourcePattern $layer.RequiredSourcePattern } } else { throw "No V8 coverage data was produced" @@ -411,17 +410,28 @@ function Write-Reports { } function Get-CoverageSummaryMarkdown { + param([switch]$CheckThresholds) $rows = @() $rustSummary = Join-Path $rustReport "summary.json" if (Test-Path -LiteralPath $rustSummary) { $totals = (Get-Content -LiteralPath $rustSummary -Raw | ConvertFrom-Json).data[0].totals - Assert-MinimumCoverage "Rust" $totals.lines.percent $MinRustLineCoverage + if ($CheckThresholds) { + Assert-MinimumCoverage "Rust" $totals.lines.percent $MinRustLineCoverage + } $rows += "| Rust, including native .pyd/.node | $([math]::Round($totals.lines.percent, 2))% | $([math]::Round($totals.functions.percent, 2))% | $([math]::Round($totals.regions.percent, 2))% regions |" } - $pythonSummary = Join-Path $pythonReport "coverage.json" - if (Test-Path -LiteralPath $pythonSummary) { + foreach ($pythonLayer in @( + [pscustomobject]@{ Name = "Python aggregate"; Path = $pythonReport } + [pscustomobject]@{ Name = "Python runtime"; Path = $pythonRuntimeReport } + [pscustomobject]@{ Name = "Generated Python WinRT projections"; Path = $pythonWinrtReport } + [pscustomobject]@{ Name = "Generated Python WinRT implementations"; Path = $pythonImplementationReport } + )) { + $pythonSummary = Join-Path $pythonLayer.Path "coverage.json" + if (-not (Test-Path -LiteralPath $pythonSummary)) { + continue + } $totals = (Get-Content -LiteralPath $pythonSummary -Raw | ConvertFrom-Json -AsHashtable)["totals"] $linePercent = if ($totals["num_statements"]) { [math]::Round(100 * $totals["covered_lines"] / $totals["num_statements"], 2) @@ -433,20 +443,20 @@ function Get-CoverageSummaryMarkdown { } else { 100 } - Assert-MinimumCoverage "Generated Python" $linePercent $MinPythonLineCoverage - $rows += "| Generated Python projections | $linePercent% | n/a | $branchPercent% branches |" + if ($CheckThresholds -and $pythonLayer.Name -eq "Python aggregate") { + Assert-MinimumCoverage "Generated Python" $linePercent $MinPythonLineCoverage + } + $rows += "| $($pythonLayer.Name) | $linePercent% | n/a | $branchPercent% branches |" } foreach ($javascriptLayer in @( [pscustomobject]@{ Name = "JavaScript aggregate"; Path = $jsReport } - [pscustomobject]@{ Name = "JavaScript runtime"; Path = $jsRuntimeReport } - [pscustomobject]@{ Name = "Generated WinRT projections"; Path = $jsWinrtReport } - [pscustomobject]@{ Name = "Generated Classic COM projections"; Path = $jsComReport } + Get-JavaScriptCoverageLayers -All )) { $jsSummary = Join-Path $javascriptLayer.Path "coverage-summary.json" if (Test-Path -LiteralPath $jsSummary) { $totals = (Get-Content -LiteralPath $jsSummary -Raw | ConvertFrom-Json).total - if ($javascriptLayer.Name -eq "JavaScript aggregate") { + if ($CheckThresholds -and $javascriptLayer.Name -eq "JavaScript aggregate") { Assert-MinimumCoverage ` $javascriptLayer.Name ` $totals.lines.pct ` @@ -473,11 +483,12 @@ function Write-CoverageSummary { if ($summary.Count -gt 0) { Set-Content -LiteralPath (Join-Path $output "summary.md") -Value $summary -Encoding utf8 } + Get-CoverageSummaryMarkdown -CheckThresholds | Out-Null } if ($ValidateOnly) { Set-Location $root - $summary = @(Get-CoverageSummaryMarkdown) + $summary = @(Get-CoverageSummaryMarkdown -CheckThresholds) if ($summary.Count -eq 0) { throw "No coverage summaries were found under $output" } @@ -574,6 +585,9 @@ try { "pytest>=8.3.5" ` --quiet } + Invoke-Step "Python coverage report regression tests" { + & $script:pythonExe -m unittest discover -s eng\coverage -p test_python_coverage.py + } Invoke-Step "Install JavaScript dependencies" { Push-Location (Join-Path $root "bindings\js") try { @@ -682,6 +696,7 @@ try { -CargoProfile coverage ` -CargoTarget $script:cargoTarget ` -Python $script:pythonExe ` + -Suite all ` -Lang $languages } } @@ -731,6 +746,7 @@ try { Write-Host " Runtime: $(Join-Path $jsRuntimeReport 'index.html')" if ($winrtCoverageExpected) { Write-Host " WinRT: $(Join-Path $jsWinrtReport 'index.html')" + Write-Host " Impl: $(Join-Path $jsImplementationReport 'index.html')" } if ($comCoverageExpected) { Write-Host " COM: $(Join-Path $jsComReport 'index.html')" diff --git a/eng/coverage/coverage.threshold.tests.ps1 b/eng/coverage/coverage.threshold.tests.ps1 index b66c8ef5..c1a5c654 100644 --- a/eng/coverage/coverage.threshold.tests.ps1 +++ b/eng/coverage/coverage.threshold.tests.ps1 @@ -50,4 +50,108 @@ Assert-ExpectedFailure { -MinJavaScriptLineCoverage 19 } "JavaScript aggregate line coverage 18.77% is below the required 19%" +Write-Host "Validating Python threshold failures..." +Assert-ExpectedFailure { + & $coverageScript ` + -OutputDirectory $fixture ` + -ValidateOnly ` + -MinPythonLineCoverage 73 +} "Generated Python line coverage 72.27% is below the required 73%" + +# Load report helpers without running builds or touching native binding outputs. +$ast = [Management.Automation.Language.Parser]::ParseFile($coverageScript, [ref]$null, [ref]$null) +foreach ($name in @( + "Get-JavaScriptCoverageLayers", + "Test-LcovSourceCovered", + "Assert-MinimumCoverage", + "Get-CoverageSummaryMarkdown", + "Write-CoverageSummary" +)) { + $function = $ast.Find({ + param($node) + $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq $name + }, $false) + if (-not $function) { throw "Missing coverage report helper: $name" } + . ([scriptblock]::Create($function.Extent.Text)) +} + +Write-Host "Validating JavaScript source families..." +$jsReport = Join-Path $fixture "javascript" +$jsRuntimeReport = Join-Path $jsReport "runtime" +$jsWinrtReport = Join-Path $jsReport "generated-winrt" +$jsImplementationReport = Join-Path $jsReport "generated-implementations" +$jsComReport = Join-Path $jsReport "generated-classic-com" +$winrtCoverageExpected = $true +$comCoverageExpected = $true +$layers = @(Get-JavaScriptCoverageLayers) +$includes = @($layers | ForEach-Object { $_.Includes }) +foreach ($expected in @( + "bindings/js/dist/**/*.js", + "tests/e2e/e2e_generated/ts/**/*.js", + "tests/e2e/e2e_generated/implementations/js/**/*.js", + "tests/e2e/e2e_generated/com/**/*.js" +)) { + if ($includes -notcontains $expected) { throw "Missing JavaScript source family: $expected" } +} +if ($layers.Count -ne 4) { throw "Expected four distinct JavaScript source families" } +$comCoverageExpected = $false +if (@(Get-JavaScriptCoverageLayers).Count -ne 3) { throw "Skipping COM must preserve implementation coverage" } +$winrtCoverageExpected = $false +if (@(Get-JavaScriptCoverageLayers).Count -ne 1) { throw "Skipping E2E must preserve runtime coverage" } +if (@(Get-JavaScriptCoverageLayers -All).Count -ne 4) { throw "Summary must discover every generated family" } + +Write-Host "Validating native source execution checks..." +$pattern = "bindings[\\/]py[\\/]src[\\/]implementation\.rs" +foreach ($separator in @("/", "\")) { + $source = (@("bindings", "py", "src", "implementation.rs") -join $separator) + if (-not (Test-LcovSourceCovered "SF:$source`r`nLH:1`r`nend_of_record`r`n" $pattern)) { + throw "Covered native implementation source was not detected: $source" + } + if (Test-LcovSourceCovered "SF:$source`nLH:0`nend_of_record`n" $pattern) { + throw "An unexecuted native source must not satisfy coverage presence checks" + } +} + +Write-Host "Validating failed gates retain the complete summary..." +$output = Join-Path $PSScriptRoot "testdata\.summary-test-$([guid]::NewGuid().ToString('N'))" +$rustReport = Join-Path $fixture "rust" +$pythonReport = Join-Path $fixture "python" +$pythonRuntimeReport = Join-Path $pythonReport "runtime" +$pythonWinrtReport = Join-Path $pythonReport "generated-winrt" +$pythonImplementationReport = Join-Path $pythonReport "generated-implementations" +$MinRustLineCoverage = 45 +$MinPythonLineCoverage = 73 +$MinJavaScriptLineCoverage = 18 +New-Item -ItemType Directory -Path $output | Out-Null +try { + Assert-ExpectedFailure { Write-CoverageSummary } "Generated Python line coverage 72.27%" + $summary = Get-Content -LiteralPath (Join-Path $output "summary.md") -Raw + if ($summary -notmatch "Python aggregate.*72\.27%" -or $summary -notmatch "JavaScript aggregate.*18\.77%") { + throw "A failing Python gate hid coverage diagnostics for another layer" + } + + Write-Host "Validating the unchanged default Python 70% boundary..." + $boundaryDirectory = Join-Path $output "python" + New-Item -ItemType Directory -Path $boundaryDirectory | Out-Null + $boundary = @{ + totals = @{ + covered_lines = 70 + num_statements = 100 + covered_branches = 0 + num_branches = 0 + } + } + $boundary | ConvertTo-Json -Depth 3 | + Set-Content -LiteralPath (Join-Path $boundaryDirectory "coverage.json") + & $coverageScript -OutputDirectory $output -ValidateOnly + $boundary.totals.covered_lines = 69 + $boundary | ConvertTo-Json -Depth 3 | + Set-Content -LiteralPath (Join-Path $boundaryDirectory "coverage.json") + Assert-ExpectedFailure { + & $coverageScript -OutputDirectory $output -ValidateOnly + } "Generated Python line coverage 69% is below the required 70%" +} finally { + Remove-Item -LiteralPath $output -Recurse -Force +} + Write-Host "Coverage threshold validation passed." diff --git a/eng/coverage/python-coveragerc b/eng/coverage/python-coveragerc index 9a369589..7ef3a443 100644 --- a/eng/coverage/python-coveragerc +++ b/eng/coverage/python-coveragerc @@ -5,14 +5,16 @@ relative_files = True [report] include = - */dynwinrt/* - tests/e2e/e2e_generated/python_bindings/* + */site-packages/dynwinrt/* + */bindings/py/src/*.py + */tests/e2e/e2e_generated/python_bindings/* + */tests/e2e/e2e_generated/implementations/python_bindings/* omit = */__pycache__/* */site-packages/coverage/* - bindings/py/tests/* - tests/e2e/runners/* - tests/e2e/typecheck/* + */bindings/py/tests/* + */tests/e2e/runners/* + */tests/e2e/typecheck/* show_missing = True skip_empty = True diff --git a/eng/coverage/python_coverage.py b/eng/coverage/python_coverage.py new file mode 100644 index 00000000..6dc100ab --- /dev/null +++ b/eng/coverage/python_coverage.py @@ -0,0 +1,155 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Combine subprocess coverage and report every measured Python product family.""" + +import argparse +import json +import os +from pathlib import Path + +from coverage import Coverage, CoverageData +from coverage.exceptions import NoDataError + + +GENERATED_LAYERS = { + "generated-winrt": "tests/e2e/e2e_generated/python_bindings/*", + "generated-implementations": ( + "tests/e2e/e2e_generated/implementations/python_bindings/*" + ), +} +RUNTIME_INCLUDES = ["*/site-packages/dynwinrt/*", "*/bindings/py/src/*.py"] + + +def _without_device_prefix(path: str) -> str: + path = path.replace("\\", "/") + if path[:8].lower() == "//?/unc/": + return "//" + path[8:] + if path.startswith("//?/"): + return path[4:] + return path + + +def normalize_path(path: str, root: Path) -> str: + """Use one repo-relative identity for normal and extended Windows paths.""" + path = _without_device_prefix(path) + prefix = _without_device_prefix(str(root)).rstrip("/") + "/" + if path.lower().startswith(prefix.lower()): + path = path[len(prefix):] + return os.path.normpath(path) + + +def filesystem_path(path: Path) -> str: + absolute = os.path.abspath(path) + if os.name != "nt" or absolute.startswith("\\\\?\\"): + return absolute + if absolute.startswith("\\\\"): + return "\\\\?\\UNC\\" + absolute[2:] + return "\\\\?\\" + absolute + + +def normalize_data(data: CoverageData, root: Path) -> None: + def source_path(path: str) -> str: + path = normalize_path(path, root) + absolute = os.path.normpath(os.path.join(root, path)) + # Removing the extended prefix from a genuinely long source makes it + # unreadable on Windows hosts where normal paths still have MAX_PATH. + if os.name == "nt" and len(absolute) >= 260: + return filesystem_path(Path(absolute)) + return path + + normalized = CoverageData(no_disk=True) + try: + normalized.update(data, map_path=source_path) + serialized = normalized.dumps() + finally: + # update() can attach the original SQLite database to this connection. + # Release it before replacing the original data on Windows. + normalized.close(force=True) + data.erase() + data.loads(serialized) + + +def _write_layer(coverage: Coverage, directory: Path, includes: list[str]) -> dict: + directory = Path(filesystem_path(directory)) + directory.mkdir(parents=True, exist_ok=True) + coverage.json_report(outfile=str(directory / "coverage.json"), include=includes) + coverage.html_report(directory=str(directory / "html"), include=includes) + coverage.xml_report(outfile=str(directory / "coverage.xml"), include=includes) + coverage.lcov_report(outfile=str(directory / "lcov.info"), include=includes) + return json.loads((directory / "coverage.json").read_text(encoding="utf-8")) + + +def write_reports( + root: Path, + directory: Path, + config: Path, + *, + require_generated: bool = False, +) -> None: + root, directory, config = root.resolve(), directory.resolve(), config.resolve() + original_directory = Path.cwd() + try: + os.chdir(root) + coverage = Coverage(config_file=str(config), data_file=str(directory / ".coverage")) + coverage.combine(data_paths=[str(directory)], strict=True, keep=True) + normalize_data(coverage.get_data(), root) + coverage.save() + + # Keep relative_files enabled for diagnostics too. Without it the same + # recorded relative filenames can be reported as entirely unexecuted. + coverage.json_report( + outfile=str(directory / "all-data.json"), include=["*"], omit=[] + ) + includes = coverage.get_option("report:include") + try: + aggregate = _write_layer(coverage, directory, includes) + except NoDataError: + if require_generated: + raise + print("No Python product files were measured; skipping product reports.") + return + + files = { + normalize_path(path, root).replace("\\", "/"): entry + for path, entry in aggregate["files"].items() + } + missing_layers = [] + generated_files = set() + for name, pattern in GENERATED_LAYERS.items(): + prefix = pattern.removesuffix("*") + selected = {path: entry for path, entry in files.items() if path.startswith(prefix)} + generated_files.update(selected) + if selected: + _write_layer(coverage, directory / name, ["*/" + pattern]) + if require_generated and not any( + entry["summary"]["covered_lines"] for entry in selected.values() + ): + missing_layers.append(name) + + if files.keys() - generated_files: + _write_layer(coverage, directory / "runtime", RUNTIME_INCLUDES) + coverage.report(include=includes) + if missing_layers: + raise RuntimeError( + "Python coverage did not execute required source families: " + + ", ".join(missing_layers) + ) + finally: + os.chdir(original_directory) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--config", type=Path, required=True) + parser.add_argument("--require-generated", action="store_true") + args = parser.parse_args() + write_reports( + args.root, args.output, args.config, require_generated=args.require_generated + ) + + +if __name__ == "__main__": + main() diff --git a/eng/coverage/test_python_coverage.py b/eng/coverage/test_python_coverage.py new file mode 100644 index 00000000..8c3e5201 --- /dev/null +++ b/eng/coverage/test_python_coverage.py @@ -0,0 +1,219 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import contextlib +import io +import json +import os +from pathlib import Path +import shutil +import unittest +import uuid + +from coverage import CoverageData +from coverage.exceptions import NoSource + +from python_coverage import normalize_data, normalize_path, write_reports + + +HERE = Path(__file__).resolve().parent +STANDARD = Path("tests/e2e/e2e_generated/python_bindings") +IMPLEMENTATIONS = Path("tests/e2e/e2e_generated/implementations/python_bindings") + + +class PathNormalizationTests(unittest.TestCase): + def test_extended_drive_paths_become_repo_relative(self): + root = Path(r"D:\a\dynwinrt\dynwinrt") + relative = str(IMPLEMENTATIONS / "windows" / "i_closable.py") + for prefix in (r"D:\a\dynwinrt\dynwinrt", r"\\?\D:\a\dynwinrt\dynwinrt"): + with self.subTest(prefix=prefix): + self.assertEqual(normalize_path(prefix + "\\" + relative, root), relative) + + def test_extended_unc_paths_and_case_insensitive_root(self): + self.assertEqual( + normalize_path( + r"\\?\UNC\SERVER\Share\Repo\tests\example.py", + Path(r"\\server\share\repo"), + ), + os.path.normpath("tests/example.py"), + ) + + def test_relative_paths_and_other_checkouts_are_not_conflated(self): + root = Path(r"D:\a\dynwinrt\dynwinrt") + self.assertEqual(normalize_path("tests/example.py", root), os.path.normpath("tests/example.py")) + other = r"D:\a\dynwinrt\dynwinrt-other\tests\example.py" + self.assertEqual(normalize_path(other, root), os.path.normpath(other)) + + def test_alias_merging_preserves_arcs_and_contexts(self): + root = Path(r"D:\a\dynwinrt\dynwinrt") + data = CoverageData(no_disk=True) + self.addCleanup(data.close, force=True) + data.set_context("normal") + data.add_arcs({str(root / "example.py"): [(1, 2), (2, 4)]}) + data.set_context("extended") + data.add_arcs({r"\\?\D:\a\dynwinrt\dynwinrt\example.py": [(1, 3), (3, 4)]}) + normalize_data(data, root) + + self.assertEqual(data.measured_files(), {"example.py"}) + self.assertEqual(set(data.arcs("example.py")), {(1, 2), (2, 4), (1, 3), (3, 4)}) + self.assertEqual(data.measured_contexts(), {"normal", "extended"}) + data.set_query_contexts(["extended"]) + self.assertEqual(set(data.arcs("example.py")), {(1, 3), (3, 4)}) + + +class ReportTests(unittest.TestCase): + def setUp(self): + self.root = HERE / "testdata" / (".report-test-" + uuid.uuid4().hex) + self.output = self.root / "reports" + self.output.mkdir(parents=True) + + def tearDown(self): + shutil.rmtree("\\\\?\\" + str(self.root) if os.name == "nt" else self.root) + + def source(self, relative: Path, text: str = "def value():\n return 3\n\nvalue()\n") -> Path: + path = self.root / relative + io_path = Path("\\\\?\\" + str(path)) if os.name == "nt" else path + io_path.parent.mkdir(parents=True, exist_ok=True) + io_path.write_text(text, encoding="utf-8") + return path + + def record(self, name: str, lines: dict[str, list[int]]) -> None: + data = CoverageData(basename=str(self.output / (".coverage." + name))) + data.set_context(name) + data.add_lines(lines) + data.write() + + def report(self, **kwargs): + with contextlib.redirect_stdout(io.StringIO()): + write_reports(self.root, self.output, HERE / "python-coveragerc", **kwargs) + + def read_report(self, name: str = "coverage.json") -> dict: + return json.loads((self.output / name).read_text(encoding="utf-8")) + + def test_aggregate_keeps_both_generated_trees_runtime_and_transitive_interfaces(self): + standard = self.source(STANDARD / "windows__i_closable.py") + implementation = self.source(IMPLEMENTATIONS / "windows__i_closable.py") + transitive = self.source(STANDARD / "windows" / "transitive.py", "def unused():\n return 7\n") + runtime = self.source(Path("bindings/py/src/implementation.py")) + runner = self.source(Path("tests/e2e/runners/runner.py")) + self.record("standard", { + str(standard.relative_to(self.root)): [1, 2, 4], + str(transitive.relative_to(self.root)): [], + str(runner.relative_to(self.root)): [1, 2, 4], + str(runtime.relative_to(self.root)): [1, 2, 4], + }) + self.record("implementations", { + "\\\\?\\" + str(implementation): [1, 2, 4], + }) + + self.report(require_generated=True) + aggregate = self.read_report() + diagnostic = self.read_report("all-data.json") + self.assertEqual(aggregate["totals"]["covered_lines"], 9) + self.assertEqual(aggregate["totals"]["num_statements"], 11) + self.assertEqual(len(aggregate["files"]), 4) + self.assertEqual(len(diagnostic["files"]), 5) + for path, entry in aggregate["files"].items(): + self.assertFalse(Path(normalize_path(path, self.root)).is_absolute(), path) + self.assertEqual(entry["summary"], diagnostic["files"][path]["summary"]) + normalized_files = { + normalize_path(path, self.root): entry + for path, entry in aggregate["files"].items() + } + missing = normalized_files[str(transitive.relative_to(self.root))]["summary"] + self.assertEqual(missing["covered_lines"], 0) + self.assertEqual(missing["num_statements"], 2) + layers = [ + self.read_report(name + "/coverage.json") + for name in ("runtime", "generated-winrt", "generated-implementations") + ] + for key in ("covered_lines", "num_statements", "num_branches", "covered_branches"): + self.assertEqual( + aggregate["totals"].get(key, 0), + sum(layer["totals"].get(key, 0) for layer in layers), + ) + for name in ("runtime", "generated-winrt", "generated-implementations"): + for report in ("html/index.html", "coverage.xml", "lcov.info"): + self.assertTrue((self.output / name / report).is_file()) + self.assertEqual(len(list(self.output.glob(".coverage.*"))), 2) + + def test_missing_implementation_measurement_fails_with_reports_retained(self): + standard = self.source(STANDARD / "sample.py") + self.record("standard", {str(standard.relative_to(self.root)): [1, 2, 4]}) + with self.assertRaisesRegex(RuntimeError, "generated-implementations"): + self.report(require_generated=True) + self.assertEqual(self.read_report()["totals"]["covered_lines"], 3) + + def test_zero_hit_implementation_family_does_not_satisfy_presence_check(self): + standard = self.source(STANDARD / "sample.py") + implementation = self.source(IMPLEMENTATIONS / "sample.py") + self.record("measured", { + str(standard.relative_to(self.root)): [1, 2, 4], + str(implementation.relative_to(self.root)): [], + }) + with self.assertRaisesRegex(RuntimeError, "generated-implementations"): + self.report(require_generated=True) + self.assertEqual( + self.read_report("generated-implementations/coverage.json")["totals"]["covered_lines"], + 0, + ) + + def test_skip_e2e_can_report_runtime_without_generated_sources(self): + runtime = self.source(Path("bindings/py/src/implementation.py")) + self.record("runtime", {str(runtime.relative_to(self.root)): [1, 2, 4]}) + self.report() + self.assertEqual(self.read_report("runtime/coverage.json")["totals"]["covered_lines"], 3) + + def test_installed_runtime_package_is_included(self): + runtime = self.source(Path("environment/Lib/site-packages/dynwinrt/implementation.py")) + self.record("runtime", {str(runtime): [1, 2, 4]}) + self.report() + self.assertEqual(self.read_report("runtime/coverage.json")["totals"]["covered_lines"], 3) + + def test_combined_branch_reports_keep_alias_hits_and_contexts(self): + source = self.source( + IMPLEMENTATIONS / "conditional.py", + "flag = True\nif flag:\n value = 1\nelse:\n value = 2\n", + ) + for context, filename, target in ( + ("truthy", str(source.relative_to(self.root)), 3), + ("falsey", "\\\\?\\" + str(source), 5), + ): + data = CoverageData(basename=str(self.output / (".coverage." + context))) + data.set_context(context) + data.add_arcs({filename: [(-1, 1), (1, 2), (2, target), (target, -1)]}) + data.write() + self.report() + totals = self.read_report()["totals"] + self.assertEqual(totals["num_branches"], 2) + self.assertEqual(totals["covered_branches"], 2) + self.assertEqual(totals["covered_lines"], 4) + combined = CoverageData(basename=str(self.output / ".coverage")) + combined.read() + self.assertEqual(len(combined.measured_files()), 1) + filename = next(iter(combined.measured_files())) + self.assertEqual(set(combined.contexts_by_lineno(filename)[2]), {"truthy", "falsey"}) + + def test_no_product_measurements_still_produce_accurate_diagnostics(self): + runner = self.source(Path("tests/e2e/runners/runner.py")) + self.record("runner", {str(runner.relative_to(self.root)): [1, 2, 4]}) + self.report() + self.assertEqual(self.read_report("all-data.json")["totals"]["covered_lines"], 3) + self.assertFalse((self.output / "coverage.json").exists()) + + def test_missing_sources_are_not_ignored(self): + self.record("missing", {str(STANDARD / "missing.py"): [1]}) + original_directory = Path.cwd() + with self.assertRaises(NoSource): + self.report() + self.assertEqual(Path.cwd(), original_directory) + + def test_extended_long_source_paths_remain_reportable(self): + long_source = self.source(IMPLEMENTATIONS / ("generic_" + "type_" * 28 + ".py")) + self.record("long", {"\\\\?\\" + str(long_source): [1, 2, 4]}) + self.report() + self.assertEqual(self.read_report()["totals"]["covered_lines"], 3) + + +if __name__ == "__main__": + unittest.main() From ad42241c127a348f891a5a8a596d513bf76989b4 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 9 Sep 2026 12:42:53 +0800 Subject: [PATCH 3/8] feat: expose typed implementation handles and restore generated coverage Keep implement as the instance factory with a stable handle-managed value, support explicit interface/handler tuples, and retain advanced descriptors and independent views. Pin Python receivers across reentrant primary disposal, share measured reverse helpers, exercise both generated source trees and scalar/array contracts, and keep existing coverage gates unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- README.md | 4 +- bindings/js/README.md | 28 ++- bindings/js/__test__/index.spec.ts | 5 +- bindings/js/runtime/winrt-implementation.cjs | 105 +++++++++ bindings/js/scripts/generate-entrypoints.mjs | 22 ++ bindings/py/README.md | 25 +- bindings/py/dynwinrt.pyi | 22 +- bindings/py/src/implementation.py | 101 ++++++++ bindings/py/src/lib.rs | 1 + bindings/py/src/runtime.rs | 18 +- bindings/py/tests/test_typing_package.py | 3 + .../winrt-interface-implementations.md | 15 ++ .../winrt-interface-implementations.md | 106 +++++---- eng/coverage/coverage.ps1 | 2 +- samples/js/interface-implementation/README.md | 10 +- samples/js/interface-implementation/app.mjs | 44 ++-- .../python/interface-implementation/README.md | 9 +- .../python/interface-implementation/app.py | 80 +++---- tests/e2e/e2e_test.ps1 | 9 + tests/e2e/implementation_test.ps1 | 2 + tests/e2e/runners/implementation_js.mjs | 152 +++++++++++- tests/e2e/runners/implementation_js.test.mjs | 4 +- tests/e2e/runners/implementation_py.py | 220 ++++++++++++++++-- .../runners/test_implementation_runners.py | 4 +- .../typecheck/python_implementation_api.py | 12 +- tests/e2e/typecheck/ts_implementation_api.ts | 16 +- .../winrt/javascript/implementation.rs | 8 +- .../codegen/winrt/javascript/project/mod.rs | 7 +- .../src/codegen/winrt/python/generator/mod.rs | 5 +- .../codegen/winrt/python/implementation.rs | 19 +- .../src/codegen/winrt/python/signature.rs | 3 +- .../src/codegen/winrt/python/stubs.rs | 1 + .../uri/windows/foundation/IStringable.d.ts | 13 +- .../uri/windows/foundation/IStringable.js | 15 +- ...iRuntimeClassWithAbsoluteCanonicalUri.d.ts | 13 +- ...UriRuntimeClassWithAbsoluteCanonicalUri.js | 15 +- .../foundation/IWwwFormUrlDecoderEntry.d.ts | 13 +- .../foundation/IWwwFormUrlDecoderEntry.js | 15 +- .../tests/snapshots/uri_py/i_stringable.py | 91 +------- ...ntime_class_with_absolute_canonical_uri.py | 91 +------- .../uri_py/i_www_form_url_decoder_entry.py | 91 +------- .../tests/snapshots/uri_pyi/i_stringable.pyi | 8 +- ...time_class_with_absolute_canonical_uri.pyi | 8 +- .../uri_pyi/i_www_form_url_decoder_entry.pyi | 8 +- .../dynwinrt-codegen/tests/tsc_check_test.rs | 15 ++ .../tests/winrt_implementation_test.rs | 90 ++++--- 46 files changed, 1025 insertions(+), 523 deletions(-) create mode 100644 bindings/js/runtime/winrt-implementation.cjs diff --git a/README.md b/README.md index d63ae994..242d04e8 100644 --- a/README.md +++ b/README.md @@ -90,7 +90,9 @@ names, native Python values, asyncio-compatible awaitables, and type stubs. Node.js and Python can supply synchronous handlers for complete non-generic WinRT interfaces. Generated `.implementation(...)` descriptors compose multiple interfaces into a standalone IInspectable object, and `.implement(...)` creates -its owner. Public typed interface views can be passed to ordinary native +its management handle. `impl.value` is a stable typed primary interface, and +`impl.dispose()` manages cleanup (Python also supports `with ... as impl`). +Public typed interface views can be passed to ordinary native consumers without a WinUI composable base or OS registration. The first release is non-agile and owner-thread-only. Reference release and diff --git a/bindings/js/README.md b/bindings/js/README.md index c85fe057..0f92f2e7 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -72,10 +72,28 @@ name while the root barrel uses a namespace-qualified name, such as ### Standalone WinRT interface implementations Metadata-generated standalone WinRT interfaces expose `implementation(handlers)` -and `implement(handlers, ...additionalDescriptors)`. The latter returns a -`DynWinRtImplementation` owner; use the public -`GeneratedInterface.fromImplementation(owner)` factory to create an -independently owned typed view. Low-level users must select an interface with +and `implement(handlers, ...additionalDescriptors)`. The latter creates a native +instance and returns `DynWinRtImplementationHandle`: + +```js +const impl = IBackgroundTask.implement(taskHandlers, { + interfaces: [[IStringable, textHandlers]], +}) +try { + impl.value.run(instanceView) +} finally { + impl.dispose() +} +``` + +`.value` is a stable, lazily created typed primary view, managed by the handle. +`release()` releases its primary view and owner without disconnecting other +native references; `dispose()` additionally disconnects the object. Neither +allows `.value` to recreate a view afterward. The common pattern does not need +`releaseProjected(impl.value)`. +`GeneratedInterface.fromImplementation(impl)` remains the advanced, +independently owned view path; positional descriptors and raw native owners +remain supported. Low-level users must select an interface with `value.cast(iid)` before invoking that interface's method handles: `toValue()` returns the canonical `IInspectable`, not an arbitrary interface's vtable. These are local, synchronous, non-agile WinRT objects, not COM class @@ -101,7 +119,7 @@ must have exactly that length. Async functions, promises, and thenable results are unsupported. Dispatch errors fail the native call; `takeError()` returns and clears the latest diagnostic, or `null` when there is none. -`release()` and owner garbage collection drop only the owner's native reference. +Low-level owner `release()` and garbage collection drop only its native reference. Separately retained native values keep their callbacks alive. `disconnect()` closes every view while retaining the owner reference; `dispose()` disconnects and releases it, and both are idempotent. Disposing during a callback allows that diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index ac820f87..718f1f17 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -148,7 +148,10 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => { test('package facades exactly partition native exports', (t) => { const nativeKeys = moduleKeys(nativeRuntime) - const expectedWinrt = nativeKeys.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom') + const expectedWinrt = [ + ...nativeKeys.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom'), + 'DynWinRtImplementationHandle', + ].sort() const safeComNames = new Set([ 'DynComDispatchParams', 'DynComAllocation', diff --git a/bindings/js/runtime/winrt-implementation.cjs b/bindings/js/runtime/winrt-implementation.cjs new file mode 100644 index 00000000..fe1e3027 --- /dev/null +++ b/bindings/js/runtime/winrt-implementation.cjs @@ -0,0 +1,105 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +'use strict' + +const { DynWinRtImplementation, DynWinRtInterfacePlan } = require('./index.js') + +class DynWinRtImplementationHandle { + #owner + #project + #releaseView + #value + #released = false + #projecting = false + + constructor(owner, project, releaseView) { + if (!(owner instanceof DynWinRtImplementation) || typeof project !== 'function' || typeof releaseView !== 'function') { + throw new TypeError('A WinRT implementation handle requires an owner and typed view projection') + } + this.#owner = owner + this.#project = project + this.#releaseView = releaseView + } + + static create(type, handlers, additional, releaseView) { + let descriptors + if (additional.length === 1 && additional[0] && Object.hasOwn(additional[0], 'interfaces')) { + const options = additional[0] + if (Object.keys(options).some(key => key !== 'interfaces') || !Array.isArray(options.interfaces)) { + throw new TypeError('WinRT implementation options require an interfaces array') + } + descriptors = options.interfaces.map(entry => { + if (!Array.isArray(entry) || entry.length !== 2 || + typeof entry[0]?.implementation !== 'function' || typeof entry[0]?.fromImplementation !== 'function') { + throw new TypeError('Each interface entry must be [generatedInterface, handlers]') + } + return entry[0].implementation(entry[1]) + }) + } else { + descriptors = additional + } + descriptors = [type.implementation(handlers), ...descriptors] + for (const descriptor of descriptors) { + if (!(descriptor?.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') { + throw new TypeError('Invalid WinRT implementation descriptor') + } + } + const dispatchers = descriptors.map(descriptor => descriptor.dispatch) + const owner = DynWinRtImplementation.create(descriptors.map(descriptor => descriptor.plan), (index, slot, args) => { + if (!Number.isInteger(index) || index < 0 || index >= dispatchers.length) { + throw new RangeError('Unknown implementation interface index') + } + return dispatchers[index](slot, args) + }) + return new DynWinRtImplementationHandle(owner, value => type.fromImplementation(value), releaseView) + } + + get value() { + if (this.#released || this.#owner.isClosed) throw new Error('WinRT implementation handle is closed or released') + if (this.#value === undefined) { + if (this.#projecting) throw new Error('WinRT implementation primary view creation is reentrant') + this.#projecting = true + try { + const value = this.#project(this.#owner) + if (this.#released || this.#owner.isClosed) { + this.#releaseView(value) + throw new Error('WinRT implementation was released during primary view creation') + } + this.#value = value + } catch (error) { + this.dispose() + throw error + } finally { + this.#projecting = false + } + } + return this.#value + } + + toValue() { + if (this.#released) throw new Error('WinRT implementation handle is released') + return this.#owner.toValue() + } + + release() { + if (this.#released) return + const value = this.#value + this.#released = true + this.#value = undefined + try { + if (value !== undefined) this.#releaseView(value) + } finally { + this.#owner.release() + } + } + + disconnect() { this.#owner.disconnect() } + dispose() { + this.disconnect() + this.release() + } + get isClosed() { return this.#owner.isClosed } + takeError() { return this.#owner.takeError() } +} + +module.exports.DynWinRtImplementationHandle = DynWinRtImplementationHandle diff --git a/bindings/js/scripts/generate-entrypoints.mjs b/bindings/js/scripts/generate-entrypoints.mjs index 545375ce..d243df4f 100644 --- a/bindings/js/scripts/generate-entrypoints.mjs +++ b/bindings/js/scripts/generate-entrypoints.mjs @@ -217,6 +217,21 @@ writeFacade('winrt', winrtExports, [...winrtExports, 'DynWinRtImplementationMeth " readonly plan: import('./index.js').DynWinRtInterfacePlan", " readonly dispatch: (vtableIndex: number, args: import('./index.js').DynWinRtValue[]) => import('./index.js').DynWinRtValue[]", '}', + 'export interface DynWinRtImplementationType { implementation(handlers: never): DynWinRtImplementationDescriptor }', + 'type ImplementationHandlers = T extends { implementation(handlers: infer H): DynWinRtImplementationDescriptor } ? H : never', + 'export type DynWinRtImplementationOptions = {', + ' readonly interfaces: { readonly [K in keyof T]: readonly [T[K], NoInfer>] }', + '}', + 'export declare class DynWinRtImplementationHandle {', + ' private constructor()', + ' readonly value: T', + " toValue(): import('./index.js').DynWinRtValue", + ' release(): void', + ' disconnect(): void', + ' dispose(): void', + ' readonly isClosed: boolean', + ' takeError(): string | null', + '}', ]) writeFacade( 'com', @@ -243,6 +258,10 @@ writeFacade( true, ) +writeFileSync( + join(distDir, 'winrt-implementation.cjs'), + readFileSync(join(packageDir, 'runtime', 'winrt-implementation.cjs'), 'utf8'), +) writeFileSync( join(distDir, 'com-projection.js'), readFileSync(join(packageDir, 'runtime', 'com-projection.cjs'), 'utf8'), @@ -266,6 +285,9 @@ function writeFacade( "'use strict'", "const native = require('./index.js')", ...exports.map((value) => `module.exports.${value} = native.${value}`), + ...(name === 'winrt' ? [ + "module.exports.DynWinRtImplementationHandle = require('./winrt-implementation.cjs').DynWinRtImplementationHandle", + ] : []), ...(comProjection ? [ "const projection = require('./com-projection.js')", 'module.exports.projectAs = projection.projectAs', diff --git a/bindings/py/README.md b/bindings/py/README.md index ae115921..c405e9bd 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -195,11 +195,10 @@ Python garbage collection. Generated, supported non-generic WinRT interfaces provide `.implementation()` and `.implement()` factories. They create standalone, `IInspectable`-rooted objects; they do not activate or register an OS class, compose a WinUI control, -or implement Classic COM interfaces. Use the public `from_implementation()` -factory to obtain a typed view without transferring the owner's reference: +or implement Classic COM interfaces. `.implement()` returns a generic management +handle with a stable typed `.value`, not a type cast or the raw handler: ```python -from dynwinrt import release_projected from generated.windows.foundation import IClosable, IStringable class Label: @@ -211,13 +210,9 @@ class Label: handler = Label() with IStringable.implement( - handler, IClosable.implementation(handler) -) as owner: - label = IStringable.from_implementation(owner) - try: - print(label.to_string()) - finally: - release_projected(label) + handler, interfaces=[(IClosable, handler)] +) as impl: + print(impl.value.to_string()) ``` The generated handler protocols describe snake-case methods and their input @@ -225,7 +220,12 @@ and output types. Additional interface descriptors provide separate native views sharing the same object identity. Every required interface must be included; an incomplete implementation is rejected before publication. `release_projected(view)` releases a view independently without disposing or -releasing its controller. +releasing its controller. The advanced `from_implementation(impl)` path accepts +both new handles and low-level native owners; positional descriptors remain +supported. The primary `.value` needs no `release_projected` in the common +pattern. It is created lazily once, and `release()`/`dispose()` release that +view along with the handle's owner reference. `.value` raises after either +operation and never recreates a released view. The low-level runtime surface is: @@ -287,7 +287,8 @@ reported as owner edges only when that owner is the sole native reference. This collects ordinary handler/self/owner cycles without treating native consumers as collectable Python references. Cycles that retain a native alias, or that have requested native weak references, may require **explicit -`dispose()`**. Callback invocation and `to_value()` require the creating thread; +`dispose()`**, including a handler capturing a typed handle whose primary view +has already been created. Callback invocation and `to_value()` require the creating thread; foreign-thread `to_value()` raises `OSError` with `RPC_E_WRONG_THREAD`. Owner release, disposal, and garbage collection can run on another Python thread without leaking the owner's native reference. This does not make diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index ec0a8da1..72fcbc8b 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -1,5 +1,5 @@ from collections.abc import Coroutine -from typing import Any, Awaitable, Callable, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload +from typing import Any, Awaitable, Callable, Generic, List, Literal, Mapping, Optional, Protocol, Sequence, TypeVar, Union, final, overload from uuid import UUID _T = TypeVar("_T", covariant=True) @@ -7,6 +7,7 @@ _P = TypeVar("_P", covariant=True) _Tracked = TypeVar("_Tracked") _Projected_co = TypeVar("_Projected_co", covariant=True) _ProjectableClass = TypeVar("_ProjectableClass", bound="_DynWinRTProjectableClass") +_Handlers_contra = TypeVar("_Handlers_contra", contravariant=True) class _DynWinRTProjector(Protocol[_Projected_co]): @@ -31,6 +32,7 @@ __all__ = [ "DynWinRTInterfacePlan", "DynWinRTImplementation", "DynWinRTImplementationDescriptor", + "DynWinRTImplementationHandle", "DynWinRTDelegateMethod", "DynWinRTOverrideInterface", "DynWinRTXamlRegistration", @@ -313,6 +315,24 @@ class DynWinRTImplementation: self, _exc_type: object, _exc_value: object, _traceback: object ) -> Literal[False]: ... +class _DynWinRTImplementationFactory(Protocol[_Handlers_contra]): + def implementation(self, handlers: _Handlers_contra) -> DynWinRTImplementationDescriptor: ... + +@final +class DynWinRTImplementationHandle(Generic[_Projected_co]): + def __init__(self, owner: DynWinRTImplementation, projector: Callable[[DynWinRTImplementation], _Projected_co]) -> None: ... + @property + def value(self) -> _Projected_co: ... + def to_value(self) -> DynWinRTValue: ... + def release(self) -> None: ... + def disconnect(self) -> None: ... + def dispose(self) -> None: ... + @property + def is_closed(self) -> bool: ... + def take_error(self) -> Optional[str]: ... + def __enter__(self) -> DynWinRTImplementationHandle[_Projected_co]: ... + def __exit__(self, _exc_type: object, _exc_value: object, _traceback: object) -> Literal[False]: ... + @final class DynWinRTOverrideInterface: diff --git a/bindings/py/src/implementation.py b/bindings/py/src/implementation.py index 6055a8a5..f0a7d796 100644 --- a/bindings/py/src/implementation.py +++ b/bindings/py/src/implementation.py @@ -2,6 +2,9 @@ # Licensed under the MIT License. import inspect as _implementation_inspect +from typing import Generic as _ImplementationGeneric, TypeVar as _ImplementationTypeVar + +_ImplementationValue = _ImplementationTypeVar("_ImplementationValue", covariant=True) def _dynwinrt_require_sync_implementation_callable(callback): @@ -71,3 +74,101 @@ def dispatch(self, vtable_index, args): return _dynwinrt_validate_implementation_result( self._dispatch(vtable_index, args) ) + + +class DynWinRTImplementationHandle(_ImplementationGeneric[_ImplementationValue]): + """Manage a lazy, stable typed primary view without mixing lifecycle methods into it.""" + + def __init__(self, owner, projector): + if not isinstance(owner, DynWinRTImplementation) or not callable(projector): + raise TypeError("A WinRT implementation handle requires an owner and typed projector") + self._owner = owner + self._projector = projector + self._value = None + self._released = False + self._projecting = False + + @staticmethod + def _create(interface, handlers, additional, interfaces): + descriptors = [interface.implementation(handlers), *additional] + for entry in interfaces: + if ( + not isinstance(entry, (tuple, list)) or len(entry) != 2 + or not getattr(entry[0], "_dynwinrt_interface_type", False) + or not callable(getattr(entry[0], "implementation", None)) + or not callable(getattr(entry[0], "from_implementation", None)) + ): + raise TypeError("Each interface entry must be (generated_interface, handler)") + descriptors.append(entry[0].implementation(entry[1])) + if any(not isinstance(item, DynWinRTImplementationDescriptor) for item in descriptors): + raise TypeError("Invalid WinRT implementation descriptor") + dispatchers = tuple(item.dispatch for item in descriptors) + + def callback(index, slot, args): + if not isinstance(index, int) or index < 0 or index >= len(dispatchers): + raise ValueError("Unknown implementation interface index") + return dispatchers[index](slot, args) + + owner = DynWinRTImplementation.create([item.plan for item in descriptors], callback) + return DynWinRTImplementationHandle(owner, interface.from_implementation) + + @property + def value(self): + if self._released or self._owner.is_closed: + raise RuntimeError("WinRT implementation handle is closed or released") + if self._value is None: + if self._projecting: + raise RuntimeError("WinRT implementation primary view creation is reentrant") + self._projecting = True + try: + value = self._projector(self._owner) + if self._released or self._owner.is_closed: + release_projected(value) + raise RuntimeError("WinRT implementation was released during primary view creation") + self._value = value + except BaseException: + self.dispose() + raise + finally: + self._projecting = False + return self._value + + def to_value(self): + if self._released: + raise RuntimeError("WinRT implementation handle is released") + return self._owner.to_value() + + def release(self): + if self._released: + return + value = self._value + self._released = True + self._value = None + try: + if value is not None: + release_projected(value) + finally: + self._owner.release() + + def disconnect(self): + self._owner.disconnect() + + def dispose(self): + self.disconnect() + self.release() + + @property + def is_closed(self): + return self._owner.is_closed + + def take_error(self): + return self._owner.take_error() + + def __enter__(self): + if self._released or self.is_closed: + raise RuntimeError("WinRT implementation handle is closed or released") + return self + + def __exit__(self, _exc_type, _exc_value, _traceback): + self.dispose() + return False diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 034b0a9b..99ebb131 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -603,6 +603,7 @@ for _name in ( 'WinRTCoroutine', 'WinRTCoroutineWithProgress', 'DynWinRTImplementationDescriptor', + 'DynWinRTImplementationHandle', 'ProjectedLifetimeScope', 'projected_lifetime_scope', 'project_as', diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index b48ad59b..04f62aa3 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -913,7 +913,9 @@ impl DynWinRTOverrideInterface { #[pymethods] impl DynWinRTMethodHandle { /// Invoke this method on a COM object. - fn invoke(&self, obj: &DynWinRTValue, args: Vec) -> PyResult { + fn invoke(&self, obj: DynWinRTValue, args: Vec) -> PyResult { + // Extraction retains the native object without holding a Python borrow + // while an implementation callback may release the original wrapper. let raw = match &obj.0 { dynwinrt::WinRTValue::Object(o) => o.as_raw(), _ => return Err(PyRuntimeError::new_err("invoke() requires an Object value")), @@ -988,7 +990,7 @@ impl DynWinRTMethodHandle { /// Used for methods with multiple out params (e.g. IVector.IndexOf → [index, found]). fn invoke_all( &self, - obj: &DynWinRTValue, + obj: DynWinRTValue, args: Vec, ) -> PyResult> { let raw = match &obj.0 { @@ -1085,7 +1087,7 @@ impl DynWinRTMethodHandle { // --- Fast paths: skip Vec alloc for common getter patterns --- /// Getter → string (0 args, zero Vec allocation) - fn get_string(&self, obj: &DynWinRTValue) -> PyResult { + fn get_string(&self, obj: DynWinRTValue) -> PyResult { let raw = obj .0 .as_object() @@ -1099,7 +1101,7 @@ impl DynWinRTMethodHandle { } /// Getter → i32 (0 args, zero Vec allocation) - fn get_i32(&self, obj: &DynWinRTValue) -> PyResult { + fn get_i32(&self, obj: DynWinRTValue) -> PyResult { let raw = obj .0 .as_object() @@ -1109,7 +1111,7 @@ impl DynWinRTMethodHandle { } /// Getter → bool (0 args, zero Vec allocation) - fn get_bool(&self, obj: &DynWinRTValue) -> PyResult { + fn get_bool(&self, obj: DynWinRTValue) -> PyResult { let raw = obj .0 .as_object() @@ -1119,7 +1121,7 @@ impl DynWinRTMethodHandle { } /// Getter → DynWinRTValue object (0 args, zero Vec allocation) - fn get_obj(&self, obj: &DynWinRTValue) -> PyResult { + fn get_obj(&self, obj: DynWinRTValue) -> PyResult { let raw = obj .0 .as_object() @@ -1132,7 +1134,7 @@ impl DynWinRTMethodHandle { } /// 1-arg invoke with hstring input → DynWinRTValue result - fn invoke_hstring(&self, obj: &DynWinRTValue, arg: String) -> PyResult { + fn invoke_hstring(&self, obj: DynWinRTValue, arg: String) -> PyResult { let raw = obj .0 .as_object() @@ -1148,7 +1150,7 @@ impl DynWinRTMethodHandle { } /// 1-arg invoke with i32 input → DynWinRTValue result - fn invoke_i32(&self, obj: &DynWinRTValue, arg: i32) -> PyResult { + fn invoke_i32(&self, obj: DynWinRTValue, arg: i32) -> PyResult { let raw = obj .0 .as_object() diff --git a/bindings/py/tests/test_typing_package.py b/bindings/py/tests/test_typing_package.py index 8db79e90..b838bf21 100644 --- a/bindings/py/tests/test_typing_package.py +++ b/bindings/py/tests/test_typing_package.py @@ -26,6 +26,9 @@ def test_wheel_exports_typed_implementation_surface(): assert name in dynwinrt.__all__ assert hasattr(dynwinrt, name) assert f"class {name}:" in stub + assert "DynWinRTImplementationHandle" in dynwinrt.__all__ + assert "class DynWinRTImplementationHandle(Generic[_Projected_co])" in stub + assert dynwinrt.DynWinRTImplementationHandle[int] signature = inspect.signature(dynwinrt.DynWinRTInterfacePlan.create) assert signature.parameters["required_iids"].default == () assert "def from_hresult(" in stub diff --git a/docs/architecture/winrt-interface-implementations.md b/docs/architecture/winrt-interface-implementations.md index 0dcd0e2a..71e632ed 100644 --- a/docs/architecture/winrt-interface-implementations.md +++ b/docs/architecture/winrt-interface-implementations.md @@ -91,6 +91,21 @@ does not disconnect independently retained native references. Explicit reference. Already-dispatched callbacks may finish, including returning their fully validated outputs; later calls return `RO_E_CLOSED`. +Generated `implement` factories now wrap that unchanged low-level controller +in a language-neutral-in-semantics typed management facade. Its lazy `.value` +caches one owning primary QI view, rather than performing QI on every access. +Facade release clears its primary view and controller reference; disposal first +disconnects the native object. Neither path can recreate the primary view. +Independent-view helpers accept either facade or low-level controller. +Python outbound method handles retain their receiver natively without keeping +a PyO3 borrow across callback entry, so disposing the primary view from inside +its own callback remains valid. + +Common Python reverse-conversion helpers live once in each generated package's +`_runtime.py`, shared by its interface modules. They are ordinary measured +generated code, not excluded coverage support. Method-specific ABI plans and +typed conversions remain with their interface. + Language bindings additionally gate dispatch on their environment/interpreter lifetime. Callback roots belong to the native object, not merely the original language wrapper. Shutdown disconnects language callback state before its diff --git a/docs/guides/windows/winrt-interface-implementations.md b/docs/guides/windows/winrt-interface-implementations.md index 98797365..39c3bd88 100644 --- a/docs/guides/windows/winrt-interface-implementations.md +++ b/docs/guides/windows/winrt-interface-implementations.md @@ -11,19 +11,19 @@ handler declaration describes exactly which methods and results to provide. ## Construction and typed interface views -`Interface.implementation(handlers)` describes one implemented interface. -`Interface.implement(handlers, ...additional)` creates a native owner from one -or more descriptors. The returned `DynWinRtImplementation` (Node) or -`DynWinRTImplementation` (Python) is distinct from a typed interface view. - -Use `Interface.fromImplementation(owner)` in Node, or -`Interface.from_implementation(owner)` in Python, to obtain a public typed view. -This keeps the owner valid and creates an independently owned interface -reference. The view is accepted by ordinary generated methods taking that -interface; no type assertion or internal `_fromNative` helper is needed. -Repeated conversions to the same IID return independent views. Python's new -conversion remains tracked by the current projected lifetime scope, but does -not reuse or replace the ordinary `from_value` identity cache. +`Interface.implement(handlers)` creates a native implementation **instance** +and returns a management handle: `DynWinRtImplementationHandle` in +Node or `DynWinRTImplementationHandle[Interface]` in Python. Its read-only +`.value` is the generated primary interface, not the handler object or a raw +native value. Calling it traverses the ordinary native WinRT ABI. + +The primary view is created lazily and cached: repeated `.value` accesses +return the same object. `release()` releases both that view, if created, and +the handle's native-owner reference. `dispose()` also disconnects future +callbacks object-wide. After either operation `.value` raises; it never +recreates a released view. The common pattern needs no separate view-release +call. Lifecycle methods live on the handle, so interface members named +`close`, `release`, or `dispose` do not collide. ### Node.js @@ -37,23 +37,14 @@ cargo run -p dynwinrt-codegen -- generate ` ```js import { roInitialize } from '@microsoft/dynwinrt'; -import { IClosable, IStringable, releaseProjected } from './generated/index.js'; +import { IStringable } from './generated/index.js'; roInitialize(1); -const owner = IStringable.implement( - { toString: () => 'Implemented in JavaScript' }, - IClosable.implementation({ close: () => console.log('Native Close call') }), -); -const text = IStringable.fromImplementation(owner); -const closable = IClosable.fromImplementation(owner); +const impl = IStringable.implement({ toString: () => 'Implemented in JavaScript' }); try { - console.log(text.toString()); // Outbound native call, then reverse callback. - owner.release(); // These two interface references remain valid. - closable.close(); + console.log(impl.value.toString()); // Native call, then reverse callback. } finally { - owner.dispose(); // Disconnect every retained view's callbacks. - releaseProjected(closable); - releaseProjected(text); + impl.dispose(); } ``` @@ -73,31 +64,15 @@ cargo run -p dynwinrt-codegen -- generate ` ``` ```python -from dynwinrt import RoApartment, release_projected -from generated.windows.foundation import IClosable, IStringable +from dynwinrt import RoApartment +from generated.windows.foundation import IStringable class TextHandler: def to_string(self) -> str: return "Implemented in Python" -class CloseHandler: - def close(self) -> None: - print("Native Close call") - -with RoApartment(1): - owner = IStringable.implement( - TextHandler(), IClosable.implementation(CloseHandler()) - ) - text = IStringable.from_implementation(owner) - closable = IClosable.from_implementation(owner) - try: - print(text.to_string()) # Crosses the native vtable in both directions. - owner.release() - closable.close() - finally: - owner.dispose() - release_projected(closable) - release_projected(text) +with RoApartment(1), IStringable.implement(TextHandler()) as impl: + print(impl.value.to_string()) # Crosses the native vtable in both directions. ``` Python handler objects may use ordinary bound methods. Generated `.pyi` @@ -110,6 +85,36 @@ Python implementations currently require the main CPython interpreter; subinterpreter-owned callbacks are rejected at construction. Captured `contextvars` follow the existing Python callback-context convention. +### Multiple interfaces and advanced views + +Routine multi-interface construction keeps the primary type inferred: + +```js +const impl = IBackgroundTask.implement(taskHandlers, { + interfaces: [[IStringable, textHandlers]], +}); +impl.value.run(instanceView); +``` + +```python +with IBackgroundTask.implement(handler, interfaces=[(IStringable, text_handler)]) as impl: + impl.value.run(instance_view) +``` + +Each entry explicitly supplies a generated interface and its handlers. Complete +metadata validation, duplicate IIDs, and required-interface checks happen before +native publication. Existing positional `.implementation(...)` descriptors are +still supported, and may be preferable for reusable heterogeneous compositions. + +`Interface.fromImplementation(impl)` / `Interface.from_implementation(impl)` +remains the advanced independent-view path; it accepts either a typed handle +or the low-level native owner. Each call owns a separate QI reference that is +released with `releaseProjected(view)` / `release_projected(view)`. Independent +views survive handle `release()`, but not object-wide `dispose()`. +Python views remain tracked by their projection lifetime scope; the ordinary +`from_value` cache behavior is unchanged. Scope exit can release a handle's +cached primary view; accessing it does not silently create a new one. + ## Supported contracts Support is determined from the entire interface, not only from the method an @@ -179,7 +184,8 @@ interfaces rather than exposing private factory interfaces. | `toValue()` / `to_value()` | Create an owned low-level native value for explicit interop | | Public typed view conversion | Create an owned typed view without consuming the owner | | `releaseProjected(view)` / `release_projected(view)` | Release that view without disposing the controller or other views | -| `release()` on the implementation owner | Drop only that owner's native reference | +| `impl.value` | Stable, handle-managed primary interface view | +| `release()` on the typed handle | Release its primary view and native-owner reference, without disconnecting other native owners | | `disconnect()` | Disconnect callbacks for the whole implemented object | | `dispose()` | Disconnect the whole object, then release the owner's reference | | `takeError()` / `take_error()` | Retrieve and clear the last contextual native callback error | @@ -208,6 +214,12 @@ Python can collect an owner-only callback cycle when that owner holds the sole native reference. Native aliases or native weak-reference use are treated conservatively and may require explicit disposal. Native reference cleanup can run on another thread without granting permission to invoke handlers there. +This includes a handler that captures its typed handle after the primary view +has been created: that view is another native reference. Use `dispose()` or +Python's handle context manager to break such cycles deterministically. +When a handle is collected without a capture cycle, its native owner and +unreferenced primary view are collected normally; independently retained native +references remain callable. Language exceptions are reported as real failing HRESULTs. The owner's error accessor provides interface/slot context; Python also reports the original diff --git a/eng/coverage/coverage.ps1 b/eng/coverage/coverage.ps1 index c3ca2572..915d9315 100644 --- a/eng/coverage/coverage.ps1 +++ b/eng/coverage/coverage.ps1 @@ -292,7 +292,7 @@ function Get-JavaScriptCoverageLayers { [pscustomobject]@{ Name = "JavaScript runtime" Path = $jsRuntimeReport - Includes = @("bindings/js/dist/**/*.js") + Includes = @("bindings/js/dist/**/*.js", "bindings/js/dist/**/*.cjs") RequiredSourcePattern = "bindings[\\/]js[\\/]dist[\\/]index\.js" } if ($All -or $winrtCoverageExpected) { diff --git a/samples/js/interface-implementation/README.md b/samples/js/interface-implementation/README.md index c7b65a23..4117eae4 100644 --- a/samples/js/interface-implementation/README.md +++ b/samples/js/interface-implementation/README.md @@ -29,9 +29,15 @@ Pop-Location The local npm dependency uses the runtime built in this checkout. Generation auto-detects the Windows SDK; pass `-Winmd` to select another Windows.winmd. -The owner and typed views have independent references. `owner.release()` +The factory returns a management handle. `impl.value` is the stable primary +interface; use `try/finally` with `impl.dispose()` for the common pattern. +`interfaces: [[Interface, handlers], ...]` adds explicitly typed interfaces. +The handle owns and releases its primary view; no `releaseProjected(impl.value)` +is needed. + +The handle and advanced independent views have separate references. `impl.release()` releases only the creator's reference, so the retained views continue to work. -`owner.dispose()` disconnects all future callbacks; the sample confirms a +`impl.dispose()` disconnects all future callbacks; the sample confirms a later native call fails and prints its contextual diagnostic. An already entered callback is allowed to finish. IClosable.Close is just another handler-defined method, not a hidden alias for owner disposal. The generated diff --git a/samples/js/interface-implementation/app.mjs b/samples/js/interface-implementation/app.mjs index e5e0f6ef..ff28bb92 100644 --- a/samples/js/interface-implementation/app.mjs +++ b/samples/js/interface-implementation/app.mjs @@ -20,7 +20,7 @@ function unavailable() { let progress = 0; let runs = 0; let closes = 0; -const instanceOwner = IBackgroundTaskInstance.implement({ +const instanceImpl = IBackgroundTaskInstance.implement({ getInstanceId: () => '4ab7eea7-29a1-4f48-a6da-22894e210ec0', getTask: unavailable, getProgress: () => progress, @@ -40,41 +40,41 @@ const handlers = { toString: () => `JavaScript task: ${runs} native Run calls`, close: () => { closes += 1; }, }; -const owner = IBackgroundTask.implement( - handlers, - IStringable.implementation(handlers), - IClosable.implementation(handlers), -); -const instance = IBackgroundTaskInstance.fromImplementation(instanceOwner); -const task = IBackgroundTask.fromImplementation(owner); -const text = IStringable.fromImplementation(owner); -const duplicateText = IStringable.fromImplementation(owner); -const closable = IClosable.fromImplementation(owner); +const impl = IBackgroundTask.implement(handlers, { + interfaces: [[IStringable, handlers], [IClosable, handlers]], +}); +const text = IStringable.fromImplementation(impl); +const duplicateText = IStringable.fromImplementation(impl); +const closable = IClosable.fromImplementation(impl); try { assert.notStrictEqual(text, duplicateText); releaseProjected(duplicateText); // Both the Run call and its progress property calls cross native vtables. - task.run(instance); - assert.equal(instance.progress, 1); + assert.strictEqual(impl.value, impl.value); + impl.value.run(instanceImpl.value); + assert.equal(instanceImpl.value.progress, 1); console.log(text.toString()); - owner.release(); - task.run(instance); - assert.equal(instance.progress, 2); + const independentTask = IBackgroundTask.fromImplementation(impl); + impl.release(); + assert.throws(() => impl.value, /released/); + independentTask.run(instanceImpl.value); + releaseProjected(independentTask); + assert.equal(instanceImpl.value.progress, 2); closable.close(); assert.equal(closes, 1); releaseProjected(closable); - assert.equal(owner.isClosed, false); + assert.equal(impl.isClosed, false); console.log(text.toString()); - owner.dispose(); + impl.dispose(); assert.throws(() => text.toString(), /closed|80000013/i); - const diagnostic = owner.takeError(); + const diagnostic = impl.takeError(); assert.match(diagnostic, /0x80000013/); console.log(diagnostic); } finally { - owner.dispose(); - instanceOwner.dispose(); - for (const view of [closable, duplicateText, text, task, instance]) releaseProjected(view); + impl.dispose(); + instanceImpl.dispose(); + for (const view of [closable, duplicateText, text]) releaseProjected(view); } diff --git a/samples/python/interface-implementation/README.md b/samples/python/interface-implementation/README.md index cd262b04..7a31c8cb 100644 --- a/samples/python/interface-implementation/README.md +++ b/samples/python/interface-implementation/README.md @@ -26,8 +26,13 @@ Generation auto-detects the Windows SDK; `-Winmd` selects an explicit metadata file. The generated package is imported from the sample directory and does not need to be installed separately. -Releasing the implementation owner's reference leaves independently retained -typed views usable. Explicit disposal in `finally` disconnects every view's +The common pattern is `with IBackgroundTask.implement(handler) as impl:`, +then `impl.value.run(instance_view)`. The primary view is stable and managed +by the handle; context exit disposes it without a separate view-release call. +`interfaces=[(Interface, handler), ...]` provides convenient additional views. + +Releasing the implementation handle's own references leaves independently retained +typed views usable. Explicit disposal or context exit disconnects every view's future callbacks. Already-entered callbacks may finish. The projected lifetime scope releases typed wrappers before the apartment exits. The implementation owner's own context-manager exit, when used, performs **dispose**, not release. diff --git a/samples/python/interface-implementation/app.py b/samples/python/interface-implementation/app.py index 1f74d32d..92234cdc 100644 --- a/samples/python/interface-implementation/app.py +++ b/samples/python/interface-implementation/app.py @@ -66,50 +66,46 @@ def close(self) -> None: def main() -> None: with RoApartment(1), projected_lifetime_scope(): - instance_owner = IBackgroundTaskInstance.implement(TaskInstance()) handlers = Task() - owner = IBackgroundTask.implement( - handlers, - IStringable.implementation(handlers), - IClosable.implementation(handlers), - ) - instance = IBackgroundTaskInstance.from_implementation(instance_owner) - task = IBackgroundTask.from_implementation(owner) - text = IStringable.from_implementation(owner) - duplicate_text = IStringable.from_implementation(owner) - closable = IClosable.from_implementation(owner) - try: - assert text is not duplicate_text - release_projected(duplicate_text) - # Run and its nested progress property calls traverse native vtables. - task.run(instance) - assert instance.progress == 1 - print(text.to_string()) - owner.release() - task.run(instance) - assert instance.progress == 2 - closable.close() - assert handlers.closes == 1 - release_projected(closable) - assert not owner.is_closed - print(text.to_string()) - owner.dispose() + with IBackgroundTaskInstance.implement(TaskInstance()) as instance_impl, IBackgroundTask.implement( + handlers, interfaces=[(IStringable, handlers), (IClosable, handlers)] + ) as impl: + # Primary views are owned by the handles and require no separate release. + assert impl.value is impl.value + impl.value.run(instance_impl.value) + assert instance_impl.value.progress == 1 + text = IStringable.from_implementation(impl) + duplicate_text = IStringable.from_implementation(impl) + closable = IClosable.from_implementation(impl) try: - text.to_string() - except OSError as error: - if error.winerror != -2147483629: # RO_E_CLOSED - raise - diagnostic = owner.take_error() - assert isinstance(diagnostic, str) and "0x80000013" in diagnostic - print(diagnostic) - else: - raise AssertionError("A disposed implementation accepted a native callback") - finally: - owner.dispose() - instance_owner.dispose() - for view in (closable, duplicate_text, text, task, instance): - release_projected(view) - assert owner.is_closed + assert text is not duplicate_text + release_projected(duplicate_text) + print(text.to_string()) + independent_task = IBackgroundTask.from_implementation(impl) + impl.release() + independent_task.run(instance_impl.value) + release_projected(independent_task) + assert instance_impl.value.progress == 2 + closable.close() + assert handlers.closes == 1 + release_projected(closable) + assert not impl.is_closed + print(text.to_string()) + impl.dispose() + try: + text.to_string() + except OSError as error: + if error.winerror != -2147483629: # RO_E_CLOSED + raise + diagnostic = impl.take_error() + assert isinstance(diagnostic, str) and "0x80000013" in diagnostic + print(diagnostic) + else: + raise AssertionError("A disposed implementation accepted a native callback") + finally: + for view in (closable, duplicate_text, text): + release_projected(view) + assert impl.is_closed if __name__ == "__main__": diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index 297d3a89..3f49b116 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -360,6 +360,10 @@ if ("py" -in $Lang) { --output $pyResult if ($LASTEXITCODE -ne 0) { $totalFail++ } else { $totalPass++ } if (Test-Path $pyResult) { $allResults += (Get-Content $pyResult -Raw | ConvertFrom-Json) } + & $pythonExe (Join-Path $runnersDir "implementation_py.py") ` + --generated $pyBindingsDir --cases "management_handle,property_views,multi_interface_lifetime,memory_buffer_event" ` + --output (Join-Path $e2eDir "standard_implementation_py.json") + if ($LASTEXITCODE -ne 0) { $totalFail++ } else { $totalPass++ } } if ("ts" -in $Lang) { @@ -377,6 +381,11 @@ if ("ts" -in $Lang) { --output $tsResult if ($LASTEXITCODE -ne 0) { $totalFail++ } else { $totalPass++ } if (Test-Path $tsResult) { $allResults += (Get-Content $tsResult -Raw | ConvertFrom-Json) } + & node (Join-Path $runnersDir "implementation_js.mjs") ` + --generated (Join-Path $e2eDir "ts") --runtime (Join-Path $root "bindings\js\dist\winrt.js") ` + --cases "management_handle,property_views,multi_interface_lifetime,memory_buffer_event" ` + --output (Join-Path $e2eDir "standard_implementation_ts.json") + if ($LASTEXITCODE -ne 0) { $totalFail++ } else { $totalPass++ } } if ("com" -in $Lang) { diff --git a/tests/e2e/implementation_test.ps1 b/tests/e2e/implementation_test.ps1 index 8209a4f0..0dca828a 100644 --- a/tests/e2e/implementation_test.ps1 +++ b/tests/e2e/implementation_test.ps1 @@ -43,6 +43,8 @@ $classes = @( "Windows.ApplicationModel.Background.IBackgroundTaskInstance", "Windows.Foundation.IStringable", "Windows.Foundation.IClosable", + "Windows.Foundation.Uri", + "Windows.Foundation.WwwFormUrlDecoder", "Windows.Foundation.IMemoryBufferReference", "Windows.Globalization.NumberFormatting.INumberParser", "Windows.Foundation.IPropertyValue", diff --git a/tests/e2e/runners/implementation_js.mjs b/tests/e2e/runners/implementation_js.mjs index 46cf5e64..80ff4d11 100644 --- a/tests/e2e/runners/implementation_js.mjs +++ b/tests/e2e/runners/implementation_js.mjs @@ -101,10 +101,104 @@ function readerHandlers(readBytes) { } const cases = { + management_handle({ g, runtime, own }) { + let calls = 0; + const impl = own(g.IStringable.implement( + { toString() { calls++; return 'typed primary'; } }, + { interfaces: [[g.IClosable, { close() { calls++; } }]] }, + )); + assert.strictEqual(impl.value, impl.value); + assert.ok(impl.value instanceof g.IStringable); + assert.equal(impl.value.toString(), 'typed primary'); + const extra = g.IStringable.fromImplementation(impl); + assert.notStrictEqual(extra, impl.value); + const closer = g.IClosable.fromImplementation(impl); + closer.close(); + const primary = impl.value; + impl.release(); + assert.throws(() => impl.value, /released/); + assert.throws(() => primary.toString(), /Object|object|released/); + assert.equal(extra.toString(), 'typed primary'); + impl.dispose(); + expectHresult(() => extra.toString(), RO_E_CLOSED); + assert.equal(calls, 3); + g.releaseProjected(extra); + g.releaseProjected(closer); + const lazy = own(g.IStringable.implement({ toString: () => 'never projected' })); + lazy.release(); + assert.throws(() => lazy.value, /released/); + assert.equal(lazy.isClosed, true); + for (const interfaces of [[[g.IStringable, {}]], [[null, {}]], [[g.IClosable]], [[g.IStringable, { toString: () => '' }]]]) { + assert.throws(() => g.IStringable.implement({ toString: () => '' }, { interfaces }), /handler|entry|entries|Duplicate|duplicate/); + } + let failedOwner; + class Broken extends g.IStringable { + static fromImplementation(owner) { + failedOwner = owner; + throw new Error('primary view failure'); + } + } + const broken = own(Broken.implement({ toString: () => 'unreachable' })); + assert.throws(() => broken.value, /primary view failure/); + assert.equal(failedOwner.isClosed, true); + assert.throws(() => broken.value, /closed|released/); + const wrong = own(g.IStringable.implement({ toString: () => 17 })); + expectHresult(() => wrong.value.toString(), E_FAIL); + takeError(wrong, /invalid implementation result/); + let reentrant; + class ReleasedDuringProjection extends g.IStringable { + static fromImplementation(owner) { + const value = super.fromImplementation(owner); + reentrant.release(); + return value; + } + } + reentrant = own(ReleasedDuringProjection.implement({ toString: () => '' })); + assert.throws(() => reentrant.value, /released during/); + assert.equal(reentrant.isClosed, true); + const disposing = own(g.IStringable.implement({ + toString() { disposing.dispose(); return 'entered callback completed'; }, + })); + assert.equal(disposing.value.toString(), 'entered callback completed'); + assert.equal(disposing.isClosed, true); + assert.throws(() => disposing.value, /closed|released/); + }, + + property_views({ g, own }) { + let length = 0; + const handlers = { + getCapacity: () => 12, getLength: () => length, + setLength(value) { if (value > 12) throw new Error('capacity exceeded'); length = value; }, + getAbsoluteCanonicalUri: () => 'https://example.test/\u96ea', + getDisplayIri: () => 'https://example.test/\u96ea', + getName: () => 'query', getValue: () => 'value\0\u96ea', + }; + const impl = own(g.IBuffer.implement(handlers, { + interfaces: [[g.IUriRuntimeClassWithAbsoluteCanonicalUri, handlers], [g.IWwwFormUrlDecoderEntry, handlers]], + })); + const uri = g.IUriRuntimeClassWithAbsoluteCanonicalUri.fromImplementation(impl); + const entry = g.IWwwFormUrlDecoderEntry.fromImplementation(impl); + assert.equal(impl.value.capacity, 12); + assert.equal(impl.value.length, 0); + impl.value.length = 7; + assert.equal(impl.value.length, 7); + assert.equal(uri.absoluteCanonicalUri, 'https://example.test/\u96ea'); + assert.equal(uri.displayIri, 'https://example.test/\u96ea'); + assert.equal(entry.name, 'query'); + assert.equal(entry.value, 'value\0\u96ea'); + expectHresult(() => { impl.value.length = 13; }, E_FAIL); + takeError(impl, /capacity exceeded/); + assert.equal(impl.value.length, 7); + impl.value.length = 0; + assert.equal(impl.value.length, 0); + g.releaseProjected(uri); + g.releaseProjected(entry); + }, + background_task({ g, runtime, own }) { const state = { progress: 17, gets: 0, sets: 0, getIds: 0 }; const instanceOwner = own(g.IBackgroundTaskInstance.implement(taskInstanceHandlers(state))); - const instance = g.IBackgroundTaskInstance.fromImplementation(instanceOwner); + const instance = instanceOwner.value; let runs = 0; const taskOwner = own(g.IBackgroundTask.implement({ run(taskInstance) { @@ -114,13 +208,15 @@ const cases = { runs++; }, })); - const task = g.IBackgroundTask.fromImplementation(taskOwner); + const task = taskOwner.value; task.run(instance); assert.deepEqual(state, { progress: 22, gets: 1, sets: 1, getIds: 1 }); assert.equal(runs, 1); + const retainedInstance = g.IBackgroundTaskInstance.fromImplementation(instanceOwner); + const retainedTask = g.IBackgroundTask.fromImplementation(taskOwner); instanceOwner.release(); taskOwner.release(); - task.run(instance); + retainedTask.run(retainedInstance); assert.deepEqual(state, { progress: 27, gets: 2, sets: 2, getIds: 2 }); assert.equal(runs, 2); const token = runtime.DynWinRtStruct.create(runtime.DynWinRtType.structType( @@ -128,12 +224,12 @@ const cases = { )); token.setI64(0, 1n); for (const action of [ - () => instance.task, - () => instance.triggerDetails, - () => instance.suspendedCount, - () => instance.getDeferral(), - () => instance.onCanceled(() => {}), - () => instance.offCanceled(token.toValue()), + () => retainedInstance.task, + () => retainedInstance.triggerDetails, + () => retainedInstance.suspendedCount, + () => retainedInstance.getDeferral(), + () => retainedInstance.onCanceled(() => {}), + () => retainedInstance.offCanceled(token.toValue()), ]) { expectHresult(action, E_FAIL); takeError(instanceOwner, /unused standalone/i); @@ -424,6 +520,40 @@ const cases = { g.releaseProjected(writer); }, + value_shapes({ g, own }) { + const values = { + UInt8: 255, Int16: -32768, UInt16: 65535, Int32: -(2 ** 31), UInt32: 2 ** 32 - 1, + Int64: -(1n << 63n), UInt64: (1n << 64n) - 1n, + Single: 1.25, Double: -2.5, Char16: 0x96ea, Boolean: true, + String: 'value\0\u96ea', Guid: instanceId, + DateTime: { universalTime: 132537600000000000n }, TimeSpan: { duration: -1250n }, + Point: { x: 1.25, y: -3.5 }, Size: { width: 3.5, height: 2.25 }, + Rect: { x: 1.25, y: 2.5, width: 3.75, height: 4 }, + }; + const called = new Set(); + const getter = (name, value) => () => { called.add(name); return value; }; + const handlers = { + getType: getter('type', g.PropertyType.Int32), + getIsNumericScalar: getter('numeric', true), + getInspectableArray: getter('inspectable', [null]), + }; + for (const [name, value] of Object.entries(values)) { + handlers[`get${name}`] = getter(name, value); + handlers[`get${name}Array`] = getter(`${name}[]`, [value, value]); + } + const impl = own(g.IPropertyValue.implement(handlers)); + assert.equal(impl.value.type, g.PropertyType.Int32); + assert.equal(impl.value.isNumericScalar, true); + assert.deepEqual(impl.value.getInspectableArray(), [null]); + for (const [name, expected] of Object.entries(values)) { + const actual = impl.value[`get${name}`](); + const array = impl.value[`get${name}Array`](); + assert.deepEqual(actual, expected); + assert.deepEqual(array, name === 'UInt8' ? Buffer.from([expected, expected]) : [expected, expected]); + } + assert.equal(called.size, Object.keys(values).length * 2 + 3); + }, + fill_array({ g, own }) { const capacities = []; const owner = own(g.IDataReader.implement(readerHandlers(capacity => { @@ -634,7 +764,9 @@ function main() { const results = []; const printedErrors = new Set(); console.log(`Node ${process.version}, ${process.arch}, ${process.execPath}`); - for (const id of caseIds) { + const selected = args.cases ? args.cases.split(',') : caseIds; + if (selected.some(id => !Object.hasOwn(cases, id))) throw new Error('Unknown implementation scenario in --cases'); + for (const id of selected) { const child = spawnSync(process.execPath, [ filename, '--case', id, '--generated', args.generated, '--runtime', args.runtime, ], { encoding: 'utf8', timeout: 90_000, maxBuffer: 8 * 1024 * 1024, windowsHide: true }); diff --git a/tests/e2e/runners/implementation_js.test.mjs b/tests/e2e/runners/implementation_js.test.mjs index d736e8ea..8b23f1ca 100644 --- a/tests/e2e/runners/implementation_js.test.mjs +++ b/tests/e2e/runners/implementation_js.test.mjs @@ -28,8 +28,8 @@ test('crash, timeout, missing result, and malformed result are failures', () => }); test('the whole requested native scenario matrix stays enabled', () => { - assert.equal(caseIds.length, 16); - assert.equal(caseIds[0], 'background_task'); + assert.equal(caseIds.length, 19); + assert.equal(caseIds[0], 'management_handle'); for (const name of ['memory_buffer_event', 'array_contracts', 'fill_array', 'named_outputs']) { assert.ok(caseIds.includes(name)); } diff --git a/tests/e2e/runners/implementation_py.py b/tests/e2e/runners/implementation_py.py index 4344d187..06984e66 100644 --- a/tests/e2e/runners/implementation_py.py +++ b/tests/e2e/runners/implementation_py.py @@ -11,6 +11,7 @@ import argparse from contextlib import ExitStack, contextmanager +from datetime import datetime, timedelta, timezone import gc import importlib import importlib.util @@ -159,10 +160,151 @@ def close(self): pass +def management_handle(g, dw, own): + class Text: + calls = 0 + + def to_string(self): + self.calls += 1 + return "typed primary" + + handler = Text() + with g.IStringable.implement(handler, interfaces=[(g.IClosable, CloseHandlers())]) as impl: + assert impl.value is impl.value + assert isinstance(impl.value, g.IStringable) + assert impl.value.to_string() == "typed primary" + extra = g.IStringable.from_implementation(impl) + assert extra is not impl.value + primary = impl.value + closer = g.IClosable.from_implementation(impl) + closer.close() + impl.release() + expect_error(lambda: impl.value, "released") + expect_error(primary.to_string, "object|released") + assert extra.to_string() == "typed primary" + expect_hresult(extra.to_string, RO_E_CLOSED) + assert handler.calls == 2 + dw.release_projected(extra) + dw.release_projected(closer) + lazy = own(g.IStringable.implement(Text())) + lazy.release() + expect_error(lambda: lazy.value, "released") + assert lazy.is_closed + for entries in ([(g.IStringable, object())], [(None, handler)], [(g.IClosable,)], [(g.IStringable, handler)]): + expect_error(lambda: g.IStringable.implement(handler, interfaces=entries), "handler|entry|entries|duplicate") + + class Broken(g.IStringable): + failed_owner = None + + @classmethod + def from_implementation(cls, owner): + cls.failed_owner = owner + raise ValueError("primary view failure") + + broken = own(Broken.implement(Text())) + expect_error(lambda: broken.value, "primary view failure") + assert Broken.failed_owner.is_closed + expect_error(lambda: broken.value, "closed|released") + class BrokenInitializer(g.IStringable): + def _set_native(self, native, *, cache=True): + raise ValueError("native view initializer failed") + failed_init = own(BrokenInitializer.implement(Text())) + expect_error(lambda: failed_init.value, "native view initializer failed") + assert failed_init.is_closed + expect_error(lambda: failed_init.value, "closed|released") + class WrongResult: + def to_string(self): return 17 + wrong = own(g.IStringable.implement(WrongResult())) + expect_hresult(wrong.value.to_string, PYTHON_CALLBACK_ERROR) + take_error(wrong, "invalid implementation result") + + class ReleasedDuringProjection(g.IStringable): + @classmethod + def from_implementation(cls, owner): + value = super().from_implementation(owner) + reentrant.release() + return value + + reentrant = own(ReleasedDuringProjection.implement(Text())) + expect_error(lambda: reentrant.value, "released during") + assert reentrant.is_closed + class DisposeInCallback: + def to_string(self): + disposing.dispose() + return "entered callback completed" + disposing = own(g.IStringable.implement(DisposeInCallback())) + assert disposing.value.to_string() == "entered callback completed" + assert disposing.is_closed + expect_error(lambda: disposing.value, "closed|released") + gc_impl = g.IStringable.implement(Text()) + primary = gc_impl.value + raw = gc_impl.to_value() + reference = weakref.ref(gc_impl) + del primary, gc_impl + gc.collect() + assert reference() is None + retained = g.IStringable.from_value(raw) + raw.release() + assert retained.to_string() == "typed primary" + dw.release_projected(retained) + +def property_views(g, dw, own): + class Properties: + length = 0 + def get_capacity(self): return 12 + def get_length(self): return self.length + def set_length(self, value): + if value > 12: raise ValueError("capacity exceeded") + self.length = value + def get_absolute_canonical_uri(self): return "https://example.test/\u96ea" + def get_display_iri(self): return "https://example.test/\u96ea" + def get_name(self): return "query" + def get_value(self): return "value\0\u96ea" + + handlers = Properties() + with g.IBuffer.implement(handlers, interfaces=[ + (g.IUriRuntimeClassWithAbsoluteCanonicalUri, handlers), + (g.IWwwFormUrlDecoderEntry, handlers), + ]) as impl: + uri = g.IUriRuntimeClassWithAbsoluteCanonicalUri.from_implementation(impl) + entry = g.IWwwFormUrlDecoderEntry.from_implementation(impl) + try: + assert impl.value.capacity == 12 and impl.value.length == 0 + impl.value.length = 7 + assert impl.value.length == handlers.length == 7 + assert uri.absolute_canonical_uri == "https://example.test/\u96ea" + assert uri.display_iri == "https://example.test/\u96ea" + assert entry.name == "query" and entry.value == "value\0\u96ea" + # Legacy cached constructors must remain independent of the new + # handle-managed primary and independent-view APIs. + raw = impl.to_value() + try: + cached = g.IBuffer.from_value(raw) + assert cached is g.IBuffer.from_value(raw) + assert cached is not impl.value + assert cached.length == 7 + uri_alias = cached.as_interface(g.IUriRuntimeClassWithAbsoluteCanonicalUri) + entry_alias = uri_alias.as_interface(g.IWwwFormUrlDecoderEntry) + assert uri_alias.display_iri == uri.display_iri + assert entry_alias.value == entry.value + for alias in (cached, uri_alias, entry_alias): + dw.release_projected(alias) + finally: + raw.release() + expect_hresult(lambda: setattr(impl.value, "length", 13), PYTHON_CALLBACK_ERROR) + take_error(impl, "capacity exceeded") + assert impl.value.length == 7 + impl.value.length = 0 + assert impl.value.length == 0 + finally: + dw.release_projected(uri) + dw.release_projected(entry) + + def background_task(g, dw, own): state = TaskInstanceHandlers() instance_owner = own(g.IBackgroundTaskInstance.implement(state)) - instance = g.IBackgroundTaskInstance.from_implementation(instance_owner) + instance = instance_owner.value class Task: runs = 0 @@ -175,13 +317,15 @@ def run(self, task_instance): handlers = Task() owner = own(g.IBackgroundTask.implement(handlers)) - task = g.IBackgroundTask.from_implementation(owner) + task = owner.value task.run(instance) assert (state.progress, state.gets, state.sets, state.get_ids) == (22, 1, 1, 1) assert handlers.runs == 1 + retained_instance = g.IBackgroundTaskInstance.from_implementation(instance_owner) + retained_task = g.IBackgroundTask.from_implementation(owner) instance_owner.release() owner.release() - task.run(instance) + retained_task.run(retained_instance) assert (state.progress, state.gets, state.sets, state.get_ids) == (27, 2, 2, 2) assert handlers.runs == 2 token = dw.DynWinRTStruct.create(dw.DynWinRTType.struct_type( @@ -189,12 +333,12 @@ def run(self, task_instance): )) token.set_i64(0, 1) for action in ( - lambda: instance.task, - lambda: instance.trigger_details, - lambda: instance.suspended_count, - lambda: instance.get_deferral(), - lambda: instance.on_canceled(lambda *_: None), - lambda: instance.off_canceled(token.to_value()), + lambda: retained_instance.task, + lambda: retained_instance.trigger_details, + lambda: retained_instance.suspended_count, + lambda: retained_instance.get_deferral(), + lambda: retained_instance.on_canceled(lambda *_: None), + lambda: retained_instance.off_canceled(token.to_value()), ): error = expect_hresult(action, PYTHON_CALLBACK_ERROR) assert "NotImplementedError" in str(error) and "Unused standalone" in str(error) @@ -260,7 +404,8 @@ def close(self): def gc_referent_ids(owner): # IDs only: keeping the objects returned by get_referents() would itself # retain the callback/handler graph and invalidate a collection assertion. - return frozenset(id(value) for value in gc.get_referents(owner)) + native_owner = getattr(owner, "_owner", owner) + return frozenset(id(value) for value in gc.get_referents(native_owner)) def generated_owner_cycle(g): @@ -743,6 +888,51 @@ def get_inspectable_array(self): dw.release_projected(view) dw.release_projected(writer) +def value_shapes(g, dw, own): + """Every IPropertyValue scalar/array getter crosses a generated native thunk.""" + values = { + "uint8": 255, "int16": -32768, "uint16": 65535, + "int32": -(1 << 31), "uint32": (1 << 32) - 1, + "int64": -(1 << 63), "uint64": (1 << 64) - 1, + "single": 1.25, "double": -2.5, "char16": "\u96ea", + "boolean": True, "string": "value\0\u96ea", "guid": INSTANCE_ID, + "date_time": datetime(2026, 9, 9, tzinfo=timezone.utc), + "time_span": timedelta(microseconds=-125), + "point": g.Point(x=1.25, y=-3.5), + "size": g.Size(width=3.5, height=2.25), + "rect": g.Rect(x=1.25, y=2.5, width=3.75, height=4.0), + } + called = set() + def getter(name, value): + def invoke(self): + called.add(name) + return value + return invoke + methods = { + "get_type": getter("type", g.PropertyType.Int32), + "get_is_numeric_scalar": getter("numeric", True), + "get_inspectable_array": getter("inspectable", [None]), + } + for name, value in values.items(): + methods["get_" + name] = getter(name, value) + methods["get_" + name + "_array"] = getter(name + "[]", [value, value]) + handlers = type("ValueHandlers", (), methods)() + with g.IPropertyValue.implement(handlers) as impl: + assert impl.value.type == g.PropertyType.Int32 + assert impl.value.is_numeric_scalar + assert impl.value.get_inspectable_array() == [None] + for name, expected in values.items(): + actual = getattr(impl.value, "get_" + name)() + array = getattr(impl.value, "get_" + name + "_array")() + if name in ("point", "size", "rect"): + fields = {"point": ("x", "y"), "size": ("width", "height"), "rect": ("x", "y", "width", "height")}[name] + assert [getattr(actual, field) for field in fields] == [getattr(expected, field) for field in fields] + assert [[getattr(item, field) for field in fields] for item in array] == [[getattr(expected, field) for field in fields]] * 2 + else: + assert actual == expected + assert array == (bytes([expected, expected]) if name == "uint8" else [expected, expected]), (name, array, expected) + assert len(called) == 2 * len(values) + 3 + def fill_array(g, dw, own): capacities = [] @@ -896,10 +1086,10 @@ def parse_double(self, text): CASES = { case.__name__: case for case in ( - background_task, multi_interface_lifetime, dispose_disconnects, + management_handle, property_views, background_task, multi_interface_lifetime, dispose_disconnects, reentrant_dispose, callback_error, async_handler_rejected, async_result_rejected, required_interfaces, memory_buffer_event, - array_contracts, fill_array, fill_array_wrong_length, named_outputs, + array_contracts, value_shapes, fill_array, fill_array_wrong_length, named_outputs, nullable_reference_results, public_view_success_gc, public_view_failed_cast_gc, ) @@ -979,6 +1169,7 @@ def main(): parser.add_argument("--generated", type=Path, required=True) parser.add_argument("--output", type=Path) parser.add_argument("--case", choices=CASES) + parser.add_argument("--cases", help="Comma-separated native scenarios for an existing generated package") args = parser.parse_args() generated = args.generated.resolve() if args.case: @@ -992,7 +1183,10 @@ def main(): print(f"Python {platform.python_version()}, {architecture}, {sys.executable}") results = [] printed_errors = set() - for case_id in CASES: + selected = args.cases.split(",") if args.cases else list(CASES) + if any(case_id not in CASES for case_id in selected): + raise ValueError("Unknown implementation scenario in --cases") + for case_id in selected: command = [ sys.executable, str(Path(__file__).resolve()), "--case", case_id, "--generated", str(generated), diff --git a/tests/e2e/runners/test_implementation_runners.py b/tests/e2e/runners/test_implementation_runners.py index 94ce7066..76c28974 100644 --- a/tests/e2e/runners/test_implementation_runners.py +++ b/tests/e2e/runners/test_implementation_runners.py @@ -35,8 +35,8 @@ def test_missing_or_malformed_marker_is_not_a_skip_or_success(self): self.assertFalse(decode_child_result("case", stdout, "", exit_code)["pass"]) def test_complete_matrix_and_nine_method_background_fixture(self): - self.assertEqual(len(CASES), 16) - self.assertEqual(next(iter(CASES)), "background_task") + self.assertEqual(len(CASES), 19) + self.assertEqual(next(iter(CASES)), "management_handle") for case in ("memory_buffer_event", "array_contracts", "fill_array", "named_outputs"): self.assertIn(case, CASES) self.assertIn("nullable_reference_results", CASES) diff --git a/tests/e2e/typecheck/python_implementation_api.py b/tests/e2e/typecheck/python_implementation_api.py index 4ac8c889..8d804259 100644 --- a/tests/e2e/typecheck/python_implementation_api.py +++ b/tests/e2e/typecheck/python_implementation_api.py @@ -7,7 +7,7 @@ from typing import Never, TypedDict from uuid import UUID -from dynwinrt import DynWinRTImplementation, DynWinRTValue, release_projected +from dynwinrt import DynWinRTImplementationHandle, DynWinRTValue, release_projected from python_bindings.windows.application_model.background import ( IBackgroundTask, IBackgroundTaskInstance, ) @@ -59,11 +59,17 @@ def close(self) -> None: def check_owner() -> None: handlers = TaskHandlers() - instance: DynWinRTImplementation = IBackgroundTaskInstance.implement(InstanceHandlers()) - owner: DynWinRTImplementation = IBackgroundTask.implement( + instance: DynWinRTImplementationHandle[IBackgroundTaskInstance] = IBackgroundTaskInstance.implement(InstanceHandlers()) + owner: DynWinRTImplementationHandle[IBackgroundTask] = IBackgroundTask.implement( handlers, IStringable.implementation(handlers), IClosable.implementation(handlers) ) task: IBackgroundTask = IBackgroundTask.from_implementation(owner) + with IBackgroundTask.implement(handlers, interfaces=[(IStringable, handlers), (IClosable, handlers)]) as impl: + primary: IBackgroundTask = impl.value + primary.run(instance.value) + impl.run(instance.value) # type: ignore[attr-defined] + impl.value = task # type: ignore[misc] + IBackgroundTask.implement(handlers, interfaces=[(IStringable, WrongText())]) # type: ignore[misc] task.run(IBackgroundTaskInstance.from_implementation(instance)) text: IStringable = IStringable.from_implementation(owner) close: IClosable = IClosable.from_implementation(owner) diff --git a/tests/e2e/typecheck/ts_implementation_api.ts b/tests/e2e/typecheck/ts_implementation_api.ts index e5b292ee..58837154 100644 --- a/tests/e2e/typecheck/ts_implementation_api.ts +++ b/tests/e2e/typecheck/ts_implementation_api.ts @@ -10,7 +10,7 @@ import { releaseProjected, } from '../e2e_generated/implementations/js/index.js'; import { - DynWinRtArray, DynWinRtImplementation, DynWinRtType, DynWinRtValue, + DynWinRtArray, DynWinRtImplementationHandle, DynWinRtType, DynWinRtValue, } from '../../../bindings/js/dist/winrt.js'; function unused(..._args: unknown[]): never { @@ -40,7 +40,7 @@ const instance = IBackgroundTaskInstance.implement({ getSuspendedCount: unused, getDeferral: unused, }); -const owner: DynWinRtImplementation = IBackgroundTask.implement({ +const owner: DynWinRtImplementationHandle = IBackgroundTask.implement({ run(value) { const native: IBackgroundTaskInstance | null = value; if (native !== null) { @@ -51,6 +51,18 @@ const owner: DynWinRtImplementation = IBackgroundTask.implement({ }, IStringable.implementation({ toString: () => 'typed owner' }), IClosable.implementation({ close() {} })); const taskView: IBackgroundTask = IBackgroundTask.fromImplementation(owner); +owner.value.run(instance.value); +const common = IBackgroundTask.implement({ run: () => {} }, { + interfaces: [[IStringable, { toString: () => 'text' }], [IClosable, { close() {} }]], +}); +const primary: IBackgroundTask = common.value; +void primary; +// @ts-expect-error The management handle is not the interface. +common.run(instance.value); +// @ts-expect-error Each configured interface checks its own handler type. +IBackgroundTask.implement({ run() {} }, { interfaces: [[IStringable, { toString: () => 17 }]] }); +// @ts-expect-error The stable primary view is read-only. +common.value = taskView; taskView.run(IBackgroundTaskInstance.fromImplementation(instance)); const stringView: IStringable = IStringable.fromImplementation(owner); const closeView: IClosable = IClosable.fromImplementation(owner); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs index df6177e2..4a827101 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs @@ -824,15 +824,15 @@ fn project_validated( bindings.push(" if (typeof DynWinRtValue.prototype.invokeDelegate !== 'function') throw new TypeError('this interface requires WinRT delegate invocation support in the runtime');".into()); } let mut factory_body = format!( - " static implementation(handlers) {{\n{}\n const plan = __getImplementationPlan();\n return Object.freeze({{ plan, dispatch(vtableIndex, args) {{\n if (!Array.isArray(args)) throw new TypeError('implementation arguments must be an array');\n switch (vtableIndex) {{\n{dispatch} default: throw new RangeError('unknown implementation vtable slot');\n }}\n }} }});\n }}\n\n static implement(handlers, ...additional) {{\n const descriptors = [this.implementation(handlers), ...additional];\n for (const descriptor of descriptors) {{\n if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor');\n }}\n const plans = descriptors.map(descriptor => descriptor.plan);\n const dispatchers = descriptors.map(descriptor => descriptor.dispatch);\n return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => {{\n if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index');\n return dispatchers[interfaceIndex](vtableIndex, args);\n }});\n }}\n", + " static implementation(handlers) {{\n{}\n const plan = __getImplementationPlan();\n return Object.freeze({{ plan, dispatch(vtableIndex, args) {{\n if (!Array.isArray(args)) throw new TypeError('implementation arguments must be an array');\n switch (vtableIndex) {{\n{dispatch} default: throw new RangeError('unknown implementation vtable slot');\n }}\n }} }});\n }}\n\n static implement(handlers, ...additional) {{\n return DynWinRtImplementationHandle.create(this, handlers, additional, view => view._obj.release());\n }}\n", bindings.join("\n") ); factory_body.push_str( - "\n static fromImplementation(owner) {\n if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller');\n const value = owner.toValue();\n try {\n return this.from(value);\n } finally {\n value.release();\n }\n }\n", + "\n static fromImplementation(owner) {\n if (!(owner instanceof DynWinRtImplementation) && !(owner instanceof DynWinRtImplementationHandle)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller or handle');\n const value = owner.toValue();\n try {\n return this.from(value);\n } finally {\n value.release();\n }\n }\n", ); let factory_declarations = format!( - " /** Validate synchronous handlers and create an independent interface descriptor.{requirements} */\n static implementation(handlers: {}Handlers): DynWinRtImplementationDescriptor;\n /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper.{requirements} */\n static implement(handlers: {}Handlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation;\n /** Query a controller for this interface and return an owned, typed view. */\n static fromImplementation(owner: DynWinRtImplementation): {};\n", - iface.name, iface.name, iface.name + " /** Validate synchronous handlers and create an independent interface descriptor.{requirements} */\n static implementation(handlers: {name}Handlers): DynWinRtImplementationDescriptor;\n /** Create an instance with a stable typed value and explicit lifetime management.{requirements} */\n static implement(handlers: {name}Handlers, options: DynWinRtImplementationOptions): DynWinRtImplementationHandle<{name}>;\n static implement(handlers: {name}Handlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementationHandle<{name}>;\n /** Query an independent view, without consuming the handle's primary value. */\n static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): {name};\n", + name = iface.name ); let exports = std::iter::once(format!("{}Handlers", iface.name)) .chain( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs index a2244373..50d94e3b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/project/mod.rs @@ -1464,9 +1464,14 @@ pub fn project_interface( imports[0].symbols.extend([ "DynWinRtInterfacePlan".into(), "DynWinRtImplementation".into(), + "DynWinRtImplementationHandle".into(), ]); imports.push(ProjectedImport { - symbols: vec!["DynWinRtImplementationDescriptor".into()], + symbols: vec![ + "DynWinRtImplementationDescriptor".into(), + "DynWinRtImplementationOptions".into(), + "DynWinRtImplementationType".into(), + ], from: context.runtime_import_name().into(), runtime_only: false, dts_only: true, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs index c8f98364..2a888f47 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -126,7 +126,10 @@ def _dynwinrt_can_cast(value, iid): \n"; pub fn generate_runtime_support_module() -> String { - format!("{HEADER}{FUTURE_ANNOTATIONS}{RUNTIME_SUPPORT_BODY}") + format!( + "{HEADER}{FUTURE_ANNOTATIONS}{RUNTIME_SUPPORT_BODY}{}", + super::implementation::HELPERS + ) } const ASYNC_IMPORT_LINE: &str = "\ diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs index f3271b2f..cf54bc3e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs @@ -22,10 +22,17 @@ from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, +) +"; +pub(super) const HELPER_IMPORTS: &str = "\ +from ._runtime import ( + _implementation_check, _implementation_field, _implementation_array, + _implementation_reference, _implementation_sync, _implementation_handler, ) "; -const HELPERS: &str = r#" +pub(super) const HELPERS: &str = r#" import inspect as _implementation_inspect @@ -673,7 +680,7 @@ fn project_validated( structs, prefix: format!("{}Implementation", iface.name), }; - let mut support = String::from(HELPERS); + let mut support = String::from(HELPER_IMPORTS); let mut declarations = String::new(); let mut result_names = HashSet::new(); for (result_name, method) in plan @@ -925,13 +932,13 @@ fn project_validated( bindings.push(" if not callable(getattr(DynWinRTValue, 'invoke_delegate', None)):\n raise TypeError('this interface requires WinRT delegate invocation support in the runtime')".into()); } let mut factory_body = format!( - " @staticmethod\n def implementation(handlers: {}Handlers) -> DynWinRTImplementationDescriptor:\n{}\n plan = _get_implementation_plan()\n def dispatch(vtable_index, args):\n if not isinstance(args, list):\n raise TypeError('implementation arguments must be a list')\n{dispatch} raise ValueError('unknown implementation vtable slot')\n return DynWinRTImplementationDescriptor(plan, dispatch)\n\n @classmethod\n def implement(cls, handlers: {}Handlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation:\n descriptors = (cls.implementation(handlers), *additional)\n if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors):\n raise TypeError('invalid implementation descriptor')\n plans = [descriptor.plan for descriptor in descriptors]\n dispatchers = tuple(descriptor.dispatch for descriptor in descriptors)\n def callback(interface_index, vtable_index, args):\n if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers):\n raise ValueError('unknown implementation interface index')\n return dispatchers[interface_index](vtable_index, args)\n return DynWinRTImplementation.create(plans, callback)\n\n", + " @staticmethod\n def implementation(handlers: {}Handlers) -> DynWinRTImplementationDescriptor:\n{}\n plan = _get_implementation_plan()\n def dispatch(vtable_index, args):\n if not isinstance(args, list):\n raise TypeError('implementation arguments must be a list')\n{dispatch} raise ValueError('unknown implementation vtable slot')\n return DynWinRTImplementationDescriptor(plan, dispatch)\n\n @classmethod\n def implement(cls, handlers: {}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces=()) -> DynWinRTImplementationHandle:\n return DynWinRTImplementationHandle._create(cls, handlers, additional, interfaces)\n\n", iface.name, bindings.join("\n"), iface.name ); factory_body.push_str(&format!( - " @classmethod\n def from_implementation(cls, owner: DynWinRTImplementation) -> '{}':\n \"\"\"Query an independently owned view, tracked by the current lifetime scope.\"\"\"\n if not isinstance(owner, DynWinRTImplementation):\n raise TypeError('from_implementation requires a DynWinRTImplementation controller')\n value = owner.to_value()\n try:\n native = value.cast(IID_{})\n try:\n view = object.__new__(cls)\n cls._set_native(view, native, cache=False)\n return view\n except BaseException:\n native.release()\n raise\n finally:\n value.release()\n\n", + " @classmethod\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle) -> '{}':\n \"\"\"Query an independently owned view, tracked by the current lifetime scope.\"\"\"\n if not isinstance(owner, (DynWinRTImplementation, DynWinRTImplementationHandle)):\n raise TypeError('from_implementation requires a DynWinRTImplementation controller or handle')\n value = owner.to_value()\n try:\n native = value.cast(IID_{})\n try:\n view = object.__new__(cls)\n cls._set_native(view, native, cache=False)\n return view\n except BaseException:\n native.release()\n raise\n finally:\n value.release()\n\n", iface.name, iface.name )); let requirements = if plan.required_interfaces.is_empty() { @@ -952,8 +959,8 @@ fn project_validated( ) }; let factory_declarations = format!( - "{requirements} def implementation(cls, handlers: {}Handlers) -> DynWinRTImplementationDescriptor: ...\n def implement(cls, handlers: {}Handlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ...\n def from_implementation(cls, owner: DynWinRTImplementation) -> {}: ...\n\n", - iface.name, iface.name, iface.name + "{requirements} def implementation(cls, handlers: {name}Handlers) -> DynWinRTImplementationDescriptor: ...\n def implement(cls, handlers: {name}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[{name}]: ...\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> {name}: ...\n\n", + name = iface.name ); let mut exports = vec![format!("{}Handlers", iface.name)]; exports.extend( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs index a472218a..4697b956 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs @@ -781,7 +781,8 @@ pub(crate) fn py_convert_array_return( TypeMeta::I8 => format!("{}.to_i8_list()", arr_expr), TypeMeta::U8 => format!("{}.to_bytes()", arr_expr), TypeMeta::I16 => format!("{}.to_i16_list()", arr_expr), - TypeMeta::U16 | TypeMeta::Char16 => format!("{}.to_u16_list()", arr_expr), + TypeMeta::U16 => format!("{}.to_u16_list()", arr_expr), + TypeMeta::Char16 => format!("[chr(value) for value in {}.to_u16_list()]", arr_expr), TypeMeta::I32 => format!("{}.to_i32_list()", arr_expr), typ @ TypeMeta::Enum { name, .. } if context.is_known_type(typ) => format!( "[_dynwinrt_enum('{}', '{}', value) for value in {}.to_i32_list()]", diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 45f70aeb..0e1490ce 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -222,6 +222,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf if implementation.supported { out.push_str(super::implementation::IMPORTS); out.push_str("from abc import ABCMeta\n"); + out.push_str("from typing import TypeVar\nfrom dynwinrt import _DynWinRTImplementationFactory\n_ImplementationHandlers = TypeVar('_ImplementationHandlers')\n"); } let collection_kind = interface_kind(iface); let is_protocol = collection_kind.is_none(); diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts index 5c4b2bcf..3dc6b82f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.d.ts @@ -1,6 +1,6 @@ // Generated by dynwinrt-codegen — do not edit -import { WinGuid, DynWinRtImplementation } from '@microsoft/dynwinrt'; -import { DynWinRtImplementationDescriptor } from '@microsoft/dynwinrt'; +import { WinGuid, DynWinRtImplementation, DynWinRtImplementationHandle } from '@microsoft/dynwinrt'; +import { DynWinRtImplementationDescriptor, DynWinRtImplementationOptions, DynWinRtImplementationType } from '@microsoft/dynwinrt'; /** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */ @@ -14,10 +14,11 @@ export declare class IStringable { private constructor(); /** Validate synchronous handlers and create an independent interface descriptor. */ static implementation(handlers: IStringableHandlers): DynWinRtImplementationDescriptor; - /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper. */ - static implement(handlers: IStringableHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation; - /** Query a controller for this interface and return an owned, typed view. */ - static fromImplementation(owner: DynWinRtImplementation): IStringable; + /** Create an instance with a stable typed value and explicit lifetime management. */ + static implement(handlers: IStringableHandlers, options: DynWinRtImplementationOptions): DynWinRtImplementationHandle; + static implement(handlers: IStringableHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementationHandle; + /** Query an independent view, without consuming the handle's primary value. */ + static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): IStringable; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IStringable; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js index b0734b3f..0c1c85e4 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IStringable.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation } = require('@microsoft/dynwinrt'); +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation, DynWinRtImplementationHandle } = require('@microsoft/dynwinrt'); const IID_IStringable = WinGuid.parse('96369f54-8eb6-48f0-abce-c1b211e627c3'); @@ -95,20 +95,11 @@ class IStringable { } static implement(handlers, ...additional) { - const descriptors = [this.implementation(handlers), ...additional]; - for (const descriptor of descriptors) { - if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor'); - } - const plans = descriptors.map(descriptor => descriptor.plan); - const dispatchers = descriptors.map(descriptor => descriptor.dispatch); - return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { - if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index'); - return dispatchers[interfaceIndex](vtableIndex, args); - }); + return DynWinRtImplementationHandle.create(this, handlers, additional, view => view._obj.release()); } static fromImplementation(owner) { - if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller'); + if (!(owner instanceof DynWinRtImplementation) && !(owner instanceof DynWinRtImplementationHandle)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller or handle'); const value = owner.toValue(); try { return this.from(value); diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts index 1e775d9b..b1ee67b4 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.d.ts @@ -1,6 +1,6 @@ // Generated by dynwinrt-codegen — do not edit -import { WinGuid, DynWinRtImplementation } from '@microsoft/dynwinrt'; -import { DynWinRtImplementationDescriptor } from '@microsoft/dynwinrt'; +import { WinGuid, DynWinRtImplementation, DynWinRtImplementationHandle } from '@microsoft/dynwinrt'; +import { DynWinRtImplementationDescriptor, DynWinRtImplementationOptions, DynWinRtImplementationType } from '@microsoft/dynwinrt'; /** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */ @@ -15,10 +15,11 @@ export declare class IUriRuntimeClassWithAbsoluteCanonicalUri { private constructor(); /** Validate synchronous handlers and create an independent interface descriptor. */ static implementation(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers): DynWinRtImplementationDescriptor; - /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper. */ - static implement(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation; - /** Query a controller for this interface and return an owned, typed view. */ - static fromImplementation(owner: DynWinRtImplementation): IUriRuntimeClassWithAbsoluteCanonicalUri; + /** Create an instance with a stable typed value and explicit lifetime management. */ + static implement(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, options: DynWinRtImplementationOptions): DynWinRtImplementationHandle; + static implement(handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementationHandle; + /** Query an independent view, without consuming the handle's primary value. */ + static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): IUriRuntimeClassWithAbsoluteCanonicalUri; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IUriRuntimeClassWithAbsoluteCanonicalUri; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js index 82bc2157..4d130bbc 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IUriRuntimeClassWithAbsoluteCanonicalUri.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation } = require('@microsoft/dynwinrt'); +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation, DynWinRtImplementationHandle } = require('@microsoft/dynwinrt'); const IID_IUriRuntimeClassWithAbsoluteCanonicalUri = WinGuid.parse('758d9661-221c-480f-a339-50656673f46f'); @@ -103,20 +103,11 @@ class IUriRuntimeClassWithAbsoluteCanonicalUri { } static implement(handlers, ...additional) { - const descriptors = [this.implementation(handlers), ...additional]; - for (const descriptor of descriptors) { - if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor'); - } - const plans = descriptors.map(descriptor => descriptor.plan); - const dispatchers = descriptors.map(descriptor => descriptor.dispatch); - return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { - if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index'); - return dispatchers[interfaceIndex](vtableIndex, args); - }); + return DynWinRtImplementationHandle.create(this, handlers, additional, view => view._obj.release()); } static fromImplementation(owner) { - if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller'); + if (!(owner instanceof DynWinRtImplementation) && !(owner instanceof DynWinRtImplementationHandle)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller or handle'); const value = owner.toValue(); try { return this.from(value); diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts index b6493ef0..cfba7a3f 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.d.ts @@ -1,6 +1,6 @@ // Generated by dynwinrt-codegen — do not edit -import { WinGuid, DynWinRtImplementation } from '@microsoft/dynwinrt'; -import { DynWinRtImplementationDescriptor } from '@microsoft/dynwinrt'; +import { WinGuid, DynWinRtImplementation, DynWinRtImplementationHandle } from '@microsoft/dynwinrt'; +import { DynWinRtImplementationDescriptor, DynWinRtImplementationOptions, DynWinRtImplementationType } from '@microsoft/dynwinrt'; /** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */ @@ -15,10 +15,11 @@ export declare class IWwwFormUrlDecoderEntry { private constructor(); /** Validate synchronous handlers and create an independent interface descriptor. */ static implementation(handlers: IWwwFormUrlDecoderEntryHandlers): DynWinRtImplementationDescriptor; - /** Create a non-agile owner-thread implementation. The controller is separate from this wrapper. */ - static implement(handlers: IWwwFormUrlDecoderEntryHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementation; - /** Query a controller for this interface and return an owned, typed view. */ - static fromImplementation(owner: DynWinRtImplementation): IWwwFormUrlDecoderEntry; + /** Create an instance with a stable typed value and explicit lifetime management. */ + static implement(handlers: IWwwFormUrlDecoderEntryHandlers, options: DynWinRtImplementationOptions): DynWinRtImplementationHandle; + static implement(handlers: IWwwFormUrlDecoderEntryHandlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementationHandle; + /** Query an independent view, without consuming the handle's primary value. */ + static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): IWwwFormUrlDecoderEntry; /** @internal Cast a raw WinRT object to this interface. */ static from(obj: any): IWwwFormUrlDecoderEntry; diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js index 8a287ae3..abda8c90 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js +++ b/tools/dynwinrt-codegen/tests/snapshots/uri/windows/foundation/IWwwFormUrlDecoderEntry.js @@ -1,5 +1,5 @@ // Generated by dynwinrt-codegen — do not edit -const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation } = require('@microsoft/dynwinrt'); +const { DynWinRtType, DynWinRtMethodSig, DynWinRtValue, DynWinRtArray, DynWinRtDelegate, WinGuid, DynWinRtInterfacePlan, DynWinRtImplementation, DynWinRtImplementationHandle } = require('@microsoft/dynwinrt'); const IID_IWwwFormUrlDecoderEntry = WinGuid.parse('125e7431-f678-4e8e-b670-20a9b06c512d'); @@ -103,20 +103,11 @@ class IWwwFormUrlDecoderEntry { } static implement(handlers, ...additional) { - const descriptors = [this.implementation(handlers), ...additional]; - for (const descriptor of descriptors) { - if (!descriptor || !(descriptor.plan instanceof DynWinRtInterfacePlan) || typeof descriptor.dispatch !== 'function') throw new TypeError('invalid implementation descriptor'); - } - const plans = descriptors.map(descriptor => descriptor.plan); - const dispatchers = descriptors.map(descriptor => descriptor.dispatch); - return DynWinRtImplementation.create(plans, (interfaceIndex, vtableIndex, args) => { - if (!Number.isInteger(interfaceIndex) || interfaceIndex < 0 || interfaceIndex >= dispatchers.length) throw new RangeError('unknown implementation interface index'); - return dispatchers[interfaceIndex](vtableIndex, args); - }); + return DynWinRtImplementationHandle.create(this, handlers, additional, view => view._obj.release()); } static fromImplementation(owner) { - if (!(owner instanceof DynWinRtImplementation)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller'); + if (!(owner instanceof DynWinRtImplementation) && !(owner instanceof DynWinRtImplementationHandle)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller or handle'); const value = owner.toValue(); try { return this.from(value); diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py index 47915c50..3f0a2977 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py @@ -18,6 +18,7 @@ from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, ) IID_IStringable = WinGUID.parse('96369f54-8eb6-48f0-abce-c1b211e627c3') @@ -30,73 +31,10 @@ class IStringableHandlers(Protocol): """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" def to_string(self) -> str: ... - -import inspect as _implementation_inspect - - -def _implementation_check(value, valid, label): - if not valid: - raise TypeError(f'{label}: invalid implementation result') - return value - - -def _implementation_field(value, name, label): - if not isinstance(value, dict) or name not in value: - raise TypeError(f'{label}: expected a result dict containing {name}') - return value[name] - - -def _implementation_array(value, label, bytes_allowed=False, capacity=None): - if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): - raise TypeError(f'{label}: expected an array') - if capacity is not None and len(value) != capacity: - raise ValueError(f'{label}: FillArray result must match capacity {capacity}') - return list(value) - - -def _implementation_reference(value, iid, label): - if value is None: - return DynWinRTValue.null_value() - raw = getattr(value, '_obj', value) - if not isinstance(raw, DynWinRTValue): - raise TypeError(f'{label}: expected a managed WinRT value or None') - return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) - - -def _implementation_sync(value, label): - if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): - if _implementation_inspect.iscoroutine(value): - value.close() - raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') - return value - - -def _implementation_handler(handlers, name, count, label): - try: - member = _implementation_inspect.getattr_static(handlers, name) - except AttributeError: - raise TypeError(f'{label}: missing synchronous handler {name}') from None - if isinstance(member, property): - raise TypeError(f'{label}: property accessors are not callback handlers: {name}') - callback = getattr(handlers, name) - if not callable(callback): - raise TypeError(f'{label}: missing synchronous handler {name}') - if (_implementation_inspect.iscoroutinefunction(callback) - or _implementation_inspect.isasyncgenfunction(callback) - or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) - or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): - raise TypeError(f'{label}.{name}: async handlers are not supported') - try: - signature = _implementation_inspect.signature(callback) - except ValueError: - pass - else: - try: - signature.bind(*([None] * count)) - except TypeError as error: - raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None - return callback - +from ._runtime import ( + _implementation_check, _implementation_field, _implementation_array, + _implementation_reference, _implementation_sync, _implementation_handler, +) _implementation_plan = None @@ -127,23 +65,14 @@ def dispatch(vtable_index, args): return DynWinRTImplementationDescriptor(plan, dispatch) @classmethod - def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: - descriptors = (cls.implementation(handlers), *additional) - if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors): - raise TypeError('invalid implementation descriptor') - plans = [descriptor.plan for descriptor in descriptors] - dispatchers = tuple(descriptor.dispatch for descriptor in descriptors) - def callback(interface_index, vtable_index, args): - if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers): - raise ValueError('unknown implementation interface index') - return dispatchers[interface_index](vtable_index, args) - return DynWinRTImplementation.create(plans, callback) + def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor, interfaces=()) -> DynWinRTImplementationHandle: + return DynWinRTImplementationHandle._create(cls, handlers, additional, interfaces) @classmethod - def from_implementation(cls, owner: DynWinRTImplementation) -> 'IStringable': + def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle) -> 'IStringable': """Query an independently owned view, tracked by the current lifetime scope.""" - if not isinstance(owner, DynWinRTImplementation): - raise TypeError('from_implementation requires a DynWinRTImplementation controller') + if not isinstance(owner, (DynWinRTImplementation, DynWinRTImplementationHandle)): + raise TypeError('from_implementation requires a DynWinRTImplementation controller or handle') value = owner.to_value() try: native = value.cast(IID_IStringable) diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py index a152b92d..139bd5df 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py @@ -18,6 +18,7 @@ from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, ) IID_IUriRuntimeClassWithAbsoluteCanonicalUri = WinGUID.parse('758d9661-221c-480f-a339-50656673f46f') @@ -32,73 +33,10 @@ class IUriRuntimeClassWithAbsoluteCanonicalUriHandlers(Protocol): """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" def get_absolute_canonical_uri(self) -> str: ... def get_display_iri(self) -> str: ... - -import inspect as _implementation_inspect - - -def _implementation_check(value, valid, label): - if not valid: - raise TypeError(f'{label}: invalid implementation result') - return value - - -def _implementation_field(value, name, label): - if not isinstance(value, dict) or name not in value: - raise TypeError(f'{label}: expected a result dict containing {name}') - return value[name] - - -def _implementation_array(value, label, bytes_allowed=False, capacity=None): - if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): - raise TypeError(f'{label}: expected an array') - if capacity is not None and len(value) != capacity: - raise ValueError(f'{label}: FillArray result must match capacity {capacity}') - return list(value) - - -def _implementation_reference(value, iid, label): - if value is None: - return DynWinRTValue.null_value() - raw = getattr(value, '_obj', value) - if not isinstance(raw, DynWinRTValue): - raise TypeError(f'{label}: expected a managed WinRT value or None') - return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) - - -def _implementation_sync(value, label): - if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): - if _implementation_inspect.iscoroutine(value): - value.close() - raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') - return value - - -def _implementation_handler(handlers, name, count, label): - try: - member = _implementation_inspect.getattr_static(handlers, name) - except AttributeError: - raise TypeError(f'{label}: missing synchronous handler {name}') from None - if isinstance(member, property): - raise TypeError(f'{label}: property accessors are not callback handlers: {name}') - callback = getattr(handlers, name) - if not callable(callback): - raise TypeError(f'{label}: missing synchronous handler {name}') - if (_implementation_inspect.iscoroutinefunction(callback) - or _implementation_inspect.isasyncgenfunction(callback) - or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) - or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): - raise TypeError(f'{label}.{name}: async handlers are not supported') - try: - signature = _implementation_inspect.signature(callback) - except ValueError: - pass - else: - try: - signature.bind(*([None] * count)) - except TypeError as error: - raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None - return callback - +from ._runtime import ( + _implementation_check, _implementation_field, _implementation_array, + _implementation_reference, _implementation_sync, _implementation_handler, +) _implementation_plan = None @@ -136,23 +74,14 @@ def dispatch(vtable_index, args): return DynWinRTImplementationDescriptor(plan, dispatch) @classmethod - def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: - descriptors = (cls.implementation(handlers), *additional) - if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors): - raise TypeError('invalid implementation descriptor') - plans = [descriptor.plan for descriptor in descriptors] - dispatchers = tuple(descriptor.dispatch for descriptor in descriptors) - def callback(interface_index, vtable_index, args): - if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers): - raise ValueError('unknown implementation interface index') - return dispatchers[interface_index](vtable_index, args) - return DynWinRTImplementation.create(plans, callback) + def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor, interfaces=()) -> DynWinRTImplementationHandle: + return DynWinRTImplementationHandle._create(cls, handlers, additional, interfaces) @classmethod - def from_implementation(cls, owner: DynWinRTImplementation) -> 'IUriRuntimeClassWithAbsoluteCanonicalUri': + def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle) -> 'IUriRuntimeClassWithAbsoluteCanonicalUri': """Query an independently owned view, tracked by the current lifetime scope.""" - if not isinstance(owner, DynWinRTImplementation): - raise TypeError('from_implementation requires a DynWinRTImplementation controller') + if not isinstance(owner, (DynWinRTImplementation, DynWinRTImplementationHandle)): + raise TypeError('from_implementation requires a DynWinRTImplementation controller or handle') value = owner.to_value() try: native = value.cast(IID_IUriRuntimeClassWithAbsoluteCanonicalUri) diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py index 6d708ee0..9438042b 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py @@ -18,6 +18,7 @@ from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, ) IID_IWwwFormUrlDecoderEntry = WinGUID.parse('125e7431-f678-4e8e-b670-20a9b06c512d') @@ -32,73 +33,10 @@ class IWwwFormUrlDecoderEntryHandlers(Protocol): """Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.""" def get_name(self) -> str: ... def get_value(self) -> str: ... - -import inspect as _implementation_inspect - - -def _implementation_check(value, valid, label): - if not valid: - raise TypeError(f'{label}: invalid implementation result') - return value - - -def _implementation_field(value, name, label): - if not isinstance(value, dict) or name not in value: - raise TypeError(f'{label}: expected a result dict containing {name}') - return value[name] - - -def _implementation_array(value, label, bytes_allowed=False, capacity=None): - if not isinstance(value, (list, tuple)) and not (bytes_allowed and isinstance(value, (bytes, bytearray))): - raise TypeError(f'{label}: expected an array') - if capacity is not None and len(value) != capacity: - raise ValueError(f'{label}: FillArray result must match capacity {capacity}') - return list(value) - - -def _implementation_reference(value, iid, label): - if value is None: - return DynWinRTValue.null_value() - raw = getattr(value, '_obj', value) - if not isinstance(raw, DynWinRTValue): - raise TypeError(f'{label}: expected a managed WinRT value or None') - return DynWinRTValue.null_value() if raw.is_null() else raw.cast(iid) - - -def _implementation_sync(value, label): - if _implementation_inspect.isawaitable(value) or _implementation_inspect.isasyncgen(value): - if _implementation_inspect.iscoroutine(value): - value.close() - raise TypeError(f'{label}: implementation callbacks must return synchronously, not a coroutine or awaitable') - return value - - -def _implementation_handler(handlers, name, count, label): - try: - member = _implementation_inspect.getattr_static(handlers, name) - except AttributeError: - raise TypeError(f'{label}: missing synchronous handler {name}') from None - if isinstance(member, property): - raise TypeError(f'{label}: property accessors are not callback handlers: {name}') - callback = getattr(handlers, name) - if not callable(callback): - raise TypeError(f'{label}: missing synchronous handler {name}') - if (_implementation_inspect.iscoroutinefunction(callback) - or _implementation_inspect.isasyncgenfunction(callback) - or _implementation_inspect.iscoroutinefunction(getattr(callback, '__call__', None)) - or _implementation_inspect.isasyncgenfunction(getattr(callback, '__call__', None))): - raise TypeError(f'{label}.{name}: async handlers are not supported') - try: - signature = _implementation_inspect.signature(callback) - except ValueError: - pass - else: - try: - signature.bind(*([None] * count)) - except TypeError as error: - raise TypeError(f'{label}.{name}: invalid handler signature: {error}') from None - return callback - +from ._runtime import ( + _implementation_check, _implementation_field, _implementation_array, + _implementation_reference, _implementation_sync, _implementation_handler, +) _implementation_plan = None @@ -136,23 +74,14 @@ def dispatch(vtable_index, args): return DynWinRTImplementationDescriptor(plan, dispatch) @classmethod - def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: - descriptors = (cls.implementation(handlers), *additional) - if any(not isinstance(descriptor, DynWinRTImplementationDescriptor) for descriptor in descriptors): - raise TypeError('invalid implementation descriptor') - plans = [descriptor.plan for descriptor in descriptors] - dispatchers = tuple(descriptor.dispatch for descriptor in descriptors) - def callback(interface_index, vtable_index, args): - if not isinstance(interface_index, int) or interface_index < 0 or interface_index >= len(dispatchers): - raise ValueError('unknown implementation interface index') - return dispatchers[interface_index](vtable_index, args) - return DynWinRTImplementation.create(plans, callback) + def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor, interfaces=()) -> DynWinRTImplementationHandle: + return DynWinRTImplementationHandle._create(cls, handlers, additional, interfaces) @classmethod - def from_implementation(cls, owner: DynWinRTImplementation) -> 'IWwwFormUrlDecoderEntry': + def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle) -> 'IWwwFormUrlDecoderEntry': """Query an independently owned view, tracked by the current lifetime scope.""" - if not isinstance(owner, DynWinRTImplementation): - raise TypeError('from_implementation requires a DynWinRTImplementation controller') + if not isinstance(owner, (DynWinRTImplementation, DynWinRTImplementationHandle)): + raise TypeError('from_implementation requires a DynWinRTImplementation controller or handle') value = owner.to_value() try: native = value.cast(IID_IWwwFormUrlDecoderEntry) diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi index 8b7a5c61..9d75b525 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi @@ -11,8 +11,12 @@ from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, ) from abc import ABCMeta +from typing import TypeVar +from dynwinrt import _DynWinRTImplementationFactory +_ImplementationHandlers = TypeVar('_ImplementationHandlers') from typing import Protocol, Self, TypeVar _InterfaceT = TypeVar('_InterfaceT') @@ -27,8 +31,8 @@ class IStringableHandlers(Protocol): class _IStringableImplementationFactory(ABCMeta): def implementation(cls, handlers: IStringableHandlers) -> DynWinRTImplementationDescriptor: ... - def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ... - def from_implementation(cls, owner: DynWinRTImplementation) -> IStringable: ... + def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IStringable]: ... + def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IStringable: ... class _IStringableIdentity(Protocol): diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi index e69f86c8..301d849c 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi @@ -11,8 +11,12 @@ from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, ) from abc import ABCMeta +from typing import TypeVar +from dynwinrt import _DynWinRTImplementationFactory +_ImplementationHandlers = TypeVar('_ImplementationHandlers') from typing import Protocol, Self, TypeVar _InterfaceT = TypeVar('_InterfaceT') @@ -28,8 +32,8 @@ class IUriRuntimeClassWithAbsoluteCanonicalUriHandlers(Protocol): class _IUriRuntimeClassWithAbsoluteCanonicalUriImplementationFactory(ABCMeta): def implementation(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers) -> DynWinRTImplementationDescriptor: ... - def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ... - def from_implementation(cls, owner: DynWinRTImplementation) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... + def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IUriRuntimeClassWithAbsoluteCanonicalUri]: ... + def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... class _IUriRuntimeClassWithAbsoluteCanonicalUriIdentity(Protocol): diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi index 02a9d22f..c5cc9139 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi @@ -11,8 +11,12 @@ from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, ) from abc import ABCMeta +from typing import TypeVar +from dynwinrt import _DynWinRTImplementationFactory +_ImplementationHandlers = TypeVar('_ImplementationHandlers') from typing import Protocol, Self, TypeVar _InterfaceT = TypeVar('_InterfaceT') @@ -28,8 +32,8 @@ class IWwwFormUrlDecoderEntryHandlers(Protocol): class _IWwwFormUrlDecoderEntryImplementationFactory(ABCMeta): def implementation(cls, handlers: IWwwFormUrlDecoderEntryHandlers) -> DynWinRTImplementationDescriptor: ... - def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor) -> DynWinRTImplementation: ... - def from_implementation(cls, owner: DynWinRTImplementation) -> IWwwFormUrlDecoderEntry: ... + def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IWwwFormUrlDecoderEntry]: ... + def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IWwwFormUrlDecoderEntry: ... class _IWwwFormUrlDecoderEntryIdentity(Protocol): diff --git a/tools/dynwinrt-codegen/tests/tsc_check_test.rs b/tools/dynwinrt-codegen/tests/tsc_check_test.rs index 4c78f045..bff74077 100644 --- a/tools/dynwinrt-codegen/tests/tsc_check_test.rs +++ b/tools/dynwinrt-codegen/tests/tsc_check_test.rs @@ -261,6 +261,21 @@ export declare class DynWinRtImplementation { readonly isClosed: boolean; takeError(): string | null; } +export interface DynWinRtImplementationType { implementation(handlers: never): DynWinRtImplementationDescriptor; } +type ImplementationHandlers = T extends { implementation(handlers: infer H): DynWinRtImplementationDescriptor } ? H : never; +export type DynWinRtImplementationOptions = { + readonly interfaces: { readonly [K in keyof T]: readonly [T[K], NoInfer>] }; +}; +export declare class DynWinRtImplementationHandle { + private constructor(); + readonly value: T; + toValue(): DynWinRtValue; + release(): void; + dispose(): void; + disconnect(): void; + readonly isClosed: boolean; + takeError(): string | null; +} export declare class DynWinRtValue { toNumber(): number; toI64(): number; diff --git a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs index 85ea416b..a39a1f20 100644 --- a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs +++ b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs @@ -261,13 +261,14 @@ fn implementation_renderers_preserve_abi_order_and_emit_typed_named_results() { assert!(js.contains("bufferCapacity") || dts.contains("bufferCapacity")); assert!( js.contains("FillArray result must match capacity") - && py.contains("FillArray result must match capacity") + && python::generate_runtime_support_module() + .contains("FillArray result must match capacity") ); assert!(dts.contains("private constructor();")); - assert!(dts.contains("static fromImplementation(owner: DynWinRtImplementation): IContract;")); + assert!(dts.contains("static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): IContract;")); assert!( pyi.contains( - "def from_implementation(cls, owner: DynWinRTImplementation) -> IContract: ..." + "def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IContract: ..." ) ); assert!(js.contains("const value = owner.toValue();")); @@ -366,8 +367,8 @@ fn implementation_invalid_contracts_keep_outbound_generation_and_reject_factorie assert!(js.contains("class IContract") && py.contains("class IContract")); assert!(dts.contains("handlers: never") && !pyi.contains("def implement(")); assert!( - !js.contains("DynWinRtImplementation.create") - && !py.contains("DynWinRTImplementation.create") + !js.contains("DynWinRtImplementationHandle.create") + && !py.contains("DynWinRTImplementationHandle._create") ); } } @@ -390,8 +391,8 @@ fn implementation_stock_winmd_covers_background_strings_closing_properties_event assert_eq!(iface.methods[0].vtable_index, 6); let [js, dts, py, pyi] = generated(iface); assert!( - js.contains("DynWinRtImplementation.create") - && py.contains("DynWinRTImplementation.create"), + js.contains("DynWinRtImplementationHandle.create") + && py.contains("DynWinRTImplementationHandle._create"), "{js}\n{py}" ); assert!(js.contains(&format!("name: \"{method}\", vtableIndex: 6"))); @@ -432,11 +433,11 @@ fn implementation_stock_winmd_covers_background_strings_closing_properties_event })); let [js, _, py, _] = generated(&reader); assert!( - js.contains("addOutFill") && js.contains("DynWinRtImplementation.create"), + js.contains("addOutFill") && js.contains("DynWinRtImplementationHandle.create"), "{js}" ); assert!( - py.contains("add_out_fill") && py.contains("DynWinRTImplementation.create"), + py.contains("add_out_fill") && py.contains("DynWinRTImplementationHandle._create"), "{py}" ); let properties = foundation @@ -446,11 +447,11 @@ fn implementation_stock_winmd_covers_background_strings_closing_properties_event let [js, _, py, _] = generated(properties); assert!( js.contains("DynWinRtArray.fromObjectValues") - && js.contains("DynWinRtImplementation.create") + && js.contains("DynWinRtImplementationHandle.create") ); assert!( py.contains("DynWinRTArray.from_object_values") - && py.contains("DynWinRTImplementation.create") + && py.contains("DynWinRTImplementationHandle._create") ); let transforms = meta::parse_class(WINDOWS_WINMD, "Windows.UI.Xaml.Media", "GeneralTransform").unwrap(); @@ -464,8 +465,8 @@ fn implementation_stock_winmd_covers_background_strings_closing_properties_event })); let [js, dts, py, pyi] = generated(&transform); assert!( - js.contains("DynWinRtImplementation.create") - && py.contains("DynWinRTImplementation.create") + js.contains("DynWinRtImplementationHandle.create") + && py.contains("DynWinRTImplementationHandle._create") ); assert!(dts.contains("result: boolean") && pyi.contains("result: bool")); let streams = meta::parse_interfaces(WINDOWS_WINMD, "Windows.Storage.Streams"); @@ -490,8 +491,8 @@ fn implementation_stock_winmd_covers_background_strings_closing_properties_event ); let [js, dts, py, pyi] = generated(random_access); assert!( - js.contains("DynWinRtImplementation.create") - && py.contains("DynWinRTImplementation.create") + js.contains("DynWinRtImplementationHandle.create") + && py.contains("DynWinRTImplementationHandle._create") ); assert!(dts.contains("Required QI views") && pyi.contains("Required QI views")); for iid in [ @@ -508,7 +509,8 @@ fn implementation_javascript_projection_validates_handlers_results_arrays_and_di let [js, _, _, _] = generated(&fixture()); let test = r#" const assert = require('node:assert/strict'); -const input = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +const payload = JSON.parse(require('node:fs').readFileSync(0, 'utf8')); +const input = payload.code; // Projection-only doubles: native vtables/ownership are covered by the native and E2E suites. class Value { constructor(kind, value) { @@ -559,8 +561,10 @@ for (const name of ['addIn', 'addOut', 'addOutFill']) Signature.prototype[name] class Plan { static create(name, type, methods, required) { return Object.assign(new Plan(), { name, type, methods, required }); } } let published = 0; class Implementation { - static create(plans, callback) { published++; return Object.assign(new Implementation(), { plans, callback, references: 1 }); } + static create(plans, callback) { published++; return (Implementation.last = Object.assign(new Implementation(), { plans, callback, references: 1 })); } toValue() { return (this.lastValue = new Value('object', { owner: this })); } + release() { if (!this.released) { this.references--; this.released = true; } } + disconnect() { this.isClosed = true; } } function releaseProjected(view) { view._obj.release(); } const ArrayValue = { @@ -570,6 +574,9 @@ const ArrayValue = { fromHresultValues(values) { return this.fromObjectValues(values.map(Value.hresult)); }, }; const runtime = { DynWinRtValue: Value, DynWinRtType: Type, DynWinRtMethodSig: Signature, DynWinRtInterfacePlan: Plan, DynWinRtImplementation: Implementation, DynWinRtArray: ArrayValue, WinGuid: { parse: value => value } }; +const handleModule = { exports: {} }; +new Function('require', 'module', payload.handle)(() => runtime, handleModule); +runtime.DynWinRtImplementationHandle = handleModule.exports.DynWinRtImplementationHandle; const moduleObject = { exports: {} }; new Function('require', 'module', 'exports', input)((name) => runtime, moduleObject, moduleObject.exports); const IContract = moduleObject.exports.IContract; @@ -625,9 +632,10 @@ assert.throws(() => IContract.implementation({ ...handlers, getTitle: () => ({ t assert.throws(() => IContract.implementation({ ...handlers, transform: () => ({ label: 'bad', buffer: [], result: true }) }).dispatch(8, [values, Value.u32(3)]), /match capacity/); assert.throws(() => IContract.implementation({ ...handlers, transform: () => ({ label: 'bad', buffer: [2147483648], result: true }) }).dispatch(8, [values, Value.u32(1)]), /invalid implementation result/); assert.throws(() => IContract.implementation({ ...handlers, transform: () => ({ buffer: [1], result: true }) }).dispatch(8, [values, Value.u32(1)]), /missing data field/); -const owner = IContract.implement(handlers); +const handle = IContract.implement(handlers); +const owner = Implementation.last; assert.equal(owner.callback(0, 6, [])[0].value, 'changed'); -assert.throws(() => owner.callback(-1, 6, []), /unknown implementation interface index/); +assert.throws(() => owner.callback(-1, 6, []), /Unknown implementation interface index/); const view = IContract.fromImplementation(owner); assert(view instanceof IContract); assert.equal(owner.lastValue.releases, 1); @@ -658,7 +666,15 @@ assert.equal(owner.references, 1); assert.throws(() => IContract.fromImplementation({}), /requires a DynWinRtImplementation controller/); console.log('JavaScript projection assertions passed'); "#; - let output = run("node", &["-e", test], &serde_json::to_string(&js).unwrap()); + let output = run( + "node", + &["-e", test], + &serde_json::json!({ + "code": js, + "handle": include_str!("../../../bindings/js/runtime/winrt-implementation.cjs"), + }) + .to_string(), + ); assert!(output.contains("assertions passed")); } @@ -744,7 +760,8 @@ fn implementation_python_projection_validates_handlers_results_arrays_and_dispat let [_, _, py, _] = generated(&fixture()); let test = r#" import sys, json, types, typing, datetime, uuid, weakref -source = json.load(sys.stdin) +payload = json.load(sys.stdin) +source = payload['code'] # Projection-only doubles, not native ABI fixtures. class Value: def __init__(self, kind, value): @@ -815,10 +832,13 @@ class Implementation: owner = Implementation() owner.plans, owner.callback = plans, callback owner.references = 1 + Implementation.last = owner return owner def to_value(self): self.last_value = Value('object', types.SimpleNamespace(owner=self)) return self.last_value + def release(self): self.references -= 1 + def disconnect(self): self.is_closed = True def release_projected(view): view._obj.release() class Array: def __init__(self, values): self.values = values @@ -849,6 +869,10 @@ for name, value in dict( binding = types.ModuleType('dynwinrt') for name, value in dict(DynWinRTInterfacePlan=Plan, DynWinRTImplementationMethod=Method, DynWinRTImplementation=Implementation, DynWinRTImplementationDescriptor=Descriptor).items(): setattr(binding, name, value) +binding.DynWinRTValue = Value +binding.release_projected = release_projected +exec(payload['handle'], binding.__dict__) +exec('import inspect as _implementation_inspect' + payload['support'].split('import inspect as _implementation_inspect', 1)[1], runtime.__dict__) package = types.ModuleType('generated'); package.__path__ = [] sys.modules.update({'generated': package, 'generated._runtime': runtime, 'dynwinrt': binding}) namespace = {'__name__': 'generated.contract', '__package__': 'generated'} @@ -928,9 +952,10 @@ raises('match capacity', lambda: Contract.implementation(ShortBuffer()).dispatch class LargeInteger(Handlers): def transform(self, values, capacity): return {'label':'bad','buffer':[2147483648],'result':True} raises('invalid implementation result', lambda: Contract.implementation(LargeInteger()).dispatch(8,[values,Value.from_u32(1)])) -owner = Contract.implement(handlers) +handle = Contract.implement(handlers) +owner = Implementation.last assert owner.callback(0,6,[])[0].value == 'changed' -raises('unknown implementation interface index', lambda: owner.callback(-1,6,[])) +raises('Unknown implementation interface index', lambda: owner.callback(-1,6,[])) view = Contract.from_implementation(owner) assert isinstance(view, Contract) assert owner.last_value.releases == 1 @@ -969,7 +994,12 @@ print('Python projection assertions passed') let output = run( "python", &["-c", test], - &serde_json::to_string(&py).unwrap(), + &serde_json::json!({ + "code": py, + "handle": include_str!("../../../bindings/py/src/implementation.py"), + "support": python::generate_runtime_support_module(), + }) + .to_string(), ); assert!(output.contains("assertions passed")); } @@ -1067,20 +1097,18 @@ fn implementation_cli_emits_background_instance_public_views() { ); assert!(artifacts[0].1.contains("private constructor();")); assert!(artifacts[0].1.contains( - "static fromImplementation(owner: DynWinRtImplementation): IBackgroundTaskInstance;" + "static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): IBackgroundTaskInstance;" + )); + assert!(artifacts[1].0.contains( + "def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle)" )); - assert!( - artifacts[1] - .0 - .contains("def from_implementation(cls, owner: DynWinRTImplementation)") - ); assert!( artifacts[1] .0 .contains("finally:\n value.release()") ); assert!(artifacts[1].1.contains( - "def from_implementation(cls, owner: DynWinRTImplementation) -> IBackgroundTaskInstance: ..." + "def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IBackgroundTaskInstance: ..." )); } From 0c27806d7f27ab9298dea75db34a89648854d049 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 9 Sep 2026 12:58:10 +0800 Subject: [PATCH 4/8] test: release rejected event inputs without relying on GC The low-level callback fixture receives an owned native value. Release it when rejecting a subscription, and cover intentional retention across a thrown callback separately. Keep natural-exit assertions, native retention semantics, and coverage gates unchanged. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/js/README.md | 8 +++++++ .../__test__/winrt-event-lifetime-child.mjs | 23 +++++++++++++++---- .../js/__test__/winrt-implementation.spec.ts | 2 +- 3 files changed, 28 insertions(+), 5 deletions(-) diff --git a/bindings/js/README.md b/bindings/js/README.md index 0f92f2e7..05a3e734 100644 --- a/bindings/js/README.md +++ b/bindings/js/README.md @@ -119,6 +119,14 @@ must have exactly that length. Async functions, promises, and thenable results are unsupported. Dispatch errors fail the native call; `takeError()` returns and clears the latest diagnostic, or `null` when there is none. +In this low-level callback API, incoming reference values own retained native +references. A callback that rejects an input without retaining it should release +that `DynWinRtValue`, including on a throwing path. Waiting for garbage collection +can keep a delegate's event-loop resource alive. Conversely, a value deliberately +retained before throwing stays valid until explicitly released or collected. +This is not a requirement to release hidden arguments of generated typed +handlers: the generated adapters retain their own conversion/lifetime contract. + Low-level owner `release()` and garbage collection drop only its native reference. Separately retained native values keep their callbacks alive. `disconnect()` closes every view while retaining the owner reference; `dispose()` disconnects diff --git a/bindings/js/__test__/winrt-event-lifetime-child.mjs b/bindings/js/__test__/winrt-event-lifetime-child.mjs index fc7b1d0b..f3763b16 100644 --- a/bindings/js/__test__/winrt-event-lifetime-child.mjs +++ b/bindings/js/__test__/winrt-event-lifetime-child.mjs @@ -54,8 +54,14 @@ const owner = DynWinRtImplementation.create([referencePlan, closePlan], (index, } if (slot === 6) return [DynWinRtValue.u32(4096)] if (slot === 7) { - if (mode === 'add-failure') throw new Error('expected subscription rejection') + if (mode === 'add-failure') { + // Low-level callback arguments own retained references. This rejecting + // source keeps none; release its input rather than waiting for V8 GC. + args[0].release() + throw new Error('expected subscription rejection') + } retained = args[0] + if (mode === 'add-failure-retained') throw new Error('expected subscription rejection') const token = DynWinRtStruct.create(tokenType) token.setI64(0, 1n) return [token.toValue()] @@ -92,9 +98,18 @@ function onClosed(callback) { } try { - if (mode === 'add-failure') { - assert.throws(() => onClosed(() => {}), /expected subscription rejection/) - assert.equal(retained, undefined) + if (mode === 'add-failure' || mode === 'add-failure-retained') { + assert.throws(() => onClosed(() => { delivered++ }), /expected subscription rejection/) + if (mode === 'add-failure-retained') { + assert.ok(retained) + retained.invokeDelegate(delegateIid, invokeSignature, [sender, DynWinRtValue.nullValue()]) + assert.equal(delivered, 1) + retained.release() + retained = undefined + } else { + assert.equal(retained, undefined) + assert.equal(delivered, 0) + } } else { assert.ok(mode === 'remove' || mode === 'once') const unsubscribe = onClosed((nativeSender, args) => { diff --git a/bindings/js/__test__/winrt-implementation.spec.ts b/bindings/js/__test__/winrt-implementation.spec.ts index 164a695e..e3d95c99 100644 --- a/bindings/js/__test__/winrt-implementation.spec.ts +++ b/bindings/js/__test__/winrt-implementation.spec.ts @@ -434,7 +434,7 @@ test('delegate owner release is idempotent and preserves independently retained retained.release() }) -for (const mode of ['remove', 'once', 'add-failure']) { +for (const mode of ['remove', 'once', 'add-failure', 'add-failure-retained']) { test.serial(`generated event ownership exits naturally after ${mode}`, (t) => { const child = spawnSync(process.execPath, [ fileURLToPath(new URL('./winrt-event-lifetime-child.mjs', import.meta.url)), mode, From 8320e584fbcdc9c9f6e0d8a949b7a9212ee2b9e8 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 9 Sep 2026 13:36:07 +0800 Subject: [PATCH 5/8] test: deterministically reject background event subscriptions Release the implementation-side visible owned delegate when the controlled task fixture declines registration. Preserve the original failure and assert subscribers are not invoked; do not alter generated temporaries, GC, exit behavior, or timeouts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../windows/winrt-interface-implementations.md | 5 +++++ tests/e2e/runners/implementation_js.mjs | 15 +++++++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/docs/guides/windows/winrt-interface-implementations.md b/docs/guides/windows/winrt-interface-implementations.md index 39c3bd88..3c1fecaf 100644 --- a/docs/guides/windows/winrt-interface-implementations.md +++ b/docs/guides/windows/winrt-interface-implementations.md @@ -162,6 +162,11 @@ native delegate. Retain it to deliver the event by calling handler receives that token and should remove and release its stored delegate. These calls invoke the delegate's native slot 3; they are not direct calls to the original subscriber's language function. +An implementation-side handler that rejects registration without retaining +the received delegate can release that visible owned view with +`releaseProjected(handler)` before throwing, for deterministic cleanup instead +of waiting for JavaScript GC. This does not transfer responsibility for the +generator's hidden subscription temporaries to application code. Generated Node subscriptions release their creator and temporary delegate references after the native add method returns. The native event source owns diff --git a/tests/e2e/runners/implementation_js.mjs b/tests/e2e/runners/implementation_js.mjs index 80ff4d11..456af268 100644 --- a/tests/e2e/runners/implementation_js.mjs +++ b/tests/e2e/runners/implementation_js.mjs @@ -66,7 +66,7 @@ function nativeStringable(runtime, owner) { new runtime.DynWinRtMethodSig().addOut(runtime.DynWinRtType.hstring())); } -function taskInstanceHandlers(state) { +function taskInstanceHandlers(state, g) { // IBackgroundTaskInstance has exactly nine slots, 6 through 14. In // particular, Canceled is not a made-up success with a fabricated token. return { @@ -75,7 +75,12 @@ function taskInstanceHandlers(state) { getProgress() { state.gets++; return state.progress; }, setProgress(value) { state.sets++; state.progress = value; }, getTriggerDetails: notImplemented, - addCanceled: notImplemented, + addCanceled(handler) { + // This controlled source rejects registration and retains no + // delegate. Release the visible owned callback view deterministically. + g.releaseProjected(handler); + notImplemented(); + }, removeCanceled: notImplemented, getSuspendedCount: notImplemented, getDeferral: notImplemented, @@ -197,7 +202,7 @@ const cases = { background_task({ g, runtime, own }) { const state = { progress: 17, gets: 0, sets: 0, getIds: 0 }; - const instanceOwner = own(g.IBackgroundTaskInstance.implement(taskInstanceHandlers(state))); + const instanceOwner = own(g.IBackgroundTaskInstance.implement(taskInstanceHandlers(state, g))); const instance = instanceOwner.value; let runs = 0; const taskOwner = own(g.IBackgroundTask.implement({ @@ -223,17 +228,19 @@ const cases = { 'Windows.Foundation.EventRegistrationToken', [runtime.DynWinRtType.i64()], )); token.setI64(0, 1n); + let canceled = 0; for (const action of [ () => retainedInstance.task, () => retainedInstance.triggerDetails, () => retainedInstance.suspendedCount, () => retainedInstance.getDeferral(), - () => retainedInstance.onCanceled(() => {}), + () => retainedInstance.onCanceled(() => { canceled++; }), () => retainedInstance.offCanceled(token.toValue()), ]) { expectHresult(action, E_FAIL); takeError(instanceOwner, /unused standalone/i); } + assert.equal(canceled, 0, 'A rejected subscription must not invoke its delegate'); }, multi_interface_lifetime({ g, own }) { From cfb879c8807dfa6b75b5b25ba06c8cb77e77241c Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Wed, 9 Sep 2026 22:25:36 +0800 Subject: [PATCH 6/8] fix: tighten Python implementation contracts and detached calls Type heterogeneous generated-package interface pairs without erasing handler relations, declare native delegate calls positional-only, and share focused E2E preparation. Pin detached receivers through reentrant disposal while preserving same-thread GIL release; cover the public WinAppSDK dispatcher projection and existing ownership paths. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 31 ++ bindings/py/README.md | 7 + bindings/py/src/runtime.rs | 82 +++- bindings/py/tests/test_implementation.py | 40 ++ .../winrt-interface-implementations.md | 7 + tests/e2e/e2e_preparation.tests.ps1 | 112 ++++++ tests/e2e/e2e_test.ps1 | 28 +- .../runners/dispatcher_implementation_py.py | 374 ++++++++++++++++++ tests/e2e/runners/implementation_py.py | 31 +- .../typecheck/python_implementation_api.py | 20 +- .../codegen/winrt/python/implementation.rs | 12 +- .../src/codegen/winrt/python/stubs.rs | 33 ++ tools/dynwinrt-codegen/src/main.rs | 158 +++++++- .../tests/e2e_preparation_test.rs | 24 ++ .../tests/winrt_implementation_test.rs | 277 +++++++++++-- 15 files changed, 1187 insertions(+), 49 deletions(-) create mode 100644 tests/e2e/e2e_preparation.tests.ps1 create mode 100644 tests/e2e/runners/dispatcher_implementation_py.py create mode 100644 tools/dynwinrt-codegen/tests/e2e_preparation_test.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 81700d63..95a56e47 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -293,6 +293,37 @@ jobs: -Codegen .\target\release\dynwinrt-codegen.exe - name: Run E2E tests run: .\tests\e2e\e2e_test.ps1 -SkipBuild + # This optional-SDK behavioral smoke is separate from generated coverage + # totals. The receiver/GIL regressions also run in instrumented core and + # binding tests; no WinAppSDK runtime bootstrap or UI loop is needed here. + - name: Test metadata-generated dispatcher implementation + shell: pwsh + run: | + $packages = Join-Path $env:RUNNER_TEMP 'dispatcher-metadata' + nuget install Microsoft.WindowsAppSDK.InteractiveExperiences ` + -Version 1.8.251104001 -OutputDirectory $packages -DirectDownload -NonInteractive + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $metadata = Join-Path $packages 'Microsoft.WindowsAppSDK.InteractiveExperiences.1.8.251104001\metadata\10.0.18362.0' + $hashes = @{ + 'Microsoft.UI.winmd' = 'BA28DFC20E18630F3037AF2B91897082E41F1FA0E1DBB001D900505AB3577FE1' + 'Microsoft.Foundation.winmd' = '56A37D003D6CD568B4BEFC95990AB28F576F128C00033C0372EAE390123F9C1F' + 'Microsoft.Graphics.winmd' = '63165F774C2699E5A44E323F932A10BEE7BD5E11F25D82A730F5FB728107EA83' + } + foreach ($entry in $hashes.GetEnumerator()) { + if ((Get-FileHash -LiteralPath (Join-Path $metadata $entry.Key) -Algorithm SHA256).Hash -ne $entry.Value) { + throw "Unexpected WinAppSDK metadata: $($entry.Key)" + } + } + $windows = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\UnionMetadata" ` + -Filter Windows.winmd -File -Recurse | Sort-Object FullName -Descending | Select-Object -First 1 + if (-not $windows) { throw 'Windows SDK metadata is required for the dispatcher smoke' } + $output = Join-Path $PWD 'artifacts\dispatcher-implementation-smoke' + .\target\release\dynwinrt-codegen.exe generate ` + --winmd (Join-Path $metadata 'Microsoft.UI.winmd') --ref $windows.FullName ` + --namespace Microsoft.UI.Dispatching --class-name DispatcherQueue ` + --lang py --output $output + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + .\bindings\py\.venv\Scripts\python.exe .\tests\e2e\runners\dispatcher_implementation_py.py --generated $output - name: Test JS TSFN lifecycle and queue handling working-directory: bindings/js run: npm run test:tsfn diff --git a/bindings/py/README.md b/bindings/py/README.md index c405e9bd..ecba5093 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -226,6 +226,10 @@ supported. The primary `.value` needs no `release_projected` in the common pattern. It is created lazily once, and `release()`/`dispose()` release that view along with the handle's owner reference. `.value` raises after either operation and never recreates a released view. +Heterogeneous convenience lists have per-pair static checking for interfaces +from the same generated package. For heterogeneous combinations across +generated packages, use positional typed `.implementation(...)` descriptors. +Runtime list acceptance and the generic homogeneous-list overload are unchanged. The low-level runtime surface is: @@ -270,6 +274,9 @@ slot 3 on the delegate's `IUnknown` root and returns all outputs as a list call, and propagates failed HRESULTs. Arguments use the existing outbound `invoke_all()` contract, including preallocated fill-array values; these helpers do not infer signatures or turn arbitrary objects into delegates. +Generated received-delegate callables use positional-only arguments in both +their Protocol declarations and runtime wrappers; ordinary projected methods +continue to accept their existing keyword arguments. ### Implementation lifetime and callback failures diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 04f62aa3..7da7608e 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -934,7 +934,7 @@ impl DynWinRTMethodHandle { fn invoke_detached( &self, py: Python<'_>, - obj: &DynWinRTValue, + obj: DynWinRTValue, args: Vec, ) -> PyResult { struct SameThreadCall { @@ -957,8 +957,11 @@ impl DynWinRTMethodHandle { unsafe impl Send for SameThreadCall {} unsafe impl Send for SameThreadResult {} - let object = match &obj.0 { - dynwinrt::WinRTValue::Object(object) => object.clone(), + // Owned extraction ends the Python receiver borrow before dispatch. + // Move its native pin into the call so reentrant disposal can release + // the original wrapper without shortening the in-flight call lifetime. + let object = match obj.0 { + dynwinrt::WinRTValue::Object(object) => object, _ => { return Err(PyRuntimeError::new_err( "invoke_detached() requires an Object value", @@ -2563,6 +2566,79 @@ mod tests { assert_eq!(array.to_i32_list().unwrap(), vec![0, 0x80004005u32 as i32]); } + #[test] + fn detached_invocation_releases_the_gil_on_the_same_native_thread() { + use dynwinrt::{ + WinRtImplementation, WinRtImplementationPlan, WinRtInterfaceDefinition, + WinRtMethodDefinition, WinRtThreadingPolicy, + }; + use std::sync::Mutex; + + Python::initialize(); + Python::attach(|py| { + let table = dynwinrt::MetadataTable::new(); + let iid = GUID::from_u128(0x96369f54_8eb6_48f0_abce_c1b211e627c3); + let signature = dynwinrt::MethodSignature::new(&table).add_out(table.hstring()); + let interface = table + .register_interface("Windows.Foundation.IStringable", iid) + .add_method("ToString", signature.clone()); + let plan = WinRtImplementationPlan::new( + vec![WinRtInterfaceDefinition { + name: "Windows.Foundation.IStringable".into(), + interface_type: interface.clone(), + required_iids: vec![], + methods: vec![WinRtMethodDefinition { + name: "ToString".into(), + vtable_index: 6, + signature, + }], + }], + WinRtThreadingPolicy::OwnerThread, + ) + .unwrap(); + let observed = Arc::new(Mutex::new(Vec::new())); + let callback_observed = observed.clone(); + let mut owner = WinRtImplementation::new( + plan, + Arc::new(move |_, slot, args| { + assert_eq!(slot, 6); + assert!(args.is_empty()); + // Observe the native boundary before a Python handler's + // Python::attach would reacquire the GIL and mask its state. + let gil = unsafe { pyo3::ffi::PyGILState_Check() }; + callback_observed + .lock() + .unwrap() + .push((gil, std::thread::current().id())); + Ok(vec![dynwinrt::WinRTValue::HString( + "native observer".into(), + )]) + }), + None, + ) + .unwrap(); + let receiver = DynWinRTValue(owner.to_value().unwrap().cast(&iid).unwrap()); + let method = DynWinRTMethodHandle(interface.method(6).unwrap()); + let direct = method.invoke(receiver.clone(), vec![]).unwrap(); + let detached = method.invoke_detached(py, receiver, vec![]).unwrap(); + for result in [direct, detached] { + assert!(matches!( + result.0, + dynwinrt::WinRTValue::HString(value) if value == "native observer" + )); + } + let invalid = method + .invoke_detached(py, DynWinRTValue(dynwinrt::WinRTValue::I32(0)), vec![]) + .err() + .expect("non-object receiver must be rejected"); + assert!(invalid.is_instance_of::(py)); + assert!(invalid.to_string().contains("requires an Object value")); + let thread = std::thread::current().id(); + assert_eq!(*observed.lock().unwrap(), vec![(1, thread), (0, thread)]); + owner.dispose().unwrap(); + }); + } + #[test] fn python_delegate_reports_unraisable_callback_errors() { let _serial = crate::errors::UNRAISABLE_HOOK_TEST_LOCK.lock().unwrap(); diff --git a/bindings/py/tests/test_implementation.py b/bindings/py/tests/test_implementation.py index 3f4ac603..55e32307 100644 --- a/bindings/py/tests/test_implementation.py +++ b/bindings/py/tests/test_implementation.py @@ -949,6 +949,46 @@ def callback(*_args): view.release() +@pytest.mark.parametrize("invocation", ["invoke", "invoke_detached"]) +@pytest.mark.parametrize("void_result", [False, True], ids=["hstring-output", "void-output"]) +def test_reentrant_dispose_can_release_the_calling_receiver(invocation, void_result): + plan, typ = _closable() if void_result else _stringable() + thread_id = threading.get_ident() + calls = [] + + def callback(*_args): + assert threading.get_ident() == thread_id + # A generated management handle releases both its primary view and its + # native owner on dispose. The call must not retain a Python borrow of + # that view; only an independent, call-local native pin may survive. + owner.dispose() + receiver.release() + calls.append("completed") + return [] if void_result else [DynWinRTValue.from_hstring("completed after receiver release")] + + owner = DynWinRTImplementation.create([plan], callback) + receiver = _view(owner, typ) + retained = _view(owner, typ) + invoke = getattr(typ.method(6), invocation) + try: + result = invoke(receiver, []) + if void_result: + assert result.to_int() == 0 + else: + assert result.to_string() == "completed after receiver release" + assert calls == ["completed"] + assert receiver.is_null() and owner.is_closed + assert owner.take_error() is None + with pytest.raises(OSError) as caught: + invoke(retained, []) + assert caught.value.winerror == CLOSED + assert calls == ["completed"] + finally: + owner.dispose() + receiver.release() + retained.release() + + def test_disposal_breaks_handler_cycle_and_allows_finalizer_reentrancy(): plan, typ = _stringable() finalized = [] diff --git a/docs/guides/windows/winrt-interface-implementations.md b/docs/guides/windows/winrt-interface-implementations.md index 3c1fecaf..95620416 100644 --- a/docs/guides/windows/winrt-interface-implementations.md +++ b/docs/guides/windows/winrt-interface-implementations.md @@ -105,6 +105,10 @@ Each entry explicitly supplies a generated interface and its handlers. Complete metadata validation, duplicate IIDs, and required-interface checks happen before native publication. Existing positional `.implementation(...)` descriptors are still supported, and may be preferable for reusable heterogeneous compositions. +Python statically checks heterogeneous convenience lists for interfaces in the +same generated package. For heterogeneous interfaces from different generated +packages, use typed positional `.implementation(...)` descriptors; runtime list +acceptance is unchanged. Homogeneous lists retain their generic typing. `Interface.fromImplementation(impl)` / `Interface.from_implementation(impl)` remains the advanced independent-view path; it accepts either a typed handle @@ -162,6 +166,9 @@ native delegate. Retain it to deliver the event by calling handler receives that token and should remove and release its stored delegate. These calls invoke the delegate's native slot 3; they are not direct calls to the original subscriber's language function. +In Python, these received native-delegate callables take positional-only +arguments, matching their generated Protocols. Ordinary projected methods keep +their existing keyword-argument support. An implementation-side handler that rejects registration without retaining the received delegate can release that visible owned view with `releaseProjected(handler)` before throwing, for deterministic cleanup instead diff --git a/tests/e2e/e2e_preparation.tests.ps1 b/tests/e2e/e2e_preparation.tests.ps1 new file mode 100644 index 00000000..d755e264 --- /dev/null +++ b/tests/e2e/e2e_preparation.tests.ps1 @@ -0,0 +1,112 @@ +#!/usr/bin/env pwsh +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$ErrorActionPreference = "Stop" +$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +$scratch = Join-Path $root "target\e2e-preparation-$PID-$([Guid]::NewGuid().ToString('N'))" +$scripts = Join-Path $scratch "tests\e2e" +$trace = Join-Path $scratch "trace.json" +$venv = Join-Path $scratch "bindings\py\.venv\Scripts\python.exe" +$explicit = Join-Path $scratch "explicit-python.exe" +$standard = Join-Path $scripts "e2e_generated\retained.json" +$shell = (Get-Process -Id $PID).Path + +try { + New-Item -ItemType Directory -Path $scripts, (Split-Path $venv), (Split-Path $standard) -Force | Out-Null + Copy-Item -LiteralPath (Join-Path $PSScriptRoot "e2e_test.ps1") -Destination $scripts + New-Item -ItemType File -Path $venv, $explicit | Out-Null + Set-Content -LiteralPath $standard -Value '{"retained": true}' -NoNewline + + # Execute the real entrypoint, intercepting only expensive external work. + # Both boundaries deliberately fail: tests cannot mistake a stub runner or + # stub build for successful generation/native E2E, and check exit propagation. + @' +param([string[]]$Lang, [string]$Python, [string]$CargoProfile, [string]$CargoTarget, [switch]$KeepGenerated) +@{ + stage = "runner"; languages = @($Lang); python = $Python + profile = $CargoProfile; target = $CargoTarget; keep = $KeepGenerated.IsPresent +} | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $PSScriptRoot "..\..\trace.json") +exit 23 +'@ | Set-Content -LiteralPath (Join-Path $scripts "implementation_test.ps1") + @' +param([string]$CaseFile) +$ErrorActionPreference = "Stop" +function cargo { + @{ stage = "build"; arguments = @($args) } | + ConvertTo-Json | Set-Content -LiteralPath (Join-Path $PSScriptRoot "trace.json") + throw "Expected preparation build boundary" +} +function node { throw "Node must not run before the focused runner" } +$parameters = Get-Content -LiteralPath $CaseFile -Raw | ConvertFrom-Json -AsHashtable +if ($parameters.ContainsKey("HideGlobalTools")) { + $parameters.Remove("HideGlobalTools") + Remove-Item Function:\node + $env:PATH = "" +} +& (Join-Path $PSScriptRoot "tests\e2e\e2e_test.ps1") @parameters +exit $LASTEXITCODE +'@ | Set-Content -LiteralPath (Join-Path $scratch "harness.ps1") + + function Invoke-PreparationCase { + param([hashtable]$Parameters, [int]$ExpectedExit, [string]$Stage, [string]$ExpectedError = "requires -Lang py and/or ts") + if (Test-Path -LiteralPath $trace) { Remove-Item -LiteralPath $trace } + $caseFile = Join-Path $scratch "case.json" + $Parameters | ConvertTo-Json | Set-Content -LiteralPath $caseFile + $output = & $shell -NoProfile -File (Join-Path $scratch "harness.ps1") $caseFile 2>&1 | Out-String + if ($LASTEXITCODE -ne $ExpectedExit) { throw "Unexpected exit $LASTEXITCODE (expected $ExpectedExit): $output" } + if ((Get-Content -LiteralPath $standard -Raw) -ne '{"retained": true}') { + throw "Focused suite changed the retained standard results" + } + if (-not $Stage) { + if (Test-Path -LiteralPath $trace) { throw "Invalid selection entered preparation/dispatch" } + if ($output -notlike "*$ExpectedError*") { throw "Unexpected selection error: $output" } + return + } + if (-not (Test-Path -LiteralPath $trace)) { throw "Did not reach $Stage boundary: $output" } + $result = Get-Content -LiteralPath $trace -Raw | ConvertFrom-Json + if ($result.stage -ne $Stage) { throw "Expected $Stage before $($result.stage): $output" } + return $result + } + + $built = Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py", "ts") + CargoProfile = "coverage"; CargoTarget = "x86_64-pc-windows-msvc" + } 1 "build" + if (($built.arguments -join " ") -ne "build -p dynwinrt-codegen --profile coverage --target x86_64-pc-windows-msvc") { + throw "Focused build lost profile/target arguments: $($built.arguments)" + } + $release = Invoke-PreparationCase @{ Suite = "implementations"; Lang = @("py") } 1 "build" + if (($release.arguments -join " ") -ne "build -p dynwinrt-codegen --release") { + throw "Focused build lost its release default: $($release.arguments)" + } + $selected = Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py", "ts"); SkipBuild = $true + CargoProfile = "dev"; CargoTarget = "aarch64-pc-windows-msvc"; KeepGenerated = $true + } 23 "runner" + if ($selected.python -ne $venv -or ($selected.languages -join ",") -ne "py,ts" -or + $selected.profile -ne "dev" -or $selected.target -ne "aarch64-pc-windows-msvc" -or -not $selected.keep) { + throw "Focused dispatch lost shared venv/language/profile/target/retention selection" + } + $selected = Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py"); SkipBuild = $true; Python = $explicit + } 23 "runner" + if ($selected.python -ne $explicit -or $selected.keep) { throw "Explicit -Python did not override the existing venv" } + $selected = Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("ts"); SkipBuild = $true + } 23 "runner" + if (($selected.languages -join ",") -ne "ts") { throw "Node-only focused selection was changed" } + $selected = Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py"); SkipBuild = $true; HideGlobalTools = $true + } 23 "runner" + if ($selected.python -ne $venv) { throw "Existing venv requires an unrelated global Python" } + Invoke-PreparationCase @{ Suite = "implementations"; Lang = @("com"); SkipBuild = $true } 1 "" + Remove-Item -LiteralPath $venv + Invoke-PreparationCase @{ + Suite = "implementations"; Lang = @("py", "ts"); SkipBuild = $true; HideGlobalTools = $true + } 1 "" "No languages available" + Write-Host "Focused E2E preparation regressions passed." +} finally { + if (Test-Path -LiteralPath $scratch) { Remove-Item -LiteralPath $scratch -Recurse -Force } +} +exit 0 diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index 3f49b116..03e69d6f 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -68,8 +68,11 @@ Write-Host "=== dynwinrt E2E Test ===" -ForegroundColor Cyan # -------------------------------------------------------------------------- # Detect available tools # -------------------------------------------------------------------------- +$venvPython = Join-Path $root "bindings\py\.venv\Scripts\python.exe" $pythonExe = if ($Python) { (Resolve-Path -LiteralPath $Python).Path +} elseif (Test-Path -LiteralPath $venvPython -PathType Leaf) { + (Resolve-Path -LiteralPath $venvPython).Path } else { (Get-Command python -ErrorAction SilentlyContinue).Source } @@ -119,15 +122,6 @@ if ("com" -in $Lang) { } } -# The focused selector shares the existing build/tool selection, but does not -# generate standard WinRT or COM fixtures (or delete their retained results). -if ($Suite -eq "implementations") { - & (Join-Path $PSScriptRoot "implementation_test.ps1") ` - -Lang $Lang -Python $pythonExe -CargoProfile $CargoProfile -CargoTarget $CargoTarget ` - -KeepGenerated:$KeepGenerated - exit $LASTEXITCODE -} - if ($Lang.Count -eq 0) { Write-Error "No languages available"; exit 1 } # -------------------------------------------------------------------------- @@ -146,7 +140,7 @@ if (-not $SkipBuild) { if (-not (Test-Path $venvPython)) { & $pythonExe -m venv .venv if ($LASTEXITCODE -ne 0) { Write-Error "Python virtual environment creation failed"; exit 1 } - & $venvPython -m pip install pytest maturin --quiet + & $venvPython -m pip install pytest maturin mypy --quiet if ($LASTEXITCODE -ne 0) { Write-Error "Python test dependency installation failed"; exit 1 } } $pythonExe = (Resolve-Path -LiteralPath $venvPython).Path @@ -188,11 +182,15 @@ if (-not $SkipBuild) { if ($LASTEXITCODE -ne 0) { Write-Error "runtime entrypoint generation failed"; exit 1 } Pop-Location } -} else { - $venvPython = Join-Path $root "bindings\py\.venv\Scripts\python.exe" - if (-not $Python -and (Test-Path $venvPython)) { - $pythonExe = (Resolve-Path -LiteralPath $venvPython).Path - } +} + +# Focused and full suites share preparation. Branch before reading or deleting +# any standard fixtures, preserving their retained output in focused runs. +if ($Suite -eq "implementations") { + & (Join-Path $PSScriptRoot "implementation_test.ps1") ` + -Lang $Lang -Python $pythonExe -CargoProfile $CargoProfile -CargoTarget $CargoTarget ` + -KeepGenerated:$KeepGenerated + exit $LASTEXITCODE } # -------------------------------------------------------------------------- diff --git a/tests/e2e/runners/dispatcher_implementation_py.py b/tests/e2e/runners/dispatcher_implementation_py.py new file mode 100644 index 00000000..ba9c8a38 --- /dev/null +++ b/tests/e2e/runners/dispatcher_implementation_py.py @@ -0,0 +1,374 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Official-metadata regression for disposing a receiver inside invoke_detached. + +Generate --namespace Microsoft.UI.Dispatching --class-name DispatcherQueue +--lang py from Microsoft.WindowsAppSDK.InteractiveExperiences 1.8.251104001, +metadata/10.0.18362.0/Microsoft.UI.winmd (SHA256 +BA28DFC20E18630F3037AF2B91897082E41F1FA0E1DBB001D900505AB3577FE1), +with Windows SDK Windows.winmd as a reference. Pass the output to --generated. +The generated public IDispatcherQueue3 is used, not a handwritten replacement. +Select DispatcherQueue, not the ExclusiveTo interface directly: its required +interface dependencies expose this factory without widening visibility rules. + +IDispatcherQueue3: 14a7a175-5c27-5a35-b079-21960cf764a8; IInspectable root; +no required interfaces. All eight contiguous HRESULT-returning ABI methods: + 6 EnqueueEventLoopExit() -> void + 7 EnsureSystemDispatcherQueue() -> void + 8 RunEventLoop() -> void + 9 RunEventLoopWithOptions(in DispatcherRunOptions, in DispatcherExitDeferral) + -> void + 10 add_FrameworkShutdownStarting(in TypedEventHandler) + -> out EventRegistrationToken + 11 remove_FrameworkShutdownStarting(in EventRegistrationToken) -> void + 12 add_FrameworkShutdownCompleted(in TypedEventHandler) + -> out EventRegistrationToken + 13 remove_FrameworkShutdownCompleted(in EventRegistrationToken) -> void +Slot 9 is metadata RunEventLoop with Overload("RunEventLoopWithOptions"). +Options use the runtime's enumI32 representation for flags 0, 1, 2 (the raw +WinMD value__ field is UInt32); EventRegistrationToken is a single Int64. +The auxiliary deferral has IID 910b5aac-3310-563e-8418-f3005579729e, no +required interfaces, and exactly slot 6 Complete() -> void/HRESULT. + +All receivers and the deferral are controlled standalone implementations. +Nothing activates a runtime class, bootstraps WinAppSDK, registers with the OS, +or runs a real event loop. No invocation monkeypatch, GC forcing, subprocess, +timeout adjustment, or forced process exit is used. +""" + +from __future__ import annotations + +import argparse +import ast +from contextlib import ExitStack +import hashlib +import importlib +import inspect +import json +from pathlib import Path +import platform +import sys +import threading +import traceback +from uuid import UUID + + +IID = "14a7a175-5c27-5a35-b079-21960cf764a8" +DEFERRAL_IID = "910b5aac-3310-563e-8418-f3005579729e" +RO_E_CLOSED = 0x80000013 +PYTHON_CALLBACK_ERROR = 0xA0EE4005 +ERROR_SENTINEL = "dispatcher fixture intentional callback failure" +METHODS = ( + (6, "EnqueueEventLoopExit"), + (7, "EnsureSystemDispatcherQueue"), + (8, "RunEventLoop"), + (9, "RunEventLoopWithOptions"), + (10, "add_FrameworkShutdownStarting"), + (11, "remove_FrameworkShutdownStarting"), + (12, "add_FrameworkShutdownCompleted"), + (13, "remove_FrameworkShutdownCompleted"), +) +CASES = { + "invoke_baseline": "enqueue_event_loop_exit", + "invoke_detached": "run_event_loop", + "invoke_detached_options": "run_event_loop_with_options", + "callback_hresult": "run_event_loop", +} + + +def import_generated(directory): + directory = directory.resolve() + assert (directory / "__init__.py").is_file(), f"Not a generated package: {directory}" + # Support the same long-path generated facades as the regular E2E runner. + parent = str(directory.parent) + if sys.platform == "win32" and not parent.startswith("\\\\?\\"): + parent = ( + "\\\\?\\UNC\\" + parent[2:] if parent.startswith("\\\\") + else "\\\\?\\" + parent + ) + sys.path.insert(0, parent) + return importlib.import_module(directory.name) + + +def registration(function, variable): + """Inspect, never alter, the authoritative generated registration.""" + path = Path(inspect.getsourcefile(function)) + source = path.read_text(encoding="utf-8") + assert source.startswith("# Generated by dynwinrt-codegen") + assignment = next( + node for node in ast.parse(source).body + if isinstance(node, ast.Assign) + and any( + isinstance(target, ast.Name) and target.id == variable + for target in node.targets + ) + ) + call, methods = assignment.value, [] + while ( + isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) + and call.func.attr == "add_method" + ): + methods.append((ast.literal_eval(call.args[0]), ast.unparse(call.args[1]))) + call = call.func.value + return path, list(reversed(methods)) + + +def check_projection(g): + assert "IDispatcherQueue3" in g.__all__, "The real public generated interface is required" + interface = g.IDispatcherQueue3 + descriptor = interface.implementation(DispatcherHandlers(g, "run_event_loop")) + plan = descriptor.plan + assert str(UUID(plan.interface_type.iid().to_string())) == IID + assert plan.name == "Microsoft.UI.Dispatching.IDispatcherQueue3" + assert tuple((m.vtable_index, m.name) for m in plan.methods) == METHODS + assert list(plan.required_iids) == [], "Do not ignore metadata-required interfaces" + path, methods = registration(interface.run_event_loop, "_IDispatcherQueue3") + assert [name for name, _ in methods] == [name for _, name in METHODS] + for name, slot, invoke in ( + ("enqueue_event_loop_exit", 6, "invoke"), + ("_run_event_loop_8", 8, "invoke_detached"), + ("_run_event_loop_9", 9, "invoke_detached"), + ): + assert f".method({slot}).{invoke}(" in inspect.getsource(getattr(interface, name)) + overload = inspect.getsource(interface.run_event_loop) + assert "self._run_event_loop_8(" in overload and "self._run_event_loop_9(" in overload + return { + "iid": IID, "required_interfaces": [], + "generated_source": str(path), + "generated_source_sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + "methods": [ + {"slot": slot, "name": name, "generated_signature": signature} + for (slot, name), (_, signature) in zip(METHODS, methods) + ], + } + + +def expect_hresult(action, expected): + try: + action() + except OSError as error: + actual = error.winerror & 0xFFFFFFFF + assert actual == expected, f"Expected 0x{expected:08X}, got 0x{actual:08X}: {error}" + return error + raise AssertionError(f"Expected native HRESULT 0x{expected:08X}") + + +def expect_local_error(action, words): + try: + action() + except RuntimeError as error: + assert any(word in str(error).lower() for word in words), str(error) + return + raise AssertionError("Disposed primary must reject access before entering native code") + + +class DispatcherHandlers: + """All eight actual handlers; unused event/system operations fail closed.""" + + def __init__(self, g, expected, *, callback_error=False): + self.g, self.expected, self.callback_error = g, expected, callback_error + self.owner = None + self.native_thread = threading.get_native_id() + self.calls = [] + self.completed = 0 + self.deferral_identity = None + + def enter(self, name): + self.calls.append((name, threading.get_native_id())) + assert self.calls == [(self.expected, self.native_thread)], self.calls + + def finish(self, name, deferral=None): + self.enter(name) + if self.callback_error: + raise ValueError(ERROR_SENTINEL) + self.owner.dispose() # The regression: release the active Python receiver. + assert self.owner.is_closed + if deferral is not None: + deferral.complete() # Still inside the already-entered dispatcher callback. + self.completed += 1 + + def enqueue_event_loop_exit(self): + self.finish("enqueue_event_loop_exit") + + def ensure_system_dispatcher_queue(self): + self.enter("ensure_system_dispatcher_queue") + raise AssertionError("Unexpected standalone EnsureSystemDispatcherQueue") + + def run_event_loop(self): + self.finish("run_event_loop") + + def run_event_loop_with_options(self, options, deferral): + assert isinstance(options, self.g.DispatcherRunOptions) + assert options == ( + self.g.DispatcherRunOptions.ContinueOnQuit + | self.g.DispatcherRunOptions.QuitOnlyLocalLoop + ) + assert isinstance(deferral, self.g.DispatcherExitDeferral) + assert deferral._obj.identity_raw() == self.deferral_identity + self.finish("run_event_loop_with_options", deferral) + + def add_framework_shutdown_starting(self, handler): + self.enter("add_framework_shutdown_starting") + raise AssertionError("Unexpected standalone FrameworkShutdownStarting subscription") + + def remove_framework_shutdown_starting(self, token): + self.enter("remove_framework_shutdown_starting") + raise AssertionError("Unexpected standalone FrameworkShutdownStarting removal") + + def add_framework_shutdown_completed(self, handler): + self.enter("add_framework_shutdown_completed") + raise AssertionError("Unexpected standalone FrameworkShutdownCompleted subscription") + + def remove_framework_shutdown_completed(self, token): + self.enter("remove_framework_shutdown_completed") + raise AssertionError("Unexpected standalone FrameworkShutdownCompleted removal") + + +def controlled_deferral(g, dw, cleanup, native_thread): + # This ExclusiveTo default interface has no public generated .implement(). + # Verify its COMPLETE generated registration before describing its one + # callback with the normal managed WinRT implementation API. Never alias an + # unrelated IID, manufacture pointers, or call DispatcherExitDeferral.create(). + _, methods = registration(g.DispatcherExitDeferral.complete, "_IDispatcherExitDeferral") + assert methods == [("Complete", "DynWinRTMethodSig()")] + interface = g.DispatcherExitDeferral.complete.__globals__["_IDispatcherExitDeferral"] + assert str(UUID(interface.iid().to_string())) == DEFERRAL_IID + plan = dw.DynWinRTInterfacePlan.create( + "Microsoft.UI.Dispatching.IDispatcherExitDeferral", interface, + [dw.DynWinRTImplementationMethod("Complete", 6, dw.DynWinRTMethodSig())], [], + ) + calls = [] + + def complete(index, slot, args): + calls.append(threading.get_native_id()) + assert (index, slot, args) == (0, 6, []) + assert calls[-1] == native_thread + return [] + + owner = dw.DynWinRTImplementation.create([plan], complete) + cleanup.callback(owner.dispose) + value = owner.to_value() + try: + # This test-only runtime-class adapter QIs the controlled resource; + # unlike the primary interface's .value path, the class has no public + # constructor/from_value factory. It does not activate an OS object. + projected = g.DispatcherExitDeferral._from_native(value) + finally: + value.release() + cleanup.callback(dw.release_projected, projected) + return owner, projected, calls + + +def exercise(g, dw, case, details): + handlers = DispatcherHandlers(g, CASES[case], callback_error=case == "callback_hresult") + deferral_calls = [] + with ExitStack() as cleanup: + owner = g.IDispatcherQueue3.implement(handlers) + handlers.owner = owner + cleanup.callback(owner.dispose) + primary = owner.value + retained = g.IDispatcherQueue3.from_implementation(owner) + cleanup.callback(dw.release_projected, retained) + assert isinstance(primary, g.IDispatcherQueue3) + assert owner.value is primary and owner.value is primary + assert retained is not primary and retained._obj is not primary._obj + assert retained._obj.identity_raw() == primary._obj.identity_raw() + assert owner.take_error() is None + try: + if case == "callback_hresult": + expect_hresult(owner.value.run_event_loop, PYTHON_CALLBACK_ERROR) + saved = owner.take_error() + assert saved is not None and ERROR_SENTINEL in saved, saved + details["expected_callback_error"] = saved + assert owner.take_error() is None + assert not owner.is_closed and owner.value is primary + assert handlers.completed == 0 + owner.dispose() + elif case == "invoke_detached_options": + deferral_owner, deferral, deferral_calls = controlled_deferral( + g, dw, cleanup, handlers.native_thread, + ) + handlers.deferral_identity = deferral._obj.identity_raw() + options = ( + g.DispatcherRunOptions.ContinueOnQuit + | g.DispatcherRunOptions.QuitOnlyLocalLoop + ) + assert owner.value.run_event_loop(options=options, deferral=deferral) is None + assert deferral_calls == [handlers.native_thread] + assert not deferral_owner.is_closed and deferral_owner.take_error() is None + deferral.complete() # Its independently owned resource survives dispatch. + assert deferral_calls == [handlers.native_thread] * 2 + assert deferral_owner.take_error() is None + elif case == "invoke_baseline": + assert owner.value.enqueue_event_loop_exit() is None + else: + assert owner.value.run_event_loop() is None + + if case != "callback_hresult": + assert handlers.completed == 1, "Already-entered callback did not complete" + assert owner.is_closed + expect_local_error(lambda: owner.value, ("closed", "released")) + expect_local_error(primary.run_event_loop, ("object", "released")) + pending = owner.take_error() + assert pending is None, f"Unexpected callback error after disposal: {pending}" + assert not retained._obj.is_null(), "Retained view must reach the native closed check" + expect_hresult(retained.run_event_loop, RO_E_CLOSED) + # The native closed gate may record its expected rejection even + # though no Python handler entered. Preserve/drain that diagnostic, + # rather than incorrectly treating it as a new callback failure. + closed = owner.take_error() + details["expected_closed_error"] = closed + assert closed is None or ( + "IDispatcherQueue3::RunEventLoop (slot 8): 0x80000013:" in closed + ), f"Unexpected error from retained closed view: {closed}" + assert handlers.calls == [(CASES[case], handlers.native_thread)] + assert threading.get_native_id() == handlers.native_thread + assert owner.take_error() is None, "Unexpected residual callback error" + owner.dispose() # Idempotent cleanup must not reenter the handlers. + assert handlers.calls == [(CASES[case], handlers.native_thread)] + finally: + details.update( + calls=handlers.calls, completed=handlers.completed, + native_thread=handlers.native_thread, deferral_calls=deferral_calls, + callback_error=owner.take_error(), owner_closed=owner.is_closed, + ) + handlers.owner = None # Deterministic cycle breaking, not global GC. + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--generated", required=True, type=Path) + parser.add_argument("--case", choices=CASES, help="Run just one focused scenario") + args = parser.parse_args() + import dynwinrt as dw + + g = import_generated(args.generated) + projection = check_projection(g) + print(json.dumps({ + "python": platform.python_version(), "compiler": platform.python_compiler(), + "runtime": dw.dynwinrt.__file__, "projection": projection, + }), flush=True) + results = [] + # Only COM apartment initialization, never runtime-class activation. + with dw.RoApartment(1): + for case in ([args.case] if args.case else CASES): + result = {"id": case, "pass": False} + try: + exercise(g, dw, case, result) + assert result["callback_error"] is None, result["callback_error"] + result["pass"] = True + except Exception as error: + result["error"] = traceback.format_exc() + if isinstance(error, OSError) and error.winerror is not None: + result["hresult"] = f"0x{error.winerror & 0xFFFFFFFF:08X}" + results.append(result) + print("DYNWINRT_DISPATCHER_RESULT=" + json.dumps(result), flush=True) + passed = sum(result["pass"] for result in results) + print(f"Dispatcher implementation: {passed}/{len(results)} passed", flush=True) + return 0 if passed == len(results) else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/e2e/runners/implementation_py.py b/tests/e2e/runners/implementation_py.py index 06984e66..6a7c5704 100644 --- a/tests/e2e/runners/implementation_py.py +++ b/tests/e2e/runners/implementation_py.py @@ -315,10 +315,25 @@ def run(self, task_instance): task_instance.progress = task_instance.progress + 5 self.runs += 1 + class Text: + def to_string(self): + return "separate text handler" + handlers = Task() - owner = own(g.IBackgroundTask.implement(handlers)) + owner = own(g.IBackgroundTask.implement(handlers, interfaces=[ + (g.IStringable, Text()), (g.IClosable, CloseHandlers()), + ])) + text = g.IStringable.from_implementation(owner) + close = g.IClosable.from_implementation(owner) + try: + assert text.to_string() == "separate text handler" + close.close() + finally: + dw.release_projected(text) + dw.release_projected(close) task = owner.value - task.run(instance) + # Native-delegate positional-only declarations do not change method kwargs. + task.run(task_instance=instance) assert (state.progress, state.gets, state.sets, state.get_ids) == (22, 1, 1, 1) assert handlers.runs == 1 retained_instance = g.IBackgroundTaskInstance.from_implementation(instance_owner) @@ -695,6 +710,18 @@ def on_closed(sender, args): unsubscribe = event_sender.subscribe_closed(on_closed) assert handlers.added == 1 + callback = callbacks[1] + for invalid in ( + lambda: callback(sender=event_sender, args=None), + lambda: callback(event_sender, args=None), + lambda: callback(), + lambda: callback(event_sender), + lambda: callback(event_sender, None, None), + ): + error = expect_error(invalid, "keyword|argument count") + assert isinstance(error, TypeError) + assert delivered == [], "Argument rejection must happen before native Invoke" + del invalid, callback owner.release() close.close() assert delivered == [4096] diff --git a/tests/e2e/typecheck/python_implementation_api.py b/tests/e2e/typecheck/python_implementation_api.py index 8d804259..34182a89 100644 --- a/tests/e2e/typecheck/python_implementation_api.py +++ b/tests/e2e/typecheck/python_implementation_api.py @@ -57,6 +57,21 @@ def close(self) -> None: pass +class Task: + def run(self, task_instance: IBackgroundTaskInstance | None) -> None: + pass + + +class Text: + def to_string(self) -> str: + return "separate text handler" + + +class Close: + def close(self) -> None: + pass + + def check_owner() -> None: handlers = TaskHandlers() instance: DynWinRTImplementationHandle[IBackgroundTaskInstance] = IBackgroundTaskInstance.implement(InstanceHandlers()) @@ -69,7 +84,10 @@ def check_owner() -> None: primary.run(instance.value) impl.run(instance.value) # type: ignore[attr-defined] impl.value = task # type: ignore[misc] - IBackgroundTask.implement(handlers, interfaces=[(IStringable, WrongText())]) # type: ignore[misc] + with IBackgroundTask.implement(Task(), interfaces=[(IStringable, Text()), (IClosable, Close())]) as mixed: + primary = mixed.value + primary.run(task_instance=instance.value) + IBackgroundTask.implement(handlers, interfaces=[(IStringable, WrongText())]) # type: ignore[list-item] task.run(IBackgroundTaskInstance.from_implementation(instance)) text: IStringable = IStringable.from_implementation(owner) close: IClosable = IClosable.from_implementation(owner) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs index cf54bc3e..e08084b4 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs @@ -775,7 +775,7 @@ fn project_validated( let params = projector.parameters(method, true)?; let comma = if params.is_empty() { "" } else { ", " }; declarations.push_str(&format!( - "\nclass {}Delegate{index}(Protocol):\n @property\n def _obj(self) -> DynWinRTValue: ...\n def __call__(self{comma}{params}) -> {}: ...\n", + "\nclass {}Delegate{index}(Protocol):\n @property\n def _obj(self) -> DynWinRTValue: ...\n def __call__(self{comma}{params}, /) -> {}: ...\n", projector.prefix, if method.output_count > 1 { format!("{}Delegate{index}Result", projector.prefix) } else { projector.result_type(method, false) } )); let args = method @@ -958,8 +958,16 @@ fn project_validated( .join(", ") ) }; + let package_overload = if context.is_packaged() { + format!( + " @overload\n def implement(cls, handlers: {name}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[_PackageImplementationPair]) -> DynWinRTImplementationHandle[{name}]: ...\n @overload\n", + name = iface.name + ) + } else { + String::new() + }; let factory_declarations = format!( - "{requirements} def implementation(cls, handlers: {name}Handlers) -> DynWinRTImplementationDescriptor: ...\n def implement(cls, handlers: {name}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[{name}]: ...\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> {name}: ...\n\n", + "{requirements} def implementation(cls, handlers: {name}Handlers) -> DynWinRTImplementationDescriptor: ...\n{package_overload} def implement(cls, handlers: {name}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[{name}]: ...\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> {name}: ...\n\n", name = iface.name ); let mut exports = vec![format!("{}Handlers", iface.name)]; diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 0e1490ce..f49c6f61 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -74,6 +74,30 @@ pub fn generate_runtime_support_stub() -> String { format!("{HEADER}{FUTURE_ANNOTATIONS}") } +/// A closed union checks each pair independently, unlike one TypeVar shared by +/// every element of a Sequence. These imports are stub-only, never eager Python +/// imports. The caller supplies only emitted, implementation-capable modules. +pub fn generate_implementation_pair_types(modules: &[String]) -> String { + let mut out = format!("{HEADER}{FUTURE_ANNOTATIONS}from typing import Never, TypeAlias\n\n"); + for (index, module) in modules.iter().enumerate() { + out.push_str(&format!( + "from .{module} import _ImplementationPair as _Pair{index}\n" + )); + } + let entries = (0..modules.len()) + .map(|index| format!("_Pair{index}")) + .collect::>(); + out.push_str(&format!( + "\n_ImplementationPair: TypeAlias = {}\n", + if entries.is_empty() { + "Never".into() + } else { + entries.join(" | ") + } + )); + out +} + fn identity_marker(prefix: &str, namespace: &str, name: &str) -> String { let identity = format!("{namespace}_{name}") .chars() @@ -223,6 +247,9 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf out.push_str(super::implementation::IMPORTS); out.push_str("from abc import ABCMeta\n"); out.push_str("from typing import TypeVar\nfrom dynwinrt import _DynWinRTImplementationFactory\n_ImplementationHandlers = TypeVar('_ImplementationHandlers')\n"); + if context.is_packaged() { + out.push_str("from typing import TypeAlias\nfrom ._implementation_types import _ImplementationPair as _PackageImplementationPair\n"); + } } let collection_kind = interface_kind(iface); let is_protocol = collection_kind.is_none(); @@ -364,6 +391,12 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf out.push_str(&implementation.declarations); let implementation_metaclass = format!("_{}ImplementationFactory", iface.name); if implementation.supported { + if context.is_packaged() { + out.push_str(&format!( + "\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{name}Handlers], {name}Handlers]\n", + name = iface.name + )); + } out.push_str(&format!("\nclass {implementation_metaclass}(ABCMeta):\n")); out.push_str(&implementation.factory_declarations); } diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 18f1c53a..169a6ccd 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -3875,12 +3875,53 @@ fn generate_py_files( } } if pyi { + write_python_implementation_pair_types(output_dir)?; let marker = output_dir.join("py.typed"); write_file(&marker, "")?; } Ok(()) } +fn write_python_implementation_pair_types(output_dir: &Path) -> Result<(), String> { + // Include retained stubs too: incremental generation must keep the complete + // package union. Only the validated interface projection emits this alias; + // classes, unsupported interfaces, delegates and user stubs contribute none. + let mut modules = BTreeSet::new(); + for entry in fs::read_dir(output_dir) + .map_err(|error| format!("Failed to read {}: {error}", output_dir.display()))? + { + let entry = entry.map_err(|error| format!("Failed to read Python module: {error}"))?; + let path = entry.path(); + let metadata = fs::symlink_metadata(&path) + .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?; + if !metadata.is_file() + || is_link_or_reparse_point(&metadata) + || path.extension().is_none_or(|extension| extension != "pyi") + { + continue; + } + let content = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + if content.starts_with(GENERATED_PYTHON_HEADER) + && content + .lines() + .any(|line| line.starts_with("_ImplementationPair: TypeAlias = tuple[")) + { + let module = path + .file_stem() + .and_then(|stem| stem.to_str()) + .ok_or_else(|| format!("Invalid Python module path {}", path.display()))?; + modules.insert(module.to_string()); + } + } + write_file( + &output_dir.join("_implementation_types.pyi"), + &dynwinrt_codegen::codegen::python_stub::generate_implementation_pair_types( + &modules.into_iter().collect::>(), + ), + ) +} + #[derive(Default)] struct PythonNamespaceGroup { classes: Vec, @@ -4392,7 +4433,17 @@ fn merge_python_lazy_root_indexes( ) -> String { let mut exports = BTreeMap::::new(); collect_python_root_exports(generated, suppressed_names, &mut exports); - collect_python_root_exports(existing, suppressed_names, &mut exports); + let replaced_modules = exports + .values() + .map(|(module, _)| module.clone()) + .collect::>(); + let mut retained = BTreeMap::new(); + collect_python_root_exports(existing, suppressed_names, &mut retained); + for (name, (module, symbol)) in retained { + if !replaced_modules.contains(&module) { + exports.entry(name).or_insert((module, symbol)); + } + } let mut out = String::from(GENERATED_PYTHON_HEADER); out.push_str("from importlib import import_module as _import_module\n\n"); @@ -4499,7 +4550,18 @@ fn merge_python_indexes( ) -> String { let mut imports = BTreeSet::new(); let mut exported_symbols = HashSet::new(); - for line in generated.lines().chain(existing.lines()) { + // A regenerated module supplies its complete current exports. In particular, + // do not retain stale Handler/Delegate aliases after implementation support + // is removed, while leaving unrelated incremental modules untouched. + let replaced_modules = generated + .lines() + .filter_map(parse_python_import_line) + .map(|(module, _)| module) + .collect::>(); + let retained = existing.lines().filter(|line| { + parse_python_import_line(line).is_none_or(|(module, _)| !replaced_modules.contains(&module)) + }); + for line in generated.lines().chain(retained) { if line.starts_with("from .") { let (line, comment) = line .split_once(" #") @@ -8674,6 +8736,98 @@ mod tests { fs::remove_dir_all(phased).unwrap(); } + #[test] + fn python_implementation_pair_union_tracks_incremental_support_and_indexes() { + let output = test_directory("implementation-pair-incremental"); + fs::create_dir_all(&output).unwrap(); + let interface = |namespace: &str, iid: &str| meta::InterfaceMeta { + namespace: namespace.into(), + name: "IValue".into(), + iid: iid.into(), + methods: vec![meta::MethodMeta { + name: "Text".into(), + vtable_index: 6, + return_type: Some(TypeMeta::String), + ..Default::default() + }], + ..Default::default() + }; + let left = interface("Example.Left", "33333333-3333-3333-3333-333333333333"); + let right = interface("Example.Right", "44444444-4444-4444-4444-444444444444"); + let ambiguity = HashSet::from(["IValue".into()]); + let context = python::PythonProjectionContext::packaged_with_ambiguities( + python_type_identities(&[], &[left.clone(), right.clone()], &[]), + ambiguity.iter().cloned(), + ) + .unwrap(); + let emit = |interfaces: &[meta::InterfaceMeta]| { + generate_py_files( + &context, + &output, + &[], + interfaces, + &[], + &[], + &HashSet::new(), + true, + ) + .unwrap(); + write_python_package_indexes(&output, &[], interfaces, &[], &ambiguity, true, true) + .unwrap(); + }; + emit(std::slice::from_ref(&left)); + let first = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + assert!(first.contains(".example__left__i_value import _ImplementationPair")); + assert!(!first.contains("example__right__i_value")); + emit(std::slice::from_ref(&right)); + let complete = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + assert!(complete.contains(".example__left__i_value import _ImplementationPair")); + assert!(complete.contains(".example__right__i_value import _ImplementationPair")); + assert!(!output.join("_implementation_types.py").exists()); + assert!( + !fs::read_to_string(output.join("__init__.py")) + .unwrap() + .contains("_Pair") + ); + for namespace in ["left", "right"] { + let stub = output.join("example").join(namespace).join("__init__.pyi"); + assert!(fs::read_to_string(stub).unwrap().contains("IValueHandlers")); + } + + let mut unsupported = left.clone(); + unsupported + .implementation_metadata + .diagnostics + .push("Unsupported contract".into()); + emit(std::slice::from_ref(&unsupported)); + let reduced = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + assert!(!reduced.contains("example__left__i_value")); + assert!(reduced.contains("example__right__i_value")); + for extension in ["py", "pyi"] { + let namespace = output.join("example").join("left"); + for module in ["__init__", "i_value"] { + let text = + fs::read_to_string(namespace.join(format!("{module}.{extension}"))).unwrap(); + assert!(!text.contains("IValueHandlers"), "{text}"); + assert!(text.contains("IValue"), "{text}"); + } + } + emit(std::slice::from_ref(&left)); + assert_eq!( + complete, + fs::read_to_string(output.join("_implementation_types.pyi")).unwrap() + ); + emit(std::slice::from_ref(&right)); + assert_eq!( + complete, + fs::read_to_string(output.join("_implementation_types.pyi")).unwrap() + ); + remove_all_generated_python_stubs(&output).unwrap(); + assert!(!output.join("_implementation_types.pyi").exists()); + assert!(output.join("example__left__i_value.py").exists()); + fs::remove_dir_all(output).unwrap(); + } + #[test] fn python_package_module_collisions_are_rejected() { let classes = vec![ diff --git a/tools/dynwinrt-codegen/tests/e2e_preparation_test.rs b/tools/dynwinrt-codegen/tests/e2e_preparation_test.rs new file mode 100644 index 00000000..7ad5559c --- /dev/null +++ b/tools/dynwinrt-codegen/tests/e2e_preparation_test.rs @@ -0,0 +1,24 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#[test] +#[cfg(windows)] +fn focused_e2e_uses_shared_build_and_interpreter_preparation() { + let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .join("tests") + .join("e2e") + .join("e2e_preparation.tests.ps1"); + let output = std::process::Command::new("pwsh") + .args(["-NoProfile", "-File"]) + .arg(script) + .output() + .expect("run the existing PowerShell E2E infrastructure"); + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} diff --git a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs index a39a1f20..b480e60c 100644 --- a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs +++ b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs @@ -757,9 +757,42 @@ console.log('prototype validation passed'); #[test] fn implementation_python_projection_validates_handlers_results_arrays_and_dispatch() { - let [_, _, py, _] = generated(&fixture()); + let mut iface = fixture(); + let zero_delegate = TypeMeta::Delegate { + namespace: "Tests".into(), + name: "ZeroCallback".into(), + iid: "41c64fe4-5f4d-4cf8-8a39-c8e2a9f396a1".into(), + }; + iface.methods.push(MethodMeta { + name: "UseZeroCallback".into(), + vtable_index: 16, + params: vec![ParamMeta { + name: "callback".into(), + typ: zero_delegate.clone(), + direction: ParamDirection::In, + }], + return_type: Some(TypeMeta::String), + ..Default::default() + }); + iface + .implementation_metadata + .delegates + .push(ImplementationDelegateMeta { + typ: zero_delegate, + invoke: MethodMeta { + name: "Invoke".into(), + vtable_index: 3, + return_type: Some(TypeMeta::String), + ..Default::default() + }, + }); + let [_, _, py, pyi] = generated(&iface); + for source in [&py, &pyi] { + assert!(source.contains("def __call__(self, value: int, /) -> str: ...")); + assert!(source.contains("def __call__(self, /) -> str: ...")); + } let test = r#" -import sys, json, types, typing, datetime, uuid, weakref +import sys, json, types, typing, datetime, uuid, weakref, ast payload = json.load(sys.stdin) source = payload['code'] # Projection-only doubles, not native ABI fixtures. @@ -783,6 +816,10 @@ class Value: if self.kind == 'object' and hasattr(self.value, 'owner'): self.value.owner.references -= 1 self.kind, self.value = 'null', None def invoke_delegate(self, iid, signature, args): + if iid == '41c64fe4-5f4d-4cf8-8a39-c8e2a9f396a1': + assert [kind for kind, typ in signature.parameters] == ['Out'] + assert args == [] + return [Value.from_hstring('zero')] if iid == '6df84c34-56fe-47fd-a7d6-2a10e986efc4': assert [kind for kind, typ in signature.parameters] == ['OutFill', 'Out'] assert len(args) == 1 @@ -877,6 +914,12 @@ package = types.ModuleType('generated'); package.__path__ = [] sys.modules.update({'generated': package, 'generated._runtime': runtime, 'dynwinrt': binding}) namespace = {'__name__': 'generated.contract', '__package__': 'generated'} exec(compile(source, 'contract.py', 'exec'), namespace) +for declaration in (source, payload['stub']): + syntax = ast.parse(declaration) + for name, count in [('IContractImplementationDelegate0', 2), ('IContractImplementationDelegate2', 1)]: + protocol = next(node for node in ast.walk(syntax) if isinstance(node, ast.ClassDef) and node.name == name) + call = next(node for node in protocol.body if isinstance(node, ast.FunctionDef) and node.name == '__call__') + assert len(call.args.posonlyargs) == count and call.args.args == [] Contract = namespace['IContract'] class Handlers: def __init__(self): self.title = 'start'; self.seen = None @@ -888,6 +931,10 @@ class Handlers: def use_callback(self, callback): if callback is None: return 'null' assert isinstance(callback._obj, Value) + raises('unexpected keyword', lambda: callback(value=7)) + raises('unexpected keyword', lambda: callback(7, value=7)) + raises('argument count', lambda: callback()) + raises('argument count', lambda: callback(7, 8)) return callback(7) def get_object(self): return Value.null_value() def echo_optional(self, value): return value @@ -899,6 +946,10 @@ class Handlers: return True def round_trip_hresult(self, value): return value def round_trip_hresults(self, values): return values + def use_zero_callback(self, callback): + raises('unexpected keyword', lambda: callback(unexpected=7)) + raises('argument count', lambda: callback(7)) + return callback() def raises(fragment, call): try: call() except (TypeError, ValueError) as error: assert fragment in str(error), str(error) @@ -933,6 +984,7 @@ assert descriptor.dispatch(10, [])[0].is_null() assert descriptor.dispatch(11, [Value.box_reference(Value.from_i32(8), None)])[0].value.boxed.value == 8 assert descriptor.dispatch(11, [Value.null_value()])[0].is_null() assert descriptor.dispatch(13, [Value('object', {})])[0].value is True +assert descriptor.dispatch(16, [Value('object', {})])[0].value == 'zero' semantic_hresult = descriptor.dispatch(14, [Value.from_hresult(-2147467259)])[0] assert semantic_hresult.kind == 'hresult' and semantic_hresult.value == -2147467259 hresult_array = descriptor.dispatch(15, [Array([Value.from_hresult(-2147467259), Value.from_hresult(0)]).to_value()])[0] @@ -996,6 +1048,7 @@ print('Python projection assertions passed') &["-c", test], &serde_json::json!({ "code": py, + "stub": pyi, "handle": include_str!("../../../bindings/py/src/implementation.py"), "support": python::generate_runtime_support_module(), }) @@ -1139,7 +1192,7 @@ fn implementation_public_python_views_type_check_without_internal_constructors() .args([ "generate", "--class-name", - "Windows.ApplicationModel.Background.IBackgroundTask,Windows.ApplicationModel.Background.IBackgroundTaskInstance,Windows.Foundation.IStringable,Windows.Foundation.IClosable", + "Windows.ApplicationModel.Background.IBackgroundTask,Windows.ApplicationModel.Background.IBackgroundTaskInstance,Windows.Foundation.IStringable,Windows.Foundation.IClosable,Windows.Foundation.IMemoryBufferReference", "--lang", "py", "--winmd", @@ -1200,12 +1253,91 @@ fn implementation_public_python_views_type_check_without_internal_constructors() .unwrap() .contains(&format!("from .{public_name} import ")) ); + // Same-named interfaces in distinct namespaces must remain distinct pairs. + // The foreign-only method shapes also exercise the generic fallback rather + // than accidentally matching a member of the primary package's closed union. + let mut next_iid = 1; + let mut synthetic = |namespace: &str, name: &str, method: &str, result: Option| { + let iid = format!("8755484b-1a1f-48eb-88e9-{next_iid:012x}"); + next_iid += 1; + InterfaceMeta { + namespace: namespace.into(), + name: name.into(), + iid, + methods: vec![MethodMeta { + name: method.into(), + vtable_index: 6, + return_type: result, + ..Default::default() + }], + ..Default::default() + } + }; + for (name, interfaces) in [ + ( + "pairs", + vec![ + synthetic("Root", "ITask", "Run", None), + synthetic("Left", "IValue", "ToString", Some(TypeMeta::String)), + synthetic("Right", "IValue", "Close", None), + ], + ), + ( + "foreign", + vec![ + synthetic("External", "IGreeting", "Greet", Some(TypeMeta::String)), + synthetic("External", "IShutdown", "Shutdown", None), + ], + ), + ] { + let directory = scratch.join(name); + std::fs::create_dir_all(&directory).unwrap(); + let context = python::PythonProjectionContext::packaged( + interfaces.iter().map(InterfaceMeta::type_identity), + ) + .unwrap(); + let root_interfaces = interfaces + .iter() + .filter(|interface| context.root_name_is_unambiguous(&interface.type_identity())) + .cloned() + .collect::>(); + let mut modules = Vec::new(); + for interface in &interfaces { + let module = context.implementation_module_for_interface(interface); + std::fs::write( + directory.join(format!("{module}.pyi")), + python_stub::generate_interface_stub(&context, interface), + ) + .unwrap(); + modules.push(module); + } + for (module, content) in [ + ( + "__init__.pyi", + python_stub::generate_index_stub(&context, &[], &root_interfaces, &[]), + ), + ("_typing.pyi", python_stub::generate_typing_support_module()), + ("_runtime.pyi", python_stub::generate_runtime_support_stub()), + ( + "_implementation_types.pyi", + python_stub::generate_implementation_pair_types(&modules), + ), + ] { + std::fs::write(directory.join(module), content).unwrap(); + } + } let consumer = scratch.join("consumer.py"); std::fs::write( &consumer, r#" from views import IStringable, IClosable, IBackgroundTask, IBackgroundTaskInstance -from dynwinrt import release_projected +from dynwinrt import DynWinRTImplementationHandle, release_projected +from typing import assert_type +from views import IMemoryBufferReferenceImplementationDelegate0 +from pairs.root__i_task import ITask as LocalTask +from pairs.left__i_value import IValue as Left +from pairs.right__i_value import IValue as Right +from foreign import IGreeting, IShutdown class Strings: def to_string(self) -> str: @@ -1223,6 +1355,9 @@ class Task: if instance is not None: instance.progress = 24 +def invoke_native_delegate(callback: IMemoryBufferReferenceImplementationDelegate0) -> None: + callback(None, None) + def consume_task(value: IBackgroundTask, instance: IBackgroundTaskInstance) -> None: value.run(instance) @@ -1235,6 +1370,46 @@ task_owner = IBackgroundTask.implement(Task()) task_view: IBackgroundTask = IBackgroundTask.from_implementation(task_owner) release_projected(task_view) task_owner.dispose() +with IBackgroundTask.implement( + Task(), interfaces=[(IStringable, Strings()), (IClosable, Closing())] +) as implementation: + assert_type(implementation, DynWinRTImplementationHandle[IBackgroundTask]) + assert_type(implementation.value, IBackgroundTask) + closer = IClosable.from_implementation(implementation) + closer.close() + release_projected(closer) +homogeneous = [(IStringable, Strings())] +assert_type( + IBackgroundTask.implement(Task(), interfaces=homogeneous), + DynWinRTImplementationHandle[IBackgroundTask], +) + +class LocalHandler: + def run(self) -> None: + pass + +class Greeting: + def greet(self) -> str: + return "foreign" + +class Shutdown: + def shutdown(self) -> None: + pass + +assert_type( + LocalTask.implement(LocalHandler(), interfaces=[(Left, Strings()), (Right, Closing())]), + DynWinRTImplementationHandle[LocalTask], +) +assert_type( + LocalTask.implement(LocalHandler(), interfaces=[(IGreeting, Greeting())]), + DynWinRTImplementationHandle[LocalTask], +) +assert_type( + LocalTask.implement( + LocalHandler(), IGreeting.implementation(Greeting()), IShutdown.implementation(Shutdown()) + ), + DynWinRTImplementationHandle[LocalTask], +) "#, ) .unwrap(); @@ -1245,30 +1420,84 @@ task_owner.dispose() .join("py") .canonicalize() .unwrap(); - let result = Command::new("python") - .args([ - "-m", - "mypy", - "--strict", - "--follow-imports=silent", - "--no-incremental", - "--cache-dir", - ]) - .arg("mypy-cache") - .arg("consumer.py") - .current_dir(&scratch) - .env("PYTHONUTF8", "1") - .env( - "MYPYPATH", - std::env::join_paths([binding_stubs, std::path::PathBuf::from(".")]).unwrap(), - ) - .output() - .expect("run the existing mypy checker"); - std::fs::remove_dir_all(&scratch).unwrap(); + let check = |file: &str| { + Command::new("python") + .args([ + "-m", + "mypy", + "--strict", + "--follow-imports=silent", + "--no-incremental", + "--cache-dir", + "mypy-cache", + file, + ]) + .current_dir(&scratch) + .env("PYTHONUTF8", "1") + .env( + "MYPYPATH", + std::env::join_paths([binding_stubs.clone(), std::path::PathBuf::from(".")]) + .unwrap(), + ) + .output() + .expect("run the existing mypy checker") + }; + let result = check("consumer.py"); assert!( result.status.success(), "{}\n{}", String::from_utf8_lossy(&result.stdout), String::from_utf8_lossy(&result.stderr) ); + let negative = r#" +from consumer import Task, Strings, Closing +from views import IBackgroundTask, IStringable, IClosable +from views import IMemoryBufferReferenceImplementationDelegate0 +from consumer import LocalHandler +from pairs.root__i_task import ITask as LocalTask +from pairs.left__i_value import IValue as Left +from pairs.right__i_value import IValue as Right +from foreign import IGreeting + +class WrongReturn: + def to_string(self) -> int: + return 1 + +class WrongSignature: + def to_string(self, required: int) -> str: + return str(required) + +class MissingMethod: + pass + +IBackgroundTask.implement(Task(), interfaces=[(IStringable, Closing()), (IClosable, Strings())]) # swapped +IBackgroundTask.implement(Task(), interfaces=[(IStringable, WrongReturn()), (IClosable, Closing())]) # return +IBackgroundTask.implement(Task(), interfaces=[(IStringable, WrongSignature()), (IClosable, Closing())]) # signature +IBackgroundTask.implement(Task(), interfaces=[(IStringable, MissingMethod()), (IClosable, Closing())]) # missing +IBackgroundTask.implement(Task(), interfaces=[(IStringable, WrongReturn())]) # homogeneous +LocalTask.implement(LocalHandler(), interfaces=[(Left, Closing()), (Right, Strings())]) +LocalTask.implement(LocalHandler(), interfaces=[(IGreeting, Closing())]) + +def reject_native_delegate_calls(callback: IMemoryBufferReferenceImplementationDelegate0) -> None: + callback(sender=None, args=None) + callback(None) + callback(None, None, None) + callback(None, args=None) +"#; + std::fs::write(scratch.join("negative.py"), negative).unwrap(); + let rejected = check("negative.py"); + let diagnostics = String::from_utf8_lossy(&rejected.stdout); + assert!(!rejected.status.success(), "{diagnostics}"); + for (index, line) in negative.lines().enumerate() { + if line.starts_with("IBackgroundTask.implement(") + || line.starts_with("LocalTask.implement(") + || line.trim_start().starts_with("callback(") + { + assert!( + diagnostics.contains(&format!("negative.py:{}: error:", index + 1)), + "incorrect pair was accepted: {line}\n{diagnostics}" + ); + } + } + std::fs::remove_dir_all(&scratch).unwrap(); } From d99df162dff45b25258588df320e1fc0d1fd88bb Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 10 Sep 2026 16:07:23 +0800 Subject: [PATCH 7/8] fix: preserve WinRT metadata and implementation projection boundaries Retain raw ECMA reference qualifiers before reverse validation, align synchronous JS void callbacks with TypeScript, and allocate generated helper symbols by owning interface and role. Track Python implementation pairs in a versioned inventory with atomic migration and retained-stub validation. Ship retrievable management source in runtime wheels and require its actual tracing and coverage without changing the gates. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/build.yml | 8 +- bindings/py/README.md | 5 + bindings/py/build.rs | 32 + bindings/py/pyproject.toml | 9 + bindings/py/python/dynwinrt/.gitignore | 2 + bindings/py/python/dynwinrt/__init__.py | 8 + .../dynwinrt/_implementation.py} | 2 + bindings/py/python/dynwinrt/py.typed | 0 bindings/py/src/implementation.rs | 25 +- .../py/tests/test_implementation_source.py | 399 ++++++++ .../winrt-interface-implementations.md | 15 + eng/coverage/python-coveragerc | 11 + eng/coverage/python_coverage.py | 33 +- eng/coverage/test_python_coverage.py | 73 +- eng/release/python/verify_python_release.py | 11 + tests/e2e/e2e_test.ps1 | 2 +- tests/e2e/runners/implementation_js.mjs | 19 +- tests/e2e/typecheck/ts_implementation_api.ts | 11 + tools/dynwinrt-codegen/README.md | 13 + .../winrt/javascript/implementation.rs | 42 +- .../src/codegen/winrt/javascript/mod.rs | 152 ++- .../codegen/winrt/python/implementation.rs | 74 +- .../src/codegen/winrt/python/mod.rs | 21 + .../src/codegen/winrt/python/naming.rs | 80 ++ .../src/codegen/winrt/python/stubs.rs | 4 +- .../winrt/shared/implementation_symbols.rs | 165 +++ .../src/codegen/winrt/shared/mod.rs | 1 + tools/dynwinrt-codegen/src/main.rs | 721 +++++++++++-- tools/dynwinrt-codegen/src/meta.rs | 25 + .../src/meta/raw_signature.rs | 350 +++++++ .../tests/implementation_naming_test.rs | 963 ++++++++++++++++++ .../tests/winrt_implementation_test.rs | 2 +- .../tests/winrt_raw_signature_test.rs | 750 ++++++++++++++ 33 files changed, 3883 insertions(+), 145 deletions(-) create mode 100644 bindings/py/build.rs create mode 100644 bindings/py/python/dynwinrt/.gitignore create mode 100644 bindings/py/python/dynwinrt/__init__.py rename bindings/py/{src/implementation.py => python/dynwinrt/_implementation.py} (98%) create mode 100644 bindings/py/python/dynwinrt/py.typed create mode 100644 bindings/py/tests/test_implementation_source.py create mode 100644 tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation_symbols.rs create mode 100644 tools/dynwinrt-codegen/src/meta/raw_signature.rs create mode 100644 tools/dynwinrt-codegen/tests/implementation_naming_test.rs create mode 100644 tools/dynwinrt-codegen/tests/winrt_raw_signature_test.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 95a56e47..c7a35f11 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -279,7 +279,7 @@ jobs: cd bindings/py python -m venv .venv .venv/Scripts/Activate.ps1 - pip install pytest maturin "mypy>=1.13,<2" --quiet + pip install pytest maturin "mypy>=1.13,<2" "coverage>=7.15,<8" --quiet maturin build --quiet pip install (Get-ChildItem ../../target/wheels/*.whl | Sort-Object LastWriteTime -Descending | Select-Object -First 1).FullName --force-reinstall --quiet - name: Test Python binding @@ -291,6 +291,12 @@ jobs: .\eng\release\python\test_generated_python_long_paths.ps1 ` -Python .\bindings\py\.venv\Scripts\python.exe ` -Codegen .\target\release\dynwinrt-codegen.exe + - name: Test generated implementation symbol identities + shell: pwsh + run: | + $env:DYNWINRT_TEST_PYTHON = (Resolve-Path .\bindings\py\.venv\Scripts\python.exe).Path + $env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1' + cargo test -p dynwinrt-codegen --test implementation_naming_test - name: Run E2E tests run: .\tests\e2e\e2e_test.ps1 -SkipBuild # This optional-SDK behavioral smoke is separate from generated coverage diff --git a/bindings/py/README.md b/bindings/py/README.md index ecba5093..35befec9 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -231,6 +231,11 @@ from the same generated package. For heterogeneous combinations across generated packages, use positional typed `.implementation(...)` descriptors. Runtime list acceptance and the generic homogeneous-list overload are unchanged. +The management implementation ships as `dynwinrt/_implementation.py` beside the +native extension. Tracebacks and coverage use this installed source file; no +build checkout is needed. The native module's public class identities and +exports are unchanged. + The low-level runtime surface is: - `DynWinRTImplementationMethod(name, vtable_index, signature)`: an immutable diff --git a/bindings/py/build.rs b/bindings/py/build.rs new file mode 100644 index 00000000..e0e32812 --- /dev/null +++ b/bindings/py/build.rs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::{env, fs, io::ErrorKind, path::PathBuf}; + +fn main() { + // Mixed maturin packages do not copy the root native stub automatically. + // Keep it authoritative and preserve the wheel's existing root stub shape. + println!("cargo:rerun-if-changed=dynwinrt.pyi"); + let root = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap()); + let source = fs::read(root.join("dynwinrt.pyi")).expect("read the native Python stub"); + // In an sdist maturin places Python sources at the workspace/archive root + // while retaining this crate at bindings/py. + let package = [root.clone(), root.join("..").join("..")] + .into_iter() + .map(|path| path.join("python").join("dynwinrt")) + .find(|path| path.join("_implementation.py").is_file()) + .expect("find the packaged Python source directory"); + let destination = package.join("__init__.pyi"); + println!("cargo:rerun-if-changed={}", destination.display()); + let needs_update = match fs::read(&destination) { + Ok(existing) => existing != source, + Err(error) if error.kind() == ErrorKind::NotFound => true, + Err(error) => panic!( + "read packaged Python stub {}: {error}", + destination.display() + ), + }; + if needs_update { + fs::write(destination, source).expect("stage the packaged Python stub"); + } +} diff --git a/bindings/py/pyproject.toml b/bindings/py/pyproject.toml index 0964ed49..3e75c010 100644 --- a/bindings/py/pyproject.toml +++ b/bindings/py/pyproject.toml @@ -30,11 +30,20 @@ Issues = "https://github.com/microsoft/dynwinrt/issues" [dependency-groups] dev = [ + "coverage>=7.15,<8", "maturin>=1.11.5", "mypy>=1.13,<2", "pytest>=8.3.5", ] +[tool.maturin] +python-source = "python" +module-name = "dynwinrt.dynwinrt" +include = [ + { path = "dynwinrt/__init__.pyi", format = "wheel" }, +] +exclude = [{ path = "python/dynwinrt/.gitignore", format = "wheel" }] + [tool.pytest.ini_options] testpaths = ["tests"] addopts = "-ra -q" # Shows extra summary info, keeps output quiet diff --git a/bindings/py/python/dynwinrt/.gitignore b/bindings/py/python/dynwinrt/.gitignore new file mode 100644 index 00000000..73204d59 --- /dev/null +++ b/bindings/py/python/dynwinrt/.gitignore @@ -0,0 +1,2 @@ +# Generated by build.rs from the authoritative native stub. +__init__.pyi diff --git a/bindings/py/python/dynwinrt/__init__.py b/bindings/py/python/dynwinrt/__init__.py new file mode 100644 index 00000000..e1a8be1d --- /dev/null +++ b/bindings/py/python/dynwinrt/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from . import dynwinrt as dynwinrt +from .dynwinrt import * + +__doc__ = dynwinrt.__doc__ +__all__ = dynwinrt.__all__ diff --git a/bindings/py/src/implementation.py b/bindings/py/python/dynwinrt/_implementation.py similarity index 98% rename from bindings/py/src/implementation.py rename to bindings/py/python/dynwinrt/_implementation.py index f0a7d796..de575332 100644 --- a/bindings/py/src/implementation.py +++ b/bindings/py/python/dynwinrt/_implementation.py @@ -1,6 +1,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. +# Loaded into the native module's globals to preserve public type identity. + import inspect as _implementation_inspect from typing import Generic as _ImplementationGeneric, TypeVar as _ImplementationTypeVar diff --git a/bindings/py/python/dynwinrt/py.typed b/bindings/py/python/dynwinrt/py.typed new file mode 100644 index 00000000..e69de29b diff --git a/bindings/py/src/implementation.rs b/bindings/py/src/implementation.rs index 238eef3f..dbc65ced 100644 --- a/bindings/py/src/implementation.rs +++ b/bindings/py/src/implementation.rs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use std::ffi::CString; +use std::path::PathBuf; use std::sync::{ Arc, Mutex, Weak, atomic::{AtomicBool, Ordering}, @@ -448,8 +448,27 @@ pub(crate) fn init(module: &Bound<'_, PyModule>) -> PyResult<()> { (runtime.bind(module.py()).getattr("shutdown")?,), )?; module.add("_dynwinrt_implementation_runtime", runtime)?; - let source = CString::new(include_str!("implementation.py")).expect("Python source has no NUL"); - module.py().run(&source, Some(&module.dict()), None)?; + // Load from the installed package, not an embedded string or a build-time + // path. Keep native globals (including __name__) for API/identity compatibility. + let source_path = module + .getattr("__spec__")? + .getattr("origin")? + .extract::()? + .with_file_name("_implementation.py"); + let source_path = module + .py() + .import("os")? + .call_method1("fspath", (source_path,))?; + let loader = module + .py() + .import("importlib.machinery")? + .getattr("SourceFileLoader")? + .call1(("dynwinrt._implementation", source_path))?; + let source = loader.call_method1("get_code", ("dynwinrt._implementation",))?; + module + .py() + .import("builtins")? + .call_method1("exec", (source, module.dict()))?; Ok(()) } diff --git a/bindings/py/tests/test_implementation_source.py b/bindings/py/tests/test_implementation_source.py new file mode 100644 index 00000000..e18ca869 --- /dev/null +++ b/bindings/py/tests/test_implementation_source.py @@ -0,0 +1,399 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Shipped management source and its real native lifecycle paths.""" + +import importlib.util +import inspect +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import textwrap +from typing import get_origin +from uuid import uuid4 + +import pytest + +import dynwinrt +import dynwinrt.dynwinrt as native +from dynwinrt import ( + DynWinRTImplementation, + DynWinRTImplementationDescriptor, + DynWinRTImplementationHandle, + DynWinRTImplementationMethod, + DynWinRTInterfacePlan, + DynWinRTMethodSig, + DynWinRTType, + RoApartment, + WinGUID, +) + + +ROOT = Path(__file__).resolve().parents[3] +PACKAGE = Path(dynwinrt.__file__).resolve().parent +SOURCE = PACKAGE / "_implementation.py" +CLOSED = -2147483629 + + +@pytest.fixture +def closable(): + iid = WinGUID.parse("30d5a829-7fa4-4026-83bb-d75bae4ea99e") + signature = DynWinRTMethodSig() + typ = DynWinRTType.register_interface("Windows.Foundation.IClosable", iid) + typ = typ.add_method("Close", signature) + plan = DynWinRTInterfacePlan.create( + "Windows.Foundation.IClosable", + typ, + [DynWinRTImplementationMethod("Close", 6, signature)], + ) + + class Closable: + _dynwinrt_interface_type = True + + def __init__(self, value): + self._obj = value + + @staticmethod + def implementation(handler): + def dispatch(slot, args): + assert slot == 6 and args == [] + return handler() + + return DynWinRTImplementationDescriptor(plan, dispatch) + + @classmethod + def from_implementation(cls, owner): + value = owner.to_value() + try: + return cls(value.cast(iid)) + finally: + value.release() + + def close(self): + assert typ.method(6).invoke_all(self._obj, []) == [] + + with RoApartment(1): + yield Closable, plan + + +@pytest.fixture +def source_artifacts(): + directory = ROOT / "bindings" / "py" / "target" / ("source-test-" + uuid4().hex) + directory.mkdir(parents=True) + try: + yield directory + finally: + shutil.rmtree(directory) + + +def test_management_code_has_retrievable_source_and_unchanged_identity(): + assert SOURCE.is_file() + assert SOURCE.read_text(encoding="utf-8") == ( + ROOT / "bindings" / "py" / "python" / "dynwinrt" / "_implementation.py" + ).read_text(encoding="utf-8") + assert SOURCE == Path(native.__spec__.origin).with_name("_implementation.py") + assert DynWinRTImplementationHandle.__module__ == "dynwinrt.dynwinrt" + assert DynWinRTImplementationDescriptor.__module__ == "dynwinrt.dynwinrt" + assert native.DynWinRTImplementationHandle is DynWinRTImplementationHandle + assert get_origin(DynWinRTImplementationHandle[int]) is DynWinRTImplementationHandle + functions = [ + value.fget if isinstance(value, property) + else value.__func__ if isinstance(value, staticmethod) + else value + for cls in (DynWinRTImplementationHandle, DynWinRTImplementationDescriptor) + for value in vars(cls).values() + if inspect.isfunction(value) or isinstance(value, (property, staticmethod)) + ] + functions.extend(( + native._dynwinrt_checked_implementation_callback, + native._dynwinrt_require_sync_implementation_callable, + native._dynwinrt_validate_implementation_result, + )) + for function in functions: + assert Path(function.__code__.co_filename) == SOURCE + assert function.__globals__ is vars(native) + assert f"def {function.__name__}(" in inspect.getsource(function) + spec = importlib.util.find_spec("dynwinrt._implementation") + assert Path(spec.origin) == SOURCE + assert spec.loader.get_source(spec.name) == SOURCE.read_text(encoding="utf-8") + assert (PACKAGE / "__init__.pyi").read_text(encoding="utf-8") == ( + ROOT / "bindings" / "py" / "dynwinrt.pyi" + ).read_text(encoding="utf-8") + + +def test_lazy_primary_view_release_and_retained_native_alias(closable): + interface, _ = closable + calls = [] + handle = DynWinRTImplementationHandle._create( + interface, lambda: calls.append("close") or [], (), () + ) + assert handle._value is None + with handle: + view = handle.value + assert handle.value is view + raw = handle.to_value() + alias = interface.from_implementation(handle) + raw.release() + try: + view.close() + handle.release() + handle.release() + assert view._obj.is_null() + assert not handle.is_closed + alias.close() + for action in (lambda: handle.value, handle.to_value, handle.__enter__): + with pytest.raises(RuntimeError, match="released"): + action() + handle.disconnect() + assert handle.is_closed + with pytest.raises(OSError) as caught: + alias.close() + assert caught.value.winerror == CLOSED + assert "disconnected" in handle.take_error() + assert handle.take_error() is None + finally: + alias._obj.release() + assert calls == ["close", "close"] + handle.dispose() + + +def test_release_without_projecting_and_dispose_on_context_exception(closable): + interface, _ = closable + first = DynWinRTImplementationHandle._create(interface, lambda: [], (), ()) + first.release() + assert first._value is None + first.dispose() + with pytest.raises(LookupError, match="consumer"): + with DynWinRTImplementationHandle._create(interface, lambda: [], (), ()) as second: + view = second.value + raise LookupError("consumer") + assert second.is_closed and view._obj.is_null() + + +@pytest.mark.parametrize("operation", ["release", "disconnect", "dispose"]) +def test_disposal_during_primary_projection_releases_the_new_view(closable, operation): + interface, _ = closable + owner = DynWinRTImplementation.create([interface.implementation(lambda: []).plan], lambda *_: []) + views = [] + handle = None + + def project(value): + view = interface.from_implementation(value) + views.append(view) + getattr(handle, operation)() + return view + + handle = DynWinRTImplementationHandle(owner, project) + with pytest.raises(RuntimeError, match="during primary view creation"): + _ = handle.value + assert owner.is_closed and not handle._projecting + assert len(views) == 1 and views[0]._obj.is_null() + handle.dispose() + + +@pytest.mark.parametrize("reentrant", [False, True]) +def test_projection_failure_closes_native_owner(closable, reentrant): + _, plan = closable + owner = DynWinRTImplementation.create([plan], lambda *_: []) + handle = None + + def project(_owner): + if reentrant: + return handle.value + raise RuntimeError("projection failed") + + handle = DynWinRTImplementationHandle(owner, project) + with pytest.raises(RuntimeError, match="reentrant" if reentrant else "projection failed"): + _ = handle.value + assert owner.is_closed and not handle._projecting + with pytest.raises(RuntimeError, match="closed"): + _ = handle.value + + +def test_owner_release_still_runs_if_projected_release_raises(closable): + interface, plan = closable + owner = DynWinRTImplementation.create([plan], lambda *_: []) + + class Projection: + def __init__(self, owner): + self.native_view = interface.from_implementation(owner) + + def release(self): + self.native_view._obj.release() + raise RuntimeError("projection cleanup failed") + + handle = DynWinRTImplementationHandle(owner, Projection) + projection = handle.value + with pytest.raises(RuntimeError, match="cleanup failed"): + handle.release() + assert projection.native_view._obj.is_null() + with pytest.raises(OSError): + owner.to_value() + handle.dispose() + + +@pytest.mark.parametrize("entry", [None, (), (object(),), (object(), object())]) +def test_invalid_interface_pairs_fail_before_native_creation(closable, entry): + interface, _ = closable + with pytest.raises(TypeError, match="interface entry"): + DynWinRTImplementationHandle._create(interface, lambda: [], (), (entry,)) + + +def test_invalid_management_inputs_and_descriptors(closable): + interface, plan = closable + with pytest.raises(TypeError, match="owner and typed projector"): + DynWinRTImplementationHandle(object(), lambda _: None) + with DynWinRTImplementation.create([plan], lambda *_: []) as owner: + with pytest.raises(TypeError, match="owner and typed projector"): + DynWinRTImplementationHandle(owner, None) + with pytest.raises(TypeError, match="Invalid WinRT implementation descriptor"): + DynWinRTImplementationHandle._create(interface, lambda: [], (object(),), ()) + with pytest.raises(TypeError, match="DynWinRTInterfacePlan"): + DynWinRTImplementationDescriptor(object(), lambda *_: []) + with pytest.raises(TypeError, match="callable"): + DynWinRTImplementationDescriptor(plan, None) + + +def test_additional_interface_pairs_dispatch_through_native_slots(closable): + interface, _ = closable + iid = WinGUID.parse("96369f54-8eb6-48f0-abce-c1b211e627c3") + signature = DynWinRTMethodSig().add_out(DynWinRTType.hstring()) + typ = DynWinRTType.register_interface("Windows.Foundation.IStringable", iid) + typ = typ.add_method("ToString", signature) + plan = DynWinRTInterfacePlan.create( + "Windows.Foundation.IStringable", typ, + [DynWinRTImplementationMethod("ToString", 6, signature)], + ) + + class Stringable: + _dynwinrt_interface_type = True + from_implementation = staticmethod(lambda owner: owner.to_value()) + + @staticmethod + def implementation(handler): + return DynWinRTImplementationDescriptor(plan, lambda *_: [handler()]) + + with DynWinRTImplementationHandle._create( + interface, lambda: [], (), + ((Stringable, lambda: dynwinrt.DynWinRTValue.from_hstring("source-visible")),), + ) as handle: + handle.value.close() + raw = handle.to_value() + view = raw.cast(iid) + raw.release() + try: + assert typ.method(6).get_string(view) == "source-visible" + finally: + view.release() + + +@pytest.mark.parametrize("loading", ["installed", "relocated-installation", "checkout", "direct-extension"]) +def test_real_lifecycle_is_counted_by_the_product_report(source_artifacts, loading): + output = source_artifacts / "reports" + output.mkdir() + consumer = source_artifacts / "consumer" + consumer.mkdir() + runtime = PACKAGE.parent if loading == "installed" else source_artifacts / "runtime" + source = ( + ROOT / "bindings" / "py" / "python" / "dynwinrt" + if loading == "checkout" else PACKAGE + ) + if loading != "installed": + shutil.copytree( + source, runtime / "dynwinrt", + ignore=shutil.ignore_patterns("*.pyd", ".gitignore"), + ) + shutil.copy2(native.__file__, runtime / "dynwinrt" / Path(native.__file__).name) + script = textwrap.dedent(""" + import sys + from pathlib import Path + sys.path.insert(0, sys.argv[1]) + from coverage import Coverage + cov = Coverage(config_file=sys.argv[2], data_file=sys.argv[3], data_suffix=True) + cov.start() + if sys.argv[4] == "direct-extension": + from importlib.util import module_from_spec, spec_from_file_location + extension = next((Path(sys.argv[1]) / "dynwinrt").glob("*.pyd")) + spec = spec_from_file_location("dynwinrt.dynwinrt", extension) + module = module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + from dynwinrt import ( + DynWinRTImplementationDescriptor, DynWinRTImplementationHandle, + DynWinRTImplementationMethod, DynWinRTInterfacePlan, DynWinRTMethodSig, + DynWinRTType, RoApartment, WinGUID, + ) + iid = WinGUID.parse("30d5a829-7fa4-4026-83bb-d75bae4ea99e") + signature = DynWinRTMethodSig() + typ = DynWinRTType.register_interface("Windows.Foundation.IClosable", iid) + typ = typ.add_method("Close", signature) + plan = DynWinRTInterfacePlan.create( + "Windows.Foundation.IClosable", typ, + [DynWinRTImplementationMethod("Close", 6, signature)], + ) + calls = [] + class Closable: + @staticmethod + def implementation(handler): + return DynWinRTImplementationDescriptor(plan, lambda *_: handler()) + @classmethod + def from_implementation(cls, owner): + value = owner.to_value() + try: + result = cls() + result._obj = value.cast(iid) + return result + finally: + value.release() + with RoApartment(1): + with DynWinRTImplementationHandle._create( + Closable, lambda: calls.append("native close") or [], (), () + ) as handle: + primary = handle.value + assert primary is handle.value + assert typ.method(6).invoke_all(primary._obj, []) == [] + handle.release() + handle.dispose() + assert primary._obj.is_null() + assert calls == ["native close"] + source = Path(DynWinRTImplementationHandle.value.fget.__code__.co_filename) + assert source == Path(sys.argv[1]) / "dynwinrt" / "_implementation.py" + assert "class DynWinRTImplementationHandle" in source.read_text(encoding="utf-8") + cov.stop() + cov.save() + """) + config = ROOT / "eng" / "coverage" / "python-coveragerc" + environment = dict(os.environ, COVERAGE_PROCESS_START="") + result = subprocess.run( + [sys.executable, "-I", "-c", script, str(runtime), str(config), + str(output / ".coverage"), loading], + cwd=consumer, env=environment, capture_output=True, text=True, timeout=60, + ) + assert result.returncode == 0, result.stdout + result.stderr + result = subprocess.run( + [sys.executable, str(ROOT / "eng" / "coverage" / "python_coverage.py"), + "--root", str(ROOT), "--output", str(output), "--config", str(config)], + cwd=consumer, env=environment, capture_output=True, text=True, timeout=60, + ) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads((output / "runtime" / "coverage.json").read_text(encoding="utf-8")) + path = next(path for path in report["files"] if path.endswith("_implementation.py")) + measured = report["files"][path] + assert 0 < measured["summary"]["covered_lines"] < measured["summary"]["num_statements"] + for name in ( + "DynWinRTImplementationHandle._create", + "DynWinRTImplementationHandle.value", + "DynWinRTImplementationHandle.release", + "DynWinRTImplementationHandle.dispose", + "DynWinRTImplementationDescriptor.__init__", + "DynWinRTImplementationDescriptor.dispatch", + "_dynwinrt_checked_implementation_callback.invoke", + ): + counts = measured["functions"][name]["summary"] + assert counts["covered_lines"] > 0, name + assert counts["num_statements"] > 0, name + aggregate = json.loads((output / "coverage.json").read_text(encoding="utf-8")) + assert aggregate["files"][path]["summary"] == measured["summary"] diff --git a/docs/guides/windows/winrt-interface-implementations.md b/docs/guides/windows/winrt-interface-implementations.md index 95620416..433b881d 100644 --- a/docs/guides/windows/winrt-interface-implementations.md +++ b/docs/guides/windows/winrt-interface-implementations.md @@ -125,6 +125,10 @@ Support is determined from the entire interface, not only from the method an application intends to call. Missing handlers, unresolved required interfaces, duplicate views, invalid slots, or unsupported signatures fail before a native object is published. +Validation retains original metadata reference qualifiers: an input scalar +`BYREF`, a by-reference logical return, or a by-reference struct field is not +silently treated as a value. Normal scalar outputs and WinRT pass/fill/receive +array contracts remain supported. | Contract | Support | | --- | --- | @@ -146,6 +150,17 @@ generated result has named fields; every field must be present and valid. The ABI order is explicit output parameters in metadata order followed by the method's logical return value. +Node handlers with no logical outputs use normal TypeScript `void` semantics: +synchronous expression results such as `closes++`, an assignment, or +`Map.delete(...)` are ignored. Promises and thenables are still rejected, and +thrown exceptions still fail the native call. Python void handlers return `None`. + +Handler, delegate-callable, and result helpers have names allocated with their +owning interface identity. If a helper would shadow a real metadata type or +another helper, codegen qualifies the helper name; real types keep their public +identity. Use factory type inference or the generated exports instead of +constructing helper names by concatenating strings. + A fill-array handler receives a **capacity**, not a writable borrowed native buffer. Return exactly that many elements. Receive-array storage and element references are allocated and transferred by the runtime. An invalid element, diff --git a/eng/coverage/python-coveragerc b/eng/coverage/python-coveragerc index 7ef3a443..4ab795a2 100644 --- a/eng/coverage/python-coveragerc +++ b/eng/coverage/python-coveragerc @@ -2,11 +2,22 @@ branch = True parallel = True relative_files = True +# Installed runtime files need an explicit tracing include; report filters alone +# do not override coverage's default third-party-module exclusion. +include = + */site-packages/dynwinrt/* + */bindings/py/src/*.py + */bindings/py/python/dynwinrt/* + */dynwinrt/*.py + */tests/e2e/e2e_generated/python_bindings/* + */tests/e2e/e2e_generated/implementations/python_bindings/* [report] include = */site-packages/dynwinrt/* */bindings/py/src/*.py + */bindings/py/python/dynwinrt/* + */dynwinrt/*.py */tests/e2e/e2e_generated/python_bindings/* */tests/e2e/e2e_generated/implementations/python_bindings/* omit = diff --git a/eng/coverage/python_coverage.py b/eng/coverage/python_coverage.py index 6dc100ab..50019599 100644 --- a/eng/coverage/python_coverage.py +++ b/eng/coverage/python_coverage.py @@ -18,7 +18,13 @@ "tests/e2e/e2e_generated/implementations/python_bindings/*" ), } -RUNTIME_INCLUDES = ["*/site-packages/dynwinrt/*", "*/bindings/py/src/*.py"] +RUNTIME_INCLUDES = [ + "*/site-packages/dynwinrt/*", + "*/bindings/py/src/*.py", + "*/bindings/py/python/dynwinrt/*", + "*/dynwinrt/*.py", +] +REQUIRED_RUNTIME_SOURCES = ("dynwinrt/_implementation.py",) def _without_device_prefix(path: str) -> str: @@ -104,16 +110,25 @@ def write_reports( includes = coverage.get_option("report:include") try: aggregate = _write_layer(coverage, directory, includes) - except NoDataError: - if require_generated: - raise - print("No Python product files were measured; skipping product reports.") - return + except NoDataError as error: + raise RuntimeError( + "Python coverage did not execute required runtime sources: " + + ", ".join(REQUIRED_RUNTIME_SOURCES) + ) from error files = { normalize_path(path, root).replace("\\", "/"): entry for path, entry in aggregate["files"].items() } + missing_runtime = [ + source for source in REQUIRED_RUNTIME_SOURCES + if not any( + (path.lower() == source or path.lower().endswith("/" + source)) + and entry["summary"]["covered_lines"] > 0 + and entry["summary"]["num_statements"] > 0 + for path, entry in files.items() + ) + ] missing_layers = [] generated_files = set() for name, pattern in GENERATED_LAYERS.items(): @@ -130,10 +145,10 @@ def write_reports( if files.keys() - generated_files: _write_layer(coverage, directory / "runtime", RUNTIME_INCLUDES) coverage.report(include=includes) - if missing_layers: + if missing_runtime or missing_layers: raise RuntimeError( - "Python coverage did not execute required source families: " - + ", ".join(missing_layers) + "Python coverage did not execute required runtime sources or source families: " + + ", ".join(missing_runtime + missing_layers) ) finally: os.chdir(original_directory) diff --git a/eng/coverage/test_python_coverage.py b/eng/coverage/test_python_coverage.py index 8c3e5201..9aca4b74 100644 --- a/eng/coverage/test_python_coverage.py +++ b/eng/coverage/test_python_coverage.py @@ -10,7 +10,7 @@ import unittest import uuid -from coverage import CoverageData +from coverage import Coverage, CoverageData from coverage.exceptions import NoSource from python_coverage import normalize_data, normalize_path, write_reports @@ -19,9 +19,14 @@ HERE = Path(__file__).resolve().parent STANDARD = Path("tests/e2e/e2e_generated/python_bindings") IMPLEMENTATIONS = Path("tests/e2e/e2e_generated/implementations/python_bindings") +RUNTIME = Path("bindings/py/python/dynwinrt/_implementation.py") class PathNormalizationTests(unittest.TestCase): + def test_product_trace_and_report_sources_agree(self): + coverage = Coverage(config_file=str(HERE / "python-coveragerc")) + self.assertEqual(coverage.get_option("run:include"), coverage.get_option("report:include")) + def test_extended_drive_paths_become_repo_relative(self): root = Path(r"D:\a\dynwinrt\dynwinrt") relative = str(IMPLEMENTATIONS / "windows" / "i_closable.py") @@ -94,7 +99,7 @@ def test_aggregate_keeps_both_generated_trees_runtime_and_transitive_interfaces( standard = self.source(STANDARD / "windows__i_closable.py") implementation = self.source(IMPLEMENTATIONS / "windows__i_closable.py") transitive = self.source(STANDARD / "windows" / "transitive.py", "def unused():\n return 7\n") - runtime = self.source(Path("bindings/py/src/implementation.py")) + runtime = self.source(RUNTIME) runner = self.source(Path("tests/e2e/runners/runner.py")) self.record("standard", { str(standard.relative_to(self.root)): [1, 2, 4], @@ -159,13 +164,13 @@ def test_zero_hit_implementation_family_does_not_satisfy_presence_check(self): ) def test_skip_e2e_can_report_runtime_without_generated_sources(self): - runtime = self.source(Path("bindings/py/src/implementation.py")) + runtime = self.source(RUNTIME) self.record("runtime", {str(runtime.relative_to(self.root)): [1, 2, 4]}) self.report() self.assertEqual(self.read_report("runtime/coverage.json")["totals"]["covered_lines"], 3) def test_installed_runtime_package_is_included(self): - runtime = self.source(Path("environment/Lib/site-packages/dynwinrt/implementation.py")) + runtime = self.source(Path("environment/Lib/site-packages/dynwinrt/_implementation.py")) self.record("runtime", {str(runtime): [1, 2, 4]}) self.report() self.assertEqual(self.read_report("runtime/coverage.json")["totals"]["covered_lines"], 3) @@ -182,22 +187,25 @@ def test_combined_branch_reports_keep_alias_hits_and_contexts(self): data = CoverageData(basename=str(self.output / (".coverage." + context))) data.set_context(context) data.add_arcs({filename: [(-1, 1), (1, 2), (2, target), (target, -1)]}) + runtime = self.source(RUNTIME, "value = 3\n") + data.add_arcs({str(runtime): [(-1, 1), (1, -1)]}) data.write() self.report() totals = self.read_report()["totals"] self.assertEqual(totals["num_branches"], 2) self.assertEqual(totals["covered_branches"], 2) - self.assertEqual(totals["covered_lines"], 4) + self.assertEqual(totals["covered_lines"], 5) combined = CoverageData(basename=str(self.output / ".coverage")) combined.read() - self.assertEqual(len(combined.measured_files()), 1) - filename = next(iter(combined.measured_files())) + self.assertEqual(len(combined.measured_files()), 2) + filename = next(path for path in combined.measured_files() if "conditional" in path) self.assertEqual(set(combined.contexts_by_lineno(filename)[2]), {"truthy", "falsey"}) - def test_no_product_measurements_still_produce_accurate_diagnostics(self): + def test_no_runtime_measurements_fail_with_accurate_diagnostics(self): runner = self.source(Path("tests/e2e/runners/runner.py")) self.record("runner", {str(runner.relative_to(self.root)): [1, 2, 4]}) - self.report() + with self.assertRaisesRegex(RuntimeError, "dynwinrt/_implementation.py"): + self.report() self.assertEqual(self.read_report("all-data.json")["totals"]["covered_lines"], 3) self.assertFalse((self.output / "coverage.json").exists()) @@ -211,8 +219,53 @@ def test_missing_sources_are_not_ignored(self): def test_extended_long_source_paths_remain_reportable(self): long_source = self.source(IMPLEMENTATIONS / ("generic_" + "type_" * 28 + ".py")) self.record("long", {"\\\\?\\" + str(long_source): [1, 2, 4]}) + runtime = self.source(RUNTIME) + self.record("runtime", {str(runtime): [1, 2, 4]}) self.report() - self.assertEqual(self.read_report()["totals"]["covered_lines"], 3) + self.assertEqual(self.read_report("generated-implementations/coverage.json")["totals"]["covered_lines"], 3) + + def test_generated_families_and_shared_helpers_cannot_replace_runtime_source(self): + sources = [ + self.source(STANDARD / "sample.py"), + self.source(STANDARD / "_runtime.py"), + self.source(IMPLEMENTATIONS / "sample.py"), + self.source(IMPLEMENTATIONS / "_runtime.py"), + ] + unrelated_runtime = self.source(Path("environment/Lib/site-packages/dynwinrt/__init__.py")) + self.record("generated", {str(path): [1, 2, 4] for path in (*sources, unrelated_runtime)}) + with self.assertRaisesRegex(RuntimeError, "dynwinrt/_implementation.py"): + self.report(require_generated=True) + self.assertEqual(self.read_report()["totals"]["covered_lines"], 15) + for name in ("generated-winrt", "generated-implementations"): + report = self.read_report(name + "/coverage.json") + self.assertTrue(any(path.endswith("_runtime.py") for path in report["files"])) + + def test_zero_hit_runtime_source_does_not_satisfy_presence_check(self): + runtime = self.source(RUNTIME) + generated = self.source(STANDARD / "sample.py") + self.record("measured", {str(runtime): [], str(generated): [1, 2, 4]}) + with self.assertRaisesRegex(RuntimeError, "dynwinrt/_implementation.py"): + self.report() + totals = self.read_report("runtime/coverage.json")["totals"] + self.assertEqual(totals["covered_lines"], 0) + self.assertEqual(totals["num_statements"], 3) + + def test_required_source_must_be_part_of_the_product_report(self): + runtime = self.source(RUNTIME) + generated = self.source(STANDARD / "sample.py") + self.record("measured", {str(runtime): [1, 2, 4], str(generated): [1, 2, 4]}) + config = self.root / "exclude-runtime.coveragerc" + config.write_text( + (HERE / "python-coveragerc").read_text(encoding="utf-8").replace( + "omit =\n", "omit =\n */dynwinrt/_implementation.py\n" + ), + encoding="utf-8", + ) + with self.assertRaisesRegex(RuntimeError, "dynwinrt/_implementation.py"): + with contextlib.redirect_stdout(io.StringIO()): + write_reports(self.root, self.output, config) + diagnostic = self.read_report("all-data.json") + self.assertTrue(any(path.endswith("_implementation.py") for path in diagnostic["files"])) if __name__ == "__main__": diff --git a/eng/release/python/verify_python_release.py b/eng/release/python/verify_python_release.py index cde07ef7..df033aae 100644 --- a/eng/release/python/verify_python_release.py +++ b/eng/release/python/verify_python_release.py @@ -146,6 +146,17 @@ def verify_wheel(args: argparse.Namespace) -> None: assert any(name.endswith(".pyd") for name in names) assert any(name.endswith("/py.typed") for name in names) assert any(name.endswith(".pyi") for name in names) + source_name = "dynwinrt/_implementation.py" + assert source_name in names, "Missing retrievable implementation management source" + source = ROOT / "bindings" / "py" / "python" / "dynwinrt" / "_implementation.py" + shipped_source = archive.read(source_name).decode("utf-8").replace("\r\n", "\n") + assert shipped_source == source.read_text(encoding="utf-8"), ( + "Wheel implementation source does not match the authoritative source" + ) + shipped_stub = archive.read("dynwinrt/__init__.pyi").decode("utf-8").replace("\r\n", "\n") + assert shipped_stub == ( + ROOT / "bindings" / "py" / "dynwinrt.pyi" + ).read_text(encoding="utf-8"), "Packaged root stub differs from the authoritative native stub" else: assert any(name.endswith("/dynwinrt-codegen.exe") for name in names) diff --git a/tests/e2e/e2e_test.ps1 b/tests/e2e/e2e_test.ps1 index 03e69d6f..928c243b 100644 --- a/tests/e2e/e2e_test.ps1 +++ b/tests/e2e/e2e_test.ps1 @@ -140,7 +140,7 @@ if (-not $SkipBuild) { if (-not (Test-Path $venvPython)) { & $pythonExe -m venv .venv if ($LASTEXITCODE -ne 0) { Write-Error "Python virtual environment creation failed"; exit 1 } - & $venvPython -m pip install pytest maturin mypy --quiet + & $venvPython -m pip install pytest maturin mypy "coverage>=7.15,<8" --quiet if ($LASTEXITCODE -ne 0) { Write-Error "Python test dependency installation failed"; exit 1 } } $pythonExe = (Resolve-Path -LiteralPath $venvPython).Path diff --git a/tests/e2e/runners/implementation_js.mjs b/tests/e2e/runners/implementation_js.mjs index 456af268..fe526f2f 100644 --- a/tests/e2e/runners/implementation_js.mjs +++ b/tests/e2e/runners/implementation_js.mjs @@ -110,7 +110,7 @@ const cases = { let calls = 0; const impl = own(g.IStringable.implement( { toString() { calls++; return 'typed primary'; } }, - { interfaces: [[g.IClosable, { close() { calls++; } }]] }, + { interfaces: [[g.IClosable, { close: () => calls++ }]] }, )); assert.strictEqual(impl.value, impl.value); assert.ok(impl.value instanceof g.IStringable); @@ -167,13 +167,18 @@ const cases = { assert.equal(disposing.value.toString(), 'entered callback completed'); assert.equal(disposing.isClosed, true); assert.throws(() => disposing.value, /closed|released/); + for (const result of [undefined, false, 17, { ignored: true }]) { + const ignored = own(g.IClosable.implement({ close: () => result })); + assert.equal(ignored.value.close(), undefined); + assert.equal(ignored.takeError(), null); + } }, property_views({ g, own }) { let length = 0; const handlers = { getCapacity: () => 12, getLength: () => length, - setLength(value) { if (value > 12) throw new Error('capacity exceeded'); length = value; }, + setLength(value) { if (value > 12) throw new Error('capacity exceeded'); return length = value; }, getAbsoluteCanonicalUri: () => 'https://example.test/\u96ea', getDisplayIri: () => 'https://example.test/\u96ea', getName: () => 'query', getValue: () => 'value\0\u96ea', @@ -349,6 +354,14 @@ const cases = { expectHresult(view.invoke, E_FAIL); takeError(owner, /promise|async|synchronous/i); } finally { view.release(); } + for (const result of [Promise.resolve(), { then() { throw new Error('must not await'); } }]) { + const ignored = own(g.IClosable.implement({ close: () => result })); + expectHresult(() => ignored.value.close(), E_FAIL); + takeError(ignored, /Promise|thenable|synchronously/i); + } + const throwing = own(g.IClosable.implement({ close() { throw new Error('void still propagates'); } })); + expectHresult(() => throwing.value.close(), E_FAIL); + takeError(throwing, /void still propagates/); }, required_interfaces({ g, own }) { @@ -388,9 +401,9 @@ const cases = { assert.equal(typeof token.value, 'bigint'); const received = callbacks.get(Number(token.value)); assert.ok(received); - assert.equal(callbacks.delete(Number(token.value)), true); g.releaseProjected(received); removed++; + return callbacks.delete(Number(token.value)); }, }, g.IClosable.implementation({ close() { diff --git a/tests/e2e/typecheck/ts_implementation_api.ts b/tests/e2e/typecheck/ts_implementation_api.ts index 58837154..4857ec74 100644 --- a/tests/e2e/typecheck/ts_implementation_api.ts +++ b/tests/e2e/typecheck/ts_implementation_api.ts @@ -17,6 +17,17 @@ function unused(..._args: unknown[]): never { throw new Error('Typecheck fixture only'); } +let closes = 0; +IClosable.implement({ close: () => closes++ }); +let length = 0; +IBuffer.implement({ getCapacity: () => 12, getLength: () => length, setLength: value => length = value }); +const tokens = new Map(); +IMemoryBufferReference.implement({ + getCapacity: () => 12, + addClosed: () => ({ value: 1n }), + removeClosed: token => tokens.delete(token.value), +}, IClosable.implementation({ close: () => undefined })); + const exactHresult: DynWinRtValue = DynWinRtValue.hresult(-2147467263); const hresults: DynWinRtArray = DynWinRtArray.fromHresultValues([0, -2147467263]); const genericHresults: DynWinRtArray = DynWinRtArray.fromObjectValues( diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index 82975a35..b40a5518 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -128,6 +128,19 @@ complete output. Python module components longer than 120 characters are shortened with a stable readable prefix and hash suffix while public type names remain unchanged. +Implementation helper names are allocated alongside metadata types and follow +their owning interfaces through incremental renames. Python's package-level +heterogeneous interface-pair union is generated from validated inventory +records, not inferred from `.pyi` text. The first typed incremental generation +over an older inventory needs the original WinMD/`--ref` inputs for interfaces +whose implementation records are missing. If those inputs are unavailable, +generation fails atomically and leaves the previous output usable: supply the +listed metadata and retry, or fully regenerate the package. New inventories +retain these records, and `--no-pyi` does not require this typing migration. +After `--no-pyi`, include the earlier types when regenerating with stubs enabled +(or fully regenerate the package). A typed append fails rather than publishing +imports of missing retained declarations or dropping interfaces from the union. + The npm wrapper accepts the legacy `--source-map`, `--declaration`, and `--no-declaration` flags as no-ops. The Rust command accepts only `js` and `py` for `--lang`. diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs index 4a827101..5ae77eef 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/implementation.rs @@ -111,10 +111,17 @@ struct Projector<'a> { context: &'a JavaScriptProjectionContext, known: &'a HashSet, plan: &'a WinRtImplementationPlan, - prefix: String, + interface: &'a InterfaceMeta, } impl Projector<'_> { + fn delegate_name(&self, index: usize) -> String { + self.context.implementation_helper_name( + self.interface, + &format!("delegate:{index}"), + &format!("ImplementationDelegate{index}"), + ) + } fn delegate_index(&self, typ: &TypeMeta) -> Option { self.plan .delegates @@ -216,8 +223,8 @@ impl Projector<'_> { fn annotation(&self, typ: &ImplementationType, writing: bool) -> String { if let Some(index) = self.delegate_index(&typ.metadata) { return format!( - "{}Delegate{index}{} | null", - self.prefix, + "{}{} | null", + self.delegate_name(index), if writing { " | DynWinRtValue" } else { "" } ); } @@ -307,7 +314,7 @@ impl Projector<'_> { fn read(&self, typ: &ImplementationType, value: &str) -> String { if let Some(index) = self.delegate_index(&typ.metadata) { - return format!("{}Delegate{index}({value})", self.prefix); + return format!("{}({value})", self.delegate_name(index)); } if let Some(inner) = ireference_inner_type(&typ.metadata) { let inner = validate_type(inner, false).expect("validated IReference value"); @@ -643,15 +650,15 @@ fn project_validated( context, known, plan, - prefix: format!("{}Implementation", iface.name), + interface: iface, }; let mut support = String::from(HELPERS); let mut declarations = String::new(); for (index, delegate) in plan.delegates.iter().enumerate() { let method = &delegate.invoke; declarations.push_str(&format!( - "export type {}Delegate{index} = (({}) => {}) & {{ readonly _obj: DynWinRtValue }};\n", - projector.prefix, + "export type {} = (({}) => {}) & {{ readonly _obj: DynWinRtValue }};\n", + projector.delegate_name(index), projector.parameters(method, true)?, projector.result_type(method, false)? )); @@ -697,12 +704,13 @@ fn project_validated( ), }; support.push_str(&format!( - "\nfunction {}Delegate{index}(value) {{\n if (value.isNull()) return null;\n const callback = (...args) => {{\n if (args.length !== {}) throw new TypeError('delegate argument count mismatch');\n const result = value.invokeDelegate({}, {}, [{args}]);\n return {returned};\n }};\n Object.defineProperty(callback, '_obj', {{ value }});\n return callback;\n}}\n", - projector.prefix, method.input_count, projector.iid(&delegate.typ), projector.signature(method) + "\nfunction {}(value) {{\n if (value.isNull()) return null;\n const callback = (...args) => {{\n if (args.length !== {}) throw new TypeError('delegate argument count mismatch');\n const result = value.invokeDelegate({}, {}, [{args}]);\n return {returned};\n }};\n Object.defineProperty(callback, '_obj', {{ value }});\n return callback;\n}}\n", + projector.delegate_name(index), method.input_count, projector.iid(&delegate.typ), projector.signature(method) )); } + let handler_type = context.implementation_helper_name(iface, "handlers", "Handlers"); declarations.push_str(&format!( - "\n/** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */\nexport interface {}Handlers {{\n", iface.name + "\n/** Synchronous owner-thread handlers. Out parameters precede the logical result; FillArray inputs are capacities. */\nexport interface {handler_type} {{\n" )); let mut handlers = HashSet::new(); let mut bindings = Vec::new(); @@ -786,12 +794,6 @@ fn project_validated( capacity.as_deref(), )); } - if outputs.is_empty() { - dispatch.push_str(&format!( - " if (result !== undefined) throw new TypeError({});\n", - quote(&format!("{label}: void handler must return undefined")) - )); - } dispatch.push_str(&format!( " return [{}];\n }}\n", outputs.join(", ") @@ -831,13 +833,11 @@ fn project_validated( "\n static fromImplementation(owner) {\n if (!(owner instanceof DynWinRtImplementation) && !(owner instanceof DynWinRtImplementationHandle)) throw new TypeError('fromImplementation requires a DynWinRtImplementation controller or handle');\n const value = owner.toValue();\n try {\n return this.from(value);\n } finally {\n value.release();\n }\n }\n", ); let factory_declarations = format!( - " /** Validate synchronous handlers and create an independent interface descriptor.{requirements} */\n static implementation(handlers: {name}Handlers): DynWinRtImplementationDescriptor;\n /** Create an instance with a stable typed value and explicit lifetime management.{requirements} */\n static implement(handlers: {name}Handlers, options: DynWinRtImplementationOptions): DynWinRtImplementationHandle<{name}>;\n static implement(handlers: {name}Handlers, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementationHandle<{name}>;\n /** Query an independent view, without consuming the handle's primary value. */\n static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): {name};\n", + " /** Validate synchronous handlers and create an independent interface descriptor.{requirements} */\n static implementation(handlers: {handler_type}): DynWinRtImplementationDescriptor;\n /** Create an instance with a stable typed value and explicit lifetime management.{requirements} */\n static implement(handlers: {handler_type}, options: DynWinRtImplementationOptions): DynWinRtImplementationHandle<{name}>;\n static implement(handlers: {handler_type}, ...additional: DynWinRtImplementationDescriptor[]): DynWinRtImplementationHandle<{name}>;\n /** Query an independent view, without consuming the handle's primary value. */\n static fromImplementation(owner: DynWinRtImplementation | DynWinRtImplementationHandle): {name};\n", name = iface.name ); - let exports = std::iter::once(format!("{}Handlers", iface.name)) - .chain( - (0..plan.delegates.len()).map(|index| format!("{}Delegate{index}", projector.prefix)), - ) + let exports = std::iter::once(handler_type) + .chain((0..plan.delegates.len()).map(|index| projector.delegate_name(index))) .collect(); Ok(ImplementationProjection { support_code: support, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs index 458d000f..1081f0d5 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/javascript/mod.rs @@ -20,8 +20,46 @@ use crate::types::{TypeKind, TypeMeta, TypeRef}; use serde::{Deserialize, Serialize}; use self::ir::ProjectedFile; +use super::shared::implementation_symbols::{HelperOwner, allocate_helpers}; +pub use super::shared::implementation_symbols::{ImplementationHelper, interface_helpers}; use super::shared::structs::{collect_used_structs_from_class, collect_used_structs_from_iface}; +pub fn implementation_helper_records(interface: &InterfaceMeta) -> Vec { + let context = JavaScriptProjectionContext::default(); + let projection = implementation::project(&context, interface, &Default::default()); + if projection.supported { + interface_helpers(interface, false) + } else { + Vec::new() + } +} + +pub fn implementation_reserved_symbols( + classes: &[ClassMeta], + interfaces: &[InterfaceMeta], +) -> BTreeSet { + classes + .iter() + .flat_map(collect_used_structs_from_class) + .chain(interfaces.iter().flat_map(collect_used_structs_from_iface)) + .filter_map(|typ| { + if let TypeMeta::Struct { name, .. } = typ { + Some(name) + } else { + None + } + }) + .flat_map(|name| { + [ + name.clone(), + format!("pack{name}"), + format!("unpack{name}"), + format!("{name}_Type"), + ] + }) + .collect() +} + #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[serde(rename_all = "lowercase")] pub enum JavaScriptTypeKind { @@ -110,6 +148,10 @@ pub struct JavaScriptTypeLayoutRecord { pub abi_identity: String, #[serde(default)] pub compatibility_aliases: BTreeSet, + #[serde(default)] + pub implementation_helpers: Vec, + #[serde(default)] + pub reserved_symbols: BTreeSet, } impl JavaScriptTypeLayoutRecord { @@ -125,6 +167,8 @@ impl JavaScriptTypeLayoutRecord { projected_name, abi_identity: abi_identity.into(), compatibility_aliases: BTreeSet::new(), + implementation_helpers: Vec::new(), + reserved_symbols: BTreeSet::new(), } } @@ -151,6 +195,21 @@ impl JavaScriptTypeLayoutRecord { .compatibility_aliases .iter() .all(|alias| is_metadata_identifier(alias)) + && self + .implementation_helpers + .iter() + .all(ImplementationHelper::is_valid) + && self + .implementation_helpers + .iter() + .map(|helper| &helper.key) + .collect::>() + .len() + == self.implementation_helpers.len() + && self + .reserved_symbols + .iter() + .all(|name| is_metadata_identifier(name)) } } @@ -184,6 +243,7 @@ struct JavaScriptModuleLayout { pub struct JavaScriptProjectionContext { layout: JavaScriptModuleLayout, runtime_import_name: String, + implementation_helpers: BTreeMap>, } impl Default for JavaScriptProjectionContext { @@ -194,6 +254,90 @@ impl Default for JavaScriptProjectionContext { } impl JavaScriptProjectionContext { + pub fn configure_implementation_helpers(&mut self, records: &[JavaScriptTypeLayoutRecord]) { + let owners = records.iter().filter_map(|record| { + let target = self.target_for_identity(&record.identity)?; + Some(HelperOwner { + identity: record.identity.to_inventory_line(), + projected_name: target.projected_name.clone(), + qualified_name: disambiguated_projected_name(&record.identity), + helpers: record.implementation_helpers.clone(), + }) + }); + let reserved = self.output_targets().flat_map(|target| { + [ + target.projected_name.clone(), + target.identity.name.clone(), + format!("IID_{}", target.projected_name), + format!("{}_PARAM_TYPES", target.projected_name), + ] + }); + self.implementation_helpers = allocate_helpers( + owners, + reserved.chain( + records + .iter() + .flat_map(|record| record.reserved_symbols.iter().cloned()), + ), + true, + ); + } + + pub fn implementation_helpers( + &self, + identity: &JavaScriptTypeIdentity, + ) -> &[ImplementationHelper] { + self.implementation_helpers + .get(&identity.to_inventory_line()) + .map_or(&[], Vec::as_slice) + } + + pub(crate) fn implementation_helper_name( + &self, + interface: &InterfaceMeta, + key: &str, + suffix: &str, + ) -> String { + let native = self.metadata_type_name(&interface.namespace, &interface.name); + let identity = JavaScriptTypeIdentity::new( + &interface.namespace, + native, + JavaScriptTypeKind::Interface, + ); + self.implementation_helpers(&identity) + .iter() + .find(|helper| helper.key == key) + .map_or_else( + || { + // Standalone projection callers still reserve the real metadata + // names, even when no incremental inventory is involved. + let owner = HelperOwner { + identity: identity.to_inventory_line(), + projected_name: interface.name.clone(), + qualified_name: disambiguated_projected_name(&identity), + helpers: interface_helpers(interface, false), + }; + let names = allocate_helpers( + [owner], + self.identities() + .map(|id| self.projected_name(&id.namespace, &id.name, id.kind)) + .chain(implementation_reserved_symbols( + &[], + std::slice::from_ref(interface), + )), + true, + ); + names + .get(&identity.to_inventory_line()) + .and_then(|helpers| helpers.iter().find(|helper| helper.key == key)) + .map_or_else( + || format!("{}{suffix}", interface.name), + |helper| helper.name.clone(), + ) + }, + |helper| helper.name.clone(), + ) + } pub fn runtime_import_name(&self) -> &str { &self.runtime_import_name } @@ -1156,13 +1300,17 @@ pub fn create_javascript_projection_context_with_records( .map(|(identity, projected)| (projected, identity)) .collect(); - Ok(JavaScriptProjectionContext { + let mut context = JavaScriptProjectionContext { layout: JavaScriptModuleLayout { targets, by_projected_name: projected_owners, }, runtime_import_name: runtime_import_name.into(), - }) + implementation_helpers: BTreeMap::new(), + }; + context + .configure_implementation_helpers(&previous_by_identity.into_values().collect::>()); + Ok(context) } fn apply_projected_type_names(context: &JavaScriptProjectionContext, typ: &mut TypeMeta) { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs index e08084b4..fe97adba 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs @@ -175,9 +175,26 @@ struct Projector<'a> { plan: &'a WinRtImplementationPlan, prefix: String, structs: Vec, + interface: &'a InterfaceMeta, } impl Projector<'_> { + fn delegate_name(&self, index: usize) -> String { + self.context.implementation_helper_name( + self.interface, + &format!("delegate:{index}"), + &format!("ImplementationDelegate{index}"), + ) + } + + fn delegate_result_name(&self, index: usize) -> String { + self.context.implementation_helper_name( + self.interface, + &format!("delegate-result:{index}"), + &format!("ImplementationDelegate{index}Result"), + ) + } + fn delegate_index(&self, typ: &TypeMeta) -> Option { self.plan .delegates @@ -271,8 +288,8 @@ impl Projector<'_> { fn annotation(&self, typ: &ImplementationType, writing: bool) -> String { if let Some(index) = self.delegate_index(&typ.metadata) { return format!( - "{}Delegate{index}{} | None", - self.prefix, + "{}{} | None", + self.delegate_name(index), if writing { " | DynWinRTValue" } else { "" } ); } @@ -346,7 +363,7 @@ impl Projector<'_> { fn read(&self, typ: &ImplementationType, value: &str) -> String { if let Some(index) = self.delegate_index(&typ.metadata) { - return format!("_{}Delegate{index}({value})", self.prefix); + return format!("_{}({value})", self.delegate_name(index)); } if let Some(inner) = ireference_inner_type(&typ.metadata) { let inner = validate_type(inner, false).expect("validated IReference value"); @@ -609,7 +626,11 @@ impl Projector<'_> { } fn result_name(&self, method: &ImplementationMethod) -> String { - format!("{}{}Result", self.prefix, method.name) + self.context.implementation_helper_name( + self.interface, + &format!("method-result:{}", method.vtable_index), + &format!("Implementation{}Result", method.name), + ) } fn result_type(&self, method: &ImplementationMethod, writing: bool) -> String { @@ -679,20 +700,20 @@ fn project_validated( plan, structs, prefix: format!("{}Implementation", iface.name), + interface: iface, }; let mut support = String::from(HELPER_IMPORTS); let mut declarations = String::new(); let mut result_names = HashSet::new(); - for (result_name, method) in plan - .methods - .iter() - .map(|method| (projector.result_name(method), method)) - .chain(plan.delegates.iter().enumerate().map(|(index, delegate)| { - ( - format!("{}Delegate{index}Result", projector.prefix), - &delegate.invoke, + for (result_name, method) in + plan.methods + .iter() + .map(|method| (projector.result_name(method), method)) + .chain( + plan.delegates.iter().enumerate().map(|(index, delegate)| { + (projector.delegate_result_name(index), &delegate.invoke) + }), ) - })) { if method.output_count > 1 { if !result_names.insert(result_name.clone()) { @@ -775,8 +796,8 @@ fn project_validated( let params = projector.parameters(method, true)?; let comma = if params.is_empty() { "" } else { ", " }; declarations.push_str(&format!( - "\nclass {}Delegate{index}(Protocol):\n @property\n def _obj(self) -> DynWinRTValue: ...\n def __call__(self{comma}{params}, /) -> {}: ...\n", - projector.prefix, if method.output_count > 1 { format!("{}Delegate{index}Result", projector.prefix) } else { projector.result_type(method, false) } + "\nclass {}(Protocol):\n @property\n def _obj(self) -> DynWinRTValue: ...\n def __call__(self{comma}{params}, /) -> {}: ...\n", + projector.delegate_name(index), if method.output_count > 1 { projector.delegate_result_name(index) } else { projector.result_type(method, false) } )); let args = method .parameters @@ -820,12 +841,13 @@ fn project_validated( ), }; support.push_str(&format!( - "\ndef _{}Delegate{index}(value):\n if value.is_null():\n return None\n def callback(*args):\n if len(args) != {}:\n raise TypeError('delegate argument count mismatch')\n result = value.invoke_delegate({}, {}, [{args}])\n return {returned}\n callback._obj = value\n return callback\n\n", - projector.prefix, method.input_count, projector.iid(&delegate.typ), projector.signature(method) + "\ndef _{}(value):\n if value.is_null():\n return None\n def callback(*args):\n if len(args) != {}:\n raise TypeError('delegate argument count mismatch')\n result = value.invoke_delegate({}, {}, [{args}])\n return {returned}\n callback._obj = value\n return callback\n\n", + projector.delegate_name(index), method.input_count, projector.iid(&delegate.typ), projector.signature(method) )); } + let handler_type = context.implementation_helper_name(iface, "handlers", "Handlers"); declarations.push_str(&format!( - "\nclass {}Handlers(Protocol):\n \"\"\"Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.\"\"\"\n", iface.name + "\nclass {handler_type}(Protocol):\n \"\"\"Synchronous handlers; multi-output results are named dicts and FillArray inputs are capacities.\"\"\"\n" )); let mut handlers = HashSet::new(); let mut bindings = Vec::new(); @@ -932,10 +954,8 @@ fn project_validated( bindings.push(" if not callable(getattr(DynWinRTValue, 'invoke_delegate', None)):\n raise TypeError('this interface requires WinRT delegate invocation support in the runtime')".into()); } let mut factory_body = format!( - " @staticmethod\n def implementation(handlers: {}Handlers) -> DynWinRTImplementationDescriptor:\n{}\n plan = _get_implementation_plan()\n def dispatch(vtable_index, args):\n if not isinstance(args, list):\n raise TypeError('implementation arguments must be a list')\n{dispatch} raise ValueError('unknown implementation vtable slot')\n return DynWinRTImplementationDescriptor(plan, dispatch)\n\n @classmethod\n def implement(cls, handlers: {}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces=()) -> DynWinRTImplementationHandle:\n return DynWinRTImplementationHandle._create(cls, handlers, additional, interfaces)\n\n", - iface.name, - bindings.join("\n"), - iface.name + " @staticmethod\n def implementation(handlers: {handler_type}) -> DynWinRTImplementationDescriptor:\n{}\n plan = _get_implementation_plan()\n def dispatch(vtable_index, args):\n if not isinstance(args, list):\n raise TypeError('implementation arguments must be a list')\n{dispatch} raise ValueError('unknown implementation vtable slot')\n return DynWinRTImplementationDescriptor(plan, dispatch)\n\n @classmethod\n def implement(cls, handlers: {handler_type}, *additional: DynWinRTImplementationDescriptor, interfaces=()) -> DynWinRTImplementationHandle:\n return DynWinRTImplementationHandle._create(cls, handlers, additional, interfaces)\n\n", + bindings.join("\n") ); factory_body.push_str(&format!( " @classmethod\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle) -> '{}':\n \"\"\"Query an independently owned view, tracked by the current lifetime scope.\"\"\"\n if not isinstance(owner, (DynWinRTImplementation, DynWinRTImplementationHandle)):\n raise TypeError('from_implementation requires a DynWinRTImplementation controller or handle')\n value = owner.to_value()\n try:\n native = value.cast(IID_{})\n try:\n view = object.__new__(cls)\n cls._set_native(view, native, cache=False)\n return view\n except BaseException:\n native.release()\n raise\n finally:\n value.release()\n\n", @@ -960,20 +980,18 @@ fn project_validated( }; let package_overload = if context.is_packaged() { format!( - " @overload\n def implement(cls, handlers: {name}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[_PackageImplementationPair]) -> DynWinRTImplementationHandle[{name}]: ...\n @overload\n", + " @overload\n def implement(cls, handlers: {handler_type}, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[_PackageImplementationPair]) -> DynWinRTImplementationHandle[{name}]: ...\n @overload\n", name = iface.name ) } else { String::new() }; let factory_declarations = format!( - "{requirements} def implementation(cls, handlers: {name}Handlers) -> DynWinRTImplementationDescriptor: ...\n{package_overload} def implement(cls, handlers: {name}Handlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[{name}]: ...\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> {name}: ...\n\n", + "{requirements} def implementation(cls, handlers: {handler_type}) -> DynWinRTImplementationDescriptor: ...\n{package_overload} def implement(cls, handlers: {handler_type}, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[{name}]: ...\n def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> {name}: ...\n\n", name = iface.name ); - let mut exports = vec![format!("{}Handlers", iface.name)]; - exports.extend( - (0..plan.delegates.len()).map(|index| format!("{}Delegate{index}", projector.prefix)), - ); + let mut exports = vec![handler_type]; + exports.extend((0..plan.delegates.len()).map(|index| projector.delegate_name(index))); exports.extend(result_names); exports.sort(); Ok(ImplementationProjection { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs index 78924041..84a04006 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs @@ -16,7 +16,28 @@ pub(crate) mod stub_helpers; pub mod stubs; pub(crate) mod type_helpers; +pub use super::shared::implementation_symbols::ImplementationHelper; pub use generator::*; +pub fn implementation_helper_records( + context: &PythonProjectionContext, + interface: &crate::meta::InterfaceMeta, +) -> Vec { + let mut projected = interface.clone(); + projected.name = context.projected_name_for_interface(interface); + let projection = implementation::project(context, &projected); + if !projection.supported { + return Vec::new(); + } + super::shared::implementation_symbols::interface_helpers(&projected, true) + .into_iter() + .map(|mut helper| { + helper.name = + context.implementation_helper_name(&projected, &helper.key, &helper.suffix); + helper.implementation_name = helper.name.clone(); + helper + }) + .collect() +} pub use naming::{ PythonProjectionContext, PythonTypeIdentity, python_identity_display_name, python_namespace_segments, python_public_module_name, python_public_qualified_module_name, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 26421f42..8dad5c5c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -5,6 +5,9 @@ use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use super::super::shared::implementation_symbols::{ + HelperOwner, ImplementationHelper, allocate_helpers, interface_helpers, +}; use crate::meta::InterfaceMeta; use crate::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; @@ -399,6 +402,7 @@ pub struct PythonProjectionContext { projections: HashMap, aliases: HashMap, compatibility_counts: HashMap, + implementation_helpers: BTreeMap>, } impl PythonProjectionContext { @@ -521,6 +525,7 @@ impl PythonProjectionContext { projections, aliases, compatibility_counts, + implementation_helpers: BTreeMap::new(), }) } @@ -547,6 +552,81 @@ impl PythonProjectionContext { self.packaged } + pub fn configure_implementation_helpers( + &mut self, + owners: impl IntoIterator)>, + ) { + let owners = owners + .into_iter() + .map(|(identity, helpers)| HelperOwner { + identity: identity.canonical_key(), + projected_name: self.projected_name(&identity), + qualified_name: semantic_qualifier(&identity), + helpers, + }) + .collect::>(); + let reserved = self.projections.iter().flat_map(|(identity, projection)| { + [ + projection.projected_name.clone(), + projection.reference_name.clone(), + legacy_projected_name(identity), + format!("IID_{}", projection.projected_name), + ] + }); + self.implementation_helpers = allocate_helpers(owners, reserved, false); + } + + pub fn implementation_helpers(&self, identity: &PythonTypeIdentity) -> &[ImplementationHelper] { + self.implementation_helpers + .get(&self.normalize_identity(identity).canonical_key()) + .map_or(&[], Vec::as_slice) + } + + pub(crate) fn implementation_helper_name( + &self, + interface: &InterfaceMeta, + key: &str, + suffix: &str, + ) -> String { + let identity = self + .projections + .iter() + .find(|(identity, projection)| { + identity.namespace() == Some(interface.namespace.as_str()) + && projection.projected_name == interface.name + }) + .map_or_else( + || interface.type_identity(), + |(identity, _)| identity.clone(), + ); + if let Some(helper) = self + .implementation_helpers(&identity) + .iter() + .find(|helper| helper.key == key) + { + return helper.name.clone(); + } + let names = allocate_helpers( + [HelperOwner { + identity: identity.canonical_key(), + projected_name: interface.name.clone(), + qualified_name: semantic_qualifier(&identity), + helpers: interface_helpers(interface, true), + }], + self.projections + .values() + .map(|projection| projection.projected_name.clone()), + false, + ); + names + .get(&identity.canonical_key()) + .and_then(|helpers| helpers.iter().find(|helper| helper.key == key)) + .map_or_else( + || format!("{}{suffix}", interface.name), + |helper| helper.name.clone(), + ) + } + pub fn normalize_identity(&self, identity: &PythonTypeIdentity) -> PythonTypeIdentity { let identity = match identity { TypeIdentity::ClosedGeneric { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index f49c6f61..da426290 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -393,8 +393,8 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf if implementation.supported { if context.is_packaged() { out.push_str(&format!( - "\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{name}Handlers], {name}Handlers]\n", - name = iface.name + "\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{handler}], {handler}]\n", + handler = context.implementation_helper_name(iface, "handlers", "Handlers") )); } out.push_str(&format!("\nclass {implementation_metaclass}(ABCMeta):\n")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation_symbols.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation_symbols.rs new file mode 100644 index 00000000..287ffb5a --- /dev/null +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/implementation_symbols.rs @@ -0,0 +1,165 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Public projection helpers have identities owned by an interface, not by the +//! spelling of its current alias. Metadata types always reserve their names first. + +use std::collections::{BTreeMap, BTreeSet}; + +use serde::{Deserialize, Serialize}; + +use crate::meta::InterfaceMeta; + +use super::implementation::project_implementation; + +#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] +pub struct ImplementationHelper { + pub key: String, + pub suffix: String, + pub name: String, + pub implementation_name: String, +} + +impl ImplementationHelper { + pub fn is_valid(&self) -> bool { + let identifier = |value: &str| { + !value.is_empty() + && value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + && !value.as_bytes()[0].is_ascii_digit() + }; + !self.key.is_empty() + && identifier(&self.suffix) + && identifier(&self.name) + && identifier(&self.implementation_name) + } + + fn new(owner: &str, key: impl Into, suffix: impl Into) -> Self { + let suffix = suffix.into(); + let name = format!("{owner}{suffix}"); + Self { + key: key.into(), + suffix, + implementation_name: name.clone(), + name, + } + } + + /// Upgrade the previous generator's explicitly exported helper metadata. + /// This recognizes projection names only; it never infers a native contract. + pub fn legacy_javascript(owner: &str, symbol: &str) -> Option { + let suffix = symbol.strip_prefix(owner)?; + let key = if suffix == "Handlers" { + "handlers".into() + } else if let Some(index) = suffix.strip_prefix("ImplementationDelegate") { + if index.is_empty() || !index.bytes().all(|byte| byte.is_ascii_digit()) { + return None; + } + format!("delegate:{index}") + } else { + return None; + }; + Some(Self::new(owner, key, suffix)) + } +} + +pub fn interface_helpers(interface: &InterfaceMeta, python: bool) -> Vec { + let Ok(plan) = project_implementation(interface) else { + return Vec::new(); + }; + let owner = &interface.name; + let mut helpers = vec![ImplementationHelper::new(owner, "handlers", "Handlers")]; + for (index, delegate) in plan.delegates.iter().enumerate() { + helpers.push(ImplementationHelper::new( + owner, + format!("delegate:{index}"), + format!("ImplementationDelegate{index}"), + )); + if python && delegate.invoke.output_count > 1 { + helpers.push(ImplementationHelper::new( + owner, + format!("delegate-result:{index}"), + format!("ImplementationDelegate{index}Result"), + )); + } + } + if python { + for method in &plan.methods { + if method.output_count > 1 { + helpers.push(ImplementationHelper::new( + owner, + format!("method-result:{}", method.vtable_index), + format!("Implementation{}Result", method.name), + )); + } + } + } + helpers +} + +pub struct HelperOwner { + pub identity: String, + pub projected_name: String, + pub qualified_name: String, + pub helpers: Vec, +} + +pub fn allocate_helpers( + owners: impl IntoIterator, + reserved: impl IntoIterator, + case_insensitive: bool, +) -> BTreeMap> { + let normalize = |s: &str| { + if case_insensitive { + s.to_ascii_lowercase() + } else { + s.into() + } + }; + let mut occupied = reserved + .into_iter() + .map(|s| normalize(&s)) + .collect::>(); + let mut owners = owners + .into_iter() + .map(|owner| (owner.identity.clone(), owner)) + .collect::>(); + let mut preferred_counts = BTreeMap::::new(); + for owner in owners.values() { + for helper in &owner.helpers { + *preferred_counts + .entry(normalize(&format!( + "{}{}", + owner.projected_name, helper.suffix + ))) + .or_default() += 1; + } + } + let mut result = BTreeMap::new(); + for (identity, owner) in &mut owners { + owner.helpers.sort_by(|a, b| a.key.cmp(&b.key)); + owner.helpers.dedup_by(|a, b| a.key == b.key); + for helper in &mut owner.helpers { + let preferred = format!("{}{}", owner.projected_name, helper.suffix); + let mut name = preferred; + if preferred_counts[&normalize(&name)] > 1 || occupied.contains(&normalize(&name)) { + name = format!("{}{}Helper", owner.qualified_name, helper.suffix); + } + if occupied.contains(&normalize(&name)) { + let mut hash = 0xcbf29ce484222325u64; + for byte in format!("{identity}|{}", helper.key).bytes() { + hash = (hash ^ u64::from(byte)).wrapping_mul(0x100000001b3); + } + name = format!("{name}_{hash:016x}"); + while occupied.contains(&normalize(&name)) { + name.push('_'); + } + } + occupied.insert(normalize(&name)); + helper.name = name; + } + result.insert(identity.clone(), owner.helpers.clone()); + } + result +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs index df2a0f9b..a6ad4763 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/mod.rs @@ -3,5 +3,6 @@ pub(crate) mod docs; pub(crate) mod implementation; +pub(crate) mod implementation_symbols; pub(crate) mod imports; pub(crate) mod structs; diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 169a6ccd..fa839d4f 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -1222,11 +1222,17 @@ fn generate_for_types( .iter() .chain(current_javascript_records.iter()) .map(|record| record.identity.clone()); - let context = javascript::create_javascript_projection_context_with_records( + let mut context = javascript::create_javascript_projection_context_with_records( identities, previous_javascript_records.iter().cloned(), runtime_import_name, )?; + let helper_records = previous_javascript_records + .iter() + .chain(current_javascript_records.iter()) + .map(|record| (record.identity.clone(), record.clone())) + .collect::>(); + context.configure_implementation_helpers(&helper_records.into_values().collect::>()); let projected_names = context .output_targets() .into_iter() @@ -1241,7 +1247,11 @@ fn generate_for_types( .filter(|record| { projected_names .get(&record.identity) - .is_some_and(|projected| projected != &record.projected_name) + .is_some_and(|projected| { + projected != &record.projected_name + || context.implementation_helpers(&record.identity) + != record.implementation_helpers + }) && !current_identities.contains(&record.identity) }) .cloned() @@ -1434,18 +1444,59 @@ fn generate_for_types( if !dry_run { if lang == "py" { + let upgrades = if pyi { + migrate_python_implementation_inventory( + winmd, + output_dir, + &all_classes, + &emittable_interfaces, + &shared_interfaces, + )? + } else { + Vec::new() + }; + let mut python_interfaces = emittable_interfaces.clone(); + let mut python_shared = shared_interfaces.clone(); + for (interface, public) in &upgrades { + if !python_interfaces + .iter() + .chain(&python_shared) + .any(|current| current.type_identity() == interface.type_identity()) + { + if *public { + python_interfaces.push(interface.clone()); + } else { + python_shared.push(interface.clone()); + } + } + } generate_py_files( python_context .as_ref() .expect("Python generation context must be available"), output_dir, &all_classes, - &emittable_interfaces, + &python_interfaces, &all_enums, - &shared_interfaces, + &python_shared, &shared_iids, pyi, )?; + let public_upgrades = upgrades + .into_iter() + .filter_map(|(interface, public)| public.then_some(interface)) + .collect::>(); + if !public_upgrades.is_empty() { + write_python_package_indexes( + output_dir, + &[], + &public_upgrades, + &[], + &meta::ambiguous_named_type_names(winmd), + pyi, + true, + )?; + } } else { let mut plan = generate_js_files( javascript_context.as_ref().expect("JavaScript context"), @@ -1528,6 +1579,11 @@ fn python_generation_context( let mut identities = python_type_identities(classes, interfaces, enums); identities.extend(python_type_identities(&[], supplemental_interfaces, &[])); identities.extend_from_slice(existing_identities); + let class_names = classes + .iter() + .map(|class| (class.namespace.clone(), class.name.clone())) + .collect(); + identities.retain(|identity| !python_type_shadowed_by_class(identity, &class_names)); python::PythonProjectionContext::packaged_with_ambiguities( identities, meta::ambiguous_named_type_names(winmd), @@ -1689,7 +1745,11 @@ fn javascript_type_layout_records( } else { javascript::JavaScriptTypeIdentity::new(&interface.namespace, &interface.name, kind) }; - record(identity, abi_identity) + let mut record = record(identity, abi_identity); + record.implementation_helpers = javascript::implementation_helper_records(interface); + record.reserved_symbols = + javascript::implementation_reserved_symbols(&[], std::slice::from_ref(interface)); + record }; let class_identities = classes .iter() @@ -1708,14 +1768,17 @@ fn javascript_type_layout_records( let mut records = classes .iter() .map(|class| { - record( + let mut record = record( javascript::JavaScriptTypeIdentity::new( &class.namespace, &class.name, javascript::JavaScriptTypeKind::Class, ), "type".into(), - ) + ); + record.reserved_symbols = + javascript::implementation_reserved_symbols(std::slice::from_ref(class), &[]); + record }) .collect::>(); records.extend( @@ -1792,12 +1855,13 @@ fn read_javascript_type_inventory(output_dir: &Path) -> Result(&content).map_err(|error| { - format!( - "Invalid JavaScript type inventory {}: {error}", - path.display() - ) - })?; + let mut inventory = + serde_json::from_str::(&content).map_err(|error| { + format!( + "Invalid JavaScript type inventory {}: {error}", + path.display() + ) + })?; if inventory.version != JAVASCRIPT_TYPE_INVENTORY_VERSION { return Err(format!( "Unsupported or invalid JavaScript type inventory in {}", @@ -1806,9 +1870,59 @@ fn read_javascript_type_inventory(output_dir: &Path) -> Result Result<(), String> { + let path = output_dir.join("index.d.ts"); + if !path.is_file() { + return Ok(()); + } + let index = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + let context = javascript::create_javascript_projection_context( + records.iter().map(|record| record.identity.clone()), + )?; + let exports = index + .lines() + .filter_map(|line| line.strip_prefix("export type ")) + .filter_map(|line| parse_root_export_metadata(&format!("export {line}"))) + .collect::>(); + for record in records + .iter_mut() + .filter(|record| record.implementation_helpers.is_empty()) + { + let target = context + .target_for_identity(&record.identity) + .expect("inventory identity"); + for symbol in exports + .iter() + .filter(|(_, module)| module == &target.canonical_module) + .flat_map(|(names, _)| names) + { + let helper = javascript::ImplementationHelper::legacy_javascript( + &record.implementation_name, + symbol, + ) + .or_else(|| { + javascript::ImplementationHelper::legacy_javascript(&record.projected_name, symbol) + }) + .ok_or_else(|| { + format!( + "Unknown retained implementation helper {symbol} in {}", + path.display() + ) + })?; + record.implementation_helpers.push(helper); + } + } + Ok(()) +} + fn validate_javascript_inventory_files( output_dir: &Path, records: &[javascript::JavaScriptTypeLayoutRecord], @@ -2074,9 +2188,6 @@ fn write_retained_javascript_projected_aliases( record.identity.namespace, record.identity.name ) })?; - if target.projected_name == record.implementation_name { - continue; - } let js_path = output_dir.join(format!("{}.js", target.canonical_module)); let dts_path = output_dir.join(format!("{}.d.ts", target.canonical_module)); let mut js = fs::read_to_string(&js_path) @@ -2085,7 +2196,9 @@ fn write_retained_javascript_projected_aliases( .map_err(|error| format!("Failed to read {}: {error}", dts_path.display()))?; let implementation = &record.implementation_name; let new = &target.projected_name; - if record.identity.kind == javascript::JavaScriptTypeKind::Delegate { + if target.projected_name != record.implementation_name + && record.identity.kind == javascript::JavaScriptTypeKind::Delegate + { if !js.contains(&format!("exports.IID_{implementation} =")) { return Err(format!( "Retained delegate module '{}' does not export IID_{implementation}", @@ -2107,7 +2220,7 @@ fn write_retained_javascript_projected_aliases( export type {new} = {implementation};\n" ), ); - } else { + } else if target.projected_name != record.implementation_name { if !js.contains(&format!("exports.{implementation} =")) { return Err(format!( "Retained JavaScript module '{}' does not export `{implementation}`", @@ -2133,6 +2246,24 @@ fn write_retained_javascript_projected_aliases( ); } } + for helper in context.implementation_helpers(&record.identity) { + let Some(previous) = record + .implementation_helpers + .iter() + .find(|previous| previous.key == helper.key) + else { + continue; + }; + if helper.name != previous.implementation_name { + append( + &mut dts, + format!( + "export type {{ {} as {} }};\n", + previous.implementation_name, helper.name + ), + ); + } + } ensure_safe_generated_destination(output_dir, &js_path)?; ensure_safe_generated_destination(output_dir, &dts_path)?; fs::write(&js_path, js) @@ -2209,13 +2340,27 @@ fn emitted_javascript_type_records( ) })? }; - Ok(javascript::JavaScriptTypeLayoutRecord::new( + let mut record = javascript::JavaScriptTypeLayoutRecord::new( target.identity.clone(), target.projected_name.clone(), abi_identity, ) .with_implementation_name(implementation_name) - .with_compatibility_aliases(compatibility_aliases)) + .with_compatibility_aliases(compatibility_aliases); + record.implementation_helpers = + context.implementation_helpers(&target.identity).to_vec(); + record.reserved_symbols = current + .iter() + .chain(previous) + .find(|record| record.identity == target.identity) + .map(|record| record.reserved_symbols.clone()) + .unwrap_or_default(); + if current_identities.contains(&target.identity) { + for helper in &mut record.implementation_helpers { + helper.implementation_name = helper.name.clone(); + } + } + Ok(record) }) .collect() } @@ -2414,6 +2559,13 @@ fn load_effective_generation_plan( } module.primary_export = Some(target.projected_name.clone()); } + if !module.public_type_exports.is_empty() { + module.public_type_exports = context + .implementation_helpers(&target.identity) + .iter() + .map(|helper| helper.name.clone()) + .collect(); + } module.compatibility_aliases = target.compatibility_aliases.clone(); } Ok(plan) @@ -3775,6 +3927,65 @@ fn generate_py_files( ) -> Result<(), String> { use dynwinrt_codegen::codegen::python_stub; + let previous = read_python_type_inventory(output_dir)?; + let mut struct_interfaces = all_interfaces.to_vec(); + struct_interfaces.extend_from_slice(shared_interfaces); + let mut current = python_generated_types(all_classes, &struct_interfaces, all_enums); + let public_interfaces = all_interfaces + .iter() + .map(meta::InterfaceMeta::type_identity) + .collect::>(); + for typ in &mut current { + if let Some(item) = &mut typ.implementation { + item.pair_eligible = public_interfaces.contains(&typ.identity); + } + } + let mut types = merge_python_generated_types(previous.clone(), current.clone()); + let mut configured = context.clone(); + configured.configure_implementation_helpers(types.iter().map(|typ| { + ( + typ.identity.clone(), + typ.implementation + .as_ref() + .map_or_else(Vec::new, |item| item.helpers.clone()), + ) + })); + let context = &configured; + let current_identities = current + .iter() + .map(|typ| typ.identity.clone()) + .collect::>(); + if pyi { + let missing = types + .iter() + .filter(|typ| !current_identities.contains(&typ.identity)) + .filter(|typ| { + !output_dir + .join(format!( + "{}.pyi", + context.implementation_module(&typ.identity) + )) + .is_file() + }) + .map(|typ| python::python_identity_display_name(&typ.identity)) + .collect::>(); + if !missing.is_empty() { + return Err(format!( + "Typed incremental generation requires retained .pyi modules for: {}. Regenerate those types with their original WinMD/--ref inputs as part of this request, or fully regenerate the package; --no-pyi keeps runtime-only generation available. Existing output has not been replaced.", + missing.join(", ") + )); + } + } + update_python_helper_layout(context, &mut types, ¤t_identities); + reconcile_retained_python_helpers( + context, + output_dir, + &previous, + &types, + ¤t_identities, + pyi, + )?; + write_file( &output_dir.join("_runtime.py"), &python::generate_runtime_support_module(), @@ -3791,8 +4002,6 @@ fn generate_py_files( } let mut generated_modules = HashSet::new(); - let mut struct_interfaces = all_interfaces.to_vec(); - struct_interfaces.extend_from_slice(shared_interfaces); let structs = python::package_structs(all_classes, &struct_interfaces); // A runtime class owns its public identity when metadata also exposes an @@ -3875,45 +4084,24 @@ fn generate_py_files( } } if pyi { - write_python_implementation_pair_types(output_dir)?; + write_python_implementation_pair_types(output_dir, &types)?; let marker = output_dir.join("py.typed"); write_file(&marker, "")?; } + write_python_type_inventory(output_dir, &types)?; Ok(()) } -fn write_python_implementation_pair_types(output_dir: &Path) -> Result<(), String> { - // Include retained stubs too: incremental generation must keep the complete - // package union. Only the validated interface projection emits this alias; - // classes, unsupported interfaces, delegates and user stubs contribute none. - let mut modules = BTreeSet::new(); - for entry in fs::read_dir(output_dir) - .map_err(|error| format!("Failed to read {}: {error}", output_dir.display()))? - { - let entry = entry.map_err(|error| format!("Failed to read Python module: {error}"))?; - let path = entry.path(); - let metadata = fs::symlink_metadata(&path) - .map_err(|error| format!("Failed to inspect {}: {error}", path.display()))?; - if !metadata.is_file() - || is_link_or_reparse_point(&metadata) - || path.extension().is_none_or(|extension| extension != "pyi") - { - continue; - } - let content = fs::read_to_string(&path) - .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; - if content.starts_with(GENERATED_PYTHON_HEADER) - && content - .lines() - .any(|line| line.starts_with("_ImplementationPair: TypeAlias = tuple[")) - { - let module = path - .file_stem() - .and_then(|stem| stem.to_str()) - .ok_or_else(|| format!("Invalid Python module path {}", path.display()))?; - modules.insert(module.to_string()); - } - } +fn write_python_implementation_pair_types( + output_dir: &Path, + types: &[PythonGeneratedType], +) -> Result<(), String> { + let modules = types + .iter() + .filter_map(|typ| typ.implementation.as_ref()) + .filter(|item| item.pair_eligible) + .map(|item| item.module.clone()) + .collect::>(); write_file( &output_dir.join("_implementation_types.pyi"), &dynwinrt_codegen::codegen::python_stub::generate_implementation_pair_types( @@ -3934,6 +4122,306 @@ struct PythonNamespaceGroup { struct PythonGeneratedType { kind: String, identity: python::PythonTypeIdentity, + #[serde(default = "legacy_python_inventory_version")] + schema_version: u32, + #[serde(default, skip_serializing_if = "Option::is_none")] + implementation: Option, +} + +fn legacy_python_inventory_version() -> u32 { + 1 +} + +#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] +struct PythonImplementationInventory { + module: String, + interface_export: String, + handler_export: String, + helpers: Vec, + pair_eligible: bool, +} + +fn merge_python_generated_types( + previous: Vec, + current: Vec, +) -> Vec { + let class_names = current + .iter() + .filter(|typ| typ.kind == "class") + .filter_map(|typ| { + Some(( + typ.identity.namespace()?.to_string(), + typ.identity.definition_name()?.to_string(), + )) + }) + .collect(); + previous + .into_iter() + .chain(current) + .filter(|typ| !python_type_shadowed_by_class(&typ.identity, &class_names)) + .map(|typ| (typ.identity.clone(), typ)) + .collect::>() + .into_values() + .collect() +} + +fn python_type_shadowed_by_class( + identity: &TypeIdentity, + classes: &HashSet<(String, String)>, +) -> bool { + matches!(identity, TypeIdentity::Named { kind: TypeIdentityKind::Interface | TypeIdentityKind::Enum, namespace, name } + if classes.contains(&(namespace.clone(), name.clone()))) +} + +fn update_python_helper_layout( + context: &python::PythonProjectionContext, + types: &mut [PythonGeneratedType], + regenerated: &HashSet, +) { + for typ in types { + if let Some(item) = &mut typ.implementation { + item.module = context.implementation_module(&typ.identity); + item.interface_export = context.projected_name(&typ.identity); + item.helpers = context.implementation_helpers(&typ.identity).to_vec(); + if regenerated.contains(&typ.identity) { + for helper in &mut item.helpers { + helper.implementation_name = helper.name.clone(); + } + } + item.handler_export = item + .helpers + .iter() + .find(|helper| helper.key == "handlers") + .expect("validated implementation has handlers") + .name + .clone(); + } + } +} + +fn migrate_python_implementation_inventory( + winmd: &str, + output_dir: &Path, + classes: &[meta::ClassMeta], + interfaces: &[meta::InterfaceMeta], + supplemental: &[meta::InterfaceMeta], +) -> Result, String> { + let mut types = read_python_type_inventory(output_dir)?; + let class_names = classes + .iter() + .map(|class| (class.namespace.clone(), class.name.clone())) + .collect(); + types.retain(|typ| !python_type_shadowed_by_class(&typ.identity, &class_names)); + if !types.iter().any(|typ| typ.schema_version == 1) { + return Ok(Vec::new()); + } + let context = python::PythonProjectionContext::packaged_with_ambiguities( + types.iter().map(|typ| typ.identity.clone()), + meta::ambiguous_named_type_names(winmd), + )?; + let mut available = interfaces + .iter() + .chain(supplemental) + .cloned() + .map(|interface| (interface.type_identity(), interface)) + .collect::>(); + let namespaces = types + .iter() + .filter(|typ| typ.schema_version == 1 && typ.kind == "interface") + .filter_map(|typ| typ.identity.namespace()) + .collect::>(); + for namespace in namespaces { + for interface in meta::parse_interfaces(winmd, namespace) { + available.insert(interface.type_identity(), interface); + } + } + // Some emitted interfaces originate in a runtime class's required set and + // intentionally cannot be selected through the public namespace parser. + for typ in types.iter().filter(|typ| typ.kind == "class") { + let Some(class) = meta::parse_class( + winmd, + typ.identity.namespace().unwrap_or_default(), + typ.identity.definition_name().unwrap_or_default(), + ) else { + continue; + }; + for interface in class.required_interfaces { + available.insert(interface.type_identity(), interface); + } + } + let mut missing = Vec::new(); + let mut upgrades = Vec::new(); + for typ in &mut types { + if typ.schema_version != 1 { + continue; + } + if matches!( + typ.identity, + TypeIdentity::Named { + kind: TypeIdentityKind::Interface, + .. + } + ) { + if let Some(interface) = available.get(&typ.identity) { + let facade = context + .public_qualified_module(&typ.identity) + .replace('.', "\\"); + let public = output_dir.join(format!("{facade}.py")).is_file(); + upgrades.push((interface.clone(), public)); + typ.implementation = python_interface_implementation_inventory(&context, interface); + if let Some(item) = &mut typ.implementation { + item.pair_eligible = public; + // Version 1 always used these original helper spellings. + // Recover from metadata, never by parsing rendered stubs. + for helper in &mut item.helpers { + helper.name = format!("{}{}", item.interface_export, helper.suffix); + helper.implementation_name = helper.name.clone(); + } + item.handler_export = format!("{}Handlers", item.interface_export); + } + } else { + missing.push(python::python_identity_display_name(&typ.identity)); + continue; + } + } + typ.schema_version = 2; + } + if !missing.is_empty() { + return Err(format!( + "Python implementation inventory v1 needs original metadata for: {}. Supply the original WinMD/--ref inputs and retry, or fully regenerate the package. Existing output has not been replaced.", + missing.join(", ") + )); + } + write_python_type_inventory(output_dir, &types)?; + Ok(upgrades) +} + +fn reconcile_retained_python_helpers( + context: &python::PythonProjectionContext, + output_dir: &Path, + previous: &[PythonGeneratedType], + current: &[PythonGeneratedType], + regenerated: &HashSet, + pyi: bool, +) -> Result<(), String> { + for typ in current + .iter() + .filter(|typ| !regenerated.contains(&typ.identity)) + { + let Some(item) = &typ.implementation else { + continue; + }; + let Some(old) = previous + .iter() + .find(|old| old.identity == typ.identity) + .and_then(|old| old.implementation.as_ref()) + else { + continue; + }; + if old.helpers == item.helpers { + continue; + } + for extension in if pyi { &["py", "pyi"][..] } else { &["py"][..] } { + let path = output_dir.join(format!("{}.{}", item.module, extension)); + let mut source = fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))?; + for helper in &item.helpers { + let Some(original) = old.helpers.iter().find(|old| old.key == helper.key) else { + continue; + }; + if helper.name != original.implementation_name { + let alias = format!("\n{} = {}\n", helper.name, original.implementation_name); + if !source.contains(&alias) { + source.push_str(&alias); + } + } + } + write_file(&path, &source)?; + } + if !item.pair_eligible { + continue; + } + let namespace = typ.identity.namespace().expect("named interface"); + let segments = python::python_namespace_segments(namespace); + let mut directory = output_dir.to_path_buf(); + for segment in &segments { + directory.push(segment); + } + let implementation_index = format!( + "from .{} import IID_{}, {}\n{}", + item.module, + item.interface_export, + item.interface_export, + item.helpers + .iter() + .map(|helper| format!("from .{} import {}\n", item.module, helper.name)) + .collect::() + ); + let mut runtime_exports = Vec::new(); + write_python_facade( + context, + &directory, + &segments, + &typ.identity, + &item.interface_export, + &implementation_index, + "py", + &mut runtime_exports, + )?; + let mut stub_exports = Vec::new(); + if pyi { + write_python_facade( + context, + &directory, + &segments, + &typ.identity, + &item.interface_export, + &implementation_index, + "pyi", + &mut stub_exports, + )?; + } + write_python_lazy_root_index( + &directory.join("__init__.py"), + &format!("{GENERATED_PYTHON_HEADER}{}", runtime_exports.join("\n")), + true, + &HashSet::new(), + )?; + if pyi { + write_python_index( + &directory.join("__init__.pyi"), + &format!("{GENERATED_PYTHON_HEADER}{}", stub_exports.join("\n")), + true, + &HashSet::new(), + )?; + } + if context.root_name_is_unambiguous(&typ.identity) { + let symbols = std::iter::once(item.interface_export.as_str()) + .chain(item.helpers.iter().map(|helper| helper.name.as_str())) + .map(|name| format!("{name} as {name}")) + .collect::>() + .join(", "); + let root = format!( + "{GENERATED_PYTHON_HEADER}from .{} import {symbols}\n", + context.public_qualified_module(&typ.identity) + ); + write_python_lazy_root_index( + &output_dir.join("__init__.py"), + &root, + true, + &HashSet::new(), + )?; + if pyi { + write_python_index( + &output_dir.join("__init__.pyi"), + &root, + true, + &HashSet::new(), + )?; + } + } + } + Ok(()) } fn write_python_package_indexes( @@ -3955,18 +4443,29 @@ fn write_python_package_indexes( } else { Vec::new() }; - all_types.extend(current_types); - let mut seen_types = HashSet::new(); - all_types.retain(|typ| seen_types.insert(typ.clone())); + all_types = merge_python_generated_types(all_types, current_types); let module_identities = all_types .iter() .map(|typ| typ.identity.clone()) .collect::>(); - let context = python::PythonProjectionContext::packaged_with_ambiguities( + let mut context = python::PythonProjectionContext::packaged_with_ambiguities( module_identities.clone(), ambiguous_named_types.iter().cloned(), )?; + context.configure_implementation_helpers(all_types.iter().map(|typ| { + ( + typ.identity.clone(), + typ.implementation + .as_ref() + .map_or_else(Vec::new, |item| item.helpers.clone()), + ) + })); + let regenerated = python_generated_types(classes, interfaces, enums) + .into_iter() + .map(|typ| typ.identity) + .collect(); + update_python_helper_layout(&context, &mut all_types, ®enerated); validate_python_public_identities(&context, &module_identities)?; let suppressed_root_names = module_identities @@ -4611,6 +5110,8 @@ fn python_generated_types( let mut types = Vec::new(); types.extend(classes.iter().map(|class| PythonGeneratedType { kind: "class".into(), + schema_version: 2, + implementation: None, identity: TypeIdentity::named( TypeIdentityKind::Class, class.namespace.clone(), @@ -4620,6 +5121,11 @@ fn python_generated_types( types.extend(interfaces.iter().map(|interface| PythonGeneratedType { kind: "interface".into(), identity: interface.type_identity(), + schema_version: 2, + implementation: python_interface_implementation_inventory( + &python::PythonProjectionContext::default(), + interface, + ), })); types.extend(enums.iter().filter_map(|typ| { let TypeMeta::Enum { .. } = typ else { @@ -4628,6 +5134,8 @@ fn python_generated_types( Some(PythonGeneratedType { kind: "enum".into(), identity: typ.type_identity(), + schema_version: 2, + implementation: None, }) })); types.extend( @@ -4636,11 +5144,32 @@ fn python_generated_types( .map(|typ| PythonGeneratedType { kind: "struct".into(), identity: typ.type_identity(), + schema_version: 2, + implementation: None, }), ); types } +fn python_interface_implementation_inventory( + context: &python::PythonProjectionContext, + interface: &meta::InterfaceMeta, +) -> Option { + let helpers = python::implementation_helper_records(context, interface); + let handler_export = helpers + .iter() + .find(|helper| helper.key == "handlers")? + .name + .clone(); + Some(PythonImplementationInventory { + module: context.implementation_module_for_interface(interface), + interface_export: context.projected_name_for_interface(interface), + handler_export, + helpers, + pair_eligible: true, + }) +} + fn read_python_type_inventory(output_dir: &Path) -> Result, String> { let path = output_dir.join(PYTHON_TYPE_INVENTORY); if !path.is_file() { @@ -4653,6 +5182,44 @@ fn read_python_type_inventory(output_dir: &Path) -> Result>() + .len() + != item.helpers.len() + || !item.helpers.iter().any(|helper| { + helper.key == "handlers" && helper.name == item.handler_export + }) + { + return Err(format!( + "Invalid Python implementation inventory for {}", + python::python_identity_display_name(&typ.identity) + )); + } + } if !matches!(typ.kind.as_str(), "class" | "interface" | "enum" | "struct") { return Err(format!( "Invalid generated type inventory kind `{}`", @@ -4690,10 +5257,9 @@ fn record_python_supplemental_types( if interfaces.is_empty() { return Ok(()); } - let mut types = read_python_type_inventory(output_dir)?; - types.extend(python_generated_types(&[], interfaces, &[])); - let mut seen = HashSet::new(); - types.retain(|typ| seen.insert(typ.clone())); + let existing = read_python_type_inventory(output_dir)?; + let types = + merge_python_generated_types(python_generated_types(&[], interfaces, &[]), existing); write_python_type_inventory(output_dir, &types) } @@ -8779,8 +9345,19 @@ mod tests { let first = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); assert!(first.contains(".example__left__i_value import _ImplementationPair")); assert!(!first.contains("example__right__i_value")); + fs::write( + output.join("unrelated.pyi"), + format!( + "{GENERATED_PYTHON_HEADER}_ImplementationPair: TypeAlias = tuple[object, object]\n" + ), + ) + .unwrap(); emit(std::slice::from_ref(&right)); let complete = fs::read_to_string(output.join("_implementation_types.pyi")).unwrap(); + assert!( + !complete.contains("unrelated"), + "pair membership must come from validated inventory, never stub text" + ); assert!(complete.contains(".example__left__i_value import _ImplementationPair")); assert!(complete.contains(".example__right__i_value import _ImplementationPair")); assert!(!output.join("_implementation_types.py").exists()); @@ -8791,7 +9368,23 @@ mod tests { ); for namespace in ["left", "right"] { let stub = output.join("example").join(namespace).join("__init__.pyi"); - assert!(fs::read_to_string(stub).unwrap().contains("IValueHandlers")); + let inventory = read_python_type_inventory(&output).unwrap(); + let handler = inventory + .iter() + .find(|typ| { + typ.identity.namespace() + == Some(&format!( + "Example.{}", + if namespace == "left" { "Left" } else { "Right" } + )) + }) + .unwrap() + .implementation + .as_ref() + .unwrap() + .handler_export + .clone(); + assert!(fs::read_to_string(stub).unwrap().contains(&handler)); } let mut unsupported = left.clone(); diff --git a/tools/dynwinrt-codegen/src/meta.rs b/tools/dynwinrt-codegen/src/meta.rs index 263de330..fdccd0df 100644 --- a/tools/dynwinrt-codegen/src/meta.rs +++ b/tools/dynwinrt-codegen/src/meta.rs @@ -8,6 +8,8 @@ use windows_metadata::{HasAttributes, reader}; use crate::types::{EnumMember, TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; +mod raw_signature; + pub const WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE: &str = "Windows.Foundation.Collections"; pub const PIID_IVECTOR: &str = "913337e9-11a1-4345-a3a2-4e7f956e222d"; pub const PIID_IOBSERVABLE_VECTOR: &str = "5917eb53-50b4-4a0d-b309-65862b3f1dbc"; @@ -1567,6 +1569,16 @@ fn parse_interface_methods( } for (i, method) in def.methods().enumerate() { let vtable_index = 6 + i; + if def + .flags() + .contains(windows_metadata::TypeAttributes::WindowsRuntime) + { + implementation_metadata.diagnostics.extend( + raw_signature::implementation_diagnostics(&method) + .into_iter() + .map(|reason| format!("{}: {reason}", method.name())), + ); + } let sig = method.signature(&winmd_generics); if sig.flags != windows_metadata::MethodCallAttributes::HASTHIS { implementation_metadata.diagnostics.push(format!( @@ -1866,6 +1878,11 @@ fn collect_implementation_delegates( )); return; }; + output.diagnostics.extend( + raw_signature::implementation_diagnostics(&invoke) + .into_iter() + .map(|reason| format!("{}.{} Invoke: {reason}", named.namespace, named.name)), + ); let signature = invoke.signature(&named.generics); if signature.flags != windows_metadata::MethodCallAttributes::HASTHIS || invoke @@ -2042,6 +2059,14 @@ fn validate_implementation_metadata_type( } } for field in def.fields() { + raw_signature::validate_implementation_field(&field).map_err(|reason| { + format!( + "field {}.{}.{}: {reason}", + named.namespace, + named.name, + field.name() + ) + })?; let field_type = field.ty(); if matches!( field_type, diff --git a/tools/dynwinrt-codegen/src/meta/raw_signature.rs b/tools/dynwinrt-codegen/src/meta/raw_signature.rs new file mode 100644 index 00000000..b2a9dd6c --- /dev/null +++ b/tools/dynwinrt-codegen/src/meta/raw_signature.rs @@ -0,0 +1,350 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Reference evidence for reverse WinRT contracts, before the lossy Type projection. + +use windows_metadata::{AsRow, ParamAttributes, reader}; + +pub(super) fn implementation_diagnostics(method: &reader::MethodDef<'_>) -> Vec { + // windows-metadata 0.59 exposes the MethodDef signature through AsRow, but + // read_type_signature drops scalar BYREF. Column 4 is Signature (II.22.26). + let mut blob = method.blob(4); + let evidence = SignatureReader::new(&blob).read(); + // Blob's debug Drop requires consumption even when evidence parsing fails. + while !blob.is_empty() { + blob.read_u8(); + } + let parameters = match evidence { + Ok(parameters) => parameters, + Err(reason) => { + return vec![format!( + "unsupported raw ECMA-335 signature evidence: {reason}" + )]; + } + }; + let definitions = method + .params() + .filter(|parameter| parameter.sequence() > 0) + .collect::>(); + parameters + .into_iter() + .enumerate() + .filter_map(|(position, byref)| { + if !byref { + return None; + } + let sequence = position + 1; + let definition = definitions.get(position); + if definition.is_some_and(|parameter| { + usize::from(parameter.sequence()) == sequence + && parameter.flags().contains(ParamAttributes::Out) + }) { + return None; + } + let name = definition.map_or("", |parameter| parameter.name()); + Some(format!( + "parameter {name} ({sequence}): input BYREF is not a WinRT implementation contract; an Out contract is required" + )) + }) + .collect() +} + +pub(super) fn validate_implementation_field(field: &reader::Field<'_>) -> Result<(), String> { + // Field.Signature is column 2 (II.22.15); Field::ty uses the same lossy reader. + let mut blob = field.blob(2); + let evidence = SignatureReader::new(&blob).read_field(); + while !blob.is_empty() { + blob.read_u8(); + } + evidence + .map_err(|reason| format!("unsupported raw ECMA-335 field signature evidence: {reason}")) +} + +/// Walk ECMA-335 II.23.2 signatures structurally. Tokens, compressed counts, +/// modifiers and nested types are operands, not candidate BYREF markers. +/// Native type support and Out/Fill/Receive semantics remain in meta.rs. +struct SignatureReader<'a> { + bytes: &'a [u8], + position: usize, +} + +impl<'a> SignatureReader<'a> { + fn new(bytes: &'a [u8]) -> Self { + Self { bytes, position: 0 } + } + + fn read(mut self) -> Result, String> { + let parameters = self.method(0)?; + if self.position != self.bytes.len() { + return Err(self.error("trailing signature bytes")); + } + Ok(parameters) + } + + fn read_field(mut self) -> Result<(), String> { + if self.byte()? != 0x06 { + return Err(self.error("not a FIELD signature")); + } + self.modifiers()?; + if self.take(0x10) { + return Err(self.error("BYREF field has no WinRT value layout")); + } + self.typ(0)?; + if self.position != self.bytes.len() { + return Err(self.error("trailing field signature bytes")); + } + Ok(()) + } + + fn method(&mut self, depth: usize) -> Result, String> { + self.check_depth(depth)?; + let flags = self.byte()?; + if !matches!(flags & 0x0f, 0..=5 | 9 | 11) { + return Err(self.error("not a method calling convention")); + } + if flags & 0x10 != 0 { + self.compressed()?; // GenericParamCount precedes ParamCount. + } + let count = self.count()?; + if self.parameter(true, depth + 1)? { + return Err(self.error("BYREF return is not a WinRT logical return contract")); + } + let mut parameters = Vec::with_capacity(count); + let mut sentinel = false; + for _ in 0..count { + if self.take(0x41) { + if sentinel || flags & 0x0f != 5 { + return Err(self.error("unexpected vararg sentinel")); + } + sentinel = true; + } + parameters.push(self.parameter(false, depth + 1)?); + } + Ok(parameters) + } + + fn parameter(&mut self, is_return: bool, depth: usize) -> Result { + self.modifiers()?; + let byref = self.take(0x10); + if (!byref && self.take(0x16)) || (is_return && !byref && self.take(0x01)) { + return Ok(byref); + } + self.typ(depth)?; + Ok(byref) + } + + fn typ(&mut self, depth: usize) -> Result<(), String> { + self.check_depth(depth)?; + match self.byte()? { + 0x02..=0x0e | 0x18 | 0x19 | 0x1c => {} + 0x0f => { + self.modifiers()?; + if !self.take(0x01) { + self.typ(depth + 1)?; + } + } + 0x11 | 0x12 => self.type_token()?, + 0x13 | 0x1e => { + self.compressed()?; + } + 0x14 => { + self.typ(depth + 1)?; + let rank = self.compressed()?; + let sizes = self.count()?; + if rank == 0 || sizes > rank as usize { + return Err(self.error("invalid array rank or size count")); + } + for _ in 0..sizes { + self.compressed()?; + } + let bounds = self.count()?; + if bounds > rank as usize { + return Err(self.error("invalid array lower-bound count")); + } + for _ in 0..bounds { + // Signed compressed lower bounds use the same byte widths. + self.compressed()?; + } + } + 0x15 => { + if !matches!(self.byte()?, 0x11 | 0x12) { + return Err(self.error("generic instance requires CLASS or VALUETYPE")); + } + self.type_token()?; + let count = self.count()?; + if count == 0 { + return Err(self.error("generic instance has no type arguments")); + } + for _ in 0..count { + self.typ(depth + 1)?; + } + } + 0x1b => { + self.method(depth + 1)?; + } + 0x1d => { + self.modifiers()?; + self.typ(depth + 1)?; + } + 0x10 => return Err(self.error("nested BYREF is not a WinRT value type")), + element => { + return Err(self.error(&format!("unsupported type element 0x{element:02x}"))); + } + } + Ok(()) + } + + fn modifiers(&mut self) -> Result<(), String> { + while self.take(0x1f) || self.take(0x20) { + self.type_token()?; + } + Ok(()) + } + + fn type_token(&mut self) -> Result<(), String> { + let token = self.compressed()?; + if token >> 2 == 0 || token & 3 == 3 { + return Err(self.error("invalid TypeDefOrRefEncoded token")); + } + Ok(()) + } + + fn count(&mut self) -> Result { + let count = self.compressed()? as usize; + if count > self.bytes.len() - self.position { + return Err(self.error("count exceeds remaining signature bytes")); + } + Ok(count) + } + + fn compressed(&mut self) -> Result { + let first = self.byte()?; + match first { + 0x00..=0x7f => Ok(u32::from(first)), + 0x80..=0xbf => Ok((u32::from(first & 0x3f) << 8) | u32::from(self.byte()?)), + 0xc0..=0xdf => Ok((u32::from(first & 0x1f) << 24) + | (u32::from(self.byte()?) << 16) + | (u32::from(self.byte()?) << 8) + | u32::from(self.byte()?)), + _ => Err(self.error("invalid compressed integer")), + } + } + + fn byte(&mut self) -> Result { + let value = self + .bytes + .get(self.position) + .copied() + .ok_or_else(|| self.error("truncated signature"))?; + self.position += 1; + Ok(value) + } + + fn take(&mut self, value: u8) -> bool { + if self.bytes.get(self.position) == Some(&value) { + self.position += 1; + true + } else { + false + } + } + + fn check_depth(&self, depth: usize) -> Result<(), String> { + if depth > 64 { + Err(self.error("signature nesting exceeds the evidence reader limit")) + } else { + Ok(()) + } + } + + fn error(&self, reason: &str) -> String { + format!("byte {}: {reason}", self.position) + } +} + +#[cfg(test)] +mod tests { + use super::SignatureReader; + + #[test] + fn compressed_counts_and_type_operands_are_not_qualifiers() { + let mut many_parameters = vec![0x20, 0x80, 0x80, 0x01]; + many_parameters.extend([0x08; 128]); + assert_eq!( + SignatureReader::new(&many_parameters).read().unwrap(), + vec![false; 128] + ); + for typ in [ + vec![0x11, 0x10], // TypeDef token + vec![0x13, 0x10], // VAR number + vec![0x1e, 0x10], // MVAR number + vec![0x14, 0x08, 1, 1, 0x10, 1, 0], // ARRAY size + vec![0x14, 0x08, 1, 0, 1, 0x80, 1], // signed lower bound -8192 + vec![0x15, 0x12, 0x10, 1, 0x15, 0x12, 0x10, 1, 0x08], + vec![0x0f, 0x20, 0x10, 0x01], // PTR custom modifier and VOID + vec![0x1b, 0, 1, 1, 0x10, 0x08], // FNPTR's parameter, not the outer one + ] { + let mut signature = vec![0x20, 2, 1]; + signature.extend(typ); + signature.extend([0x10, 0x08]); + assert_eq!( + SignatureReader::new(&signature).read().unwrap(), + [false, true] + ); + } + assert_eq!( + SignatureReader::new(&[0x30, 0x10, 1, 1, 0x13, 0x10]) + .read() + .unwrap(), + [false] + ); + } + + #[test] + fn malformed_evidence_fails_closed() { + for signature in [ + &[0x20, 1, 1, 0x10][..], + &[0x20, 1, 1, 0x10, 0x10, 0x08], + &[0x20, 1, 1, 0x20, 0x80], + &[0x20, 1, 1, 0x15, 0x12, 0x10, 1, 0x10, 0x08], + &[0x20, 1, 1, 0x1d], + &[0x20, 1, 1, 0x08, 0x08], + &[0x20, 0xff, 1, 0x08], + ] { + assert!( + SignatureReader::new(signature).read().is_err(), + "{signature:?}" + ); + } + let mut nested = vec![0x20, 1, 1]; + nested.extend([0x1d; 65]); + nested.push(0x08); + assert!( + SignatureReader::new(&nested) + .read() + .unwrap_err() + .contains("nesting") + ); + } + + #[test] + fn field_evidence_preserves_reference_qualifiers_after_modifiers() { + assert!(SignatureReader::new(&[0x06, 0x08]).read_field().is_ok()); + for modifier in [0x1f, 0x20] { + assert!( + SignatureReader::new(&[0x06, modifier, 0x10, 0x08]) + .read_field() + .is_ok() + ); + assert!( + SignatureReader::new(&[0x06, modifier, 0x10, 0x10, 0x08]) + .read_field() + .unwrap_err() + .contains("BYREF field") + ); + } + for signature in [&[0x20, 0x08][..], &[0x06], &[0x06, 0x08, 0x08]] { + assert!(SignatureReader::new(signature).read_field().is_err()); + } + } +} diff --git a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs new file mode 100644 index 00000000..46328ebd --- /dev/null +++ b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs @@ -0,0 +1,963 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::BTreeMap; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use windows_metadata::{ + MethodAttributes, MethodCallAttributes, MethodImplAttributes, ParamAttributes, Signature, Type, + TypeAttributes, Value, writer, +}; + +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Self { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("target") + .join(format!( + "implementation-names-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn root() -> PathBuf { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .canonicalize() + .unwrap(); + let text = path.to_string_lossy(); + PathBuf::from(text.strip_prefix(r"\\?\").unwrap_or(&text)) +} + +fn names(path: &Path, definitions: &[(&str, &str, &str, u32)]) { + names_with_callback(path, definitions, false); +} + +fn names_with_callback(path: &Path, definitions: &[(&str, &str, &str, u32)], callback_owner: bool) { + let mut file = writer::File::new("ImplementationNames"); + let attribute = file.TypeRef("Windows.Foundation.Metadata", "GuidAttribute"); + let constructor = file.MemberRef( + ".ctor", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types: vec![ + Type::U32, + Type::U16, + Type::U16, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + ], + }, + writer::MemberRefParent::TypeRef(attribute), + ); + for &(namespace, name, method, id) in definitions { + let interface = file.TypeDef( + namespace, + name, + writer::TypeDefOrRef::default(), + TypeAttributes::Public + | TypeAttributes::Interface + | TypeAttributes::Abstract + | TypeAttributes::WindowsRuntime, + ); + let values = vec![ + Value::U32(id), + Value::U16(0x6281), + Value::U16(0x4900), + Value::U8(0xb7), + Value::U8(0x82), + Value::U8(4), + Value::U8(3), + Value::U8(2), + Value::U8(1), + Value::U8(9), + Value::U8(0x10), + ]; + file.Attribute( + writer::HasAttribute::TypeDef(interface), + writer::AttributeType::MemberRef(constructor), + &values + .into_iter() + .map(|value| (String::new(), value)) + .collect::>(), + ); + file.MethodDef( + method, + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::I32, + types: vec![], + }, + MethodAttributes::Public + | MethodAttributes::Abstract + | MethodAttributes::Virtual + | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + if callback_owner && name == "IComplex" { + file.MethodDef( + "UseCallback", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types: vec![Type::named("Contoso", "Callback")], + }, + MethodAttributes::Public + | MethodAttributes::Abstract + | MethodAttributes::Virtual + | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + file.Param("callback", 1, ParamAttributes::In); + for method in ["Split", "Delegate0"] { + file.MethodDef( + method, + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::I32, + types: vec![Type::I32], + }, + MethodAttributes::Public + | MethodAttributes::Abstract + | MethodAttributes::Virtual + | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + file.Param("first", 1, ParamAttributes::Out); + } + } + } + if callback_owner { + let base = file.TypeRef("System", "MulticastDelegate"); + let delegate = file.TypeDef( + "Contoso", + "Callback", + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + let values = vec![ + Value::U32(0x31d44799), + Value::U16(0x6281), + Value::U16(0x4900), + Value::U8(0xb7), + Value::U8(0x82), + Value::U8(4), + Value::U8(3), + Value::U8(2), + Value::U8(1), + Value::U8(9), + Value::U8(0x10), + ]; + file.Attribute( + writer::HasAttribute::TypeDef(delegate), + writer::AttributeType::MemberRef(constructor), + &values + .into_iter() + .map(|value| (String::new(), value)) + .collect::>(), + ); + file.MethodDef( + ".ctor", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types: vec![], + }, + MethodAttributes::Public | MethodAttributes::SpecialName, + MethodImplAttributes::default(), + ); + file.MethodDef( + "Invoke", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::I32, + types: vec![Type::I32], + }, + MethodAttributes::Public | MethodAttributes::Virtual | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + file.Param("first", 1, ParamAttributes::Out); + } + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, file.into_stream()).unwrap(); +} + +#[test] +fn delegate_and_named_result_helpers_share_the_symbol_allocator() { + let fixture = Fixture::new(); + let metadata = fixture.0.join("metadata").join("Complex.winmd"); + names_with_callback( + &metadata, + &[ + ("Contoso", "IComplex", "ReadValue", 0x31d44751), + ( + "Contoso", + "IComplexImplementationDelegate0", + "RealDelegateName", + 0x31d44752, + ), + ( + "Contoso", + "IComplexImplementationDelegate0Result", + "RealResultName", + 0x31d44753, + ), + ( + "Contoso", + "IComplexImplementationSplitResult", + "RealSplitName", + 0x31d44754, + ), + ], + true, + ); + let names = "Contoso.IComplex,Contoso.IComplexImplementationDelegate0,Contoso.IComplexImplementationDelegate0Result,Contoso.IComplexImplementationSplitResult"; + for lang in ["js", "py"] { + let output = fixture.0.join(if lang == "py" { "pyviews" } else { "js" }); + success(generate(&metadata, &output, lang, names, &[])); + if lang == "js" { + typecheck_js(&output); + continue; + } + let inventory = python_inventory(&output); + let record = inventory + .iter() + .find(|record| record["identity"]["name"] == "IComplex") + .unwrap(); + let helpers = record["implementation"]["helpers"] + .as_array() + .expect("complete delegate contract must remain implementable"); + let helper = |key: &str| { + helpers.iter().find(|item| item["key"] == key).unwrap()["name"] + .as_str() + .unwrap() + }; + let delegate = helper("delegate:0"); + let delegate_result = helper("delegate-result:0"); + let split = helper("method-result:8"); + let method_result = helper("method-result:9"); + assert_ne!(delegate_result, method_result); + assert_ne!(delegate, "IComplexImplementationDelegate0"); + assert_ne!(split, "IComplexImplementationSplitResult"); + typecheck_py( + &fixture.0, + &format!( + r#" +from pyviews import ( + IComplex, IComplexImplementationDelegate0, IComplexImplementationDelegate0Result, + IComplexImplementationSplitResult, {delegate}, {delegate_result}, {split}, {method_result}, +) +class Handler: + def read_value(self) -> int: return 1 + def use_callback(self, callback: {delegate} | None) -> None: + if callback is not None: + result: {delegate_result} = callback() + def split(self) -> {split}: return {{"first": 1, "result": 2}} + def delegate0(self) -> {method_result}: return {{"first": 3, "result": 4}} +IComplex.implementation(Handler()) +IComplexImplementationDelegate0.from_value +IComplexImplementationDelegate0Result.from_value +IComplexImplementationSplitResult.from_value +"# + ), + ); + if runtime_available() { + success(Command::new(python()).args(["-c", r#" +import pyviews as g +for name in ('IComplexImplementationDelegate0', 'IComplexImplementationDelegate0Result', 'IComplexImplementationSplitResult'): + assert hasattr(getattr(g, name), 'from_value'), name +"#]).current_dir(&fixture.0).output().unwrap()); + } + } +} + +fn generate(metadata: &Path, output: &Path, lang: &str, selected: &str, extra: &[&str]) -> Output { + let runtime = root() + .join("bindings") + .join("js") + .join("dist") + .join("winrt.js"); + let runtime = runtime.to_string_lossy().replace('\\', "/"); + Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd"]) + .arg(metadata) + .args(["--output"]) + .arg(output) + .args([ + "--lang", + lang, + "--class-name", + selected, + "--import-name", + &runtime, + ]) + .args(extra) + .output() + .unwrap() +} + +fn success(output: Output) { + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn typecheck_js(output: &Path) { + let tsc = root() + .join("bindings") + .join("js") + .join("node_modules") + .join("typescript") + .join("bin") + .join("tsc"); + if !tsc.is_file() + || !root() + .join("bindings") + .join("js") + .join("dist") + .join("winrt.d.ts") + .is_file() + { + assert_ne!( + std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref(), + Ok("1"), + "the native naming E2E requires built runtime declarations and the existing TypeScript dependency" + ); + eprintln!("Native naming typechecks run after building bindings in the E2E job."); + return; + } + success( + Command::new("node") + .arg(tsc) + .args([ + "--noEmit", + "--strict", + "--target", + "ES2022", + "--module", + "Node16", + "--moduleResolution", + "Node16", + "--types", + "node", + "--typeRoots", + ]) + .arg( + root() + .join("bindings") + .join("js") + .join("node_modules") + .join("@types"), + ) + .arg(output.join("index.d.ts")) + .output() + .unwrap(), + ); +} + +fn python() -> PathBuf { + std::env::var_os("DYNWINRT_TEST_PYTHON") + .map(PathBuf::from) + .unwrap_or_else(|| { + let venv = root() + .join("bindings") + .join("py") + .join(".venv") + .join("Scripts") + .join("python.exe"); + if venv.is_file() { + venv + } else { + PathBuf::from("python") + } + }) +} + +fn typecheck_py(directory: &Path, source: &str) { + if !Command::new(python()) + .args(["-m", "mypy", "--version"]) + .output() + .is_ok_and(|output| output.status.success()) + { + assert_ne!( + std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref(), + Ok("1"), + "mypy is required by the native naming E2E" + ); + eprintln!( + "Python naming typechecks require the E2E environment's existing mypy dependency." + ); + return; + } + fs::write(directory.join("consumer.py"), source).unwrap(); + success( + Command::new(python()) + .args([ + "-m", + "mypy", + "--strict", + "--no-incremental", + "--follow-imports=silent", + "consumer.py", + ]) + .current_dir(directory) + .env( + "MYPYPATH", + std::env::join_paths([root().join("bindings").join("py"), directory.to_path_buf()]) + .unwrap(), + ) + .output() + .unwrap(), + ); +} + +fn runtime_available() -> bool { + let available = Command::new(python()) + .args([ + "-c", + "import dynwinrt; assert hasattr(dynwinrt, 'DynWinRTImplementationHandle')", + ]) + .output() + .is_ok_and(|result| result.status.success()); + assert!( + available || std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref() != Ok("1"), + "runtime naming regressions require the current Python binding" + ); + available +} + +fn python_inventory(directory: &Path) -> Vec { + fs::read_to_string(directory.join(".dynwinrt-generated-types")) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() +} + +fn snapshot(directory: &Path) -> BTreeMap> { + fn visit(root: &Path, path: &Path, files: &mut BTreeMap>) { + for entry in fs::read_dir(path).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + visit(root, &path, files); + } else { + files.insert( + path.strip_prefix(root).unwrap().to_path_buf(), + fs::read(path).unwrap(), + ); + } + } + } + let mut files = BTreeMap::new(); + visit(directory, directory, &mut files); + files +} + +#[test] +fn helper_collision_keeps_real_metadata_types_and_owned_handler_exports() { + let fixture = Fixture::new(); + let metadata = fixture.0.join("metadata").join("Names.winmd"); + names( + &metadata, + &[ + ("Contoso", "IValue", "ReadValue", 0x31d44731), + ("Contoso", "IValueHandlers", "ReadRealInterface", 0x31d44732), + ], + ); + let js = fixture.0.join("js"); + let py = fixture.0.join("pyviews"); + success(generate( + &metadata, + &js, + "js", + "Contoso.IValue,Contoso.IValueHandlers", + &[], + )); + success(generate( + &metadata, + &py, + "py", + "Contoso.IValue,Contoso.IValueHandlers", + &[], + )); + typecheck_js(&js); + let records = python_inventory(&py); + let item = records + .iter() + .find(|record| record["identity"]["name"] == "IValue") + .unwrap(); + let helper = item["implementation"]["handler_export"].as_str().unwrap(); + assert_ne!(helper, "IValueHandlers"); + typecheck_py( + &fixture.0, + &format!( + r#" +from pyviews import IValue, IValueHandlers, {helper} +from pyviews.contoso.i_value_handlers import IValueHandlers as Deep +from typing import assert_type +class Handler: + def read_value(self) -> int: return 1 +class Real: + def read_real_interface(self) -> int: return 2 +handler: {helper} = Handler() +assert_type(IValue.implement(handler).value, IValue) +assert_type(Deep.implement(Real()).value, IValueHandlers) +with IValue.implement(handler, interfaces=[(IValueHandlers, Real())]) as impl: + assert_type(impl.value, IValue) +"# + ), + ); + if runtime_available() { + success(Command::new(python()).args(["-c", r#" +import pyviews as g +import dynwinrt as dw +from pyviews.contoso.i_value_handlers import IValueHandlers +assert g.IValueHandlers is IValueHandlers and hasattr(IValueHandlers, 'from_value') +class Handler: + def read_value(self): return 1 +class Real: + def read_real_interface(self): return 2 +with dw.RoApartment(1), g.IValue.implement(Handler(), interfaces=[(IValueHandlers, Real())]) as impl: + assert impl.value.read_value() == 1 + other = IValueHandlers.from_implementation(impl) + try: assert other.read_real_interface() == 2 + finally: dw.release_projected(other) +"#]).current_dir(&fixture.0).output().unwrap()); + success(Command::new("node").args(["-e", r#" +const assert = require('node:assert/strict'); +const g = require('./js'); +const deep = require('./js/contoso/IValueHandlers.js'); +assert.equal(typeof g.IValueHandlers.implement, 'function'); +const impl = g.IValue.implement({ readValue: () => 1 }, { interfaces: [[g.IValueHandlers, { readRealInterface: () => 2 }]] }); +try { + assert.equal(impl.value.readValue(), 1); + const other = deep.IValueHandlers.fromImplementation(impl); + try { assert.equal(other.readRealInterface(), 2); } finally { g.releaseProjected(other); } +} finally { impl.dispose(); } +"#]).current_dir(&fixture.0).output().unwrap()); + } +} + +#[test] +fn incremental_helper_aliases_match_clean_generation_and_retain_unrelated_modules() { + let fixture = Fixture::new(); + let initial = fixture.0.join("initial").join("Initial.winmd"); + let extra = fixture.0.join("extra").join("Extra.winmd"); + let combined = fixture.0.join("combined").join("Combined.winmd"); + let first = [ + ("AlphaBeta", "IWidget", "ReadAlphaBeta", 0x31d44733), + ("Control", "IWidget", "ReadControl", 0x31d44734), + ]; + let second = [("Alpha.Beta", "IWidget", "ReadAlphaDotBeta", 0x31d44735)]; + names(&initial, &first); + names(&extra, &second); + names(&combined, &[first.as_slice(), second.as_slice()].concat()); + for lang in ["js", "py"] { + let incremental = fixture.0.join(format!("{lang}_incremental")); + let clean = fixture.0.join(format!("{lang}_clean")); + success(generate( + &initial, + &incremental, + lang, + "AlphaBeta.IWidget,Control.IWidget", + &[], + )); + let retained = if lang == "js" { + "control\\IWidget.js" + } else { + "control__i_widget.py" + }; + let original = fs::read(incremental.join(retained)).unwrap(); + // New manifests retain helper identity and eligibility without old WinMD. + success(generate( + &extra, + &incremental, + lang, + "Alpha.Beta.IWidget", + &[], + )); + assert_eq!(original, fs::read(incremental.join(retained)).unwrap()); + success(generate( + &combined, + &clean, + lang, + "Alpha.Beta.IWidget,Control.IWidget,AlphaBeta.IWidget", + &[], + )); + if lang == "js" { + assert_eq!( + fs::read(incremental.join("index.d.ts")).unwrap(), + fs::read(clean.join("index.d.ts")).unwrap() + ); + typecheck_js(&incremental); + typecheck_js(&clean); + } else { + assert_eq!( + fs::read(incremental.join("_implementation_types.pyi")).unwrap(), + fs::read(clean.join("_implementation_types.pyi")).unwrap() + ); + let exports = |path: &Path| { + python_inventory(path) + .into_iter() + .map(|record| { + ( + record["identity"].to_string(), + ( + record["implementation"]["handler_export"].clone(), + record["implementation"]["interface_export"].clone(), + ), + ) + }) + .collect::>() + }; + assert_eq!(exports(&incremental), exports(&clean)); + typecheck_py( + &fixture.0, + r#" +from py_incremental.alpha.beta.i_widget import IWidget as A +from py_incremental.alpha_beta.i_widget import IWidget as B +from py_incremental.control.i_widget import IWidget as C +class One: + def read_alpha_dot_beta(self) -> int: return 1 +class Two: + def read_alpha_beta(self) -> int: return 2 +class Three: + def read_control(self) -> int: return 3 +with A.implement(One(), interfaces=[(B, Two()), (C, Three())]) as impl: + value: A = impl.value +"#, + ); + } + let before = snapshot(&incremental); + success(generate( + &extra, + &incremental, + lang, + "Alpha.Beta.IWidget", + &[], + )); + assert_eq!( + before, + snapshot(&incremental), + "repeated {lang} append must be stable" + ); + } +} + +#[test] +fn appending_a_real_type_renames_only_the_retained_helper_not_its_interface() { + let fixture = Fixture::new(); + let first = fixture.0.join("first").join("First.winmd"); + let second = fixture.0.join("second").join("Second.winmd"); + let both = fixture.0.join("both").join("Both.winmd"); + let definitions = [ + ("Contoso", "IValue", "ReadValue", 0x31d44761), + ("Contoso", "IValueHandlers", "ReadRealInterface", 0x31d44762), + ]; + names(&first, &definitions[..1]); + names(&second, &definitions[1..]); + names(&both, &definitions); + for lang in ["js", "py"] { + let output = fixture.0.join(format!("{lang}views")); + let clean = fixture.0.join(format!("{lang}clean")); + success(generate(&first, &output, lang, "Contoso.IValue", &[])); + success(generate( + &second, + &output, + lang, + "Contoso.IValueHandlers", + &[], + )); + success(generate( + &both, + &clean, + lang, + "Contoso.IValueHandlers,Contoso.IValue", + &[], + )); + if lang == "js" { + assert_eq!( + fs::read(output.join("index.d.ts")).unwrap(), + fs::read(clean.join("index.d.ts")).unwrap() + ); + typecheck_js(&output); + let source = fs::read_to_string(output.join("contoso").join("IValue.d.ts")).unwrap(); + assert!(source.contains("export type { IValueHandlers as ")); + assert!( + source.contains("export class IValue") + || source.contains("export declare class IValue") + ); + } else { + let inventory = python_inventory(&output); + let real = inventory + .iter() + .find(|record| record["identity"]["name"] == "IValueHandlers") + .unwrap(); + assert_eq!(real["implementation"]["interface_export"], "IValueHandlers"); + typecheck_py( + &fixture.0, + r#" +from pyviews import IValue, IValueHandlers +class First: + def read_value(self) -> int: return 1 +class Second: + def read_real_interface(self) -> int: return 2 +with IValue.implement(First(), interfaces=[(IValueHandlers, Second())]) as impl: + value: IValue = impl.value +"#, + ); + if runtime_available() { + success(Command::new(python()).args(["-c", "import pyviews as g; from pyviews.contoso.i_value_handlers import IValueHandlers; assert g.IValueHandlers is IValueHandlers; assert hasattr(g.IValueHandlers, 'from_value')"]) + .current_dir(&fixture.0).output().unwrap()); + } + } + let previous = snapshot(&output); + success(generate( + &second, + &output, + lang, + "Contoso.IValueHandlers", + &[], + )); + assert_eq!(previous, snapshot(&output)); + } +} + +#[test] +fn python_inventory_migration_uses_metadata_not_stub_text_and_fails_atomically() { + let fixture = Fixture::new(); + let initial = fixture.0.join("initial").join("Initial.winmd"); + let extra = fixture.0.join("extra").join("Extra.winmd"); + names(&initial, &[("Original", "IFirst", "Read", 0x31d44741)]); + names(&extra, &[("Extra", "ISecond", "Other", 0x31d44742)]); + for (suffix, no_pyi) in [("typed", false), ("runtime", true)] { + let output = fixture.0.join(suffix); + success(generate(&initial, &output, "py", "Original.IFirst", &[])); + let records = python_inventory(&output) + .into_iter() + .map(|mut record| { + record.as_object_mut().unwrap().remove("schema_version"); + record.as_object_mut().unwrap().remove("implementation"); + record.to_string() + }) + .collect::>(); + fs::write( + output.join(".dynwinrt-generated-types"), + records.join("\n") + "\n", + ) + .unwrap(); + if no_pyi { + success(generate( + &extra, + &output, + "py", + "Extra.ISecond", + &["--no-pyi"], + )); + assert!(!output.join("_implementation_types.pyi").exists()); + } else { + let before = snapshot(&output); + let rejected = generate(&extra, &output, "py", "Extra.ISecond", &[]); + assert!(!rejected.status.success()); + let message = String::from_utf8_lossy(&rejected.stderr); + assert!( + message.contains("Original.IFirst") && message.contains("--ref"), + "{message}" + ); + assert_eq!(before, snapshot(&output)); + success(generate( + &extra, + &output, + "py", + "Extra.ISecond", + &["--ref", initial.to_str().unwrap()], + )); + assert!( + python_inventory(&output) + .iter() + .all(|record| record["schema_version"] == 2) + ); + assert_eq!( + fs::read_to_string(output.join("_implementation_types.pyi")) + .unwrap() + .matches(" import _ImplementationPair") + .count(), + 2 + ); + } + } +} + +#[test] +fn typed_append_after_no_pyi_requires_regenerating_missing_declarations() { + let fixture = Fixture::new(); + let first = fixture.0.join("first").join("First.winmd"); + let second = fixture.0.join("second").join("Second.winmd"); + names(&first, &[("Original", "IFirst", "Read", 0x31d44771)]); + names(&second, &[("Extra", "ISecond", "Other", 0x31d44772)]); + let output = fixture.0.join("pyviews"); + success(generate( + &first, + &output, + "py", + "Original.IFirst", + &["--no-pyi"], + )); + assert!(!output.join("original__i_first.pyi").exists()); + let before = snapshot(&output); + let rejected = generate(&second, &output, "py", "Extra.ISecond", &[]); + assert!(!rejected.status.success()); + let error = String::from_utf8_lossy(&rejected.stderr); + assert!( + error.contains("retained .pyi") && error.contains("Original.IFirst"), + "{error}" + ); + assert_eq!(before, snapshot(&output)); + success(generate( + &second, + &output, + "py", + "Original.IFirst,Extra.ISecond", + &["--ref", first.to_str().unwrap()], + )); + assert!(output.join("original__i_first.pyi").is_file()); + assert_eq!( + fs::read_to_string(output.join("_implementation_types.pyi")) + .unwrap() + .matches(" import _ImplementationPair") + .count(), + 2 + ); +} + +#[test] +fn legacy_interface_facade_cannot_override_a_current_runtime_class() { + let fixture = Fixture::new(); + let first = fixture.0.join("first").join("First.winmd"); + names(&first, &[("Contoso", "IValue", "Read", 0x31d44781)]); + let output = fixture.0.join("pyviews"); + success(generate(&first, &output, "py", "Contoso.IValue", &[])); + let legacy = python_inventory(&output) + .into_iter() + .map(|mut record| { + record.as_object_mut().unwrap().remove("schema_version"); + record.as_object_mut().unwrap().remove("implementation"); + record.to_string() + }) + .collect::>(); + fs::write( + output.join(".dynwinrt-generated-types"), + legacy.join("\n") + "\n", + ) + .unwrap(); + let metadata = fixture.0.join("class.winmd"); + let mut file = writer::File::new("ClassPrecedence"); + let object = file.TypeRef("System", "Object"); + file.TypeDef( + "Contoso", + "IValue", + writer::TypeDefOrRef::TypeRef(object), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + fs::write(&metadata, file.into_stream()).unwrap(); + success(generate(&metadata, &output, "py", "Contoso.IValue", &[])); + let inventory = python_inventory(&output); + assert!( + inventory + .iter() + .any(|record| record["kind"] == "class" && record["identity"]["name"] == "IValue") + ); + assert!( + !inventory + .iter() + .any(|record| record["kind"] == "interface" && record["identity"]["name"] == "IValue") + ); + for extension in ["py", "pyi"] { + assert!( + !fs::read_to_string(output.join(format!("__init__.{extension}"))) + .unwrap() + .contains("IValueHandlers") + ); + assert!( + !fs::read_to_string(output.join(format!("contoso__i_value.{extension}"))) + .unwrap() + .contains("def implement(") + ); + } + assert!( + !fs::read_to_string(output.join("_implementation_types.pyi")) + .unwrap() + .contains("contoso__i_value") + ); +} + +#[test] +fn legacy_migration_reuses_records_already_present_without_their_metadata() { + let fixture = Fixture::new(); + let initial = fixture.0.join("initial").join("Initial.winmd"); + let extra = fixture.0.join("extra").join("Extra.winmd"); + names(&initial, &[("Original", "IFirst", "Read", 0x31d44741)]); + names(&extra, &[("Extra", "ISecond", "Other", 0x31d44742)]); + let third = fixture.0.join("third").join("Third.winmd"); + names(&third, &[("Last", "IThird", "Last", 0x31d44743)]); + let output = fixture.0.join("partial"); + success(generate(&initial, &output, "py", "Original.IFirst", &[])); + success(generate(&extra, &output, "py", "Extra.ISecond", &[])); + let lines = python_inventory(&output) + .into_iter() + .map(|mut record| { + if record["identity"]["name"] == "IFirst" { + record.as_object_mut().unwrap().remove("schema_version"); + record.as_object_mut().unwrap().remove("implementation"); + } + record.to_string() + }) + .collect::>(); + fs::write( + output.join(".dynwinrt-generated-types"), + lines.join("\n") + "\n", + ) + .unwrap(); + let retained = fs::read(output.join("extra__i_second.py")).unwrap(); + success(generate( + &third, + &output, + "py", + "Last.IThird", + &["--ref", initial.to_str().unwrap()], + )); + assert_eq!( + retained, + fs::read(output.join("extra__i_second.py")).unwrap() + ); + assert!( + python_inventory(&output) + .iter() + .all(|record| record["schema_version"] == 2) + ); +} diff --git a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs index b480e60c..9aa88922 100644 --- a/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs +++ b/tools/dynwinrt-codegen/tests/winrt_implementation_test.rs @@ -1049,7 +1049,7 @@ print('Python projection assertions passed') &serde_json::json!({ "code": py, "stub": pyi, - "handle": include_str!("../../../bindings/py/src/implementation.py"), + "handle": include_str!("../../../bindings/py/python/dynwinrt/_implementation.py"), "support": python::generate_runtime_support_module(), }) .to_string(), diff --git a/tools/dynwinrt-codegen/tests/winrt_raw_signature_test.rs b/tools/dynwinrt-codegen/tests/winrt_raw_signature_test.rs new file mode 100644 index 00000000..43dad3d0 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/winrt_raw_signature_test.rs @@ -0,0 +1,750 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +mod common; + +use std::collections::{HashMap, HashSet}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::meta::{self, InterfaceMeta, ParamDirection}; +use dynwinrt_codegen::types::TypeMeta; +use windows_metadata::{ + AsRow, FieldAttributes, GenericParamAttributes, MethodAttributes, MethodCallAttributes, + MethodImplAttributes, ParamAttributes, Signature, Type, TypeAttributes, TypeName, Value, + reader, writer, +}; + +const NAMESPACE: &str = "Tests.RawSignature"; +const BYREF: u8 = 0x10; +const PTR: u8 = 0x0f; +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture(PathBuf); + +impl Fixture { + fn parse(bytes: Vec) -> InterfaceMeta { + let directory = Self( + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("target") + .join(format!( + "winrt-raw-signature-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )), + ); + fs::create_dir_all(&directory.0).unwrap(); + let path = directory.0.join("Input.winmd"); + fs::write(&path, bytes).unwrap(); + meta::parse_interfaces(path.to_str().unwrap(), NAMESPACE) + .into_iter() + .find(|interface| interface.name == "IProbe") + .expect("writer-authored WinMD must contain IProbe") + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +fn add_iid(file: &mut writer::File, definition: writer::HasAttribute, id: u32) { + let attribute = file.TypeRef("Windows.Foundation.Metadata", "GuidAttribute"); + let constructor = file.MemberRef( + ".ctor", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types: vec![ + Type::U32, + Type::U16, + Type::U16, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + ], + }, + writer::MemberRefParent::TypeRef(attribute), + ); + file.Attribute( + definition, + writer::AttributeType::MemberRef(constructor), + &[ + Value::U32(id), + Value::U16(0x7ba5), + Value::U16(0x4036), + Value::U8(0xa0), + Value::U8(0x24), + Value::U8(1), + Value::U8(2), + Value::U8(3), + Value::U8(4), + Value::U8(5), + Value::U8(6), + ] + .into_iter() + .map(|value| (String::new(), value)) + .collect::>(), + ); +} + +fn add_method( + file: &mut writer::File, + name: &str, + parameters: &[(String, Type, ParamAttributes)], + return_type: Type, +) { + file.MethodDef( + name, + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type, + types: parameters.iter().map(|(_, typ, _)| typ.clone()).collect(), + }, + MethodAttributes::Public + | MethodAttributes::Virtual + | MethodAttributes::Abstract + | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + for (position, (name, _, flags)) in parameters.iter().enumerate() { + file.Param(name, (position + 1).try_into().unwrap(), *flags); + } +} + +fn fixture( + parameters: Vec<(String, Type, ParamAttributes)>, + return_type: Type, + delegate: bool, +) -> Vec { + fixture_file(parameters, return_type, delegate).into_stream() +} + +fn fixture_file( + parameters: Vec<(String, Type, ParamAttributes)>, + return_type: Type, + delegate: bool, +) -> writer::File { + let mut file = writer::File::new("RawSignatureControls"); + let interface_flags = TypeAttributes::Public + | TypeAttributes::Abstract + | TypeAttributes::Interface + | TypeAttributes::WindowsRuntime; + let interface = file.TypeDef( + NAMESPACE, + "IProbe", + writer::TypeDefOrRef::default(), + interface_flags, + ); + add_iid( + &mut file, + writer::HasAttribute::TypeDef(interface), + 0x509f6031, + ); + if delegate { + add_method( + &mut file, + "Take", + &[parameter( + "callback", + Type::named(NAMESPACE, "Callback"), + ParamAttributes::In, + )], + Type::Void, + ); + } else { + add_method(&mut file, "Take", ¶meters, return_type.clone()); + } + + let generic = file.TypeDef( + NAMESPACE, + "IBox`1", + writer::TypeDefOrRef::default(), + interface_flags, + ); + add_iid( + &mut file, + writer::HasAttribute::TypeDef(generic), + 0x509f6032, + ); + file.GenericParam( + "T", + writer::TypeOrMethodDef::TypeDef(generic), + 0, + GenericParamAttributes::default(), + ); + let modifier = file.TypeDef( + NAMESPACE, + "IgnoredModifier", + writer::TypeDefOrRef::default(), + TypeAttributes::Public, + ); + assert_eq!(writer::TypeDefOrRef::TypeDef(modifier).encode(), 0x10); + + if delegate { + let base = file.TypeRef("System", "MulticastDelegate"); + let callback = file.TypeDef( + NAMESPACE, + "Callback", + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + add_iid( + &mut file, + writer::HasAttribute::TypeDef(callback), + 0x509f6033, + ); + add_method(&mut file, ".ctor", &[], Type::Void); + add_method(&mut file, "Invoke", ¶meters, return_type); + } + file +} + +fn parameter(name: &str, typ: Type, flags: ParamAttributes) -> (String, Type, ParamAttributes) { + (name.into(), typ, flags) +} + +fn with_method( + bytes: &[u8], + delegate: bool, + read: impl FnOnce(reader::MethodDef<'_>, usize) -> T, +) -> T { + let image = bytes.to_vec(); + let image_address = image.as_ptr() as usize; + let index = reader::Index::new(vec![reader::File::new(image).unwrap()]); + let definition = index + .get(NAMESPACE, if delegate { "Callback" } else { "IProbe" }) + .next() + .unwrap(); + let method = definition + .methods() + .find(|method| method.name() == if delegate { "Invoke" } else { "Take" }) + .unwrap(); + read(method, image_address) +} + +fn raw_signature(bytes: &[u8], delegate: bool) -> Vec { + with_method(bytes, delegate, |method, _| { + let mut blob = method.blob(4); + (0..blob.len()).map(|_| blob.read_u8()).collect() + }) +} + +fn patch_signature(mut bytes: Vec, delegate: bool, edit: impl FnOnce(&mut [u8])) -> Vec { + let (offset, original) = with_method(&bytes, delegate, |method, image_address| { + let mut blob = method.blob(4); + // File::new retains its input Vec; locate this MethodDef's actual blob, + // not an incidental matching byte sequence elsewhere in the PE image. + let offset = (blob.as_ptr() as usize).checked_sub(image_address).unwrap(); + let signature = (0..blob.len()).map(|_| blob.read_u8()).collect::>(); + (offset, signature) + }); + let payload = bytes.get_mut(offset..offset + original.len()).unwrap(); + assert_eq!(payload, original); + edit(payload); + let expected = payload.to_vec(); + assert_eq!(raw_signature(&bytes, delegate), expected); + bytes +} + +fn pointer_to_byref(bytes: Vec, delegate: bool) -> Vec { + patch_signature(bytes, delegate, |signature| { + let pointer = signature.len() - 2; + assert_eq!(&signature[pointer..], &[PTR, 0x08]); + signature[pointer] = BYREF; + }) +} + +fn generated(interface: &InterfaceMeta) -> [String; 4] { + let known = HashSet::from([interface.name.clone()]); + let projected = project::project_interface( + &Default::default(), + interface, + &known, + &HashSet::new(), + &HashMap::new(), + &HashMap::new(), + &HashMap::new(), + ); + let context = common::projection_context( + &[], + std::slice::from_ref(interface), + &known, + &HashSet::new(), + ); + [ + render_js::render(&projected), + render_dts::render(&projected), + python::generate_interface(&context, interface), + python_stub::generate_interface_stub(&context, interface), + ] +} + +fn assert_implementable(interface: &InterfaceMeta) { + assert!( + interface.implementation_metadata.diagnostics.is_empty(), + "{:?}", + interface.implementation_metadata.diagnostics + ); + let [js, dts, py, pyi] = generated(interface); + assert!(js.contains("DynWinRtImplementationHandle.create"), "{js}"); + assert!( + dts.contains("IProbeHandlers") && !dts.contains("handlers: never"), + "{dts}" + ); + assert!(py.contains("DynWinRTImplementationHandle._create"), "{py}"); + assert!(pyi.contains("def implement("), "{pyi}"); +} + +fn assert_rejected(interface: &InterfaceMeta, diagnostic: &str) { + assert!( + interface + .implementation_metadata + .diagnostics + .iter() + .any(|reason| reason.contains(diagnostic)), + "missing {diagnostic:?} in {:?}", + interface.implementation_metadata.diagnostics + ); + let [js, dts, py, pyi] = generated(interface); + for (extension, output) in [("js", &js), ("d.ts", &dts), ("py", &py), ("pyi", &pyi)] { + assert!(output.contains(diagnostic), "{extension}: {output}"); + assert!(output.contains("class IProbe"), "{extension}: {output}"); + } + assert!(!js.contains("DynWinRtImplementationHandle.create")); + assert!(!py.contains("DynWinRTImplementationHandle._create")); + assert!(dts.contains("handlers: never")); + assert!(!pyi.contains("def implement(")); +} + +#[test] +fn scalar_byref_input_fails_closed_without_changing_outbound_metadata() { + for flags in [ParamAttributes::In, ParamAttributes::default()] { + let value = fixture( + vec![parameter("value", Type::I32, flags)], + Type::Void, + false, + ); + let pointer = fixture( + vec![parameter( + "value", + Type::PtrMut(Box::new(Type::I32), 1), + flags, + )], + Type::Void, + false, + ); + let byref = pointer_to_byref(pointer.clone(), false); + assert_eq!(raw_signature(&value, false), [0x20, 1, 1, 0x08]); + assert_eq!(raw_signature(&pointer, false), [0x20, 1, 1, PTR, 0x08]); + assert_eq!(raw_signature(&byref, false), [0x20, 1, 1, BYREF, 0x08]); + for bytes in [&value, &byref] { + assert_eq!( + with_method(bytes, false, |method, _| method.signature(&[]).types), + [Type::I32], + "upstream 0.59 erases scalar BYREF" + ); + } + assert_eq!( + with_method(&pointer, false, |method, _| method.signature(&[]).types), + [Type::PtrMut(Box::new(Type::I32), 1)] + ); + let value = Fixture::parse(value); + let byref = Fixture::parse(byref); + assert_implementable(&value); + assert_rejected(&Fixture::parse(pointer), "unsupported native type PtrMut"); + assert_rejected(&byref, "input BYREF"); + assert!( + byref + .implementation_metadata + .diagnostics + .iter() + .any(|reason| { + reason.contains("Take") && reason.contains("value") && reason.contains("BYREF") + }) + ); + assert_eq!( + format!("{:?}", value.methods), + format!("{:?}", byref.methods), + "reverse evidence must not rewrite permissive outbound metadata" + ); + let [js, dts, py, pyi] = generated(&byref); + assert!( + js.contains("take(value)") && js.contains(".addIn(DynWinRtType.i32())"), + "{js}" + ); + assert!(dts.contains("take(value: number): void"), "{dts}"); + assert!( + py.contains("def take(") && py.contains(".add_in(DynWinRTType.i32_type())"), + "{py}" + ); + assert!( + pyi.contains("value: int") && pyi.contains("def take("), + "{pyi}" + ); + } +} + +#[test] +fn modifiers_are_tokens_not_reference_markers_and_cannot_hide_byref() { + for modifier in [0x1f, 0x20] { + for byref in [false, true] { + let inner = if byref { + Type::PtrMut(Box::new(Type::I32), 1) + } else { + Type::I32 + }; + let bytes = fixture( + vec![parameter( + "value", + Type::ConstRef(Box::new(inner)), + ParamAttributes::In, + )], + Type::Void, + false, + ); + let bytes = patch_signature(bytes, false, |signature| { + assert_eq!(&signature[..4], &[0x20, 1, 1, 0x1f]); + assert!(signature[4] < 0x80); + signature[3] = modifier; + signature[4] = 0x10; // TypeDefOrRefEncoded for IgnoredModifier, not BYREF. + if byref { + assert_eq!(&signature[5..], &[PTR, 0x08]); + signature[5] = BYREF; + } else { + assert_eq!(&signature[5..], &[0x08]); + } + }); + let interface = Fixture::parse(bytes); + if byref { + assert_rejected(&interface, "input BYREF"); + } else { + assert_implementable(&interface); + } + } + } +} + +fn boxed(typ: Type) -> Type { + Type::Name(TypeName { + namespace: NAMESPACE.into(), + name: "IBox`1".into(), + generics: vec![typ], + }) +} + +#[test] +fn scalar_out_and_pass_fill_receive_arrays_preserve_their_contracts() { + for delegate in [false, true] { + let bytes = fixture( + vec![ + parameter( + "pass", + Type::Array(Box::new(Type::I32)), + ParamAttributes::In, + ), + parameter( + "fill", + Type::Array(Box::new(Type::I32)), + ParamAttributes::Out, + ), + parameter( + "receive", + Type::ArrayRef(Box::new(Type::I32)), + ParamAttributes::Out, + ), + parameter("plainScalar", Type::I32, ParamAttributes::Out), + parameter( + "scalar", + Type::PtrMut(Box::new(Type::I32), 1), + ParamAttributes::Out, + ), + ], + Type::Array(Box::new(Type::I32)), + delegate, + ); + let interface = Fixture::parse(pointer_to_byref(bytes, delegate)); + assert_implementable(&interface); + let method = if delegate { + &interface.implementation_metadata.delegates[0].invoke + } else { + &interface.methods[0] + }; + assert_eq!( + method + .params + .iter() + .map(|parameter| ¶meter.direction) + .collect::>(), + [ + &ParamDirection::In, + &ParamDirection::OutFill, + &ParamDirection::Out, + &ParamDirection::Out, + &ParamDirection::Out + ] + ); + assert_eq!(method.params[3].typ, TypeMeta::I32); + assert_eq!(method.params[4].typ, TypeMeta::I32); + assert_eq!( + method.return_type, + Some(TypeMeta::Array(Box::new(TypeMeta::I32))) + ); + } +} + +#[test] +fn nested_generic_values_and_counts_do_not_shift_parameter_evidence() { + let nested = boxed(boxed(Type::I32)); + let mut parameters = vec![ + parameter("nested", nested.clone(), ParamAttributes::In), + parameter( + "pass", + Type::Array(Box::new(nested.clone())), + ParamAttributes::In, + ), + parameter( + "fill", + Type::Array(Box::new(nested.clone())), + ParamAttributes::Out, + ), + parameter( + "receive", + Type::ArrayRef(Box::new(nested.clone())), + ParamAttributes::Out, + ), + ]; + parameters + .extend((4..16).map(|position| { + parameter(&format!("value{position}"), Type::I32, ParamAttributes::In) + })); + let valid = fixture(parameters.clone(), nested.clone(), false); + assert_eq!( + raw_signature(&valid, false)[1], + BYREF, + "parameter count is not a type qualifier" + ); + assert_implementable(&Fixture::parse(valid)); + parameters.last_mut().unwrap().1 = Type::PtrMut(Box::new(Type::I32), 1); + let byref = pointer_to_byref(fixture(parameters, nested, false), false); + let interface = Fixture::parse(byref); + assert_rejected(&interface, "input BYREF"); + assert!( + interface + .implementation_metadata + .diagnostics + .iter() + .any(|reason| reason.contains("value15")) + ); +} + +#[test] +fn delegate_invoke_cannot_bypass_raw_input_reference_validation() { + let value = fixture( + vec![parameter("value", Type::I32, ParamAttributes::In)], + Type::I32, + true, + ); + assert_implementable(&Fixture::parse(value)); + let pointer = fixture( + vec![parameter( + "value", + Type::PtrMut(Box::new(Type::I32), 1), + ParamAttributes::In, + )], + Type::I32, + true, + ); + assert_rejected( + &Fixture::parse(pointer.clone()), + "unsupported native type PtrMut", + ); + let byref = Fixture::parse(pointer_to_byref(pointer, true)); + assert_rejected(&byref, "input BYREF"); + assert!( + byref + .implementation_metadata + .diagnostics + .iter() + .any(|reason| { + reason.contains("Callback") && reason.contains("Invoke") && reason.contains("value") + }) + ); +} + +#[test] +fn byref_return_is_not_erased_into_a_logical_value_output() { + for delegate in [false, true] { + let value = fixture(vec![], Type::I32, delegate); + assert_implementable(&Fixture::parse(value)); + let pointer = fixture(vec![], Type::PtrMut(Box::new(Type::I32), 1), delegate); + let byref = pointer_to_byref(pointer, delegate); + assert_eq!(raw_signature(&byref, delegate), [0x20, 0, BYREF, 0x08]); + assert_eq!( + with_method(&byref, delegate, |method, _| method + .signature(&[]) + .return_type), + Type::I32 + ); + assert_rejected(&Fixture::parse(byref), "BYREF return"); + } +} + +fn struct_fixture(field_type: Type, delegate: bool) -> Vec { + let mut file = fixture_file( + vec![parameter( + "container", + Type::named(NAMESPACE, "Container"), + ParamAttributes::In, + )], + Type::Void, + delegate, + ); + let base = file.TypeRef("System", "ValueType"); + let flags = TypeAttributes::Public + | TypeAttributes::Sealed + | TypeAttributes::SequentialLayout + | TypeAttributes::WindowsRuntime; + file.TypeDef( + NAMESPACE, + "Payload", + writer::TypeDefOrRef::TypeRef(base), + flags, + ); + file.Field("Value", &field_type, FieldAttributes::Public); + file.TypeDef( + NAMESPACE, + "Container", + writer::TypeDefOrRef::TypeRef(base), + flags, + ); + file.Field( + "Payload", + &Type::named(NAMESPACE, "Payload"), + FieldAttributes::Public, + ); + file.into_stream() +} + +fn with_field(bytes: &[u8], read: impl FnOnce(reader::Field<'_>, usize) -> T) -> T { + let image = bytes.to_vec(); + let image_address = image.as_ptr() as usize; + let index = reader::Index::new(vec![reader::File::new(image).unwrap()]); + let definition = index.get(NAMESPACE, "Payload").next().unwrap(); + let field = definition.fields().next().unwrap(); + read(field, image_address) +} + +#[test] +fn recursive_struct_fields_cannot_erase_byref_into_a_value_layout() { + for delegate in [false, true] { + let value = struct_fixture(Type::I32, delegate); + let pointer = struct_fixture(Type::PtrMut(Box::new(Type::I32), 1), delegate); + let (offset, raw) = with_field(&pointer, |field, image_address| { + assert_eq!(field.ty(), Type::PtrMut(Box::new(Type::I32), 1)); + let mut blob = field.blob(2); + let offset = (blob.as_ptr() as usize).checked_sub(image_address).unwrap(); + let signature = (0..blob.len()).map(|_| blob.read_u8()).collect::>(); + (offset, signature) + }); + assert_eq!(raw, [0x06, PTR, 0x08]); + let mut byref = pointer.clone(); + assert_eq!(&byref[offset..offset + raw.len()], raw); + byref[offset + 1] = BYREF; + with_field(&byref, |field, _| { + let mut blob = field.blob(2); + let signature = (0..blob.len()).map(|_| blob.read_u8()).collect::>(); + assert_eq!(signature, [0x06, BYREF, 0x08]); + assert_eq!( + field.ty(), + Type::I32, + "upstream also erases scalar field BYREF" + ); + }); + let value = Fixture::parse(value); + assert_implementable(&value); + assert_rejected(&Fixture::parse(pointer), "unsupported native type PtrMut"); + let byref = Fixture::parse(byref); + assert_rejected(&byref, "BYREF field"); + let method = if delegate { "Invoke" } else { "Take" }; + assert!( + byref + .implementation_metadata + .diagnostics + .iter() + .any(|reason| { + reason.contains("Payload") + && reason.contains("Value") + && reason.contains(method) + }) + ); + assert_eq!( + format!("{:?}", value.methods), + format!("{:?}", byref.methods) + ); + } +} + +#[test] +fn receive_array_input_stays_unsupported() { + for delegate in [false, true] { + let bytes = fixture( + vec![parameter( + "receive", + Type::ArrayRef(Box::new(Type::I32)), + ParamAttributes::In, + )], + Type::Void, + delegate, + ); + assert_rejected(&Fixture::parse(bytes), "input BYREF"); + } +} + +#[test] +fn stock_winrt_scalar_out_and_array_signatures_remain_implementable() { + let winmd = r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; + if !Path::new(winmd).is_file() { + eprintln!("Skipping stock signature controls: Windows.winmd is unavailable"); + return; + } + let foundation = meta::parse_interfaces(winmd, "Windows.Foundation"); + let mut interfaces = ["IStringable", "IClosable", "IPropertyValue"] + .into_iter() + .map(|name| { + foundation + .iter() + .find(|interface| interface.name == name) + .unwrap() + .clone() + }) + .collect::>(); + interfaces.push( + meta::parse_class(winmd, "Windows.Storage.Streams", "DataReader") + .unwrap() + .default_interface + .unwrap(), + ); + for interface in interfaces { + assert!( + interface.implementation_metadata.diagnostics.is_empty(), + "{}: {:?}", + interface.name, + interface.implementation_metadata.diagnostics + ); + let [js, dts, py, pyi] = generated(&interface); + assert!(js.contains("DynWinRtImplementationHandle.create"), "{js}"); + assert!(!dts.contains("handlers: never"), "{dts}"); + assert!(py.contains("DynWinRTImplementationHandle._create"), "{py}"); + assert!(pyi.contains("def implement("), "{pyi}"); + eprintln!("Validated stock signature evidence for {}", interface.name); + } +} From 8369f92d5b94fff1129ca58384d4b8fed5253197 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Thu, 10 Sep 2026 17:40:41 +0800 Subject: [PATCH 8/8] fix: replace complete Python implementation root export sets Reconcile root visibility independently of helper renames using structured owner records and explicit old/current source replacement, including empty export sets. Preserve namespace views, pair unions, unrelated aliases, runtime-only generation, and atomic output. Cover single-to-ambiguous binary metadata, stable helper names, regenerated owners, star imports, strict typing, and source-path replacement. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/dynwinrt-codegen/README.md | 2 + .../src/codegen/winrt/python/naming.rs | 11 + tools/dynwinrt-codegen/src/main.rs | 168 +++++++++++++-- .../tests/implementation_naming_test.rs | 202 ++++++++++++++++++ 4 files changed, 361 insertions(+), 22 deletions(-) diff --git a/tools/dynwinrt-codegen/README.md b/tools/dynwinrt-codegen/README.md index b40a5518..22487db0 100644 --- a/tools/dynwinrt-codegen/README.md +++ b/tools/dynwinrt-codegen/README.md @@ -130,6 +130,8 @@ remain unchanged. Implementation helper names are allocated alongside metadata types and follow their owning interfaces through incremental renames. Python's package-level +root exports drop an interface and its helpers when its short name becomes +ambiguous, while namespace imports remain available. Python's heterogeneous interface-pair union is generated from validated inventory records, not inferred from `.pyi` text. The first typed incremental generation over an older inventory needs the original WinMD/`--ref` inputs for interfaces diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 8dad5c5c..82458af6 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -806,6 +806,17 @@ impl PythonProjectionContext { .to_string() } + pub fn public_qualified_module_for_export( + &self, + identity: &PythonTypeIdentity, + projected_name: &str, + ) -> String { + let identity = self.normalize_identity(identity); + let mut segments = python_namespace_segments(identity.namespace().unwrap_or_default()); + segments.push(public_module_name(&identity, projected_name)); + segments.join(".") + } + pub fn root_name_is_unambiguous(&self, identity: &PythonTypeIdentity) -> bool { self.compatibility_counts .get(&legacy_projected_name(identity)) diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index fa839d4f..2fd43e93 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -4088,6 +4088,7 @@ fn generate_py_files( let marker = output_dir.join("py.typed"); write_file(&marker, "")?; } + reconcile_python_implementation_root_exports(context, output_dir, &previous, &types, pyi)?; write_python_type_inventory(output_dir, &types)?; Ok(()) } @@ -4395,32 +4396,80 @@ fn reconcile_retained_python_helpers( &HashSet::new(), )?; } - if context.root_name_is_unambiguous(&typ.identity) { - let symbols = std::iter::once(item.interface_export.as_str()) + } + Ok(()) +} + +fn reconcile_python_implementation_root_exports( + context: &python::PythonProjectionContext, + output_dir: &Path, + previous: &[PythonGeneratedType], + current: &[PythonGeneratedType], + pyi: bool, +) -> Result<(), String> { + let mut replaced_modules = HashSet::new(); + let mut generated = String::from(GENERATED_PYTHON_HEADER); + for typ in current { + let old = previous + .iter() + .find(|old| old.identity == typ.identity) + .and_then(|old| old.implementation.as_ref()); + let item = typ.implementation.as_ref(); + if old.is_none() && item.is_none() { + continue; + } + replaced_modules.extend([ + format!(".{}", context.implementation_module(&typ.identity)), + format!(".{}", context.public_qualified_module(&typ.identity)), + ]); + for record in old.into_iter().chain(item) { + replaced_modules.insert(format!(".{}", record.module)); + replaced_modules.insert(format!( + ".{}", + context.public_qualified_module_for_export(&typ.identity, &record.interface_export) + )); + } + if let Some(item) = item + .filter(|item| item.pair_eligible && context.root_name_is_unambiguous(&typ.identity)) + { + let module = context.public_qualified_module(&typ.identity); + for name in std::iter::once(item.interface_export.as_str()) .chain(item.helpers.iter().map(|helper| helper.name.as_str())) - .map(|name| format!("{name} as {name}")) - .collect::>() - .join(", "); - let root = format!( - "{GENERATED_PYTHON_HEADER}from .{} import {symbols}\n", - context.public_qualified_module(&typ.identity) - ); - write_python_lazy_root_index( - &output_dir.join("__init__.py"), - &root, - true, - &HashSet::new(), - )?; - if pyi { - write_python_index( - &output_dir.join("__init__.pyi"), - &root, - true, - &HashSet::new(), - )?; + { + generated.push_str(&format!("from .{module} import {name} as {name}\n")); } } } + if replaced_modules.is_empty() { + return Ok(()); + } + // Visibility is independent of helper spelling. An empty set removes + // an owner's old root exports without touching its namespace facade. + for extension in if pyi { &["py", "pyi"][..] } else { &["py"][..] } { + let path = output_dir.join(format!("__init__.{extension}")); + let existing = if path.is_file() { + fs::read_to_string(&path) + .map_err(|error| format!("Failed to read {}: {error}", path.display()))? + } else { + GENERATED_PYTHON_HEADER.to_string() + }; + let content = if *extension == "py" { + merge_python_lazy_root_indexes_replacing( + &existing, + &generated, + &HashSet::new(), + &replaced_modules, + ) + } else { + merge_python_indexes_replacing( + &existing, + &generated, + &HashSet::new(), + &replaced_modules, + ) + }; + write_file(&path, &content)?; + } Ok(()) } @@ -4929,12 +4978,22 @@ fn merge_python_lazy_root_indexes( existing: &str, generated: &str, suppressed_names: &HashSet, +) -> String { + merge_python_lazy_root_indexes_replacing(existing, generated, suppressed_names, &HashSet::new()) +} + +fn merge_python_lazy_root_indexes_replacing( + existing: &str, + generated: &str, + suppressed_names: &HashSet, + replaced_modules: &HashSet, ) -> String { let mut exports = BTreeMap::::new(); collect_python_root_exports(generated, suppressed_names, &mut exports); let replaced_modules = exports .values() .map(|(module, _)| module.clone()) + .chain(replaced_modules.iter().cloned()) .collect::>(); let mut retained = BTreeMap::new(); collect_python_root_exports(existing, suppressed_names, &mut retained); @@ -5046,6 +5105,15 @@ fn merge_python_indexes( existing: &str, generated: &str, suppressed_names: &HashSet, +) -> String { + merge_python_indexes_replacing(existing, generated, suppressed_names, &HashSet::new()) +} + +fn merge_python_indexes_replacing( + existing: &str, + generated: &str, + suppressed_names: &HashSet, + replaced_modules: &HashSet, ) -> String { let mut imports = BTreeSet::new(); let mut exported_symbols = HashSet::new(); @@ -5056,6 +5124,7 @@ fn merge_python_indexes( .lines() .filter_map(parse_python_import_line) .map(|(module, _)| module) + .chain(replaced_modules.iter().cloned()) .collect::>(); let retained = existing.lines().filter(|line| { parse_python_import_line(line).is_none_or(|(module, _)| !replaced_modules.contains(&module)) @@ -10806,6 +10875,61 @@ mod tests { assert!(!appended.contains("\"Second\": (")); } + #[test] + fn python_root_replacement_removes_empty_owners_and_previous_source_paths() { + type Merge = fn(&str, &str, &HashSet, &HashSet) -> String; + for merge in [ + merge_python_lazy_root_indexes_replacing as Merge, + merge_python_indexes_replacing as Merge, + ] { + let prior = format!( + "{GENERATED_PYTHON_HEADER}\ +from .old.facade import IWidget as IWidget\n\ +from .old__canonical import IWidgetHandlers as OldHandlers\n\ +from .third.facade import IWidgetHandlers as IWidgetHandlers, Stable as PublicStable\n" + ); + let owned = HashSet::from([ + ".old.facade".to_string(), + ".old__canonical".to_string(), + ".new.facade".to_string(), + ]); + let existing = merge( + GENERATED_PYTHON_HEADER, + &prior, + &HashSet::new(), + &HashSet::new(), + ); + for replacement in [ + GENERATED_PYTHON_HEADER.to_string(), + format!( + "{GENERATED_PYTHON_HEADER}from .new.facade import NewWidget as NewWidget\n" + ), + ] { + let merged = merge(&existing, &replacement, &HashSet::new(), &owned); + let mut exports = BTreeMap::new(); + collect_python_root_exports(&merged, &HashSet::new(), &mut exports); + assert!(!exports.contains_key("IWidget")); + assert!(!exports.contains_key("OldHandlers")); + assert_eq!( + exports["IWidgetHandlers"], + (".third.facade".into(), "IWidgetHandlers".into()) + ); + assert_eq!( + exports["PublicStable"], + (".third.facade".into(), "Stable".into()) + ); + assert_eq!( + exports.contains_key("NewWidget"), + replacement.contains("NewWidget") + ); + assert_eq!( + merged, + merge(&merged, &replacement, &HashSet::new(), &owned) + ); + } + } + } + #[test] fn generated_inventory_does_not_claim_nested_manual_metadata() { let output = test_directory("manual-metadata"); diff --git a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs index 46328ebd..2f3acc2c 100644 --- a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs +++ b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs @@ -813,6 +813,208 @@ fn python_inventory_migration_uses_metadata_not_stub_text_and_fails_atomically() } } +#[test] +fn python_root_exports_follow_single_to_ambiguous_owner_visibility() { + for pyi in [true, false] { + for first in ["Alpha", "Beta"] { + check_root_owner_visibility(first, "IStable", pyi, false); + } + } +} + +#[test] +fn python_root_visibility_changes_even_when_helper_names_do_not() { + check_root_owner_visibility("Alpha", "IWidgetHandlers", true, false); +} + +#[test] +fn python_root_exports_also_replace_regenerated_owners_with_empty_sets() { + check_root_owner_visibility("Alpha", "IStable", true, true); +} + +fn check_root_owner_visibility(first: &str, unrelated: &str, pyi: bool, regenerate_first: bool) { + let fixture = Fixture::new(); + let alpha = ("Alpha", "IWidget", "ReadAlpha", 0x31d44791); + let beta = ("Beta", "IWidget", "ReadBeta", 0x31d44792); + let stable = ("Third", unrelated, "ReadThird", 0x31d44793); + let (first_type, second_type) = if first == "Alpha" { + (alpha, beta) + } else { + (beta, alpha) + }; + let initial = fixture.0.join("initial").join("Initial.winmd"); + let extra = fixture.0.join("extra").join("Extra.winmd"); + let third = fixture.0.join("third").join("Third.winmd"); + let combined = fixture.0.join("combined").join("Combined.winmd"); + names(&initial, &[first_type]); + names(&extra, &[second_type]); + names(&third, &[stable]); + names(&combined, &[alpha, beta, stable]); + let output = fixture.0.join("incremental"); + let clean = fixture.0.join("clean"); + let options = if pyi { &[][..] } else { &["--no-pyi"][..] }; + success(generate( + &initial, + &output, + "py", + &format!("{}.IWidget", first_type.0), + options, + )); + assert!( + fs::read_to_string(output.join("__init__.py")) + .unwrap() + .contains("\"IWidgetHandlers\"") + ); + success(generate( + &third, + &output, + "py", + &format!("Third.{unrelated}"), + options, + )); + let before = python_inventory(&output); + let old_owner = before + .iter() + .find(|record| record["identity"]["namespace"] == first) + .unwrap(); + let unchanged_module = before + .iter() + .find(|record| record["identity"]["namespace"] == "Third") + .unwrap()["implementation"]["module"] + .as_str() + .unwrap(); + let unchanged_source = fs::read(output.join(format!("{unchanged_module}.py"))).unwrap(); + let selected = if regenerate_first { + "Alpha.IWidget,Beta.IWidget".to_string() + } else { + format!("{}.IWidget", second_type.0) + }; + let extra_options = if regenerate_first { + vec!["--ref", initial.to_str().unwrap()] + } else { + options.to_vec() + }; + success(generate(&extra, &output, "py", &selected, &extra_options)); + success(generate( + &combined, + &clean, + "py", + &format!("Alpha.IWidget,Beta.IWidget,Third.{unrelated}"), + options, + )); + let after = python_inventory(&output); + if unrelated == "IWidgetHandlers" { + let owner = after + .iter() + .find(|record| record["identity"]["namespace"] == first) + .unwrap(); + assert_eq!( + old_owner["implementation"]["helpers"], + owner["implementation"]["helpers"] + ); + } + if runtime_available() { + success(Command::new(python()).args(["-I", "-c", r#" +import importlib +import json +from pathlib import Path +import sys +sys.path.insert(0, sys.argv[1]) +import incremental +import clean +namespace = {} +exec("from incremental import *", namespace) +exec("from clean import *", {}) +assert set(incremental.__all__) == set(clean.__all__) +assert incremental._EXPORTS == clean._EXPORTS +assert "IWidget" not in incremental.__all__ +for name in incremental.__all__: + assert namespace[name] is getattr(incremental, name) +third_name = sys.argv[2] +assert hasattr(getattr(incremental, third_name), "from_value") +if third_name != "IWidgetHandlers": + assert "IWidgetHandlers" not in incremental.__all__ +records = [json.loads(line) for line in (Path(sys.argv[1]) / "incremental" / ".dynwinrt-generated-types").read_text().splitlines()] +views = {} +for ns in ("Alpha", "Beta"): + record = next(record for record in records if record["identity"]["namespace"] == ns) + facade = importlib.import_module("incremental." + ns.lower() + ".i_widget") + namespace_module = importlib.import_module("incremental." + ns.lower()) + helper = record["implementation"]["handler_export"] + assert getattr(facade, helper) is getattr(namespace_module, helper) + assert helper not in incremental.__all__ + views[ns] = facade.IWidget +class Alpha: + def read_alpha(self): return 17 +class Beta: + def read_beta(self): return 23 +from dynwinrt import RoApartment, release_projected +with RoApartment(1), views["Alpha"].implement(Alpha(), interfaces=[(views["Beta"], Beta())]) as impl: + assert impl.value.read_alpha() == 17 + other = views["Beta"].from_implementation(impl) + try: assert other.read_beta() == 23 + finally: release_projected(other) +"#]).arg(&fixture.0).arg(unrelated).output().unwrap()); + } + assert_eq!( + fs::read_to_string(output.join("__init__.py")).unwrap(), + fs::read_to_string(clean.join("__init__.py")).unwrap() + ); + assert_eq!( + unchanged_source, + fs::read(output.join(format!("{unchanged_module}.py"))).unwrap() + ); + if pyi { + assert_eq!( + fs::read_to_string(output.join("__init__.pyi")).unwrap(), + fs::read_to_string(clean.join("__init__.pyi")).unwrap() + ); + assert_eq!( + fs::read(output.join("_implementation_types.pyi")).unwrap(), + fs::read(clean.join("_implementation_types.pyi")).unwrap() + ); + let handler = |ns: &str| { + after + .iter() + .find(|record| record["identity"]["namespace"] == ns) + .unwrap()["implementation"]["handler_export"] + .as_str() + .unwrap() + }; + typecheck_py( + &fixture.0, + &format!( + r#" +from incremental import * +from incremental.alpha.i_widget import IWidget as AlphaWidget, {alpha_handler} +from incremental.beta.i_widget import IWidget as BetaWidget, {beta_handler} +from typing import assert_type +class Alpha: + def read_alpha(self) -> int: return 17 +class Beta: + def read_beta(self) -> int: return 23 +class Third: + def read_third(self) -> int: return 31 +a: {alpha_handler} = Alpha() +b: {beta_handler} = Beta() +with AlphaWidget.implement(a, interfaces=[(BetaWidget, b)]) as impl: + assert_type(impl.value, AlphaWidget) +with {unrelated}.implement(Third()) as third: + assert_type(third.value, {unrelated}) +"#, + alpha_handler = handler("Alpha"), + beta_handler = handler("Beta") + ), + ); + } else { + assert!(!output.join("__init__.pyi").exists()); + assert!(!output.join("_implementation_types.pyi").exists()); + } + let repeated = snapshot(&output); + success(generate(&extra, &output, "py", &selected, &extra_options)); + assert_eq!(repeated, snapshot(&output)); +} + #[test] fn typed_append_after_no_pyi_requires_regenerating_missing_declarations() { let fixture = Fixture::new();