Skip to content

Emit an ExternType impl for shared structs and enums #341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 8, 2020
Merged
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
22 changes: 18 additions & 4 deletions macro/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream {
for api in apis {
match api {
Api::Include(_) | Api::RustType(_) | Api::Impl(_) => {}
Api::Struct(strct) => expanded.extend(expand_struct(strct)),
Api::Enum(enm) => expanded.extend(expand_enum(enm)),
Api::Struct(strct) => expanded.extend(expand_struct(namespace, strct)),
Api::Enum(enm) => expanded.extend(expand_enum(namespace, enm)),
Api::CxxType(ety) => {
let ident = &ety.ident;
if !types.structs.contains_key(ident) && !types.enums.contains_key(ident) {
Expand Down Expand Up @@ -125,37 +125,46 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream {
}
}

fn expand_struct(strct: &Struct) -> TokenStream {
fn expand_struct(namespace: &Namespace, strct: &Struct) -> TokenStream {
let ident = &strct.ident;
let doc = &strct.doc;
let derives = &strct.derives;
let type_id = type_id(namespace, ident);
let fields = strct.fields.iter().map(|field| {
// This span on the pub makes "private type in public interface" errors
// appear in the right place.
let vis = Token![pub](field.ident.span());
quote!(#vis #field)
});

quote! {
#doc
#[derive(#(#derives),*)]
#[repr(C)]
pub struct #ident {
#(#fields,)*
}

unsafe impl ::cxx::ExternType for #ident {
type Id = #type_id;
type Kind = ::cxx::kind::Trivial;
}
}
}

fn expand_enum(enm: &Enum) -> TokenStream {
fn expand_enum(namespace: &Namespace, enm: &Enum) -> TokenStream {
let ident = &enm.ident;
let doc = &enm.doc;
let repr = enm.repr;
let type_id = type_id(namespace, ident);
let variants = enm.variants.iter().map(|variant| {
let variant_ident = &variant.ident;
let discriminant = &variant.discriminant;
Some(quote! {
pub const #variant_ident: Self = #ident { repr: #discriminant };
})
});

quote! {
#doc
#[derive(Copy, Clone, PartialEq, Eq)]
Expand All @@ -168,6 +177,11 @@ fn expand_enum(enm: &Enum) -> TokenStream {
impl #ident {
#(#variants)*
}

unsafe impl ::cxx::ExternType for #ident {
type Id = #type_id;
type Kind = ::cxx::kind::Trivial;
}
}
}

Expand Down