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
6 changes: 4 additions & 2 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -565,16 +565,18 @@ jobs:
--codegen $env:DYNWINRT_CODEGEN --runtime-wheel $wheel[0].FullName `
--uv (Resolve-Path target\python-layout-tools\Scripts\uv.exe).Path `
--work-dir (Join-Path $env:RUNNER_TEMP 'python-src-layout')
- name: Test generated implementation and overload identities
- name: Test generated implementations, overloads, and stream contexts
shell: pwsh
run: |
$env:DYNWINRT_TEST_PYTHON = (Resolve-Path .\bindings\py\.venv\Scripts\python.exe).Path
$env:DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME = '1'
$env:DYNWINRT_REQUIRE_MYPY = '1'
cargo test -p dynwinrt-codegen `
--test implementation_naming_test `
--test python_constructor_diagnostics_test `
--test python_overload_legacy_compat_test `
--test python_released_implementation_test
--test python_released_implementation_test `
--test python_context_manager_typing_test
- name: Test generated collection protocols
shell: pwsh
run: |
Expand Down
43 changes: 40 additions & 3 deletions bindings/py/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -792,9 +792,46 @@ WinRT is never initialized implicitly. A call on a thread without an apartment
raises `OSError` with `CO_E_NOTINITIALIZED` in `error.winerror`; its message
explains how to open one.

Generated runtime classes that implement `IClosable` support `with` and an
idempotent `close()` method. Prefer deterministic cleanup instead of relying on
Python garbage collection.
Generated runtime classes that implement `IClosable`, and interfaces whose
WinMD required-interface closure includes it, support `with` and an idempotent
`close()` helper. This includes `IRandomAccessStream`, `IInputStream`,
`IOutputStream`, and `IRandomAccessStreamWithContentType`; regenerate bindings
to use the interface helpers. Existing concrete classes such as `DataWriter`
and `InMemoryRandomAccessStream` keep the same behavior.

Generate and install the project before using this example:

```powershell
dynwinrt-codegen generate --lang py --class-name Windows.Storage.StorageFile --output generated
python -m pip install .\generated
```

```python
from generated import FileAccessMode, StorageFile

