Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/architecture/winrt-interface-implementations.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,17 @@ Common Python reverse-conversion helpers live once in each generated package's
generated code, not excluded coverage support. Method-specific ABI plans and
typed conversions remain with their interface.

Python handler, delegate, and result annotations share the enclosing module's
type-name mapping with ordinary projected members. Self-interface references use
the locally declared class name; imported structs use the same collision alias
in `.py` and `.pyi`. Types with identical short names in other namespaces remain
distinct imports, including references nested in arrays or delegate signatures.
Self-import filtering compares canonical identities, so a closed generic such
as `IBox<String>` cannot hide a distinct named `IBox_String` in the same namespace.
Standalone interface and runtime-class modules use the actual declared metadata
names for embedded struct helpers, even when their cross-module projected names
are disambiguated; standalone struct modules retain aliases for imported fields.

Language bindings additionally gate dispatch on their environment/interpreter
lifetime. Callback roots belong to the native object, not merely the original
language wrapper. Shutdown disconnects language callback state before its
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ pub fn generate_class(
shared_iids: &HashSet<String>,
) -> String {
let used_structs = collect_used_structs_from_class(class);
let context = context.with_local_types(None, &used_structs);
let context = context.as_ref();
let collection_iface = class_interface(class);
let collection_kind = collection_iface.and_then(interface_kind);
let known_full_names = context.known_full_names();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection};
use crate::types::{TypeKind, TypeMeta};

