use super::*;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum InterfaceKind {
None,
Default,
Static,
Composable,
Base,
}
#[derive(Clone, Debug)]
pub enum MethodOrName<M> {
Method(M),
Name(MethodDef),
}
pub trait MethodItem {
fn def(&self) -> MethodDef;
fn dependencies(&self) -> &TypeMap;
}
impl MethodItem for Method {
fn def(&self) -> MethodDef {
self.def
}
fn dependencies(&self) -> &TypeMap {
&self.dependencies
}
}
impl MethodItem for CppMethod {
fn def(&self) -> MethodDef {
self.def
}
fn dependencies(&self) -> &TypeMap {
&self.dependencies
}
}
pub fn named_methods<M: MethodItem>(
methods: &[MethodOrName<M>],
) -> impl Iterator<Item = (&M, TokenStream)> {
let mut names = MethodNames::new();
methods.iter().filter_map(move |method| match method {
MethodOrName::Method(method) => Some((method, names.add(method.def()))),
MethodOrName::Name(def) => {
names.add(*def);
None
}
})
}
pub fn write_vtbl_methods<M: MethodItem>(
methods: &[MethodOrName<M>],
class_cfg: &Cfg,
config: &Config,
mut signature: impl FnMut(&M) -> TokenStream,
) -> Vec<TokenStream> {
let mut names = MethodNames::new();
methods
.iter()
.map(|method| match method {
MethodOrName::Method(method) => {
let method_cfg = class_cfg.difference(method.dependencies(), config);
let yes = method_cfg.write(config, false);
let name = names.add(method.def());
let sig = signature(method);
if yes.is_empty() {
quote! {
pub #name: unsafe extern "system" fn #sig,
}
} else {
let no = method_cfg.write(config, true);
quote! {
#yes
pub #name: unsafe extern "system" fn #sig,
#no
#name: usize,
}
}
}
MethodOrName::Name(method) => {
let name = names.add(*method);
quote! { #name: usize, }
}
})
.collect()
}
pub fn write_impl_field_methods<M: MethodItem>(
methods: &[MethodOrName<M>],
mut method_field: impl FnMut(&TokenStream) -> TokenStream,
) -> Vec<TokenStream> {
let mut names = MethodNames::new();
methods
.iter()
.map(|method| match method {
MethodOrName::Method(method) => {
let name = names.add(method.def());
method_field(&name)
}
MethodOrName::Name(method) => {
let name = names.add(*method);
quote! { #name: 0, }
}
})
.collect()
}
pub fn write_impl_trait_methods<M: MethodItem>(
methods: &[MethodOrName<M>],
mut signature: impl FnMut(&M) -> TokenStream,
) -> Vec<TokenStream> {
let mut names = MethodNames::new();
methods
.iter()
.map(|method| match method {
MethodOrName::Method(method) => {
let name = names.add(method.def());
let sig = signature(method);
quote! { fn #name #sig; }
}
_ => quote! {},
})
.collect()
}
#[derive(Clone, Debug)]
pub struct Interface {
pub def: TypeDef,
pub generics: Vec<Type>,
pub kind: InterfaceKind,
}
impl PartialEq for Interface {
fn eq(&self, other: &Self) -> bool {
self.def == other.def
}
}
impl Eq for Interface {}
impl std::hash::Hash for Interface {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.def.hash(state);
}
}
impl Ord for Interface {
fn cmp(&self, other: &Self) -> Ordering {
(self.def.name(), self.def).cmp(&(other.def.name(), other.def))
}
}
impl PartialOrd for Interface {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Interface {
pub fn type_name(&self) -> TypeName {
self.def.type_name()
}
pub fn get_methods(&self, config: &Config) -> Vec<MethodOrName<Method>> {
self.def
.methods()
.map(|def| {
let method = Method::new(def, &self.generics, config.reader);
if !config.plan.includes_method(def, &self.generics) {
MethodOrName::Name(method.def)
} else {
MethodOrName::Method(method)
}
})
.collect()
}
pub fn has_skipped_methods(&self, config: &Config) -> bool {
self.def
.methods()
.any(|def| !config.plan.includes_method(def, &self.generics))
}
fn write_cfg(&self, config: &Config) -> (Cfg, TokenStream) {
write_full_cfg(self, config)
}
pub fn write(&self, config: &Config) -> TokenStream {
let type_name = self.def.type_name();
let methods = self.get_methods(config);
let required_interfaces = self.required_interfaces(config.reader);
let name = self.write_name(config);
let vtbl_name = self.write_vtbl_name(config);
let is_exclusive = self.is_exclusive();
let constraints = config.write_generic_constraints(&self.generics);
let named_phantoms = config.write_generic_named_phantoms(&self.generics);
let (class_cfg, cfg) = self.write_cfg(config);
let vtbl = {
let core = config.write_core();
let methods_for_vtbl: &[MethodOrName<Method>] = {
let last_real = methods
.iter()
.rposition(|m| matches!(m, MethodOrName::Method(_)));
match last_real {
Some(pos) => &methods[..=pos],
None => &[],
}
};
let vtbl_methods = write_vtbl_methods(methods_for_vtbl, &class_cfg, config, |method| {
let vtbl = method.write_abi(config, false);
quote! { (#vtbl) -> #core HRESULT }
});
let hide_vtbl = config.doc_hidden_in_package();
quote! {
#cfg
#[repr(C)]
#hide_vtbl
pub struct #vtbl_name where #constraints {
pub base__: #core IInspectable_Vtbl,
#(#vtbl_methods)*
#named_phantoms
}
}
};
if config.bindgen.style.is_sys() {
let mut result = quote! {};
if !config.bindgen.layout.is_package() {
if let Some(guid) = self.def.guid_attribute() {
let name: TokenStream = format!("IID_{}", trim_tick(self.def.name()))
.parse()
.unwrap();
result.combine(config.write_cpp_const_guid(name, &guid));
}
result.combine(vtbl);
}
result
} else {
let guid = config.write_guid_u128(&self.def.guid_attribute().unwrap());
let runtime_name = if config.emit_runtime_name(type_name) {
let arity = self.generics.len();
let name = if arity == 0 {
format!("{type_name}")
} else {
format!("{type_name}`{arity}")
};
let name = Literal::byte_string(name.as_bytes());
quote! { , #name }
} else {
quote! {}
};
let mut result = quote! {
#cfg
windows_core::imp::define_winrt_interface!(#name, #vtbl_name, #guid #runtime_name);
};
if !is_exclusive && self.generics.is_empty() {
result.combine(quote! {
#cfg
windows_core::imp::interface_hierarchy!(#name, windows_core::IUnknown, windows_core::IInspectable);
});
}
if !is_exclusive && !required_interfaces.is_empty() {
if self.generics.is_empty() {
let interfaces: Vec<_> = required_interfaces
.iter()
.filter(|ty| {
config.provides(&Type::Interface((*ty).clone()))
&& config.plan.selection.includes_hierarchy(
type_name.namespace(),
type_name.name(),
ty,
)
})
.map(|ty| ty.write_name(config))
.collect();
if !interfaces.is_empty() {
result.combine(quote! {
#cfg
windows_core::imp::required_hierarchy!(#name, #(#interfaces),*);
});
}
} else {
let interfaces = required_interfaces
.iter()
.filter(|ty| {
config.provides(&Type::Interface((*ty).clone()))
&& config.plan.selection.includes_hierarchy(
type_name.namespace(),
type_name.name(),
ty,
)
})
.map(|ty| {
let ty = ty.write_name(config);
quote!{
impl<#constraints> windows_core::imp::CanInto<#ty> for #name { const QUERY: bool = true; }
}
});
result.combine(quote! {
#(#interfaces)*
});
}
}
let minimal = config.bindgen.style.is_minimal();
let implementation_only = config.should_implement(type_name, false)
&& config.plan.selection.is_shell(type_name);
let suppress_methods = minimal
&& ((is_exclusive && self.is_factory(config.reader)) || implementation_only);
let emit_methods = !suppress_methods && (!is_exclusive || minimal);
if emit_methods {
let method_names = &mut MethodNames::new();
let mut method_tokens = TokenStream::new();
let mut iterable = None;
let self_config = config.with_self_ty(self.type_name(), &self.generics);
for (method, vname) in named_methods(&methods) {
let cfg = method.write_cfg(config, &class_cfg, false);
let method = method.write(
&self_config,
Some(self),
InterfaceKind::Default,
method_names,
&vname,
true,
);
method_tokens.combine(quote! {
#cfg
#method
});
}
for interface in &required_interfaces {
if !config.bindgen.style.emit_inherited_forwarders()
|| !config.plan.selection.includes_hierarchy(
type_name.namespace(),
type_name.name(),
interface,
)
{
continue;
}
for (method, vname) in named_methods(&interface.get_methods(config)) {
let cfg = method.write_cfg(config, &class_cfg, false);
let def = method.def;
let method = method.write(
&self_config,
Some(interface),
interface.kind,
method_names,
&vname,
true,
);
if interface.type_name() == TypeName::IIterable && def.name() == "First" {
iterable = Some((interface, method_names.last_name(def)));
}
method_tokens.combine(quote! {
#cfg
#method
});
}
}
if !method_tokens.is_empty() {
result.combine(quote! {
#cfg
impl<#constraints> #name {
#method_tokens
}
});
}
if self.def.is_agile() {
result.combine(quote! {
#cfg
unsafe impl<#constraints> Send for #name {}
#cfg
unsafe impl<#constraints> Sync for #name {}
});
}
let into_iterator = if config.bindgen.style.emit_iterable_into_iterator() {
iterable.map(|(interface, first)| {
let ty = interface.generics[0].write_name(config);
quote! {
#cfg
impl<#constraints> IntoIterator for #name {
type Item = #ty;
type IntoIter = windows_collections::BufferedIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
IntoIterator::into_iter(&self)
}
}
#cfg
impl<#constraints> IntoIterator for &#name {
type Item = #ty;
type IntoIter = windows_collections::BufferedIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
windows_collections::BufferedIterator::new(self.#first().unwrap())
}
}
}
})
} else {
None
};
if let Some(into_iterator) = into_iterator {
result.combine(into_iterator);
}
}
if config.should_implement(type_name, !is_exclusive) {
let vis = config.item_vis();
let impl_name: TokenStream = format!("{}_Impl", trim_tick(self.def.name()))
.parse()
.unwrap();
let generics: Vec<_> = self
.generics
.iter()
.map(|ty| ty.write_name(config))
.collect();
let runtime_name = format!("{type_name}");
let cfg = if config.bindgen.layout.is_package() {
let mut dependencies = self.dependencies(config.reader);
for interface in std::iter::once(self).chain(&required_interfaces) {
for method in interface.get_methods(config) {
if let MethodOrName::Method(method) = method {
dependencies.combine(&method.dependencies);
}
}
}
Cfg::new(&dependencies, config).write(config, false)
} else {
quote! {}
};
result.combine(if self.generics.is_empty() {
quote! {
#cfg
impl<#constraints> windows_core::RuntimeName for #name {
const NAME: &'static str = #runtime_name;
}
}
} else {
quote! {
#cfg
impl<#constraints> windows_core::RuntimeName for #name {
const NAME: &'static str = #runtime_name;
const RUNTIME_CLASS_NAME: windows_core::imp::ConstBuffer = <Self as windows_core::RuntimeType>::NAME;
}
}
});
let has_skipped_methods = methods
.iter()
.any(|method| matches!(method, MethodOrName::Name(_)))
|| required_interfaces
.iter()
.any(|ty| ty.has_skipped_methods(config));
if !has_skipped_methods {
let field_methods = write_impl_field_methods(&methods, |name| {
quote! { #name: #name::<#(#generics,)* Identity, OFFSET>, }
});
let mut names = MethodNames::new();
let impl_methods: Vec<_> = methods.iter().map(|method| match method {
MethodOrName::Method(method) => {
let name = names.add(method.def);
let signature = method.write_abi(config, true);
let call = quote! { #impl_name::#name };
let upcall = method.write_upcall(call, true, config);
quote! {
unsafe extern "system" fn #name<#constraints Identity: #impl_name <#(#generics,)*>, const OFFSET: isize> (#signature) -> windows_core::HRESULT {
unsafe {
let this: &Identity = &*((this as *const *const ()).offset(OFFSET) as *const Identity);
#upcall
}
}
}
}
_ => quote! {},
}).collect();
let trait_methods = write_impl_trait_methods(&methods, |method| {
method.write_impl_signature(config, true, true)
});
let requires = if required_interfaces.is_empty() {
quote! { windows_core::IUnknownImpl }
} else {
let interfaces = required_interfaces
.iter()
.map(|ty| ty.write_impl_name(config));
quote! { #(#interfaces)+* }
};
result.combine(quote! {
#cfg
pub trait #impl_name <#(#generics),*> : #requires where #constraints {
#(#trait_methods)*
}
#cfg
impl<#constraints> #vtbl_name {
#vis const fn new<Identity: #impl_name <#(#generics,)*>, const OFFSET: isize>() -> Self {
#(#impl_methods)*
Self {
base__: windows_core::IInspectable_Vtbl::new::<Identity, OFFSET>(),
#(#field_methods)*
#named_phantoms
}
}
#vis fn matches(iid: &windows_core::GUID) -> bool {
iid == &<#name as windows_core::Interface>::IID
}
}
});
}
}
result.combine(vtbl);
if emit_methods {
result.combine(self.write_extensions(&methods));
}
result
}
}
fn write_extensions(&self, methods: &[MethodOrName<Method>]) -> TokenStream {
let has_method = |name: &str| {
methods.iter().any(
|method| matches!(method, MethodOrName::Method(method) if method.def.name() == name),
)
};
match self.type_name() {
TypeName::IIterator
if ["get_Current", "get_HasCurrent", "MoveNext"]
.iter()
.all(|name| has_method(name)) =>
{
quote! {
impl<T: windows_core::RuntimeType> Iterator for IIterator<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
let result = if self.HasCurrent().unwrap_or(false) {
self.Current().ok()
} else {
None
};
if result.is_some() {
let _ = self.MoveNext();
}
result
}
}
}
}
TypeName::IIterable if has_method("First") => {
quote! {
impl<T: windows_core::RuntimeType> IntoIterator for IIterable<T> {
type Item = T;
type IntoIter = windows_collections::BufferedIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
IntoIterator::into_iter(&self)
}
}
impl<T: windows_core::RuntimeType> IntoIterator for &IIterable<T> {
type Item = T;
type IntoIter = windows_collections::BufferedIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
windows_collections::BufferedIterator::new(self.First().unwrap())
}
}
}
}
_ => quote! {},
}
}
pub fn write_name(&self, config: &Config) -> TokenStream {
self.type_name().write(config, &self.generics)
}
fn write_vtbl_name(&self, config: &Config) -> TokenStream {
let name: TokenStream = format!("{}_Vtbl", trim_tick(self.def.name()))
.parse()
.unwrap();
if self.generics.is_empty() {
name
} else {
let generics = self.generics.iter().map(|ty| ty.write_name(config));
quote! { #name < #(#generics,)* > }
}
}
pub fn write_impl_name(&self, config: &Config) -> TokenStream {
let name: TokenStream = format!("{}_Impl", trim_tick(self.def.name()))
.parse()
.unwrap();
let namespace = config.write_namespace(self.def.type_name());
if self.generics.is_empty() {
quote! { #namespace #name }
} else {
let generics = self.generics.iter().map(|ty| ty.write_name(config));
quote! { #namespace #name < #(#generics),* > }
}
}
pub fn is_exclusive(&self) -> bool {
self.def.has_attribute("ExclusiveToAttribute")
}
pub fn is_factory(&self, reader: &Reader) -> bool {
let Some(attribute) = self.def.find_attribute("ExclusiveToAttribute") else {
return false;
};
let value = attribute.value();
let Some((_, Value::TypeName(class_tn))) = value.first() else {
return false;
};
let Some(Type::Class(class)) = reader
.with_full_name(class_tn.namespace.as_str(), class_tn.name.as_str())
.next()
else {
return false;
};
let our_namespace = self.def.namespace();
let our_name = self.def.name();
for attribute in class.def.attributes() {
match attribute.name() {
"StaticAttribute" | "ActivatableAttribute" | "ComposableAttribute" => {
for (_, arg) in attribute.value() {
if let Value::TypeName(tn) = arg
&& tn.namespace.as_str() == our_namespace
&& tn.name.as_str() == our_name
{
return true;
}
}
}
_ => {}
}
}
false
}
pub fn runtime_signature(&self, reader: &Reader) -> String {
interface_signature(self.def, &self.generics, reader)
}
pub fn required_interfaces(&self, reader: &Reader) -> Vec<Self> {
fn walk(interface: &Interface, set: &mut Vec<Interface>, reader: &Reader) {
for ty in interface
.def
.interface_impls()
.map(|imp| imp.ty(&interface.generics, reader))
{
let Type::Interface(interface) = ty else {
panic!();
};
if !set.iter().any(|existing| existing.def == interface.def) {
walk(&interface, set, reader);
set.push(interface);
}
}
}
let mut set = vec![];
walk(self, &mut set, reader);
set.sort();
set.dedup();
set
}
}
impl Dependencies for Interface {
fn combine(&self, dependencies: &mut TypeMap, reader: &Reader) {
Type::Object.combine(dependencies, reader);
for interface in self.required_interfaces(reader) {
Type::Interface(interface).combine(dependencies, reader);
}
for ty in &self.generics {
ty.combine(dependencies, reader);
}
let is_iterable = self.type_name() == TypeName::IIterable;
for method in self.def.methods() {
for ty in method.method_signature(&self.generics, reader).types() {
if is_iterable || ty.is_core() {
ty.combine(dependencies, reader);
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn definition_identity_agrees_across_collections() {
let reader = default_reader(false);
let Type::Interface(mut left) = reader
.with_full_name("Windows.Foundation.Collections", "IIterable`1")
.next()
.unwrap()
else {
panic!();
};
left.generics = vec![Type::String];
let mut right = left.clone();
right.generics = vec![Type::U32];
assert_eq!(left.cmp(&right), Ordering::Equal);
assert_eq!(left, right);
assert_eq!(HashSet::from([left.clone(), right.clone()]).len(), 1);
assert_eq!(BTreeSet::from([left, right]).len(), 1);
}
}