blob: ac10b78deb2c25ec9513b6b308d50bfe12e92317 [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 {
26 hidden.extend(quote!(const fn __assert_sized<T>() {}));
27 has_rust_type = true;
28 }
29 let ident = &ety.ident;
30 hidden.extend(quote!(__assert_sized::<#ident>();));
31 }
32 }
33
34 for api in &apis {
35 match api {
36 Api::Include(_) | Api::RustType(_) => {}
37 Api::Struct(strct) => expanded.extend(expand_struct(strct)),
38 Api::CxxType(ety) => expanded.extend(expand_cxx_type(ety)),
39 Api::CxxFunction(efn) => {
40 expanded.extend(expand_cxx_function_shim(namespace, efn, types));
41 }
42 Api::RustFunction(efn) => {
43 hidden.extend(expand_rust_function_shim(namespace, efn, types))
44 }
45 }
46 }
47
48 for ty in types {
49 if let Type::RustBox(ty) = ty {
50 if let Type::Ident(ident) = &ty.inner {
51 if Atom::from(ident).is_none() {
52 hidden.extend(expand_rust_box(namespace, ident));
53 }
54 }
55 } else if let Type::UniquePtr(ptr) = ty {
56 if let Type::Ident(ident) = &ptr.inner {
57 if Atom::from(ident).is_none() {
58 expanded.extend(expand_unique_ptr(namespace, ident));
59 }
60 }
61 }
62 }
63
64 // Work around https://github.com/rust-lang/rust/issues/67851.
65 if !hidden.is_empty() {
66 expanded.extend(quote! {
67 #[doc(hidden)]
68 const _: () = {
69 #hidden
70 };
71 });
72 }
73
74 let attrs = ffi
75 .attrs
76 .into_iter()
77 .filter(|attr| attr.path.is_ident("doc"));
78 let vis = &ffi.vis;
79
80 Ok(quote! {
81 #(#attrs)*
82 #[deny(improper_ctypes)]
83 #[allow(non_snake_case)]
84 #vis mod #ident {
85 #expanded
86 }
87 })
88}
89
90fn expand_struct(strct: &Struct) -> TokenStream {
91 let ident = &strct.ident;
92 let doc = &strct.doc;
93 let derives = &strct.derives;
94 let fields = strct.fields.iter().map(|field| {
95 // This span on the pub makes "private type in public interface" errors
96 // appear in the right place.
97 let vis = Token![pub](field.ident.span());
98 quote!(#vis #field)
99 });
100 quote! {
101 #doc
102 #[derive(#(#derives),*)]
103 #[repr(C)]
104 pub struct #ident {
105 #(#fields,)*
106 }
107 }
108}
109
110fn expand_cxx_type(ety: &ExternType) -> TokenStream {
111 let ident = &ety.ident;
112 let doc = &ety.doc;
113 quote! {
114 #doc
115 #[repr(C)]
116 pub struct #ident {
117 _private: ::cxx::private::Opaque,
118 }
119 }
120}
121
122fn expand_cxx_function_decl(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
123 let ident = &efn.ident;
124 let args = efn.args.iter().map(|arg| expand_extern_arg(arg, types));
125 let ret = expand_extern_return_type(&efn.ret, types);
126 let mut outparam = None;
127 if indirect_return(&efn.ret, types) {
128 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
129 outparam = Some(quote!(__return: *mut #ret));
130 }
David Tolnaye43b7372020-01-08 08:46:20 -0800131 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400132 let local_name = format_ident!("__{}", ident);
133 quote! {
134 #[link_name = #link_name]
135 fn #local_name(#(#args,)* #outparam) #ret;
136 }
137}
138
139fn expand_cxx_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
140 let ident = &efn.ident;
141 let doc = &efn.doc;
142 let decl = expand_cxx_function_decl(namespace, efn, types);
143 let args = &efn.args;
144 let ret = expand_return_type(&efn.ret);
145 let indirect_return = indirect_return(&efn.ret, types);
146 let vars = efn.args.iter().map(|arg| {
147 let var = &arg.ident;
148 match &arg.ty {
149 Type::Ident(ident) if ident == "String" => {
150 quote!(#var.as_mut_ptr() as *mut ::cxx::private::RustString)
151 }
152 Type::RustBox(_) => quote!(::std::boxed::Box::into_raw(#var)),
153 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::into_raw(#var)),
154 Type::Ref(ty) => match &ty.inner {
155 Type::Ident(ident) if ident == "String" => {
156 quote!(::cxx::private::RustString::from_ref(#var))
157 }
158 _ => quote!(#var),
159 },
160 Type::Str(_) => quote!(::cxx::private::RustStr::from(#var)),
161 ty if types.needs_indirect_abi(ty) => quote!(#var.as_mut_ptr()),
162 _ => quote!(#var),
163 }
164 });
165 let mut setup = efn
166 .args
167 .iter()
168 .filter(|arg| types.needs_indirect_abi(&arg.ty))
169 .map(|arg| {
170 let var = &arg.ident;
171 // These are arguments for which C++ has taken ownership of the data
172 // behind the mut reference it received.
173 quote! {
174 let mut #var = std::mem::MaybeUninit::new(#var);
175 }
176 })
177 .collect::<TokenStream>();
178 let local_name = format_ident!("__{}", ident);
179 let call = if indirect_return {
180 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
181 setup.extend(quote! {
182 let mut __return = ::std::mem::MaybeUninit::<#ret>::uninit();
183 #local_name(#(#vars,)* __return.as_mut_ptr());
184 });
185 quote! {
186 __return.assume_init()
187 }
188 } else {
189 quote! {
190 #local_name(#(#vars),*)
191 }
192 };
193 let expr = efn
194 .ret
195 .as_ref()
196 .and_then(|ret| match ret {
197 Type::Ident(ident) if ident == "String" => Some(quote!(#call.into_string())),
198 Type::RustBox(_) => Some(quote!(::std::boxed::Box::from_raw(#call))),
199 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::from_raw(#call))),
200 Type::Ref(ty) => match &ty.inner {
201 Type::Ident(ident) if ident == "String" => Some(quote!(#call.as_string())),
202 _ => None,
203 },
204 Type::Str(_) => Some(quote!(#call.as_str())),
205 _ => None,
206 })
207 .unwrap_or(call);
208 quote! {
209 #doc
210 pub fn #ident(#(#args),*) #ret {
211 extern "C" {
212 #decl
213 }
214 unsafe {
215 #setup
216 #expr
217 }
218 }
219 }
220}
221
222fn expand_rust_type(ety: &ExternType) -> TokenStream {
223 let ident = &ety.ident;
224 quote! {
225 use super::#ident;
226 }
227}
228
229fn expand_rust_function_shim(namespace: &Namespace, efn: &ExternFn, types: &Types) -> TokenStream {
230 let ident = &efn.ident;
231 let args = efn.args.iter().map(|arg| expand_extern_arg(arg, types));
232 let vars = efn.args.iter().map(|arg| {
233 let ident = &arg.ident;
David Tolnay17955e22020-01-20 17:58:24 -0800234 let var = if types.needs_indirect_abi(&arg.ty) {
David Tolnay7db73692019-10-20 14:51:12 -0400235 quote!(::std::ptr::read(#ident))
236 } else {
237 quote!(#ident)
David Tolnay17955e22020-01-20 17:58:24 -0800238 };
239 match &arg.ty {
240 Type::Ident(ident) if ident == "String" => quote!(#var.into_string()),
241 Type::RustBox(_) => quote!(::std::boxed::Box::from_raw(#var)),
242 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::from_raw(#var)),
243 Type::Ref(ty) => match &ty.inner {
244 Type::Ident(ident) if ident == "String" => quote!(#var.as_string()),
245 _ => var,
246 },
247 Type::Str(_) => quote!(#var.as_str()),
248 _ => var,
David Tolnay7db73692019-10-20 14:51:12 -0400249 }
250 });
251 let mut outparam = None;
252 let call = quote! {
253 ::cxx::private::catch_unwind(__fn, move || super::#ident(#(#vars),*))
254 };
255 let mut expr = efn
256 .ret
257 .as_ref()
258 .and_then(|ret| match ret {
259 Type::Ident(ident) if ident == "String" => {
260 Some(quote!(::cxx::private::RustString::from(#call)))
261 }
262 Type::RustBox(_) => Some(quote!(::std::boxed::Box::into_raw(#call))),
263 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::into_raw(#call))),
264 Type::Ref(ty) => match &ty.inner {
265 Type::Ident(ident) if ident == "String" => {
266 Some(quote!(::cxx::private::RustString::from_ref(#call)))
267 }
268 _ => None,
269 },
270 Type::Str(_) => Some(quote!(::cxx::private::RustStr::from(#call))),
271 _ => None,
272 })
273 .unwrap_or(call);
274 if indirect_return(&efn.ret, types) {
275 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
276 outparam = Some(quote!(__return: *mut #ret));
277 expr = quote!(::std::ptr::write(__return, #expr));
278 }
279 let ret = expand_extern_return_type(&efn.ret, types);
David Tolnaye43b7372020-01-08 08:46:20 -0800280 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400281 let local_name = format_ident!("__{}", ident);
282 let catch_unwind_label = format!("::{}", ident);
283 quote! {
284 #[doc(hidden)]
285 #[export_name = #link_name]
286 unsafe extern "C" fn #local_name(#(#args,)* #outparam) #ret {
287 let __fn = concat!(module_path!(), #catch_unwind_label);
288 #expr
289 }
290 }
291}
292
293fn expand_rust_box(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnaye43b7372020-01-08 08:46:20 -0800294 let link_prefix = format!("cxxbridge01$rust_box${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400295 let link_uninit = format!("{}uninit", link_prefix);
296 let link_set_raw = format!("{}set_raw", link_prefix);
297 let link_drop = format!("{}drop", link_prefix);
298 let link_deref = format!("{}deref", link_prefix);
299 let link_deref_mut = format!("{}deref_mut", link_prefix);
300
301 let local_prefix = format_ident!("{}__box_", ident);
302 let local_uninit = format_ident!("{}uninit", local_prefix);
303 let local_set_raw = format_ident!("{}set_raw", local_prefix);
304 let local_drop = format_ident!("{}drop", local_prefix);
305 let local_deref = format_ident!("{}deref", local_prefix);
306 let local_deref_mut = format_ident!("{}deref_mut", local_prefix);
307
308 let span = ident.span();
309 quote_spanned! {span=>
310 #[doc(hidden)]
311 #[export_name = #link_uninit]
312 unsafe extern "C" fn #local_uninit(
313 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
314 ) {
315 ::std::ptr::write(
316 this,
317 ::std::boxed::Box::new(::std::mem::MaybeUninit::uninit()),
318 );
319 }
320 #[doc(hidden)]
321 #[export_name = #link_set_raw]
322 unsafe extern "C" fn #local_set_raw(
323 this: *mut ::std::boxed::Box<#ident>,
324 raw: *mut #ident,
325 ) {
326 ::std::ptr::write(this, ::std::boxed::Box::from_raw(raw));
327 }
328 #[doc(hidden)]
329 #[export_name = #link_drop]
330 unsafe extern "C" fn #local_drop(this: *mut ::std::boxed::Box<#ident>) {
331 ::std::ptr::drop_in_place(this);
332 }
333 #[doc(hidden)]
334 #[export_name = #link_deref]
335 unsafe extern "C" fn #local_deref(
336 this: *const ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
337 ) -> *const ::std::mem::MaybeUninit<#ident> {
338 &**this
339 }
340 #[doc(hidden)]
341 #[export_name = #link_deref_mut]
342 unsafe extern "C" fn #local_deref_mut(
343 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
344 ) -> *mut ::std::mem::MaybeUninit<#ident> {
345 &mut **this
346 }
347 }
348}
349
350fn expand_unique_ptr(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnaye43b7372020-01-08 08:46:20 -0800351 let prefix = format!("cxxbridge01$unique_ptr${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400352 let link_null = format!("{}null", prefix);
353 let link_new = format!("{}new", prefix);
354 let link_raw = format!("{}raw", prefix);
355 let link_get = format!("{}get", prefix);
356 let link_release = format!("{}release", prefix);
357 let link_drop = format!("{}drop", prefix);
358
359 quote! {
360 unsafe impl ::cxx::private::UniquePtrTarget for #ident {
361 fn __null() -> *mut ::std::ffi::c_void {
362 extern "C" {
363 #[link_name = #link_null]
364 fn __null(this: *mut *mut ::std::ffi::c_void);
365 }
366 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
367 unsafe { __null(&mut repr) }
368 repr
369 }
370 fn __new(mut value: Self) -> *mut ::std::ffi::c_void {
371 extern "C" {
372 #[link_name = #link_new]
373 fn __new(this: *mut *mut ::std::ffi::c_void, value: *mut #ident);
374 }
375 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
376 unsafe { __new(&mut repr, &mut value) }
377 repr
378 }
379 unsafe fn __raw(raw: *mut Self) -> *mut ::std::ffi::c_void {
380 extern "C" {
381 #[link_name = #link_raw]
382 fn __raw(this: *mut *mut ::std::ffi::c_void, raw: *mut #ident);
383 }
384 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
385 __raw(&mut repr, raw);
386 repr
387 }
388 unsafe fn __get(repr: *mut ::std::ffi::c_void) -> *const Self {
389 extern "C" {
390 #[link_name = #link_get]
391 fn __get(this: *const *mut ::std::ffi::c_void) -> *const #ident;
392 }
393 __get(&repr)
394 }
395 unsafe fn __release(mut repr: *mut ::std::ffi::c_void) -> *mut Self {
396 extern "C" {
397 #[link_name = #link_release]
398 fn __release(this: *mut *mut ::std::ffi::c_void) -> *mut #ident;
399 }
400 __release(&mut repr)
401 }
402 unsafe fn __drop(mut repr: *mut ::std::ffi::c_void) {
403 extern "C" {
404 #[link_name = #link_drop]
405 fn __drop(this: *mut *mut ::std::ffi::c_void);
406 }
407 __drop(&mut repr);
408 }
409 }
410 }
411}
412
413fn expand_return_type(ret: &Option<Type>) -> TokenStream {
414 match ret {
415 Some(ret) => quote!(-> #ret),
416 None => TokenStream::new(),
417 }
418}
419
420fn indirect_return(ret: &Option<Type>, types: &Types) -> bool {
421 ret.as_ref()
422 .map_or(false, |ret| types.needs_indirect_abi(ret))
423}
424
425fn expand_extern_type(ty: &Type) -> TokenStream {
426 match ty {
427 Type::Ident(ident) if ident == "String" => quote!(::cxx::private::RustString),
428 Type::RustBox(ty) | Type::UniquePtr(ty) => {
429 let inner = &ty.inner;
430 quote!(*mut #inner)
431 }
432 Type::Ref(ty) => match &ty.inner {
433 Type::Ident(ident) if ident == "String" => quote!(&::cxx::private::RustString),
434 _ => quote!(#ty),
435 },
436 Type::Str(_) => quote!(::cxx::private::RustStr),
437 _ => quote!(#ty),
438 }
439}
440
441fn expand_extern_return_type(ret: &Option<Type>, types: &Types) -> TokenStream {
442 let ret = match ret {
443 Some(ret) if !types.needs_indirect_abi(ret) => ret,
444 _ => return TokenStream::new(),
445 };
446 let ty = expand_extern_type(ret);
447 quote!(-> #ty)
448}
449
450fn expand_extern_arg(arg: &Var, types: &Types) -> TokenStream {
451 let ident = &arg.ident;
452 let ty = expand_extern_type(&arg.ty);
453 if types.needs_indirect_abi(&arg.ty) {
454 quote!(#ident: *mut #ty)
455 } else {
456 quote!(#ident: #ty)
457 }
458}