blob: 16dab26b0b7c129866e7d5df0f3849ee02ca1868 [file] [log] [blame]
David Tolnay7db73692019-10-20 14:51:12 -04001use crate::namespace::Namespace;
2use crate::syntax::atom::Atom;
3use crate::syntax::{self, check, Api, ExternFn, ExternType, Struct, Type, Types, Var};
4use 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;
126 let args = efn.args.iter().map(|arg| expand_extern_arg(arg, types));
127 let ret = expand_extern_return_type(&efn.ret, types);
128 let mut outparam = None;
129 if indirect_return(&efn.ret, types) {
130 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
131 outparam = Some(quote!(__return: *mut #ret));
132 }
David Tolnaye43b7372020-01-08 08:46:20 -0800133 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400134 let local_name = format_ident!("__{}", ident);
135 quote! {
136 #[link_name = #link_name]
137 fn #local_name(#(#args,)* #outparam) #ret;
138 }
139}
140
141fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
142 let ident = &efn.ident;
143 let doc = &efn.doc;
144 let decl = expand_cxx_function_decl(namespace, efn, types);
145 let args = &efn.args;
146 let ret = expand_return_type(&efn.ret);
147 let indirect_return = indirect_return(&efn.ret, types);
148 let vars = efn.args.iter().map(|arg| {
149 let var = &arg.ident;
150 match &arg.ty {
151 Type::Ident(ident) if ident == "String" => {
152 quote!(#var.as_mut_ptr() as *mut ::cxx::private::RustString)
153 }
154 Type::RustBox(_) => quote!(::std::boxed::Box::into_raw(#var)),
155 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::into_raw(#var)),
156 Type::Ref(ty) => match &ty.inner {
157 Type::Ident(ident) if ident == "String" => {
158 quote!(::cxx::private::RustString::from_ref(#var))
159 }
160 _ => quote!(#var),
161 },
162 Type::Str(_) => quote!(::cxx::private::RustStr::from(#var)),
163 ty if types.needs_indirect_abi(ty) => quote!(#var.as_mut_ptr()),
164 _ => quote!(#var),
165 }
166 });
167 let mut setup = efn
168 .args
169 .iter()
170 .filter(|arg| types.needs_indirect_abi(&arg.ty))
171 .map(|arg| {
172 let var = &arg.ident;
173 // These are arguments for which C++ has taken ownership of the data
174 // behind the mut reference it received.
175 quote! {
176 let mut #var = std::mem::MaybeUninit::new(#var);
177 }
178 })
179 .collect::<TokenStream>();
180 let local_name = format_ident!("__{}", ident);
181 let call = if indirect_return {
182 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
183 setup.extend(quote! {
184 let mut __return = ::std::mem::MaybeUninit::<#ret>::uninit();
185 #local_name(#(#vars,)* __return.as_mut_ptr());
186 });
187 quote! {
188 __return.assume_init()
189 }
190 } else {
191 quote! {
192 #local_name(#(#vars),*)
193 }
194 };
195 let expr = efn
196 .ret
197 .as_ref()
198 .and_then(|ret| match ret {
199 Type::Ident(ident) if ident == "String" => Some(quote!(#call.into_string())),
200 Type::RustBox(_) => Some(quote!(::std::boxed::Box::from_raw(#call))),
201 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::from_raw(#call))),
202 Type::Ref(ty) => match &ty.inner {
203 Type::Ident(ident) if ident == "String" => Some(quote!(#call.as_string())),
204 _ => None,
205 },
206 Type::Str(_) => Some(quote!(#call.as_str())),
207 _ => None,
208 })
209 .unwrap_or(call);
210 quote! {
211 #doc
212 pub fn #ident(#(#args),*) #ret {
213 extern "C" {
214 #decl
215 }
216 unsafe {
217 #setup
218 #expr
219 }
220 }
221 }
222}
223
224fn expand_rust_type(ety: &ExternType) -> TokenStream {
225 let ident = &ety.ident;
226 quote! {
227 use super::#ident;
228 }
229}
230
231fn expand_rust_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
232 let ident = &efn.ident;
233 let args = efn.args.iter().map(|arg| expand_extern_arg(arg, types));
234 let vars = efn.args.iter().map(|arg| {
235 let ident = &arg.ident;
David Tolnay17955e22020-01-20 17:58:24 -0800236 match &arg.ty {
David Tolnay40226ab2020-03-03 00:05:35 -0800237 Type::Ident(i) if i == "String" => quote!(::std::mem::take((*#ident).as_mut_string())),
238 Type::RustBox(_) => quote!(::std::boxed::Box::from_raw(#ident)),
239 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::from_raw(#ident)),
David Tolnay17955e22020-01-20 17:58:24 -0800240 Type::Ref(ty) => match &ty.inner {
David Tolnay40226ab2020-03-03 00:05:35 -0800241 Type::Ident(i) if i == "String" => quote!(#ident.as_string()),
242 _ => quote!(#ident),
David Tolnay17955e22020-01-20 17:58:24 -0800243 },
David Tolnay40226ab2020-03-03 00:05:35 -0800244 Type::Str(_) => quote!(#ident.as_str()),
245 ty if types.needs_indirect_abi(ty) => quote!(::std::ptr::read(#ident)),
246 _ => quote!(#ident),
David Tolnay7db73692019-10-20 14:51:12 -0400247 }
248 });
249 let mut outparam = None;
250 let call = quote! {
251 ::cxx::private::catch_unwind(__fn, move || super::#ident(#(#vars),*))
252 };
253 let mut expr = efn
254 .ret
255 .as_ref()
256 .and_then(|ret| match ret {
257 Type::Ident(ident) if ident == "String" => {
258 Some(quote!(::cxx::private::RustString::from(#call)))
259 }
260 Type::RustBox(_) => Some(quote!(::std::boxed::Box::into_raw(#call))),
261 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::into_raw(#call))),
262 Type::Ref(ty) => match &ty.inner {
263 Type::Ident(ident) if ident == "String" => {
264 Some(quote!(::cxx::private::RustString::from_ref(#call)))
265 }
266 _ => None,
267 },
268 Type::Str(_) => Some(quote!(::cxx::private::RustStr::from(#call))),
269 _ => None,
270 })
271 .unwrap_or(call);
272 if indirect_return(&efn.ret, types) {
273 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
274 outparam = Some(quote!(__return: *mut #ret));
275 expr = quote!(::std::ptr::write(__return, #expr));
276 }
277 let ret = expand_extern_return_type(&efn.ret, types);
David Tolnaye43b7372020-01-08 08:46:20 -0800278 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400279 let local_name = format_ident!("__{}", ident);
280 let catch_unwind_label = format!("::{}", ident);
281 quote! {
282 #[doc(hidden)]
283 #[export_name = #link_name]
284 unsafe extern "C" fn #local_name(#(#args,)* #outparam) #ret {
285 let __fn = concat!(module_path!(), #catch_unwind_label);
286 #expr
287 }
288 }
289}
290
291fn expand_rust_box(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnay9081beb2020-03-01 19:51:46 -0800292 let link_prefix = format!("cxxbridge01$box${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400293 let link_uninit = format!("{}uninit", link_prefix);
294 let link_set_raw = format!("{}set_raw", link_prefix);
295 let link_drop = format!("{}drop", link_prefix);
296 let link_deref = format!("{}deref", link_prefix);
297 let link_deref_mut = format!("{}deref_mut", link_prefix);
298
299 let local_prefix = format_ident!("{}__box_", ident);
300 let local_uninit = format_ident!("{}uninit", local_prefix);
301 let local_set_raw = format_ident!("{}set_raw", local_prefix);
302 let local_drop = format_ident!("{}drop", local_prefix);
303 let local_deref = format_ident!("{}deref", local_prefix);
304 let local_deref_mut = format_ident!("{}deref_mut", local_prefix);
305
306 let span = ident.span();
307 quote_spanned! {span=>
308 #[doc(hidden)]
309 #[export_name = #link_uninit]
310 unsafe extern "C" fn #local_uninit(
311 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
312 ) {
313 ::std::ptr::write(
314 this,
315 ::std::boxed::Box::new(::std::mem::MaybeUninit::uninit()),
316 );
317 }
318 #[doc(hidden)]
319 #[export_name = #link_set_raw]
320 unsafe extern "C" fn #local_set_raw(
321 this: *mut ::std::boxed::Box<#ident>,
322 raw: *mut #ident,
323 ) {
324 ::std::ptr::write(this, ::std::boxed::Box::from_raw(raw));
325 }
326 #[doc(hidden)]
327 #[export_name = #link_drop]
328 unsafe extern "C" fn #local_drop(this: *mut ::std::boxed::Box<#ident>) {
329 ::std::ptr::drop_in_place(this);
330 }
331 #[doc(hidden)]
332 #[export_name = #link_deref]
333 unsafe extern "C" fn #local_deref(
334 this: *const ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
335 ) -> *const ::std::mem::MaybeUninit<#ident> {
336 &**this
337 }
338 #[doc(hidden)]
339 #[export_name = #link_deref_mut]
340 unsafe extern "C" fn #local_deref_mut(
341 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
342 ) -> *mut ::std::mem::MaybeUninit<#ident> {
343 &mut **this
344 }
345 }
346}
347
348fn expand_unique_ptr(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnaye43b7372020-01-08 08:46:20 -0800349 let prefix = format!("cxxbridge01$unique_ptr${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400350 let link_null = format!("{}null", prefix);
351 let link_new = format!("{}new", prefix);
352 let link_raw = format!("{}raw", prefix);
353 let link_get = format!("{}get", prefix);
354 let link_release = format!("{}release", prefix);
355 let link_drop = format!("{}drop", prefix);
356
357 quote! {
358 unsafe impl ::cxx::private::UniquePtrTarget for #ident {
359 fn __null() -> *mut ::std::ffi::c_void {
360 extern "C" {
361 #[link_name = #link_null]
362 fn __null(this: *mut *mut ::std::ffi::c_void);
363 }
364 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
365 unsafe { __null(&mut repr) }
366 repr
367 }
368 fn __new(mut value: Self) -> *mut ::std::ffi::c_void {
369 extern "C" {
370 #[link_name = #link_new]
371 fn __new(this: *mut *mut ::std::ffi::c_void, value: *mut #ident);
372 }
373 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
374 unsafe { __new(&mut repr, &mut value) }
375 repr
376 }
377 unsafe fn __raw(raw: *mut Self) -> *mut ::std::ffi::c_void {
378 extern "C" {
379 #[link_name = #link_raw]
380 fn __raw(this: *mut *mut ::std::ffi::c_void, raw: *mut #ident);
381 }
382 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
383 __raw(&mut repr, raw);
384 repr
385 }
386 unsafe fn __get(repr: *mut ::std::ffi::c_void) -> *const Self {
387 extern "C" {
388 #[link_name = #link_get]
389 fn __get(this: *const *mut ::std::ffi::c_void) -> *const #ident;
390 }
391 __get(&repr)
392 }
393 unsafe fn __release(mut repr: *mut ::std::ffi::c_void) -> *mut Self {
394 extern "C" {
395 #[link_name = #link_release]
396 fn __release(this: *mut *mut ::std::ffi::c_void) -> *mut #ident;
397 }
398 __release(&mut repr)
399 }
400 unsafe fn __drop(mut repr: *mut ::std::ffi::c_void) {
401 extern "C" {
402 #[link_name = #link_drop]
403 fn __drop(this: *mut *mut ::std::ffi::c_void);
404 }
405 __drop(&mut repr);
406 }
407 }
408 }
409}
410
411fn expand_return_type(ret: &Option<Type>) -> TokenStream {
412 match ret {
413 Some(ret) => quote!(-> #ret),
414 None => TokenStream::new(),
415 }
416}
417
418fn indirect_return(ret: &Option<Type>, types: &Types) -> bool {
419 ret.as_ref()
420 .map_or(false, |ret| types.needs_indirect_abi(ret))
421}
422
423fn expand_extern_type(ty: &Type) -> TokenStream {
424 match ty {
425 Type::Ident(ident) if ident == "String" => quote!(::cxx::private::RustString),
426 Type::RustBox(ty) | Type::UniquePtr(ty) => {
427 let inner = &ty.inner;
428 quote!(*mut #inner)
429 }
430 Type::Ref(ty) => match &ty.inner {
431 Type::Ident(ident) if ident == "String" => quote!(&::cxx::private::RustString),
432 _ => quote!(#ty),
433 },
434 Type::Str(_) => quote!(::cxx::private::RustStr),
435 _ => quote!(#ty),
436 }
437}
438
439fn expand_extern_return_type(ret: &Option<Type>, types: &Types) -> TokenStream {
440 let ret = match ret {
441 Some(ret) if !types.needs_indirect_abi(ret) => ret,
442 _ => return TokenStream::new(),
443 };
444 let ty = expand_extern_type(ret);
445 quote!(-> #ty)
446}
447
448fn expand_extern_arg(arg: &Var, types: &Types) -> TokenStream {
449 let ident = &arg.ident;
450 let ty = expand_extern_type(&arg.ty);
451 if types.needs_indirect_abi(&arg.ty) {
452 quote!(#ident: *mut #ty)
453 } else {
454 quote!(#ident: #ty)
455 }
456}