From 7f275f82dd6104ec7ff0fcc6a77f4b1bb5d5b32a Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sun, 20 Sep 2026 12:04:17 +0800 Subject: [PATCH 1/5] Fix Python consumer instance and input typing Separate interface instance protocols from wrapper factories, model native Object inputs without widening outputs, and use Self for context-manager covariance. Add strict same-package, independent-package, SDK, and native lifetime regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- bindings/py/dynwinrt.pyi | 4 +- tools/dynwinrt-codegen/python/README.md | 18 +- .../src/codegen/winrt/python/generator/mod.rs | 7 +- .../src/codegen/winrt/python/method.rs | 2 +- .../src/codegen/winrt/python/shared.rs | 7 + .../src/codegen/winrt/python/stubs.rs | 84 ++- .../src/codegen/winrt/python/type_helpers.rs | 43 +- .../tests/composable_factory_test.rs | 4 +- .../tests/ibuffer_projection_test.rs | 2 +- .../tests/python_consumer_typing_test.rs | 561 ++++++++++++++++++ .../python_context_manager_typing_test.rs | 1 + .../tests/python_inheritance_typing_test.rs | 3 +- .../snapshots/data_writer_py/data_writer.py | 2 +- ...i_iterator_i_www_form_url_decoder_entry.py | 2 +- .../tests/snapshots/uri_py/i_stringable.py | 2 +- ...ntime_class_with_absolute_canonical_uri.py | 2 +- .../uri_py/i_www_form_url_decoder_entry.py | 2 +- .../tests/snapshots/uri_py/uri.py | 2 +- .../snapshots/uri_py/www_form_url_decoder.py | 2 +- ..._iterator_i_www_form_url_decoder_entry.pyi | 4 +- .../tests/snapshots/uri_pyi/i_stringable.pyi | 9 +- ...time_class_with_absolute_canonical_uri.pyi | 9 +- .../uri_pyi/i_www_form_url_decoder_entry.pyi | 9 +- .../tests/snapshots/uri_pyi/uri.pyi | 8 +- .../uri_pyi/www_form_url_decoder.pyi | 10 +- 25 files changed, 738 insertions(+), 61 deletions(-) create mode 100644 tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs diff --git a/bindings/py/dynwinrt.pyi b/bindings/py/dynwinrt.pyi index 72fcbc8b..6acc0133 100644 --- a/bindings/py/dynwinrt.pyi +++ b/bindings/py/dynwinrt.pyi @@ -11,8 +11,8 @@ _Handlers_contra = TypeVar("_Handlers_contra", contravariant=True) class _DynWinRTProjector(Protocol[_Projected_co]): - @classmethod - def from_value(cls, obj: "DynWinRTValue") -> _Projected_co: ... + # Models the factory object, whose from_value method is already bound. + def from_value(self, obj: "DynWinRTValue") -> _Projected_co: ... class _DynWinRTProjectableClass: ... diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md index d2980131..143188d3 100644 --- a/tools/dynwinrt-codegen/python/README.md +++ b/tools/dynwinrt-codegen/python/README.md @@ -128,9 +128,25 @@ implement standard `collections.abc` protocols, flags use `enum.IntFlag`, and compatible method inputs accept native Python sequences, mappings, `bytes`, `bytearray`, `uuid.UUID`, `datetime.datetime`, and `datetime.timedelta`. +Interface protocols describe native **instances**, including their canonical +identity and methods, not wrapper factories. For example, `StorageFile` can be +passed to an `IStorageFile` parameter without defining `from_value`. +`IStorageFile.from_value(raw)` and `value.as_interface(IStorageFile)` remain +available for explicit, IID-checked projection. + +WinRT `Object` inputs accept a `DynWinRTValue` or a projected native wrapper +whose `_obj` is a `DynWinRTValue`, including interface views and runtime-class +`Like` views. They do not implicitly box arbitrary Python objects, strings, or +`None`; use an explicitly boxed or null `DynWinRTValue` instead. `Object` +outputs remain `DynWinRTValue | None`. Context managers retain the entered +instance's type (`Self`), including derived wrappers passed through a base +`Like` protocol, and still close the object without suppressing exceptions. + The output directory belongs to codegen; do not store handwritten files in it. After changing metadata files, SDK versions, or reference inputs, regenerate the -complete output. +complete output. Regenerate with the updated generator to pick up these +consumer typing contracts, and use the matching runtime package and its stubs. +No runtime API change or consumer cast is required. ### Closed-generic stub migration diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs index 32b69f8e..10171b3a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -45,7 +45,7 @@ from ._runtime import ( TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, @@ -64,7 +64,7 @@ from collections.abc import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, ) from datetime import datetime, timedelta -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Protocol from uuid import UUID from weakref import ref as _weakref_ref from dynwinrt import ( @@ -127,7 +127,8 @@ def _dynwinrt_can_cast(value, iid): pub fn generate_runtime_support_module() -> String { format!( - "{HEADER}{FUTURE_ANNOTATIONS}{RUNTIME_SUPPORT_BODY}{}", + "{HEADER}{FUTURE_ANNOTATIONS}{RUNTIME_SUPPORT_BODY}{}{}", + super::shared::NATIVE_OBJECT_PROTOCOL, super::implementation::HELPERS ) } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs index 08c617b6..3cb9aea5 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs @@ -1078,7 +1078,7 @@ mod tests { ); assert!(code.contains( - "def write_async(self, buffer: 'DynWinRTValue') -> WinRTCoroutineWithProgress[int, int]:" + "def write_async(self, buffer: 'DynWinRTValue | _DynWinRTObject') -> WinRTCoroutineWithProgress[int, int]:" )); assert!(code.contains("return _dynwinrt_track_projected(_DynWinRTAsyncWithProgress(")); assert!(code.contains("'WinRTAsyncWithProgress')")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs index b562a1e8..ac2f973b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs @@ -6,6 +6,13 @@ use crate::meta::MethodMeta; +pub(super) const NATIVE_OBJECT_PROTOCOL: &str = " + +class _DynWinRTObject(Protocol): + @property + def _obj(self) -> DynWinRTValue: ... +"; + /// Reorder methods so that property getters always come before their matching setters. /// Python requires `@property` to appear before `@prop.setter`. pub(crate) fn reorder_getters_before_setters(methods: &[MethodMeta]) -> Vec<&MethodMeta> { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 673c63c0..d02dab78 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -46,8 +46,11 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, )\n"; +const NATIVE_OBJECT_STUB: &str = "\ + \x20 @builtins.property\n\ + \x20 def _obj(self) -> DynWinRTValue: ...\n"; const ASYNC_IMPORT_LINE: &str = "from dynwinrt import WinRTCoroutine, WinRTCoroutineWithProgress\n"; pub fn generate_typing_support_module() -> String { @@ -59,7 +62,7 @@ from collections.abc import (\n\ MutableSequence as MutableSequence, Sequence as Sequence,\n\ )\n\ from datetime import datetime as datetime, timedelta as timedelta\n\ -from typing import overload as overload\n\ +from typing import Protocol, overload as overload\n\ from uuid import UUID as UUID\n\ from dynwinrt import (\n\ DynWinRTType as DynWinRTType, DynWinRTValue as DynWinRTValue,\n\ @@ -68,7 +71,8 @@ from dynwinrt import (\n\ _DynWinRTProjector as _DynWinRTProjector,\n\ _DynWinRTProjectableClass as _DynWinRTProjectableClass,\n\ _DynWinRTRuntimeClass as _DynWinRTRuntimeClass,\n\ -)\n" +)\n{}", + super::shared::NATIVE_OBJECT_PROTOCOL, ) } @@ -252,21 +256,27 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf return out; } let implementation = super::implementation::project(context, iface); + let collection_kind = interface_kind(iface); + let is_protocol = collection_kind.is_none(); + let has_projection = !iface.iid.is_empty() || iface.generic_piid.is_some(); + let has_factory = implementation.supported || (is_protocol && has_projection); + let is_buffer = + crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid); let mut out = String::new(); out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); out.push_str(IMPORT_LINE); + if has_factory { + out.push_str("from abc import ABCMeta\n"); + } if implementation.supported { out.push_str(super::implementation::IMPORTS); - out.push_str("from abc import ABCMeta\n"); out.push_str("from typing import TypeVar\nfrom dynwinrt import _DynWinRTImplementationFactory\n_ImplementationHandlers = TypeVar('_ImplementationHandlers')\n"); if context.is_packaged() { out.push_str("from typing import TypeAlias\nfrom ._implementation_types import _ImplementationPair as _PackageImplementationPair\n"); } } - let collection_kind = interface_kind(iface); - let is_protocol = collection_kind.is_none(); out.push_str("from typing import Protocol, Self, TypeVar\n"); if methods_have_async_output(iface.methods.iter()) { out.push_str(ASYNC_IMPORT_LINE); @@ -402,16 +412,34 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf } out.push_str(&implementation.declarations); - let implementation_metaclass = format!("_{}ImplementationFactory", iface.name); - if implementation.supported { - if context.is_packaged() { + let factory_metaclass = if implementation.supported { + format!("_{}ImplementationFactory", iface.name) + } else { + format!("_{}Factory", iface.name) + }; + if implementation.supported && context.is_packaged() { + out.push_str(&format!( + "\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{handler}], {handler}]\n", + handler = context.implementation_helper_name(iface, "handlers", "Handlers") + )); + } + if has_factory { + out.push_str(&format!("\nclass {factory_metaclass}(ABCMeta):\n")); + if is_protocol && has_projection { out.push_str(&format!( - "\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{handler}], {handler}]\n", - handler = context.implementation_helper_name(iface, "handlers", "Handlers") + " def from_value(cls, obj: DynWinRTValue) -> {}: ...\n", + iface.name )); } - out.push_str(&format!("\nclass {implementation_metaclass}(ABCMeta):\n")); - out.push_str(&implementation.factory_declarations); + if is_buffer { + out.push_str(&format!( + " def from_bytes(cls, data: bytes | bytearray) -> {}: ...\n", + iface.name + )); + } + if implementation.supported { + out.push_str(&implementation.factory_declarations); + } } let collection_base = @@ -443,8 +471,8 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf } let mut seen_bases = HashSet::new(); bases.retain(|base| seen_bases.insert(base.clone())); - if implementation.supported { - bases.push(format!("metaclass={implementation_metaclass}")); + if has_factory { + bases.push(format!("metaclass={factory_metaclass}")); } if bases.is_empty() { out.push_str(&format!("\nclass {}:\n", iface.name)); @@ -459,6 +487,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf }, " ", )); + out.push_str(NATIVE_OBJECT_STUB); if !implementation.supported { out.push_str(&implementation.factory_declarations); } @@ -466,20 +495,18 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n"); } out.push_str(&collection_protocol_stubs(iface, context, 4)); - if !iface.iid.is_empty() || iface.generic_piid.is_some() { + if has_projection { out.push('\n'); - out.push_str(" @classmethod\n"); - out.push_str(" def from_value(cls, obj: DynWinRTValue) -> Self: ...\n"); + if !is_protocol { + out.push_str(" @classmethod\n"); + out.push_str(" def from_value(cls, obj: DynWinRTValue) -> Self: ...\n"); + } out.push_str( " def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ...\n", ); } - if crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid) { - out.push_str( - "\n @staticmethod\n\ - \x20 def from_bytes(data: bytes | bytearray) -> 'IBuffer': ...\n\ - \x20 def to_bytes(self) -> bytes: ...\n", - ); + if is_buffer { + out.push_str("\n def to_bytes(self) -> bytes: ...\n"); } // IVector / IMap create() @@ -1045,6 +1072,7 @@ pub fn generate_class_stub( out.push_str(&format!("\nclass {symbol}:\n")); } out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n"); + out.push_str(NATIVE_OBJECT_STUB); out.push_str(&collection_protocol_stubs(req_iface, context, 4)); out.push('\n'); out.push_str(" @classmethod\n"); @@ -1102,6 +1130,9 @@ fn emit_class_instance_stubs( has_closable: bool, ) -> String { let mut out = String::new(); + if super::has_native_projector(class) { + out.push_str(NATIVE_OBJECT_STUB); + } if let Some(collection_iface) = collection_iface { out.push_str(&collection_protocol_stubs(collection_iface, context, 4)); } @@ -1205,10 +1236,7 @@ fn emit_class_instance_stubs( if has_closable { out.push('\n'); out.push_str(" def close(self) -> None: ...\n"); - out.push_str(&format!( - " def __enter__(self) -> '{}': ...\n", - context.class_name(class) - )); + out.push_str(" def __enter__(self) -> Self: ...\n"); out.push_str( " def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> Literal[False]: ...\n", ); 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 3b1c7afa..5c76df4a 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -107,7 +107,8 @@ fn py_param_type(typ: &TypeMeta, context: &PythonProjectionContext) -> String { format!("'{}'", context.reference_name_for_type(typ)) } TypeMeta::Array(inner) => py_array_param_type(inner, context), - TypeMeta::Object | TypeMeta::Delegate { .. } => "'DynWinRTValue'".to_string(), + TypeMeta::Object => "'DynWinRTValue | _DynWinRTObject'".to_string(), + TypeMeta::Delegate { .. } => "'DynWinRTValue'".to_string(), TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(), typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(), typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(), @@ -413,6 +414,7 @@ fn py_array_param_type(inner: &TypeMeta, context: &PythonProjectionContext) -> S fn py_native_param_element_type(inner: &TypeMeta, context: &PythonProjectionContext) -> String { match inner { + TypeMeta::Object => py_param_type(inner, context), TypeMeta::RuntimeClass { name, .. } if context.is_known_type(inner) => { format!( "'{}'", @@ -653,6 +655,45 @@ mod tests { ); } + #[test] + fn object_inputs_accept_native_wrappers_without_widening_outputs() { + let context = PythonProjectionContext::default(); + assert_eq!( + py_param_type_safe(&TypeMeta::Object, &context), + "'DynWinRTValue | _DynWinRTObject'" + ); + assert_eq!( + py_array_param_type(&TypeMeta::Object, &context), + "DynWinRTArray | Sequence['DynWinRTValue | _DynWinRTObject']" + ); + for (name, piid, args, expected) in [ + ( + "IIterable`1", + "faa585ea-6214-4217-afda-7f46de5869b3", + vec![TypeMeta::Object], + "Iterable['DynWinRTValue | _DynWinRTObject']", + ), + ( + "IMap`2", + "3c2925fe-8519-45c1-aa79-197b6718c1c1", + vec![TypeMeta::String, TypeMeta::Object], + "Mapping[str, 'DynWinRTValue | _DynWinRTObject']", + ), + ] { + let typ = TypeMeta::Parameterized { + namespace: "Windows.Foundation.Collections".into(), + name: name.into(), + piid: piid.into(), + args, + }; + assert_eq!(py_param_type_safe(&typ, &context), expected); + } + assert_eq!( + py_return_type_safe(Some(&TypeMeta::Object), &context), + "DynWinRTValue | None" + ); + } + #[test] fn reference_returns_are_annotated_as_nullable() { let runtime_class = TypeMeta::RuntimeClass { diff --git a/tools/dynwinrt-codegen/tests/composable_factory_test.rs b/tools/dynwinrt-codegen/tests/composable_factory_test.rs index ee93c3d4..a6525c85 100644 --- a/tools/dynwinrt-codegen/tests/composable_factory_test.rs +++ b/tools/dynwinrt-codegen/tests/composable_factory_test.rs @@ -161,7 +161,9 @@ fn composable_factory_returns_public_instance() { pyi.contains("def __init__(self) -> None: ..."), "Python composable constructor stub must hide the ABI-only outer argument:\n{pyi}" ); - assert!(pyi.contains("def create_instance(outer: 'DynWinRTValue') -> 'Widget': ...")); + assert!(pyi.contains( + "def create_instance(outer: 'DynWinRTValue | _DynWinRTObject') -> 'Widget': ..." + )); assert!(pyi.contains( "native overrides are registered during construction; unsupported ABI shapes fail closed" )); diff --git a/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs b/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs index ddc377d9..dcd93c99 100644 --- a/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs +++ b/tools/dynwinrt-codegen/tests/ibuffer_projection_test.rs @@ -92,7 +92,7 @@ fn python_projects_copied_ibuffer_conversions() { ); assert!(implementation.contains("def from_bytes(data: bytes | bytearray) -> 'IBuffer':")); assert!(implementation.contains("return IBuffer._from_native(DynWinRTValue.from_bytes(data))")); - assert!(stub.contains("def from_bytes(data: bytes | bytearray) -> 'IBuffer': ...")); + assert!(stub.contains("def from_bytes(cls, data: bytes | bytearray) -> IBuffer: ...")); assert!(stub.contains("def to_bytes(self) -> bytes: ...")); } diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs new file mode 100644 index 00000000..fe74e5e8 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -0,0 +1,561 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +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}; + +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .parent() + .unwrap() + .join("target") + .join(format!( + "pc{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +fn python() -> PathBuf { + std::env::var_os("DYNWINRT_TEST_PYTHON") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("python")) +} + +fn diagnostics(output: &Output) -> String { + format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +fn has_mypy() -> bool { + let available = Command::new(python()) + .args(["-m", "mypy", "--version"]) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + available || std::env::var("DYNWINRT_REQUIRE_MYPY").as_deref() != Ok("1"), + "DYNWINRT_REQUIRE_MYPY=1 but mypy is unavailable", + ); + if !available { + eprintln!("Skipping consumer checks: mypy unavailable; set DYNWINRT_TEST_PYTHON."); + } + available +} + +fn typecheck(fixture: &Fixture, packages: &[&str], consumer: &str, errors: &[&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 { + &[true, false][..] + } else { + &[true][..] + } { + let mut command = Command::new(python()); + command + .args([ + "-B", + "-m", + "mypy", + "--strict", + "--no-incremental", + "--follow-imports=normal", + "--no-pretty", + "--show-error-codes", + "--cache-dir", + ".mypy_cache", + ]) + .args(packages) + .arg("consumer.py") + .current_dir(&fixture.0); + if *source_stubs { + command.env( + "MYPYPATH", + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .join("bindings") + .join("py"), + ); + } else { + command.env_remove("MYPYPATH"); + } + let output = command.output().unwrap(); + let text = diagnostics(&output); + if errors.is_empty() { + assert!(output.status.success(), "{text}"); + } else { + assert_eq!(output.status.code(), Some(1), "{text}"); + let actual = text + .lines() + .filter(|line| line.contains(": error:")) + .collect::>(); + assert_eq!(actual.len(), errors.len(), "{text}"); + for (line, code) in actual.iter().zip(errors) { + assert!(line.starts_with("consumer.py:"), "{text}"); + assert!(line.ends_with(code), "{text}"); + } + } + } +} + +fn parameter(typ: TypeMeta) -> ParamMeta { + ParamMeta { + name: "value".into(), + typ, + direction: ParamDirection::In, + } +} + +fn interface(name: &str, id: u32, methods: Vec) -> InterfaceMeta { + InterfaceMeta { + namespace: "Contoso".into(), + name: name.into(), + iid: format!("{id:08x}-1111-1111-1111-111111111111"), + methods, + ..Default::default() + } +} + +fn class(name: &str, interface: InterfaceMeta) -> ClassMeta { + ClassMeta { + namespace: "Contoso".into(), + name: name.into(), + full_name: format!("Contoso.{name}"), + default_interface: Some(interface), + is_referenced_as_value: true, + ..Default::default() + } +} + +fn generate_fixture(fixture: &Fixture, package: &str) { + let named = vec![MethodMeta { + name: "get_Name".into(), + vtable_index: 6, + is_property_getter: true, + return_type: Some(TypeMeta::String), + ..Default::default() + }]; + let item = interface("IItem", 1, named.clone()); + let unrelated = interface("IUnrelated", 2, named); + let closable = InterfaceMeta { + namespace: "Windows.Foundation".into(), + name: "IClosable".into(), + iid: "30d5a829-7fa4-4026-83bb-d75bae4ea99e".into(), + methods: vec![MethodMeta { + name: "Close".into(), + vtable_index: 6, + ..Default::default() + }], + ..Default::default() + }; + let mut resource = class("Resource", item.clone()); + resource.required_interfaces.push(closable.clone()); + let mut derived = class("DerivedResource", item.clone()); + derived.required_interfaces.push(closable.clone()); + derived.base_class = Some(TypeRef { + namespace: "Contoso".into(), + name: "Resource".into(), + kind: TypeKind::Class, + }); + let content = interface( + "IContent", + 3, + vec![ + MethodMeta { + name: "get_Content".into(), + vtable_index: 6, + is_property_getter: true, + return_type: Some(TypeMeta::Object), + ..Default::default() + }, + MethodMeta { + name: "put_Content".into(), + vtable_index: 7, + is_property_setter: true, + params: vec![parameter(TypeMeta::Object)], + ..Default::default() + }, + MethodMeta { + name: "SetObject".into(), + vtable_index: 8, + params: vec![parameter(TypeMeta::Object)], + ..Default::default() + }, + MethodMeta { + name: "SetObjects".into(), + vtable_index: 9, + params: vec![parameter(TypeMeta::Array(Box::new(TypeMeta::Object)))], + ..Default::default() + }, + ], + ); + let classes = [ + resource, + derived, + class("Unrelated", unrelated.clone()), + class("Content", content.clone()), + ]; + let interfaces = [item, unrelated, closable, content]; + let identities = classes + .iter() + .map(|class| TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name)) + .chain(interfaces.iter().map(InterfaceMeta::type_identity)); + let context = python::PythonProjectionContext::new(identities, true).unwrap(); + let directory = fixture.0.join(package); + fs::create_dir_all(&directory).unwrap(); + fs::write(directory.join("__init__.py"), "").unwrap(); + fs::write(directory.join("__init__.pyi"), "").unwrap(); + fs::write( + directory.join("_runtime.py"), + python::generate_runtime_support_module(), + ) + .unwrap(); + fs::write( + directory.join("_runtime.pyi"), + python_stub::generate_runtime_support_stub(), + ) + .unwrap(); + fs::write( + directory.join("_typing.pyi"), + python_stub::generate_typing_support_module(), + ) + .unwrap(); + fs::write( + directory.join("_implementation_types.pyi"), + python_stub::generate_implementation_pair_types(&[]), + ) + .unwrap(); + let shared = interfaces.iter().map(|iface| iface.iid.clone()).collect(); + for iface in interfaces { + let module = context.implementation_module(&iface.type_identity()); + fs::write( + directory.join(format!("{module}.py")), + python::generate_interface(&context, &iface), + ) + .unwrap(); + fs::write( + directory.join(format!("{module}.pyi")), + python_stub::generate_interface_stub(&context, &iface), + ) + .unwrap(); + } + for class in classes { + let identity = TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name); + let module = context.implementation_module(&identity); + fs::write( + directory.join(format!("{module}.py")), + python::generate_class(&context, &class, &shared), + ) + .unwrap(); + fs::write( + directory.join(format!("{module}.pyi")), + python_stub::generate_class_stub(&context, &class, &shared), + ) + .unwrap(); + } +} + +#[test] +fn strict_consumers_separate_instances_factories_and_native_object_inputs() { + if !has_mypy() { + return; + } + let fixture = Fixture::new(); + generate_fixture(&fixture, "first"); + generate_fixture(&fixture, "second"); + typecheck( + &fixture, + &["first", "second"], + r#"from typing import assert_type +from dynwinrt import DynWinRTValue, _DynWinRTProjector +from first.contoso__i_item import IItem +from first.contoso__resource import Resource, ResourceLike +from first.contoso__derived_resource import DerivedResource +from first.contoso__content import Content +from second.contoso__i_item import IItem as OtherItem +from second.contoso__derived_resource import DerivedResource as OtherDerived + +def use_item(value: IItem) -> str: + return value.name + +def use_base(value: ResourceLike) -> str: + with value as entered: + assert_type(entered, ResourceLike) + return entered.name + +def valid(raw: DynWinRTValue, resource: Resource, derived: DerivedResource, + other: OtherDerived, item: OtherItem, content: Content) -> None: + use_item(resource) + use_item(derived) + use_item(other) + use_item(item) + use_base(derived) + use_base(other) + with derived as entered: + assert_type(entered, DerivedResource) + projector: _DynWinRTProjector[IItem] = IItem + assert_type(projector.from_value(raw), IItem) + assert_type(IItem.from_value(raw), IItem) + assert_type(resource.as_interface(IItem), IItem) + assert_type(resource.as_interface(OtherItem), OtherItem) + assert_type(content.content, DynWinRTValue | None) + content.content = resource + content.content = other + content.content = item + content.content = raw + content.set_object(derived) + content.set_objects([resource, other, item, raw]) +"#, + &[], + ); + typecheck( + &fixture, + &["first", "second"], + r#"from dynwinrt import DynWinRTValue +from first.contoso__i_item import IItem +from first.contoso__i_unrelated import IUnrelated +from first.contoso__resource import Resource, ResourceLike +from first.contoso__unrelated import Unrelated +from first.contoso__content import Content +from second.contoso__unrelated import Unrelated as OtherUnrelated + +class WrongObject: + _obj: int = 42 + +def use_item(value: IItem) -> None: + pass + +def use_base(value: ResourceLike) -> None: + pass + +def invalid(raw: DynWinRTValue, resource: Resource, unrelated: Unrelated, + other: OtherUnrelated, interface: IUnrelated, content: Content) -> None: + use_item(unrelated) + use_item(other) + use_item(interface) + use_base(unrelated) + resource.as_interface(Resource) + content.content = object() + content.content = "not boxed" + content.content = None + content.content = Resource + content.set_object(WrongObject()) + content.set_objects([42]) +"#, + &[ + "[arg-type]", + "[arg-type]", + "[arg-type]", + "[arg-type]", + "[arg-type]", + "[assignment]", + "[assignment]", + "[assignment]", + "[assignment]", + "[arg-type]", + "[list-item]", + ], + ); +} + +#[test] +fn real_windows_consumers_accept_file_stream_content_and_composition_instances() { + let winmd = Path::new( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ); + if !winmd.is_file() || !has_mypy() { + eprintln!("Skipping SDK consumers: Windows.winmd or mypy unavailable."); + return; + } + let fixture = Fixture::new(); + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd"]) + .arg(winmd) + .args([ + "--class-name", + "Windows.Storage.FileIO,Windows.Storage.StorageFile,\ + Windows.Media.Playback.MediaPlayer,Windows.Media.SpeechSynthesis.SpeechSynthesisStream,\ + Windows.UI.Xaml.Controls.Button,Windows.UI.Xaml.Controls.TextBlock,\ + Windows.UI.Composition.ExpressionAnimation,Windows.UI.Composition.ContainerVisual", + "--lang", + "py", + "--output", + ]) + .arg(fixture.0.join("sdk")) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + typecheck( + &fixture, + &["sdk"], + r#"from typing import assert_type +from dynwinrt import DynWinRTValue +from sdk.windows.storage import FileIO, StorageFile +from sdk.windows.media.playback import MediaPlayer +from sdk.windows.media.speech_synthesis import SpeechSynthesisStream +from sdk.windows.storage.streams import Buffer, IBuffer +from sdk.windows.ui.xaml.controls import Button, TextBlock +from sdk.windows.ui.composition import ContainerVisual, ExpressionAnimation + +async def file_io(file: StorageFile) -> str: + await FileIO.write_text_async(file, "hello") + await FileIO.append_text_async(file, " world") + return await FileIO.read_text_async(file) + +def stream_source(player: MediaPlayer, stream: SpeechSynthesisStream) -> None: + player.set_stream_source(stream) + +def buffer_view(buffer: Buffer, data: bytes) -> IBuffer: + assert_type(IBuffer.from_bytes(data), IBuffer) + assert_type(buffer.as_interface(IBuffer), IBuffer) + return buffer + +def content(button: Button, text: TextBlock) -> None: + assert_type(button.content, DynWinRTValue | None) + button.content = text + +def reference(animation: ExpressionAnimation, visual: ContainerVisual) -> None: + animation.set_reference_parameter("target", visual) + with visual as entered: + assert_type(entered, ContainerVisual) +"#, + &[], + ); +} + +#[test] +fn native_object_inputs_keep_projection_factories_and_context_lifetimes() { + let available = Command::new(python()) + .args(["-c", "from dynwinrt import DynWinRTImplementationHandle"]) + .output() + .is_ok_and(|output| output.status.success()); + if !available { + assert_ne!( + std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref(), + Ok("1"), + "DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME=1 but the matching runtime is unavailable" + ); + eprintln!("Skipping native consumers: set DYNWINRT_TEST_PYTHON to the matching runtime."); + return; + } + let fixture = Fixture::new(); + generate_fixture(&fixture, "views"); + let script = r#"from typing import get_type_hints +from dynwinrt import DynWinRTValue, RoApartment, project_as, projected_lifetime_scope +from views._runtime import _DynWinRTObject +from views.contoso__i_item import IItem +from views.contoso__i_content import IContent +from views.contoso__resource import Resource +from views.contoso__derived_resource import DerivedResource +from views.contoso__content import Content +from views.windows__foundation__i_closable import IClosable + +class ItemHandlers: + closed = 0 + + def get_name(self) -> str: + return "native item" + + def close(self) -> None: + self.closed += 1 + +class ContentHandlers: + def __init__(self) -> None: + self.value: DynWinRTValue | None = None + self.items: list[DynWinRTValue | None] = [] + + def get_content(self) -> DynWinRTValue | None: + return self.value + + def set_content(self, value: DynWinRTValue | None) -> None: + self.value = value + + def set_object(self, value: DynWinRTValue | None) -> None: + self.value = value + + def set_objects(self, value: list[DynWinRTValue | None]) -> None: + self.items = value + +class WrongObject: + _obj = 42 + +assert get_type_hints(Content.set_object)["value"] == DynWinRTValue | _DynWinRTObject +assert get_type_hints(Content.content.fset)["value"] == DynWinRTValue | _DynWinRTObject +assert "value" in get_type_hints(Content.set_objects) +item_handlers = ItemHandlers() +content_handlers = ContentHandlers() +with RoApartment(1), projected_lifetime_scope(): + with IItem.implement(item_handlers, IClosable.implementation(item_handlers)) as item_owner: + with IContent.implement(content_handlers) as content_owner: + resource = project_as(item_owner.value, Resource) + content = project_as(content_owner.value, Content) + interface = resource.as_interface(IItem) + assert interface.name == "native item" + assert IItem.from_value(resource._obj).name == "native item" + with project_as(item_owner.value, DerivedResource) as derived: + assert derived.__enter__() is derived + for value in (resource, derived, interface, resource._obj): + content.content = value + result = content.content + assert isinstance(result, DynWinRTValue) + assert IItem.from_value(result).name == "native item" + content.set_object(value) + assert content_handlers.value is not None + content.set_objects([resource, derived, interface, resource._obj]) + assert len(content_handlers.items) == 4 + assert all(item is not None for item in content_handlers.items) + content.content = DynWinRTValue.null_value() + assert content.content is None + assert item_handlers.closed == 1 + try: + with resource as entered: + assert entered is resource + raise ValueError("not suppressed") + except ValueError as error: + assert str(error) == "not suppressed" + else: + raise AssertionError("__exit__ suppressed an exception") + assert item_handlers.closed == 2 + for invalid in (object(), "not boxed", None, 42, WrongObject()): + try: + content.set_object(invalid) + except TypeError: + pass + else: + raise AssertionError("invalid Object input was accepted") + assert item_owner.take_error() is None + assert content_owner.take_error() is None +"#; + fs::write(fixture.0.join("runtime.py"), script).unwrap(); + let output = Command::new(python()) + .args(["-B", "runtime.py"]) + .current_dir(&fixture.0) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); +} diff --git a/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs b/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs index ee3edda3..0bd163fc 100644 --- a/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs @@ -30,6 +30,7 @@ fn closable_context_manager_never_suppresses_exceptions() { ); assert!(stub.contains("from typing import Literal"), "{stub}"); + assert!(stub.contains("def __enter__(self) -> Self: ..."), "{stub}"); assert!( stub.contains( "def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> Literal[False]: ..." diff --git a/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs b/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs index 1f7e2e9b..bdf317d0 100644 --- a/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs @@ -73,7 +73,8 @@ fn stubs_model_runtime_class_and_interface_bases_without_runtime_inheritance() { "{interface_stub}" ); assert!( - interface_stub.contains("class IDerived(_IDerivedIdentity, Protocol):"), + interface_stub + .contains("class IDerived(_IDerivedIdentity, Protocol, metaclass=_IDerivedFactory):"), "{interface_stub}" ); diff --git a/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py b/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py index 281623ce..42b7b420 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py +++ b/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py index 88b80268..2937caea 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_iterator_i_www_form_url_decoder_entry.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py index 3f0a2977..d1b2576a 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_stringable.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py index 139bd5df..64c0fed9 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_uri_runtime_class_with_absolute_canonical_uri.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py index 9438042b..d255ba1d 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/i_www_form_url_decoder_entry.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/uri.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/uri.py index 779535a1..70d15aa3 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/uri.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/uri.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_py/www_form_url_decoder.py b/tools/dynwinrt-codegen/tests/snapshots/uri_py/www_form_url_decoder.py index 2b079573..f9baae09 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_py/www_form_url_decoder.py +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_py/www_form_url_decoder.py @@ -5,7 +5,7 @@ TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - _property, _weakref_ref, + _DynWinRTObject, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi index da77b1df..ae2e8fc3 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_iterator_i_www_form_url_decoder_entry.pyi @@ -5,7 +5,7 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, ) from typing import Protocol, Self, TypeVar @@ -20,6 +20,8 @@ class _IIterator_IWwwFormUrlDecoderEntryIdentity(Protocol): def _dynwinrt_iid_g2bb0b33cef11eb455ace3197fce2b56f216f6802e23b208c88ebad8f950f8628(self) -> None: ... class IIterator_IWwwFormUrlDecoderEntry(_IIterator_IWwwFormUrlDecoderEntryIdentity, Iterator[IWwwFormUrlDecoderEntry | None]): + @builtins.property + def _obj(self) -> DynWinRTValue: ... # Windows.Foundation.Collections.IIterator_IWwwFormUrlDecoderEntry cannot be implemented: generic interface implementations are not supported def __init__(self, obj: DynWinRTValue) -> None: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi index 9d75b525..6be150a9 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi @@ -5,15 +5,15 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, ) +from abc import ABCMeta from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, DynWinRTImplementationHandle, ) -from abc import ABCMeta from typing import TypeVar from dynwinrt import _DynWinRTImplementationFactory _ImplementationHandlers = TypeVar('_ImplementationHandlers') @@ -30,6 +30,7 @@ class IStringableHandlers(Protocol): def to_string(self) -> str: ... class _IStringableImplementationFactory(ABCMeta): + def from_value(cls, obj: DynWinRTValue) -> IStringable: ... def implementation(cls, handlers: IStringableHandlers) -> DynWinRTImplementationDescriptor: ... def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IStringable]: ... def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IStringable: ... @@ -39,9 +40,9 @@ class _IStringableIdentity(Protocol): def _dynwinrt_iid_windows_foundation_istringable(self) -> None: ... class IStringable(_IStringableIdentity, Protocol, metaclass=_IStringableImplementationFactory): + @builtins.property + def _obj(self) -> DynWinRTValue: ... - @classmethod - def from_value(cls, obj: DynWinRTValue) -> Self: ... def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ... def to_string(self) -> str: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi index 301d849c..870cdeda 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi @@ -5,15 +5,15 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, ) +from abc import ABCMeta from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, DynWinRTImplementationHandle, ) -from abc import ABCMeta from typing import TypeVar from dynwinrt import _DynWinRTImplementationFactory _ImplementationHandlers = TypeVar('_ImplementationHandlers') @@ -31,6 +31,7 @@ class IUriRuntimeClassWithAbsoluteCanonicalUriHandlers(Protocol): def get_display_iri(self) -> str: ... class _IUriRuntimeClassWithAbsoluteCanonicalUriImplementationFactory(ABCMeta): + def from_value(cls, obj: DynWinRTValue) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... def implementation(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers) -> DynWinRTImplementationDescriptor: ... def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IUriRuntimeClassWithAbsoluteCanonicalUri]: ... def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... @@ -40,9 +41,9 @@ class _IUriRuntimeClassWithAbsoluteCanonicalUriIdentity(Protocol): def _dynwinrt_iid_windows_foundation_iuriruntimeclasswithabsolutecanonicaluri(self) -> None: ... class IUriRuntimeClassWithAbsoluteCanonicalUri(_IUriRuntimeClassWithAbsoluteCanonicalUriIdentity, Protocol, metaclass=_IUriRuntimeClassWithAbsoluteCanonicalUriImplementationFactory): + @builtins.property + def _obj(self) -> DynWinRTValue: ... - @classmethod - def from_value(cls, obj: DynWinRTValue) -> Self: ... def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ... @builtins.property diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi index c5cc9139..313afafd 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi @@ -5,15 +5,15 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, ) +from abc import ABCMeta from typing import Protocol, TypedDict from dynwinrt import ( DynWinRTInterfacePlan, DynWinRTImplementationMethod, DynWinRTImplementation, DynWinRTImplementationDescriptor, DynWinRTImplementationHandle, ) -from abc import ABCMeta from typing import TypeVar from dynwinrt import _DynWinRTImplementationFactory _ImplementationHandlers = TypeVar('_ImplementationHandlers') @@ -31,6 +31,7 @@ class IWwwFormUrlDecoderEntryHandlers(Protocol): def get_value(self) -> str: ... class _IWwwFormUrlDecoderEntryImplementationFactory(ABCMeta): + def from_value(cls, obj: DynWinRTValue) -> IWwwFormUrlDecoderEntry: ... def implementation(cls, handlers: IWwwFormUrlDecoderEntryHandlers) -> DynWinRTImplementationDescriptor: ... def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IWwwFormUrlDecoderEntry]: ... def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IWwwFormUrlDecoderEntry: ... @@ -40,9 +41,9 @@ class _IWwwFormUrlDecoderEntryIdentity(Protocol): def _dynwinrt_iid_windows_foundation_iwwwformurldecoderentry(self) -> None: ... class IWwwFormUrlDecoderEntry(_IWwwFormUrlDecoderEntryIdentity, Protocol, metaclass=_IWwwFormUrlDecoderEntryImplementationFactory): + @builtins.property + def _obj(self) -> DynWinRTValue: ... - @classmethod - def from_value(cls, obj: DynWinRTValue) -> Self: ... def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ... @builtins.property diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/uri.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/uri.pyi index 58c15063..815ffece 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/uri.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/uri.pyi @@ -5,7 +5,7 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, ) from ._typing import _DynWinRTRuntimeClass from typing import Protocol, Self @@ -29,6 +29,8 @@ class _UriIdentity(Protocol): def _dynwinrt_iid_windows_foundation_iuriruntimeclasswithabsolutecanonicaluri(self) -> None: ... class UriLike(_UriIdentity, Protocol): + @builtins.property + def _obj(self) -> DynWinRTValue: ... @builtins.property def absolute_uri(self) -> str: ... @@ -110,6 +112,8 @@ class Uri(UriLike, _DynWinRTRuntimeClass): class IUriRuntimeClassWithAbsoluteCanonicalUri: def __init__(self, obj: DynWinRTValue) -> None: ... + @builtins.property + def _obj(self) -> DynWinRTValue: ... @classmethod def from_value(cls, obj: DynWinRTValue) -> Self: ... @@ -124,6 +128,8 @@ class IUriRuntimeClassWithAbsoluteCanonicalUri: class IStringable: def __init__(self, obj: DynWinRTValue) -> None: ... + @builtins.property + def _obj(self) -> DynWinRTValue: ... @classmethod def from_value(cls, obj: DynWinRTValue) -> Self: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi index fe6d4f7f..46688389 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/www_form_url_decoder.pyi @@ -5,7 +5,7 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - _DynWinRTProjector, + _DynWinRTObject, _DynWinRTProjector, ) from ._typing import _DynWinRTRuntimeClass from typing import Protocol, Self @@ -29,6 +29,8 @@ class _WwwFormUrlDecoderIdentity(Protocol): def _dynwinrt_iid_windows_foundation_iwwwformurldecoderruntimeclass(self) -> None: ... class WwwFormUrlDecoderLike(_WwwFormUrlDecoderIdentity, Protocol): + @builtins.property + def _obj(self) -> DynWinRTValue: ... def __len__(self) -> int: ... @overload @@ -53,6 +55,8 @@ class WwwFormUrlDecoderLike(_WwwFormUrlDecoderIdentity, Protocol): class WwwFormUrlDecoder(_WwwFormUrlDecoderIdentity, Sequence[IWwwFormUrlDecoderEntry | None], _DynWinRTRuntimeClass): def __init__(self, query: str) -> None: ... + @builtins.property + def _obj(self) -> DynWinRTValue: ... def __len__(self) -> int: ... @overload @@ -81,6 +85,8 @@ class WwwFormUrlDecoder(_WwwFormUrlDecoderIdentity, Sequence[IWwwFormUrlDecoderE class IVectorView_IWwwFormUrlDecoderEntry(Sequence[IWwwFormUrlDecoderEntry | None]): def __init__(self, obj: DynWinRTValue) -> None: ... + @builtins.property + def _obj(self) -> DynWinRTValue: ... def __len__(self) -> int: ... @overload @@ -104,6 +110,8 @@ class IVectorView_IWwwFormUrlDecoderEntry(Sequence[IWwwFormUrlDecoderEntry | Non class IIterable_IWwwFormUrlDecoderEntry(Iterable[IWwwFormUrlDecoderEntry | None]): def __init__(self, obj: DynWinRTValue) -> None: ... + @builtins.property + def _obj(self) -> DynWinRTValue: ... def __iter__(self) -> Iterator[IWwwFormUrlDecoderEntry | None]: ... From 1813cddf681a872b1c90c2a13f2781d5c0b57480 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sun, 20 Sep 2026 13:08:25 +0800 Subject: [PATCH 2/5] Align observable vector tests with Python Object inputs Update the stale factory expectation shared by test-rust and coverage. Assert matching generated Python implementation and stub input types, native-wrapper unwrapping, and unchanged nullable raw-value outputs. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../tests/observable_vector_test.rs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/tools/dynwinrt-codegen/tests/observable_vector_test.rs b/tools/dynwinrt-codegen/tests/observable_vector_test.rs index bf3595fa..2d2b788a 100644 --- a/tools/dynwinrt-codegen/tests/observable_vector_test.rs +++ b/tools/dynwinrt-codegen/tests/observable_vector_test.rs @@ -102,8 +102,14 @@ fn observable_vector_projects_python_mutable_sequence_and_typed_events() { py.contains("_dynwinrt_symbol('i_vector_object', 'IVector_Object')._set_native(self, obj)") ); assert!(py.contains("self._observable_obj = obj.cast(IID_IObservableVector_Object)")); - assert!(py.contains("def create(items: Iterable['DynWinRTValue'])")); - assert!(py.contains("_dynwinrt_new_vector(items,")); + let create_signature = "def create(items: Iterable['DynWinRTValue | _DynWinRTObject']) -> 'IObservableVector_Object':"; + assert!(py.contains(create_signature), "{py}"); + assert!( + py.contains( + "_dynwinrt_new_vector(items, lambda item: getattr(item, '_obj', item), DynWinRTType.object())" + ), + "{py}" + ); assert!(py.contains("def as_vector(self) -> 'IVector_Object':")); assert!(py.contains("def on_vector_changed(self, callback: Callable[[")); assert!(py.contains("'IObservableVector_Object'")); @@ -121,6 +127,11 @@ fn observable_vector_projects_python_mutable_sequence_and_typed_events() { assert!(pyi.contains( "from .windows__foundation__collections__i_vector_changed_event_args import IVectorChangedEventArgs" )); + assert!(pyi.contains(&format!("{create_signature} ...")), "{pyi}"); + assert!( + pyi.contains("def __getitem__(self, index: int) -> DynWinRTValue | None: ..."), + "{pyi}" + ); assert!(pyi.contains("def as_vector(self) -> 'IVector_Object': ...")); assert!(pyi.contains("def on_vector_changed(self, callback: Callable[[")); } From 90146b546d5e3a0e2d6f2d4427f02a750b2fe800 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sun, 20 Sep 2026 13:45:16 +0800 Subject: [PATCH 3/5] Assert Python property contracts instead of decorator counts Cover qualified decorators and unchanged nullable Object outputs individually, including the native wrapper's read-only _obj property. Avoid a brittle total that changed with the added input protocol capability. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../python_property_name_collision_test.rs | 25 +++++++++++++++---- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs b/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs index 5f51ffe1..570bb835 100644 --- a/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs +++ b/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs @@ -46,10 +46,25 @@ fn property_named_property_does_not_shadow_the_decorator() { let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("_property, _weakref_ref,")); - assert_eq!(py.matches(" @_property\n").count(), 2); - assert!(py.contains("def property(self)")); - assert!(py.contains("def old_value(self)")); - assert!(pyi.contains("import builtins")); - assert_eq!(pyi.matches(" @builtins.property\n").count(), 2); + for name in ["property", "old_value"] { + assert!( + py.contains(&format!( + " @_property\n def {name}(self) -> DynWinRTValue | None:" + )), + "{py}" + ); + assert!( + pyi.contains(&format!( + " @builtins.property\n def {name}(self) -> DynWinRTValue | None: ..." + )), + "{pyi}" + ); + } + assert!( + pyi.contains(" @builtins.property\n def _obj(self) -> DynWinRTValue: ..."), + "{pyi}" + ); + assert!(!py.contains(" @property\n"), "{py}"); + assert!(!pyi.contains(" @property\n"), "{pyi}"); } From 17d94036620909d879abe570d3143047e50d8b75 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sun, 20 Sep 2026 15:38:57 +0800 Subject: [PATCH 4/5] Fix Python collection subscript input typing Use projected input contracts for collection keys and mutation values while preserving raw nullable outputs and existing ABC contracts. Distinguish scalar and slice assignment, and cover PropertySet, generated maps, typed vectors, independent identities, invalid inputs, and native null carriers. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/dynwinrt-codegen/python/README.md | 8 + .../src/codegen/winrt/python/stubs.rs | 23 +- .../src/codegen/winrt/python/type_helpers.rs | 18 ++ .../tests/python_consumer_typing_test.rs | 256 +++++++++++++++++- 4 files changed, 289 insertions(+), 16 deletions(-) diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md index 143188d3..8d873efa 100644 --- a/tools/dynwinrt-codegen/python/README.md +++ b/tools/dynwinrt-codegen/python/README.md @@ -142,6 +142,14 @@ outputs remain `DynWinRTValue | None`. Context managers retain the entered instance's type (`Self`), including derived wrappers passed through a base `Like` protocol, and still close the object without suppressing exceptions. +Collection subscripts use the input contract for keys and values: for example, +`properties["uri"] = uri` accepts a generated `Uri`, while reading the item still +returns `DynWinRTValue | None`. Sequence item assignment, slice assignment, and +`insert` likewise accept projected inputs without changing their read types; +integer indices take one item and slices take an iterable of items. Existing +nullable `collections.abc` contracts remain unchanged. To pass a native null +reference, use `DynWinRTValue.null_value()`, not implicit `None` boxing. + The output directory belongs to codegen; do not store handwritten files in it. After changing metadata files, SDK versions, or reference inputs, regenerate the complete output. Regenerate with the updated generator to pick up these diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index d02dab78..6fcc0fb6 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -1291,6 +1291,11 @@ fn collection_protocol_stubs( .first() .map(|typ| super::type_helpers::py_return_type_safe(Some(typ), context)) .unwrap_or_else(|| "object".to_string()); + let item_input = iface + .generic_args + .first() + .map(|typ| super::type_helpers::py_collection_input_type(typ, context)) + .unwrap_or_else(|| "object".to_string()); match kind { super::collections::CollectionKind::Iterable => { format!("\n{indent}def __iter__(self) -> Iterator[{item_type}]: ...\n") @@ -1311,9 +1316,12 @@ fn collection_protocol_stubs( ); if kind == super::collections::CollectionKind::MutableSequence { result.push_str(&format!( - "{indent}def __setitem__(self, index: int | slice, value: {item_type} | Iterable[{item_type}]) -> None: ...\n\ + "{indent}@overload\n\ + {indent}def __setitem__(self, index: int, value: {item_input}) -> None: ...\n\ + {indent}@overload\n\ + {indent}def __setitem__(self, index: slice, value: Iterable[{item_input}]) -> None: ...\n\ {indent}def __delitem__(self, index: int | slice) -> None: ...\n\ - {indent}def insert(self, index: int, value: {item_type}) -> None: ...\n" + {indent}def insert(self, index: int, value: {item_input}) -> None: ...\n" )); } result @@ -1329,12 +1337,17 @@ fn collection_protocol_stubs( let mut result = format!( "\n{indent}def __len__(self) -> int: ...\n\ {indent}def __iter__(self) -> Iterator[{key_type}]: ...\n\ - {indent}def __getitem__(self, key: {key_type}) -> {value_type}: ...\n" + {indent}def __getitem__(self, key: {item_input}) -> {value_type}: ...\n" ); if kind == super::collections::CollectionKind::MutableMapping { + let value_input = iface + .generic_args + .get(1) + .map(|typ| super::type_helpers::py_collection_input_type(typ, context)) + .unwrap_or_else(|| "object".to_string()); result.push_str(&format!( - "{indent}def __setitem__(self, key: {key_type}, value: {value_type}) -> None: ...\n\ - {indent}def __delitem__(self, key: {key_type}) -> None: ...\n" + "{indent}def __setitem__(self, key: {item_input}, value: {value_input}) -> None: ...\n\ + {indent}def __delitem__(self, key: {item_input}) -> None: ...\n" )); } result 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 5c76df4a..3cfdfae7 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -143,6 +143,19 @@ pub(crate) fn py_param_type_safe(typ: &TypeMeta, context: &PythonProjectionConte } } +pub(super) fn py_collection_input_type( + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> String { + let input = py_param_type_safe(typ, context); + // Keep the existing nullable ABC contract; only widen its projected inputs. + if is_nullable_reference_type(typ) { + py_optional_type(input) + } else { + input + } +} + pub(crate) fn py_return_type_safe( typ: Option<&TypeMeta>, context: &PythonProjectionContext, @@ -692,6 +705,11 @@ mod tests { py_return_type_safe(Some(&TypeMeta::Object), &context), "DynWinRTValue | None" ); + assert_eq!( + py_collection_input_type(&TypeMeta::Object, &context), + "DynWinRTValue | _DynWinRTObject | None" + ); + assert_eq!(py_collection_input_type(&TypeMeta::I32, &context), "int"); } #[test] diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index fe74e5e8..2b7c0da5 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -67,6 +67,21 @@ fn has_mypy() -> bool { available } +fn has_implementation_runtime() -> bool { + let available = Command::new(python()) + .args(["-c", "from dynwinrt import DynWinRTImplementationHandle"]) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + available || std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref() != Ok("1"), + "DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME=1 but the matching runtime is unavailable" + ); + if !available { + eprintln!("Skipping native consumers: set DYNWINRT_TEST_PYTHON to the matching runtime."); + } + available +} + fn typecheck(fixture: &Fixture, packages: &[&str], consumer: &str, errors: &[&str]) { fs::write(fixture.0.join("consumer.py"), consumer).unwrap(); let installed = std::env::var("DYNWINRT_TEST_INSTALLED_RUNTIME").as_deref() == Ok("1"); @@ -220,7 +235,65 @@ fn generate_fixture(fixture: &Fixture, package: &str) { class("Unrelated", unrelated.clone()), class("Content", content.clone()), ]; - let interfaces = [item, unrelated, closable, content]; + let resource_type = TypeMeta::RuntimeClass { + namespace: "Contoso".into(), + name: "Resource".into(), + default_interface: None, + }; + let mut interfaces = vec![item, unrelated, closable, content]; + for (name, definition, piid, args) in [ + ( + "IVector_Object", + "IVector`1", + "913337e9-11a1-4345-a3a2-4e7f956e222d", + vec![TypeMeta::Object], + ), + ( + "IVector_Resource", + "IVector`1", + "913337e9-11a1-4345-a3a2-4e7f956e222d", + vec![resource_type], + ), + ( + "IMap_Object_Object", + "IMap`2", + "3c2925fe-8519-45c1-aa79-197b6718c1c1", + vec![TypeMeta::Object, TypeMeta::Object], + ), + ] { + let methods = if definition == "IVector`1" { + vec![ + MethodMeta { + name: "GetAt".into(), + vtable_index: 6, + params: vec![ParamMeta { + name: "index".into(), + typ: TypeMeta::U32, + direction: ParamDirection::In, + }], + return_type: Some(args[0].clone()), + ..Default::default() + }, + MethodMeta { + name: "Append".into(), + vtable_index: 13, + params: vec![parameter(args[0].clone())], + ..Default::default() + }, + ] + } else { + Vec::new() + }; + interfaces.push(InterfaceMeta { + namespace: "Windows.Foundation.Collections".into(), + name: name.into(), + generic_name: Some(definition.into()), + generic_piid: Some(piid.into()), + generic_args: args, + methods, + ..Default::default() + }); + } let identities = classes .iter() .map(|class| TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name)) @@ -297,6 +370,9 @@ from first.contoso__i_item import IItem from first.contoso__resource import Resource, ResourceLike from first.contoso__derived_resource import DerivedResource from first.contoso__content import Content +from first.windows__foundation__collections__i_map_object_object import IMap_Object_Object +from first.windows__foundation__collections__i_vector_object import IVector_Object +from first.windows__foundation__collections__i_vector_resource import IVector_Resource from second.contoso__i_item import IItem as OtherItem from second.contoso__derived_resource import DerivedResource as OtherDerived @@ -330,6 +406,24 @@ def valid(raw: DynWinRTValue, resource: Resource, derived: DerivedResource, content.content = raw content.set_object(derived) content.set_objects([resource, other, item, raw]) + +def collections(resource: Resource, derived: OtherDerived, raw: DynWinRTValue, + vector: IVector_Object, resources: IVector_Resource, + mapping: IMap_Object_Object) -> None: + vector[0] = resource + vector[1:2] = [resource, derived, raw] + vector.insert(0, derived) + vector.append(derived) + resources[0] = derived + resources[1:2] = [resource, derived] + resources.insert(0, derived) + resources.append(derived) + mapping[resource] = derived + assert_type(vector[0], DynWinRTValue | None) + assert_type(vector[:], list[DynWinRTValue | None]) + assert_type(resources[0], Resource | None) + assert_type(mapping[resource], DynWinRTValue | None) + del mapping[resource] "#, &[], ); @@ -342,6 +436,9 @@ from first.contoso__i_unrelated import IUnrelated from first.contoso__resource import Resource, ResourceLike from first.contoso__unrelated import Unrelated from first.contoso__content import Content +from first.windows__foundation__collections__i_map_object_object import IMap_Object_Object +from first.windows__foundation__collections__i_vector_object import IVector_Object +from first.windows__foundation__collections__i_vector_resource import IVector_Resource from second.contoso__unrelated import Unrelated as OtherUnrelated class WrongObject: @@ -366,6 +463,18 @@ def invalid(raw: DynWinRTValue, resource: Resource, unrelated: Unrelated, content.content = Resource content.set_object(WrongObject()) content.set_objects([42]) + +def invalid_collections(resource: Resource, unrelated: Unrelated, + vector: IVector_Object, resources: IVector_Resource, + mapping: IMap_Object_Object) -> None: + vector[0] = object() + vector[0] = [resource] + vector[:] = resource + vector[:] = [42] + resources[0] = unrelated + resources.append(unrelated) + mapping[WrongObject()] = resource + mapping[resource] = object() "#, &[ "[arg-type]", @@ -379,6 +488,14 @@ def invalid(raw: DynWinRTValue, resource: Resource, unrelated: Unrelated, "[assignment]", "[arg-type]", "[list-item]", + "[call-overload]", + "[call-overload]", + "[call-overload]", + "[list-item]", + "[call-overload]", + "[arg-type]", + "[index]", + "[assignment]", ], ); } @@ -449,18 +566,135 @@ def reference(animation: ExpressionAnimation, visual: ContainerVisual) -> None: } #[test] -fn native_object_inputs_keep_projection_factories_and_context_lifetimes() { - let available = Command::new(python()) - .args(["-c", "from dynwinrt import DynWinRTImplementationHandle"]) +fn collection_subscripts_accept_projected_inputs_and_keep_raw_outputs() { + let winmd = Path::new( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ); + if !winmd.is_file() || !has_mypy() { + eprintln!("Skipping SDK collections: Windows.winmd or mypy unavailable."); + return; + } + let fixture = Fixture::new(); + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd"]) + .arg(winmd) + .args([ + "--class-name", + "Windows.Foundation.Collections.PropertySet,Windows.Foundation.Uri", + "--lang", + "py", + "--output", + ]) + .arg(fixture.0.join("sdk")) .output() - .is_ok_and(|output| output.status.success()); - if !available { - assert_ne!( - std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref(), - Ok("1"), - "DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME=1 but the matching runtime is unavailable" + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + let imports = r#"from typing import assert_type +from dynwinrt import DynWinRTValue +from sdk.windows.foundation import Uri +from sdk.windows.foundation.collections import IMap_String_Object, PropertySet +from sdk.windows__foundation__collections__property_set import ( + IMap_String_Object as EmbeddedMap, PropertySetLike, +) +"#; + typecheck( + &fixture, + &["sdk"], + &format!( + r#"{imports} +def valid(uri: Uri, raw: DynWinRTValue, properties: PropertySet, + like: PropertySetLike, mapping: IMap_String_Object, + embedded: EmbeddedMap) -> None: + properties["uri"] = uri + properties["raw"] = raw + like["uri"] = uri + mapping["uri"] = uri + embedded["uri"] = uri + assert_type(properties["uri"], DynWinRTValue | None) + assert_type(like["uri"], DynWinRTValue | None) + assert_type(mapping["uri"], DynWinRTValue | None) + assert_type(embedded["uri"], DynWinRTValue | None) + del properties["uri"] + del mapping["uri"] +"# + ), + &[], + ); + typecheck( + &fixture, + &["sdk"], + &format!( + r#"{imports} +class WrongObject: + _obj: int = 42 + +def invalid(uri: Uri, properties: PropertySet, mapping: IMap_String_Object) -> None: + properties["plain"] = object() + properties["string"] = "unboxed" + properties["wrong"] = WrongObject() + mapping["number"] = 42 + mapping["class"] = Uri + mapping[42] = uri + result: Uri = properties["uri"] +"# + ), + &[ + "[assignment]", + "[assignment]", + "[assignment]", + "[assignment]", + "[assignment]", + "[index]", + "[assignment]", + ], + ); + if has_implementation_runtime() { + fs::write( + fixture.0.join("collections_runtime.py"), + r#"from dynwinrt import DynWinRTValue, RoApartment, projected_lifetime_scope +from sdk.windows.foundation import Uri +from sdk.windows.foundation.collections import IMap_String_Object, PropertySet + +with RoApartment(1), projected_lifetime_scope(): + uri = Uri("https://example.com/collection-input") + properties = PropertySet() + mapping = IMap_String_Object.create({"uri": uri}) + for collection in (properties, mapping): + collection["uri"] = uri + value = collection["uri"] + assert isinstance(value, DynWinRTValue) + assert value.identity_raw() == uri._obj.identity_raw() + value.release() + collection["null"] = DynWinRTValue.null_value() + assert collection["null"] is None + collection.insert("raw", uri._obj) + value = collection["raw"] + assert isinstance(value, DynWinRTValue) + assert value.identity_raw() == uri._obj.identity_raw() + value.release() + del collection["uri"] + assert not collection.has_key("uri") +print("collection-subscript-native-ok", flush=True) +"#, + ) + .unwrap(); + let output = Command::new(python()) + .args(["-B", "collections_runtime.py"]) + .current_dir(&fixture.0) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + assert!( + String::from_utf8_lossy(&output.stdout).contains("collection-subscript-native-ok"), + "{}", + diagnostics(&output) ); - eprintln!("Skipping native consumers: set DYNWINRT_TEST_PYTHON to the matching runtime."); + } +} + +#[test] +fn native_object_inputs_keep_projection_factories_and_context_lifetimes() { + if !has_implementation_runtime() { return; } let fixture = Fixture::new(); From 5fc91889eac4156780198e19897a7755b73adaeb Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sun, 20 Sep 2026 15:57:19 +0800 Subject: [PATCH 5/5] Preserve Python interface subclass factory return types Bind metaclass from_value to its receiving interface class through the existing TypeVar instead of fixing its return to the base interface. Keep factories outside instance protocols and preserve independent static factory results. Add exact subclass, projector, wrong-input, and native identity regressions. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tools/dynwinrt-codegen/python/README.md | 6 +- .../src/codegen/winrt/python/stubs.rs | 8 +- .../tests/python_consumer_typing_test.rs | 121 ++++++++++++++++++ .../tests/python_identity_cache_test.rs | 16 +++ .../tests/snapshots/uri_pyi/i_stringable.pyi | 2 +- ...time_class_with_absolute_canonical_uri.pyi | 2 +- .../uri_pyi/i_www_form_url_decoder_entry.pyi | 2 +- 7 files changed, 149 insertions(+), 8 deletions(-) diff --git a/tools/dynwinrt-codegen/python/README.md b/tools/dynwinrt-codegen/python/README.md index 8d873efa..2b16f617 100644 --- a/tools/dynwinrt-codegen/python/README.md +++ b/tools/dynwinrt-codegen/python/README.md @@ -132,7 +132,11 @@ Interface protocols describe native **instances**, including their canonical identity and methods, not wrapper factories. For example, `StorageFile` can be passed to an `IStorageFile` parameter without defining `from_value`. `IStorageFile.from_value(raw)` and `value.as_interface(IStorageFile)` remain -available for explicit, IID-checked projection. +available for explicit, IID-checked projection. Inherited `from_value` factories +retain the receiving interface subclass: `TaggedBuffer.from_value(raw)` and +`value.as_interface(TaggedBuffer)` return `TaggedBuffer`, not `IBuffer`. +Independent static factories such as `IBuffer.from_bytes` keep their declared +base-interface result. WinRT `Object` inputs accept a `DynWinRTValue` or a projected native wrapper whose `_obj` is a `DynWinRTValue`, including interface views and runtime-class diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 6fcc0fb6..c1499928 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -426,10 +426,10 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf if has_factory { out.push_str(&format!("\nclass {factory_metaclass}(ABCMeta):\n")); if is_protocol && has_projection { - out.push_str(&format!( - " def from_value(cls, obj: DynWinRTValue) -> {}: ...\n", - iface.name - )); + // Bind the result to the receiving interface class, not its metaclass. + out.push_str( + " def from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT: ...\n", + ); } if is_buffer { out.push_str(&format!( diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index 2b7c0da5..622a464b 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -565,6 +565,127 @@ def reference(animation: ExpressionAnimation, visual: ContainerVisual) -> None: ); } +#[test] +fn interface_factory_preserves_subclass_types_and_runtime_identity() { + let winmd = Path::new( + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd", + ); + if !winmd.is_file() || !has_mypy() { + eprintln!("Skipping SDK factories: Windows.winmd or mypy unavailable."); + return; + } + let fixture = Fixture::new(); + let output = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd"]) + .arg(winmd) + .args([ + "--class-name", + "Windows.Storage.Streams.Buffer", + "--lang", + "py", + "--output", + ]) + .arg(fixture.0.join("sdk")) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + let prelude = r#"from typing import assert_type +from dynwinrt import DynWinRTValue +from sdk.windows.storage.streams import Buffer, IBuffer + +class TaggedBuffer(IBuffer): + def tag(self) -> str: + return "tagged" + +class SpecializedBuffer(TaggedBuffer): + pass +"#; + typecheck( + &fixture, + &["sdk"], + &format!( + r#"{prelude} +from dynwinrt import _DynWinRTProjector + +def valid(raw: DynWinRTValue, buffer: Buffer, factory: type[TaggedBuffer]) -> None: + assert_type(IBuffer.from_value(raw), IBuffer) + assert_type(TaggedBuffer.from_value(raw), TaggedBuffer) + assert_type(SpecializedBuffer.from_value(raw), SpecializedBuffer) + assert_type(factory.from_value(raw), TaggedBuffer) + assert_type(TaggedBuffer.from_value(raw).tag(), str) + assert_type(buffer.as_interface(IBuffer), IBuffer) + assert_type(buffer.as_interface(TaggedBuffer), TaggedBuffer) + assert_type(buffer.as_interface(SpecializedBuffer), SpecializedBuffer) + projector: _DynWinRTProjector[TaggedBuffer] = TaggedBuffer + assert_type(projector.from_value(raw), TaggedBuffer) + assert_type(TaggedBuffer.from_bytes(b"static factory"), IBuffer) +"# + ), + &[], + ); + typecheck( + &fixture, + &["sdk"], + &format!( + r#"{prelude} +def invalid(raw: DynWinRTValue, buffer: Buffer) -> None: + TaggedBuffer.from_value(object()) + tagged: TaggedBuffer = IBuffer.from_value(raw) + specialized: SpecializedBuffer = TaggedBuffer.from_value(raw) + IBuffer.from_value(raw).tag() + static_result: TaggedBuffer = TaggedBuffer.from_bytes(b"base result") + buffer.as_interface(Buffer) +"# + ), + &[ + "[arg-type]", + "[assignment]", + "[assignment]", + "[attr-defined]", + "[assignment]", + "[arg-type]", + ], + ); + if has_implementation_runtime() { + fs::write( + fixture.0.join("factory_runtime.py"), + format!( + r#"{prelude} +from dynwinrt import RoApartment, projected_lifetime_scope + +with RoApartment(1), projected_lifetime_scope(): + buffer = Buffer.from_bytes(b"subclass factory") + base = IBuffer.from_value(buffer._obj) + tagged = TaggedBuffer.from_value(buffer._obj) + specialized = SpecializedBuffer.from_value(buffer._obj) + assert type(base) is IBuffer + assert type(tagged) is TaggedBuffer + assert type(specialized) is SpecializedBuffer + assert tagged.tag() == "tagged" + assert specialized.to_bytes() == b"subclass factory" + assert TaggedBuffer.from_value(tagged._obj) is tagged + assert buffer.as_interface(TaggedBuffer) is tagged + assert buffer.as_interface(SpecializedBuffer) is specialized + assert type(TaggedBuffer.from_bytes(b"static factory")) is IBuffer +print("subclass-factory-native-ok", flush=True) +"# + ), + ) + .unwrap(); + let output = Command::new(python()) + .args(["-B", "factory_runtime.py"]) + .current_dir(&fixture.0) + .output() + .unwrap(); + assert!(output.status.success(), "{}", diagnostics(&output)); + assert!( + String::from_utf8_lossy(&output.stdout).contains("subclass-factory-native-ok"), + "{}", + diagnostics(&output) + ); + } +} + #[test] fn collection_subscripts_accept_projected_inputs_and_keep_raw_outputs() { let winmd = Path::new( diff --git a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs index b7e6cce9..dffc7572 100644 --- a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs +++ b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs @@ -174,6 +174,22 @@ fn interface_generation_uses_projected_identity_cache() { py.contains("return cls._from_native(obj.cast(IID_IWidget))"), "from_value should reuse the cached wrapper path:\n{py}" ); + let pyi = common::generate_interface_stub( + &iface, + &HashSet::from(["IWidget".to_string()]), + &HashSet::new(), + ); + assert!( + pyi.contains( + "def from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT: ..." + ), + "{pyi}" + ); + let instance = pyi + .split("\nclass IWidget(") + .nth(1) + .expect("interface instance protocol"); + assert!(!instance.contains("def from_value("), "{pyi}"); } #[test] diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi index 6be150a9..8a689201 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_stringable.pyi @@ -30,7 +30,7 @@ class IStringableHandlers(Protocol): def to_string(self) -> str: ... class _IStringableImplementationFactory(ABCMeta): - def from_value(cls, obj: DynWinRTValue) -> IStringable: ... + def from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT: ... def implementation(cls, handlers: IStringableHandlers) -> DynWinRTImplementationDescriptor: ... def implement(cls, handlers: IStringableHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IStringable]: ... def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IStringable: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi index 870cdeda..10b3a07b 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_uri_runtime_class_with_absolute_canonical_uri.pyi @@ -31,7 +31,7 @@ class IUriRuntimeClassWithAbsoluteCanonicalUriHandlers(Protocol): def get_display_iri(self) -> str: ... class _IUriRuntimeClassWithAbsoluteCanonicalUriImplementationFactory(ABCMeta): - def from_value(cls, obj: DynWinRTValue) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... + def from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT: ... def implementation(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers) -> DynWinRTImplementationDescriptor: ... def implement(cls, handlers: IUriRuntimeClassWithAbsoluteCanonicalUriHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IUriRuntimeClassWithAbsoluteCanonicalUri]: ... def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IUriRuntimeClassWithAbsoluteCanonicalUri: ... diff --git a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi index 313afafd..612cec3e 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi +++ b/tools/dynwinrt-codegen/tests/snapshots/uri_pyi/i_www_form_url_decoder_entry.pyi @@ -31,7 +31,7 @@ class IWwwFormUrlDecoderEntryHandlers(Protocol): def get_value(self) -> str: ... class _IWwwFormUrlDecoderEntryImplementationFactory(ABCMeta): - def from_value(cls, obj: DynWinRTValue) -> IWwwFormUrlDecoderEntry: ... + def from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT: ... def implementation(cls, handlers: IWwwFormUrlDecoderEntryHandlers) -> DynWinRTImplementationDescriptor: ... def implement(cls, handlers: IWwwFormUrlDecoderEntryHandlers, *additional: DynWinRTImplementationDescriptor, interfaces: Sequence[tuple[_DynWinRTImplementationFactory[_ImplementationHandlers], _ImplementationHandlers]] = ...) -> DynWinRTImplementationHandle[IWwwFormUrlDecoderEntry]: ... def from_implementation(cls, owner: DynWinRTImplementation | DynWinRTImplementationHandle[object]) -> IWwwFormUrlDecoderEntry: ...