From add16ac433f4559b7b3578c13004f104454ce16f Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 22:53:09 +0800 Subject: [PATCH 1/3] Align Python collection bulk and default contracts Reuse checked write-input types for mapping update/setdefault and existing vector bulk helpers across class, interface, Like and inline output surfaces. Return the stored read projection after a missing-key default insertion without consuming the caller's source or changing fallback defaults, raw Object reads, JSON null preflight or ordinary partial-update behavior. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c1f7c114-f863-4ba4-824e-3a7423613fa2 --- bindings/py/README.md | 18 ++ bindings/py/src/lib.rs | 7 + bindings/py/tests/test_object_value_view.py | 51 ++++ .../src/codegen/winrt/python/collections.rs | 114 +++++++++ .../codegen/winrt/python/generator/class.rs | 19 ++ .../src/codegen/winrt/python/generator/mod.rs | 10 +- .../codegen/winrt/python/generator/types.rs | 8 + .../src/codegen/winrt/python/naming.rs | 14 + .../src/codegen/winrt/python/shared.rs | 10 + .../src/codegen/winrt/python/stubs.rs | 32 +-- .../src/codegen/winrt/python/type_helpers.rs | 2 +- ...python_collection_helper_collision_test.rs | 241 +++++++++++++++--- .../tests/python_consumer_typing_test.rs | 222 +++++++++++++++- .../tests/python_json_native_null_test.rs | 10 + 14 files changed, 687 insertions(+), 71 deletions(-) diff --git a/bindings/py/README.md b/bindings/py/README.md index c3a3bdac..8b22e823 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -162,6 +162,24 @@ and iterators work with `iter()` and `next()`. Mutable vectors support indexing, slicing, assignment, insertion, and deletion; mutable maps support standard mapping assignment and deletion. +Bulk writes use the same checked inputs as item assignment: `update()` accepts +mappings or iterables of key/value pairs, plus keyword entries for string-keyed +maps; `extend()` and `+=` accept iterables of valid vector inputs. They do not +change the types returned by reads. `extend()` returns `None`, and `+=` returns +the same wrapper. + +`setdefault(key, default)` returns the value as `self[key]` reads it, including +after inserting a missing key. For an `Object`-valued map such as `PropertySet`, +a generated wrapper with a valid `_obj` can be a write input, but reads and +`setdefault()` still return `DynWinRTValue | None`, not that input wrapper or an +automatically unboxed Python value. The input remains usable. A present key +leaves its default unused, while a missing key requires a valid default +(`None` can be omitted only for nullable value types). Explicit fallback +defaults passed to `get()` or `pop()` are not stored and remain unchanged. +Native failures propagate; ordinary bulk writes can retain entries already +written before a later failure. The stock JSON null preflight described above +still rejects null inputs before mutation. + Method inputs accept normal Python sequences and mappings in place of compatible WinRT collection interfaces, subject to the producer limits below. Byte arrays accept `bytes` and `bytearray`; GUID, diff --git a/bindings/py/src/lib.rs b/bindings/py/src/lib.rs index 8bba4e28..5303d01c 100644 --- a/bindings/py/src/lib.rs +++ b/bindings/py/src/lib.rs @@ -611,6 +611,13 @@ class _WinRTMutableMappingMixin(_MutableMapping): raise KeyError(key) self.remove(key) + def setdefault(self, key, default=None): + try: + return self[key] + except KeyError: + self[key] = default + return self[key] + def update(self, other=(), /, **kwargs): contract = getattr(type(self), '_dynwinrt_non_null_collection_contract', None) native = getattr(self, '_collection_obj', self._obj) diff --git a/bindings/py/tests/test_object_value_view.py b/bindings/py/tests/test_object_value_view.py index 4f2d5a53..f9c9f3b1 100644 --- a/bindings/py/tests/test_object_value_view.py +++ b/bindings/py/tests/test_object_value_view.py @@ -10,6 +10,7 @@ """ import gc +import sys from collections.abc import Mapping, MutableMapping from contextlib import contextmanager from datetime import datetime, timedelta, timezone @@ -687,6 +688,56 @@ def __init__(self, obj): assert "empty" not in view +@pytest.mark.parametrize("failure_slot", [8, 10, 6], ids=["lookup", "insert", "read-after-insert"]) +def test_raw_setdefault_propagates_native_failure_without_consuming_default( + failure_slot, monkeypatch +): + plan = map_implementation_plan("Tests.IMap_DefaultFailure", OBJECT) + calls = [] + reports = [] + inserted = False + failure = RuntimeError(f"expected native map failure at slot {failure_slot}") + monkeypatch.setattr(sys, "unraisablehook", reports.append) + + def dispatch(_interface, slot, args): + nonlocal inserted + calls.append(slot) + if slot == failure_slot: + raise failure + if slot == 8: + return [DynWinRTValue.from_bool(inserted)] + if slot == 10: + assert args[0].to_string() == "default" + inserted = True + return [DynWinRTValue.from_bool(False)] + raise AssertionError(f"unexpected native map slot {slot}") + + owner = DynWinRTImplementation.create([plan], dispatch) + raw = owner.to_value() + mapping = GeneratedStyleMap(raw) + default = uri() + identity = default.identity_raw() + try: + with pytest.raises(OSError) as caught: + mapping.setdefault("default", SimpleNamespace(_obj=default)) + assert caught.value.winerror == 0xA0EE4005 - 2**32 + assert inserted is (failure_slot == 6) + assert calls == { + 8: [8], + 10: [8, 10], + 6: [8, 10, 8, 6], + }[failure_slot] + assert len(reports) == 1 and reports[0].exc_value is failure + assert str(failure) in owner.take_error() + assert not default.is_released() and default.identity_raw() == identity + finally: + release_projected(mapping) + raw.release() + default.release() + owner.release() + assert owner.is_closed + + def test_contains_len_and_iteration_do_not_unbox(monkeypatch): view = object_value_view(property_set()) view["count"] = 5 diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs index 43bfab51..a4c1d163 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs @@ -6,6 +6,12 @@ use crate::meta::{ }; use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; +use super::naming::{PythonProjectionContext, PythonSupportSymbol}; +use super::nullability::{AnnotationSurface, ElementContainer, may_project_none}; +use super::type_helpers::{ + py_collection_input_type, py_collection_item_type, py_optional_type, py_param_type_safe, +}; + pub(crate) const IITERABLE_PIID: &str = "faa585ea-6214-4217-afda-7f46de5869b3"; pub(crate) const IITERATOR_PIID: &str = "6a79e863-4300-459a-9966-cbb660963ee1"; pub(crate) const IVECTOR_PIID: &str = "913337e9-11a1-4345-a3a2-4e7f956e222d"; @@ -232,6 +238,114 @@ pub(crate) fn is_mapping_input(kind: CollectionKind, args: &[TypeMeta]) -> bool )) } +/// 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( + iface: &InterfaceMeta, + owner_name: &str, + context: &PythonProjectionContext, + surface: AnnotationSurface, + stock_json_receiver: bool, + indent_spaces: usize, +) -> String { + let indent = " ".repeat(indent_spaces); + let input = |typ| { + if stock_json_receiver { + py_param_type_safe(typ, context) + } else { + py_collection_input_type(typ, context) + } + }; + let is_stub = surface == AnnotationSurface::Stub; + match ( + projected_interface_kind(iface), + iface.generic_args.as_slice(), + ) { + (Some(CollectionKind::MutableSequence), [element]) => { + let element = input(element); + if is_stub { + format!( + "{indent}def extend(self, values: Iterable[{element}]) -> None: ...\n\ + {indent}def __iadd__(self, values: Iterable[{element}]) -> Self: ...\n" + ) + } else { + format!( + "\n{indent}def extend(self, values: Iterable[{element}]) -> None:\n\ + {indent} super().extend(values)\n\ + \n{indent}def __iadd__(self, values: Iterable[{element}]) -> Self:\n\ + {indent} self.extend(values)\n\ + {indent} return self\n" + ) + } + } + (Some(CollectionKind::MutableMapping), [key, value]) => { + let key_input = py_collection_input_type(key, context); + let value_input = input(value); + let value_read = if stock_json_receiver { + py_param_type_safe(value, context) + } else { + py_collection_item_type(value, ElementContainer::Mutable, surface, context) + }; + let supports = context.support_symbol_reference(PythonSupportSymbol::MappingInput); + let key_variable = context.support_symbol_reference(PythonSupportSymbol::MappingKey); + let key_reference = if is_stub { + key_variable.to_string() + } else { + format!("{owner_name}.{key_variable}") + }; + let key_bound = serde_json::to_string(super::type_helpers::unquoted(&key_input)) + .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) { + format!(", **kwargs: {value_input}") + } else { + String::new() + }; + let mut result = format!( + "\n{indent}{key_variable} = TypeVar('{key_variable}', bound={key_bound})\n\ + \n{indent}@overload\n\ + {indent}def update(self, other: {mapping}, /{keywords}) -> None: ...\n\ + {indent}@overload\n\ + {indent}def update(self, other: {pairs} = (), /{keywords}) -> None: ...\n" + ); + if !is_stub { + // Keep runtime kwargs handling, including partial updates, in + // the existing checked mixin even for non-string key types. + result.push_str(&format!( + "{indent}def update(self, other: {mapping} | {pairs} = (), /, **kwargs: {value_input}) -> None:\n\ + {indent} super().update(other, **kwargs)\n" + )); + } + let nullable = may_project_none(value) && !stock_json_receiver; + if is_stub { + let default = if nullable { " = None" } else { "" }; + result.push_str(&format!( + "\n{indent}def setdefault(self, key: {key_input}, default: {value_input}{default}) -> {value_read}: ...\n" + )); + } else { + if !nullable { + result.push_str(&format!( + "\n{indent}@overload\n\ + {indent}def setdefault(self, key: {key_input}, default: {value_input}, /) -> {value_read}: ...\n\ + {indent}@overload\n\ + {indent}def setdefault(self, key: {key_input}, *, default: {value_input}) -> {value_read}: ...\n" + )); + } + let default_input = py_optional_type(value_input); + // An omitted/invalid default is still ignored for an existing + // key. The overloads constrain values that may be inserted. + result.push_str(&format!( + "\n{indent}def setdefault(self, key: {key_input}, default: {default_input} = None) -> {value_read}:\n\ + {indent} return super().setdefault(key, default)\n" + )); + } + result + } + _ => String::new(), + } +} + #[cfg(test)] mod tests { use super::*; 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 05bb189e..880e69a0 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -701,6 +701,17 @@ pub fn generate_class<'a>( )); } + if let Some(iface) = collection_iface { + out.push_str(&super::super::collections::protocol_helper_methods( + iface, + &context.class_name(class), + context, + super::super::nullability::AnnotationSurface::Runtime, + stock_json_receiver, + 4, + )); + } + // Auto-generate close() if class implements IClosable const ICLOSABLE_IID: &str = "30d5a829-7fa4-4026-83bb-d75bae4ea99e"; if class @@ -949,6 +960,14 @@ pub fn generate_class<'a>( py_runtime_symbol(context, &iterable_identity, &iterable_name) )); } + out.push_str(&super::super::collections::protocol_helper_methods( + req_iface, + &symbol, + context, + super::super::nullability::AnnotationSurface::Runtime, + false, + 4, + )); } out } 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 da102310..1d72626f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -54,6 +54,7 @@ fn import_line( needs_legacy_int_guard: bool, ) -> String { let object_input = context.support_symbol_import(PythonSupportSymbol::ObjectInput); + let mapping_input = context.support_symbol_import(PythonSupportSymbol::MappingInput); let can_cast = context.support_symbol_import(PythonSupportSymbol::CanCast); let mut legacy_helpers = String::new(); if needs_legacy_helper { @@ -73,10 +74,10 @@ fn import_line( "\ from ._runtime import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, - TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, + TYPE_CHECKING, Self, TypeVar, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - {object_input}, _property, _weakref_ref, + {object_input}, {mapping_input}, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, {can_cast}, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, {legacy_helpers} _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, @@ -119,7 +120,7 @@ from collections.abc import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, ) from datetime import datetime, timedelta -from typing import TYPE_CHECKING, Protocol +from typing import TYPE_CHECKING, Protocol, Self, TypeVar, overload from uuid import UUID from weakref import ref as _weakref_ref from dynwinrt import ( @@ -254,8 +255,9 @@ fn as_interface_method(context: &PythonProjectionContext) -> String { 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::shared::MAPPING_INPUT_PROTOCOL, super::implementation::HELPERS ) } 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 04fe0424..df68bdb4 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -288,6 +288,14 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe )); } out.push_str(" _dynwinrt_interface_type = True\n"); + out.push_str(&super::super::collections::protocol_helper_methods( + iface, + &iface.name, + context, + super::super::nullability::AnnotationSurface::Runtime, + false, + 4, + )); out.push_str(&implementation.factory_body); if !iface.iid.is_empty() || iface.generic_piid.is_some() { out.push_str(&format!( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 56bf3bc0..de7a0eb2 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -18,6 +18,8 @@ pub type PythonTypeIdentity = TypeIdentity; #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(crate) enum PythonSupportSymbol { ObjectInput, + MappingInput, + MappingKey, AsInterface, CollectionItem, CanCast, @@ -29,6 +31,8 @@ impl PythonSupportSymbol { fn name(self) -> &'static str { match self { Self::ObjectInput => "_DynWinRTObject", + Self::MappingInput => "_SupportsKeysAndGetItem", + Self::MappingKey => "_MapUpdateKeyT", Self::AsInterface => "_dynwinrt_as_interface", Self::CollectionItem => "_dynwinrt_collection_item", Self::CanCast => "_dynwinrt_can_cast", @@ -1003,6 +1007,8 @@ impl PythonProjectionContext { // Support imports yield to metadata declarations and their allocated roles. for helper in [ PythonSupportSymbol::ObjectInput, + PythonSupportSymbol::MappingInput, + PythonSupportSymbol::MappingKey, PythonSupportSymbol::AsInterface, PythonSupportSymbol::CollectionItem, PythonSupportSymbol::CanCast, @@ -1587,6 +1593,8 @@ mod tests { let [second, third] = [format!("{name}_2"), format!("{name}_3")]; let others = [ PythonSupportSymbol::ObjectInput, + PythonSupportSymbol::MappingInput, + PythonSupportSymbol::MappingKey, PythonSupportSymbol::AsInterface, PythonSupportSymbol::CollectionItem, PythonSupportSymbol::CanCast, @@ -1647,6 +1655,12 @@ mod tests { assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::ObjectInput); } + #[test] + fn mapping_input_helper_yields_to_visible_roles_without_renaming_metadata() { + assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::MappingInput); + assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::MappingKey); + } + #[test] fn as_interface_helper_yields_to_visible_roles_without_renaming_metadata() { assert_support_helper_yields_to_visible_roles(PythonSupportSymbol::AsInterface); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs index ac2f973b..d6120d83 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs @@ -13,6 +13,16 @@ class _DynWinRTObject(Protocol): def _obj(self) -> DynWinRTValue: ... "; +pub(super) const MAPPING_INPUT_PROTOCOL: &str = " +_MapKeyT = TypeVar('_MapKeyT') +_MapValueT_co = TypeVar('_MapValueT_co', covariant=True) + + +class _SupportsKeysAndGetItem(Protocol[_MapKeyT, _MapValueT_co]): + def keys(self) -> Iterable[_MapKeyT]: ... + def __getitem__(self, key: _MapKeyT, /) -> _MapValueT_co: ... +"; + /// 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 95524302..e0e7307d 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -48,6 +48,7 @@ const HEADER: &str = "# Generated by dynwinrt-codegen — do not edit\n"; const FUTURE_ANNOTATIONS: &str = "from __future__ import annotations\n"; fn import_line(context: &PythonProjectionContext) -> String { let object_input = context.support_symbol_import(PythonSupportSymbol::ObjectInput); + let mapping_input = context.support_symbol_import(PythonSupportSymbol::MappingInput); format!( "\ import builtins @@ -55,7 +56,7 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - {object_input}, _DynWinRTProjector, + {object_input}, {mapping_input}, _DynWinRTProjector, )\n" ) } @@ -73,7 +74,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 Protocol, overload as overload\n\ +from typing import Protocol, TypeVar, overload as overload\n\ from uuid import UUID as UUID\n\ from dynwinrt import (\n\ DynWinRTType as DynWinRTType, DynWinRTValue as DynWinRTValue,\n\ @@ -82,8 +83,9 @@ from dynwinrt import (\n\ _DynWinRTProjector as _DynWinRTProjector,\n\ _DynWinRTProjectableClass as _DynWinRTProjectableClass,\n\ _DynWinRTRuntimeClass as _DynWinRTRuntimeClass,\n\ -)\n{}", +)\n{}{}", super::shared::NATIVE_OBJECT_PROTOCOL, + super::shared::MAPPING_INPUT_PROTOCOL, ) } @@ -1346,7 +1348,7 @@ fn collection_protocol_stubs( } }) .unwrap_or_else(|| "object".to_string()); - match kind { + let mut result = match kind { super::collections::CollectionKind::Iterable => { format!("\n{indent}def __iter__(self) -> Iterator[{item_type}]: ...\n") } @@ -1373,12 +1375,6 @@ fn collection_protocol_stubs( {indent}def __delitem__(self, index: int | slice) -> None: ...\n\ {indent}def insert(self, index: int, value: {item_input}) -> None: ...\n" )); - if stock_json_receiver { - result.push_str(&format!( - "{indent}def extend(self, values: Iterable[{item_input}]) -> None: ...\n\ - {indent}def __iadd__(self, values: Iterable[{item_input}]) -> Self: ...\n" - )); - } } result } @@ -1422,16 +1418,20 @@ fn collection_protocol_stubs( "{indent}def __setitem__(self, key: {item_input}, value: {value_input}) -> None: ...\n\ {indent}def __delitem__(self, key: {item_input}) -> None: ...\n" )); - if stock_json_receiver { - result.push_str(&format!( - "{indent}def setdefault(self, key: {item_input}, default: {value_input}) -> {value_type}: ...\n" - )); - } } result } super::collections::CollectionKind::KeyValuePair => String::new(), - } + }; + result.push_str(&super::collections::protocol_helper_methods( + iface, + &iface.name, + context, + AnnotationSurface::Stub, + stock_json_receiver, + indent_spaces, + )); + result } fn emit_constructor_stubs(class: &ClassMeta, context: &PythonProjectionContext) -> String { 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 92c19725..f3693a71 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -69,7 +69,7 @@ pub(crate) fn py_optional_type(typ: String) -> String { format!("{} | None", unquoted) } -fn unquoted(typ: &str) -> &str { +pub(super) fn unquoted(typ: &str) -> &str { typ.strip_prefix('\'') .and_then(|value| value.strip_suffix('\'')) .unwrap_or(typ) diff --git a/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs b/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs index 6bc676be..23d3bb49 100644 --- a/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs +++ b/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs @@ -210,23 +210,24 @@ fn write_standalone(root: &Path, classes: &[ClassMeta]) -> Modules { modules(&context) } -fn generate_packaged(root: &Path, custom: &Path, classes: &[ClassMeta]) -> Modules { +fn generate_packaged(root: &Path, custom: &Path, classes: &[ClassMeta], no_pyi: bool) -> Modules { let package = root.join("pyviews"); - success( - Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) - .args(["generate", "--winmd"]) - .arg(custom) - .args(["--ref", WINDOWS_WINMD, "--output"]) - .arg(&package) - .args([ - "--lang", - "py", - "--class-name", - "Audit.Vector._dynwinrt_collection_item,Audit.Map._dynwinrt_collection_item", - ]) - .output() - .unwrap(), - ); + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(custom) + .args(["--ref", WINDOWS_WINMD, "--output"]) + .arg(&package) + .args([ + "--lang", + "py", + "--class-name", + "Audit.Vector._dynwinrt_collection_item,Audit.Map._dynwinrt_collection_item", + ]); + if no_pyi { + command.arg("--no-pyi"); + } + success(command.output().unwrap()); let context = projection_context(classes, true); let modules = modules(&context); for (module, operation) in [ @@ -273,6 +274,13 @@ with dw.RoApartment(1), dw.projected_lifetime_scope(): item.release() vector.replace_all([live, None]) assert vector[1] is None + projected = type('Projected', (), {{'_obj': live}})() + assert vector.extend(item for item in [projected, None]) is None + assert vector.__iadd__([projected]) is vector + for index in (2, 4): + item = vector[index] + assert item is not None and item.identity_raw() == live.identity_raw() + item.release() mapping = Map._from_native( dw.DynWinRTValue.create_map( @@ -285,6 +293,29 @@ with dw.RoApartment(1), dw.projected_lifetime_scope(): value = mapping.lookup(live) assert value is not None and value.identity_raw() == live.identity_raw() value.release() + mapping.remove(None) + stored = mapping.setdefault(None, projected) + assert isinstance(stored, dw.DynWinRTValue) and stored is not live + assert stored.identity_raw() == live.identity_raw() + stored.release() + existing = mapping.setdefault(None, object()) + assert isinstance(existing, dw.DynWinRTValue) + assert existing.identity_raw() == live.identity_raw() + existing.release() + mapping.update({{None: None}}) + mapping.update([(live, projected)]) + assert mapping[None] is None + for operation in ( + lambda: mapping.update({{None: object()}}), + lambda: vector.extend([42]), + ): + try: + operation() + except TypeError: + pass + else: + raise AssertionError('bulk helper accepted an unboxed input') + assert not live.is_released() live.release() @@ -339,7 +370,7 @@ fn old_hardcoded_binding_fails(root: &Path, modules: &Modules) { ); } -fn strict_typecheck(root: &Path, modules: &Modules) { +fn strict_typecheck(root: &Path, modules: &Modules, no_pyi: bool) { let available = Command::new(python()) .args(["-m", "mypy", "--version"]) .output() @@ -354,18 +385,30 @@ fn strict_typecheck(root: &Path, modules: &Modules) { } let consumer = format!( r#" +from typing import assert_type from dynwinrt import DynWinRTValue from pyviews.{vector_class} import {COLLIDING} as Vector from pyviews.{map_class} import {COLLIDING} as Map -def vectors(vector: Vector, value: DynWinRTValue) -> None: +class Projected: + def __init__(self, value: DynWinRTValue) -> None: + self._obj = value + +def vectors(vector: Vector, value: DynWinRTValue, projected: Projected) -> None: vector.append(None) vector.append(value) vector.replace_all([None, value]) + assert_type(vector.extend([projected, None]), None) + assert_type(vector.__iadd__([projected]), Vector) + vector += [projected, value] def maps(mapping: Map, value: DynWinRTValue) -> None: mapping.insert(None, None) mapping.insert(value, value) + mapping.update({{value: value, None: None}}) + mapping.update({{Projected(value): Projected(value)}}) + mapping.update([(None, Projected(value))]) + assert_type(mapping.setdefault(value, Projected(value)), DynWinRTValue | None) "#, vector_class = modules.vector_class, map_class = modules.map_class, @@ -378,28 +421,71 @@ def maps(mapping: Map, value: DynWinRTValue) -> None: .join("py") .canonicalize() .unwrap(); - success( - Command::new(python()) - .args([ - "-B", - "-m", - "mypy", - "--strict", - "--follow-imports=silent", - "--no-incremental", - "--cache-dir", - "mypy-cache", - "typing_probe.py", - ]) - .current_dir(root) - .env( - "MYPYPATH", - std::env::join_paths([binding_stubs, root.to_path_buf()]).unwrap(), - ) - .output() - .unwrap(), - ); - if let Some(pyright) = std::env::var_os("DYNWINRT_PYRIGHT") { + let mut command = Command::new(python()); + command + .args([ + "-B", + "-m", + "mypy", + "--strict", + "--follow-imports=silent", + "--no-incremental", + "--cache-dir", + "mypy-cache", + ]) + .current_dir(root); + if no_pyi { + command.env_remove("MYPYPATH"); + } else { + command.env( + "MYPYPATH", + std::env::join_paths([binding_stubs, root.to_path_buf()]).unwrap(), + ); + } + success(command.arg("typing_probe.py").output().unwrap()); + fs::write( + root.join("invalid_probe.py"), + format!( + r#"from dynwinrt import DynWinRTValue +from pyviews.{vector_class} import {COLLIDING} as Vector +from pyviews.{map_class} import {COLLIDING} as Map + +class WrongObject: + _obj: int = 42 + +def invalid(vector: Vector, mapping: Map, value: DynWinRTValue) -> None: + vector.extend([WrongObject()]) + vector += [42] + mapping.update({{None: object()}}) + mapping.update({{object(): value}}) + mapping.setdefault(None, 42) +"#, + vector_class = modules.vector_class, + map_class = modules.map_class, + ), + ) + .unwrap(); + let output = command.arg("invalid_probe.py").output().unwrap(); + let text = String::from_utf8_lossy(&output.stdout); + let errors = text + .lines() + .filter(|line| line.contains(": error:")) + .collect::>(); + assert_eq!(output.status.code(), Some(1), "{text}"); + assert_eq!(errors.len(), 5, "{text}"); + for (line, code) in errors.iter().zip([ + "[list-item]", + "[list-item]", + "[dict-item]", + "[type-var]", + "[arg-type]", + ]) { + assert!( + line.starts_with("invalid_probe.py:") && line.ends_with(code), + "{text}" + ); + } + if !no_pyi && let Some(pyright) = std::env::var_os("DYNWINRT_PYRIGHT") { fs::write( root.join("pyright_probe.py"), format!("# pyright: strict, reportPrivateUsage=false\n{consumer}"), @@ -417,6 +503,56 @@ def maps(mapping: Map, value: DynWinRTValue) -> None: } } +fn assert_incremental_parity(complete: &Path, root: &Path, custom: &Path, no_pyi: bool) { + let incremental = root.join("pyviews"); + for class in [ + "Audit.Vector._dynwinrt_collection_item", + "Audit.Map._dynwinrt_collection_item", + ] { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(custom) + .args([ + "--ref", + WINDOWS_WINMD, + "--lang", + "py", + "--class-name", + class, + "--output", + ]) + .arg(&incremental); + if no_pyi { + command.arg("--no-pyi"); + } + success(command.output().unwrap()); + } + let modules = |directory: &Path| { + let mut files = fs::read_dir(directory) + .unwrap() + .map(|entry| entry.unwrap().file_name()) + .filter(|name| { + Path::new(name) + .extension() + .is_some_and(|ext| ext == "py" || ext == "pyi") + }) + .collect::>(); + files.sort(); + files + }; + let files = modules(&complete.join("pyviews")); + assert_eq!(modules(&incremental), files); + for file in files { + assert_eq!( + fs::read(complete.join("pyviews").join(&file)).unwrap(), + fs::read(incremental.join(&file)).unwrap(), + "incremental helper surface drift: {}", + file.to_string_lossy() + ); + } +} + #[test] fn collection_helper_aliases_execute_for_packaged_and_standalone_outputs() { if !Path::new(WINDOWS_WINMD).is_file() { @@ -437,9 +573,30 @@ fn collection_helper_aliases_execute_for_packaged_and_standalone_outputs() { } let packaged = fixture.0.join("packaged"); - let modules = generate_packaged(&packaged, &custom, &classes); - strict_typecheck(&packaged, &modules); + let modules = generate_packaged(&packaged, &custom, &classes, false); + assert_incremental_parity(&packaged, &fixture.0.join("incremental"), &custom, false); + strict_typecheck(&packaged, &modules, false); if runtime_available() { runtime_probe(&packaged, &modules); } + + let no_pyi = fixture.0.join("no_pyi"); + let modules = generate_packaged(&no_pyi, &custom, &classes, true); + assert_incremental_parity( + &no_pyi, + &fixture.0.join("incremental_no_pyi"), + &custom, + true, + ); + assert!(fs::read_dir(no_pyi.join("pyviews")).unwrap().all(|entry| { + entry + .unwrap() + .path() + .extension() + .is_none_or(|ext| ext != "pyi") + })); + strict_typecheck(&no_pyi, &modules, true); + if runtime_available() { + runtime_probe(&no_pyi, &modules); + } } diff --git a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs index 8eda636e..1d332059 100644 --- a/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_consumer_typing_test.rs @@ -523,11 +523,18 @@ def collections(resource: Resource, derived: OtherDerived, raw: DynWinRTValue, vector[1:2] = [resource, derived, raw] vector.insert(0, derived) vector.append(derived) + assert_type(vector.extend([resource, derived, raw, None]), None) + assert_type(vector.__iadd__([resource, derived, raw, None]), IVector_Object) resources[0] = derived resources[1:2] = [resource, derived] resources.insert(0, derived) resources.append(derived) + assert_type(resources.extend([resource, derived, None]), None) + assert_type(resources.__iadd__([resource, derived, None]), IVector_Resource) mapping[resource] = derived + mapping.update({resource: derived, raw: raw, None: None}) + mapping.update([(resource, derived), (raw, raw), (None, None)]) + assert_type(mapping.setdefault(resource, derived), DynWinRTValue | None) assert_type(vector[0], DynWinRTValue | None) assert_type(vector[:], list[DynWinRTValue | None]) assert_type(resources[0], Resource | None) @@ -580,8 +587,12 @@ def invalid_collections(resource: Resource, unrelated: Unrelated, vector[0] = [resource] vector[:] = resource vector[:] = [42] + vector.extend([object()]) + vector += [WrongObject()] resources[0] = unrelated resources.append(unrelated) + resources.extend([unrelated]) + resources += [unrelated] mapping[WrongObject()] = resource mapping[resource] = object() "#, @@ -601,8 +612,12 @@ def invalid_collections(resource: Resource, unrelated: Unrelated, "[call-overload]", "[call-overload]", "[list-item]", + "[list-item]", + "[list-item]", "[call-overload]", "[arg-type]", + "[list-item]", + "[list-item]", "[index]", "[assignment]", ], @@ -617,12 +632,16 @@ from first.windows__foundation__collections__i_map_object_object import IMap_Obj from first.__RESOURCE_MAP_MODULE__ import IMap_Resource_Resource def nullable_reference_keys( - objects: IMap_Object_Object, resources: IMap_Resource_Resource + objects: IMap_Object_Object, resources: IMap_Resource_Resource, + resource: Resource ) -> None: objects[None] = None assert_type(objects[None], DynWinRTValue | None) resources[None] = None resources.update({None: None}) + resources.update({resource: resource}) + resources.update([(None, resource), (resource, None)]) + assert_type(resources.setdefault(resource, resource), Resource | None) assert_type(resources.setdefault(None, None), Resource | None) assert_type(resources[None], Resource | None) "# @@ -670,12 +689,12 @@ def invalid_key(guid: IMap_Guid_Object, string: IMap_String_Object) -> None: &[ "[index]", "[call-overload]", - "[dict-item]", - "[call-overload]", + "[type-var]", + "[arg-type]", "[index]", "[call-overload]", - "[dict-item]", - "[call-overload]", + "[type-var]", + "[arg-type]", ], ); pyright_typecheck( @@ -693,7 +712,7 @@ def invalid_key(guid: IMap_Guid_Object, string: IMap_String_Object) -> None: string.update({None: None}) string.setdefault(None, None) "#, - 12, + 10, ); } @@ -1006,6 +1025,18 @@ from sdk.windows.foundation.collections import IMap_String_Object, PropertySet from sdk.windows__foundation__collections__property_set import ( IMap_String_Object as EmbeddedMap, PropertySetLike, ) + +class NativeCarrier: + def __init__(self, raw: DynWinRTValue) -> None: + self._obj = raw + +class KeyedValues: + def __init__(self, uri: Uri) -> None: + self.uri = uri + def keys(self) -> list[str]: + return ["uri"] + def __getitem__(self, key: str) -> Uri: + return self.uri "#; typecheck( &fixture, @@ -1015,11 +1046,36 @@ from sdk.windows__foundation__collections__property_set import ( def valid(uri: Uri, raw: DynWinRTValue, properties: PropertySet, like: PropertySetLike, mapping: IMap_String_Object, embedded: EmbeddedMap) -> None: + like = properties properties["uri"] = uri properties["raw"] = raw like["uri"] = uri mapping["uri"] = uri embedded["uri"] = uri + properties.update({{"uri": uri, "raw": raw, "null": None}}) + properties.update([("uri", uri), ("raw", raw), ("null", None)]) + properties.update(uri=uri, raw=raw, null=None) + properties.update({{"uri": uri}}, keyword=raw) + properties.update(KeyedValues(uri)) + properties.update({{"carrier": NativeCarrier(raw)}}) + like.update({{"uri": uri}}) + like.update([("uri", uri)], keyword=uri) + like.update(keyword=uri) + mapping.update({{"uri": uri}}) + mapping.update([("uri", uri)], keyword=uri) + mapping.update(keyword=uri) + embedded.update({{"uri": uri}}) + embedded.update([("uri", uri)], keyword=uri) + embedded.update(keyword=uri) + assert_type(properties.setdefault("uri", uri), DynWinRTValue | None) + assert_type(properties.setdefault("raw", raw), DynWinRTValue | None) + assert_type(properties.setdefault("null"), DynWinRTValue | None) + assert_type(properties.setdefault(key="uri", default=uri), DynWinRTValue | None) + assert_type(like.setdefault("uri", uri), DynWinRTValue | None) + assert_type(mapping.setdefault("uri", uri), DynWinRTValue | None) + assert_type(embedded.setdefault("uri", uri), DynWinRTValue | None) + assert_type(properties.get("missing", uri), DynWinRTValue | Uri | None) + assert_type(properties.pop("missing", uri), DynWinRTValue | Uri | None) assert_type(properties["uri"], DynWinRTValue | None) assert_type(like["uri"], DynWinRTValue | None) assert_type(mapping["uri"], DynWinRTValue | None) @@ -1046,6 +1102,14 @@ def invalid(uri: Uri, properties: PropertySet, mapping: IMap_String_Object) -> N mapping["class"] = Uri mapping[42] = uri result: Uri = properties["uri"] + properties.update({{"wrong": WrongObject()}}) + properties.update([("unboxed", object())]) + properties.update(unboxed="string") + properties.update({{42: uri}}) + mapping.update({{"class": Uri}}) + properties.setdefault("unboxed", 42) + properties.setdefault("wrong", WrongObject()) + properties.setdefault(42, uri) "# ), &[ @@ -1056,20 +1120,43 @@ def invalid(uri: Uri, properties: PropertySet, mapping: IMap_String_Object) -> N "[assignment]", "[index]", "[assignment]", + "[dict-item]", + "[list-item]", + "[call-overload]", + "[type-var]", + "[dict-item]", + "[arg-type]", + "[arg-type]", + "[arg-type]", ], ); if has_implementation_runtime() { fs::write( fixture.0.join("collections_runtime.py"), - r#"from dynwinrt import DynWinRTValue, RoApartment, projected_lifetime_scope + r#"from dynwinrt import ( + DynWinRTImplementation, DynWinRTImplementationMethod, DynWinRTInterfacePlan, + DynWinRTMethodSig, DynWinRTType, DynWinRTValue, RoApartment, WinGUID, + projected_lifetime_scope, release_projected, +) +import threading 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 + +class NativeCarrier: + def __init__(self, obj): + self._obj = obj + +class IgnoredDefault: + @property + def _obj(self): + raise AssertionError("an existing key evaluated its unused default") 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): + for index, collection in enumerate((properties, mapping, EmbeddedMap.from_value(properties._obj))): collection["uri"] = uri value = collection["uri"] assert isinstance(value, DynWinRTValue) @@ -1082,8 +1169,127 @@ with RoApartment(1), projected_lifetime_scope(): assert isinstance(value, DynWinRTValue) assert value.identity_raw() == uri._obj.identity_raw() value.release() + carrier = NativeCarrier(uri._obj) + collection.update({"bulk": uri, "carrier": carrier}, keyword=uri) + collection.update((entry for entry in [("pair", uri), ("raw", uri._obj)])) + key = f"default_{index}" + missing = collection.setdefault(key, carrier) + existing = collection.setdefault(key, IgnoredDefault()) + for result in (missing, existing, collection[key]): + assert isinstance(result, DynWinRTValue) and result is not uri._obj + assert result.identity_raw() == uri._obj.identity_raw() + result.release() + assert not uri._obj.is_released() + assert uri.absolute_uri == "https://example.com/collection-input" + assert collection.get("absent", uri) is uri + assert collection.pop("absent", uri) is uri + assert not collection.has_key("absent") + assert collection.setdefault("null-default") is None + assert collection.setdefault("null-default", IgnoredDefault()) is None del collection["uri"] assert not collection.has_key("uri") + + class WrongObject: + _obj = 42 + + for invalid in (object(), 42, "unboxed", WrongObject(), Uri): + for operation in ( + lambda: properties.update({"invalid": invalid}), + lambda: properties.update([("invalid", invalid)]), + lambda: properties.update(invalid=invalid), + lambda: properties.setdefault("invalid", invalid), + ): + try: + operation() + except TypeError: + pass + else: + raise AssertionError(f"accepted invalid input {type(invalid).__name__}") + assert not properties.has_key("invalid") + assert properties.setdefault("null-default", invalid) is None + for operation in ( + lambda: properties.update({42: uri}), + lambda: properties.setdefault(42, uri), + ): + try: + operation() + except TypeError: + pass + else: + raise AssertionError("accepted a non-string key") + try: + properties.update((entry for entry in [("early", uri), ("late", 42)])) + except TypeError: + pass + else: + raise AssertionError("accepted an invalid later entry") + assert properties["early"].identity_raw() == uri._obj.identity_raw() + assert not properties.has_key("late") + + released = Uri("https://example.com/released") + release_projected(released) + for operation in ( + lambda: properties.update(released=released), + lambda: properties.setdefault("released", released), + ): + try: + operation() + except RuntimeError as error: + assert "released" in str(error) + else: + raise AssertionError("accepted a released input") + assert properties.setdefault("null-default", released) is None + assert not properties.has_key("released") + + iid = WinGUID.parse("96369f54-8eb6-48f0-abce-c1b211e627c3") + signature = DynWinRTMethodSig().add_out(DynWinRTType.hstring()) + stringable = DynWinRTType.register_interface("Tests.IMapDefaultOwner", iid) + stringable = stringable.add_method("ToString", signature) + plan = DynWinRTInterfacePlan.create( + "Tests.IMapDefaultOwner", stringable, + [DynWinRTImplementationMethod("ToString", 6, signature)], + ) + owner = DynWinRTImplementation.create( + [plan], lambda *_: [DynWinRTValue.from_hstring("owner alive")], + ) + source = owner.to_value() + retained = properties.setdefault("owned", NativeCarrier(source)) + assert isinstance(retained, DynWinRTValue) + assert retained.identity_raw() == source.identity_raw() + errors = [] + + def worker(): + with RoApartment(1): + foreign = PropertySet() + foreign["existing"] = None + assert foreign.setdefault("existing", NativeCarrier(retained)) is None + for operation in ( + lambda: foreign.update({"foreign": NativeCarrier(retained)}), + lambda: foreign.setdefault("foreign", NativeCarrier(retained)), + ): + try: + operation() + except RuntimeError as error: + assert "non-agile" in str(error) or "thread" in str(error) + errors.append(error) + else: + raise AssertionError("accepted a foreign-thread non-agile input") + assert not foreign.has_key("foreign") + + thread = threading.Thread(target=worker) + thread.start() + thread.join() + assert len(errors) == 2 + source_view = source.cast(iid) + assert stringable.method(6).invoke(source_view, []).to_string() == "owner alive" + source_view.release() + owner.release() + source.release() + retained.release() + assert not owner.is_closed + del properties["owned"] + assert owner.is_closed +assert uri._obj.is_released() and missing.is_released() print("collection-subscript-native-ok", flush=True) "#, ) diff --git a/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs b/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs index dd83ea64..3a325a8f 100644 --- a/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs +++ b/tools/dynwinrt-codegen/tests/python_json_native_null_test.rs @@ -329,6 +329,7 @@ with RoApartment(): lambda: array.replace_all(array_of_null), lambda: array.replace_all(array_of_null.to_value()), lambda: array.extend([json_null, None]), + lambda: array.extend(value for value in [json_null, None]), lambda: operator.iadd(array, [json_null, None]), lambda: view.append(None), lambda: view.set_at(0, None), @@ -345,11 +346,13 @@ with RoApartment(): lambda: obj.set_named_value('bad', native_null), lambda: obj.update({'good': json_null, 'bad': None}), lambda: obj.update([('good', json_null), ('bad', native_null)]), + lambda: obj.update(entry for entry in [('good', json_null), ('bad', None)]), lambda: obj.update([('good', json_null), (None, json_null)]), lambda: obj.setdefault('bad'), lambda: map_view.insert('bad', None), lambda: operator.setitem(map_view, 'bad', None), lambda: map_view.update({'good': json_null, 'bad': None}), + lambda: map_view.update(entry for entry in [('good', json_null), ('bad', native_null)]), ): rejected_without_mutation(obj, mutation) @@ -357,6 +360,12 @@ with RoApartment(): obj['valid'] = json_null assert array[-1].stringify() == 'null' assert obj['valid'].stringify() == 'null' + stored = obj.setdefault('default', json_null) + assert type(stored) is type(obj['default']) + assert stored._obj.identity_raw() == json_null._obj.identity_raw() + assert obj.setdefault('default', None)._obj.identity_raw() == stored._obj.identity_raw() + assert obj.setdefault('default')._obj.identity_raw() == stored._obj.identity_raw() + assert json_null.stringify() == 'null' activated_array = JsonArray.create() activated_object = JsonObject.create() activated_array.append(json_null) @@ -395,6 +404,7 @@ with RoApartment(): assert not borrowed_map.is_released() borrowed_map.release() generic_map.update({'next': None}) + assert generic_map.setdefault('default', None) is None assert generic_map['original'] is None and generic_map['next'] is None try: JsonObject(generic_map._obj) From 24c895f22209b09e1d695cf12d84e9416b5e3c42 Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Fri, 9 Oct 2026 23:56:35 +0800 Subject: [PATCH 2/3] Keep helper imports and typing checks scoped to their actual surfaces Preserve existing non-collection snapshots by importing helper protocols and annotations only in modules that emit bulk helpers. Reuse the established source/installed dual-mode typing harness so metadata-only coverage can check generated inline declarations before building a native runtime, while installed-mode checks remain source-mask-free. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c1f7c114-f863-4ba4-824e-3a7423613fa2 --- .../src/codegen/winrt/python/collections.rs | 41 +++++++++ .../codegen/winrt/python/generator/class.rs | 5 ++ .../src/codegen/winrt/python/generator/mod.rs | 5 +- .../codegen/winrt/python/generator/types.rs | 5 ++ .../src/codegen/winrt/python/stubs.rs | 13 ++- ...python_collection_helper_collision_test.rs | 89 ++++++++++--------- 6 files changed, 112 insertions(+), 46 deletions(-) diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs index a4c1d163..f5f94d9e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs @@ -238,6 +238,47 @@ pub(crate) fn is_mapping_input(kind: CollectionKind, args: &[TypeMeta]) -> bool )) } +/// Keep helper-only imports out of unrelated collection and value projections. +pub(super) fn protocol_helper_imports<'a>( + interfaces: impl IntoIterator, + context: &PythonProjectionContext, + surface: AnnotationSurface, +) -> String { + let mut sequence = false; + let mut mapping = false; + for iface in interfaces { + match ( + projected_interface_kind(iface), + iface.generic_args.as_slice(), + ) { + (Some(CollectionKind::MutableSequence), [_]) => sequence = true, + (Some(CollectionKind::MutableMapping), [_, _]) => mapping = true, + _ => {} + } + } + let mut names = Vec::new(); + if surface == AnnotationSurface::Runtime { + if sequence { + names.push("Self".to_string()); + } + if mapping { + names.extend(["TypeVar".to_string(), "overload".to_string()]); + } + } + if mapping { + names.push(context.support_symbol_import(PythonSupportSymbol::MappingInput)); + } + if names.is_empty() { + String::new() + } else { + let support = match surface { + AnnotationSurface::Runtime => "_runtime", + AnnotationSurface::Stub => "_typing", + }; + format!("from .{support} import {}\n", names.join(", ")) + } +} + /// 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( 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 880e69a0..a4fa7717 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -90,6 +90,11 @@ pub fn generate_class<'a>( needs_legacy_helper, needs_legacy_int_guard, )); + out.push_str(&super::super::collections::protocol_helper_imports( + class.all_interfaces(), + context, + super::super::nullability::AnnotationSurface::Runtime, + )); out.push_str(&collection_item_import( context, class 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 1d72626f..86e02084 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -54,7 +54,6 @@ fn import_line( needs_legacy_int_guard: bool, ) -> String { let object_input = context.support_symbol_import(PythonSupportSymbol::ObjectInput); - let mapping_input = context.support_symbol_import(PythonSupportSymbol::MappingInput); let can_cast = context.support_symbol_import(PythonSupportSymbol::CanCast); let mut legacy_helpers = String::new(); if needs_legacy_helper { @@ -74,10 +73,10 @@ fn import_line( "\ from ._runtime import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, - TYPE_CHECKING, Self, TypeVar, UUID, WinGUID, datetime, overload, timedelta, + TYPE_CHECKING, UUID, WinGUID, datetime, timedelta, DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface, - {object_input}, {mapping_input}, _property, _weakref_ref, + {object_input}, _property, _weakref_ref, _dynwinrt_array, _dynwinrt_bind_overload, {can_cast}, _dynwinrt_create_delegate, _dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid, {legacy_helpers} _dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime, 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 df68bdb4..1c5cd44e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -101,6 +101,11 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe plan.has_legacy_fallback(), plan.has_legacy_int_guard(), )); + out.push_str(&super::super::collections::protocol_helper_imports( + std::iter::once(iface), + context, + super::super::nullability::AnnotationSurface::Runtime, + )); out.push_str(&collection_item_import( context, iface.methods.iter(), diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index e0e7307d..f87e1819 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -48,7 +48,6 @@ const HEADER: &str = "# Generated by dynwinrt-codegen — do not edit\n"; const FUTURE_ANNOTATIONS: &str = "from __future__ import annotations\n"; fn import_line(context: &PythonProjectionContext) -> String { let object_input = context.support_symbol_import(PythonSupportSymbol::ObjectInput); - let mapping_input = context.support_symbol_import(PythonSupportSymbol::MappingInput); format!( "\ import builtins @@ -56,7 +55,7 @@ from ._typing import ( Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence, UUID, WinGUID, datetime, overload, timedelta, DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate, - {object_input}, {mapping_input}, _DynWinRTProjector, + {object_input}, _DynWinRTProjector, )\n" ) } @@ -287,6 +286,11 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf if has_factory { out.push_str("from abc import ABCMeta\n"); } + out.push_str(&super::collections::protocol_helper_imports( + std::iter::once(iface), + context, + AnnotationSurface::Stub, + )); if implementation.supported { out.push_str(super::implementation::IMPORTS); out.push_str("from typing import TypeVar\nfrom dynwinrt import _DynWinRTImplementationFactory\n_ImplementationHandlers = TypeVar('_ImplementationHandlers')\n"); @@ -657,6 +661,11 @@ pub fn generate_class_stub<'a>( out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); out.push_str(&import_line(context)); + out.push_str(&super::collections::protocol_helper_imports( + class.all_interfaces(), + context, + AnnotationSurface::Stub, + )); if projectable { out.push_str("from ._typing import _DynWinRTRuntimeClass\n"); } else if native_projectable { diff --git a/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs b/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs index 23d3bb49..4ec1256a 100644 --- a/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs +++ b/tools/dynwinrt-codegen/tests/python_collection_helper_collision_test.rs @@ -421,28 +421,6 @@ def maps(mapping: Map, value: DynWinRTValue) -> None: .join("py") .canonicalize() .unwrap(); - let mut command = Command::new(python()); - command - .args([ - "-B", - "-m", - "mypy", - "--strict", - "--follow-imports=silent", - "--no-incremental", - "--cache-dir", - "mypy-cache", - ]) - .current_dir(root); - if no_pyi { - command.env_remove("MYPYPATH"); - } else { - command.env( - "MYPYPATH", - std::env::join_paths([binding_stubs, root.to_path_buf()]).unwrap(), - ); - } - success(command.arg("typing_probe.py").output().unwrap()); fs::write( root.join("invalid_probe.py"), format!( @@ -465,25 +443,54 @@ def invalid(vector: Vector, mapping: Map, value: DynWinRTValue) -> None: ), ) .unwrap(); - let output = command.arg("invalid_probe.py").output().unwrap(); - let text = String::from_utf8_lossy(&output.stdout); - let errors = text - .lines() - .filter(|line| line.contains(": error:")) - .collect::>(); - assert_eq!(output.status.code(), Some(1), "{text}"); - assert_eq!(errors.len(), 5, "{text}"); - for (line, code) in errors.iter().zip([ - "[list-item]", - "[list-item]", - "[dict-item]", - "[type-var]", - "[arg-type]", - ]) { - assert!( - line.starts_with("invalid_probe.py:") && line.ends_with(code), - "{text}" - ); + 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", + "--follow-imports=silent", + "--no-incremental", + "--cache-dir", + "mypy-cache", + ]) + .current_dir(root); + if *source_stubs { + command.env( + "MYPYPATH", + std::env::join_paths([binding_stubs.clone(), root.to_path_buf()]).unwrap(), + ); + } else { + command.env_remove("MYPYPATH"); + } + success(command.arg("typing_probe.py").output().unwrap()); + let output = command.arg("invalid_probe.py").output().unwrap(); + let text = String::from_utf8_lossy(&output.stdout); + let errors = text + .lines() + .filter(|line| line.contains(": error:")) + .collect::>(); + assert_eq!(output.status.code(), Some(1), "{text}"); + assert_eq!(errors.len(), 5, "{text}"); + for (line, code) in errors.iter().zip([ + "[list-item]", + "[list-item]", + "[dict-item]", + "[type-var]", + "[arg-type]", + ]) { + assert!( + line.starts_with("invalid_probe.py:") && line.ends_with(code), + "{text}" + ); + } } if !no_pyi && let Some(pyright) = std::env::var_os("DYNWINRT_PYRIGHT") { fs::write( From b4b89f6ce5bde5d8f558cd361d5889c7f06ca91a Mon Sep 17 00:00:00 2001 From: Leilei Zhang Date: Sat, 10 Oct 2026 02:31:40 +0800 Subject: [PATCH 3/3] Preserve native collection members when refining Python helpers Plan helper refinements in the existing shared Python member namespace. Native instance/static methods, properties and compatibility aliases keep their established names, signatures and dispatch; a native extend also retains inherited += behavior. Reuse the plan across runtime, stub, Like and interface surfaces and cover real WinMD/native callbacks in both output modes and the hosted native Python lane. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: c1f7c114-f863-4ba4-824e-3a7423613fa2 --- .github/workflows/build.yml | 2 +- bindings/py/README.md | 7 + .../src/codegen/winrt/python/collections.rs | 56 +- .../codegen/winrt/python/generator/class.rs | 2 + .../codegen/winrt/python/generator/types.rs | 1 + .../src/codegen/winrt/python/member_plan.rs | 305 ++++++++- .../src/codegen/winrt/python/stubs.rs | 27 +- ...python_collection_member_collision_test.rs | 624 ++++++++++++++++++ 8 files changed, 989 insertions(+), 35 deletions(-) create mode 100644 tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 869eed99..fb22698d 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -577,7 +577,7 @@ jobs: reference_array_results_preserve_null_elements -- --exact if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } cargo test -p dynwinrt-codegen --test python_collection_helper_collision_test ` - collection_helper_aliases_execute_for_packaged_and_standalone_outputs -- --exact + --test python_collection_member_collision_test -- --nocapture if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } cargo test -p dynwinrt-codegen --test python_delegate_callback_test ` nested_delegate_callback_argument_preserves_native_null -- --exact --nocapture diff --git a/bindings/py/README.md b/bindings/py/README.md index 8b22e823..169fa867 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -168,6 +168,13 @@ maps; `extend()` and `+=` accept iterables of valid vector inputs. They do not change the types returned by reads. `extend()` returns `None`, and `+=` returns the same wrapper. +If metadata already exposes a native member with a helper's Python name, that +native method, property or compatibility alias keeps its existing meaning. +Use an explicit collection interface view for the standard collection helper +instead; generated helper refinements never replace a native entry point. +When a vector has a native `extend`, `+=` keeps its inherited dispatch to that +member rather than gaining a new bulk-write refinement. + `setdefault(key, default)` returns the value as `self[key]` reads it, including after inserting a missing key. For an `Object`-valued map such as `PropertySet`, a generated wrapper with a valid `_obj` can be a write input, but reads and diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs index f5f94d9e..7014c895 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs @@ -6,6 +6,7 @@ use crate::meta::{ }; use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; +use super::member_plan::CollectionHelperPlan; use super::naming::{PythonProjectionContext, PythonSupportSymbol}; use super::nullability::{AnnotationSurface, ElementContainer, may_project_none}; use super::type_helpers::{ @@ -283,6 +284,7 @@ pub(super) fn protocol_helper_imports<'a>( /// read projection (or Self), never the caller's unconverted input. pub(super) fn protocol_helper_methods( iface: &InterfaceMeta, + helpers: &CollectionHelperPlan, owner_name: &str, context: &PythonProjectionContext, surface: AnnotationSurface, @@ -304,20 +306,31 @@ pub(super) fn protocol_helper_methods( ) { (Some(CollectionKind::MutableSequence), [element]) => { let element = input(element); - if is_stub { - format!( - "{indent}def extend(self, values: Iterable[{element}]) -> None: ...\n\ - {indent}def __iadd__(self, values: Iterable[{element}]) -> Self: ...\n" - ) - } else { - format!( - "\n{indent}def extend(self, values: Iterable[{element}]) -> None:\n\ - {indent} super().extend(values)\n\ - \n{indent}def __iadd__(self, values: Iterable[{element}]) -> Self:\n\ + let mut result = String::new(); + if helpers.extend { + result.push_str(&if is_stub { + format!("{indent}def extend(self, values: Iterable[{element}]) -> None: ...\n") + } else { + format!( + "\n{indent}def extend(self, values: Iterable[{element}]) -> None:\n\ + {indent} super().extend(values)\n" + ) + }); + } + if helpers.iadd { + result.push_str(&if is_stub { + format!( + "{indent}def __iadd__(self, values: Iterable[{element}]) -> Self: ...\n" + ) + } else { + format!( + "\n{indent}def __iadd__(self, values: Iterable[{element}]) -> Self:\n\ {indent} self.extend(values)\n\ {indent} return self\n" - ) + ) + }); } + result } (Some(CollectionKind::MutableMapping), [key, value]) => { let key_input = py_collection_input_type(key, context); @@ -343,28 +356,31 @@ pub(super) fn protocol_helper_methods( } else { String::new() }; - let mut result = format!( - "\n{indent}{key_variable} = TypeVar('{key_variable}', bound={key_bound})\n\ + let mut result = String::new(); + if helpers.update { + result.push_str(&format!( + "\n{indent}{key_variable} = TypeVar('{key_variable}', bound={key_bound})\n\ \n{indent}@overload\n\ {indent}def update(self, other: {mapping}, /{keywords}) -> None: ...\n\ {indent}@overload\n\ {indent}def update(self, other: {pairs} = (), /{keywords}) -> None: ...\n" - ); - if !is_stub { - // Keep runtime kwargs handling, including partial updates, in - // the existing checked mixin even for non-string key types. - result.push_str(&format!( + )); + if !is_stub { + // Keep runtime kwargs handling, including partial updates, in + // the existing checked mixin even for non-string key types. + result.push_str(&format!( "{indent}def update(self, other: {mapping} | {pairs} = (), /, **kwargs: {value_input}) -> None:\n\ {indent} super().update(other, **kwargs)\n" )); + } } let nullable = may_project_none(value) && !stock_json_receiver; - if is_stub { + if helpers.setdefault && is_stub { let default = if nullable { " = None" } else { "" }; result.push_str(&format!( "\n{indent}def setdefault(self, key: {key_input}, default: {value_input}{default}) -> {value_read}: ...\n" )); - } else { + } else if helpers.setdefault { if !nullable { result.push_str(&format!( "\n{indent}@overload\n\ 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 a4fa7717..fe627da4 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -709,6 +709,7 @@ pub fn generate_class<'a>( if let Some(iface) = collection_iface { out.push_str(&super::super::collections::protocol_helper_methods( iface, + &plan.instance.collection_helpers, &context.class_name(class), context, super::super::nullability::AnnotationSurface::Runtime, @@ -967,6 +968,7 @@ pub fn generate_class<'a>( } out.push_str(&super::super::collections::protocol_helper_methods( req_iface, + &iface_plan.collection_helpers, &symbol, context, super::super::nullability::AnnotationSurface::Runtime, 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 1c5cd44e..69605d87 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -295,6 +295,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe out.push_str(" _dynwinrt_interface_type = True\n"); out.push_str(&super::super::collections::protocol_helper_methods( iface, + &plan.collection_helpers, &iface.name, context, super::super::nullability::AnnotationSurface::Runtime, 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 aaf3915f..1704d599 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs @@ -46,7 +46,8 @@ use crate::meta::{ use crate::types::TypeMeta; use super::collections::{ - class_interface, interface_kind, observable_vector_identity, runtime_mixin, type_kind, + CollectionKind, class_interface, interface_kind, observable_vector_identity, + projected_interface_kind, runtime_mixin, type_kind, }; use super::naming::{PythonProjectionContext, to_snake_case}; use super::native_types::{FoundationType, foundation_type}; @@ -199,10 +200,38 @@ pub(crate) struct ScopePlan<'a> { group_of: HashMap<*const MethodMeta, usize>, aliases: Vec>, previous_attributes: HashMap<*const MethodMeta, String>, + defined_names: HashSet, + pub(crate) collection_helpers: CollectionHelperPlan, #[cfg(test)] fallbacks: Vec, } +/// Refine inherited helpers only when no native member owns their Python name. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct CollectionHelperPlan { + pub(crate) update: bool, + pub(crate) setdefault: bool, + pub(crate) extend: bool, + pub(crate) iadd: bool, +} + +impl CollectionHelperPlan { + fn new(iface: Option<&InterfaceMeta>, names: &HashSet) -> Self { + let kind = iface.and_then(projected_interface_kind); + let mapping = kind == Some(CollectionKind::MutableMapping); + let sequence = kind == Some(CollectionKind::MutableSequence); + let extend = sequence && !names.contains("extend"); + Self { + update: mapping && !names.contains("update"), + setdefault: mapping && !names.contains("setdefault"), + extend, + // 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__"), + } + } +} + impl<'a> ScopePlan<'a> { /// Walk members in generator order, yielding each method group once, at its /// first method. @@ -319,10 +348,15 @@ impl<'a> ClassMemberPlan<'a> { &class_abi_name_exceptions(class), ) .into_iter(); - Self { - statics: scopes.next().expect("static scope"), - instance: scopes.next().expect("instance scope"), - } + let statics = scopes.next().expect("static scope"); + let mut instance = scopes.next().expect("instance scope"); + let names = statics + .defined_names + .union(&instance.defined_names) + .cloned() + .collect(); + instance.collection_helpers = CollectionHelperPlan::new(class_interface(class), &names); + Self { statics, instance } } } @@ -397,14 +431,16 @@ pub(crate) fn interface_member_plan<'a>( interface: &'a InterfaceMeta, context: &PythonProjectionContext, ) -> ScopePlan<'a> { - plan_scopes_with_context( + let mut plan = plan_scopes_with_context( &[vec![interface]], &interface_reserved_names(interface), context, &BTreeSet::new(), ) .pop() - .expect("interface scope") + .expect("interface scope"); + plan.collection_helpers = CollectionHelperPlan::new(Some(interface), &plan.defined_names); + plan } /// Interfaces whose methods are projected as instance members of a runtime class. @@ -1065,12 +1101,32 @@ fn plan_scopes_with_context<'a>( .collect(), } }) - .collect(); + .collect::>(); + let mut defined_names = plan_groups + .iter() + .flat_map(|group| { + std::iter::once(group.name.clone()).chain( + group + .candidates + .iter() + .map(|candidate| candidate.attribute.clone()), + ) + }) + .chain(aliases.iter().map(|alias| alias.name.clone())) + .collect::>(); + for method in scopes[scope] + .iter() + .flat_map(|interface| &interface.methods) + { + insert_accessor_names(method, scopes.len() > 1 && scope == 0, &mut defined_names); + } ScopePlan { groups: plan_groups, group_of, aliases, previous_attributes, + defined_names, + collection_helpers: CollectionHelperPlan::default(), #[cfg(test)] fallbacks: fallback .iter() @@ -1346,6 +1402,239 @@ mod tests { .collect() } + fn collection_interface(mapping: bool) -> InterfaceMeta { + InterfaceMeta { + namespace: "Windows.Foundation.Collections".into(), + name: if mapping { + "IMap_String_Object" + } else { + "IVector_Object" + } + .into(), + generic_piid: Some( + if mapping { + super::super::collections::IMAP_PIID + } else { + super::super::collections::IVECTOR_PIID + } + .into(), + ), + generic_args: if mapping { + vec![TypeMeta::String, TypeMeta::Object] + } else { + vec![TypeMeta::Object] + }, + ..Default::default() + } + } + + fn helper_available(helpers: CollectionHelperPlan, name: &str) -> bool { + match name { + "update" => helpers.update, + "setdefault" => helpers.setdefault, + "extend" => helpers.extend, + "__iadd__" => helpers.iadd, + _ => panic!("unknown collection helper"), + } + } + + #[test] + fn collection_helpers_yield_to_methods_statics_properties_and_compatibility_aliases() { + for (mapping, abi, name) in [ + (true, "Update", "update"), + (true, "Setdefault", "setdefault"), + (false, "Extend", "extend"), + ] { + for owner in [ + "method", + "overloads", + "static", + "property", + "setter", + "alias", + "static_alias", + ] { + let collection = collection_interface(mapping); + let mut native = method(abi, 6, TypeMeta::I32); + let mut methods = Vec::new(); + match owner { + "property" => { + native.name = format!("get_{abi}"); + native.raw_name = native.name.clone(); + native.is_property_getter = true; + native.params.clear(); + } + "setter" => { + native.name = format!("put_{abi}"); + native.raw_name = native.name.clone(); + native.is_property_setter = true; + } + "alias" | "static_alias" => native.raw_name = "Transform".into(), + "overloads" => methods.push(method(&format!("{abi}2"), 7, TypeMeta::String)), + _ => {} + } + methods.insert(0, native); + let native_iface = interface("INative", methods); + let class = ClassMeta { + namespace: "Contoso".into(), + name: "NativeCollection".into(), + default_interface: Some(collection.clone()), + required_interfaces: if owner.starts_with("static") { + vec![] + } else { + vec![native_iface.clone()] + }, + static_interfaces: if owner.starts_with("static") { + vec![native_iface] + } else { + vec![] + }, + ..Default::default() + }; + let plan = ClassMemberPlan::new(&class, &PythonProjectionContext::default()); + assert!( + !helper_available(plan.instance.collection_helpers, name), + "{name} overwrote {owner}" + ); + if name == "extend" { + assert!(!plan.instance.collection_helpers.iadd, "{owner}"); + } + if owner == "alias" || owner == "static_alias" { + let aliases = if owner == "static_alias" { + &plan.statics.aliases + } else { + &plan.instance.aliases + }; + assert!(aliases.iter().any(|alias| alias.name == name)); + } + let peer = if mapping { "update" } else { "extend" }; + if peer != name { + assert!( + helper_available(plan.instance.collection_helpers, peer), + "{owner}" + ); + } + let context = PythonProjectionContext::default(); + let source = + super::super::generator::generate_class(&context, &class, &HashSet::new()); + let stub = + super::super::stubs::generate_class_stub(&context, &class, &HashSet::new()); + let body = |code: &str, marker: &str| { + let body = code + .split_once(marker) + .expect("generated collection declaration") + .1; + body.split_once("\nclass ") + .map_or(body, |(body, _)| body) + .to_string() + }; + for code in [ + body(&source, "\nclass NativeCollection("), + body(&stub, "\nclass NativeCollection("), + body(&stub, "\nclass NativeCollectionLike("), + ] { + let helper_signature = match name { + "update" => "def update(self, other:", + "setdefault" => "def setdefault(self, key:", + "extend" => "def extend(self, values:", + _ => unreachable!(), + }; + assert!(!code.contains(helper_signature), "{owner}: {code}"); + if name == "extend" { + assert!(!code.contains("def __iadd__("), "{owner}: {code}"); + } + } + } + } + } + + #[test] + fn interface_helpers_share_the_final_member_namespace_without_renaming_native_entries() { + for (mapping, abi, name) in [ + (true, "Update", "update"), + (true, "Setdefault", "setdefault"), + (false, "Extend", "extend"), + ] { + let mut iface = collection_interface(mapping); + let context = PythonProjectionContext::default(); + assert!(helper_available( + interface_member_plan(&iface, &context).collection_helpers, + name + )); + let mut native = method(abi, 6, TypeMeta::I32); + native.raw_name = "Transform".into(); + iface.methods.push(native); + let plan = interface_member_plan(&iface, &context); + assert!(!helper_available(plan.collection_helpers, name)); + assert_eq!(plan.aliases[0].name, name); + assert_eq!(plan.aliases[0].target, "transform"); + let source = super::super::generator::generate_interface(&context, &iface); + let stub = super::super::stubs::generate_interface_stub(&context, &iface); + assert!(source.contains(&format!(" {name} = transform\n"))); + assert!(!source.contains(&format!("def {name}(self,"))); + assert_eq!(stub.matches(&format!("def {name}(")).count(), 1); + assert!(!stub.contains(&format!("def {name}(self, other:"))); + } + } + + #[test] + fn metadata_iadd_names_keep_their_established_normalization() { + assert_eq!(to_snake_case("__iadd__"), "iadd__"); + for owner in ["method", "static", "property", "alias"] { + let mut native = method("__iadd__", 6, TypeMeta::I32); + if owner == "property" { + native.name = "get___iadd__".into(); + native.is_property_getter = true; + native.params.clear(); + } else if owner == "alias" { + native.raw_name = "Transform".into(); + } + let native_iface = interface("INative", vec![native]); + let class = ClassMeta { + default_interface: Some(collection_interface(false)), + required_interfaces: if owner == "static" { + vec![] + } else { + vec![native_iface.clone()] + }, + static_interfaces: if owner == "static" { + vec![native_iface] + } else { + vec![] + }, + ..Default::default() + }; + let plan = ClassMemberPlan::new(&class, &PythonProjectionContext::default()); + assert!(plan.instance.collection_helpers.iadd, "{owner}"); + let names = if owner == "static" { + &plan.statics.defined_names + } else { + &plan.instance.defined_names + }; + assert!(names.contains("iadd__"), "{owner}"); + assert!(!names.contains("__iadd__"), "{owner}"); + } + let names = HashSet::from(["__iadd__".to_string()]); + let helpers = CollectionHelperPlan::new(Some(&collection_interface(false)), &names); + assert!(helpers.extend && !helpers.iadd); + } + + #[test] + fn static_property_getters_do_not_claim_the_instance_helper_name() { + let mut getter = method("get_Update", 6, TypeMeta::I32); + getter.is_property_getter = true; + getter.params.clear(); + let class = ClassMeta { + default_interface: Some(collection_interface(true)), + static_interfaces: vec![interface("IStatics", vec![getter])], + ..Default::default() + }; + let plan = ClassMemberPlan::new(&class, &PythonProjectionContext::default()); + assert!(plan.instance.collection_helpers.update); + assert!(plan.statics.defined_names.contains("get_update")); + assert!(!plan.statics.defined_names.contains("update")); + } + #[test] fn python_numeric_overload_method_cmp_prefers_narrower_and_signed_ranges() { let i8 = method("Read", 6, TypeMeta::I8); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index f87e1819..dd4c39f8 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -29,8 +29,8 @@ use super::collections::{ projected_interface_kind, stock_json_class_contract, }; use super::member_plan::{ - ClassMemberPlan, MethodGroup, PlannedMember, ScopePlan, class_instance_interfaces, - interface_member_plan, + ClassMemberPlan, CollectionHelperPlan, MethodGroup, PlannedMember, ScopePlan, + class_instance_interfaces, interface_member_plan, }; use super::naming::{PythonProjectionContext, PythonSupportSymbol, is_py_reserved, to_snake_case}; use super::native_types::foundation_type; @@ -494,7 +494,14 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf if !is_protocol { out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n"); } - out.push_str(&collection_protocol_stubs(iface, context, 4, false)); + let plan = interface_member_plan(iface, context); + out.push_str(&collection_protocol_stubs( + iface, + &plan.collection_helpers, + context, + 4, + false, + )); if has_projection { out.push('\n'); if !is_protocol { @@ -573,7 +580,6 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf )); } - let plan = interface_member_plan(iface, context); let members = reorder_getters_before_setters(&iface.methods) .into_iter() .map(|method| (iface, method)); @@ -1084,14 +1090,20 @@ pub fn generate_class_stub<'a>( } 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, false)); + let iface_plan = interface_member_plan(req_iface, context); + out.push_str(&collection_protocol_stubs( + req_iface, + &iface_plan.collection_helpers, + context, + 4, + false, + )); out.push('\n'); 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", ); - let iface_plan = interface_member_plan(req_iface, context); let members = reorder_getters_before_setters(&req_iface.methods) .into_iter() .map(|method| (req_iface, method)); @@ -1160,6 +1172,7 @@ fn emit_class_instance_stubs<'a>( if let Some(collection_iface) = collection_iface { out.push_str(&collection_protocol_stubs( collection_iface, + &plan.collection_helpers, context, 4, stock_json_receiver, @@ -1314,6 +1327,7 @@ fn emit_class_instance_stubs<'a>( fn collection_protocol_stubs( iface: &InterfaceMeta, + helpers: &CollectionHelperPlan, context: &PythonProjectionContext, indent_spaces: usize, stock_json_receiver: bool, @@ -1434,6 +1448,7 @@ fn collection_protocol_stubs( }; result.push_str(&super::collections::protocol_helper_methods( iface, + helpers, &iface.name, context, AnnotationSurface::Stub, diff --git a/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs b/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs new file mode 100644 index 00000000..c1448c36 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/python_collection_member_collision_test.rs @@ -0,0 +1,624 @@ +// 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 windows_metadata::{ + MethodAttributes, MethodCallAttributes, MethodImplAttributes, ParamAttributes, Signature, Type, + TypeAttributes, TypeName, Value, writer, +}; + +const WINDOWS_WINMD: &str = + r"C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.26100.0\Windows.winmd"; +const NAMESPACE: &str = "Audit.HelperMembers"; +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .parent() + .unwrap() + .join("target") + .join(format!( + "pmc{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&root).unwrap(); + Self(root) + } +} + +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(|| "python".into()) +} + +fn success(output: Output) { + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn assert_source_diagnostics(output: Output, no_pyi: bool, invalid_consumer: bool) { + let text = format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + let fails = !no_pyi || invalid_consumer; + assert_eq!(output.status.success(), !fails, "{text}"); + let errors = text + .lines() + .filter(|line| line.contains(": error:")) + .collect::>(); + let consumer = errors + .iter() + .filter(|line| line.starts_with("invalid.py:")) + .collect::>(); + assert_eq!( + consumer.len(), + if invalid_consumer { 5 } else { 0 }, + "{text}" + ); + for (line, code) in consumer.iter().zip([ + "[arg-type]", + "[arg-type]", + "[arg-type]", + "[arg-type]", + "[operator]", + ]) { + assert!(line.ends_with(code), "{text}"); + } + let errors = errors + .into_iter() + .filter(|line| !line.starts_with("invalid.py:")) + .collect::>(); + if no_pyi { + assert!(errors.is_empty(), "{text}"); + return; + } + let expected = [ + ( + "audit__helper_members__native_vector.pyi", + "Return type \"int\" of \"extend\"", + ), + ( + "audit__helper_members__native_vector.pyi", + "Argument 1 of \"extend\"", + ), + ( + "audit__helper_members__native_property_map.pyi", + "Signature of \"update\"", + ), + ( + "audit__helper_members__native_map.pyi", + "Signature of \"update\"", + ), + ( + "audit__helper_members__native_map.pyi", + "Signature of \"setdefault\"", + ), + ]; + assert_eq!(errors.len(), expected.len(), "{text}"); + for (file, message) in expected { + assert_eq!( + errors + .iter() + .filter(|line| { + line.contains(file) && line.contains(message) && line.ends_with("[override]") + }) + .count(), + 1, + "{text}" + ); + } +} + +fn attribute( + file: &mut writer::File, + owner: writer::HasAttribute, + name: &str, + types: Vec, + values: Vec, +) { + let attribute = file.TypeRef("Windows.Foundation.Metadata", name); + let constructor = file.MemberRef( + ".ctor", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types, + }, + writer::MemberRefParent::TypeRef(attribute), + ); + file.Attribute( + owner, + writer::AttributeType::MemberRef(constructor), + &values + .into_iter() + .map(|value| (String::new(), value)) + .collect::>(), + ); +} + +fn native_interface( + file: &mut writer::File, + name: &str, + id: u32, + methods: &[(&str, Option<&str>, bool)], +) { + let definition = file.TypeDef( + NAMESPACE, + name, + writer::TypeDefOrRef::default(), + TypeAttributes::Public + | TypeAttributes::Interface + | TypeAttributes::Abstract + | TypeAttributes::WindowsRuntime, + ); + attribute( + file, + writer::HasAttribute::TypeDef(definition), + "GuidAttribute", + vec![ + Type::U32, + Type::U16, + Type::U16, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + ], + vec![ + Value::U32(id), + Value::U16(0x7342), + Value::U16(0x4830), + Value::U8(0x87), + Value::U8(0xa1), + Value::U8(0x11), + Value::U8(0x12), + Value::U8(0x13), + Value::U8(0x14), + Value::U8(0x15), + Value::U8(0x16), + ], + ); + for &(name, alias, property) in methods { + let mut attributes = MethodAttributes::Public + | MethodAttributes::Abstract + | MethodAttributes::Virtual + | MethodAttributes::NewSlot; + if property { + attributes |= MethodAttributes::SpecialName; + } + let method = file.MethodDef( + name, + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::I32, + types: if property { vec![] } else { vec![Type::I32] }, + }, + attributes, + MethodImplAttributes::default(), + ); + if !property { + file.Param("value", 1, ParamAttributes::In); + } + if let Some(alias) = alias { + attribute( + file, + writer::HasAttribute::MethodDef(method), + "OverloadAttribute", + vec![Type::String], + vec![Value::Utf8(alias.into())], + ); + } + } +} + +fn collection_class(file: &mut writer::File, name: &str, native: &str, vector: bool) { + let object = file.TypeRef("System", "Object"); + let class = file.TypeDef( + NAMESPACE, + name, + writer::TypeDefOrRef::TypeRef(object), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + let default = file.InterfaceImpl(class, &Type::named(NAMESPACE, native)); + attribute( + file, + writer::HasAttribute::InterfaceImpl(default), + "DefaultAttribute", + vec![], + vec![], + ); + file.InterfaceImpl( + class, + &Type::Name(TypeName { + namespace: "Windows.Foundation.Collections".into(), + name: if vector { "IVector`1" } else { "IMap`2" }.into(), + generics: if vector { + vec![Type::Object] + } else { + vec![Type::String, Type::Object] + }, + }), + ); +} + +fn metadata(path: &Path) { + let mut file = writer::File::new("CollectionMemberCollisions"); + native_interface( + &mut file, + "IMapNative", + 0x4a219101, + &[ + ("Update", None, false), + ("Transform", Some("Setdefault"), false), + ], + ); + native_interface( + &mut file, + "IVectorNative", + 0x4a219102, + &[ + ("Extend", None, false), + ("Transform", Some("__iadd__"), false), + ], + ); + native_interface( + &mut file, + "IPropertyNative", + 0x4a219103, + &[("get_Update", None, true)], + ); + native_interface(&mut file, "IViews", 0x4a219104, &[]); + for (name, collection, arguments) in [ + ("GetMapping", "IMap`2", vec![Type::String, Type::Object]), + ("GetVector", "IVector`1", vec![Type::Object]), + ] { + file.MethodDef( + name, + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Name(TypeName { + namespace: "Windows.Foundation.Collections".into(), + name: collection.into(), + generics: arguments, + }), + types: vec![], + }, + MethodAttributes::Public + | MethodAttributes::Abstract + | MethodAttributes::Virtual + | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + } + collection_class(&mut file, "NativeMap", "IMapNative", false); + collection_class(&mut file, "NativeVector", "IVectorNative", true); + collection_class(&mut file, "NativePropertyMap", "IPropertyNative", false); + fs::write(path, file.into_stream()).unwrap(); +} + +fn generate(fixture: &Fixture, metadata: &Path, no_pyi: bool) -> PathBuf { + let package = fixture.0.join("views"); + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command + .args(["generate", "--winmd"]) + .arg(metadata) + .args([ + "--ref", + WINDOWS_WINMD, + "--namespace", + NAMESPACE, + "--lang", + "py", + "--output", + ]) + .arg(&package); + if no_pyi { + command.arg("--no-pyi"); + } + success(command.output().unwrap()); + package +} + +const CONSUMER: &str = r#"from typing import assert_type +from dynwinrt import DynWinRTValue +from views.audit__helper_members__native_map import NativeMap, NativeMapLike, IMap_String_Object as EmbeddedMap +from views.audit__helper_members__native_vector import NativeVector, NativeVectorLike +from views.audit__helper_members__native_property_map import NativePropertyMap, NativePropertyMapLike +from views.windows__foundation__collections__i_map_string_object import IMap_String_Object + +def native(mapping: NativeMap, vector: NativeVector, property_map: NativePropertyMap, + mapping_like: NativeMapLike, vector_like: NativeVectorLike, + property_like: NativePropertyMapLike) -> None: + assert_type(mapping.update(23), int) + assert_type(mapping.setdefault(23), int) + assert_type(mapping.transform(23), int) + assert_type(vector.extend(23), int) + assert_type(vector.iadd__(23), int) + assert_type(vector.transform(23), int) + assert_type(property_map.update, int) + assert_type(mapping_like.update(23), int) + assert_type(mapping_like.setdefault(23), int) + assert_type(vector_like.extend(23), int) + assert_type(vector_like.iadd__(23), int) + assert_type(property_like.update, int) + +def helpers(mapping: IMap_String_Object, embedded: EmbeddedMap, raw: DynWinRTValue) -> None: + assert_type(mapping.update({"entry": raw}), None) + assert_type(embedded.update(entry=raw), None) + assert_type(mapping.setdefault("entry", raw), DynWinRTValue | None) + assert_type(embedded.setdefault("entry", raw), DynWinRTValue | None) +"#; + +const INLINE_CONSUMER: &str = r#"from typing import assert_type +from dynwinrt import DynWinRTValue +from views.audit__helper_members__native_map import NativeMap, IMap_String_Object as EmbeddedMap +from views.audit__helper_members__native_vector import NativeVector +from views.audit__helper_members__native_property_map import NativePropertyMap +from views.windows__foundation__collections__i_map_string_object import IMap_String_Object + +def native(mapping: NativeMap, vector: NativeVector, property_map: NativePropertyMap) -> None: + assert_type(mapping.update(23), int) + assert_type(mapping.setdefault(23), int) + assert_type(mapping.transform(23), int) + assert_type(vector.extend(23), int) + assert_type(vector.iadd__(23), int) + assert_type(vector.transform(23), int) + assert_type(property_map.update, int) + +def helpers(mapping: IMap_String_Object, embedded: EmbeddedMap, raw: DynWinRTValue) -> None: + assert_type(mapping.update({"entry": raw}), None) + assert_type(embedded.update(entry=raw), None) + assert_type(mapping.setdefault("entry", raw), DynWinRTValue | None) + assert_type(embedded.setdefault("entry", raw), DynWinRTValue | None) +"#; + +const INVALID_CONSUMER: &str = r#"from dynwinrt import DynWinRTValue +from views.audit__helper_members__native_map import NativeMap +from views.audit__helper_members__native_vector import NativeVector +from views.audit__helper_members__native_property_map import NativePropertyMap + +def invalid(mapping: NativeMap, vector: NativeVector, + property_map: NativePropertyMap, raw: DynWinRTValue) -> None: + mapping.update({"entry": raw}) + mapping.setdefault(raw) + vector.extend([raw]) + vector.iadd__([raw]) + property_map.update(raw) +"#; + +const RUNTIME: &str = r#"import ast +from pathlib import Path +from dynwinrt import ( + DynWinRTImplementation, DynWinRTImplementationMethod, DynWinRTInterfacePlan, + DynWinRTMethodSig, DynWinRTType, DynWinRTValue, RoApartment, WinGUID, + projected_lifetime_scope, +) +from views.audit.helper_members import NativeMap, NativeVector, NativePropertyMap +from views.windows.foundation.collections import IMap_String_Object, IVector_Object +from views.audit__helper_members__native_map import IMap_String_Object as EmbeddedMap + +T = DynWinRTType +def plan(name, iid, methods): + interface = T.register_interface(name, iid) + definitions = [] + for slot, method in enumerate(methods, 6): + member = method[0] + if len(method) == 2: + signature = method[1] + else: + signature = DynWinRTMethodSig() + for typ in method[1]: + signature = signature.add_in(typ) + if method[2] is not None: + signature = signature.add_out(method[2]) + interface = interface.add_method(member, signature) + definitions.append(DynWinRTImplementationMethod(member, slot, signature)) + return DynWinRTInterfacePlan.create(name, interface, definitions) + +map_view = T.parameterized(WinGUID.parse("e480ce40-a338-4ada-adcf-272272e48cb9"), [T.hstring(), T.object()]) +map_iid = T.parameterized(WinGUID.parse("3c2925fe-8519-45c1-aa79-197b6718c1c1"), [T.hstring(), T.object()]).iid() +map_plan = plan("Audit.HelperMembers.IMap", map_iid, [ + ("Lookup", [T.hstring()], T.object()), ("get_Size", [], T.u32_type()), + ("HasKey", [T.hstring()], T.bool_type()), ("GetView", [], map_view), + ("Insert", [T.hstring(), T.object()], T.bool_type()), ("Remove", [T.hstring()], None), + ("Clear", [], None), +]) +vector_view = T.parameterized(WinGUID.parse("bbe1fa4c-b0e3-4583-baef-1f1b2e483e56"), [T.object()]) +vector_iid = T.parameterized(WinGUID.parse("913337e9-11a1-4345-a3a2-4e7f956e222d"), [T.object()]).iid() +vector_plan = plan("Audit.HelperMembers.IVector", vector_iid, [ + ("GetAt", [T.u32_type()], T.object()), ("get_Size", [], T.u32_type()), + ("GetView", [], vector_view), + ("IndexOf", DynWinRTMethodSig().add_in(T.object()).add_out(T.u32_type()).add_out(T.bool_type())), + ("SetAt", [T.u32_type(), T.object()], None), + ("InsertAt", [T.u32_type(), T.object()], None), ("RemoveAt", [T.u32_type()], None), + ("Append", [T.object()], None), ("RemoveAtEnd", [], None), ("Clear", [], None), + ("GetMany", DynWinRTMethodSig().add_in(T.u32_type()).add_out_fill(T.array_type(T.object())).add_out(T.u32_type())), + ("ReplaceAll", [T.array_type(T.object())], None), +]) +calls = [] +store = {} +with RoApartment(1), projected_lifetime_scope(): + def map_dispatch(interface, slot, args): + if interface == 0: + calls.append((slot, args[0].to_int() if args else None)) + return [DynWinRTValue.from_i32((slot - 5) * 100 + (args[0].to_int() if args else 1))] + key = args[0].to_string() if args else None + if slot == 6: + return [store[key]] + if slot == 7: + return [DynWinRTValue.from_u32(len(store))] + if slot == 8: + return [DynWinRTValue.from_bool(key in store)] + if slot == 10: + replaced = key in store + store[key] = args[1].cast(WinGUID.parse("00000000-0000-0000-c000-000000000046")) + return [DynWinRTValue.from_bool(replaced)] + if slot == 11: + del store[key] + return [] + if slot == 12: + store.clear() + return [] + raise AssertionError(f"unexpected map slot {slot}") + + native_map = plan("Audit.HelperMembers.IMapNative", + WinGUID.parse("4a219101-7342-4830-87a1-111213141516"), + [("Update", [T.i32_type()], T.i32_type()), ("Transform", [T.i32_type()], T.i32_type())]) + owner = DynWinRTImplementation.create([native_map, map_plan], map_dispatch) + source = owner.to_value() + mapping = NativeMap._from_native(source) + assert mapping.update(23) == 123 and calls == [(6, 23)] + assert mapping.setdefault(23) == 223 + assert mapping.transform(24) == 224 + assert calls == [(6, 23), (7, 23), (7, 24)] + assert not source.is_released() + ordinary = IVector_Object.create([]) + assert ordinary.extend([source]) is None + assert ordinary.__iadd__([source]) is ordinary + result = ordinary[0] + assert result.identity_raw() == source.identity_raw() + result.release() + for view_type in (IMap_String_Object, EmbeddedMap): + view = view_type.from_value(source) + assert view.update({"entry": source}) is None + result = view.setdefault("default", source) + assert isinstance(result, DynWinRTValue) + assert result.identity_raw() == source.identity_raw() + result.release() + + native_vector = plan("Audit.HelperMembers.IVectorNative", + WinGUID.parse("4a219102-7342-4830-87a1-111213141516"), + [("Extend", [T.i32_type()], T.i32_type()), ("Transform", [T.i32_type()], T.i32_type())]) + def vector_dispatch(interface, slot, args): + assert interface == 0 + calls.append((slot, args[0].to_int())) + return [DynWinRTValue.from_i32((slot - 5) * 100 + args[0].to_int())] + vector_owner = DynWinRTImplementation.create([native_vector, vector_plan], vector_dispatch) + vector_source = vector_owner.to_value() + vector = NativeVector._from_native(vector_source) + assert vector.extend(23) == 123 + assert vector.iadd__(23) == 223 + assert vector.transform(24) == 224 + assert calls[-3:] == [(6, 23), (7, 23), (7, 24)] + assert vector.__iadd__(25) is vector + assert calls[-1] == (6, 25) + + property_plan = plan("Audit.HelperMembers.IPropertyNative", + WinGUID.parse("4a219103-7342-4830-87a1-111213141516"), + [("get_Update", [], T.i32_type())]) + property_owner = DynWinRTImplementation.create([property_plan, map_plan], map_dispatch) + property_source = property_owner.to_value() + property_map = NativePropertyMap._from_native(property_source) + assert property_map.update == 101 and calls[-1] == (6, None) + + for cls, names in ( + (NativeMap, ("update", "setdefault")), + (NativeVector, ("extend", "iadd__", "__iadd__")), + (NativePropertyMap, ("update",)), + ): + path = Path(cls.__init__.__code__.co_filename) + node = next(node for node in ast.parse(path.read_text(encoding="utf-8")).body + if isinstance(node, ast.ClassDef) and node.name == cls.__name__) + for name in names: + definitions = [member for member in node.body if isinstance(member, ast.FunctionDef) and member.name == name] + assert len(definitions) <= 1, (cls, name, len(definitions)) + store.clear() +assert source.is_released() and vector_source.is_released() and property_source.is_released() +print("native-member-collisions-ok", flush=True) +"#; + +#[test] +fn native_collection_members_keep_their_names_dispatch_and_aliases_in_both_output_modes() { + if !Path::new(WINDOWS_WINMD).is_file() { + eprintln!("Skipping collection member SDK test: Windows.winmd unavailable."); + return; + } + for no_pyi in [false, true] { + let fixture = Fixture::new(); + let metadata_path = fixture.0.join("Members.winmd"); + metadata(&metadata_path); + generate(&fixture, &metadata_path, no_pyi); + let runtime = Command::new(python()) + .args(["-c", "from dynwinrt import DynWinRTImplementation"]) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + runtime + || std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref() != Ok("1") + ); + if runtime { + fs::write(fixture.0.join("runtime.py"), RUNTIME).unwrap(); + success( + Command::new(python()) + .args(["-B", "runtime.py"]) + .current_dir(&fixture.0) + .output() + .unwrap(), + ); + } + let mypy = Command::new(python()) + .args(["-m", "mypy", "--version"]) + .output() + .is_ok_and(|output| output.status.success()); + assert!(mypy || std::env::var("DYNWINRT_REQUIRE_MYPY").as_deref() != Ok("1")); + if mypy { + fs::write( + fixture.0.join("consumer.py"), + if no_pyi { INLINE_CONSUMER } else { CONSUMER }, + ) + .unwrap(); + let mut command = Command::new(python()); + command + .args([ + "-B", + "-m", + "mypy", + "--strict", + "--follow-imports=silent", + "--no-incremental", + "consumer.py", + ]) + .current_dir(&fixture.0); + if std::env::var("DYNWINRT_TEST_INSTALLED_RUNTIME").as_deref() == Ok("1") { + command.env_remove("MYPYPATH"); + } else { + command.env( + "MYPYPATH", + Path::new(env!("CARGO_MANIFEST_DIR")).join(r"..\..\bindings\py"), + ); + } + // Main already reports these exact nominal ABC overrides. + assert_source_diagnostics(command.output().unwrap(), no_pyi, false); + fs::write(fixture.0.join("invalid.py"), INVALID_CONSUMER).unwrap(); + command.arg("invalid.py"); + assert_source_diagnostics(command.output().unwrap(), no_pyi, true); + } + } +}