diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 72a873d4..b3c7aa53 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -91,17 +91,15 @@ jobs: run: | npm install --prefix target/tsc --no-save --ignore-scripts --no-package-lock typescript@5.9.3 $tsc = (Resolve-Path target/tsc/node_modules/typescript/bin/tsc).Path - $windowsWinmd = Get-ChildItem 'C:\Program Files (x86)\Windows Kits\10\UnionMetadata' ` - -Filter Windows.winmd -File -Recurse | - Sort-Object FullName -Descending | - Select-Object -First 1 - if (-not $windowsWinmd) { - throw 'Windows SDK metadata is required for declaration tests' - } "DYNWINRT_TSC=$tsc" >> $env:GITHUB_ENV - "DYNWINRT_WINDOWS_WINMD=$($windowsWinmd.FullName)" >> $env:GITHUB_ENV "DYNWINRT_REQUIRE_TSC=1" >> $env:GITHUB_ENV - uses: NuGet/setup-nuget@v2 + - name: Restore pinned Windows SDK corpus + shell: pwsh + run: | + $winmd = .\eng\ci\restore-windows-metadata.ps1 ` + -OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus') + "DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV - name: Install Win32 metadata shell: pwsh run: | @@ -579,6 +577,10 @@ jobs: cargo test -p dynwinrt-codegen --test python_consumer_typing_test ` reference_array_results_preserve_null_elements -- --exact if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + $env:DYNWINRT_TEST_INSTALLED_RUNTIME = '1' + cargo test -p dynwinrt-codegen --test python_consumer_typing_test ` + resource_dictionary_keys_are_scoped_and_typed_in_stubs_and_inline_sources -- --exact + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } cargo test -p dynwinrt-codegen --test python_collection_helper_collision_test ` --test python_collection_member_collision_test -- --nocapture if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index bbe33c65..c6ebe048 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -15,6 +15,7 @@ on: - 'crates/dynwinrt/**' - 'crates/dynwinrt-com-contracts/**' - 'eng/coverage/**' + - 'eng/ci/restore-windows-metadata.ps1' - 'tests/e2e/**' - 'tools/dynwinrt-codegen/**' push: @@ -57,6 +58,13 @@ jobs: - uses: NuGet/setup-nuget@v2 + - name: Restore pinned Windows SDK corpus + shell: pwsh + run: | + $winmd = .\eng\ci\restore-windows-metadata.ps1 ` + -OutputDirectory (Join-Path $env:RUNNER_TEMP 'windows-sdk-corpus') + "DYNWINRT_WINDOWS_WINMD=$winmd" >> $env:GITHUB_ENV + - name: Install cargo-llvm-cov shell: pwsh run: cargo install cargo-llvm-cov --version 0.8.7 --locked diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fe460372..e9e010c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,6 +44,20 @@ cargo build -p dynwinrt-codegen ### Running Tests +The codegen's exhaustive Windows SDK corpus assertions use the immutable +`Microsoft.Windows.SDK.CPP` package pinned in +`tools/dynwinrt-codegen/tests/windows_sdk_corpus.json`, not whichever SDK servicing +update is installed on the machine. Restore and verify that metadata before +running codegen library tests or the coverage pipeline (requires `nuget` on PATH): + +```powershell +$env:DYNWINRT_WINDOWS_WINMD = .\eng\ci\restore-windows-metadata.ps1 ` + -OutputDirectory .\target\windows-sdk-corpus +``` + +CI uses the same helper and SHA-256 pin. A missing or different corpus fails with +restore instructions rather than skipping the exact member/count assertions. + ```bash # Core library tests cargo test -p dynwinrt diff --git a/bindings/py/README.md b/bindings/py/README.md index f7fa3915..9f4003c8 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -436,6 +436,30 @@ classes with no instance surface are not projection targets. ### Explicit boxing and unboxing of `Object` values +Generated `Microsoft.UI.Xaml.ResourceDictionary` and +`Windows.UI.Xaml.ResourceDictionary` projections, and their WinMD-derived +classes such as `Windows.UI.Xaml.ColorPaletteResources`, accept string keys directly: + +```python +raw_style = resources.lookup("AccentButtonStyle") +raw_style = resources["AccentButtonStyle"] +raw_style = resources.get("AccentButtonStyle") +``` + +Their key-taking lookup, membership, insert, update and removal operations box +`str` as a WinRT string internally. String subclasses, including `StrEnum` and +`str`/`Enum` members, use their underlying string contents rather than custom +`__str__()` formatting. Existing raw or projected-object keys remain accepted, +and results and enumerated keys remain raw `DynWinRTValue` objects +(or `None` where already supported). `lookup()` preserves native errors; +missing `[]` keys raise `KeyError`, and `get()` keeps its normal default. +The `get()` and `pop()` result annotations include the supplied default type +in both `.pyi` and inline-only (`--no-pyi`) output. WinMD-derived projections +retain the base dictionary's key contract even with an independent default interface. +This is a ResourceDictionary-specific input convenience, not automatic boxing +for generic `IMap`, `IMapView` or other +`Object`/`IInspectable` APIs. Continue boxing their inputs explicitly. + Generic WinRT `Object`/`IInspectable` results and parameters remain raw `DynWinRTValue` instances: an `Object` may be any runtime object, not only a boxed value. Convert explicitly where the application expects a boxed diff --git a/eng/ci/restore-windows-metadata.ps1 b/eng/ci/restore-windows-metadata.ps1 new file mode 100644 index 00000000..e3565846 --- /dev/null +++ b/eng/ci/restore-windows-metadata.ps1 @@ -0,0 +1,31 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +param( + [Parameter(Mandatory = $true)][string]$OutputDirectory, + [string]$NuGet = "nuget" +) + +$ErrorActionPreference = "Stop" +$root = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +$pin = Get-Content -LiteralPath (Join-Path $root "tools\dynwinrt-codegen\tests\windows_sdk_corpus.json") -Raw | + ConvertFrom-Json +$destination = [IO.Path]::GetFullPath($OutputDirectory) +$packageRoot = Join-Path $destination "$($pin.package).$($pin.version)" +$winmd = Join-Path $packageRoot $pin.relative_path +if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) { + & $NuGet install $pin.package -Version $pin.version ` + -OutputDirectory $destination -DirectDownload -NonInteractive | Out-Host + if ($LASTEXITCODE -ne 0) { + throw "Failed to restore $($pin.package) $($pin.version)" + } +} +if (-not (Test-Path -LiteralPath $winmd -PathType Leaf)) { + throw "Pinned Windows SDK package is missing $($pin.relative_path)" +} +$actual = (Get-FileHash -LiteralPath $winmd -Algorithm SHA256).Hash +if ($actual -ne $pin.sha256) { + throw "Pinned Windows SDK metadata hash mismatch: expected $($pin.sha256), got $actual at $winmd" +} +Write-Host "Verified Windows SDK corpus: $($pin.package) $($pin.version), SHA256 $actual" +(Resolve-Path -LiteralPath $winmd).Path diff --git a/eng/ci/test_ci.py b/eng/ci/test_ci.py index df818269..c01e2495 100644 --- a/eng/ci/test_ci.py +++ b/eng/ci/test_ci.py @@ -2,6 +2,7 @@ # Licensed under the MIT License. import copy +import hashlib import json import os from pathlib import Path @@ -191,6 +192,87 @@ def test_missing_empty_and_invalid_readmes_fail_in_github_wrapper(self): readme.write_bytes(original) +class WindowsCorpusTests(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory(prefix="dynwinrt-ci-corpus-") + self.addCleanup(self.temporary.cleanup) + self.repo = Path(self.temporary.name) + self.relative_pin = Path("tools/dynwinrt-codegen/tests/windows_sdk_corpus.json") + self.pin = json.loads((ROOT / self.relative_pin).read_text(encoding="utf-8")) + self.payload = b"test metadata bytes" + self.pin["sha256"] = hashlib.sha256(self.payload).hexdigest() + destination = self.repo / self.relative_pin + destination.parent.mkdir(parents=True) + destination.write_text(json.dumps(self.pin), encoding="utf-8") + self.script = self.repo / "eng/ci/restore-windows-metadata.ps1" + self.script.parent.mkdir(parents=True) + shutil.copyfile(CI / "restore-windows-metadata.ps1", self.script) + self.output = self.repo / "packages" + self.winmd = ( + self.output / f"{self.pin['package']}.{self.pin['version']}" + / self.pin["relative_path"] + ) + self.nuget = self.repo / "nuget.ps1" + self.nuget.write_text( + "param([string]$Command, [string]$Id, [string]$Version, " + "[string]$OutputDirectory, [switch]$DirectDownload, [switch]$NonInteractive)\n" + "if ($Command -ne 'install' -or -not $DirectDownload -or -not $NonInteractive) { exit 2 }\n" + f"if ($Id -ne '{self.pin['package']}' -or $Version -ne '{self.pin['version']}') {{ exit 3 }}\n" + "$package = Join-Path $OutputDirectory \"$Id.$Version\"\n" + f"$path = Join-Path $package '{self.pin['relative_path']}'\n" + "New-Item -ItemType Directory -Path (Split-Path -Parent $path) -Force | Out-Null\n" + "[IO.File]::WriteAllBytes($path, [Text.Encoding]::UTF8.GetBytes('test metadata bytes'))\n" + "exit 0\n", + encoding="utf-8", + ) + + def restore(self): + return powershell( + self.script, "-OutputDirectory", self.output, "-NuGet", self.nuget, + ) + + def test_restore_verifies_content_and_reuses_only_verified_existing_input(self): + result = self.restore() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + returned = Path(result.stdout.strip().splitlines()[-1]) + self.assertTrue(returned.is_absolute()) + self.assertTrue(returned.samefile(self.winmd), f"{returned} != {self.winmd}") + self.assertEqual(self.winmd.read_bytes(), self.payload) + self.nuget.unlink() + result = self.restore() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_modified_input_and_failed_restore_are_errors(self): + self.winmd.parent.mkdir(parents=True) + self.winmd.write_bytes(b"rolling SDK changed in-place") + result = self.restore() + self.assertNotEqual(result.returncode, 0) + self.assertIn("metadata hash mismatch", result.stdout + result.stderr) + self.assertEqual(self.winmd.read_bytes(), b"rolling SDK changed in-place") + self.winmd.unlink() + self.nuget.write_text("exit 7\n", encoding="utf-8") + result = self.restore() + self.assertNotEqual(result.returncode, 0) + self.assertIn("Failed to restore", result.stdout + result.stderr) + + def test_build_and_coverage_share_the_pinned_corpus_input(self): + coverage = yaml.safe_load( + (ROOT / ".github/workflows/coverage.yml").read_text(encoding="utf-8") + ) + triggers = coverage.get("on", coverage.get(True)) + self.assertIn( + "eng/ci/restore-windows-metadata.ps1", triggers["pull_request"]["paths"] + ) + for job in (JOBS["test-rust"], coverage["jobs"]["coverage"]): + step, = [ + step for step in job["steps"] + if step.get("name") == "Restore pinned Windows SDK corpus" + ] + self.assertIn(r".\eng\ci\restore-windows-metadata.ps1", step["run"]) + self.assertIn("DYNWINRT_WINDOWS_WINMD=$winmd", step["run"]) + self.assertNotIn("Sort-Object", step["run"]) + + class WorkflowTests(unittest.TestCase): def ancestors(self, job): needs = JOBS[job].get("needs", []) diff --git a/tests/e2e/runners/py_winui_runner.py b/tests/e2e/runners/py_winui_runner.py index e283e37e..e55880a1 100644 --- a/tests/e2e/runners/py_winui_runner.py +++ b/tests/e2e/runners/py_winui_runner.py @@ -14,6 +14,82 @@ from pathlib import Path +def check_resource_dictionary_keys(resources): + from enum import Enum, StrEnum + from types import SimpleNamespace + from dynwinrt import DynWinRTValue, to_winrt_object, unbox_object + from dynwinrt.values import Char16 + + class ResourceKey(StrEnum): + ACCENT = "AccentButtonStyle" + + class LegacyResourceKey(str, Enum): + ACCENT = "AccentButtonStyle" + + name = "AccentButtonStyle" + boxed = to_winrt_object(name) + identity = boxed.identity_raw() + style = resources.lookup(boxed) + assert isinstance(style, DynWinRTValue) and not style.is_null() + for key in (name, boxed, SimpleNamespace(_obj=boxed), ResourceKey.ACCENT, LegacyResourceKey.ACCENT): + assert resources.lookup(key).identity_raw() == style.identity_raw() + assert resources[key].identity_raw() == style.identity_raw() + assert resources.get(key).identity_raw() == style.identity_raw() + assert resources.has_key(key) and key in resources + + missing = "DynWinRT.Missing.Resource.StringKey" + errors = [] + for key in (to_winrt_object(missing), missing): + try: + resources.lookup(key) + except OSError as error: + errors.append((error.winerror, str(error))) + else: + raise AssertionError("missing ResourceDictionary.lookup did not raise") + assert errors[0] == errors[1] + try: + resources[missing] + except KeyError as error: + assert error.args == (missing,) + else: + raise AssertionError("missing ResourceDictionary item did not raise") + fallback = object() + assert resources.get(missing) is None + assert resources.get(missing, fallback) is fallback + assert resources.pop(missing, fallback) is fallback + + local = type(resources)() + assert local.insert("first", style) is False + assert local.insert("first", style) is True + local["second"] = style + local.update(third=style) + assert local.setdefault("first", style).identity_raw() == style.identity_raw() + assert local.setdefault("fourth", style).identity_raw() == style.identity_raw() + # Even tagged str subclasses are keys of the native String contract. + local[Char16("x")] = style + assert local["x"].identity_raw() == style.identity_raw() + keys = list(local) + assert len(local) == len(keys) == 5 + assert all(isinstance(key, DynWinRTValue) for key in keys) + assert {unbox_object(key) for key in keys} == {"first", "second", "third", "fourth", "x"} + assert local != {unbox_object(key): style for key in keys} + local.remove("first") + del local["second"] + assert local.pop("third").identity_raw() == style.identity_raw() + assert len(local) == 2 + assert boxed.identity_raw() == identity and not boxed.is_released() + assert resources.lookup(boxed).identity_raw() == style.identity_raw() + released = to_winrt_object(name) + released.release() + for key in (released, SimpleNamespace(_obj=released)): + try: + resources.lookup(key) + except RuntimeError as error: + assert "released" in str(error) + else: + raise AssertionError("released ResourceDictionary key was accepted") + + def load_type(package: str, namespace: str, name: str): return getattr(importlib.import_module(f"{package}.{namespace}"), name) @@ -207,6 +283,7 @@ def launched() -> None: f"{sorted(theme_names)!r}" ) state["fluent_theme_names"] = sorted(theme_names) + check_resource_dictionary_keys(resources) if app.requested_theme != ApplicationTheme.Dark: raise RuntimeError( "Application requested theme was not applied" diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs index 7014c895..0717cb83 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs @@ -4,7 +4,7 @@ use crate::meta::{ ClassMeta, CollectionInputRole, InterfaceMeta, WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, }; -use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; +use crate::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta}; use super::member_plan::CollectionHelperPlan; use super::naming::{PythonProjectionContext, PythonSupportSymbol}; @@ -38,6 +38,70 @@ const JSON_OBJECT: NonNullJsonCollection = NonNullJsonCollection { class_iid: "064e24dd-29c2-4f83-9ac1-9ee11578beb3", }; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum CollectionInputContract { + #[default] + General, + NonNullJson, + ResourceDictionary, +} + +impl CollectionInputContract { + pub(crate) fn for_class(class: &ClassMeta) -> Self { + if stock_json_class_contract(class).is_some() { + return Self::NonNullJson; + } + let is_resource_dictionary = |namespace: &str, name: &str| { + matches!(namespace, "Microsoft.UI.Xaml" | "Windows.UI.Xaml") + && name == "ResourceDictionary" + }; + let inherits_resource_dictionary = class + .base_class + .iter() + .chain(&class.ancestor_classes) + .any(|ancestor| { + ancestor.kind == TypeKind::Class + && is_resource_dictionary(&ancestor.namespace, &ancestor.name) + }); + if class.full_name == format!("{}.{}", class.namespace, class.name) + && (is_resource_dictionary(&class.namespace, &class.name) + || inherits_resource_dictionary) + && class_interface(class).is_some_and(|iface| { + iface.namespace == WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE + && iface.generic_piid.as_deref() == Some(IMAP_PIID) + && iface.generic_args == [TypeMeta::Object, TypeMeta::Object] + }) + { + Self::ResourceDictionary + } else { + Self::General + } + } + + pub(crate) fn is_non_null_json(self) -> bool { + self == Self::NonNullJson + } + + pub(crate) fn string_key(self, typ: &TypeMeta, role: CollectionInputRole) -> bool { + self == Self::ResourceDictionary + && role == CollectionInputRole::Key + && *typ == TypeMeta::Object + } + + pub(crate) fn key_input_type( + self, + typ: &TypeMeta, + context: &PythonProjectionContext, + ) -> String { + let input = py_collection_input_type(typ, context); + if self.string_key(typ, CollectionInputRole::Key) { + format!("str | {}", super::type_helpers::unquoted(&input)) + } else { + input + } + } +} + fn is_json_value(typ: &TypeMeta) -> bool { matches!( typ, @@ -280,6 +344,21 @@ pub(super) fn protocol_helper_imports<'a>( } } +/// Module scope lets type checkers bind defaults and get_type_hints resolve them. +pub(super) fn protocol_helper_typevars( + helpers: &CollectionHelperPlan, + context: &PythonProjectionContext, + input_contract: CollectionInputContract, +) -> String { + if input_contract != CollectionInputContract::ResourceDictionary + || !(helpers.get || helpers.pop) + { + return String::new(); + } + let default = context.support_symbol_reference(PythonSupportSymbol::MappingDefault); + format!("\n{default} = TypeVar('{default}')\n") +} + /// Bulk helpers write the same inputs as item assignment, but return only the /// read projection (or Self), never the caller's unconverted input. pub(super) fn protocol_helper_methods( @@ -288,12 +367,12 @@ pub(super) fn protocol_helper_methods( owner_name: &str, context: &PythonProjectionContext, surface: AnnotationSurface, - stock_json_receiver: bool, + input_contract: CollectionInputContract, indent_spaces: usize, ) -> String { let indent = " ".repeat(indent_spaces); let input = |typ| { - if stock_json_receiver { + if input_contract.is_non_null_json() { py_param_type_safe(typ, context) } else { py_collection_input_type(typ, context) @@ -333,9 +412,9 @@ pub(super) fn protocol_helper_methods( result } (Some(CollectionKind::MutableMapping), [key, value]) => { - let key_input = py_collection_input_type(key, context); + let key_input = input_contract.key_input_type(key, context); let value_input = input(value); - let value_read = if stock_json_receiver { + let value_read = if input_contract.is_non_null_json() { py_param_type_safe(value, context) } else { py_collection_item_type(value, ElementContainer::Mutable, surface, context) @@ -351,7 +430,9 @@ pub(super) fn protocol_helper_methods( .expect("serialize a Python type annotation"); let mapping = format!("{supports}[{key_reference}, {value_input}]"); let pairs = format!("Iterable[tuple[{key_input}, {value_input}]]"); - let keywords = if matches!(key, TypeMeta::String | TypeMeta::Char16) { + let keywords = if matches!(key, TypeMeta::String | TypeMeta::Char16) + || input_contract.string_key(key, CollectionInputRole::Key) + { format!(", **kwargs: {value_input}") } else { String::new() @@ -374,7 +455,7 @@ pub(super) fn protocol_helper_methods( )); } } - let nullable = may_project_none(value) && !stock_json_receiver; + let nullable = may_project_none(value) && !input_contract.is_non_null_json(); if helpers.setdefault && is_stub { let default = if nullable { " = None" } else { "" }; result.push_str(&format!( @@ -389,7 +470,7 @@ pub(super) fn protocol_helper_methods( {indent}def setdefault(self, key: {key_input}, *, default: {value_input}) -> {value_read}: ...\n" )); } - let default_input = py_optional_type(value_input); + let default_input = py_optional_type(value_input.clone()); // An omitted/invalid default is still ignored for an existing // key. The overloads constrain values that may be inserted. result.push_str(&format!( @@ -397,6 +478,50 @@ pub(super) fn protocol_helper_methods( {indent} return super().setdefault(key, default)\n" )); } + if input_contract.string_key(key, CollectionInputRole::Key) { + if helpers.getitem && !is_stub { + result.push_str(&format!( + "\n{indent}def __getitem__(self, key: {key_input}) -> {value_read}:\n\ + {indent} value = super().__getitem__(key)\n\ + {indent} if value is None or isinstance(value, DynWinRTValue):\n\ + {indent} return value\n\ + {indent} raise TypeError('ResourceDictionary Object results must remain raw DynWinRTValue objects')\n" + )); + } + if helpers.setitem && !is_stub { + result.push_str(&format!( + "\n{indent}def __setitem__(self, key: {key_input}, value: {value_input}) -> None:\n\ + {indent} super().__setitem__(key, value)\n" + )); + } + if helpers.delitem && !is_stub { + result.push_str(&format!( + "\n{indent}def __delitem__(self, key: {key_input}) -> None:\n\ + {indent} super().__delitem__(key)\n" + )); + } + if helpers.get || helpers.pop { + let default_variable = + context.support_symbol_reference(PythonSupportSymbol::MappingDefault); + for (name, enabled) in [("get", helpers.get), ("pop", helpers.pop)] { + if !enabled { + continue; + } + result.push_str(&format!( + "\n{indent}@overload\n\ + {indent}def {name}(self, key: {key_input}) -> {value_read}: ...\n\ + {indent}@overload\n\ + {indent}def {name}(self, key: {key_input}, default: {default_variable}) -> {value_read} | {default_variable}: ...\n" + )); + if !is_stub { + result.push_str(&format!( + "{indent}def {name}(self, key: {key_input}, *args: object, **kwargs: object) -> object:\n\ + {indent} return super().{name}(key, *args, **kwargs)\n" + )); + } + } + } + } result } _ => String::new(), @@ -407,6 +532,177 @@ pub(super) fn protocol_helper_methods( mod tests { use super::*; + #[test] + fn resource_keys_require_the_full_class_identity_and_object_map_contract() { + let resource = |namespace: &str| ClassMeta { + namespace: namespace.into(), + name: "ResourceDictionary".into(), + full_name: format!("{namespace}.ResourceDictionary"), + default_interface: Some(InterfaceMeta { + namespace: WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE.into(), + generic_piid: Some(IMAP_PIID.into()), + generic_args: vec![TypeMeta::Object, TypeMeta::Object], + ..Default::default() + }), + ..Default::default() + }; + for namespace in ["Microsoft.UI.Xaml", "Windows.UI.Xaml"] { + let class = resource(namespace); + let contract = CollectionInputContract::for_class(&class); + assert_eq!(contract, CollectionInputContract::ResourceDictionary); + assert!(contract.string_key(&TypeMeta::Object, CollectionInputRole::Key)); + assert!(!contract.string_key(&TypeMeta::Object, CollectionInputRole::Value)); + assert!(!contract.string_key(&TypeMeta::Object, CollectionInputRole::Element)); + assert!(!contract.string_key(&TypeMeta::String, CollectionInputRole::Key)); + + let base = crate::types::TypeRef { + namespace: namespace.into(), + name: "ResourceDictionary".into(), + kind: TypeKind::Class, + }; + let mut derived = ClassMeta { + namespace: "Contoso".into(), + name: "DerivedResources".into(), + full_name: "Contoso.DerivedResources".into(), + base_class: Some(base.clone()), + default_interface: Some(InterfaceMeta { + namespace: "Contoso".into(), + name: "IDerivedResources".into(), + ..Default::default() + }), + required_interfaces: vec![class.default_interface.unwrap()], + ..Default::default() + }; + assert_eq!( + CollectionInputContract::for_class(&derived), + CollectionInputContract::ResourceDictionary + ); + derived.base_class = Some(crate::types::TypeRef { + namespace: "Contoso".into(), + name: "IntermediateResources".into(), + kind: TypeKind::Class, + }); + assert_eq!( + CollectionInputContract::for_class(&derived), + CollectionInputContract::General + ); + derived.ancestor_classes.push(base); + assert_eq!( + CollectionInputContract::for_class(&derived), + CollectionInputContract::ResourceDictionary + ); + derived.required_interfaces[0].generic_args[0] = TypeMeta::String; + assert_eq!( + CollectionInputContract::for_class(&derived), + CollectionInputContract::General + ); + } + let mut controls = vec![resource("Contoso")]; + let mut wrong_full_name = resource("Microsoft.UI.Xaml"); + wrong_full_name.full_name = "Contoso.ResourceDictionary".into(); + controls.push(wrong_full_name); + let mut wrong_class = resource("Microsoft.UI.Xaml"); + wrong_class.name = "Other".into(); + wrong_class.full_name = "Microsoft.UI.Xaml.Other".into(); + controls.push(wrong_class); + for (namespace, piid, args) in [ + ( + "Contoso", + IMAP_PIID, + vec![TypeMeta::Object, TypeMeta::Object], + ), + ( + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + IMAP_VIEW_PIID, + vec![TypeMeta::Object, TypeMeta::Object], + ), + ( + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + IMAP_PIID, + vec![TypeMeta::String, TypeMeta::Object], + ), + ( + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + IMAP_PIID, + vec![TypeMeta::Object, TypeMeta::String], + ), + ] { + let mut class = resource("Microsoft.UI.Xaml"); + let iface = class.default_interface.as_mut().unwrap(); + iface.namespace = namespace.into(); + iface.generic_piid = Some(piid.into()); + iface.generic_args = args; + controls.push(class); + } + for class in controls { + assert_eq!( + CollectionInputContract::for_class(&class), + CollectionInputContract::General + ); + } + } + + #[test] + fn mapping_default_typevars_are_module_scoped_and_collision_aware() { + let peer = TypeMeta::RuntimeClass { + namespace: "Contoso".into(), + name: "_MapDefaultT".into(), + default_interface: None, + }; + let interface = InterfaceMeta { + namespace: WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE.into(), + generic_piid: Some(IMAP_PIID.into()), + generic_args: vec![TypeMeta::Object, TypeMeta::Object], + methods: vec![crate::meta::MethodMeta { + return_type: Some(peer.clone()), + ..Default::default() + }], + ..Default::default() + }; + let class = ClassMeta { + namespace: "Microsoft.UI.Xaml".into(), + name: "ResourceDictionary".into(), + full_name: "Microsoft.UI.Xaml.ResourceDictionary".into(), + default_interface: Some(interface.clone()), + ..Default::default() + }; + let context = PythonProjectionContext::standalone([ + TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name), + peer.type_identity(), + ]) + .unwrap(); + let local = context.for_class_module(&class, &[]); + let symbol = local.support_symbol_reference(PythonSupportSymbol::MappingDefault); + assert_ne!(symbol, "_MapDefaultT"); + let helpers = CollectionHelperPlan { + get: true, + pop: true, + ..Default::default() + }; + let contract = CollectionInputContract::ResourceDictionary; + assert_eq!( + protocol_helper_typevars(&helpers, &local, contract), + format!("\n{symbol} = TypeVar('{symbol}')\n") + ); + assert!( + protocol_helper_typevars(&helpers, &local, CollectionInputContract::General).is_empty() + ); + for surface in [AnnotationSurface::Runtime, AnnotationSurface::Stub] { + let methods = protocol_helper_methods( + &interface, + &helpers, + &class.name, + &local, + surface, + contract, + 4, + ); + assert!(methods.contains(&format!("default: {symbol}"))); + assert!(!methods.contains(&format!("{}.{symbol}", class.name))); + assert!(!methods.contains("TypeVar(")); + } + } + #[test] fn json_null_contract_needs_the_exact_element_iid_and_native_class() { let json_value = TypeMeta::Interface { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs index fe627da4..c08e288f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -8,8 +8,8 @@ use super::structs::{generate_struct_helpers, generate_struct_imports}; use super::*; use crate::codegen::winrt::extensions::winui::{self, WinUiAbiType}; use crate::codegen::winrt::python::collections::{ - CollectionKind, class_interface, interface_kind, map_iterable_identity, - non_null_json_collection, runtime_mixin, stock_json_class_contract, + CollectionInputContract, CollectionKind, class_interface, interface_kind, + map_iterable_identity, non_null_json_collection, runtime_mixin, stock_json_class_contract, }; use crate::codegen::winrt::python::member_plan::{ ClassMemberPlan, PlannedMember, ScopePlan, class_instance_interfaces, interface_member_plan, @@ -42,7 +42,7 @@ pub fn generate_class<'a>( let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); - let stock_json_receiver = stock_json_class_contract(class).is_some(); + let input_contract = CollectionInputContract::for_class(class); let non_null_json = collection_iface .zip(collection_kind) .and_then(|(iface, kind)| non_null_json_collection(kind, &iface.generic_args)); @@ -102,6 +102,14 @@ pub fn generate_class<'a>( .flat_map(|interface| interface.methods.iter()), collection_iface.is_some(), )); + if input_contract == CollectionInputContract::ResourceDictionary { + out.push_str(&format!( + "from dynwinrt import to_winrt_object as {}\n\ + from dynwinrt.values import PropertyType as {}\n", + context.support_symbol_reference(PythonSupportSymbol::BoxObject), + context.support_symbol_reference(PythonSupportSymbol::PropertyType), + )); + } if has_public_composition { out.push_str( "from dynwinrt import register_xaml_runtime_class as _dynwinrt_register_xaml_runtime_class\n", @@ -143,6 +151,11 @@ pub fn generate_class<'a>( { out.push_str(IREFERENCE_HELPER); } + out.push_str(&super::super::collections::protocol_helper_typevars( + &plan.instance.collection_helpers, + context, + input_contract, + )); out.push('\n'); let mut type_checking_imports = Vec::new(); @@ -651,7 +664,7 @@ pub fn generate_class<'a>( .name .strip_prefix("put_") .is_some_and(|suffix| property_getters.contains(suffix)), - stock_json_receiver, + input_contract, } }; // Python evaluates decorators while building the class. Emit every getter @@ -713,7 +726,7 @@ pub fn generate_class<'a>( &context.class_name(class), context, super::super::nullability::AnnotationSurface::Runtime, - stock_json_receiver, + input_contract, 4, )); } @@ -926,7 +939,7 @@ pub fn generate_class<'a>( .iter() .any(|candidate| candidate.name == format!("get_{suffix}")) }), - stock_json_receiver: false, + input_contract: CollectionInputContract::General, }; let members = reorder_getters_before_setters(&req_iface.methods) .into_iter() @@ -972,7 +985,7 @@ pub fn generate_class<'a>( &symbol, context, super::super::nullability::AnnotationSurface::Runtime, - false, + CollectionInputContract::General, 4, )); } @@ -1347,6 +1360,7 @@ fn generate_python_constructor( .map(|candidate| DispatchCandidate { legacy_preservation: None, params: candidate.public_params.clone(), + guards: None, body: vec![format!( "return {}", candidate.call_expr.replace("type(self)", "cls") @@ -1565,6 +1579,7 @@ fn generate_python_constructor( DispatchCandidate { legacy_preservation: None, params: candidate.public_params.clone(), + guards: None, body, } }) 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 69605d87..3e1c1c0e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -7,9 +7,9 @@ use super::imports::{emit_type_checking_imports, format_py_type_import}; use super::structs::{generate_struct_helpers, generate_struct_imports}; use super::*; use crate::codegen::winrt::python::collections::{ - CollectionKind, interface_kind, map_iterable_identity, non_null_json_collection, - observable_collection_identity, observable_map_identity, observable_vector_identity, - runtime_mixin, + CollectionInputContract, CollectionKind, interface_kind, map_iterable_identity, + non_null_json_collection, observable_collection_identity, observable_map_identity, + observable_vector_identity, runtime_mixin, }; use crate::codegen::winrt::python::member_plan::{PlannedMember, interface_member_plan}; use crate::meta::CollectionInputRole; @@ -299,7 +299,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe &iface.name, context, super::super::nullability::AnnotationSurface::Runtime, - false, + CollectionInputContract::General, 4, )); out.push_str(&implementation.factory_body); @@ -659,7 +659,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe .iter() .any(|candidate| candidate.name == format!("get_{suffix}")) }), - stock_json_receiver: false, + input_contract: CollectionInputContract::General, }; let members = reorder_getters_before_setters(&iface.methods) .into_iter() diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs index 1704d599..42117751 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs @@ -213,6 +213,11 @@ pub(crate) struct CollectionHelperPlan { pub(crate) setdefault: bool, pub(crate) extend: bool, pub(crate) iadd: bool, + pub(crate) get: bool, + pub(crate) pop: bool, + pub(crate) getitem: bool, + pub(crate) setitem: bool, + pub(crate) delitem: bool, } impl CollectionHelperPlan { @@ -228,6 +233,11 @@ impl CollectionHelperPlan { // Inherited += calls self.extend; do not refine its input contract // when a native member, property or alias owns that operation. iadd: extend && !names.contains("__iadd__"), + get: mapping && !names.contains("get"), + pop: mapping && !names.contains("pop"), + getitem: mapping && !names.contains("__getitem__"), + setitem: mapping && !names.contains("__setitem__"), + delitem: mapping && !names.contains("__delitem__"), } } } @@ -1432,6 +1442,8 @@ mod tests { match name { "update" => helpers.update, "setdefault" => helpers.setdefault, + "get" => helpers.get, + "pop" => helpers.pop, "extend" => helpers.extend, "__iadd__" => helpers.iadd, _ => panic!("unknown collection helper"), @@ -1443,6 +1455,8 @@ mod tests { for (mapping, abi, name) in [ (true, "Update", "update"), (true, "Setdefault", "setdefault"), + (true, "Get", "get"), + (true, "Pop", "pop"), (false, "Extend", "extend"), ] { for owner in [ @@ -1454,7 +1468,10 @@ mod tests { "alias", "static_alias", ] { - let collection = collection_interface(mapping); + let mut collection = collection_interface(mapping); + if mapping { + collection.generic_args[0] = TypeMeta::Object; + } let mut native = method(abi, 6, TypeMeta::I32); let mut methods = Vec::new(); match owner { @@ -1476,8 +1493,9 @@ mod tests { methods.insert(0, native); let native_iface = interface("INative", methods); let class = ClassMeta { - namespace: "Contoso".into(), - name: "NativeCollection".into(), + namespace: "Microsoft.UI.Xaml".into(), + name: "ResourceDictionary".into(), + full_name: "Microsoft.UI.Xaml.ResourceDictionary".into(), default_interface: Some(collection.clone()), required_interfaces: if owner.starts_with("static") { vec![] @@ -1529,13 +1547,15 @@ mod tests { .to_string() }; for code in [ - body(&source, "\nclass NativeCollection("), - body(&stub, "\nclass NativeCollection("), - body(&stub, "\nclass NativeCollectionLike("), + body(&source, "\nclass ResourceDictionary("), + body(&stub, "\nclass ResourceDictionary("), + body(&stub, "\nclass ResourceDictionaryLike("), ] { let helper_signature = match name { "update" => "def update(self, other:", "setdefault" => "def setdefault(self, key:", + "get" => "def get(self, key:", + "pop" => "def pop(self, key:", "extend" => "def extend(self, values:", _ => unreachable!(), }; @@ -2597,14 +2617,8 @@ mod tests { fn windows_corpus_marks_every_new_dispatcher_with_its_old_standalone_method() { use crate::codegen::winrt::python::naming::PythonProjectionContext; use crate::meta; - use std::path::Path; - - const WINMD: &str = - r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; - if !Path::new(WINMD).is_file() { - eprintln!("Skipping: Windows.winmd not found"); - return; - } + let winmd = crate::test_metadata::windows_winmd(); + let winmd = winmd.as_str(); fn assert_scope(interfaces: &[&InterfaceMeta], plan: &ScopePlan<'_>) -> (usize, usize) { let methods = interfaces @@ -2653,21 +2667,21 @@ mod tests { (count, bool_shadows) } - let namespaces = meta::list_namespaces(WINMD); + let namespaces = meta::list_namespaces(winmd); let mut identities = BTreeSet::new(); for namespace in &namespaces { identities.extend( - meta::parse_enums(WINMD, namespace) + meta::parse_enums(winmd, namespace) .into_iter() .map(|typ| typ.type_identity()), ); identities.extend( - meta::parse_interfaces(WINMD, namespace) + meta::parse_interfaces(winmd, namespace) .into_iter() .map(|interface| interface.type_identity()), ); identities.extend( - meta::parse_namespace(WINMD, namespace) + meta::parse_namespace(winmd, namespace) .into_iter() .map(|class| { crate::types::TypeIdentity::named( @@ -2685,7 +2699,7 @@ mod tests { let mut compatibility_fallbacks = BTreeSet::new(); let mut interface_fallbacks = BTreeSet::new(); for namespace in namespaces { - for class in meta::parse_namespace(WINMD, &namespace) { + for class in meta::parse_namespace(winmd, &namespace) { let statics = class .factory_interfaces .iter() @@ -2720,7 +2734,7 @@ mod tests { bool_shadows += count.1; } } - for interface in meta::parse_interfaces(WINMD, &namespace) { + for interface in meta::parse_interfaces(winmd, &namespace) { if !interface.is_delegate() { let interface_plan = interface_member_plan(&interface, &context); interface_fallbacks.extend( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs index 44b8fa98..538bde97 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs @@ -9,7 +9,7 @@ use crate::codegen::winrt::shared::imports::{ fill_array_output_index, fill_array_uses_retval_count, get_in_params, }; -use super::collections::non_null_json_input; +use super::collections::{CollectionInputContract, non_null_json_input}; use super::delegates::{ py_delegate_input_arg, py_event_handler_arg, py_once_callback_check, py_runtime_delegate_callable_type, py_runtime_delegate_param_type, @@ -20,7 +20,7 @@ use super::nullability::AnnotationSurface; use super::signature::{ LegacyPreservationPredicate, py_convert_return, py_has_permissive_guard, py_interface_cast_guard, py_type_guard, py_wrap_arg, py_wrap_async, - py_wrap_async_with_converters, py_wrap_collection_input, + py_wrap_async_with_converters, py_wrap_collection_input_for_receiver, }; use super::type_helpers::{ method_pydoc, py_factory_return_type, py_method_abi_output_count, py_method_outputs, @@ -62,6 +62,7 @@ fn py_build_method_args_expr( method: &MethodMeta, context: &PythonProjectionContext, receiver: Option<&str>, + input_contract: CollectionInputContract, ) -> String { method .params @@ -80,7 +81,9 @@ fn py_build_method_args_expr( .iter() .find_map(|(parameter, role)| (*parameter == index).then_some(*role)); let wrapped = match role { - Some(role) => py_wrap_collection_input(&name, ¶m.typ, role, context), + Some(role) => { + py_wrap_collection_input_for_receiver(&name, ¶m.typ, role, context, input_contract) + } None => py_wrap_method_arg(&name, ¶m.typ, context), }; if let (Some(receiver), Some(role)) = (receiver, role) @@ -147,6 +150,7 @@ pub(crate) struct DispatchCandidate<'a> { pub(crate) legacy_preservation: Option<&'a LegacyPreservation>, /// Python-visible input parameters, in call order. pub(crate) params: Vec<&'a crate::meta::ParamMeta>, + pub(crate) guards: Option>, /// Statements run when the candidate matches, relative to its `if` block. pub(crate) body: Vec, } @@ -175,12 +179,16 @@ pub(crate) fn emit_dispatch( let guards = candidates .iter() .map(|candidate| { - candidate - .params - .iter() - .enumerate() - .map(|(index, param)| param_guard(&format!("_bound[{index}]"), ¶m.typ, context)) - .collect::>() + candidate.guards.clone().unwrap_or_else(|| { + candidate + .params + .iter() + .enumerate() + .map(|(index, param)| { + param_guard(&format!("_bound[{index}]"), ¶m.typ, context) + }) + .collect() + }) }) .collect::>(); let needs_legacy_bound = candidates.iter().any(|candidate| { @@ -461,7 +469,8 @@ fn generate_factory_method_invoke_named( } out.push_str(&method_pydoc(method, &in_params)); - let args_expr = py_build_method_args_expr(method, context, None); + let args_expr = + py_build_method_args_expr(method, context, None, CollectionInputContract::General); let iface_symbol = context.reference_name(&iface.type_identity()); let call_expr = method_call_expr( &context.registration_symbol(iface), @@ -561,7 +570,8 @@ fn generate_static_method_invoke_named( )); } out.push_str(&method_pydoc(method, &in_params)); - let args_expr = py_build_method_args_expr(method, context, None); + let args_expr = + py_build_method_args_expr(method, context, None, CollectionInputContract::General); let call_expr = method_call_expr( &context.registration_symbol(iface), method, @@ -580,7 +590,7 @@ pub(crate) struct InstanceOverload<'a> { pub(crate) method: &'a MethodMeta, pub(crate) sibling_methods: Option<&'a [MethodMeta]>, pub(crate) property_has_getter: bool, - pub(crate) stock_json_receiver: bool, + pub(crate) input_contract: CollectionInputContract, } /// Render an instance accessor (property or event method). @@ -596,7 +606,7 @@ pub(crate) fn generate_instance_accessor( None, overload.sibling_methods, overload.property_has_getter, - overload.stock_json_receiver, + overload.input_contract, ) } @@ -630,7 +640,7 @@ pub(crate) fn generate_instance_method_group<'a>( Some(attribute), overload.sibling_methods, overload.property_has_getter, - overload.stock_json_receiver, + overload.input_contract, )); } if overloads.len() == 1 { @@ -650,10 +660,42 @@ pub(crate) fn generate_instance_method_group<'a>( let candidates = overloads .iter() .zip(&group.candidates) - .map(|((overload, attribute, _), candidate)| DispatchCandidate { - legacy_preservation: candidate.legacy_preservation.as_ref(), - params: get_in_params(overload.method), - body: vec![format!("return self.{attribute}(*_bound)")], + .map(|((overload, attribute, _), candidate)| { + let guards = overload + .method + .params + .iter() + .enumerate() + .filter(|(_, param)| { + matches!( + param.direction, + crate::meta::ParamDirection::In | crate::meta::ParamDirection::OutFill + ) + }) + .enumerate() + .map(|(input_index, (index, param))| { + let name = format!("_bound[{input_index}]"); + let mut guard = param_guard(&name, ¶m.typ, context); + if overload + .method + .collection_inputs + .iter() + .any(|(parameter, role)| { + *parameter == index + && overload.input_contract.string_key(¶m.typ, *role) + }) + { + guard.strict = format!("(isinstance({name}, str) or {})", guard.strict); + } + guard + }) + .collect(); + DispatchCandidate { + legacy_preservation: candidate.legacy_preservation.as_ref(), + params: get_in_params(overload.method), + guards: Some(guards), + body: vec![format!("return self.{attribute}(*_bound)")], + } }) .collect::>(); let legacy = group @@ -765,6 +807,7 @@ pub(crate) fn generate_static_method_group<'a>( .map(|((overload, attribute, _), candidate)| DispatchCandidate { legacy_preservation: candidate.legacy_preservation.as_ref(), params: get_in_params(overload.method), + guards: None, body: vec![format!( "return {}.{attribute}(*_bound)", context.class_name(overload.class) @@ -800,7 +843,7 @@ pub(crate) fn generate_method_body( name_override: Option<&str>, sibling_methods: Option<&[MethodMeta]>, property_has_getter: bool, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { let in_params = get_in_params(method); let return_type = method.return_type.as_ref(); @@ -955,8 +998,7 @@ pub(crate) fn generate_method_body( iface_var, method.vtable_index, obj_expr, arg )); } else { - let py_params = - py_runtime_method_param_list_for_receiver(method, context, stock_json_receiver); + let py_params = py_runtime_method_param_list_for_receiver(method, context, input_contract); let py_return = py_method_return_type(method, AnnotationSurface::Runtime, context); let method_name = name_override .map(|s| s.to_string()) @@ -973,7 +1015,7 @@ pub(crate) fn generate_method_body( )); out.push_str(&method_pydoc(method, &in_params)); - let args_expr = py_build_method_args_expr(method, context, Some(obj_expr)); + let args_expr = py_build_method_args_expr(method, context, Some(obj_expr), input_contract); let call_expr = method_call_expr(iface_var, method, obj_expr, &args_expr, context); emit_method_result(&mut out, &call_expr, method, context); } @@ -1043,7 +1085,7 @@ mod tests { method: candidate.method, sibling_methods: None, property_has_getter: true, - stock_json_receiver: false, + input_contract: CollectionInputContract::General, }, context, ) @@ -1053,6 +1095,32 @@ mod tests { instance_group_on(&[("IReader", methods)], context) } + #[test] + fn resource_key_contract_reaches_native_overload_groups_without_replacing_lookup() { + let mut class = crate::meta::parse_class( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + "Windows.UI.Xaml", + "ResourceDictionary", + ) + .expect("stock ResourceDictionary metadata"); + let native = overloaded_method("Lookup2", 6, TypeMeta::I32); + class + .required_interfaces + .push(interface("INative", &[&native])); + let source = super::super::generator::generate_class( + &PythonProjectionContext::default(), + &class, + &Default::default(), + ); + assert_eq!(source.matches("def lookup(").count(), 1, "{source}"); + assert!(source.contains("isinstance(_bound[0], str) or"), "{source}"); + assert!(source.contains("\n lookup2 = lookup\n"), "{source}"); + assert!( + source.contains("_dynwinrt_property_type.String"), + "{source}" + ); + } + /// Plan `methods` as the statics of `class_name` and render the first method group. fn static_group( class_name: &str, @@ -1123,7 +1191,7 @@ mod tests { method: candidate.method, sibling_methods: None, property_has_getter: true, - stock_json_receiver: false, + input_contract: CollectionInputContract::General, }, &PythonProjectionContext::default(), ); @@ -1249,7 +1317,7 @@ mod tests { None, None, true, - false, + CollectionInputContract::General, ); assert!(code.contains("def load_async(self) -> WinRTCoroutine[int]:")); @@ -1285,7 +1353,7 @@ mod tests { None, None, true, - false, + CollectionInputContract::General, ); assert!(code.contains( @@ -1451,7 +1519,7 @@ print(Runner().run(DynWinRtDelegate())) None, Some(&siblings), true, - false, + CollectionInputContract::General, ); assert!(code.contains("def on_changed(self, callback:")); @@ -1503,7 +1571,7 @@ print(Runner().run(DynWinRtDelegate())) None, Some(std::slice::from_ref(&add)), true, - false, + CollectionInputContract::General, ); assert!(code.contains("'routed_event_handler', 'IID_RoutedEventHandler'")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index de7a0eb2..dbcd86ac 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -20,8 +20,11 @@ pub(crate) enum PythonSupportSymbol { ObjectInput, MappingInput, MappingKey, + MappingDefault, AsInterface, CollectionItem, + BoxObject, + PropertyType, CanCast, LegacyCall, LegacyIntGuard, @@ -33,8 +36,11 @@ impl PythonSupportSymbol { Self::ObjectInput => "_DynWinRTObject", Self::MappingInput => "_SupportsKeysAndGetItem", Self::MappingKey => "_MapUpdateKeyT", + Self::MappingDefault => "_MapDefaultT", Self::AsInterface => "_dynwinrt_as_interface", Self::CollectionItem => "_dynwinrt_collection_item", + Self::BoxObject => "_dynwinrt_to_winrt_object", + Self::PropertyType => "_dynwinrt_property_type", Self::CanCast => "_dynwinrt_can_cast", Self::LegacyCall => "_dynwinrt_legacy_call", Self::LegacyIntGuard => "_dynwinrt_legacy_int_guard", @@ -1009,8 +1015,11 @@ impl PythonProjectionContext { PythonSupportSymbol::ObjectInput, PythonSupportSymbol::MappingInput, PythonSupportSymbol::MappingKey, + PythonSupportSymbol::MappingDefault, PythonSupportSymbol::AsInterface, PythonSupportSymbol::CollectionItem, + PythonSupportSymbol::BoxObject, + PythonSupportSymbol::PropertyType, PythonSupportSymbol::CanCast, PythonSupportSymbol::LegacyCall, PythonSupportSymbol::LegacyIntGuard, @@ -1595,8 +1604,11 @@ mod tests { PythonSupportSymbol::ObjectInput, PythonSupportSymbol::MappingInput, PythonSupportSymbol::MappingKey, + PythonSupportSymbol::MappingDefault, PythonSupportSymbol::AsInterface, PythonSupportSymbol::CollectionItem, + PythonSupportSymbol::BoxObject, + PythonSupportSymbol::PropertyType, PythonSupportSymbol::CanCast, PythonSupportSymbol::LegacyCall, PythonSupportSymbol::LegacyIntGuard, @@ -1671,6 +1683,13 @@ mod tests { assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::CollectionItem); } + #[test] + fn resource_key_helpers_yield_to_visible_roles() { + assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::BoxObject); + assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::PropertyType); + assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::MappingDefault); + } + #[test] fn overload_helpers_yield_to_visible_roles_without_renaming_metadata() { for helper in [ diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs index fd44ca91..af499043 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs @@ -1084,6 +1084,25 @@ pub(crate) fn py_wrap_collection_input( py_wrap_collection_item(name, typ, role, context) } +pub(crate) fn py_wrap_collection_input_for_receiver( + name: &str, + typ: &TypeMeta, + role: CollectionInputRole, + context: &PythonProjectionContext, + input_contract: super::collections::CollectionInputContract, +) -> String { + if input_contract.string_key(typ, role) { + let key = format!( + "{}(str.__str__({name}), {}.String) if isinstance({name}, str) else {name}", + context.support_symbol_reference(PythonSupportSymbol::BoxObject), + context.support_symbol_reference(PythonSupportSymbol::PropertyType), + ); + py_wrap_collection_input(&format!("({key})"), typ, role, context) + } else { + py_wrap_collection_input(name, typ, role, context) + } +} + fn py_wrap_collection( name: &str, typ: &TypeMeta, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs index 5f9d7190..0c56b865 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs @@ -7,6 +7,7 @@ use crate::codegen::winrt::shared::imports::get_in_params; use crate::meta::{CollectionInputRole, MethodMeta}; use crate::types::{FieldMeta, TypeMeta}; +use super::collections::CollectionInputContract; use super::delegates::{py_delegate_callable_type, py_delegate_param_type}; use super::naming::{PythonProjectionContext, PythonSymbol, STRUCT_SYMBOLS, to_snake_case}; use super::native_types::{FoundationType, foundation_type}; @@ -186,7 +187,7 @@ pub(super) fn emit_method_stub( event_has_remove: bool, property_has_getter: bool, overrides_mutable_sequence: bool, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { emit_method_stub_named( method, @@ -196,7 +197,7 @@ pub(super) fn emit_method_stub( event_has_remove, property_has_getter, overrides_mutable_sequence, - stock_json_receiver, + input_contract, ) } @@ -218,7 +219,7 @@ pub(super) fn emit_method_stub_named( event_has_remove: bool, property_has_getter: bool, overrides_mutable_sequence: bool, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { let indent = " ".repeat(indent_spaces); let in_params = get_in_params(method); @@ -328,8 +329,12 @@ pub(super) fn emit_method_stub_named( ); } } else { - let py_params = py_method_param_list_for_receiver(method, context, stock_json_receiver); - let py_return = match (stock_json_receiver, method.raw_name.as_str(), return_type) { + let py_params = py_method_param_list_for_receiver(method, context, input_contract); + let py_return = match ( + input_contract.is_non_null_json(), + method.raw_name.as_str(), + return_type, + ) { (true, "GetAt", Some(typ)) if super::collections::non_null_json_input(CollectionInputRole::Element, typ) .is_some() => @@ -358,7 +363,7 @@ pub(super) fn emit_method_stub_named( // them. Empty structural protocols can make mypy consider the // override compatible. let override_ignore = if overrides_mutable_sequence - && !stock_json_receiver + && !input_contract.is_non_null_json() && method_name == "append" && in_params.first().is_some_and(|param| { py_param_type_safe(¶m.typ, context) @@ -482,7 +487,7 @@ mod tests { true, true, false, - false, + CollectionInputContract::General, ); assert!(code.contains("def on_changed(")); assert!(code.contains("-> 'DynWinRTValue': ...")); @@ -499,7 +504,7 @@ mod tests { false, true, false, - false, + CollectionInputContract::General, ); assert!(code.contains("def on_changed(")); assert!(!code.contains("subscribe_changed")); @@ -532,7 +537,7 @@ mod tests { false, true, true, - false, + CollectionInputContract::General, ); let scalar = emit_method_stub( &append(TypeMeta::I32), @@ -541,7 +546,7 @@ mod tests { false, true, true, - false, + CollectionInputContract::General, ); assert!(reference.contains("type: ignore[override, unused-ignore]")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 2ae32543..0b130200 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -25,8 +25,8 @@ use crate::codegen::winrt::shared::structs::{ }; use super::collections::{ - CollectionKind, class_interface, interface_kind, observable_vector_identity, - projected_interface_kind, stock_json_class_contract, + CollectionInputContract, CollectionKind, class_interface, interface_kind, + observable_vector_identity, projected_interface_kind, }; use super::member_plan::{ ClassMemberPlan, CollectionHelperPlan, MethodGroup, PlannedMember, ScopePlan, @@ -500,7 +500,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf &plan.collection_helpers, context, 4, - false, + CollectionInputContract::General, )); if has_projection { out.push('\n'); @@ -607,7 +607,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf event_has_remove, property_has_getter, collection_kind == Some(CollectionKind::MutableSequence), - false, + CollectionInputContract::General, ) } PlannedMember::Group(group) => emit_instance_stub_group( @@ -615,7 +615,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf context, 4, collection_kind == Some(CollectionKind::MutableSequence), - false, + CollectionInputContract::General, ), }); } @@ -624,7 +624,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf context, 4, collection_kind == Some(CollectionKind::MutableSequence), - false, + CollectionInputContract::General, )); out @@ -641,7 +641,7 @@ pub fn generate_class_stub<'a>( let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); - let stock_json_receiver = stock_json_class_contract(class).is_some(); + let input_contract = CollectionInputContract::for_class(class); let known_full_names = context.known_full_names(); let winui_bootstrap = winui::resolve_application_bootstrap(class, &known_full_names); let has_public_composition = class @@ -835,6 +835,11 @@ pub fn generate_class_stub<'a>( )); } out.push('\n'); + out.push_str(&super::collections::protocol_helper_typevars( + &plan.instance.collection_helpers, + context, + input_contract, + )); if supports_interface_projection { out.push_str("_InterfaceT = TypeVar('_InterfaceT')\n\n"); } @@ -868,7 +873,7 @@ pub fn generate_class_stub<'a>( AnnotationSurface::Stub, context, ); - if stock_json_receiver { + if input_contract.is_non_null_json() { match (kind, iface.generic_args.as_slice()) { (CollectionKind::MutableSequence, [value]) => Some(format!( "MutableSequence[{}]", @@ -890,7 +895,7 @@ pub fn generate_class_stub<'a>( context, &plan.instance, collection_iface, - stock_json_receiver, + input_contract, false, has_closable, ); @@ -966,7 +971,7 @@ pub fn generate_class_stub<'a>( context, &plan.instance, collection_iface, - stock_json_receiver, + input_contract, collection_kind == Some(CollectionKind::MutableSequence), has_closable, )); @@ -1096,7 +1101,7 @@ pub fn generate_class_stub<'a>( &iface_plan.collection_helpers, context, 4, - false, + CollectionInputContract::General, )); out.push('\n'); out.push_str(" @classmethod\n"); @@ -1131,7 +1136,7 @@ pub fn generate_class_stub<'a>( event_has_remove, property_has_getter, interface_kind(req_iface) == Some(CollectionKind::MutableSequence), - false, + CollectionInputContract::General, ) } PlannedMember::Group(group) => emit_instance_stub_group( @@ -1139,7 +1144,7 @@ pub fn generate_class_stub<'a>( context, 4, interface_kind(req_iface) == Some(CollectionKind::MutableSequence), - false, + CollectionInputContract::General, ), }); } @@ -1148,7 +1153,7 @@ pub fn generate_class_stub<'a>( context, 4, interface_kind(req_iface) == Some(CollectionKind::MutableSequence), - false, + CollectionInputContract::General, )); } @@ -1161,7 +1166,7 @@ fn emit_class_instance_stubs<'a>( context: &PythonProjectionContext, plan: &ScopePlan<'a>, collection_iface: Option<&InterfaceMeta>, - stock_json_receiver: bool, + input_contract: CollectionInputContract, mutable_sequence_override: bool, has_closable: bool, ) -> String { @@ -1175,7 +1180,7 @@ fn emit_class_instance_stubs<'a>( &plan.collection_helpers, context, 4, - stock_json_receiver, + input_contract, )); } @@ -1262,7 +1267,7 @@ fn emit_class_instance_stubs<'a>( event_has_remove, property_has_getter, mutable_sequence_override, - stock_json_receiver, + input_contract, ) } PlannedMember::Group(group) => emit_instance_stub_group( @@ -1270,7 +1275,7 @@ fn emit_class_instance_stubs<'a>( context, 4, mutable_sequence_override, - stock_json_receiver, + input_contract, ), }); } @@ -1279,7 +1284,7 @@ fn emit_class_instance_stubs<'a>( context, 4, mutable_sequence_override, - stock_json_receiver, + input_contract, )); if has_closable { out.push('\n'); @@ -1330,7 +1335,7 @@ fn collection_protocol_stubs( helpers: &CollectionHelperPlan, context: &PythonProjectionContext, indent_spaces: usize, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { let Some(kind) = projected_interface_kind(iface) else { return String::new(); @@ -1342,7 +1347,9 @@ fn collection_protocol_stubs( .generic_args .first() .map(|typ| { - if stock_json_receiver && kind == super::collections::CollectionKind::MutableSequence { + if input_contract.is_non_null_json() + && kind == super::collections::CollectionKind::MutableSequence + { super::type_helpers::py_param_type_safe(typ, context) } else if matches!( kind, @@ -1364,8 +1371,15 @@ fn collection_protocol_stubs( .generic_args .first() .map(|typ| { - if stock_json_receiver && kind == super::collections::CollectionKind::MutableSequence { + if input_contract.is_non_null_json() + && kind == super::collections::CollectionKind::MutableSequence + { super::type_helpers::py_param_type_safe(typ, context) + } else if matches!( + kind, + CollectionKind::Mapping | CollectionKind::MutableMapping + ) { + input_contract.key_input_type(typ, context) } else { super::type_helpers::py_collection_input_type(typ, context) } @@ -1409,7 +1423,7 @@ fn collection_protocol_stubs( .generic_args .get(1) .map(|typ| { - if stock_json_receiver { + if input_contract.is_non_null_json() { super::type_helpers::py_param_type_safe(typ, context) } else { super::type_helpers::py_collection_item_type( @@ -1432,7 +1446,7 @@ fn collection_protocol_stubs( .generic_args .get(1) .map(|typ| { - if stock_json_receiver { + if input_contract.is_non_null_json() { super::type_helpers::py_param_type_safe(typ, context) } else { super::type_helpers::py_collection_input_type(typ, context) @@ -1454,7 +1468,7 @@ fn collection_protocol_stubs( &iface.name, context, AnnotationSurface::Stub, - stock_json_receiver, + input_contract, indent_spaces, )); result @@ -1639,13 +1653,18 @@ fn typed_signatures<'m>( methods: impl IntoIterator, return_type: impl Fn(&MethodMeta) -> String, context: &PythonProjectionContext, + input_contract: CollectionInputContract, ) -> Vec<(&'m MethodMeta, bool)> { let mut signatures = HashSet::new(); let mut parameter_signatures = HashSet::new(); methods .into_iter() .filter_map(|method| { - let parameters = super::type_helpers::py_method_param_list(method, context); + let parameters = super::type_helpers::py_method_param_list_for_receiver( + method, + context, + input_contract, + ); signatures .insert((parameters.clone(), return_type(method))) .then(|| (method, !parameter_signatures.insert(parameters))) @@ -1677,7 +1696,7 @@ fn emit_instance_stub_group( context: &PythonProjectionContext, indent_spaces: usize, overrides_mutable_sequence: bool, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { let indent = " ".repeat(indent_spaces); let methods = typed_signatures( @@ -1686,6 +1705,7 @@ fn emit_instance_stub_group( super::type_helpers::py_method_return_type(method, AnnotationSurface::Stub, context) }, context, + input_contract, ); let overloaded = methods.len() > 1; methods @@ -1699,7 +1719,7 @@ fn emit_instance_stub_group( false, true, overrides_mutable_sequence, - stock_json_receiver, + input_contract, ); if duplicate { stub = ignore_unreachable_overload(stub); @@ -1718,7 +1738,7 @@ fn emit_instance_compatibility_alias_stubs( context: &PythonProjectionContext, indent_spaces: usize, overrides_mutable_sequence: bool, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { let indent = " ".repeat(indent_spaces); let mut out = String::new(); @@ -1729,6 +1749,7 @@ fn emit_instance_compatibility_alias_stubs( super::type_helpers::py_method_return_type(method, AnnotationSurface::Stub, context) }, context, + input_contract, ); for (method, duplicate) in &methods { if methods.len() > 1 { @@ -1742,7 +1763,7 @@ fn emit_instance_compatibility_alias_stubs( false, true, overrides_mutable_sequence, - stock_json_receiver, + input_contract, ); if *duplicate { stub = ignore_unreachable_overload(stub); @@ -1782,6 +1803,7 @@ fn emit_static_compatibility_alias_stubs( alias.signatures.iter().copied(), |method| static_return_type(class_name, class, method, context), context, + CollectionInputContract::General, ); for (method, duplicate) in &methods { if methods.len() > 1 { @@ -1831,6 +1853,7 @@ fn emit_static_stub_group( group.candidates.iter().map(|candidate| candidate.method), |method| static_return_type(class_name, class, method, context), context, + CollectionInputContract::General, ); let overloaded = methods.len() > 1; methods @@ -2111,6 +2134,7 @@ mod tests { } }, &context, + CollectionInputContract::General, ); assert_eq!( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs index f3693a71..c8d3c977 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -10,7 +10,9 @@ use crate::codegen::winrt::shared::imports::{ use crate::meta::{CollectionInputRole, MethodMeta}; use crate::types::TypeMeta; -use super::collections::{CollectionKind, abc_name, is_mapping_input, type_kind}; +use super::collections::{ + CollectionInputContract, CollectionKind, abc_name, is_mapping_input, type_kind, +}; use super::docs::format_pydoc; use super::naming::to_snake_case; use super::naming::{PythonProjectionContext, PythonSupportSymbol, PythonSymbol}; @@ -755,18 +757,18 @@ pub(super) fn py_method_param_list( method: &MethodMeta, context: &PythonProjectionContext, ) -> String { - py_method_param_list_for_receiver(method, context, false) + py_method_param_list_for_receiver(method, context, CollectionInputContract::General) } fn collection_input_param_type( typ: &TypeMeta, role: Option, context: &PythonProjectionContext, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> Option { match role { Some(role @ (CollectionInputRole::Element | CollectionInputRole::Value)) - if stock_json_receiver + if input_contract.is_non_null_json() && super::collections::non_null_json_input(role, typ).is_some() => { if let TypeMeta::Array(element) = typ { @@ -781,7 +783,7 @@ fn collection_input_param_type( Some(CollectionInputRole::Element | CollectionInputRole::Value) => { Some(py_collection_contract_input_type(typ, context)) } - Some(CollectionInputRole::Key) => Some(py_collection_input_type(typ, context)), + Some(CollectionInputRole::Key) => Some(input_contract.key_input_type(typ, context)), None => None, } } @@ -789,7 +791,7 @@ fn collection_input_param_type( pub(super) fn py_method_param_list_for_receiver( method: &MethodMeta, context: &PythonProjectionContext, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { method .params @@ -806,15 +808,14 @@ pub(super) fn py_method_param_list_for_receiver( .collection_inputs .iter() .find_map(|(parameter, role)| (*parameter == index).then_some(*role)); - let param_type = - collection_input_param_type(¶m.typ, role, context, stock_json_receiver) - .unwrap_or_else(|| { - if context.is_delegate_type(¶m.typ) { - super::delegates::py_delegate_param_type(¶m.typ, context) - } else { - py_param_type_safe(¶m.typ, context) - } - }); + let param_type = collection_input_param_type(¶m.typ, role, context, input_contract) + .unwrap_or_else(|| { + if context.is_delegate_type(¶m.typ) { + super::delegates::py_delegate_param_type(¶m.typ, context) + } else { + py_param_type_safe(¶m.typ, context) + } + }); format!("{}: {}", to_snake_case(¶m.name), param_type) }) .collect::>() @@ -827,13 +828,13 @@ pub(super) fn py_runtime_method_param_list( method: &MethodMeta, context: &PythonProjectionContext, ) -> String { - py_runtime_method_param_list_for_receiver(method, context, false) + py_runtime_method_param_list_for_receiver(method, context, CollectionInputContract::General) } pub(super) fn py_runtime_method_param_list_for_receiver( method: &MethodMeta, context: &PythonProjectionContext, - stock_json_receiver: bool, + input_contract: CollectionInputContract, ) -> String { method .params @@ -850,15 +851,14 @@ pub(super) fn py_runtime_method_param_list_for_receiver( .collection_inputs .iter() .find_map(|(parameter, role)| (*parameter == index).then_some(*role)); - let param_type = - collection_input_param_type(¶m.typ, role, context, stock_json_receiver) - .unwrap_or_else(|| { - if context.is_delegate_type(¶m.typ) { - super::delegates::py_runtime_delegate_param_type().to_string() - } else { - py_param_type_safe(¶m.typ, context) - } - }); + let param_type = collection_input_param_type(¶m.typ, role, context, input_contract) + .unwrap_or_else(|| { + if context.is_delegate_type(¶m.typ) { + super::delegates::py_runtime_delegate_param_type().to_string() + } else { + py_param_type_safe(¶m.typ, context) + } + }); format!("{}: {}", to_snake_case(¶m.name), param_type) }) .collect::>() diff --git a/tools/dynwinrt-codegen/src/documented_nulls.rs b/tools/dynwinrt-codegen/src/documented_nulls.rs index 45b04d3d..9193ad66 100644 --- a/tools/dynwinrt-codegen/src/documented_nulls.rs +++ b/tools/dynwinrt-codegen/src/documented_nulls.rs @@ -401,18 +401,15 @@ mod tests { /// typos and drift, and the key derivation against metadata changes. #[test] fn every_entry_resolves_to_a_flagged_windows_sdk_member() { - // Documented, but absent from the 10.0.26100 SDK metadata: newer APIs, + // Documented, but absent from the pinned 10.0.26100.8249 metadata: newer APIs, // and AllJoyn, which the SDK dropped. const ABSENT_FROM_TEST_SDK: [&str; 3] = [ "M:Windows.Devices.AllJoyn.AllJoynServiceInfo.FromIdAsync(System.String)", "M:Windows.Gaming.UI.GameMonitor.GetDefault()", "M:Windows.System.User.GetUserAgeRangeAsync()", ]; - if !Path::new(WINDOWS_WINMD).is_file() { - eprintln!("Skipping: Windows.winmd not found"); - return; - } - let index = crate::meta::load_index(WINDOWS_WINMD).expect("Windows.winmd index"); + let winmd = crate::test_metadata::windows_winmd(); + let index = crate::meta::load_index(&winmd).expect("Windows.winmd index"); let mut by_owner = BTreeMap::>::new(); for entry in entries() { let id = normalize_api_id(entry); diff --git a/tools/dynwinrt-codegen/src/lib.rs b/tools/dynwinrt-codegen/src/lib.rs index 09db795e..fe8f9d2e 100644 --- a/tools/dynwinrt-codegen/src/lib.rs +++ b/tools/dynwinrt-codegen/src/lib.rs @@ -7,6 +7,8 @@ pub mod com_metadata; mod contract_registry; mod documented_nulls; pub mod meta; +#[cfg(test)] +mod test_metadata; pub mod types; mod win32_contracts; pub mod win32_metadata; diff --git a/tools/dynwinrt-codegen/src/meta.rs b/tools/dynwinrt-codegen/src/meta.rs index c3cc6e47..de961832 100644 --- a/tools/dynwinrt-codegen/src/meta.rs +++ b/tools/dynwinrt-codegen/src/meta.rs @@ -361,6 +361,8 @@ pub struct ClassMeta { pub full_name: String, /// Direct WinRT runtime-class base, excluding System.Object. pub base_class: Option, + /// Resolved WinMD ancestor classes, nearest first, excluding System.Object. + pub ancestor_classes: Vec, pub default_interface: Option, /// Supplemental interfaces, including parameterized and versioned interfaces. pub required_interfaces: Vec, @@ -1520,6 +1522,7 @@ fn parse_class_from_index(index: &reader::Index, namespace: &str, name: &str) -> .map(|e| (e.namespace().to_string(), e.name().to_string())); // The documentation lists inherited members under the class declaring them. let mut documentation_owners = vec![full_name.clone()]; + let mut ancestor_classes = Vec::new(); while let Some((ext_ns, ext_name)) = ancestor_key.take() { if ext_ns == "System" && ext_name == "Object" { break; @@ -1528,6 +1531,11 @@ fn parse_class_from_index(index: &reader::Index, namespace: &str, name: &str) -> Some(d) => d, None => break, }; + ancestor_classes.push(TypeRef { + namespace: ext_ns.clone(), + name: ext_name.clone(), + kind: TypeKind::Class, + }); documentation_owners.push(format!("{ext_ns}.{ext_name}")); for iface_impl in parent_def.interface_impls() { let iface_ty = iface_impl.interface(&[]); @@ -1693,6 +1701,7 @@ fn parse_class_from_index(index: &reader::Index, namespace: &str, name: &str) -> namespace: namespace.to_string(), full_name, base_class, + ancestor_classes, default_interface, required_interfaces, overridable_interfaces, diff --git a/tools/dynwinrt-codegen/src/test_metadata.rs b/tools/dynwinrt-codegen/src/test_metadata.rs new file mode 100644 index 00000000..f26a84f4 --- /dev/null +++ b/tools/dynwinrt-codegen/src/test_metadata.rs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Fixed metadata input for Windows SDK corpus assertions, not runtime discovery. + +use std::path::PathBuf; + +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Corpus { + package: String, + version: String, + relative_path: String, + sha256: String, +} + +pub(crate) fn windows_winmd() -> String { + let corpus: Corpus = serde_json::from_str(include_str!("../tests/windows_sdk_corpus.json")) + .expect("valid Windows SDK corpus descriptor"); + let path = std::env::var_os("DYNWINRT_WINDOWS_WINMD") + .map(PathBuf::from) + .unwrap_or_else(|| { + PathBuf::from( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ) + }); + let instructions = format!( + "Windows corpus tests require {} {} ({}). \ + Run eng\\ci\\restore-windows-metadata.ps1 -OutputDirectory \ + and set DYNWINRT_WINDOWS_WINMD to its returned path; \ + a rolling SDK installation is not a pinned corpus.", + corpus.package, corpus.version, corpus.relative_path, + ); + let bytes = std::fs::read(&path) + .unwrap_or_else(|error| panic!("Cannot read {}: {error}. {instructions}", path.display())); + assert_eq!( + format!("{:x}", Sha256::digest(&bytes)), + corpus.sha256, + "Unexpected Windows metadata content at {}. {instructions}", + path.display() + ); + path.to_str() + .expect("Windows metadata path must be Unicode") + .into() +} diff --git a/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs b/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs index b7924c4c..e9c15cb8 100644 --- a/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs +++ b/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs @@ -21,6 +21,17 @@ fn sdk_color_palette_resources_projects_inherited_generic_map_interfaces() { } let class = parse_class(WINDOWS_WINMD, "Windows.UI.Xaml", "ColorPaletteResources").unwrap(); + assert_eq!( + class + .ancestor_classes + .iter() + .map(|ancestor| (ancestor.namespace.as_str(), ancestor.name.as_str())) + .collect::>(), + [ + ("Windows.UI.Xaml", "ResourceDictionary"), + ("Windows.UI.Xaml", "DependencyObject"), + ] + ); let map = class .required_interfaces .iter() @@ -66,4 +77,9 @@ fn sdk_color_palette_resources_projects_inherited_generic_map_interfaces() { && py.contains("def insert("), "{py}" ); + assert!(py.contains("def lookup(self, key: str |"), "{py}"); + assert!( + py.contains("_dynwinrt_to_winrt_object(str.__str__(key), _dynwinrt_property_type.String)"), + "{py}" + ); } diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index 0cf86fdf..9e32ff12 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -11,6 +11,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; +use windows_metadata::{MethodCallAttributes, Signature, Type, TypeAttributes, TypeName, writer}; static NEXT: AtomicU64 = AtomicU64::new(0); @@ -85,9 +86,21 @@ fn has_implementation_runtime() -> bool { } fn typecheck(fixture: &Fixture, packages: &[&str], consumer: &str, errors: &[&str]) { + typecheck_with_imports(fixture, packages, consumer, errors, "normal"); +} + +fn typecheck_with_imports( + fixture: &Fixture, + packages: &[&str], + consumer: &str, + errors: &[&str], + follow_imports: &str, +) { fs::write(fixture.0.join("consumer.py"), consumer).unwrap(); let installed = std::env::var("DYNWINRT_TEST_INSTALLED_RUNTIME").as_deref() == Ok("1"); - for source_stubs in if installed { + for source_stubs in if installed && follow_imports == "silent" { + &[false][..] + } else if installed { &[true, false][..] } else { &[true][..] @@ -100,7 +113,8 @@ fn typecheck(fixture: &Fixture, packages: &[&str], consumer: &str, errors: &[&st "mypy", "--strict", "--no-incremental", - "--follow-imports=normal", + "--follow-imports", + follow_imports, "--no-pretty", "--show-error-codes", "--cache-dir", @@ -994,6 +1008,464 @@ print("subclass-factory-native-ok", flush=True) } } +#[test] +fn resource_dictionary_keys_are_scoped_and_typed_in_stubs_and_inline_sources() { + let winmd = Path::new( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ); + assert!( + winmd.is_file(), + "ResourceDictionary fixtures require Windows.winmd" + ); + if !has_mypy() { + return; + } + let runtime = has_implementation_runtime(); + let fixture = Fixture::new(); + let metadata = fixture.0.join("ResourceKeys.winmd"); + let mut file = writer::File::new("ResourceKeys"); + let object = file.TypeRef("System", "Object"); + let default = file.TypeRef("Windows.Foundation.Metadata", "DefaultAttribute"); + let default_constructor = file.MemberRef( + ".ctor", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types: vec![], + }, + writer::MemberRefParent::TypeRef(default), + ); + for namespace in ["Microsoft.UI.Xaml", "Contoso"] { + let class = file.TypeDef( + namespace, + "ResourceDictionary", + writer::TypeDefOrRef::TypeRef(object), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + let implementation = file.InterfaceImpl( + class, + &Type::Name(TypeName { + namespace: "Windows.Foundation.Collections".into(), + name: "IMap`2".into(), + generics: vec![Type::Object, Type::Object], + }), + ); + file.Attribute( + writer::HasAttribute::InterfaceImpl(implementation), + writer::AttributeType::MemberRef(default_constructor), + &[], + ); + } + for (name, base_namespace, base_name) in [ + ( + "DerivedResources", + "Microsoft.UI.Xaml", + "ResourceDictionary", + ), + ("GrandchildResources", "Contoso", "DerivedResources"), + ("UnrelatedResources", "Contoso", "ResourceDictionary"), + ] { + let base = file.TypeRef(base_namespace, base_name); + let class = file.TypeDef( + "Contoso", + name, + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::WindowsRuntime, + ); + let implementation = + file.InterfaceImpl(class, &Type::named("Windows.Foundation", "IStringable")); + file.Attribute( + writer::HasAttribute::InterfaceImpl(implementation), + writer::AttributeType::MemberRef(default_constructor), + &[], + ); + } + fs::write(&metadata, file.into_stream()).unwrap(); + + let consumer = r#"from enum import Enum, StrEnum +from typing import assert_type +from dynwinrt import DynWinRTValue +from views.microsoft__ui__xaml__resource_dictionary import ResourceDictionary +from views.windows__ui__xaml__resource_dictionary import ResourceDictionary as UwpResourceDictionary +from views.windows__ui__xaml__color_palette_resources import ColorPaletteResources +from views.contoso__derived_resources import DerivedResources +from views.contoso__grandchild_resources import GrandchildResources + +class ResourceKey(StrEnum): + STYLE = "AccentButtonStyle" + +class LegacyResourceKey(str, Enum): + STYLE = "AccentButtonStyle" + +class Carrier: + def __init__(self, value: DynWinRTValue) -> None: + self._obj = value + +def keys(resources: ResourceDictionary, raw: DynWinRTValue, carrier: Carrier) -> None: + assert_type(resources.lookup("AccentButtonStyle"), DynWinRTValue | None) + assert_type(resources["AccentButtonStyle"], DynWinRTValue | None) + assert_type(resources.get("AccentButtonStyle"), DynWinRTValue | None) + assert_type(resources.get("absent", 17), DynWinRTValue | int | None) + assert_type(resources.get(key="absent", default=17), DynWinRTValue | int | None) + assert_type(resources.has_key("AccentButtonStyle"), bool) + assert_type(resources.insert("new", carrier), bool) + resources["new"] = raw + resources.update({"new": raw}, other=carrier) + resources.update([("new", carrier)]) + assert_type(resources.setdefault("new", carrier), DynWinRTValue | None) + assert_type(resources.pop("new"), DynWinRTValue | None) + assert_type(resources.pop("absent", 17), DynWinRTValue | int | None) + resources.remove("new") + del resources["new"] + for key in (raw, carrier, None): + assert_type(resources.lookup(key), DynWinRTValue | None) + assert_type(resources[key], DynWinRTValue | None) + +def stock_contract(resources: UwpResourceDictionary) -> None: + assert_type(resources.lookup("style"), DynWinRTValue | None) + assert_type(resources["style"], DynWinRTValue | None) + assert_type(resources.get("style"), DynWinRTValue | None) + +def inherited_keys( + resources: DerivedResources | GrandchildResources | ColorPaletteResources, raw: DynWinRTValue +) -> None: + assert_type(resources.lookup("style"), DynWinRTValue | None) + assert_type(resources["style"], DynWinRTValue | None) + assert_type(resources.get("absent", 17), DynWinRTValue | int | None) + assert_type(resources.pop(raw, 17), DynWinRTValue | int | None) + assert_type(resources.has_key("style"), bool) + assert_type(resources.insert("style", raw), bool) + resources.update({"style": raw}) + resources["style"] = raw + resources.remove("style") + del resources["style"] + +def raw_key_defaults(resources: ResourceDictionary, raw: DynWinRTValue) -> None: + assert_type(resources.get(raw, 17), DynWinRTValue | int | None) + assert_type(resources.pop(raw, 17), DynWinRTValue | int | None) + +def string_enum_keys(resources: ResourceDictionary | UwpResourceDictionary, raw: DynWinRTValue) -> None: + for key in (ResourceKey.STYLE, LegacyResourceKey.STYLE): + assert_type(resources.lookup(key), DynWinRTValue | None) + assert_type(resources[key], DynWinRTValue | None) + assert_type(resources.get(key), DynWinRTValue | None) + assert_type(resources.get(key, 17), DynWinRTValue | int | None) + assert_type(resources.has_key(key), bool) + assert_type(resources.insert(key, raw), bool) + resources[key] = raw + resources.update({key: raw}) + resources.update([(key, raw)]) + assert_type(resources.setdefault(key, raw), DynWinRTValue | None) + assert_type(resources.pop(key), DynWinRTValue | None) + resources.remove(key) + del resources[key] +"#; + let like_consumer = r#" +from collections.abc import Iterator +from views.microsoft__ui__xaml__resource_dictionary import ResourceDictionaryLike +from views.windows__ui__xaml__resource_dictionary import ResourceDictionaryLike as UwpResourceDictionaryLike + +class PythonChild(ResourceDictionary): + pass + +def base_contracts( + direct: DerivedResources, indirect: GrandchildResources, + palette: ColorPaletteResources, python_child: PythonChild +) -> None: + base: ResourceDictionaryLike = direct + base = indirect + base = python_child + assert_type(base.lookup("style"), DynWinRTValue | None) + uwp_base: UwpResourceDictionaryLike = palette + assert_type(uwp_base.lookup("style"), DynWinRTValue | None) + +def like_keys(resources: ResourceDictionaryLike, concrete: ResourceDictionary) -> None: + resources = concrete + assert_type(resources.lookup("style"), DynWinRTValue | None) + assert_type(resources["style"], DynWinRTValue | None) + assert_type(resources.get("style"), DynWinRTValue | None) + assert_type(resources.pop("absent", 17), DynWinRTValue | int | None) + assert_type(resources.__iter__(), Iterator[DynWinRTValue | None]) + assert_type(iter(concrete), Iterator[DynWinRTValue | None]) +"#; + let invalid = r#"from dynwinrt import DynWinRTValue +from views.microsoft__ui__xaml__resource_dictionary import ResourceDictionary +from views.contoso__resource_dictionary import ResourceDictionary as Unrelated +from views.contoso__unrelated_resources import UnrelatedResources +from views.windows__foundation__collections__i_map_object_object import IMap_Object_Object +from views.__MAP_VIEW_MODULE__ import IMapView_Object_Object + +def invalid(resources: ResourceDictionary, other: Unrelated, mapping: IMap_Object_Object, + view: IMapView_Object_Object, raw: DynWinRTValue, unrelated_child: UnrelatedResources) -> None: + resources.lookup(17) + resources[17] + resources.insert("style", "not an Object value") + resources.update(style=17) + other.lookup("style") + mapping.lookup("style") + view.lookup("style") + unrelated_child.lookup("style") +"#; + let invalid = invalid.replace( + "__MAP_VIEW_MODULE__", + &common::python_module(TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IMapView", + [ + TypeMeta::Object.type_identity(), + TypeMeta::Object.type_identity(), + ], + )), + ); + for no_pyi in [false, true] { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(format!("{};{}", metadata.display(), winmd.display())) + .args([ + "--class-name", + "Microsoft.UI.Xaml.ResourceDictionary,Contoso.ResourceDictionary,Windows.UI.Xaml.ResourceDictionary,\ + Contoso.DerivedResources,Contoso.GrandchildResources,Contoso.UnrelatedResources,Windows.UI.Xaml.ColorPaletteResources", + "--lang", + "py", + "--output", + ]) + .arg(fixture.0.join("views")); + if no_pyi { + command.arg("--no-pyi"); + } + let output = command.output().unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + let source = fs::read_to_string( + fixture + .0 + .join("views") + .join("microsoft__ui__xaml__resource_dictionary.py"), + ) + .unwrap(); + assert_eq!(source.matches("def lookup(").count(), 1); + assert!(source.contains("_dynwinrt_to_winrt_object(str.__str__(key), _dynwinrt_property_type.String) if isinstance(key, str) else key")); + for module in [ + "contoso__derived_resources", + "contoso__grandchild_resources", + "windows__ui__xaml__color_palette_resources", + ] { + let derived = + fs::read_to_string(fixture.0.join("views").join(format!("{module}.py"))).unwrap(); + assert!(derived.contains("def lookup(self, key: str |")); + assert!(derived.contains( + "_dynwinrt_to_winrt_object(str.__str__(key), _dynwinrt_property_type.String)" + )); + assert!(derived.contains(".invoke(self._collection_obj,")); + } + let other = fs::read_to_string( + fixture + .0 + .join("views") + .join("contoso__resource_dictionary.py"), + ) + .unwrap(); + assert!(!other.contains("to_winrt_object")); + let unrelated_child = fs::read_to_string( + fixture + .0 + .join("views") + .join("contoso__unrelated_resources.py"), + ) + .unwrap(); + assert!(!unrelated_child.contains("to_winrt_object")); + typecheck_with_imports( + &fixture, + if no_pyi { &[] } else { &["views"] }, + &format!("{consumer}{}", if no_pyi { "" } else { like_consumer }), + &[], + if no_pyi { "silent" } else { "normal" }, + ); + pyright_typecheck( + &fixture, + &format!("{consumer}{}", if no_pyi { "" } else { like_consumer }), + 0, + ); + typecheck_with_imports( + &fixture, + &[], + &invalid, + &[ + "[arg-type]", + "[index]", + "[arg-type]", + "[call-overload]", + "[arg-type]", + "[arg-type]", + "[arg-type]", + "[arg-type]", + ], + if no_pyi { "silent" } else { "normal" }, + ); + if runtime { + let output = Command::new(python()) + .args(["-B", "-c", r#" +import ast +from enum import Enum, StrEnum +from pathlib import Path +from types import SimpleNamespace +from typing import get_overloads, get_type_hints, get_args +import threading +from dynwinrt import ( + DynWinRTArray, DynWinRTImplementation, DynWinRTImplementationMethod, + DynWinRTInterfacePlan, DynWinRTMethodSig, DynWinRTType, DynWinRTValue, RoApartment, WinGUID, + projected_lifetime_scope, to_winrt_object, unbox_object, +) +from dynwinrt.values import Char16 +from views.microsoft__ui__xaml__resource_dictionary import ResourceDictionary +from views.contoso__resource_dictionary import ResourceDictionary as Unrelated +from views.windows.foundation.collections import IMap_Object_Object + +class ResourceKey(StrEnum): + STYLE = "enum resource" + +class LegacyResourceKey(str, Enum): + STYLE = "legacy enum resource" + +class DisplayKey(str): + def __str__(self): + return "not the stored key" + +source = ast.parse((Path("views") / "microsoft__ui__xaml__resource_dictionary.py").read_text(encoding="utf-8")) +owner = next(node for node in source.body if isinstance(node, ast.ClassDef) and node.name == "ResourceDictionary") +assert sum(isinstance(node, ast.FunctionDef) and node.name == "lookup" for node in owner.body) == 1 +for method in (ResourceDictionary.get, ResourceDictionary.pop): + overloads = get_overloads(method) + assert len(overloads) == 2 + hints = get_type_hints(overloads[1]) + assert hints["default"].__name__.startswith("_MapDefaultT") + assert hints["default"] in get_args(hints["return"]) +with RoApartment(1), projected_lifetime_scope(): + key = to_winrt_object("raw key") + value = to_winrt_object("raw value") + identities = key.identity_raw(), value.identity_raw() + native = DynWinRTValue.create_map([key], [value], DynWinRTType.object(), DynWinRTType.object()) + assert native._try_query_interface(WinGUID.parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")) + resources = ResourceDictionary._from_native(native.cast(WinGUID.parse("00000000-0000-0000-c000-000000000046"))) + carrier = SimpleNamespace(_obj=key) + for source_key in (key, carrier): + assert resources.lookup(source_key).identity_raw() == identities[1] + assert resources[source_key].identity_raw() == identities[1] + assert resources.get(source_key).identity_raw() == identities[1] + assert resources.has_key(source_key) + assert resources.insert("boxed by projection", value) is False + assert {unbox_object(item) for item in resources} == {"raw key", "boxed by projection"} + assert resources.has_key("raw key") + assert resources.lookup("raw key").identity_raw() == identities[1] + fallback = object() + assert resources.get("absent", fallback) is fallback + assert resources.pop("absent", default=fallback) is fallback + for string_key in (ResourceKey.STYLE, LegacyResourceKey.STYLE, DisplayKey("stored key"), Char16("x")): + assert resources.insert(string_key, value) is False + assert resources.insert(string_key, value) is True + assert resources.has_key(string_key) and string_key in resources + assert resources.lookup(string_key).identity_raw() == identities[1] + assert resources.lookup(str.__str__(string_key)).identity_raw() == identities[1] + assert resources[string_key].identity_raw() == identities[1] + assert resources.get(string_key).identity_raw() == identities[1] + assert str.__str__(string_key) in {unbox_object(item) for item in resources} + resources.remove(string_key) + assert not resources.has_key(string_key) + resources[string_key] = value + assert resources.setdefault(string_key, None).identity_raw() == identities[1] + del resources[string_key] + resources.update({string_key: value}) + assert resources.pop(string_key).identity_raw() == identities[1] + resources.update([(string_key, value)]) + del resources[string_key] + assert resources.setdefault(string_key, value).identity_raw() == identities[1] + assert resources.pop(string_key).identity_raw() == identities[1] + assert resources.get(string_key, fallback) is fallback + assert resources.pop(string_key, default=fallback) is fallback + try: + resources[string_key] + except KeyError as error: + assert error.args == (string_key,) + else: + raise AssertionError("missing string subclass key was accepted") + for mapping in (IMap_Object_Object.from_value(native), Unrelated._from_native(native.cast(WinGUID.parse("00000000-0000-0000-c000-000000000046")))): + for string_key in ("raw key", ResourceKey.STYLE, LegacyResourceKey.STYLE): + try: + mapping.lookup(string_key) + except TypeError as error: + assert "DynWinRTValue" in str(error), error + else: + raise AssertionError("unrelated Object-key map auto-boxed a string") + generic = IMap_Object_Object.from_value(native) + for invalid in (17, DynWinRTValue.from_i32(17), SimpleNamespace(_obj="not native")): + errors = [] + for projection in (generic, resources): + try: + projection.lookup(invalid) + except (TypeError, OSError) as error: + if isinstance(error, OSError): + assert error.winerror == -2147024809, error + errors.append((type(error), str(error))) + else: + raise AssertionError("invalid Object input reached native dispatch") + assert errors[0] == errors[1], errors + assert (key.identity_raw(), value.identity_raw()) == identities + assert not native.is_released() + released = to_winrt_object("released") + released.release() + for source_key in (released, SimpleNamespace(_obj=released)): + try: + resources.lookup(source_key) + except RuntimeError as error: + assert "released" in str(error), error + else: + raise AssertionError("released key reached native dispatch") + iid = WinGUID.parse("96369f54-8eb6-48f0-abce-c1b211e627c3") + signature = DynWinRTMethodSig().add_out(DynWinRTType.hstring()) + interface = DynWinRTType.register_interface("Windows.Foundation.IStringable", iid).add_method("ToString", signature) + plan = DynWinRTInterfacePlan.create("Windows.Foundation.IStringable", interface, [ + DynWinRTImplementationMethod("ToString", 6, signature) + ]) + calls = [] + def callback(*args): + calls.append(args) + return [DynWinRTValue.from_hstring("live")] + owner = DynWinRTImplementation.create([plan], callback) + source = owner.to_value() + array = DynWinRTArray.from_object_values([source], DynWinRTType.object()) + guarded = array.get(0) + assert not guarded._try_query_interface(WinGUID.parse("94ea2b94-e9cc-49e0-c0ff-ee64ca8f5b90")) + failures = [] + def foreign(): + try: + with RoApartment(1): + for source_key in (guarded, SimpleNamespace(_obj=guarded)): + try: + resources.lookup(source_key) + except RuntimeError as error: + assert "owning COM apartment thread" in str(error), error + else: + raise AssertionError("non-agile key reached native dispatch") + except BaseException as error: + failures.append(error) + thread = threading.Thread(target=foreign) + thread.start() + thread.join(10) + assert not thread.is_alive() and not failures, failures + assert not calls and not guarded.is_released() and not source.is_released() + owner.release() +print("resource-key-fixture-ok") +"#]) + .current_dir(&fixture.0) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + assert!(String::from_utf8_lossy(&output.stdout).contains("resource-key-fixture-ok")); + } + } +} + #[test] fn collection_subscripts_accept_projected_inputs_and_keep_raw_outputs() { let winmd = Path::new( diff --git a/tools/dynwinrt-codegen/tests/windows_sdk_corpus.json b/tools/dynwinrt-codegen/tests/windows_sdk_corpus.json new file mode 100644 index 00000000..b03e287c --- /dev/null +++ b/tools/dynwinrt-codegen/tests/windows_sdk_corpus.json @@ -0,0 +1,6 @@ +{ + "package": "Microsoft.Windows.SDK.CPP", + "version": "10.0.26100.8249", + "relative_path": "c/UnionMetadata/10.0.26100.0/Windows.winmd", + "sha256": "11191cbcc796e520d47547b3f986be94a48556fe336d4e63334596d9f31a7806" +}