Skip to content

Commit 4396abf

Browse files
authored
Merge pull request #341 from dtolnay/shared
Emit an ExternType impl for shared structs and enums
2 parents 9420532 + 8684cc5 commit 4396abf

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

macro/src/expand.rs

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,8 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream {
4141
for api in apis {
4242
match api {
4343
Api::Include(_) | Api::RustType(_) | Api::Impl(_) => {}
44-
Api::Struct(strct) => expanded.extend(expand_struct(strct)),
45-
Api::Enum(enm) => expanded.extend(expand_enum(enm)),
44+
Api::Struct(strct) => expanded.extend(expand_struct(namespace, strct)),
45+
Api::Enum(enm) => expanded.extend(expand_enum(namespace, enm)),
4646
Api::CxxType(ety) => {
4747
let ident = &ety.ident;
4848
if !types.structs.contains_key(ident) && !types.enums.contains_key(ident) {
@@ -125,37 +125,46 @@ fn expand(ffi: Module, apis: &[Api], types: &Types) -> TokenStream {
125125
}
126126
}
127127

128-
fn expand_struct(strct: &Struct) -> TokenStream {
128+
fn expand_struct(namespace: &Namespace, strct: &Struct) -> TokenStream {
129129
let ident = &strct.ident;
130130
let doc = &strct.doc;
131131
let derives = &strct.derives;
132+
let type_id = type_id(namespace, ident);
132133
let fields = strct.fields.iter().map(|field| {
133134
// This span on the pub makes "private type in public interface" errors
134135
// appear in the right place.
135136
let vis = Token![pub](field.ident.span());
136137
quote!(#vis #field)
137138
});
139+
138140
quote! {
139141
#doc
140142
#[derive(#(#derives),*)]
141143
#[repr(C)]
142144
pub struct #ident {
143145
#(#fields,)*
144146
}
147+
148+
unsafe impl ::cxx::ExternType for #ident {
149+
type Id = #type_id;
150+
type Kind = ::cxx::kind::Trivial;
151+
}
145152
}
146153
}
147154

148-
fn expand_enum(enm: &Enum) -> TokenStream {
155+
fn expand_enum(namespace: &Namespace, enm: &Enum) -> TokenStream {
149156
let ident = &enm.ident;
150157
let doc = &enm.doc;
151158
let repr = enm.repr;
159+
let type_id = type_id(namespace, ident);
152160
let variants = enm.variants.iter().map(|variant| {
153161
let variant_ident = &variant.ident;
154162
let discriminant = &variant.discriminant;
155163
Some(quote! {
156164
pub const #variant_ident: Self = #ident { repr: #discriminant };
157165
})
158166
});
167+
159168
quote! {
160169
#doc
161170
#[derive(Copy, Clone, PartialEq, Eq)]
@@ -168,6 +177,11 @@ fn expand_enum(enm: &Enum) -> TokenStream {
168177
impl #ident {
169178
#(#variants)*
170179
}
180+
181+
unsafe impl ::cxx::ExternType for #ident {
182+
type Id = #type_id;
183+
type Kind = ::cxx::kind::Trivial;
184+
}
171185
}
172186
}
173187

0 commit comments

Comments
 (0)