From 8fccf98d7389b6146b5e7cea7ba9810564a1bbc4 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Tue, 8 Sep 2026 05:59:39 +0800 Subject: [PATCH] Project ambiguous COM overloads as explicit slot-named methods Preserve existing arity/shape dispatch for distinguishable groups. Emit stable AtSlot names for previously unsupported ordinary overloads without guessing ABI behavior, retain each validated method plan, reject alias collisions, and update exact coverage evidence. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 9ef7fa55-eb2a-4360-bd17-05feae50fadb --- .github/workflows/build.yml | 28 +- README.md | 18 +- .../classic-com-contract-evidence-registry.md | 42 ++- .../classic-com-generated-unsafe.md | 31 +- docs/architecture/classic-com-support.md | 43 ++- docs/guides/windows/classic-com-usage.md | 31 ++ docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md | 61 ++-- .../classic-com-capability-summary.json | 48 +-- .../classic-com-interface-support.csv | 48 +-- .../src/codegen/com/capability.rs | 24 +- tools/dynwinrt-codegen/src/codegen/com/ir.rs | 7 +- .../src/codegen/com/project/mod.rs | 298 ++++++++++++++++-- .../tests/com_explicit_overload_test.rs | 186 +++++++++++ 13 files changed, 711 insertions(+), 154 deletions(-) create mode 100644 tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 84e1d2e3..b3b6a31a 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -92,7 +92,7 @@ jobs: if ($result.eligible_interfaces -ne 7929) { throw "Classic COM census denominator changed: $($result.eligible_interfaces)" } - if ($result.complete_interfaces -lt 5697) { + if ($result.complete_interfaces -lt 5721) { throw "Classic COM complete coverage regressed: $($result.complete_interfaces)" } if ($result.coverage_percent -lt 70.0) { @@ -109,14 +109,14 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $result = Get-Content (Join-Path $output 'classic-com-capability-summary.json') -Raw | ConvertFrom-Json - if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5697) { + if ($result.eligible_interfaces -ne 7929 -or $result.safe_complete -ne 5721) { throw "Classic COM safe totals changed in capability census" } $support = Import-Csv (Join-Path $output 'classic-com-interface-support.csv') if ( @($support).Count -ne 7929 -or - @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5697 -or - @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2232 + @($support | Where-Object { $_.safe_complete -eq 'true' }).Count -ne 5721 -or + @($support | Where-Object { $_.safe_complete -eq 'false' }).Count -ne 2208 ) { throw "Classic COM compact interface support index changed" } @@ -127,9 +127,9 @@ jobs: } } $expected = @{ - x64 = @(412, 1431, 389) - i686 = @(411, 1408, 413) - arm64 = @(412, 1431, 389) + x64 = @(388, 1431, 389) + i686 = @(387, 1408, 413) + arm64 = @(388, 1431, 389) } foreach ($target in @('x64', 'i686', 'arm64')) { $counts = $result.targets.$target @@ -142,16 +142,16 @@ jobs: } } if ( - $result.safeEvidence.safeComplete -ne 5697 -or - $result.safeEvidence.standardDerived -ne 5332 -or - $result.safeEvidence.exactRegistryDependent -ne 365 -or - $result.safeEvidence.metadataFactOccurrences -ne 5983 -or - $result.safeEvidence.comStandardFactOccurrences -ne 26134 -or + $result.safeEvidence.safeComplete -ne 5721 -or + $result.safeEvidence.standardDerived -ne 5355 -or + $result.safeEvidence.exactRegistryDependent -ne 366 -or + $result.safeEvidence.metadataFactOccurrences -ne 6012 -or + $result.safeEvidence.comStandardFactOccurrences -ne 26247 -or $result.safeEvidence.registeredExactEntries -ne 532 -or $result.safeEvidence.metadataMatchedExactEntries -ne 532 -or $result.safeEvidence.safeConsumedExactEntries -ne 431 -or - $result.safeEvidence.exactEntryInterfaceDependencies -ne 693 -or - $result.safeEvidence.exactFamilyInterfaceDependencies -ne 424 + $result.safeEvidence.exactEntryInterfaceDependencies -ne 694 -or + $result.safeEvidence.exactFamilyInterfaceDependencies -ne 425 ) { throw "Classic COM safe evidence dependency census changed" } diff --git a/README.md b/README.md index ffe26c57..48af4592 100644 --- a/README.md +++ b/README.md @@ -138,18 +138,20 @@ can omit the bootstrap call. Classic COM support is functional and tested, but remains a **preview under active development**. It targets a conservatively validated subset of `IUnknown`- and `IInspectable`-rooted interfaces from `Windows.Win32.winmd`; it -is not a general Automation or native Win32 projection, and it does not project -flat DLL exports. +is not a general Automation or native Win32 projection, and it does not provide +general flat DLL export projection. The current CI baseline against -`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,697 of 7,929 -eligible interfaces (71.85%)** with complete safe code generation. Supported +`Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is **5,721 of 7,929 +eligible interfaces (72.15%)** with complete safe code generation. Supported contracts include generated coclass activation and QueryInterface views, managed interface ownership, native POD layouts, typed counted buffers, BSTR/HSTRING, validated VARIANT, SAFEARRAY and PROPVARIANT subsets, the target-device-independent `TYMED_HGLOBAL` FORMATETC/STGMEDIUM subset, variable-length WAVEFORMATEX audio formats with exact CoTaskMem outputs, and synchronous JavaScript implementations of fully supported callback interfaces. +Separate bounded one-shot audio activation and owned-copy transactions are +also available; copy-only facades are not counted as complete interfaces. Seventeen stock-Windows Node E2E runners exercise representative Shell, Automation, stream, callback, HWND, and WinRT interop scenarios. @@ -178,6 +180,14 @@ the documented in-process, null-parameter audio endpoint subset and `activate(IAudioClient)` and `DynComAudioFormat.pcm()` format negotiation, without a per-interface native adapter. +Existing distinguishable overloads keep their APIs unchanged. Otherwise fully +validated normal COM overload groups with colliding JavaScript signatures or +projected buffers now expose every member as +`AtSlot`, with no ambiguous unsuffixed method. +This naming-only projection promotes 24 interfaces; it does not guess ABI +contracts or provide a universal overload parser. See the +[overload usage and limits](docs/guides/windows/classic-com-usage.md#58-explicit-overload-names). + - [Classic COM JavaScript usage guide](docs/guides/windows/classic-com-usage.md) - [Supported ABI, coverage, limitations, and ownership model](docs/architecture/classic-com-support.md) diff --git a/docs/architecture/classic-com-contract-evidence-registry.md b/docs/architecture/classic-com-contract-evidence-registry.md index 6284f7f3..0eb1870e 100644 --- a/docs/architecture/classic-com-contract-evidence-registry.md +++ b/docs/architecture/classic-com-contract-evidence-registry.md @@ -348,7 +348,7 @@ Current code registries are migrated without changing behavior: - exact fail-closed hazards such as `GetPrivateData`. Migration or promotion is complete only when generated safe snapshots, the -5,697/7,929 safe census, generated unsafe manifests, and all live tests agree +5,721/7,929 safe census, generated unsafe manifests, and all live tests agree with the exact evidence dependencies. ## User contracts @@ -434,19 +434,27 @@ The safe-complete evidence census is: | Evidence class | Safe interfaces | | --- | ---: | -| `standard_derived` | 5,332 | -| `exact_registry_dependent` | 365 | -| **Total** | **5,697** | +| `standard_derived` | 5,355 | +| `exact_registry_dependent` | 366 | +| **Total** | **5,721** | The registry contains **532 declared entries**, all 532 match the pinned metadata, and 431 distinct entries are consumed by complete safe plans. These plans have -693 entry/interface dependencies and 424 family/interface dependencies. -Per-interface dependency-set totals also include 5,983 metadata-attribute -dependencies and 26,134 COM-standard-rule dependencies. +694 entry/interface dependencies and 425 family/interface dependencies. +Per-interface dependency-set totals also include 6,012 metadata-attribute +dependencies and 26,247 COM-standard-rule dependencies. + +PR4's explicit overload names promote 24 previously raw-metadata-complete +interfaces: 23 standard-derived and one exact-registry-dependent. +`IGenericDescriptor2` now consumes the existing `IGenericDescriptor::GetBody` +slot-6 ownership entry, bringing that entry's interface dependencies from one +to two. No entries are added: registered/matched and distinct safe-consumed +entry counts remain 532 and 431. The new names select already validated +normal methods; they do not supply missing ABI, ownership, or lifetime facts. | Exact contract kind | Safe-interface dependencies | | --- | ---: | -| `ownership` | 182 | +| `ownership` | 183 | | `parameter-direction` | 45 | | `bounded-two-call` | 16 | | `conditional-output` | 10 | @@ -471,7 +479,7 @@ Family rollups deliberately count each interface once per family: | `com.sequential-stream-buffer.v1` | 2 | 2 | 7 | | `buffers.counted-buffer.v1` | 3 | 2 | 2 | | `buffers.bounded-two-call.v1` | 2 | 2 | 16 | -| `com.ownership.v1` | 169 | 118 | 123 | +| `com.ownership.v1` | 169 | 118 | 124 | | `com.parameter-direction.v1` | 3 | 3 | 15 | | `com.reserved-null-input.v1` | 2 | 2 | 1 | | `com.nullable-input.v1` | 2 | 2 | 2 | @@ -504,12 +512,12 @@ Universal rule dependencies are: | `com.automation.bstr-replacement.v1` | 99 | | `com.enumerator-next.generic.v1` | 25 | | `com.handle.borrowed-no-cleanup.v1` | 45 | -| `com.hresult.failure.v1` | 5,579 | -| `com.interface.input-borrow.v1` | 1,890 | -| `com.interface.typed-output-plus-one.v1` | 3,458 | -| `com.iunknown.identity-refcount.v1` | 5,697 | -| `com.query-interface.output-plus-one.v1` | 5,697 | -| `com.standard-cleanup.matching-allocator.v1` | 1,437 | +| `com.hresult.failure.v1` | 5,603 | +| `com.interface.input-borrow.v1` | 1,908 | +| `com.interface.typed-output-plus-one.v1` | 3,480 | +| `com.iunknown.identity-refcount.v1` | 5,721 | +| `com.query-interface.output-plus-one.v1` | 5,721 | +| `com.standard-cleanup.matching-allocator.v1` | 1,438 | These are dependency counts: an inherited contract can be consumed by several interfaces, and one interface can consume several IDs or kinds. They are not @@ -556,3 +564,7 @@ helpers. Delete existing generated bindings and completely regenerate every selected root with matching updated runtime/codegen versions; there is no in-place migration or support for mixed old/new generated classes. The contract-data schema is unaffected, as are other generated `.as(...)` paths. + +PR4 requires no further manifest change. Already-supported safe output, +including distinguishable overload dispatch, remains byte-identical; +previously rejected overload groups had no valid safe surface to migrate. diff --git a/docs/architecture/classic-com-generated-unsafe.md b/docs/architecture/classic-com-generated-unsafe.md index a6200663..9c8ffb55 100644 --- a/docs/architecture/classic-com-generated-unsafe.md +++ b/docs/architecture/classic-com-generated-unsafe.md @@ -123,6 +123,23 @@ Codegen uses the same capability classifier as `com-capability-census`. The complete inherited interface passes the existing safe semantic projection. Generate the existing safe class and no unsafe replacement. +PR4 resolves previously rejected overload groups only after every member has a +fully validated normal COM call plan. Colliding JavaScript arity/shapes or +projected buffers receive explicit +`AtSlot` names for every member, with no +ambiguous unsuffixed method. Existing distinguishable dispatch stays +unchanged; collisions with projected members and synthesized/dynamic-IID/ +non-normal groups still fail closed. Renderers consume the selected IR names +without guessing runtime types or native semantics. + +This promotes 24 raw-metadata-complete interfaces, bringing complete safe +coverage to **5,721 / 7,929** and leaving **2,208** incomplete interfaces. +Promoted interfaces receive no duplicate unsafe companion. Native ABI, +conversion, lifetime, and raw-runtime capabilities remain unchanged, and +PR3's copy-only facades remain excluded from complete safe coverage. +Already-supported safe output remains byte-identical, so PR4 needs no +additional manifest version. + ### Raw metadata complete Metadata contains every fact needed to express the outbound ABI through Phase 1 @@ -598,7 +615,7 @@ trailing dots/spaces, and Windows device names (`CON`, `PRN`, `AUX`, `NUL`, `CLOCK$`, `CONIN$`, `CONOUT$`, `COM1`-`COM9`, and `LPT1`-`LPT9`), including device names with extensions. -Retained schema-11 `modulePath` is never trusted. Codegen rederives it from the +Retained schema-12 `modulePath` is never trusted. Codegen rederives it from the validated qualified interface identity and exact `Unsafe` class name, requires an exact match, and then checks the case-insensitive path key. Case-only namespaces or type names therefore fail instead of aliasing on @@ -707,17 +724,19 @@ Stage 2 is implemented: arguments; - parameter requirements come from the same per-target classifier analysis; - runtime-blocked methods remain omitted; -- support schema 11 records every parameter index/name, strategy type, exact +- support schema 12 records every parameter index/name, strategy type, exact reason, native direction/nullability, and known target pointee layouts; and - a raw pointer is never substituted for missing ownership. -For official 71.0.14 metadata, **1,442 of 1,446** x64 manual-contract interfaces -have at least one portable executable generated high-level method. **1,441** +For official 71.0.14-preview metadata, **1,427 of 1,431** x64 manual-contract interfaces +have at least one portable executable generated high-level method. **1,426** have an executable manual method, one retains only metadata-complete methods, and four have no portable executable method because every candidate is blocked -on another generated target. There are **6,083** portable executable manual +on another generated target. There are **6,046** portable executable manual methods, **0** remaining portable manual-classified methods omitted, and -**1,163** cross-target runtime-blocked methods still omitted. +**1,161** cross-target runtime-blocked methods still omitted. The existing +`official_stage2_coverage_is_exact` test confirms these measurements are +unchanged by PR4; its promotions come from the raw-metadata-complete bucket. ### Stage 3 diff --git a/docs/architecture/classic-com-support.md b/docs/architecture/classic-com-support.md index 7a17f502..52ef9fc2 100644 --- a/docs/architecture/classic-com-support.md +++ b/docs/architecture/classic-com-support.md @@ -4,8 +4,8 @@ general Automation or native Win32 projection. > **Status: preview, under active development.** The current CI baseline against -> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,697 complete safe -> interface projections out of 7,929 eligible interfaces (71.85%). Earlier +> `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview is 5,721 complete safe +> interface projections out of 7,929 eligible interfaces (72.15%). Earlier > inventory and demand-snapshot sections retain the metadata versions and dates > stated in those sections. @@ -154,6 +154,31 @@ renderer cannot see `TypeMeta` or metadata attributes and has no default pointer/Buffer fallback; it only serializes the validated projected IR with exhaustive type matches. +## Explicit COM overload names + +Existing overload groups with distinguishable JavaScript arity/shape retain +their exact dispatch and generated API. PR4 handles previously rejected +groups only when every member is an otherwise fully validated **normal COM +method**. Groups with colliding JavaScript signatures or projected buffers +receive deterministic public names +`AtSlot` for **every** member; the ambiguous +unsuffixed method is absent. + +The slot is the absolute inherited vtable slot, not an overload ordinal. +For example, `ID2D1Device1::CreateDeviceContext` produces two explicit +`createDeviceContextAtSlot...` members; the generated declarations give their +exact names and return types. Native method names, slots, ABI signatures, +conversions, and lifetime plans are unchanged. Projection selects the names in +IR; the renderer only serializes them and adds no runtime type or ABI guesses. + +Alias collisions with actual projected members fail closed. Synthesized, +dynamic-IID, and other non-normal method groups still reject; this is not a +universal overloaded-method parser or a way around incomplete native +contracts. See the [usage guide](../guides/windows/classic-com-usage.md#58-explicit-overload-names). +PR4 does not change COM manifest version 4 or unsafe support schema 12: +already-supported safe output remains byte-identical, and the newly admitted +groups previously had no valid safe surface. + ## Bounded native one-shot completion The first supported flat export is the exact @@ -262,8 +287,8 @@ interface projections. They do not expose `GetBuffer`, `ReleaseBuffer`, `Lock`, or `Unlock` independently. WIC retains its previously complete native interface surface (including acquisition of an opaque owned lock) and adds the copy operation. An external lock never gains byte access or writable rights from -this operation. The complete safe census remains **5,697 / 7,929**; it does not -count the three copy-only facades as newly complete interfaces. +this operation. The three copy-only facades remain excluded from the current +**5,721 / 7,929** complete safe census. ### Private context and lifecycle @@ -730,7 +755,7 @@ not be described as solving every problem in the map above. | Fail-closed generation | Unknown/unsafe layouts, untagged/by-value/output unions, bitfields, flexible arrays, nested owned fields, unsupported VARTYPE/BYREF/SAFEARRAY/PROPVARIANT combinations, unsupported arrays, pointer outputs, ownership, and in/out shapes stop generation with a targeted error. | | Consumable output | Classic COM files live under `com/`, with `./com` and `./com/*` package exports. The generated package root is always WinRT-only; COM-only output deliberately has no root entrypoint. | | Explicit vtable registration | Every generated method is registered with `.addMethodAt(vtableIndex, name, signature)`, keyed by its actual metadata-derived vtable slot. Methods are never deduplicated by name, so same-name overloads at different slots both register correctly. | -| Same-name overload projection | Overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) are grouped once during projection (not by renderer heuristics). A single public JS method dispatches to a private per-slot implementation using only a validated, mutually-distinguishable arity/shape key (`typeof`-based: boolean/number/bigint/string/object); ambiguous groups fail generation closed with a diagnostic naming the interface, method, and reason. The `.d.ts` emits one TypeScript overload signature per branch, contiguously. | +| Same-name overload projection | Existing distinguishable overloads (e.g. `IDCompositionEffectGroup::SetOpacity`) retain their single public dispatcher, validated arity/shape keys, and contiguous TypeScript overload signatures. Previously rejected groups of fully validated normal methods use explicit `AtSlot` names for every member and omit the ambiguous unsuffixed name. Projection selects these names; the renderer does not infer ABI semantics. Collisions and non-normal groups fail closed. | | Lifecycle ergonomics | Generated interface wrappers declare a protected constructor (`protected constructor(obj: unknown);`) so only generated coclasses can subclass them. Coclasses expose a public zero-argument constructor, and every wrapper provides an idempotent `release()` that delegates to the managed native value. Factory-activated interop wrappers retain `static create()` with JSDoc reminding callers to initialize COM first. | | Doc-link rendering | When win32metadata attaches a `DocumentationAttribute` (a `learn.microsoft.com` URL) to a method, the generator renders it as an `@see {@link ...}` comment in both `.js` and `.d.ts`. No raw metadata is imported into the renderer — the URL is threaded through `ProjectedComMethod.doc`, populated once during projection. | | Acronym-aware parameter casing | Parameter names are lowered using the same acronym-run-aware rule as method names, so a Hungarian-prefixed trailing acronym like `hwndMDI` projects as `mdi` (not the previous naive `mDI`). | @@ -1545,13 +1570,15 @@ restricting InOut to proven caller-allocation-preserving contracts, bringing that census to 5,691. The variable-length WAVEFORMATEX model and three pinned audio method contracts promote five more interfaces, bringing that census to 5,696. The exact `IMMDevice::Activate` and `GetId` contracts promote one more -complete interface, bringing the current literal census to -**5,697 / 7,929 = 71.850170%**. The result remains above the +complete interface, bringing that census to 5,697, unchanged by PR2 completion +and PR3 copy-only facades. PR4's explicit overload names move 24 previously +raw-metadata-complete interfaces into the safe set, bringing the current +literal census to **5,721 / 7,929 = 72.152857%**. The result remains above the 70% target without admitting any unmodeled target-device, storage-medium, audio-output ownership, ownership-transfer, or callback shape. CI reproduces this number with `dynwinrt-codegen com-census --json` and fails -if the denominator changes, complete generation drops below 5,697, or coverage +if the denominator changes, complete generation drops below 5,721, or coverage falls below 70%. ## Public-code frequency snapshot diff --git a/docs/guides/windows/classic-com-usage.md b/docs/guides/windows/classic-com-usage.md index 5b8f46eb..43f85f08 100644 --- a/docs/guides/windows/classic-com-usage.md +++ b/docs/guides/windows/classic-com-usage.md @@ -800,6 +800,37 @@ external WIC locks are not supported. See the [exact lifecycle/evidence contract](../../architecture/classic-com-support.md#bounded-borrowed-buffer-copies) for supported formats, HRESULT handling, and validation. +### 5.8 Explicit overload names + +Existing overloads that codegen can distinguish by JavaScript arity/shape keep +their current names and dispatch unchanged. PR4 also admits previously +rejected groups of otherwise fully validated **normal COM methods** whose +JavaScript signatures collide or use projected buffers. Every member receives +`AtSlot`; there is no ambiguous unsuffixed method +and no extra slot argument to pass. + +For example, generate `Windows.Win32.Graphics.Direct2D.ID2D1Device1` and inspect +its `.d.ts`. Its two inherited `CreateDeviceContext` slots become distinct +`createDeviceContextAtSlot...` methods instead of `createDeviceContext`. +Schematically, where `N` and `M` mean the actual absolute metadata slots: + +```text +createDeviceContextAtSlotN(options) +createDeviceContextAtSlotM(options) +``` + +Use the exact name and typed signature from the generated declaration for the +native overload you need. These deterministic names preserve the native slot, +arguments, result conversion, and lifetime contract; changing JavaScript +values is not a way to select an absent unsuffixed method. + +Alias collisions with actual projected member names fail closed. +Synthesized, dynamic-IID, and other non-normal groups still reject, as do +incomplete ABI or ownership contracts. This is not a universal overload +parser. PR4 preserves already-supported generated APIs byte-for-byte and +requires no new manifest version; the manifest 4 / support schema 12 upgrade +requirements for older borrowed-copy output still apply. + ## 6. JavaScript projections of common native types | Native semantics | JavaScript/TypeScript | diff --git a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md index 78826204..967dc67e 100644 --- a/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md +++ b/docs/status/CLASSIC_COM_API_SUPPORT_PLAN.md @@ -32,17 +32,28 @@ B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D | Result | Interfaces | Percentage | | ---------------------------------------------------- | ---------: | ---------: | | Externally addressable Classic COM interfaces | 7,929 | 100% | -| Complete safe generation | 5,697 | 71.85% | -| Rejected because at least one contract is incomplete | 2,232 | 28.15% | +| Complete safe generation | 5,721 | 72.15% | +| Rejected because at least one contract is incomplete | 2,208 | 27.85% | The denominator contains addressable COM interface identities, not flat Win32 DLL exports. A complete interface means that its full inherited vtable can be generated without guessing ABI, layout, count relationships, ownership, or cleanup. -The 5,697 figure is semantic codegen coverage, not a claim that every interface +The 5,721 figure is semantic codegen coverage, not a claim that every interface has a dedicated live Windows test or can be activated on every machine. +PR4 promotes **24** previously raw-metadata-complete interfaces by naming +otherwise validated normal overloads explicitly. Every member of a formerly +rejected same-shape/arity or projected-buffer group receives +`AtSlot`; the ambiguous unsuffixed method is not +emitted. Existing distinguishable overload dispatch, native ABI/conversion/ +lifetime plans, and already-supported generated output remain unchanged. +Alias collisions and synthesized/dynamic-IID/non-normal groups still fail +closed. This needs no further manifest version change and does not turn the +PR3 bounded-copy facades into complete native interface projections. +See [overload usage and limits](../guides/windows/classic-com-usage.md#58-explicit-overload-names). + Reproduce the census with: ```powershell @@ -269,7 +280,7 @@ non-addressable identities block every method before companion selection. `MFASYNCRESULT` therefore produces no callable class. When an interface has no executable method, generation transactionally commits -a schema-11 report containing every blocked/manual method and exact reasons, +a schema-12 report containing every blocked/manual method and exact reasons, emits no class `.js`/`.d.ts`, and then exits nonzero. The metadata record is a sorted, deduplicated set of every loaded emission/reference/sibling winmd, with per-file hashes, a set hash, and an optional exact defining file; it contains no @@ -323,7 +334,7 @@ generated `runtime.js`/`.d.ts` provides closed pointee, pointer-output, handle, interface-replacement, counted-buffer, owned-pointer, and raw-fallback strategies. Generated methods validate strategy types before dispatch, clean dirty HRESULT failure outputs according to the selected strategy, and report -exact per-parameter requirements in support schema 11. +exact per-parameter requirements in support schema 12. Strategy capabilities are unforgeable frozen objects backed by private WeakMaps. Private generated helpers perform prepare, writable-span overlap @@ -370,25 +381,30 @@ and **1,161 runtime-blocked methods** still omitted. Stage 1 of the [Classic COM contract evidence registry](../architecture/classic-com-contract-evidence-registry.md) -classifies all 5,697 safe-complete interfaces exactly once: +classifies all 5,721 safe-complete interfaces exactly once: | Evidence class | Interfaces | | --- | ---: | -| `standard_derived` | 5,332 | -| `exact_registry_dependent` | 365 | +| `standard_derived` | 5,355 | +| `exact_registry_dependent` | 366 | The registry declares 532 selector-specific entries; all 532 match pinned -metadata, 431 distinct entries are consumed by complete safe plans, which contain 693 -entry/interface plus 424 family/interface dependencies. They also consume -5,983 metadata-attribute and 26,134 universal COM-rule dependency sets. +metadata, 431 distinct entries are consumed by complete safe plans, which contain 694 +entry/interface plus 425 family/interface dependencies. They also consume +6,012 metadata-attribute and 26,247 universal COM-rule dependency sets. Entry/interface dependencies by kind are SAFEARRAY 263, enumerator-next 74, -borrowed-handle 54, ownership 182, parameter-direction 45, bounded-two-call 16, +borrowed-handle 54, ownership 183, parameter-direction 45, bounded-two-call 16, counted-buffer 16, conditional-output 10, flag-selected-buffer 3, null-input 4, semantic-HRESULT 3, compound-dispatch 1, borrowed-storage 15, and contextual-effect 7. Complete per-entry status, per-family rollups, and per-interface entry IDs are retained in the summary and interface CSV. These are dependency counts, not net contribution; no ablation claim is made. +The 24 PR4 promotions comprise 23 standard-derived interfaces and one +exact-registry-dependent interface, `IGenericDescriptor2`. Its inherited +`GetBody` reuses an existing slot-6 ownership entry; no registry entries or +distinct safe-consumed entries are added. + Borrowed buffers now have synchronous **owned-copy** transactions for WASAPI render/capture, STA WIC BGRA8 locks, and linear `IMFMediaBuffer`. Audio requires observed successful initialization and GetService provenance; external @@ -415,7 +431,7 @@ placeholder WAVEFORMATEX. Other audio-format inputs remain required. contract, and `IMMDevice::GetId` adds a JSON-backed slot-5 CoTaskMem ownership entry. Both are consumed by the complete safe endpoint plan. The `com.ownership.v1` family now has 169 registered entries, 118 safe-used -entries, and 123 family/interface dependencies. +entries, and 124 family/interface dependencies. The storage-medium contracts also pin `IOleCache::SetData` (including inherited `IOleCache2` calls) to caller-retained ownership and describe the distinct @@ -440,19 +456,24 @@ allocator, or ownership declaration can corrupt memory or crash the process. For `Microsoft.Windows.SDK.Win32Metadata` 71.0.14-preview (`Windows.Win32.winmd` SHA-256 `B64EE4818A7ED9F9D135038D58C51BD08369184D4D5ED428F20E9DE55DF8121D`), -the safe census is 5,697 of 7,929 interfaces. The separate outbound raw census -classifies the 2,232 safe-incomplete interfaces as: +the safe census is 5,721 of 7,929 interfaces. The separate outbound raw census +classifies the 2,208 safe-incomplete interfaces as: | Target | Metadata-complete | Manual contract | Runtime-blocked | | ------ | ----------------: | --------------: | --------------: | -| x64 | 412 | 1,431 | 389 | -| i686 | 411 | 1,408 | 413 | -| ARM64 | 412 | 1,431 | 389 | +| x64 | 388 | 1,431 | 389 | +| i686 | 387 | 1,408 | 413 | +| ARM64 | 388 | 1,431 | 389 | Including safe-complete interfaces, x64 and ARM64 have 6,109 metadata-complete, 1,431 manual, and 389 blocked interfaces. i686 has 6,108 metadata-complete, 1,408 manual, and 413 blocked interfaces. +These all-interface raw totals are unchanged by PR4: all 24 promotions come +from the safe-incomplete raw-metadata-complete bucket. Manual/runtime-blocked +classifications and the measured Stage 2 executable-method totals are +unchanged. + Pointer-shaped types are analyzed recursively. A missing pointee layout for an external input pointer is manual-contract; the same missing layout for a writable/readable `T*` caller-storage contract is runtime-blocked. Thus @@ -468,7 +489,7 @@ External pointer/callback requirements affect 1,089 x64/ARM64 interfaces and 1,090 i686 interfaces; 6,804 require external acquisition and all 7,929 retain the current-apartment rule. -For all 5,697 safe-complete interfaces, cleanup is derived from the validated +For all 5,721 safe-complete interfaces, cleanup is derived from the validated projected result conversions rather than the raw analyzer. Pure values, borrowed handles, caller buffers, and plain arrays are `none_required`. Managed COM/dynamic-IID adoption, BSTR, HSTRING, CoTaskMem, VARIANT, @@ -555,7 +576,7 @@ as ABI support. The legacy `com-census --json` output remains unchanged. ## Copyable user-facing statement > dynwinrt supports the Classic COM interface portion of Windows.Win32 -> metadata. With Win32Metadata 71.0.14-preview, 5,697 of 7,929 addressable COM +> metadata. With Win32Metadata 71.0.14-preview, 5,721 of 7,929 addressable COM > interfaces pass complete safe generation. Safe symbols never fall back to an > unsafe implementation; ordinary generation may instead emit an explicitly > named `*Unsafe` outbound companion containing only metadata-complete methods. diff --git a/docs/status/generated/classic-com-capability-summary.json b/docs/status/generated/classic-com-capability-summary.json index 808f2d03..4df35312 100644 --- a/docs/status/generated/classic-com-capability-summary.json +++ b/docs/status/generated/classic-com-capability-summary.json @@ -80,19 +80,19 @@ "parsed_interface_identities": 7944, "eligible_interfaces": 7929, "not_addressable": 15, - "safe_complete": 5697, - "safe_incomplete": 2232, + "safe_complete": 5721, + "safe_incomplete": 2208, "safeEvidence": { - "safeComplete": 5697, - "standardDerived": 5332, - "exactRegistryDependent": 365, - "metadataFactOccurrences": 5983, - "comStandardFactOccurrences": 26134, + "safeComplete": 5721, + "standardDerived": 5355, + "exactRegistryDependent": 366, + "metadataFactOccurrences": 6012, + "comStandardFactOccurrences": 26247, "registeredExactEntries": 532, "metadataMatchedExactEntries": 532, "safeConsumedExactEntries": 431, - "exactEntryInterfaceDependencies": 693, - "exactFamilyInterfaceDependencies": 424, + "exactEntryInterfaceDependencies": 694, + "exactFamilyInterfaceDependencies": 425, "byContractKind": { "borrowed-handle": 54, "borrowed-storage": 15, @@ -104,7 +104,7 @@ "enumerator-next": 74, "flag-selected-buffer": 3, "null-input": 4, - "ownership": 182, + "ownership": 183, "parameter-direction": 45, "safearray": 263, "semantic-hresult": 3 @@ -404,7 +404,7 @@ "com.ownership.entry.windows-win32-media-directshow-tv.iatsc-vct.26879a1832f946c691f0fb6479270e8c.getrecordname.slot-8.param-1-pwsname.v1": 1, "com.ownership.entry.windows-win32-media-directshow-tv.iatsccontentadvisorydescriptor.ff76e60c028343eaba32b422238547ee.getrecordratingdescriptiontext.slot-10.param-2-pptext.v1": 1, "com.ownership.entry.windows-win32-media-directshow-tv.idvb-st.4d5b9f232a0245debcda5d5dbfbfbe62.getdata.slot-5.param-0-ppdata.v1": 1, - "com.ownership.entry.windows-win32-media-directshow-tv.igenericdescriptor.6a5918f8a77a4f61aed05702bdcda3e6.getbody.slot-6.param-0-ppbval.v1": 1, + "com.ownership.entry.windows-win32-media-directshow-tv.igenericdescriptor.6a5918f8a77a4f61aed05702bdcda3e6.getbody.slot-6.param-0-ppbval.v1": 2, "com.ownership.entry.windows-win32-media-directshow-tv.istreambufferconfigure.ce14dfae40984af7bbf7d6511f835414.getdirectory.slot-4.param-0-ppszdirectoryname.v1": 3, "com.ownership.entry.windows-win32-media-directshow-tv.istreambufferconfigure3.7e2d2a1e71924bd780c1061fd1d10402.getnamespace.slot-16.param-0-ppsznamespace.v1": 1, "com.ownership.entry.windows-win32-media-directshow.iamdeviceremoval.f90a6130b65811d2ae490000f8754b99.deviceinfo.slot-3.param-1-pwszsymboliclink.v1": 1, @@ -552,7 +552,7 @@ "buffers.counted-buffer.v1": 2, "com.enumerator-next-exception.v1": 74, "com.nullable-input.v1": 2, - "com.ownership.v1": 123, + "com.ownership.v1": 124, "com.parameter-direction.v1": 15, "com.reserved-null-input.v1": 1, "com.semantic-hresult.v1": 3, @@ -563,9 +563,9 @@ }, "byMetadataAttribute": { "CanReturnMultipleSuccessValuesAttribute": 46, - "ConstAttribute": 3332, + "ConstAttribute": 3351, "FreeWithAttribute": 3, - "NativeArrayInfoAttribute": 2602 + "NativeArrayInfoAttribute": 2612 }, "byStandardRuleId": { "com.activation.output-plus-one.v1": 976, @@ -573,12 +573,12 @@ "com.automation.bstr-replacement.v1": 99, "com.enumerator-next.generic.v1": 25, "com.handle.borrowed-no-cleanup.v1": 45, - "com.hresult.failure.v1": 5579, - "com.interface.input-borrow.v1": 1890, - "com.interface.typed-output-plus-one.v1": 3458, - "com.iunknown.identity-refcount.v1": 5697, - "com.query-interface.output-plus-one.v1": 5697, - "com.standard-cleanup.matching-allocator.v1": 1437 + "com.hresult.failure.v1": 5603, + "com.interface.input-borrow.v1": 1908, + "com.interface.typed-output-plus-one.v1": 3480, + "com.iunknown.identity-refcount.v1": 5721, + "com.query-interface.output-plus-one.v1": 5721, + "com.standard-cleanup.matching-allocator.v1": 1438 }, "exactEntryStatus": { "audio.conditional-output.entry.windows-win32-media-audio.iaudioclient.1cb9ad4cdbfa4c32b178c2f568a703b2.isformatsupported.slot-7.v1": { @@ -7419,7 +7419,7 @@ "registered": true, "metadataMatched": true, "safeConsumed": true, - "interfaceDependencies": 1 + "interfaceDependencies": 2 }, "com.ownership.entry.windows-win32-media-directshow-tv.istreambufferconfigure.ce14dfae40984af7bbf7d6511f835414.getdirectory.slot-4.param-0-ppszdirectoryname.v1": { "familyId": "com.ownership.v1", @@ -11356,7 +11356,7 @@ "raw_metadata_complete": 6109, "raw_manual_contract": 1431, "raw_runtime_blocked": 389, - "safe_incomplete_raw_metadata_complete": 412, + "safe_incomplete_raw_metadata_complete": 388, "safe_incomplete_raw_manual_contract": 1431, "safe_incomplete_raw_runtime_blocked": 389 }, @@ -11364,7 +11364,7 @@ "raw_metadata_complete": 6108, "raw_manual_contract": 1408, "raw_runtime_blocked": 413, - "safe_incomplete_raw_metadata_complete": 411, + "safe_incomplete_raw_metadata_complete": 387, "safe_incomplete_raw_manual_contract": 1408, "safe_incomplete_raw_runtime_blocked": 413 }, @@ -11372,7 +11372,7 @@ "raw_metadata_complete": 6109, "raw_manual_contract": 1431, "raw_runtime_blocked": 389, - "safe_incomplete_raw_metadata_complete": 412, + "safe_incomplete_raw_metadata_complete": 388, "safe_incomplete_raw_manual_contract": 1431, "safe_incomplete_raw_runtime_blocked": 389 } diff --git a/docs/status/generated/classic-com-interface-support.csv b/docs/status/generated/classic-com-interface-support.csv index 7a0d55f1..f2848afe 100644 --- a/docs/status/generated/classic-com-interface-support.csv +++ b/docs/status/generated/classic-com-interface-support.csv @@ -13,7 +13,7 @@ Windows.Win32.AI.MachineLearning.DirectML,IDMLOperatorInitializer,427c1113-435c- Windows.Win32.AI.MachineLearning.DirectML,IDMLPageable,b1ab0825-4542-4a4b-8617-6dde6e8f6201,false,,external_pointee_storage Windows.Win32.AI.MachineLearning.WinML,IMLOperatorAttributes,4b1b1759-ec40-466c-aab4-beb5347fd24c,false,,external_pointee_storage Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernel,11c4b4a0-b467-4eaa-a1a6-b961d8d0ed79,true,standard_derived, -Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelContext,82536a28-f022-4769-9d3f-8b278f84c0c3,false,,safe_projection_incomplete +Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelContext,82536a28-f022-4769-9d3f-8b278f84c0c3,true,standard_derived, Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelCreationContext,5459b53d-a0fc-4665-addd-70171ef7e631,false,,incomplete_pointee_layout_for_storage Windows.Win32.AI.MachineLearning.WinML,IMLOperatorKernelFactory,ef15ad6f-0dc9-4908-ab35-a575a30dfbf8,true,standard_derived, Windows.Win32.AI.MachineLearning.WinML,IMLOperatorRegistry,2af9dd2d-b516-4672-9ab5-530c208493ad,false,,external_pointee_storage @@ -565,13 +565,13 @@ Windows.Win32.Graphics.Direct2D,ID2D1ComputeTransform,0d85573c-01e3-4f7d-bfd9-0d Windows.Win32.Graphics.Direct2D,ID2D1ConcreteTransform,1a799d8a-69f7-4e4c-9fed-437ccc6684cc,true,standard_derived, Windows.Win32.Graphics.Direct2D,ID2D1DCRenderTarget,1c51bc64-de61-46fd-9899-63a5d8f03950,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.Direct2D,ID2D1Device,47dd575d-ac05-4cdd-8049-9b02cd16f44c,true,standard_derived, -Windows.Win32.Graphics.Direct2D,ID2D1Device1,d21768e1-23a4-4823-a14b-7c3eba85d658,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device2,a44472e1-8dfb-4e60-8492-6e2861c9ca8b,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device3,852f2087-802c-4037-ab60-ff2e7ee6fc01,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device4,d7bdb159-5683-4a46-bc9c-72dc720b858b,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device5,d55ba0a4-6405-4694-aef5-08ee1a4358b4,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device6,7bfef914-2d75-4bad-be87-e18ddb077b6d,false,,safe_projection_incomplete -Windows.Win32.Graphics.Direct2D,ID2D1Device7,f07c8968-dd4e-4ba6-9cbd-eb6d3752dcbb,false,,safe_projection_incomplete +Windows.Win32.Graphics.Direct2D,ID2D1Device1,d21768e1-23a4-4823-a14b-7c3eba85d658,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device2,a44472e1-8dfb-4e60-8492-6e2861c9ca8b,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device3,852f2087-802c-4037-ab60-ff2e7ee6fc01,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device4,d7bdb159-5683-4a46-bc9c-72dc720b858b,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device5,d55ba0a4-6405-4694-aef5-08ee1a4358b4,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device6,7bfef914-2d75-4bad-be87-e18ddb077b6d,true,standard_derived, +Windows.Win32.Graphics.Direct2D,ID2D1Device7,f07c8968-dd4e-4ba6-9cbd-eb6d3752dcbb,true,standard_derived, Windows.Win32.Graphics.Direct2D,ID2D1DeviceContext,e8f7fe7a-191c-466d-ad95-975678bda998,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.Direct2D,ID2D1DeviceContext1,d37f57e4-6908-459f-a199-e72f24f79987,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.Direct2D,ID2D1DeviceContext2,394ea6a3-0c34-4321-950b-6ca20f0be6c7,false,,incomplete_pointee_layout_for_storage @@ -968,7 +968,7 @@ Windows.Win32.Graphics.DirectComposition,IDCompositionDevice3,0987cb06-f916-48bf Windows.Win32.Graphics.DirectComposition,IDCompositionDevice4,85fc5cca-2da6-494c-86b6-4a775c049b8a,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionDevice5,2c6bebfe-a603-472f-af34-d2443356e61b,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionDeviceDebug,a1a3c64a-224f-4a81-9773-4f03a89d3c6c,true,standard_derived, -Windows.Win32.Graphics.DirectComposition,IDCompositionDynamicTexture,a1de1d3f-6405-447f-8e95-1383a34b0277,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectComposition,IDCompositionDynamicTexture,a1de1d3f-6405-447f-8e95-1383a34b0277,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionEffect,ec81b08f-bfcb-4e8d-b193-a915587999e8,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionEffectGroup,a7929a74-e6b2-4bd6-8b95-4040119ca34d,true,standard_derived, Windows.Win32.Graphics.DirectComposition,IDCompositionFilterEffect,30c421d5-8cb2-4e9f-b133-37be270d4ac2,true,standard_derived, @@ -1058,8 +1058,8 @@ Windows.Win32.Graphics.DirectWrite,IDWriteFont1,acd16696-8c14-4f5d-877e-fe3fc1d3 Windows.Win32.Graphics.DirectWrite,IDWriteFont2,29748ed6-8c9c-4a6a-be0b-d912e8538944,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteFont3,29748ed6-8c9c-4a6a-be0b-d912e8538944,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection,a84cee02-3eea-4eee-a827-87c1a02a0fcc,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection1,53585141-d9f8-4095-8321-d73cf6bd116c,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection2,514039c6-4617-4064-bf8b-92ea83e506e0,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection1,53585141-d9f8-4095-8321-d73cf6bd116c,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection2,514039c6-4617-4064-bf8b-92ea83e506e0,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontCollection3,a4d055a6-f9e3-4e25-93b7-9e309f3af8e9,false,,missing_handle_ownership Windows.Win32.Graphics.DirectWrite,IDWriteFontCollectionLoader,cca920e4-52f0-492b-bfa8-29c72ee0a468,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontDownloadListener,b06fe5b9-43ec-4393-881b-dbe4dc72fda7,true,standard_derived, @@ -1075,29 +1075,29 @@ Windows.Win32.Graphics.DirectWrite,IDWriteFontFace7,3945b85b-bc95-40f7-b72c-8b73 Windows.Win32.Graphics.DirectWrite,IDWriteFontFaceReference,5e7fa7ca-dde3-424c-89f0-9fcd6fed58cd,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFaceReference1,c081fe77-2fd1-41ac-a5a3-34983c4ba61a,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteFontFallback,efa008f9-f7a1-48bf-b05c-f224713cc0ff,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontFallback1,2397599d-dd0d-4681-bd6a-f4f31eaade77,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontFallback1,2397599d-dd0d-4681-bd6a-f4f31eaade77,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFallbackBuilder,fd882d06-8aba-4fb8-b849-8be8b73e14de,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily,da20d8ef-812a-4c43-9802-62ec4abd7add,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily1,da20d8ef-812a-4c43-9802-62ec4abd7adf,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily2,3ed49e77-a398-4261-b9cf-c126c2131ef3,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily1,da20d8ef-812a-4c43-9802-62ec4abd7adf,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontFamily2,3ed49e77-a398-4261-b9cf-c126c2131ef3,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFile,739d886a-cef5-47dc-8769-1a8b41bebbb0,false,,missing_allocator Windows.Win32.Graphics.DirectWrite,IDWriteFontFileEnumerator,72755049-5ff7-435d-8348-4be97cfa6c7c,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFileLoader,727cad4e-d6af-4c9e-8a08-d695b11caa49,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontFileStream,6d4865fe-0ab8-4d91-8f62-5dd6be34a3e0,false,,external_pointee_storage Windows.Win32.Graphics.DirectWrite,IDWriteFontList,1a0d8438-1d97-4ec1-aef9-a2fb86ed6acb,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteFontList1,da20d8ef-812a-4c43-9802-62ec4abd7ade,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontList2,c0763a34-77af-445a-b735-08c37b0a5bf5,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontList1,da20d8ef-812a-4c43-9802-62ec4abd7ade,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontList2,c0763a34-77af-445a-b735-08c37b0a5bf5,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontResource,1f803a76-6871-48e8-987f-b975551c50f2,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontSet,53585141-d9f8-4095-8321-d73cf6bd116b,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontSet,53585141-d9f8-4095-8321-d73cf6bd116b,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteFontSet1,7e9fda85-6c92-4053-bc47-7ae3530db4d3,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteFontSet2,dc7ead19-e54c-43af-b2da-4e2b79ba3f7f,false,,missing_handle_ownership Windows.Win32.Graphics.DirectWrite,IDWriteFontSet3,7c073ef2-a7f4-4045-8c32-8ab8ae640f90,false,,missing_handle_ownership Windows.Win32.Graphics.DirectWrite,IDWriteFontSet4,eec175fc-bea9-4c86-8b53-ccbdd7df0c82,false,,missing_count_relation -Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder,2f642afe-9c68-4f40-b8be-457401afcb3d,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder1,3ff7715f-3cdc-4dc6-9b72-ec5621dccafd,false,,safe_projection_incomplete -Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder2,ee5ba612-b131-463c-8f4f-3189b9401e45,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder,2f642afe-9c68-4f40-b8be-457401afcb3d,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder1,3ff7715f-3cdc-4dc6-9b72-ec5621dccafd,true,standard_derived, +Windows.Win32.Graphics.DirectWrite,IDWriteFontSetBuilder2,ee5ba612-b131-463c-8f4f-3189b9401e45,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteGdiInterop,1edd9491-9853-4299-898f-6432983b6f3a,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteGdiInterop1,4556be70-3abd-4f70-90be-421780a6f515,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteGdiInterop1,4556be70-3abd-4f70-90be-421780a6f515,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteGlyphRunAnalysis,7d97dbf7-e085-42d4-81e3-6a883bded118,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteInMemoryFontFileLoader,dc102f47-a12d-4b1c-822d-9e117e33043f,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteInlineObject,8339fde3-106f-47ab-8373-1c6295eb10b3,true,standard_derived, @@ -1122,7 +1122,7 @@ Windows.Win32.Graphics.DirectWrite,IDWriteTextAnalyzer1,80dad800-e21f-4e83-96ce- Windows.Win32.Graphics.DirectWrite,IDWriteTextAnalyzer2,553a9ff3-5693-4df7-b52b-74806f7f2eb9,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat,9c906818-31d7-4fd3-a151-7c5e225db55a,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat1,5f174b49-0d8b-4cfb-8bca-f1cce9d06c67,true,standard_derived, -Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat2,f67e0edd-9e3d-4ecc-8c32-4183253dfe70,false,,safe_projection_incomplete +Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat2,f67e0edd-9e3d-4ecc-8c32-4183253dfe70,true,standard_derived, Windows.Win32.Graphics.DirectWrite,IDWriteTextFormat3,6d3b5641-e550-430d-a85b-b7bf48a93427,false,,safe_projection_incomplete Windows.Win32.Graphics.DirectWrite,IDWriteTextLayout,53737037-6d14-410b-9bfe-0b182bb70961,false,,incomplete_pointee_layout_for_storage Windows.Win32.Graphics.DirectWrite,IDWriteTextLayout1,9064d822-80a7-465c-a986-df65f78b8feb,false,,incomplete_pointee_layout_for_storage @@ -1945,7 +1945,7 @@ Windows.Win32.Media.DirectShow.Tv,IEnumTuneRequests,1993299c-ced6-4788-87a3-4200 Windows.Win32.Media.DirectShow.Tv,IEnumTuningSpaces,8b8eb248-fc2b-11d2-9d8c-00c04f72d980,true,exact_registry_dependent, Windows.Win32.Media.DirectShow.Tv,IEvalRat,c5c5c5b1-3abc-11d6-b25b-00c04fa0c026,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IGenericDescriptor,6a5918f8-a77a-4f61-aed0-5702bdcda3e6,true,exact_registry_dependent, -Windows.Win32.Media.DirectShow.Tv,IGenericDescriptor2,bf02fb7e-9792-4e10-a68d-033a2cc246a5,false,,safe_projection_incomplete +Windows.Win32.Media.DirectShow.Tv,IGenericDescriptor2,bf02fb7e-9792-4e10-a68d-033a2cc246a5,true,exact_registry_dependent, Windows.Win32.Media.DirectShow.Tv,IGpnvsCommonBase,907e0b5c-e42d-4f04-91f0-26f401f36907,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IGuideData,61571138-5b01-43cd-aeaf-60b784a0bf93,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IGuideDataEvent,efda0c80-f395-42c3-9b3c-56b37dec7bb7,true,standard_derived, @@ -1973,7 +1973,7 @@ Windows.Win32.Media.DirectShow.Tv,IIsdbHierarchicalTransmissionDescriptor,b7b3ae Windows.Win32.Media.DirectShow.Tv,IIsdbLogoTransmissionDescriptor,e0103f49-4ae1-4f07-9098-756db1fa88cd,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IIsdbSIParameterDescriptor,f837dc36-867c-426a-9111-f62093951a45,false,,incomplete_pointee_layout_for_storage Windows.Win32.Media.DirectShow.Tv,IIsdbSeriesDescriptor,07ef6370-1660-4f26-87fc-614adab24b11,false,,incomplete_pointee_layout_for_storage -Windows.Win32.Media.DirectShow.Tv,IIsdbSiParser2,900e4bb7-18cd-453f-98be-3be6aa211772,false,,safe_projection_incomplete +Windows.Win32.Media.DirectShow.Tv,IIsdbSiParser2,900e4bb7-18cd-453f-98be-3be6aa211772,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IIsdbTSInformationDescriptor,d7ad183e-38f5-4210-b55f-ec8d601bbd47,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,IIsdbTerrestrialDeliverySystemDescriptor,39fae0a6-d151-44dd-a28a-765de5991670,true,standard_derived, Windows.Win32.Media.DirectShow.Tv,ILanguageComponentType,b874c8ba-0fa2-11d3-9d8e-00c04f72d980,false,,incomplete_pointee_layout_for_storage diff --git a/tools/dynwinrt-codegen/src/codegen/com/capability.rs b/tools/dynwinrt-codegen/src/codegen/com/capability.rs index 0bb45559..04375dbb 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/capability.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/capability.rs @@ -4557,11 +4557,11 @@ mod tests { ) .unwrap(); assert_eq!(report.summary.eligible_interfaces, 7_929); - assert_eq!(report.summary.safe_complete, 5_697); - assert_eq!(report.summary.safe_incomplete, 2_232); - assert_eq!(report.summary.safe_evidence.safe_complete, 5_697); - assert_eq!(report.summary.safe_evidence.standard_derived, 5_332); - assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 365); + assert_eq!(report.summary.safe_complete, 5_721); + assert_eq!(report.summary.safe_incomplete, 2_208); + assert_eq!(report.summary.safe_evidence.safe_complete, 5_721); + assert_eq!(report.summary.safe_evidence.standard_derived, 5_355); + assert_eq!(report.summary.safe_evidence.exact_registry_dependent, 366); assert_eq!( report.summary.safe_evidence.standard_derived + report.summary.safe_evidence.exact_registry_dependent, @@ -4569,11 +4569,11 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.metadata_fact_occurrences, - 5_983 + 6_012 ); assert_eq!( report.summary.safe_evidence.com_standard_fact_occurrences, - 26_134 + 26_247 ); assert_eq!(report.summary.safe_evidence.registered_exact_entries, 532); assert_eq!( @@ -4589,14 +4589,14 @@ mod tests { .summary .safe_evidence .exact_entry_interface_dependencies, - 693 + 694 ); assert_eq!( report .summary .safe_evidence .exact_family_interface_dependencies, - 424 + 425 ); assert_eq!( report.summary.safe_evidence.by_contract_kind, @@ -4611,7 +4611,7 @@ mod tests { ("enumerator-next".into(), 74), ("flag-selected-buffer".into(), 3), ("null-input".into(), 4), - ("ownership".into(), 182), + ("ownership".into(), 183), ("parameter-direction".into(), 45), ("safearray".into(), 263), ("semantic-hresult".into(), 3), @@ -4619,7 +4619,7 @@ mod tests { ); assert_eq!( report.summary.safe_evidence.by_family_id["com.ownership.v1"], - 123 + 124 ); assert_eq!( report.summary.safe_evidence.by_family_id["audio.conditional-output.v1"], @@ -4888,7 +4888,7 @@ mod tests { counts.safe_incomplete_raw_runtime_blocked, ), ( - 412 - usize::from(target == CensusTarget::I686), + 388 - usize::from(target == CensusTarget::I686), 1_431 - 23 * usize::from(target == CensusTarget::I686), 389 + 24 * usize::from(target == CensusTarget::I686) ) diff --git a/tools/dynwinrt-codegen/src/codegen/com/ir.rs b/tools/dynwinrt-codegen/src/codegen/com/ir.rs index 0177b553..eac38045 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/ir.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/ir.rs @@ -540,8 +540,9 @@ pub(super) enum ProjectedComMethodKind { /// overload dispatch — anything that can present as more than one shape (or /// that overlaps another candidate's shape, e.g. `Buffer` inputs being /// `typeof 'object'` just like a projected COM object) is deliberately left -/// unclassified (`None` from `dispatch_shape`) so overload grouping fails -/// closed instead of guessing. +/// unclassified (`None` from `dispatch_shape`). The projection can emit explicit +/// slot-named entries for validated ordinary methods, but never guesses an +/// implicit dispatcher. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum DispatchShape { Boolean, @@ -619,7 +620,7 @@ pub(super) struct ComSinkPlan { /// overload-dispatch purposes. Returns `None` for any type whose JS /// representation is ambiguous or overlaps another candidate shape (pointer /// types accept `Buffer`/`bigint`/`number` in ways that collide with other -/// categories), so overload grouping can fail closed rather than guess. +/// categories), so overload grouping cannot invent an implicit dispatcher. pub(super) fn dispatch_shape(typ: &ComType) -> Option { match typ { ComType::Primitive(ComPrimitive::Bool) | ComType::Win32Bool => Some(DispatchShape::Boolean), diff --git a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs index aaccc8d9..bf202882 100644 --- a/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/com/project/mod.rs @@ -3184,7 +3184,7 @@ fn input_arity(method: &ProjectedComMethod) -> usize { } fn group_overloads( - methods: Vec, + mut methods: Vec, interface_name: &str, ) -> Result, String> { let mut order = Vec::new(); @@ -3200,12 +3200,17 @@ fn group_overloads( .push(index); } + let mut public_names = methods + .iter() + .map(|method| method.camel_name.clone()) + .collect::>(); let mut overloads = vec![None; methods.len()]; for name in &order { let indices = &groups[name]; if indices.len() < 2 { continue; } + let mut explicit = false; for &index in indices { let method = &methods[index]; if method.kind != ProjectedComMethodKind::Normal { @@ -3217,12 +3222,7 @@ fn group_overloads( )); } if method.string_buffer.is_some() || !method.typed_buffers.is_empty() { - return Err(format!( - "{interface_name}.{name}: cannot project {} overloads sharing the name `{name}` \ - because at least one uses a projected buffer, which is not a \ - safely dispatchable JS shape", - indices.len() - )); + explicit = true; } } @@ -3235,13 +3235,20 @@ fn group_overloads( .push(index); } + let mut planned = Vec::new(); for (arity, bucket) in arity_buckets { + if explicit { + break; + } if bucket.len() == 1 { - overloads[bucket[0]] = Some(OverloadInfo { - public_name: name.clone(), - impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), - dispatch: OverloadDispatch::Arity, - }); + planned.push(( + bucket[0], + OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[bucket[0]].vtable_index), + dispatch: OverloadDispatch::Arity, + }, + )); continue; } let key_param_index = (0..arity).find(|&key_index| { @@ -3258,26 +3265,49 @@ fn group_overloads( }) }); let Some(key_param_index) = key_param_index else { - return Err(format!( - "{interface_name}.{name}: {} overloads share arity {arity} but no parameter \ - position has mutually distinguishable JS shapes (arity/type/category); \ - overload dispatch cannot be safely generated", - bucket.len() - )); + explicit = true; + break; }; for &index in &bucket { let (_, param) = input_params_of(&methods[index])[key_param_index]; let shape = dispatch_shape(¶m.typ).expect("validated distinguishable shape above"); - overloads[index] = Some(OverloadInfo { - public_name: name.clone(), - impl_name: format!("_{name}_{}", methods[index].vtable_index), - dispatch: OverloadDispatch::ArityAndShape { - key_param_index, - shape, + planned.push(( + index, + OverloadInfo { + public_name: name.clone(), + impl_name: format!("_{name}_{}", methods[index].vtable_index), + dispatch: OverloadDispatch::ArityAndShape { + key_param_index, + shape, + }, }, + )); + } + } + if explicit { + for &index in indices { + let method = &mut methods[index]; + let alias = format!("{name}AtSlot{}", method.vtable_index); + if !public_names.insert(alias.clone()) { + return Err(format!( + "{interface_name}.{name}: explicit overload name `{alias}` collides with another projected member" + )); + } + method.camel_name = alias; + let note = format!( + "Explicit overload of `{name}` at native vtable slot {}. The ambiguous unsuffixed method is not exposed.", + method.vtable_index + ); + method.doc = Some(match method.doc.take() { + Some(doc) => format!("{doc}\n\n{note}"), + None => note, }); } + } else { + for (index, plan) in planned { + overloads[index] = Some(plan); + } } } @@ -3304,6 +3334,226 @@ fn input_params_of(method: &ProjectedComMethod) -> Vec<(usize, &ProjectedComPara mod tests { use super::*; + fn overload_method(name: &str, slot: usize, types: Vec) -> ProjectedComMethod { + ProjectedComMethod { + name: name.into(), + camel_name: camel_case(name), + vtable_index: slot, + params: types + .into_iter() + .enumerate() + .map(|(index, typ)| ProjectedComParam { + name: format!("value{index}"), + typ, + direction: ComParamDirection::In, + surface_input: true, + surface_result: false, + nullable: false, + }) + .collect(), + return_convention: ComReturnConvention::HResult, + results: Vec::new(), + string_buffer: None, + typed_buffers: Vec::new(), + shared_counts: Vec::new(), + kind: ProjectedComMethodKind::Normal, + doc: None, + overload: None, + } + } + + #[test] + fn ambiguous_overloads_get_stable_explicit_slot_names() { + let methods = vec![ + overload_method("Pick", 3, Vec::new()), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::I32)]), + overload_method("Pick", 8, vec![ComType::Primitive(ComPrimitive::F64)]), + ]; + let projected = group_overloads(methods.clone(), "IExample").unwrap(); + assert_eq!( + projected + .iter() + .map(|method| method.camel_name.as_str()) + .collect::>(), + ["pickAtSlot3", "pickAtSlot4", "pickAtSlot8"] + ); + assert!(projected.iter().all(|method| method.overload.is_none())); + assert!(projected.iter().all(|method| method.name == "Pick")); + let mut reordered = methods; + reordered.reverse(); + let reordered = group_overloads(reordered, "IExample").unwrap(); + for method in reordered { + assert_eq!( + method.camel_name, + format!("pickAtSlot{}", method.vtable_index) + ); + assert!( + method + .doc + .unwrap() + .contains("ambiguous unsuffixed method is not exposed") + ); + } + } + + #[test] + fn distinguishable_overload_dispatch_is_unchanged() { + for methods in [ + vec![ + overload_method("Pick", 3, Vec::new()), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::I32)]), + ], + vec![ + overload_method("Pick", 3, vec![ComType::Primitive(ComPrimitive::Bool)]), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::I32)]), + ], + ] { + let projected = group_overloads(methods, "IExample").unwrap(); + assert!(projected.iter().all(|method| method.camel_name == "pick")); + assert!(projected.iter().all(|method| method.overload.is_some())); + } + } + + #[test] + fn explicit_overload_names_never_overwrite_a_declared_member() { + let error = group_overloads( + vec![ + overload_method("Pick", 3, vec![ComType::Primitive(ComPrimitive::I32)]), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::U32)]), + overload_method("PickAtSlot3", 5, Vec::new()), + ], + "IExample", + ) + .unwrap_err(); + assert!( + error.contains("pickAtSlot3") && error.contains("collides"), + "{error}" + ); + } + + #[test] + fn explicit_overloads_do_not_relax_synthesized_method_contracts() { + let ordinary = overload_method("Pick", 3, Vec::new()); + let mut synthesized = overload_method("Pick", 4, Vec::new()); + synthesized.kind = ProjectedComMethodKind::FixedCapacityBytes { + guid_param_index: 0, + }; + let error = group_overloads(vec![ordinary, synthesized], "IExample").unwrap_err(); + assert!(error.contains("synthesized/dynamic-IID"), "{error}"); + } + + #[test] + fn explicit_overload_javascript_routes_without_runtime_guessing() { + let methods = group_overloads( + vec![ + overload_method("Pick", 3, vec![ComType::Primitive(ComPrimitive::I32)]), + overload_method("Pick", 4, vec![ComType::Primitive(ComPrimitive::F64)]), + ], + "IOverloads", + ) + .unwrap(); + let interface = ProjectedComInterface { + name: "IOverloads".into(), + namespace: "Tests".into(), + iid: "73552640-8c23-43df-93f7-24d7842430f1".into(), + base_iids: Vec::new(), + is_iunknown_rooted: true, + methods, + activation: ActivationPlan::None, + referenced_enums: Vec::new(), + sink: None, + evidence_dependencies: crate::contract_registry::EvidenceDependencies::default(), + borrowed_storage: None, + }; + let output = + crate::codegen::com::javascript::render::render_com_interface(&interface).unwrap(); + let source = serde_json::to_string(&output.js).unwrap(); + let script = format!( + r#" +const assert = require('node:assert/strict'); +const vm = require('node:vm'); +const calls = []; +const registrations = []; +class Sig {{ addIn() {{ return this; }} }} +const runtime = {{ + DynComMethodSig: Sig, + WinGuid: {{ parse: value => value }}, + __registerComProjection() {{}}, + DynCom: {{ + i32Type() {{}}, f64Type() {{}}, bindComObject() {{}}, + i32: value => ['i32', value], f64: value => ['f64', value], + registerIUnknownInterface() {{ + return {{ + addMethodAt(slot, name) {{ registrations.push([slot, name]); return this; }}, + method(slot) {{ return {{ invoke(_object, args) {{ calls.push([slot, args]); }} }}; }} + }}; + }} + }} +}}; +const exported = {{}}; +vm.runInNewContext({source}, {{ require: () => runtime, exports: exported }}); +const raw = {{ cast() {{ return this; }}, release() {{}} }}; +const value = exported.IOverloads._fromNative(raw); +assert.equal(value.pick, undefined); +value.pickAtSlot3(7); +value.pickAtSlot4(1.5); +assert.deepEqual(registrations, [[3, 'Pick'], [4, 'Pick']]); +assert.deepEqual(JSON.parse(JSON.stringify(calls)), [[3, [['i32', 7]]], [4, [['f64', 1.5]]]]); +"# + ); + let result = std::process::Command::new("node") + .arg("-e") + .arg(script) + .output() + .expect("Node is required for explicit overload routing coverage"); + assert!( + result.status.success(), + "{}", + String::from_utf8_lossy(&result.stderr) + ); + } + + #[test] + fn buffer_overloads_use_explicit_entries_without_losing_their_plan() { + let mut buffer = overload_method( + "Put", + 4, + vec![ComType::TypedBuffer { + element: Box::new(ComType::Primitive(ComPrimitive::U8)), + }], + ); + buffer.params[0].direction = ComParamDirection::InputBuffer; + buffer.params.push(ProjectedComParam { + name: "count".into(), + typ: ComType::Primitive(ComPrimitive::U32), + direction: ComParamDirection::In, + surface_input: false, + surface_result: false, + nullable: false, + }); + let plan = TypedBufferPlan { + buffer_param_index: 0, + element: ComType::Primitive(ComPrimitive::U8), + relation: TypedBufferRelation::Input { + count_param_index: 1, + actual_length_param_index: None, + unit: ProjectedBufferCountUnit::Bytes, + }, + }; + buffer.typed_buffers.push(plan.clone()); + let result = group_overloads( + vec![ + overload_method("Put", 3, vec![ComType::Primitive(ComPrimitive::I32)]), + buffer, + ], + "IExample", + ) + .unwrap(); + assert_eq!(result[0].camel_name, "putAtSlot3"); + assert_eq!(result[1].camel_name, "putAtSlot4"); + assert_eq!(result[1].typed_buffers, [plan]); + } + #[test] fn endpoint_activation_preserves_the_semantic_call_plan() { let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { diff --git a/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs b/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs new file mode 100644 index 00000000..a0a4c40b --- /dev/null +++ b/tools/dynwinrt-codegen/tests/com_explicit_overload_test.rs @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use dynwinrt_codegen::{codegen::com, com_metadata}; +use std::{fs, path::Path, process::Command}; + +#[test] +fn ambiguous_native_overloads_expose_exact_callable_slots() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + for (namespace, interface_name, method_name, camel_name) in [ + ( + "Windows.Win32.Graphics.Direct2D", + "ID2D1Device1", + "CreateDeviceContext", + "createDeviceContext", + ), + ( + "Windows.Win32.Graphics.Direct2D", + "ID2D1Device7", + "CreateDeviceContext", + "createDeviceContext", + ), + ( + "Windows.Win32.Graphics.DirectWrite", + "IDWriteFontCollection1", + "GetFontFamily", + "getFontFamily", + ), + ( + "Windows.Win32.AI.MachineLearning.WinML", + "IMLOperatorKernelContext", + "GetOutputTensor", + "getOutputTensor", + ), + ( + "Windows.Win32.Graphics.DirectComposition", + "IDCompositionDynamicTexture", + "SetTexture", + "setTexture", + ), + ] { + let interface = + com_metadata::parse_com_interface(&winmd, namespace, interface_name).unwrap(); + let output = com::generate_com_interface_files(&interface, &winmd) + .unwrap_or_else(|error| panic!("{interface_name}: {error}")); + let slots = interface + .raw_methods + .as_ref() + .unwrap() + .iter() + .filter(|method| method.metadata_name == method_name) + .map(|method| method.vtable_index) + .collect::>(); + assert!( + slots.len() >= 2, + "{interface_name} must exercise inherited overloads" + ); + for slot in slots { + let name = format!("{camel_name}AtSlot{slot}"); + assert!( + output.dts.contains(&format!("{name}(")), + "{interface_name}: missing {name}" + ); + assert!( + output.js.contains(&format!("{name}(")), + "{interface_name}: missing {name}" + ); + assert!( + output.js.contains(&format!(".method({slot}).invoke")), + "{interface_name}: lost slot {slot}" + ); + assert!( + output + .js + .contains(&format!(".addMethodAt({slot}, '{method_name}'")), + "{interface_name}: registration changed" + ); + } + + assert!(!output.dts.contains(&format!(" {camel_name}("))); + assert!(!output.js.contains(&format!(" {camel_name}("))); + } +} + +#[test] +fn generated_explicit_overload_declarations_typecheck() { + let Ok(winmd) = std::env::var("DYNWINRT_WIN32_WINMD") else { + return; + }; + let package = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .parent() + .unwrap() + .join(r"bindings\js"); + let tsc = package.join(r"node_modules\typescript\bin\tsc"); + if !tsc.is_file() { + eprintln!("Skipping: repository TypeScript compiler not available"); + return; + } + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let output = std::env::temp_dir().join(format!( + "dynwinrt-com-overloads-{}-{nonce}", + std::process::id() + )); + let generation = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd", &winmd, "--class-name", + "Windows.Win32.Graphics.Direct2D.ID2D1Device1,Windows.Win32.Graphics.DirectWrite.IDWriteFontCollection1", + "--output"]) + .arg(&output) + .output() + .expect("run overload codegen"); + assert!( + generation.status.success(), + "{}", + String::from_utf8_lossy(&generation.stderr) + ); + let device = com_metadata::parse_com_interface( + &winmd, + "Windows.Win32.Graphics.Direct2D", + "ID2D1Device1", + ) + .unwrap(); + let slots = device + .raw_methods + .as_ref() + .unwrap() + .iter() + .filter(|method| method.metadata_name == "CreateDeviceContext") + .map(|method| method.vtable_index) + .collect::>(); + let calls = slots + .iter() + .map(|slot| format!("device.createDeviceContextAtSlot{slot}(0);")) + .collect::>() + .join("\n"); + fs::write( + output.join("usage.ts"), + format!( + "import type {{ ID2D1Device1 }} from './com/index.js';\n\ + declare const device: ID2D1Device1;\n{calls}\n\ + // @ts-expect-error ambiguous unsuffixed overload is intentionally absent\n\ + device.createDeviceContext(0);\n\ + // @ts-expect-error the native enum input remains typed\n\ + device.createDeviceContextAtSlot{}('invalid');\n", + slots[0] + ), + ) + .unwrap(); + let config = serde_json::json!({ + "compilerOptions": { + "target": "ES2022", "module": "Node16", "moduleResolution": "Node16", + "strict": true, "noEmit": true, "skipLibCheck": false, + "baseUrl": output, + "typeRoots": [package.join(r"node_modules\@types")], + "paths": { + "@microsoft/dynwinrt/com": [package.join(r"dist\com.d.ts")], + "@microsoft/dynwinrt/com/unsafe": [package.join(r"dist\com-unsafe.d.ts")] + } + }, + "include": ["usage.ts", "com/**/*.d.ts"] + }); + fs::write( + output.join("tsconfig.json"), + serde_json::to_vec(&config).unwrap(), + ) + .unwrap(); + let checked = Command::new("node") + .arg(tsc) + .args(["--noEmit", "-p"]) + .arg(output.join("tsconfig.json")) + .output() + .expect("run overload tsc"); + fs::remove_dir_all(&output).unwrap(); + assert!( + checked.status.success(), + "{}\n{}", + String::from_utf8_lossy(&checked.stdout), + String::from_utf8_lossy(&checked.stderr) + ); +}