use crate::codegen::winrt::shared::imports::{
collect_iface_type_imports, collect_struct_field_type_imports, collect_type_imports,
collect_used_generic_identities_from_class, collect_used_generic_identities_from_methods,
collect_used_generic_identities_from_type, ireference_inner_type,
collect_iface_type_imports_by_identity, collect_struct_field_type_imports,
collect_type_imports, collect_used_generic_identities_from_class,
collect_used_generic_identities_from_methods, collect_used_generic_identities_from_type,
ireference_inner_type,
};
use crate::codegen::winrt::shared::structs::{
collect_used_structs_from_class, collect_used_structs_from_iface,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,23 @@ pub(super) fn generate_struct_imports(
let mut imports = structs
.iter()
.filter_map(|typ| {
let TypeMeta::Struct { .. } = typ else {
let TypeMeta::Struct { name, .. } = typ else {
return None;
};
let names = struct_runtime_import_names(typ)
.into_iter()
.map(|export| {
if export == *name {
context.struct_type_import(typ, &export)
} else {
export
}
})
.collect::<Vec<_>>();
Some(format!(
"from .{} import {} # noqa: F401\n",
context.implementation_module_for_type(typ),
struct_runtime_import_names(typ).join(", ")
names.join(", ")
))
})
.collect::<Vec<_>>();
Expand Down Expand Up @@ -149,6 +159,7 @@ pub(super) fn generate_struct_helpers(context: &PythonProjectionContext, s: &Typ
&& foundation_type(&f.typ).is_none()
&& name != "HResult"
{
let name = context.reference_name_for_type(&f.typ);
out.push_str(&format!(
" self.{snake} = {name}() if {snake} is None else {snake}\n"
));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ pub fn generate_enum(_context: &PythonProjectionContext, en: &TypeMeta) -> Optio

/// Generate a Python file for a WinRT interface (non-exclusive).
pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String {
let used_structs = collect_used_structs_from_iface(iface);
let type_imports = collect_iface_type_imports_by_identity(iface);
let context = context.with_local_types(Some(iface), &used_structs);
let context = context.as_ref();
let mut projected_iface = iface.clone();
projected_iface.name = context.projected_name_for_interface(iface);
let iface = &projected_iface;
Expand All @@ -86,8 +90,6 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe
}
let implementation = super::super::implementation::project(context, iface);

let used_structs = collect_used_structs_from_iface(iface);

let mut out = String::new();
out.push_str(HEADER);
out.push_str(FUTURE_ANNOTATIONS);
Expand Down Expand Up @@ -195,7 +197,6 @@ pub fn generate_interface(context: &PythonProjectionContext, iface: &InterfaceMe
}

// Type imports for referenced types
let type_imports = collect_iface_type_imports(iface);
let mut sorted_type_imports: Vec<_> = type_imports.iter().collect();
sorted_type_imports
.sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind)));
Expand Down
42 changes: 42 additions & 0 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/naming.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

//! Python naming and identifier helpers.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use super::super::shared::implementation_symbols::{
Expand Down Expand Up @@ -552,6 +553,47 @@ impl PythonProjectionContext {
self.packaged
}

/// Interfaces declare projected names; embedded structs retain metadata names.
pub(super) fn with_local_types(
&self,
interface: Option<&InterfaceMeta>,
structs: &[TypeMeta],
) -> Cow<'_, Self> {
let declarations = interface
.into_iter()
.map(|interface| {
(
interface.type_identity(),
self.projected_name_for_interface(interface),
)
})
.chain(structs.iter().filter_map(|typ| match typ {
TypeMeta::Struct { name, .. } if !self.is_packaged() => {
Some((typ.type_identity(), name.clone()))
}
_ => None,
}));
let mut context = Cow::Borrowed(self);
for (identity, declaration_name) in declarations {
let identity = self.normalize_identity(&identity);
if self.reference_name(&identity) != declaration_name
&& let Some(projection) = context.to_mut().projections.get_mut(&identity)
{
projection.reference_name = declaration_name;
}
}
context
}

pub(super) fn struct_type_import(&self, typ: &TypeMeta, name: &str) -> String {
let reference = self.reference_name_for_type(typ);
if reference == name {
name.into()
} else {
format!("{name} as {reference}")
}
}

pub fn configure_implementation_helpers(
&mut self,
owners: impl IntoIterator<Item = (PythonTypeIdentity, Vec<ImplementationHelper>)>,
Expand Down
2 changes: 1 addition & 1 deletion tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ pub(crate) fn py_struct_field_read_type(
TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(),
typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(),
typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(),
TypeMeta::Struct { name, .. } => format!("'{}'", name),
TypeMeta::Struct { .. } => format!("'{}'", context.reference_name_for_type(typ)),
_ => "'DynWinRTValue'".to_string(),
}
}
16 changes: 13 additions & 3 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,23 @@ pub(super) fn generate_struct_stub_imports(
let mut imports = structs
.iter()
.filter_map(|typ| {
let TypeMeta::Struct { .. } = typ else {
let TypeMeta::Struct { name, .. } = typ else {
return None;
};
let names = py_struct_export_names(typ)
.into_iter()
.map(|export| {
if export == *name {
context.struct_type_import(typ, &export)
} else {
export
}
})
.collect::<Vec<_>>();
Some(format!(
"from .{} import {} # noqa: F401\n",
context.implementation_module_for_type(typ),
py_struct_export_names(typ).join(", ")
names.join(", ")
))
})
.collect::<Vec<_>>();
Expand Down Expand Up @@ -243,7 +253,7 @@ pub(super) fn py_struct_field_stub_type(
TypeMeta::Struct { name, .. } if name == "HResult" => "int".to_string(),
typ if foundation_type(typ) == Some(FoundationType::DateTime) => "datetime".to_string(),
typ if foundation_type(typ) == Some(FoundationType::TimeSpan) => "timedelta".to_string(),
TypeMeta::Struct { name, .. } => format!("'{}'", name),
TypeMeta::Struct { .. } => format!("'{}'", context.reference_name_for_type(typ)),
_ => "object".to_string(),
}
}
Expand Down
15 changes: 9 additions & 6 deletions tools/dynwinrt-codegen/src/codegen/winrt/python/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ use crate::types::{TypeKind, TypeMeta};

use crate::codegen::winrt::extensions::winui;
use crate::codegen::winrt::shared::imports::{
collect_iface_type_imports, collect_struct_field_type_imports, collect_type_imports,
collect_used_generic_identities_from_class, collect_used_generic_identities_from_methods,
collect_used_generic_identities_from_type,
collect_iface_type_imports_by_identity, collect_struct_field_type_imports,
collect_type_imports, collect_used_generic_identities_from_class,
collect_used_generic_identities_from_methods, collect_used_generic_identities_from_type,
};
use crate::codegen::winrt::shared::structs::{
collect_used_structs_from_class, collect_used_structs_from_iface,
Expand Down Expand Up @@ -221,6 +221,10 @@ pub fn generate_enum_stub(_context: &PythonProjectionContext, en: &TypeMeta) ->

/// Generate a `.pyi` stub for an interface (or a delegate).
pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &InterfaceMeta) -> String {
let used_structs = collect_used_structs_from_iface(iface);
let type_imports = collect_iface_type_imports_by_identity(iface);
let context = context.with_local_types(Some(iface), &used_structs);
let context = context.as_ref();
let mut projected_iface = iface.clone();
projected_iface.name = context.projected_name_for_interface(iface);
let iface = &projected_iface;
Expand All @@ -237,8 +241,6 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
}
let implementation = super::implementation::project(context, iface);

let used_structs = collect_used_structs_from_iface(iface);

let mut out = String::new();
out.push_str(HEADER);
out.push_str(FUTURE_ANNOTATIONS);
Expand Down Expand Up @@ -350,7 +352,6 @@ pub fn generate_interface_stub(context: &PythonProjectionContext, iface: &Interf
out.push_str(&format!("from .{module} import {imports} # noqa: F401\n",));
}

let type_imports = collect_iface_type_imports(iface);
let mut sorted_type_imports: Vec<_> = type_imports.iter().collect();
sorted_type_imports
.sort_by(|a, b| (&a.namespace, &a.name, &a.kind).cmp(&(&b.namespace, &b.name, &b.kind)));
Expand Down Expand Up @@ -568,6 +569,8 @@ pub fn generate_class_stub(
shared_iids: &HashSet<String>,
) -> String {
let used_structs = collect_used_structs_from_class(class);
let context = context.with_local_types(None, &used_structs);
let context = context.as_ref();
let collection_iface = class_interface(class);
let collection_kind = collection_iface.and_then(interface_kind);
let known_full_names = context.known_full_names();
Expand Down
25 changes: 22 additions & 3 deletions tools/dynwinrt-codegen/src/codegen/winrt/shared/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use std::collections::HashSet;
use std::sync::LazyLock;

use crate::meta::{ClassMeta, InterfaceMeta, MethodMeta, ParamDirection};
use crate::types::{TypeIdentity, TypeKind, TypeMeta, TypeRef};
use crate::types::{TypeIdentity, TypeIdentityKind, TypeKind, TypeMeta, TypeRef};

/// Empty set passed as `deferred` for codegen (no circular dep handling needed).
pub(crate) static NO_DEFERRED: LazyLock<HashSet<String>> = LazyLock::new(HashSet::new);
Expand Down Expand Up @@ -186,12 +186,31 @@ fn collect_methods_type_imports(

/// Collect type references from an interface for import generation.
pub(crate) fn collect_iface_type_imports(iface: &InterfaceMeta) -> HashSet<TypeRef> {
collect_iface_type_imports_except(iface, &iface.name)
}

/// Python imports exclude only the owning canonical interface identity.
pub(crate) fn collect_iface_type_imports_by_identity(iface: &InterfaceMeta) -> HashSet<TypeRef> {
let self_identity = iface.type_identity();
let mut imports = collect_iface_type_imports_except(iface, "");
imports.retain(|reference| {
let kind = match reference.kind {
TypeKind::Class => TypeIdentityKind::Class,
TypeKind::Enum => TypeIdentityKind::Enum,
TypeKind::Interface => TypeIdentityKind::Interface,
};
TypeIdentity::named(kind, &reference.namespace, &reference.name) != self_identity
});
imports
}

fn collect_iface_type_imports_except(iface: &InterfaceMeta, self_name: &str) -> HashSet<TypeRef> {
let mut imports = HashSet::new();
collect_methods_type_imports(&iface.methods, &iface.name, false, &mut imports);
collect_methods_type_imports(&iface.methods, self_name, false, &mut imports);
for delegate in &iface.implementation_metadata.delegates {
collect_methods_type_imports(
std::slice::from_ref(&delegate.invoke),
&iface.name,
self_name,
false,
&mut imports,
);
Expand Down
Loading
Loading