blob: 1896a134395e029408f9b3ca1a2ee0c566e35d08 [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 let var = if types.needs_indirect_abi(&arg.ty) {
David Tolnay7db73692019-10-20 14:51:12 -0400237 quote!(::std::ptr::read(#ident))
238 } else {
239 quote!(#ident)
David Tolnay17955e22020-01-20 17:58:24 -0800240 };
241 match &arg.ty {
242 Type::Ident(ident) if ident == "String" => quote!(#var.into_string()),
243 Type::RustBox(_) => quote!(::std::boxed::Box::from_raw(#var)),
244 Type::UniquePtr(_) => quote!(::cxx::UniquePtr::from_raw(#var)),
245 Type::Ref(ty) => match &ty.inner {
246 Type::Ident(ident) if ident == "String" => quote!(#var.as_string()),
247 _ => var,
248 },
249 Type::Str(_) => quote!(#var.as_str()),
250 _ => var,
David Tolnay7db73692019-10-20 14:51:12 -0400251 }
252 });
253 let mut outparam = None;
254 let call = quote! {
255 ::cxx::private::catch_unwind(__fn, move || super::#ident(#(#vars),*))
256 };
257 let mut expr = efn
258 .ret
259 .as_ref()
260 .and_then(|ret| match ret {
261 Type::Ident(ident) if ident == "String" => {
262 Some(quote!(::cxx::private::RustString::from(#call)))
263 }
264 Type::RustBox(_) => Some(quote!(::std::boxed::Box::into_raw(#call))),
265 Type::UniquePtr(_) => Some(quote!(::cxx::UniquePtr::into_raw(#call))),
266 Type::Ref(ty) => match &ty.inner {
267 Type::Ident(ident) if ident == "String" => {
268 Some(quote!(::cxx::private::RustString::from_ref(#call)))
269 }
270 _ => None,
271 },
272 Type::Str(_) => Some(quote!(::cxx::private::RustStr::from(#call))),
273 _ => None,
274 })
275 .unwrap_or(call);
276 if indirect_return(&efn.ret, types) {
277 let ret = expand_extern_type(efn.ret.as_ref().unwrap());
278 outparam = Some(quote!(__return: *mut #ret));
279 expr = quote!(::std::ptr::write(__return, #expr));
280 }
281 let ret = expand_extern_return_type(&efn.ret, types);
David Tolnaye43b7372020-01-08 08:46:20 -0800282 let link_name = format!("{}cxxbridge01${}", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400283 let local_name = format_ident!("__{}", ident);
284 let catch_unwind_label = format!("::{}", ident);
285 quote! {
286 #[doc(hidden)]
287 #[export_name = #link_name]
288 unsafe extern "C" fn #local_name(#(#args,)* #outparam) #ret {
289 let __fn = concat!(module_path!(), #catch_unwind_label);
290 #expr
291 }
292 }
293}
294
295fn expand_rust_box(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnay9081beb2020-03-01 19:51:46 -0800296 let link_prefix = format!("cxxbridge01$box${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400297 let link_uninit = format!("{}uninit", link_prefix);
298 let link_set_raw = format!("{}set_raw", link_prefix);
299 let link_drop = format!("{}drop", link_prefix);
300 let link_deref = format!("{}deref", link_prefix);
301 let link_deref_mut = format!("{}deref_mut", link_prefix);
302
303 let local_prefix = format_ident!("{}__box_", ident);
304 let local_uninit = format_ident!("{}uninit", local_prefix);
305 let local_set_raw = format_ident!("{}set_raw", local_prefix);
306 let local_drop = format_ident!("{}drop", local_prefix);
307 let local_deref = format_ident!("{}deref", local_prefix);
308 let local_deref_mut = format_ident!("{}deref_mut", local_prefix);
309
310 let span = ident.span();
311 quote_spanned! {span=>
312 #[doc(hidden)]
313 #[export_name = #link_uninit]
314 unsafe extern "C" fn #local_uninit(
315 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
316 ) {
317 ::std::ptr::write(
318 this,
319 ::std::boxed::Box::new(::std::mem::MaybeUninit::uninit()),
320 );
321 }
322 #[doc(hidden)]
323 #[export_name = #link_set_raw]
324 unsafe extern "C" fn #local_set_raw(
325 this: *mut ::std::boxed::Box<#ident>,
326 raw: *mut #ident,
327 ) {
328 ::std::ptr::write(this, ::std::boxed::Box::from_raw(raw));
329 }
330 #[doc(hidden)]
331 #[export_name = #link_drop]
332 unsafe extern "C" fn #local_drop(this: *mut ::std::boxed::Box<#ident>) {
333 ::std::ptr::drop_in_place(this);
334 }
335 #[doc(hidden)]
336 #[export_name = #link_deref]
337 unsafe extern "C" fn #local_deref(
338 this: *const ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
339 ) -> *const ::std::mem::MaybeUninit<#ident> {
340 &**this
341 }
342 #[doc(hidden)]
343 #[export_name = #link_deref_mut]
344 unsafe extern "C" fn #local_deref_mut(
345 this: *mut ::std::boxed::Box<::std::mem::MaybeUninit<#ident>>,
346 ) -> *mut ::std::mem::MaybeUninit<#ident> {
347 &mut **this
348 }
349 }
350}
351
352fn expand_unique_ptr(namespace: &Namespace, ident: &Ident) -> TokenStream {
David Tolnaye43b7372020-01-08 08:46:20 -0800353 let prefix = format!("cxxbridge01$unique_ptr${}{}$", namespace, ident);
David Tolnay7db73692019-10-20 14:51:12 -0400354 let link_null = format!("{}null", prefix);
355 let link_new = format!("{}new", prefix);
356 let link_raw = format!("{}raw", prefix);
357 let link_get = format!("{}get", prefix);
358 let link_release = format!("{}release", prefix);
359 let link_drop = format!("{}drop", prefix);
360
361 quote! {
362 unsafe impl ::cxx::private::UniquePtrTarget for #ident {
363 fn __null() -> *mut ::std::ffi::c_void {
364 extern "C" {
365 #[link_name = #link_null]
366 fn __null(this: *mut *mut ::std::ffi::c_void);
367 }
368 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
369 unsafe { __null(&mut repr) }
370 repr
371 }
372 fn __new(mut value: Self) -> *mut ::std::ffi::c_void {
373 extern "C" {
374 #[link_name = #link_new]
375 fn __new(this: *mut *mut ::std::ffi::c_void, value: *mut #ident);
376 }
377 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
378 unsafe { __new(&mut repr, &mut value) }
379 repr
380 }
381 unsafe fn __raw(raw: *mut Self) -> *mut ::std::ffi::c_void {
382 extern "C" {
383 #[link_name = #link_raw]
384 fn __raw(this: *mut *mut ::std::ffi::c_void, raw: *mut #ident);
385 }
386 let mut repr = ::std::ptr::null_mut::<::std::ffi::c_void>();
387 __raw(&mut repr, raw);
388 repr
389 }
390 unsafe fn __get(repr: *mut ::std::ffi::c_void) -> *const Self {
391 extern "C" {
392 #[link_name = #link_get]
393 fn __get(this: *const *mut ::std::ffi::c_void) -> *const #ident;
394 }
395 __get(&repr)
396 }
397 unsafe fn __release(mut repr: *mut ::std::ffi::c_void) -> *mut Self {
398 extern "C" {
399 #[link_name = #link_release]
400 fn __release(this: *mut *mut ::std::ffi::c_void) -> *mut #ident;
401 }
402 __release(&mut repr)
403 }
404 unsafe fn __drop(mut repr: *mut ::std::ffi::c_void) {
405 extern "C" {
406 #[link_name = #link_drop]
407 fn __drop(this: *mut *mut ::std::ffi::c_void);
408 }
409 __drop(&mut repr);
410 }
411 }
412 }
413}
414
415fn expand_return_type(ret: &Option<Type>) -> TokenStream {
416 match ret {
417 Some(ret) => quote!(-> #ret),
418 None => TokenStream::new(),
419 }
420}
421
422fn indirect_return(ret: &Option<Type>, types: &Types) -> bool {
423 ret.as_ref()
424 .map_or(false, |ret| types.needs_indirect_abi(ret))
425}
426
427fn expand_extern_type(ty: &Type) -> TokenStream {
428 match ty {
429 Type::Ident(ident) if ident == "String" => quote!(::cxx::private::RustString),
430 Type::RustBox(ty) | Type::UniquePtr(ty) => {
431 let inner = &ty.inner;
432 quote!(*mut #inner)
433 }
434 Type::Ref(ty) => match &ty.inner {
435 Type::Ident(ident) if ident == "String" => quote!(&::cxx::private::RustString),
436 _ => quote!(#ty),
437 },
438 Type::Str(_) => quote!(::cxx::private::RustStr),
439 _ => quote!(#ty),
440 }
441}
442
443fn expand_extern_return_type(ret: &Option<Type>, types: &Types) -> TokenStream {
444 let ret = match ret {
445 Some(ret) if !types.needs_indirect_abi(ret) => ret,
446 _ => return TokenStream::new(),
447 };
448 let ty = expand_extern_type(ret);
449 quote!(-> #ty)
450}
451
452fn expand_extern_arg(arg: &Var, types: &Types) -> TokenStream {
453 let ident = &arg.ident;
454 let ty = expand_extern_type(&arg.ty);
455 if types.needs_indirect_abi(&arg.ty) {
456 quote!(#ident: *mut #ty)
457 } else {
458 quote!(#ident: #ty)
459 }
460}