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
4 changes: 2 additions & 2 deletions bindings/py/dynwinrt.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ _Handlers_contra = TypeVar("_Handlers_contra", contravariant=True)


class _DynWinRTProjector(Protocol[_Projected_co]):
@classmethod
def from_value(cls, obj: "DynWinRTValue") -> _Projected_co: ...
# Models the factory object, whose from_value method is already bound.
def from_value(self, obj: "DynWinRTValue") -> _Projected_co: ...


class _DynWinRTProjectableClass: ...
Expand Down
30 changes: 29 additions & 1 deletion tools/dynwinrt-codegen/python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,37 @@ implement standard `collections.abc` protocols, flags use `enum.IntFlag`, and
compatible method inputs accept native Python sequences, mappings, `bytes`,
`bytearray`, `uuid.UUID`, `datetime.datetime`, and `datetime.timedelta`.

Interface protocols describe native **instances**, including their canonical
identity and methods, not wrapper factories. For example, `StorageFile` can be
passed to an `IStorageFile` parameter without defining `from_value`.
`IStorageFile.from_value(raw)` and `value.as_interface(IStorageFile)` remain
available for explicit, IID-checked projection. Inherited `from_value` factories
retain the receiving interface subclass: `TaggedBuffer.from_value(raw)` and
`value.as_interface(TaggedBuffer)` return `TaggedBuffer`, not `IBuffer`.
Independent static factories such as `IBuffer.from_bytes` keep their declared
base-interface result.

WinRT `Object` inputs accept a `DynWinRTValue` or a projected native wrapper
whose `_obj` is a `DynWinRTValue`, including interface views and runtime-class
`Like` views. They do not implicitly box arbitrary Python objects, strings, or
`None`; use an explicitly boxed or null `DynWinRTValue` instead. `Object`
outputs remain `DynWinRTValue | None`. Context managers retain the entered
instance's type (`Self`), including derived wrappers passed through a base
`Like` protocol, and still close the object without suppressing exceptions.

Collection subscripts use the input contract for keys and values: for example,
`properties["uri"] = uri` accepts a generated `Uri`, while reading the item still
returns `DynWinRTValue | None`. Sequence item assignment, slice assignment, and
`insert` likewise accept projected inputs without changing their read types;
integer indices take one item and slices take an iterable of items. Existing
nullable `collections.abc` contracts remain unchanged. To pass a native null
reference, use `DynWinRTValue.null_value()`, not implicit `None` boxing.

The output directory belongs to codegen; do not store handwritten files in it.
After changing metadata files, SDK versions, or reference inputs, regenerate the
complete output.
complete output. Regenerate with the updated generator to pick up these
consumer typing contracts, and use the matching runtime package and its stubs.
No runtime API change or consumer cast is required.

