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