blob: 9ebb62359acc8585390939046ee7bde9b89bb0c9 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::namespace::Namespace;
David Tolnaya52602b2020-03-06 10:24:34 -08002use crate::syntax::atom::Atom::{self, *};
David Tolnay39d575f2020-03-03 00:10:56 -08003use crate::syntax::{self, check, Api, ExternFn, ExternType, Struct, Type, Types};
David Tolnay7db73692019-10-20 14:51:12 -04004use proc_macro2::{Ident, Span, TokenStream};
5use quote::{format_ident, quote, quote_spanned};
6use syn::{Error, ItemMod, Result, Token};
7
8pub fn bridge(namespace: &Namespace, ffi: ItemMod) -> Result<TokenStream> {
9 let ident = &ffi.ident;
10 let content = ffi.content.ok_or(Error::new(
11 Span::call_site(),
12 "#[cxx::bridge] module must have inline contents",
13 ))?;
14 let apis = syntax::parse_items(content.1)?;
15 let ref types = Types::collect(&apis)?;
16 check::typecheck(&apis, types)?;
17
18 let mut expanded = TokenStream::new();
19 let mut hidden = TokenStream::new();
20 let mut has_rust_type = false;
21
22 for api in &apis {
23 if let Api::RustType(ety) = api {
24 expanded.extend(expand_rust_type(ety));
25 if !has_rust_type {
David Tolnay199d7352020-01-20 18:40:10 -080026 hidden.extend(quote!(
27 const fn __assert_sized<T>() {}
28 ));
David Tolnay7db73692019-10-20 14:51:12 -040029 has_rust_type = true;
30 }
31 let ident = &ety.ident;
32 hidden.extend(quote!(__assert_sized::<#ident>();));
33 }
34 }
35
36 for api in &apis {
37 match api {
38 Api::Include(_) | Api::RustType(_) => {}
39 Api::Struct(strct) => expanded.extend(expand_struct(strct)),
40 Api::CxxType(ety) => expanded.extend(expand_cxx_type(ety)),
41 Api::CxxFunction(efn) => {
42 expanded.extend(expand_cxx_function_shim(namespace, efn, types));
43 }
44 Api::RustFunction(efn) => {
45 hidden.extend(expand_rust_function_shim(namespace, efn, types))
46 }
47 }
48 }
49
50 for ty in types {
51 if let Type::RustBox(ty) = ty {
52 if let Type::Ident(ident) = &ty.inner {
53 if Atom::from(ident).is_none() {
54 hidden.extend(expand_rust_box(namespace, ident));
55 }
56 }
57 } else if let Type::UniquePtr(ptr) = ty {
58 if let Type::Ident(ident) = &ptr.inner {
59 if Atom::from(ident).is_none() {
60 expanded.extend(expand_unique_ptr(namespace, ident));
61 }
62 }
63 }
64 }
65
66 // Work around https://github.com/rust-lang/rust/issues/67851.
67 if !hidden.is_empty() {
68 expanded.extend(quote! {
69 #[doc(hidden)]
70 const _: () = {
71 #hidden
72 };
73 });
74 }
75
76 let attrs = ffi
77 .attrs
78 .into_iter()
79 .filter(|attr| attr.path.is_ident("doc"));
80 let vis = &ffi.vis;
81
82 Ok(quote! {
83 #(#attrs)*
84 #[deny(improper_ctypes)]
85 #[allow(non_snake_case)]
86 #vis mod #ident {
87 #expanded
88 }
89 })
90}
91
92fn expand_struct(strct: &Struct) -> TokenStream {
93 let ident = &strct.ident;
94 let doc = &strct.doc;
95 let derives = &strct.derives;
96 let fields = strct.fields.iter().map(|field| {
97 // This span on the pub makes "private type in public interface" errors
98 // appear in the right place.
99 let vis = Token![pub](field.ident.span());
100 quote!(#vis #field)
101 });
102 quote! {
103 #doc
104 #[derive(#(#derives),*)]
105 #[repr(C)]
106 pub struct #ident {
107 #(#fields,)*
108 }
109 }
110}
111
112fn expand_cxx_type(ety: &ExternType) -> TokenStream {
113 let ident = &ety.ident;
114 let doc = &ety.doc;
115 quote! {
116 #doc
117 #[repr(C)]
118 pub struct #ident {
119 _private: ::cxx::private::Opaque,
120 }
121 }
122}
123
124fn expand_cxx_function_decl(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
125 let ident = &efn.ident;
David Tolnay39d575f2020-03-03 00:10:56 -0800126 let args = efn.args.iter().map(|arg| {
127 let ident = &arg.ident;
128 let ty = expand_extern_type(&arg.ty);
David Tolnaya46a2372020-03-06 10:03:48 -0800129 if arg.ty == RustString {
130 quote!(#ident: *const #ty)
131 } else if types.needs_indirect_abi(&arg.ty) {
David Tolnay39d575f2020-03-03 00:10:56 -0800132 quote!(#ident: *mut #ty)
133 } else {
134 quote!(#ident: #ty)
135 }
136 });
David Tolnay7db73692019-10-20 14:51:12 -0400137 let ret = expand_extern_return_type(&efn.ret, types);
138 let mut outparam = None;
139 if indirect_return(&efn.ret, types) {
140 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
141 outparam = Some(quote!(__return: *mut #ret));
142 }
David Tolnaye43b7372020-01-08 08:46:20 -0800143 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400144 let local_name = format_ident!("__{}", ident);
145 quote! {
146 #[link_name = #link_name]
147 fn #local_name(#(#args,)* #outparam) #ret;
148 }
149}
150
151fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
152 let ident = &efn.ident;
153 let doc = &efn.doc;
154 let decl = expand_cxx_function_decl(namespace, efn, types);
155 let args = &efn.args;
156 let ret = expand_return_type(&efn.ret);
157 let indirect_return = indirect_return(&efn.ret, types);
158 let vars = efn.args.iter().map(|arg| {
159 let var = &arg.ident;
160 match &arg.ty {
David Tolnaya52602b2020-03-06 10:24:34 -0800161 Type::Ident(ident) if ident == RustString => {
David Tolnaya46a2372020-03-06 10:03:48 -0800162 quote!(#var.as_mut_ptr() as *const ::cxx::private::RustString)
David Tolnay7db73692019-10-20 14:51:12 -0400163 }
164 Type::RustBox(_) => quote!(::std::boxed::Box::into_raw(#var)),
165 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::into_raw(#var)),
166 Type::Ref(ty) => match &ty.inner {
David Tolnaya52602b2020-03-06 10:24:34 -0800167 Type::Ident(ident) if ident == RustString => {
David Tolnay7db73692019-10-20 14:51:12 -0400168 quote!(::cxx::private::RustString::from_ref(#var))
169 }
170 _ => quote!(#var),
171 },
172 Type::Str(_) => quote!(::cxx::private::RustStr::from(#var)),
173 ty if types.needs_indirect_abi(ty) => quote!(#var.as_mut_ptr()),
174 _ => quote!(#var),
175 }
176 });
177 let mut setup = efn
178 .args
179 .iter()
180 .filter(|arg| types.needs_indirect_abi(&arg.ty))
181 .map(|arg| {
182 let var = &arg.ident;
183 // These are arguments for which C++ has taken ownership of the data
184 // behind the mut reference it received.
185 quote! {
186 let mut #var = std::mem::MaybeUninit::new(#var);
187 }
188 })
189 .collect::<TokenStream>();
190 let local_name = format_ident!("__{}", ident);
191 let call = if indirect_return {
192 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
193 setup.extend(quote! {
194 let mut __return = ::std::mem::MaybeUninit::<#ret>::uninit();
195 #local_name(#(#vars,)* __return.as_mut_ptr());
196 });
197 quote! {
198 __return.assume_init()
199 }
200 } else {
201 quote! {
202 #local_name(#(#vars),*)
203 }
204 };
205 let expr = efn
206 .ret
207 .as_ref()
208 .and_then(|ret| match ret {
David Tolnaya52602b2020-03-06 10:24:34 -0800209 Type::Ident(ident) if ident == RustString => Some(quote!(#call.into_string())),
David Tolnay7db73692019-10-20 14:51:12 -0400210 Type::RustBox(_) => Some(quote!(::std::boxed::Box::from_raw(#call))),
211 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::from_raw(#call))),
212 Type::Ref(ty) => match &ty.inner {
David Tolnaya52602b2020-03-06 10:24:34 -0800213 Type::Ident(ident) if ident == RustString => Some(quote!(#call.as_string())),
David Tolnay7db73692019-10-20 14:51:12 -0400214 _ => None,
215 },
216 Type::Str(_) => Some(quote!(#call.as_str())),
217 _ => None,
218 })
219 .unwrap_or(call);
220 quote! {
221 #doc
222 pub fn #ident(#(#args),*) #ret {
223 extern "C" {
224 #decl
225 }
226 unsafe {
227 #setup
228 #expr
229 }
230 }
231 }
232}
233
234fn expand_rust_type(ety: &ExternType) -> TokenStream {
235 let ident = &ety.ident;
236 quote! {
237 use super::#ident;
238 }
239}
240
241fn expand_rust_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
242 let ident = &efn.ident;
David Tolnay39d575f2020-03-03 00:10:56 -0800243 let args = efn.args.iter().map(|arg| {
244 let ident = &arg.ident;
245 let ty = expand_extern_type(&arg.ty);
246 if types.needs_indirect_abi(&arg.ty) {
247 quote!(#ident: *mut #ty)
248 } else {
249 quote!(#ident: #ty)
250 }
251 });
David Tolnay7db73692019-10-20 14:51:12 -0400252 let vars = efn.args.iter().map(|arg| {
253 let ident = &arg.ident;
David Tolnay17955e22020-01-20 17:58:24 -0800254 match &arg.ty {
David Tolnaya52602b2020-03-06 10:24:34 -0800255 Type::Ident(i) if i == RustString => quote!(::std::mem::take((*#ident).as_mut_string())),
David Tolnay40226ab2020-03-03 00:05:35 -0800256 Type::RustBox(_) => quote!(::std::boxed::Box::from_raw(#ident)),
257 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::from_raw(#ident)),
David Tolnay17955e22020-01-20 17:58:24 -0800258 Type::Ref(ty) => match &ty.inner {
David Tolnaya52602b2020-03-06 10:24:34 -0800259 Type::Ident(i) if i == RustString => quote!(#ident.as_string()),
David Tolnay40226ab2020-03-03 00:05:35 -0800260 _ => quote!(#ident),
David Tolnay17955e22020-01-20 17:58:24 -0800261 },
David Tolnay40226ab2020-03-03 00:05:35 -0800262 Type::Str(_) => quote!(#ident.as_str()),
263 ty if types.needs_indirect_abi(ty) => quote!(::std::ptr::read(#ident)),
264 _ => quote!(#ident),
David Tolnay7db73692019-10-20 14:51:12 -0400265 }
266 });
267 let mut outparam = None;
268 let call = quote! {
269 ::cxx::private::catch_unwind(__fn, move || super::#ident(#(#vars),*))
270 };
271 let mut expr = efn
272 .ret
273 .as_ref()
274 .and_then(|ret| match ret {
David Tolnaya52602b2020-03-06 10:24:34 -0800275 Type::Ident(ident) if ident == RustString => {
David Tolnay7db73692019-10-20 14:51:12 -0400276 Some(quote!(::cxx::private::RustString::from(#call)))
277 }
278 Type::RustBox(_) => Some(quote!(::std::boxed::Box::into_raw(#call))),
279 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::into_raw(#call))),
280 Type::Ref(ty) => match &ty.inner {
David Tolnaya52602b2020-03-06 10:24:34 -0800281 Type::Ident(ident) if ident == RustString => {
David Tolnay7db73692019-10-20 14:51:12 -0400282 Some(quote!(::cxx::private::RustString::from_ref(#call)))
283 }
284 _ => None,
285 },
286 Type::Str(_) => Some(quote!(::cxx::private::RustStr::from(#call))),
287 _ => None,
288 })
289 .unwrap_or(call);
290 if indirect_return(&efn.ret, types) {
291 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
292 outparam = Some(quote!(__return: *mut #ret));
293 expr = quote!(::std::ptr::write(__return, #expr));
294 }
295 let ret = expand_extern_return_type(&efn.ret, types);
David Tolnaye43b7372020-01-08 08:46:20 -0800296 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400297 let local_name = format_ident!("__{}", ident);
298 let catch_unwind_label = format!("::{}", ident);
299 quote! {
300 #[doc(hidden)]
301 #[export_name = #link_name]
302 unsafe extern "C" fn #local_name(#(#args,)* #outparam) #ret {
303 let __fn = concat!(module_path!(), #catch_unwind_label);
304 #expr
305 }
306 }
307}
308
309fn expand_rust_box(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnay9081beb2020-03-01 19:51:46 -0800310 let link_prefix = format!("cxxbridge01$box${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400311 let link_uninit = format!("{}uninit", link_prefix);
312 let link_set_raw = format!("{}set_raw", link_prefix);
313 let link_drop = format!("{}drop", link_prefix);
314 let link_deref = format!("{}deref", link_prefix);
315 let link_deref_mut = format!("{}deref_mut", link_prefix);
316
317 let local_prefix = format_ident!("{}__box_", ident);
318 let local_uninit = format_ident!("{}uninit", local_prefix);
319 let local_set_raw = format_ident!("{}set_raw", local_prefix);
320 let local_drop = format_ident!("{}drop", local_prefix);
321 let local_deref = format_ident!("{}deref", local_prefix);
322 let local_deref_mut = format_ident!("{}deref_mut", local_prefix);
323
324 let span = ident.span();
325 quote_spanned! {span=>
326 #[doc(hidden)]
327 #[export_name = #link_uninit]
328 unsafe extern "C" fn #local_uninit(
329 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
330 ) {
331 ::std::ptr::write(
332 this,
333 ::std::boxed::Box::new(::std::mem::MaybeUninit::uninit()),
334 );
335 }
336 #[doc(hidden)]
337 #[export_name = #link_set_raw]
338 unsafe extern "C" fn #local_set_raw(
339 this: *mut ::std::boxed::Box<#ident>,
340 raw: *mut #ident,
341 ) {
342 ::std::ptr::write(this, ::std::boxed::Box::from_raw(raw));
343 }
344 #[doc(hidden)]
345 #[export_name = #link_drop]
346 unsafe extern "C" fn #local_drop(this: *mut ::std::boxed::Box<#ident>) {
347 ::std::ptr::drop_in_place(this);
348 }
349 #[doc(hidden)]
350 #[export_name = #link_deref]
351 unsafe extern "C" fn #local_deref(
352 this: *const ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
353 ) -> *const ::std::mem::MaybeUninit<#ident> {
354 &**this
355 }
356 #[doc(hidden)]
357 #[export_name = #link_deref_mut]
358 unsafe extern "C" fn #local_deref_mut(
359 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
360 ) -> *mut ::std::mem::MaybeUninit<#ident> {
361 &mut **this
362 }
363 }
364}
365
366fn expand_unique_ptr(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnaye43b7372020-01-08 08:46:20 -0800367 let prefix = format!("cxxbridge01$unique_ptr${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400368 let link_null = format!("{}null", prefix);
369 let link_new = format!("{}new", prefix);
370 let link_raw = format!("{}raw", prefix);
371 let link_get = format!("{}get", prefix);
372 let link_release = format!("{}release", prefix);
373 let link_drop = format!("{}drop", prefix);
374
375 quote! {
376 unsafe impl ::cxx::private::UniquePtrTarget for #ident {
377 fn __null() -> *mut ::std::ffi::c_void {
378 extern "C" {
379 #[link_name = #link_null]
380 fn __null(this: *mut *mut ::std::ffi::c_void);
381 }
382 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
383 unsafe { __null(&mut repr) }
384 repr
385 }
386 fn __new(mut value: Self) -> *mut ::std::ffi::c_void {
387 extern "C" {
388 #[link_name = #link_new]
389 fn __new(this: *mut *mut ::std::ffi::c_void, value: *mut #ident);
390 }
391 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
392 unsafe { __new(&mut repr, &mut value) }
393 repr
394 }
395 unsafe fn __raw(raw: *mut Self) -> *mut ::std::ffi::c_void {
396 extern "C" {
397 #[link_name = #link_raw]
398 fn __raw(this: *mut *mut ::std::ffi::c_void, raw: *mut #ident);
399 }
400 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
401 __raw(&mut repr, raw);
402 repr
403 }
404 unsafe fn __get(repr: *mut ::std::ffi::c_void) -> *const Self {
405 extern "C" {
406 #[link_name = #link_get]
407 fn __get(this: *const *mut ::std::ffi::c_void) -> *const #ident;
408 }
409 __get(&repr)
410 }
411 unsafe fn __release(mut repr: *mut ::std::ffi::c_void) -> *mut Self {
412 extern "C" {
413 #[link_name = #link_release]
414 fn __release(this: *mut *mut ::std::ffi::c_void) -> *mut #ident;
415 }
416 __release(&mut repr)
417 }
418 unsafe fn __drop(mut repr: *mut ::std::ffi::c_void) {
419 extern "C" {
420 #[link_name = #link_drop]
421 fn __drop(this: *mut *mut ::std::ffi::c_void);
422 }
423 __drop(&mut repr);
424 }
425 }
426 }
427}
428
429fn expand_return_type(ret: &Option<Type>) -> TokenStream {
430 match ret {
431 Some(ret) => quote!(-> #ret),
432 None => TokenStream::new(),
433 }
434}
435
436fn indirect_return(ret: &Option<Type>, types: &Types) -> bool {
437 ret.as_ref()
438 .map_or(false, |ret| types.needs_indirect_abi(ret))
439}
440
441fn expand_extern_type(ty: &Type) -> TokenStream {
442 match ty {
David Tolnaya52602b2020-03-06 10:24:34 -0800443 Type::Ident(ident) if ident == RustString => quote!(::cxx::private::RustString),
David Tolnay7db73692019-10-20 14:51:12 -0400444 Type::RustBox(ty) | Type::UniquePtr(ty) => {
445 let inner = &ty.inner;
446 quote!(*mut #inner)
447 }
448 Type::Ref(ty) => match &ty.inner {
David Tolnaya52602b2020-03-06 10:24:34 -0800449 Type::Ident(ident) if ident == RustString => quote!(&::cxx::private::RustString),
David Tolnay7db73692019-10-20 14:51:12 -0400450 _ => quote!(#ty),
451 },
452 Type::Str(_) => quote!(::cxx::private::RustStr),
453 _ => quote!(#ty),
454 }
455}
456
457fn expand_extern_return_type(ret: &Option<Type>, types: &Types) -> TokenStream {
458 let ret = match ret {
459 Some(ret) if !types.needs_indirect_abi(ret) => ret,
460 _ => return TokenStream::new(),
461 };
462 let ty = expand_extern_type(ret);
463 quote!(-> #ty)
464}