blob: 6bf53655a526e2f96cb1918ae0900d9f326acad8 [file] [log] [blame]
Marcel Hlopko42abfc82021-08-09 07:03:17 +00001// Part of the Crubit project, under the Apache License v2.0 with LLVM
2// Exceptions. See /LICENSE for license information.
3// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
4
Lukasz Anforowiczaab8ad22021-12-19 20:29:26 +00005use anyhow::{anyhow, bail, Result};
Marcel Hlopko884ae7f2021-08-18 13:58:22 +00006use ffi_types::*;
Marcel Hlopko42abfc82021-08-09 07:03:17 +00007use ir::*;
8use itertools::Itertools;
Googler5ea88642021-09-29 08:05:59 +00009use proc_macro2::{Ident, Literal, TokenStream};
Marcel Hlopko42abfc82021-08-09 07:03:17 +000010use quote::format_ident;
11use quote::quote;
Googler7cced422021-12-06 11:58:39 +000012use std::collections::{BTreeSet, HashMap};
Marcel Hlopko42abfc82021-08-09 07:03:17 +000013use std::iter::Iterator;
14use std::panic::catch_unwind;
15use std::process;
Marcel Hlopko65d05f02021-12-09 12:29:24 +000016use token_stream_printer::{rs_tokens_to_formatted_string, tokens_to_string};
Marcel Hlopko42abfc82021-08-09 07:03:17 +000017
Marcel Hlopko45fba972021-08-23 19:52:20 +000018/// FFI equivalent of `Bindings`.
19#[repr(C)]
20pub struct FfiBindings {
21 rs_api: FfiU8SliceBox,
22 rs_api_impl: FfiU8SliceBox,
23}
24
25/// Deserializes IR from `json` and generates bindings source code.
Marcel Hlopko42abfc82021-08-09 07:03:17 +000026///
27/// This function panics on error.
28///
29/// Ownership:
Michael Forsterbee84482021-10-13 08:35:38 +000030/// * function doesn't take ownership of (in other words it borrows) the
31/// param `json`
Marcel Hlopko42abfc82021-08-09 07:03:17 +000032/// * function passes ownership of the returned value to the caller
33///
34/// Safety:
Michael Forsterbee84482021-10-13 08:35:38 +000035/// * function expects that param `json` is a FfiU8Slice for a valid array of
36/// bytes with the given size.
Marcel Hlopko42abfc82021-08-09 07:03:17 +000037/// * function expects that param `json` doesn't change during the call.
38#[no_mangle]
Marcel Hlopko45fba972021-08-23 19:52:20 +000039pub unsafe extern "C" fn GenerateBindingsImpl(json: FfiU8Slice) -> FfiBindings {
Marcel Hlopko42abfc82021-08-09 07:03:17 +000040 catch_unwind(|| {
Marcel Hlopko45fba972021-08-23 19:52:20 +000041 // It is ok to abort here.
42 let Bindings { rs_api, rs_api_impl } = generate_bindings(json.as_slice()).unwrap();
43
44 FfiBindings {
45 rs_api: FfiU8SliceBox::from_boxed_slice(rs_api.into_bytes().into_boxed_slice()),
46 rs_api_impl: FfiU8SliceBox::from_boxed_slice(
47 rs_api_impl.into_bytes().into_boxed_slice(),
48 ),
49 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +000050 })
51 .unwrap_or_else(|_| process::abort())
52}
53
Marcel Hlopko45fba972021-08-23 19:52:20 +000054/// Source code for generated bindings.
55struct Bindings {
56 // Rust source code.
57 rs_api: String,
58 // C++ source code.
59 rs_api_impl: String,
Marcel Hlopko42abfc82021-08-09 07:03:17 +000060}
61
Marcel Hlopko45fba972021-08-23 19:52:20 +000062fn generate_bindings(json: &[u8]) -> Result<Bindings> {
63 let ir = deserialize_ir(json)?;
Marcel Hlopkoca84ff42021-12-09 14:15:14 +000064
65 // The code is formatted with a non-default rustfmt configuration. Prevent
66 // downstream workflows from reformatting with a different configuration.
Marcel Hlopko89547752021-12-10 09:39:41 +000067 let rs_api =
68 format!("#![rustfmt::skip]\n{}", rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?);
69 let rs_api_impl = tokens_to_string(generate_rs_api_impl(&ir)?)?;
Marcel Hlopkoca84ff42021-12-09 14:15:14 +000070
Marcel Hlopko45fba972021-08-23 19:52:20 +000071 Ok(Bindings { rs_api, rs_api_impl })
72}
73
Devin Jeanpierre6d5e7cc2021-10-21 12:56:07 +000074/// Rust source code with attached information about how to modify the parent
75/// crate.
Devin Jeanpierre273eeae2021-10-06 13:29:35 +000076///
Michael Forsterbee84482021-10-13 08:35:38 +000077/// For example, the snippet `vec![].into_raw_parts()` is not valid unless the
78/// `vec_into_raw_parts` feature is enabled. So such a snippet should be
79/// represented as:
Devin Jeanpierre273eeae2021-10-06 13:29:35 +000080///
81/// ```
82/// RsSnippet {
Devin Jeanpierre6d5e7cc2021-10-21 12:56:07 +000083/// features: btree_set![make_ident("vec_into_raw_parts")],
Devin Jeanpierre273eeae2021-10-06 13:29:35 +000084/// tokens: quote!{vec![].into_raw_parts()},
85/// }
86/// ```
87struct RsSnippet {
88 /// Rust feature flags used by this snippet.
89 features: BTreeSet<Ident>,
90 /// The snippet itself, as a token stream.
91 tokens: TokenStream,
92}
93
94impl From<TokenStream> for RsSnippet {
95 fn from(tokens: TokenStream) -> Self {
96 RsSnippet { features: BTreeSet::new(), tokens }
97 }
98}
99
Michael Forsterbee84482021-10-13 08:35:38 +0000100/// If we know the original C++ function is codegenned and already compatible
101/// with `extern "C"` calling convention we skip creating/calling the C++ thunk
102/// since we can call the original C++ directly.
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000103fn can_skip_cc_thunk(func: &Func) -> bool {
Devin Jeanpierre96839c12021-12-14 00:27:38 +0000104 // ## Inline functions
105 //
Michael Forsterbee84482021-10-13 08:35:38 +0000106 // Inline functions may not be codegenned in the C++ library since Clang doesn't
107 // know if Rust calls the function or not. Therefore in order to make inline
108 // functions callable from Rust we need to generate a C++ file that defines
109 // a thunk that delegates to the original inline function. When compiled,
110 // Clang will emit code for this thunk and Rust code will call the
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000111 // thunk when the user wants to call the original inline function.
112 //
Michael Forsterbee84482021-10-13 08:35:38 +0000113 // This is not great runtime-performance-wise in regular builds (inline function
114 // will not be inlined, there will always be a function call), but it is
115 // correct. ThinLTO builds will be able to see through the thunk and inline
116 // code across the language boundary. For non-ThinLTO builds we plan to
117 // implement <internal link> which removes the runtime performance overhead.
Devin Jeanpierre96839c12021-12-14 00:27:38 +0000118 if func.is_inline {
119 return false;
120 }
121 // ## Virtual functions
122 //
123 // When calling virtual `A::Method()`, it's not necessarily the case that we'll
124 // specifically call the concrete `A::Method` impl. For example, if this is
125 // called on something whose dynamic type is some subclass `B` with an
126 // overridden `B::Method`, then we'll call that.
127 //
128 // We must reuse the C++ dynamic dispatching system. In this case, the easiest
129 // way to do it is by resorting to a C++ thunk, whose implementation will do
130 // the lookup.
131 //
132 // In terms of runtime performance, since this only occurs for virtual function
133 // calls, which are already slow, it may not be such a big deal. We can
134 // benchmark it later. :)
135 if let Some(meta) = &func.member_func_metadata {
136 if let Some(inst_meta) = &meta.instance_method_metadata {
137 if inst_meta.is_virtual {
138 return false;
139 }
140 }
141 }
142
143 true
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000144}
145
Michael Forstered642022021-10-04 09:48:25 +0000146/// Generates Rust source code for a given `Func`.
147///
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000148/// Returns the generated function or trait impl, and the thunk, as a tuple.
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000149fn generate_func(func: &Func, ir: &IR) -> Result<(RsSnippet, RsSnippet)> {
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +0000150 let empty_result = Ok((quote! {}.into(), quote! {}.into()));
Michael Forstered642022021-10-04 09:48:25 +0000151 let mangled_name = &func.mangled_name;
Googlera675ae02021-12-07 08:04:59 +0000152 let thunk_ident = thunk_ident(func);
Michael Forster409d9412021-10-07 08:35:29 +0000153 let doc_comment = generate_doc_comment(&func.doc_comment);
Googler7cced422021-12-06 11:58:39 +0000154 let lifetime_to_name = HashMap::<LifetimeId, String>::from_iter(
155 func.lifetime_params.iter().map(|l| (l.id, l.name.clone())),
156 );
Lukasz Anforowicz4ad012b2021-12-15 18:13:40 +0000157 let return_type_fragment = if func.return_type.rs_type.is_unit_type() {
158 quote! {}
159 } else {
160 let return_type_name = format_rs_type(&func.return_type.rs_type, ir, &lifetime_to_name)?;
161 quote! { -> #return_type_name }
162 };
Michael Forstered642022021-10-04 09:48:25 +0000163
164 let param_idents =
165 func.params.iter().map(|p| make_ident(&p.identifier.identifier)).collect_vec();
166
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000167 let param_types = func
168 .params
169 .iter()
Googler7cced422021-12-06 11:58:39 +0000170 .map(|p| format_rs_type(&p.type_.rs_type, ir, &lifetime_to_name))
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000171 .collect::<Result<Vec<_>>>()?;
Michael Forstered642022021-10-04 09:48:25 +0000172
Googler7cced422021-12-06 11:58:39 +0000173 let lifetimes = func
174 .lifetime_params
175 .iter()
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +0000176 .map(|l| syn::Lifetime::new(&format!("'{}", l.name), proc_macro2::Span::call_site()));
177 let generic_params = format_generic_params(lifetimes);
Googler7cced422021-12-06 11:58:39 +0000178
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000179 let record: Option<&Record> =
180 func.member_func_metadata.as_ref().map(|meta| meta.find_record(ir)).transpose()?;
181
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000182 let mut calls_thunk = true;
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000183 let api_func = match &func.name {
184 UnqualifiedIdentifier::Identifier(id) => {
185 let ident = make_ident(&id.identifier);
Lukasz Anforowiczee7669e2021-12-15 17:04:36 +0000186 let fn_def = quote! {
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000187 #doc_comment
188 #[inline(always)]
Lukasz Anforowicz4ad012b2021-12-15 18:13:40 +0000189 pub fn #ident #generic_params( #( #param_idents: #param_types ),*
190 ) #return_type_fragment {
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000191 unsafe { crate::detail::#thunk_ident( #( #param_idents ),* ) }
192 }
Lukasz Anforowiczee7669e2021-12-15 17:04:36 +0000193 };
Lukasz Anforowiczaab8ad22021-12-19 20:29:26 +0000194 match &func.member_func_metadata {
Lukasz Anforowiczee7669e2021-12-15 17:04:36 +0000195 None => fn_def,
Lukasz Anforowiczaab8ad22021-12-19 20:29:26 +0000196 Some(meta) => {
197 let type_name = make_ident(&meta.find_record(ir)?.identifier.identifier);
Lukasz Anforowiczee7669e2021-12-15 17:04:36 +0000198 quote! { impl #type_name { #fn_def } }
199 }
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000200 }
Michael Forstered642022021-10-04 09:48:25 +0000201 }
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000202
203 UnqualifiedIdentifier::Destructor => {
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000204 let record = record.ok_or_else(|| anyhow!("Destructors must be member functions."))?;
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000205 let type_name = make_ident(&record.identifier.identifier);
206 match record.destructor.definition {
207 // TODO(b/202258760): Only omit destructor if `Copy` is specified.
208 SpecialMemberDefinition::Trivial => {
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +0000209 return empty_result;
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000210 }
211 SpecialMemberDefinition::NontrivialMembers => {
212 calls_thunk = false;
213 quote! {
214 #doc_comment
215 impl Drop for #type_name {
216 #[inline(always)]
217 fn drop(&mut self) {
218 /* the destructors of the members can be invoked instead */
219 }
220 }
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000221 }
222 }
Devin Jeanpierre7b62e952021-12-08 21:43:30 +0000223 SpecialMemberDefinition::NontrivialUserDefined => {
Devin Jeanpierref61ba6f2021-12-17 08:57:45 +0000224 // Note: to avoid double-destruction of the fields, they are all wrapped in
225 // ManuallyDrop in this case. See `generate_record`.
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000226 quote! {
227 #doc_comment
228 impl Drop for #type_name {
229 #[inline(always)]
230 fn drop(&mut self) {
231 unsafe { crate::detail::#thunk_ident(self) }
232 }
233 }
234 }
235 }
236 SpecialMemberDefinition::Deleted => {
237 bail!("Deleted destructors can't be called") // TODO(b/200066399): handle this?
238 }
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000239 }
240 }
241
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000242 UnqualifiedIdentifier::Constructor => {
243 let record = record.ok_or_else(|| anyhow!("Constructors must be member functions."))?;
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +0000244 if !record.is_trivial_abi {
245 return empty_result;
246 }
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000247 let type_name = make_ident(&record.identifier.identifier);
248 match func.params.len() {
249 0 => bail!("Constructor should have at least 1 parameter (__this)"),
250 1 => quote! {
251 #doc_comment
252 impl Default for #type_name {
253 #[inline(always)]
254 fn default() -> Self {
255 let mut tmp = std::mem::MaybeUninit::<Self>::uninit();
256 unsafe {
257 crate::detail::#thunk_ident(tmp.as_mut_ptr());
258 tmp.assume_init()
259 }
260 }
261 }
262 },
263 _ => {
264 // TODO(b/208946210): Map some of these constructors to the From trait.
265 // TODO(b/200066396): Map other constructors (to the Clone trait?).
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +0000266 return empty_result;
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000267 }
268 }
269 }
Michael Forstered642022021-10-04 09:48:25 +0000270 };
271
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000272 let thunk = if calls_thunk {
273 let thunk_attr = if can_skip_cc_thunk(func) {
274 quote! {#[link_name = #mangled_name]}
275 } else {
276 quote! {}
277 };
278
279 quote! {
280 #thunk_attr
Lukasz Anforowicz4ad012b2021-12-15 18:13:40 +0000281 pub(crate) fn #thunk_ident #generic_params( #( #param_idents: #param_types ),*
282 ) #return_type_fragment ;
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000283 }
Michael Forstered642022021-10-04 09:48:25 +0000284 } else {
285 quote! {}
286 };
287
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000288 Ok((api_func.into(), thunk.into()))
Michael Forstered642022021-10-04 09:48:25 +0000289}
290
Michael Forstercc5941a2021-10-07 07:12:24 +0000291fn generate_doc_comment(comment: &Option<String>) -> TokenStream {
292 match comment {
Michael Forster028800b2021-10-05 12:39:59 +0000293 Some(text) => {
Marcel Hlopko89547752021-12-10 09:39:41 +0000294 // token_stream_printer (and rustfmt) don't put a space between /// and the doc
295 // comment, let's add it here so our comments are pretty.
Michael Forster028800b2021-10-05 12:39:59 +0000296 let doc = format!(" {}", text.replace("\n", "\n "));
297 quote! {#[doc=#doc]}
298 }
299 None => quote! {},
Michael Forstercc5941a2021-10-07 07:12:24 +0000300 }
301}
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +0000302
303fn format_generic_params<T: quote::ToTokens>(params: impl IntoIterator<Item = T>) -> TokenStream {
304 let mut params = params.into_iter().peekable();
305 if params.peek().is_none() {
306 quote! {}
307 } else {
308 quote! { < #( #params ),* > }
309 }
310}
311
Michael Forsterbee84482021-10-13 08:35:38 +0000312/// Generates Rust source code for a given `Record` and associated assertions as
313/// a tuple.
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000314fn generate_record(record: &Record, ir: &IR) -> Result<(RsSnippet, RsSnippet)> {
Michael Forstercc5941a2021-10-07 07:12:24 +0000315 let ident = make_ident(&record.identifier.identifier);
316 let doc_comment = generate_doc_comment(&record.doc_comment);
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000317 let field_idents =
318 record.fields.iter().map(|f| make_ident(&f.identifier.identifier)).collect_vec();
Michael Forstercc5941a2021-10-07 07:12:24 +0000319 let field_doc_coments =
320 record.fields.iter().map(|f| generate_doc_comment(&f.doc_comment)).collect_vec();
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000321 let field_types = record
322 .fields
323 .iter()
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000324 .map(|f| {
Googler7cced422021-12-06 11:58:39 +0000325 let mut formatted = format_rs_type(&f.type_.rs_type, ir, &HashMap::new())?;
Devin Jeanpierre7b62e952021-12-08 21:43:30 +0000326 if record.destructor.definition == SpecialMemberDefinition::NontrivialUserDefined {
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000327 formatted = quote! {
328 std::mem::ManuallyDrop<#formatted>
329 };
330 }
331 Ok(formatted)
332 })
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000333 .collect::<Result<Vec<_>>>()?;
Googlerec589eb2021-09-17 07:45:39 +0000334 let field_accesses = record
335 .fields
336 .iter()
337 .map(|f| {
338 if f.access == AccessSpecifier::Public {
339 quote! { pub }
340 } else {
341 quote! {}
342 }
343 })
344 .collect_vec();
Googlerec648ff2021-09-23 07:19:53 +0000345 let size = record.size;
346 let alignment = record.alignment;
Googleraaa0a532021-10-01 09:11:27 +0000347 let field_assertions =
348 record.fields.iter().zip(field_idents.iter()).map(|(field, field_ident)| {
349 let offset = field.offset;
350 quote! {
351 // The IR contains the offset in bits, while offset_of!()
352 // returns the offset in bytes, so we need to convert.
Googler209b10a2021-12-06 09:11:57 +0000353 const _: () = assert!(offset_of!(#ident, #field_ident) * 8 == #offset);
Googleraaa0a532021-10-01 09:11:27 +0000354 }
355 });
Michael Forsterdb8101a2021-10-08 06:56:03 +0000356 let mut record_features = BTreeSet::new();
357 let mut assertion_features = BTreeSet::new();
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000358
359 // TODO(mboehme): For the time being, we're using unstable features to
360 // be able to use offset_of!() in static assertions. This is fine for a
361 // prototype, but longer-term we want to either get those features
362 // stabilized or find an alternative. For more details, see
363 // b/200120034#comment15
Michael Forsterdb8101a2021-10-08 06:56:03 +0000364 assertion_features.insert(make_ident("const_ptr_offset_from"));
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000365
366 let derives = generate_copy_derives(record);
Devin Jeanpierre9227d2c2021-10-06 12:26:05 +0000367 let derives = if derives.is_empty() {
368 quote! {}
369 } else {
370 quote! {#[derive( #(#derives),* )]}
371 };
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000372 let unpin_impl;
Devin Jeanpierree6e16652021-12-22 15:54:46 +0000373 if record.is_unpin() {
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000374 unpin_impl = quote! {};
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000375 } else {
Michael Forsterbee84482021-10-13 08:35:38 +0000376 // negative_impls are necessary for universal initialization due to Rust's
377 // coherence rules: PhantomPinned isn't enough to prove to Rust that a
378 // blanket impl that requires Unpin doesn't apply. See http://<internal link>=h.f6jp8ifzgt3n
Michael Forsterdb8101a2021-10-08 06:56:03 +0000379 record_features.insert(make_ident("negative_impls"));
380 unpin_impl = quote! {
381 __NEWLINE__ __NEWLINE__
382 impl !Unpin for #ident {}
383 };
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000384 }
385
Googlerf4792062021-10-20 07:21:21 +0000386 let empty_struct_placeholder_field = if record.fields.is_empty() {
387 quote! {
388 /// Prevent empty C++ struct being zero-size in Rust.
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000389 placeholder: std::mem::MaybeUninit<u8>,
Googlerf4792062021-10-20 07:21:21 +0000390 }
391 } else {
392 quote! {}
393 };
394
Michael Forsterdb8101a2021-10-08 06:56:03 +0000395 let record_tokens = quote! {
Michael Forster028800b2021-10-05 12:39:59 +0000396 #doc_comment
Devin Jeanpierre9227d2c2021-10-06 12:26:05 +0000397 #derives
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000398 #[repr(C)]
399 pub struct #ident {
Michael Forstercc5941a2021-10-07 07:12:24 +0000400 #( #field_doc_coments #field_accesses #field_idents: #field_types, )*
Googlerf4792062021-10-20 07:21:21 +0000401 #empty_struct_placeholder_field
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000402 }
Googlerec648ff2021-09-23 07:19:53 +0000403
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000404 #unpin_impl
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000405 };
406
Michael Forsterdb8101a2021-10-08 06:56:03 +0000407 let assertion_tokens = quote! {
Googler209b10a2021-12-06 09:11:57 +0000408 const _: () = assert!(std::mem::size_of::<#ident>() == #size);
409 const _: () = assert!(std::mem::align_of::<#ident>() == #alignment);
Michael Forsterdb8101a2021-10-08 06:56:03 +0000410 #( #field_assertions )*
411 };
412
413 Ok((
414 RsSnippet { features: record_features, tokens: record_tokens },
415 RsSnippet { features: assertion_features, tokens: assertion_tokens },
416 ))
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000417}
418
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000419fn generate_copy_derives(record: &Record) -> Vec<Ident> {
420 if record.is_trivial_abi
421 && record.copy_constructor.access == ir::AccessSpecifier::Public
422 && record.copy_constructor.definition == SpecialMemberDefinition::Trivial
423 {
424 // TODO(b/202258760): Make `Copy` inclusion configurable.
425 vec![make_ident("Clone"), make_ident("Copy")]
426 } else {
427 vec![]
428 }
429}
430
Michael Forster523dbd42021-10-12 11:05:44 +0000431/// Generates Rust source code for a given `UnsupportedItem`.
432fn generate_unsupported(item: &UnsupportedItem) -> Result<TokenStream> {
Googler48a74dd2021-10-25 07:31:53 +0000433 let location = if item.source_loc.filename.is_empty() {
434 "<unknown location>".to_string()
435 } else {
436 // TODO(forster): The "google3" prefix should probably come from a command line
437 // argument.
438 // TODO(forster): Consider linking to the symbol instead of to the line number
439 // to avoid wrong links while generated files have not caught up.
440 format!("google3/{};l={}", &item.source_loc.filename, &item.source_loc.line)
441 };
Michael Forster6a184ad2021-10-12 13:04:05 +0000442 let message = format!(
Googler48a74dd2021-10-25 07:31:53 +0000443 "{}\nError while generating bindings for item '{}':\n{}",
444 &location, &item.name, &item.message
Michael Forster6a184ad2021-10-12 13:04:05 +0000445 );
Michael Forster523dbd42021-10-12 11:05:44 +0000446 Ok(quote! { __COMMENT__ #message })
447}
448
Michael Forsterf1dce422021-10-13 09:50:16 +0000449/// Generates Rust source code for a given `Comment`.
450fn generate_comment(comment: &Comment) -> Result<TokenStream> {
451 let text = &comment.text;
452 Ok(quote! { __COMMENT__ #text })
453}
454
Marcel Hlopko89547752021-12-10 09:39:41 +0000455fn generate_rs_api(ir: &IR) -> Result<TokenStream> {
Michael Forstered642022021-10-04 09:48:25 +0000456 let mut items = vec![];
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000457 let mut thunks = vec![];
Michael Forsterdb8101a2021-10-08 06:56:03 +0000458 let mut assertions = vec![];
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000459
Googler454f2652021-12-06 12:53:12 +0000460 // We import nullable pointers as an Option<&T> and assume that at the ABI
461 // level, None is represented as a zero pointer value whereas Some is
462 // represented as as non-zero pointer value. This seems like a pretty safe
463 // assumption to make, but to provide some safeguard, assert that
464 // `Option<&i32>` and `&i32` have the same size.
465 assertions.push(quote! {
466 const _: () = assert!(std::mem::size_of::<Option<&i32>>() == std::mem::size_of::<&i32>());
467 });
468
Michael Forsterbee84482021-10-13 08:35:38 +0000469 // TODO(jeanpierreda): Delete has_record, either in favor of using RsSnippet, or not
470 // having uses. See https://chat.google.com/room/AAAAnQmj8Qs/6QbkSvWcfhA
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000471 let mut has_record = false;
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000472 let mut features = BTreeSet::new();
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000473
Devin Jeanpierred6da7002021-10-21 12:55:20 +0000474 // For #![rustfmt::skip].
475 features.insert(make_ident("custom_inner_attributes"));
476
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +0000477 for item in ir.items() {
Michael Forstered642022021-10-04 09:48:25 +0000478 match item {
479 Item::Func(func) => {
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000480 let (snippet, thunk) = generate_func(func, ir)?;
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000481 features.extend(snippet.features);
482 features.extend(thunk.features);
483 items.push(snippet.tokens);
484 thunks.push(thunk.tokens);
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000485 }
Michael Forstered642022021-10-04 09:48:25 +0000486 Item::Record(record) => {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000487 if !ir.is_in_current_target(record) {
488 continue;
489 }
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000490 let (snippet, assertions_snippet) = generate_record(record, ir)?;
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000491 features.extend(snippet.features);
Michael Forsterdb8101a2021-10-08 06:56:03 +0000492 features.extend(assertions_snippet.features);
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000493 items.push(snippet.tokens);
Michael Forsterdb8101a2021-10-08 06:56:03 +0000494 assertions.push(assertions_snippet.tokens);
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000495 has_record = true;
Michael Forstered642022021-10-04 09:48:25 +0000496 }
Michael Forster523dbd42021-10-12 11:05:44 +0000497 Item::UnsupportedItem(unsupported) => items.push(generate_unsupported(unsupported)?),
Michael Forsterf1dce422021-10-13 09:50:16 +0000498 Item::Comment(comment) => items.push(generate_comment(comment)?),
Michael Forstered642022021-10-04 09:48:25 +0000499 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000500 }
501
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000502 let mod_detail = if thunks.is_empty() {
503 quote! {}
504 } else {
505 quote! {
506 mod detail {
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +0000507 use super::*;
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000508 extern "C" {
509 #( #thunks )*
510 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000511 }
512 }
513 };
514
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000515 let imports = if has_record {
Googlerec648ff2021-09-23 07:19:53 +0000516 quote! {
Googleraaa0a532021-10-01 09:11:27 +0000517 use memoffset_unstable_const::offset_of;
Googlerec648ff2021-09-23 07:19:53 +0000518 }
Michael Forstered642022021-10-04 09:48:25 +0000519 } else {
520 quote! {}
Googlerec648ff2021-09-23 07:19:53 +0000521 };
522
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000523 let features = if features.is_empty() {
524 quote! {}
525 } else {
526 quote! {
527 #![feature( #(#features),* )]
528 }
529 };
530
Marcel Hlopko89547752021-12-10 09:39:41 +0000531 Ok(quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +0000532 #features __NEWLINE__ __NEWLINE__
533 #imports __NEWLINE__ __NEWLINE__
Googlerec648ff2021-09-23 07:19:53 +0000534
Michael Forsterdb8101a2021-10-08 06:56:03 +0000535 #( #items __NEWLINE__ __NEWLINE__ )*
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000536
Michael Forsterdb8101a2021-10-08 06:56:03 +0000537 #mod_detail __NEWLINE__ __NEWLINE__
538
539 #( #assertions __NEWLINE__ __NEWLINE__ )*
Marcel Hlopko89547752021-12-10 09:39:41 +0000540 })
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000541}
542
543fn make_ident(ident: &str) -> Ident {
544 format_ident!("{}", ident)
545}
546
Googler7cced422021-12-06 11:58:39 +0000547fn format_rs_type(
548 ty: &ir::RsType,
549 ir: &IR,
550 lifetime_to_name: &HashMap<LifetimeId, String>,
551) -> Result<TokenStream> {
Googlerb0365ce2021-12-02 09:09:04 +0000552 enum TypeKind<'a> {
553 Pointer(TokenStream),
Googler7cced422021-12-06 11:58:39 +0000554 Reference(TokenStream),
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000555 Record(TokenStream),
Googlerb0365ce2021-12-02 09:09:04 +0000556 Unit,
557 Other(&'a str),
558 }
559 let kind = if let Some(ref name) = ty.name {
560 match name.as_str() {
561 "*mut" => TypeKind::Pointer(quote! {mut}),
562 "*const" => TypeKind::Pointer(quote! {const}),
Googler7cced422021-12-06 11:58:39 +0000563 "&mut" => TypeKind::Reference(quote! {mut}),
564 "&" => TypeKind::Reference(quote! {}),
Googlerb0365ce2021-12-02 09:09:04 +0000565 "()" => TypeKind::Unit,
566 _ => TypeKind::Other(name),
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000567 }
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000568 } else {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000569 let record = ir.record_for_type(ty)?;
570 let ident = make_ident(record.identifier.identifier.as_str());
571 let path: TokenStream = if ir.is_in_current_target(record) {
572 quote! {#ident}
573 } else {
574 let owning_crate = make_ident(record.owning_crate_name()?);
575 quote! {#owning_crate::#ident}
576 };
577 TypeKind::Record(path)
Googlerb0365ce2021-12-02 09:09:04 +0000578 };
579 match kind {
580 TypeKind::Pointer(mutability) => {
Googlerff7fc232021-12-02 09:43:00 +0000581 if ty.type_args.len() != 1 {
582 bail!("Invalid pointer type (need exactly 1 type argument): {:?}", ty);
Googlerb0365ce2021-12-02 09:09:04 +0000583 }
Googler7cced422021-12-06 11:58:39 +0000584 let nested_type = format_rs_type(&ty.type_args[0], ir, lifetime_to_name)?;
Googlerb0365ce2021-12-02 09:09:04 +0000585 Ok(quote! {* #mutability #nested_type})
586 }
Googler7cced422021-12-06 11:58:39 +0000587 TypeKind::Reference(mutability) => {
588 if ty.lifetime_args.len() != 1 || ty.type_args.len() != 1 {
589 bail!(
590 "Invalid reference type (need exactly 1 lifetime argument and 1 type argument): {:?}",
591 ty
592 );
593 }
594 let nested_type = format_rs_type(&ty.type_args[0], ir, lifetime_to_name)?;
595 let lifetime_id = &ty.lifetime_args[0];
596 let lifetime = syn::Lifetime::new(
597 &format!("'{}", lifetime_to_name.get(lifetime_id).unwrap()),
598 proc_macro2::Span::call_site(),
599 );
600 Ok(quote! {& #lifetime #mutability #nested_type})
601 }
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000602 TypeKind::Record(path) => {
Googlerff7fc232021-12-02 09:43:00 +0000603 if !ty.type_args.is_empty() {
604 bail!("Type arguments on records are not yet supported: {:?}", ty);
Googlerb0365ce2021-12-02 09:09:04 +0000605 }
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000606 Ok(path)
Googlerb0365ce2021-12-02 09:09:04 +0000607 }
608 TypeKind::Unit => {
Googlerff7fc232021-12-02 09:43:00 +0000609 if !ty.type_args.is_empty() {
610 bail!("Unit type must not have type arguments: {:?}", ty);
Googlerb0365ce2021-12-02 09:09:04 +0000611 }
612 Ok(quote! {()})
613 }
614 TypeKind::Other(name) => {
Googlerb0365ce2021-12-02 09:09:04 +0000615 let ident = make_ident(name);
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +0000616 let type_args = format_generic_params(
617 ty.type_args
618 .iter()
619 .map(|type_arg| format_rs_type(type_arg, ir, lifetime_to_name))
620 .collect::<Result<Vec<_>>>()?,
621 );
Googler454f2652021-12-06 12:53:12 +0000622 Ok(quote! {#ident #type_args})
Googlerb0365ce2021-12-02 09:09:04 +0000623 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000624 }
625}
626
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000627fn format_cc_type(ty: &ir::CcType, ir: &IR) -> Result<TokenStream> {
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000628 let const_fragment = if ty.is_const {
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +0000629 quote! {const}
630 } else {
631 quote! {}
632 };
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000633 if let Some(ref name) = ty.name {
634 match name.as_str() {
635 "*" => {
Googlerff7fc232021-12-02 09:43:00 +0000636 if ty.type_args.len() != 1 {
637 bail!("Invalid pointer type (need exactly 1 type argument): {:?}", ty);
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000638 }
Googlerff7fc232021-12-02 09:43:00 +0000639 assert_eq!(ty.type_args.len(), 1);
640 let nested_type = format_cc_type(&ty.type_args[0], ir)?;
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000641 Ok(quote! {#nested_type * #const_fragment})
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000642 }
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000643 ident => {
Googlerff7fc232021-12-02 09:43:00 +0000644 if !ty.type_args.is_empty() {
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000645 bail!("Type not yet supported: {:?}", ty);
646 }
647 let ident = make_ident(ident);
648 Ok(quote! {#ident #const_fragment})
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000649 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000650 }
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000651 } else {
652 let ident = make_ident(ir.record_for_type(ty)?.identifier.identifier.as_str());
653 Ok(quote! {#ident})
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000654 }
655}
656
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000657fn cc_struct_layout_assertion(record: &Record, ir: &IR) -> TokenStream {
658 if !ir.is_in_current_target(record) {
659 return quote! {};
660 }
Googler5ea88642021-09-29 08:05:59 +0000661 let record_ident = make_ident(&record.identifier.identifier);
662 let size = Literal::usize_unsuffixed(record.size);
663 let alignment = Literal::usize_unsuffixed(record.alignment);
Lukasz Anforowicz74704712021-12-22 15:30:31 +0000664 let field_assertions =
665 record.fields.iter().filter(|f| f.access == AccessSpecifier::Public).map(|field| {
666 let field_ident = make_ident(&field.identifier.identifier);
667 let offset = Literal::usize_unsuffixed(field.offset);
668 // The IR contains the offset in bits, while C++'s offsetof()
669 // returns the offset in bytes, so we need to convert.
670 quote! {
671 static_assert(offsetof(#record_ident, #field_ident) * 8 == #offset);
672 }
673 });
Googler5ea88642021-09-29 08:05:59 +0000674 quote! {
675 static_assert(sizeof(#record_ident) == #size);
676 static_assert(alignof(#record_ident) == #alignment);
677 #( #field_assertions )*
678 }
679}
680
Googlera675ae02021-12-07 08:04:59 +0000681fn thunk_ident(func: &Func) -> Ident {
682 format_ident!("__rust_thunk__{}", func.mangled_name)
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000683}
684
Marcel Hlopko89547752021-12-10 09:39:41 +0000685fn generate_rs_api_impl(ir: &IR) -> Result<TokenStream> {
Michael Forsterbee84482021-10-13 08:35:38 +0000686 // This function uses quote! to generate C++ source code out of convenience.
687 // This is a bold idea so we have to continously evaluate if it still makes
688 // sense or the cost of working around differences in Rust and C++ tokens is
689 // greather than the value added.
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000690 //
Michael Forsterbee84482021-10-13 08:35:38 +0000691 // See rs_bindings_from_cc/
692 // token_stream_printer.rs for a list of supported placeholders.
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000693 let mut thunks = vec![];
Michael Forster7ef80732021-10-01 18:12:19 +0000694 for func in ir.functions() {
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000695 if can_skip_cc_thunk(&func) {
696 continue;
697 }
698
Googlera675ae02021-12-07 08:04:59 +0000699 let thunk_ident = thunk_ident(func);
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000700 let implementation_function = match &func.name {
701 UnqualifiedIdentifier::Identifier(id) => {
Lukasz Anforowiczaab8ad22021-12-19 20:29:26 +0000702 let fn_ident = make_ident(&id.identifier);
703 let static_method_metadata = func
704 .member_func_metadata
705 .as_ref()
706 .filter(|meta| meta.instance_method_metadata.is_none());
707 match static_method_metadata {
708 None => quote! {#fn_ident},
709 Some(meta) => {
710 let record_ident = make_ident(&meta.find_record(ir)?.identifier.identifier);
711 quote! { #record_ident :: #fn_ident }
712 }
713 }
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000714 }
Devin Jeanpierrecc6cf092021-12-16 04:31:14 +0000715 // Use destroy_at to avoid needing to spell out the class name. Destructor identiifers
716 // use the name of the type itself, without namespace qualification, template
717 // parameters, or aliases. We do not need to use that naming scheme anywhere else in
718 // the bindings, and it can be difficult (impossible?) to spell in the general case. By
719 // using destroy_at, we avoid needing to determine or remember what the correct spelling
720 // is.
Lukasz Anforowicze643ec92021-12-22 15:45:15 +0000721 UnqualifiedIdentifier::Constructor => {
722 if func.params.len() == 1 {
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +0000723 quote! { rs_api_impl_support::construct_at }
Lukasz Anforowicze643ec92021-12-22 15:45:15 +0000724 } else {
725 // TODO(b/208946210): Map some of these constructors to the From trait.
726 // TODO(b/200066396): Map other constructors (to the Clone trait?).
727 continue;
728 }
729 }
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000730 UnqualifiedIdentifier::Destructor => quote! {std::destroy_at},
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000731 };
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000732 let return_type_name = format_cc_type(&func.return_type.cc_type, ir)?;
Lukasz Anforowicze643ec92021-12-22 15:45:15 +0000733 let return_stmt = if func.return_type.cc_type.is_void() {
734 quote! {}
735 } else {
736 quote! { return }
737 };
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000738
739 let param_idents =
740 func.params.iter().map(|p| make_ident(&p.identifier.identifier)).collect_vec();
741
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000742 let param_types = func
743 .params
744 .iter()
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000745 .map(|p| format_cc_type(&p.type_.cc_type, ir))
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000746 .collect::<Result<Vec<_>>>()?;
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000747
748 thunks.push(quote! {
749 extern "C" #return_type_name #thunk_ident( #( #param_types #param_idents ),* ) {
Lukasz Anforowicze643ec92021-12-22 15:45:15 +0000750 #return_stmt #implementation_function( #( #param_idents ),* );
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000751 }
752 });
753 }
754
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000755 let layout_assertions = ir.records().map(|record| cc_struct_layout_assertion(record, ir));
Googler5ea88642021-09-29 08:05:59 +0000756
Devin Jeanpierre231ef8d2021-10-27 10:50:44 +0000757 let mut standard_headers = <BTreeSet<Ident>>::new();
758 standard_headers.insert(make_ident("memory")); // ubiquitous.
759 if ir.records().next().is_some() {
760 standard_headers.insert(make_ident("cstddef"));
761 };
Googler5ea88642021-09-29 08:05:59 +0000762
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +0000763 let mut includes =
764 vec!["rs_bindings_from_cc/support/cxx20_backports.h"];
765
Michael Forsterbee84482021-10-13 08:35:38 +0000766 // In order to generate C++ thunk in all the cases Clang needs to be able to
767 // access declarations from public headers of the C++ library.
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +0000768 includes.extend(ir.used_headers().map(|i| &i.name as &str));
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000769
Marcel Hlopko89547752021-12-10 09:39:41 +0000770 Ok(quote! {
Googler5ea88642021-09-29 08:05:59 +0000771 #( __HASH_TOKEN__ include <#standard_headers> __NEWLINE__)*
Michael Forsterdb8101a2021-10-08 06:56:03 +0000772 #( __HASH_TOKEN__ include #includes __NEWLINE__)* __NEWLINE__
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000773
Michael Forsterdb8101a2021-10-08 06:56:03 +0000774 #( #thunks )* __NEWLINE__ __NEWLINE__
Googler5ea88642021-09-29 08:05:59 +0000775
Michael Forsterdb8101a2021-10-08 06:56:03 +0000776 #( #layout_assertions __NEWLINE__ __NEWLINE__ )*
Marcel Hlopkoc6b726c2021-10-07 06:53:09 +0000777
778 // To satisfy http://cs/symbol:devtools.metadata.Presubmit.CheckTerminatingNewline check.
779 __NEWLINE__
Marcel Hlopko89547752021-12-10 09:39:41 +0000780 })
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000781}
782
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000783#[cfg(test)]
784mod tests {
Devin Jeanpierre45cb1162021-10-27 10:54:28 +0000785 use super::*;
Michael Forstered642022021-10-04 09:48:25 +0000786 use anyhow::anyhow;
Marcel Hlopko89547752021-12-10 09:39:41 +0000787 use ir_testing::{ir_from_cc, ir_from_cc_dependency, ir_func, ir_record};
788 use token_stream_matchers::{
789 assert_cc_matches, assert_cc_not_matches, assert_rs_matches, assert_rs_not_matches,
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000790 };
Michael Forsterdb8101a2021-10-08 06:56:03 +0000791 use token_stream_printer::tokens_to_string;
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000792
793 #[test]
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +0000794 // TODO(hlopko): Move this test to a more principled place where it can access
795 // `ir_testing`.
796 fn test_duplicate_decl_ids_err() {
797 let mut r1 = ir_record("R1");
Marcel Hlopko264b9ad2021-12-02 21:06:44 +0000798 r1.id = DeclId(42);
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +0000799 let mut r2 = ir_record("R2");
Marcel Hlopko264b9ad2021-12-02 21:06:44 +0000800 r2.id = DeclId(42);
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +0000801 let result = make_ir_from_items([r1.into(), r2.into()]);
802 assert!(result.is_err());
803 assert!(result.unwrap_err().to_string().contains("Duplicate decl_id found in"));
804 }
805
806 #[test]
Marcel Hlopko45fba972021-08-23 19:52:20 +0000807 fn test_simple_function() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +0000808 let ir = ir_from_cc("int Add(int a, int b);")?;
809 let rs_api = generate_rs_api(&ir)?;
810 assert_rs_matches!(
811 rs_api,
812 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +0000813 #[inline(always)]
Marcel Hlopko89547752021-12-10 09:39:41 +0000814 pub fn Add(a: i32, b: i32) -> i32 {
Googlera675ae02021-12-07 08:04:59 +0000815 unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) }
Marcel Hlopko89547752021-12-10 09:39:41 +0000816 }
817 }
818 );
819 assert_rs_matches!(
820 rs_api,
821 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +0000822 mod detail {
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +0000823 use super::*;
Michael Forsterdb8101a2021-10-08 06:56:03 +0000824 extern "C" {
825 #[link_name = "_Z3Addii"]
Googlera675ae02021-12-07 08:04:59 +0000826 pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32;
Marcel Hlopko89547752021-12-10 09:39:41 +0000827 }
828 }
829 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000830 );
Michael Forsterdb8101a2021-10-08 06:56:03 +0000831
Marcel Hlopko89547752021-12-10 09:39:41 +0000832 assert_cc_not_matches!(generate_rs_api_impl(&ir)?, quote! {__rust_thunk___Z3Addii});
Michael Forsterdb8101a2021-10-08 06:56:03 +0000833
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000834 Ok(())
835 }
836
837 #[test]
838 fn test_inline_function() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +0000839 let ir = ir_from_cc("inline int Add(int a, int b);")?;
840 let rs_api = generate_rs_api(&ir)?;
841 assert_rs_matches!(
842 rs_api,
843 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +0000844 #[inline(always)]
Marcel Hlopko89547752021-12-10 09:39:41 +0000845 pub fn Add(a: i32, b: i32) -> i32 {
Googlera675ae02021-12-07 08:04:59 +0000846 unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) }
Marcel Hlopko89547752021-12-10 09:39:41 +0000847 }
848 }
849 );
850 assert_rs_matches!(
851 rs_api,
852 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +0000853 mod detail {
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +0000854 use super::*;
Michael Forsterdb8101a2021-10-08 06:56:03 +0000855 extern "C" {
Googlera675ae02021-12-07 08:04:59 +0000856 pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32;
Marcel Hlopko89547752021-12-10 09:39:41 +0000857 }
858 }
859 }
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000860 );
861
Marcel Hlopko89547752021-12-10 09:39:41 +0000862 assert_cc_matches!(
863 generate_rs_api_impl(&ir)?,
864 quote! {
Googlera675ae02021-12-07 08:04:59 +0000865 extern "C" int __rust_thunk___Z3Addii(int a, int b) {
Marcel Hlopko89547752021-12-10 09:39:41 +0000866 return Add(a, b);
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000867 }
Marcel Hlopko89547752021-12-10 09:39:41 +0000868 }
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000869 );
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000870 Ok(())
871 }
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000872
873 #[test]
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000874 fn test_simple_function_with_types_from_other_target() -> Result<()> {
875 let ir = ir_from_cc_dependency(
876 "inline ReturnStruct DoSomething(ParamStruct param);",
877 "struct ReturnStruct {}; struct ParamStruct {};",
878 )?;
879
Marcel Hlopko89547752021-12-10 09:39:41 +0000880 let rs_api = generate_rs_api(&ir)?;
881 assert_rs_matches!(
882 rs_api,
883 quote! {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000884 #[inline(always)]
885 pub fn DoSomething(param: dependency::ParamStruct)
Marcel Hlopko89547752021-12-10 09:39:41 +0000886 -> dependency::ReturnStruct {
Googlera675ae02021-12-07 08:04:59 +0000887 unsafe { crate::detail::__rust_thunk___Z11DoSomething11ParamStruct(param) }
Marcel Hlopko89547752021-12-10 09:39:41 +0000888 }
889 }
890 );
891 assert_rs_matches!(
892 rs_api,
893 quote! {
894 mod detail {
895 use super::*;
896 extern "C" {
897 pub(crate) fn __rust_thunk___Z11DoSomething11ParamStruct(param: dependency::ParamStruct)
898 -> dependency::ReturnStruct;
899 }
900 }}
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000901 );
902
Marcel Hlopko89547752021-12-10 09:39:41 +0000903 assert_cc_matches!(
904 generate_rs_api_impl(&ir)?,
905 quote! {
Googlera675ae02021-12-07 08:04:59 +0000906 extern "C" ReturnStruct __rust_thunk___Z11DoSomething11ParamStruct(ParamStruct param) {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000907 return DoSomething(param);
908 }
Marcel Hlopko89547752021-12-10 09:39:41 +0000909 }
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000910 );
911 Ok(())
912 }
913
914 #[test]
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000915 fn test_simple_struct() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +0000916 let ir = ir_from_cc(&tokens_to_string(quote! {
917 struct SomeStruct {
918 int public_int;
919 protected:
920 int protected_int;
921 private:
922 int private_int;
923 };
924 })?)?;
Michael Forster028800b2021-10-05 12:39:59 +0000925
Marcel Hlopko89547752021-12-10 09:39:41 +0000926 let rs_api = generate_rs_api(&ir)?;
927 assert_rs_matches!(
928 rs_api,
929 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +0000930 #[derive(Clone, Copy)]
931 #[repr(C)]
932 pub struct SomeStruct {
933 pub public_int: i32,
934 protected_int: i32,
935 private_int: i32,
Marcel Hlopko89547752021-12-10 09:39:41 +0000936 }
937 }
938 );
939 assert_rs_matches!(
940 rs_api,
941 quote! {
Googler454f2652021-12-06 12:53:12 +0000942 const _: () = assert!(std::mem::size_of::<Option<&i32>>() == std::mem::size_of::<&i32>());
Googler209b10a2021-12-06 09:11:57 +0000943 const _: () = assert!(std::mem::size_of::<SomeStruct>() == 12usize);
944 const _: () = assert!(std::mem::align_of::<SomeStruct>() == 4usize);
945 const _: () = assert!(offset_of!(SomeStruct, public_int) * 8 == 0usize);
946 const _: () = assert!(offset_of!(SomeStruct, protected_int) * 8 == 32usize);
947 const _: () = assert!(offset_of!(SomeStruct, private_int) * 8 == 64usize);
Marcel Hlopko89547752021-12-10 09:39:41 +0000948 }
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000949 );
Marcel Hlopko89547752021-12-10 09:39:41 +0000950 let rs_api_impl = generate_rs_api_impl(&ir)?;
951 assert_cc_matches!(
952 rs_api_impl,
953 quote! {
954 extern "C" void __rust_thunk___ZN10SomeStructD1Ev(SomeStruct * __this) {
Lukasz Anforowicze643ec92021-12-22 15:45:15 +0000955 std :: destroy_at (__this) ;
Marcel Hlopko89547752021-12-10 09:39:41 +0000956 }
957 }
958 );
959 assert_cc_matches!(
960 rs_api_impl,
961 quote! {
Googler5ea88642021-09-29 08:05:59 +0000962 static_assert(sizeof(SomeStruct) == 12);
963 static_assert(alignof(SomeStruct) == 4);
964 static_assert(offsetof(SomeStruct, public_int) * 8 == 0);
Marcel Hlopko89547752021-12-10 09:39:41 +0000965 }
Googler5ea88642021-09-29 08:05:59 +0000966 );
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000967 Ok(())
968 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +0000969
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000970 #[test]
Marcel Hlopkodd1fcb12021-12-22 14:13:59 +0000971 fn test_record_static_methods_qualify_call_in_thunk() -> Result<()> {
972 let ir = ir_from_cc(&tokens_to_string(quote! {
973 struct SomeStruct {
974 static inline int some_func() { return 42; }
975 };
976 })?)?;
977
978 assert_cc_matches!(
979 generate_rs_api_impl(&ir)?,
980 quote! {
981 extern "C" int __rust_thunk___ZN10SomeStruct9some_funcEv() {
982 return SomeStruct::some_func();
983 }
984 }
985 );
986 Ok(())
987 }
988
989 #[test]
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000990 fn test_struct_from_other_target() -> Result<()> {
991 let ir = ir_from_cc_dependency("// intentionally empty", "struct SomeStruct {};")?;
Marcel Hlopko89547752021-12-10 09:39:41 +0000992 assert_rs_not_matches!(generate_rs_api(&ir)?, quote! { SomeStruct });
993 assert_cc_not_matches!(generate_rs_api_impl(&ir)?, quote! { SomeStruct });
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000994 Ok(())
995 }
996
997 #[test]
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000998 fn test_copy_derives() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +0000999 let record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001000 assert_eq!(generate_copy_derives(&record), &["Clone", "Copy"]);
1001 }
1002
1003 #[test]
1004 fn test_copy_derives_not_is_trivial_abi() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001005 let mut record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001006 record.is_trivial_abi = false;
1007 assert_eq!(generate_copy_derives(&record), &[""; 0]);
1008 }
1009
Devin Jeanpierree6e16652021-12-22 15:54:46 +00001010 /// A type can be unsafe to pass in mut references from C++, but still
1011 /// Clone+Copy when handled by value.
1012 #[test]
1013 fn test_copy_derives_not_is_mut_reference_safe() {
1014 let mut record = ir_record("S");
1015 record.is_final = false;
1016 assert_eq!(generate_copy_derives(&record), &["Clone", "Copy"]);
1017 }
1018
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001019 #[test]
1020 fn test_copy_derives_ctor_nonpublic() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001021 let mut record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001022 for access in [ir::AccessSpecifier::Protected, ir::AccessSpecifier::Private] {
1023 record.copy_constructor.access = access;
1024 assert_eq!(generate_copy_derives(&record), &[""; 0]);
1025 }
1026 }
1027
1028 #[test]
1029 fn test_copy_derives_ctor_deleted() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001030 let mut record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001031 record.copy_constructor.definition = ir::SpecialMemberDefinition::Deleted;
1032 assert_eq!(generate_copy_derives(&record), &[""; 0]);
1033 }
1034
1035 #[test]
Devin Jeanpierrebe2f33b2021-10-21 12:54:19 +00001036 fn test_copy_derives_ctor_nontrivial_members() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001037 let mut record = ir_record("S");
Devin Jeanpierrebe2f33b2021-10-21 12:54:19 +00001038 record.copy_constructor.definition = ir::SpecialMemberDefinition::NontrivialMembers;
1039 assert_eq!(generate_copy_derives(&record), &[""; 0]);
1040 }
1041
1042 #[test]
1043 fn test_copy_derives_ctor_nontrivial_self() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001044 let mut record = ir_record("S");
Devin Jeanpierre7b62e952021-12-08 21:43:30 +00001045 record.copy_constructor.definition = ir::SpecialMemberDefinition::NontrivialUserDefined;
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001046 assert_eq!(generate_copy_derives(&record), &[""; 0]);
1047 }
1048
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001049 #[test]
1050 fn test_ptr_func() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001051 let ir = ir_from_cc(&tokens_to_string(quote! {
1052 inline int* Deref(int*const* p);
1053 })?)?;
Devin Jeanpierred6da7002021-10-21 12:55:20 +00001054
Marcel Hlopko89547752021-12-10 09:39:41 +00001055 let rs_api = generate_rs_api(&ir)?;
1056 assert_rs_matches!(
1057 rs_api,
1058 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001059 #[inline(always)]
1060 pub fn Deref(p: *const *mut i32) -> *mut i32 {
Googlera675ae02021-12-07 08:04:59 +00001061 unsafe { crate::detail::__rust_thunk___Z5DerefPKPi(p) }
Marcel Hlopko89547752021-12-10 09:39:41 +00001062 }
1063 }
1064 );
1065 assert_rs_matches!(
1066 rs_api,
1067 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001068 mod detail {
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +00001069 use super::*;
Michael Forsterdb8101a2021-10-08 06:56:03 +00001070 extern "C" {
Googlera675ae02021-12-07 08:04:59 +00001071 pub(crate) fn __rust_thunk___Z5DerefPKPi(p: *const *mut i32) -> *mut i32;
Marcel Hlopko89547752021-12-10 09:39:41 +00001072 }
1073 }
1074 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001075 );
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001076
Marcel Hlopko89547752021-12-10 09:39:41 +00001077 assert_cc_matches!(
1078 generate_rs_api_impl(&ir)?,
1079 quote! {
Googlera675ae02021-12-07 08:04:59 +00001080 extern "C" int* __rust_thunk___Z5DerefPKPi(int* const * p) {
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001081 return Deref(p);
1082 }
Marcel Hlopko89547752021-12-10 09:39:41 +00001083 }
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001084 );
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001085 Ok(())
1086 }
Michael Forstered642022021-10-04 09:48:25 +00001087
1088 #[test]
1089 fn test_item_order() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001090 let ir = ir_from_cc(
1091 "int first_func();
1092 struct FirstStruct {};
1093 int second_func();
1094 struct SecondStruct {};",
1095 )?;
Michael Forstered642022021-10-04 09:48:25 +00001096
Marcel Hlopko89547752021-12-10 09:39:41 +00001097 let rs_api = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?;
1098
Michael Forstered642022021-10-04 09:48:25 +00001099 let idx = |s: &str| rs_api.find(s).ok_or(anyhow!("'{}' missing", s));
1100
Googlera675ae02021-12-07 08:04:59 +00001101 println!("{:?}", ir);
1102
Michael Forstered642022021-10-04 09:48:25 +00001103 let f1 = idx("fn first_func")?;
1104 let f2 = idx("fn second_func")?;
1105 let s1 = idx("struct FirstStruct")?;
1106 let s2 = idx("struct SecondStruct")?;
Googlera675ae02021-12-07 08:04:59 +00001107 let t1 = idx("fn __rust_thunk___Z10first_funcv")?;
1108 let t2 = idx("fn __rust_thunk___Z11second_funcv")?;
Michael Forstered642022021-10-04 09:48:25 +00001109
1110 assert!(f1 < s1);
1111 assert!(s1 < f2);
1112 assert!(f2 < s2);
1113 assert!(s2 < t1);
1114 assert!(t1 < t2);
1115
1116 Ok(())
1117 }
Michael Forster028800b2021-10-05 12:39:59 +00001118
1119 #[test]
Michael Forster409d9412021-10-07 08:35:29 +00001120 fn test_doc_comment_func() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001121 let ir = ir_from_cc(
1122 "
1123 // Doc Comment
1124 // with two lines
1125 int func();",
1126 )?;
Michael Forster409d9412021-10-07 08:35:29 +00001127
Marcel Hlopko89547752021-12-10 09:39:41 +00001128 assert_rs_matches!(
1129 generate_rs_api(&ir)?,
1130 // leading space is intentional so there is a space between /// and the text of the
1131 // comment
1132 quote! {
1133 #[doc = " Doc Comment\n with two lines"]
1134 #[inline(always)]
1135 pub fn func
1136 }
Michael Forster409d9412021-10-07 08:35:29 +00001137 );
1138
1139 Ok(())
1140 }
1141
1142 #[test]
1143 fn test_doc_comment_record() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001144 let ir = ir_from_cc(
1145 "// Doc Comment\n\
1146 //\n\
1147 // * with bullet\n\
1148 struct SomeStruct {\n\
1149 // Field doc\n\
1150 int field;\
1151 };",
1152 )?;
Michael Forster028800b2021-10-05 12:39:59 +00001153
Marcel Hlopko89547752021-12-10 09:39:41 +00001154 assert_rs_matches!(
1155 generate_rs_api(&ir)?,
1156 quote! {
1157 #[doc = " Doc Comment\n \n * with bullet"]
1158 #[derive(Clone, Copy)]
1159 #[repr(C)]
1160 pub struct SomeStruct {
1161 # [doc = " Field doc"]
1162 pub field: i32,
1163 }
1164 }
Michael Forstercc5941a2021-10-07 07:12:24 +00001165 );
Michael Forster028800b2021-10-05 12:39:59 +00001166 Ok(())
1167 }
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001168
Devin Jeanpierre96839c12021-12-14 00:27:38 +00001169 #[test]
1170 fn test_virtual_thunk() -> Result<()> {
1171 let ir = ir_from_cc("struct Polymorphic { virtual void Foo(); };")?;
1172
1173 assert_cc_matches!(
1174 generate_rs_api_impl(&ir)?,
1175 quote! {
1176 extern "C" void __rust_thunk___ZN11Polymorphic3FooEv(Polymorphic * __this)
1177 }
1178 );
1179 Ok(())
1180 }
1181
Devin Jeanpierree6e16652021-12-22 15:54:46 +00001182 /// A trivially relocatable final struct is safe to use in Rust as normal,
1183 /// and is Unpin.
1184 #[test]
1185 fn test_no_negative_impl_unpin() -> Result<()> {
1186 let ir = ir_from_cc("struct Trivial final {};")?;
1187 let rs_api = generate_rs_api(&ir)?;
1188 assert_rs_not_matches!(rs_api, quote! {impl !Unpin});
1189 Ok(())
1190 }
1191
1192 /// A non-final struct, even if it's trivial, is not usable by mut
1193 /// reference, and so is !Unpin.
1194 #[test]
1195 fn test_negative_impl_unpin_nonfinal() -> Result<()> {
1196 let ir = ir_from_cc("struct Nonfinal {};")?;
1197 let rs_api = generate_rs_api(&ir)?;
1198 assert_rs_matches!(rs_api, quote! {impl !Unpin for Nonfinal {}});
1199 Ok(())
1200 }
1201
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001202 /// At the least, a trivial type should have no drop impl if or until we add
1203 /// empty drop impls.
1204 #[test]
1205 fn test_no_impl_drop() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00001206 let ir = ir_from_cc("struct Trivial {};")?;
Marcel Hlopko89547752021-12-10 09:39:41 +00001207 let rs_api = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?;
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001208 assert!(!rs_api.contains("impl Drop"));
1209 Ok(())
1210 }
1211
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001212 /// User-defined destructors *must* become Drop impls with ManuallyDrop
1213 /// fields
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001214 #[test]
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001215 fn test_impl_drop_user_defined_destructor() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00001216 let ir = ir_from_cc(
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001217 r#"struct UserDefinedDestructor {
1218 ~UserDefinedDestructor();
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001219 int x;
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001220 };"#,
1221 )?;
1222 let rs_api = generate_rs_api(&ir)?;
Marcel Hlopko89547752021-12-10 09:39:41 +00001223 println!("{}", rs_api);
1224 assert_rs_matches!(rs_api, quote! {impl Drop});
1225 assert_rs_not_matches!(rs_api, quote! {fn drop(&mut self) {}});
1226 assert_rs_matches!(rs_api, quote! {pub x: std::mem::ManuallyDrop<i32>,});
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001227 Ok(())
1228 }
1229
1230 /// nontrivial types without user-defined destructors must have an empty
1231 /// drop definition.
1232 #[test]
1233 fn test_impl_drop_nontrivial_member_destructor() -> Result<()> {
1234 // TODO(jeanpierreda): This would be cleaner if the UserDefinedDestructor code were
1235 // omitted. For example, we simulate it so that UserDefinedDestructor
1236 // comes from another library.
Googler7cced422021-12-06 11:58:39 +00001237 let ir = ir_from_cc(
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001238 r#"struct UserDefinedDestructor {
1239 ~UserDefinedDestructor();
1240 };
1241
1242 struct NontrivialMembers {
1243 UserDefinedDestructor udd;
1244 int x;
1245 };"#,
1246 )?;
1247 let rs_api = generate_rs_api(&ir)?;
Marcel Hlopko89547752021-12-10 09:39:41 +00001248 assert_rs_matches!(rs_api, quote! {fn drop(&mut self) {}});
1249 assert_rs_matches!(rs_api, quote! {pub x: i32,});
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001250 Ok(())
1251 }
1252
1253 /// Trivial types (at least those that are mapped to Copy rust types) do not
1254 /// get a Drop impl.
1255 #[test]
1256 fn test_impl_drop_trivial() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00001257 let ir = ir_from_cc(
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001258 r#"struct Trivial {
1259 ~Trivial() = default;
1260 int x;
1261 };"#,
1262 )?;
1263 let rs_api = generate_rs_api(&ir)?;
Marcel Hlopko89547752021-12-10 09:39:41 +00001264 assert_rs_not_matches!(rs_api, quote! {impl Drop});
1265 assert_rs_matches!(rs_api, quote! {pub x: i32});
Devin Jeanpierre91de7012021-10-21 12:53:51 +00001266 Ok(())
1267 }
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001268
1269 #[test]
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00001270 fn test_impl_default_explicitly_defaulted_constructor() -> Result<()> {
1271 let ir = ir_from_cc(
1272 r#"struct DefaultedConstructor {
1273 DefaultedConstructor() = default;
1274 };"#,
1275 )?;
1276 let rs_api = generate_rs_api(&ir)?;
1277 assert_rs_matches!(
1278 rs_api,
1279 quote! {
1280 impl Default for DefaultedConstructor {
1281 #[inline(always)]
1282 fn default() -> Self {
1283 let mut tmp = std::mem::MaybeUninit::<Self>::uninit();
1284 unsafe {
1285 crate::detail::__rust_thunk___ZN20DefaultedConstructorC1Ev(
1286 tmp.as_mut_ptr());
1287 tmp.assume_init()
1288 }
1289 }
1290 }
1291 }
1292 );
1293 let rs_api_impl = generate_rs_api_impl(&ir)?;
1294 assert_cc_matches!(
1295 rs_api_impl,
1296 quote! {
1297 extern "C" void __rust_thunk___ZN20DefaultedConstructorC1Ev(
1298 DefaultedConstructor* __this) {
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +00001299 rs_api_impl_support::construct_at (__this) ;
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00001300 }
1301 }
1302 );
1303 Ok(())
1304 }
1305
1306 #[test]
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +00001307 fn test_impl_default_non_trivial_struct() -> Result<()> {
1308 let ir = ir_from_cc(
1309 r#"struct NonTrivialStructWithConstructors {
1310 NonTrivialStructWithConstructors();
1311 ~NonTrivialStructWithConstructors(); // Non-trivial
1312 };"#,
1313 )?;
1314 let rs_api = generate_rs_api(&ir)?;
1315 assert_rs_not_matches!(rs_api, quote! {impl Default});
1316 Ok(())
1317 }
1318
1319 #[test]
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001320 fn test_thunk_ident_function() {
1321 let func = ir_func("foo");
Googlera675ae02021-12-07 08:04:59 +00001322 assert_eq!(thunk_ident(&func), make_ident("__rust_thunk___Z3foov"));
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001323 }
1324
1325 #[test]
1326 fn test_thunk_ident_special_names() {
Marcel Hlopko4b13b962021-12-06 12:40:56 +00001327 let ir = ir_from_cc("struct Class {};").unwrap();
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001328
Googler45ad2752021-12-06 12:12:35 +00001329 let destructor =
1330 ir.functions().find(|f| f.name == UnqualifiedIdentifier::Destructor).unwrap();
Googlera675ae02021-12-07 08:04:59 +00001331 assert_eq!(thunk_ident(&destructor), make_ident("__rust_thunk___ZN5ClassD1Ev"));
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001332
Googler45ad2752021-12-06 12:12:35 +00001333 let constructor =
1334 ir.functions().find(|f| f.name == UnqualifiedIdentifier::Constructor).unwrap();
Googlera675ae02021-12-07 08:04:59 +00001335 assert_eq!(thunk_ident(&constructor), make_ident("__rust_thunk___ZN5ClassC1Ev"));
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001336 }
Googler7cced422021-12-06 11:58:39 +00001337
1338 #[test]
Marcel Hlopko89547752021-12-10 09:39:41 +00001339 fn test_elided_lifetimes() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00001340 let ir = ir_from_cc(
1341 r#"#pragma clang lifetime_elision
1342 struct S {
1343 int& f(int& i);
1344 };"#,
Marcel Hlopko89547752021-12-10 09:39:41 +00001345 )?;
1346 let rs_api = generate_rs_api(&ir)?;
1347 assert_rs_matches!(
1348 rs_api,
1349 quote! {
1350 pub fn f<'a, 'b>(__this: &'b mut S, i: &'a mut i32) -> &'b mut i32 { ... }
1351 }
Googler7cced422021-12-06 11:58:39 +00001352 );
Marcel Hlopko89547752021-12-10 09:39:41 +00001353 assert_rs_matches!(
1354 rs_api,
1355 quote! {
1356 pub(crate) fn __rust_thunk___ZN1S1fERi<'a, 'b>(__this: &'b mut S, i: &'a mut i32)
1357 -> &'b mut i32;
1358 }
Googler7cced422021-12-06 11:58:39 +00001359 );
Marcel Hlopko89547752021-12-10 09:39:41 +00001360 Ok(())
Googler7cced422021-12-06 11:58:39 +00001361 }
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +00001362
1363 #[test]
1364 fn test_format_generic_params() -> Result<()> {
1365 assert_rs_matches!(format_generic_params(std::iter::empty::<syn::Ident>()), quote! {});
1366
1367 let idents = ["T1", "T2"].iter().map(|s| make_ident(s));
1368 assert_rs_matches!(format_generic_params(idents), quote! { < T1, T2 > });
1369
1370 let lifetimes = ["a", "b"]
1371 .iter()
1372 .map(|s| syn::Lifetime::new(&format!("'{}", s), proc_macro2::Span::call_site()));
1373 assert_rs_matches!(format_generic_params(lifetimes), quote! { < 'a, 'b > });
1374
1375 Ok(())
1376 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +00001377}