### Closed-generic stub migration

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ from ._runtime import (
TYPE_CHECKING, UUID, WinGUID, datetime, timedelta,
DynWinRTType, DynWinRTMethodSig, DynWinRTValue, DynWinRTArray,
DynWinRTStruct, DynWinRtDelegate, DynWinRTOverrideInterface,
_property, _weakref_ref,
_DynWinRTObject, _property, _weakref_ref,
_dynwinrt_array, _dynwinrt_bind_overload, _dynwinrt_can_cast, _dynwinrt_create_delegate,
_dynwinrt_datetime_to_ticks, _dynwinrt_delegate, _dynwinrt_enum, _dynwinrt_guid,
_dynwinrt_map, _dynwinrt_new_vector, _dynwinrt_ticks_to_datetime,
Expand All @@ -64,7 +64,7 @@ from collections.abc import (
Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence,
)
from datetime import datetime, timedelta
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Protocol
from uuid import UUID
from weakref import ref as _weakref_ref
from dynwinrt import (
Expand Down Expand Up @@ -127,7 +127,8 @@ def _dynwinrt_can_cast(value, iid):

pub fn generate_runtime_support_module() -> String {
format!(
"{HEADER}{FUTURE_ANNOTATIONS}{RUNTIME_SUPPORT_BODY}{}",
"{HEADER}{FUTURE_ANNOTATIONS}{RUNTIME_SUPPORT_BODY}{}{}",
super::shared::NATIVE_OBJECT_PROTOCOL,
super::implementation::HELPERS
)
}
Expand Down
2 changes: 1 addition & 1 deletion tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1078,7 +1078,7 @@ mod tests {
);

assert!(code.contains(
"def write_async(self, buffer: 'DynWinRTValue') -> WinRTCoroutineWithProgress[int, int]:"
"def write_async(self, buffer: 'DynWinRTValue | _DynWinRTObject') -> WinRTCoroutineWithProgress[int, int]:"
));
assert!(code.contains("return _dynwinrt_track_projected(_DynWinRTAsyncWithProgress("));
assert!(code.contains("'WinRTAsyncWithProgress')"));
Expand Down
7 changes: 7 additions & 0 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@

use crate::meta::MethodMeta;

pub(super) const NATIVE_OBJECT_PROTOCOL: &str = "

class _DynWinRTObject(Protocol):
@property
def _obj(self) -> DynWinRTValue: ...
";

/// Reorder methods so that property getters always come before their matching setters.
/// Python requires `@property` to appear before `@prop.setter`.
pub(crate) fn reorder_getters_before_setters(methods: &[MethodMeta]) -> Vec<&MethodMeta> {
Expand Down
107 changes: 74 additions & 33 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,11 @@ from ._typing import (
Callable, Iterable, Iterator, Mapping, MutableMapping, MutableSequence, Sequence,
UUID, WinGUID, datetime, overload, timedelta,
DynWinRTType, DynWinRTValue, DynWinRTArray, DynWinRTStruct, DynWinRtDelegate,
_DynWinRTProjector,
_DynWinRTObject, _DynWinRTProjector,
)\n";
const NATIVE_OBJECT_STUB: &str = "\
\x20 @builtins.property\n\
\x20 def _obj(self) -> DynWinRTValue: ...\n";
const ASYNC_IMPORT_LINE: &str = "from dynwinrt import WinRTCoroutine, WinRTCoroutineWithProgress\n";

pub fn generate_typing_support_module() -> String {
Expand All @@ -59,7 +62,7 @@ from collections.abc import (\n\
MutableSequence as MutableSequence, Sequence as Sequence,\n\
)\n\
from datetime import datetime as datetime, timedelta as timedelta\n\
from typing import overload as overload\n\
from typing import Protocol, overload as overload\n\
from uuid import UUID as UUID\n\
from dynwinrt import (\n\
DynWinRTType as DynWinRTType, DynWinRTValue as DynWinRTValue,\n\
Expand All @@ -68,7 +71,8 @@ from dynwinrt import (\n\
_DynWinRTProjector as _DynWinRTProjector,\n\
_DynWinRTProjectableClass as _DynWinRTProjectableClass,\n\
_DynWinRTRuntimeClass as _DynWinRTRuntimeClass,\n\
)\n"
)\n{}",
super::shared::NATIVE_OBJECT_PROTOCOL,
)
}

Expand Down Expand Up @@ -252,21 +256,27 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
return out;
}
let implementation = super::implementation::project(context, iface);
let collection_kind = interface_kind(iface);
let is_protocol = collection_kind.is_none();
let has_projection = !iface.iid.is_empty() || iface.generic_piid.is_some();
let has_factory = implementation.supported || (is_protocol && has_projection);
let is_buffer =
crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid);

