diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 410a244e..298e1176 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -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: | diff --git a/bindings/py/README.md b/bindings/py/README.md index 9696d875..d673ba25 100644 --- a/bindings/py/README.md +++ b/bindings/py/README.md @@ -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 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 d72e9149..7f1d384b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -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. 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 86e02084..b94aebad 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -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" 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 3e1c1c0e..d6ddb3cf 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -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", @@ -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 } 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 42117751..ce29e7a5 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/member_plan.rs @@ -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"; @@ -202,10 +202,50 @@ pub(crate) struct ScopePlan<'a> { previous_attributes: HashMap<*const MethodMeta, String>, defined_names: HashSet, pub(crate) collection_helpers: CollectionHelperPlan, + pub(crate) closable_helpers: ClosableHelperPlan, #[cfg(test)] fallbacks: Vec, } +#[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) -> 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 { @@ -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 } @@ -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() diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs index d6120d83..48dbd446 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/shared.rs @@ -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 = " diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index 0b130200..2a3ed1d7 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -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, @@ -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(); @@ -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); } @@ -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, @@ -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 } @@ -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() { diff --git a/tools/dynwinrt-codegen/tests/python_constructor_diagnostics_test.rs b/tools/dynwinrt-codegen/tests/python_constructor_diagnostics_test.rs index 6af608c4..1594914f 100644 --- a/tools/dynwinrt-codegen/tests/python_constructor_diagnostics_test.rs +++ b/tools/dynwinrt-codegen/tests/python_constructor_diagnostics_test.rs @@ -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}; @@ -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!( @@ -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"), ); diff --git a/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs b/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs index 0bd163fc..7d903d92 100644 --- a/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs @@ -4,8 +4,23 @@ mod common; use std::collections::HashSet; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; +use std::sync::atomic::{AtomicU64, Ordering}; -use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta}; +use dynwinrt_codegen::meta::{ + self, ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, +}; +use dynwinrt_codegen::types::TypeMeta; +use windows_metadata::{ + GenericParamAttributes, MethodCallAttributes, 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 ICLOSABLE_IID: &str = "30d5a829-7fa4-4026-83bb-d75bae4ea99e"; #[test] fn closable_context_manager_never_suppresses_exceptions() { @@ -38,3 +53,671 @@ fn closable_context_manager_never_suppresses_exceptions() { "{stub}" ); } + +fn closable_type() -> TypeMeta { + TypeMeta::Interface { + namespace: "Windows.Foundation".into(), + name: "IClosable".into(), + iid: ICLOSABLE_IID.into(), + } +} + +fn resource_interface() -> InterfaceMeta { + InterfaceMeta { + name: "IResource".into(), + namespace: "Contoso".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + base_interfaces: vec![closable_type()], + ..Default::default() + } +} + +fn assert_helpers(interface: &InterfaceMeta, close: bool, context: bool) { + let known = HashSet::from(["IClosable".into()]); + let runtime = common::generate_interface(interface, &known, &HashSet::new()); + let stub = common::generate_interface_stub(interface, &known, &HashSet::new()); + assert_eq!(runtime.contains(" def close(self):"), close, "{runtime}"); + for source in [&runtime, &stub] { + assert_eq!(source.contains(" def __enter__("), context, "{source}"); + assert_eq!(source.contains(" def __exit__("), context, "{source}"); + } + if context { + assert!(stub.contains("def __enter__(self) -> Self: ..."), "{stub}"); + assert!(stub.contains("-> Literal[False]: ..."), "{stub}"); + assert!( + runtime.contains("self.close()\n return False"), + "{runtime}" + ); + } + if close { + assert!(runtime.contains("self._closed = False"), "{runtime}"); + assert!( + runtime.contains(".from_value(self._obj).close()"), + "{runtime}" + ); + assert!(stub.contains("def close(self) -> None: ..."), "{stub}"); + } +} + +#[test] +fn closable_interfaces_use_metadata_iids_not_names_or_generic_arguments() { + let mut interface = resource_interface(); + assert_helpers(&interface, true, true); + interface.base_interfaces.clear(); + interface + .implementation_metadata + .required_interfaces + .push(closable_type()); + assert_helpers(&interface, true, true); + + interface.generic_piid = Some(interface.iid.clone()); + interface.generic_name = Some("IResource".into()); + interface.generic_args = vec![TypeMeta::String]; + assert_helpers(&interface, true, true); + interface.implementation_metadata.is_generic_definition = true; + assert_helpers(&interface, false, false); + interface.implementation_metadata.is_generic_definition = false; + interface + .implementation_metadata + .required_interfaces + .clear(); + interface.generic_args = vec![closable_type()]; + assert_helpers(&interface, false, false); + + interface.generic_piid = None; + interface.generic_args.clear(); + interface.name = "IClosable".into(); + assert_helpers(&interface, false, false); + interface.base_interfaces.push(TypeMeta::Interface { + namespace: "Contoso".into(), + name: "IClosable".into(), + iid: interface.iid.clone(), + }); + assert_helpers(&interface, false, false); +} + +#[test] +fn iclosable_keeps_its_native_close_member() { + let interface = InterfaceMeta { + name: "IClosable".into(), + namespace: "Windows.Foundation".into(), + iid: ICLOSABLE_IID.to_uppercase(), + methods: vec![MethodMeta { + name: "Close".into(), + vtable_index: 6, + ..Default::default() + }], + ..Default::default() + }; + assert_helpers(&interface, false, true); + let runtime = common::generate_interface(&interface, &HashSet::new(), &HashSet::new()); + assert!( + runtime.contains("_IClosable.method(6).invoke(self._obj, [])"), + "{runtime}" + ); + assert!(!runtime.contains("self._closed"), "{runtime}"); +} + +#[test] +fn closable_helpers_yield_to_native_members_and_aliases() { + for method in [ + MethodMeta { + name: "Close".into(), + params: vec![ParamMeta { + name: "reason".into(), + typ: TypeMeta::String, + direction: ParamDirection::In, + }], + ..Default::default() + }, + MethodMeta { + name: "get_Close".into(), + is_property_getter: true, + return_type: Some(TypeMeta::I32), + ..Default::default() + }, + ] { + let interface = InterfaceMeta { + methods: vec![MethodMeta { + vtable_index: 6, + ..method + }], + ..resource_interface() + }; + assert_helpers(&interface, false, false); + let runtime = common::generate_interface(&interface, &HashSet::new(), &HashSet::new()); + assert!(runtime.contains(" def close("), "{runtime}"); + assert!( + runtime.contains("_IResource.method(6).invoke(self._obj,"), + "{runtime}" + ); + } + let interface = InterfaceMeta { + methods: vec![MethodMeta { + name: "CloseWithReason".into(), + raw_name: "Close".into(), + vtable_index: 6, + ..Default::default() + }], + ..resource_interface() + }; + assert_helpers(&interface, false, false); + for source in [ + common::generate_interface(&interface, &HashSet::new(), &HashSet::new()), + common::generate_interface_stub(&interface, &HashSet::new(), &HashSet::new()), + ] { + assert!(source.contains(" def close("), "{source}"); + assert!(source.contains("close_with_reason"), "{source}"); + } + let interface = InterfaceMeta { + methods: vec![MethodMeta { + name: "Close".into(), + raw_name: "Shutdown".into(), + vtable_index: 6, + ..Default::default() + }], + ..resource_interface() + }; + assert_helpers(&interface, false, false); + let runtime = common::generate_interface(&interface, &HashSet::new(), &HashSet::new()); + assert!(runtime.contains(" def shutdown("), "{runtime}"); + assert!(runtime.contains(" close = shutdown"), "{runtime}"); +} + +#[test] +fn real_stream_requirements_include_transitive_closable_without_inheriting_methods() { + if !Path::new(WINDOWS_WINMD).exists() { + eprintln!("Skipping: Windows.winmd not found"); + return; + } + let interfaces = meta::parse_interfaces(WINDOWS_WINMD, "Windows.Storage.Streams"); + for name in [ + "IInputStream", + "IOutputStream", + "IRandomAccessStream", + "IRandomAccessStreamWithContentType", + ] { + let interface = interfaces + .iter() + .find(|interface| interface.name == name) + .unwrap(); + assert_helpers(interface, true, true); + if name == "IRandomAccessStreamWithContentType" { + assert!(!interface.base_interfaces.contains(&closable_type())); + assert!( + interface + .implementation_metadata + .required_interfaces + .contains(&closable_type()) + ); + let runtime = common::generate_interface(interface, &HashSet::new(), &HashSet::new()); + assert!(!runtime.contains("def seek("), "{runtime}"); + } + } + for name in [ + "IBuffer", + "IContentTypeProvider", + "IRandomAccessStreamReference", + ] { + assert_helpers( + interfaces + .iter() + .find(|interface| interface.name == name) + .unwrap(), + false, + false, + ); + } +} + +#[test] +fn closed_generic_required_interface_closure_is_not_its_type_argument_closure() { + if !Path::new(WINDOWS_WINMD).exists() { + eprintln!("Skipping: Windows.winmd not found"); + return; + } + let fixture = Fixture::new(); + let mut file = writer::File::new("ClosableGenerics"); + let mut define = |name: &str, id, generic, required: Type| { + let interface = file.TypeDef( + "Contoso", + name, + writer::TypeDefOrRef::default(), + TypeAttributes::Public + | TypeAttributes::Interface + | TypeAttributes::Abstract + | TypeAttributes::WindowsRuntime, + ); + let attribute = file.TypeRef("Windows.Foundation.Metadata", "GuidAttribute"); + let constructor = file.MemberRef( + ".ctor", + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: Type::Void, + types: vec![ + Type::U32, + Type::U16, + Type::U16, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + Type::U8, + ], + }, + writer::MemberRefParent::TypeRef(attribute), + ); + file.Attribute( + writer::HasAttribute::TypeDef(interface), + writer::AttributeType::MemberRef(constructor), + &[ + Value::U32(id), + Value::U16(1), + Value::U16(2), + Value::U8(3), + Value::U8(4), + Value::U8(5), + Value::U8(6), + Value::U8(7), + Value::U8(8), + Value::U8(9), + Value::U8(10), + ] + .into_iter() + .map(|value| (String::new(), value)) + .collect::>(), + ); + if generic { + file.GenericParam( + "T", + writer::TypeOrMethodDef::TypeDef(interface), + 0, + GenericParamAttributes::default(), + ); + } + file.InterfaceImpl(interface, &required); + }; + let generic = |namespace: &str, name: &str, argument| { + Type::Name(TypeName { + namespace: namespace.into(), + name: name.into(), + generics: vec![argument], + }) + }; + define( + "IResource`1", + 1, + true, + Type::named("Windows.Foundation", "IClosable"), + ); + define( + "IDerived`1", + 2, + true, + generic("Contoso", "IResource`1", Type::Generic(0)), + ); + define( + "IRoot", + 3, + false, + generic("Contoso", "IDerived`1", Type::String), + ); + define( + "IContainer", + 4, + false, + generic( + "Windows.Foundation.Collections", + "IVector`1", + Type::named("Windows.Foundation", "IClosable"), + ), + ); + let winmd = fixture.0.join("ClosableGenerics.winmd"); + fs::write(&winmd, file.into_stream()).unwrap(); + let inputs = format!("{};{WINDOWS_WINMD}", winmd.display()); + let roots = meta::parse_interfaces(&inputs, "Contoso"); + let root = roots + .iter() + .find(|interface| interface.name == "IRoot") + .unwrap(); + assert_helpers(root, true, true); + assert!(!root.base_interfaces.contains(&closable_type())); + let container = roots + .iter() + .find(|interface| interface.name == "IContainer") + .unwrap(); + assert_helpers(container, false, false); + let dependencies = meta::resolve_python_dependencies(&inputs, &[], &roots, &[]); + for name in ["IResource_String", "IDerived_String", "IVector_IClosable"] { + let interface = dependencies + .interfaces + .iter() + .find(|interface| interface.name == name) + .unwrap_or_else(|| panic!("missing closed dependency {name}")); + let closable = name != "IVector_IClosable"; + assert_helpers(interface, closable, closable); + } +} + +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("target") + .join(format!( + "pcm{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +fn python() -> PathBuf { + std::env::var_os("DYNWINRT_TEST_PYTHON") + .map(PathBuf::from) + .unwrap_or_else(|| "python".into()) +} + +fn diagnostics(output: &Output) -> String { + format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ) +} + +fn success(output: Output) { + assert!(output.status.success(), "{}", diagnostics(&output)); +} + +fn available(import: &str, required: &str) -> bool { + let available = Command::new(python()) + .args(["-c", import]) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + available || std::env::var(required).as_deref() != Ok("1"), + "{required}=1: {import}" + ); + if !available { + eprintln!("Skipping Python probe: {import}; set DYNWINRT_TEST_PYTHON."); + } + available +} + +fn generate_streams(fixture: &Fixture, no_pyi: bool) { + let mut command = Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")); + command.args(["generate", "--lang", "py", "--winmd", WINDOWS_WINMD, "--class-name", + "Windows.Storage.StorageFile,Windows.Storage.Streams.InMemoryRandomAccessStream,Windows.Storage.Streams.DataWriter,Windows.Storage.Streams.Buffer,Windows.Storage.Streams.IRandomAccessStreamWithContentType"]); + let project = fixture.0.join("views"); + command.arg("--output").arg(&project); + if no_pyi { + command.arg("--no-pyi"); + } + success(command.output().unwrap()); + let package = common::python_package_dir(&project); + assert_eq!(package, project.join("src").join("views")); + assert!(package.join("__init__.py").is_file()); + assert_eq!(package.join("__init__.pyi").is_file(), !no_pyi); + assert!(!project.join("__init__.py").exists()); +} + +#[test] +fn generated_stream_contexts_close_real_native_resources() { + if !Path::new(WINDOWS_WINMD).exists() + || !available( + "from dynwinrt import DynWinRTImplementationHandle", + "DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME", + ) + { + return; + } + for no_pyi in [false, true] { + let fixture = Fixture::new(); + generate_streams(&fixture, no_pyi); + fs::write(fixture.0.join("probe.py"), NATIVE_PROBE).unwrap(); + success( + Command::new(python()) + .arg("-B") + .arg("probe.py") + .env("PYTHONPATH", common::python_fixture_search_path(&fixture.0)) + .current_dir(&fixture.0) + .output() + .unwrap(), + ); + } +} + +const NATIVE_PROBE: &str = r#" +import asyncio +import inspect +from pathlib import Path +from tempfile import TemporaryDirectory +from dynwinrt import RoApartment, projected_lifetime_scope +import views as g + +assert Path(g.__file__).resolve() == (Path('views') / 'src' / 'views' / '__init__.py').resolve() + +async def expect_closed(action): + try: + value = action() + if inspect.isawaitable(value): + await value + except OSError as error: + assert error.winerror & 0xFFFFFFFF == 0x80000013, error + else: + raise AssertionError('native operation should fail with RO_E_CLOSED') + +def expect_closed_entry(stream): + try: + stream.__enter__() + except RuntimeError as error: + assert 'closed WinRT object' in str(error), error + else: + raise AssertionError('closed projection can be reentered') + +async def main(): + with TemporaryDirectory() as directory: + path = Path(directory) / 'input.txt' + path.write_bytes(b'closable') + file = await g.StorageFile.get_file_from_path_async(str(path)) + stream = await file.open_async(g.FileAccessMode.Read) + assert type(stream) is g.IRandomAccessStream + assert stream.size == 8 + stream.close() + stream.close() + assert not stream._obj.is_null(), 'Close must not release the projection' + expect_closed_entry(stream) + await expect_closed(lambda: stream.size) + + failure = ValueError('application error') + stream = await file.open_async(g.FileAccessMode.Read) + try: + with stream as entered: + assert entered is stream and stream.size == 8 + raise failure + except ValueError as error: + assert error is failure + else: + raise AssertionError('context swallowed application exception') + await expect_closed(lambda: stream.size) + + buffer = g.Buffer.create(8).as_interface(g.IBuffer) + with await file.open_async(g.FileAccessMode.Read) as stream: + input_stream = stream.get_input_stream_at(0) + assert type(input_stream) is g.IInputStream + with input_stream as entered: + assert entered is input_stream + read = await input_stream.read_async(buffer, 8, g.InputStreamOptions.None_) + assert read.to_bytes() == b'closable' + input_stream.close() + expect_closed_entry(input_stream) + await expect_closed(lambda: input_stream.read_async(buffer, 1, g.InputStreamOptions.None_)) + + content = await file.open_read_async() + assert type(content) is g.IRandomAccessStreamWithContentType + alias = content.as_interface(g.IRandomAccessStream) + with content as entered: + assert entered is content and alias.size == 8 + assert not alias._obj.is_null() + await expect_closed(lambda: alias.size) + + with g.InMemoryRandomAccessStream.create() as memory: + output = memory.get_output_stream_at(0) + assert type(output) is g.IOutputStream + with output as entered: + assert entered is output + assert await output.write_async(buffer) == 8 + output.close() + await expect_closed(lambda: output.write_async(buffer)) + await expect_closed(lambda: memory.size) + with g.DataWriter.create_default() as writer: + writer.write_byte(42) + writer.close() + await expect_closed(lambda: writer.write_byte(43)) + + memory = g.InMemoryRandomAccessStream.create() + with memory.as_interface(g.IClosable) as closable: + assert type(closable) is g.IClosable + assert memory.size == 0 + await expect_closed(lambda: memory.size) + assert not hasattr(buffer, 'close') and not hasattr(buffer, '__enter__') + assert not hasattr(file.as_interface(g.IStorageFile), 'close') + + class Input: + def read_async(self, buffer, count, options): + raise NotImplementedError('unused') + + class Close: + calls = 0 + def close(self): + self.calls += 1 + if self.calls == 1: + raise ValueError('retry close') + + handler = Close() + with g.IInputStream.implement(Input(), interfaces=[(g.IClosable, handler)]) as owner: + view = owner.value + try: + view.close() + except OSError: + assert handler.calls == 1 + else: + raise AssertionError('failed Close was swallowed') + assert view.__enter__() is view + view.close() + view.close() + assert handler.calls == 2 + assert not owner.is_closed, 'Close must not dispose the implementation owner' + expect_closed_entry(view) + direct = view.as_interface(g.IClosable) + direct.close() + direct.close() + assert handler.calls == 4, 'IClosable.Close must retain native repeat-call semantics' + +with RoApartment(), projected_lifetime_scope(): + asyncio.run(main()) +print('real stream close/context, exceptions, aliases, retry, and existing classes: OK') +"#; + +#[test] +fn generated_stream_context_typing_preserves_self_and_non_suppression() { + if !Path::new(WINDOWS_WINMD).exists() || !available("import mypy", "DYNWINRT_REQUIRE_MYPY") { + return; + } + let fixture = Fixture::new(); + generate_streams(&fixture, false); + fs::write(fixture.0.join("consumer.py"), r#" +from typing import assert_type +from views import IClosable, IInputStream, IOutputStream, IRandomAccessStream, IRandomAccessStreamWithContentType, InMemoryRandomAccessStream, DataWriter, StorageFile, FileAccessMode + +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: + assert_type(stream, IRandomAccessStream) + size = stream.size + return size + +def interfaces(input: IInputStream, output: IOutputStream, content: IRandomAccessStreamWithContentType, close: IClosable) -> None: + with input as i, output as o, content as c, close as closer: + assert_type(i, IInputStream) + assert_type(o, IOutputStream) + assert_type(c, IRandomAccessStreamWithContentType) + assert_type(closer, IClosable) + result = 1 + assert_type(result, int) + input.close() + output.close() + content.close() + close.close() + with InMemoryRandomAccessStream.create() as memory: + assert_type(memory, InMemoryRandomAccessStream) + with DataWriter.create_default() as writer: + assert_type(writer, DataWriter) +"#).unwrap(); + let typecheck = || { + Command::new(python()) + .args([ + "-B", + "-m", + "mypy", + "--strict", + "--no-incremental", + "--follow-imports=silent", + "--no-pretty", + "--show-error-codes", + "--cache-dir", + ".mypy_cache", + "consumer.py", + ]) + .env( + "MYPYPATH", + common::python_fixture_mypy_path(&fixture.0, true), + ) + .current_dir(&fixture.0) + .output() + .unwrap() + }; + success(typecheck()); + fs::write( + fixture.0.join("consumer.py"), + r#" +from views import IBuffer +def unsupported(buffer: IBuffer) -> None: + buffer.close() + with buffer: + pass +"#, + ) + .unwrap(); + let output = typecheck(); + let text = diagnostics(&output); + assert_eq!(output.status.code(), Some(1), "{text}"); + for member in ["close", "__enter__", "__exit__"] { + assert!( + text.contains(&format!("has no attribute \"{member}\"")), + "{text}" + ); + } + assert_eq!( + text.lines() + .filter(|line| line.contains(": error:")) + .count(), + 3, + "{text}" + ); +}