From 949fe0806151a11194bd5f53f6ae39c90056d607 Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Thu, 17 Sep 2026 20:22:53 +0800 Subject: [PATCH 1/2] Fix Python projection annotation aliases Use consistent local and imported type names in generated handler, delegate, result, and struct annotations. Preserve same-named interfaces from other namespaces and standalone embedded struct names. Add collision and typing regression coverage without changing JavaScript output. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: bdea384f-3022-47e8-8c74-11fd768c2105 --- .../winrt-interface-implementations.md | 8 + .../codegen/winrt/python/generator/class.rs | 7 + .../src/codegen/winrt/python/generator/mod.rs | 7 +- .../codegen/winrt/python/generator/structs.rs | 15 +- .../codegen/winrt/python/generator/types.rs | 14 +- .../src/codegen/winrt/python/naming.rs | 27 ++ .../src/codegen/winrt/python/structs.rs | 2 +- .../src/codegen/winrt/python/stub_helpers.rs | 16 +- .../src/codegen/winrt/python/stubs.rs | 27 +- .../src/codegen/winrt/shared/imports.rs | 19 +- .../tests/implementation_naming_test.rs | 372 ++++++++++++++++++ 11 files changed, 494 insertions(+), 20 deletions(-) diff --git a/docs/architecture/winrt-interface-implementations.md b/docs/architecture/winrt-interface-implementations.md index 71e632ed..ff3f3518 100644 --- a/docs/architecture/winrt-interface-implementations.md +++ b/docs/architecture/winrt-interface-implementations.md @@ -106,6 +106,14 @@ Common Python reverse-conversion helpers live once in each generated package's generated code, not excluded coverage support. Method-specific ABI plans and typed conversions remain with their interface. +Python handler, delegate, and result annotations share the enclosing module's +type-name mapping with ordinary projected members. Self-interface references use +the locally declared class name; imported structs use the same collision alias +in `.py` and `.pyi`. Types with identical short names in other namespaces remain +distinct imports, including references nested in arrays or delegate signatures. +Standalone interface and runtime-class modules use local names for embedded +struct helpers; standalone struct modules retain aliases for imported fields. + Language bindings additionally gate dispatch on their environment/interpreter lifetime. Callback roots belong to the native object, not merely the original language wrapper. Shutdown disconnects language callback state before its 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 7893e33c..afa5be90 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -34,6 +34,13 @@ pub fn generate_class( shared_iids: &HashSet, ) -> String { let used_structs = collect_used_structs_from_class(class); + let context = context.with_local_types( + used_structs + .iter() + .filter(|_| !context.is_packaged()) + .map(TypeMeta::type_identity), + ); + let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); let known_full_names = context.known_full_names(); 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 2a888f47..e3ee877e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -13,9 +13,10 @@ use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection}; use crate::types::{TypeKind, TypeMeta}; use crate::codegen::winrt::shared::imports::{ - collect_iface_type_imports, collect_struct_field_type_imports, collect_type_imports, - collect_used_generic_identities_from_class, collect_used_generic_identities_from_methods, - collect_used_generic_identities_from_type, ireference_inner_type, + collect_iface_type_imports_by_identity, collect_struct_field_type_imports, + collect_type_imports, collect_used_generic_identities_from_class, + collect_used_generic_identities_from_methods, collect_used_generic_identities_from_type, + ireference_inner_type, }; use crate::codegen::winrt::shared::structs::{ collect_used_structs_from_class, collect_used_structs_from_iface, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs index 1205be1f..21244db5 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs @@ -34,13 +34,23 @@ pub(super) fn generate_struct_imports( let mut imports = structs .iter() .filter_map(|typ| { - let TypeMeta::Struct { .. } = typ else { + let TypeMeta::Struct { name, .. } = typ else { return None; }; + let names = struct_runtime_import_names(typ) + .into_iter() + .map(|export| { + if export == *name { + context.struct_type_import(typ, &export) + } else { + export + } + }) + .collect::>(); Some(format!( "from .{} import {} # noqa: F401\n", context.implementation_module_for_type(typ), - struct_runtime_import_names(typ).join(", ") + names.join(", ") )) }) .collect::>(); @@ -149,6 +159,7 @@ pub(super) fn generate_struct_helpers(context: &PythonProjectionContext, s: &Typ && foundation_type(&f.typ).is_none() && name != "HResult" { + let name = context.reference_name_for_type(&f.typ); out.push_str(&format!( " self.{snake} = {name}() if {snake} is None else {snake}\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 e1d6ff82..b761f6da 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -77,6 +77,17 @@ pub fn generate_enum(_context: &PythonProjectionContext, en: &TypeMeta) -> Optio /// Generate a Python file for a WinRT interface (non-exclusive). pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String { + let used_structs = collect_used_structs_from_iface(iface); + let type_imports = collect_iface_type_imports_by_identity(iface); + let context = context.with_local_types( + std::iter::once(iface.type_identity()).chain( + used_structs + .iter() + .filter(|_| !context.is_packaged()) + .map(TypeMeta::type_identity), + ), + ); + let context = context.as_ref(); let mut projected_iface = iface.clone(); projected_iface.name = context.projected_name_for_interface(iface); let iface = &projected_iface; @@ -86,8 +97,6 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe } let implementation = super::super::implementation::project(context, iface); - let used_structs = collect_used_structs_from_iface(iface); - let mut out = String::new(); out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); @@ -195,7 +204,6 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe } // Type imports for referenced types - let type_imports = collect_iface_type_imports(iface); let mut sorted_type_imports: Vec<_> = type_imports.iter().collect(); sorted_type_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 82458af6..bfbd0d94 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -3,6 +3,7 @@ //! Python naming and identifier helpers. +use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; use super::super::shared::implementation_symbols::{ @@ -552,6 +553,32 @@ impl PythonProjectionContext { self.packaged } + /// Locally declared types use their exported names, not cross-module aliases. + pub(super) fn with_local_types( + &self, + identities: impl IntoIterator, + ) -> Cow<'_, Self> { + let mut context = Cow::Borrowed(self); + for identity in identities { + let identity = self.normalize_identity(&identity); + if self.reference_name(&identity) != self.projected_name(&identity) + && let Some(projection) = context.to_mut().projections.get_mut(&identity) + { + projection.reference_name = projection.projected_name.clone(); + } + } + context + } + + pub(super) fn struct_type_import(&self, typ: &TypeMeta, name: &str) -> String { + let reference = self.reference_name_for_type(typ); + if reference == name { + name.into() + } else { + format!("{name} as {reference}") + } + } + pub fn configure_implementation_helpers( &mut self, owners: impl IntoIterator)>, diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs index 97d7f538..eb94e3d1 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs @@ -138,7 +138,7 @@ pub(crate) fn py_struct_field_read_type( TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(), typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(), typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(), - TypeMeta::Struct { name, .. } => format!("'{}'", name), + TypeMeta::Struct { .. } => format!("'{}'", context.reference_name_for_type(typ)), _ => "'DynWinRTValue'".to_string(), } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs index 9060f200..bfe4045c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs @@ -91,13 +91,23 @@ pub(super) fn generate_struct_stub_imports( let mut imports = structs .iter() .filter_map(|typ| { - let TypeMeta::Struct { .. } = typ else { + let TypeMeta::Struct { name, .. } = typ else { return None; }; + let names = py_struct_export_names(typ) + .into_iter() + .map(|export| { + if export == *name { + context.struct_type_import(typ, &export) + } else { + export + } + }) + .collect::>(); Some(format!( "from .{} import {} # noqa: F401\n", context.implementation_module_for_type(typ), - py_struct_export_names(typ).join(", ") + names.join(", ") )) }) .collect::>(); @@ -243,7 +253,7 @@ pub(super) fn py_struct_field_stub_type( TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(), typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(), typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(), - TypeMeta::Struct { name, .. } => format!("'{}'", name), + TypeMeta::Struct { .. } => format!("'{}'", context.reference_name_for_type(typ)), _ => "object".to_string(), } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index da426290..e09d6452 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -13,9 +13,9 @@ use crate::types::{TypeKind, TypeMeta}; use crate::codegen::winrt::extensions::winui; use crate::codegen::winrt::shared::imports::{ - collect_iface_type_imports, collect_struct_field_type_imports, collect_type_imports, - collect_used_generic_identities_from_class, collect_used_generic_identities_from_methods, - collect_used_generic_identities_from_type, + collect_iface_type_imports_by_identity, collect_struct_field_type_imports, + collect_type_imports, collect_used_generic_identities_from_class, + collect_used_generic_identities_from_methods, collect_used_generic_identities_from_type, }; use crate::codegen::winrt::shared::structs::{ collect_used_structs_from_class, collect_used_structs_from_iface, @@ -221,6 +221,17 @@ pub fn generate_enum_stub(_context: &PythonProjectionContext, en: &TypeMeta) -> /// Generate a `.pyi` stub for an interface (or a delegate). pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String { + let used_structs = collect_used_structs_from_iface(iface); + let type_imports = collect_iface_type_imports_by_identity(iface); + let context = context.with_local_types( + std::iter::once(iface.type_identity()).chain( + used_structs + .iter() + .filter(|_| !context.is_packaged()) + .map(TypeMeta::type_identity), + ), + ); + let context = context.as_ref(); let mut projected_iface = iface.clone(); projected_iface.name = context.projected_name_for_interface(iface); let iface = &projected_iface; @@ -237,8 +248,6 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf } let implementation = super::implementation::project(context, iface); - let used_structs = collect_used_structs_from_iface(iface); - let mut out = String::new(); out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); @@ -350,7 +359,6 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf out.push_str(&format!("from .{module} import {imports} # noqa: F401\n",)); } - let type_imports = collect_iface_type_imports(iface); let mut sorted_type_imports: Vec<_> = type_imports.iter().collect(); sorted_type_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); @@ -568,6 +576,13 @@ pub fn generate_class_stub( shared_iids: &HashSet, ) -> String { let used_structs = collect_used_structs_from_class(class); + let context = context.with_local_types( + used_structs + .iter() + .filter(|_| !context.is_packaged()) + .map(TypeMeta::type_identity), + ); + let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); let known_full_names = context.known_full_names(); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs index f74873eb..b91fc2b9 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs @@ -186,12 +186,27 @@ fn collect_methods_type_imports( /// Collect type references from an interface for import generation. pub(crate) fn collect_iface_type_imports(iface: &InterfaceMeta) -> HashSet { + collect_iface_type_imports_except(iface, &iface.name) +} + +/// Python aliases distinguish same-named interfaces from different namespaces. +pub(crate) fn collect_iface_type_imports_by_identity(iface: &InterfaceMeta) -> HashSet { + let mut imports = collect_iface_type_imports_except(iface, ""); + imports.retain(|reference| { + reference.kind != TypeKind::Interface + || reference.namespace != iface.namespace + || reference.name != iface.name + }); + imports +} + +fn collect_iface_type_imports_except(iface: &InterfaceMeta, self_name: &str) -> HashSet { let mut imports = HashSet::new(); - collect_methods_type_imports(&iface.methods, &iface.name, false, &mut imports); + collect_methods_type_imports(&iface.methods, self_name, false, &mut imports); for delegate in &iface.implementation_metadata.delegates { collect_methods_type_imports( std::slice::from_ref(&delegate.invoke), - &iface.name, + self_name, false, &mut imports, ); diff --git a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs index 2f3acc2c..0c4d20f8 100644 --- a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs +++ b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs @@ -7,6 +7,12 @@ use std::path::{Path, PathBuf}; use std::process::{Command, Output}; use std::sync::atomic::{AtomicU64, Ordering}; +use dynwinrt_codegen::codegen::{python, python_stub}; +use dynwinrt_codegen::meta::{ + ClassMeta, ImplementationDelegateMeta, InterfaceImplementationMetadata, InterfaceMeta, + MethodMeta, ParamDirection, ParamMeta, +}; +use dynwinrt_codegen::types::{FieldMeta, TypeIdentityKind, TypeMeta}; use windows_metadata::{ MethodAttributes, MethodCallAttributes, MethodImplAttributes, ParamAttributes, Signature, Type, TypeAttributes, Value, writer, @@ -459,6 +465,372 @@ fn python_inventory(directory: &Path) -> Vec { .collect() } +#[test] +fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { + let fixture = Fixture::new(); + let package = fixture.0.join("pyviews"); + fs::create_dir_all(&package).unwrap(); + let interface_type = |namespace: &str| TypeMeta::Interface { + namespace: namespace.into(), + name: "IValue".into(), + iid: format!( + "31d44731-6281-4900-b782-04030201091{}", + if namespace == "Alpha" { 0 } else { 1 } + ), + }; + let payload = |namespace: &str| TypeMeta::Struct { + namespace: namespace.into(), + name: "Payload".into(), + fields: vec![FieldMeta { + name: "Value".into(), + typ: TypeMeta::I32, + }], + }; + let array = |typ| TypeMeta::Array(Box::new(typ)); + let mut structs = Vec::new(); + let mut interfaces = Vec::new(); + for (namespace, peer_namespace) in [("Alpha", "Beta"), ("Beta", "Alpha")] { + let this = interface_type(namespace); + let peer = interface_type(peer_namespace); + let structure = payload(namespace); + let envelope = TypeMeta::Struct { + namespace: namespace.into(), + name: "Envelope".into(), + fields: vec![FieldMeta { + name: "Item".into(), + typ: structure.clone(), + }], + }; + let callback = TypeMeta::Delegate { + namespace: namespace.into(), + name: "Callback".into(), + iid: format!("31d44731-6281-4900-b782-04030201092{}", interfaces.len()), + }; + let mut methods = Vec::new(); + for (name, typ) in [ + ("EchoStruct", structure.clone()), + ("EchoSelf", this.clone()), + ("EchoPeer", peer), + ("EchoArray", array(structure.clone())), + ("EchoEnvelope", envelope.clone()), + ] { + methods.push(MethodMeta { + name: name.into(), + vtable_index: 6 + methods.len(), + params: vec![ParamMeta { + name: "value".into(), + typ: typ.clone(), + direction: ParamDirection::In, + }], + return_type: Some(typ), + ..Default::default() + }); + } + methods.push(MethodMeta { + name: "UseCallback".into(), + vtable_index: 6 + methods.len(), + params: vec![ParamMeta { + name: "callback".into(), + typ: callback.clone(), + direction: ParamDirection::In, + }], + ..Default::default() + }); + let TypeMeta::Interface { iid, .. } = this.clone() else { + unreachable!() + }; + interfaces.push(InterfaceMeta { + namespace: namespace.into(), + name: "IValue".into(), + iid, + methods, + implementation_metadata: InterfaceImplementationMetadata { + delegates: vec![ImplementationDelegateMeta { + typ: callback, + invoke: MethodMeta { + name: "Invoke".into(), + vtable_index: 3, + params: vec![ + ParamMeta { + name: "value".into(), + typ: this.clone(), + direction: ParamDirection::In, + }, + ParamMeta { + name: "owner".into(), + typ: this, + direction: ParamDirection::Out, + }, + ], + return_type: Some(array(structure.clone())), + ..Default::default() + }, + }], + ..Default::default() + }, + ..Default::default() + }); + structs.extend([structure, envelope]); + } + let identities = interfaces + .iter() + .map(InterfaceMeta::type_identity) + .chain(structs.iter().map(TypeMeta::type_identity)) + .chain(interfaces.iter().flat_map(|interface| { + interface + .implementation_metadata + .delegates + .iter() + .map(|delegate| delegate.typ.type_identity()) + })) + .collect::>(); + let context = python::PythonProjectionContext::packaged(identities.clone()).unwrap(); + let mut modules = Vec::new(); + let mut consumer = "from typing import assert_type\n".to_string(); + for interface in &interfaces { + let namespace = &interface.namespace; + let module = context.implementation_module_for_interface(interface); + for delegate in &interface.implementation_metadata.delegates { + let TypeMeta::Delegate { + namespace, + name, + iid, + } = &delegate.typ + else { + unreachable!() + }; + let metadata = InterfaceMeta { + namespace: namespace.clone(), + name: name.clone(), + iid: iid.clone(), + methods: vec![ + MethodMeta { + name: ".ctor".into(), + ..Default::default() + }, + delegate.invoke.clone(), + ], + ..Default::default() + }; + let module = context.implementation_module_for_interface(&metadata); + fs::write( + package.join(format!("{module}.py")), + python::generate_interface(&context, &metadata), + ) + .unwrap(); + fs::write( + package.join(format!("{module}.pyi")), + python_stub::generate_interface_stub(&context, &metadata), + ) + .unwrap(); + } + let helpers = python::implementation_helper_records(&context, interface); + let helper = |key| { + helpers + .iter() + .find(|helper| helper.key == key) + .unwrap() + .name + .as_str() + }; + for (extension, source) in [ + ("py", python::generate_interface(&context, interface)), + ( + "pyi", + python_stub::generate_interface_stub(&context, interface), + ), + ] { + assert!(source.contains(&format!("Payload as {namespace}_Payload_struct"))); + assert!(source.contains(&format!( + "def echo_struct(self, value: {namespace}_Payload_struct) -> {namespace}_Payload_struct: ..." + ))); + assert!( + source.contains("def echo_self(self, value: IValue | None) -> IValue | None: ...") + ); + assert!(source.contains(&format!( + "def echo_array(self, value: list[{namespace}_Payload_struct]) -> list[{namespace}_Payload_struct]: ..." + ))); + assert!(source.contains("def __call__(self, value: IValue | None, /)")); + assert!(source.contains(" owner: IValue | None\n")); + assert!(source.contains(&format!(" result: list[{namespace}_Payload_struct]\n"))); + assert!(!source.contains(&format!("{namespace}_IValue_interface"))); + fs::write(package.join(format!("{module}.{extension}")), source).unwrap(); + } + let peer = if namespace == "Alpha" { + "Beta" + } else { + "Alpha" + }; + consumer.push_str(&format!( + "from pyviews.{module} import IValue as {namespace}, {handlers} as {namespace}Handlers, {delegate} as {namespace}Callback\n\ + from pyviews.{payload_module} import Payload as {namespace}Payload\n\ + from pyviews.{envelope_module} import Envelope as {namespace}Envelope\n\ + def check_{namespace}(handlers: {namespace}Handlers, value: {namespace}, peer: {peer}, payload: {namespace}Payload, callback: {namespace}Callback) -> None:\n\ + \x20 assert_type(handlers.echo_struct(payload), {namespace}Payload)\n\ + \x20 assert_type(handlers.echo_self(value), {namespace} | None)\n\ + \x20 assert_type(handlers.echo_peer(peer), {peer} | None)\n\ + \x20 assert_type(handlers.echo_array([payload]), list[{namespace}Payload])\n\ + \x20 assert_type(handlers.echo_envelope({namespace}Envelope(payload)).item, {namespace}Payload)\n\ + \x20 assert_type(callback(value)['owner'], {namespace} | None)\n\ + \x20 assert_type(callback(value)['result'], list[{namespace}Payload])\n", + handlers = helper("handlers"), + delegate = helper("delegate:0"), + payload_module = context.implementation_module_for_type(&payload(namespace)), + envelope_module = format!("{}__envelope", namespace.to_lowercase()), + )); + modules.push(module); + } + for structure in &structs { + let module = context.implementation_module_for_type(structure); + fs::write( + package.join(format!("{module}.py")), + python::generate_struct(&context, structure).unwrap(), + ) + .unwrap(); + fs::write( + package.join(format!("{module}.pyi")), + python_stub::generate_struct_stub(&context, structure).unwrap(), + ) + .unwrap(); + } + let standalone = + python::PythonProjectionContext::standalone(identities.into_iter().filter(|identity| { + identity.kind() != Some(TypeIdentityKind::Delegate) + || identity.namespace() == Some("Alpha") + })) + .unwrap(); + let class = ClassMeta { + namespace: "Alpha".into(), + name: "Host".into(), + full_name: "Alpha.Host".into(), + static_interfaces: vec![InterfaceMeta { + namespace: "Alpha".into(), + name: "IHostStatics".into(), + iid: "31d44731-6281-4900-b782-040302010930".into(), + methods: vec![MethodMeta { + name: "EchoEnvelope".into(), + vtable_index: 6, + params: vec![ParamMeta { + name: "value".into(), + typ: structs[1].clone(), + direction: ParamDirection::In, + }], + return_type: Some(structs[1].clone()), + ..Default::default() + }], + ..Default::default() + }], + ..Default::default() + }; + for (extension, source) in [ + ( + "py", + python::generate_class(&standalone, &class, &Default::default()), + ), + ( + "pyi", + python_stub::generate_class_stub(&standalone, &class, &Default::default()), + ), + ] { + assert!(source.contains("class Payload:")); + assert!(source.contains("class Envelope:")); + assert!(!source.contains("Alpha_Payload_struct")); + assert!(!source.contains("Alpha_Envelope_struct")); + fs::write(package.join(format!("alpha__host.{extension}")), source).unwrap(); + } + for (extension, source) in [ + ( + "py", + python::generate_struct(&standalone, &structs[1]).unwrap(), + ), + ( + "pyi", + python_stub::generate_struct_stub(&standalone, &structs[1]).unwrap(), + ), + ] { + assert!(!source.contains("class Payload:")); + assert!(source.contains("from .alpha__payload import Payload as Alpha_Payload_struct")); + fs::write( + package.join(format!("alpha__standalone_envelope.{extension}")), + source, + ) + .unwrap(); + } + consumer.push_str( + "from pyviews.alpha__host import Host, Envelope as InlineEnvelope, Payload as InlinePayload\n\ + from pyviews.alpha__standalone_envelope import Envelope as StandaloneEnvelope\n\ + assert_type(Host.echo_envelope(InlineEnvelope()), InlineEnvelope)\n\ + assert_type(InlineEnvelope().item, InlinePayload)\n\ + assert_type(StandaloneEnvelope().item, AlphaPayload)\n" + ); + for (name, source) in [ + ("__init__.py", String::new()), + ("_runtime.py", python::generate_runtime_support_module()), + ("_runtime.pyi", python_stub::generate_runtime_support_stub()), + ("_typing.pyi", python_stub::generate_typing_support_module()), + ( + "_implementation_types.pyi", + python_stub::generate_implementation_pair_types(&modules), + ), + ] { + fs::write(package.join(name), source).unwrap(); + } + typecheck_py(&fixture.0, &consumer); + + // Imported stubs are otherwise silenced by the consumer harness. + if Command::new(python()) + .args(["-m", "mypy", "--version"]) + .output() + .is_ok_and(|output| output.status.success()) + { + success( + Command::new(python()) + .args([ + "-m", + "mypy", + "--no-incremental", + "--follow-imports=silent", + "pyviews", + ]) + .current_dir(&fixture.0) + .env("MYPYPATH", root().join("bindings").join("py")) + .output() + .unwrap(), + ); + } + if runtime_available() { + success(Command::new(python()).args(["-B", "-c", r#" +import ast, importlib, pathlib, typing +for path in pathlib.Path('pyviews').glob('*__*.py'): + module = importlib.import_module('pyviews.' + path.stem) + for statement in ast.parse(path.read_text(encoding='utf-8')).body: + if isinstance(statement, ast.If) and ast.unparse(statement.test) == 'TYPE_CHECKING': + exec(compile(ast.Module(body=statement.body, type_ignores=[]), str(path), 'exec'), vars(module)) + for value in list(vars(module).values()): + if isinstance(value, type) and value.__module__ == module.__name__: + typing.get_type_hints(value) + for name, method in vars(value).items(): + if value.__name__ == 'IValue' and not name.startswith('echo_'): + continue + if callable(method) and hasattr(method, '__annotations__'): + typing.get_type_hints(method, vars(module)) + if hasattr(module, 'Envelope'): + assert type(module.Envelope().item).__name__ == 'Payload' + if path.stem == 'alpha__host': + assert type(module.Envelope().item) is module.Payload +"#]).current_dir(&fixture.0).output().unwrap()); + } + + for source in [ + python::generate_interface(&standalone, &interfaces[0]), + python_stub::generate_interface_stub(&standalone, &interfaces[0]), + ] { + assert!(source.contains("def echo_struct(self, value: Payload) -> Payload: ...")); + assert!(source.contains("def echo_self(self, value: IValue | None) -> IValue | None: ...")); + assert!(!source.contains("Alpha_Payload_struct")); + } +} + fn snapshot(directory: &Path) -> BTreeMap> { fn visit(root: &Path, path: &Path, files: &mut BTreeMap>) { for entry in fs::read_dir(path).unwrap() { From 5042b30108b06448141b3e31b760b5ebda0a1e4e Mon Sep 17 00:00:00 2001 From: "Leilei Zhang (from Dev Box)" Date: Fri, 18 Sep 2026 01:13:58 +0800 Subject: [PATCH 2/2] Fix full-identity Python annotation collisions Bind standalone struct references to their actual declared names and compare canonical identities when excluding Python self imports. Add generic-versus-named collision regressions for standalone and packaged projections while preserving JavaScript output. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../winrt-interface-implementations.md | 7 +- .../codegen/winrt/python/generator/class.rs | 7 +- .../codegen/winrt/python/generator/types.rs | 9 +- .../src/codegen/winrt/python/naming.rs | 25 +- .../src/codegen/winrt/python/stubs.rs | 16 +- .../src/codegen/winrt/shared/imports.rs | 14 +- .../tests/implementation_naming_test.rs | 375 ++++++++++++++++-- 7 files changed, 381 insertions(+), 72 deletions(-) diff --git a/docs/architecture/winrt-interface-implementations.md b/docs/architecture/winrt-interface-implementations.md index ff3f3518..2a1bfad1 100644 --- a/docs/architecture/winrt-interface-implementations.md +++ b/docs/architecture/winrt-interface-implementations.md @@ -111,8 +111,11 @@ type-name mapping with ordinary projected members. Self-interface references use the locally declared class name; imported structs use the same collision alias in `.py` and `.pyi`. Types with identical short names in other namespaces remain distinct imports, including references nested in arrays or delegate signatures. -Standalone interface and runtime-class modules use local names for embedded -struct helpers; standalone struct modules retain aliases for imported fields. +Self-import filtering compares canonical identities, so a closed generic such +as `IBox` cannot hide a distinct named `IBox_String` in the same namespace. +Standalone interface and runtime-class modules use the actual declared metadata +names for embedded struct helpers, even when their cross-module projected names +are disambiguated; standalone struct modules retain aliases for imported fields. Language bindings additionally gate dispatch on their environment/interpreter lifetime. Callback roots belong to the native object, not merely the original 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 afa5be90..355cc9d1 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -34,12 +34,7 @@ pub fn generate_class( shared_iids: &HashSet, ) -> String { let used_structs = collect_used_structs_from_class(class); - let context = context.with_local_types( - used_structs - .iter() - .filter(|_| !context.is_packaged()) - .map(TypeMeta::type_identity), - ); + let context = context.with_local_types(None, &used_structs); let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); 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 b761f6da..05c8750b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -79,14 +79,7 @@ pub fn generate_enum(_context: &PythonProjectionContext, en: &TypeMeta) -> Optio pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String { let used_structs = collect_used_structs_from_iface(iface); let type_imports = collect_iface_type_imports_by_identity(iface); - let context = context.with_local_types( - std::iter::once(iface.type_identity()).chain( - used_structs - .iter() - .filter(|_| !context.is_packaged()) - .map(TypeMeta::type_identity), - ), - ); + let context = context.with_local_types(Some(iface), &used_structs); let context = context.as_ref(); let mut projected_iface = iface.clone(); projected_iface.name = context.projected_name_for_interface(iface); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index bfbd0d94..62827e0e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -553,18 +553,33 @@ impl PythonProjectionContext { self.packaged } - /// Locally declared types use their exported names, not cross-module aliases. + /// Interfaces declare projected names; embedded structs retain metadata names. pub(super) fn with_local_types( &self, - identities: impl IntoIterator, + interface: Option<&InterfaceMeta>, + structs: &[TypeMeta], ) -> Cow<'_, Self> { + let declarations = interface + .into_iter() + .map(|interface| { + ( + interface.type_identity(), + self.projected_name_for_interface(interface), + ) + }) + .chain(structs.iter().filter_map(|typ| match typ { + TypeMeta::Struct { name, .. } if !self.is_packaged() => { + Some((typ.type_identity(), name.clone())) + } + _ => None, + })); let mut context = Cow::Borrowed(self); - for identity in identities { + for (identity, declaration_name) in declarations { let identity = self.normalize_identity(&identity); - if self.reference_name(&identity) != self.projected_name(&identity) + if self.reference_name(&identity) != declaration_name && let Some(projection) = context.to_mut().projections.get_mut(&identity) { - projection.reference_name = projection.projected_name.clone(); + projection.reference_name = declaration_name; } } context diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index e09d6452..ab27338f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -223,14 +223,7 @@ pub fn generate_enum_stub(_context: &PythonProjectionContext, en: &TypeMeta) -> pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String { let used_structs = collect_used_structs_from_iface(iface); let type_imports = collect_iface_type_imports_by_identity(iface); - let context = context.with_local_types( - std::iter::once(iface.type_identity()).chain( - used_structs - .iter() - .filter(|_| !context.is_packaged()) - .map(TypeMeta::type_identity), - ), - ); + let context = context.with_local_types(Some(iface), &used_structs); let context = context.as_ref(); let mut projected_iface = iface.clone(); projected_iface.name = context.projected_name_for_interface(iface); @@ -576,12 +569,7 @@ pub fn generate_class_stub( shared_iids: &HashSet, ) -> String { let used_structs = collect_used_structs_from_class(class); - let context = context.with_local_types( - used_structs - .iter() - .filter(|_| !context.is_packaged()) - .map(TypeMeta::type_identity), - ); + let context = context.with_local_types(None, &used_structs); let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs index b91fc2b9..0ce68512 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs @@ -8,7 +8,7 @@ use std::collections::HashSet; use std::sync::LazyLock; use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection}; -use crate::types::{TypeIdentity, TypeKind, TypeMeta, TypeRef}; +use crate::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; /// Empty set passed as `deferred` for codegen (no circular dep handling needed). pub(crate) static NO_DEFERRED: LazyLock> = LazyLock::new(HashSet::new); @@ -189,13 +189,17 @@ pub(crate) fn collect_iface_type_imports(iface: &InterfaceMeta) -> HashSet HashSet { + let self_identity = iface.type_identity(); let mut imports = collect_iface_type_imports_except(iface, ""); imports.retain(|reference| { - reference.kind != TypeKind::Interface - || reference.namespace != iface.namespace - || reference.name != iface.name + let kind = match reference.kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + TypeIdentity::named(kind, &reference.namespace, &reference.name) != self_identity }); imports } diff --git a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs index 0c4d20f8..16bd74e5 100644 --- a/tools/dynwinrt-codegen/tests/implementation_naming_test.rs +++ b/tools/dynwinrt-codegen/tests/implementation_naming_test.rs @@ -457,6 +457,49 @@ fn runtime_available() -> bool { available } +fn typecheck_py_package(directory: &Path) { + if Command::new(python()) + .args(["-m", "mypy", "--version"]) + .output() + .is_ok_and(|output| output.status.success()) + { + success( + Command::new(python()) + .args([ + "-m", + "mypy", + "--no-incremental", + "--follow-imports=silent", + "pyviews", + ]) + .current_dir(directory) + .env("MYPYPATH", root().join("bindings").join("py")) + .output() + .unwrap(), + ); + } +} + +fn write_python_module(package: &Path, module: &str, source: String, stub: String) { + fs::write(package.join(format!("{module}.py")), source).unwrap(); + fs::write(package.join(format!("{module}.pyi")), stub).unwrap(); +} + +fn write_python_support(package: &Path, implementation_modules: &[String]) { + for (name, source) in [ + ("__init__.py", String::new()), + ("_runtime.py", python::generate_runtime_support_module()), + ("_runtime.pyi", python_stub::generate_runtime_support_stub()), + ("_typing.pyi", python_stub::generate_typing_support_module()), + ( + "_implementation_types.pyi", + python_stub::generate_implementation_pair_types(implementation_modules), + ), + ] { + fs::write(package.join(name), source).unwrap(); + } +} + fn python_inventory(directory: &Path) -> Vec { fs::read_to_string(directory.join(".dynwinrt-generated-types")) .unwrap() @@ -763,41 +806,11 @@ fn python_handler_annotations_resolve_colliding_struct_and_interface_names() { assert_type(InlineEnvelope().item, InlinePayload)\n\ assert_type(StandaloneEnvelope().item, AlphaPayload)\n" ); - for (name, source) in [ - ("__init__.py", String::new()), - ("_runtime.py", python::generate_runtime_support_module()), - ("_runtime.pyi", python_stub::generate_runtime_support_stub()), - ("_typing.pyi", python_stub::generate_typing_support_module()), - ( - "_implementation_types.pyi", - python_stub::generate_implementation_pair_types(&modules), - ), - ] { - fs::write(package.join(name), source).unwrap(); - } + write_python_support(&package, &modules); typecheck_py(&fixture.0, &consumer); // Imported stubs are otherwise silenced by the consumer harness. - if Command::new(python()) - .args(["-m", "mypy", "--version"]) - .output() - .is_ok_and(|output| output.status.success()) - { - success( - Command::new(python()) - .args([ - "-m", - "mypy", - "--no-incremental", - "--follow-imports=silent", - "pyviews", - ]) - .current_dir(&fixture.0) - .env("MYPYPATH", root().join("bindings").join("py")) - .output() - .unwrap(), - ); - } + typecheck_py_package(&fixture.0); if runtime_available() { success(Command::new(python()).args(["-B", "-c", r#" import ast, importlib, pathlib, typing @@ -831,6 +844,304 @@ for path in pathlib.Path('pyviews').glob('*__*.py'): } } +fn collision_box_type() -> TypeMeta { + TypeMeta::Parameterized { + namespace: "Contoso".into(), + name: "IBox`1".into(), + piid: "31d44731-6281-4900-b782-040302010910".into(), + args: vec![TypeMeta::String], + } +} + +fn collision_box_interface(methods: Vec) -> InterfaceMeta { + let TypeMeta::Parameterized { piid, args, .. } = collision_box_type() else { + unreachable!() + }; + InterfaceMeta { + namespace: "Contoso".into(), + name: "IBox_String".into(), + generic_piid: Some(piid), + generic_name: Some("IBox`1".into()), + generic_args: args, + methods, + ..Default::default() + } +} + +fn echo_type(name: &str, typ: TypeMeta, vtable_index: usize) -> MethodMeta { + MethodMeta { + name: name.into(), + vtable_index, + params: vec![ParamMeta { + name: "value".into(), + typ: typ.clone(), + direction: ParamDirection::In, + }], + return_type: Some(typ), + ..Default::default() + } +} + +#[test] +fn python_full_identity_collision_preserves_local_struct_declarations() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.0.join("pyviews"); + fs::create_dir_all(&package).unwrap(); + let structure = TypeMeta::Struct { + namespace: "Contoso".into(), + name: "IBox_String".into(), + fields: vec![FieldMeta { + name: "Value".into(), + typ: TypeMeta::I32, + }], + }; + let envelope = TypeMeta::Struct { + namespace: "Contoso".into(), + name: "Envelope".into(), + fields: vec![FieldMeta { + name: "Item".into(), + typ: structure.clone(), + }], + }; + let generic = collision_box_interface(vec![echo_type("EchoSelf", collision_box_type(), 6)]); + let host = InterfaceMeta { + namespace: "Contoso".into(), + name: "IHost".into(), + iid: "31d44731-6281-4900-b782-040302010912".into(), + methods: vec![ + echo_type("EchoEnvelope", envelope.clone(), 6), + echo_type("EchoBox", collision_box_type(), 7), + ], + ..Default::default() + }; + let class = ClassMeta { + namespace: "Contoso".into(), + name: "Host".into(), + full_name: "Contoso.Host".into(), + static_interfaces: vec![host.clone()], + ..Default::default() + }; + let context = python::PythonProjectionContext::new( + [ + generic.type_identity(), + host.type_identity(), + structure.type_identity(), + envelope.type_identity(), + ], + packaged, + ) + .unwrap(); + let struct_alias = context.reference_name_for_type(&structure); + assert_eq!(struct_alias, "IBox_String_Contoso_IBox_String_struct"); + for (module, source, stub) in [ + ( + context.implementation_module_for_interface(&host), + python::generate_interface(&context, &host), + python_stub::generate_interface_stub(&context, &host), + ), + ( + "contoso__host".into(), + python::generate_class(&context, &class, &Default::default()), + python_stub::generate_class_stub(&context, &class, &Default::default()), + ), + ] { + for text in [&source, &stub] { + if packaged { + assert!(text.contains(&format!("IBox_String as {struct_alias}"))); + } else { + assert!(text.contains("class IBox_String:")); + assert!(text.contains("class Envelope:")); + assert!(!text.contains(&struct_alias), "{module}: {text}"); + } + } + if !packaged { + assert!(source.contains("self.item = IBox_String() if item is None else item")); + assert!(stub.contains(" item: 'IBox_String'\n")); + } + write_python_module(&package, &module, source, stub); + } + write_python_module( + &package, + &context.implementation_module_for_interface(&generic), + python::generate_interface(&context, &generic), + python_stub::generate_interface_stub(&context, &generic), + ); + if packaged { + for typ in [&structure, &envelope] { + write_python_module( + &package, + &context.implementation_module_for_type(typ), + python::generate_struct(&context, typ).unwrap(), + python_stub::generate_struct_stub(&context, typ).unwrap(), + ); + } + } + let modules = if packaged { + vec![context.implementation_module_for_interface(&host)] + } else { + vec![] + }; + write_python_support(&package, &modules); + let (class_payload, interface_payload) = if packaged { + let module = context.implementation_module_for_type(&structure); + (module.clone(), module) + } else { + ("contoso__host".into(), "contoso__i_host".into()) + }; + let (class_envelope, interface_envelope) = if packaged { + let module = context.implementation_module_for_type(&envelope); + (module.clone(), module) + } else { + ("contoso__host".into(), "contoso__i_host".into()) + }; + typecheck_py( + &fixture.0, + &format!( + "from typing import assert_type\n\ + from pyviews.contoso__host import Host\n\ + from pyviews.contoso__i_host import IHost\n\ + from pyviews.{class_envelope} import Envelope as ClassEnvelope\n\ + from pyviews.{interface_envelope} import Envelope as InterfaceEnvelope\n\ + from pyviews.{class_payload} import IBox_String as ClassPayload\n\ + from pyviews.{interface_payload} import IBox_String as InterfacePayload\n\ + assert_type(ClassEnvelope().item, ClassPayload)\n\ + assert_type(InterfaceEnvelope().item, InterfacePayload)\n\ + def check(interface: IHost) -> None:\n\ + \x20 assert_type(Host.echo_envelope(ClassEnvelope()), ClassEnvelope)\n\ + \x20 assert_type(interface.echo_envelope(InterfaceEnvelope()), InterfaceEnvelope)\n" + ), + ); + typecheck_py_package(&fixture.0); + if runtime_available() { + success( + Command::new(python()) + .args([ + "-B", + "-c", + r#" +import importlib, typing +for name in ('contoso__host', 'contoso__i_host'): + module = importlib.import_module('pyviews.' + name) + envelope = module.Envelope() + assert type(envelope.item).__name__ == 'IBox_String' + assert typing.get_type_hints(module.Envelope.__init__)['item'] == type(envelope.item) | None + if hasattr(module, 'IBox_String'): + assert type(envelope.item) is module.IBox_String +"#, + ]) + .current_dir(&fixture.0) + .output() + .unwrap(), + ); + } + } +} + +#[test] +fn python_full_identity_collision_imports_named_peer_not_generic_self() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.0.join("pyviews"); + fs::create_dir_all(&package).unwrap(); + let mut peers = Vec::new(); + let mut methods = vec![echo_type("EchoSelf", collision_box_type(), 6)]; + for (namespace, method, iid) in [ + ( + "Contoso", + "EchoPeer", + "31d44731-6281-4900-b782-040302010911", + ), + ( + "Fabrikam", + "EchoForeign", + "31d44731-6281-4900-b782-040302010913", + ), + ] { + let typ = TypeMeta::Interface { + namespace: namespace.into(), + name: "IBox_String".into(), + iid: iid.into(), + }; + methods.push(echo_type(method, typ.clone(), 6 + methods.len())); + peers.push(InterfaceMeta { + namespace: namespace.into(), + name: "IBox_String".into(), + iid: iid.into(), + methods: vec![echo_type("EchoSelf", typ, 6)], + ..Default::default() + }); + } + let generic = collision_box_interface(methods); + let context = python::PythonProjectionContext::new( + std::iter::once(generic.type_identity()) + .chain(peers.iter().map(InterfaceMeta::type_identity)), + packaged, + ) + .unwrap(); + let mut implementation_modules = Vec::new(); + for interface in std::iter::once(&generic).chain(&peers) { + let module = context.implementation_module_for_interface(interface); + let source = python::generate_interface(&context, interface); + let stub = python_stub::generate_interface_stub(&context, interface); + for text in [&source, &stub] { + assert!(!text.contains(&format!("from .{module} import "))); + if interface.generic_piid.is_some() { + for peer in &peers { + let peer_module = context.implementation_module_for_interface(peer); + assert!( + text.contains(&format!("from .{peer_module} import ")), + "missing named peer import: {text}" + ); + } + } + } + write_python_module(&package, &module, source, stub); + if packaged && interface.generic_piid.is_none() { + implementation_modules.push(module); + } + } + write_python_support(&package, &implementation_modules); + let generic_module = context.implementation_module_for_interface(&generic); + let generic_name = context.projected_name_for_interface(&generic); + let peer_module = context.implementation_module_for_interface(&peers[0]); + let peer_name = context.projected_name_for_interface(&peers[0]); + let foreign_module = context.implementation_module_for_interface(&peers[1]); + let foreign_name = context.projected_name_for_interface(&peers[1]); + typecheck_py( + &fixture.0, + &format!( + "from typing import assert_type\n\ + from pyviews.{generic_module} import {generic_name} as Box\n\ + from pyviews.{peer_module} import {peer_name} as Peer\n\ + from pyviews.{foreign_module} import {foreign_name} as Foreign\n\ + def check(box: Box, peer: Peer, foreign: Foreign) -> None:\n\ + \x20 assert_type(box.echo_self(box), Box | None)\n\ + \x20 assert_type(box.echo_peer(peer), Peer | None)\n\ + \x20 assert_type(box.echo_foreign(foreign), Foreign | None)\n\ + \x20 assert_type(peer.echo_self(peer), Peer | None)\n" + ), + ); + typecheck_py_package(&fixture.0); + if runtime_available() { + success(Command::new(python()).args(["-B", "-c", &format!(r#" +import ast, importlib, pathlib, typing +module = importlib.import_module('pyviews.{generic_module}') +for statement in ast.parse(pathlib.Path(module.__file__).read_text(encoding='utf-8')).body: + if isinstance(statement, ast.If) and ast.unparse(statement.test) == 'TYPE_CHECKING': + exec(compile(ast.Module(body=statement.body, type_ignores=[]), module.__file__, 'exec'), vars(module)) +box = module.{generic_name} +peer = importlib.import_module('pyviews.{peer_module}').{peer_name} +foreign = importlib.import_module('pyviews.{foreign_module}').{foreign_name} +for method, expected in ((box.echo_self, box), (box.echo_peer, peer), (box.echo_foreign, foreign), (peer.echo_self, peer)): + hints = typing.get_type_hints(method) + assert hints['value'] is expected + assert hints['return'] == expected | None +"#)]).current_dir(&fixture.0).output().unwrap()); + } + } +} + fn snapshot(directory: &Path) -> BTreeMap> { fn visit(root: &Path, path: &Path, files: &mut BTreeMap>) { for entry in fs::read_dir(path).unwrap() {