let mut out = String::new();
out.push_str(HEADER);
out.push_str(FUTURE_ANNOTATIONS);
out.push_str(IMPORT_LINE);
if has_factory {
out.push_str("from abc import ABCMeta\n");
}
if implementation.supported {
out.push_str(super::implementation::IMPORTS);
out.push_str("from abc import ABCMeta\n");
out.push_str("from typing import TypeVar\nfrom dynwinrt import _DynWinRTImplementationFactory\n_ImplementationHandlers = TypeVar('_ImplementationHandlers')\n");
if context.is_packaged() {
out.push_str("from typing import TypeAlias\nfrom ._implementation_types import _ImplementationPair as _PackageImplementationPair\n");
}
}
let collection_kind = interface_kind(iface);
let is_protocol = collection_kind.is_none();
out.push_str("from typing import Protocol, Self, TypeVar\n");
if methods_have_async_output(iface.methods.iter()) {
out.push_str(ASYNC_IMPORT_LINE);
Expand Down Expand Up @@ -402,16 +412,34 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
}

out.push_str(&implementation.declarations);
let implementation_metaclass = format!("_{}ImplementationFactory", iface.name);
if implementation.supported {
if context.is_packaged() {
let factory_metaclass = if implementation.supported {
format!("_{}ImplementationFactory", iface.name)
} else {
format!("_{}Factory", iface.name)
};
if implementation.supported && context.is_packaged() {
out.push_str(&format!(
"\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{handler}], {handler}]\n",
handler = context.implementation_helper_name(iface, "handlers", "Handlers")
));
}
if has_factory {
out.push_str(&format!("\nclass {factory_metaclass}(ABCMeta):\n"));
if is_protocol && has_projection {
// Bind the result to the receiving interface class, not its metaclass.
out.push_str(
" def from_value(cls: type[_InterfaceT], obj: DynWinRTValue) -> _InterfaceT: ...\n",
);
}
if is_buffer {
out.push_str(&format!(
"\n_ImplementationPair: TypeAlias = tuple[_DynWinRTImplementationFactory[{handler}], {handler}]\n",
handler = context.implementation_helper_name(iface, "handlers", "Handlers")
" def from_bytes(cls, data: bytes | bytearray) -> {}: ...\n",
iface.name
));
}
out.push_str(&format!("\nclass {implementation_metaclass}(ABCMeta):\n"));
out.push_str(&implementation.factory_declarations);
if implementation.supported {
out.push_str(&implementation.factory_declarations);
}
}

let collection_base =
Expand Down Expand Up @@ -443,8 +471,8 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
}
let mut seen_bases = HashSet::new();
bases.retain(|base| seen_bases.insert(base.clone()));
if implementation.supported {
bases.push(format!("metaclass={implementation_metaclass}"));
if has_factory {
bases.push(format!("metaclass={factory_metaclass}"));
}
if bases.is_empty() {
out.push_str(&format!("\nclass {}:\n", iface.name));
Expand All @@ -459,27 +487,26 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
},
" ",
));
out.push_str(NATIVE_OBJECT_STUB);
if !implementation.supported {
out.push_str(&implementation.factory_declarations);
}
if !is_protocol {
out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n");
}
out.push_str(&collection_protocol_stubs(iface, context, 4));
if !iface.iid.is_empty() || iface.generic_piid.is_some() {
if has_projection {
out.push('\n');
out.push_str(" @classmethod\n");
out.push_str(" def from_value(cls, obj: DynWinRTValue) -> Self: ...\n");
if !is_protocol {
out.push_str(" @classmethod\n");
out.push_str(" def from_value(cls, obj: DynWinRTValue) -> Self: ...\n");
}
out.push_str(
" def as_interface(self, interface_class: _DynWinRTProjector[_InterfaceT]) -> _InterfaceT: ...\n",
);
}
if crate::codegen::winrt::is_ibuffer_interface(&iface.namespace, &iface.name, &iface.iid) {
out.push_str(
"\n @staticmethod\n\
\x20 def from_bytes(data: bytes | bytearray) -> 'IBuffer': ...\n\
\x20 def to_bytes(self) -> bytes: ...\n",
);
if is_buffer {
out.push_str("\n def to_bytes(self) -> bytes: ...\n");
}

// IVector<T> / IMap<K,V> create()
Expand Down Expand Up @@ -1045,6 +1072,7 @@ pub fn generate_class_stub(
out.push_str(&format!("\nclass {symbol}:\n"));
}
out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n");
out.push_str(NATIVE_OBJECT_STUB);
out.push_str(&collection_protocol_stubs(req_iface, context, 4));
out.push('\n');
out.push_str(" @classmethod\n");
Expand Down Expand Up @@ -1102,6 +1130,9 @@ fn emit_class_instance_stubs(
has_closable: bool,
) -> String {
let mut out = String::new();
if super::has_native_projector(class) {
out.push_str(NATIVE_OBJECT_STUB);
}
if let Some(collection_iface) = collection_iface {
out.push_str(&collection_protocol_stubs(collection_iface, context, 4));
}
Expand Down Expand Up @@ -1205,10 +1236,7 @@ fn emit_class_instance_stubs(
if has_closable {
out.push('\n');
out.push_str(" def close(self) -> None: ...\n");
out.push_str(&format!(
" def __enter__(self) -> '{}': ...\n",
context.class_name(class)
));
out.push_str(" def __enter__(self) -> Self: ...\n");
out.push_str(
" def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> Literal[False]: ...\n",
);
Expand Down Expand Up @@ -1263,6 +1291,11 @@ fn collection_protocol_stubs(
.first()
.map(|typ| super::type_helpers::py_return_type_safe(Some(typ), context))
.unwrap_or_else(|| "object".to_string());
let item_input = iface
.generic_args
.first()
.map(|typ| super::type_helpers::py_collection_input_type(typ, context))
.unwrap_or_else(|| "object".to_string());
match kind {
super::collections::CollectionKind::Iterable => {
format!("\n{indent}def __iter__(self) -> Iterator[{item_type}]: ...\n")
Expand All @@ -1283,9 +1316,12 @@ fn collection_protocol_stubs(
);
if kind == super::collections::CollectionKind::MutableSequence {
result.push_str(&format!(
"{indent}def __setitem__(self, index: int | slice, value: {item_type} | Iterable[{item_type}]) -> None: ...\n\
"{indent}@overload\n\
{indent}def __setitem__(self, index: int, value: {item_input}) -> None: ...\n\
{indent}@overload\n\
{indent}def __setitem__(self, index: slice, value: Iterable[{item_input}]) -> None: ...\n\
{indent}def __delitem__(self, index: int | slice) -> None: ...\n\
{indent}def insert(self, index: int, value: {item_type}) -> None: ...\n"
{indent}def insert(self, index: int, value: {item_input}) -> None: ...\n"
));
}
result
Expand All @@ -1301,12 +1337,17 @@ fn collection_protocol_stubs(
let mut result = format!(
"\n{indent}def __len__(self) -> int: ...\n\
{indent}def __iter__(self) -> Iterator[{key_type}]: ...\n\
{indent}def __getitem__(self, key: {key_type}) -> {value_type}: ...\n"
{indent}def __getitem__(self, key: {item_input}) -> {value_type}: ...\n"
);
if kind == super::collections::CollectionKind::MutableMapping {
let value_input = iface
.generic_args
.get(1)
.map(|typ| super::type_helpers::py_collection_input_type(typ, context))
.unwrap_or_else(|| "object".to_string());
result.push_str(&format!(
"{indent}def __setitem__(self, key: {key_type}, value: {value_type}) -> None: ...\n\
{indent}def __delitem__(self, key: {key_type}) -> None: ...\n"
"{indent}def __setitem__(self, key: {item_input}, value: {value_input}) -> None: ...\n\
{indent}def __delitem__(self, key: {item_input}) -> None: ...\n"
));
}
result
Expand Down
Loading
Loading