async def read_size(path: str) -> int:
file = await StorageFile.get_file_from_path_async(path)
with await file.open_async(FileAccessMode.Read) as stream:
return stream.size
```

Exiting the context calls native `IClosable.Close` through QueryInterface,
including when the body raises; it does not suppress application exceptions.
Successful helper calls mark that projection closed, repeated `close()` calls
are no-ops, and entering it again raises `RuntimeError`. A failed close remains
retryable. Native aliases can observe closure even though their Python
projections are distinct.

`IClosable` itself also supports `with`; its existing metadata-defined `close()`
keeps its native repeat-call behavior. Helpers never replace an interface's
own projected members. If a native member owns `close` or a context-helper name,
use `with stream.as_interface(IClosable):` instead.

These operations close the native resource; they do not release the projection
or substitute for `release_projected()` / `projected_lifetime_scope()`.
Interfaces without an explicit `IClosable` requirement and arbitrary `Object`
values do not gain closing methods. Prefer deterministic cleanup instead of
relying on Python garbage collection.

## Standalone WinRT interface implementations

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -738,28 +738,7 @@ pub fn generate_class<'a>(
.iter()
.any(|ri| ri.iid == ICLOSABLE_IID)
{
out.push('\n');
out.push_str(" def close(self):\n");
out.push_str(" if self._closed:\n return\n");
out.push_str(&format!(
" {}.from_value(self._obj).close()\n",
py_runtime_named_symbol(
context,
TypeIdentityKind::Interface,
"Windows.Foundation",
"IClosable",
"IClosable",
)
));
out.push_str(" self._closed = True\n\n");
out.push_str(" def __enter__(self):\n");
out.push_str(
" if self._closed:\n\
\x20 raise RuntimeError('cannot enter a closed WinRT object')\n\
\x20 return self\n\n",
);
out.push_str(" def __exit__(self, _exc_type, _exc_value, _traceback):\n");
out.push_str(" self.close()\n return False\n");
out.push_str(&generate_closable_methods(context, true));
}

// IStringable → __str__ / __repr__ delegates to the runtime IStringable.
Expand Down
30 changes: 30 additions & 0 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,36 @@ use super::type_helpers::methods_have_async_output;
const HEADER: &str = "# Generated by dynwinrt-codegen — do not edit\n";
const FUTURE_ANNOTATIONS: &str = "from __future__ import annotations\n";

fn generate_closable_methods(context: &PythonProjectionContext, synthesize_close: bool) -> String {
let mut out = String::from("\n");
if synthesize_close {
out.push_str(" def close(self):\n");
out.push_str(" if self._closed:\n return\n");
out.push_str(&format!(
" {}.from_value(self._obj).close()\n",
py_runtime_named_symbol(
context,
crate::types::TypeIdentityKind::Interface,
"Windows.Foundation",
"IClosable",
"IClosable",
)
));
out.push_str(" self._closed = True\n\n");
}
out.push_str(" def __enter__(self):\n");
if synthesize_close {
out.push_str(
" if self._closed:\n\
\x20 raise RuntimeError('cannot enter a closed WinRT object')\n",
);
}
out.push_str(" return self\n\n");
out.push_str(" def __exit__(self, _exc_type, _exc_value, _traceback):\n");
out.push_str(" self.close()\n return False\n");
out
}

fn emit_map_dispatch(out: &mut String, iid: &str, attribute: &str) {
out.push_str(&format!(
" _dynwinrt_map_dispatch = ({iid}, '{attribute}')\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,9 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe
} else {
out.push_str(" raise TypeError('Cannot construct an interface without an IID')\n");
}
if plan.closable_helpers.close {
out.push_str(" self._closed = False\n");
}
out.push_str(" self._dynwinrt_native_ready = True\n");
out.push_str(&format!(
" _dynwinrt_track_projected(self, '{}.{}')\n",
Expand Down Expand Up @@ -686,6 +689,12 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe
out.push('\n');
out.push_str(&aliases);
}
if plan.closable_helpers.context {
out.push_str(&generate_closable_methods(
context,
plan.closable_helpers.close,
));
}

out
}
Expand Down
44 changes: 43 additions & 1 deletion tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,12 @@ use super::collections::{
};
use super::naming::{PythonProjectionContext, to_snake_case};
use super::native_types::{FoundationType, foundation_type};
use super::shared::{ICLOSABLE_IID, is_closable, requires_closable};
use super::signature::{
LegacyGuardOverlap, LegacyPreservationPredicate, legacy_guard_overlap,
py_dispatch_type_sort_key, py_has_permissive_guard,
};

const ICLOSABLE_IID: &str = "30d5a829-7fa4-4026-83bb-d75bae4ea99e";
const ITHREAD_POOL_STATICS_IID: &str = "b6bf67dd-84bd-44f8-ac1c-93ebcb9dba91";
const WORK_ITEM_HANDLER_IID: &str = "1d1a8b8b-fa66-414f-9cbd-b65fc99d17fa";

Expand Down Expand Up @@ -202,10 +202,50 @@ pub(crate) struct ScopePlan<'a> {
previous_attributes: HashMap<*const MethodMeta, String>,
defined_names: HashSet<String>,
pub(crate) collection_helpers: CollectionHelperPlan,
pub(crate) closable_helpers: ClosableHelperPlan,
#[cfg(test)]
fallbacks: Vec<String>,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct ClosableHelperPlan {
pub(crate) close: bool,
pub(crate) context: bool,
}

impl ClosableHelperPlan {
fn new(interface: &InterfaceMeta, names: &HashSet<String>) -> Self {
if !requires_closable(interface)
|| ["__enter__", "__exit__", "_closed"]
.iter()
.any(|name| names.contains(*name))
{
return Self::default();
}
if is_closable(interface) {
// Keep IClosable.Close's metadata projection and native repeat-call semantics.
let native_close = interface.methods.len() == 1
&& interface.methods.iter().any(|method| {
method.name == "Close"
&& method.vtable_index == 6
&& method.params.is_empty()
&& method.return_type.is_none()
&& !is_accessor(method)
})
&& names.contains("close");
return Self {
close: false,
context: native_close,
};
}
let available = !names.contains("close");
Self {
close: available,
context: available,
}
}
}

/// Refine inherited helpers only when no native member owns their Python name.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct CollectionHelperPlan {
Expand Down Expand Up @@ -450,6 +490,7 @@ pub(crate) fn interface_member_plan<'a>(
.pop()
.expect("interface scope");
plan.collection_helpers = CollectionHelperPlan::new(Some(interface), &plan.defined_names);
plan.closable_helpers = ClosableHelperPlan::new(interface, &plan.defined_names);
plan
}

Expand Down Expand Up @@ -1137,6 +1178,7 @@ fn plan_scopes_with_context<'a>(
previous_attributes,
defined_names,
collection_helpers: CollectionHelperPlan::default(),
closable_helpers: ClosableHelperPlan::default(),
#[cfg(test)]
fallbacks: fallback
.iter()
Expand Down
32 changes: 31 additions & 1 deletion tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,37 @@
//! Shared Python codegen helpers used by both `python` (implementation) and
//! `python_stub` (.pyi stub) emitters.

use crate::meta::MethodMeta;
use crate::meta::{InterfaceMeta, MethodMeta};
use crate::types::TypeMeta;

pub(super) const ICLOSABLE_IID: &str = "30d5a829-7fa4-4026-83bb-d75bae4ea99e";

pub(super) fn is_closable(interface: &InterfaceMeta) -> bool {
interface.generic_piid.is_none() && interface.iid.eq_ignore_ascii_case(ICLOSABLE_IID)
}

pub(super) fn requires_closable(interface: &InterfaceMeta) -> bool {
if interface.implementation_metadata.is_generic_definition
|| interface.is_delegate()
|| (interface.iid.is_empty() && interface.generic_piid.is_none())
{
return false;
}
is_closable(interface)
|| interface
.base_interfaces
.iter()
// The parser records the substituted, transitive WinMD requirements here.
.chain(&interface.implementation_metadata.required_interfaces)
.any(|typ| {
matches!(typ, TypeMeta::Interface { iid, .. } if iid.eq_ignore_ascii_case(ICLOSABLE_IID))
})
}

pub(super) const CLOSE_STUB: &str = " def close(self) -> None: ...\n";
pub(super) const CONTEXT_MANAGER_STUB: &str = "\
\x20 def __enter__(self) -> Self: ...\n\
\x20 def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> Literal[False]: ...\n";

pub(super) const NATIVE_OBJECT_PROTOCOL: &str = "

Expand Down
21 changes: 14 additions & 7 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use super::member_plan::{
use super::naming::{PythonProjectionContext, PythonSupportSymbol, is_py_reserved, to_snake_case};
use super::native_types::foundation_type;
use super::nullability::{AnnotationSurface, ElementContainer};
use super::shared::reorder_getters_before_setters;
use super::shared::{CLOSE_STUB, CONTEXT_MANAGER_STUB, reorder_getters_before_setters};
use super::signature::py_dynwinrt_type;
use super::stub_helpers::{
emit_method_stub, emit_method_stub_named, emit_static_method_stub,
Expand Down Expand Up @@ -272,6 +272,7 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
return out;
}
let implementation = super::implementation::project(context, iface);
let plan = interface_member_plan(iface, context);
let collection_kind = projected_interface_kind(iface);
let is_protocol = collection_kind.is_none();
let has_projection = !iface.iid.is_empty() || iface.generic_piid.is_some();
Expand Down Expand Up @@ -299,6 +300,9 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
}
}
out.push_str("from typing import Protocol, Self, TypeVar\n");
if plan.closable_helpers.context {
out.push_str("from typing import Literal\n");
}
if methods_have_async_output(iface.methods.iter()) {
out.push_str(ASYNC_IMPORT_LINE);
}
Expand Down Expand Up @@ -494,7 +498,6 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
if !is_protocol {
out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n");
}
let plan = interface_member_plan(iface, context);
out.push_str(&collection_protocol_stubs(
iface,
&plan.collection_helpers,
Expand Down Expand Up @@ -626,6 +629,13 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
collection_kind == Some(CollectionKind::MutableSequence),
CollectionInputContract::General,
));
if plan.closable_helpers.context {
out.push('\n');
if plan.closable_helpers.close {
out.push_str(CLOSE_STUB);
}
out.push_str(CONTEXT_MANAGER_STUB);
}

out
}
Expand Down Expand Up @@ -1288,11 +1298,8 @@ fn emit_class_instance_stubs<'a>(
));
if has_closable {
out.push('\n');
out.push_str(" def close(self) -> None: ...\n");
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",
);
out.push_str(CLOSE_STUB);
out.push_str(CONTEXT_MANAGER_STUB);
}

if super::has_projectable_default_interface(class) || !class.required_interfaces.is_empty() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

mod common;

use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
Expand Down Expand Up @@ -61,8 +63,9 @@ fn generated_constructor_errors_preserve_valid_calls_and_native_failures() {
.output()
.expect("generate constructor test package"),
);
let uri = fs::read_to_string(generated.0.join("windows__foundation__uri.py")).unwrap();
let stub = fs::read_to_string(generated.0.join("windows__foundation__uri.pyi")).unwrap();
let package_dir = common::python_package_dir(&generated.0);
let uri = fs::read_to_string(package_dir.join("windows__foundation__uri.py")).unwrap();
let stub = fs::read_to_string(package_dir.join("windows__foundation__uri.pyi")).unwrap();
for params in ["uri: str", "base_uri: str, relative_uri: str"] {
assert!(uri.contains(&format!("Uri({params})")), "{uri}");
assert!(
Expand Down Expand Up @@ -202,7 +205,10 @@ print("constructor-diagnostics-native-ok")
let output = assert_success(
Command::new(python)
.args(["-B", "-c", &script.replace("PY_PACKAGE", &package)])
.env("PYTHONPATH", &target)
.env(
"PYTHONPATH",
common::python_fixture_search_path(&generated.0),
)
.output()
.expect("run native constructor diagnostics"),
);
Expand Down
Loading
Loading