diff --git a/docs/architecture/winrt-interface-implementations.md b/docs/architecture/winrt-interface-implementations.md index 5f4f5d5d..35bf4be6 100644 --- a/docs/architecture/winrt-interface-implementations.md +++ b/docs/architecture/winrt-interface-implementations.md @@ -117,16 +117,35 @@ 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. -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. +Python declarations, annotations, imports, and conversion helpers share a +module-local symbol mapping keyed by canonical `TypeIdentity` and symbol role. +Self-class and self-interface references use the actual local declaration; +foreign class `Like` and identity markers import the defining module's symbol +and alias it to the consuming module's reference name. Handler, delegate, array, +and result-dictionary conversions use the same mapping as ordinary members. +Self-import filtering distinguishes namespaces, kinds, and named versus closed +generic types, so `IBox` cannot hide a distinct named `IBox_String`. + +Struct modules retain their public `pack_*`, `unpack_*`, and `*_TYPE` names. +When different struct names normalize to the same helper name (for example, +`URLValue` and `UrlValue`), consumers import those helpers under distinct +identity-qualified aliases. Standalone interface and runtime-class modules keep +embedded struct class names and disambiguate only colliding helper symbols; +standalone struct modules retain aliases for imported fields. The existing +fail-closed guard for identical raw struct names in one closure remains. +The allocator also compares helpers with actual local and imported type/marker +symbols, not unrelated types elsewhere in the package. If a foreign type +collides with an owning struct's public helper or type constant, the foreign +import is aliased instead; the struct's isolated public API stays unchanged. +Actual native registration variables also participate in module allocation: +the interface registration, or a class's default/factory/static/required +registrations and its activation factory only when emitted. Registration +declarations and invocation sites read the same symbol roles, independently of +type aliases, so neither an existing helper nor a newly qualified helper alias +can overwrite a registration object. +Enum declarations, namespace exports, defaults, and runtime conversions use the +same projected name, including named/closed-generic collisions; native enum +descriptors continue to use the original metadata identity. 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/common.rs b/tools/dynwinrt-codegen/src/codegen/common.rs index e7130eff..1366596f 100644 --- a/tools/dynwinrt-codegen/src/codegen/common.rs +++ b/tools/dynwinrt-codegen/src/codegen/common.rs @@ -597,30 +597,32 @@ mod tests { #[test] fn py_wrap_arg_types() { + let context = PythonProjectionContext::default(); assert_eq!( - py_wrap_arg("s", &TypeMeta::String), + py_wrap_arg("s", &TypeMeta::String, &context), "DynWinRTValue.from_hstring(s)" ); assert_eq!( - py_wrap_arg("b", &TypeMeta::Bool), + py_wrap_arg("b", &TypeMeta::Bool, &context), "DynWinRTValue.from_bool(b)" ); assert_eq!( - py_wrap_arg("n", &TypeMeta::I32), + py_wrap_arg("n", &TypeMeta::I32, &context), "DynWinRTValue.from_i32(n)" ); assert_eq!( - py_wrap_arg("n", &TypeMeta::I64), + py_wrap_arg("n", &TypeMeta::I64, &context), "DynWinRTValue.from_i64(n)" ); assert_eq!( - py_wrap_arg("f", &TypeMeta::F64), + py_wrap_arg("f", &TypeMeta::F64, &context), "DynWinRTValue.from_f64(f)" ); } #[test] fn wraps_python_ireference_inputs() { + let context = PythonProjectionContext::default(); let reference = |inner| TypeMeta::Parameterized { namespace: "Windows.Foundation".into(), name: "IReference".into(), @@ -629,7 +631,7 @@ mod tests { }; assert!( - py_wrap_arg("value", &reference(TypeMeta::String)) + py_wrap_arg("value", &reference(TypeMeta::String), &context) .contains("lambda value: DynWinRTValue.from_hstring(value)") ); assert!( @@ -639,7 +641,8 @@ mod tests { namespace: "Windows.Foundation".into(), name: "Point".into(), fields: vec![], - }) + }), + &context ) .contains("lambda value: _pack_point(value).to_value()") ); @@ -654,7 +657,8 @@ mod tests { is_flags: false, doc: None, deprecated: None, - }) + }), + &context ) .contains("lambda value: DynWinRTValue.enum_value(") ); @@ -792,16 +796,17 @@ mod tests { #[test] fn py_struct_field_setter_expressions() { + let context = PythonProjectionContext::default(); assert_eq!( - py_struct_field_setter(&TypeMeta::Bool, 0, "v"), + py_struct_field_setter(&context, &TypeMeta::Bool, 0, "v"), "s.set_u8(0, 1 if v else 0)" ); assert_eq!( - py_struct_field_setter(&TypeMeta::I32, 1, "x"), + py_struct_field_setter(&context, &TypeMeta::I32, 1, "x"), "s.set_i32(1, x)" ); assert_eq!( - py_struct_field_setter(&TypeMeta::String, 2, "s_"), + py_struct_field_setter(&context, &TypeMeta::String, 2, "s_"), "s.set_hstring(2, s_)" ); } 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 355cc9d1..186f113c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -34,7 +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(None, &used_structs); + let context = context.for_class_module(class, &used_structs); let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); @@ -190,7 +190,8 @@ pub fn generate_class( } // Type imports - let imports = collect_type_imports(class); + let imports = + crate::codegen::winrt::shared::imports::collect_class_type_imports_by_identity(class); let mut sorted_imports: Vec<_> = imports.iter().collect(); sorted_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); @@ -276,45 +277,21 @@ pub fn generate_class( out.push('\n'); // Interface registrations - if let Some(ref iface) = class.default_interface { - let symbol = interface_symbol(context, iface); - out.push_str(&py_generate_interface_registration( - iface, - &format!("_{symbol}"), - &symbol, - )); - out.push('\n'); - } - for iface in &class.factory_interfaces { - let symbol = interface_symbol(context, iface); - out.push_str(&py_generate_interface_registration( - iface, - &format!("_{symbol}"), - &symbol, - )); - out.push('\n'); - } - for iface in &class.static_interfaces { - let symbol = interface_symbol(context, iface); - out.push_str(&py_generate_interface_registration( - iface, - &format!("_{symbol}"), - &symbol, - )); - out.push('\n'); - } - for iface in &class.required_interfaces { + for iface in class.all_interfaces() { let symbol = interface_symbol(context, iface); out.push_str(&py_generate_interface_registration( iface, - &format!("_{symbol}"), + &context.registration_symbol(iface), &symbol, )); out.push('\n'); } // IActivationFactory for default constructor if class.has_default_activation() { - out.push_str("_IActivationFactory = DynWinRTType.register_interface(\n"); + out.push_str(&format!( + "{} = DynWinRTType.register_interface(\n", + context.activation_factory_symbol(class), + )); out.push_str( " 'IActivationFactory', WinGUID.parse('00000035-0000-0000-c000-000000000046')) \\\n", ); @@ -332,9 +309,12 @@ pub fn generate_class( // Class declaration if let Some(mixin) = collection_kind.and_then(runtime_mixin) { - out.push_str(&format!("\nclass {}({mixin}):\n", class.name)); + out.push_str(&format!( + "\nclass {}({mixin}):\n", + context.class_name(class) + )); } else { - out.push_str(&format!("\nclass {}:\n", class.name)); + out.push_str(&format!("\nclass {}:\n", context.class_name(class))); } { let doc = crate::codegen::winrt::shared::docs::DocText { @@ -414,10 +394,14 @@ pub fn generate_class( }); let ctor_name = default_constructor_name(has_create_factory); out.push_str(" @staticmethod\n"); - out.push_str(&format!(" def {}() -> '{}':\n", ctor_name, class.name)); out.push_str(&format!( - " return {}._from_native(_IActivationFactory.method(6).invoke(DynWinRTValue.activation_factory('{}'), []))\n", - class.name, class.full_name + " def {}() -> '{}':\n", + ctor_name, + context.class_name(class) + )); + out.push_str(&format!( + " return {}._from_native({}.method(6).invoke(DynWinRTValue.activation_factory('{}'), []))\n", + context.class_name(class), context.activation_factory_symbol(class), class.full_name )); out.push('\n'); } @@ -501,14 +485,17 @@ pub fn generate_class( if create_instance_no_args { out.push('\n'); out.push_str(" @staticmethod\n"); - out.push_str(&format!(" def create() -> '{}':\n", class.name)); + out.push_str(&format!( + " def create() -> '{}':\n", + context.class_name(class) + )); out.push_str(&format!( " \"\"\"Create a new `{}` instance. Alias for `create_instance()`.\"\"\"\n", - class.name + context.class_name(class) )); out.push_str(&format!( " return {}.create_instance()\n", - class.name + context.class_name(class) )); } } @@ -542,7 +529,7 @@ pub fn generate_class( out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create_with_metadata_provider(metadata_provider: '{metadata_provider}', on_launched: Callable[[], object] | None = None) -> '{}':\n", - class.name, + context.class_name(class), )); out.push_str( " \"\"\"Compose a WinUI `Application` that exposes the supplied XAML metadata provider.\n\ @@ -558,14 +545,14 @@ pub fn generate_class( )); out.push_str(&format!( " return {}._from_native(DynWinRTValue.create_xaml_application(getattr(metadata_provider, '_obj', metadata_provider), _launched))\n", - class.name + context.class_name(class) )); out.push('\n'); out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create(on_launched: Callable[[], object] | None = None) -> '{}':\n", - class.name + context.class_name(class) )); out.push_str( " \"\"\"Compose a WinUI `Application`, install WinUI's default Fluent resources,\n\ @@ -578,7 +565,7 @@ pub fn generate_class( out.push_str(" def _on_launched_wrapped(_args):\n"); out.push_str(&format!( " _app = {}.get_current()\n", - class.name + context.class_name(class) )); out.push_str(" if _app is None:\n"); out.push_str( @@ -597,7 +584,7 @@ pub fn generate_class( )); out.push_str(&format!( " _app = {}._from_native(DynWinRTValue.create_xaml_application(getattr(_provider, '_obj', _provider), _launched))\n", - class.name + context.class_name(class) )); if bootstrap.supports_unpackaged_resources { out.push_str( @@ -671,7 +658,7 @@ pub fn generate_class( &instance_method_names, ); let overload = InstanceOverload { - iface_var: format!("_{iface_symbol}"), + iface_var: context.registration_symbol(iface), obj_expr: obj_expr.clone(), method, sibling_methods: Some(iface.methods.as_slice()), @@ -856,7 +843,7 @@ pub fn generate_class( if imported_names.contains(&symbol) { continue; } - let reg_var = format!("_{symbol}"); + let reg_var = context.registration_symbol(req_iface); out.push('\n'); if let Some(mixin) = interface_kind(req_iface).and_then(runtime_mixin) { out.push_str(&format!("\nclass {symbol}({mixin}):\n")); @@ -1119,9 +1106,10 @@ fn build_ctor_candidates<'a>( .collect::>() .join(", "); let composed_call_expr = format!( - "_{factory}.method({vtable}).invoke_composed_with_overrides({class}._get_f_{factory}(), [{wrapped_args}], {outer_index}, {inner_output_index}, {instance_output_index}, {agile}, _override_interfaces)", + "{registration}.method({vtable}).invoke_composed_with_overrides({class}._get_f_{factory}(), [{wrapped_args}], {outer_index}, {inner_output_index}, {instance_output_index}, {agile}, _override_interfaces)", + registration = context.registration_symbol(factory), factory = interface_symbol(context, factory), - class = class.name, + class = context.class_name(class), vtable = method.vtable_index, agile = if class.is_agile { "True" } else { "False" }, ); @@ -1338,7 +1326,10 @@ fn generate_python_constructor( ); } if !candidates.is_empty() { - out.push_str(&format!(" if cls is {}:\n", class.name)); + out.push_str(&format!( + " if cls is {}:\n", + context.class_name(class) + )); for candidate in &candidates { let parameter_names = candidate .public_params @@ -1383,10 +1374,13 @@ fn generate_python_constructor( out.push_str(" def _set_native(self, obj: DynWinRTValue):\n"); } if let Some(native_override_names) = &native_override_names { - out.push_str(&format!(" if type(self) is not {}:\n", class.name)); + out.push_str(&format!( + " if type(self) is not {}:\n", + context.class_name(class) + )); out.push_str(&format!( " _native_members = set().union(*(set(_type.__dict__) for _type in type(self).__mro__ if _type is not {}))\n", - class.name + context.class_name(class) )); out.push_str(&format!( " _native_overrides = sorted(_native_members.intersection({native_override_names}))\n" @@ -1394,7 +1388,7 @@ fn generate_python_constructor( out.push_str(" if _native_overrides:\n"); out.push_str(&format!( " if _allow_native_overrides:\n pass\n else:\n raise TypeError(\"{} native overrides require public composable construction: \" + \", \".join(_native_overrides))\n", - class.name + context.class_name(class) )); } if let Some(default_iface) = &class.default_interface { @@ -1441,19 +1435,19 @@ fn generate_python_constructor( ); out.push_str(&format!( " \"\"\"Register a Python `{}` subclass for process-local XAML markup activation.\"\"\"\n", - class.name + context.class_name(class) )); out.push_str(&format!( " if not isinstance(control_type, type) or control_type is {} or not issubclass(control_type, {}):\n", - class.name, class.name + context.class_name(class), context.class_name(class) )); out.push_str(&format!( " raise TypeError(\"control_type must be a Python subclass of {}\")\n", - class.name + context.class_name(class) )); out.push_str(&format!( " _native_members = set().union(*(set(_type.__dict__) for _type in control_type.__mro__ if _type is not {}))\n", - class.name + context.class_name(class) )); out.push_str(&format!( " _native_overrides = sorted(_native_members.intersection({native_override_names}))\n" @@ -1464,7 +1458,7 @@ fn generate_python_constructor( out.push_str(" if _unsupported_native_overrides:\n"); out.push_str(&format!( " raise TypeError(\"{} native override ABI is unsupported: \" + \", \".join(_unsupported_native_overrides))\n", - class.name + context.class_name(class) )); let default_iid = class .default_interface @@ -1495,12 +1489,12 @@ fn generate_python_constructor( .expect("public composition override names"); out.push_str(&format!( " _is_python_subclass = type(self) is not {}\n", - class.name + context.class_name(class) )); out.push_str(" if _is_python_subclass:\n"); out.push_str(&format!( " _native_members = set().union(*(set(_type.__dict__) for _type in type(self).__mro__ if _type is not {}))\n", - class.name + context.class_name(class) )); out.push_str(&format!( " _native_overrides = sorted(_native_members.intersection({native_override_names}))\n" @@ -1511,7 +1505,7 @@ fn generate_python_constructor( out.push_str(" if _unsupported_native_overrides:\n"); out.push_str(&format!( " raise TypeError(\"{} native override ABI is unsupported: \" + \", \".join(_unsupported_native_overrides))\n", - class.name + context.class_name(class) )); out.push_str(" _override_interfaces = []\n"); out.push_str(" _override_target_ref = _weakref_ref(self)\n"); @@ -1590,7 +1584,7 @@ fn generate_python_constructor( out.push_str(" if _is_python_subclass:\n"); out.push_str(&format!( " raise TypeError(\"{} does not support Python subclass construction for this constructor\")\n", - class.name + context.class_name(class) )); } out.push_str(&format!( @@ -1602,12 +1596,12 @@ fn generate_python_constructor( if candidates.is_empty() { out.push_str(&format!( " raise TypeError(\"{} cannot be constructed directly\")\n\n", - class.name + context.class_name(class) )); } else { out.push_str(&format!( " raise TypeError(\"No matching constructor for {}\")\n\n", - class.name + context.class_name(class) )); } out diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/imports.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/imports.rs index c37c6cdc..ec7ae738 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/imports.rs @@ -3,56 +3,7 @@ //! Python generated-module import formatting. -use super::*; - -/// Format a Python import line based on type kind. -pub(super) fn format_py_type_import( - context: &PythonProjectionContext, - namespace: &str, - name: &str, - kind: TypeKind, -) -> String { - let identity_kind = match kind { - TypeKind::Class => crate::types::TypeIdentityKind::Class, - TypeKind::Enum => crate::types::TypeIdentityKind::Enum, - TypeKind::Interface => crate::types::TypeIdentityKind::Interface, - }; - let identity = crate::types::TypeIdentity::named(identity_kind, namespace, name); - let module = context.implementation_module(&identity); - let projected_name = context.projected_name(&identity); - let reference_name = context.reference_name(&identity); - let imported = |name: &str, alias: &str| { - if name == alias { - name.to_string() - } else { - format!("{name} as {alias}") - } - }; - if kind == TypeKind::Interface { - format!( - "from .{module} import {}, {} # noqa: F401\n", - imported( - &format!("IID_{projected_name}"), - &format!("IID_{reference_name}") - ), - imported(&projected_name, &reference_name) - ) - } else if kind == TypeKind::Class { - format!( - "from .{module} import {}, {} # noqa: F401\n", - imported(&projected_name, &reference_name), - imported( - &format!("{projected_name}Like"), - &format!("{reference_name}Like") - ) - ) - } else { - format!( - "from .{module} import {} # noqa: F401\n", - imported(&projected_name, &reference_name) - ) - } -} +pub(super) use super::super::naming::format_py_type_import; pub(super) fn emit_type_checking_imports(out: &mut String, imports: Vec) { let mut imports = imports; diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs index 0aa149d3..53ba7e58 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs @@ -20,7 +20,7 @@ pub fn generate_index( let mut sorted_classes: Vec<_> = classes.iter().collect(); sorted_classes.sort_by(|a, b| a.name.cmp(&b.name)); for class in sorted_classes { - if seen.insert(class.name.clone()) { + if seen.insert(context.class_name(class)) { let identity = crate::types::TypeIdentity::named( crate::types::TypeIdentityKind::Class, class.namespace.clone(), @@ -34,7 +34,7 @@ pub fn generate_index( let mut sorted_ifaces: Vec<_> = interfaces.iter().collect(); sorted_ifaces.sort_by(|a, b| a.name.cmp(&b.name)); for iface in sorted_ifaces { - if !seen.insert(iface.name.clone()) { + if !seen.insert(context.projected_name_for_interface(iface)) { continue; } let is_delegate = iface.is_delegate(); @@ -71,8 +71,8 @@ pub fn generate_index( name_a.cmp(name_b) }); for en in sorted_enums { - if let TypeMeta::Enum { name, .. } = en { - if seen.insert(name.clone()) { + if let TypeMeta::Enum { .. } = en { + if seen.insert(context.projected_name_for_type(en)) { let identity = en.type_identity(); let module = context.implementation_module(&identity); let name = context.projected_name(&identity); @@ -95,7 +95,7 @@ pub fn generate_public_index( let mut classes = classes.iter().collect::>(); classes.sort_by(|left, right| left.name.cmp(&right.name)); for class in classes { - if seen.insert(class.name.clone()) { + if seen.insert(context.class_name(class)) { let identity = crate::types::TypeIdentity::named( crate::types::TypeIdentityKind::Class, class.namespace.clone(), @@ -114,7 +114,7 @@ pub fn generate_public_index( interfaces.sort_by(|left, right| left.name.cmp(&right.name)); for interface in interfaces { let is_delegate = interface.is_delegate(); - if !is_delegate && seen.insert(interface.name.clone()) { + if !is_delegate && seen.insert(context.projected_name_for_interface(interface)) { let identity = interface.type_identity(); let name = context.projected_name(&identity); out.push_str(&format!( @@ -137,10 +137,10 @@ pub fn generate_public_index( _ => "", }); for typ in enums { - let TypeMeta::Enum { name, .. } = typ else { + let TypeMeta::Enum { .. } = typ else { continue; }; - if seen.insert(name.clone()) { + if seen.insert(context.projected_name_for_type(typ)) { let identity = typ.type_identity(); let name = context.projected_name(&identity); out.push_str(&format!( @@ -267,7 +267,7 @@ pub fn append_to_index( ); let module = context.implementation_module(&identity); let name = context.projected_name(&identity); - if !exported_modules.contains(&module) && seen.insert(class.name.clone()) { + if !exported_modules.contains(&module) && seen.insert(name.clone()) { out.push_str(&format!("from .{} import {} # noqa: F401\n", module, name)); } } @@ -278,7 +278,7 @@ pub fn append_to_index( let identity = iface.type_identity(); let module = context.implementation_module(&identity); let name = context.projected_name(&identity); - if exported_modules.contains(&module) || !seen.insert(iface.name.clone()) { + if exported_modules.contains(&module) || !seen.insert(name.clone()) { continue; } let is_delegate = iface.is_delegate(); @@ -310,11 +310,11 @@ pub fn append_to_index( name_a.cmp(name_b) }); for en in sorted_enums { - if let TypeMeta::Enum { name, .. } = en { + if let TypeMeta::Enum { .. } = en { let identity = en.type_identity(); let module = context.implementation_module(&identity); let projected_name = context.projected_name(&identity); - if !exported_modules.contains(&module) && seen.insert(name.clone()) { + if !exported_modules.contains(&module) && seen.insert(projected_name.clone()) { out.push_str(&format!( "from .{} import {} # noqa: F401\n", module, projected_name 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 e3ee877e..32b69f8e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -14,9 +14,8 @@ use crate::types::{TypeKind, TypeMeta}; use crate::codegen::winrt::shared::imports::{ 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, + 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 21244db5..e267aeba 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs @@ -5,28 +5,17 @@ use super::imports::{emit_type_checking_imports, format_py_type_import}; use super::*; +use crate::codegen::winrt::python::naming::{PythonSymbol, STRUCT_SYMBOLS}; use crate::codegen::winrt::python::native_types::{FoundationType, foundation_type}; use crate::codegen::winrt::python::type_helpers::py_optional_type; use crate::types::FieldMeta; +pub(super) use super::super::naming::py_struct_export_names; + // ====================================================================== // Struct helpers: Python dataclass-style + _unpack/_pack functions // ====================================================================== -fn struct_runtime_import_names(s: &TypeMeta) -> Vec { - let TypeMeta::Struct { name, .. } = s else { - return Vec::new(); - }; - let snake = to_snake_case(name); - let mut names = py_struct_export_names(s); - names.extend([ - format!("_{name}_TYPE"), - format!("_pack_{snake}"), - format!("_unpack_{snake}"), - ]); - names -} - pub(super) fn generate_struct_imports( context: &PythonProjectionContext, structs: &[TypeMeta], @@ -34,18 +23,13 @@ pub(super) fn generate_struct_imports( let mut imports = structs .iter() .filter_map(|typ| { - let TypeMeta::Struct { name, .. } = typ else { + let TypeMeta::Struct { .. } = typ else { return None; }; - let names = struct_runtime_import_names(typ) + let names = STRUCT_SYMBOLS .into_iter() - .map(|export| { - if export == *name { - context.struct_type_import(typ, &export) - } else { - export - } - }) + .filter(|role| *role != PythonSymbol::Type || foundation_type(typ).is_none()) + .map(|role| context.symbol_import(&typ.type_identity(), role)) .collect::>(); Some(format!( "from .{} import {} # noqa: F401\n", @@ -66,13 +50,17 @@ pub fn generate_struct(context: &PythonProjectionContext, s: &TypeMeta) -> Optio if name == "HResult" { return None; } + let dependencies = collect_used_structs_from_struct(s); + let mut module_structs = dependencies.clone(); + module_structs.push(s.clone()); + let context = context.for_struct_module(s, &module_structs); + let context = context.as_ref(); let mut out = String::new(); out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); out.push_str(IMPORT_LINE); - let dependencies = collect_used_structs_from_struct(s); out.push_str(&generate_struct_imports(context, &dependencies)); if has_ireference_struct_field(std::slice::from_ref(s)) { out.push_str(IREFERENCE_HELPER); @@ -110,7 +98,7 @@ pub fn generate_struct(context: &PythonProjectionContext, s: &TypeMeta) -> Optio pub(super) fn generate_struct_helpers(context: &PythonProjectionContext, s: &TypeMeta) -> String { if let Some(kind) = foundation_type(s) { - return generate_foundation_struct_helpers(s, kind); + return generate_foundation_struct_helpers(context, s, kind); } let (namespace, name, fields) = match s { @@ -122,7 +110,12 @@ pub(super) fn generate_struct_helpers(context: &PythonProjectionContext, s: &Typ _ => return String::new(), }; let mut out = String::new(); - let snake_name = to_snake_case(name); + let pack = context.struct_symbol(s, PythonSymbol::Pack); + let unpack = context.struct_symbol(s, PythonSymbol::Unpack); + let private_pack = context.struct_symbol(s, PythonSymbol::PrivatePack); + let private_unpack = context.struct_symbol(s, PythonSymbol::PrivateUnpack); + let type_constant = context.struct_symbol(s, PythonSymbol::TypeConstant); + let private_type_constant = context.struct_symbol(s, PythonSymbol::PrivateTypeConstant); let field_names = py_struct_field_names(fields); let slot_names = fields.iter().map(py_struct_slot_name).collect::>(); @@ -207,10 +200,7 @@ pub(super) fn generate_struct_helpers(context: &PythonProjectionContext, s: &Typ out.push('\n'); // unpack function - out.push_str(&format!( - "\ndef unpack_{}(v: DynWinRTValue) -> {}:\n", - snake_name, name - )); + out.push_str(&format!("\ndef {unpack}(v: DynWinRTValue) -> {name}:\n",)); out.push_str(" s = v.as_struct()\n"); let field_args: Vec = fields .iter() @@ -225,33 +215,29 @@ pub(super) fn generate_struct_helpers(context: &PythonProjectionContext, s: &Typ .collect(); out.push_str(&format!(" return {}({})\n", name, field_args.join(", "))); // Internal alias - out.push_str(&format!("_unpack_{0} = unpack_{0}\n", snake_name)); + out.push_str(&format!("{private_unpack} = {unpack}\n")); // Type constant let full_name = format!("{}.{}", namespace, name); let field_types: Vec = fields.iter().map(|f| py_dynwinrt_type(&f.typ)).collect(); out.push_str(&format!( - "{}_TYPE = DynWinRTType.struct_type('{}', [{}])\n", - name, + "{type_constant} = DynWinRTType.struct_type('{}', [{}])\n", full_name, field_types.join(", ") )); - out.push_str(&format!("_{0}_TYPE = {0}_TYPE\n", name)); + out.push_str(&format!("{private_type_constant} = {type_constant}\n")); // pack function - out.push_str(&format!( - "\ndef pack_{}(v: {}) -> DynWinRTStruct:\n", - snake_name, name - )); - out.push_str(&format!(" s = DynWinRTStruct.create({}_TYPE)\n", name)); + out.push_str(&format!("\ndef {pack}(v: {name}) -> DynWinRTStruct:\n",)); + out.push_str(&format!(" s = DynWinRTStruct.create({type_constant})\n")); for (i, f) in fields.iter().enumerate() { out.push_str(&format!( " {}\n", - py_struct_field_setter(&f.typ, i, &format!("v.{}", to_snake_case(&f.name))) + py_struct_field_setter(context, &f.typ, i, &format!("v.{}", to_snake_case(&f.name))) )); } out.push_str(" return s\n"); - out.push_str(&format!("_pack_{0} = pack_{0}\n", snake_name)); + out.push_str(&format!("{private_pack} = {pack}\n")); out } @@ -315,7 +301,11 @@ fn py_struct_repr_expr(field_names: &[String]) -> String { format!("f'{{type(self).__name__}}({fields})'") } -fn generate_foundation_struct_helpers(s: &TypeMeta, kind: FoundationType) -> String { +fn generate_foundation_struct_helpers( + context: &PythonProjectionContext, + s: &TypeMeta, + kind: FoundationType, +) -> String { let TypeMeta::Struct { namespace, name, @@ -324,7 +314,12 @@ fn generate_foundation_struct_helpers(s: &TypeMeta, kind: FoundationType) -> Str else { unreachable!() }; - let snake_name = to_snake_case(name); + let pack = context.struct_symbol(s, PythonSymbol::Pack); + let unpack = context.struct_symbol(s, PythonSymbol::Unpack); + let private_pack = context.struct_symbol(s, PythonSymbol::PrivatePack); + let private_unpack = context.struct_symbol(s, PythonSymbol::PrivateUnpack); + let type_constant = context.struct_symbol(s, PythonSymbol::TypeConstant); + let private_type_constant = context.struct_symbol(s, PythonSymbol::PrivateTypeConstant); let native_type = match kind { FoundationType::DateTime => "datetime", FoundationType::TimeSpan => "timedelta", @@ -343,17 +338,17 @@ fn generate_foundation_struct_helpers(s: &TypeMeta, kind: FoundationType) -> Str .collect::>() .join(", "); format!( - "\ndef unpack_{snake_name}(v: DynWinRTValue) -> {native_type}:\n\ + "\ndef {unpack}(v: DynWinRTValue) -> {native_type}:\n\ \x20 return {from_ticks}(v.as_struct().get_i64(0))\n\ - _unpack_{snake_name} = unpack_{snake_name}\n\ - {name}_TYPE = DynWinRTType.struct_type('{namespace}.{name}', [{field_types}])\n\ - _{name}_TYPE = {name}_TYPE\n\ + {private_unpack} = {unpack}\n\ + {type_constant} = DynWinRTType.struct_type('{namespace}.{name}', [{field_types}])\n\ + {private_type_constant} = {type_constant}\n\ \n\ - def pack_{snake_name}(v: {native_type}) -> DynWinRTStruct:\n\ - \x20 s = DynWinRTStruct.create({name}_TYPE)\n\ + def {pack}(v: {native_type}) -> DynWinRTStruct:\n\ + \x20 s = DynWinRTStruct.create({type_constant})\n\ \x20 s.set_i64(0, {to_ticks}(v))\n\ \x20 return s\n\ - _pack_{snake_name} = pack_{snake_name}\n" + {private_pack} = {pack}\n" ) } @@ -375,10 +370,10 @@ pub(super) fn py_default_value(context: &PythonProjectionContext, typ: &TypeMeta | TypeMeta::U32 | TypeMeta::I64 | TypeMeta::U64 => "0".to_string(), - TypeMeta::Enum { name, .. } => format!( + TypeMeta::Enum { .. } => format!( "_dynwinrt_enum('{}', '{}', 0)", context.implementation_module_for_type(typ), - name + context.projected_name_for_type(typ) ), TypeMeta::Char16 => "'\\0'".to_string(), TypeMeta::F32 | TypeMeta::F64 => "0.0".to_string(), @@ -397,24 +392,3 @@ fn py_struct_constructor_field_type(context: &PythonProjectionContext, typ: &Typ _ => py_struct_field_type(context, typ), } } - -/// Returns the exported names for struct helpers (for Python index). -pub(super) fn py_struct_export_names(s: &TypeMeta) -> Vec { - match s { - TypeMeta::Struct { name, .. } => { - let snake = to_snake_case(name); - let mut names = if foundation_type(s).is_none() { - vec![name.clone()] - } else { - Vec::new() - }; - names.extend([ - format!("{}_TYPE", name), - format!("pack_{}", snake), - format!("unpack_{}", snake), - ]); - names - } - _ => vec![], - } -} 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 05c8750b..ab0873f1 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -13,24 +13,18 @@ use crate::codegen::winrt::python::collections::{ use crate::types::{TypeIdentity, TypeIdentityKind}; /// Generate a Python file for a single enum. -pub fn generate_enum(_context: &PythonProjectionContext, en: &TypeMeta) -> Option { - let (name, members, is_flags, enum_doc, enum_dep) = match en { +pub fn generate_enum(context: &PythonProjectionContext, en: &TypeMeta) -> Option { + let (members, is_flags, enum_doc, enum_dep) = match en { TypeMeta::Enum { - name, members, is_flags, doc, deprecated, .. - } => ( - name, - members, - *is_flags, - doc.as_deref(), - deprecated.as_deref(), - ), + } => (members, *is_flags, doc.as_deref(), deprecated.as_deref()), _ => return None, }; + let name = context.projected_name_for_type(en); let mut out = String::new(); out.push_str(HEADER); @@ -79,8 +73,9 @@ 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(Some(iface), &used_structs); + let context = context.for_interface_module(iface, &used_structs); let context = context.as_ref(); + let registration_symbol = context.registration_symbol(iface); let mut projected_iface = iface.clone(); projected_iface.name = context.projected_name_for_interface(iface); let iface = &projected_iface; @@ -244,7 +239,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe // Interface registration out.push_str(&py_generate_interface_registration( iface, - &format!("_{}", iface.name), + ®istration_symbol, &iface.name, )); out.push('\n'); @@ -365,7 +360,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe &iface.generic_args[0], context, ); - let wrap = py_wrap_native_value("item", &iface.generic_args[0]); + let wrap = py_wrap_native_value("item", &iface.generic_args[0], context); let vector_identity = observable_vector .as_ref() .expect("observable vector companion"); @@ -390,7 +385,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe &iface.generic_args[0], context, ); - let wrap = py_wrap_native_value("item", &iface.generic_args[0]); + let wrap = py_wrap_native_value("item", &iface.generic_args[0], context); out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create(items: Iterable[{}]) -> '{}':\n", @@ -412,8 +407,8 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe &iface.generic_args[1], context, ); - let wrap_key = py_wrap_native_value("item", &iface.generic_args[0]); - let wrap_value = py_wrap_native_value("item", &iface.generic_args[1]); + let wrap_key = py_wrap_native_value("item", &iface.generic_args[0], context); + let wrap_value = py_wrap_native_value("item", &iface.generic_args[1], context); out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create(items: Mapping[{}, {}]) -> '{}':\n", @@ -440,26 +435,40 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe } if is_element_factory { + let class_name = |name| { + context.projected_name(&TypeIdentity::named( + TypeIdentityKind::Class, + "Microsoft.UI.Xaml", + name, + )) + }; let get_args = py_runtime_named_symbol( context, TypeIdentityKind::Class, "Microsoft.UI.Xaml", "ElementFactoryGetArgs", - "ElementFactoryGetArgs", + &class_name("ElementFactoryGetArgs"), ); let recycle_args = py_runtime_named_symbol( context, TypeIdentityKind::Class, "Microsoft.UI.Xaml", "ElementFactoryRecycleArgs", - "ElementFactoryRecycleArgs", + &class_name("ElementFactoryRecycleArgs"), ); let ui_element_iid = py_runtime_named_symbol( context, TypeIdentityKind::Class, "Microsoft.UI.Xaml", "UIElement", - "IID_IUIElement", + &format!( + "IID_{}", + context.reference_name(&TypeIdentity::named( + TypeIdentityKind::Interface, + "Microsoft.UI.Xaml", + "IUIElement", + )) + ), ); out.push_str( r#" @staticmethod @@ -559,7 +568,7 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe } // Instance methods (reorder so @property comes before @x.setter) - let iface_var = format!("_{}", iface.name); + let iface_var = registration_symbol; let obj_expr = if observable_vector.is_some() { "self._observable_obj" } else { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs index fe97adba..81e9e8c5 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/implementation.rs @@ -743,16 +743,13 @@ fn project_validated( projector.prefix )); if let Some(kind) = foundation_type(&typ.metadata) { - let TypeMeta::Struct { name, .. } = &typ.metadata else { - unreachable!() - }; let annotation = match kind { FoundationType::DateTime => "datetime", FoundationType::TimeSpan => "timedelta", }; support.push_str(&format!( - " _implementation_check(value, isinstance(value, {annotation}), label)\n return _pack_{}(value).to_value()\n\n", - to_snake_case(name) + " _implementation_check(value, isinstance(value, {annotation}), label)\n return {}(value).to_value()\n\n", + context.struct_symbol(&typ.metadata, super::naming::PythonSymbol::PrivatePack) )); continue; } @@ -782,6 +779,7 @@ fn project_validated( projector.write(typ, &value, &field_name, None) ), _ => super::structs::py_struct_field_setter( + context, &typ.metadata, index, &projector.check_scalar(typ, &value, &field_name), diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs index 8c4bcd1d..08c617b6 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs @@ -132,7 +132,7 @@ pub(crate) fn py_wrap_method_arg( py_runtime_symbol(context, &delegate, &format!("{projected_name}_PARAM_TYPES")) ); } - py_wrap_arg(name, typ) + py_wrap_arg(name, typ, context) } fn py_build_method_args_expr( @@ -201,10 +201,11 @@ fn method_call_expr( method: &MethodMeta, obj_expr: &str, args_expr: &str, + context: &PythonProjectionContext, ) -> String { let invoke = if py_method_abi_output_count(method) > 1 { "invoke_all" - } else if winui::call_behavior(iface_var.trim_start_matches('_'), &method.name) + } else if winui::call_behavior(&context.registration_call_name(iface_var), &method.name) == WinUiCallBehavior::BlockingReentrant { "invoke_detached" @@ -281,7 +282,7 @@ fn generate_factory_method_invoke_named( let in_params = get_in_params(method); let py_params = py_param_list(&in_params, context); - let return_py_type = py_factory_return_type(&class.name, method, context); + let return_py_type = py_factory_return_type(&context.class_name(class), method, context); let mut out = String::new(); let method_name = name_override @@ -305,10 +306,11 @@ fn generate_factory_method_invoke_named( let args_expr = py_build_method_args_expr(&in_params, context); let iface_symbol = context.reference_name(&iface.type_identity()); let call_expr = method_call_expr( - &format!("_{iface_symbol}"), + &context.registration_symbol(iface), method, - &format!("{}._get_f_{iface_symbol}()", class.name), + &format!("{}._get_f_{iface_symbol}()", context.class_name(class)), &args_expr, + context, ); let result_expr = if py_method_abi_output_count(method) > 1 { out.push_str(&format!(" _results = {}\n", call_expr)); @@ -320,13 +322,20 @@ fn generate_factory_method_invoke_named( if let Some(async_type) = method.return_type.as_ref().filter(|typ| typ.is_async()) { let result_converter = match async_type { TypeMeta::AsyncOperation(_) | TypeMeta::AsyncOperationWithProgress(_, _) => { - Some(format!("lambda value: {}._from_native(value)", class.name)) + Some(format!( + "lambda value: {}._from_native(value)", + context.class_name(class) + )) } _ => None, }; py_wrap_async(&result_expr, async_type, result_converter, context) } else { - format!("{}._from_native({})", class.name, result_expr) + format!( + "{}._from_native({})", + context.class_name(class), + result_expr + ) }; out.push_str(&format!(" return {}\n", result_expr)); out @@ -358,7 +367,7 @@ fn generate_static_method_invoke_named( let statics_call = format!( "{cls}._get_s_{iface}()", - cls = class.name, + cls = context.class_name(class), iface = iface_symbol ); @@ -372,7 +381,13 @@ fn generate_static_method_invoke_named( prop_name, py_return )); out.push_str(&method_pydoc(method, &in_params)); - let call_expr = method_call_expr(&format!("_{iface_symbol}"), method, &statics_call, ""); + let call_expr = method_call_expr( + &context.registration_symbol(iface), + method, + &statics_call, + "", + context, + ); emit_method_result(&mut out, &call_expr, method, context); } else { out.push_str(" @staticmethod\n"); @@ -390,10 +405,11 @@ fn generate_static_method_invoke_named( out.push_str(&method_pydoc(method, &in_params)); let args_expr = py_build_method_args_expr(&in_params, context); let call_expr = method_call_expr( - &format!("_{iface_symbol}"), + &context.registration_symbol(iface), method, &statics_call, &args_expr, + context, ); emit_method_result(&mut out, &call_expr, method, context); } @@ -622,7 +638,7 @@ pub(crate) fn generate_static_method_group( }; out.push_str(&format!( " if {condition}:\n return {}.{private_name}(*_bound)\n", - overload.class.name + context.class_name(overload.class) )); } out.push_str(&format!( @@ -769,7 +785,7 @@ pub(crate) fn generate_method_body( out.push_str(" @_property\n"); out.push_str(&format!(" def {}(self) -> {}:\n", prop_name, py_return)); out.push_str(&method_pydoc(method, &in_params)); - let call_expr = method_call_expr(iface_var, method, obj_expr, ""); + let call_expr = method_call_expr(iface_var, method, obj_expr, "", context); emit_method_result(&mut out, &call_expr, method, context); } else if method.is_property_setter { let prop_name = to_snake_case(method.name.strip_prefix("put_").unwrap_or(&method.name)); @@ -831,7 +847,7 @@ pub(crate) fn generate_method_body( out.push_str(&method_pydoc(method, &in_params)); let args_expr = py_build_method_args_expr(&in_params, context); - let call_expr = method_call_expr(iface_var, method, obj_expr, &args_expr); + let call_expr = method_call_expr(iface_var, method, obj_expr, &args_expr, context); emit_method_result(&mut out, &call_expr, method, context); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index 62827e0e..f90f2cf2 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -14,6 +14,103 @@ use crate::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; pub type PythonTypeIdentity = TypeIdentity; +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub(crate) enum PythonSymbol { + Type, + Like, + Identity, + Pack, + Unpack, + TypeConstant, + PrivatePack, + PrivateUnpack, + PrivateTypeConstant, + Registration, + ActivationFactoryRegistration, +} + +impl PythonSymbol { + fn named(self, name: &str) -> String { + match self { + Self::Type => name.into(), + Self::Like => format!("{name}Like"), + Self::Identity => format!("_{name}Identity"), + Self::Pack => format!("pack_{}", to_snake_case(name)), + Self::Unpack => format!("unpack_{}", to_snake_case(name)), + Self::TypeConstant => format!("{name}_TYPE"), + Self::PrivatePack => format!("_pack_{}", to_snake_case(name)), + Self::PrivateUnpack => format!("_unpack_{}", to_snake_case(name)), + Self::PrivateTypeConstant => format!("_{name}_TYPE"), + Self::Registration => format!("_{name}"), + Self::ActivationFactoryRegistration => "_IActivationFactory".into(), + } + } + + fn is_registration(self) -> bool { + matches!( + self, + Self::Registration | Self::ActivationFactoryRegistration + ) + } +} + +pub(crate) const STRUCT_SYMBOLS: [PythonSymbol; 7] = [ + PythonSymbol::Type, + PythonSymbol::TypeConstant, + PythonSymbol::Pack, + PythonSymbol::Unpack, + PythonSymbol::PrivateTypeConstant, + PythonSymbol::PrivatePack, + PythonSymbol::PrivateUnpack, +]; + +pub(super) fn py_struct_export_names(typ: &TypeMeta) -> Vec { + let TypeMeta::Struct { name, .. } = typ else { + return Vec::new(); + }; + STRUCT_SYMBOLS[..4] + .iter() + .filter(|role| { + **role != PythonSymbol::Type || super::native_types::foundation_type(typ).is_none() + }) + .map(|role| role.named(name)) + .collect() +} + +pub(super) fn format_py_type_import( + context: &PythonProjectionContext, + namespace: &str, + name: &str, + kind: TypeKind, +) -> String { + let identity_kind = match kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + let identity = TypeIdentity::named(identity_kind, namespace, name); + let module = context.implementation_module(&identity); + let type_import = context.symbol_import(&identity, PythonSymbol::Type); + let names = match kind { + TypeKind::Interface => { + let declaration = format!("IID_{}", context.projected_name(&identity)); + let reference = format!("IID_{}", context.reference_name(&identity)); + let iid = if declaration == reference { + declaration + } else { + format!("{declaration} as {reference}") + }; + format!("{iid}, {type_import}") + } + TypeKind::Class => format!( + "{type_import}, {}", + context.symbol_import(&identity, PythonSymbol::Like) + ), + TypeKind::Enum => type_import, + }; + format!("from .{module} import {names} # noqa: F401\n") +} + #[derive(Clone, Debug)] struct PythonProjection { implementation_module: String, @@ -404,6 +501,7 @@ pub struct PythonProjectionContext { aliases: HashMap, compatibility_counts: HashMap, implementation_helpers: BTreeMap>, + module_symbols: HashMap<(PythonTypeIdentity, PythonSymbol), String>, } impl PythonProjectionContext { @@ -527,6 +625,7 @@ impl PythonProjectionContext { aliases, compatibility_counts, implementation_helpers: BTreeMap::new(), + module_symbols: HashMap::new(), }) } @@ -553,22 +652,140 @@ impl PythonProjectionContext { self.packaged } - /// Interfaces declare projected names; embedded structs retain metadata names. - pub(super) fn with_local_types( + fn imported_type_symbols( &self, - interface: Option<&InterfaceMeta>, + references: impl IntoIterator, + generics: impl IntoIterator, + ) -> Vec<(PythonTypeIdentity, PythonSymbol)> { + let mut symbols = Vec::new(); + for reference in references { + if !self.is_known_ref(&reference) { + continue; + } + let kind = match reference.kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + let identity = self.normalize_identity(&TypeIdentity::named( + kind, + reference.namespace, + reference.name, + )); + if identity.kind() == Some(TypeIdentityKind::Delegate) { + continue; + } + symbols.push((identity.clone(), PythonSymbol::Type)); + if kind == TypeIdentityKind::Class { + symbols.push((identity, PythonSymbol::Like)); + } + } + for identity in generics { + let identity = self.normalize_identity(&identity); + if identity.kind() != Some(TypeIdentityKind::Delegate) { + symbols.push((identity, PythonSymbol::Type)); + } + } + symbols + } + + pub(super) fn for_class_module( + &self, + class: &crate::meta::ClassMeta, structs: &[TypeMeta], ) -> Cow<'_, Self> { - let declarations = interface - .into_iter() - .map(|interface| { - ( - interface.type_identity(), - self.projected_name_for_interface(interface), - ) - }) + use crate::codegen::winrt::shared::imports::{ + collect_class_type_imports_by_identity, collect_used_generic_identities_from_class, + }; + let mut imports = self.imported_type_symbols( + collect_class_type_imports_by_identity(class), + collect_used_generic_identities_from_class(class), + ); + // Required views are visible either as peer imports or inline wrappers. + imports.extend( + class + .required_interfaces + .iter() + .filter(|interface| !interface.iid.is_empty()) + .map(|interface| (interface.type_identity(), PythonSymbol::Type)), + ); + if let Some(base) = class + .base_class + .as_ref() + .filter(|base| self.is_known_ref(base)) + { + imports.push(( + TypeIdentity::named(TypeIdentityKind::Class, &base.namespace, &base.name), + PythonSymbol::Identity, + )); + } + let owner = TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name); + let registrations = class + .all_interfaces() + .map(|interface| (interface.type_identity(), PythonSymbol::Registration)) + .chain( + class + .has_default_activation() + .then(|| (owner.clone(), PythonSymbol::ActivationFactoryRegistration)), + ); + self.with_local_types(Some(owner.clone()), structs, imports, registrations) + } + + pub(super) fn for_interface_module( + &self, + interface: &InterfaceMeta, + structs: &[TypeMeta], + ) -> Cow<'_, Self> { + use crate::codegen::winrt::shared::imports::{ + collect_iface_type_imports_by_identity, collect_used_generic_identities_from_methods, + }; + let mut generics = collect_used_generic_identities_from_methods(&interface.methods); + for delegate in &interface.implementation_metadata.delegates { + generics.extend(collect_used_generic_identities_from_methods( + std::slice::from_ref(&delegate.invoke), + )); + } + self.with_local_types( + Some(interface.type_identity()), + structs, + self.imported_type_symbols(collect_iface_type_imports_by_identity(interface), generics), + (!interface.is_delegate()) + .then(|| (interface.type_identity(), PythonSymbol::Registration)), + ) + } + + pub(super) fn for_struct_module(&self, typ: &TypeMeta, structs: &[TypeMeta]) -> Cow<'_, Self> { + use crate::codegen::winrt::shared::imports::{ + collect_struct_field_type_imports, collect_used_generic_identities_from_type, + }; + self.with_local_types( + Some(typ.type_identity()), + structs, + self.imported_type_symbols( + collect_struct_field_type_imports(typ), + collect_used_generic_identities_from_type(typ), + ), + [], + ) + } + + /// Bind local declarations and imported conversion helpers in one module. + fn with_local_types( + &self, + owner: Option, + structs: &[TypeMeta], + imports: impl IntoIterator, + registrations: impl IntoIterator, + ) -> Cow<'_, Self> { + let declarations = owner + .iter() + .map(|identity| (identity.clone(), self.declaration_name(identity))) .chain(structs.iter().filter_map(|typ| match typ { - TypeMeta::Struct { name, .. } if !self.is_packaged() => { + TypeMeta::Struct { name, .. } + if !self.is_packaged() + && owner.as_ref().and_then(TypeIdentity::kind) + != Some(TypeIdentityKind::Struct) => + { Some((typ.type_identity(), name.clone())) } _ => None, @@ -582,18 +799,179 @@ impl PythonProjectionContext { projection.reference_name = declaration_name; } } + let mut symbols = BTreeMap::new(); + for typ in structs { + let identity = self.identity_for_type(typ); + for role in STRUCT_SYMBOLS { + if role != PythonSymbol::Type || super::native_types::foundation_type(typ).is_none() + { + symbols.insert( + (identity.clone(), role), + context.symbol_reference(&identity, role), + ); + } + } + } + for (identity, role) in imports { + let identity = self.normalize_identity(&identity); + if owner.as_ref() != Some(&identity) { + symbols.insert( + (identity.clone(), role), + context.symbol_reference(&identity, role), + ); + } + } + if let Some(identity) = &owner + && identity.kind() != Some(TypeIdentityKind::Struct) + { + let mut roles = vec![PythonSymbol::Type]; + if identity.kind() == Some(TypeIdentityKind::Class) { + roles.extend([PythonSymbol::Like, PythonSymbol::Identity]); + } + for role in roles { + symbols.insert( + (identity.clone(), role), + context.symbol_reference(identity, role), + ); + } + } + for (identity, role) in registrations { + let identity = self.normalize_identity(&identity); + symbols.insert( + (identity.clone(), role), + context.symbol_reference(&identity, role), + ); + } + let mut groups = BTreeMap::>::new(); + for (key, name) in &symbols { + groups.entry(name.clone()).or_default().push(key.clone()); + } + let mut reserved = groups.keys().cloned().collect::>(); + if groups.values().any(|group| group.len() > 1) { + // Freeze each visible role before changing a type alias: its Like and + // identity imports may keep their existing, independently valid names. + context.to_mut().module_symbols.extend(symbols); + } + for group in groups.values().filter(|group| group.len() > 1) { + let can_alias_helper = |identity: &TypeIdentity, role: PythonSymbol| { + identity.kind() == Some(TypeIdentityKind::Struct) + && role != PythonSymbol::Type + && owner.as_ref() != Some(identity) + }; + let fixed_symbol_count = group + .iter() + .filter(|(identity, role)| !can_alias_helper(identity, *role)) + .count(); + let owns_struct_symbol = group.iter().any(|(identity, _)| { + owner.as_ref() == Some(identity) + && identity.kind() == Some(TypeIdentityKind::Struct) + }); + for (identity, role) in group { + let rename = if role.is_registration() { + fixed_symbol_count > 1 + } else { + owner.as_ref() != Some(identity) + && (can_alias_helper(identity, *role) || owns_struct_symbol) + }; + if !rename { + continue; + } + let candidate = role.named(&semantic_qualifier(identity)); + let mut name = candidate.clone(); + let mut index = 0; + while !reserved.insert(name.clone()) { + name = format!( + "{candidate}_{:016x}_{index}", + stable_module_hash(&identity.canonical_key()) + ); + index += 1; + } + context + .to_mut() + .module_symbols + .insert((identity.clone(), *role), name); + } + } 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() + pub(crate) fn declaration_name(&self, identity: &PythonTypeIdentity) -> String { + if identity.kind() == Some(TypeIdentityKind::Struct) { + legacy_projected_name(identity) + } else { + self.projected_name(identity) + } + } + + pub(crate) fn symbol_declaration( + &self, + identity: &PythonTypeIdentity, + role: PythonSymbol, + ) -> String { + role.named(&self.declaration_name(identity)) + } + + pub(crate) fn symbol_reference( + &self, + identity: &PythonTypeIdentity, + role: PythonSymbol, + ) -> String { + let identity = self.normalize_identity(identity); + if let Some(symbol) = self.module_symbols.get(&(identity.clone(), role)) { + return symbol.clone(); + } + let name = + if identity.kind() == Some(TypeIdentityKind::Struct) && role != PythonSymbol::Type { + self.declaration_name(&identity) + } else { + self.reference_name(&identity) + }; + role.named(&name) + } + + pub(crate) fn symbol_import( + &self, + identity: &PythonTypeIdentity, + role: PythonSymbol, + ) -> String { + let declaration = self.symbol_declaration(identity, role); + let reference = self.symbol_reference(identity, role); + if declaration == reference { + declaration } else { - format!("{name} as {reference}") + format!("{declaration} as {reference}") } } + pub(crate) fn struct_symbol(&self, typ: &TypeMeta, role: PythonSymbol) -> String { + self.symbol_reference(&self.identity_for_type(typ), role) + } + + pub(crate) fn registration_symbol(&self, interface: &InterfaceMeta) -> String { + self.symbol_reference(&interface.type_identity(), PythonSymbol::Registration) + } + + pub(crate) fn activation_factory_symbol(&self, class: &crate::meta::ClassMeta) -> String { + self.symbol_reference( + &TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name), + PythonSymbol::ActivationFactoryRegistration, + ) + } + + pub(crate) fn registration_call_name(&self, variable: &str) -> String { + self.module_symbols + .iter() + .find(|((_, role), name)| *role == PythonSymbol::Registration && *name == variable) + .map_or_else( + || variable.trim_start_matches('_').to_string(), + |((identity, _), _)| { + self.unaliased_reference_name(identity) + .trim_start_matches('_') + .to_string() + }, + ) + } + pub fn configure_implementation_helpers( &mut self, owners: impl IntoIterator)>, @@ -769,12 +1147,30 @@ impl PythonProjectionContext { self.projected_name(&interface.type_identity()) } + pub(crate) fn class_name(&self, class: &crate::meta::ClassMeta) -> String { + self.projected_name(&TypeIdentity::named( + TypeIdentityKind::Class, + &class.namespace, + &class.name, + )) + } + pub fn reference_name(&self, identity: &PythonTypeIdentity) -> String { let identity = self.normalize_identity(identity); + if let Some(name) = self + .module_symbols + .get(&(identity.clone(), PythonSymbol::Type)) + { + return name.clone(); + } + self.unaliased_reference_name(&identity) + } + + fn unaliased_reference_name(&self, identity: &PythonTypeIdentity) -> String { self.projections - .get(&identity) + .get(identity) .map(|projection| projection.reference_name.clone()) - .unwrap_or_else(|| self.projected_name(&identity)) + .unwrap_or_else(|| self.projected_name(identity)) } pub fn reference_name_for_type(&self, typ: &TypeMeta) -> String { @@ -989,6 +1385,213 @@ pub fn to_snake_case_filename(name: &str) -> String { mod tests { use super::*; + #[test] + fn module_helper_aliases_preserve_isolated_exports_and_input_order() { + let alpha = TypeMeta::Struct { + namespace: "Alpha".into(), + name: "URLValue".into(), + fields: vec![], + }; + let beta = TypeMeta::Struct { + namespace: "Beta".into(), + name: "UrlValue".into(), + fields: vec![], + }; + let context = + PythonProjectionContext::packaged([alpha.type_identity(), beta.type_identity()]) + .unwrap(); + let forward = context + .with_local_types(None, &[alpha.clone(), beta.clone()], [], []) + .into_owned(); + let reverse = context + .with_local_types(None, &[beta.clone(), alpha.clone()], [], []) + .into_owned(); + for role in [ + PythonSymbol::Pack, + PythonSymbol::Unpack, + PythonSymbol::PrivatePack, + PythonSymbol::PrivateUnpack, + ] { + assert_ne!( + forward.struct_symbol(&alpha, role), + forward.struct_symbol(&beta, role) + ); + for typ in [&alpha, &beta] { + assert_eq!( + forward.struct_symbol(typ, role), + reverse.struct_symbol(typ, role) + ); + assert_eq!( + forward.symbol_import(&typ.type_identity(), role), + format!( + "{} as {}", + context.symbol_declaration(&typ.type_identity(), role), + forward.struct_symbol(typ, role), + ) + ); + } + } + assert_eq!( + context.struct_symbol(&alpha, PythonSymbol::Pack), + "pack_url_value" + ); + assert_eq!( + context.struct_symbol(&beta, PythonSymbol::Pack), + "pack_url_value" + ); + let owned = context + .with_local_types( + Some(alpha.type_identity()), + &[alpha.clone(), beta.clone()], + [], + [], + ) + .into_owned(); + assert_eq!( + owned.struct_symbol(&alpha, PythonSymbol::Pack), + "pack_url_value" + ); + assert_ne!( + owned.struct_symbol(&beta, PythonSymbol::Pack), + "pack_url_value" + ); + } + + #[test] + fn cross_role_aliases_use_visible_imports_and_preserve_owned_struct_exports() { + let typ = TypeMeta::Struct { + namespace: "Alpha".into(), + name: "URLValue".into(), + fields: vec![], + }; + let class = TypeIdentity::named(TypeIdentityKind::Class, "Kinds", "pack_url_value"); + let enum_type = TypeIdentity::named(TypeIdentityKind::Enum, "Kinds", "URLValue_TYPE"); + let context = PythonProjectionContext::packaged([ + typ.type_identity(), + class.clone(), + enum_type.clone(), + ]) + .unwrap(); + let structs = std::slice::from_ref(&typ); + let unrelated = context.with_local_types(None, structs, [], []); + assert_eq!( + unrelated.struct_symbol(&typ, PythonSymbol::Pack), + "pack_url_value" + ); + assert_eq!( + unrelated.struct_symbol(&typ, PythonSymbol::TypeConstant), + "URLValue_TYPE" + ); + let imports = [ + (class.clone(), PythonSymbol::Type), + (class.clone(), PythonSymbol::Like), + (enum_type.clone(), PythonSymbol::Type), + ]; + let consumer = context.with_local_types(None, structs, imports.clone(), []); + assert_ne!( + consumer.struct_symbol(&typ, PythonSymbol::Pack), + "pack_url_value" + ); + assert_ne!( + consumer.struct_symbol(&typ, PythonSymbol::TypeConstant), + "URLValue_TYPE" + ); + assert_eq!(consumer.reference_name(&class), "pack_url_value"); + assert_eq!(consumer.reference_name(&enum_type), "URLValue_TYPE"); + + let owned = context.with_local_types(Some(typ.type_identity()), structs, imports, []); + assert_eq!( + owned.struct_symbol(&typ, PythonSymbol::Pack), + "pack_url_value" + ); + assert_eq!( + owned.struct_symbol(&typ, PythonSymbol::TypeConstant), + "URLValue_TYPE" + ); + assert_ne!(owned.reference_name(&class), "pack_url_value"); + assert_ne!(owned.reference_name(&enum_type), "URLValue_TYPE"); + assert_eq!( + owned.symbol_reference(&class, PythonSymbol::Like), + "pack_url_valueLike", + ); + assert_eq!( + owned.symbol_import(&class, PythonSymbol::Type), + format!("pack_url_value as {}", owned.reference_name(&class)), + ); + } + + #[test] + fn registration_aliases_keep_independent_type_and_call_behavior_names() { + let interface = InterfaceMeta { + namespace: "Audit".into(), + name: "IApplicationStatics".into(), + ..Default::default() + }; + let typ = TypeMeta::Struct { + namespace: "Alpha".into(), + name: "_IApplicationStatics".into(), + fields: vec![], + }; + let context = + PythonProjectionContext::standalone([interface.type_identity(), typ.type_identity()]) + .unwrap(); + let module = context.for_interface_module(&interface, std::slice::from_ref(&typ)); + let registration = module.registration_symbol(&interface); + assert_ne!(registration, "_IApplicationStatics"); + assert_eq!(module.reference_name_for_type(&typ), "_IApplicationStatics"); + assert_eq!( + module.registration_call_name(®istration), + "IApplicationStatics" + ); + assert_eq!( + module.registration_call_name(®istration), + context.registration_call_name("_IApplicationStatics"), + ); + } + + #[test] + fn activation_registration_is_reserved_only_for_default_activation() { + let mut class = crate::meta::ClassMeta { + namespace: "Audit".into(), + name: "Wrapper".into(), + full_name: "Audit.Wrapper".into(), + ..Default::default() + }; + let typ = TypeMeta::Struct { + namespace: "Alpha".into(), + name: "_IActivationFactory".into(), + fields: vec![], + }; + let context = PythonProjectionContext::standalone([ + TypeIdentity::named(TypeIdentityKind::Class, &class.namespace, &class.name), + typ.type_identity(), + ]) + .unwrap(); + let structs = std::slice::from_ref(&typ); + let inactive = context.for_class_module(&class, structs); + assert_eq!( + inactive.reference_name_for_type(&typ), + "_IActivationFactory" + ); + assert!( + !inactive + .module_symbols + .keys() + .any(|(_, role)| role.is_registration()) + ); + + class.constructors.push(crate::meta::ConstructorMeta { + kind: crate::meta::ConstructorKind::DefaultActivation, + factory_interface: None, + }); + let active = context.for_class_module(&class, structs); + assert_eq!(active.reference_name_for_type(&typ), "_IActivationFactory"); + assert_ne!( + active.activation_factory_symbol(&class), + "_IActivationFactory" + ); + } + #[test] fn snake_case_keeps_winrt_uint_tokens_together() { assert_eq!(to_snake_case("UInt8"), "uint8"); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs index 4697b956..222bfde2 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs @@ -6,7 +6,7 @@ use crate::meta::{InterfaceMeta, MethodMeta, ParamDirection}; use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; -use super::naming::{PythonProjectionContext, to_snake_case}; +use super::naming::{PythonProjectionContext, PythonSymbol}; use crate::codegen::winrt::python::collections::{CollectionKind, is_mapping_input, type_kind}; use crate::codegen::winrt::python::native_types::{FoundationType, foundation_type}; use crate::codegen::winrt::shared::imports::ireference_inner_type; @@ -346,17 +346,17 @@ pub(crate) fn py_build_method_sig(method: &MethodMeta) -> String { } /// Wrap a Python variable name into a DynWinRTValue expression. -pub(crate) fn py_wrap_arg(name: &str, typ: &TypeMeta) -> String { +pub(crate) fn py_wrap_arg(name: &str, typ: &TypeMeta, context: &PythonProjectionContext) -> String { if let Some(inner) = ireference_inner_type(typ) { let value_type = py_dynwinrt_type(inner); - let wrapped = py_wrap_reference_value("value", inner); + let wrapped = py_wrap_native_value("value", inner, context); return format!( "_dynwinrt_box_reference({}, {}, lambda value: {})", name, value_type, wrapped ); } - if let Some(wrapped) = py_wrap_collection(name, typ) { + if let Some(wrapped) = py_wrap_collection(name, typ, context) { return wrapped; } @@ -388,7 +388,7 @@ pub(crate) fn py_wrap_arg(name: &str, typ: &TypeMeta) -> String { TypeMeta::Array(inner) => format!( "_dynwinrt_array({}, lambda item: {}, {}, {})", name, - py_wrap_native_value("item", inner), + py_wrap_native_value("item", inner, context), py_dynwinrt_type(inner), if matches!(inner.as_ref(), TypeMeta::U8) { "True" @@ -401,20 +401,22 @@ pub(crate) fn py_wrap_arg(name: &str, typ: &TypeMeta) -> String { } if struct_name == "HResult" => { format!("DynWinRTValue.from_hresult({})", name) } - TypeMeta::Struct { - name: struct_name, .. - } => { - format!("_pack_{}({}).to_value()", to_snake_case(struct_name), name) + TypeMeta::Struct { .. } => { + format!( + "{}({}).to_value()", + context.struct_symbol(typ, PythonSymbol::PrivatePack), + name + ) } _ => name.to_string(), } } -fn py_wrap_reference_value(name: &str, typ: &TypeMeta) -> String { - py_wrap_native_value(name, typ) -} - -pub(crate) fn py_wrap_native_value(name: &str, typ: &TypeMeta) -> String { +pub(crate) fn py_wrap_native_value( + name: &str, + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> String { match typ { TypeMeta::Bool => format!("DynWinRTValue.from_bool({})", name), TypeMeta::I8 => format!("DynWinRTValue.from_i8({})", name), @@ -440,9 +442,11 @@ pub(crate) fn py_wrap_native_value(name: &str, typ: &TypeMeta) -> String { } if struct_name == "HResult" => { format!("DynWinRTValue.from_hresult({})", name) } - TypeMeta::Struct { - name: struct_name, .. - } => format!("_pack_{}({}).to_value()", to_snake_case(struct_name), name), + TypeMeta::Struct { .. } => format!( + "{}({}).to_value()", + context.struct_symbol(typ, PythonSymbol::PrivatePack), + name + ), TypeMeta::RuntimeClass { .. } => py_runtime_class_wrap(name, typ), TypeMeta::Object | TypeMeta::Interface { .. } @@ -451,7 +455,7 @@ pub(crate) fn py_wrap_native_value(name: &str, typ: &TypeMeta) -> String { TypeMeta::Array(inner) => format!( "_dynwinrt_array({}, lambda item: {}, {}, {})", name, - py_wrap_native_value("item", inner), + py_wrap_native_value("item", inner, context), py_dynwinrt_type(inner), if matches!(inner.as_ref(), TypeMeta::U8) { "True" @@ -463,7 +467,11 @@ pub(crate) fn py_wrap_native_value(name: &str, typ: &TypeMeta) -> String { } } -fn py_wrap_collection(name: &str, typ: &TypeMeta) -> Option { +fn py_wrap_collection( + name: &str, + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> Option { let TypeMeta::Parameterized { args, .. } = typ else { return None; }; @@ -485,8 +493,8 @@ fn py_wrap_collection(name: &str, typ: &TypeMeta) -> Option { return Some(format!( "_dynwinrt_map({}, lambda item: {}, lambda item: {}, {}, {})", name, - py_wrap_native_value("item", key), - py_wrap_native_value("item", value), + py_wrap_native_value("item", key, context), + py_wrap_native_value("item", value, context), py_dynwinrt_type(key), py_dynwinrt_type(value) )); @@ -499,7 +507,7 @@ fn py_wrap_collection(name: &str, typ: &TypeMeta) -> Option { return Some(format!( "_dynwinrt_vector({}, lambda item: {}, {})", name, - py_wrap_native_value("item", element), + py_wrap_native_value("item", element, context), py_dynwinrt_type(element) )); } @@ -558,7 +566,7 @@ pub(crate) fn py_type_guard( TypeIdentityKind::Enum, namespace, type_name, - type_name + &context.projected_name_for_type(typ) ) ), TypeMeta::Enum { .. } => py_exact_int_guard(name), @@ -590,7 +598,7 @@ pub(crate) fn py_type_guard( TypeIdentityKind::Class, namespace, type_name, - type_name + &context.projected_name_for_type(typ) ) ), TypeMeta::Interface { @@ -604,7 +612,7 @@ pub(crate) fn py_type_guard( TypeIdentityKind::Interface, namespace, type_name, - type_name + &context.projected_name_for_type(typ) ) ), TypeMeta::Object @@ -645,14 +653,11 @@ pub(crate) fn py_convert_return( Some(TypeMeta::U64) => format!("{}.to_u64()", expr), Some(TypeMeta::F32 | TypeMeta::F64) => format!("{}.to_f64()", expr), Some(TypeMeta::Bool) => format!("{}.to_bool()", expr), - Some(typ @ TypeMeta::Enum { name, .. }) if context.is_known_type(typ) => { - let TypeMeta::Enum { name, .. } = typ else { - unreachable!() - }; + Some(typ @ TypeMeta::Enum { .. }) if context.is_known_type(typ) => { format!( "_dynwinrt_enum('{}', '{}', {}.to_number())", context.implementation_module_for_type(typ), - name, + context.projected_name_for_type(typ), expr ) } @@ -666,18 +671,20 @@ pub(crate) fn py_convert_return( wrapper, expr ) } - Some(typ @ TypeMeta::RuntimeClass { name, .. }) if context.is_known_type(typ) => { - let TypeMeta::RuntimeClass { name, .. } = typ else { - unreachable!() - }; - let wrapper = py_runtime_type_symbol(context, typ, name); + Some(typ @ TypeMeta::RuntimeClass { .. }) if context.is_known_type(typ) => { + let wrapper = + py_runtime_type_symbol(context, typ, &context.projected_name_for_type(typ)); format!( "(lambda value: None if value.is_null() else {}._from_native(value))({})", wrapper, expr ) } Some(TypeMeta::Struct { name, .. }) if name == "HResult" => format!("{}.to_number()", expr), - Some(TypeMeta::Struct { name, .. }) => format!("_unpack_{}({})", to_snake_case(name), expr), + Some(typ @ TypeMeta::Struct { .. }) => format!( + "{}({})", + context.struct_symbol(typ, PythonSymbol::PrivateUnpack), + expr + ), Some(TypeMeta::Delegate { .. }) => { format!( "(lambda value: None if value.is_null() else value)({})", @@ -784,10 +791,10 @@ pub(crate) fn py_convert_array_return( TypeMeta::U16 => format!("{}.to_u16_list()", arr_expr), TypeMeta::Char16 => format!("[chr(value) for value in {}.to_u16_list()]", arr_expr), TypeMeta::I32 => format!("{}.to_i32_list()", arr_expr), - typ @ TypeMeta::Enum { name, .. } if context.is_known_type(typ) => format!( + typ @ TypeMeta::Enum { .. } if context.is_known_type(typ) => format!( "[_dynwinrt_enum('{}', '{}', value) for value in {}.to_i32_list()]", context.implementation_module_for_type(typ), - name, + context.projected_name_for_type(typ), arr_expr ), TypeMeta::Enum { .. } => format!("{}.to_i32_list()", arr_expr), @@ -803,16 +810,16 @@ pub(crate) fn py_convert_array_return( arr_expr ), TypeMeta::Struct { name, .. } if name == "HResult" => format!("{}.to_i32_list()", arr_expr), - TypeMeta::Struct { name, .. } => format!( - "[_unpack_{}(v) for v in {}.to_values()]", - to_snake_case(name), + TypeMeta::Struct { .. } => format!( + "[{}(v) for v in {}.to_values()]", + context.struct_symbol(inner, PythonSymbol::PrivateUnpack), arr_expr ), - typ @ TypeMeta::RuntimeClass { name, .. } if context.is_known_type(typ) => { + typ @ TypeMeta::RuntimeClass { .. } if context.is_known_type(typ) => { format!( "_dynwinrt_wrap_values('{}', '{}', {}.to_values())", context.implementation_module_for_type(typ), - name, + context.projected_name_for_type(typ), arr_expr ) } @@ -913,7 +920,7 @@ mod tests { "_dynwinrt_can_cast(value, IID_ARG_Microsoft_UI_Xaml_Media_Geometry)" ); assert_eq!( - py_wrap_native_value("value", &geometry), + py_wrap_native_value("value", &geometry, &PythonProjectionContext::default()), "getattr(value, '_obj', value).cast(IID_ARG_Microsoft_UI_Xaml_Media_Geometry)" ); let mut constants = Vec::new(); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs index eb94e3d1..d281478c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs @@ -5,7 +5,7 @@ use crate::types::TypeMeta; -use super::naming::{PythonProjectionContext, to_snake_case}; +use super::naming::{PythonProjectionContext, PythonSymbol}; use super::native_types::{FoundationType, foundation_type}; use super::signature::{py_runtime_symbol, py_wrap_arg}; use super::type_helpers::py_optional_type; @@ -45,18 +45,16 @@ pub(crate) fn py_struct_field_getter( TypeMeta::F64 => format!("s.get_f64({})", index), TypeMeta::String => format!("s.get_hstring({})", index), TypeMeta::Guid => format!("_dynwinrt_uuid(s.get_guid({}))", index), - TypeMeta::Enum { - name, underlying, .. - } => format!( + TypeMeta::Enum { underlying, .. } => format!( "_dynwinrt_enum('{}', '{}', {})", context.implementation_module_for_type(typ), - name, + context.projected_name_for_type(typ), py_struct_field_getter(context, underlying, index) ), TypeMeta::Struct { name, .. } if name == "HResult" => format!("s.get_i32({})", index), - TypeMeta::Struct { name, .. } => format!( - "_unpack_{}(s.get_struct({}).to_value())", - to_snake_case(name), + TypeMeta::Struct { .. } => format!( + "{}(s.get_struct({}).to_value())", + context.struct_symbol(typ, PythonSymbol::PrivateUnpack), index ), _ => format!("s.get_object({})", index), @@ -64,9 +62,18 @@ pub(crate) fn py_struct_field_getter( } /// Python struct field setter expression. -pub(crate) fn py_struct_field_setter(typ: &TypeMeta, index: usize, value_expr: &str) -> String { +pub(crate) fn py_struct_field_setter( + context: &PythonProjectionContext, + typ: &TypeMeta, + index: usize, + value_expr: &str, +) -> String { if ireference_inner_type(typ).is_some() { - return format!("s.set_object({}, {})", index, py_wrap_arg(value_expr, typ)); + return format!( + "s.set_object({}, {})", + index, + py_wrap_arg(value_expr, typ, context) + ); } match typ { @@ -85,15 +92,15 @@ pub(crate) fn py_struct_field_setter(typ: &TypeMeta, index: usize, value_expr: & TypeMeta::String => format!("s.set_hstring({}, {})", index, value_expr), TypeMeta::Guid => format!("s.set_guid({}, _dynwinrt_guid({}))", index, value_expr), TypeMeta::Enum { underlying, .. } => { - py_struct_field_setter(underlying, index, &format!("int({value_expr})")) + py_struct_field_setter(context, underlying, index, &format!("int({value_expr})")) } TypeMeta::Struct { name, .. } if name == "HResult" => { format!("s.set_i32({}, {})", index, value_expr) } - TypeMeta::Struct { name, .. } => format!( - "s.set_struct({}, _pack_{}({}))", + TypeMeta::Struct { .. } => format!( + "s.set_struct({}, {}({}))", index, - to_snake_case(name), + context.struct_symbol(typ, PythonSymbol::PrivatePack), value_expr ), _ => format!("s.set_object({}, {})", index, value_expr), 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 bfe4045c..8e2c8f3c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs @@ -5,9 +5,9 @@ use crate::codegen::winrt::shared::imports::get_in_params; use crate::meta::MethodMeta; -use crate::types::{FieldMeta, TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta}; +use crate::types::{FieldMeta, TypeMeta}; -use super::naming::{PythonProjectionContext, to_snake_case}; +use super::naming::{PythonProjectionContext, PythonSymbol, STRUCT_SYMBOLS, to_snake_case}; use super::native_types::{FoundationType, foundation_type}; use super::structs::{py_struct_field_read_type, py_struct_field_type}; use super::type_helpers::{ @@ -16,73 +16,7 @@ use super::type_helpers::{ }; use crate::codegen::winrt::shared::imports::ireference_inner_type; -pub(super) fn format_py_type_import( - context: &PythonProjectionContext, - namespace: &str, - name: &str, - kind: TypeKind, -) -> String { - let identity_kind = match kind { - TypeKind::Class => TypeIdentityKind::Class, - TypeKind::Enum => TypeIdentityKind::Enum, - TypeKind::Interface => TypeIdentityKind::Interface, - }; - let identity = TypeIdentity::named(identity_kind, namespace, name); - let module = context.implementation_module(&identity); - let projected_name = context.projected_name(&identity); - let reference_name = context.reference_name(&identity); - let imported = |name: &str, alias: &str| { - if name == alias { - name.to_string() - } else { - format!("{name} as {alias}") - } - }; - if kind == TypeKind::Interface { - format!( - "from .{module} import {}, {} # noqa: F401\n", - imported( - &format!("IID_{projected_name}"), - &format!("IID_{reference_name}") - ), - imported(&projected_name, &reference_name) - ) - } else if kind == TypeKind::Class { - format!( - "from .{module} import {}, {} # noqa: F401\n", - imported(&projected_name, &reference_name), - imported( - &format!("{projected_name}Like"), - &format!("{reference_name}Like") - ) - ) - } else { - format!( - "from .{module} import {} # noqa: F401\n", - imported(&projected_name, &reference_name) - ) - } -} - -pub(super) fn py_struct_export_names(s: &TypeMeta) -> Vec { - match s { - TypeMeta::Struct { name, .. } => { - let snake = to_snake_case(name); - let mut names = if foundation_type(s).is_none() { - vec![name.clone()] - } else { - Vec::new() - }; - names.extend([ - format!("{}_TYPE", name), - format!("pack_{}", snake), - format!("unpack_{}", snake), - ]); - names - } - _ => vec![], - } -} +pub(super) use super::naming::{format_py_type_import, py_struct_export_names}; pub(super) fn generate_struct_stub_imports( context: &PythonProjectionContext, @@ -91,18 +25,14 @@ pub(super) fn generate_struct_stub_imports( let mut imports = structs .iter() .filter_map(|typ| { - let TypeMeta::Struct { name, .. } = typ else { + let TypeMeta::Struct { .. } = 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 - } - }) + let names = STRUCT_SYMBOLS[..4] + .iter() + .copied() + .filter(|role| *role != PythonSymbol::Type || foundation_type(typ).is_none()) + .map(|role| context.symbol_import(&typ.type_identity(), role)) .collect::>(); Some(format!( "from .{} import {} # noqa: F401\n", @@ -117,19 +47,18 @@ pub(super) fn generate_struct_stub_imports( } pub(super) fn emit_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) -> String { + let pack = context.struct_symbol(s, PythonSymbol::Pack); + let unpack = context.struct_symbol(s, PythonSymbol::Unpack); + let type_constant = context.struct_symbol(s, PythonSymbol::TypeConstant); if let Some(kind) = foundation_type(s) { - let TypeMeta::Struct { name, .. } = s else { - unreachable!() - }; - let snake_name = to_snake_case(name); let native_type = match kind { FoundationType::DateTime => "datetime", FoundationType::TimeSpan => "timedelta", }; return format!( - "\ndef unpack_{snake_name}(v: DynWinRTValue) -> {native_type}: ...\n\ - {name}_TYPE: 'DynWinRTType'\n\ - def pack_{snake_name}(v: {native_type}) -> DynWinRTStruct: ...\n" + "\ndef {unpack}(v: DynWinRTValue) -> {native_type}: ...\n\ + {type_constant}: 'DynWinRTType'\n\ + def {pack}(v: {native_type}) -> DynWinRTStruct: ...\n" ); } @@ -142,7 +71,6 @@ pub(super) fn emit_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) _ => return String::new(), }; let mut out = String::new(); - let snake_name = to_snake_case(name); let slot_names = fields.iter().map(py_struct_slot_name).collect::>(); out.push_str(&format!("\nclass {}:\n", name)); @@ -191,15 +119,9 @@ pub(super) fn emit_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) out.push_str(" def __repr__(self) -> str: ...\n"); out.push('\n'); - out.push_str(&format!( - "def unpack_{}(v: DynWinRTValue) -> {}: ...\n", - snake_name, name - )); - out.push_str(&format!("{}_TYPE: 'DynWinRTType'\n", name)); - out.push_str(&format!( - "def pack_{}(v: {}) -> DynWinRTStruct: ...\n", - snake_name, name - )); + out.push_str(&format!("def {unpack}(v: DynWinRTValue) -> {name}: ...\n",)); + out.push_str(&format!("{type_constant}: 'DynWinRTType'\n")); + out.push_str(&format!("def {pack}(v: {name}) -> DynWinRTStruct: ...\n",)); out } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index ab27338f..c09a80f7 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs @@ -14,8 +14,8 @@ use crate::types::{TypeKind, TypeMeta}; use crate::codegen::winrt::extensions::winui; use crate::codegen::winrt::shared::imports::{ 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, + 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, @@ -131,15 +131,17 @@ pub fn generate_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) -> if name == "HResult" { return None; } + let dependencies = collect_used_structs_from_struct(s); + let mut module_structs = dependencies.clone(); + module_structs.push(s.clone()); + let context = context.for_struct_module(s, &module_structs); + let context = context.as_ref(); let mut out = String::new(); out.push_str(HEADER); out.push_str(FUTURE_ANNOTATIONS); out.push_str(IMPORT_LINE); - out.push_str(&generate_struct_stub_imports( - context, - &collect_used_structs_from_struct(s), - )); + out.push_str(&generate_struct_stub_imports(context, &dependencies)); let mut imports = collect_struct_field_type_imports(s) .into_iter() @@ -173,24 +175,18 @@ pub fn generate_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) -> } /// Generate a `.pyi` stub for an enum. Returns `None` for non-enum TypeMeta. -pub fn generate_enum_stub(_context: &PythonProjectionContext, en: &TypeMeta) -> Option { - let (name, members, is_flags, doc, deprecated) = match en { +pub fn generate_enum_stub(context: &PythonProjectionContext, en: &TypeMeta) -> Option { + let (members, is_flags, doc, deprecated) = match en { TypeMeta::Enum { - name, members, is_flags, doc, deprecated, .. - } => ( - name, - members, - *is_flags, - doc.as_deref(), - deprecated.as_deref(), - ), + } => (members, *is_flags, doc.as_deref(), deprecated.as_deref()), _ => return None, }; + let name = context.projected_name_for_type(en); let mut out = String::new(); out.push_str(HEADER); let enum_base = if is_flags { "IntFlag" } else { "IntEnum" }; @@ -223,7 +219,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(Some(iface), &used_structs); + let context = context.for_interface_module(iface, &used_structs); let context = context.as_ref(); let mut projected_iface = iface.clone(); projected_iface.name = context.projected_name_for_interface(iface); @@ -513,14 +509,24 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf } if iface.namespace == "Microsoft.UI.Xaml" && iface.name == "IElementFactory" { - out.push_str( + let class_reference = |name| { + context.reference_name(&crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + &iface.namespace, + name, + )) + }; + let get_args = class_reference("ElementFactoryGetArgs"); + let recycle_args = class_reference("ElementFactoryRecycleArgs"); + let element = class_reference("UIElement"); + out.push_str(&format!( "\n @staticmethod\n\ \x20 def create(\n\ - \x20 get_element: Callable[['ElementFactoryGetArgs'], 'UIElement'],\n\ - \x20 recycle_element: Callable[['ElementFactoryRecycleArgs'], object],\n\ + \x20 get_element: Callable[['{get_args}'], '{element}'],\n\ + \x20 recycle_element: Callable[['{recycle_args}'], object],\n\ \x20 ) -> 'IElementFactory': ...\n\ \x20 def release_callbacks(self) -> None: ...\n", - ); + )); } for methods in super::overloads::grouped_methods(reorder_getters_before_setters(&iface.methods)) @@ -569,7 +575,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(None, &used_structs); + let context = context.for_class_module(class, &used_structs); let context = context.as_ref(); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); @@ -707,7 +713,8 @@ pub fn generate_class_stub( out.push_str(&format!("from .{module} import {imports} # noqa: F401\n",)); } - let imports = collect_type_imports(class); + let imports = + crate::codegen::winrt::shared::imports::collect_class_type_imports_by_identity(class); let mut sorted_imports: Vec<_> = imports.iter().collect(); sorted_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); @@ -746,13 +753,12 @@ pub fn generate_class_stub( base.namespace.clone(), base.name.clone(), ); - let name = context.reference_name(&identity); out.push_str(&format!( - "from .{} import _{}Identity # noqa: F401\n", + "from .{} import {} # noqa: F401\n", context.implementation_module(&identity), - name + context.symbol_import(&identity, super::naming::PythonSymbol::Identity) )); - format!("_{name}Identity") + context.symbol_reference(&identity, super::naming::PythonSymbol::Identity) }); for req_iface in &class.required_interfaces { let symbol = interface_symbol(context, req_iface); @@ -829,7 +835,7 @@ pub fn generate_class_stub( if crate::codegen::winrt::is_buffer_class(&class.namespace, &class.name) { instance_stub_body.push_str(" def to_bytes(self) -> bytes: ...\n"); } - let identity_name = format!("_{}Identity", class.name); + let identity_name = format!("_{}Identity", context.class_name(class)); let mut identity_bases = base_identity.into_iter().collect::>(); identity_bases.push("Protocol".into()); out.push_str(&format!( @@ -854,7 +860,7 @@ pub fn generate_class_stub( out.push_str(&format!( "\nclass {}Like({identity_name}, Protocol):\n", - class.name + context.class_name(class) )); if instance_stub_body.is_empty() { out.push_str(" pass\n"); @@ -865,14 +871,18 @@ pub fn generate_class_stub( let bases = collection_base .as_ref() .map(|base| vec![identity_name, base.clone()]) - .unwrap_or_else(|| vec![format!("{}Like", class.name)]); + .unwrap_or_else(|| vec![format!("{}Like", context.class_name(class))]); let mut bases = bases; if projectable { bases.push("_DynWinRTRuntimeClass".into()); } else if native_projectable { bases.push("_DynWinRTProjectableClass".into()); } - out.push_str(&format!("\nclass {}({}):\n", class.name, bases.join(", "))); + out.push_str(&format!( + "\nclass {}({}):\n", + context.class_name(class), + bases.join(", ") + )); out.push_str(&super::docs::format_pydoc( &crate::codegen::winrt::shared::docs::DocText { summary: class.doc.as_deref(), @@ -915,7 +925,8 @@ pub fn generate_class_stub( out.push_str(" @staticmethod\n"); out.push_str(&format!( " def {}() -> '{}': ...\n", - ctor_name, class.name + ctor_name, + context.class_name(class) )); } @@ -932,10 +943,14 @@ pub fn generate_class_stub( .collect::>(); for group in grouped_static_stubs(&static_methods) { out.push('\n'); - out.push_str(&emit_static_stub_group(&class.name, &group, context)); + out.push_str(&emit_static_stub_group( + &context.class_name(class), + &group, + context, + )); } out.push_str(&emit_static_compatibility_alias_stubs( - &class.name, + &context.class_name(class), static_methods.iter().copied(), context, 4, @@ -964,7 +979,10 @@ pub fn generate_class_stub( if has_create_instance_alias { out.push('\n'); out.push_str(" @staticmethod\n"); - out.push_str(&format!(" def create() -> '{}': ...\n", class.name)); + out.push_str(&format!( + " def create() -> '{}': ...\n", + context.class_name(class) + )); } if let Some(bootstrap) = winui_bootstrap { @@ -973,12 +991,12 @@ pub fn generate_class_stub( out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create_with_metadata_provider(metadata_provider: '{metadata_provider}', on_launched: Callable[[], object] | None = ...) -> '{}': ...\n", - class.name, + context.class_name(class), )); out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create(on_launched: Callable[[], object] | None = ...) -> '{}': ...\n", - class.name + context.class_name(class) )); } @@ -1176,7 +1194,7 @@ fn emit_class_instance_stubs( out.push_str(" def close(self) -> None: ...\n"); out.push_str(&format!( " def __enter__(self) -> '{}': ...\n", - class.name + context.class_name(class) )); out.push_str( " def __exit__(self, exc_type: object, exc_value: object, traceback: object) -> Literal[False]: ...\n", @@ -1199,15 +1217,20 @@ fn emit_class_instance_stubs( \x20 **kwargs: object,\n\ \x20 ) -> _DispatchResultT: ...\n", ); - out.push_str( + let priority = context.reference_name(&crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Enum, + &class.namespace, + "DispatcherQueuePriority", + )); + out.push_str(&format!( "\n async def enqueue_with_priority_async(\n\ \x20 self,\n\ - \x20 priority: 'DispatcherQueuePriority',\n\ + \x20 priority: '{priority}',\n\ \x20 callback: Callable[..., _DispatchResultT],\n\ \x20 *args: object,\n\ \x20 **kwargs: object,\n\ \x20 ) -> _DispatchResultT: ...\n", - ); + )); } out @@ -1618,7 +1641,7 @@ pub fn generate_index_stub( let mut sorted_classes: Vec<_> = classes.iter().collect(); sorted_classes.sort_by(|a, b| a.name.cmp(&b.name)); for class in sorted_classes { - if seen.insert(class.name.clone()) { + if seen.insert(context.class_name(class)) { let identity = crate::types::TypeIdentity::named( crate::types::TypeIdentityKind::Class, class.namespace.clone(), @@ -1633,7 +1656,7 @@ pub fn generate_index_stub( let mut sorted_ifaces: Vec<_> = interfaces.iter().collect(); sorted_ifaces.sort_by(|a, b| a.name.cmp(&b.name)); for iface in sorted_ifaces { - if !seen.insert(iface.name.clone()) { + if !seen.insert(context.projected_name_for_interface(iface)) { continue; } let is_delegate = iface.is_delegate(); @@ -1671,8 +1694,8 @@ pub fn generate_index_stub( na.cmp(nb) }); for en in sorted_enums { - if let TypeMeta::Enum { name, .. } = en { - if seen.insert(name.clone()) { + if let TypeMeta::Enum { .. } = en { + if seen.insert(context.projected_name_for_type(en)) { let identity = en.type_identity(); let module = context.implementation_module(&identity); let name = context.projected_name(&identity); @@ -1695,7 +1718,7 @@ pub fn generate_public_index_stub( let mut classes = classes.iter().collect::>(); classes.sort_by(|left, right| left.name.cmp(&right.name)); for class in classes { - if seen.insert(class.name.clone()) { + if seen.insert(context.class_name(class)) { let identity = crate::types::TypeIdentity::named( crate::types::TypeIdentityKind::Class, class.namespace.clone(), @@ -1715,7 +1738,7 @@ pub fn generate_public_index_stub( interfaces.sort_by(|left, right| left.name.cmp(&right.name)); for interface in interfaces { let is_delegate = interface.is_delegate(); - if !is_delegate && seen.insert(interface.name.clone()) { + if !is_delegate && seen.insert(context.projected_name_for_interface(interface)) { let identity = interface.type_identity(); let name = context.projected_name(&identity); out.push_str(&format!( @@ -1739,10 +1762,10 @@ pub fn generate_public_index_stub( _ => "", }); for typ in enums { - let TypeMeta::Enum { name, .. } = typ else { + let TypeMeta::Enum { .. } = typ else { continue; }; - if seen.insert(name.clone()) { + if seen.insert(context.projected_name_for_type(typ)) { let identity = typ.type_identity(); let name = context.projected_name(&identity); out.push_str(&format!( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs index 950cd4da..3b1c7afa 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -12,8 +12,8 @@ use crate::types::TypeMeta; use super::collections::{CollectionKind, is_mapping_input, type_kind}; use super::docs::format_pydoc; -use super::naming::PythonProjectionContext; use super::naming::to_snake_case; +use super::naming::{PythonProjectionContext, PythonSymbol}; use super::native_types::{FoundationType, foundation_type}; /// Build the Python docstring for a method body. Uses snake_case param display @@ -95,7 +95,10 @@ fn py_param_type(typ: &TypeMeta, context: &PythonProjectionContext) -> String { TypeMeta::Char16 => "str".to_string(), TypeMeta::Guid => "UUID".to_string(), TypeMeta::RuntimeClass { .. } => { - format!("'{}Like'", context.reference_name_for_type(typ)) + format!( + "'{}'", + context.symbol_reference(&typ.type_identity(), PythonSymbol::Like) + ) } TypeMeta::Enum { .. } | TypeMeta::Interface { .. } => { format!("'{}'", context.reference_name_for_type(typ)) @@ -411,7 +414,10 @@ fn py_array_param_type(inner: &TypeMeta, context: &PythonProjectionContext) -> S fn py_native_param_element_type(inner: &TypeMeta, context: &PythonProjectionContext) -> String { match inner { TypeMeta::RuntimeClass { name, .. } if context.is_known_type(inner) => { - format!("'{}Like'", context.reference_name_for_type(inner)) + format!( + "'{}'", + context.symbol_reference(&inner.type_identity(), PythonSymbol::Like) + ) } _ => py_native_element_type(inner, context), } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs index 0ce68512..a8abb5d6 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs @@ -227,6 +227,19 @@ pub(crate) fn collect_type_imports(class: &ClassMeta) -> HashSet { imports } +pub(crate) fn collect_class_type_imports_by_identity(class: &ClassMeta) -> HashSet { + let mut imports = HashSet::new(); + for iface in class.all_interfaces() { + collect_methods_type_imports(&iface.methods, "", true, &mut imports); + } + imports.retain(|reference| { + reference.kind != TypeKind::Class + || reference.namespace != class.namespace + || reference.name != class.name + }); + imports +} + pub(crate) fn collect_struct_field_type_imports(typ: &TypeMeta) -> HashSet { let TypeMeta::Struct { name, fields, .. } = typ else { return HashSet::new(); diff --git a/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs b/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs new file mode 100644 index 00000000..93345e5b --- /dev/null +++ b/tools/dynwinrt-codegen/tests/python_symbol_mapping_test.rs @@ -0,0 +1,2720 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; +use std::fs; +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::{ + self, ClassMeta, ConstructorKind, ConstructorMeta, InterfaceMeta, MethodMeta, ParamDirection, + ParamMeta, +}; +use dynwinrt_codegen::types::{ + EnumMember, TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef, +}; +use windows_metadata::{ + FieldAttributes, GenericParamAttributes, MethodAttributes, MethodCallAttributes, + MethodImplAttributes, ParamAttributes, Signature, Type, TypeAttributes, TypeName, Value, + writer, +}; + +static NEXT: AtomicU64 = AtomicU64::new(0); + +struct Fixture(PathBuf); + +impl Fixture { + fn new() -> Self { + let directory = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("target") + .join(format!( + "python-symbols-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + fs::create_dir_all(&directory).unwrap(); + Self(directory) + } + + fn package(&self) -> PathBuf { + let package = self.0.join("pyviews"); + fs::create_dir_all(&package).unwrap(); + package + } +} + +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn root() -> PathBuf { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("..") + .join("..") + .canonicalize() + .unwrap(); + let text = path.to_string_lossy(); + PathBuf::from(text.strip_prefix(r"\\?\").unwrap_or(&text)) +} + +fn python() -> PathBuf { + std::env::var_os("DYNWINRT_TEST_PYTHON") + .map(PathBuf::from) + .unwrap_or_else(|| { + let venv = root() + .join("bindings") + .join("py") + .join(".venv") + .join("Scripts") + .join("python.exe"); + if venv.is_file() { + venv + } else { + PathBuf::from("python") + } + }) +} + +fn success(output: Output) { + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); +} + +fn available(arguments: &[&str], description: &str) -> bool { + let available = Command::new(python()) + .args(arguments) + .output() + .is_ok_and(|output| output.status.success()); + assert!( + available || std::env::var("DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME").as_deref() != Ok("1"), + "{description} is required by DYNWINRT_REQUIRE_IMPLEMENTATION_RUNTIME=1", + ); + if !available { + eprintln!( + "Skipping {description}; set DYNWINRT_TEST_PYTHON to the prepared E2E interpreter." + ); + } + available +} + +fn typecheck(directory: &Path, consumer: &str) { + if !available( + &["-m", "mypy", "--version"], + "whole-package Python typechecking", + ) { + return; + } + fs::write(directory.join("consumer.py"), consumer).unwrap(); + // Explicitly check every generated module, not only the public consumer. + success( + Command::new(python()) + .args([ + "-m", + "mypy", + "--no-incremental", + "--follow-imports=normal", + "pyviews", + "consumer.py", + ]) + .current_dir(directory) + .env("MYPYPATH", root().join("bindings").join("py")) + .output() + .unwrap(), + ); +} + +fn reject_consumer(directory: &Path, consumer: &str, codes: &[&str]) { + if !available( + &["-m", "mypy", "--version"], + "strict negative consumer typechecking", + ) { + return; + } + fs::write(directory.join("negative.py"), consumer).unwrap(); + let output = Command::new(python()) + .args([ + "-m", + "mypy", + "--strict", + "--no-incremental", + "--follow-imports=normal", + "--show-error-codes", + "--no-pretty", + "pyviews", + "negative.py", + ]) + .current_dir(directory) + .env("MYPYPATH", root().join("bindings").join("py")) + .output() + .unwrap(); + let diagnostics = String::from_utf8_lossy(&output.stdout); + assert_eq!(output.status.code(), Some(1), "{diagnostics}"); + let errors = diagnostics + .lines() + .filter(|line| line.contains(": error:")) + .collect::>(); + assert_eq!(errors.len(), codes.len(), "{diagnostics}"); + for (error, code) in errors.iter().zip(codes) { + assert!(error.starts_with("negative.py:"), "{diagnostics}"); + assert!(error.ends_with(code), "{diagnostics}"); + } +} + +fn runtime(directory: &Path, source: &str) { + if available( + &[ + "-c", + "import dynwinrt; assert hasattr(dynwinrt, 'DynWinRTImplementationHandle')", + ], + "native Python projection operations", + ) { + fs::write(directory.join("runtime_probe.py"), source).unwrap(); + success( + Command::new(python()) + .args(["-B", "runtime_probe.py"]) + .current_dir(directory) + .output() + .unwrap(), + ); + } +} + +fn module(package: &Path, name: &str, source: String, stub: String) { + fs::write(package.join(format!("{name}.py")), source).unwrap(); + fs::write(package.join(format!("{name}.pyi")), stub).unwrap(); +} + +fn support(package: &Path, interfaces: &[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(interfaces), + ), + ] { + fs::write(package.join(name), source).unwrap(); + } +} + +fn class_type(namespace: &str, name: &str) -> TypeMeta { + TypeMeta::RuntimeClass { + namespace: namespace.into(), + name: name.into(), + default_interface: None, + } +} + +fn echo(name: &str, typ: TypeMeta, index: usize) -> MethodMeta { + MethodMeta { + name: name.into(), + raw_name: name.into(), + vtable_index: index, + params: vec![ParamMeta { + name: "value".into(), + typ: typ.clone(), + direction: ParamDirection::In, + }], + return_type: Some(typ), + ..Default::default() + } +} + +fn class(namespace: &str, name: &str, methods: Vec, id: u32) -> ClassMeta { + ClassMeta { + namespace: namespace.into(), + name: name.into(), + full_name: format!("{namespace}.{name}"), + default_interface: Some(InterfaceMeta { + namespace: namespace.into(), + name: format!("I{name}"), + iid: format!("{id:08x}-6281-4900-b782-040302010910"), + methods, + ..Default::default() + }), + ..Default::default() + } +} + +fn class_identity(class: &ClassMeta) -> TypeIdentity { + class_type(&class.namespace, &class.name).type_identity() +} + +#[test] +fn python_class_self_and_base_markers_use_declarations_in_both_layouts() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.package(); + let mut classes = Vec::new(); + for (namespace, foreign, id) in + [("Alpha", "Beta", 0x51931001), ("Beta", "Alpha", 0x51931010)] + { + classes.push(class(namespace, "Base", vec![], id)); + let mut widget = class( + namespace, + "Widget", + vec![ + echo("EchoSelf", class_type(namespace, "Widget"), 6), + echo("EchoForeign", class_type(foreign, "Widget"), 7), + ], + id + 1, + ); + widget.base_class = Some(TypeRef { + namespace: namespace.into(), + name: "Base".into(), + kind: TypeKind::Class, + }); + classes.push(widget); + let mut derived = class(namespace, "Derived", vec![], id + 2); + derived.base_class = Some(TypeRef { + namespace: foreign.into(), + name: "Base".into(), + kind: TypeKind::Class, + }); + classes.push(derived); + } + let context = python::PythonProjectionContext::new( + classes + .iter() + .map(class_identity) + .chain(classes.iter().filter_map(|class| { + class + .default_interface + .as_ref() + .map(InterfaceMeta::type_identity) + })), + packaged, + ) + .unwrap(); + let mut consumer = "from typing import assert_type\n".to_string(); + for class in &classes { + let identity = class_identity(class); + let name = context.projected_name(&identity); + let module_name = context.implementation_module(&identity); + let source = python::generate_class(&context, class, &Default::default()); + let stub = python_stub::generate_class_stub(&context, class, &Default::default()); + for text in [&source, &stub] { + assert!( + !text.contains(&format!("from .{module_name} import ")), + "{text}" + ); + assert!(text.contains(&format!("class {name}")), "{text}"); + } + if class.name == "Widget" { + let foreign = if class.namespace == "Alpha" { + "Beta" + } else { + "Alpha" + }; + assert_ne!( + context.reference_name(&identity), + name, + "fixture must require a local self binding" + ); + assert!( + stub.contains("def echo_self(self, value: 'WidgetLike') -> Widget | None:"), + "{stub}" + ); + assert!( + !source.contains(&context.reference_name(&identity)), + "{source}" + ); + let foreign_module = + context.implementation_module(&class_type(foreign, "Widget").type_identity()); + assert!( + stub.contains(&format!("from .{foreign_module} import Widget as ")), + "{stub}" + ); + } + if let Some(base) = &class.base_class { + let identity = class_type(&base.namespace, &base.name).type_identity(); + let declaration = context.projected_name(&identity); + let reference = context.reference_name(&identity); + assert_ne!(declaration, reference); + assert!( + stub.contains(&format!( + "from .{} import _{declaration}Identity as _{reference}Identity", + context.implementation_module(&identity), + )), + "{stub}" + ); + assert!( + stub.contains(&format!( + "class _{name}Identity(_{reference}Identity, Protocol):" + )), + "{stub}" + ); + } + consumer.push_str(&format!( + "from pyviews.{module_name} import {name} as {namespace}{name}, {name}Like as {namespace}{name}Like\n", + namespace = class.namespace, + )); + module(&package, &module_name, source, stub); + } + consumer.push_str( + r#" +def alpha(value: AlphaWidget, peer: BetaWidget, child: AlphaDerived) -> None: + own: AlphaBaseLike = value + foreign: BetaBaseLike = child + assert_type(value.echo_self(value), AlphaWidget | None) + assert_type(value.echo_foreign(peer), BetaWidget | None) +def beta(value: BetaWidget, peer: AlphaWidget, child: BetaDerived) -> None: + own: BetaBaseLike = value + foreign: AlphaBaseLike = child + assert_type(value.echo_self(value), BetaWidget | None) + assert_type(value.echo_foreign(peer), AlphaWidget | None) +"#, + ); + support(&package, &[]); + typecheck(&fixture.0, &consumer); + reject_consumer( + &fixture.0, + &format!( + r#"{consumer} +def reject_wrong_identity(value: AlphaWidget, peer: BetaWidget) -> None: + value.echo_self(peer) + wrong_base: AlphaBaseLike = peer + result = value.echo_self(value) + if result is not None: + result.no_such_member() +"# + ), + &["[arg-type]", "[assignment]", "[attr-defined]"], + ); + } +} + +#[test] +fn python_named_class_closed_generic_collision_uses_allocated_declaration() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.package(); + let namespace = "Classes"; + let named_type = class_type(namespace, "IBucket_String"); + let generic_type = TypeMeta::Parameterized { + namespace: namespace.into(), + name: "IBucket`1".into(), + piid: "51931300-6281-4900-b782-040302010910".into(), + args: vec![TypeMeta::String], + }; + let mut named = class( + namespace, + "IBucket_String", + vec![ + echo("EchoSelf", named_type.clone(), 6), + echo("EchoGeneric", generic_type.clone(), 7), + ], + 0x51931301, + ); + let factory = InterfaceMeta { + namespace: namespace.into(), + name: "IBucketFactory".into(), + iid: "51931302-6281-4900-b782-040302010910".into(), + methods: vec![MethodMeta { + name: "CreateNamed".into(), + raw_name: "CreateNamed".into(), + vtable_index: 6, + params: vec![ParamMeta { + name: "value".into(), + typ: TypeMeta::I32, + direction: ParamDirection::In, + }], + return_type: Some(named_type.clone()), + ..Default::default() + }], + ..Default::default() + }; + named.constructors = vec![ + ConstructorMeta { + kind: ConstructorKind::DefaultActivation, + factory_interface: None, + }, + ConstructorMeta { + kind: ConstructorKind::FactoryActivation, + factory_interface: Some(TypeRef { + namespace: namespace.into(), + name: factory.name.clone(), + kind: TypeKind::Interface, + }), + }, + ]; + named.has_default_constructor = true; + named.factory_interfaces.push(factory); + named.static_interfaces.push(InterfaceMeta { + namespace: namespace.into(), + name: "IBucketStatics".into(), + iid: "51931303-6281-4900-b782-040302010910".into(), + methods: vec![MethodMeta { + name: "GetCurrent".into(), + raw_name: "GetCurrent".into(), + vtable_index: 6, + return_type: Some(named_type.clone()), + ..Default::default() + }], + ..Default::default() + }); + let mut derived = class(namespace, "Derived", vec![], 0x51931304); + derived.base_class = Some(TypeRef { + namespace: namespace.into(), + name: "IBucket_String".into(), + kind: TypeKind::Class, + }); + derived + .required_interfaces + .push(named.default_interface.as_ref().unwrap().clone()); + let generic = InterfaceMeta { + namespace: namespace.into(), + name: "IBucket_String".into(), + generic_name: Some("IBucket`1".into()), + generic_piid: Some("51931300-6281-4900-b782-040302010910".into()), + generic_args: vec![TypeMeta::String], + methods: vec![ + echo("EchoSelf", generic_type.clone(), 6), + echo("EchoNamed", named_type.clone(), 7), + ], + ..Default::default() + }; + assert_ne!(named_type.type_identity(), generic.type_identity()); + let context = python::PythonProjectionContext::new( + [ + named_type.type_identity(), + generic.type_identity(), + class_identity(&derived), + ] + .into_iter() + .chain(named.all_interfaces().map(InterfaceMeta::type_identity)) + .chain(derived.all_interfaces().map(InterfaceMeta::type_identity)), + packaged, + ) + .unwrap(); + let named_declaration = context.projected_name_for_type(&named_type); + let generic_declaration = context.projected_name_for_interface(&generic); + let named_module = context.implementation_module_for_type(&named_type); + let generic_module = context.implementation_module_for_interface(&generic); + let derived_module = context.implementation_module(&class_identity(&derived)); + assert_ne!(named_declaration, "IBucket_String"); + assert_ne!(named_declaration, generic_declaration); + let source = python::generate_class(&context, &named, &Default::default()); + let stub = python_stub::generate_class_stub(&context, &named, &Default::default()); + for text in [&source, &stub] { + assert!( + text.contains(&format!("class {named_declaration}")), + "{text}" + ); + assert!( + text.contains(&format!( + "from .{generic_module} import {generic_declaration}" + )), + "{text}", + ); + assert!( + !text.contains(&format!("from .{named_module} import ")), + "{text}" + ); + } + assert!( + source.contains("activation_factory('Classes.IBucket_String')"), + "the allocated Python declaration must not change the native activation name:\n{source}", + ); + assert!( + !source.contains(&format!( + "activation_factory('Classes.{named_declaration}')" + )), + "{source}", + ); + assert!( + stub.contains(&format!("class _{named_declaration}Identity(")) + && stub.contains(&format!("class {named_declaration}Like(")), + "{stub}", + ); + module(&package, &named_module, source, stub); + let derived_stub = + python_stub::generate_class_stub(&context, &derived, &Default::default()); + assert!( + derived_stub.contains(&format!( + "from .{named_module} import _{named_declaration}Identity" + )), + "{derived_stub}", + ); + module( + &package, + &derived_module, + python::generate_class(&context, &derived, &Default::default()), + derived_stub, + ); + let source = python::generate_interface(&context, &generic); + let stub = python_stub::generate_interface_stub(&context, &generic); + for text in [&source, &stub] { + assert!( + text.contains(&format!("from .{named_module} import {named_declaration}")), + "a named peer is not the closed generic's self type:\n{text}", + ); + assert!( + !text.contains(&format!("from .{generic_module} import ")), + "{text}" + ); + } + module(&package, &generic_module, source, stub); + support(&package, &[]); + let imports = format!( + "from pyviews.{named_module} import {named_declaration} as Named, {named_declaration}Like as NamedLike\n\ + from pyviews.{generic_module} import {generic_declaration} as Bucket\n\ + from pyviews.{derived_module} import Derived\n", + ); + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +assert_type(Named(), Named) +assert_type(Named(7), Named) +assert_type(Named.get_current(), Named | None) +def check(named: Named, generic: Bucket, derived: Derived) -> None: + base: NamedLike = derived + assert_type(named.echo_self(named), Named | None) + assert_type(named.echo_generic(generic), Bucket | None) + assert_type(generic.echo_self(generic), Bucket | None) + assert_type(generic.echo_named(named), Named | None) +"#, + ), + ); + runtime( + &fixture.0, + &format!( + r#" +from pyviews.{named_module} import {named_declaration} as Named +from pyviews.{generic_module} import {generic_declaration} as Bucket +assert Named is not Bucket +assert Named.__name__ == "{named_declaration}" +assert Bucket.__name__ == "{generic_declaration}" +"#, + ), + ); + } +} + +fn enumeration(namespace: &str, name: &str) -> TypeMeta { + TypeMeta::Enum { + namespace: namespace.into(), + name: name.into(), + underlying: Box::new(TypeMeta::I32), + members: vec![EnumMember { + name: "Unknown".into(), + value: 0, + doc: None, + }], + is_flags: false, + doc: None, + deprecated: None, + } +} + +#[test] +fn python_element_factory_and_dispatcher_helpers_resolve_colliding_names() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.package(); + let xaml = "Microsoft.UI.Xaml"; + let dispatching = "Microsoft.UI.Dispatching"; + let mut classes = Vec::new(); + for namespace in [xaml, "Shadow"] { + for name in [ + "ElementFactoryGetArgs", + "ElementFactoryRecycleArgs", + "UIElement", + ] { + classes.push(class( + namespace, + name, + vec![], + 0x51931100 + classes.len() as u32, + )); + } + } + let factory = InterfaceMeta { + namespace: xaml.into(), + name: "IElementFactory".into(), + iid: "75faba47-2cf2-54ae-91e6-0581556fddaa".into(), + methods: vec![ + MethodMeta { + name: "GetElement".into(), + raw_name: "GetElement".into(), + vtable_index: 6, + params: vec![ParamMeta { + name: "args".into(), + typ: class_type(xaml, "ElementFactoryGetArgs"), + direction: ParamDirection::In, + }], + return_type: Some(class_type(xaml, "UIElement")), + ..Default::default() + }, + MethodMeta { + name: "RecycleElement".into(), + raw_name: "RecycleElement".into(), + vtable_index: 7, + params: vec![ParamMeta { + name: "args".into(), + typ: class_type(xaml, "ElementFactoryRecycleArgs"), + direction: ParamDirection::In, + }], + ..Default::default() + }, + ], + ..Default::default() + }; + let priorities = [ + enumeration(dispatching, "DispatcherQueuePriority"), + enumeration("Shadow", "DispatcherQueuePriority"), + ]; + let queue = class( + dispatching, + "DispatcherQueue", + vec![echo("EchoPriority", priorities[0].clone(), 6)], + 0x51931110, + ); + classes.push(queue.clone()); + let context = python::PythonProjectionContext::new( + classes + .iter() + .map(class_identity) + .chain(classes.iter().filter_map(|class| { + class + .default_interface + .as_ref() + .map(InterfaceMeta::type_identity) + })) + .chain(priorities.iter().map(TypeMeta::type_identity)) + .chain([factory.type_identity()]), + packaged, + ) + .unwrap(); + let stub = python_stub::generate_interface_stub(&context, &factory); + let get_args = context.reference_name_for_type(&class_type(xaml, "ElementFactoryGetArgs")); + let recycle_args = + context.reference_name_for_type(&class_type(xaml, "ElementFactoryRecycleArgs")); + let element = context.reference_name_for_type(&class_type(xaml, "UIElement")); + assert_ne!(get_args, "ElementFactoryGetArgs"); + assert!( + stub.contains(&format!( + "get_element: Callable[['{get_args}'], '{element}']" + )), + "{stub}" + ); + assert!( + stub.contains(&format!( + "recycle_element: Callable[['{recycle_args}'], object]" + )), + "{stub}" + ); + let factory_source = python::generate_interface(&context, &factory); + for name in ["ElementFactoryGetArgs", "ElementFactoryRecycleArgs"] { + let typ = class_type(xaml, name); + assert!( + factory_source.contains(&format!( + "'{}', '{}'", + context.implementation_module_for_type(&typ), + context.projected_name_for_type(&typ), + )), + "runtime lookup must target the declaring module, not a consumer alias:\n{factory_source}", + ); + } + let ui_element_interface = classes + .iter() + .find(|class| class.namespace == xaml && class.name == "UIElement") + .unwrap() + .default_interface + .as_ref() + .unwrap(); + let ui_element_iid = format!( + "IID_{}", + context.reference_name(&ui_element_interface.type_identity()), + ); + assert_ne!( + ui_element_iid, "IID_IUIElement", + "fixture must qualify the interface IID" + ); + assert!( + factory_source.contains(&format!( + "'{}', '{ui_element_iid}'", + context.implementation_module_for_type(&class_type(xaml, "UIElement")), + )), + "the extension must load the IID exported by the class module:\n{factory_source}", + ); + module( + &package, + &context.implementation_module_for_interface(&factory), + factory_source, + stub, + ); + for class in &classes { + let source = python::generate_class(&context, class, &Default::default()); + let stub = python_stub::generate_class_stub(&context, class, &Default::default()); + if class.namespace == xaml && class.name == "UIElement" { + assert!( + source.contains(&format!("{ui_element_iid} = WinGUID.parse(")), + "{source}" + ); + } + if class.name == "DispatcherQueue" { + let priority = context.reference_name_for_type(&priorities[0]); + assert_ne!(priority, "DispatcherQueuePriority"); + assert!(stub.contains(&format!("priority: '{priority}'")), "{stub}"); + } + module( + &package, + &context.implementation_module(&class_identity(class)), + source, + stub, + ); + } + for typ in &priorities { + module( + &package, + &context.implementation_module_for_type(typ), + python::generate_enum(&context, typ).unwrap(), + python_stub::generate_enum_stub(&context, typ).unwrap(), + ); + } + support(&package, &[]); + typecheck( + &fixture.0, + &format!( + r#" +from typing import assert_type +from pyviews.{factory_module} import IElementFactory +from pyviews.{get_module} import ElementFactoryGetArgs +from pyviews.{recycle_module} import ElementFactoryRecycleArgs +from pyviews.{element_module} import UIElement +from pyviews.{queue_module} import DispatcherQueue +from pyviews.{priority_module} import DispatcherQueuePriority +def element(args: ElementFactoryGetArgs) -> UIElement: + raise NotImplementedError +def recycle(args: ElementFactoryRecycleArgs) -> None: + pass +assert_type(IElementFactory.create(element, recycle), IElementFactory) +async def schedule(queue: DispatcherQueue) -> None: + assert_type(await queue.enqueue_with_priority_async(DispatcherQueuePriority.Unknown, lambda: 7), int) +"#, + factory_module = context.implementation_module_for_interface(&factory), + get_module = context + .implementation_module_for_type(&class_type(xaml, "ElementFactoryGetArgs")), + recycle_module = context + .implementation_module_for_type(&class_type(xaml, "ElementFactoryRecycleArgs")), + element_module = + context.implementation_module_for_type(&class_type(xaml, "UIElement")), + queue_module = context.implementation_module(&class_identity(&queue)), + priority_module = context.implementation_module_for_type(&priorities[0]), + ), + ); + runtime( + &fixture.0, + &format!( + r#" +import dynwinrt as dw +from pyviews.{factory_module} import IElementFactory +def unused(args): + raise AssertionError("factory creation must not invoke callbacks") +with dw.RoApartment(1): + factory = IElementFactory.create(unused, unused) + try: + assert type(factory) is IElementFactory + finally: + factory.release_callbacks() + dw.release_projected(factory) +"#, + factory_module = context.implementation_module_for_interface(&factory), + ), + ); + } +} + +fn iid(file: &mut writer::File, definition: writer::TypeDef, id: u32) { + 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(definition), + writer::AttributeType::MemberRef(constructor), + &[ + Value::U32(id), + Value::U16(0x6281), + Value::U16(0x4900), + Value::U8(0xb7), + Value::U8(0x82), + Value::U8(4), + Value::U8(3), + Value::U8(2), + Value::U8(1), + Value::U8(9), + Value::U8(0x10), + ] + .into_iter() + .map(|value| (String::new(), value)) + .collect::>(), + ); +} + +fn interface(file: &mut writer::File, namespace: &str, name: &str, id: u32) -> writer::TypeDef { + let definition = file.TypeDef( + namespace, + name, + writer::TypeDefOrRef::default(), + TypeAttributes::Public + | TypeAttributes::Interface + | TypeAttributes::Abstract + | TypeAttributes::WindowsRuntime, + ); + iid(file, definition, id); + definition +} + +fn structure(file: &mut writer::File, namespace: &str, name: &str, fields: &[(&str, Type)]) { + let base = file.TypeRef("System", "ValueType"); + file.TypeDef( + namespace, + name, + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public + | TypeAttributes::Sealed + | TypeAttributes::SequentialLayout + | TypeAttributes::WindowsRuntime, + ); + for (name, typ) in fields { + file.Field(name, typ, FieldAttributes::Public); + } +} + +fn method( + file: &mut writer::File, + name: &str, + result: Type, + params: &[(&str, Type, ParamAttributes)], +) { + file.MethodDef( + name, + &Signature { + flags: MethodCallAttributes::HASTHIS, + return_type: result, + types: params.iter().map(|(_, typ, _)| typ.clone()).collect(), + }, + MethodAttributes::Public + | MethodAttributes::Abstract + | MethodAttributes::Virtual + | MethodAttributes::NewSlot, + MethodImplAttributes::default(), + ); + for (index, (name, _, flags)) in params.iter().enumerate() { + file.Param(name, index as u16 + 1, *flags); + } +} + +fn metadata(path: &Path) { + let mut file = writer::File::new("PythonSymbolMapping"); + let alpha = Type::named("Alpha", "URLValue"); + let beta = Type::named("Beta", "UrlValue"); + let pair = Type::named("Containers", "NormalizedPair"); + structure(&mut file, "Alpha", "URLValue", &[("Value", Type::I32)]); + structure(&mut file, "Beta", "UrlValue", &[("Other", Type::I64)]); + structure( + &mut file, + "Containers", + "NormalizedPair", + &[("First", alpha.clone()), ("Second", beta.clone())], + ); + interface(&mut file, "Audit", "IAlpha", 0x51931205); + method( + &mut file, + "EchoAlpha", + alpha.clone(), + &[("value", alpha.clone(), ParamAttributes::In)], + ); + let callback_base = file.TypeRef("System", "MulticastDelegate"); + let callback = file.TypeDef( + "Audit", + "PairCallback", + writer::TypeDefOrRef::TypeRef(callback_base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + iid(&mut file, callback, 0x51931200); + method(&mut file, ".ctor", Type::Void, &[]); + method( + &mut file, + "Invoke", + Type::Void, + &[ + ("first", alpha.clone(), ParamAttributes::In), + ("second", beta.clone(), ParamAttributes::In), + ], + ); + interface(&mut file, "Audit", "IHelpers", 0x51931201); + for (name, typ) in [ + ("EchoAlpha", alpha.clone()), + ("EchoBeta", beta.clone()), + ("EchoPair", pair.clone()), + ("EchoArray", Type::Array(Box::new(alpha.clone()))), + ] { + method( + &mut file, + name, + typ.clone(), + &[("value", typ, ParamAttributes::In)], + ); + } + method( + &mut file, + "Split", + alpha, + &[("second", beta, ParamAttributes::Out)], + ); + method( + &mut file, + "UseCallback", + pair, + &[( + "callback", + Type::named("Audit", "PairCallback"), + ParamAttributes::In, + )], + ); + + let generic = interface(&mut file, "Enums", "IBucket`1", 0x51931202); + file.GenericParam( + "T", + writer::TypeOrMethodDef::TypeDef(generic), + 0, + GenericParamAttributes::default(), + ); + method(&mut file, "Ping", Type::Void, &[]); + let base = file.TypeRef("System", "Enum"); + file.TypeDef( + "Enums", + "IBucket_String", + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + file.Field( + "value__", + &Type::I32, + FieldAttributes::Public | FieldAttributes::SpecialName | FieldAttributes::RTSpecialName, + ); + let kind = Type::named("Enums", "IBucket_String"); + let member = file.Field( + "Unknown", + &kind, + FieldAttributes::Public + | FieldAttributes::Static + | FieldAttributes::Literal + | FieldAttributes::HasDefault, + ); + file.Constant(writer::HasConstant::Field(member), &Value::I32(0)); + let bucket = Type::Name(TypeName { + namespace: "Enums".into(), + name: "IBucket`1".into(), + generics: vec![Type::String], + }); + interface(&mut file, "Enums", "IUse", 0x51931203); + method(&mut file, "GetBucket", bucket.clone(), &[]); + method( + &mut file, + "EchoKind", + kind.clone(), + &[("value", kind.clone(), ParamAttributes::In)], + ); + method( + &mut file, + "EchoKinds", + Type::Array(Box::new(kind.clone())), + &[( + "value", + Type::Array(Box::new(kind.clone())), + ParamAttributes::In, + )], + ); + interface(&mut file, "Consumers", "IForeign", 0x51931204); + method(&mut file, "GetBucket", bucket, &[]); + method( + &mut file, + "EchoKind", + kind.clone(), + &[("value", kind, ParamAttributes::In)], + ); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, file.into_stream()).unwrap(); +} + +fn helper_interface(path: &Path) -> InterfaceMeta { + meta::parse_interfaces(path.to_str().unwrap(), "Audit") + .into_iter() + .find(|interface| interface.name == "IHelpers") + .unwrap() +} + +fn structures(interface: &InterfaceMeta) -> Vec { + interface + .methods + .iter() + .take(3) + .map(|method| method.return_type.clone().unwrap()) + .collect() +} + +fn write_structs( + package: &Path, + context: &python::PythonProjectionContext, + structures: &[TypeMeta], +) { + for typ in structures { + module( + package, + &context.implementation_module_for_type(typ), + python::generate_struct(context, typ).unwrap(), + python_stub::generate_struct_stub(context, typ).unwrap(), + ); + } +} + +fn imported_symbol(source: &str, module: &str, declaration: &str) -> String { + let prefix = format!("from .{module} import "); + source + .lines() + .filter_map(|line| line.trim().strip_prefix(&prefix)) + .flat_map(|imports| imports.split('#').next().unwrap().split(',')) + .find_map(|import| { + let words = import.split_whitespace().collect::>(); + (words.first().copied() == Some(declaration)).then(|| words.last().unwrap().to_string()) + }) + .unwrap_or_else(|| panic!("missing {declaration} from {module}:\n{source}")) +} + +fn registration_metadata(path: &Path, initial_collision: bool) -> (InterfaceMeta, Vec) { + let mut file = writer::File::new("PythonRegistrationSymbols"); + structure(&mut file, "Alpha", "URLValue", &[("Value", Type::I32)]); + structure(&mut file, "Beta", "UrlValue", &[("Other", Type::I64)]); + let name = if initial_collision { + "pack_url_value" + } else { + "pack_beta_url_value_struct" + }; + interface(&mut file, "Audit", name, 0x51931500); + let alpha = Type::named("Alpha", "URLValue"); + method( + &mut file, + "EchoAlpha", + alpha.clone(), + &[("value", alpha, ParamAttributes::In)], + ); + if !initial_collision { + let beta = Type::named("Beta", "UrlValue"); + method( + &mut file, + "EchoBeta", + beta.clone(), + &[("value", beta, ParamAttributes::In)], + ); + } + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, file.into_stream()).unwrap(); + let interface = meta::parse_interfaces(path.to_str().unwrap(), "Audit") + .pop() + .unwrap(); + let structures = interface + .methods + .iter() + .map(|method| method.return_type.clone().unwrap()) + .collect(); + (interface, structures) +} + +fn unused_registration_identities() -> impl Iterator { + ["unpack_url_value", "URLValue_TYPE", "IActivationFactory"] + .into_iter() + .map(|name| TypeIdentity::named(TypeIdentityKind::Interface, "Unrelated", name)) +} + +fn registration_bindings(source: &str, expected: &[&str]) -> BTreeMap { + let lines = source.lines().collect::>(); + let mut registrations = BTreeMap::new(); + for (index, line) in lines.iter().enumerate() { + let Some(symbol) = line.strip_suffix(" = DynWinRTType.register_interface(") else { + continue; + }; + assert!(!symbol.starts_with(char::is_whitespace), "{line}"); + let arguments = lines[index + 1].trim(); + let quote = arguments.chars().next().unwrap(); + assert!(matches!(quote, '\'' | '"'), "{arguments}"); + let name = arguments[1..].split(quote).next().unwrap(); + assert!( + registrations + .insert(name.to_string(), symbol.to_string()) + .is_none(), + "duplicate registration for {name}:\n{source}" + ); + let assignments = lines + .iter() + .filter(|line| { + line.starts_with(&format!("{symbol} = ")) + || line.starts_with(&format!("def {symbol}(")) + || line.starts_with(&format!("class {symbol}:")) + || line.starts_with(&format!("class {symbol}(")) + }) + .count(); + let imports = lines + .iter() + .filter_map(|line| { + line.trim() + .strip_prefix("from ")? + .split_once(" import ") + .map(|(_, names)| names) + }) + .flat_map(|names| names.split('#').next().unwrap().split(',')) + .filter(|name| name.split_whitespace().last() == Some(symbol)) + .count(); + assert_eq!( + assignments + imports, + 1, + "native registration {symbol} must not share its binding with any helper or type:\n{source}" + ); + assert!( + source.contains(&format!("{symbol}.method(")), + "generated calls must reference their allocated registration {symbol}:\n{source}" + ); + } + assert_eq!( + registrations + .keys() + .map(String::as_str) + .collect::>(), + expected.iter().copied().collect(), + "reserve exactly the registrations this module actually emits:\n{source}", + ); + registrations +} + +fn registration_struct_modules( + package: &Path, + context: &python::PythonProjectionContext, + structures: &[TypeMeta], +) { + let isolated = python::PythonProjectionContext::new( + structures.iter().map(TypeMeta::type_identity), + context.is_packaged(), + ) + .unwrap(); + for structure in structures { + let source = python::generate_struct(context, structure).unwrap(); + let stub = python_stub::generate_struct_stub(context, structure).unwrap(); + assert_eq!( + source, + python::generate_struct(&isolated, structure).unwrap(), + "non-emitted interface registrations must not alter an owning struct's public API" + ); + assert_eq!( + stub, + python_stub::generate_struct_stub(&isolated, structure).unwrap() + ); + module( + package, + &context.implementation_module_for_type(structure), + source, + stub, + ); + } +} + +#[test] +fn python_native_registration_interface_symbols_do_not_shadow_struct_helpers() { + for packaged in [true, false] { + for initial_collision in [true, false] { + let fixture = Fixture::new(); + let package = fixture.package(); + let (interface, structures) = registration_metadata( + &fixture.0.join("metadata").join("Input.winmd"), + initial_collision, + ); + let identities = structures + .iter() + .map(TypeMeta::type_identity) + .chain([interface.type_identity()]) + .collect::>(); + let context = + python::PythonProjectionContext::new(identities.clone(), packaged).unwrap(); + let reordered = + python::PythonProjectionContext::new(identities.iter().rev().cloned(), packaged) + .unwrap(); + let unrelated = python::PythonProjectionContext::new( + identities + .into_iter() + .chain(unused_registration_identities()), + packaged, + ) + .unwrap(); + let source = python::generate_interface(&context, &interface); + let stub = python_stub::generate_interface_stub(&context, &interface); + for alternative in [&reordered, &unrelated] { + assert_eq!(source, python::generate_interface(alternative, &interface)); + assert_eq!( + stub, + python_stub::generate_interface_stub(alternative, &interface) + ); + } + let registrations = registration_bindings(&source, &[&interface.name]); + let owner_module = context.implementation_module_for_interface(&interface); + module(&package, &owner_module, source, stub); + registration_struct_modules(&package, &unrelated, &structures); + support( + &package, + if packaged { + std::slice::from_ref(&owner_module) + } else { + &[] + }, + ); + let alpha_module = context.implementation_module_for_type(&structures[0]); + let payload_module = if packaged { + &alpha_module + } else { + &owner_module + }; + let mut imports = format!( + "from pyviews.{owner_module} import {name} as Projection\n\ + from pyviews.{payload_module} import URLValue as Alpha\n", + name = context.projected_name_for_interface(&interface), + ); + let mut beta_check = String::new(); + let mut beta_runtime = String::new(); + let mut beta_public = String::new(); + if let Some(beta) = structures.get(1) { + let beta_module = context.implementation_module_for_type(beta); + let payload_module = if packaged { + &beta_module + } else { + &owner_module + }; + imports.push_str(&format!( + "from pyviews.{payload_module} import UrlValue as Beta\n" + )); + beta_check.push_str(" assert_type(value.echo_beta(Beta(2**40)), Beta)\n"); + beta_runtime + .push_str(" assert view.echo_beta(Beta(2**40)) == Beta(2**40 + 1)\n"); + beta_public = format!( + "from pyviews.{beta_module} import UrlValue as CanonicalBeta, pack_url_value as pack_beta, unpack_url_value as unpack_beta\n\ + assert unpack_beta(pack_beta(CanonicalBeta(2**40)).to_value()) == CanonicalBeta(2**40)\n" + ); + } + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +def check(value: Projection) -> None: + assert_type(value.echo_alpha(Alpha(17)), Alpha) +{beta_check} +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + r#"{imports} +def reject(value: Projection) -> None: + value.echo_alpha(17) + wrong: str = value.echo_alpha(Alpha(17)) +"# + ), + &["[arg-type]", "[assignment]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import importlib +import struct +import typing +import dynwinrt as dw +from pyviews.{alpha_module} import URLValue as CanonicalAlpha, URLValue_TYPE, pack_url_value as pack_alpha, unpack_url_value as unpack_alpha +assert struct.calcsize("P") == 8 +assert isinstance(URLValue_TYPE, dw.DynWinRTType) +assert typing.get_type_hints(pack_alpha)["v"] is CanonicalAlpha +assert typing.get_type_hints(unpack_alpha)["return"] is CanonicalAlpha +assert unpack_alpha(pack_alpha(CanonicalAlpha(17)).to_value()) == CanonicalAlpha(17) +{beta_public} +owner = importlib.import_module("pyviews.{owner_module}") +registrations = {registrations} +for symbol in registrations.values(): + assert isinstance(getattr(owner, symbol), dw.DynWinRTType) +class Handler: + def __init__(self): self.calls = [] + def echo_alpha(self, value): + self.calls.append(("alpha", value.value)) + return type(value)(value.value + 1) + def echo_beta(self, value): + self.calls.append(("beta", value.other)) + return type(value)(value.other + 1) +handler = Handler() +with dw.RoApartment(1), Projection.implement(handler) as implementation: + view = implementation.value + assert view.echo_alpha(Alpha(17)) == Alpha(18) +{beta_runtime} +assert handler.calls == {expected_calls} +for symbol in registrations.values(): + assert isinstance(getattr(owner, symbol), dw.DynWinRTType) +"#, + registrations = serde_json::to_string(®istrations).unwrap(), + expected_calls = if initial_collision { + "[('alpha', 17)]" + } else { + "[('alpha', 17), ('beta', 2**40)]" + }, + ), + ); + } + } +} + +#[test] +fn python_native_registration_class_routes_reserve_all_emitted_interfaces() { + for packaged in [true, false] { + for initial_collision in [true, false] { + for shared_required in [true, false] { + let fixture = Fixture::new(); + let package = fixture.package(); + let (default, structures) = registration_metadata( + &fixture.0.join("metadata").join("Input.winmd"), + initial_collision, + ); + let mut required = default.clone(); + required.name = "unpack_alpha_url_value_struct".into(); + required.iid = "51931501-6281-4900-b782-040302010910".into(); + for method in &mut required.methods { + method.name = format!("Required{}", method.name); + method.raw_name = method.name.clone(); + } + let mut statics = default.clone(); + statics.name = "unpack_beta_url_value_struct".into(); + statics.iid = "51931502-6281-4900-b782-040302010910".into(); + for method in &mut statics.methods { + method.name = format!("Static{}", method.name); + method.raw_name = method.name.clone(); + } + let factory = InterfaceMeta { + namespace: "Audit".into(), + name: "pack_alpha_url_value_struct".into(), + iid: "51931503-6281-4900-b782-040302010910".into(), + methods: vec![MethodMeta { + name: "CreateWrapper".into(), + raw_name: "CreateWrapper".into(), + vtable_index: 6, + params: structures + .iter() + .enumerate() + .map(|(index, typ)| ParamMeta { + name: format!("value{index}"), + typ: typ.clone(), + direction: ParamDirection::In, + }) + .collect(), + return_type: Some(class_type("Audit", "Wrapper")), + ..Default::default() + }], + ..Default::default() + }; + let wrapper = ClassMeta { + namespace: "Audit".into(), + name: "Wrapper".into(), + full_name: "Audit.Wrapper".into(), + default_interface: Some(default.clone()), + required_interfaces: vec![required.clone()], + static_interfaces: vec![statics.clone()], + factory_interfaces: vec![factory.clone()], + constructors: vec![ConstructorMeta { + kind: ConstructorKind::FactoryActivation, + factory_interface: Some(TypeRef { + namespace: factory.namespace.clone(), + name: factory.name.clone(), + kind: TypeKind::Interface, + }), + }], + ..Default::default() + }; + let identities = structures + .iter() + .map(TypeMeta::type_identity) + .chain(wrapper.all_interfaces().map(InterfaceMeta::type_identity)) + .chain([class_identity(&wrapper)]) + .collect::>(); + let context = + python::PythonProjectionContext::new(identities.clone(), packaged).unwrap(); + let reordered = python::PythonProjectionContext::new( + identities.iter().rev().cloned(), + packaged, + ) + .unwrap(); + let unrelated = python::PythonProjectionContext::new( + identities + .into_iter() + .chain(unused_registration_identities()), + packaged, + ) + .unwrap(); + let shared_iids = if shared_required { + HashSet::from([required.iid.clone()]) + } else { + HashSet::new() + }; + let source = python::generate_class(&context, &wrapper, &shared_iids); + let stub = python_stub::generate_class_stub(&context, &wrapper, &shared_iids); + let required_module = context.implementation_module_for_interface(&required); + let required_symbol = context.reference_name(&required.type_identity()); + if shared_required { + assert_eq!( + imported_symbol( + &source, + &required_module, + &context.projected_name_for_interface(&required) + ), + required_symbol, + ); + assert!( + !source.contains(&format!("\nclass {required_symbol}:")), + "{source}" + ); + } else { + assert!( + source.contains(&format!("\nclass {required_symbol}:")), + "{source}" + ); + assert!( + stub.contains(&format!("\nclass {required_symbol}:")), + "{stub}" + ); + assert!( + !source.contains(&format!("from .{required_module} import ")), + "{source}" + ); + } + for alternative in [&reordered, &unrelated] { + assert_eq!( + source, + python::generate_class(alternative, &wrapper, &shared_iids) + ); + assert_eq!( + stub, + python_stub::generate_class_stub(alternative, &wrapper, &shared_iids) + ); + } + let expected = wrapper + .all_interfaces() + .map(|interface| interface.name.as_str()) + .collect::>(); + let registrations = registration_bindings(&source, &expected); + assert!(!registrations.contains_key("IActivationFactory")); + for interface in wrapper.all_interfaces() { + let iid = format!("IID_{}", context.reference_name(&interface.type_identity())); + assert!( + source.contains(&format!("\"{}\", {iid})", interface.name)), + "{source}" + ); + assert!(source.contains(&interface.iid), "{source}"); + } + assert!( + source.contains("activation_factory('Audit.Wrapper')"), + "{source}" + ); + let wrapper_module = context.implementation_module(&class_identity(&wrapper)); + module(&package, &wrapper_module, source, stub); + for interface in [&default, &required] { + module( + &package, + &context.implementation_module_for_interface(interface), + python::generate_interface(&context, interface), + python_stub::generate_interface_stub(&context, interface), + ); + } + registration_struct_modules(&package, &unrelated, &structures); + let implementation_modules = [&default, &required] + .map(|interface| context.implementation_module_for_interface(interface)); + support( + &package, + if packaged { + &implementation_modules + } else { + &[] + }, + ); + let alpha_module = context.implementation_module_for_type(&structures[0]); + let payload_module = if packaged { + &alpha_module + } else { + &wrapper_module + }; + let mut imports = format!( + "from pyviews.{wrapper_module} import Wrapper\n\ + from pyviews.{payload_module} import URLValue as Alpha\n", + ); + let mut beta_check = String::new(); + let mut beta_runtime = String::new(); + let mut beta_constructor = String::new(); + if let Some(beta) = structures.get(1) { + let beta_module = context.implementation_module_for_type(beta); + let payload_module = if packaged { + &beta_module + } else { + &wrapper_module + }; + imports.push_str(&format!( + "from pyviews.{payload_module} import UrlValue as Beta\n" + )); + beta_check = " assert_type(value.echo_beta(Beta(2**40)), Beta)\n assert_type(value.required_echo_beta(Beta(2**40)), Beta)\n assert_type(Wrapper.static_echo_beta(Beta(2**40)), Beta)\n".into(); + beta_runtime = " assert value.echo_beta(Beta(2**40)) == Beta(2**40 + 1)\n assert value.required_echo_beta(Beta(2**40)) == Beta(2**40 + 2)\n".into(); + beta_constructor = ", Beta(2**40)".into(); + } + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +def check(value: Wrapper) -> None: + assert_type(value.echo_alpha(Alpha(17)), Alpha) + assert_type(value.required_echo_alpha(Alpha(17)), Alpha) + assert_type(Wrapper.static_echo_alpha(Alpha(17)), Alpha) + assert_type(Wrapper(Alpha(17){beta_constructor}), Wrapper) +{beta_check} +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + r#"{imports} +def reject(value: Wrapper) -> None: + value.echo_alpha("wrong") + value.required_echo_alpha("wrong") +"# + ), + &["[arg-type]", "[arg-type]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import importlib +import struct +import dynwinrt as dw +from pyviews.{default_module} import {default_name} as DefaultProjection +from pyviews.{required_module} import {required_name} as RequiredProjection +assert struct.calcsize("P") == 8 +owner = importlib.import_module("pyviews.{wrapper_module}") +registrations = {registrations} +for symbol in registrations.values(): + assert isinstance(getattr(owner, symbol), dw.DynWinRTType) +class DefaultHandler: + def __init__(self): self.calls = [] + def echo_alpha(self, value): + self.calls.append(("alpha", value.value)) + return type(value)(value.value + 1) + def echo_beta(self, value): + self.calls.append(("beta", value.other)) + return type(value)(value.other + 1) +class RequiredHandler: + def __init__(self): self.calls = [] + def required_echo_alpha(self, value): + self.calls.append(("alpha", value.value)) + return type(value)(value.value + 2) + def required_echo_beta(self, value): + self.calls.append(("beta", value.other)) + return type(value)(value.other + 2) +default, required = DefaultHandler(), RequiredHandler() +with dw.RoApartment(1), DefaultProjection.implement(default, interfaces=[(RequiredProjection, required)]) as implementation: + value = Wrapper._from_native(implementation.value._obj) + try: + assert value.echo_alpha(Alpha(17)) == Alpha(18) + assert value.required_echo_alpha(Alpha(17)) == Alpha(19) +{beta_runtime} + finally: + dw.release_projected(value) +assert default.calls == {expected_calls} +assert required.calls == {expected_calls} +for symbol in registrations.values(): + assert isinstance(getattr(owner, symbol), dw.DynWinRTType) +"#, + default_module = implementation_modules[0], + required_module = implementation_modules[1], + default_name = context.projected_name_for_interface(&default), + required_name = context.projected_name_for_interface(&required), + registrations = serde_json::to_string(®istrations).unwrap(), + expected_calls = if initial_collision { + "[('alpha', 17)]" + } else { + "[('alpha', 17), ('beta', 2**40)]" + }, + ), + ); + } + } + } +} + +#[test] +fn python_native_registration_activation_factory_reserves_only_when_emitted() { + for packaged in [true, false] { + let fixture = Fixture::new(); + let package = fixture.package(); + let kind = enumeration("Kinds", "_IActivationFactory"); + let mut owner = class( + "Audit", + "ActivationOwner", + vec![echo("EchoKind", kind.clone(), 6)], + 0x51931510, + ); + owner.has_default_constructor = true; + let identities = [ + class_identity(&owner), + owner.default_interface.as_ref().unwrap().type_identity(), + kind.type_identity(), + ]; + let context = python::PythonProjectionContext::new(identities.clone(), packaged).unwrap(); + let unrelated = python::PythonProjectionContext::new( + identities + .into_iter() + .chain(unused_registration_identities()), + packaged, + ) + .unwrap(); + let kind_module = context.implementation_module_for_type(&kind); + let inactive = python::generate_class(&context, &owner, &Default::default()); + let inactive_stub = python_stub::generate_class_stub(&context, &owner, &Default::default()); + assert_eq!( + inactive, + python::generate_class(&unrelated, &owner, &Default::default()) + ); + assert_eq!( + inactive_stub, + python_stub::generate_class_stub(&unrelated, &owner, &Default::default()) + ); + assert_eq!( + imported_symbol(&inactive, &kind_module, "_IActivationFactory"), + "_IActivationFactory" + ); + assert_eq!( + imported_symbol(&inactive_stub, &kind_module, "_IActivationFactory"), + "_IActivationFactory" + ); + registration_bindings(&inactive, &["IActivationOwner"]); + owner.constructors.push(ConstructorMeta { + kind: ConstructorKind::DefaultActivation, + factory_interface: None, + }); + let source = python::generate_class(&context, &owner, &Default::default()); + let stub = python_stub::generate_class_stub(&context, &owner, &Default::default()); + let registrations = + registration_bindings(&source, &["IActivationOwner", "IActivationFactory"]); + let kind_symbol = imported_symbol(&source, &kind_module, "_IActivationFactory"); + assert_ne!(registrations["IActivationFactory"], kind_symbol); + assert!( + source.contains("00000035-0000-0000-c000-000000000046"), + "{source}" + ); + let owner_module = context.implementation_module(&class_identity(&owner)); + module(&package, &owner_module, source, stub); + module( + &package, + &kind_module, + python::generate_enum(&context, &kind).unwrap(), + python_stub::generate_enum_stub(&context, &kind).unwrap(), + ); + support(&package, &[]); + typecheck( + &fixture.0, + &format!( + r#" +from typing import assert_type +from pyviews.{owner_module} import ActivationOwner +from pyviews.{kind_module} import _IActivationFactory as Kind +def check(value: ActivationOwner) -> None: + assert_type(value.echo_kind(Kind.Unknown), Kind) + assert_type(ActivationOwner(), ActivationOwner) +"# + ), + ); + runtime( + &fixture.0, + &format!( + r#" +import importlib +import dynwinrt as dw +from pyviews.{kind_module} import _IActivationFactory as Kind +owner = importlib.import_module("pyviews.{owner_module}") +for symbol in {registrations}.values(): + assert isinstance(getattr(owner, symbol), dw.DynWinRTType) +assert Kind.Unknown.value == 0 +"#, + registrations = serde_json::to_string(®istrations).unwrap() + ), + ); + } +} + +fn cross_role_metadata(path: &Path, enum_fields: bool) -> (InterfaceMeta, [TypeMeta; 3]) { + let mut file = writer::File::new("PythonCrossRoleSymbols"); + let mut fields = vec![("Value", Type::I32)]; + if enum_fields { + fields.extend([ + ("PackKind", Type::named("Kinds", "pack_url_value")), + ("TypeKind", Type::named("Kinds", "URLValue_TYPE")), + ]); + } + structure(&mut file, "Alpha", "URLValue", &fields); + for name in ["pack_url_value", "URLValue_TYPE"] { + let base = file.TypeRef("System", "Enum"); + file.TypeDef( + "Kinds", + name, + writer::TypeDefOrRef::TypeRef(base), + TypeAttributes::Public | TypeAttributes::Sealed | TypeAttributes::WindowsRuntime, + ); + file.Field( + "value__", + &Type::I32, + FieldAttributes::Public | FieldAttributes::SpecialName | FieldAttributes::RTSpecialName, + ); + let member = file.Field( + "Unknown", + &Type::named("Kinds", name), + FieldAttributes::Public + | FieldAttributes::Static + | FieldAttributes::Literal + | FieldAttributes::HasDefault, + ); + file.Constant(writer::HasConstant::Field(member), &Value::I32(0)); + } + interface(&mut file, "Audit", "IUse", 0x51931400); + for (name, typ) in [ + ("Echo", Type::named("Alpha", "URLValue")), + ("EchoPackKind", Type::named("Kinds", "pack_url_value")), + ("EchoTypeKind", Type::named("Kinds", "URLValue_TYPE")), + ] { + method( + &mut file, + name, + typ.clone(), + &[("value", typ, ParamAttributes::In)], + ); + } + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, file.into_stream()).unwrap(); + let interface = meta::parse_interfaces(path.to_str().unwrap(), "Audit") + .pop() + .unwrap(); + let types = std::array::from_fn(|index| interface.methods[index].return_type.clone().unwrap()); + (interface, types) +} + +fn cross_role_modules( + package: &Path, + context: &python::PythonProjectionContext, + types: &[TypeMeta; 3], +) { + write_structs(package, context, &types[..1]); + for enumeration in &types[1..] { + module( + package, + &context.implementation_module_for_type(enumeration), + python::generate_enum(context, enumeration).unwrap(), + python_stub::generate_enum_stub(context, enumeration).unwrap(), + ); + } +} + +#[test] +fn python_cross_role_imported_enums_do_not_shadow_struct_helpers() { + for packaged in [true, false] { + let fixture = Fixture::new(); + let package = fixture.package(); + let (interface, types) = + cross_role_metadata(&fixture.0.join("metadata").join("Input.winmd"), false); + let identities = types + .iter() + .map(TypeMeta::type_identity) + .chain([interface.type_identity()]) + .collect::>(); + let baseline = python::PythonProjectionContext::new(identities.clone(), packaged).unwrap(); + let context = python::PythonProjectionContext::new( + identities + .into_iter() + .chain([enumeration("Unrelated", "unpack_url_value").type_identity()]), + packaged, + ) + .unwrap(); + let owner_module = context.implementation_module_for_interface(&interface); + let struct_module = context.implementation_module_for_type(&types[0]); + let pack_kind_module = context.implementation_module_for_type(&types[1]); + let type_kind_module = context.implementation_module_for_type(&types[2]); + let source = python::generate_interface(&context, &interface); + let stub = python_stub::generate_interface_stub(&context, &interface); + assert_eq!( + source, + python::generate_interface(&baseline, &interface), + "a non-imported similarly named type must not change module symbols" + ); + assert_eq!( + stub, + python_stub::generate_interface_stub(&baseline, &interface) + ); + let pack_kind_alias = imported_symbol(&source, &pack_kind_module, "pack_url_value"); + let type_kind_alias = imported_symbol(&source, &type_kind_module, "URLValue_TYPE"); + if packaged { + assert_eq!( + imported_symbol(&source, &struct_module, "unpack_url_value"), + "unpack_url_value" + ); + } else { + assert!(source.contains("def unpack_url_value("), "{source}"); + } + module(&package, &owner_module, source, stub); + cross_role_modules(&package, &context, &types); + support( + &package, + if packaged { + std::slice::from_ref(&owner_module) + } else { + &[] + }, + ); + let payload_module = if packaged { + &struct_module + } else { + &owner_module + }; + let imports = format!( + "from pyviews.{owner_module} import IUse\n\ + from pyviews.{payload_module} import URLValue\n\ + from pyviews.{pack_kind_module} import pack_url_value as PackKind\n\ + from pyviews.{type_kind_module} import URLValue_TYPE as TypeKind\n", + ); + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +def check(value: IUse) -> None: + assert_type(value.echo(URLValue(17)), URLValue) + assert_type(value.echo_pack_kind(PackKind.Unknown), PackKind) + assert_type(value.echo_type_kind(TypeKind.Unknown), TypeKind) +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + r#"{imports} +def reject(value: IUse) -> None: + value.echo(PackKind.Unknown) + value.echo_pack_kind(URLValue(17)) + wrong: TypeKind = value.echo_pack_kind(PackKind.Unknown) +"# + ), + &["[arg-type]", "[arg-type]", "[assignment]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import typing +import dynwinrt as dw +from pyviews.{struct_module} import URLValue as Canonical, pack_url_value, unpack_url_value, URLValue_TYPE +assert isinstance(URLValue_TYPE, dw.DynWinRTType) +assert unpack_url_value(pack_url_value(Canonical(17)).to_value()) == Canonical(17) +assert typing.get_type_hints(pack_url_value)["v"] is Canonical +assert typing.get_type_hints(unpack_url_value)["return"] is Canonical +foreign = {{"{pack_kind_alias}": PackKind, "{type_kind_alias}": TypeKind}} +assert typing.get_type_hints(IUse.echo)["return"] is URLValue +assert typing.get_type_hints(IUse.echo_pack_kind, localns=foreign)["return"] is PackKind +assert typing.get_type_hints(IUse.echo_type_kind, localns=foreign)["return"] is TypeKind +class Handler: + def echo(self, value): return value + def echo_pack_kind(self, value): return value + def echo_type_kind(self, value): return value +with dw.RoApartment(1), IUse.implement(Handler()) as implementation: + assert implementation.value.echo(URLValue(17)) == URLValue(17) + assert implementation.value.echo_pack_kind(PackKind.Unknown) is PackKind.Unknown + assert implementation.value.echo_type_kind(TypeKind.Unknown) is TypeKind.Unknown +"# + ), + ); + } +} + +#[test] +fn python_cross_role_class_owners_keep_self_bindings_and_qualified_helpers() { + for packaged in [true, false] { + for (index, name) in ["pack_url_value", "URLValue_TYPE"].into_iter().enumerate() { + let fixture = Fixture::new(); + let package = fixture.package(); + let (_, types) = + cross_role_metadata(&fixture.0.join("metadata").join("Input.winmd"), false); + let owner = class( + "Owners", + name, + vec![ + echo("EchoSelf", class_type("Owners", name), 6), + echo("EchoPayload", types[0].clone(), 7), + MethodMeta { + name: "GetSelf".into(), + raw_name: "GetSelf".into(), + vtable_index: 8, + return_type: Some(class_type("Owners", name)), + ..Default::default() + }, + ], + 0x51931410 + index as u32, + ); + let identities = [ + class_identity(&owner), + types[0].type_identity(), + owner.default_interface.as_ref().unwrap().type_identity(), + ]; + let baseline = + python::PythonProjectionContext::new(identities.clone(), packaged).unwrap(); + let context = python::PythonProjectionContext::new( + identities + .into_iter() + .chain([enumeration("Unrelated", "unpack_url_value").type_identity()]), + packaged, + ) + .unwrap(); + let owner_module = context.implementation_module(&class_identity(&owner)); + let struct_module = context.implementation_module_for_type(&types[0]); + let source = python::generate_class(&context, &owner, &Default::default()); + let stub = python_stub::generate_class_stub(&context, &owner, &Default::default()); + assert_eq!( + source, + python::generate_class(&baseline, &owner, &Default::default()) + ); + assert_eq!( + stub, + python_stub::generate_class_stub(&baseline, &owner, &Default::default()) + ); + assert!(source.contains(&format!("class {name}:")), "{source}"); + module(&package, &owner_module, source, stub); + write_structs(&package, &context, &types[..1]); + support(&package, &[]); + let payload_module = if packaged { + &struct_module + } else { + &owner_module + }; + let imports = format!( + "from pyviews.{owner_module} import {name} as Owner\n\ + from pyviews.{payload_module} import URLValue\n", + ); + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +def check(value: Owner) -> None: + assert_type(value.echo_self(value), Owner | None) + assert_type(value.get_self(), Owner | None) + assert_type(value.echo_payload(URLValue(17)), URLValue) +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + r#"{imports} +def reject(value: Owner, payload: URLValue) -> None: + value.echo_self(payload) + value.echo_payload(value) +"# + ), + &["[arg-type]", "[arg-type]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import typing +from pyviews.{struct_module} import URLValue as Canonical, pack_url_value, unpack_url_value +assert isinstance(Owner, type) +assert Owner.__name__ == "{name}" +assert typing.get_type_hints(Owner.get_self)["return"] == Owner | None +assert typing.get_type_hints(Owner.echo_payload)["return"] is URLValue +assert typing.get_type_hints(pack_url_value)["v"] is Canonical +assert typing.get_type_hints(unpack_url_value)["return"] is Canonical +assert unpack_url_value(pack_url_value(Canonical(17)).to_value()) == Canonical(17) +"# + ), + ); + } + } +} + +#[test] +fn python_cross_role_owning_struct_preserves_public_helpers_and_aliases_field_enums() { + for packaged in [true, false] { + let fixture = Fixture::new(); + let package = fixture.package(); + let (interface, types) = + cross_role_metadata(&fixture.0.join("metadata").join("Input.winmd"), true); + let identities = types + .iter() + .map(TypeMeta::type_identity) + .chain([interface.type_identity()]) + .collect::>(); + let baseline = python::PythonProjectionContext::new(identities.clone(), packaged).unwrap(); + let context = python::PythonProjectionContext::new( + identities + .into_iter() + .chain([enumeration("Unrelated", "unpack_url_value").type_identity()]), + packaged, + ) + .unwrap(); + let struct_module = context.implementation_module_for_type(&types[0]); + let pack_kind_module = context.implementation_module_for_type(&types[1]); + let type_kind_module = context.implementation_module_for_type(&types[2]); + let source = python::generate_struct(&context, &types[0]).unwrap(); + let stub = python_stub::generate_struct_stub(&context, &types[0]).unwrap(); + assert_eq!( + source, + python::generate_struct(&baseline, &types[0]).unwrap() + ); + assert_eq!( + stub, + python_stub::generate_struct_stub(&baseline, &types[0]).unwrap() + ); + for text in [&source, &stub] { + assert!( + text.contains("def pack_url_value(") && text.contains("def unpack_url_value("), + "{text}" + ); + assert_ne!( + imported_symbol(text, &pack_kind_module, "pack_url_value"), + "pack_url_value", + "the owning struct's public pack helper must win over a foreign field type" + ); + assert_ne!( + imported_symbol(text, &type_kind_module, "URLValue_TYPE"), + "URLValue_TYPE", + "the owning struct's public type constant must win over a foreign field type" + ); + } + let pack_kind_alias = imported_symbol(&source, &pack_kind_module, "pack_url_value"); + let type_kind_alias = imported_symbol(&source, &type_kind_module, "URLValue_TYPE"); + cross_role_modules(&package, &context, &types); + support(&package, &[]); + let imports = format!( + "from pyviews.{struct_module} import URLValue, pack_url_value, unpack_url_value, URLValue_TYPE\n\ + from pyviews.{pack_kind_module} import pack_url_value as PackKind\n\ + from pyviews.{type_kind_module} import URLValue_TYPE as TypeKind\n", + ); + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +from dynwinrt import DynWinRTType +assert_type(URLValue_TYPE, DynWinRTType) +assert_type(URLValue().pack_kind, PackKind) +assert_type(URLValue().type_kind, TypeKind) +assert_type(unpack_url_value(pack_url_value(URLValue()).to_value()), URLValue) +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + r#"{imports} +def reject(value: URLValue) -> None: + pack_url_value(PackKind.Unknown) + value.pack_kind = TypeKind.Unknown + value.type_kind = PackKind.Unknown +"# + ), + &["[arg-type]", "[assignment]", "[assignment]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import typing +import dynwinrt as dw +foreign = {{"{pack_kind_alias}": PackKind, "{type_kind_alias}": TypeKind}} +hints = typing.get_type_hints(URLValue.__init__, localns=foreign) +assert hints["pack_kind"] is PackKind +assert hints["type_kind"] is TypeKind +assert typing.get_type_hints(pack_url_value)["v"] is URLValue +assert typing.get_type_hints(unpack_url_value)["return"] is URLValue +assert isinstance(URLValue_TYPE, dw.DynWinRTType) +default = URLValue() +assert type(default.pack_kind) is PackKind +assert type(default.type_kind) is TypeKind +value = URLValue(17, PackKind.Unknown, TypeKind.Unknown) +result = unpack_url_value(pack_url_value(value).to_value()) +assert result == value +assert type(result.pack_kind) is PackKind +assert type(result.type_kind) is TypeKind +"# + ), + ); + } +} + +#[test] +fn python_normalized_struct_helpers_round_trip_nested_fields_arrays_and_delegates() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.package(); + let winmd = fixture.0.join("metadata").join("Input.winmd"); + metadata(&winmd); + let interface = helper_interface(&winmd); + let structures = structures(&interface); + let callback = interface + .implementation_metadata + .delegates + .iter() + .find(|delegate| delegate.typ.type_identity().definition_name() == Some("PairCallback")) + .expect("metadata must retain the callback contract"); + let context = python::PythonProjectionContext::new( + structures.iter().map(TypeMeta::type_identity).chain([ + interface.type_identity(), + callback + .typ + .type_identity() + .with_kind(TypeIdentityKind::Delegate), + ]), + packaged, + ) + .unwrap(); + let callback_meta = InterfaceMeta { + namespace: "Audit".into(), + name: "PairCallback".into(), + iid: match &callback.typ { + TypeMeta::Delegate { iid, .. } | TypeMeta::Interface { iid, .. } => iid.clone(), + _ => unreachable!(), + }, + methods: vec![ + MethodMeta { + name: ".ctor".into(), + ..Default::default() + }, + callback.invoke.clone(), + ], + ..Default::default() + }; + for iface in [&interface, &callback_meta] { + module( + &package, + &context.implementation_module_for_interface(iface), + python::generate_interface(&context, iface), + python_stub::generate_interface_stub(&context, iface), + ); + } + write_structs(&package, &context, &structures); + let owner_module = context.implementation_module_for_interface(&interface); + let source = fs::read_to_string(package.join(format!("{owner_module}.py"))).unwrap(); + if packaged { + for declaration in ["_pack_url_value", "_unpack_url_value"] { + let alpha = imported_symbol( + &source, + &context.implementation_module_for_type(&structures[0]), + declaration, + ); + let beta = imported_symbol( + &source, + &context.implementation_module_for_type(&structures[1]), + declaration, + ); + assert_ne!( + alpha, beta, + "different canonical structs must not bind the same helper" + ); + } + } else { + let functions = source + .lines() + .filter_map(|line| line.strip_prefix("def ")) + .filter_map(|line| line.split_once('(').map(|(name, _)| name)) + .collect::>(); + assert_eq!( + functions.len(), + functions.iter().collect::>().len(), + "inline normalized helpers must not overwrite each other:\n{source}" + ); + } + support( + &package, + if packaged { + std::slice::from_ref(&owner_module) + } else { + &[] + }, + ); + let helper_records = python::implementation_helper_records(&context, &interface); + let helper_name = |key| { + helper_records + .iter() + .find(|record| record.key == key) + .unwrap() + .name + .clone() + }; + let alpha_module = if packaged { + context.implementation_module_for_type(&structures[0]) + } else { + owner_module.clone() + }; + let beta_module = if packaged { + context.implementation_module_for_type(&structures[1]) + } else { + owner_module.clone() + }; + let pair_module = if packaged { + context.implementation_module_for_type(&structures[2]) + } else { + owner_module.clone() + }; + let imports = format!( + "from pyviews.{owner_module} import IHelpers, {handlers} as Handlers, {callback} as Callback, {split} as SplitResult\n\ + from pyviews.{alpha_module} import URLValue\n\ + from pyviews.{beta_module} import UrlValue\n\ + from pyviews.{pair_module} import NormalizedPair\n", + handlers = helper_name("handlers"), + callback = helper_name("delegate:0"), + split = helper_name(&format!( + "method-result:{}", + interface + .methods + .iter() + .find(|method| method.name == "Split") + .unwrap() + .vtable_index + )), + ); + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +class Handler: + def echo_alpha(self, value: URLValue) -> URLValue: return value + def echo_beta(self, value: UrlValue) -> UrlValue: return value + def echo_pair(self, value: NormalizedPair) -> NormalizedPair: return value + def echo_array(self, value: list[URLValue]) -> list[URLValue]: return value + def split(self) -> SplitResult: return {{"second": UrlValue(2**40), "result": URLValue(17)}} + def use_callback(self, callback: Callback | None) -> NormalizedPair: + assert callback is not None + callback(URLValue(17), UrlValue(2**40)) + return NormalizedPair(URLValue(17), UrlValue(2**40)) +handlers: Handlers = Handler() +assert_type(NormalizedPair().first, URLValue) +assert_type(NormalizedPair().second, UrlValue) +def check(value: IHelpers) -> None: + assert_type(value.echo_alpha(URLValue()), URLValue) + assert_type(value.echo_beta(UrlValue()), UrlValue) + assert_type(value.echo_array([URLValue()]), list[URLValue]) + assert_type(value.echo_pair(NormalizedPair()).second, UrlValue) +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + "{imports}\ndef reject_wrong_struct(value: IHelpers) -> None:\n value.echo_alpha(UrlValue())\n" + ), + &["[arg-type]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import dynwinrt as dw +from pyviews.{alpha_standalone} import URLValue as Alpha, pack_url_value as pack_alpha, unpack_url_value as unpack_alpha +from pyviews.{beta_standalone} import UrlValue as Beta, pack_url_value as pack_beta, unpack_url_value as unpack_beta +from pyviews.{pair_standalone} import NormalizedPair as Pair, pack_normalized_pair, unpack_normalized_pair +assert unpack_alpha(pack_alpha(Alpha(17)).to_value()) == Alpha(17) +assert unpack_beta(pack_beta(Beta(2**40)).to_value()) == Beta(2**40) +pair = Pair(Alpha(17), Beta(2**40)) +assert unpack_normalized_pair(pack_normalized_pair(pair).to_value()) == pair +assert type(Pair().first) is Alpha +assert type(Pair().second) is Beta +assert type(NormalizedPair().first) is URLValue +assert type(NormalizedPair().second) is UrlValue +class Handler: + def echo_alpha(self, value): return value + def echo_beta(self, value): return value + def echo_pair(self, value): return value + def echo_array(self, value): return value + def split(self): return {{"second": UrlValue(2**40), "result": URLValue(17)}} + def use_callback(self, callback): + assert callback is not None + callback(URLValue(17), UrlValue(2**40)) + return NormalizedPair(URLValue(17), UrlValue(2**40)) +with dw.RoApartment(1), IHelpers.implement(Handler()) as implementation: + view = implementation.value + assert view.echo_alpha(URLValue(17)) == URLValue(17) + assert view.echo_beta(UrlValue(2**40)) == UrlValue(2**40) + assert view.echo_pair(NormalizedPair(URLValue(17), UrlValue(2**40))) == NormalizedPair(URLValue(17), UrlValue(2**40)) + assert view.echo_array([URLValue(17), URLValue(-3)]) == [URLValue(17), URLValue(-3)] + result = view.split() + assert result == (UrlValue(2**40), URLValue(17)), repr(result) + # Forward delegates receive native values; use the public struct projections. + seen = [] + callback_result = view.use_callback(lambda first, second: seen.append((unpack_alpha(first).value, unpack_beta(second).other))) + assert seen == [(17, 2**40)], seen + assert callback_result == NormalizedPair(URLValue(17), UrlValue(2**40)), repr(callback_result) +"#, + alpha_standalone = context.implementation_module_for_type(&structures[0]), + beta_standalone = context.implementation_module_for_type(&structures[1]), + pair_standalone = context.implementation_module_for_type(&structures[2]), + ), + ); + assert!( + source.contains("Alpha.URLValue") && source.contains("Beta.UrlValue"), + "{source}" + ); + } +} + +#[test] +fn python_enum_closed_generic_collision_preserves_projection_and_native_identity() { + for packaged in [false, true] { + let fixture = Fixture::new(); + let package = fixture.package(); + let winmd = fixture.0.join("metadata").join("Input.winmd"); + metadata(&winmd); + let enumeration = meta::parse_enums(winmd.to_str().unwrap(), "Enums") + .pop() + .unwrap(); + let local = meta::parse_interfaces(winmd.to_str().unwrap(), "Enums") + .into_iter() + .find(|interface| interface.name == "IUse") + .unwrap(); + let foreign = meta::parse_interfaces(winmd.to_str().unwrap(), "Consumers") + .pop() + .unwrap(); + let generic_type = local.methods[0].return_type.clone().unwrap(); + let TypeMeta::Parameterized { + piid, args, name, .. + } = &generic_type + else { + panic!("closed generic return") + }; + let generic = InterfaceMeta { + namespace: "Enums".into(), + name: "IBucket_String".into(), + generic_name: Some(name.clone()), + generic_piid: Some(piid.clone()), + generic_args: args.clone(), + methods: vec![MethodMeta { + name: "Ping".into(), + raw_name: "Ping".into(), + vtable_index: 6, + ..Default::default() + }], + ..Default::default() + }; + assert_ne!(enumeration.type_identity(), generic.type_identity()); + let context = python::PythonProjectionContext::new( + [ + enumeration.type_identity(), + local.type_identity(), + foreign.type_identity(), + generic.type_identity(), + ], + packaged, + ) + .unwrap(); + let enum_name = context.projected_name_for_type(&enumeration); + let generic_name = context.projected_name_for_interface(&generic); + assert_ne!( + enum_name, "IBucket_String", + "named enum must yield to the closed generic declaration" + ); + assert_ne!(enum_name, generic_name); + let enum_module = context.implementation_module_for_type(&enumeration); + for source in [ + python::generate_enum(&context, &enumeration).unwrap(), + python_stub::generate_enum_stub(&context, &enumeration).unwrap(), + ] { + assert!( + source.contains(&format!("class {enum_name}(IntEnum):")), + "{source}" + ); + } + module( + &package, + &enum_module, + python::generate_enum(&context, &enumeration).unwrap(), + python_stub::generate_enum_stub(&context, &enumeration).unwrap(), + ); + for interface in [&local, &foreign, &generic] { + let source = python::generate_interface(&context, interface); + let stub = python_stub::generate_interface_stub(&context, interface); + if interface.generic_piid.is_none() { + for text in [&source, &stub] { + assert!( + text.contains(&format!("from .{enum_module} import {enum_name}")), + "{text}" + ); + } + assert!( + source.contains("DynWinRTType.enum_type('Enums.IBucket_String'"), + "{source}" + ); + assert!( + !source.contains(&format!("DynWinRTType.enum_type('Enums.{enum_name}'")), + "{source}" + ); + assert!( + !source.contains(&format!("'{enum_module}', 'IBucket_String'")), + "runtime lookups must use the projected enum declaration, including arrays:\n{source}", + ); + } + module( + &package, + &context.implementation_module_for_interface(interface), + source, + stub, + ); + } + let owners = [&local, &foreign] + .map(|interface| context.implementation_module_for_interface(interface)); + support(&package, if packaged { &owners } else { &[] }); + let interfaces = [local.clone(), foreign.clone(), generic.clone()]; + let reversed = interfaces.iter().rev().cloned().collect::>(); + let enums = std::slice::from_ref(&enumeration); + let index = python::generate_index(&context, &[], &interfaces, enums); + let index_stub = python_stub::generate_index_stub(&context, &[], &interfaces, enums); + assert_eq!( + index, + python::generate_index(&context, &[], &reversed, enums) + ); + assert_eq!( + index_stub, + python_stub::generate_index_stub(&context, &[], &reversed, enums) + ); + for text in [&index, &index_stub] { + assert_eq!(imported_symbol(text, &enum_module, &enum_name), enum_name); + assert_eq!( + imported_symbol( + text, + &context.implementation_module_for_interface(&generic), + &generic_name + ), + generic_name, + "the named enum must not suppress its same-spelling closed generic in a direct index", + ); + } + for (text, reordered) in [ + ( + python::generate_public_index(&context, &[], &interfaces, enums), + python::generate_public_index(&context, &[], &reversed, enums), + ), + ( + python_stub::generate_public_index_stub(&context, &[], &interfaces, enums), + python_stub::generate_public_index_stub(&context, &[], &reversed, enums), + ), + ] { + assert_eq!(text, reordered); + for (identity, name) in [ + (enumeration.type_identity(), &enum_name), + (generic.type_identity(), &generic_name), + ] { + assert_eq!( + imported_symbol(&text, &context.public_qualified_module(&identity), name), + *name, + "public indexes must retain both canonical identities", + ); + } + } + module(&package, "__init__", index, index_stub); + let imports = format!( + "from pyviews.{enum_module} import {enum_name} as Kind\n\ + from pyviews.{generic_module} import {generic_name} as Bucket\n\ + from pyviews.{local_module} import IUse\n\ + from pyviews.{foreign_module} import IForeign\n\ + from pyviews import {enum_name} as RootKind, {generic_name} as RootBucket\n", + generic_module = context.implementation_module_for_interface(&generic), + local_module = owners[0], + foreign_module = owners[1], + ); + typecheck( + &fixture.0, + &format!( + r#"{imports} +from typing import assert_type +assert_type(RootKind(0), Kind) +def check(local: IUse, foreign: IForeign) -> None: + assert_type(local.get_bucket(), Bucket | None) + assert_type(local.get_bucket(), RootBucket | None) + assert_type(foreign.get_bucket(), Bucket | None) + assert_type(local.echo_kind(Kind.Unknown), Kind) + assert_type(foreign.echo_kind(Kind.Unknown), Kind) + assert_type(local.echo_kinds([Kind.Unknown]), list[Kind]) +"# + ), + ); + reject_consumer( + &fixture.0, + &format!( + "{imports}\ndef reject_wrong_enum(value: IUse) -> None:\n value.echo_kind(0)\n" + ), + &["[arg-type]"], + ); + runtime( + &fixture.0, + &format!( + r#"{imports} +import dynwinrt as dw +from enum import IntEnum +assert RootKind is Kind +assert RootBucket is Bucket +assert issubclass(Kind, IntEnum) +assert not issubclass(Bucket, IntEnum) +class Handler: + def get_bucket(self): return None + def echo_kind(self, value): + assert type(value) is Kind + return value + def echo_kinds(self, value): return value +with dw.RoApartment(1): + for projection in (IUse, IForeign): + with projection.implement(Handler()) as implementation: + assert implementation.value.echo_kind(Kind.Unknown) is Kind.Unknown + assert implementation.value.get_bucket() is None + with IUse.implement(Handler()) as implementation: + kinds = implementation.value.echo_kinds([Kind.Unknown]) + assert kinds == [Kind.Unknown] + assert all(type(value) is Kind for value in kinds) +"# + ), + ); + } +} + +fn generate(winmd: &Path, package: &Path, selected: &str) { + success( + Command::new(env!("CARGO_BIN_EXE_dynwinrt-codegen")) + .args(["generate", "--winmd"]) + .arg(winmd) + .args(["--output"]) + .arg(package) + .args(["--lang", "py", "--class-name", selected]) + .output() + .unwrap(), + ); +} + +fn python_files(directory: &Path) -> BTreeMap> { + fn visit(root: &Path, directory: &Path, files: &mut BTreeMap>) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + visit(root, &path, files); + } else if matches!( + path.extension().and_then(|extension| extension.to_str()), + Some("py" | "pyi") + ) { + files.insert( + path.strip_prefix(root).unwrap().to_path_buf(), + fs::read(path).unwrap(), + ); + } + } + } + let mut files = BTreeMap::new(); + visit(directory, directory, &mut files); + files +} + +#[test] +fn python_symbol_collisions_incremental_package_matches_clean_generation() { + let fixture = Fixture::new(); + let winmd = fixture.0.join("metadata").join("Input.winmd"); + metadata(&winmd); + let incremental = fixture.0.join("incremental").join("pyviews"); + let clean = fixture.0.join("clean").join("pyviews"); + generate(&winmd, &incremental, "Audit.IAlpha,Enums.IUse"); + let alpha_before = fs::read(incremental.join("alpha__url_value.py")).unwrap(); + generate(&winmd, &incremental, "Audit.IHelpers,Consumers.IForeign"); + generate( + &winmd, + &clean, + "Audit.IAlpha,Audit.IHelpers,Enums.IUse,Consumers.IForeign", + ); + assert_eq!( + alpha_before, + fs::read(incremental.join("alpha__url_value.py")).unwrap() + ); + let incremental_files = python_files(&incremental); + let clean_files = python_files(&clean); + assert_eq!( + incremental_files.keys().collect::>(), + clean_files.keys().collect::>() + ); + for (name, expected) in clean_files { + assert_eq!( + incremental_files[&name], + expected, + "incremental mismatch: {}", + name.display() + ); + } + let consumer = r#" +from typing import assert_type +from pyviews.alpha.url_value import URLValue, pack_url_value, unpack_url_value +from pyviews.beta.url_value import UrlValue +from pyviews.containers.normalized_pair import NormalizedPair +from pyviews.audit.i_helpers import IHelpers +assert_type(unpack_url_value(pack_url_value(URLValue(17)).to_value()), URLValue) +assert_type(NormalizedPair().first, URLValue) +assert_type(NormalizedPair().second, UrlValue) +def check(value: IHelpers) -> None: + assert_type(value.echo_alpha(URLValue()), URLValue) + assert_type(value.echo_beta(UrlValue()), UrlValue) +"#; + typecheck(incremental.parent().unwrap(), consumer); + typecheck(clean.parent().unwrap(), consumer); + runtime( + incremental.parent().unwrap(), + r#" +from pyviews.alpha.url_value import URLValue, pack_url_value as pack_alpha, unpack_url_value as unpack_alpha +from pyviews.beta.url_value import UrlValue, pack_url_value as pack_beta, unpack_url_value as unpack_beta +from pyviews.containers.normalized_pair import NormalizedPair, pack_normalized_pair, unpack_normalized_pair +assert unpack_alpha(pack_alpha(URLValue(17)).to_value()) == URLValue(17) +assert unpack_beta(pack_beta(UrlValue(2**40)).to_value()) == UrlValue(2**40) +pair = NormalizedPair(URLValue(17), UrlValue(2**40)) +assert unpack_normalized_pair(pack_normalized_pair(pair).to_value()) == pair +"#, + ); +}