use super::*;
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct CppInterface {
pub def: TypeDef,
}
impl Ord for CppInterface {
fn cmp(&self, other: &Self) -> Ordering {
self.def.name().cmp(other.def.name())
}
}
impl PartialOrd for CppInterface {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl CppInterface {
pub fn type_name(&self) -> TypeName {
self.def.type_name()
}
pub fn get_methods(&self, config: &Config) -> Vec<MethodOrName<CppMethod>> {
if self.def.methods().any(|method| {
method
.find_attribute("NativeOverrideSlotAttribute")
.is_some()
}) {
Self::vtable_methods(self.def, config.reader);
}
self.def
.methods()
.filter(|method| {
method
.find_attribute("NativeOverrideSlotAttribute")
.is_none()
})
.map(|def| {
let method = CppMethod::new(def, config.reader);
if !config.plan.includes_method(def, &[]) {
MethodOrName::Name(method.def)
} else {
MethodOrName::Method(method)
}
})
.collect()
}
fn vtable_methods(def: TypeDef, reader: &Reader) -> Vec<MethodDef> {
assert!(
def.interface_impls().count() <= 1,
"native slot overrides require a single base on `{}`",
def.name()
);
let mut methods = if let Some(base) = def.interface_impls().next() {
let windows_metadata::Type::ClassName(base) = base.interface(&[]) else {
panic!("invalid native interface base on `{}`", def.name());
};
Self::vtable_methods(def.index().expect(&base.namespace, &base.name), reader)
} else {
Vec::new()
};
let inherited = methods.len();
let mut overrides = BTreeSet::new();
for method in def.methods() {
if let Some(attribute) = method.find_attribute("NativeOverrideSlotAttribute") {
assert_eq!(
method
.attributes()
.filter(|attr| attr.name() == "NativeOverrideSlotAttribute")
.count(),
1,
"duplicate native override slot on `{}`",
method.name()
);
let values = attribute.value();
let [(_, Value::U32(slot))] = values.as_slice() else {
panic!("invalid native override slot on `{}`", method.name());
};
let slot = *slot as usize;
assert!(
slot < inherited
&& overrides.insert(slot)
&& !method.flags().contains(MethodAttributes::NewSlot),
"invalid inherited slot on `{}.{}`",
def.name(),
method.name()
);
let base = methods[slot];
let signature = method.method_signature(&[], reader);
let base_signature = base.method_signature(&[], reader);
assert!(
method.name() == base.name()
&& signature.call_flags == base_signature.call_flags
&& signature.params.len() == base_signature.params.len()
&& same_override_type(
&signature.return_type,
&base_signature.return_type,
reader,
)
&& signature
.params
.iter()
.zip(&base_signature.params)
.all(|(a, b)| { same_override_type(&a.ty, &b.ty, reader) }),
"incompatible inherited slot on `{}.{}`",
def.name(),
method.name()
);
methods[slot] = method;
} else {
methods.push(method);
}
}
methods
}
pub fn has_skipped_methods(&self, config: &Config) -> bool {
self.def
.methods()
.any(|def| !config.plan.includes_method(def, &[]))
}
fn write_cfg(&self, config: &Config) -> (Cfg, TokenStream) {
write_full_cfg(self, config)
}
pub fn write(&self, config: &Config) -> TokenStream {
let methods = self.get_methods(config);
let vis = config.item_vis();
let base_interfaces = self.base_interfaces(config.reader);
let has_unknown_base = matches!(base_interfaces.first(), Some(Type::IUnknown));
let (class_cfg, cfg) = self.write_cfg(config);
let vtbl_name = self.write_vtbl_name(config);
let vtbl = {
let core = config.write_core();
let base = match base_interfaces.last() {
Some(Type::IUnknown) => {
quote! { pub base__: #core IUnknown_Vtbl, }
}
Some(Type::Object) => {
quote! { pub base__: #core IInspectable_Vtbl, }
}
Some(Type::CppInterface(ty)) => {
let name = ty.write_vtbl_name(config);
quote! { pub base__: #name, }
}
_ => quote! {},
};
let methods = write_vtbl_methods(&methods, &class_cfg, config, |method| {
method.write_abi(config, false)
});
let hide_vtbl = config.doc_hidden_in_package();
quote! {
#cfg
#[repr(C)]
#hide_vtbl
pub struct #vtbl_name {
#base
#(#methods)*
}
}
};
if config.bindgen.style.is_sys() {
let mut result = quote! {};
if !config.bindgen.layout.is_package() {
if has_unknown_base && let Some(guid) = self.def.guid_attribute() {
let name: TokenStream = format!("IID_{}", self.def.name()).parse().unwrap();
result.combine(config.write_cpp_const_guid(name, &guid));
}
result.combine(vtbl);
}
result
} else {
let name = to_ident(self.def.name());
let mut result = if has_unknown_base {
if let Some(guid) = self.def.guid_attribute() {
let guid = config.write_guid_u128(&guid);
if base_interfaces.contains(&Type::Object) {
quote! {
#cfg
windows_core::imp::define_interface!(#name, #vtbl_name, #guid, inspectable);
}
} else {
quote! {
#cfg
windows_core::imp::define_interface!(#name, #vtbl_name, #guid);
}
}
} else {
quote! {
#cfg
windows_core::imp::define_interface!(#name, #vtbl_name, 0);
}
}
} else {
quote! {
#cfg
windows_core::imp::define_interface!(#name, #vtbl_name);
}
};
if let Some(Type::CppInterface(base)) = base_interfaces.last() {
let base = base.write_name(config);
result.combine(quote! {
#cfg
impl core::ops::Deref for #name {
type Target = #base;
fn deref(&self) -> &Self::Target {
unsafe { core::mem::transmute(self) }
}
}
});
}
if !base_interfaces.is_empty() {
let bases = base_interfaces.iter().map(|ty| ty.write_name(config));
result.combine(quote! {
#cfg
windows_core::imp::interface_hierarchy!(#name, #(#bases),*);
});
}
let suppress_methods = config.bindgen.style.is_minimal()
&& config.should_implement(self.def.type_name(), false)
&& config.plan.selection.is_shell(self.type_name());
let mut methods_tokens = quote! {};
if !suppress_methods {
let method_names = &mut MethodNames::new();
let self_config = config.with_self_ty(self.type_name(), &[]);
for (method, vname) in named_methods(&methods) {
let cfg = method.write_cfg(config, &class_cfg, false);
let method = method.write(&self_config, method_names, &vname);
methods_tokens.combine(quote! {
#cfg
#method
});
}
}
if !methods_tokens.is_empty() {
result.combine(quote! {
#cfg
impl #name {
#methods_tokens
}
});
}
result.combine(vtbl);
if self.def.is_agile() || (config.reader.legacy() && legacy::is_agile(self.def)) {
result.combine(quote! {
#cfg
unsafe impl Send for #name {}
#cfg
unsafe impl Sync for #name {}
});
}
if config.should_implement(self.def.type_name(), true) {
let impl_name: TokenStream = format!("{}_Impl", self.def.name()).parse().unwrap();
let cfg = if config.bindgen.layout.is_package() {
let mut dependencies = self.dependencies(config.reader);
let bases = base_interfaces.iter().filter_map(|ty| match ty {
Type::CppInterface(ty) => Some(ty),
_ => None,
});
for interface in std::iter::once(self).chain(bases) {
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! {}
};
let field_methods = write_impl_field_methods(&methods, |name| {
if has_unknown_base {
quote! { #name: #name::<Identity, OFFSET>, }
} else {
quote! { #name: #name::<Identity>, }
}
});
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 upcall = method.write_upcall(&impl_name, &name, config);
if has_unknown_base {
quote! {
unsafe extern "system" fn #name<Identity: #impl_name, const OFFSET: isize> #signature {
unsafe {
let this: &Identity = &*((this as *const *const ()).offset(OFFSET) as *const Identity);
#upcall
}
}
}
} else {
quote! {
unsafe extern "system" fn #name<Identity: #impl_name> #signature {
unsafe {
let this = (this as *mut *mut core::ffi::c_void) as *const windows_core::ScopedHeap;
let this = &*((*this).this as *const Identity);
#upcall
}
}
}
}
}
_ => quote! {},
}).collect();
let trait_methods = write_impl_trait_methods(&methods, |method| {
method.write_impl_signature(config)
});
let impl_base = base_interfaces.last().map(|ty| ty.write_impl_name(config));
let field_base = base_interfaces.last().map(|ty|{
match ty {
Type::IUnknown => quote! { base__: windows_core::IUnknown_Vtbl::new::<Identity, OFFSET>(), },
Type::Object => quote! { base__: windows_core::IInspectable_Vtbl::new::<Identity, OFFSET>(), },
Type::CppInterface(ty) => {
let ty = ty.write_vtbl_name(config);
if has_unknown_base {
quote! { base__: #ty::new::<Identity, OFFSET>(), }
} else {
quote! { base__: #ty::new::<Identity>(), }
}
}
rest => panic!("{rest:?}"),
}
});
let has_skipped_methods = methods
.iter()
.any(|method| matches!(method, MethodOrName::Name(_)))
|| base_interfaces.iter().any(|ty| match ty {
Type::CppInterface(ty) => ty.has_skipped_methods(config),
_ => false,
});
if has_skipped_methods {
if has_unknown_base {
result.combine(quote! {
#cfg
impl windows_core::RuntimeName for #name {}
});
}
} else {
result.combine( if has_unknown_base {
let matches = base_interfaces.last().and_then(|ty|{
match ty {
Type::CppInterface(ty) => {
let name = ty.write_vtbl_name(config);
Some(quote! { || #name::matches(iid) })
}
_ => None,
}
});
quote! {
#cfg
pub trait #impl_name: #impl_base {
#(#trait_methods)*
}
#cfg
impl #vtbl_name {
#vis const fn new<Identity: #impl_name, const OFFSET: isize>() -> Self {
#(#impl_methods)*
Self {
#field_base
#(#field_methods)*
}
}
#vis fn matches(iid: &windows_core::GUID) -> bool {
iid == &<#name as windows_core::Interface>::IID #matches
}
}
#cfg
impl windows_core::RuntimeName for #name {}
}
} else {
let implvtbl_ident = impl_name.join("Vtbl");
quote! {
#cfg
pub trait #impl_name : #impl_base {
#(#trait_methods)*
}
#cfg
impl #vtbl_name {
#vis const fn new<Identity: #impl_name>() -> Self {
#(#impl_methods)*
Self{
#field_base
#(#field_methods)*
}
}
}
#cfg
struct #implvtbl_ident<T: #impl_name> (core::marker::PhantomData<T>);
#cfg
impl<T: #impl_name> #implvtbl_ident<T> {
const VTABLE: #vtbl_name = #vtbl_name::new::<T>();
}
#cfg
impl #name {
#vis fn new<'a, T: #impl_name>(this: &'a T) -> windows_core::ScopedInterface<'a, Self> {
let this = windows_core::ScopedHeap { vtable: &#implvtbl_ident::<T>::VTABLE as *const _ as *const _, this: this as *const _ as *const _ };
let this = windows_core::imp::box_into_raw(windows_core::imp::box_new(this));
unsafe { windows_core::ScopedInterface::new(<Self as windows_core::Interface>::from_raw(this as *mut _)) }
}
}
}
});
}
}
result
}
}
pub fn write_name(&self, config: &Config) -> TokenStream {
self.type_name().write(config, &[])
}
fn write_vtbl_name(&self, config: &Config) -> TokenStream {
let name: TokenStream = format!("{}_Vtbl", self.def.name()).parse().unwrap();
let namespace = config.write_namespace(self.def.type_name());
quote! { #namespace #name }
}
pub fn write_impl_name(&self, config: &Config) -> TokenStream {
let name: TokenStream = format!("{}_Impl", self.def.name()).parse().unwrap();
let namespace = config.write_namespace(self.def.type_name());
quote! { #namespace #name }
}
pub fn base_interfaces(&self, reader: &Reader) -> Vec<Type> {
let mut bases = vec![];
let mut def = self.def;
while let Some(base) = def
.interface_impls()
.map(move |imp| imp.ty(&[], reader))
.next()
{
match base {
Type::CppInterface(ref ty) => {
def = ty.def;
bases.insert(0, base);
}
Type::Object => {
bases.insert(0, Type::IUnknown);
bases.insert(1, Type::Object);
break;
}
Type::IUnknown => {
bases.insert(0, Type::IUnknown);
break;
}
rest => panic!("{rest:?}"),
}
}
bases
}
}
fn same_override_type(a: &Type, b: &Type, reader: &Reader) -> bool {
let a = a.projection_type(reader);
let b = b.projection_type(reader);
match (&a, &b) {
(Type::PtrMut(..), Type::PtrMut(..)) | (Type::PtrConst(..), Type::PtrConst(..)) => {
same_override_type(&a.deref(), &b.deref(), reader)
}
_ => a == b,
}
}
impl Dependencies for CppInterface {
fn combine(&self, dependencies: &mut TypeMap, reader: &Reader) {
let base_interfaces = self.base_interfaces(reader);
for interface in &base_interfaces {
interface.combine(dependencies, reader);
}
for method in self.def.methods() {
for ty in method.method_signature(&[], reader).types() {
if ty.is_core() {
ty.combine(dependencies, reader);
}
}
}
}
}