diff --git a/docs/status/PYTHON_CHECKLIST.md b/docs/status/PYTHON_CHECKLIST.md index 15963f78..62d44378 100644 --- a/docs/status/PYTHON_CHECKLIST.md +++ b/docs/status/PYTHON_CHECKLIST.md @@ -42,6 +42,14 @@ of a dynamic projection. - [x] Preserve `Uri` implementation and `.pyi` snapshots. - [x] Organize output by WinRT namespace instead of one flat short-name namespace. +- [x] Derive Python symbols, implementation modules, facade modules, and stable + path hashes from a namespace- and kind-preserving semantic type identity, + including recursively closed generic arguments. +- [x] Keep same-short-name types available through their namespace facades, + omit ambiguous root exports, and use deterministic qualified aliases in + consumer modules instead of selecting a short-name ABI implicitly. +- [x] Pass an immutable Python projection context through generation and + rendering instead of installing thread-local module-layout state. - [x] Detect and reject namespace/type filename collisions. - [x] Add stage/swap generation and remove stale Python output. - [x] Emit a consumable Python package manifest with an exact runtime diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index ac5aad69..e2026415 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -1582,7 +1582,9 @@ def block_on_sta(): from typing import get_type_hints module = importlib.import_module( - implementation_module_name(pkg_name, namespace, cls.__name__) + implementation_module_name( + pkg_name, namespace, 'Direct3DSurfaceDescription' + ) ) descriptor_type = getattr(module, 'Direct3DSurfaceDescription') nested_type = getattr(module, 'Direct3DMultisampleDescription') diff --git a/tools/dynwinrt-codegen/src/codegen/common.rs b/tools/dynwinrt-codegen/src/codegen/common.rs index ca129286..de6677cd 100644 --- a/tools/dynwinrt-codegen/src/codegen/common.rs +++ b/tools/dynwinrt-codegen/src/codegen/common.rs @@ -608,34 +608,32 @@ mod tests { #[test] fn py_convert_return_basic() { - let known = HashSet::new(); + let context = PythonProjectionContext::default(); assert_eq!( - py_convert_return("r", Some(&TypeMeta::String), false, &known), + py_convert_return("r", Some(&TypeMeta::String), false, &context), "r.to_string()" ); assert_eq!( - py_convert_return("r", Some(&TypeMeta::I32), false, &known), + py_convert_return("r", Some(&TypeMeta::I32), false, &context), "r.to_number()" ); assert_eq!( - py_convert_return("r", Some(&TypeMeta::U32), false, &known), + py_convert_return("r", Some(&TypeMeta::U32), false, &context), "r.to_u32()" ); assert_eq!( - py_convert_return("r", Some(&TypeMeta::U64), false, &known), + py_convert_return("r", Some(&TypeMeta::U64), false, &context), "r.to_u64()" ); assert_eq!( - py_convert_return("r", Some(&TypeMeta::Bool), false, &known), + py_convert_return("r", Some(&TypeMeta::Bool), false, &context), "r.to_bool()" ); - assert_eq!(py_convert_return("r", None, false, &known), "r"); + assert_eq!(py_convert_return("r", None, false, &context), "r"); } #[test] fn py_convert_return_with_known_class() { - let mut known = HashSet::new(); - known.insert("Uri".to_string()); let rt = TypeMeta::RuntimeClass { namespace: "Windows.Foundation".into(), name: "Uri".into(), @@ -645,12 +643,13 @@ mod tests { iid: "abc".into(), })), }; + let context = PythonProjectionContext::packaged([rt.type_identity()]).unwrap(); assert_eq!( - py_convert_return("r", Some(&rt), false, &known), + py_convert_return("r", Some(&rt), false, &context), "(lambda value: None if value.is_null() else _dynwinrt_symbol('windows__foundation__uri', 'Uri')._from_native(value))(r)" ); assert_eq!( - py_convert_array_return("r", &rt, &known), + py_convert_array_return("r", &rt, &context), "_dynwinrt_wrap_values('windows__foundation__uri', 'Uri', r.to_values())" ); } @@ -667,13 +666,13 @@ mod tests { deprecated: None, }; assert_eq!( - py_convert_return("r", Some(&en), false, &HashSet::new()), + py_convert_return("r", Some(&en), false, &PythonProjectionContext::default()), "r.to_number()" ); - let known = HashSet::from(["DayOfWeek".to_string()]); + let context = PythonProjectionContext::packaged([en.type_identity()]).unwrap(); assert_eq!( - py_convert_return("r", Some(&en), false, &known), + py_convert_return("r", Some(&en), false, &context), "_dynwinrt_enum('windows__globalization__day_of_week', 'DayOfWeek', r.to_number())" ); } @@ -718,16 +717,23 @@ mod tests { #[test] fn py_struct_field_getter_expressions() { + let context = PythonProjectionContext::default(); assert_eq!( - py_struct_field_getter(&TypeMeta::Bool, 0), + py_struct_field_getter(&context, &TypeMeta::Bool, 0), "s.get_u8(0) != 0" ); - assert_eq!(py_struct_field_getter(&TypeMeta::I32, 2), "s.get_i32(2)"); assert_eq!( - py_struct_field_getter(&TypeMeta::String, 1), + py_struct_field_getter(&context, &TypeMeta::I32, 2), + "s.get_i32(2)" + ); + assert_eq!( + py_struct_field_getter(&context, &TypeMeta::String, 1), "s.get_hstring(1)" ); - assert_eq!(py_struct_field_getter(&TypeMeta::F64, 3), "s.get_f64(3)"); + assert_eq!( + py_struct_field_getter(&context, &TypeMeta::F64, 3), + "s.get_f64(3)" + ); } #[test] @@ -748,9 +754,10 @@ mod tests { #[test] fn py_struct_field_type_mappings() { - assert_eq!(py_struct_field_type(&TypeMeta::Bool), "bool"); - assert_eq!(py_struct_field_type(&TypeMeta::String), "str"); - assert_eq!(py_struct_field_type(&TypeMeta::I32), "int"); - assert_eq!(py_struct_field_type(&TypeMeta::F64), "float"); + let context = PythonProjectionContext::default(); + assert_eq!(py_struct_field_type(&context, &TypeMeta::Bool), "bool"); + assert_eq!(py_struct_field_type(&context, &TypeMeta::String), "str"); + assert_eq!(py_struct_field_type(&context, &TypeMeta::I32), "int"); + assert_eq!(py_struct_field_type(&context, &TypeMeta::F64), "float"); } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs index a4a7c3c5..aae58a1c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs @@ -1,8 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use crate::meta::{ClassMeta, InterfaceMeta, make_parameterized_name}; -use crate::types::TypeMeta; +use crate::meta::{ClassMeta, InterfaceMeta, WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE}; +use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; pub(crate) const IITERABLE_PIID: &str = "faa585ea-6214-4217-afda-7f46de5869b3"; pub(crate) const IITERATOR_PIID: &str = "6a79e863-4300-459a-9966-cbb660963ee1"; @@ -95,18 +95,35 @@ pub(crate) fn abc_name(kind: CollectionKind) -> Option<&'static str> { } } -pub(crate) fn map_iterable_name(args: &[TypeMeta]) -> Option { +pub(crate) fn map_iterable_identity(args: &[TypeMeta]) -> Option { if args.len() != 2 { return None; } - let pair = make_parameterized_name("IKeyValuePair", args); - Some(format!("IIterable_{pair}")) + let pair = TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IKeyValuePair", + args.iter().map(TypeMeta::type_identity), + ); + Some(TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IIterable", + [pair], + )) } -pub(crate) fn observable_vector_name(iface: &InterfaceMeta) -> Option { +pub(crate) fn observable_vector_identity(iface: &InterfaceMeta) -> Option { (iface.generic_piid.as_deref() == Some(IOBSERVABLE_VECTOR_PIID) && iface.generic_args.len() == 1) - .then(|| iface.name.replacen("IObservableVector", "IVector", 1)) + .then(|| { + TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IVector", + iface.generic_args.iter().map(TypeMeta::type_identity), + ) + }) } pub(crate) fn is_mapping_input(kind: CollectionKind, args: &[TypeMeta]) -> bool { 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 517495f4..b8e8e56d 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/class.rs @@ -8,9 +8,10 @@ use super::structs::{generate_struct_helpers, generate_struct_imports}; use super::*; use crate::codegen::winrt::extensions::winui::{self, WinUiAbiType}; use crate::codegen::winrt::python::collections::{ - CollectionKind, class_interface, interface_kind, map_iterable_name, runtime_mixin, + CollectionKind, class_interface, interface_kind, map_iterable_identity, runtime_mixin, }; use crate::meta::{ConstructorKind, ParamMeta}; +use crate::types::{TypeIdentity, TypeIdentityKind}; fn project_winui_abi_types(types: &[WinUiAbiType]) -> String { types @@ -22,17 +23,21 @@ fn project_winui_abi_types(types: &[WinUiAbiType]) -> String { .join(", ") } +fn interface_symbol(context: &PythonProjectionContext, interface: &InterfaceMeta) -> String { + context.reference_name(&interface.type_identity()) +} + /// Generate a Python file for a single RuntimeClass. pub fn generate_class( + context: &PythonProjectionContext, class: &ClassMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, shared_iids: &HashSet, ) -> String { let used_structs = collect_used_structs_from_class(class); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); - let winui_bootstrap = winui::resolve_application_bootstrap(class, known_types); + let known_full_names = context.known_full_names(); + let winui_bootstrap = winui::resolve_application_bootstrap(class, &known_full_names); let has_public_composition = class .constructors .iter() @@ -41,7 +46,9 @@ pub fn generate_class( class .default_interface .as_ref() - .is_some_and(|default_iface| default_iface.name == collection_iface.name) + .is_some_and(|default_iface| { + default_iface.type_identity() == collection_iface.type_identity() + }) }); let collection_obj_expr = if collection_uses_default { "self._obj" @@ -86,8 +93,8 @@ pub fn generate_class( ) { out.push_str(ASYNC_IMPORT_LINE); } - if python_module_layout_installed() { - out.push_str(&generate_struct_imports(&used_structs)); + if context.is_packaged() { + out.push_str(&generate_struct_imports(context, &used_structs)); } if has_ireference_input( class @@ -107,31 +114,41 @@ pub fn generate_class( for iface in &all_ifaces { delegate_names.extend(super::super::collect_referenced_delegate_names( &iface.methods, - delegate_type_names, + context, )); runtime_delegate_names.extend(super::super::collect_runtime_delegate_names( &iface.methods, - delegate_type_names, + context, )); } // Collection generics import (skip delegates) let mut imported_names: HashSet = HashSet::new(); - let collection_names = collect_used_generics_from_class(class); - for cname in &collection_names { - if !delegate_names.contains(cname) { - let module = to_snake_case_filename(cname); - type_checking_imports - .push(format!("from .{} import {} # noqa: F401\n", module, cname)); - imported_names.insert(cname.clone()); + let collection_identities = collect_used_generic_identities_from_class(class); + for identity in &collection_identities { + let identity = context.normalize_identity(identity); + if !delegate_names.contains(&identity) { + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if name == reference_name { + name + } else { + format!("{name} as {reference_name}") + }; + type_checking_imports.push(format!("from .{module} import {import} # noqa: F401\n")); + imported_names.insert(reference_name); } } for iface in class.all_interfaces() { if iface.generic_piid.as_deref() == Some(crate::codegen::winrt::python::collections::IOBSERVABLE_VECTOR_PIID) { - if imported_names.insert(iface.name.clone()) { + let identity = iface.type_identity(); + let reference_name = context.reference_name(&identity); + if imported_names.insert(reference_name) { type_checking_imports.push(format_py_type_import( + context, &iface.namespace, &iface.name, crate::types::TypeKind::Interface, @@ -139,9 +156,14 @@ pub fn generate_class( } let event_args = "IVectorChangedEventArgs"; if imported_names.insert(event_args.into()) { + let identity = TypeIdentity::named( + TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + event_args, + ); type_checking_imports.push(format!( "from .{} import {event_args} # noqa: F401\n", - to_snake_case_filename(event_args) + context.implementation_module(&identity) )); } } @@ -150,11 +172,19 @@ pub fn generate_class( // Import delegate IID + PARAM_TYPES let mut sorted_delegates: Vec<_> = runtime_delegate_names.iter().collect(); sorted_delegates.sort(); - for dname in &sorted_delegates { - let module = to_snake_case_filename(dname); - type_checking_imports.push(format!( - "from .{module} import IID_{dname}, {dname}_PARAM_TYPES # noqa: F401\n", - )); + for identity in &sorted_delegates { + let module = context.implementation_module(identity); + let dname = context.projected_name(identity); + let reference_name = context.reference_name(identity); + let imports = if dname == reference_name { + format!("IID_{dname}, {dname}_PARAM_TYPES") + } else { + format!( + "IID_{dname} as IID_{reference_name}, \ + {dname}_PARAM_TYPES as {reference_name}_PARAM_TYPES" + ) + }; + type_checking_imports.push(format!("from .{module} import {imports} # noqa: F401\n",)); } // Type imports @@ -163,29 +193,47 @@ pub fn generate_class( sorted_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); for r in &sorted_imports { - if known_types.contains(&r.name) && !delegate_names.contains(&r.name) { - type_checking_imports.push(format_py_type_import(&r.namespace, &r.name, r.kind)); - imported_names.insert(r.name.clone()); + let identity_kind = match r.kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + let identity = context.normalize_identity(&TypeIdentity::named( + identity_kind, + r.namespace.clone(), + r.name.clone(), + )); + if context.is_known_ref(r) && !delegate_names.contains(&identity) { + type_checking_imports.push(format_py_type_import( + context, + &r.namespace, + &r.name, + r.kind, + )); + let reference_name = context.reference_name(&identity); + imported_names.insert(reference_name.clone()); if r.kind == TypeKind::Interface { - imported_names.insert(format!("IID_{}", r.name)); + imported_names.insert(format!("IID_{reference_name}")); } } } // Import shared required interfaces for req_iface in &class.required_interfaces { + let symbol = interface_symbol(context, req_iface); if req_iface.generic_piid.is_none() && !req_iface.iid.is_empty() && shared_iids.contains(&req_iface.iid) - && !imported_names.contains(&req_iface.name) + && !imported_names.contains(&symbol) { type_checking_imports.push(format_py_type_import( + context, &req_iface.namespace, &req_iface.name, TypeKind::Interface, )); - imported_names.insert(req_iface.name.clone()); - imported_names.insert(format!("IID_{}", req_iface.name)); + imported_names.insert(symbol.clone()); + imported_names.insert(format!("IID_{symbol}")); } } emit_type_checking_imports(&mut out, type_checking_imports); @@ -199,7 +247,7 @@ pub fn generate_class( .chain(class.overridable_interfaces.iter()) .collect(); for iface in &all_class_ifaces { - let iid_name = format!("IID_{}", iface.name); + let iid_name = format!("IID_{}", interface_symbol(context, iface)); if declared_iids.insert(iid_name.clone()) { if let Some(iid_expr) = py_interface_iid_expr(iface) { out.push_str(&format!("{} = {}\n", iid_name, iid_expr)); @@ -227,30 +275,38 @@ pub fn generate_class( // 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!("_{}", iface.name), + &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!("_{}", iface.name), + &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!("_{}", iface.name), + &format!("_{symbol}"), + &symbol, )); out.push('\n'); } for iface in &class.required_interfaces { + let symbol = interface_symbol(context, iface); out.push_str(&py_generate_interface_registration( iface, - &format!("_{}", iface.name), + &format!("_{symbol}"), + &symbol, )); out.push('\n'); } @@ -265,9 +321,9 @@ pub fn generate_class( } // Struct helpers - if !python_module_layout_installed() { + if !context.is_packaged() { for s in &used_structs { - out.push_str(&generate_struct_helpers(s)); + out.push_str(&generate_struct_helpers(context, s)); out.push('\n'); } } @@ -295,9 +351,8 @@ pub fn generate_class( } out.push_str(&generate_python_constructor( + context, class, - known_types, - delegate_type_names, collection_iface, collection_uses_default, )); @@ -307,26 +362,28 @@ pub fn generate_class( // during interpreter shutdown when WinUI releases them after RoUninitialize. let mut declared: HashSet = HashSet::new(); for iface in &class.factory_interfaces { - let key = format!("f_{}", iface.name); + let symbol = interface_symbol(context, iface); + let key = format!("f_{symbol}"); if !iface.iid.is_empty() && declared.insert(key.clone()) { out.push_str(" @staticmethod\n"); out.push_str(&format!(" def _get_{}():\n", key)); out.push_str(&format!( " return DynWinRTValue.activation_factory('{full}').cast(IID_{iface})\n", - iface = iface.name, + iface = symbol, full = class.full_name, )); out.push('\n'); } } for iface in &class.static_interfaces { - let key = format!("s_{}", iface.name); + let symbol = interface_symbol(context, iface); + let key = format!("s_{symbol}"); if !iface.iid.is_empty() && declared.insert(key.clone()) { out.push_str(" @staticmethod\n"); out.push_str(&format!(" def _get_{}():\n", key)); out.push_str(&format!( " return DynWinRTValue.activation_factory('{full}').cast(IID_{iface})\n", - iface = iface.name, + iface = symbol, full = class.full_name, )); out.push('\n'); @@ -380,7 +437,7 @@ pub fn generate_class( || method.is_event_add || method.is_event_remove { - key = format!("{}#{key}", iface.name); + key = format!("{}#{key}", interface_symbol(context, iface)); } let overload = StaticOverload { class, @@ -401,11 +458,7 @@ pub fn generate_class( } for (_, overloads) in static_groups { out.push('\n'); - out.push_str(&generate_static_method_group( - &overloads, - known_types, - &delegate_names, - )); + out.push_str(&generate_static_method_group(&overloads, context)); } let static_aliases = generate_compatibility_aliases(static_methods.iter().copied()); if !static_aliases.is_empty() { @@ -452,12 +505,21 @@ pub fn generate_class( let controls_resources = spec.controls_resources; let resource_manager = spec.resource_manager; let callback_types = project_winui_abi_types(spec.launched_callback_params); - let metadata_module = - python_module_name(metadata_provider.namespace, metadata_provider.name); - let resources_module = - python_module_name(controls_resources.namespace, controls_resources.name); - let resource_manager_module = - python_module_name(resource_manager.namespace, resource_manager.name); + let metadata_module = context.implementation_module_for_named( + TypeIdentityKind::Class, + metadata_provider.namespace, + metadata_provider.name, + ); + let resources_module = context.implementation_module_for_named( + TypeIdentityKind::Class, + controls_resources.namespace, + controls_resources.name, + ); + let resource_manager_module = context.implementation_module_for_named( + TypeIdentityKind::Class, + resource_manager.namespace, + resource_manager.name, + ); let metadata_provider = metadata_provider.name; let controls_resources = controls_resources.name; let resource_manager = resource_manager.name; @@ -567,20 +629,22 @@ pub fn generate_class( // before any cross-interface setter that references it. for setter_phase in [false, true] { for iface in &instance_ifaces { - let obj_expr = - if collection_iface.is_some_and(|collection| collection.name == iface.name) { - collection_obj_expr - } else if class - .default_interface - .as_ref() - .is_some_and(|default_iface| default_iface.name == iface.name) - { - "self._obj" - } else { - "" - }; + let obj_expr = if collection_iface + .is_some_and(|collection| collection.type_identity() == iface.type_identity()) + { + collection_obj_expr + } else if class + .default_interface + .as_ref() + .is_some_and(|default_iface| default_iface.type_identity() == iface.type_identity()) + { + "self._obj" + } else { + "" + }; + let iface_symbol = interface_symbol(context, iface); let obj_expr = if obj_expr.is_empty() { - format!("self._obj.cast(IID_{})", iface.name) + format!("self._obj.cast(IID_{iface_symbol})") } else { obj_expr.to_string() }; @@ -593,7 +657,7 @@ pub fn generate_class( &instance_method_names, ); let overload = InstanceOverload { - iface_var: format!("_{}", iface.name), + iface_var: format!("_{iface_symbol}"), obj_expr: obj_expr.clone(), method, sibling_methods: Some(iface.methods.as_slice()), @@ -616,11 +680,7 @@ pub fn generate_class( } for (_, overloads) in method_groups { out.push('\n'); - out.push_str(&generate_instance_method_group( - &overloads, - known_types, - &delegate_names, - )); + out.push_str(&generate_instance_method_group(&overloads, context)); } let instance_aliases = generate_compatibility_aliases( instance_ifaces @@ -635,14 +695,15 @@ pub fn generate_class( if matches!( collection_kind, Some(CollectionKind::Mapping | CollectionKind::MutableMapping) - ) && let Some(iterable_name) = - collection_iface.and_then(|iface| map_iterable_name(&iface.generic_args)) + ) && let Some(iterable_identity) = + collection_iface.and_then(|iface| map_iterable_identity(&iface.generic_args)) { + let iterable_name = context.projected_name(&iterable_identity); out.push('\n'); out.push_str(" def _iter_pairs(self):\n"); out.push_str(&format!( " return iter({}({}))\n", - py_runtime_symbol(&iterable_name, &iterable_name), + py_runtime_symbol(context, &iterable_identity, &iterable_name), collection_obj_expr )); } @@ -659,7 +720,13 @@ pub fn generate_class( out.push_str(" if self._closed:\n return\n"); out.push_str(&format!( " {}.from_value(self._obj).close()\n", - py_runtime_symbol("IClosable", "IClosable") + py_runtime_named_symbol( + context, + TypeIdentityKind::Interface, + "Windows.Foundation", + "IClosable", + "IClosable", + ) )); out.push_str(" self._closed = True\n\n"); out.push_str(" def __enter__(self):\n"); @@ -771,21 +838,19 @@ pub fn generate_class( if req_iface.iid.is_empty() { continue; } - if imported_names.contains(&req_iface.name) { + let symbol = interface_symbol(context, req_iface); + if imported_names.contains(&symbol) { continue; } - let reg_var = format!("_{}", req_iface.name); + let reg_var = format!("_{symbol}"); out.push('\n'); if let Some(mixin) = interface_kind(req_iface).and_then(runtime_mixin) { - out.push_str(&format!("\nclass {}({mixin}):\n", req_iface.name)); + out.push_str(&format!("\nclass {symbol}({mixin}):\n")); } else { - out.push_str(&format!("\nclass {}:\n", req_iface.name)); + out.push_str(&format!("\nclass {symbol}:\n")); } out.push_str(" _dynwinrt_interface_type = True\n"); - out.push_str(&format!( - " _dynwinrt_interface_iid = IID_{}\n", - req_iface.name - )); + out.push_str(&format!(" _dynwinrt_interface_iid = IID_{symbol}\n")); out.push_str(" def __new__(cls, *args, **kwargs):\n"); out.push_str( " if len(args) == 1 and not kwargs and isinstance(args[0], DynWinRTValue):\n\ @@ -793,10 +858,7 @@ pub fn generate_class( \x20 return super().__new__(cls)\n\n", ); out.push_str(" def _set_native(self, obj: DynWinRTValue):\n"); - out.push_str(&format!( - " self._obj = obj.cast(IID_{})\n", - req_iface.name - )); + out.push_str(&format!(" self._obj = obj.cast(IID_{symbol})\n")); out.push_str(" self._dynwinrt_native_ready = True\n"); out.push_str(&format!( " _dynwinrt_track_projected(self, '{}.{}')\n", @@ -809,26 +871,22 @@ pub fn generate_class( " if getattr(self, '_dynwinrt_native_ready', False):\n\ \x20 return\n", ); - out.push_str(&format!( - " {}._set_native(self, obj)\n", - req_iface.name - )); + out.push_str(&format!(" {symbol}._set_native(self, obj)\n")); out.push('\n'); out.push_str(" @classmethod\n"); out.push_str(&format!( " def _from_native(cls, obj: DynWinRTValue) -> '{}':\n", - req_iface.name + symbol )); out.push_str(" return cls(obj)\n"); out.push('\n'); out.push_str(" @classmethod\n"); out.push_str(&format!( " def from_value(cls, obj: DynWinRTValue) -> '{}':\n", - req_iface.name + symbol )); out.push_str(&format!( - " return cls._from_native(obj.cast(IID_{}))\n", - req_iface.name + " return cls._from_native(obj.cast(IID_{symbol}))\n" )); out.push('\n'); out.push_str(" def as_interface(self, interface_class):\n"); @@ -853,11 +911,7 @@ pub fn generate_class( }), }) .collect::>(); - out.push_str(&generate_instance_method_group( - &overloads, - known_types, - &delegate_names, - )); + out.push_str(&generate_instance_method_group(&overloads, context)); } let aliases = generate_compatibility_aliases(req_iface.methods.iter()); if !aliases.is_empty() { @@ -867,13 +921,14 @@ pub fn generate_class( if matches!( interface_kind(req_iface), Some(CollectionKind::Mapping | CollectionKind::MutableMapping) - ) && let Some(iterable_name) = map_iterable_name(&req_iface.generic_args) + ) && let Some(iterable_identity) = map_iterable_identity(&req_iface.generic_args) { + let iterable_name = context.projected_name(&iterable_identity); out.push('\n'); out.push_str(" def _iter_pairs(self):\n"); out.push_str(&format!( " return iter({}(self._obj))\n", - py_runtime_symbol(&iterable_name, &iterable_name) + py_runtime_symbol(context, &iterable_identity, &iterable_name) )); } } @@ -932,9 +987,9 @@ struct PyCtorCandidate<'a> { } fn build_ctor_candidates<'a>( + context: &PythonProjectionContext, class: &'a ClassMeta, factory_names: &HashSet, - delegate_type_names: &HashSet, ) -> Vec> { fn push_unique<'a>(candidates: &mut Vec>, candidate: PyCtorCandidate<'a>) { if let Some(existing) = candidates.iter_mut().find(|existing| { @@ -1044,14 +1099,14 @@ fn build_ctor_candidates<'a>( crate::codegen::winrt::python::method::py_wrap_method_arg( &format!("_bound[{index}]"), ¶m.typ, - delegate_type_names, + context, ) }) .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)", - factory = factory.name, + factory = interface_symbol(context, factory), class = class.name, vtable = method.vtable_index, agile = if class.is_agile { "True" } else { "False" }, @@ -1189,9 +1244,8 @@ fn python_tuple(values: &[String]) -> String { } fn generate_python_constructor( + context: &PythonProjectionContext, class: &ClassMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, collection_iface: Option<&InterfaceMeta>, collection_uses_default: bool, ) -> String { @@ -1253,7 +1307,7 @@ fn generate_python_constructor( .collect::>(); let factory_names = crate::codegen::winrt::python::overloads::method_names(static_methods.iter().copied()); - let mut candidates = build_ctor_candidates(class, &factory_names, delegate_type_names); + let mut candidates = build_ctor_candidates(context, class, &factory_names); candidates.sort_by(|left, right| { crate::codegen::winrt::python::overloads::cmp_python_dispatch_params( &left.public_params, @@ -1291,12 +1345,7 @@ fn generate_python_constructor( .iter() .enumerate() .map(|(index, param)| { - py_method_type_guard( - &format!("_bound[{index}]"), - ¶m.typ, - known_types, - delegate_type_names, - ) + py_method_type_guard(&format!("_bound[{index}]"), ¶m.typ, context) }) .collect::>(); let condition = if guards.is_empty() { @@ -1338,10 +1387,8 @@ fn generate_python_constructor( if default_iface.iid.is_empty() { out.push_str(" self._obj = obj\n"); } else { - out.push_str(&format!( - " self._obj = obj.cast(IID_{})\n", - default_iface.name - )); + let symbol = interface_symbol(context, default_iface); + out.push_str(&format!(" self._obj = obj.cast(IID_{symbol})\n")); } } else { out.push_str(" self._obj = obj\n"); @@ -1349,9 +1396,9 @@ fn generate_python_constructor( if let Some(collection_iface) = collection_iface && !collection_uses_default { + let symbol = interface_symbol(context, collection_iface); out.push_str(&format!( - " self._collection_obj = obj.cast(IID_{})\n", - collection_iface.name + " self._collection_obj = obj.cast(IID_{symbol})\n" )); } if class @@ -1408,7 +1455,7 @@ fn generate_python_constructor( let default_iid = class .default_interface .as_ref() - .map(|interface| format!("IID_{}", interface.name)) + .map(|interface| format!("IID_{}", interface_symbol(context, interface))) .expect("public composable runtime class has a default interface"); out.push_str(&format!( " return _dynwinrt_register_xaml_runtime_class(runtime_class_name, '{}', {default_iid}, control_type, _native_overrides)\n\n", @@ -1479,9 +1526,9 @@ fn generate_python_constructor( )); } out.push_str(" if _override_callbacks:\n"); + let symbol = interface_symbol(context, interface); out.push_str(&format!( - " _override_interfaces.append(DynWinRTOverrideInterface(IID_{}, [{}], _override_callbacks))\n", - interface.name, + " _override_interfaces.append(DynWinRTOverrideInterface(IID_{symbol}, [{}], _override_callbacks))\n", shapes .iter() .map(|shape| format!("'{shape}'")) @@ -1510,12 +1557,7 @@ fn generate_python_constructor( .iter() .enumerate() .map(|(index, param)| { - py_method_type_guard( - &format!("_bound[{index}]"), - ¶m.typ, - known_types, - delegate_type_names, - ) + py_method_type_guard(&format!("_bound[{index}]"), ¶m.typ, context) }) .collect::>(); let condition = if guards.is_empty() { @@ -1657,7 +1699,7 @@ mod tests { ..Default::default() }; - let code = generate_class(&class, &HashSet::new(), &HashSet::new(), &HashSet::new()); + let code = generate_class(&PythonProjectionContext::default(), &class, &HashSet::new()); assert!(code.contains("def _create_6_0("), "{code}"); assert!(code.contains("def _create_6_1("), "{code}"); assert!(code.contains("type(self)._create_6_0(_bound[0])"), "{code}"); @@ -1700,19 +1742,18 @@ mod tests { fn python_constructor_enum_overload_prefers_enum_over_i32_in_both_orders() { let integer = constructor_method("Create", 6, TypeMeta::I32); let enumeration = constructor_method("Create2", 7, enum_type("Mode")); - let known_types = HashSet::from(["Mode".to_string()]); + let context = + PythonProjectionContext::packaged([enum_type("Mode").type_identity()]).unwrap(); let forward = generate_python_constructor( + &context, &constructor_class(vec![integer.clone(), enumeration.clone()]), - &known_types, - &HashSet::new(), None, false, ); let reverse = generate_python_constructor( + &context, &constructor_class(vec![enumeration, integer]), - &known_types, - &HashSet::new(), None, false, ); 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 ba404109..c37c6cdc 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/imports.rs @@ -6,14 +6,51 @@ use super::*; /// Format a Python import line based on type kind. -pub(super) fn format_py_type_import(namespace: &str, name: &str, kind: TypeKind) -> String { - let module = python_module_name(namespace, name); +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 IID_{name}, {name} # noqa: F401\n") + 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 {name}, {name}Like # noqa: F401\n") + 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 {name} # noqa: F401\n") + format!( + "from .{module} import {} # noqa: F401\n", + imported(&projected_name, &reference_name) + ) } } 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 241f1606..b4759582 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/index.rs @@ -9,6 +9,7 @@ use super::*; /// Generate a Python `__init__.py` that re-exports all generated types. pub fn generate_index( + context: &PythonProjectionContext, classes: &[ClassMeta], interfaces: &[InterfaceMeta], enums: &[TypeMeta], @@ -20,11 +21,14 @@ pub fn generate_index( sorted_classes.sort_by(|a, b| a.name.cmp(&b.name)); for class in sorted_classes { if seen.insert(class.name.clone()) { - let module = python_module_name(&class.namespace, &class.name); - out.push_str(&format!( - "from .{} import {} # noqa: F401\n", - module, class.name - )); + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); + out.push_str(&format!("from .{} import {} # noqa: F401\n", module, name)); } } let mut sorted_ifaces: Vec<_> = interfaces.iter().collect(); @@ -33,20 +37,21 @@ pub fn generate_index( if !seen.insert(iface.name.clone()) { continue; } - let is_delegate = iface.methods.iter().any(|m| m.name == ".ctor") - && iface.methods.iter().any(|m| m.name == "Invoke"); - let module = python_module_name(&iface.namespace, &iface.name); + let is_delegate = iface.is_delegate(); + let identity = iface.type_identity(); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); if is_delegate { out.push_str(&format!( "from .{module} import IID_{iname}, {iname}_PARAM_TYPES # noqa: F401\n", module = module, - iname = iface.name + iname = name )); } else { out.push_str(&format!( "from .{module} import IID_{iname}, {iname} # noqa: F401\n", module = module, - iname = iface.name + iname = name )); } } @@ -63,12 +68,11 @@ pub fn generate_index( name_a.cmp(name_b) }); for en in sorted_enums { - if let TypeMeta::Enum { - namespace, name, .. - } = en - { + if let TypeMeta::Enum { name, .. } = en { if seen.insert(name.clone()) { - let module = python_module_name(namespace, name); + let identity = en.type_identity(); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); out.push_str(&format!("from .{} import {} # noqa: F401\n", module, name)); } } @@ -77,6 +81,7 @@ pub fn generate_index( } pub fn generate_public_index( + context: &PythonProjectionContext, classes: &[ClassMeta], interfaces: &[InterfaceMeta], enums: &[TypeMeta], @@ -88,10 +93,16 @@ pub fn generate_public_index( classes.sort_by(|left, right| left.name.cmp(&right.name)); for class in classes { if seen.insert(class.name.clone()) { + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + let name = context.projected_name(&identity); out.push_str(&format!( "from .{} import {} # noqa: F401\n", - python_public_qualified_module_name(&class.namespace, &class.name), - class.name + context.public_qualified_module(&identity), + name )); } } @@ -99,19 +110,14 @@ pub fn generate_public_index( let mut interfaces = interfaces.iter().collect::>(); interfaces.sort_by(|left, right| left.name.cmp(&right.name)); for interface in interfaces { - let is_delegate = interface - .methods - .iter() - .any(|method| method.name == ".ctor") - && interface - .methods - .iter() - .any(|method| method.name == "Invoke"); + let is_delegate = interface.is_delegate(); if !is_delegate && seen.insert(interface.name.clone()) { + let identity = interface.type_identity(); + let name = context.projected_name(&identity); out.push_str(&format!( "from .{} import {} # noqa: F401\n", - python_public_qualified_module_name(&interface.namespace, &interface.name), - interface.name + context.public_qualified_module(&identity), + name )); } } @@ -122,16 +128,15 @@ pub fn generate_public_index( _ => "", }); for typ in enums { - let TypeMeta::Enum { - namespace, name, .. - } = typ - else { + let TypeMeta::Enum { name, .. } = typ else { continue; }; if seen.insert(name.clone()) { + let identity = typ.type_identity(); + let name = context.projected_name(&identity); out.push_str(&format!( "from .{} import {} # noqa: F401\n", - python_public_qualified_module_name(namespace, name), + context.public_qualified_module(&identity), name )); } @@ -139,7 +144,7 @@ pub fn generate_public_index( out } -pub fn generate_struct_index(structs: &[TypeMeta]) -> String { +pub fn generate_struct_index(context: &PythonProjectionContext, structs: &[TypeMeta]) -> String { let mut out = String::from(HEADER); let mut seen = HashSet::new(); let mut sorted = structs.iter().collect::>(); @@ -161,14 +166,17 @@ pub fn generate_struct_index(structs: &[TypeMeta]) -> String { } out.push_str(&format!( "from .{} import {} # noqa: F401\n", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), py_struct_export_names(typ).join(", ") )); } out } -pub fn generate_public_struct_index(structs: &[TypeMeta]) -> String { +pub fn generate_public_struct_index( + context: &PythonProjectionContext, + structs: &[TypeMeta], +) -> String { let mut out = String::from(HEADER); let mut seen = HashSet::new(); let mut sorted = structs.iter().collect::>(); @@ -190,7 +198,7 @@ pub fn generate_public_struct_index(structs: &[TypeMeta]) -> String { } out.push_str(&format!( "from .{} import {} # noqa: F401\n", - python_public_qualified_module_name(namespace, name), + context.public_qualified_module(&typ.type_identity()), name )); } @@ -199,6 +207,7 @@ pub fn generate_public_struct_index(structs: &[TypeMeta]) -> String { /// Append new types to an existing `__init__.py`. pub fn append_to_index( + context: &PythonProjectionContext, existing: &str, classes: &[ClassMeta], interfaces: &[InterfaceMeta], @@ -242,35 +251,39 @@ pub fn append_to_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 { - let module = python_module_name(&class.namespace, &class.name); + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); if !exported_modules.contains(&module) && seen.insert(class.name.clone()) { - out.push_str(&format!( - "from .{} import {} # noqa: F401\n", - module, class.name - )); + out.push_str(&format!("from .{} import {} # noqa: F401\n", module, name)); } } let mut sorted_ifaces: Vec<_> = interfaces.iter().collect(); sorted_ifaces.sort_by(|a, b| a.name.cmp(&b.name)); for iface in sorted_ifaces { - let module = python_module_name(&iface.namespace, &iface.name); + 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()) { continue; } - let is_delegate = iface.methods.iter().any(|m| m.name == ".ctor") - && iface.methods.iter().any(|m| m.name == "Invoke"); + let is_delegate = iface.is_delegate(); if is_delegate { out.push_str(&format!( "from .{module} import IID_{iname}, {iname}_PARAM_TYPES # noqa: F401\n", module = module, - iname = iface.name + iname = name )); } else { out.push_str(&format!( "from .{module} import IID_{iname}, {iname} # noqa: F401\n", module = module, - iname = iface.name + iname = name )); } } @@ -288,13 +301,15 @@ pub fn append_to_index( name_a.cmp(name_b) }); for en in sorted_enums { - if let TypeMeta::Enum { - namespace, name, .. - } = en - { - let module = python_module_name(namespace, name); + if let TypeMeta::Enum { name, .. } = 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()) { - out.push_str(&format!("from .{} import {} # noqa: F401\n", module, name)); + 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 b1babfea..ceba1796 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/mod.rs @@ -14,8 +14,8 @@ use crate::types::{TypeKind, TypeMeta}; use crate::codegen::winrt::shared::imports::{ collect_iface_type_imports, collect_struct_field_type_imports, collect_type_imports, - collect_used_generics_from_class, collect_used_generics_from_methods, - collect_used_generics_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, @@ -26,14 +26,11 @@ use super::method::{ InstanceOverload, StaticOverload, StaticOverloadKind, generate_instance_method_group, generate_static_method_group, py_method_type_guard, }; -use super::naming::{ - is_py_reserved, python_module_layout_installed, python_module_name, - python_public_qualified_module_name, to_snake_case, to_snake_case_filename, -}; +use super::naming::{PythonProjectionContext, is_py_reserved, to_snake_case}; use super::shared::reorder_getters_before_setters; use super::signature::{ py_collect_runtime_class_iid_consts, py_dynwinrt_type, py_generate_interface_registration, - py_interface_iid_expr, py_runtime_symbol, py_wrap_native_value, + py_interface_iid_expr, py_runtime_named_symbol, py_runtime_symbol, py_wrap_native_value, }; use super::structs::{ py_struct_field_getter, py_struct_field_read_type, py_struct_field_setter, py_struct_field_type, 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 c35f6097..1205be1f 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs @@ -27,19 +27,19 @@ fn struct_runtime_import_names(s: &TypeMeta) -> Vec { names } -pub(super) fn generate_struct_imports(structs: &[TypeMeta]) -> String { +pub(super) fn generate_struct_imports( + context: &PythonProjectionContext, + structs: &[TypeMeta], +) -> String { let mut imports = structs .iter() .filter_map(|typ| { - let TypeMeta::Struct { - namespace, name, .. - } = typ - else { + let TypeMeta::Struct { .. } = typ else { return None; }; Some(format!( "from .{} import {} # noqa: F401\n", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), struct_runtime_import_names(typ).join(", ") )) }) @@ -49,7 +49,7 @@ pub(super) fn generate_struct_imports(structs: &[TypeMeta]) -> String { imports.concat() } -pub fn generate_struct(s: &TypeMeta) -> Option { +pub fn generate_struct(context: &PythonProjectionContext, s: &TypeMeta) -> Option { let TypeMeta::Struct { name, .. } = s else { return None; }; @@ -63,7 +63,7 @@ pub fn generate_struct(s: &TypeMeta) -> Option { out.push_str(IMPORT_LINE); let dependencies = collect_used_structs_from_struct(s); - out.push_str(&generate_struct_imports(&dependencies)); + out.push_str(&generate_struct_imports(context, &dependencies)); if has_ireference_struct_field(std::slice::from_ref(s)) { out.push_str(IREFERENCE_HELPER); } @@ -71,21 +71,34 @@ pub fn generate_struct(s: &TypeMeta) -> Option { let mut type_checking_imports = collect_struct_field_type_imports(s) .into_iter() - .map(|type_ref| format_py_type_import(&type_ref.namespace, &type_ref.name, type_ref.kind)) + .map(|type_ref| { + format_py_type_import(context, &type_ref.namespace, &type_ref.name, type_ref.kind) + }) .collect::>(); - type_checking_imports.extend(collect_used_generics_from_type(s).into_iter().map(|name| { - format!( - "from .{} import {} # noqa: F401\n", - to_snake_case_filename(&name), - name - ) - })); + type_checking_imports.extend( + collect_used_generic_identities_from_type(s) + .into_iter() + .map(|identity| { + let identity = context.normalize_identity(&identity); + let name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if name == reference_name { + name + } else { + format!("{name} as {reference_name}") + }; + format!( + "from .{} import {import} # noqa: F401\n", + context.implementation_module(&identity), + ) + }), + ); emit_type_checking_imports(&mut out, type_checking_imports); - out.push_str(&generate_struct_helpers(s)); + out.push_str(&generate_struct_helpers(context, s)); Some(out) } -pub(super) fn generate_struct_helpers(s: &TypeMeta) -> String { +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); } @@ -121,8 +134,8 @@ pub(super) fn generate_struct_helpers(s: &TypeMeta) -> String { format!( "{}: {} = {}", to_snake_case(&f.name), - py_struct_constructor_field_type(&f.typ), - py_default_value(&f.typ) + py_struct_constructor_field_type(context, &f.typ), + py_default_value(context, &f.typ) ) }) .collect(); @@ -156,8 +169,8 @@ pub(super) fn generate_struct_helpers(s: &TypeMeta) -> String { \x20 @{snake}.setter\n\ \x20 def {snake}(self, value: {write_type}) -> None:\n\ \x20 self._{snake} = _dynwinrt_unbox_reference(value)\n", - read_type = py_struct_field_read_type(&f.typ), - write_type = py_struct_field_type(&f.typ), + read_type = py_struct_field_read_type(context, &f.typ), + write_type = py_struct_field_type(context, &f.typ), )); } } @@ -195,7 +208,7 @@ pub(super) fn generate_struct_helpers(s: &TypeMeta) -> String { format!( "{}={}", to_snake_case(&f.name), - py_struct_field_getter(&f.typ, i) + py_struct_field_getter(context, &f.typ, i) ) }) .collect(); @@ -334,7 +347,7 @@ fn generate_foundation_struct_helpers(s: &TypeMeta, kind: FoundationType) -> Str } /// Python default value for struct field initialization. -pub(super) fn py_default_value(typ: &TypeMeta) -> String { +pub(super) fn py_default_value(context: &PythonProjectionContext, typ: &TypeMeta) -> String { match foundation_type(typ) { Some(FoundationType::DateTime) => return "_dynwinrt_ticks_to_datetime(0)".to_string(), Some(FoundationType::TimeSpan) => return "timedelta(0)".to_string(), @@ -351,11 +364,9 @@ pub(super) fn py_default_value(typ: &TypeMeta) -> String { | TypeMeta::U32 | TypeMeta::I64 | TypeMeta::U64 => "0".to_string(), - TypeMeta::Enum { - namespace, name, .. - } => format!( + TypeMeta::Enum { name, .. } => format!( "_dynwinrt_enum('{}', '{}', 0)", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), name ), TypeMeta::Char16 => "'\\0'".to_string(), @@ -367,12 +378,12 @@ pub(super) fn py_default_value(typ: &TypeMeta) -> String { } } -fn py_struct_constructor_field_type(typ: &TypeMeta) -> String { +fn py_struct_constructor_field_type(context: &PythonProjectionContext, typ: &TypeMeta) -> String { match typ { TypeMeta::Struct { name, .. } if foundation_type(typ).is_none() && name != "HResult" => { - py_optional_type(py_struct_field_type(typ)) + py_optional_type(py_struct_field_type(context, typ)) } - _ => py_struct_field_type(typ), + _ => py_struct_field_type(context, typ), } } 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 03bf5867..01d05b9c 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/types.rs @@ -7,11 +7,13 @@ use super::imports::{emit_type_checking_imports, format_py_type_import}; use super::structs::{generate_struct_helpers, generate_struct_imports}; use super::*; use crate::codegen::winrt::python::collections::{ - CollectionKind, interface_kind, map_iterable_name, observable_vector_name, runtime_mixin, + CollectionKind, interface_kind, map_iterable_identity, observable_vector_identity, + runtime_mixin, }; +use crate::types::{TypeIdentity, TypeIdentityKind}; /// Generate a Python file for a single enum. -pub fn generate_enum(en: &TypeMeta) -> Option { +pub fn generate_enum(_context: &PythonProjectionContext, en: &TypeMeta) -> Option { let (name, members, is_flags, enum_doc, enum_dep) = match en { TypeMeta::Enum { name, @@ -74,13 +76,11 @@ pub fn generate_enum(en: &TypeMeta) -> Option { } /// Generate a Python file for a WinRT interface (non-exclusive). -pub fn generate_interface( - iface: &InterfaceMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, -) -> String { - let is_delegate = iface.methods.iter().any(|m| m.name == ".ctor") - && iface.methods.iter().any(|m| m.name == "Invoke"); +pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String { + let mut projected_iface = iface.clone(); + projected_iface.name = context.projected_name_for_interface(iface); + let iface = &projected_iface; + let is_delegate = iface.is_delegate(); if is_delegate { return generate_delegate(iface); } @@ -97,7 +97,7 @@ pub fn generate_interface( out.push_str("from dynwinrt import DynWinRtElementFactory\n"); } let collection_kind = interface_kind(iface); - let observable_vector = observable_vector_name(iface); + let observable_vector = observable_vector_identity(iface); if observable_vector.is_none() && let Some(mixin) = collection_kind.and_then(runtime_mixin) { @@ -106,8 +106,8 @@ pub fn generate_interface( if methods_have_async_output(iface.methods.iter()) { out.push_str(ASYNC_IMPORT_LINE); } - if python_module_layout_installed() { - out.push_str(&generate_struct_imports(&used_structs)); + if context.is_packaged() { + out.push_str(&generate_struct_imports(context, &used_structs)); } if has_ireference_input(iface.methods.iter()) || has_ireference_struct_field(&used_structs) { out.push_str(IREFERENCE_HELPER); @@ -116,31 +116,50 @@ pub fn generate_interface( let mut type_checking_imports = Vec::new(); // Collect delegate names - let delegate_names = - super::super::collect_referenced_delegate_names(&iface.methods, delegate_type_names); + let delegate_names = super::super::collect_referenced_delegate_names(&iface.methods, context); let runtime_delegate_names = - super::super::collect_runtime_delegate_names(&iface.methods, delegate_type_names); + super::super::collect_runtime_delegate_names(&iface.methods, context); // Import parameterized collection types (skip delegates) - let collection_names = collect_used_generics_from_methods(&iface.methods); - for cname in &collection_names { - if cname != &iface.name && !delegate_names.contains(cname) { - let module = to_snake_case_filename(cname); - type_checking_imports - .push(format!("from .{} import {} # noqa: F401\n", module, cname)); + let collection_identities = collect_used_generic_identities_from_methods(&iface.methods); + for identity in &collection_identities { + let identity = context.normalize_identity(identity); + if identity != iface.type_identity() && !delegate_names.contains(&identity) { + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if name == reference_name { + name + } else { + format!("{name} as {reference_name}") + }; + type_checking_imports.push(format!("from .{module} import {import} # noqa: F401\n")); } } - if let Some(vector_name) = &observable_vector - && !collection_names.contains(vector_name) - { - let module = to_snake_case_filename(vector_name); - type_checking_imports.push(format!( - "from .{module} import {vector_name} # noqa: F401\n" - )); + if let Some(identity) = &observable_vector { + if !collection_identities + .iter() + .any(|candidate| context.normalize_identity(candidate) == *identity) + { + let module = context.implementation_module(&identity); + let vector_name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if vector_name == reference_name { + vector_name + } else { + format!("{vector_name} as {reference_name}") + }; + type_checking_imports.push(format!("from .{module} import {import} # noqa: F401\n")); + } } if observable_vector.is_some() { let event_args = "IVectorChangedEventArgs"; - let module = to_snake_case_filename(event_args); + let identity = TypeIdentity::named( + TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + event_args, + ); + let module = context.implementation_module(&identity); type_checking_imports.push(format!( "from .{module} import {event_args} # noqa: F401\n" )); @@ -149,11 +168,19 @@ pub fn generate_interface( // Import delegate IID + PARAM_TYPES let mut sorted_delegates: Vec<_> = runtime_delegate_names.iter().collect(); sorted_delegates.sort(); - for dname in &sorted_delegates { - let module = to_snake_case_filename(dname); - type_checking_imports.push(format!( - "from .{module} import IID_{dname}, {dname}_PARAM_TYPES # noqa: F401\n", - )); + for identity in &sorted_delegates { + let module = context.implementation_module(identity); + let dname = context.projected_name(identity); + let reference_name = context.reference_name(identity); + let imports = if dname == reference_name { + format!("IID_{dname}, {dname}_PARAM_TYPES") + } else { + format!( + "IID_{dname} as IID_{reference_name}, \ + {dname}_PARAM_TYPES as {reference_name}_PARAM_TYPES" + ) + }; + type_checking_imports.push(format!("from .{module} import {imports} # noqa: F401\n",)); } // Type imports for referenced types @@ -162,8 +189,23 @@ pub fn generate_interface( sorted_type_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); for r in &sorted_type_imports { - if known_types.contains(&r.name) && !delegate_names.contains(&r.name) { - type_checking_imports.push(format_py_type_import(&r.namespace, &r.name, r.kind)); + let identity_kind = match r.kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + let identity = context.normalize_identity(&TypeIdentity::named( + identity_kind, + r.namespace.clone(), + r.name.clone(), + )); + if context.is_known_ref(r) && !delegate_names.contains(&identity) { + type_checking_imports.push(format_py_type_import( + context, + &r.namespace, + &r.name, + r.kind, + )); } } emit_type_checking_imports(&mut out, type_checking_imports); @@ -191,23 +233,25 @@ pub fn generate_interface( out.push_str(&py_generate_interface_registration( iface, &format!("_{}", iface.name), + &iface.name, )); out.push('\n'); // Struct helpers - if !python_module_layout_installed() { + if !context.is_packaged() { for s in &used_structs { - out.push_str(&generate_struct_helpers(s)); + out.push_str(&generate_struct_helpers(context, s)); out.push('\n'); } } // Wrapper class - if let Some(vector_name) = &observable_vector { + if let Some(identity) = &observable_vector { + let vector_name = context.projected_name(identity); out.push_str(&format!( "\nclass {}({}):\n", iface.name, - py_runtime_symbol(vector_name, vector_name) + py_runtime_symbol(context, identity, &vector_name) )); } else if let Some(mixin) = collection_kind.and_then(runtime_mixin) { out.push_str(&format!("\nclass {}({mixin}):\n", iface.name)); @@ -240,10 +284,11 @@ pub fn generate_interface( \x20 return super().__new__(cls)\n\n", ); out.push_str(" def _set_native(self, obj: DynWinRTValue):\n"); - if let Some(vector_name) = &observable_vector { + if let Some(identity) = &observable_vector { + let vector_name = context.projected_name(identity); out.push_str(&format!( " {}._set_native(self, obj)\n", - py_runtime_symbol(vector_name, vector_name) + py_runtime_symbol(context, identity, &vector_name) )); out.push_str(&format!( " self._observable_obj = obj.cast(IID_{})\n", @@ -302,12 +347,13 @@ pub fn generate_interface( let elem_type = py_dynwinrt_type(&iface.generic_args[0]); let elem_annotation = crate::codegen::winrt::python::type_helpers::py_param_type_safe( &iface.generic_args[0], - known_types, + context, ); let wrap = py_wrap_native_value("item", &iface.generic_args[0]); - let vector_name = observable_vector + let vector_identity = observable_vector .as_ref() .expect("observable vector companion"); + let vector_name = context.projected_name(vector_identity); out.push_str(" @staticmethod\n"); out.push_str(&format!( " def create(items: Iterable[{}]) -> '{}':\n", @@ -318,16 +364,15 @@ pub fn generate_interface( iface.name, wrap, elem_type )); out.push_str(&format!(" def as_vector(self) -> '{}':\n", vector_name)); - out.push_str(&format!( - " return {}(self._obj)\n", - py_runtime_symbol(vector_name, vector_name) - )); + out.push_str(&format!(" return {}(self._obj)\n", { + py_runtime_symbol(context, vector_identity, &vector_name) + })); out.push('\n'); } else if piid == "913337e9-11a1-4345-a3a2-4e7f956e222d" && iface.generic_args.len() == 1 { let elem_type = py_dynwinrt_type(&iface.generic_args[0]); let elem_annotation = crate::codegen::winrt::python::type_helpers::py_param_type_safe( &iface.generic_args[0], - known_types, + context, ); let wrap = py_wrap_native_value("item", &iface.generic_args[0]); out.push_str(" @staticmethod\n"); @@ -345,11 +390,11 @@ pub fn generate_interface( let val_type = py_dynwinrt_type(&iface.generic_args[1]); let key_annotation = crate::codegen::winrt::python::type_helpers::py_param_type_safe( &iface.generic_args[0], - known_types, + context, ); let val_annotation = crate::codegen::winrt::python::type_helpers::py_param_type_safe( &iface.generic_args[1], - known_types, + 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]); @@ -367,10 +412,27 @@ pub fn generate_interface( } if is_element_factory { - let get_args = py_runtime_symbol("ElementFactoryGetArgs", "ElementFactoryGetArgs"); - let recycle_args = - py_runtime_symbol("ElementFactoryRecycleArgs", "ElementFactoryRecycleArgs"); - let ui_element_iid = py_runtime_symbol("UIElement", "IID_IUIElement"); + let get_args = py_runtime_named_symbol( + context, + TypeIdentityKind::Class, + "Microsoft.UI.Xaml", + "ElementFactoryGetArgs", + "ElementFactoryGetArgs", + ); + let recycle_args = py_runtime_named_symbol( + context, + TypeIdentityKind::Class, + "Microsoft.UI.Xaml", + "ElementFactoryRecycleArgs", + "ElementFactoryRecycleArgs", + ); + let ui_element_iid = py_runtime_named_symbol( + context, + TypeIdentityKind::Class, + "Microsoft.UI.Xaml", + "UIElement", + "IID_IUIElement", + ); out.push_str( r#" @staticmethod def create(get_element, recycle_element): @@ -458,12 +520,13 @@ pub fn generate_interface( if matches!( collection_kind, Some(CollectionKind::Mapping | CollectionKind::MutableMapping) - ) && let Some(iterable_name) = map_iterable_name(&iface.generic_args) + ) && let Some(iterable_identity) = map_iterable_identity(&iface.generic_args) { + let iterable_name = context.projected_name(&iterable_identity); out.push_str(" def _iter_pairs(self):\n"); out.push_str(&format!( " return iter({}(self._obj))\n\n", - py_runtime_symbol(&iterable_name, &iterable_name) + py_runtime_symbol(context, &iterable_identity, &iterable_name) )); } @@ -494,11 +557,7 @@ pub fn generate_interface( }), }) .collect::>(); - out.push_str(&generate_instance_method_group( - &overloads, - known_types, - &delegate_names, - )); + out.push_str(&generate_instance_method_group(&overloads, context)); } let aliases = generate_compatibility_aliases(iface.methods.iter()); if !aliases.is_empty() { @@ -599,7 +658,7 @@ mod tests { deprecated: None, }; - let code = generate_enum(&value).unwrap(); + let code = generate_enum(&PythonProjectionContext::default(), &value).unwrap(); assert!(code.contains("from enum import IntFlag")); assert!(code.contains("class Options(IntFlag):")); } @@ -612,7 +671,8 @@ mod tests { iid: "11111111-1111-1111-1111-111111111111".into(), ..Default::default() }; - let code = generate_interface(&iface, &HashSet::new(), &HashSet::new()); + let context = PythonProjectionContext::standalone([iface.type_identity()]).unwrap(); + let code = generate_interface(&context, &iface); assert!(code.contains("_dynwinrt_interface_type = True")); assert!(code.contains("_dynwinrt_interface_iid = IID_IWidget")); assert!(code.contains("@classmethod\n def from_value(cls, obj: DynWinRTValue)")); @@ -632,11 +692,12 @@ mod tests { }], ..Default::default() }; - let code = generate_interface( - &iface, - &HashSet::from(["Widget".into(), "IVector_Widget".into()]), - &HashSet::new(), - ); + let context = PythonProjectionContext::standalone([ + iface.type_identity(), + TypeIdentity::named(TypeIdentityKind::Class, "Contoso", "Widget"), + ]) + .unwrap(); + let code = generate_interface(&context, &iface); assert!(code.contains("def create(items: Iterable['WidgetLike'])")); assert!(!code.contains("def create(items: Iterable[WidgetLike | None])")); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs index aa07cfed..d30f08f9 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/method.rs @@ -1,39 +1,34 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use std::collections::HashSet; - use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta}; -use crate::types::TypeMeta; +use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; use crate::codegen::winrt::extensions::winui::{self, WinUiCallBehavior}; use crate::codegen::winrt::shared::imports::{ fill_array_output_index, fill_array_uses_retval_count, get_in_params, }; -use super::naming::to_snake_case; +use super::naming::{PythonProjectionContext, PythonTypeIdentity, to_snake_case}; use super::signature::{ - py_convert_return, py_runtime_symbol, py_type_guard, py_wrap_arg, py_wrap_async, - py_wrap_async_with_converters, + py_convert_return, py_runtime_named_symbol, py_runtime_symbol, py_type_guard, py_wrap_arg, + py_wrap_async, py_wrap_async_with_converters, }; use super::type_helpers::{ method_pydoc, py_delegate_callable_type, py_factory_return_type, py_method_abi_output_count, py_method_outputs, py_method_return_type, py_output_type, py_param_list, }; -fn is_delegate_type(typ: &TypeMeta, delegate_type_names: &HashSet) -> bool { - delegate_name(typ, delegate_type_names).is_some() +fn is_delegate_type(typ: &TypeMeta, context: &PythonProjectionContext) -> bool { + context.is_delegate_type(typ) } -fn delegate_value_converter( - typ: &TypeMeta, - delegate_type_names: &HashSet, -) -> Option { - if is_delegate_type(typ, delegate_type_names) { +fn delegate_value_converter(typ: &TypeMeta, context: &PythonProjectionContext) -> Option { + if is_delegate_type(typ, context) { return Some("lambda value: None if value.is_null() else value".into()); } if let TypeMeta::Array(inner) = typ - && is_delegate_type(inner, delegate_type_names) + && is_delegate_type(inner, context) { return Some( "lambda value: [None if item.is_null() else item for item in value.as_array().to_values()]" @@ -52,14 +47,17 @@ fn delegate_value_converter( /// invoking the user's `callback`. /// /// The wrapper falls back to a passthrough (`callback`) for unknown delegate shapes. -fn build_event_wrapper(typ: Option<&TypeMeta>, known_types: &HashSet) -> (String, String) { +fn build_event_wrapper( + typ: Option<&TypeMeta>, + context: &PythonProjectionContext, +) -> (String, String) { match typ { Some(typ @ TypeMeta::Parameterized { name, args, .. }) if name.split('`').next() == Some("TypedEventHandler") && args.len() == 2 => { - let sender_conv = py_convert_return("__sender__", Some(&args[0]), false, known_types); - let args_conv = py_convert_return("__args__", Some(&args[1]), false, known_types); - let sig = py_delegate_callable_type(typ, known_types); + let sender_conv = py_convert_return("__sender__", Some(&args[0]), false, context); + let args_conv = py_convert_return("__args__", Some(&args[1]), false, context); + let sig = py_delegate_callable_type(typ, context); let wrapper = format!( "(lambda callback=callback: (lambda __sender__, __args__: callback({}, {})))()", sender_conv, args_conv @@ -69,8 +67,8 @@ fn build_event_wrapper(typ: Option<&TypeMeta>, known_types: &HashSet) -> Some(typ @ TypeMeta::Parameterized { name, args, .. }) if name.split('`').next() == Some("EventHandler") && args.len() == 1 => { - let args_conv = py_convert_return("__args__", Some(&args[0]), false, known_types); - let sig = py_delegate_callable_type(typ, known_types); + let args_conv = py_convert_return("__args__", Some(&args[0]), false, context); + let sig = py_delegate_callable_type(typ, context); let wrapper = format!( "(lambda callback=callback: (lambda __sender__, __args__: callback(__sender__, {})))()", args_conv @@ -80,16 +78,28 @@ fn build_event_wrapper(typ: Option<&TypeMeta>, known_types: &HashSet) -> Some(typ @ TypeMeta::Parameterized { name, args, .. }) if name.split('`').next() == Some("VectorChangedEventHandler") && args.len() == 1 => { - let observable_name = crate::meta::make_parameterized_name("IObservableVector", args); + let observable_identity = TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IObservableVector", + args.iter().map(TypeMeta::type_identity), + ); + let observable_name = context.projected_name(&observable_identity); let sender = format!( "(lambda value: None if value.is_null() else {}(value))(__sender__)", - py_runtime_symbol(&observable_name, &observable_name) + py_runtime_symbol(context, &observable_identity, &observable_name) ); let event_args = format!( "(lambda value: None if value.is_null() else {}(value))(__args__)", - py_runtime_symbol("IVectorChangedEventArgs", "IVectorChangedEventArgs") + py_runtime_named_symbol( + context, + TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IVectorChangedEventArgs", + "IVectorChangedEventArgs", + ) ); - let sig = py_delegate_callable_type(typ, known_types); + let sig = py_delegate_callable_type(typ, context); let wrapper = format!( "(lambda callback=callback: (lambda __sender__, __args__: callback({}, {})))()", sender, event_args @@ -100,30 +110,26 @@ fn build_event_wrapper(typ: Option<&TypeMeta>, known_types: &HashSet) -> } } -fn delegate_name(typ: &TypeMeta, delegate_type_names: &HashSet) -> Option { - match typ { - TypeMeta::Delegate { name, .. } => Some(name.clone()), - TypeMeta::Interface { name, .. } if delegate_type_names.contains(name) => { - Some(name.clone()) - } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); - delegate_type_names.contains(&concrete).then_some(concrete) - } - _ => None, - } +fn delegate_identity( + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> Option { + context + .is_delegate_type(typ) + .then(|| context.identity_for_type(typ)) } pub(crate) fn py_wrap_method_arg( name: &str, typ: &TypeMeta, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { - if let Some(delegate) = delegate_name(typ, delegate_type_names) { + if let Some(delegate) = delegate_identity(typ, context) { + let projected_name = context.projected_name(&delegate); return format!( "_dynwinrt_delegate({name}, {}, {})", - py_runtime_symbol(&delegate, &format!("IID_{delegate}")), - py_runtime_symbol(&delegate, &format!("{delegate}_PARAM_TYPES")) + py_runtime_symbol(context, &delegate, &format!("IID_{projected_name}")), + py_runtime_symbol(context, &delegate, &format!("{projected_name}_PARAM_TYPES")) ); } py_wrap_arg(name, typ) @@ -131,13 +137,11 @@ pub(crate) fn py_wrap_method_arg( fn py_build_method_args_expr( in_params: &[&crate::meta::ParamMeta], - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { in_params .iter() - .map(|param| { - py_wrap_method_arg(&to_snake_case(¶m.name), ¶m.typ, delegate_type_names) - }) + .map(|param| py_wrap_method_arg(&to_snake_case(¶m.name), ¶m.typ, context)) .collect::>() .join(", ") } @@ -145,24 +149,18 @@ fn py_build_method_args_expr( pub(crate) fn py_method_type_guard( name: &str, typ: &TypeMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { - if is_delegate_type(typ, delegate_type_names) { + if is_delegate_type(typ, context) { return format!( "(callable({name}) or isinstance(getattr({name}, '_obj', {name}), DynWinRTValue))" ); } - py_type_guard(name, typ, known_types) + py_type_guard(name, typ, context) } -fn convert_method_output( - expr: &str, - typ: &TypeMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, -) -> String { - if let Some(converter) = delegate_value_converter(typ, delegate_type_names) { +fn convert_method_output(expr: &str, typ: &TypeMeta, context: &PythonProjectionContext) -> String { + if let Some(converter) = delegate_value_converter(typ, context) { return format!("({converter})({expr})"); } match typ { @@ -170,9 +168,9 @@ fn convert_method_output( return py_wrap_async_with_converters( expr, typ, - delegate_value_converter(result, delegate_type_names), + delegate_value_converter(result, context), None, - known_types, + context, ); } TypeMeta::AsyncActionWithProgress(progress) => { @@ -180,22 +178,22 @@ fn convert_method_output( expr, typ, None, - delegate_value_converter(progress, delegate_type_names), - known_types, + delegate_value_converter(progress, context), + context, ); } TypeMeta::AsyncOperationWithProgress(result, progress) => { return py_wrap_async_with_converters( expr, typ, - delegate_value_converter(result, delegate_type_names), - delegate_value_converter(progress, delegate_type_names), - known_types, + delegate_value_converter(result, context), + delegate_value_converter(progress, context), + context, ); } _ => {} } - py_convert_return(expr, Some(typ), typ.is_async(), known_types) + py_convert_return(expr, Some(typ), typ.is_async(), context) } fn method_call_expr( @@ -223,8 +221,7 @@ fn emit_method_result( out: &mut String, call_expr: &str, method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) { let outputs = py_method_outputs(method); if outputs.is_empty() { @@ -233,8 +230,7 @@ fn emit_method_result( } if py_method_abi_output_count(method) == 1 { - let converted = - convert_method_output(call_expr, outputs[0].1, known_types, delegate_type_names); + let converted = convert_method_output(call_expr, outputs[0].1, context); out.push_str(&format!(" return {}\n", converted)); return; } @@ -243,12 +239,7 @@ fn emit_method_result( let converted = outputs .iter() .map(|(index, typ)| { - let converted = convert_method_output( - &format!("_results[{}]", index), - typ, - known_types, - delegate_type_names, - ); + let converted = convert_method_output(&format!("_results[{}]", index), typ, context); if fill_array_uses_retval_count(method) && fill_array_output_index(method) == Some(*index) { @@ -275,31 +266,22 @@ pub(crate) fn generate_factory_method_invoke( class: &ClassMeta, iface: &InterfaceMeta, method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { - generate_factory_method_invoke_named( - class, - iface, - method, - known_types, - delegate_type_names, - None, - ) + generate_factory_method_invoke_named(class, iface, method, context, None) } fn generate_factory_method_invoke_named( class: &ClassMeta, iface: &InterfaceMeta, method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, name_override: Option<&str>, ) -> String { let in_params = get_in_params(method); - let py_params = py_param_list(&in_params, known_types, delegate_type_names); + let py_params = py_param_list(&in_params, context); - let return_py_type = py_factory_return_type(&class.name, method, known_types); + let return_py_type = py_factory_return_type(&class.name, method, context); let mut out = String::new(); let method_name = name_override @@ -320,11 +302,12 @@ fn generate_factory_method_invoke_named( } out.push_str(&method_pydoc(method, &in_params)); - let args_expr = py_build_method_args_expr(&in_params, delegate_type_names); + 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.name), + &format!("_{iface_symbol}"), method, - &format!("{}._get_f_{}()", class.name, iface.name), + &format!("{}._get_f_{iface_symbol}()", class.name), &args_expr, ); let result_expr = if py_method_abi_output_count(method) > 1 { @@ -341,7 +324,7 @@ fn generate_factory_method_invoke_named( } _ => None, }; - py_wrap_async(&result_expr, async_type, result_converter, known_types) + py_wrap_async(&result_expr, async_type, result_converter, context) } else { format!("{}._from_native({})", class.name, result_expr) }; @@ -353,38 +336,30 @@ pub(crate) fn generate_static_method_invoke( class: &ClassMeta, iface: &InterfaceMeta, method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { - generate_static_method_invoke_named( - class, - iface, - method, - known_types, - delegate_type_names, - None, - ) + generate_static_method_invoke_named(class, iface, method, context, None) } fn generate_static_method_invoke_named( class: &ClassMeta, iface: &InterfaceMeta, method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, name_override: Option<&str>, ) -> String { let in_params = get_in_params(method); - let py_params = py_param_list(&in_params, known_types, delegate_type_names); + let py_params = py_param_list(&in_params, context); - let py_return = py_method_return_type(method, known_types, delegate_type_names); + let py_return = py_method_return_type(method, context); let mut out = String::new(); + let iface_symbol = context.reference_name(&iface.type_identity()); let statics_call = format!( "{cls}._get_s_{iface}()", cls = class.name, - iface = iface.name + iface = iface_symbol ); // Static property getter @@ -397,14 +372,8 @@ 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.name), method, &statics_call, ""); - emit_method_result( - &mut out, - &call_expr, - method, - known_types, - delegate_type_names, - ); + let call_expr = method_call_expr(&format!("_{iface_symbol}"), method, &statics_call, ""); + emit_method_result(&mut out, &call_expr, method, context); } else { out.push_str(" @staticmethod\n"); let method_name = name_override @@ -419,20 +388,14 @@ fn generate_static_method_invoke_named( )); } out.push_str(&method_pydoc(method, &in_params)); - let args_expr = py_build_method_args_expr(&in_params, delegate_type_names); + let args_expr = py_build_method_args_expr(&in_params, context); let call_expr = method_call_expr( - &format!("_{}", iface.name), + &format!("_{iface_symbol}"), method, &statics_call, &args_expr, ); - emit_method_result( - &mut out, - &call_expr, - method, - known_types, - delegate_type_names, - ); + emit_method_result(&mut out, &call_expr, method, context); } out } @@ -473,8 +436,7 @@ pub(crate) fn private_overload_names<'a>( pub(crate) fn generate_instance_method_group( overloads: &[InstanceOverload<'_>], - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { if overloads.len() == 1 { let overload = &overloads[0]; @@ -482,8 +444,7 @@ pub(crate) fn generate_instance_method_group( &overload.iface_var, &overload.obj_expr, overload.method, - known_types, - delegate_type_names, + context, None, overload.sibling_methods, overload.property_has_getter, @@ -509,8 +470,7 @@ pub(crate) fn generate_instance_method_group( &overload.iface_var, &overload.obj_expr, overload.method, - known_types, - delegate_type_names, + context, Some(private_name), overload.sibling_methods, overload.property_has_getter, @@ -541,12 +501,7 @@ pub(crate) fn generate_instance_method_group( .iter() .enumerate() .map(|(index, param)| { - py_method_type_guard( - &format!("_bound[{index}]"), - ¶m.typ, - known_types, - delegate_type_names, - ) + py_method_type_guard(&format!("_bound[{index}]"), ¶m.typ, context) }) .collect::>(); let condition = if guards.is_empty() { @@ -579,8 +534,7 @@ pub(crate) struct StaticOverload<'a> { pub(crate) fn generate_static_method_group( overloads: &[StaticOverload<'_>], - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { if overloads.len() == 1 { let overload = &overloads[0]; @@ -589,15 +543,13 @@ pub(crate) fn generate_static_method_group( overload.class, overload.iface, overload.method, - known_types, - delegate_type_names, + context, ), StaticOverloadKind::Static => generate_static_method_invoke( overload.class, overload.iface, overload.method, - known_types, - delegate_type_names, + context, ), }; } @@ -622,16 +574,14 @@ pub(crate) fn generate_static_method_group( overload.class, overload.iface, overload.method, - known_types, - delegate_type_names, + context, Some(private_name), ), StaticOverloadKind::Static => generate_static_method_invoke_named( overload.class, overload.iface, overload.method, - known_types, - delegate_type_names, + context, Some(private_name), ), }; @@ -662,12 +612,7 @@ pub(crate) fn generate_static_method_group( .iter() .enumerate() .map(|(index, param)| { - py_method_type_guard( - &format!("_bound[{index}]"), - ¶m.typ, - known_types, - delegate_type_names, - ) + py_method_type_guard(&format!("_bound[{index}]"), ¶m.typ, context) }) .collect::>(); let condition = if guards.is_empty() { @@ -690,8 +635,7 @@ pub(crate) fn generate_method_body( iface_var: &str, obj_expr: &str, method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, name_override: Option<&str>, sibling_methods: Option<&[MethodMeta]>, property_has_getter: bool, @@ -708,7 +652,7 @@ pub(crate) fn generate_method_body( let suffix = method.name.strip_prefix("add_").unwrap_or(&method.name); let event_name = to_snake_case(suffix); let delegate_typ = in_params.first().map(|p| &p.typ); - let delegate_name = delegate_typ.and_then(|typ| delegate_name(typ, delegate_type_names)); + let delegate_identity = delegate_typ.and_then(|typ| delegate_identity(typ, context)); // Find matching remove_ in the same interface to know its vtable index. let remove_target = format!("remove_{}", suffix); let remove_idx = sibling_methods.and_then(|methods| { @@ -720,7 +664,7 @@ pub(crate) fn generate_method_body( // Compute callback wrapper: for TypedEventHandler / EventHandler, // wrap raw ABI args back into projected values before invoking the user callback. - let (callback_signature, wrapper) = build_event_wrapper(delegate_typ, known_types); + let (callback_signature, wrapper) = build_event_wrapper(delegate_typ, context); out.push_str(&format!( " def on_{}(self, callback: {}):\n", @@ -729,9 +673,11 @@ pub(crate) fn generate_method_body( out.push_str(&method_pydoc(method, &in_params)); // Wrapping expression bound to `_wrapped` before delegate construction. out.push_str(&format!(" _wrapped = {}\n", wrapper)); - if let Some(ref dname) = delegate_name { - let iid = py_runtime_symbol(dname, &format!("IID_{}", dname)); - let param_types = py_runtime_symbol(dname, &format!("{}_PARAM_TYPES", dname)); + if let Some(ref identity) = delegate_identity { + let delegate_name = context.projected_name(identity); + let iid = py_runtime_symbol(context, identity, &format!("IID_{delegate_name}")); + let param_types = + py_runtime_symbol(context, identity, &format!("{delegate_name}_PARAM_TYPES")); out.push_str(&format!( " _handler = _dynwinrt_create_delegate({}, {}, _wrapped)\n", iid, param_types @@ -818,31 +764,22 @@ pub(crate) fn generate_method_body( if method.is_property_getter && in_params.is_empty() { let prop_name = to_snake_case(method.name.strip_prefix("get_").unwrap_or(&method.name)); let py_return = return_type - .map(|typ| py_output_type(typ, known_types, delegate_type_names)) + .map(|typ| py_output_type(typ, context)) .unwrap_or_else(|| "None".to_string()); 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, ""); - emit_method_result( - &mut out, - &call_expr, - method, - known_types, - delegate_type_names, - ); + 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)); let param_type = in_params .first() .map(|p| { - if is_delegate_type(&p.typ, delegate_type_names) { + if is_delegate_type(&p.typ, context) { // Reuse py_delegate_param_type via a temporary param_list call. - let params = super::type_helpers::py_param_list( - std::slice::from_ref(p), - known_types, - delegate_type_names, - ); + let params = + super::type_helpers::py_param_list(std::slice::from_ref(p), context); // params is "name: Type" — extract the "Type" part. params .splitn(2, ": ") @@ -850,7 +787,7 @@ pub(crate) fn generate_method_body( .map(|s| s.to_string()) .unwrap_or_else(|| "Callable[..., object] | 'DynWinRTValue'".to_string()) } else { - super::type_helpers::py_param_type_safe(&p.typ, known_types) + super::type_helpers::py_param_type_safe(&p.typ, context) } }) .unwrap_or_else(|| "object".to_string()); @@ -869,15 +806,15 @@ pub(crate) fn generate_method_body( out.push_str(&method_pydoc(method, &in_params)); let arg = in_params .first() - .map(|p| py_wrap_method_arg("value", &p.typ, delegate_type_names)) + .map(|p| py_wrap_method_arg("value", &p.typ, context)) .unwrap_or_else(|| "value".to_string()); out.push_str(&format!( " {}.method({}).invoke({}, [{}])\n", iface_var, method.vtable_index, obj_expr, arg )); } else { - let py_params = py_param_list(&in_params, known_types, delegate_type_names); - let py_return = py_method_return_type(method, known_types, delegate_type_names); + let py_params = py_param_list(&in_params, context); + let py_return = py_method_return_type(method, context); let method_name = name_override .map(|s| s.to_string()) .unwrap_or_else(|| to_snake_case(&method.name)); @@ -893,15 +830,9 @@ pub(crate) fn generate_method_body( )); out.push_str(&method_pydoc(method, &in_params)); - let args_expr = py_build_method_args_expr(&in_params, delegate_type_names); + let args_expr = py_build_method_args_expr(&in_params, context); let call_expr = method_call_expr(iface_var, method, obj_expr, &args_expr); - emit_method_result( - &mut out, - &call_expr, - method, - known_types, - delegate_type_names, - ); + emit_method_result(&mut out, &call_expr, method, context); } out @@ -958,7 +889,7 @@ mod tests { }, ]; - let code = generate_instance_method_group(&overloads, &HashSet::new(), &HashSet::new()); + let code = generate_instance_method_group(&overloads, &PythonProjectionContext::default()); assert_eq!(code.matches("def _register_6_").count(), 2, "{code}"); assert!(code.contains("self._register_6_0(*_bound)"), "{code}"); assert!(code.contains("self._register_6_1(*_bound)"), "{code}"); @@ -1058,13 +989,14 @@ mod tests { name: "Widget".into(), ..Default::default() }; - let code = generate_static_method_invoke( - &class, - &iface, - &method, - &HashSet::from(["Handler".into()]), - &HashSet::from(["Handler".into()]), - ); + let delegate_identity = method + .return_type + .as_ref() + .unwrap() + .type_identity() + .with_kind(TypeIdentityKind::Delegate); + let context = PythonProjectionContext::standalone([delegate_identity]).unwrap(); + let code = generate_static_method_invoke(&class, &iface, &method, &context); assert!( code.contains("def get_handler() -> DynWinRTValue | None:"), @@ -1088,8 +1020,7 @@ mod tests { "_IReader", "self._obj", &method, - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), None, None, true, @@ -1124,8 +1055,7 @@ mod tests { "_IOutputStream", "self._obj", &method, - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), None, None, true, @@ -1182,7 +1112,7 @@ mod tests { }, ]; - let code = generate_instance_method_group(&overloads, &HashSet::new(), &HashSet::new()); + let code = generate_instance_method_group(&overloads, &PythonProjectionContext::default()); assert!(code.contains("def _read_6(self, value: str)")); assert!(code.contains("def _read_7(self, value: int)")); assert!(code.contains("def read(self, *args, **kwargs)")); @@ -1237,11 +1167,9 @@ mod tests { }, ]; - let code = generate_instance_method_group( - &overloads, - &HashSet::new(), - &HashSet::from(["WorkItemHandler".into()]), - ); + let context = + PythonProjectionContext::standalone([callback.params[0].typ.type_identity()]).unwrap(); + let code = generate_instance_method_group(&overloads, &context); assert!(code.contains("callable(_bound[0])")); assert!(code.contains("_dynwinrt_delegate(handler,")); assert!(code.contains("'work_item_handler', 'IID_WorkItemHandler'")); @@ -1263,6 +1191,13 @@ mod tests { TypeMeta::Object, ], }; + let context = PythonProjectionContext::standalone([ + handler_type + .type_identity() + .with_kind(TypeIdentityKind::Delegate), + TypeIdentity::named(TypeIdentityKind::Class, "Contoso", "Widget"), + ]) + .unwrap(); let add = MethodMeta { name: "add_Changed".into(), raw_name: "add_Changed".into(), @@ -1292,8 +1227,7 @@ mod tests { "_IWidget", "self._obj", &add, - &HashSet::from(["Widget".into()]), - &HashSet::from(["TypedEventHandler_Widget_Object".into()]), + &context, None, Some(&siblings), true, @@ -1330,12 +1264,16 @@ mod tests { is_event_add: true, ..Default::default() }; + let delegate_identity = add.params[0] + .typ + .type_identity() + .with_kind(TypeIdentityKind::Delegate); + let context = PythonProjectionContext::standalone([delegate_identity]).unwrap(); let code = generate_method_body( "_IButton", "self._obj", &add, - &HashSet::new(), - &HashSet::from(["RoutedEventHandler".into()]), + &context, None, Some(std::slice::from_ref(&add)), true, @@ -1388,7 +1326,7 @@ mod tests { }, ]; - let code = generate_static_method_group(&overloads, &HashSet::new(), &HashSet::new()); + let code = generate_static_method_group(&overloads, &PythonProjectionContext::default()); assert!(code.contains("def _create_6()")); assert!(code.contains("def _create_7(value: str)")); assert!(code.contains("def create(*args, **kwargs)")); @@ -1401,13 +1339,11 @@ mod tests { let forward = generate_instance_method_group( &[instance_overload(&wide), instance_overload(&narrow)], - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), ); let reverse = generate_instance_method_group( &[instance_overload(&narrow), instance_overload(&wide)], - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), ); assert_eq!(forward, reverse); @@ -1435,7 +1371,7 @@ mod tests { instance_overload(&signed), ]; - let code = generate_instance_method_group(&overloads, &HashSet::new(), &HashSet::new()); + let code = generate_instance_method_group(&overloads, &PythonProjectionContext::default()); assert_contains_in_order( &code, @@ -1484,16 +1420,14 @@ mod tests { static_overload(&class, &iface, &float), static_overload(&class, &iface, &integer), ], - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), ); let reverse = generate_static_method_group( &[ static_overload(&class, &iface, &integer), static_overload(&class, &iface, &float), ], - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), ); assert_eq!(forward, reverse); @@ -1508,17 +1442,17 @@ mod tests { fn python_known_int_enum_instance_overload_prefers_enum_over_i8_in_both_orders() { let integer = overloaded_method("Read", 6, TypeMeta::I8); let enumeration = overloaded_method("Read2", 7, enum_type("Mode", false)); - let known_types = HashSet::from(["Mode".to_string()]); + let context = + PythonProjectionContext::standalone([enum_type("Mode", false).type_identity()]) + .unwrap(); let forward = generate_instance_method_group( &[instance_overload(&integer), instance_overload(&enumeration)], - &known_types, - &HashSet::new(), + &context, ); let reverse = generate_instance_method_group( &[instance_overload(&enumeration), instance_overload(&integer)], - &known_types, - &HashSet::new(), + &context, ); let forward_dispatcher = @@ -1593,7 +1527,9 @@ print(json.dumps([exercise(ReaderForward), exercise(ReaderReverse)])) fn python_known_int_flag_static_overload_prefers_enum_over_i32_in_both_orders() { let integer = overloaded_method("Create", 6, TypeMeta::I32); let flags = overloaded_method("Create2", 7, enum_type("Options", true)); - let known_types = HashSet::from(["Options".to_string()]); + let context = + PythonProjectionContext::standalone([enum_type("Options", true).type_identity()]) + .unwrap(); let iface = InterfaceMeta { name: "IFactoryStatics".into(), ..Default::default() @@ -1612,16 +1548,14 @@ print(json.dumps([exercise(ReaderForward), exercise(ReaderReverse)])) static_overload(&class_forward, &iface, &integer), static_overload(&class_forward, &iface, &flags), ], - &known_types, - &HashSet::new(), + &context, ); let reverse = generate_static_method_group( &[ static_overload(&class_reverse, &iface, &flags), static_overload(&class_reverse, &iface, &integer), ], - &known_types, - &HashSet::new(), + &context, ); let forward_dispatcher = extract_generated_block( diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs index 8a509acc..f8116d7e 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/mod.rs @@ -17,9 +17,9 @@ pub(crate) mod type_helpers; pub use generator::*; pub use naming::{ - PythonModuleLayoutGuard, PythonTypeIdentity, install_python_module_layout, - python_module_layout_installed, python_module_name, python_namespace_segments, - python_public_module_name, python_public_qualified_module_name, to_snake_case_filename, + PythonProjectionContext, PythonTypeIdentity, python_identity_display_name, + python_namespace_segments, python_public_module_name, python_public_qualified_module_name, + to_snake_case_filename, }; pub(crate) fn has_projectable_default_interface(class: &crate::meta::ClassMeta) -> bool { @@ -63,50 +63,41 @@ pub(crate) fn has_native_projector(class: &crate::meta::ClassMeta) -> bool { pub(crate) fn collect_referenced_delegate_names( methods: &[crate::meta::MethodMeta], - known_delegate_names: &std::collections::HashSet, -) -> std::collections::HashSet { + context: &PythonProjectionContext, +) -> std::collections::HashSet { fn collect( typ: &crate::types::TypeMeta, - known: &std::collections::HashSet, - result: &mut std::collections::HashSet, + context: &PythonProjectionContext, + result: &mut std::collections::HashSet, ) { use crate::types::TypeMeta; + if context.is_delegate_type(typ) { + result.insert(context.identity_for_type(typ)); + } match typ { - TypeMeta::Delegate { name, .. } => { - result.insert(name.clone()); - } - TypeMeta::Interface { name, .. } => { - if known.contains(name) { - result.insert(name.clone()); - } - } TypeMeta::AsyncActionWithProgress(inner) | TypeMeta::AsyncOperation(inner) | TypeMeta::Array(inner) => { - collect(inner, known, result); + collect(inner, context, result); } TypeMeta::AsyncOperationWithProgress(result_type, progress) => { - collect(result_type, known, result); - collect(progress, known, result); + collect(result_type, context, result); + collect(progress, context, result); } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); - if known.contains(&concrete) { - result.insert(concrete); - } + TypeMeta::Parameterized { args, .. } => { for argument in args { - collect(argument, known, result); + collect(argument, context, result); } } TypeMeta::RuntimeClass { default_interface: Some(interface), .. } => { - collect(interface, known, result); + collect(interface, context, result); } TypeMeta::Struct { fields, .. } => { for field in fields { - collect(&field.typ, known, result); + collect(&field.typ, context, result); } } _ => {} @@ -116,10 +107,10 @@ pub(crate) fn collect_referenced_delegate_names( let mut result = std::collections::HashSet::new(); for method in methods { for parameter in &method.params { - collect(¶meter.typ, known_delegate_names, &mut result); + collect(¶meter.typ, context, &mut result); } if let Some(return_type) = &method.return_type { - collect(return_type, known_delegate_names, &mut result); + collect(return_type, context, &mut result); } } result @@ -127,10 +118,9 @@ pub(crate) fn collect_referenced_delegate_names( pub(crate) fn collect_runtime_delegate_names( methods: &[crate::meta::MethodMeta], - known_delegate_names: &std::collections::HashSet, -) -> std::collections::HashSet { + context: &PythonProjectionContext, +) -> std::collections::HashSet { use crate::meta::ParamDirection; - use crate::types::TypeMeta; let mut result = std::collections::HashSet::new(); for method in methods { @@ -138,20 +128,8 @@ pub(crate) fn collect_runtime_delegate_names( if parameter.direction != ParamDirection::In { continue; } - match ¶meter.typ { - TypeMeta::Delegate { name, .. } => { - result.insert(name.clone()); - } - TypeMeta::Interface { name, .. } if known_delegate_names.contains(name) => { - result.insert(name.clone()); - } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); - if known_delegate_names.contains(&concrete) { - result.insert(concrete); - } - } - _ => {} + if context.is_delegate_type(¶meter.typ) { + result.insert(context.identity_for_type(¶meter.typ)); } } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs index f01fe36a..72caf6d0 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs @@ -3,23 +3,19 @@ //! Python naming and identifier helpers. -use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; -#[derive(Clone, Debug, Eq, Hash, PartialEq)] -pub struct PythonTypeIdentity { - pub namespace: String, - pub name: String, -} +use crate::meta::InterfaceMeta; +use crate::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; -#[derive(Default)] -struct PythonModuleLayout { - modules: HashMap, - unique_modules: HashMap, -} +pub type PythonTypeIdentity = TypeIdentity; -thread_local! { - static MODULE_LAYOUT: RefCell> = const { RefCell::new(None) }; +#[derive(Clone, Debug)] +struct PythonProjection { + implementation_module: String, + projected_name: String, + public_module: String, + reference_name: String, } const MAX_PYTHON_MODULE_COMPONENT_LENGTH: usize = 120; @@ -34,7 +30,7 @@ fn stable_module_hash(value: &str) -> u64 { hash } -fn shorten_module_component(value: &str) -> String { +fn shorten_module_component_with_hash_input(value: &str, hash_input: &str) -> String { if value.chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH { return value.to_string(); } @@ -45,84 +41,684 @@ fn shorten_module_component(value: &str) -> String { .collect::() .trim_end_matches('_') .to_string(); - format!("{prefix}_{:016x}", stable_module_hash(value)) + format!("{prefix}_{:016x}", stable_module_hash(hash_input)) } -pub struct PythonModuleLayoutGuard; +fn shorten_module_component(value: &str) -> String { + shorten_module_component_with_hash_input(value, value) +} -impl Drop for PythonModuleLayoutGuard { - fn drop(&mut self) { - MODULE_LAYOUT.with(|layout| { - *layout.borrow_mut() = None; - }); +fn identity_kind_name(kind: TypeIdentityKind) -> &'static str { + match kind { + TypeIdentityKind::Class => "class", + TypeIdentityKind::Delegate => "delegate", + TypeIdentityKind::Enum => "enum", + TypeIdentityKind::Interface => "interface", + TypeIdentityKind::Struct => "struct", } } -pub fn python_module_layout_installed() -> bool { - MODULE_LAYOUT.with(|layout| layout.borrow().is_some()) +fn legacy_projected_name(identity: &PythonTypeIdentity) -> String { + match identity { + TypeIdentity::Primitive { name } | TypeIdentity::Named { name, .. } => name.clone(), + TypeIdentity::ClosedGeneric { + name, arguments, .. + } => format!( + "{}_{}", + name.split('`').next().unwrap_or(name), + arguments + .iter() + .map(legacy_projected_name) + .collect::>() + .join("_") + ), + TypeIdentity::Array { element } => { + format!("Array_{}", legacy_projected_name(element)) + } + TypeIdentity::AsyncAction => "IAsyncAction".to_string(), + TypeIdentity::AsyncActionWithProgress { progress } => { + format!( + "IAsyncActionWithProgress_{}", + legacy_projected_name(progress) + ) + } + TypeIdentity::AsyncOperation { result } => { + format!("IAsyncOperation_{}", legacy_projected_name(result)) + } + TypeIdentity::AsyncOperationWithProgress { result, progress } => format!( + "IAsyncOperationWithProgress_{}_{}", + legacy_projected_name(result), + legacy_projected_name(progress) + ), + } } -pub fn install_python_module_layout( - identities: impl IntoIterator, -) -> Result { - let identities: HashSet<_> = identities.into_iter().collect(); - let mut counts = HashMap::::new(); - for identity in &identities { - *counts.entry(identity.name.clone()).or_default() += 1; +fn sanitize_symbol_component(value: &str) -> String { + let mut result = String::with_capacity(value.len()); + let mut previous_underscore = false; + for character in value.chars() { + if character.is_ascii_alphanumeric() { + result.push(character); + previous_underscore = false; + } else if !previous_underscore { + result.push('_'); + previous_underscore = true; + } + } + let result = result.trim_matches('_'); + if result.is_empty() { + return "Type".to_string(); } + if result.as_bytes()[0].is_ascii_digit() { + format!("_{result}") + } else { + result.to_string() + } +} - let mut modules = HashMap::new(); - let mut unique_modules = HashMap::new(); - let mut owners = HashMap::::new(); - for identity in identities { - let module = qualified_module_name(&identity.namespace, &identity.name); - if let Some(existing) = owners.insert(module.clone(), identity.clone()) { - return Err(format!( - "Python module name collision: `{}.{}` and `{}.{}` both normalize to `{module}.py`", - existing.namespace, existing.name, identity.namespace, identity.name - )); +fn semantic_qualifier(identity: &PythonTypeIdentity) -> String { + match identity { + TypeIdentity::Primitive { name } => sanitize_symbol_component(name), + TypeIdentity::Named { + kind, + namespace, + name, + } => sanitize_symbol_component(&format!( + "{}_{}_{}", + namespace, + name, + identity_kind_name(*kind) + )), + TypeIdentity::ClosedGeneric { + kind, + namespace, + name, + arguments, + } => sanitize_symbol_component(&format!( + "{}_{}_{}_{}", + namespace, + name, + identity_kind_name(*kind), + arguments + .iter() + .map(semantic_qualifier) + .collect::>() + .join("_") + )), + TypeIdentity::Array { element } => { + format!("Array_{}", semantic_qualifier(element)) + } + TypeIdentity::AsyncAction => "IAsyncAction".to_string(), + TypeIdentity::AsyncActionWithProgress { progress } => { + format!("IAsyncActionWithProgress_{}", semantic_qualifier(progress)) } - if counts[&identity.name] == 1 { - unique_modules.insert(identity.name.clone(), module.clone()); + TypeIdentity::AsyncOperation { result } => { + format!("IAsyncOperation_{}", semantic_qualifier(result)) } - modules.insert(identity, module); + TypeIdentity::AsyncOperationWithProgress { result, progress } => format!( + "IAsyncOperationWithProgress_{}_{}", + semantic_qualifier(result), + semantic_qualifier(progress) + ), } +} - MODULE_LAYOUT.with(|layout| { - *layout.borrow_mut() = Some(PythonModuleLayout { - modules, - unique_modules, - }); - }); - Ok(PythonModuleLayoutGuard) +pub fn python_identity_display_name(identity: &PythonTypeIdentity) -> String { + match identity { + TypeIdentity::Primitive { name } => name.clone(), + TypeIdentity::Named { + kind, + namespace, + name, + } => format!("{namespace}.{name} ({})", identity_kind_name(*kind)), + TypeIdentity::ClosedGeneric { + kind, + namespace, + name, + arguments, + } => format!( + "{}.{}<{}> ({})", + namespace, + name, + arguments + .iter() + .map(python_identity_display_name) + .collect::>() + .join(", "), + identity_kind_name(*kind) + ), + TypeIdentity::Array { element } => { + format!("{}[]", python_identity_display_name(element)) + } + TypeIdentity::AsyncAction => "Windows.Foundation.IAsyncAction".to_string(), + TypeIdentity::AsyncActionWithProgress { progress } => format!( + "Windows.Foundation.IAsyncActionWithProgress<{}>", + python_identity_display_name(progress) + ), + TypeIdentity::AsyncOperation { result } => format!( + "Windows.Foundation.IAsyncOperation<{}>", + python_identity_display_name(result) + ), + TypeIdentity::AsyncOperationWithProgress { result, progress } => format!( + "Windows.Foundation.IAsyncOperationWithProgress<{}, {}>", + python_identity_display_name(result), + python_identity_display_name(progress) + ), + } } -pub fn python_module_name(namespace: &str, name: &str) -> String { - MODULE_LAYOUT.with(|layout| { - layout - .borrow() - .as_ref() - .and_then(|layout| { - layout - .modules - .get(&PythonTypeIdentity { - namespace: namespace.to_string(), - name: name.to_string(), - }) - .cloned() - .or_else(|| layout.unique_modules.get(name).cloned()) +fn collect_named_identity_counts( + identity: &PythonTypeIdentity, + identities: &mut HashMap>, +) { + match identity { + TypeIdentity::Named { name, .. } => { + identities + .entry(name.clone()) + .or_default() + .insert(identity.clone()); + } + TypeIdentity::ClosedGeneric { arguments, .. } => { + for argument in arguments { + collect_named_identity_counts(argument, identities); + } + } + TypeIdentity::Array { element } => collect_named_identity_counts(element, identities), + TypeIdentity::AsyncActionWithProgress { progress } => { + collect_named_identity_counts(progress, identities) + } + TypeIdentity::AsyncOperation { result } => { + collect_named_identity_counts(result, identities) + } + TypeIdentity::AsyncOperationWithProgress { result, progress } => { + collect_named_identity_counts(result, identities); + collect_named_identity_counts(progress, identities); + } + TypeIdentity::Primitive { .. } | TypeIdentity::AsyncAction => {} + } +} + +fn qualified_argument_name( + identity: &PythonTypeIdentity, + ambiguous_named_types: &HashSet, +) -> String { + match identity { + TypeIdentity::Named { + kind, + namespace, + name, + } if ambiguous_named_types.contains(name) => sanitize_symbol_component(&format!( + "{}_{}_{}", + namespace, + name, + identity_kind_name(*kind) + )), + TypeIdentity::ClosedGeneric { + name, arguments, .. + } => format!( + "{}_{}", + name, + arguments + .iter() + .map(|argument| qualified_argument_name(argument, ambiguous_named_types)) + .collect::>() + .join("_") + ), + TypeIdentity::Array { element } => format!( + "Array_{}", + qualified_argument_name(element, ambiguous_named_types) + ), + _ => legacy_projected_name(identity), + } +} + +fn projected_names( + identities: &BTreeSet, + externally_ambiguous_named_types: &HashSet, +) -> HashMap { + let mut named_identity_counts = HashMap::>::new(); + for identity in identities { + collect_named_identity_counts(identity, &mut named_identity_counts); + } + let mut ambiguous_named_types = named_identity_counts + .into_iter() + .filter(|(_, identities)| identities.len() > 1) + .map(|(name, _)| name) + .collect::>(); + ambiguous_named_types.extend(externally_ambiguous_named_types.iter().cloned()); + + let mut groups = BTreeMap::>::new(); + for identity in identities { + groups + .entry(legacy_projected_name(identity)) + .or_default() + .push(identity); + } + + let mut result = HashMap::new(); + for (legacy_name, group) in groups { + let intrinsic_names = group + .iter() + .map(|identity| { + ( + *identity, + if matches!(identity, TypeIdentity::ClosedGeneric { .. }) { + qualified_argument_name(identity, &ambiguous_named_types) + } else { + legacy_projected_name(identity) + }, + ) }) - .unwrap_or_else(|| qualified_module_name(namespace, name)) - }) + .collect::>(); + let intrinsic_names_are_unique = intrinsic_names + .iter() + .map(|(_, name)| to_snake_case(name)) + .collect::>() + .len() + == intrinsic_names.len(); + if intrinsic_names_are_unique + && intrinsic_names.iter().any(|(_, name)| name != &legacy_name) + { + for (identity, name) in intrinsic_names { + result.insert(identity.clone(), name); + } + continue; + } + + let namespaces = group + .iter() + .filter_map(|identity| identity.namespace()) + .collect::>(); + let safely_separated_by_namespace = namespaces.len() == group.len() + && group.iter().all(|identity| identity.namespace().is_some()); + if group.len() == 1 || safely_separated_by_namespace { + for identity in group { + result.insert(identity.clone(), legacy_name.clone()); + } + continue; + } + + let mut candidate_owners = HashMap::::new(); + for identity in group { + let mut candidate = format!("{}_{}", legacy_name, semantic_qualifier(identity)); + let normalized = to_snake_case(&candidate); + if let Some(existing) = candidate_owners.get(&normalized) + && *existing != identity + { + candidate.push_str(&format!( + "_{:016x}", + stable_module_hash(&identity.canonical_key()) + )); + } + candidate_owners.insert(to_snake_case(&candidate), identity); + result.insert(identity.clone(), candidate); + } + } + result } -fn qualified_module_name(namespace: &str, name: &str) -> String { +fn qualified_module_name( + identity: &PythonTypeIdentity, + namespace: &str, + projected_name: &str, +) -> String { let namespace = python_namespace_segments(namespace).join("__"); - shorten_module_component(&if namespace.is_empty() { - to_snake_case(name) + let candidate = if namespace.is_empty() { + to_snake_case(projected_name) } else { - format!("{namespace}__{}", to_snake_case(name)) - }) + format!("{namespace}__{}", to_snake_case(projected_name)) + }; + shorten_module_component_with_hash_input(&candidate, &identity.canonical_key()) +} + +fn public_module_name(identity: &PythonTypeIdentity, projected_name: &str) -> String { + shorten_module_component_with_hash_input( + &to_snake_case(projected_name), + &identity.canonical_key(), + ) +} + +/// Explicit, immutable naming and lookup state for one Python projection. +#[derive(Clone, Debug, Default)] +pub struct PythonProjectionContext { + packaged: bool, + projections: HashMap, + aliases: HashMap, + compatibility_counts: HashMap, +} + +impl PythonProjectionContext { + pub fn new( + identities: impl IntoIterator, + packaged: bool, + ) -> Result { + Self::new_with_ambiguities(identities, packaged, std::iter::empty()) + } + + pub fn new_with_ambiguities( + identities: impl IntoIterator, + packaged: bool, + ambiguous_named_types: impl IntoIterator, + ) -> Result { + let identities = identities.into_iter().collect::>(); + let ambiguous_named_types = ambiguous_named_types.into_iter().collect::>(); + let projected_names = projected_names(&identities, &ambiguous_named_types); + let mut projected_name_counts = HashMap::::new(); + for name in projected_names.values() { + *projected_name_counts.entry(name.clone()).or_default() += 1; + } + let mut projections = HashMap::new(); + let mut aliases = HashMap::new(); + let mut compatibility_counts = HashMap::new(); + let mut module_owners = HashMap::::new(); + let mut public_module_owners = HashMap::::new(); + + for identity in &identities { + *compatibility_counts + .entry(legacy_projected_name(identity)) + .or_default() += 1; + if identity.kind() == Some(TypeIdentityKind::Delegate) { + aliases.insert( + identity.with_kind(TypeIdentityKind::Interface), + identity.clone(), + ); + } + } + + for identity in identities { + let namespace = identity.namespace().ok_or_else(|| { + format!( + "Python generated type identity must be named: {}", + python_identity_display_name(&identity) + ) + })?; + let projected_name = projected_names[&identity].clone(); + let public_module = public_module_name(&identity, &projected_name); + let compatibility_name = legacy_projected_name(&identity); + let reference_name = if projected_name_counts + .get(&projected_name) + .copied() + .unwrap_or_default() + > 1 + || (ambiguous_named_types.contains(&compatibility_name) + && matches!(identity, TypeIdentity::Named { .. })) + { + semantic_qualifier(&identity) + } else { + projected_name.clone() + }; + let implementation_module = if packaged + || matches!( + identity, + TypeIdentity::Named { + kind: TypeIdentityKind::Class + | TypeIdentityKind::Enum + | TypeIdentityKind::Interface + | TypeIdentityKind::Struct, + .. + } + ) { + qualified_module_name(&identity, namespace, &projected_name) + } else { + public_module.clone() + }; + + if let Some(existing) = + module_owners.insert(implementation_module.clone(), identity.clone()) + && existing != identity + { + return Err(format!( + "Python implementation module collision: `{}` and `{}` both normalize to \ + `{implementation_module}.py`", + python_identity_display_name(&existing), + python_identity_display_name(&identity) + )); + } + let public_key = format!( + "{}/{}", + python_namespace_segments(namespace).join("/"), + public_module + ); + if let Some(existing) = + public_module_owners.insert(public_key.clone(), identity.clone()) + && existing != identity + { + return Err(format!( + "Python public module collision: `{}` and `{}` both normalize to \ + `{public_key}.py`", + python_identity_display_name(&existing), + python_identity_display_name(&identity) + )); + } + + projections.insert( + identity, + PythonProjection { + implementation_module, + projected_name, + public_module, + reference_name, + }, + ); + } + + Ok(Self { + packaged, + projections, + aliases, + compatibility_counts, + }) + } + + pub fn packaged( + identities: impl IntoIterator, + ) -> Result { + Self::new(identities, true) + } + + pub fn packaged_with_ambiguities( + identities: impl IntoIterator, + ambiguous_named_types: impl IntoIterator, + ) -> Result { + Self::new_with_ambiguities(identities, true, ambiguous_named_types) + } + + pub fn standalone( + identities: impl IntoIterator, + ) -> Result { + Self::new(identities, false) + } + + pub fn is_packaged(&self) -> bool { + self.packaged + } + + pub fn normalize_identity(&self, identity: &PythonTypeIdentity) -> PythonTypeIdentity { + let identity = match identity { + TypeIdentity::ClosedGeneric { + kind, + namespace, + name, + arguments, + } => TypeIdentity::closed_generic( + *kind, + namespace.clone(), + name.clone(), + arguments + .iter() + .map(|argument| self.normalize_identity(argument)), + ), + TypeIdentity::Array { element } => TypeIdentity::Array { + element: Box::new(self.normalize_identity(element)), + }, + TypeIdentity::AsyncActionWithProgress { progress } => { + TypeIdentity::AsyncActionWithProgress { + progress: Box::new(self.normalize_identity(progress)), + } + } + TypeIdentity::AsyncOperation { result } => TypeIdentity::AsyncOperation { + result: Box::new(self.normalize_identity(result)), + }, + TypeIdentity::AsyncOperationWithProgress { result, progress } => { + TypeIdentity::AsyncOperationWithProgress { + result: Box::new(self.normalize_identity(result)), + progress: Box::new(self.normalize_identity(progress)), + } + } + _ => identity.clone(), + }; + self.aliases.get(&identity).cloned().unwrap_or(identity) + } + + pub fn identity_for_type(&self, typ: &TypeMeta) -> PythonTypeIdentity { + self.normalize_identity(&typ.type_identity()) + } + + pub fn contains_identity(&self, identity: &PythonTypeIdentity) -> bool { + self.projections + .contains_key(&self.normalize_identity(identity)) + } + + pub fn is_known_type(&self, typ: &TypeMeta) -> bool { + self.contains_identity(&typ.type_identity()) + } + + pub fn known_full_names(&self) -> HashSet { + self.projections + .keys() + .filter_map(|identity| { + Some(format!( + "{}.{}", + identity.namespace()?, + identity.definition_name()? + )) + }) + .collect() + } + + pub fn is_known_ref(&self, reference: &TypeRef) -> bool { + let kind = match reference.kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + self.contains_identity(&TypeIdentity::named( + kind, + reference.namespace.clone(), + reference.name.clone(), + )) + } + + pub fn is_delegate_type(&self, typ: &TypeMeta) -> bool { + self.identity_for_type(typ).kind() == Some(TypeIdentityKind::Delegate) + } + + pub fn projected_name(&self, identity: &PythonTypeIdentity) -> String { + let identity = self.normalize_identity(identity); + self.projections + .get(&identity) + .map(|projection| projection.projected_name.clone()) + .unwrap_or_else(|| legacy_projected_name(&identity)) + } + + pub fn compatibility_name(&self, identity: &PythonTypeIdentity) -> String { + legacy_projected_name(&self.normalize_identity(identity)) + } + + pub fn projected_name_for_type(&self, typ: &TypeMeta) -> String { + self.projected_name(&self.identity_for_type(typ)) + } + + pub fn projected_name_for_interface(&self, interface: &InterfaceMeta) -> String { + self.projected_name(&interface.type_identity()) + } + + pub fn reference_name(&self, identity: &PythonTypeIdentity) -> String { + let identity = self.normalize_identity(identity); + self.projections + .get(&identity) + .map(|projection| projection.reference_name.clone()) + .unwrap_or_else(|| self.projected_name(&identity)) + } + + pub fn reference_name_for_type(&self, typ: &TypeMeta) -> String { + self.reference_name(&self.identity_for_type(typ)) + } + + pub fn implementation_module(&self, identity: &PythonTypeIdentity) -> String { + let identity = self.normalize_identity(identity); + self.projections + .get(&identity) + .map(|projection| projection.implementation_module.clone()) + .unwrap_or_else(|| { + let projected_name = legacy_projected_name(&identity); + if self.packaged + || matches!( + identity, + TypeIdentity::Named { + kind: TypeIdentityKind::Class + | TypeIdentityKind::Enum + | TypeIdentityKind::Interface + | TypeIdentityKind::Struct, + .. + } + ) + { + qualified_module_name( + &identity, + identity.namespace().unwrap_or_default(), + &projected_name, + ) + } else { + public_module_name(&identity, &projected_name) + } + }) + } + + pub fn implementation_module_for_type(&self, typ: &TypeMeta) -> String { + self.implementation_module(&self.identity_for_type(typ)) + } + + pub fn implementation_module_for_named( + &self, + kind: TypeIdentityKind, + namespace: &str, + name: &str, + ) -> String { + self.implementation_module(&TypeIdentity::named(kind, namespace, name)) + } + + pub fn implementation_module_for_interface(&self, interface: &InterfaceMeta) -> String { + self.implementation_module(&interface.type_identity()) + } + + pub fn public_qualified_module(&self, identity: &PythonTypeIdentity) -> String { + let identity = self.normalize_identity(identity); + let mut segments = python_namespace_segments(identity.namespace().unwrap_or_default()); + let module = self + .projections + .get(&identity) + .map(|projection| projection.public_module.clone()) + .unwrap_or_else(|| public_module_name(&identity, &legacy_projected_name(&identity))); + segments.push(module); + segments.join(".") + } + + pub fn public_module(&self, identity: &PythonTypeIdentity) -> String { + self.public_qualified_module(identity) + .rsplit('.') + .next() + .unwrap_or_default() + .to_string() + } + + pub fn root_name_is_unambiguous(&self, identity: &PythonTypeIdentity) -> bool { + self.compatibility_counts + .get(&legacy_projected_name(identity)) + .copied() + .unwrap_or_default() + == 1 + } } pub fn python_namespace_segments(namespace: &str) -> Vec { @@ -239,13 +835,7 @@ pub(crate) fn is_py_reserved(s: &str) -> bool { /// Convert a PascalCase name to a snake_case Python filename (without extension). pub fn to_snake_case_filename(name: &str) -> String { - MODULE_LAYOUT.with(|layout| { - layout - .borrow() - .as_ref() - .and_then(|layout| layout.unique_modules.get(name).cloned()) - .unwrap_or_else(|| shorten_module_component(&to_snake_case(name))) - }) + shorten_module_component(&to_snake_case(name)) } #[cfg(test)] @@ -290,18 +880,15 @@ mod tests { } #[test] - fn installed_layout_shortens_implementation_and_public_modules_consistently() { + fn projection_context_shortens_implementation_and_public_modules_consistently() { let name = "TypedEventHandler_MediaPlaybackCommandManager_MediaPlaybackCommandManagerAutoRepeatModeReceivedEventArgsAdditionalCompatibilitySuffix"; - let _guard = install_python_module_layout([PythonTypeIdentity { - namespace: "Windows.Foundation".into(), - name: name.into(), - }]) - .unwrap(); - let implementation = python_module_name("Windows.Foundation", name); + let identity = TypeIdentity::named(TypeIdentityKind::Delegate, "Windows.Foundation", name); + let context = PythonProjectionContext::packaged([identity.clone()]).unwrap(); + let implementation = context.implementation_module(&identity); assert!(implementation.chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH); - assert_eq!(to_snake_case_filename(name), implementation); + assert_eq!(implementation, context.implementation_module(&identity)); assert!( - python_public_module_name(name).chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH + context.public_module(&identity).chars().count() <= MAX_PYTHON_MODULE_COMPONENT_LENGTH ); } @@ -320,16 +907,10 @@ mod tests { } #[test] - fn module_layout_collision_detection_uses_normalized_names() { - let err = install_python_module_layout([ - PythonTypeIdentity { - namespace: "Example".into(), - name: "UInt32".into(), - }, - PythonTypeIdentity { - namespace: "Example".into(), - name: "Uint32".into(), - }, + fn projection_context_collision_detection_uses_normalized_names() { + let err = PythonProjectionContext::packaged([ + TypeIdentity::named(TypeIdentityKind::Interface, "Example", "UInt32"), + TypeIdentity::named(TypeIdentityKind::Interface, "Example", "Uint32"), ]) .err() .expect("normalized module name collision should fail"); @@ -340,28 +921,201 @@ mod tests { } #[test] - fn missing_layout_identity_keeps_namespace_qualification() { - let _layout = install_python_module_layout([PythonTypeIdentity { - namespace: "Microsoft.UI.Dispatching".into(), - name: "Other".into(), - }]) + fn missing_context_identity_keeps_namespace_qualification() { + let context = PythonProjectionContext::packaged([TypeIdentity::named( + TypeIdentityKind::Class, + "Microsoft.UI.Dispatching", + "Other", + )]) .unwrap(); assert_eq!( - python_module_name("Windows.System", "DispatcherQueue"), + context.implementation_module(&TypeIdentity::named( + TypeIdentityKind::Class, + "Windows.System", + "DispatcherQueue", + )), "windows__system__dispatcher_queue" ); } #[test] - fn missing_identity_reuses_unique_compatible_name() { - let _layout = install_python_module_layout([PythonTypeIdentity { - namespace: "Microsoft.Graphics.DirectX".into(), - name: "DirectXPixelFormat".into(), - }]) + fn same_short_named_types_keep_namespace_facade_names_and_distinct_modules() { + let left = TypeIdentity::named(TypeIdentityKind::Interface, "Example.Left", "IValue"); + let right = TypeIdentity::named(TypeIdentityKind::Interface, "Example.Right", "IValue"); + let context = PythonProjectionContext::packaged([left.clone(), right.clone()]).unwrap(); + + assert_eq!(context.projected_name(&left), "IValue"); + assert_eq!(context.projected_name(&right), "IValue"); + assert_ne!( + context.implementation_module(&left), + context.implementation_module(&right) + ); + assert!(!context.root_name_is_unambiguous(&left)); + assert!(!context.root_name_is_unambiguous(&right)); + } + + #[test] + fn same_short_closed_generics_use_distinct_reference_aliases() { + let closed = |namespace: &str| { + TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + namespace, + "IBox", + [TypeIdentity::Primitive { + name: "String".into(), + }], + ) + }; + let left = closed("Example.Left"); + let right = closed("Example.Right"); + let context = PythonProjectionContext::packaged([left.clone(), right.clone()]).unwrap(); + + assert_eq!(context.projected_name(&left), "IBox_String"); + assert_eq!(context.projected_name(&right), "IBox_String"); + assert_ne!( + context.reference_name(&left), + context.reference_name(&right) + ); + } + + #[test] + fn closed_generic_names_preserve_nested_semantic_identity() { + let point = |namespace| TypeIdentity::named(TypeIdentityKind::Struct, namespace, "Point"); + let vector = |argument| { + TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IVector", + [argument], + ) + }; + let left = vector(point("Example.Left")); + let right = vector(point("Example.Right")); + let nested_left = vector(left.clone()); + let nested_right = vector(right.clone()); + let context = PythonProjectionContext::packaged([ + left.clone(), + right.clone(), + nested_left.clone(), + nested_right.clone(), + ]) + .unwrap(); + + assert_ne!( + context.projected_name(&left), + context.projected_name(&right) + ); + assert_ne!( + context.projected_name(&nested_left), + context.projected_name(&nested_right) + ); + assert_ne!( + context.implementation_module(&nested_left), + context.implementation_module(&nested_right) + ); + } + + #[test] + fn metadata_ambiguity_keeps_phased_generic_names_stable() { + let closed = |namespace: &str| { + TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Example.Collections", + "IBox", + [TypeIdentity::named( + TypeIdentityKind::Struct, + namespace, + "Point", + )], + ) + }; + let left = closed("Example.Left"); + let right = closed("Example.Right"); + let left_phase = PythonProjectionContext::packaged_with_ambiguities( + [left.clone()], + ["Point".to_string()], + ) + .unwrap(); + let right_phase = PythonProjectionContext::packaged_with_ambiguities( + [right.clone()], + ["Point".to_string()], + ) .unwrap(); + let combined = PythonProjectionContext::packaged_with_ambiguities( + [left.clone(), right.clone()], + ["Point".to_string()], + ) + .unwrap(); + + assert_eq!( + left_phase.projected_name(&left), + combined.projected_name(&left) + ); assert_eq!( - python_module_name("Windows.Graphics.DirectX", "DirectXPixelFormat"), - "microsoft__graphics__direct_x__direct_x_pixel_format" + right_phase.projected_name(&right), + combined.projected_name(&right) + ); + assert_ne!( + left_phase.projected_name(&left), + right_phase.projected_name(&right) ); } + + #[test] + fn ordinary_closed_generic_names_remain_compatible() { + let reference = TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + "Windows.Foundation", + "IReference", + [TypeIdentity::Primitive { + name: "UInt32".into(), + }], + ); + let context = PythonProjectionContext::packaged([reference.clone()]).unwrap(); + + assert_eq!(context.projected_name(&reference), "IReference_UInt32"); + assert_eq!( + context.implementation_module(&reference), + "windows__foundation__i_reference_uint32" + ); + } + + #[test] + fn canonical_hash_input_is_stable_and_kind_sensitive() { + let interface = TypeIdentity::named(TypeIdentityKind::Interface, "Example", "Value"); + let runtime_class = TypeIdentity::named(TypeIdentityKind::Class, "Example", "Value"); + + assert_eq!(interface.canonical_key(), interface.clone().canonical_key()); + assert_ne!(interface.canonical_key(), runtime_class.canonical_key()); + assert_ne!(interface, runtime_class); + } + + #[test] + fn closed_generic_projection_identity_does_not_replace_abi_identity() { + let point = |namespace: &str| TypeMeta::Struct { + namespace: namespace.into(), + name: "Point".into(), + fields: vec![], + }; + let interface = |argument: TypeMeta| InterfaceMeta { + name: "IBox_Point".into(), + namespace: "Example.Collections".into(), + iid: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(), + generic_piid: Some("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into()), + generic_name: Some("IBox`1".into()), + generic_args: vec![argument], + ..Default::default() + }; + let left = interface(point("Example.Left")); + let right = interface(point("Example.Right")); + + assert_ne!(left.type_identity(), right.type_identity()); + let left_abi = + crate::codegen::winrt::python::signature::py_interface_iid_expr(&left).unwrap(); + let right_abi = + crate::codegen::winrt::python::signature::py_interface_iid_expr(&right).unwrap(); + assert_ne!(left_abi, right_abi); + assert!(left_abi.contains("Example.Left.Point")); + assert!(right_abi.contains("Example.Right.Point")); + } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs index 9264aed4..98e25700 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/signature.rs @@ -3,29 +3,45 @@ //! Python method signatures, argument wrapping, and return conversion. -use std::collections::HashSet; - use crate::meta::{InterfaceMeta, MethodMeta, ParamDirection}; -use crate::types::TypeMeta; +use crate::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; -use super::naming::{python_module_name, to_snake_case, to_snake_case_filename}; +use super::naming::{PythonProjectionContext, to_snake_case}; 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; -pub(crate) fn py_runtime_symbol(type_name: &str, symbol_name: &str) -> String { +pub(crate) fn py_runtime_symbol( + context: &PythonProjectionContext, + identity: &TypeIdentity, + symbol_name: &str, +) -> String { format!( "_dynwinrt_symbol('{}', '{}')", - to_snake_case_filename(type_name), + context.implementation_module(identity), symbol_name ) } -fn py_runtime_namespaced_symbol(namespace: &str, type_name: &str, symbol_name: &str) -> String { - format!( - "_dynwinrt_symbol('{}', '{}')", - python_module_name(namespace, type_name), - symbol_name +pub(crate) fn py_runtime_type_symbol( + context: &PythonProjectionContext, + typ: &TypeMeta, + symbol_name: &str, +) -> String { + py_runtime_symbol(context, &context.identity_for_type(typ), symbol_name) +} + +pub(crate) fn py_runtime_named_symbol( + context: &PythonProjectionContext, + kind: TypeIdentityKind, + namespace: &str, + type_name: &str, + symbol_name: &str, +) -> String { + py_runtime_symbol( + context, + &TypeIdentity::named(kind, namespace, type_name), + symbol_name, ) } @@ -490,11 +506,15 @@ fn py_wrap_collection(name: &str, typ: &TypeMeta) -> Option { None } -pub(crate) fn py_type_guard(name: &str, typ: &TypeMeta, known_types: &HashSet) -> String { +pub(crate) fn py_type_guard( + name: &str, + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> String { if let Some(inner) = ireference_inner_type(typ) { return format!( "({name} is None or {})", - py_type_guard(name, inner, known_types) + py_type_guard(name, inner, context) ); } @@ -531,9 +551,15 @@ pub(crate) fn py_type_guard(name: &str, typ: &TypeMeta, known_types: &HashSet format!( + } if context.is_known_type(typ) => format!( "isinstance({name}, {})", - py_runtime_namespaced_symbol(namespace, type_name, type_name) + py_runtime_named_symbol( + context, + TypeIdentityKind::Enum, + namespace, + type_name, + type_name + ) ), TypeMeta::Enum { .. } => py_exact_int_guard(name), TypeMeta::Array(_) => format!( @@ -545,9 +571,10 @@ pub(crate) fn py_type_guard(name: &str, typ: &TypeMeta, known_types: &HashSet { format!("isinstance({name}, timedelta)") } - TypeMeta::Struct { - name: type_name, .. - } => format!("isinstance({name}, {type_name})"), + TypeMeta::Struct { .. } => format!( + "isinstance({name}, {})", + context.reference_name_for_type(typ) + ), typ @ TypeMeta::RuntimeClass { .. } if py_runtime_class_iid_const(typ).is_some() => { let (iid, _) = py_runtime_class_iid_const(typ).expect("checked above"); format!("_dynwinrt_can_cast({name}, {iid})") @@ -556,17 +583,29 @@ pub(crate) fn py_type_guard(name: &str, typ: &TypeMeta, known_types: &HashSet format!( + } if context.is_known_type(typ) => format!( "isinstance({name}, {})", - py_runtime_namespaced_symbol(namespace, type_name, type_name) + py_runtime_named_symbol( + context, + TypeIdentityKind::Class, + namespace, + type_name, + type_name + ) ), TypeMeta::Interface { namespace, name: type_name, .. - } if known_types.contains(type_name) => format!( + } if context.is_known_type(typ) => format!( "isinstance({name}, {})", - py_runtime_namespaced_symbol(namespace, type_name, type_name) + py_runtime_named_symbol( + context, + TypeIdentityKind::Interface, + namespace, + type_name, + type_name + ) ), TypeMeta::Object | TypeMeta::Delegate { .. } @@ -584,14 +623,14 @@ pub(crate) fn py_convert_return( expr: &str, return_type: Option<&TypeMeta>, is_async: bool, - known_types: &HashSet, + context: &PythonProjectionContext, ) -> String { if is_async { return py_wrap_async( expr, return_type.expect("async conversion requires a return type"), None, - known_types, + context, ); } match return_type { @@ -606,32 +645,32 @@ 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(TypeMeta::Enum { - namespace, name, .. - }) if known_types.contains(name) => { + Some(typ @ TypeMeta::Enum { name, .. }) if context.is_known_type(typ) => { + let TypeMeta::Enum { name, .. } = typ else { + unreachable!() + }; format!( "_dynwinrt_enum('{}', '{}', {}.to_number())", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), name, expr ) } Some(TypeMeta::Enum { .. }) => format!("{}.to_number()", expr), - Some(typ @ TypeMeta::Parameterized { name, args, .. }) - if ireference_inner_type(typ).is_some() => - { - let concrete = crate::meta::make_parameterized_name(name, args); - let wrapper = py_runtime_symbol(&concrete, &concrete); + Some(typ @ TypeMeta::Parameterized { .. }) if ireference_inner_type(typ).is_some() => { + let concrete = context.projected_name_for_type(typ); + let wrapper = py_runtime_type_symbol(context, typ, &concrete); format!( "(lambda value: None if value.is_null() else {}(value).value)({})", wrapper, expr ) } - Some(TypeMeta::RuntimeClass { - namespace, name, .. - }) if known_types.contains(name) => { - let wrapper = py_runtime_namespaced_symbol(namespace, name, name); + 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); format!( "(lambda value: None if value.is_null() else {}._from_native(value))({})", wrapper, expr @@ -645,10 +684,9 @@ pub(crate) fn py_convert_return( expr ) } - Some(TypeMeta::Interface { - namespace, name, .. - }) if known_types.contains(name) => { - let wrapper = py_runtime_namespaced_symbol(namespace, name, name); + Some(typ @ TypeMeta::Interface { .. }) if context.is_known_type(typ) => { + let projected_name = context.projected_name_for_type(typ); + let wrapper = py_runtime_type_symbol(context, typ, &projected_name); format!( "(lambda value: None if value.is_null() else {}(value))({})", wrapper, expr @@ -660,10 +698,10 @@ pub(crate) fn py_convert_return( expr ) } - Some(TypeMeta::Parameterized { name, args, .. }) => { - let concrete = crate::meta::make_parameterized_name(name, args); - if known_types.contains(&concrete) { - let wrapper = py_runtime_symbol(&concrete, &concrete); + Some(typ @ TypeMeta::Parameterized { .. }) => { + let concrete = context.projected_name_for_type(typ); + if context.is_known_type(typ) { + let wrapper = py_runtime_type_symbol(context, typ, &concrete); format!( "(lambda value: None if value.is_null() else {}(value))({})", wrapper, expr @@ -677,16 +715,16 @@ pub(crate) fn py_convert_return( } Some(TypeMeta::Array(inner)) => { let arr_expr = format!("{}.as_array()", expr); - py_convert_array_return(&arr_expr, inner, known_types) + py_convert_array_return(&arr_expr, inner, context) } _ => expr.to_string(), } } -fn py_value_converter(typ: &TypeMeta, known_types: &HashSet) -> String { +fn py_value_converter(typ: &TypeMeta, context: &PythonProjectionContext) -> String { format!( "lambda value: {}", - py_convert_return("value", Some(typ), false, known_types) + py_convert_return("value", Some(typ), false, context) ) } @@ -694,9 +732,9 @@ pub(crate) fn py_wrap_async( expr: &str, async_type: &TypeMeta, result_converter: Option, - known_types: &HashSet, + context: &PythonProjectionContext, ) -> String { - py_wrap_async_with_converters(expr, async_type, result_converter, None, known_types) + py_wrap_async_with_converters(expr, async_type, result_converter, None, context) } pub(crate) fn py_wrap_async_with_converters( @@ -704,7 +742,7 @@ pub(crate) fn py_wrap_async_with_converters( async_type: &TypeMeta, result_converter: Option, progress_converter: Option, - known_types: &HashSet, + context: &PythonProjectionContext, ) -> String { match async_type { TypeMeta::AsyncAction => format!( @@ -715,19 +753,19 @@ pub(crate) fn py_wrap_async_with_converters( TypeMeta::AsyncOperation(result) => format!( "_dynwinrt_track_projected(_DynWinRTAsync({}, {}), 'WinRTAsync')", expr, - result_converter.unwrap_or_else(|| py_value_converter(result, known_types)) + result_converter.unwrap_or_else(|| py_value_converter(result, context)) ), TypeMeta::AsyncActionWithProgress(progress) => format!( "_dynwinrt_track_projected(_DynWinRTAsyncWithProgress({}, {}, {}), 'WinRTAsyncWithProgress')", expr, result_converter.unwrap_or_else(|| "lambda _value: None".to_string()), - progress_converter.unwrap_or_else(|| py_value_converter(progress, known_types)) + progress_converter.unwrap_or_else(|| py_value_converter(progress, context)) ), TypeMeta::AsyncOperationWithProgress(result, progress) => format!( "_dynwinrt_track_projected(_DynWinRTAsyncWithProgress({}, {}, {}), 'WinRTAsyncWithProgress')", expr, - result_converter.unwrap_or_else(|| py_value_converter(result, known_types)), - progress_converter.unwrap_or_else(|| py_value_converter(progress, known_types)) + result_converter.unwrap_or_else(|| py_value_converter(result, context)), + progress_converter.unwrap_or_else(|| py_value_converter(progress, context)) ), _ => panic!("py_wrap_async requires an async type: {:?}", async_type), } @@ -737,7 +775,7 @@ pub(crate) fn py_wrap_async_with_converters( pub(crate) fn py_convert_array_return( arr_expr: &str, inner: &TypeMeta, - known_types: &HashSet, + context: &PythonProjectionContext, ) -> String { match inner { TypeMeta::I8 => format!("{}.to_i8_list()", arr_expr), @@ -745,11 +783,9 @@ pub(crate) fn py_convert_array_return( TypeMeta::I16 => format!("{}.to_i16_list()", arr_expr), TypeMeta::U16 | TypeMeta::Char16 => format!("{}.to_u16_list()", arr_expr), TypeMeta::I32 => format!("{}.to_i32_list()", arr_expr), - TypeMeta::Enum { - namespace, name, .. - } if known_types.contains(name) => format!( + typ @ TypeMeta::Enum { name, .. } if context.is_known_type(typ) => format!( "[_dynwinrt_enum('{}', '{}', value) for value in {}.to_i32_list()]", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), name, arr_expr ), @@ -771,32 +807,29 @@ pub(crate) fn py_convert_array_return( to_snake_case(name), arr_expr ), - TypeMeta::RuntimeClass { - namespace, name, .. - } if known_types.contains(name) => { + typ @ TypeMeta::RuntimeClass { name, .. } if context.is_known_type(typ) => { format!( "_dynwinrt_wrap_values('{}', '{}', {}.to_values())", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), name, arr_expr ) } - TypeMeta::Interface { - namespace, name, .. - } if known_types.contains(name) => { + typ @ TypeMeta::Interface { .. } if context.is_known_type(typ) => { + let projected_name = context.projected_name_for_type(typ); format!( "_dynwinrt_wrap_values('{}', '{}', {}.to_values())", - python_module_name(namespace, name), - name, + context.implementation_module_for_type(typ), + projected_name, arr_expr ) } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); - if known_types.contains(&concrete) { + typ @ TypeMeta::Parameterized { .. } => { + let concrete = context.projected_name_for_type(typ); + if context.is_known_type(typ) { format!( "_dynwinrt_wrap_values('{}', '{}', {}.to_values())", - to_snake_case_filename(&concrete), + context.implementation_module_for_type(typ), concrete, arr_expr ) @@ -816,13 +849,17 @@ pub(crate) fn py_convert_array_return( } /// Generate a Python `_IFoo = DynWinRTType.register_interface(...)` block. -pub(crate) fn py_generate_interface_registration(iface: &InterfaceMeta, var_name: &str) -> String { +pub(crate) fn py_generate_interface_registration( + iface: &InterfaceMeta, + var_name: &str, + symbol_name: &str, +) -> String { let mut out = String::new(); out.push_str(&format!( "{} = DynWinRTType.register_interface(\n", var_name )); - out.push_str(&format!(" \"{}\", IID_{}) \\\n", iface.name, iface.name)); + out.push_str(&format!(" \"{}\", IID_{symbol_name}) \\\n", iface.name)); for (i, method) in iface.methods.iter().enumerate() { let trailing = if i + 1 < iface.methods.len() { " \\" @@ -871,7 +908,7 @@ mod tests { fn runtime_class_inputs_cast_to_the_expected_interface() { let geometry = geometry_type(); assert_eq!( - py_type_guard("value", &geometry, &HashSet::from(["Geometry".into()])), + py_type_guard("value", &geometry, &PythonProjectionContext::default()), "_dynwinrt_can_cast(value, IID_ARG_Microsoft_UI_Xaml_Media_Geometry)" ); assert_eq!( @@ -891,17 +928,17 @@ mod tests { #[test] fn python_numeric_overload_integer_guards_use_exact_ranges() { - let known = HashSet::new(); + let context = PythonProjectionContext::default(); assert_eq!( - py_type_guard("value", &TypeMeta::I8, &known), + py_type_guard("value", &TypeMeta::I8, &context), "isinstance(value, int) and not isinstance(value, bool) and not isinstance(value, __import__('enum').Enum) and -128 <= value <= 127" ); assert_eq!( - py_type_guard("value", &TypeMeta::U8, &known), + py_type_guard("value", &TypeMeta::U8, &context), "isinstance(value, int) and not isinstance(value, bool) and not isinstance(value, __import__('enum').Enum) and 0 <= value <= 255" ); assert_eq!( - py_type_guard("value", &TypeMeta::U64, &known), + py_type_guard("value", &TypeMeta::U64, &context), format!( "isinstance(value, int) and not isinstance(value, bool) and not isinstance(value, __import__('enum').Enum) and 0 <= value <= {}", u64::MAX @@ -911,26 +948,35 @@ mod tests { #[test] fn python_numeric_overload_float_guards_reject_enum_instances() { - let known = HashSet::new(); + let context = PythonProjectionContext::default(); assert_eq!( - py_type_guard("value", &TypeMeta::F64, &known), + py_type_guard("value", &TypeMeta::F64, &context), "isinstance(value, (int, float)) and not isinstance(value, bool) and not isinstance(value, __import__('enum').Enum)" ); } #[test] fn python_known_enum_guards_are_precise_and_unknown_enums_fail_closed() { - let known = HashSet::from(["Mode".to_string()]); + let mode = enum_type("Mode", false); + let context = PythonProjectionContext::packaged([mode.type_identity()]).unwrap(); assert_eq!( - py_type_guard("value", &enum_type("Mode", false), &known), + py_type_guard("value", &mode, &context), "isinstance(value, _dynwinrt_symbol('contoso__mode', 'Mode'))" ); assert_eq!( - py_type_guard("value", &enum_type("Mode", false), &HashSet::new()), + py_type_guard( + "value", + &enum_type("Mode", false), + &PythonProjectionContext::default() + ), "isinstance(value, int) and not isinstance(value, bool) and not isinstance(value, __import__('enum').Enum)" ); assert_eq!( - py_type_guard("value", &enum_type("Options", true), &HashSet::new()), + py_type_guard( + "value", + &enum_type("Options", true), + &PythonProjectionContext::default() + ), "isinstance(value, int) and not isinstance(value, bool) and not isinstance(value, __import__('enum').Enum)" ); } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs index b0b7fc38..97d7f538 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::{python_module_name, to_snake_case}; +use super::naming::{PythonProjectionContext, to_snake_case}; use super::native_types::{FoundationType, foundation_type}; use super::signature::{py_runtime_symbol, py_wrap_arg}; use super::type_helpers::py_optional_type; @@ -16,15 +16,16 @@ use crate::codegen::winrt::shared::imports::ireference_inner_type; // ====================================================================== /// Python struct field getter expression. -pub(crate) fn py_struct_field_getter(typ: &TypeMeta, index: usize) -> String { +pub(crate) fn py_struct_field_getter( + context: &PythonProjectionContext, + typ: &TypeMeta, + index: usize, +) -> String { if let Some(_inner) = ireference_inner_type(typ) { - let TypeMeta::Parameterized { name, args, .. } = typ else { - unreachable!() - }; - let concrete = crate::meta::make_parameterized_name(name, args); + let concrete = context.projected_name_for_type(typ); return format!( "(lambda value: None if value.is_null() else {}(value).value)(s.get_object({}))", - py_runtime_symbol(&concrete, &concrete), + py_runtime_symbol(context, &context.identity_for_type(typ), &concrete), index ); } @@ -45,15 +46,12 @@ pub(crate) fn py_struct_field_getter(typ: &TypeMeta, index: usize) -> String { TypeMeta::String => format!("s.get_hstring({})", index), TypeMeta::Guid => format!("_dynwinrt_uuid(s.get_guid({}))", index), TypeMeta::Enum { - namespace, - name, - underlying, - .. + name, underlying, .. } => format!( "_dynwinrt_enum('{}', '{}', {})", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), name, - py_struct_field_getter(underlying, index) + py_struct_field_getter(context, underlying, index) ), TypeMeta::Struct { name, .. } if name == "HResult" => format!("s.get_i32({})", index), TypeMeta::Struct { name, .. } => format!( @@ -103,23 +101,23 @@ pub(crate) fn py_struct_field_setter(typ: &TypeMeta, index: usize, value_expr: & } /// Python type annotation for a struct field. -pub(crate) fn py_struct_field_type(typ: &TypeMeta) -> String { +pub(crate) fn py_struct_field_type(context: &PythonProjectionContext, typ: &TypeMeta) -> String { if let Some(inner) = ireference_inner_type(typ) { - let TypeMeta::Parameterized { name, args, .. } = typ else { - unreachable!() - }; - let native = py_optional_type(py_struct_field_read_type(inner)); - let wrapper = crate::meta::make_parameterized_name(name, args); + let native = py_optional_type(py_struct_field_read_type(context, inner)); + let wrapper = context.reference_name_for_type(typ); return format!("{native} | {wrapper}"); } - py_struct_field_read_type(typ) + py_struct_field_read_type(context, typ) } /// Python read annotation for a struct field. -pub(crate) fn py_struct_field_read_type(typ: &TypeMeta) -> String { +pub(crate) fn py_struct_field_read_type( + context: &PythonProjectionContext, + typ: &TypeMeta, +) -> String { if let Some(inner) = ireference_inner_type(typ) { - return py_optional_type(py_struct_field_read_type(inner)); + return py_optional_type(py_struct_field_read_type(context, inner)); } match typ { @@ -136,7 +134,7 @@ pub(crate) fn py_struct_field_read_type(typ: &TypeMeta) -> String { | TypeMeta::U64 => "int".to_string(), TypeMeta::Char16 => "str".to_string(), TypeMeta::F32 | TypeMeta::F64 => "float".to_string(), - TypeMeta::Enum { name, .. } => format!("'{}'", name), + TypeMeta::Enum { .. } => format!("'{}'", context.reference_name_for_type(typ)), TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(), typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(), typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(), 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 e7d34bcd..9060f200 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs @@ -3,13 +3,11 @@ //! Rendering helpers for Python type stubs. -use std::collections::HashSet; - use crate::codegen::winrt::shared::imports::get_in_params; use crate::meta::MethodMeta; -use crate::types::{FieldMeta, TypeKind, TypeMeta}; +use crate::types::{FieldMeta, TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta}; -use super::naming::{python_module_name, to_snake_case}; +use super::naming::{PythonProjectionContext, 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::{ @@ -18,14 +16,51 @@ use super::type_helpers::{ }; use crate::codegen::winrt::shared::imports::ireference_inner_type; -pub(super) fn format_py_type_import(namespace: &str, name: &str, kind: TypeKind) -> String { - let module = python_module_name(namespace, name); +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 IID_{name}, {name} # noqa: F401\n") + 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 {name}, {name}Like # noqa: F401\n") + 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 {name} # noqa: F401\n") + format!( + "from .{module} import {} # noqa: F401\n", + imported(&projected_name, &reference_name) + ) } } @@ -49,19 +84,19 @@ pub(super) fn py_struct_export_names(s: &TypeMeta) -> Vec { } } -pub(super) fn generate_struct_stub_imports(structs: &[TypeMeta]) -> String { +pub(super) fn generate_struct_stub_imports( + context: &PythonProjectionContext, + structs: &[TypeMeta], +) -> String { let mut imports = structs .iter() .filter_map(|typ| { - let TypeMeta::Struct { - namespace, name, .. - } = typ - else { + let TypeMeta::Struct { .. } = typ else { return None; }; Some(format!( "from .{} import {} # noqa: F401\n", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), py_struct_export_names(typ).join(", ") )) }) @@ -71,7 +106,7 @@ pub(super) fn generate_struct_stub_imports(structs: &[TypeMeta]) -> String { imports.concat() } -pub(super) fn emit_struct_stub(s: &TypeMeta) -> String { +pub(super) fn emit_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) -> String { if let Some(kind) = foundation_type(s) { let TypeMeta::Struct { name, .. } = s else { unreachable!() @@ -114,7 +149,7 @@ pub(super) fn emit_struct_stub(s: &TypeMeta) -> String { format!( "{}: {} = ...", to_snake_case(&f.name), - py_struct_field_stub_type(&f.typ) + py_struct_field_stub_type(context, &f.typ) ) }) .collect(); @@ -130,14 +165,14 @@ pub(super) fn emit_struct_stub(s: &TypeMeta) -> String { \x20 def {snake}(self) -> {read_type}: ...\n\ \x20 @{snake}.setter\n\ \x20 def {snake}(self, value: {write_type}) -> None: ...\n", - read_type = py_struct_field_read_type(&f.typ), - write_type = py_struct_field_type(&f.typ), + read_type = py_struct_field_read_type(context, &f.typ), + write_type = py_struct_field_type(context, &f.typ), )); } else { out.push_str(&format!( " {}: {}\n", snake, - py_struct_field_stub_type(&f.typ) + py_struct_field_stub_type(context, &f.typ) )); } } @@ -182,9 +217,12 @@ fn py_string_tuple_literal(values: &[String]) -> String { } } -pub(super) fn py_struct_field_stub_type(typ: &TypeMeta) -> String { +pub(super) fn py_struct_field_stub_type( + context: &PythonProjectionContext, + typ: &TypeMeta, +) -> String { if ireference_inner_type(typ).is_some() { - return py_struct_field_type(typ); + return py_struct_field_type(context, typ); } match typ { @@ -197,7 +235,7 @@ pub(super) fn py_struct_field_stub_type(typ: &TypeMeta) -> String { | TypeMeta::U32 | TypeMeta::I64 | TypeMeta::U64 => "int".to_string(), - TypeMeta::Enum { name, .. } => format!("'{}'", name), + TypeMeta::Enum { .. } => format!("'{}'", context.reference_name_for_type(typ)), TypeMeta::Char16 => "str".to_string(), TypeMeta::F32 | TypeMeta::F64 => "float".to_string(), TypeMeta::String => "str".to_string(), @@ -212,8 +250,7 @@ pub(super) fn py_struct_field_stub_type(typ: &TypeMeta) -> String { pub(super) fn emit_method_stub( method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, indent_spaces: usize, event_has_remove: bool, property_has_getter: bool, @@ -221,8 +258,7 @@ pub(super) fn emit_method_stub( ) -> String { emit_method_stub_named( method, - known_types, - delegate_type_names, + context, indent_spaces, None, event_has_remove, @@ -243,8 +279,7 @@ fn emit_documented_stub(out: &mut String, indent: &str, signature: &str, doc: &s pub(super) fn emit_method_stub_named( method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, indent_spaces: usize, name_override: Option<&str>, event_has_remove: bool, @@ -255,16 +290,8 @@ pub(super) fn emit_method_stub_named( let in_params = get_in_params(method); let return_type = method.return_type.as_ref(); - let is_delegate_type = |typ: Option<&TypeMeta>| -> bool { - match typ { - Some(TypeMeta::Delegate { .. }) => true, - Some(TypeMeta::Interface { name, .. }) => delegate_type_names.contains(name), - Some(TypeMeta::Parameterized { name, args, .. }) => { - delegate_type_names.contains(&crate::meta::make_parameterized_name(name, args)) - } - _ => false, - } - }; + let is_delegate_type = + |typ: Option<&TypeMeta>| -> bool { typ.is_some_and(|typ| context.is_delegate_type(typ)) }; let mut out = String::new(); let body_indent = format!("{indent} "); @@ -277,7 +304,7 @@ pub(super) fn emit_method_stub_named( // Build a typed callback signature matching the runtime .py side. let delegate_typ = in_params.first().map(|p| &p.typ); let callback_sig = delegate_typ - .map(|typ| py_delegate_callable_type(typ, known_types)) + .map(|typ| py_delegate_callable_type(typ, context)) .unwrap_or_else(|| "Callable[..., object]".to_string()); emit_documented_stub( &mut out, @@ -319,7 +346,7 @@ pub(super) fn emit_method_stub_named( if method.is_property_getter && in_params.is_empty() { let prop_name = to_snake_case(method.name.strip_prefix("get_").unwrap_or(&method.name)); let py_return = return_type - .map(|typ| py_output_type(typ, known_types, delegate_type_names)) + .map(|typ| py_output_type(typ, context)) .unwrap_or_else(|| "None".to_string()); out.push_str(&format!("{indent}@builtins.property\n")); emit_documented_stub( @@ -339,7 +366,7 @@ pub(super) fn emit_method_stub_named( } else { in_params .first() - .map(|p| py_param_type_safe(&p.typ, known_types)) + .map(|p| py_param_type_safe(&p.typ, context)) .unwrap_or_else(|| "object".to_string()) }; if property_has_getter { @@ -361,8 +388,8 @@ pub(super) fn emit_method_stub_named( ); } } else { - let py_params = py_param_list(&in_params, known_types, delegate_type_names); - let py_return = py_method_return_type(method, known_types, delegate_type_names); + let py_params = py_param_list(&in_params, context); + let py_return = py_method_return_type(method, context); let method_name = name_override .map(str::to_string) .unwrap_or_else(|| to_snake_case(&method.name)); @@ -378,8 +405,8 @@ pub(super) fn emit_method_stub_named( let override_ignore = if overrides_mutable_sequence && method_name == "append" && in_params.first().is_some_and(|param| { - py_param_type_safe(¶m.typ, known_types) - != super::type_helpers::py_return_type_safe(Some(¶m.typ), known_types) + py_param_type_safe(¶m.typ, context) + != super::type_helpers::py_return_type_safe(Some(¶m.typ), context) }) { " # type: ignore[override, unused-ignore]" } else { @@ -400,35 +427,26 @@ pub(super) fn emit_method_stub_named( pub(super) fn emit_static_method_stub( class_name: &str, method: &MethodMeta, - known_types: &HashSet, + context: &PythonProjectionContext, is_factory: bool, - delegate_type_names: &HashSet, ) -> String { - emit_static_method_stub_named( - class_name, - method, - known_types, - is_factory, - delegate_type_names, - None, - ) + emit_static_method_stub_named(class_name, method, context, is_factory, None) } pub(super) fn emit_static_method_stub_named( class_name: &str, method: &MethodMeta, - known_types: &HashSet, + context: &PythonProjectionContext, is_factory: bool, - delegate_type_names: &HashSet, name_override: Option<&str>, ) -> String { let in_params = get_in_params(method); - let py_params = py_param_list(&in_params, known_types, delegate_type_names); + let py_params = py_param_list(&in_params, context); let py_return = if is_factory { - py_factory_return_type(class_name, method, known_types) + py_factory_return_type(class_name, method, context) } else { - py_method_return_type(method, known_types, delegate_type_names) + py_method_return_type(method, context) }; let mut out = String::new(); @@ -498,8 +516,7 @@ mod tests { fn paired_event_stubs_preserve_token_api_and_add_helpers() { let code = emit_method_stub( &event_add(), - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), 4, true, true, @@ -515,8 +532,7 @@ mod tests { fn add_only_event_stub_does_not_advertise_unavailable_helpers() { let code = emit_method_stub( &event_add(), - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), 4, false, true, @@ -539,23 +555,17 @@ mod tests { }], ..Default::default() }; - let reference = emit_method_stub( - &append(TypeMeta::Interface { - namespace: "Contoso".into(), - name: "Widget".into(), - iid: "11111111-1111-1111-1111-111111111111".into(), - }), - &HashSet::from(["Widget".into()]), - &HashSet::new(), - 4, - false, - true, - true, - ); + let reference_type = TypeMeta::Interface { + namespace: "Contoso".into(), + name: "Widget".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + }; + let context = + PythonProjectionContext::standalone([reference_type.type_identity()]).unwrap(); + let reference = emit_method_stub(&append(reference_type), &context, 4, false, true, true); let scalar = emit_method_stub( &append(TypeMeta::I32), - &HashSet::new(), - &HashSet::new(), + &PythonProjectionContext::default(), 4, false, true, @@ -565,4 +575,31 @@ mod tests { assert!(reference.contains("type: ignore[override, unused-ignore]")); assert!(!scalar.contains("type: ignore[override")); } + + #[test] + fn ambiguous_enum_struct_fields_use_semantic_reference_aliases() { + let enumeration = |namespace: &str| TypeMeta::Enum { + namespace: namespace.into(), + name: "Mode".into(), + underlying: Box::new(TypeMeta::I32), + members: vec![], + is_flags: false, + doc: None, + deprecated: None, + }; + let left = enumeration("Example.Left"); + let right = enumeration("Example.Right"); + let context = + PythonProjectionContext::packaged([left.type_identity(), right.type_identity()]) + .unwrap(); + + assert_eq!( + py_struct_field_stub_type(&context, &left), + "'Example_Left_Mode_enum'" + ); + assert_eq!( + py_struct_field_read_type(&context, &right), + "'Example_Right_Mode_enum'" + ); + } } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs index fedae44d..9af6054e 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, collect_struct_field_type_imports, collect_type_imports, - collect_used_generics_from_class, collect_used_generics_from_methods, - collect_used_generics_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, @@ -23,12 +23,9 @@ use crate::codegen::winrt::shared::structs::{ }; use super::collections::{ - CollectionKind, abc_name, class_interface, interface_kind, observable_vector_name, -}; -use super::naming::{ - is_py_reserved, python_module_layout_installed, python_module_name, - python_public_qualified_module_name, to_snake_case, to_snake_case_filename, + CollectionKind, abc_name, class_interface, interface_kind, observable_vector_identity, }; +use super::naming::{PythonProjectionContext, is_py_reserved, to_snake_case}; use super::native_types::foundation_type; use super::shared::reorder_getters_before_setters; use super::signature::py_dynwinrt_type; @@ -95,11 +92,15 @@ fn interface_marker(interface: &InterfaceMeta) -> String { identity_marker("iid", &interface.namespace, &interface.name) } +fn interface_symbol(context: &PythonProjectionContext, interface: &InterfaceMeta) -> String { + context.reference_name(&interface.type_identity()) +} + fn class_marker(class: &ClassMeta) -> String { identity_marker("class", &class.namespace, &class.name) } -pub fn generate_struct_stub(s: &TypeMeta) -> Option { +pub fn generate_struct_stub(context: &PythonProjectionContext, s: &TypeMeta) -> Option { let TypeMeta::Struct { name, .. } = s else { return None; }; @@ -112,29 +113,43 @@ pub fn generate_struct_stub(s: &TypeMeta) -> Option { out.push_str(FUTURE_ANNOTATIONS); out.push_str(IMPORT_LINE); out.push_str(&generate_struct_stub_imports( + context, &collect_used_structs_from_struct(s), )); let mut imports = collect_struct_field_type_imports(s) .into_iter() - .map(|type_ref| format_py_type_import(&type_ref.namespace, &type_ref.name, type_ref.kind)) + .map(|type_ref| { + format_py_type_import(context, &type_ref.namespace, &type_ref.name, type_ref.kind) + }) .collect::>(); - imports.extend(collect_used_generics_from_type(s).into_iter().map(|name| { - format!( - "from .{} import {} # noqa: F401\n", - to_snake_case_filename(&name), - name - ) - })); + imports.extend( + collect_used_generic_identities_from_type(s) + .into_iter() + .map(|identity| { + let identity = context.normalize_identity(&identity); + let name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if name == reference_name { + name + } else { + format!("{name} as {reference_name}") + }; + format!( + "from .{} import {import} # noqa: F401\n", + context.implementation_module(&identity), + ) + }), + ); imports.sort(); imports.dedup(); out.push_str(&imports.concat()); - out.push_str(&emit_struct_stub(s)); + out.push_str(&emit_struct_stub(context, s)); Some(out) } /// Generate a `.pyi` stub for an enum. Returns `None` for non-enum TypeMeta. -pub fn generate_enum_stub(en: &TypeMeta) -> Option { +pub fn generate_enum_stub(_context: &PythonProjectionContext, en: &TypeMeta) -> Option { let (name, members, is_flags, doc, deprecated) = match en { TypeMeta::Enum { name, @@ -181,13 +196,11 @@ pub fn generate_enum_stub(en: &TypeMeta) -> Option { } /// Generate a `.pyi` stub for an interface (or a delegate). -pub fn generate_interface_stub( - iface: &InterfaceMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, -) -> String { - let is_delegate = iface.methods.iter().any(|m| m.name == ".ctor") - && iface.methods.iter().any(|m| m.name == "Invoke"); +pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String { + let mut projected_iface = iface.clone(); + projected_iface.name = context.projected_name_for_interface(iface); + let iface = &projected_iface; + let is_delegate = iface.is_delegate(); if is_delegate { // Delegate stub: only IID + PARAM_TYPES declarations let mut out = String::new(); @@ -218,41 +231,63 @@ pub fn generate_interface_stub( { out.push_str("from typing import Callable\n"); } - if python_module_layout_installed() { - out.push_str(&generate_struct_stub_imports(&used_structs)); + if context.is_packaged() { + out.push_str(&generate_struct_stub_imports(context, &used_structs)); } out.push('\n'); if !iface.iid.is_empty() || iface.generic_piid.is_some() { out.push_str("_InterfaceT = TypeVar('_InterfaceT')\n\n"); } - let delegate_names = - super::collect_referenced_delegate_names(&iface.methods, delegate_type_names); - let runtime_delegate_names = - super::collect_runtime_delegate_names(&iface.methods, delegate_type_names); + let delegate_names = super::collect_referenced_delegate_names(&iface.methods, context); + let runtime_delegate_names = super::collect_runtime_delegate_names(&iface.methods, context); - let collection_names = collect_used_generics_from_methods(&iface.methods); - let observable_vector = observable_vector_name(iface); - for cname in &collection_names { - if cname != &iface.name && !delegate_names.contains(cname) { - let module = to_snake_case_filename(cname); - out.push_str(&format!( - "from .{} import {} # noqa: F401\n", - module, cname - )); + let collection_identities = collect_used_generic_identities_from_methods(&iface.methods); + let observable_vector = observable_vector_identity(iface); + for identity in &collection_identities { + let identity = context.normalize_identity(identity); + if identity != iface.type_identity() && !delegate_names.contains(&identity) { + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if name == reference_name { + name + } else { + format!("{name} as {reference_name}") + }; + out.push_str(&format!("from .{module} import {import} # noqa: F401\n")); } } - if let Some(vector_name) = &observable_vector - && !collection_names.contains(vector_name) - { - let module = to_snake_case_filename(vector_name); - out.push_str(&format!( - "from .{module} import {vector_name} # noqa: F401\n" - )); + if observable_vector.is_some() { + let identity = crate::types::TypeIdentity::closed_generic( + crate::types::TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IVector", + iface.generic_args.iter().map(TypeMeta::type_identity), + ); + if !collection_identities + .iter() + .any(|candidate| context.normalize_identity(candidate) == identity) + { + let module = context.implementation_module(&identity); + let vector_name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if vector_name == reference_name { + vector_name + } else { + format!("{vector_name} as {reference_name}") + }; + out.push_str(&format!("from .{module} import {import} # noqa: F401\n")); + } } if observable_vector.is_some() { let event_args = "IVectorChangedEventArgs"; - let module = to_snake_case_filename(event_args); + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + event_args, + ); + let module = context.implementation_module(&identity); out.push_str(&format!( "from .{module} import {event_args} # noqa: F401\n" )); @@ -260,11 +295,19 @@ pub fn generate_interface_stub( let mut sorted_delegates: Vec<_> = runtime_delegate_names.iter().collect(); sorted_delegates.sort(); - for dname in &sorted_delegates { - let module = to_snake_case_filename(dname); - out.push_str(&format!( - "from .{module} import IID_{dname}, {dname}_PARAM_TYPES # noqa: F401\n", - )); + for identity in &sorted_delegates { + let module = context.implementation_module(identity); + let dname = context.projected_name(identity); + let reference_name = context.reference_name(identity); + let imports = if dname == reference_name { + format!("IID_{dname}, {dname}_PARAM_TYPES") + } else { + format!( + "IID_{dname} as IID_{reference_name}, \ + {dname}_PARAM_TYPES as {reference_name}_PARAM_TYPES" + ) + }; + out.push_str(&format!("from .{module} import {imports} # noqa: F401\n",)); } let type_imports = collect_iface_type_imports(iface); @@ -272,8 +315,23 @@ pub fn generate_interface_stub( sorted_type_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); for r in &sorted_type_imports { - if known_types.contains(&r.name) && !delegate_names.contains(&r.name) { - out.push_str(&format_py_type_import(&r.namespace, &r.name, r.kind)); + let identity_kind = match r.kind { + TypeKind::Class => crate::types::TypeIdentityKind::Class, + TypeKind::Enum => crate::types::TypeIdentityKind::Enum, + TypeKind::Interface => crate::types::TypeIdentityKind::Interface, + }; + let identity = context.normalize_identity(&crate::types::TypeIdentity::named( + identity_kind, + r.namespace.clone(), + r.name.clone(), + )); + if context.is_known_ref(r) && !delegate_names.contains(&identity) { + out.push_str(&format_py_type_import( + context, + &r.namespace, + &r.name, + r.kind, + )); } } out.push('\n'); @@ -283,9 +341,9 @@ pub fn generate_interface_stub( } out.push('\n'); - if !python_module_layout_installed() { + if !context.is_packaged() { for s in &used_structs { - out.push_str(&emit_struct_stub(s)); + out.push_str(&emit_struct_stub(context, s)); out.push('\n'); } } @@ -297,13 +355,13 @@ pub fn generate_interface_stub( [element] => Some(format!( "{}[{}]", abc, - super::type_helpers::py_return_type_safe(Some(element), known_types) + super::type_helpers::py_return_type_safe(Some(element), context) )), [key, value] => Some(format!( "{}[{}, {}]", abc, - super::type_helpers::py_return_type_safe(Some(key), known_types), - super::type_helpers::py_return_type_safe(Some(value), known_types) + super::type_helpers::py_return_type_safe(Some(key), context), + super::type_helpers::py_return_type_safe(Some(value), context) )), _ => None, }); @@ -338,7 +396,7 @@ pub fn generate_interface_stub( if !is_protocol { out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n"); } - out.push_str(&collection_protocol_stubs(iface, known_types, 4)); + out.push_str(&collection_protocol_stubs(iface, context, 4)); if !iface.iid.is_empty() || iface.generic_piid.is_some() { out.push('\n'); out.push_str(" @classmethod\n"); @@ -351,11 +409,12 @@ pub fn generate_interface_stub( // IVector / IMap create() if let Some(ref piid) = iface.generic_piid { if piid == "5917eb53-50b4-4a0d-b309-65862b3f1dbc" && iface.generic_args.len() == 1 { - let element = - super::type_helpers::py_param_type_safe(&iface.generic_args[0], known_types); - let vector_name = observable_vector - .as_ref() - .expect("observable vector companion"); + let element = super::type_helpers::py_param_type_safe(&iface.generic_args[0], context); + let vector_name = context.projected_name( + observable_vector + .as_ref() + .expect("observable vector companion"), + ); out.push('\n'); out.push_str(" @staticmethod\n"); out.push_str(&format!( @@ -367,8 +426,7 @@ pub fn generate_interface_stub( vector_name )); } else if piid == "913337e9-11a1-4345-a3a2-4e7f956e222d" && iface.generic_args.len() == 1 { - let element = - super::type_helpers::py_param_type_safe(&iface.generic_args[0], known_types); + let element = super::type_helpers::py_param_type_safe(&iface.generic_args[0], context); out.push('\n'); out.push_str(" @staticmethod\n"); out.push_str(&format!( @@ -376,9 +434,8 @@ pub fn generate_interface_stub( element, iface.name )); } else if piid == "3c2925fe-8519-45c1-aa79-197b6718c1c1" && iface.generic_args.len() == 2 { - let key = super::type_helpers::py_param_type_safe(&iface.generic_args[0], known_types); - let value = - super::type_helpers::py_param_type_safe(&iface.generic_args[1], known_types); + let key = super::type_helpers::py_param_type_safe(&iface.generic_args[0], context); + let value = super::type_helpers::py_param_type_safe(&iface.generic_args[1], context); out.push('\n'); out.push_str(" @staticmethod\n"); out.push_str(&format!( @@ -421,8 +478,7 @@ pub fn generate_interface_stub( out.push('\n'); out.push_str(&emit_instance_stub_group( &methods, - known_types, - &delegate_names, + context, 4, event_has_remove, property_has_getter, @@ -431,8 +487,7 @@ pub fn generate_interface_stub( } out.push_str(&emit_instance_compatibility_alias_stubs( iface.methods.iter(), - known_types, - &delegate_names, + context, 4, collection_kind == Some(CollectionKind::MutableSequence), )); @@ -442,15 +497,15 @@ pub fn generate_interface_stub( /// Generate a `.pyi` stub for a runtime class. pub fn generate_class_stub( + context: &PythonProjectionContext, class: &ClassMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, shared_iids: &HashSet, ) -> String { let used_structs = collect_used_structs_from_class(class); let collection_iface = class_interface(class); let collection_kind = collection_iface.and_then(interface_kind); - let winui_bootstrap = winui::resolve_application_bootstrap(class, known_types); + let known_full_names = context.known_full_names(); + let winui_bootstrap = winui::resolve_application_bootstrap(class, &known_full_names); let has_public_composition = class .constructors .iter() @@ -503,8 +558,8 @@ pub fn generate_class_stub( } else if winui::is_dispatcher_queue(class) { out.push_str("from typing import TypeVar\n"); } - if python_module_layout_installed() { - out.push_str(&generate_struct_stub_imports(&used_structs)); + if context.is_packaged() { + out.push_str(&generate_struct_stub_imports(context, &used_structs)); } out.push('\n'); if winui::is_dispatcher_queue(class) { @@ -516,38 +571,49 @@ pub fn generate_class_stub( for iface in class.all_interfaces() { delegate_names.extend(super::collect_referenced_delegate_names( &iface.methods, - delegate_type_names, + context, )); runtime_delegate_names.extend(super::collect_runtime_delegate_names( &iface.methods, - delegate_type_names, + context, )); } let mut imported_names: HashSet = HashSet::new(); - let collection_names = collect_used_generics_from_class(class); - for cname in &collection_names { - if !delegate_names.contains(cname) { - let module = to_snake_case_filename(cname); - out.push_str(&format!( - "from .{} import {} # noqa: F401\n", - module, cname - )); - imported_names.insert(cname.clone()); + let collection_identities = collect_used_generic_identities_from_class(class); + for identity in &collection_identities { + let identity = context.normalize_identity(identity); + if !delegate_names.contains(&identity) { + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); + let reference_name = context.reference_name(&identity); + let import = if name == reference_name { + name + } else { + format!("{name} as {reference_name}") + }; + out.push_str(&format!("from .{module} import {import} # noqa: F401\n")); + imported_names.insert(reference_name); } } for iface in class.all_interfaces() { if iface.generic_piid.as_deref() == Some(super::collections::IOBSERVABLE_VECTOR_PIID) { - if imported_names.insert(iface.name.clone()) { - let module = to_snake_case_filename(&iface.name); + let identity = iface.type_identity(); + let projected_name = context.projected_name(&identity); + if imported_names.insert(projected_name.clone()) { + let module = context.implementation_module(&identity); out.push_str(&format!( - "from .{module} import {} # noqa: F401\n", - iface.name + "from .{module} import {projected_name} # noqa: F401\n" )); } let event_args = "IVectorChangedEventArgs"; if imported_names.insert(event_args.into()) { - let module = to_snake_case_filename(event_args); + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + event_args, + ); + let module = context.implementation_module(&identity); out.push_str(&format!( "from .{module} import {event_args} # noqa: F401\n" )); @@ -557,11 +623,19 @@ pub fn generate_class_stub( let mut sorted_delegates: Vec<_> = runtime_delegate_names.iter().collect(); sorted_delegates.sort(); - for dname in &sorted_delegates { - let module = to_snake_case_filename(dname); - out.push_str(&format!( - "from .{module} import IID_{dname}, {dname}_PARAM_TYPES # noqa: F401\n", - )); + for identity in &sorted_delegates { + let module = context.implementation_module(identity); + let dname = context.projected_name(identity); + let reference_name = context.reference_name(identity); + let imports = if dname == reference_name { + format!("IID_{dname}, {dname}_PARAM_TYPES") + } else { + format!( + "IID_{dname} as IID_{reference_name}, \ + {dname}_PARAM_TYPES as {reference_name}_PARAM_TYPES" + ) + }; + out.push_str(&format!("from .{module} import {imports} # noqa: F401\n",)); } let imports = collect_type_imports(class); @@ -569,46 +643,74 @@ pub fn generate_class_stub( sorted_imports .sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind))); for r in &sorted_imports { - if known_types.contains(&r.name) && !delegate_names.contains(&r.name) { - out.push_str(&format_py_type_import(&r.namespace, &r.name, r.kind)); - imported_names.insert(r.name.clone()); + let identity_kind = match r.kind { + TypeKind::Class => crate::types::TypeIdentityKind::Class, + TypeKind::Enum => crate::types::TypeIdentityKind::Enum, + TypeKind::Interface => crate::types::TypeIdentityKind::Interface, + }; + let identity = context.normalize_identity(&crate::types::TypeIdentity::named( + identity_kind, + r.namespace.clone(), + r.name.clone(), + )); + if context.is_known_ref(r) && !delegate_names.contains(&identity) { + out.push_str(&format_py_type_import( + context, + &r.namespace, + &r.name, + r.kind, + )); + let reference_name = context.reference_name(&identity); + imported_names.insert(reference_name.clone()); if r.kind == TypeKind::Interface { - imported_names.insert(format!("IID_{}", r.name)); + imported_names.insert(format!("IID_{reference_name}")); } } } let base_identity = class .base_class .as_ref() - .filter(|base| known_types.contains(&base.name)) + .filter(|base| context.is_known_ref(base)) .map(|base| { + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + base.namespace.clone(), + base.name.clone(), + ); + let name = context.reference_name(&identity); out.push_str(&format!( "from .{} import _{}Identity # noqa: F401\n", - python_module_name(&base.namespace, &base.name), - base.name + context.implementation_module(&identity), + name )); - format!("_{}Identity", base.name) + format!("_{name}Identity") }); for req_iface in &class.required_interfaces { + let symbol = interface_symbol(context, req_iface); if req_iface.generic_piid.is_none() && !req_iface.iid.is_empty() && shared_iids.contains(&req_iface.iid) - && !imported_names.contains(&req_iface.name) + && !imported_names.contains(&symbol) { out.push_str(&format_py_type_import( + context, &req_iface.namespace, &req_iface.name, TypeKind::Interface, )); - imported_names.insert(req_iface.name.clone()); - imported_names.insert(format!("IID_{}", req_iface.name)); + imported_names.insert(symbol.clone()); + imported_names.insert(format!("IID_{symbol}")); } } if let Some(bootstrap) = winui_bootstrap { let metadata_provider = bootstrap.spec.metadata_provider; out.push_str(&format!( "from .{} import {} # noqa: F401\n", - python_module_name(metadata_provider.namespace, metadata_provider.name), + context.implementation_module_for_named( + crate::types::TypeIdentityKind::Class, + metadata_provider.namespace, + metadata_provider.name, + ), metadata_provider.name, )); } @@ -620,7 +722,7 @@ pub fn generate_class_stub( // IID constants (declarations only) let mut declared_iids = HashSet::new(); for iface in class.all_interfaces() { - let iid_name = format!("IID_{}", iface.name); + let iid_name = format!("IID_{}", interface_symbol(context, iface)); if !iface.iid.is_empty() && !imported_names.contains(&iid_name) && declared_iids.insert(iid_name.clone()) @@ -630,9 +732,9 @@ pub fn generate_class_stub( } out.push('\n'); - if !python_module_layout_installed() { + if !context.is_packaged() { for s in &used_structs { - out.push_str(&emit_struct_stub(s)); + out.push_str(&emit_struct_stub(context, s)); out.push('\n'); } } @@ -643,24 +745,18 @@ pub fn generate_class_stub( [element] => Some(format!( "{}[{}]", abc, - super::type_helpers::py_return_type_safe(Some(element), known_types) + super::type_helpers::py_return_type_safe(Some(element), context) )), [key, value] => Some(format!( "{}[{}, {}]", abc, - super::type_helpers::py_return_type_safe(Some(key), known_types), - super::type_helpers::py_return_type_safe(Some(value), known_types) + super::type_helpers::py_return_type_safe(Some(key), context), + super::type_helpers::py_return_type_safe(Some(value), context) )), _ => None, }); - let instance_stub_body = emit_class_instance_stubs( - class, - known_types, - &delegate_names, - collection_iface, - false, - has_closable, - ); + let instance_stub_body = + emit_class_instance_stubs(class, context, collection_iface, false, has_closable); let identity_name = format!("_{}Identity", class.name); let mut identity_bases = base_identity.into_iter().collect::>(); identity_bases.push("Protocol".into()); @@ -713,12 +809,11 @@ pub fn generate_class_stub( }, " ", )); - out.push_str(&emit_constructor_stubs(class, known_types, &delegate_names)); + out.push_str(&emit_constructor_stubs(class, context)); if collection_base.is_some() { out.push_str(&emit_class_instance_stubs( class, - known_types, - &delegate_names, + context, collection_iface, collection_kind == Some(CollectionKind::MutableSequence), has_closable, @@ -759,18 +854,12 @@ 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, - known_types, - delegate_type_names, - )); + out.push_str(&emit_static_stub_group(&class.name, &group, context)); } out.push_str(&emit_static_compatibility_alias_stubs( &class.name, static_methods.iter().copied(), - known_types, - delegate_type_names, + context, 4, )); @@ -820,7 +909,8 @@ pub fn generate_class_stub( if req_iface.iid.is_empty() { continue; } - if imported_names.contains(&req_iface.name) { + let symbol = interface_symbol(context, req_iface); + if imported_names.contains(&symbol) { continue; } out.push('\n'); @@ -830,23 +920,23 @@ pub fn generate_class_stub( [element] => Some(format!( "{}[{}]", abc, - super::type_helpers::py_return_type_safe(Some(element), known_types) + super::type_helpers::py_return_type_safe(Some(element), context) )), [key, value] => Some(format!( "{}[{}, {}]", abc, - super::type_helpers::py_return_type_safe(Some(key), known_types), - super::type_helpers::py_return_type_safe(Some(value), known_types) + super::type_helpers::py_return_type_safe(Some(key), context), + super::type_helpers::py_return_type_safe(Some(value), context) )), _ => None, }); if let Some(base) = required_base { - out.push_str(&format!("\nclass {}({base}):\n", req_iface.name)); + out.push_str(&format!("\nclass {symbol}({base}):\n")); } else { - out.push_str(&format!("\nclass {}:\n", req_iface.name)); + out.push_str(&format!("\nclass {symbol}:\n")); } out.push_str(" def __init__(self, obj: DynWinRTValue) -> None: ...\n"); - out.push_str(&collection_protocol_stubs(req_iface, known_types, 4)); + out.push_str(&collection_protocol_stubs(req_iface, context, 4)); out.push('\n'); out.push_str(" @classmethod\n"); out.push_str(" def from_value(cls, obj: DynWinRTValue) -> Self: ...\n"); @@ -876,8 +966,7 @@ pub fn generate_class_stub( out.push('\n'); out.push_str(&emit_instance_stub_group( &methods, - known_types, - &delegate_names, + context, 4, event_has_remove, property_has_getter, @@ -886,8 +975,7 @@ pub fn generate_class_stub( } out.push_str(&emit_instance_compatibility_alias_stubs( req_iface.methods.iter(), - known_types, - &delegate_names, + context, 4, interface_kind(req_iface) == Some(CollectionKind::MutableSequence), )); @@ -899,15 +987,14 @@ pub fn generate_class_stub( fn emit_class_instance_stubs( class: &ClassMeta, - known_types: &HashSet, - delegate_names: &HashSet, + context: &PythonProjectionContext, collection_iface: Option<&InterfaceMeta>, mutable_sequence_override: bool, has_closable: bool, ) -> String { let mut out = String::new(); if let Some(collection_iface) = collection_iface { - out.push_str(&collection_protocol_stubs(collection_iface, known_types, 4)); + out.push_str(&collection_protocol_stubs(collection_iface, context, 4)); } let instance_ifaces = class @@ -993,8 +1080,7 @@ fn emit_class_instance_stubs( out.push('\n'); out.push_str(&emit_instance_stub_group( &methods, - known_types, - delegate_names, + context, 4, event_has_remove, property_has_getter, @@ -1003,8 +1089,7 @@ fn emit_class_instance_stubs( } out.push_str(&emit_instance_compatibility_alias_stubs( original_instance_methods.iter().copied(), - known_types, - delegate_names, + context, 4, mutable_sequence_override, )); @@ -1052,7 +1137,7 @@ fn emit_class_instance_stubs( fn collection_protocol_stubs( iface: &InterfaceMeta, - known_types: &HashSet, + context: &PythonProjectionContext, indent_spaces: usize, ) -> String { let Some(kind) = interface_kind(iface) else { @@ -1062,7 +1147,7 @@ fn collection_protocol_stubs( let item_type = iface .generic_args .first() - .map(|typ| super::type_helpers::py_return_type_safe(Some(typ), known_types)) + .map(|typ| super::type_helpers::py_return_type_safe(Some(typ), context)) .unwrap_or_else(|| "object".to_string()); match kind { super::collections::CollectionKind::Iterable => { @@ -1097,7 +1182,7 @@ fn collection_protocol_stubs( let value_type = iface .generic_args .get(1) - .map(|typ| super::type_helpers::py_return_type_safe(Some(typ), known_types)) + .map(|typ| super::type_helpers::py_return_type_safe(Some(typ), context)) .unwrap_or_else(|| "object".to_string()); let mut result = format!( "\n{indent}def __len__(self) -> int: ...\n\ @@ -1116,11 +1201,7 @@ fn collection_protocol_stubs( } } -fn emit_constructor_stubs( - class: &ClassMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, -) -> String { +fn emit_constructor_stubs(class: &ClassMeta, context: &PythonProjectionContext) -> String { // Collect (public_params_only, ...) for each accessible constructor. // Composable factories: strip trailing outer + skip ProtectedComposition. let mut overloads: Vec> = Vec::new(); @@ -1217,8 +1298,7 @@ fn emit_constructor_stubs( if count > 1 { out.push_str(" @overload\n"); } - let param_str = - super::type_helpers::py_param_list(params, known_types, delegate_type_names); + let param_str = super::type_helpers::py_param_list(params, context); if param_str.is_empty() { out.push_str(" def __init__(self) -> None: ...\n"); } else { @@ -1289,8 +1369,7 @@ fn has_constructor_stub_overload(class: &ClassMeta) -> bool { fn emit_instance_stub_group( methods: &[&MethodMeta], - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, indent_spaces: usize, event_has_remove: bool, property_has_getter: bool, @@ -1303,8 +1382,7 @@ fn emit_instance_stub_group( if ordered_methods.len() == 1 { return emit_method_stub( ordered_methods[0], - known_types, - delegate_type_names, + context, indent_spaces, event_has_remove, property_has_getter, @@ -1321,8 +1399,7 @@ fn emit_instance_stub_group( "{indent}@overload\n{}", emit_method_stub_named( method, - known_types, - delegate_type_names, + context, indent_spaces, Some(&public_name), event_has_remove, @@ -1336,8 +1413,7 @@ fn emit_instance_stub_group( fn emit_instance_compatibility_alias_stubs<'a>( methods: impl IntoIterator, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, indent_spaces: usize, overrides_mutable_sequence: bool, ) -> String { @@ -1357,8 +1433,7 @@ fn emit_instance_compatibility_alias_stubs<'a>( } out.push_str(&emit_method_stub_named( method, - known_types, - delegate_type_names, + context, indent_spaces, Some(&legacy), false, @@ -1373,8 +1448,7 @@ fn emit_instance_compatibility_alias_stubs<'a>( fn emit_static_compatibility_alias_stubs<'a>( class_name: &str, methods: impl IntoIterator, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, indent_spaces: usize, ) -> String { let methods = methods.into_iter().collect::>(); @@ -1394,9 +1468,8 @@ fn emit_static_compatibility_alias_stubs<'a>( out.push_str(&emit_static_method_stub_named( class_name, method, - known_types, + context, *is_factory, - delegate_type_names, Some(&legacy), )); } @@ -1423,8 +1496,7 @@ fn grouped_static_stubs<'a>( fn emit_static_stub_group( class_name: &str, methods: &[(&MethodMeta, bool)], - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { let mut ordered_methods = methods.iter().copied().collect::>(); ordered_methods.sort_by(|(left, _), (right, _)| { @@ -1433,13 +1505,7 @@ fn emit_static_stub_group( if ordered_methods.len() == 1 { let (method, is_factory) = ordered_methods[0]; - return emit_static_method_stub( - class_name, - method, - known_types, - is_factory, - delegate_type_names, - ); + return emit_static_method_stub(class_name, method, context, is_factory); } let names = super::overloads::method_names(ordered_methods.iter().map(|(method, _)| *method)); let public_name = super::overloads::method_group_key(ordered_methods[0].0, &names); @@ -1451,9 +1517,8 @@ fn emit_static_stub_group( emit_static_method_stub_named( class_name, method, - known_types, + context, *is_factory, - delegate_type_names, Some(&public_name), ) ) @@ -1463,6 +1528,7 @@ fn emit_static_stub_group( /// Generate an `__init__.pyi` index stub. pub fn generate_index_stub( + context: &PythonProjectionContext, classes: &[ClassMeta], interfaces: &[InterfaceMeta], enums: &[TypeMeta], @@ -1475,11 +1541,14 @@ pub fn generate_index_stub( sorted_classes.sort_by(|a, b| a.name.cmp(&b.name)); for class in sorted_classes { if seen.insert(class.name.clone()) { - let module = python_module_name(&class.namespace, &class.name); - out.push_str(&format!( - "from .{} import {} as {}\n", - module, class.name, class.name - )); + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); + out.push_str(&format!("from .{} import {} as {}\n", module, name, name)); } } @@ -1489,20 +1558,21 @@ pub fn generate_index_stub( if !seen.insert(iface.name.clone()) { continue; } - let is_delegate = iface.methods.iter().any(|m| m.name == ".ctor") - && iface.methods.iter().any(|m| m.name == "Invoke"); - let module = python_module_name(&iface.namespace, &iface.name); + let is_delegate = iface.is_delegate(); + let identity = iface.type_identity(); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); if is_delegate { out.push_str(&format!( "from .{module} import IID_{iname}, {iname}_PARAM_TYPES\n", module = module, - iname = iface.name + iname = name )); } else { out.push_str(&format!( "from .{module} import IID_{iname}, {iname} as {iname}\n", module = module, - iname = iface.name + iname = name )); } } @@ -1520,12 +1590,11 @@ pub fn generate_index_stub( na.cmp(nb) }); for en in sorted_enums { - if let TypeMeta::Enum { - namespace, name, .. - } = en - { + if let TypeMeta::Enum { name, .. } = en { if seen.insert(name.clone()) { - let module = python_module_name(namespace, name); + let identity = en.type_identity(); + let module = context.implementation_module(&identity); + let name = context.projected_name(&identity); out.push_str(&format!("from .{} import {} as {}\n", module, name, name)); } } @@ -1534,6 +1603,7 @@ pub fn generate_index_stub( } pub fn generate_public_index_stub( + context: &PythonProjectionContext, classes: &[ClassMeta], interfaces: &[InterfaceMeta], enums: &[TypeMeta], @@ -1545,11 +1615,17 @@ pub fn generate_public_index_stub( classes.sort_by(|left, right| left.name.cmp(&right.name)); for class in classes { if seen.insert(class.name.clone()) { + let identity = crate::types::TypeIdentity::named( + crate::types::TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + let name = context.projected_name(&identity); out.push_str(&format!( "from .{} import {} as {}\n", - python_public_qualified_module_name(&class.namespace, &class.name), - class.name, - class.name + context.public_qualified_module(&identity), + name, + name )); } } @@ -1557,20 +1633,15 @@ pub fn generate_public_index_stub( let mut interfaces = interfaces.iter().collect::>(); interfaces.sort_by(|left, right| left.name.cmp(&right.name)); for interface in interfaces { - let is_delegate = interface - .methods - .iter() - .any(|method| method.name == ".ctor") - && interface - .methods - .iter() - .any(|method| method.name == "Invoke"); + let is_delegate = interface.is_delegate(); if !is_delegate && seen.insert(interface.name.clone()) { + let identity = interface.type_identity(); + let name = context.projected_name(&identity); out.push_str(&format!( "from .{} import {} as {}\n", - python_public_qualified_module_name(&interface.namespace, &interface.name), - interface.name, - interface.name + context.public_qualified_module(&identity), + name, + name )); } } @@ -1581,25 +1652,27 @@ pub fn generate_public_index_stub( _ => "", }); for typ in enums { - let TypeMeta::Enum { - namespace, name, .. - } = typ - else { + let TypeMeta::Enum { name, .. } = typ else { continue; }; if seen.insert(name.clone()) { + let identity = typ.type_identity(); + let name = context.projected_name(&identity); out.push_str(&format!( "from .{} import {} as {}\n", - python_public_qualified_module_name(namespace, name), + context.public_qualified_module(&identity), + name, name, - name )); } } out } -pub fn generate_struct_index_stub(structs: &[TypeMeta]) -> String { +pub fn generate_struct_index_stub( + context: &PythonProjectionContext, + structs: &[TypeMeta], +) -> String { let mut out = String::from(HEADER); let mut seen = HashSet::new(); let mut sorted = structs.iter().collect::>(); @@ -1621,7 +1694,7 @@ pub fn generate_struct_index_stub(structs: &[TypeMeta]) -> String { } out.push_str(&format!( "from .{} import {}\n", - python_module_name(namespace, name), + context.implementation_module_for_type(typ), py_struct_export_names(typ) .into_iter() .map(|name| format!("{name} as {name}")) @@ -1632,7 +1705,10 @@ pub fn generate_struct_index_stub(structs: &[TypeMeta]) -> String { out } -pub fn generate_public_struct_index_stub(structs: &[TypeMeta]) -> String { +pub fn generate_public_struct_index_stub( + context: &PythonProjectionContext, + structs: &[TypeMeta], +) -> String { let mut out = String::from(HEADER); let mut seen = HashSet::new(); let mut sorted = structs.iter().collect::>(); @@ -1654,7 +1730,7 @@ pub fn generate_public_struct_index_stub(structs: &[TypeMeta]) -> String { } out.push_str(&format!( "from .{} import {} as {}\n", - python_public_qualified_module_name(namespace, name), + context.public_qualified_module(&typ.type_identity()), name, name )); 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 fc284a30..34438dd2 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/type_helpers.rs @@ -3,8 +3,6 @@ //! Python type annotations and method documentation helpers. -use std::collections::HashSet; - use crate::codegen::winrt::shared::docs::{DocText, find_param_doc}; use crate::codegen::winrt::shared::imports::{ fill_array_uses_retval_count, ireference_inner_type, method_abi_output_count, @@ -14,6 +12,7 @@ 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::native_types::{FoundationType, foundation_type}; @@ -80,7 +79,7 @@ fn is_nullable_reference_type(typ: &TypeMeta) -> bool { ) } -fn py_param_type(typ: &TypeMeta) -> String { +fn py_param_type(typ: &TypeMeta, context: &PythonProjectionContext) -> String { match typ { TypeMeta::Bool => "bool".to_string(), TypeMeta::I8 @@ -95,116 +94,121 @@ fn py_param_type(typ: &TypeMeta) -> String { TypeMeta::String => "str".to_string(), TypeMeta::Char16 => "str".to_string(), TypeMeta::Guid => "UUID".to_string(), - TypeMeta::RuntimeClass { name, .. } => format!("'{}Like'", name), - TypeMeta::Enum { name, .. } | TypeMeta::Interface { name, .. } => { - format!("'{}'", name) + TypeMeta::RuntimeClass { .. } => { + format!("'{}Like'", context.reference_name_for_type(typ)) + } + TypeMeta::Enum { .. } | TypeMeta::Interface { .. } => { + format!("'{}'", context.reference_name_for_type(typ)) } - TypeMeta::Parameterized { name, args, .. } => { - format!("'{}'", crate::meta::make_parameterized_name(name, args)) + TypeMeta::Parameterized { .. } => { + format!("'{}'", context.reference_name_for_type(typ)) } - TypeMeta::Array(inner) => py_array_param_type(inner, &HashSet::new()), + TypeMeta::Array(inner) => py_array_param_type(inner, context), TypeMeta::Object | TypeMeta::Delegate { .. } => "'DynWinRTValue'".to_string(), TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(), typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(), typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(), - TypeMeta::Struct { name, .. } => format!("'{}'", name), + TypeMeta::Struct { .. } => format!("'{}'", context.reference_name_for_type(typ)), _ => "object".to_string(), } } -pub(crate) fn py_param_type_safe(typ: &TypeMeta, known: &HashSet) -> String { +pub(crate) fn py_param_type_safe(typ: &TypeMeta, context: &PythonProjectionContext) -> String { if let Some(inner) = ireference_inner_type(typ) { - let native = py_optional_type(py_return_type_safe(Some(inner), known)); - let wrapper = match typ { - TypeMeta::Parameterized { name, args, .. } => { - crate::meta::make_parameterized_name(name, args) - } - _ => unreachable!(), - }; + let native = py_optional_type(py_return_type_safe(Some(inner), context)); + let wrapper = context.reference_name_for_type(typ); return format!("{} | {}", native, wrapper); } - if let Some(annotation) = py_collection_param_type(typ, known) { + if let Some(annotation) = py_collection_param_type(typ, context) { return annotation; } if let TypeMeta::Array(inner) = typ { - return py_array_param_type(inner, known); + return py_array_param_type(inner, context); } match typ { TypeMeta::RuntimeClass { name, .. } | TypeMeta::Enum { name, .. } | TypeMeta::Interface { name, .. } - if !known.contains(name) => + if !context.is_known_type(typ) => { "'DynWinRTValue'".to_string() } - _ => py_param_type(typ), + _ => py_param_type(typ, context), } } -pub(crate) fn py_return_type_safe(typ: Option<&TypeMeta>, known: &HashSet) -> String { +pub(crate) fn py_return_type_safe( + typ: Option<&TypeMeta>, + context: &PythonProjectionContext, +) -> String { if let Some(inner) = typ.and_then(ireference_inner_type) { - return py_optional_type(py_return_type_safe(Some(inner), known)); + return py_optional_type(py_return_type_safe(Some(inner), context)); } - if let Some(async_type) = typ.and_then(|typ| py_async_return_type(typ, known)) { + if let Some(async_type) = typ.and_then(|typ| py_async_return_type(typ, context)) { return async_type; } - if let Some(annotation) = typ.and_then(|typ| py_collection_return_type(typ, known)) { + if let Some(annotation) = typ.and_then(|typ| py_collection_return_type(typ, context)) { return py_optional_type(annotation); } match typ { - Some(TypeMeta::Enum { name, .. }) if !known.contains(name) => "int".to_string(), - Some(TypeMeta::RuntimeClass { name, .. }) | Some(TypeMeta::Interface { name, .. }) - if !known.contains(name) => + Some(typ @ TypeMeta::Enum { .. }) if !context.is_known_type(typ) => "int".to_string(), + Some(typ @ (TypeMeta::RuntimeClass { .. } | TypeMeta::Interface { .. })) + if !context.is_known_type(typ) => { "DynWinRTValue | None".to_string() } - Some(TypeMeta::Array(inner)) => py_array_return_type(inner, known), - Some(typ) if is_nullable_reference_type(typ) => py_optional_type(py_return_type(Some(typ))), - _ => py_return_type(typ), + Some(TypeMeta::Array(inner)) => py_array_return_type(inner, context), + Some(typ) if is_nullable_reference_type(typ) => { + py_optional_type(py_return_type(Some(typ), context)) + } + _ => py_return_type(typ, context), } } fn py_async_return_type_with_result( typ: &TypeMeta, result_override: Option, - known: &HashSet, + context: &PythonProjectionContext, ) -> Option { match typ { TypeMeta::AsyncAction => Some("WinRTAsync[None]".to_string()), TypeMeta::AsyncOperation(result) => Some(format!( "WinRTAsync[{}]", - result_override.unwrap_or_else(|| py_return_type_safe(Some(result), known)) + result_override.unwrap_or_else(|| py_return_type_safe(Some(result), context)) )), TypeMeta::AsyncActionWithProgress(progress) => Some(format!( "WinRTAsyncWithProgress[None, {}]", - py_return_type_safe(Some(progress), known) + py_return_type_safe(Some(progress), context) )), TypeMeta::AsyncOperationWithProgress(result, progress) => Some(format!( "WinRTAsyncWithProgress[{}, {}]", - result_override.unwrap_or_else(|| py_return_type_safe(Some(result), known)), - py_return_type_safe(Some(progress), known) + result_override.unwrap_or_else(|| py_return_type_safe(Some(result), context)), + py_return_type_safe(Some(progress), context) )), _ => None, } } -pub(super) fn py_async_return_type(typ: &TypeMeta, known: &HashSet) -> Option { - py_async_return_type_with_result(typ, None, known) +pub(super) fn py_async_return_type( + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> Option { + py_async_return_type_with_result(typ, None, context) } pub(super) fn py_factory_return_type( class_name: &str, method: &MethodMeta, - known: &HashSet, + context: &PythonProjectionContext, ) -> String { method .return_type .as_ref() .and_then(|typ| { - py_async_return_type_with_result(typ, Some(format!("'{}'", class_name)), known) + py_async_return_type_with_result(typ, Some(format!("'{}'", class_name)), context) }) .unwrap_or_else(|| format!("'{}'", class_name)) } @@ -255,65 +259,52 @@ pub(super) fn py_method_outputs(method: &MethodMeta) -> Vec<(usize, &TypeMeta)> outputs } -fn is_delegate_output(typ: &TypeMeta, delegate_type_names: &HashSet) -> bool { - match typ { - TypeMeta::Delegate { .. } => true, - TypeMeta::Interface { name, .. } => delegate_type_names.contains(name), - TypeMeta::Parameterized { name, args, .. } => { - delegate_type_names.contains(&crate::meta::make_parameterized_name(name, args)) - } - _ => false, - } +fn is_delegate_output(typ: &TypeMeta, context: &PythonProjectionContext) -> bool { + context.is_delegate_type(typ) } -pub(super) fn py_output_type( - typ: &TypeMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, -) -> String { +pub(super) fn py_output_type(typ: &TypeMeta, context: &PythonProjectionContext) -> String { match typ { - _ if is_delegate_output(typ, delegate_type_names) => "DynWinRTValue | None".to_string(), - TypeMeta::Array(inner) if is_delegate_output(inner, delegate_type_names) => { + _ if is_delegate_output(typ, context) => "DynWinRTValue | None".to_string(), + TypeMeta::Array(inner) if is_delegate_output(inner, context) => { "list[DynWinRTValue | None]".to_string() } - TypeMeta::AsyncOperation(inner) => format!( - "WinRTAsync[{}]", - py_output_type(inner, known_types, delegate_type_names) - ), + TypeMeta::AsyncOperation(inner) => { + format!("WinRTAsync[{}]", py_output_type(inner, context)) + } TypeMeta::AsyncOperationWithProgress(result, progress) => format!( "WinRTAsyncWithProgress[{}, {}]", - py_output_type(result, known_types, delegate_type_names), - py_output_type(progress, known_types, delegate_type_names) + py_output_type(result, context), + py_output_type(progress, context) ), TypeMeta::AsyncActionWithProgress(progress) => format!( "WinRTAsyncWithProgress[None, {}]", - py_output_type(progress, known_types, delegate_type_names) + py_output_type(progress, context) ), - _ => py_return_type_safe(Some(typ), known_types), + _ => py_return_type_safe(Some(typ), context), } } pub(super) fn py_method_return_type( method: &MethodMeta, - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { let outputs = py_method_outputs(method); match outputs.as_slice() { [] => "None".to_string(), - [(_, typ)] => py_output_type(typ, known_types, delegate_type_names), + [(_, typ)] => py_output_type(typ, context), _ => format!( "tuple[{}]", outputs .iter() - .map(|(_, typ)| py_output_type(typ, known_types, delegate_type_names)) + .map(|(_, typ)| py_output_type(typ, context)) .collect::>() .join(", ") ), } } -fn py_return_type(typ: Option<&TypeMeta>) -> String { +fn py_return_type(typ: Option<&TypeMeta>, context: &PythonProjectionContext) -> String { match typ { Some(TypeMeta::String) => "str".to_string(), Some(TypeMeta::Guid) => "UUID".to_string(), @@ -330,26 +321,28 @@ fn py_return_type(typ: Option<&TypeMeta>) -> String { ) => "int".to_string(), Some(TypeMeta::Char16) => "str".to_string(), Some(TypeMeta::F32 | TypeMeta::F64) => "float".to_string(), - Some(TypeMeta::RuntimeClass { name, .. }) => format!("'{}'", name), - Some(TypeMeta::Enum { name, .. }) => format!("'{}'", name), - Some(TypeMeta::Interface { name, .. }) => format!("'{}'", name), - Some(TypeMeta::Parameterized { name, args, .. }) => { - format!("'{}'", crate::meta::make_parameterized_name(name, args)) + Some(typ @ TypeMeta::RuntimeClass { .. }) + | Some(typ @ TypeMeta::Enum { .. }) + | Some(typ @ TypeMeta::Interface { .. }) => { + format!("'{}'", context.reference_name_for_type(typ)) + } + Some(typ @ TypeMeta::Parameterized { .. }) => { + format!("'{}'", context.reference_name_for_type(typ)) } Some(TypeMeta::AsyncOperation(inner)) => { - format!("WinRTAsync[{}]", py_return_type(Some(inner))) + format!("WinRTAsync[{}]", py_return_type(Some(inner), context)) } Some(TypeMeta::AsyncOperationWithProgress(result, progress)) => format!( "WinRTAsyncWithProgress[{}, {}]", - py_return_type(Some(result)), - py_return_type(Some(progress)) + py_return_type(Some(result), context), + py_return_type(Some(progress), context) ), Some(TypeMeta::AsyncAction) => "WinRTAsync[None]".to_string(), Some(TypeMeta::AsyncActionWithProgress(progress)) => format!( "WinRTAsyncWithProgress[None, {}]", - py_return_type(Some(progress)) + py_return_type(Some(progress), context) ), - Some(TypeMeta::Array(inner)) => py_array_return_type(inner, &HashSet::new()), + Some(TypeMeta::Array(inner)) => py_array_return_type(inner, context), Some(TypeMeta::Object) | Some(TypeMeta::Delegate { .. }) => "'DynWinRTValue'".to_string(), Some(TypeMeta::Struct { name, .. }) if name == "HResult" => "int".to_string(), Some(typ) if foundation_type(typ) == Some(FoundationType::DateTime) => { @@ -358,12 +351,14 @@ fn py_return_type(typ: Option<&TypeMeta>) -> String { Some(typ) if foundation_type(typ) == Some(FoundationType::TimeSpan) => { "timedelta".to_string() } - Some(TypeMeta::Struct { name, .. }) => format!("'{}'", name), + Some(typ @ TypeMeta::Struct { .. }) => { + format!("'{}'", context.reference_name_for_type(typ)) + } None => "None".to_string(), } } -fn py_native_element_type(inner: &TypeMeta, known_types: &HashSet) -> String { +fn py_native_element_type(inner: &TypeMeta, context: &PythonProjectionContext) -> String { match inner { TypeMeta::Bool => "bool".to_string(), TypeMeta::String => "str".to_string(), @@ -377,22 +372,24 @@ fn py_native_element_type(inner: &TypeMeta, known_types: &HashSet) -> St | TypeMeta::I64 | TypeMeta::U64 => "int".to_string(), TypeMeta::Char16 => "str".to_string(), - TypeMeta::Enum { name, .. } if known_types.contains(name) => format!("'{name}'"), + TypeMeta::Enum { .. } if context.is_known_type(inner) => { + format!("'{}'", context.reference_name_for_type(inner)) + } TypeMeta::Enum { .. } => "int".to_string(), TypeMeta::F32 | TypeMeta::F64 => "float".to_string(), TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(), typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(), typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(), - TypeMeta::Struct { name, .. } => format!("'{name}'"), - TypeMeta::RuntimeClass { name, .. } if known_types.contains(name) => { - format!("'{name}'") + TypeMeta::Struct { .. } => format!("'{}'", context.reference_name_for_type(inner)), + TypeMeta::RuntimeClass { .. } if context.is_known_type(inner) => { + format!("'{}'", context.reference_name_for_type(inner)) } - TypeMeta::Interface { name, .. } if known_types.contains(name) => { - format!("'{name}'") + TypeMeta::Interface { .. } if context.is_known_type(inner) => { + format!("'{}'", context.reference_name_for_type(inner)) } - TypeMeta::Parameterized { name, args, .. } => { - let concrete = crate::meta::make_parameterized_name(name, args); - if known_types.contains(&concrete) { + TypeMeta::Parameterized { .. } => { + let concrete = context.reference_name_for_type(inner); + if context.is_known_type(inner) { format!("'{concrete}'") } else { "'DynWinRTValue'".to_string() @@ -402,8 +399,8 @@ fn py_native_element_type(inner: &TypeMeta, known_types: &HashSet) -> St } } -fn py_array_param_type(inner: &TypeMeta, known_types: &HashSet) -> String { - let element = py_native_param_element_type(inner, known_types); +fn py_array_param_type(inner: &TypeMeta, context: &PythonProjectionContext) -> String { + let element = py_native_param_element_type(inner, context); if matches!(inner, TypeMeta::U8) { format!("DynWinRTArray | bytes | bytearray | Sequence[{element}]") } else { @@ -411,20 +408,20 @@ fn py_array_param_type(inner: &TypeMeta, known_types: &HashSet) -> Strin } } -fn py_native_param_element_type(inner: &TypeMeta, known_types: &HashSet) -> String { +fn py_native_param_element_type(inner: &TypeMeta, context: &PythonProjectionContext) -> String { match inner { - TypeMeta::RuntimeClass { name, .. } if known_types.contains(name) => { - format!("'{name}Like'") + TypeMeta::RuntimeClass { name, .. } if context.is_known_type(inner) => { + format!("'{}Like'", context.reference_name_for_type(inner)) } - _ => py_native_element_type(inner, known_types), + _ => py_native_element_type(inner, context), } } -fn py_array_return_type(inner: &TypeMeta, known_types: &HashSet) -> String { +fn py_array_return_type(inner: &TypeMeta, context: &PythonProjectionContext) -> String { if matches!(inner, TypeMeta::U8) { "bytes".to_string() } else { - let element = py_native_element_type(inner, known_types); + let element = py_native_element_type(inner, context); let element = if is_nullable_reference_type(inner) { py_optional_type(element) } else { @@ -434,7 +431,7 @@ fn py_array_return_type(inner: &TypeMeta, known_types: &HashSet) -> Stri } } -fn py_collection_param_type(typ: &TypeMeta, known_types: &HashSet) -> Option { +fn py_collection_param_type(typ: &TypeMeta, context: &PythonProjectionContext) -> Option { let TypeMeta::Parameterized { args, .. } = typ else { return None; }; @@ -455,8 +452,8 @@ fn py_collection_param_type(typ: &TypeMeta, known_types: &HashSet) -> Op }; return Some(format!( "Mapping[{}, {}]", - py_native_param_element_type(key, known_types), - py_native_param_element_type(value, known_types) + py_native_param_element_type(key, context), + py_native_param_element_type(value, context) )); } let element = args.first()?; @@ -473,13 +470,13 @@ fn py_collection_param_type(typ: &TypeMeta, known_types: &HashSet) -> Op } else { "Sequence" }, - py_native_param_element_type(element, known_types) + py_native_param_element_type(element, context) )), _ => None, } } -fn py_collection_return_type(typ: &TypeMeta, known_types: &HashSet) -> Option { +fn py_collection_return_type(typ: &TypeMeta, context: &PythonProjectionContext) -> Option { let TypeMeta::Parameterized { args, .. } = typ else { return None; }; @@ -488,7 +485,7 @@ fn py_collection_return_type(typ: &TypeMeta, known_types: &HashSet) -> O let types = args .iter() .map(|arg| { - let element = py_native_element_type(arg, known_types); + let element = py_native_element_type(arg, context); if is_nullable_reference_type(arg) { py_optional_type(element) } else { @@ -501,24 +498,14 @@ fn py_collection_return_type(typ: &TypeMeta, known_types: &HashSet) -> O pub(super) fn py_param_list( in_params: &[&crate::meta::ParamMeta], - known_types: &HashSet, - delegate_type_names: &HashSet, + context: &PythonProjectionContext, ) -> String { in_params .iter() .map(|p| { let param_type = match &p.typ { - TypeMeta::Delegate { .. } => py_delegate_param_type(&p.typ, known_types), - TypeMeta::Interface { name, .. } if delegate_type_names.contains(name) => { - py_delegate_param_type(&p.typ, known_types) - } - TypeMeta::Parameterized { name, args, .. } - if delegate_type_names - .contains(&crate::meta::make_parameterized_name(name, args)) => - { - py_delegate_param_type(&p.typ, known_types) - } - _ => py_param_type_safe(&p.typ, known_types), + typ if context.is_delegate_type(typ) => py_delegate_param_type(typ, context), + _ => py_param_type_safe(&p.typ, context), }; format!("{}: {}", to_snake_case(&p.name), param_type) }) @@ -529,25 +516,34 @@ pub(super) fn py_param_list( /// Produce a typed Python annotation for a delegate parameter, with /// `TypedEventHandler` / `EventHandler` unwrapped. Bespoke non-parametric /// delegates fall back to `Callable[..., object]`. -pub(crate) fn py_delegate_callable_type(typ: &TypeMeta, known_types: &HashSet) -> String { +pub(crate) fn py_delegate_callable_type( + typ: &TypeMeta, + context: &PythonProjectionContext, +) -> String { match typ { TypeMeta::Parameterized { name, args, .. } if name.split('`').next() == Some("TypedEventHandler") && args.len() == 2 => { - let sender = py_return_type_safe(Some(&args[0]), known_types); - let arg = py_return_type_safe(Some(&args[1]), known_types); + let sender = py_return_type_safe(Some(&args[0]), context); + let arg = py_return_type_safe(Some(&args[1]), context); format!("Callable[[{}, {}], object]", sender, arg) } TypeMeta::Parameterized { name, args, .. } if name.split('`').next() == Some("EventHandler") && args.len() == 1 => { - let arg = py_return_type_safe(Some(&args[0]), known_types); + let arg = py_return_type_safe(Some(&args[0]), context); format!("Callable[[object, {}], object]", arg) } TypeMeta::Parameterized { name, args, .. } if name.split('`').next() == Some("VectorChangedEventHandler") && args.len() == 1 => { - let observable = crate::meta::make_parameterized_name("IObservableVector", args); + let observable_identity = crate::types::TypeIdentity::closed_generic( + crate::types::TypeIdentityKind::Interface, + crate::meta::WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, + "IObservableVector", + args.iter().map(TypeMeta::type_identity), + ); + let observable = context.reference_name(&observable_identity); format!( "Callable[['{}', 'IVectorChangedEventArgs'], object]", observable @@ -557,8 +553,8 @@ pub(crate) fn py_delegate_callable_type(typ: &TypeMeta, known_types: &HashSet) -> String { - let sig = py_delegate_callable_type(typ, known_types); +fn py_delegate_param_type(typ: &TypeMeta, context: &PythonProjectionContext) -> String { + let sig = py_delegate_callable_type(typ, context); format!("{sig} | 'DynWinRTValue'") } @@ -593,7 +589,7 @@ mod tests { assert_eq!(outputs[0], (0, &TypeMeta::U32)); assert_eq!(outputs[1], (1, &TypeMeta::Bool)); assert_eq!( - py_method_return_type(&method, &HashSet::new(), &HashSet::new()), + py_method_return_type(&method, &PythonProjectionContext::default()), "tuple[int, bool]" ); } @@ -626,7 +622,7 @@ mod tests { (0, &TypeMeta::Array(Box::new(TypeMeta::String))) ); assert_eq!( - py_method_return_type(&method, &HashSet::new(), &HashSet::new()), + py_method_return_type(&method, &PythonProjectionContext::default()), "list[str]" ); assert_eq!( @@ -642,7 +638,7 @@ mod tests { #[test] fn object_arrays_return_typed_runtime_values() { assert_eq!( - py_array_return_type(&TypeMeta::Object, &HashSet::new()), + py_array_return_type(&TypeMeta::Object, &PythonProjectionContext::default()), "list[DynWinRTValue | None]" ); } @@ -659,22 +655,26 @@ mod tests { name: "IWidget".into(), iid: "11111111-1111-1111-1111-111111111111".into(), }; - let known = HashSet::from(["Widget".into(), "IWidget".into()]); + let context = PythonProjectionContext::standalone([ + runtime_class.type_identity(), + interface.type_identity(), + ]) + .unwrap(); assert_eq!( - py_return_type_safe(Some(&runtime_class), &known), + py_return_type_safe(Some(&runtime_class), &context), "Widget | None" ); assert_eq!( - py_return_type_safe(Some(&interface), &known), + py_return_type_safe(Some(&interface), &context), "IWidget | None" ); assert_eq!( - py_return_type_safe(Some(&TypeMeta::Object), &known), + py_return_type_safe(Some(&TypeMeta::Object), &context), "DynWinRTValue | None" ); assert_eq!( - py_array_return_type(&runtime_class, &known), + py_array_return_type(&runtime_class, &context), "list[Widget | None]" ); } @@ -690,12 +690,13 @@ mod tests { }, direction: ParamDirection::In, }; + let context = PythonProjectionContext::standalone([param + .typ + .type_identity() + .with_kind(crate::types::TypeIdentityKind::Delegate)]) + .unwrap(); assert_eq!( - py_param_list( - &[¶m], - &HashSet::from(["Handler".into()]), - &HashSet::from(["Handler".into()]) - ), + py_param_list(&[¶m], &context), "handler: Callable[..., object] | 'DynWinRTValue'" ); } @@ -710,11 +711,11 @@ mod tests { }; assert_eq!( - py_return_type_safe(Some(&reference), &HashSet::new()), + py_return_type_safe(Some(&reference), &PythonProjectionContext::default()), "int | None" ); assert_eq!( - py_param_type_safe(&reference, &HashSet::new()), + py_param_type_safe(&reference, &PythonProjectionContext::default()), "int | None | IReference_UInt32" ); assert_eq!(py_optional_type("'DayOfWeek'".into()), "DayOfWeek | None"); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs index 06cc0966..20a5fb65 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs @@ -8,7 +8,7 @@ use std::collections::HashSet; use std::sync::LazyLock; use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection}; -use crate::types::{TypeKind, TypeMeta, TypeRef}; +use crate::types::{TypeIdentity, TypeKind, TypeMeta, TypeRef}; /// Empty set passed as `deferred` for codegen (no circular dep handling needed). pub(crate) static NO_DEFERRED: LazyLock> = LazyLock::new(HashSet::new); @@ -34,70 +34,69 @@ pub(crate) fn ireference_inner_type(typ: &TypeMeta) -> Option<&TypeMeta> { } } -/// Collect the set of known generic collection names used in method signatures. -/// Returns e.g. ["IVectorView", "IMap"] for import generation. -pub(crate) fn collect_used_generics_from_methods(methods: &[MethodMeta]) -> Vec { - let refs: Vec<&MethodMeta> = methods.iter().collect(); - collect_used_generics_from_methods_inner(&refs) -} - -fn visit_used_generics(typ: &TypeMeta, names: &mut HashSet) { +fn visit_used_generic_identities(typ: &TypeMeta, identities: &mut HashSet) { match typ { - TypeMeta::Parameterized { name, args, .. } => { - names.insert(crate::meta::make_parameterized_name(name, args)); - for arg in args { - visit_used_generics(arg, names); + TypeMeta::Parameterized { args, .. } => { + identities.insert(typ.type_identity()); + for argument in args { + visit_used_generic_identities(argument, identities); } } TypeMeta::AsyncOperation(inner) | TypeMeta::AsyncActionWithProgress(inner) => { - visit_used_generics(inner, names) + visit_used_generic_identities(inner, identities) } - TypeMeta::AsyncOperationWithProgress(r, p) => { - visit_used_generics(r, names); - visit_used_generics(p, names); + TypeMeta::AsyncOperationWithProgress(result, progress) => { + visit_used_generic_identities(result, identities); + visit_used_generic_identities(progress, identities); } - TypeMeta::Array(inner) => visit_used_generics(inner, names), + TypeMeta::Array(inner) => visit_used_generic_identities(inner, identities), TypeMeta::Struct { fields, .. } => { for field in fields { - visit_used_generics(&field.typ, names); + visit_used_generic_identities(&field.typ, identities); } } _ => {} } } -pub(crate) fn collect_used_generics_from_type(typ: &TypeMeta) -> Vec { - let mut names = HashSet::new(); - visit_used_generics(typ, &mut names); - let mut sorted = names.into_iter().collect::>(); +pub(crate) fn collect_used_generic_identities_from_type(typ: &TypeMeta) -> Vec { + let mut identities = HashSet::new(); + visit_used_generic_identities(typ, &mut identities); + let mut sorted = identities.into_iter().collect::>(); sorted.sort(); sorted } -/// Shared implementation for collecting generic names from method references. -fn collect_used_generics_from_methods_inner(methods: &[&MethodMeta]) -> Vec { - let mut names: HashSet = HashSet::new(); - for m in methods { - for p in &m.params { - visit_used_generics(&p.typ, &mut names); +fn collect_used_generic_identities_from_methods_inner( + methods: &[&MethodMeta], +) -> Vec { + let mut identities = HashSet::new(); + for method in methods { + for parameter in &method.params { + visit_used_generic_identities(¶meter.typ, &mut identities); } - if let Some(ref rt) = m.return_type { - visit_used_generics(rt, &mut names); + if let Some(return_type) = &method.return_type { + visit_used_generic_identities(return_type, &mut identities); } } - let mut sorted: Vec = names.into_iter().collect(); + let mut sorted = identities.into_iter().collect::>(); sorted.sort(); sorted } -/// Collect all used generic names from a class (all its interfaces). -pub(crate) fn collect_used_generics_from_class(class: &ClassMeta) -> Vec { - let all_methods: Vec<&MethodMeta> = class +pub(crate) fn collect_used_generic_identities_from_methods( + methods: &[MethodMeta], +) -> Vec { + let methods = methods.iter().collect::>(); + collect_used_generic_identities_from_methods_inner(&methods) +} + +pub(crate) fn collect_used_generic_identities_from_class(class: &ClassMeta) -> Vec { + let methods = class .all_interfaces() - .flat_map(|iface| &iface.methods) - .collect(); - // Reuse the same visitor logic as collect_used_generics_from_methods - collect_used_generics_from_methods_inner(&all_methods) + .flat_map(|interface| interface.methods.iter()) + .collect::>(); + collect_used_generic_identities_from_methods_inner(&methods) } // ====================================================================== diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index 23e79565..c5fc28e6 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -20,7 +20,7 @@ use dynwinrt_codegen::codegen::winrt::extensions::winui; use dynwinrt_codegen::codegen::{project, render_dts, render_js}; use dynwinrt_codegen::com_metadata; use dynwinrt_codegen::meta; -use dynwinrt_codegen::types::TypeMeta; +use dynwinrt_codegen::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; use dynwinrt_codegen::xml_doc::DocTable; #[derive(Parser)] @@ -664,17 +664,6 @@ fn run() -> Result<(), String> { // Write (or append to) the index file for the output directory if !dry_run { - type AppendFn = - fn(&str, &[meta::ClassMeta], &[meta::InterfaceMeta], &[TypeMeta]) -> String; - type GenerateFn = - fn(&[meta::ClassMeta], &[meta::InterfaceMeta], &[TypeMeta]) -> String; - let (append_fn, generate_fn): (AppendFn, GenerateFn) = if lang == "py" { - (python::append_to_index, python::generate_index) - } else { - // For JS lang, we use an in-memory `.ts` index then split into .js + .d.ts. - // We pick a sentinel filename `index.js` to detect presence; `.d.ts` is written alongside. - (typescript::append_to_index, typescript::generate_index) - }; let deps = resolve_dependencies_for_lang( &winmd, &classes, @@ -733,6 +722,7 @@ fn run() -> Result<(), String> { &all_classes, &all_interfaces, &all_enums, + &meta::ambiguous_named_type_names(&winmd), pyi, true, )?; @@ -746,9 +736,14 @@ fn run() -> Result<(), String> { let existing = fs::read_to_string(&dts_path).map_err(|e| { format!("Failed to read {}: {}", dts_path.display(), e) })?; - append_fn(&existing, &all_classes, &all_interfaces, &all_enums) + typescript::append_to_index( + &existing, + &all_classes, + &all_interfaces, + &all_enums, + ) } else { - generate_fn(&all_classes, &all_interfaces, &all_enums) + typescript::generate_index(&all_classes, &all_interfaces, &all_enums) }; write_js_barrel_and_manifest(output_dir, &index_content)?; } @@ -886,6 +881,7 @@ fn run() -> Result<(), String> { &all_classes, &all_interfaces, &all_enums, + &meta::ambiguous_named_type_names(&winmd), pyi, false, )?; @@ -1141,6 +1137,7 @@ fn generate_for_types( let mut struct_interfaces = emittable_interfaces.clone(); struct_interfaces.extend(shared_interfaces.iter().cloned()); python::validate_struct_symbol_uniqueness(&all_classes, &struct_interfaces)?; + validate_python_interface_abi_identities(&struct_interfaces)?; } for iface in &shared_interfaces { known_types.insert(iface.name.clone()); @@ -1159,8 +1156,9 @@ fn generate_for_types( } } - let python_layout = if lang == "py" { - Some(install_python_generation_layout( + let python_context = if lang == "py" { + Some(python_generation_context( + winmd, &all_classes, &emittable_interfaces, &all_enums, @@ -1170,19 +1168,23 @@ fn generate_for_types( } else { None }; - let (delegate_signatures, delegate_sig_refs, delegate_param_wraps) = - project::build_delegate_signatures(&all_interfaces, &delegate_type_names, &known_types); + let (delegate_signatures, delegate_sig_refs, delegate_param_wraps) = if lang == "py" { + (HashMap::new(), HashMap::new(), HashMap::new()) + } else { + project::build_delegate_signatures(&all_interfaces, &delegate_type_names, &known_types) + }; if !dry_run { if lang == "py" { generate_py_files( + python_context + .as_ref() + .expect("Python generation context must be available"), output_dir, &all_classes, &emittable_interfaces, &all_enums, &shared_interfaces, - &known_types, - &delegate_type_names, &shared_iids, pyi, )?; @@ -1211,7 +1213,6 @@ fn generate_for_types( )?, )?; } - drop(python_layout); } Ok(( @@ -1228,49 +1229,67 @@ fn python_type_identities( enums: &[TypeMeta], ) -> Vec { let mut identities = Vec::new(); - identities.extend(classes.iter().map(|class| python::PythonTypeIdentity { - namespace: class.namespace.clone(), - name: class.name.clone(), + identities.extend(classes.iter().map(|class| { + TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ) })); + identities.extend(interfaces.iter().map(meta::InterfaceMeta::type_identity)); identities.extend( - interfaces + enums .iter() - .map(|interface| python::PythonTypeIdentity { - namespace: interface.namespace.clone(), - name: interface.name.clone(), - }), + .filter(|typ| matches!(typ, TypeMeta::Enum { .. })) + .map(TypeMeta::type_identity), ); - identities.extend(enums.iter().filter_map(|typ| { - let TypeMeta::Enum { - namespace, name, .. - } = typ - else { - return None; - }; - Some(python::PythonTypeIdentity { - namespace: namespace.clone(), - name: name.clone(), - }) - })); identities.extend( - python::package_struct_identities(classes, interfaces) - .into_iter() - .map(|(namespace, name)| python::PythonTypeIdentity { namespace, name }), + python::package_structs(classes, interfaces) + .iter() + .map(TypeMeta::type_identity), ); identities } -fn install_python_generation_layout( +fn python_generation_context( + winmd: &str, classes: &[meta::ClassMeta], interfaces: &[meta::InterfaceMeta], enums: &[TypeMeta], supplemental_interfaces: &[meta::InterfaceMeta], existing_identities: &[python::PythonTypeIdentity], -) -> Result { +) -> Result { let mut identities = python_type_identities(classes, interfaces, enums); identities.extend(python_type_identities(&[], supplemental_interfaces, &[])); identities.extend_from_slice(existing_identities); - python::install_python_module_layout(identities) + python::PythonProjectionContext::packaged_with_ambiguities( + identities, + meta::ambiguous_named_type_names(winmd), + ) +} + +fn validate_python_interface_abi_identities( + interfaces: &[meta::InterfaceMeta], +) -> Result<(), String> { + let mut abi_by_identity = HashMap::::new(); + for interface in interfaces { + let identity = interface.type_identity(); + let abi = interface + .generic_piid + .as_ref() + .map(|piid| format!("piid:{piid}")) + .unwrap_or_else(|| format!("iid:{}", interface.iid)); + if let Some(existing) = abi_by_identity.insert(identity.clone(), abi.clone()) + && existing != abi + { + return Err(format!( + "Python semantic identity `{}` has conflicting ABI identities `{existing}` and \ + `{abi}`", + python::python_identity_display_name(&identity) + )); + } + } + Ok(()) } const JAVASCRIPT_TYPE_INVENTORY: &str = ".dynwinrt-js-types"; @@ -3311,13 +3330,12 @@ fn strip_broken_imports(output_dir: &Path) -> Result<(), String> { } fn generate_py_files( + context: &python::PythonProjectionContext, output_dir: &Path, all_classes: &[meta::ClassMeta], all_interfaces: &[meta::InterfaceMeta], all_enums: &[TypeMeta], shared_interfaces: &[meta::InterfaceMeta], - known_types: &HashSet, - delegate_type_names: &HashSet, shared_iids: &HashSet, pyi: bool, ) -> Result<(), String> { @@ -3347,40 +3365,37 @@ fn generate_py_files( // interface or enum with the same namespace/name. Generate in precedence // order and render each final module exactly once. for class in all_classes { - let module = python::python_module_name(&class.namespace, &class.name); + let identity = TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + let module = context.implementation_module(&identity); if !generated_modules.insert(module.clone()) { continue; } - let code = python::generate_class(class, known_types, delegate_type_names, shared_iids); + let code = python::generate_class(context, class, shared_iids); let filepath = output_dir.join(format!("{module}.py")); write_file(&filepath, &code)?; println!("Generated {}", filepath.display()); if pyi { - let stub = python_stub::generate_class_stub( - class, - known_types, - delegate_type_names, - shared_iids, - ); + let stub = python_stub::generate_class_stub(context, class, shared_iids); write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; } } for en in all_enums { - if let TypeMeta::Enum { - namespace, name, .. - } = en - { - let module = python::python_module_name(namespace, name); + if let TypeMeta::Enum { .. } = en { + let module = context.implementation_module_for_type(en); if !generated_modules.insert(module.clone()) { continue; } - if let Some(code) = python::generate_enum(en) { + if let Some(code) = python::generate_enum(context, en) { let filepath = output_dir.join(format!("{module}.py")); write_file(&filepath, &code)?; println!("Generated {}", filepath.display()); } if pyi { - if let Some(stub) = python_stub::generate_enum_stub(en) { + if let Some(stub) = python_stub::generate_enum_stub(context, en) { let p = output_dir.join(format!("{module}.pyi")); write_file(&p, &stub)?; } @@ -3388,17 +3403,16 @@ fn generate_py_files( } } for iface in all_interfaces.iter().chain(shared_interfaces) { - let module = python::python_module_name(&iface.namespace, &iface.name); + let module = context.implementation_module_for_interface(iface); if !generated_modules.insert(module.clone()) { continue; } - let code = python::generate_interface(iface, known_types, delegate_type_names); + let code = python::generate_interface(context, iface); let filepath = output_dir.join(format!("{module}.py")); write_file(&filepath, &code)?; println!("Generated {}", filepath.display()); if pyi { - let stub = - python_stub::generate_interface_stub(iface, known_types, delegate_type_names); + let stub = python_stub::generate_interface_stub(context, iface); write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; } } @@ -3409,19 +3423,19 @@ fn generate_py_files( else { continue; }; - let module = python::python_module_name(namespace, name); + let module = context.implementation_module_for_type(typ); if !generated_modules.insert(module.clone()) { return Err(format!( "Python struct module `{namespace}.{name}` collides with another generated type" )); } - if let Some(code) = python::generate_struct(typ) { + if let Some(code) = python::generate_struct(context, typ) { let filepath = output_dir.join(format!("{module}.py")); write_file(&filepath, &code)?; println!("Generated {}", filepath.display()); } if pyi { - if let Some(stub) = python_stub::generate_struct_stub(typ) { + if let Some(stub) = python_stub::generate_struct_stub(context, typ) { write_file(&output_dir.join(format!("{module}.pyi")), &stub)?; } } @@ -3441,7 +3455,7 @@ struct PythonNamespaceGroup { structs: Vec, } -#[derive(Clone, Debug, Eq, Hash, PartialEq)] +#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] struct PythonGeneratedType { kind: String, identity: python::PythonTypeIdentity, @@ -3452,11 +3466,13 @@ fn write_python_package_indexes( classes: &[meta::ClassMeta], interfaces: &[meta::InterfaceMeta], enums: &[TypeMeta], + ambiguous_named_types: &HashSet, pyi: bool, append: bool, ) -> Result<(), String> { use dynwinrt_codegen::codegen::python_stub; + validate_python_interface_abi_identities(interfaces)?; let current_structs = python::package_structs(classes, interfaces); let current_types = python_generated_types(classes, interfaces, enums); let mut all_types = if append { @@ -3472,58 +3488,60 @@ fn write_python_package_indexes( .iter() .map(|typ| typ.identity.clone()) .collect::>(); - let _layout = python::install_python_module_layout(module_identities.clone())?; - validate_python_public_identities(&module_identities)?; - - let mut interface_counts = HashMap::::new(); - for typ in &all_types { - if typ.kind == "interface" { - *interface_counts - .entry(typ.identity.name.clone()) - .or_default() += 1; - } - } - if let Some((name, _)) = interface_counts.iter().find(|(_, count)| **count > 1) { - return Err(format!( - "Python generation cannot safely project multiple interfaces named `{name}`; \ - their delegate and generic runtime symbols are ambiguous" - )); - } + let context = python::PythonProjectionContext::packaged_with_ambiguities( + module_identities.clone(), + ambiguous_named_types.iter().cloned(), + )?; + validate_python_public_identities(&context, &module_identities)?; - let mut counts = HashMap::::new(); - for typ in &all_types { - *counts.entry(typ.identity.name.clone()).or_default() += 1; - } - let suppressed_root_names = counts + let suppressed_root_names = module_identities .iter() - .filter(|(_, count)| **count > 1) - .map(|(name, _)| name.clone()) + .filter(|identity| !context.root_name_is_unambiguous(identity)) + .flat_map(|identity| { + [ + context.compatibility_name(identity), + context.projected_name(identity), + context.reference_name(identity), + ] + }) .collect::>(); let root_classes = classes .iter() - .filter(|class| counts[&class.name] == 1) + .filter(|class| { + context.root_name_is_unambiguous(&TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + )) + }) .cloned() .collect::>(); let root_interfaces = interfaces .iter() - .filter(|interface| counts[&interface.name] == 1) + .filter(|interface| context.root_name_is_unambiguous(&interface.type_identity())) .cloned() .collect::>(); let root_enums = enums .iter() - .filter(|typ| matches!(typ, TypeMeta::Enum { name, .. } if counts[name] == 1)) + .filter(|typ| { + matches!(typ, TypeMeta::Enum { .. }) + && context.root_name_is_unambiguous(&typ.type_identity()) + }) .cloned() .collect::>(); let root_structs = current_structs .iter() - .filter(|typ| matches!(typ, TypeMeta::Struct { name, .. } if counts[name] == 1)) + .filter(|typ| { + matches!(typ, TypeMeta::Struct { .. }) + && context.root_name_is_unambiguous(&typ.type_identity()) + }) .cloned() .collect::>(); let mut root_index = - python::generate_public_index(&root_classes, &root_interfaces, &root_enums); + python::generate_public_index(&context, &root_classes, &root_interfaces, &root_enums); root_index.push_str( - python::generate_public_struct_index(&root_structs) + python::generate_public_struct_index(&context, &root_structs) .strip_prefix(GENERATED_PYTHON_HEADER) .unwrap_or_default(), ); @@ -3534,10 +3552,14 @@ fn write_python_package_indexes( &suppressed_root_names, )?; if pyi { - let mut root_stub = - python_stub::generate_public_index_stub(&root_classes, &root_interfaces, &root_enums); + let mut root_stub = python_stub::generate_public_index_stub( + &context, + &root_classes, + &root_interfaces, + &root_enums, + ); root_stub.push_str( - python_stub::generate_public_struct_index_stub(&root_structs) + python_stub::generate_public_struct_index_stub(&context, &root_structs) .strip_prefix(GENERATED_PYTHON_HEADER) .unwrap_or_default(), ); @@ -3585,13 +3607,14 @@ fn write_python_package_indexes( } for (namespace, group) in groups { - write_python_namespace_group(output_dir, &namespace, &group, pyi, append)?; + write_python_namespace_group(&context, output_dir, &namespace, &group, pyi, append)?; } write_python_type_inventory(output_dir, &all_types)?; Ok(()) } fn write_python_namespace_group( + context: &python::PythonProjectionContext, output_dir: &Path, namespace: &str, group: &PythonNamespaceGroup, @@ -3626,24 +3649,35 @@ fn write_python_namespace_group( let mut seen = HashSet::new(); for class in &group.classes { - if !seen.insert(class.name.clone()) { + let identity = TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ); + if !seen.insert(identity.clone()) { continue; } - let runtime = python::generate_index(std::slice::from_ref(class), &[], &[]); + let type_name = context.projected_name(&identity); + let runtime = python::generate_index(context, std::slice::from_ref(class), &[], &[]); write_python_facade( + context, &package_dir, &segments, - &class.name, + &identity, + &type_name, &runtime, "py", &mut runtime_exports, )?; if pyi { - let stub = python_stub::generate_index_stub(std::slice::from_ref(class), &[], &[]); + let stub = + python_stub::generate_index_stub(context, std::slice::from_ref(class), &[], &[]); write_python_facade( + context, &package_dir, &segments, - &class.name, + &identity, + &type_name, &stub, "pyi", &mut stub_exports, @@ -3651,24 +3685,35 @@ fn write_python_namespace_group( } } for interface in &group.interfaces { - if !seen.insert(interface.name.clone()) { + let identity = interface.type_identity(); + if !seen.insert(identity.clone()) { continue; } - let runtime = python::generate_index(&[], std::slice::from_ref(interface), &[]); + let type_name = context.projected_name(&identity); + let runtime = python::generate_index(context, &[], std::slice::from_ref(interface), &[]); write_python_facade( + context, &package_dir, &segments, - &interface.name, + &identity, + &type_name, &runtime, "py", &mut runtime_exports, )?; if pyi { - let stub = python_stub::generate_index_stub(&[], std::slice::from_ref(interface), &[]); + let stub = python_stub::generate_index_stub( + context, + &[], + std::slice::from_ref(interface), + &[], + ); write_python_facade( + context, &package_dir, &segments, - &interface.name, + &identity, + &type_name, &stub, "pyi", &mut stub_exports, @@ -3676,27 +3721,34 @@ fn write_python_namespace_group( } } for typ in &group.enums { - let TypeMeta::Enum { name, .. } = typ else { + let TypeMeta::Enum { .. } = typ else { continue; }; - if !seen.insert(name.clone()) { + let identity = typ.type_identity(); + if !seen.insert(identity.clone()) { continue; } - let runtime = python::generate_index(&[], &[], std::slice::from_ref(typ)); + let type_name = context.projected_name(&identity); + let runtime = python::generate_index(context, &[], &[], std::slice::from_ref(typ)); write_python_facade( + context, &package_dir, &segments, - name, + &identity, + &type_name, &runtime, "py", &mut runtime_exports, )?; if pyi { - let stub = python_stub::generate_index_stub(&[], &[], std::slice::from_ref(typ)); + let stub = + python_stub::generate_index_stub(context, &[], &[], std::slice::from_ref(typ)); write_python_facade( + context, &package_dir, &segments, - name, + &identity, + &type_name, &stub, "pyi", &mut stub_exports, @@ -3704,30 +3756,36 @@ fn write_python_namespace_group( } } for typ in &group.structs { - let TypeMeta::Struct { name, .. } = typ else { + let TypeMeta::Struct { .. } = typ else { continue; }; - if !seen.insert(name.clone()) { + let identity = typ.type_identity(); + if !seen.insert(identity.clone()) { continue; } - let runtime = python::generate_struct_index(std::slice::from_ref(typ)); + let type_name = context.projected_name(&identity); + let runtime = python::generate_struct_index(context, std::slice::from_ref(typ)); if runtime.lines().any(|line| line.starts_with("from .")) { write_python_facade( + context, &package_dir, &segments, - name, + &identity, + &type_name, &runtime, "py", &mut runtime_exports, )?; } if pyi { - let stub = python_stub::generate_struct_index_stub(std::slice::from_ref(typ)); + let stub = python_stub::generate_struct_index_stub(context, std::slice::from_ref(typ)); if stub.lines().any(|line| line.starts_with("from .")) { write_python_facade( + context, &package_dir, &segments, - name, + &identity, + &type_name, &stub, "pyi", &mut stub_exports, @@ -3757,8 +3815,10 @@ fn write_python_namespace_group( } fn write_python_facade( + context: &python::PythonProjectionContext, package_dir: &Path, namespace_segments: &[String], + identity: &python::PythonTypeIdentity, type_name: &str, implementation_index: &str, extension: &str, @@ -3802,7 +3862,7 @@ fn write_python_facade( if extension == "py" && exported_type { facade.push_str(&format!("\n{type_name}.__module__ = __name__\n")); } - let public_module = python::python_public_module_name(type_name); + let public_module = context.public_module(identity); write_file( &package_dir.join(format!("{public_module}.{extension}")), &facade, @@ -3814,6 +3874,8 @@ fn write_python_facade( format!("from .{public_module} import {type_name}") }; package_exports.push(package_export); + } else if !exports.is_empty() { + package_exports.push(format!("from .{public_module} import {exports}")); } Ok(()) } @@ -4013,39 +4075,31 @@ fn python_generated_types( let mut types = Vec::new(); types.extend(classes.iter().map(|class| PythonGeneratedType { kind: "class".into(), - identity: python::PythonTypeIdentity { - namespace: class.namespace.clone(), - name: class.name.clone(), - }, + identity: TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + ), })); types.extend(interfaces.iter().map(|interface| PythonGeneratedType { kind: "interface".into(), - identity: python::PythonTypeIdentity { - namespace: interface.namespace.clone(), - name: interface.name.clone(), - }, + identity: interface.type_identity(), })); types.extend(enums.iter().filter_map(|typ| { - let TypeMeta::Enum { - namespace, name, .. - } = typ - else { + let TypeMeta::Enum { .. } = typ else { return None; }; Some(PythonGeneratedType { kind: "enum".into(), - identity: python::PythonTypeIdentity { - namespace: namespace.clone(), - name: name.clone(), - }, + identity: typ.type_identity(), }) })); types.extend( - python::package_struct_identities(classes, interfaces) + python::package_structs(classes, interfaces) .into_iter() - .map(|(namespace, name)| PythonGeneratedType { + .map(|typ| PythonGeneratedType { kind: "struct".into(), - identity: python::PythonTypeIdentity { namespace, name }, + identity: typ.type_identity(), }), ); types @@ -4061,23 +4115,15 @@ fn read_python_type_inventory(output_dir: &Path) -> Result>(); + .collect::, _>>()?; lines.sort(); lines.dedup(); write_file( @@ -4124,24 +4168,30 @@ fn validate_python_public_paths( enums: &[TypeMeta], ) -> Result<(), String> { let identities = python_type_identities(classes, interfaces, enums); - validate_python_public_identities(&identities) + let context = python::PythonProjectionContext::packaged(identities.clone())?; + validate_python_public_identities(&context, &identities) } fn validate_python_public_identities( + context: &python::PythonProjectionContext, identities: &[python::PythonTypeIdentity], ) -> Result<(), String> { let mut namespace_owners = HashMap::::new(); let mut namespace_paths = HashSet::new(); for identity in identities { - let segments = python::python_namespace_segments(&identity.namespace); + let namespace = identity.namespace().ok_or_else(|| { + format!( + "Python public type identity must be named: {}", + python::python_identity_display_name(identity) + ) + })?; + let segments = python::python_namespace_segments(namespace); let normalized = segments.join("/"); - if let Some(existing) = - namespace_owners.insert(normalized.clone(), identity.namespace.clone()) - { - if existing != identity.namespace { + if let Some(existing) = namespace_owners.insert(normalized.clone(), namespace.to_string()) { + if existing != namespace { return Err(format!( "Python namespace collision: `{existing}` and `{}` both normalize to `{normalized}`", - identity.namespace + namespace )); } } @@ -4152,20 +4202,22 @@ fn validate_python_public_identities( let mut module_owners = HashMap::::new(); for identity in identities { - let mut segments = python::python_namespace_segments(&identity.namespace); - segments.push(python::python_public_module_name(&identity.name)); + let namespace = identity.namespace().expect("validated named identity"); + let mut segments = python::python_namespace_segments(namespace); + segments.push(context.public_module(identity)); let module_path = segments.join("/"); if namespace_paths.contains(&module_path) { return Err(format!( - "Python package/module collision: `{}.{}` normalizes to package path `{module_path}`", - identity.namespace, identity.name + "Python package/module collision: `{}` normalizes to package path `{module_path}`", + python::python_identity_display_name(identity) )); } if let Some(existing) = module_owners.insert(module_path.clone(), identity.clone()) { if existing != *identity { return Err(format!( - "Python module collision: `{}.{}` and `{}.{}` both normalize to `{module_path}.py`", - existing.namespace, existing.name, identity.namespace, identity.name + "Python module collision: `{}` and `{}` both normalize to `{module_path}.py`", + python::python_identity_display_name(&existing), + python::python_identity_display_name(identity) )); } } @@ -6061,7 +6113,8 @@ mod tests { }, ]; - write_python_package_indexes(&output, &classes, &[], &[], true, false).unwrap(); + write_python_package_indexes(&output, &classes, &[], &[], &HashSet::new(), true, false) + .unwrap(); let root = fs::read_to_string(output.join("__init__.py")).unwrap(); assert!(!root.contains("ResourceManager")); @@ -6112,6 +6165,7 @@ mod tests { std::slice::from_ref(&contoso), &[], &[], + &HashSet::new(), true, true, ) @@ -6127,6 +6181,7 @@ mod tests { std::slice::from_ref(&fabrikam), &[], &[], + &HashSet::new(), true, true, ) @@ -6154,6 +6209,389 @@ mod tests { fs::remove_dir_all(output).unwrap(); } + #[test] + fn incremental_python_generation_removes_disambiguated_generic_root_export() { + let output = test_directory("incremental-generic-root"); + fs::create_dir_all(&output).unwrap(); + let interface = |namespace: &str| meta::InterfaceMeta { + name: "IBox_Point".into(), + namespace: "Example.Collections".into(), + iid: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(), + generic_piid: Some("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into()), + generic_name: Some("IBox`1".into()), + generic_args: vec![TypeMeta::Struct { + namespace: namespace.into(), + name: "Point".into(), + fields: vec![], + }], + ..Default::default() + }; + let left = interface("Example.Left"); + let right = interface("Example.Right"); + let ambiguity = HashSet::from(["Point".into()]); + + write_python_package_indexes( + &output, + &[], + std::slice::from_ref(&left), + &[], + &ambiguity, + true, + true, + ) + .unwrap(); + let first_root = fs::read_to_string(output.join("__init__.py")).unwrap(); + assert!( + first_root.contains("IBox_Example_Left_Point_struct"), + "{first_root}" + ); + + write_python_package_indexes( + &output, + &[], + std::slice::from_ref(&right), + &[], + &ambiguity, + true, + true, + ) + .unwrap(); + let final_root = fs::read_to_string(output.join("__init__.py")).unwrap(); + assert!(!final_root.contains("IBox_"), "{final_root}"); + + fs::remove_dir_all(output).unwrap(); + } + + fn colliding_delegate(namespace: &str, iid: &str) -> meta::InterfaceMeta { + meta::InterfaceMeta { + name: "ChangedHandler".into(), + namespace: namespace.into(), + iid: iid.into(), + methods: vec![ + meta::MethodMeta { + name: ".ctor".into(), + ..Default::default() + }, + meta::MethodMeta { + name: "Invoke".into(), + params: vec![meta::ParamMeta { + name: "value".into(), + typ: TypeMeta::String, + direction: meta::ParamDirection::In, + }], + ..Default::default() + }, + ], + ..Default::default() + } + } + + fn colliding_interface(namespace: &str, iid: &str, delegate_iid: &str) -> meta::InterfaceMeta { + meta::InterfaceMeta { + name: "IValue".into(), + namespace: namespace.into(), + iid: iid.into(), + methods: vec![meta::MethodMeta { + name: "SetHandler".into(), + params: vec![meta::ParamMeta { + name: "handler".into(), + typ: TypeMeta::Interface { + namespace: namespace.into(), + name: "ChangedHandler".into(), + iid: delegate_iid.into(), + }, + direction: meta::ParamDirection::In, + }], + ..Default::default() + }], + ..Default::default() + } + } + + fn python_output_tree(root: &Path) -> BTreeMap { + fn visit(root: &Path, directory: &Path, output: &mut BTreeMap) { + for entry in fs::read_dir(directory).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + visit(root, &path, output); + } else { + output.insert( + path.strip_prefix(root) + .unwrap() + .to_string_lossy() + .replace('\\', "/"), + fs::read_to_string(path).unwrap(), + ); + } + } + } + + let mut output = BTreeMap::new(); + visit(root, root, &mut output); + output + } + + #[test] + fn same_short_interfaces_and_delegates_use_semantic_identity() { + let output = test_directory("same-short-python-identities"); + fs::create_dir_all(&output).unwrap(); + let left_delegate = + colliding_delegate("Example.Left", "11111111-1111-1111-1111-111111111111"); + let right_delegate = + colliding_delegate("Example.Right", "22222222-2222-2222-2222-222222222222"); + let left_interface = colliding_interface( + "Example.Left", + "33333333-3333-3333-3333-333333333333", + &left_delegate.iid, + ); + let right_interface = colliding_interface( + "Example.Right", + "44444444-4444-4444-4444-444444444444", + &right_delegate.iid, + ); + let classes = vec![meta::ClassMeta { + name: "Combined".into(), + namespace: "Example.Cross".into(), + full_name: "Example.Cross.Combined".into(), + default_interface: Some(left_interface.clone()), + required_interfaces: vec![right_interface.clone()], + ..Default::default() + }]; + let interfaces = vec![ + left_interface, + right_interface, + meta::InterfaceMeta { + name: "ICrossNamespace".into(), + namespace: "Example.Cross".into(), + iid: "55555555-5555-5555-5555-555555555555".into(), + methods: vec![meta::MethodMeta { + name: "UseValues".into(), + params: vec![ + meta::ParamMeta { + name: "left".into(), + typ: TypeMeta::Interface { + namespace: "Example.Left".into(), + name: "IValue".into(), + iid: "33333333-3333-3333-3333-333333333333".into(), + }, + direction: meta::ParamDirection::In, + }, + meta::ParamMeta { + name: "right".into(), + typ: TypeMeta::Interface { + namespace: "Example.Right".into(), + name: "IValue".into(), + iid: "44444444-4444-4444-4444-444444444444".into(), + }, + direction: meta::ParamDirection::In, + }, + ], + ..Default::default() + }], + ..Default::default() + }, + left_delegate, + right_delegate, + ]; + let ambiguity = HashSet::from(["IValue".into(), "ChangedHandler".into()]); + let context = python::PythonProjectionContext::packaged_with_ambiguities( + python_type_identities(&classes, &interfaces, &[]), + ambiguity.iter().cloned(), + ) + .unwrap(); + + generate_py_files( + &context, + &output, + &classes, + &interfaces, + &[], + &[], + &HashSet::new(), + true, + ) + .unwrap(); + write_python_package_indexes(&output, &classes, &interfaces, &[], &ambiguity, true, false) + .unwrap(); + + let left = fs::read_to_string(output.join("example__left__i_value.py")).unwrap(); + let right = fs::read_to_string(output.join("example__right__i_value.py")).unwrap(); + assert!( + left.contains( + "_dynwinrt_symbol('example__left__changed_handler', 'IID_ChangedHandler')" + ) + ); + assert!( + right.contains( + "_dynwinrt_symbol('example__right__changed_handler', 'IID_ChangedHandler')" + ) + ); + let cross = + fs::read_to_string(output.join("example__cross__i_cross_namespace.py")).unwrap(); + assert!( + cross.contains("IValue as Example_Left_IValue_interface"), + "{cross}" + ); + assert!( + cross.contains("IValue as Example_Right_IValue_interface"), + "{cross}" + ); + assert!( + cross.contains( + "left: 'Example_Left_IValue_interface', right: 'Example_Right_IValue_interface'" + ), + "{cross}" + ); + assert!( + cross.contains("33333333-3333-3333-3333-333333333333"), + "{cross}" + ); + assert!( + cross.contains("44444444-4444-4444-4444-444444444444"), + "{cross}" + ); + let combined = fs::read_to_string(output.join("example__cross__combined.py")).unwrap(); + assert!( + combined.contains("IID_Example_Left_IValue_interface"), + "{combined}" + ); + assert!( + combined.contains("IID_Example_Right_IValue_interface"), + "{combined}" + ); + assert!( + combined.contains("_Example_Left_IValue_interface = DynWinRTType.register_interface"), + "{combined}" + ); + assert!( + combined.contains("_Example_Right_IValue_interface = DynWinRTType.register_interface"), + "{combined}" + ); + let root = fs::read_to_string(output.join("__init__.py")).unwrap(); + assert!(!root.contains("IValue"), "{root}"); + assert!(!root.contains("ChangedHandler"), "{root}"); + for namespace in ["left", "right"] { + let facade = + fs::read_to_string(output.join("example").join(namespace).join("__init__.py")) + .unwrap(); + assert!(facade.contains("\"IValue\""), "{facade}"); + assert!(facade.contains("\"IID_ChangedHandler\""), "{facade}"); + assert!( + facade.contains("\"ChangedHandler_PARAM_TYPES\""), + "{facade}" + ); + assert!(facade.contains("(\".i_value\", \"IValue\")"), "{facade}"); + assert!( + facade.contains("(\".changed_handler\", \"IID_ChangedHandler\")"), + "{facade}" + ); + } + fs::remove_dir_all(output).unwrap(); + } + + #[test] + fn conflicting_abi_for_one_python_semantic_identity_fails_closed() { + let interfaces = [ + meta::InterfaceMeta { + name: "IValue".into(), + namespace: "Example".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + ..Default::default() + }, + meta::InterfaceMeta { + name: "IValue".into(), + namespace: "Example".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), + ..Default::default() + }, + ]; + + let error = validate_python_interface_abi_identities(&interfaces).unwrap_err(); + assert!(error.contains("Example.IValue"), "{error}"); + assert!(error.contains("conflicting ABI identities"), "{error}"); + } + + #[test] + fn same_short_python_generation_is_incrementally_byte_stable() { + let one_shot = test_directory("same-short-one-shot"); + let phased = test_directory("same-short-phased"); + fs::create_dir_all(&one_shot).unwrap(); + fs::create_dir_all(&phased).unwrap(); + let left_delegate = + colliding_delegate("Example.Left", "11111111-1111-1111-1111-111111111111"); + let right_delegate = + colliding_delegate("Example.Right", "22222222-2222-2222-2222-222222222222"); + let left = vec![ + colliding_interface( + "Example.Left", + "33333333-3333-3333-3333-333333333333", + &left_delegate.iid, + ), + left_delegate, + ]; + let right = vec![ + colliding_interface( + "Example.Right", + "44444444-4444-4444-4444-444444444444", + &right_delegate.iid, + ), + right_delegate, + ]; + let all = [left.as_slice(), right.as_slice()].concat(); + let ambiguity = HashSet::from(["IValue".into(), "ChangedHandler".into()]); + + let one_shot_context = python::PythonProjectionContext::packaged_with_ambiguities( + python_type_identities(&[], &all, &[]), + ambiguity.iter().cloned(), + ) + .unwrap(); + generate_py_files( + &one_shot_context, + &one_shot, + &[], + &all, + &[], + &[], + &HashSet::new(), + true, + ) + .unwrap(); + write_python_package_indexes(&one_shot, &[], &all, &[], &ambiguity, true, false).unwrap(); + + for phase in [&left, &right] { + let existing = read_python_type_inventory(&phased) + .unwrap() + .into_iter() + .map(|typ| typ.identity) + .collect::>(); + let mut identities = python_type_identities(&[], phase, &[]); + identities.extend(existing); + let context = python::PythonProjectionContext::packaged_with_ambiguities( + identities, + ambiguity.iter().cloned(), + ) + .unwrap(); + generate_py_files( + &context, + &phased, + &[], + phase, + &[], + &[], + &HashSet::new(), + true, + ) + .unwrap(); + write_python_package_indexes(&phased, &[], phase, &[], &ambiguity, true, true).unwrap(); + } + + assert_eq!(python_output_tree(&one_shot), python_output_tree(&phased)); + write_python_package_indexes(&phased, &[], &right, &[], &ambiguity, true, true).unwrap(); + assert_eq!(python_output_tree(&one_shot), python_output_tree(&phased)); + fs::remove_dir_all(one_shot).unwrap(); + fs::remove_dir_all(phased).unwrap(); + } + #[test] fn python_package_module_collisions_are_rejected() { let classes = vec![ @@ -6324,19 +6762,9 @@ mod tests { fn python_generation_emits_shared_runtime_and_typing_support() { let output = test_directory("python-shared-support"); fs::create_dir_all(&output).unwrap(); + let context = python::PythonProjectionContext::packaged([]).unwrap(); - generate_py_files( - &output, - &[], - &[], - &[], - &[], - &HashSet::new(), - &HashSet::new(), - &HashSet::new(), - true, - ) - .unwrap(); + generate_py_files(&context, &output, &[], &[], &[], &[], &HashSet::new(), true).unwrap(); assert!(output.join("_runtime.py").is_file()); assert!(output.join("_runtime.pyi").is_file()); @@ -6386,25 +6814,20 @@ mod tests { default_interface: Some(interface), ..Default::default() }; - let known_types = HashSet::from(["Point".into(), "Widget".into()]); - - { - let _layout = - install_python_generation_layout(std::slice::from_ref(&class), &[], &[], &[], &[]) - .unwrap(); - generate_py_files( - &output, - std::slice::from_ref(&class), - &[], - &[], - &[], - &known_types, - &HashSet::new(), - &HashSet::new(), - true, - ) - .unwrap(); - } + let context = + python_generation_context("", std::slice::from_ref(&class), &[], &[], &[], &[]) + .unwrap(); + generate_py_files( + &context, + &output, + std::slice::from_ref(&class), + &[], + &[], + &[], + &HashSet::new(), + true, + ) + .unwrap(); let class_py = fs::read_to_string(output.join("contoso__widget.py")).unwrap(); let class_pyi = fs::read_to_string(output.join("contoso__widget.pyi")).unwrap(); @@ -6415,8 +6838,16 @@ mod tests { assert!(!class_pyi.contains("\nclass Point:")); assert!(struct_py.contains("\nclass Point:")); - write_python_package_indexes(&output, std::slice::from_ref(&class), &[], &[], true, false) - .unwrap(); + write_python_package_indexes( + &output, + std::slice::from_ref(&class), + &[], + &[], + &HashSet::new(), + true, + false, + ) + .unwrap(); let point_facade = fs::read_to_string(output.join("windows/foundation/point.py")).unwrap(); assert!(point_facade.contains("Point.__module__ = __name__")); assert!(point_facade.contains("Point_TYPE")); @@ -6505,14 +6936,15 @@ mod tests { #[test] fn incremental_python_generation_reuses_existing_module_layout() { - let existing = [python::PythonTypeIdentity { - namespace: "Windows.Foundation.Collections".into(), - name: "IIterable_IKeyValuePair_Object_Object".into(), - }]; - let _layout = install_python_generation_layout(&[], &[], &[], &[], &existing).unwrap(); + let existing = [TypeIdentity::named( + TypeIdentityKind::Interface, + "Windows.Foundation.Collections", + "IIterable_IKeyValuePair_Object_Object", + )]; + let context = python_generation_context("", &[], &[], &[], &[], &existing).unwrap(); assert_eq!( - python::to_snake_case_filename("IIterable_IKeyValuePair_Object_Object"), + context.implementation_module(&existing[0]), "windows__foundation__collections__i_iterable_i_key_value_pair_object_object" ); } @@ -6527,22 +6959,20 @@ mod tests { ..Default::default() }]; - { - let _layout = install_python_generation_layout(&[], &[], &[], &shared, &[]).unwrap(); - assert_eq!( - python::to_snake_case_filename("IIterable_IKeyValuePair_Object_Object"), - "windows__foundation__collections__i_iterable_i_key_value_pair_object_object" - ); - } + let context = python_generation_context("", &[], &[], &[], &shared, &[]).unwrap(); + assert_eq!( + context.implementation_module_for_interface(&shared[0]), + "windows__foundation__collections__i_iterable_i_key_value_pair_object_object" + ); write_python_type_inventory(&output, &[]).unwrap(); record_python_supplemental_types(&output, &shared).unwrap(); let inventory = read_python_type_inventory(&output).unwrap(); - assert!(inventory.iter().any(|typ| typ.identity - == python::PythonTypeIdentity { - namespace: shared[0].namespace.clone(), - name: shared[0].name.clone(), - })); + assert!( + inventory + .iter() + .any(|typ| typ.identity == shared[0].type_identity()) + ); fs::remove_dir_all(output).unwrap(); } @@ -6764,6 +7194,7 @@ mod tests { &[], std::slice::from_ref(&interface), &[], + &HashSet::new(), true, false, ) diff --git a/tools/dynwinrt-codegen/src/meta.rs b/tools/dynwinrt-codegen/src/meta.rs index 40980266..730a509d 100644 --- a/tools/dynwinrt-codegen/src/meta.rs +++ b/tools/dynwinrt-codegen/src/meta.rs @@ -1,12 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::path::Path; use windows_metadata::{HasAttributes, reader}; -use crate::types::{EnumMember, TypeKind, TypeMeta, TypeRef}; +use crate::types::{EnumMember, TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef}; pub const WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE: &str = "Windows.Foundation.Collections"; pub const PIID_IVECTOR: &str = "913337e9-11a1-4345-a3a2-4e7f956e222d"; @@ -68,6 +68,8 @@ pub struct InterfaceMeta { pub methods: Vec, /// For parameterized interfaces: the PIID (generic IID before instantiation). pub generic_piid: Option, + /// Metadata name of the generic definition before projection name mangling. + pub generic_name: Option, /// For parameterized interfaces: the type arguments used to instantiate. pub generic_args: Vec, /// XML doc summary (populated from sibling .xml). @@ -76,6 +78,35 @@ pub struct InterfaceMeta { pub deprecated: Option, } +impl InterfaceMeta { + pub fn is_delegate(&self) -> bool { + self.methods.iter().any(|method| method.name == ".ctor") + && self.methods.iter().any(|method| method.name == "Invoke") + } + + pub fn type_identity(&self) -> TypeIdentity { + let kind = if self.is_delegate() { + TypeIdentityKind::Delegate + } else { + TypeIdentityKind::Interface + }; + if self.generic_piid.is_some() { + let generic_name = self + .generic_name + .as_deref() + .unwrap_or_else(|| self.name.split('_').next().unwrap_or(self.name.as_str())); + TypeIdentity::closed_generic( + kind, + self.namespace.clone(), + generic_name, + self.generic_args.iter().map(TypeMeta::type_identity), + ) + } else { + TypeIdentity::named(kind, self.namespace.clone(), self.name.clone()) + } + } +} + fn same_interface_identity(left: &InterfaceMeta, right: &InterfaceMeta) -> bool { if left.namespace != right.namespace { return false; @@ -265,6 +296,47 @@ pub fn list_namespaces(winmd_paths: &str) -> Vec { sorted } +/// Return named type short names that identify more than one semantic type in +/// the loaded metadata graph. +pub fn ambiguous_named_type_names(winmd_paths: &str) -> HashSet { + let Some(index) = load_index(winmd_paths) else { + return HashSet::new(); + }; + let mut identities = HashMap::>::new(); + for def in index.all() { + let namespace = def.namespace(); + if namespace.is_empty() { + continue; + } + let name = def.name().split('`').next().unwrap_or(def.name()); + let kind = match def.extends() { + Some(base) if base.namespace() == "System" && base.name() == "Enum" => { + TypeIdentityKind::Enum + } + Some(base) if base.namespace() == "System" && base.name() == "ValueType" => { + TypeIdentityKind::Struct + } + Some(base) + if base.namespace() == "System" + && matches!(base.name(), "Delegate" | "MulticastDelegate") => + { + TypeIdentityKind::Delegate + } + Some(_) => TypeIdentityKind::Class, + None => TypeIdentityKind::Interface, + }; + identities + .entry(name.to_string()) + .or_default() + .insert((namespace.to_string(), kind)); + } + identities + .into_iter() + .filter(|(_, identities)| identities.len() > 1) + .map(|(name, _)| name) + .collect() +} + /// Parse a WinMD file and extract metadata for a single RuntimeClass. /// Accepts multiple winmd paths separated by ';'. pub fn parse_class(winmd_paths: &str, namespace: &str, name: &str) -> Option { @@ -454,7 +526,7 @@ pub fn resolve_python_dependencies( existing_interfaces, existing_enums, true, - false, + true, ) } @@ -464,7 +536,7 @@ fn resolve_dependencies_impl( existing_interfaces: &[InterfaceMeta], existing_enums: &[TypeMeta], include_inheritance: bool, - fully_qualified_identity: bool, + preserve_semantic_identity: bool, ) -> ResolvedDeps { let index = match load_index(winmd_paths) { Some(idx) => idx, @@ -477,62 +549,26 @@ fn resolve_dependencies_impl( } }; - // Track all known type names (already generated or discovered) - let mut known: HashSet = HashSet::new(); + // Preserve semantic identities so namespace-distinct and closed generic + // dependencies cannot collapse before either language projects a name. + let mut known: HashSet = HashSet::new(); for c in classes { - known.insert(c.name.clone()); + known.insert(dependency_identity( + TypeIdentity::named(TypeIdentityKind::Class, c.namespace.clone(), c.name.clone()), + &c.name, + preserve_semantic_identity, + )); } for i in existing_interfaces { - known.insert(i.name.clone()); + known.insert(dependency_identity( + i.type_identity(), + &i.name, + preserve_semantic_identity, + )); } - for e in existing_enums { - if let TypeMeta::Enum { name, .. } = e { - known.insert(name.clone()); - } + for typ in existing_enums { + known.insert(type_dependency_identity(typ, preserve_semantic_identity)); } - let mut known_named = HashSet::new(); - known_named.extend(classes.iter().map(|class| TypeRef { - namespace: class.namespace.clone(), - name: class.name.clone(), - kind: TypeKind::Class, - })); - known_named.extend(existing_interfaces.iter().map(|interface| TypeRef { - namespace: interface.namespace.clone(), - name: interface.name.clone(), - kind: TypeKind::Interface, - })); - known_named.extend(existing_enums.iter().filter_map(|typ| { - let TypeMeta::Enum { - namespace, name, .. - } = typ - else { - return None; - }; - Some(TypeRef { - namespace: namespace.clone(), - name: name.clone(), - kind: TypeKind::Enum, - }) - })); - let mut known_parameterized = existing_interfaces - .iter() - .filter_map(|interface| { - interface.generic_piid.as_ref().map(|piid| { - let suffix = make_parameterized_name("", &interface.generic_args); - let generic_name = interface - .name - .strip_suffix(&suffix) - .unwrap_or(&interface.name); - parameterized_dependency_key( - &interface.namespace, - generic_name, - piid, - &interface.generic_args, - ) - }) - }) - .collect::>(); - let mut dep_classes: Vec = Vec::new(); let mut dep_interfaces: Vec = Vec::new(); let mut dep_enums: Vec = Vec::new(); @@ -546,6 +582,7 @@ fn resolve_dependencies_impl( &mut worklist, &mut param_worklist, include_inheritance, + preserve_semantic_identity, ); collect_all_refs_from_interfaces( existing_interfaces, @@ -553,6 +590,7 @@ fn resolve_dependencies_impl( &mut worklist, &mut param_worklist, include_inheritance, + preserve_semantic_identity, ); // Fixpoint: keep resolving until no new types are discovered @@ -568,14 +606,11 @@ fn resolve_dependencies_impl( let mut new_interfaces = Vec::new(); for r in &batch { - if fully_qualified_identity { - if !known_named.insert(r.clone()) { - continue; - } - } else if known.contains(&r.name) { + let identity = type_ref_dependency_identity(r, preserve_semantic_identity); + if known.contains(&identity) { continue; } - known.insert(r.name.clone()); + known.insert(identity); match r.kind { TypeKind::Interface => { @@ -640,16 +675,17 @@ fn resolve_dependencies_impl( continue; } let concrete_name = make_parameterized_name(name, &resolved_args); - if fully_qualified_identity { - let identity = - parameterized_dependency_key(namespace, name, piid, &resolved_args); - if !known_parameterized.insert(identity) { - continue; - } - } else if known.contains(&concrete_name) { + let resolved_type = TypeMeta::Parameterized { + namespace: namespace.clone(), + name: name.clone(), + piid: piid.clone(), + args: resolved_args.clone(), + }; + let identity = type_dependency_identity(&resolved_type, preserve_semantic_identity); + if known.contains(&identity) { continue; } - known.insert(concrete_name.clone()); + known.insert(identity); if let Some(iface) = parse_parameterized_interface( &index, @@ -676,6 +712,7 @@ fn resolve_dependencies_impl( &mut worklist, &mut param_worklist, include_inheritance, + preserve_semantic_identity, ); collect_all_refs_from_interfaces( &new_interfaces, @@ -683,6 +720,7 @@ fn resolve_dependencies_impl( &mut worklist, &mut param_worklist, include_inheritance, + preserve_semantic_identity, ); dep_classes.extend(new_classes); @@ -754,9 +792,10 @@ fn visit_type_refs(typ: &TypeMeta, named: &mut Vec, parameterized: &mut /// Collect all type references from methods: both named and parameterized. fn collect_all_refs_from_methods( methods: &[MethodMeta], - _known: &HashSet, + known: &HashSet, named_out: &mut Vec, param_out: &mut Vec, + preserve_semantic_identity: bool, ) { let mut named = Vec::new(); let mut parameterized = Vec::new(); @@ -768,89 +807,80 @@ fn collect_all_refs_from_methods( visit_type_refs(rt, &mut named, &mut parameterized); } } - named_out.extend(named); - param_out.extend(parameterized); + for r in named { + if !known.contains(&type_ref_dependency_identity( + &r, + preserve_semantic_identity, + )) { + named_out.push(r); + } + } + for r in parameterized { + if !known.contains(&type_dependency_identity(&r, preserve_semantic_identity)) { + param_out.push(r); + } + } } fn collect_interface_base_ref( base: &TypeMeta, - _known: &HashSet, + known: &HashSet, named_out: &mut Vec, param_out: &mut Vec, + preserve_semantic_identity: bool, ) { let mut named = Vec::new(); let mut parameterized = Vec::new(); visit_type_refs(base, &mut named, &mut parameterized); - named_out.extend(named); - param_out.extend(parameterized); + named_out.extend(named.into_iter().filter(|reference| { + !known.contains(&type_ref_dependency_identity( + reference, + preserve_semantic_identity, + )) + })); + param_out.extend(parameterized.into_iter().filter(|reference| { + !known.contains(&type_dependency_identity( + reference, + preserve_semantic_identity, + )) + })); } -fn type_dependency_key(typ: &TypeMeta) -> String { - match typ { - TypeMeta::Bool => "bool".into(), - TypeMeta::I8 => "i8".into(), - TypeMeta::U8 => "u8".into(), - TypeMeta::I16 => "i16".into(), - TypeMeta::U16 => "u16".into(), - TypeMeta::I32 => "i32".into(), - TypeMeta::U32 => "u32".into(), - TypeMeta::I64 => "i64".into(), - TypeMeta::U64 => "u64".into(), - TypeMeta::F32 => "f32".into(), - TypeMeta::F64 => "f64".into(), - TypeMeta::Char16 => "char16".into(), - TypeMeta::String => "string".into(), - TypeMeta::Guid => "guid".into(), - TypeMeta::Object => "object".into(), - TypeMeta::Interface { - namespace, name, .. - } => format!("interface:{namespace}.{name}"), - TypeMeta::RuntimeClass { - namespace, name, .. - } => format!("class:{namespace}.{name}"), - TypeMeta::Delegate { - namespace, name, .. - } => format!("delegate:{namespace}.{name}"), - TypeMeta::Parameterized { - namespace, - name, - piid, - args, - } => parameterized_dependency_key(namespace, name, piid, args), - TypeMeta::Array(inner) => format!("array:{}", type_dependency_key(inner)), - TypeMeta::Struct { - namespace, name, .. - } => format!("struct:{namespace}.{name}"), - TypeMeta::Enum { - namespace, name, .. - } => format!("enum:{namespace}.{name}"), - TypeMeta::AsyncAction => "async-action".into(), - TypeMeta::AsyncActionWithProgress(progress) => { - format!("async-action-progress:{}", type_dependency_key(progress)) - } - TypeMeta::AsyncOperation(result) => { - format!("async-operation:{}", type_dependency_key(result)) +fn dependency_identity( + semantic: TypeIdentity, + legacy_name: &str, + preserve_semantic_identity: bool, +) -> TypeIdentity { + if preserve_semantic_identity { + semantic + } else { + TypeIdentity::Primitive { + name: format!("legacy:{legacy_name}"), } - TypeMeta::AsyncOperationWithProgress(result, progress) => format!( - "async-operation-progress:{},{}", - type_dependency_key(result), - type_dependency_key(progress) - ), } } -fn parameterized_dependency_key( - namespace: &str, - name: &str, - piid: &str, - args: &[TypeMeta], -) -> String { - format!( - "generic:{namespace}.{name}:{piid}<{}>", - args.iter() - .map(type_dependency_key) - .collect::>() - .join(",") +fn type_dependency_identity(typ: &TypeMeta, preserve_semantic_identity: bool) -> TypeIdentity { + dependency_identity( + typ.type_identity(), + &type_meta_short_name(typ), + preserve_semantic_identity, + ) +} + +fn type_ref_dependency_identity( + reference: &TypeRef, + preserve_semantic_identity: bool, +) -> TypeIdentity { + let kind = match reference.kind { + TypeKind::Class => TypeIdentityKind::Class, + TypeKind::Enum => TypeIdentityKind::Enum, + TypeKind::Interface => TypeIdentityKind::Interface, + }; + dependency_identity( + TypeIdentity::named(kind, reference.namespace.clone(), reference.name.clone()), + &reference.name, + preserve_semantic_identity, ) } @@ -890,21 +920,41 @@ fn type_meta_short_name(typ: &TypeMeta) -> String { /// Collect all refs from a list of classes (iterates all interface methods). fn collect_all_refs_from_classes( classes: &[ClassMeta], - known: &HashSet, + known: &HashSet, named_out: &mut Vec, param_out: &mut Vec, include_class_bases: bool, + preserve_semantic_identity: bool, ) { for c in classes { - if include_class_bases && let Some(base) = &c.base_class { + if include_class_bases + && let Some(base) = &c.base_class + && !known.contains(&type_ref_dependency_identity( + base, + preserve_semantic_identity, + )) + { named_out.push(base.clone()); } for iface in c.all_interfaces() { - collect_all_refs_from_methods(&iface.methods, known, named_out, param_out); + collect_all_refs_from_methods( + &iface.methods, + known, + named_out, + param_out, + preserve_semantic_identity, + ); } // Required interfaces themselves may need to be resolved for iface in &c.required_interfaces { - if iface.generic_piid.is_none() && !iface.name.is_empty() { + if iface.generic_piid.is_none() + && !iface.name.is_empty() + && !known.contains(&dependency_identity( + iface.type_identity(), + &iface.name, + preserve_semantic_identity, + )) + { named_out.push(TypeRef { namespace: iface.namespace.clone(), name: iface.name.clone(), @@ -918,16 +968,29 @@ fn collect_all_refs_from_classes( /// Collect all refs from a list of standalone interfaces. fn collect_all_refs_from_interfaces( interfaces: &[InterfaceMeta], - known: &HashSet, + known: &HashSet, named_out: &mut Vec, param_out: &mut Vec, include_interface_bases: bool, + preserve_semantic_identity: bool, ) { for i in interfaces { - collect_all_refs_from_methods(&i.methods, known, named_out, param_out); + collect_all_refs_from_methods( + &i.methods, + known, + named_out, + param_out, + preserve_semantic_identity, + ); if include_interface_bases { for base in &i.base_interfaces { - collect_interface_base_ref(base, known, named_out, param_out); + collect_interface_base_ref( + base, + known, + named_out, + param_out, + preserve_semantic_identity, + ); } } if i.generic_piid.as_deref() == Some(PIID_IOBSERVABLE_VECTOR) && i.generic_args.len() == 1 { @@ -937,7 +1000,12 @@ fn collect_all_refs_from_interfaces( piid: PIID_IVECTOR.into(), args: i.generic_args.clone(), }; - param_out.push(vector); + if !known.contains(&type_dependency_identity( + &vector, + preserve_semantic_identity, + )) { + param_out.push(vector); + } } } } @@ -1400,7 +1468,10 @@ fn parse_parameterized_interface( ) -> Option { let trimmed_name = generic_name.split('`').next().unwrap_or(generic_name); let def = index.get(namespace, trimmed_name).next()?; - parse_interface_methods(index, &def, concrete_name, namespace, piid, generic_args) + let mut interface = + parse_interface_methods(index, &def, concrete_name, namespace, piid, generic_args)?; + interface.generic_name = Some(generic_name.to_string()); + Some(interface) } fn interface_meta_type_identity(typ: &TypeMeta) -> Option<(String, String)> { @@ -1592,6 +1663,7 @@ fn parse_interface_methods( base_interfaces, methods, generic_piid, + generic_name: None, generic_args: generic_args_vec, doc: None, deprecated: None, @@ -2016,6 +2088,61 @@ mod tests { assert_eq!(name, "IIterable_IVector_Int32"); } + #[test] + fn dependency_identity_preserves_namespace_inside_closed_generics() { + let point = |namespace: &str| TypeMeta::Struct { + namespace: namespace.into(), + name: "Point".into(), + fields: vec![], + }; + let closed = |argument| TypeMeta::Parameterized { + namespace: "Example.Collections".into(), + name: "IBox`1".into(), + piid: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(), + args: vec![argument], + }; + let left = closed(point("Example.Left")); + let right = closed(point("Example.Right")); + + let projected_name = |typ: &TypeMeta| match typ { + TypeMeta::Parameterized { name, args, .. } => make_parameterized_name(name, args), + _ => unreachable!(), + }; + assert_eq!(projected_name(&left), projected_name(&right)); + assert_ne!(left.type_identity(), right.type_identity()); + } + + #[test] + fn dependency_collection_keeps_same_short_named_references() { + let left = TypeMeta::Interface { + namespace: "Example.Left".into(), + name: "IValue".into(), + iid: "11111111-1111-1111-1111-111111111111".into(), + }; + let right = TypeMeta::Interface { + namespace: "Example.Right".into(), + name: "IValue".into(), + iid: "22222222-2222-2222-2222-222222222222".into(), + }; + let known = HashSet::from([left.type_identity()]); + let method = MethodMeta { + params: vec![ParamMeta { + name: "value".into(), + typ: right, + direction: ParamDirection::In, + }], + ..Default::default() + }; + let mut named = Vec::new(); + let mut parameterized = Vec::new(); + + collect_all_refs_from_methods(&[method], &known, &mut named, &mut parameterized, true); + + assert_eq!(named.len(), 1); + assert_eq!(named[0].namespace, "Example.Right"); + assert!(parameterized.is_empty()); + } + #[test] fn instantiated_interface_identity_includes_generic_arguments() { let interface = |arg| InterfaceMeta { @@ -2036,16 +2163,17 @@ mod tests { #[test] fn parameterized_dependency_identity_includes_argument_namespace() { let key = |namespace: &str| { - parameterized_dependency_key( - WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE, - "IVector", - PIID_IVECTOR, - &[TypeMeta::RuntimeClass { + TypeMeta::Parameterized { + namespace: WINDOWS_FOUNDATION_COLLECTIONS_NAMESPACE.into(), + name: "IVector".into(), + piid: PIID_IVECTOR.into(), + args: vec![TypeMeta::RuntimeClass { namespace: namespace.into(), name: "PointerPoint".into(), default_interface: None, }], - ) + } + .type_identity() }; assert_ne!(key("Windows.UI.Input"), key("Microsoft.UI.Input")); @@ -2209,19 +2337,18 @@ mod tests { "versioned User interfaces must remain available" ); - let known_types = HashSet::from(["User".to_string()]); - let py = crate::codegen::winrt::python::generate_class( - &class, - &known_types, - &HashSet::new(), - &HashSet::new(), - ); - let pyi = crate::codegen::python_stub::generate_class_stub( - &class, - &known_types, - &HashSet::new(), - &HashSet::new(), - ); + let context = crate::codegen::python::PythonProjectionContext::standalone( + std::iter::once(TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + )) + .chain(class.all_interfaces().map(InterfaceMeta::type_identity)), + ) + .unwrap(); + let py = crate::codegen::winrt::python::generate_class(&context, &class, &HashSet::new()); + let pyi = + crate::codegen::python_stub::generate_class_stub(&context, &class, &HashSet::new()); assert!(py.contains("def _from_native(cls, obj: DynWinRTValue):")); assert!(py.contains("User cannot be constructed directly")); assert!(pyi.contains("def __init__(self, _not_constructible: NoReturn) -> None: ...")); @@ -2338,17 +2465,27 @@ mod tests { .iter() .any(|interface| interface.name == "IAutomationPeerOverrides") ); - let known_types = HashSet::from(["AutomationPeer".to_string()]); + let context = crate::codegen::python::PythonProjectionContext::standalone( + std::iter::once(TypeIdentity::named( + TypeIdentityKind::Class, + automation_peer.namespace.clone(), + automation_peer.name.clone(), + )) + .chain( + automation_peer + .all_interfaces() + .map(InterfaceMeta::type_identity), + ), + ) + .unwrap(); let py = crate::codegen::winrt::python::generate_class( + &context, &automation_peer, - &known_types, - &HashSet::new(), &HashSet::new(), ); let pyi = crate::codegen::python_stub::generate_class_stub( + &context, &automation_peer, - &known_types, - &HashSet::new(), &HashSet::new(), ); assert!(py.contains("AutomationPeer cannot be constructed directly")); @@ -2589,6 +2726,7 @@ mod iface_tests { &mut named, &mut parameterized, false, + true, ); assert!(named.is_empty()); diff --git a/tools/dynwinrt-codegen/src/types.rs b/tools/dynwinrt-codegen/src/types.rs index 1e897645..122fe7c2 100644 --- a/tools/dynwinrt-codegen/src/types.rs +++ b/tools/dynwinrt-codegen/src/types.rs @@ -2,13 +2,209 @@ // Licensed under the MIT License. /// The kind of a named WinRT type reference. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +#[derive( + Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Deserialize, serde::Serialize, +)] +#[serde(rename_all = "snake_case")] pub enum TypeKind { Class, Enum, Interface, } +/// The semantic kind of a projected WinRT type. +#[derive( + Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Deserialize, serde::Serialize, +)] +#[serde(rename_all = "snake_case")] +pub enum TypeIdentityKind { + Class, + Delegate, + Enum, + Interface, + Struct, +} + +/// Canonical identity for a WinRT type, including recursively closed generics. +/// +/// Projection names are deliberately not part of this model. Language +/// projections may derive readable symbols and paths from this identity without +/// weakening the namespace, kind, or nested generic argument identity used for +/// lookup and collision handling. +#[derive( + Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, serde::Deserialize, serde::Serialize, +)] +#[serde(tag = "shape", rename_all = "snake_case")] +pub enum TypeIdentity { + Primitive { + name: String, + }, + Named { + kind: TypeIdentityKind, + namespace: String, + name: String, + }, + ClosedGeneric { + kind: TypeIdentityKind, + namespace: String, + name: String, + arguments: Vec, + }, + Array { + element: Box, + }, + AsyncAction, + AsyncActionWithProgress { + progress: Box, + }, + AsyncOperation { + result: Box, + }, + AsyncOperationWithProgress { + result: Box, + progress: Box, + }, +} + +impl TypeIdentity { + pub fn named( + kind: TypeIdentityKind, + namespace: impl Into, + name: impl Into, + ) -> Self { + Self::Named { + kind, + namespace: namespace.into(), + name: name.into(), + } + } + + pub fn closed_generic( + kind: TypeIdentityKind, + namespace: impl Into, + name: impl Into, + arguments: impl IntoIterator, + ) -> Self { + Self::ClosedGeneric { + kind, + namespace: namespace.into(), + name: name + .into() + .split('`') + .next() + .unwrap_or_default() + .to_string(), + arguments: arguments.into_iter().collect(), + } + } + + pub fn kind(&self) -> Option { + match self { + Self::Named { kind, .. } | Self::ClosedGeneric { kind, .. } => Some(*kind), + _ => None, + } + } + + pub fn namespace(&self) -> Option<&str> { + match self { + Self::Named { namespace, .. } | Self::ClosedGeneric { namespace, .. } => { + Some(namespace) + } + _ => None, + } + } + + pub fn definition_name(&self) -> Option<&str> { + match self { + Self::Named { name, .. } | Self::ClosedGeneric { name, .. } => Some(name), + _ => None, + } + } + + pub fn with_kind(&self, kind: TypeIdentityKind) -> Self { + match self { + Self::Named { + namespace, name, .. + } => Self::named(kind, namespace.clone(), name.clone()), + Self::ClosedGeneric { + namespace, + name, + arguments, + .. + } => Self::closed_generic( + kind, + namespace.clone(), + name.clone(), + arguments.iter().cloned(), + ), + _ => self.clone(), + } + } + + /// Stable, unambiguous text used only as hash input and diagnostics. + pub fn canonical_key(&self) -> String { + fn atom(value: &str) -> String { + format!("{}:{value}", value.len()) + } + + fn append(identity: &TypeIdentity, out: &mut String) { + match identity { + TypeIdentity::Primitive { name } => { + out.push_str("p"); + out.push_str(&atom(name)); + } + TypeIdentity::Named { + kind, + namespace, + name, + } => { + out.push_str("n"); + out.push_str(&format!("{kind:?}:")); + out.push_str(&atom(namespace)); + out.push_str(&atom(name)); + } + TypeIdentity::ClosedGeneric { + kind, + namespace, + name, + arguments, + } => { + out.push_str("g"); + out.push_str(&format!("{kind:?}:")); + out.push_str(&atom(namespace)); + out.push_str(&atom(name)); + out.push_str(&format!("{}:", arguments.len())); + for argument in arguments { + append(argument, out); + } + } + TypeIdentity::Array { element } => { + out.push('a'); + append(element, out); + } + TypeIdentity::AsyncAction => out.push_str("async-action"), + TypeIdentity::AsyncActionWithProgress { progress } => { + out.push_str("async-action-progress"); + append(progress, out); + } + TypeIdentity::AsyncOperation { result } => { + out.push_str("async-operation"); + append(result, out); + } + TypeIdentity::AsyncOperationWithProgress { result, progress } => { + out.push_str("async-operation-progress"); + append(result, out); + append(progress, out); + } + } + } + + let mut result = String::new(); + append(self, &mut result); + result + } +} + /// A reference to a named WinRT type (namespace + name + kind). /// Replaces raw `(String, String, &str)` tuples for type-safe dependency tracking. #[derive(Debug, Clone, PartialEq, Eq, Hash)] @@ -104,6 +300,72 @@ pub struct EnumMember { } impl TypeMeta { + /// Return the canonical semantic identity represented by this metadata type. + pub fn type_identity(&self) -> TypeIdentity { + let primitive = |name: &str| TypeIdentity::Primitive { + name: name.to_string(), + }; + match self { + Self::Bool => primitive("Boolean"), + Self::I8 => primitive("Int8"), + Self::U8 => primitive("UInt8"), + Self::I16 => primitive("Int16"), + Self::U16 => primitive("UInt16"), + Self::I32 => primitive("Int32"), + Self::U32 => primitive("UInt32"), + Self::I64 => primitive("Int64"), + Self::U64 => primitive("UInt64"), + Self::F32 => primitive("Single"), + Self::F64 => primitive("Double"), + Self::Char16 => primitive("Char16"), + Self::String => primitive("String"), + Self::Guid => primitive("Guid"), + Self::Object => primitive("Object"), + Self::Interface { + namespace, name, .. + } => TypeIdentity::named(TypeIdentityKind::Interface, namespace, name), + Self::RuntimeClass { + namespace, name, .. + } => TypeIdentity::named(TypeIdentityKind::Class, namespace, name), + Self::Delegate { + namespace, name, .. + } => TypeIdentity::named(TypeIdentityKind::Delegate, namespace, name), + Self::Parameterized { + namespace, + name, + args, + .. + } => TypeIdentity::closed_generic( + TypeIdentityKind::Interface, + namespace, + name, + args.iter().map(TypeMeta::type_identity), + ), + Self::Array(element) => TypeIdentity::Array { + element: Box::new(element.type_identity()), + }, + Self::Struct { + namespace, name, .. + } => TypeIdentity::named(TypeIdentityKind::Struct, namespace, name), + Self::Enum { + namespace, name, .. + } => TypeIdentity::named(TypeIdentityKind::Enum, namespace, name), + Self::AsyncAction => TypeIdentity::AsyncAction, + Self::AsyncActionWithProgress(progress) => TypeIdentity::AsyncActionWithProgress { + progress: Box::new(progress.type_identity()), + }, + Self::AsyncOperation(result) => TypeIdentity::AsyncOperation { + result: Box::new(result.type_identity()), + }, + Self::AsyncOperationWithProgress(result, progress) => { + TypeIdentity::AsyncOperationWithProgress { + result: Box::new(result.type_identity()), + progress: Box::new(progress.type_identity()), + } + } + } + } + /// Returns true if this type represents an async operation. pub fn is_async(&self) -> bool { matches!( diff --git a/tools/dynwinrt-codegen/tests/common/mod.rs b/tools/dynwinrt-codegen/tests/common/mod.rs new file mode 100644 index 00000000..40b07d41 --- /dev/null +++ b/tools/dynwinrt-codegen/tests/common/mod.rs @@ -0,0 +1,195 @@ +#![allow(dead_code)] + +use std::collections::HashSet; + +use dynwinrt_codegen::codegen::python::{self, PythonProjectionContext}; +use dynwinrt_codegen::codegen::python_stub; +use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta}; +use dynwinrt_codegen::types::{TypeIdentity, TypeIdentityKind, TypeMeta}; + +fn compatibility_name(typ: &TypeMeta) -> String { + match typ { + TypeMeta::RuntimeClass { name, .. } + | TypeMeta::Interface { name, .. } + | TypeMeta::Delegate { name, .. } + | TypeMeta::Struct { name, .. } + | TypeMeta::Enum { name, .. } => name.clone(), + TypeMeta::Parameterized { name, args, .. } => { + dynwinrt_codegen::meta::make_parameterized_name(name, args) + } + _ => String::new(), + } +} + +fn collect_type( + typ: &TypeMeta, + known: &HashSet, + delegates: &HashSet, + identities: &mut HashSet, +) { + let compatibility_name = compatibility_name(typ); + let raw_identity = typ.type_identity(); + let full_name = raw_identity + .namespace() + .zip(raw_identity.definition_name()) + .map(|(namespace, name)| format!("{namespace}.{name}")); + if known.contains(&compatibility_name) + || full_name.as_ref().is_some_and(|name| known.contains(name)) + || delegates.contains(&compatibility_name) + || matches!(typ, TypeMeta::Delegate { .. }) + { + let identity = if delegates.contains(&compatibility_name) { + raw_identity.with_kind(TypeIdentityKind::Delegate) + } else { + raw_identity + }; + identities.insert(identity); + } + + match typ { + TypeMeta::Parameterized { args, .. } => { + for argument in args { + collect_type(argument, known, delegates, identities); + } + } + TypeMeta::Array(inner) + | TypeMeta::AsyncActionWithProgress(inner) + | TypeMeta::AsyncOperation(inner) => collect_type(inner, known, delegates, identities), + TypeMeta::AsyncOperationWithProgress(result, progress) => { + collect_type(result, known, delegates, identities); + collect_type(progress, known, delegates, identities); + } + TypeMeta::RuntimeClass { + default_interface: Some(interface), + .. + } => collect_type(interface, known, delegates, identities), + TypeMeta::Struct { fields, .. } => { + for field in fields { + collect_type(&field.typ, known, delegates, identities); + } + } + _ => {} + } +} + +fn collect_methods( + methods: &[MethodMeta], + known: &HashSet, + delegates: &HashSet, + identities: &mut HashSet, +) { + for method in methods { + for parameter in &method.params { + collect_type(¶meter.typ, known, delegates, identities); + } + if let Some(return_type) = &method.return_type { + collect_type(return_type, known, delegates, identities); + } + } +} + +fn context( + classes: &[&ClassMeta], + interfaces: &[&InterfaceMeta], + known: &HashSet, + delegates: &HashSet, + packaged: bool, +) -> PythonProjectionContext { + let mut identities = HashSet::new(); + for full_name in known.iter().filter(|name| name.contains('.')) { + if let Some((namespace, name)) = full_name.rsplit_once('.') { + identities.insert(TypeIdentity::named( + TypeIdentityKind::Class, + namespace, + name, + )); + } + } + for class in classes { + identities.insert(TypeIdentity::named( + TypeIdentityKind::Class, + class.namespace.clone(), + class.name.clone(), + )); + for interface in class + .all_interfaces() + .chain(class.overridable_interfaces.iter()) + { + identities.insert(interface.type_identity()); + collect_methods(&interface.methods, known, delegates, &mut identities); + } + } + for interface in interfaces { + identities.insert(interface.type_identity()); + collect_methods(&interface.methods, known, delegates, &mut identities); + } + PythonProjectionContext::new(identities, packaged).unwrap() +} + +pub fn projection_context( + classes: &[ClassMeta], + interfaces: &[InterfaceMeta], + known: &HashSet, + delegates: &HashSet, +) -> PythonProjectionContext { + context( + &classes.iter().collect::>(), + &interfaces.iter().collect::>(), + known, + delegates, + false, + ) +} + +pub fn packaged_projection_context( + classes: &[ClassMeta], + interfaces: &[InterfaceMeta], + known: &HashSet, + delegates: &HashSet, +) -> PythonProjectionContext { + context( + &classes.iter().collect::>(), + &interfaces.iter().collect::>(), + known, + delegates, + true, + ) +} + +pub fn generate_class( + class: &ClassMeta, + known: &HashSet, + delegates: &HashSet, + shared_iids: &HashSet, +) -> String { + let context = context(&[class], &[], known, delegates, false); + python::generate_class(&context, class, shared_iids) +} + +pub fn generate_class_stub( + class: &ClassMeta, + known: &HashSet, + delegates: &HashSet, + shared_iids: &HashSet, +) -> String { + let context = context(&[class], &[], known, delegates, false); + python_stub::generate_class_stub(&context, class, shared_iids) +} + +pub fn generate_interface( + interface: &InterfaceMeta, + known: &HashSet, + delegates: &HashSet, +) -> String { + let context = context(&[], &[interface], known, delegates, false); + python::generate_interface(&context, interface) +} + +pub fn generate_interface_stub( + interface: &InterfaceMeta, + known: &HashSet, + delegates: &HashSet, +) -> String { + let context = context(&[], &[interface], known, delegates, false); + python_stub::generate_interface_stub(&context, interface) +} diff --git a/tools/dynwinrt-codegen/tests/composable_factory_test.rs b/tools/dynwinrt-codegen/tests/composable_factory_test.rs index 09879162..e038e310 100644 --- a/tools/dynwinrt-codegen/tests/composable_factory_test.rs +++ b/tools/dynwinrt-codegen/tests/composable_factory_test.rs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::{HashMap, HashSet}; -use dynwinrt_codegen::codegen::{javascript, project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{javascript, project, render_dts, render_js}; use dynwinrt_codegen::meta::{ ClassMeta, ConstructorKind, ConstructorMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, @@ -109,13 +111,13 @@ fn composable_factory_returns_public_instance() { "factory declaration must return the runtime class:\n{dts}" ); - let py = python::generate_class( + let py = common::generate_class( &class, &HashSet::from(["Widget".into()]), &HashSet::new(), &HashSet::new(), ); - let pyi = python_stub::generate_class_stub( + let pyi = common::generate_class_stub( &class, &HashSet::from(["Widget".into()]), &HashSet::new(), @@ -174,7 +176,7 @@ fn composable_factory_returns_public_instance() { factory_interface: None, }, ); - let duplicate_py = python::generate_class( + let duplicate_py = common::generate_class( &duplicate_signature, &HashSet::from(["Widget".into()]), &HashSet::new(), @@ -195,7 +197,7 @@ fn composable_factory_returns_public_instance() { typ: TypeMeta::Object, direction: ParamDirection::In, }); - let unsupported_py = python::generate_class( + let unsupported_py = common::generate_class( &unsupported_override, &HashSet::from(["Widget".into()]), &HashSet::new(), @@ -222,13 +224,13 @@ fn composable_factory_returns_public_instance() { assert!(protected_dts.contains("private constructor();")); assert!(protected_dts.contains("static createInstance(outer: unknown): Widget;")); - let protected_py = python::generate_class( + let protected_py = common::generate_class( &protected, &HashSet::from(["Widget".into()]), &HashSet::new(), &HashSet::new(), ); - let protected_pyi = python_stub::generate_class_stub( + let protected_pyi = common::generate_class_stub( &protected, &HashSet::from(["Widget".into()]), &HashSet::new(), @@ -284,8 +286,8 @@ fn python_zero_arg_create_instance_gets_typed_create_alias() { }; let known = HashSet::from(["Widget".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("def create() -> 'Widget':")); assert!(py.contains("return Widget.create_instance()")); @@ -455,7 +457,7 @@ fn parameterized_default_interface_uses_computed_iid() { assert!(dts.contains("getMany(startIndex: number, items: RowDefinition[]): RowDefinition[];")); assert!(dts.contains("replaceAll(items: RowDefinition[]): void;")); - let py = python::generate_class( + let py = common::generate_class( &class, &HashSet::from([ "RowDefinition".into(), @@ -569,13 +571,9 @@ fn winui_application_projects_fluent_bootstrap_helpers() { assert!(dts.contains("static create(onLaunched?: () => void): Application;")); assert!(dts.contains("private constructor();")); - let py = python::generate_class(&application, &known_types, &delegate_names, &HashSet::new()); - let pyi = python_stub::generate_class_stub( - &application, - &known_types, - &delegate_names, - &HashSet::new(), - ); + let py = common::generate_class(&application, &known_types, &delegate_names, &HashSet::new()); + let pyi = + common::generate_class_stub(&application, &known_types, &delegate_names, &HashSet::new()); assert!(py.contains("def create_with_metadata_provider(")); assert!(py.contains("def create(on_launched: Callable[[], object] | None = None)")); assert!( @@ -614,13 +612,9 @@ fn winui_application_without_extension_dependencies_has_no_bootstrap_helpers() { ); let js = render_js::render(&projected); let dts = render_dts::render(&projected); - let py = python::generate_class(&application, &known_types, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub( - &application, - &known_types, - &HashSet::new(), - &HashSet::new(), - ); + let py = common::generate_class(&application, &known_types, &HashSet::new(), &HashSet::new()); + let pyi = + common::generate_class_stub(&application, &known_types, &HashSet::new(), &HashSet::new()); assert!(!js.contains("createWithMetadataProvider")); assert!(!dts.contains("createWithMetadataProvider")); diff --git a/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs b/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs index 6495ca4d..b3c8b7c2 100644 --- a/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs +++ b/tools/dynwinrt-codegen/tests/delegate_dependency_closure_test.rs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::{HashMap, HashSet}; -use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{project, render_dts, render_js}; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::TypeMeta; @@ -109,8 +111,8 @@ fn generated_interfaces_import_only_runtime_delegates() { ); let js = render_js::render(&projected); let dts = render_dts::render(&projected); - let py = python::generate_interface(&interface, &known_types, &delegates); - let pyi = python_stub::generate_interface_stub(&interface, &known_types, &delegates); + let py = common::generate_interface(&interface, &known_types, &delegates); + let pyi = common::generate_interface_stub(&interface, &known_types, &delegates); assert_eq!( js.matches("require('./DataProviderHandler.js')").count(), @@ -232,8 +234,8 @@ fn generated_classes_do_not_import_output_only_delegates() { ); let js = render_js::render(&projected); let dts = render_dts::render(&projected); - let py = python::generate_class(&class, &known_types, &delegates, &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known_types, &delegates, &HashSet::new()); + let py = common::generate_class(&class, &known_types, &delegates, &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known_types, &delegates, &HashSet::new()); assert!( js.contains("require('./InputHandler.js')") @@ -274,11 +276,11 @@ fn delegate_free_interfaces_do_not_import_global_delegates() { assert!(!render_js::render(&projected).contains("UnrelatedHandler"),); assert!( - !python::generate_interface(&interface, &known_types, &delegates,) + !common::generate_interface(&interface, &known_types, &delegates,) .contains("unrelated_handler"), ); assert!( - !python_stub::generate_interface_stub(&interface, &known_types, &delegates,) + !common::generate_interface_stub(&interface, &known_types, &delegates,) .contains("unrelated_handler"), ); } diff --git a/tools/dynwinrt-codegen/tests/element_factory_test.rs b/tools/dynwinrt-codegen/tests/element_factory_test.rs index 4247a042..33c8913d 100644 --- a/tools/dynwinrt-codegen/tests/element_factory_test.rs +++ b/tools/dynwinrt-codegen/tests/element_factory_test.rs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::{HashMap, HashSet}; -use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{project, render_dts, render_js}; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::TypeMeta; @@ -243,8 +245,8 @@ fn element_factory_projects_js_callback_constructor() { ); let js = render_js::render(&projected); let dts = render_dts::render(&projected); - let py = python::generate_interface(&interface, &known_types, &HashSet::new()); - let pyi = python_stub::generate_interface_stub(&interface, &known_types, &HashSet::new()); + let py = common::generate_interface(&interface, &known_types, &HashSet::new()); + let pyi = common::generate_interface_stub(&interface, &known_types, &HashSet::new()); assert!(js.contains("DynWinRtElementFactory.create")); assert!(js.contains("const elements = new Map()")); diff --git a/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs b/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs index 790dec63..5cba1381 100644 --- a/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs +++ b/tools/dynwinrt-codegen/tests/generic_ancestor_test.rs @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; use dynwinrt_codegen::codegen::render_js; use dynwinrt_codegen::codegen::winrt::javascript::project; -use dynwinrt_codegen::codegen::winrt::python; use dynwinrt_codegen::meta::{InterfaceMeta, parse_class}; use dynwinrt_codegen::types::TypeMeta; @@ -51,7 +52,7 @@ fn sdk_color_palette_resources_projects_inherited_generic_map_interfaces() { &delegate_param_wraps, ); let js = render_js::render(&projected); - let py = python::generate_class(&class, &known_types, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known_types, &HashSet::new(), &HashSet::new()); assert!(js.contains("lookup(") && js.contains("insert("), "{js}"); assert!( py.contains("class ColorPaletteResources(_WinRTMutableMappingMixin):") diff --git a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs index 9c85dd1c..e0ad1e4b 100644 --- a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs +++ b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs @@ -1,11 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::{HashMap, HashSet}; use dynwinrt_codegen::codegen::winrt::javascript::{self, project}; -use dynwinrt_codegen::codegen::winrt::python; -use dynwinrt_codegen::codegen::{python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{render_dts, render_js}; use dynwinrt_codegen::meta::{ ClassMeta, InterfaceMeta, MethodMeta, parse_class, resolve_dependencies, }; @@ -123,8 +124,8 @@ fn synthetic_ireference_point_field_uses_native_optional_projection() { "Point".to_string(), "IReference_Point".to_string(), ]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); let (js, dts) = generate_javascript(&class, &known); let constructor = "def __init__(self, value: Point | None | IReference_Point = None):"; @@ -238,8 +239,8 @@ fn scalar_ireference_fields_preserve_native_python_types() { "IReference_String".to_string(), "IReference_Mode".to_string(), ]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); let (js, dts) = generate_javascript(&class, &known); for output in [&py, &pyi] { @@ -305,8 +306,8 @@ fn nested_struct_defaults_and_enum_fields_are_python_native() { "Inner".to_string(), "Outer".to_string(), ]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( py.contains("class Inner:\n __slots__ = ('count',)"), @@ -378,8 +379,8 @@ fn empty_structs_emit_slots_and_value_semantics() { }; let class = class_with_struct("UsesEmptyMarker", empty); let known = HashSet::from(["UsesEmptyMarker".to_string(), "EmptyMarker".to_string()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( py.contains( @@ -415,8 +416,8 @@ fn sdk_http_progress_ireference_u64_fields_are_native_optional_values() { let class = parse_class(WINDOWS_WINMD, "Windows.Web.Http", "HttpClient").unwrap(); let known = HashSet::from(["HttpClient".to_string(), "HttpProgressStage".to_string()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); let (js, dts) = generate_javascript(&class, &known); for output in [&py, &pyi] { diff --git a/tools/dynwinrt-codegen/tests/nullable_return_test.rs b/tools/dynwinrt-codegen/tests/nullable_return_test.rs index fab7a244..f91309de 100644 --- a/tools/dynwinrt-codegen/tests/nullable_return_test.rs +++ b/tools/dynwinrt-codegen/tests/nullable_return_test.rs @@ -1,10 +1,12 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; use std::path::Path; -use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{project, render_dts, render_js}; use dynwinrt_codegen::meta; use dynwinrt_codegen::types::TypeMeta; @@ -148,13 +150,9 @@ fn ireference_values_are_projected_as_native_nullable_values() { ); let js = render_js::render(&projected); let dts = render_dts::render(&projected); - let py = python::generate_class(class, &known_types, &delegate_type_names, &HashSet::new()); - let pyi = python_stub::generate_class_stub( - class, - &known_types, - &delegate_type_names, - &HashSet::new(), - ); + let py = common::generate_class(class, &known_types, &delegate_type_names, &HashSet::new()); + let pyi = + common::generate_class_stub(class, &known_types, &delegate_type_names, &HashSet::new()); assert!(py.contains("def day(self) -> int | None:")); assert!(py.contains( diff --git a/tools/dynwinrt-codegen/tests/observable_vector_test.rs b/tools/dynwinrt-codegen/tests/observable_vector_test.rs index da28f070..e2d72234 100644 --- a/tools/dynwinrt-codegen/tests/observable_vector_test.rs +++ b/tools/dynwinrt-codegen/tests/observable_vector_test.rs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::{HashMap, HashSet}; -use dynwinrt_codegen::codegen::{project, python, python_stub, render_dts, render_js}; +use dynwinrt_codegen::codegen::{project, render_dts, render_js}; use dynwinrt_codegen::meta::{InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::TypeMeta; @@ -91,7 +93,7 @@ fn observable_vector_projects_python_mutable_sequence_and_typed_events() { ]); let delegate_types = HashSet::from(["VectorChangedEventHandler_Object".into()]); - let py = python::generate_interface(&interface, &known_types, &delegate_types); + let py = common::generate_interface(&interface, &known_types, &delegate_types); assert!(py.contains( "class IObservableVector_Object(_dynwinrt_symbol('i_vector_object', 'IVector_Object')):" )); @@ -108,14 +110,16 @@ fn observable_vector_projects_python_mutable_sequence_and_typed_events() { assert!(py.contains("_dynwinrt_create_delegate(")); assert!(py.contains("_IObservableVector_Object.method(6).invoke(self._observable_obj")); - let pyi = python_stub::generate_interface_stub(&interface, &known_types, &delegate_types); + let pyi = common::generate_interface_stub(&interface, &known_types, &delegate_types); assert!( pyi.contains( "class IObservableVector_Object(_IObservableVector_ObjectIdentity, MutableSequence[DynWinRTValue | None]):" ), "{pyi}" ); - assert!(pyi.contains("from .i_vector_changed_event_args import IVectorChangedEventArgs")); + assert!(pyi.contains( + "from .windows__foundation__collections__i_vector_changed_event_args import IVectorChangedEventArgs" + )); assert!(pyi.contains("def as_vector(self) -> 'IVector_Object': ...")); assert!(pyi.contains("def on_vector_changed(self, callback: Callable[[")); } @@ -161,7 +165,7 @@ fn generic_delegate_iid_uses_declared_type_arguments() { }; let projected = project::project_delegate(&interface, &HashMap::new(), &HashMap::new()); let js = render_js::render(&projected); - let py = python::generate_interface( + let py = common::generate_interface( &interface, &HashSet::new(), &HashSet::from(["VectorChangedEventHandler_Object".into()]), diff --git a/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs b/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs index b61f7765..9b73889b 100644 --- a/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs +++ b/tools/dynwinrt-codegen/tests/python_constructor_boundary_test.rs @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; use std::path::Path; -use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{ self, ClassMeta, ConstructorKind, ConstructorMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, @@ -60,8 +61,8 @@ fn system_returned_class_keeps_only_internal_native_wrapping() { }; let known = HashSet::from(["SystemResult".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("def _from_native(cls, obj: DynWinRTValue):")); assert!(py.contains("_dynwinrt_runtime_class_type = True")); @@ -94,8 +95,8 @@ fn static_only_class_has_only_qi_checked_projection_entry() { }; let known = HashSet::from(["ApiInformation".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( py.contains("def _from_native(cls, obj: DynWinRTValue):"), @@ -140,9 +141,8 @@ fn static_only_class_has_only_qi_checked_projection_entry() { .is_some_and(|interface| !interface.iid.is_empty()); checked += 1; let known = HashSet::from([name.into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = - python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( !py.contains("from_value = classmethod"), "{namespace}.{name}:\n{py}" @@ -200,7 +200,7 @@ fn real_factory_constructors_reference_generated_private_helpers() { continue; }; checked += 1; - let code = python::generate_class( + let code = common::generate_class( &class, &HashSet::from([name.into()]), &HashSet::new(), @@ -243,8 +243,8 @@ fn externally_returned_empty_class_keeps_native_projection() { ))); class.is_referenced_as_value = true; let known = HashSet::from(["DeviceWatcherTrigger".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("_dynwinrt_runtime_class_type = True"), "{py}"); assert!( @@ -282,8 +282,8 @@ fn externally_returned_empty_class_with_static_interface_keeps_native_projection }; let known = HashSet::from(["ExternallyReturned".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( py.contains("def _from_native(cls, obj: DynWinRTValue):"), "{py}" @@ -292,7 +292,7 @@ fn externally_returned_empty_class_with_static_interface_keeps_native_projection assert!(pyi.contains("_DynWinRTRuntimeClass"), "{pyi}"); class.is_referenced_as_value = false; - let static_only = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let static_only = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); assert!(static_only.contains("def _from_native("), "{static_only}"); assert!( static_only.contains("_dynwinrt_projectable_class_type = True"), @@ -333,8 +333,8 @@ fn only_referenced_public_factory_metadata_becomes_a_constructor() { }; let known = HashSet::from(["SystemResult".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("type(self).create_result(_bound[0])")); assert!(!py.contains("self._set_native(type(self).create()._obj)")); @@ -390,7 +390,7 @@ fn numeric_constructor_overloads_dispatch_by_specificity() { }; let known = HashSet::from(["SystemResult".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); let narrow_guard = "-128 <= _bound[0] <= 127"; let wide_guard = "-2147483648 <= _bound[0] <= 2147483647"; assert!( @@ -399,7 +399,7 @@ fn numeric_constructor_overloads_dispatch_by_specificity() { "{py}" ); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert_eq!(pyi.matches(" @overload\n").count(), 4, "{pyi}"); } @@ -422,8 +422,8 @@ fn protected_composition_is_not_public_construction() { }; let known = HashSet::from(["SystemResult".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("SystemResult cannot be constructed directly")); assert!(pyi.contains("def __init__(self, _not_constructible: NoReturn) -> None: ...")); @@ -470,8 +470,8 @@ fn unresolved_or_unsupported_constructor_metadata_fails_closed() { }; for class in [&missing_dependency, &malformed_composition] { - let py = python::generate_class(class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("SystemResult cannot be constructed directly")); assert!(pyi.contains("from typing import NoReturn")); assert!(pyi.contains("def __init__(self, _not_constructible: NoReturn) -> None: ...")); diff --git a/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs b/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs index e8325bc1..ee3edda3 100644 --- a/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_context_manager_typing_test.rs @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; -use dynwinrt_codegen::codegen::python_stub; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta}; #[test] @@ -21,7 +22,7 @@ fn closable_context_manager_never_suppresses_exceptions() { ..Default::default() }; - let stub = python_stub::generate_class_stub( + let stub = common::generate_class_stub( &class, &HashSet::from(["IClosable".into(), "Resource".into()]), &HashSet::new(), diff --git a/tools/dynwinrt-codegen/tests/python_dispatcher_scheduling_test.rs b/tools/dynwinrt-codegen/tests/python_dispatcher_scheduling_test.rs index 695fd5ba..5bd79c7f 100644 --- a/tools/dynwinrt-codegen/tests/python_dispatcher_scheduling_test.rs +++ b/tools/dynwinrt-codegen/tests/python_dispatcher_scheduling_test.rs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; -use dynwinrt_codegen::codegen::python; -use dynwinrt_codegen::codegen::python_stub; use dynwinrt_codegen::meta::ClassMeta; #[test] @@ -19,7 +19,7 @@ fn dispatcher_queue_emits_awaitable_scheduling_helpers() { let delegate_types = HashSet::new(); let shared_iids = HashSet::new(); - let runtime = python::generate_class(&class, &known_types, &delegate_types, &shared_iids); + let runtime = common::generate_class(&class, &known_types, &delegate_types, &shared_iids); assert!(runtime.contains("import asyncio")); assert!(runtime.contains("async def enqueue_async(self, callback, *args, **kwargs):")); assert!(runtime.contains( @@ -29,8 +29,7 @@ fn dispatcher_queue_emits_awaitable_scheduling_helpers() { assert!(runtime.contains("except RuntimeError:")); assert!(runtime.contains("DispatcherQueue rejected the callback.")); - let stub = - python_stub::generate_class_stub(&class, &known_types, &delegate_types, &shared_iids); + let stub = common::generate_class_stub(&class, &known_types, &delegate_types, &shared_iids); assert!(stub.contains("_DispatchResultT = TypeVar('_DispatchResultT')")); assert!(stub.contains("async def enqueue_async(")); assert!(stub.contains("Callable[..., _DispatchResultT]")); diff --git a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs index 2482e0da..b9896e2f 100644 --- a/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs +++ b/tools/dynwinrt-codegen/tests/python_identity_cache_test.rs @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; -use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{ ClassMeta, ConstructorKind, ConstructorMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, @@ -33,7 +34,7 @@ fn runtime_class_generation_uses_projected_identity_cache() { ..Default::default() }; - let py = python::generate_class( + let py = common::generate_class( &class, &HashSet::from(["Widget".to_string()]), &HashSet::new(), @@ -115,7 +116,7 @@ fn runtime_class_public_constructor_registers_final_self() { ..Default::default() }; - let py = python::generate_class( + let py = common::generate_class( &class, &HashSet::from(["Widget".to_string()]), &HashSet::new(), @@ -145,7 +146,7 @@ fn interface_generation_uses_projected_identity_cache() { ..Default::default() }; - let py = python::generate_interface( + let py = common::generate_interface( &iface, &HashSet::from(["IWidget".to_string()]), &HashSet::new(), @@ -196,8 +197,8 @@ fn embedded_interface_projection_preserves_subclasses_and_qi_helpers() { ..Default::default() }; let known = HashSet::from(["Widget".to_string()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); let inline = py .split("\nclass IExtra:") .nth(1) diff --git a/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs b/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs index 9ea285bf..b39881e1 100644 --- a/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs +++ b/tools/dynwinrt-codegen/tests/python_inheritance_typing_test.rs @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; use std::path::Path; -use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{ self, ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta, }; @@ -54,7 +55,7 @@ fn stubs_model_runtime_class_and_interface_bases_without_runtime_inheritance() { ..Default::default() }; let interface_stub = - python_stub::generate_interface_stub(&interface, &HashSet::new(), &HashSet::new()); + common::generate_interface_stub(&interface, &HashSet::new(), &HashSet::new()); assert!( !interface_stub.contains("from .contoso__i_base import"), "{interface_stub}" @@ -94,7 +95,7 @@ fn stubs_model_runtime_class_and_interface_bases_without_runtime_inheritance() { }], ..Default::default() }; - let class_stub = python_stub::generate_class_stub( + let class_stub = common::generate_class_stub( &class, &HashSet::from(["Base".into(), "Derived".into(), "IDerived".into()]), &HashSet::new(), @@ -181,7 +182,7 @@ fn real_windows_metadata_exposes_xaml_and_stream_typing_relationships() { .chain(["SpeechSynthesisStream".into()]) .collect::>(); let stream_stub = - python_stub::generate_class_stub(&stream, &known, &HashSet::new(), &HashSet::new()); + common::generate_class_stub(&stream, &known, &HashSet::new(), &HashSet::new()); assert!( stream_stub .contains("class SpeechSynthesisStreamLike(_SpeechSynthesisStreamIdentity, Protocol):"), @@ -222,9 +223,9 @@ fn real_windows_metadata_exposes_xaml_and_stream_typing_relationships() { .map(|interface| interface.name.clone()) .collect::>(); let with_content_stub = - python_stub::generate_interface_stub(with_content_type, &known_interfaces, &HashSet::new()); + common::generate_interface_stub(with_content_type, &known_interfaces, &HashSet::new()); let with_content_runtime = - python::generate_interface(with_content_type, &known_interfaces, &HashSet::new()); + common::generate_interface(with_content_type, &known_interfaces, &HashSet::new()); assert!( with_content_stub .contains("class IRandomAccessStreamWithContentType(_IRandomAccessStreamWithContentTypeIdentity, Protocol):"), diff --git a/tools/dynwinrt-codegen/tests/python_numeric_overload_dispatch_test.rs b/tools/dynwinrt-codegen/tests/python_numeric_overload_dispatch_test.rs index efc16895..f61b6606 100644 --- a/tools/dynwinrt-codegen/tests/python_numeric_overload_dispatch_test.rs +++ b/tools/dynwinrt-codegen/tests/python_numeric_overload_dispatch_test.rs @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; -use dynwinrt_codegen::codegen::python_stub; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::TypeMeta; @@ -41,7 +42,7 @@ fn python_numeric_overload_stubs_retain_typing_overload() { }; let known = HashSet::from(["Reader".into()]); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(pyi.contains("overload, timedelta")); assert_eq!(pyi.matches(" @overload\n").count(), 2); diff --git a/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs b/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs index 41961818..da6eebdc 100644 --- a/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs +++ b/tools/dynwinrt-codegen/tests/python_overload_normalization_test.rs @@ -1,10 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; use std::path::Path; -use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{self, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::{TypeMeta, TypeMeta::AsyncOperation}; @@ -79,8 +80,8 @@ fn default_option_method_is_one_python_overload_group_with_legacy_alias() { "StorageFile".into(), ]); - let runtime = python::generate_interface(&interface, &known, &HashSet::new()); - let stub = python_stub::generate_interface_stub(&interface, &known, &HashSet::new()); + let runtime = common::generate_interface(&interface, &known, &HashSet::new()); + let stub = common::generate_interface_stub(&interface, &known, &HashSet::new()); assert_eq!( runtime.matches("def create_file_async(self, *args").count(), @@ -116,8 +117,8 @@ fn real_storage_folder_default_options_method_is_normalized() { "StorageFolder".into(), ]); - let runtime = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let stub = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let runtime = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let stub = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( runtime.contains("def create_file_async(self, *args"), diff --git a/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs b/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs index 5e972aa9..5f51ffe1 100644 --- a/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs +++ b/tools/dynwinrt-codegen/tests/python_property_name_collision_test.rs @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; -use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta}; use dynwinrt_codegen::types::TypeMeta; @@ -41,8 +42,8 @@ fn property_named_property_does_not_shadow_the_decorator() { }; let known = HashSet::from(["ChangedEventArgs".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!(py.contains("_property, _weakref_ref,")); assert_eq!(py.matches(" @_property\n").count(), 2); diff --git a/tools/dynwinrt-codegen/tests/python_write_only_property_test.rs b/tools/dynwinrt-codegen/tests/python_write_only_property_test.rs index 041562f3..90e2af0f 100644 --- a/tools/dynwinrt-codegen/tests/python_write_only_property_test.rs +++ b/tools/dynwinrt-codegen/tests/python_write_only_property_test.rs @@ -1,9 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +mod common; + use std::collections::HashSet; -use dynwinrt_codegen::codegen::{python, python_stub}; use dynwinrt_codegen::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection, ParamMeta}; use dynwinrt_codegen::types::TypeMeta; @@ -51,8 +52,8 @@ fn versioned_setter_uses_main_property_but_standalone_set_method() { }; let known = HashSet::from(["Widget".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); let inline_py = py .split("class IWidget2:") @@ -115,8 +116,8 @@ fn cross_interface_getter_is_emitted_before_an_earlier_setter() { }; let known = HashSet::from(["Widget".into()]); - let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); - let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + let py = common::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = common::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( py.find(" @_property\n def value") diff --git a/tools/dynwinrt-codegen/tests/snapshot_test.rs b/tools/dynwinrt-codegen/tests/snapshot_test.rs index b01ebcbb..7e9b491a 100644 --- a/tools/dynwinrt-codegen/tests/snapshot_test.rs +++ b/tools/dynwinrt-codegen/tests/snapshot_test.rs @@ -7,13 +7,14 @@ //! To update snapshots after an intentional output change, run: //! cargo run -p dynwinrt-codegen -- generate --namespace Windows.Foundation --class-name Uri --output tests/snapshots/uri +mod common; + use std::collections::{HashMap, HashSet}; use std::fs; use std::path::Path; use dynwinrt_codegen::codegen::common::to_snake_case_filename; -use dynwinrt_codegen::codegen::python_stub; -use dynwinrt_codegen::codegen::{javascript, project, render_dts, render_js}; +use dynwinrt_codegen::codegen::{javascript, project, python, python_stub, render_dts, render_js}; use dynwinrt_codegen::meta; use dynwinrt_codegen::types::TypeMeta; @@ -287,22 +288,30 @@ fn snapshot_uri_pyi_class() { .map(|i| i.name.clone()) .collect(); let shared_iids: HashSet = HashSet::new(); + let context = common::projection_context( + &all_classes, + &all_interfaces, + &known_types, + &delegate_type_names, + ); let mut generated: HashMap = HashMap::new(); for iface in &all_interfaces { - let code = python_stub::generate_interface_stub(iface, &known_types, &delegate_type_names); + let code = python_stub::generate_interface_stub(&context, iface); generated.insert(format!("{}.pyi", to_snake_case_filename(&iface.name)), code); } for class in &all_classes { - let code = python_stub::generate_class_stub( - class, - &known_types, - &delegate_type_names, - &shared_iids, - ); + let code = python_stub::generate_class_stub(&context, class, &shared_iids); generated.insert(format!("{}.pyi", to_snake_case_filename(&class.name)), code); } - let index = python_stub::generate_index_stub(&all_classes, &all_interfaces, &all_enums); + let index_context = common::packaged_projection_context( + &all_classes, + &all_interfaces, + &known_types, + &delegate_type_names, + ); + let index = + python_stub::generate_index_stub(&index_context, &all_classes, &all_interfaces, &all_enums); generated.insert("__init__.pyi".to_string(), index); let snapshot_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/uri_pyi"); @@ -346,7 +355,6 @@ fn snapshot_uri_pyi_class() { /// Guards Phase 3 refactor (common.rs split + Lang trait) from drifting output. #[test] fn snapshot_uri_py_class() { - use dynwinrt_codegen::codegen::python; let winmd = WINDOWS_WINMD; let classes = match meta::parse_class(winmd, "Windows.Foundation", "Uri") { Some(c) => vec![c], @@ -382,17 +390,29 @@ fn snapshot_uri_py_class() { .map(|i| i.name.clone()) .collect(); let shared_iids: HashSet = HashSet::new(); + let context = common::projection_context( + &all_classes, + &all_interfaces, + &known_types, + &delegate_type_names, + ); let mut generated: HashMap = HashMap::new(); for iface in &all_interfaces { - let code = python::generate_interface(iface, &known_types, &delegate_type_names); + let code = python::generate_interface(&context, iface); generated.insert(format!("{}.py", to_snake_case_filename(&iface.name)), code); } for class in &all_classes { - let code = python::generate_class(class, &known_types, &delegate_type_names, &shared_iids); + let code = python::generate_class(&context, class, &shared_iids); generated.insert(format!("{}.py", to_snake_case_filename(&class.name)), code); } - let index = python::generate_index(&all_classes, &all_interfaces, &all_enums); + let index_context = common::packaged_projection_context( + &all_classes, + &all_interfaces, + &known_types, + &delegate_type_names, + ); + let index = python::generate_index(&index_context, &all_classes, &all_interfaces, &all_enums); generated.insert("__init__.py".to_string(), index); let snapshot_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/uri_py"); @@ -438,8 +458,6 @@ fn snapshot_uri_py_class() { /// Snapshot a method-rich Python class outside Windows.Foundation. #[test] fn snapshot_data_writer_py_class() { - use dynwinrt_codegen::codegen::python; - let classes = match meta::parse_class(WINDOWS_WINMD, "Windows.Storage.Streams", "DataWriter") { Some(class) => vec![class], None => { @@ -478,7 +496,7 @@ fn snapshot_data_writer_py_class() { .iter() .find(|class| class.name == "DataWriter") .expect("DataWriter class"); - let actual = python::generate_class(class, &known_types, &delegate_type_names, &HashSet::new()); + let actual = common::generate_class(class, &known_types, &delegate_type_names, &HashSet::new()); let snapshot_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/snapshots/data_writer_py"); let snapshot_path = snapshot_dir.join("data_writer.py"); diff --git a/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py b/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py index c0350900..89f256ed 100644 --- a/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py +++ b/tools/dynwinrt-codegen/tests/snapshots/data_writer_py/data_writer.py @@ -239,7 +239,7 @@ def byte_order(self, value: 'ByteOrder'): def close(self): if self._closed: return - _dynwinrt_symbol('i_closable', 'IClosable').from_value(self._obj).close() + _dynwinrt_symbol('windows__foundation__i_closable', 'IClosable').from_value(self._obj).close() self._closed = True def __enter__(self):