Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,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
Expand Down
25 changes: 25 additions & 0 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,31 @@ 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.

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
`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.

Sequence containment, `index()`, `count()`, and `remove()`, mapping equality,
and value/item-view membership compare WinRT references by canonical COM
identity, including different generated class/interface views and raw
Expand Down
7 changes: 7 additions & 0 deletions bindings/py/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -699,6 +699,13 @@ class _WinRTMutableMappingMixin(_WinRTMappingMixin, _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)
Expand Down
51 changes: 51 additions & 0 deletions bindings/py/tests/test_object_value_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""

import gc
import sys
from collections.abc import Mapping, MutableMapping
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
Expand Down Expand Up @@ -724,6 +725,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
Expand Down
171 changes: 171 additions & 0 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ 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::{
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";
Expand Down Expand Up @@ -232,6 +239,170 @@ 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<Item = &'a InterfaceMeta>,
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(
iface: &InterfaceMeta,
helpers: &CollectionHelperPlan,
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);
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);
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 = 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!(
"{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 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 if helpers.setdefault {
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::*;
Expand Down
26 changes: 26 additions & 0 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -701,6 +706,18 @@ 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,
stock_json_receiver,
4,
));
}

// Auto-generate close() if class implements IClosable
const ICLOSABLE_IID: &str = "30d5a829-7fa4-4026-83bb-d75bae4ea99e";
if class
Expand Down Expand Up @@ -949,6 +966,15 @@ pub fn generate_class<'a>(
py_runtime_symbol(context, &iterable_identity, &iterable_name)
));
}
out.push_str(&super::super::collections::protocol_helper_methods(
req_iface,
&iface_plan.collection_helpers,
&symbol,
context,
super::super::nullability::AnnotationSurface::Runtime,
false,
4,
));
}
out
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,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 (
Expand Down Expand Up @@ -254,8 +254,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
)
}
Expand Down
14 changes: 14 additions & 0 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -288,6 +293,15 @@ 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,
false,
4,
));
out.push_str(&implementation.factory_body);
if !iface.iid.is_empty() || iface.generic_piid.is_some() {
out.push_str(&format!(
Expand Down
Loading
Loading