blob: 66816bc8b574bbe013ffc814d67f5d03589dea5e [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 Anforowicze57215c2022-01-12 14:54:16 +00005#[cfg(test)]
6#[macro_use]
7extern crate static_assertions;
8
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00009use anyhow::{anyhow, bail, ensure, Context, Result};
Marcel Hlopko884ae7f2021-08-18 13:58:22 +000010use ffi_types::*;
Marcel Hlopko42abfc82021-08-09 07:03:17 +000011use ir::*;
12use itertools::Itertools;
Googler5ea88642021-09-29 08:05:59 +000013use proc_macro2::{Ident, Literal, TokenStream};
Marcel Hlopko42abfc82021-08-09 07:03:17 +000014use quote::format_ident;
15use quote::quote;
Googlerd03d05b2022-01-07 10:10:57 +000016use std::collections::{BTreeSet, HashMap, HashSet};
Marcel Hlopko42abfc82021-08-09 07:03:17 +000017use std::iter::Iterator;
18use std::panic::catch_unwind;
19use std::process;
Marcel Hlopko65d05f02021-12-09 12:29:24 +000020use token_stream_printer::{rs_tokens_to_formatted_string, tokens_to_string};
Marcel Hlopko42abfc82021-08-09 07:03:17 +000021
Marcel Hlopko45fba972021-08-23 19:52:20 +000022/// FFI equivalent of `Bindings`.
23#[repr(C)]
24pub struct FfiBindings {
25 rs_api: FfiU8SliceBox,
26 rs_api_impl: FfiU8SliceBox,
27}
28
29/// Deserializes IR from `json` and generates bindings source code.
Marcel Hlopko42abfc82021-08-09 07:03:17 +000030///
31/// This function panics on error.
32///
33/// Ownership:
Michael Forsterbee84482021-10-13 08:35:38 +000034/// * function doesn't take ownership of (in other words it borrows) the
35/// param `json`
Marcel Hlopko42abfc82021-08-09 07:03:17 +000036/// * function passes ownership of the returned value to the caller
37///
38/// Safety:
Michael Forsterbee84482021-10-13 08:35:38 +000039/// * function expects that param `json` is a FfiU8Slice for a valid array of
40/// bytes with the given size.
Marcel Hlopko42abfc82021-08-09 07:03:17 +000041/// * function expects that param `json` doesn't change during the call.
42#[no_mangle]
Marcel Hlopko45fba972021-08-23 19:52:20 +000043pub unsafe extern "C" fn GenerateBindingsImpl(json: FfiU8Slice) -> FfiBindings {
Marcel Hlopko42abfc82021-08-09 07:03:17 +000044 catch_unwind(|| {
Marcel Hlopko45fba972021-08-23 19:52:20 +000045 // It is ok to abort here.
46 let Bindings { rs_api, rs_api_impl } = generate_bindings(json.as_slice()).unwrap();
47
48 FfiBindings {
49 rs_api: FfiU8SliceBox::from_boxed_slice(rs_api.into_bytes().into_boxed_slice()),
50 rs_api_impl: FfiU8SliceBox::from_boxed_slice(
51 rs_api_impl.into_bytes().into_boxed_slice(),
52 ),
53 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +000054 })
55 .unwrap_or_else(|_| process::abort())
56}
57
Marcel Hlopko45fba972021-08-23 19:52:20 +000058/// Source code for generated bindings.
59struct Bindings {
60 // Rust source code.
61 rs_api: String,
62 // C++ source code.
63 rs_api_impl: String,
Marcel Hlopko42abfc82021-08-09 07:03:17 +000064}
65
Marcel Hlopko45fba972021-08-23 19:52:20 +000066fn generate_bindings(json: &[u8]) -> Result<Bindings> {
67 let ir = deserialize_ir(json)?;
Marcel Hlopkoca84ff42021-12-09 14:15:14 +000068
69 // The code is formatted with a non-default rustfmt configuration. Prevent
70 // downstream workflows from reformatting with a different configuration.
Marcel Hlopko89547752021-12-10 09:39:41 +000071 let rs_api =
72 format!("#![rustfmt::skip]\n{}", rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?);
73 let rs_api_impl = tokens_to_string(generate_rs_api_impl(&ir)?)?;
Marcel Hlopkoca84ff42021-12-09 14:15:14 +000074
Marcel Hlopko45fba972021-08-23 19:52:20 +000075 Ok(Bindings { rs_api, rs_api_impl })
76}
77
Devin Jeanpierre6d5e7cc2021-10-21 12:56:07 +000078/// Rust source code with attached information about how to modify the parent
79/// crate.
Devin Jeanpierre273eeae2021-10-06 13:29:35 +000080///
Michael Forsterbee84482021-10-13 08:35:38 +000081/// For example, the snippet `vec![].into_raw_parts()` is not valid unless the
82/// `vec_into_raw_parts` feature is enabled. So such a snippet should be
83/// represented as:
Devin Jeanpierre273eeae2021-10-06 13:29:35 +000084///
85/// ```
86/// RsSnippet {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +000087/// features: btree_set![make_rs_ident("vec_into_raw_parts")],
Devin Jeanpierre273eeae2021-10-06 13:29:35 +000088/// tokens: quote!{vec![].into_raw_parts()},
89/// }
90/// ```
91struct RsSnippet {
92 /// Rust feature flags used by this snippet.
93 features: BTreeSet<Ident>,
94 /// The snippet itself, as a token stream.
95 tokens: TokenStream,
96}
97
98impl From<TokenStream> for RsSnippet {
99 fn from(tokens: TokenStream) -> Self {
100 RsSnippet { features: BTreeSet::new(), tokens }
101 }
102}
103
Michael Forsterbee84482021-10-13 08:35:38 +0000104/// If we know the original C++ function is codegenned and already compatible
105/// with `extern "C"` calling convention we skip creating/calling the C++ thunk
106/// since we can call the original C++ directly.
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000107fn can_skip_cc_thunk(func: &Func) -> bool {
Devin Jeanpierre96839c12021-12-14 00:27:38 +0000108 // ## Inline functions
109 //
Michael Forsterbee84482021-10-13 08:35:38 +0000110 // Inline functions may not be codegenned in the C++ library since Clang doesn't
111 // know if Rust calls the function or not. Therefore in order to make inline
112 // functions callable from Rust we need to generate a C++ file that defines
113 // a thunk that delegates to the original inline function. When compiled,
114 // Clang will emit code for this thunk and Rust code will call the
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000115 // thunk when the user wants to call the original inline function.
116 //
Michael Forsterbee84482021-10-13 08:35:38 +0000117 // This is not great runtime-performance-wise in regular builds (inline function
118 // will not be inlined, there will always be a function call), but it is
119 // correct. ThinLTO builds will be able to see through the thunk and inline
120 // code across the language boundary. For non-ThinLTO builds we plan to
121 // implement <internal link> which removes the runtime performance overhead.
Devin Jeanpierre96839c12021-12-14 00:27:38 +0000122 if func.is_inline {
123 return false;
124 }
125 // ## Virtual functions
126 //
127 // When calling virtual `A::Method()`, it's not necessarily the case that we'll
128 // specifically call the concrete `A::Method` impl. For example, if this is
129 // called on something whose dynamic type is some subclass `B` with an
130 // overridden `B::Method`, then we'll call that.
131 //
132 // We must reuse the C++ dynamic dispatching system. In this case, the easiest
133 // way to do it is by resorting to a C++ thunk, whose implementation will do
134 // the lookup.
135 //
136 // In terms of runtime performance, since this only occurs for virtual function
137 // calls, which are already slow, it may not be such a big deal. We can
138 // benchmark it later. :)
139 if let Some(meta) = &func.member_func_metadata {
140 if let Some(inst_meta) = &meta.instance_method_metadata {
141 if inst_meta.is_virtual {
142 return false;
143 }
144 }
145 }
146
147 true
Marcel Hlopko3164eee2021-08-24 20:09:22 +0000148}
149
Googlerd03d05b2022-01-07 10:10:57 +0000150/// Uniquely identifies a generated Rust function.
151#[derive(Clone, PartialEq, Eq, Hash)]
152struct FunctionId {
153 // If the function is on a trait impl, contains the name of the Self type for
154 // which the trait is being implemented.
155 self_type: Option<syn::Path>,
156 // Fully qualified path of the function. For functions in impl blocks, this
157 // includes the name of the type or trait on which the function is being
158 // implemented, e.g. `Default::default`.
159 function_path: syn::Path,
160}
161
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000162/// Returns the name of `func` in C++ syntax.
Googlerd03d05b2022-01-07 10:10:57 +0000163fn cxx_function_name(func: &Func, ir: &IR) -> Result<String> {
164 let record: Option<&str> = func
165 .member_func_metadata
166 .as_ref()
167 .map(|meta| meta.find_record(ir))
168 .transpose()?
169 .map(|r| &*r.identifier.identifier);
170
171 let func_name = match &func.name {
172 UnqualifiedIdentifier::Identifier(id) => id.identifier.clone(),
173 UnqualifiedIdentifier::Destructor => {
174 format!("~{}", record.expect("destructor must be associated with a record"))
175 }
176 UnqualifiedIdentifier::Constructor => {
177 format!("~{}", record.expect("constructor must be associated with a record"))
178 }
179 };
180
181 if let Some(record_name) = record {
182 Ok(format!("{}::{}", record_name, func_name))
183 } else {
184 Ok(func_name)
185 }
186}
187
Michael Forstered642022021-10-04 09:48:25 +0000188/// Generates Rust source code for a given `Func`.
189///
Googlerd03d05b2022-01-07 10:10:57 +0000190/// Returns None if no code was generated for the function; otherwise, returns
191/// a tuple containing:
192/// - The generated function or trait impl
193/// - The thunk
194/// - A `FunctionId` identifying the generated Rust function
195fn generate_func(func: &Func, ir: &IR) -> Result<Option<(RsSnippet, RsSnippet, FunctionId)>> {
Michael Forstered642022021-10-04 09:48:25 +0000196 let mangled_name = &func.mangled_name;
Googlera675ae02021-12-07 08:04:59 +0000197 let thunk_ident = thunk_ident(func);
Michael Forster409d9412021-10-07 08:35:29 +0000198 let doc_comment = generate_doc_comment(&func.doc_comment);
Googler7cced422021-12-06 11:58:39 +0000199 let lifetime_to_name = HashMap::<LifetimeId, String>::from_iter(
200 func.lifetime_params.iter().map(|l| (l.id, l.name.clone())),
201 );
Lukasz Anforowicz4ad012b2021-12-15 18:13:40 +0000202 let return_type_fragment = if func.return_type.rs_type.is_unit_type() {
203 quote! {}
204 } else {
Googlerb7e361d2022-01-04 14:02:59 +0000205 let return_type_name = format_rs_type(&func.return_type.rs_type, ir, &lifetime_to_name)
206 .with_context(|| format!("Failed to format return type for {:?}", func))?;
Lukasz Anforowicz4ad012b2021-12-15 18:13:40 +0000207 quote! { -> #return_type_name }
208 };
Michael Forstered642022021-10-04 09:48:25 +0000209
210 let param_idents =
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000211 func.params.iter().map(|p| make_rs_ident(&p.identifier.identifier)).collect_vec();
Michael Forstered642022021-10-04 09:48:25 +0000212
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000213 let param_type_kinds = func
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000214 .params
215 .iter()
Googlerb7e361d2022-01-04 14:02:59 +0000216 .map(|p| {
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000217 RsTypeKind::new(&p.type_.rs_type, ir).with_context(|| {
218 format!("Failed to process type of parameter {:?} on {:?}", p, func)
Googlerb7e361d2022-01-04 14:02:59 +0000219 })
220 })
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000221 .collect::<Result<Vec<_>>>()?;
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000222 let param_types = param_type_kinds
223 .iter()
224 .map(|t| {
225 t.format(ir, &lifetime_to_name)
226 .with_context(|| format!("Failed to format parameter type {:?} on {:?}", t, func))
227 })
228 .collect::<Result<Vec<_>>>()?;
229 let is_unsafe = param_type_kinds.iter().any(|p| matches!(p, RsTypeKind::Pointer { .. }));
Michael Forstered642022021-10-04 09:48:25 +0000230
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000231 let maybe_record: Option<&Record> =
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000232 func.member_func_metadata.as_ref().map(|meta| meta.find_record(ir)).transpose()?;
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000233 let maybe_record_name = maybe_record.map(|r| make_rs_ident(&r.identifier.identifier));
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000234
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000235 // Find 1) the `func_name` and `impl_kind` of the API function to generate
236 // and 2) whether to `format_first_param_as_self` (`&self` or `&mut self`).
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000237 enum ImplKind {
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000238 None, // No `impl` needed
239 Struct, // e.g. `impl SomeStruct { ... }` (SomeStruct based on func.member_func_metadata)
240 Trait {
241 trait_name: TokenStream, // e.g. quote!{ From<int> }
242 record_name: Ident, /* e.g. SomeStruct (might *not* be from
243 * func.member_func_metadata) */
244 },
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000245 }
246 let impl_kind: ImplKind;
247 let func_name: syn::Ident;
248 let format_first_param_as_self: bool;
Googlerd03d05b2022-01-07 10:10:57 +0000249 match &func.name {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000250 UnqualifiedIdentifier::Identifier(id) if id.identifier == "operator==" => {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000251 match (param_type_kinds.get(0), param_type_kinds.get(1)) {
252 (
253 Some(RsTypeKind::Reference {
254 referent: lhs,
255 mutability: Mutability::Const,
256 ..
257 }),
258 Some(RsTypeKind::Reference {
259 referent: rhs,
260 mutability: Mutability::Const,
261 ..
262 }),
263 ) => match **lhs {
264 RsTypeKind::Record(lhs_record) => {
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000265 let lhs: Ident = make_rs_ident(&lhs_record.identifier.identifier);
266 let rhs: TokenStream = rhs.format(ir, &lifetime_to_name)?;
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000267 format_first_param_as_self = true;
268 func_name = make_rs_ident("eq");
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000269 impl_kind = ImplKind::Trait {
270 trait_name: quote! {PartialEq<#rhs>},
271 record_name: lhs,
272 };
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000273 }
274 _ => return Ok(None),
275 },
276 _ => return Ok(None),
277 };
278 }
279 UnqualifiedIdentifier::Identifier(id) if id.identifier.starts_with("operator") => {
280 return Ok(None);
281 }
Devin Jeanpierref2ec8712021-10-13 20:47:16 +0000282 UnqualifiedIdentifier::Identifier(id) => {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000283 func_name = make_rs_ident(&id.identifier);
Lukasz Anforowiczf9564622022-01-28 14:31:04 +0000284 match maybe_record {
285 None => {
286 impl_kind = ImplKind::None;
287 format_first_param_as_self = false;
288 }
289 Some(record) => {
290 impl_kind = ImplKind::Struct;
291 if func.is_instance_method() {
292 let first_param = param_type_kinds.first().ok_or_else(|| {
293 anyhow!("Missing `__this` parameter in an instance method: {:?}", func)
294 })?;
295 format_first_param_as_self = first_param.is_ref_to(record)
296 } else {
297 format_first_param_as_self = false;
298 }
299 }
300 };
Michael Forstered642022021-10-04 09:48:25 +0000301 }
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000302 UnqualifiedIdentifier::Destructor => {
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000303 // Note: to avoid double-destruction of the fields, they are all wrapped in
304 // ManuallyDrop in this case. See `generate_record`.
305 let record =
306 maybe_record.ok_or_else(|| anyhow!("Destructors must be member functions."))?;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000307 if !should_implement_drop(record) {
308 return Ok(None);
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000309 }
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000310 let record_name = maybe_record_name
311 .clone()
312 .ok_or_else(|| anyhow!("Destructors must be member functions."))?;
313 impl_kind = ImplKind::Trait { trait_name: quote! {Drop}, record_name };
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000314 func_name = make_rs_ident("drop");
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000315 format_first_param_as_self = true;
Devin Jeanpierre91de7012021-10-21 12:53:51 +0000316 }
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000317 UnqualifiedIdentifier::Constructor => {
Lukasz Anforowicz71716b72022-01-26 17:05:05 +0000318 let member_func_metadata = func
319 .member_func_metadata
320 .as_ref()
321 .ok_or_else(|| anyhow!("Constructors must be member functions."))?;
322 let record = maybe_record
323 .ok_or_else(|| anyhow!("Constructors must be associated with a record."))?;
324 let instance_method_metadata =
325 member_func_metadata
326 .instance_method_metadata
327 .as_ref()
328 .ok_or_else(|| anyhow!("Constructors must be instance methods."))?;
329
Devin Jeanpierre88343c72022-01-15 01:10:23 +0000330 if !record.is_unpin() {
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000331 // TODO: Handle <internal link>
Googlerd03d05b2022-01-07 10:10:57 +0000332 return Ok(None);
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +0000333 }
Lukasz Anforowicz55673c92022-01-27 19:37:26 +0000334 if is_unsafe {
335 // TODO(b/216648347): Allow this outside of traits (e.g. after supporting
336 // translating C++ constructors into static methods in Rust).
337 return Ok(None);
338 }
339
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000340 let record_name = maybe_record_name
341 .clone()
342 .ok_or_else(|| anyhow!("Constructors must be member functions."))?;
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000343 match func.params.len() {
Lukasz Anforowiczf9564622022-01-28 14:31:04 +0000344 0 => bail!("Missing `__this` parameter in a constructor: {:?}", func),
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000345 1 => {
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000346 impl_kind = ImplKind::Trait { trait_name: quote! {Default}, record_name };
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000347 func_name = make_rs_ident("default");
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000348 format_first_param_as_self = false;
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000349 }
Lukasz Anforowicz73326af2022-01-05 01:13:10 +0000350 2 => {
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000351 // TODO(lukasza): Do something smart with move constructor.
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000352 if param_type_kinds[1].is_shared_ref_to(record) {
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000353 // Copy constructor
354 if should_derive_clone(record) {
355 return Ok(None);
356 } else {
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000357 impl_kind = ImplKind::Trait { trait_name: quote! {Clone}, record_name };
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000358 func_name = make_rs_ident("clone");
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000359 format_first_param_as_self = true;
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000360 }
Lukasz Anforowicz71716b72022-01-26 17:05:05 +0000361 } else if !instance_method_metadata.is_explicit_ctor {
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000362 let param_type = &param_types[1];
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000363 impl_kind = ImplKind::Trait {
364 trait_name: quote! {From< #param_type >},
365 record_name,
366 };
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000367 func_name = make_rs_ident("from");
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000368 format_first_param_as_self = false;
Lukasz Anforowicz71716b72022-01-26 17:05:05 +0000369 } else {
370 return Ok(None);
Lukasz Anforowicz73326af2022-01-05 01:13:10 +0000371 }
372 }
373 _ => {
Lukasz Anforowicz55673c92022-01-27 19:37:26 +0000374 // TODO(b/216648347): Support bindings for other constructors.
Googlerd03d05b2022-01-07 10:10:57 +0000375 return Ok(None);
Lukasz Anforowicz73326af2022-01-05 01:13:10 +0000376 }
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000377 }
378 }
379 }
380
381 let api_func_def = {
Lukasz Anforowicz95551272022-01-20 00:02:24 +0000382 // Clone params, return type, etc - we may need to mutate them in the
383 // API func, but we want to retain the originals for the thunk.
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000384 let mut return_type_fragment = return_type_fragment.clone();
385 let mut thunk_args = param_idents.iter().map(|id| quote! { #id}).collect_vec();
386 let mut api_params = param_idents
387 .iter()
388 .zip(param_types.iter())
389 .map(|(ident, type_)| quote! { #ident : #type_ })
390 .collect_vec();
Lukasz Anforowicz95551272022-01-20 00:02:24 +0000391 let mut lifetimes = func.lifetime_params.iter().collect_vec();
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000392 let mut maybe_first_api_param = param_type_kinds.get(0);
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000393
394 if func.name == UnqualifiedIdentifier::Constructor {
395 return_type_fragment = quote! { -> Self };
396
Lukasz Anforowiczf9564622022-01-28 14:31:04 +0000397 // Drop `__this` parameter from the public Rust API. Presence of
398 // element #0 is indirectly verified by a `Constructor`-related
399 // `match` branch a little bit above.
400 api_params.remove(0);
401 thunk_args.remove(0);
Lukasz Anforowicz95551272022-01-20 00:02:24 +0000402
Lukasz Anforowicz326c4e42022-01-27 14:43:00 +0000403 // Remove the lifetime associated with `__this`.
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000404 let maybe_first_lifetime = func.params[0].type_.rs_type.lifetime_args.first();
Lukasz Anforowicz55673c92022-01-27 19:37:26 +0000405 let no_longer_needed_lifetime_id = maybe_first_lifetime
406 .ok_or_else(|| anyhow!("Missing lifetime on `__this` parameter: {:?}", func))?;
407 lifetimes.retain(|l| l.id != *no_longer_needed_lifetime_id);
408 // TODO(lukasza): Also cover the case where the lifetime of `__this`
409 // is also used *deep* in another parameter:
410 // fn constructor<'a>(__this: &'a mut Self, x: SomeStruct<'a>)
411 if let Some(type_still_dependent_on_removed_lifetime) = param_type_kinds
412 .iter()
413 .skip(1) // Skipping `__this`
414 .find(|t| {
415 matches!(t, RsTypeKind::Reference{ lifetime_id, .. }
416 if *lifetime_id == *no_longer_needed_lifetime_id)
417 })
418 {
419 bail!(
420 "The lifetime of `__this` is unexpectedly also used by another \
421 parameter {:?} in function {:?}",
422 type_still_dependent_on_removed_lifetime,
423 func.name
424 );
Lukasz Anforowicz95551272022-01-20 00:02:24 +0000425 }
426
427 // Rebind `maybe_first_api_param` to the next param after `__this`.
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000428 maybe_first_api_param = param_type_kinds.get(1);
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000429 }
430
431 // Change `__this: &'a SomeStruct` into `&'a self` if needed.
432 if format_first_param_as_self {
433 let first_api_param = maybe_first_api_param
434 .ok_or_else(|| anyhow!("No parameter to format as 'self': {:?}", func))?;
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000435 let self_decl = first_api_param
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000436 .format_as_self_param_for_instance_method(func, ir, &lifetime_to_name)
437 .with_context(|| {
438 format!("Failed to format as `self` param: {:?}", first_api_param)
439 })?;
Lukasz Anforowiczf9564622022-01-28 14:31:04 +0000440 // Presence of element #0 is verified by `ok_or_else` on
441 // `maybe_first_api_param` above.
442 api_params[0] = self_decl;
443 thunk_args[0] = quote! { self };
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000444 }
445
446 let func_body = match &func.name {
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000447 UnqualifiedIdentifier::Identifier(_) => {
448 let mut body = quote! { crate::detail::#thunk_ident( #( #thunk_args ),* ) };
449 // Only need to wrap everything in an `unsafe { ... }` block if
450 // the *whole* api function is safe.
451 if !is_unsafe {
452 body = quote! { unsafe { #body } };
453 }
454 body
455 }
456 UnqualifiedIdentifier::Destructor => {
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000457 quote! { unsafe { crate::detail::#thunk_ident( #( #thunk_args ),* ) } }
458 }
459 UnqualifiedIdentifier::Constructor => {
460 // SAFETY: A user-defined constructor is not guaranteed to
461 // initialize all the fields. To make the `assume_init()` call
462 // below safe, the memory is zero-initialized first. This is a
463 // bit safer, because zero-initialized memory represents a valid
464 // value for the currently supported field types (this may
465 // change once the bindings generator starts supporting
466 // reference fields). TODO(b/213243309): Double-check if
467 // zero-initialization is desirable here.
468 quote! {
469 let mut tmp = std::mem::MaybeUninit::<Self>::zeroed();
470 unsafe {
471 crate::detail::#thunk_ident( &mut tmp #( , #thunk_args )* );
472 tmp.assume_init()
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000473 }
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000474 }
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000475 }
476 };
477
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000478 let (pub_, unsafe_) = match impl_kind {
479 ImplKind::None | ImplKind::Struct => (
480 quote! { pub },
481 if is_unsafe {
482 quote! {unsafe}
483 } else {
484 quote! {}
485 },
486 ),
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000487 ImplKind::Trait { .. } => {
Lukasz Anforowicz55673c92022-01-27 19:37:26 +0000488 // Currently supported bindings have no unsafe trait functions.
489 assert!(!is_unsafe || func.name == UnqualifiedIdentifier::Destructor);
490 (quote! {}, quote! {})
491 }
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000492 };
493
Lukasz Anforowicz95551272022-01-20 00:02:24 +0000494 let lifetimes = lifetimes.into_iter().map(|l| format_lifetime_name(&l.name));
495 let generic_params = format_generic_params(lifetimes);
496
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000497 quote! {
498 #[inline(always)]
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000499 #pub_ #unsafe_ fn #func_name #generic_params( #( #api_params ),* ) #return_type_fragment {
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000500 #func_body
501 }
Lukasz Anforowicz13cf7492021-12-22 15:29:52 +0000502 }
Michael Forstered642022021-10-04 09:48:25 +0000503 };
504
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000505 let api_func: TokenStream;
506 let function_id: FunctionId;
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000507 match impl_kind {
508 ImplKind::None => {
509 api_func = quote! { #doc_comment #api_func_def };
510 function_id = FunctionId { self_type: None, function_path: func_name.into() };
511 }
512 ImplKind::Struct => {
513 let record_name =
514 maybe_record_name.ok_or_else(|| anyhow!("Struct methods must have records"))?;
515 api_func = quote! { impl #record_name { #doc_comment #api_func_def } };
516 function_id = FunctionId {
517 self_type: None,
518 function_path: syn::parse2(quote! { #record_name :: #func_name })?,
519 };
520 }
Lukasz Anforowicz732ca642022-02-03 20:58:38 +0000521 ImplKind::Trait { trait_name, record_name } => {
Lukasz Anforowiczab65e292022-01-14 23:04:21 +0000522 api_func = quote! { #doc_comment impl #trait_name for #record_name { #api_func_def } };
523 function_id = FunctionId {
524 self_type: Some(record_name.into()),
525 function_path: syn::parse2(quote! { #trait_name :: #func_name })?,
526 };
527 }
528 }
529
Lukasz Anforowicz6d553632022-01-06 21:36:14 +0000530 let thunk = {
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000531 let thunk_attr = if can_skip_cc_thunk(func) {
532 quote! {#[link_name = #mangled_name]}
533 } else {
534 quote! {}
535 };
536
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +0000537 // For constructors inject MaybeUninit into the type of `__this_` parameter.
538 let mut param_types = param_types;
539 if func.name == UnqualifiedIdentifier::Constructor {
540 if param_types.is_empty() || func.params.is_empty() {
541 bail!("Constructors should have at least one parameter (__this)");
542 }
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +0000543 param_types[0] = param_type_kinds[0]
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +0000544 .format_as_this_param_for_constructor_thunk(ir, &lifetime_to_name)
545 .with_context(|| {
546 format!("Failed to format `__this` param for a thunk: {:?}", func.params[0])
547 })?;
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +0000548 }
549
Lukasz Anforowicz95551272022-01-20 00:02:24 +0000550 let lifetimes = func.lifetime_params.iter().map(|l| format_lifetime_name(&l.name));
551 let generic_params = format_generic_params(lifetimes);
552
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000553 quote! {
554 #thunk_attr
Lukasz Anforowicz4ad012b2021-12-15 18:13:40 +0000555 pub(crate) fn #thunk_ident #generic_params( #( #param_idents: #param_types ),*
556 ) #return_type_fragment ;
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000557 }
Michael Forstered642022021-10-04 09:48:25 +0000558 };
559
Googlerd03d05b2022-01-07 10:10:57 +0000560 Ok(Some((api_func.into(), thunk.into(), function_id)))
Michael Forstered642022021-10-04 09:48:25 +0000561}
562
Michael Forstercc5941a2021-10-07 07:12:24 +0000563fn generate_doc_comment(comment: &Option<String>) -> TokenStream {
564 match comment {
Michael Forster028800b2021-10-05 12:39:59 +0000565 Some(text) => {
Marcel Hlopko89547752021-12-10 09:39:41 +0000566 // token_stream_printer (and rustfmt) don't put a space between /// and the doc
567 // comment, let's add it here so our comments are pretty.
Michael Forster028800b2021-10-05 12:39:59 +0000568 let doc = format!(" {}", text.replace("\n", "\n "));
569 quote! {#[doc=#doc]}
570 }
571 None => quote! {},
Michael Forstercc5941a2021-10-07 07:12:24 +0000572 }
573}
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +0000574
575fn format_generic_params<T: quote::ToTokens>(params: impl IntoIterator<Item = T>) -> TokenStream {
576 let mut params = params.into_iter().peekable();
577 if params.peek().is_none() {
578 quote! {}
579 } else {
580 quote! { < #( #params ),* > }
581 }
582}
583
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000584fn should_implement_drop(record: &Record) -> bool {
585 match record.destructor.definition {
586 // TODO(b/202258760): Only omit destructor if `Copy` is specified.
587 SpecialMemberDefinition::Trivial => false,
588
589 // TODO(b/212690698): Avoid calling into the C++ destructor (e.g. let
590 // Rust drive `drop`-ing) to avoid (somewhat unergonomic) ManuallyDrop
591 // if we can ask Rust to preserve C++ field destruction order in
592 // NontrivialMembers case.
593 SpecialMemberDefinition::NontrivialMembers => true,
594
595 // The `impl Drop` for NontrivialUserDefined needs to call into the
596 // user-defined destructor on C++ side.
597 SpecialMemberDefinition::NontrivialUserDefined => true,
598
599 // TODO(b/213516512): Today the IR doesn't contain Func entries for
600 // deleted functions/destructors/etc. But, maybe we should generate
601 // `impl Drop` in this case? With `unreachable!`? With
602 // `std::mem::forget`?
603 SpecialMemberDefinition::Deleted => false,
604 }
605}
606
607/// Returns whether fields of type `ty` need to be wrapped in `ManuallyDrop<T>`
608/// to prevent the fields from being destructed twice (once by the C++
609/// destructor calkled from the `impl Drop` of the struct and once by `drop` on
610/// the Rust side).
611///
612/// A type is safe to destroy twice if it implements `Copy`. Fields of such
613/// don't need to be wrapped in `ManuallyDrop<T>` even if the struct
614/// containing the fields provides an `impl Drop` that calles into a C++
615/// destructor (in addition to dropping the fields on the Rust side).
616///
617/// Note that it is not enough to just be `!needs_drop<T>()`: Rust only
618/// guarantees that it is safe to use-after-destroy for `Copy` types. See
619/// e.g. the documentation for
620/// [`drop_in_place`](https://doc.rust-lang.org/std/ptr/fn.drop_in_place.html):
621///
622/// > if `T` is not `Copy`, using the pointed-to value after calling
623/// > `drop_in_place` can cause undefined behavior
624fn needs_manually_drop(ty: &ir::RsType, ir: &IR) -> Result<bool> {
625 let ty_implements_copy = RsTypeKind::new(ty, ir)?.implements_copy();
626 Ok(!ty_implements_copy)
627}
628
Michael Forsterbee84482021-10-13 08:35:38 +0000629/// Generates Rust source code for a given `Record` and associated assertions as
630/// a tuple.
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000631fn generate_record(record: &Record, ir: &IR) -> Result<(RsSnippet, RsSnippet)> {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000632 let ident = make_rs_ident(&record.identifier.identifier);
Michael Forstercc5941a2021-10-07 07:12:24 +0000633 let doc_comment = generate_doc_comment(&record.doc_comment);
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000634 let field_idents =
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000635 record.fields.iter().map(|f| make_rs_ident(&f.identifier.identifier)).collect_vec();
Michael Forstercc5941a2021-10-07 07:12:24 +0000636 let field_doc_coments =
637 record.fields.iter().map(|f| generate_doc_comment(&f.doc_comment)).collect_vec();
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000638 let field_types = record
639 .fields
640 .iter()
Devin Jeanpierreb69bcae2022-02-03 09:45:50 +0000641 .enumerate()
642 .map(|(i, f)| {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000643 // [[no_unique_address]] fields are replaced by an unaligned block of memory
644 // which fills space up to the next field.
Devin Jeanpierreb69bcae2022-02-03 09:45:50 +0000645 // See: docs/struct_layout
646 if f.is_no_unique_address {
647 let next_offset = if let Some(next) = record.fields.get(i + 1) {
648 next.offset
649 } else {
650 record.size * 8
651 };
652 let width = Literal::usize_unsuffixed((next_offset - f.offset) / 8);
653 return Ok(quote! {[std::mem::MaybeUninit<u8>; #width]});
654 }
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000655 let mut formatted = format_rs_type(&f.type_.rs_type, ir, &HashMap::new())
656 .with_context(|| {
Googlerb7e361d2022-01-04 14:02:59 +0000657 format!("Failed to format type for field {:?} on record {:?}", f, record)
658 })?;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000659 // TODO(b/212696226): Verify cases where ManuallyDrop<T> is skipped
660 // via static asserts in the generated code.
661 if should_implement_drop(record) && needs_manually_drop(&f.type_.rs_type, ir)? {
662 // TODO(b/212690698): Avoid (somewhat unergonomic) ManuallyDrop
663 // if we can ask Rust to preserve field destruction order if the
664 // destructor is the SpecialMemberDefinition::NontrivialMembers
665 // case.
666 formatted = quote! { std::mem::ManuallyDrop<#formatted> }
Lukasz Anforowicz6d553632022-01-06 21:36:14 +0000667 };
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +0000668 Ok(formatted)
669 })
Devin Jeanpierre09c6f452021-09-29 07:34:24 +0000670 .collect::<Result<Vec<_>>>()?;
Googlerec589eb2021-09-17 07:45:39 +0000671 let field_accesses = record
672 .fields
673 .iter()
674 .map(|f| {
Devin Jeanpierreb69bcae2022-02-03 09:45:50 +0000675 if f.access == AccessSpecifier::Public && !f.is_no_unique_address {
Googlerec589eb2021-09-17 07:45:39 +0000676 quote! { pub }
677 } else {
678 quote! {}
679 }
680 })
681 .collect_vec();
Googlerec648ff2021-09-23 07:19:53 +0000682 let size = record.size;
683 let alignment = record.alignment;
Googleraaa0a532021-10-01 09:11:27 +0000684 let field_assertions =
685 record.fields.iter().zip(field_idents.iter()).map(|(field, field_ident)| {
686 let offset = field.offset;
687 quote! {
688 // The IR contains the offset in bits, while offset_of!()
689 // returns the offset in bytes, so we need to convert.
Googler209b10a2021-12-06 09:11:57 +0000690 const _: () = assert!(offset_of!(#ident, #field_ident) * 8 == #offset);
Googleraaa0a532021-10-01 09:11:27 +0000691 }
692 });
Michael Forsterdb8101a2021-10-08 06:56:03 +0000693 let mut record_features = BTreeSet::new();
694 let mut assertion_features = BTreeSet::new();
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000695
696 // TODO(mboehme): For the time being, we're using unstable features to
697 // be able to use offset_of!() in static assertions. This is fine for a
698 // prototype, but longer-term we want to either get those features
699 // stabilized or find an alternative. For more details, see
700 // b/200120034#comment15
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000701 assertion_features.insert(make_rs_ident("const_ptr_offset_from"));
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000702
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000703 let derives = generate_derives(record);
Devin Jeanpierre9227d2c2021-10-06 12:26:05 +0000704 let derives = if derives.is_empty() {
705 quote! {}
706 } else {
707 quote! {#[derive( #(#derives),* )]}
708 };
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000709 let unpin_impl;
Devin Jeanpierree6e16652021-12-22 15:54:46 +0000710 if record.is_unpin() {
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000711 unpin_impl = quote! {};
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000712 } else {
Michael Forsterbee84482021-10-13 08:35:38 +0000713 // negative_impls are necessary for universal initialization due to Rust's
714 // coherence rules: PhantomPinned isn't enough to prove to Rust that a
715 // blanket impl that requires Unpin doesn't apply. See http://<internal link>=h.f6jp8ifzgt3n
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000716 record_features.insert(make_rs_ident("negative_impls"));
Michael Forsterdb8101a2021-10-08 06:56:03 +0000717 unpin_impl = quote! {
718 __NEWLINE__ __NEWLINE__
719 impl !Unpin for #ident {}
720 };
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000721 }
722
Devin Jeanpierrec80e6242022-02-03 01:56:40 +0000723 let mut repr_attributes = vec![quote! {C}];
724 if record.override_alignment && record.alignment > 1 {
725 let alignment = Literal::usize_unsuffixed(record.alignment);
726 repr_attributes.push(quote! {align(#alignment)});
727 }
728
729 // Adjust the struct to also include base class subobjects. We use an opaque
730 // field because subobjects can live in the alignment of base class
731 // subobjects.
732 let base_subobjects_field = if let Some(base_size) = record.base_size {
733 let n = proc_macro2::Literal::usize_unsuffixed(base_size);
734 quote! {
735 __base_class_subobjects: [std::mem::MaybeUninit<u8>; #n],
736 }
737 } else {
738 quote! {}
739 };
740
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000741 let empty_struct_placeholder_field =
742 if record.fields.is_empty() && record.base_size.unwrap_or(0) == 0 {
743 quote! {
744 /// Prevent empty C++ struct being zero-size in Rust.
745 placeholder: std::mem::MaybeUninit<u8>,
746 }
747 } else {
748 quote! {}
749 };
Googlerf4792062021-10-20 07:21:21 +0000750
Devin Jeanpierre56777022022-02-03 01:57:15 +0000751 let base_class_into = cc_struct_upcast_impl(record, ir)?;
752
Michael Forsterdb8101a2021-10-08 06:56:03 +0000753 let record_tokens = quote! {
Michael Forster028800b2021-10-05 12:39:59 +0000754 #doc_comment
Devin Jeanpierre9227d2c2021-10-06 12:26:05 +0000755 #derives
Devin Jeanpierrec80e6242022-02-03 01:56:40 +0000756 #[repr(#( #repr_attributes ),*)]
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000757 pub struct #ident {
Devin Jeanpierrec80e6242022-02-03 01:56:40 +0000758 #base_subobjects_field
Michael Forstercc5941a2021-10-07 07:12:24 +0000759 #( #field_doc_coments #field_accesses #field_idents: #field_types, )*
Googlerf4792062021-10-20 07:21:21 +0000760 #empty_struct_placeholder_field
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000761 }
Googlerec648ff2021-09-23 07:19:53 +0000762
Devin Jeanpierre56777022022-02-03 01:57:15 +0000763 #base_class_into
764
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000765 #unpin_impl
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000766 };
767
Michael Forsterdb8101a2021-10-08 06:56:03 +0000768 let assertion_tokens = quote! {
Googler209b10a2021-12-06 09:11:57 +0000769 const _: () = assert!(std::mem::size_of::<#ident>() == #size);
770 const _: () = assert!(std::mem::align_of::<#ident>() == #alignment);
Michael Forsterdb8101a2021-10-08 06:56:03 +0000771 #( #field_assertions )*
772 };
773
774 Ok((
775 RsSnippet { features: record_features, tokens: record_tokens },
776 RsSnippet { features: assertion_features, tokens: assertion_tokens },
777 ))
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000778}
779
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000780fn should_derive_clone(record: &Record) -> bool {
Devin Jeanpierre88343c72022-01-15 01:10:23 +0000781 record.is_unpin()
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000782 && record.copy_constructor.access == ir::AccessSpecifier::Public
783 && record.copy_constructor.definition == SpecialMemberDefinition::Trivial
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000784}
785
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000786fn should_derive_copy(record: &Record) -> bool {
787 // TODO(b/202258760): Make `Copy` inclusion configurable.
788 should_derive_clone(record)
789}
790
791fn generate_derives(record: &Record) -> Vec<Ident> {
792 let mut derives = vec![];
Lukasz Anforowicz2e41bb62022-01-11 18:23:07 +0000793 if should_derive_clone(record) {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000794 derives.push(make_rs_ident("Clone"));
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000795 }
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000796 if should_derive_copy(record) {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000797 derives.push(make_rs_ident("Copy"));
Lukasz Anforowicze57215c2022-01-12 14:54:16 +0000798 }
799 derives
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +0000800}
801
Googler6a0a5252022-01-11 14:08:09 +0000802fn generate_type_alias(type_alias: &TypeAlias, ir: &IR) -> Result<TokenStream> {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000803 let ident = make_rs_ident(&type_alias.identifier.identifier);
Googler6a0a5252022-01-11 14:08:09 +0000804 let underlying_type = format_rs_type(&type_alias.underlying_type.rs_type, ir, &HashMap::new())
805 .with_context(|| format!("Failed to format underlying type for {:?}", type_alias))?;
806 Ok(quote! {pub type #ident = #underlying_type;})
807}
808
Michael Forster523dbd42021-10-12 11:05:44 +0000809/// Generates Rust source code for a given `UnsupportedItem`.
810fn generate_unsupported(item: &UnsupportedItem) -> Result<TokenStream> {
Googler48a74dd2021-10-25 07:31:53 +0000811 let location = if item.source_loc.filename.is_empty() {
812 "<unknown location>".to_string()
813 } else {
814 // TODO(forster): The "google3" prefix should probably come from a command line
815 // argument.
816 // TODO(forster): Consider linking to the symbol instead of to the line number
817 // to avoid wrong links while generated files have not caught up.
818 format!("google3/{};l={}", &item.source_loc.filename, &item.source_loc.line)
819 };
Michael Forster6a184ad2021-10-12 13:04:05 +0000820 let message = format!(
Googler48a74dd2021-10-25 07:31:53 +0000821 "{}\nError while generating bindings for item '{}':\n{}",
822 &location, &item.name, &item.message
Michael Forster6a184ad2021-10-12 13:04:05 +0000823 );
Michael Forster523dbd42021-10-12 11:05:44 +0000824 Ok(quote! { __COMMENT__ #message })
825}
826
Michael Forsterf1dce422021-10-13 09:50:16 +0000827/// Generates Rust source code for a given `Comment`.
828fn generate_comment(comment: &Comment) -> Result<TokenStream> {
829 let text = &comment.text;
830 Ok(quote! { __COMMENT__ #text })
831}
832
Marcel Hlopko89547752021-12-10 09:39:41 +0000833fn generate_rs_api(ir: &IR) -> Result<TokenStream> {
Michael Forstered642022021-10-04 09:48:25 +0000834 let mut items = vec![];
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000835 let mut thunks = vec![];
Michael Forsterdb8101a2021-10-08 06:56:03 +0000836 let mut assertions = vec![];
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000837
Googler454f2652021-12-06 12:53:12 +0000838 // We import nullable pointers as an Option<&T> and assume that at the ABI
839 // level, None is represented as a zero pointer value whereas Some is
840 // represented as as non-zero pointer value. This seems like a pretty safe
841 // assumption to make, but to provide some safeguard, assert that
842 // `Option<&i32>` and `&i32` have the same size.
843 assertions.push(quote! {
844 const _: () = assert!(std::mem::size_of::<Option<&i32>>() == std::mem::size_of::<&i32>());
845 });
846
Michael Forsterbee84482021-10-13 08:35:38 +0000847 // TODO(jeanpierreda): Delete has_record, either in favor of using RsSnippet, or not
848 // having uses. See https://chat.google.com/room/AAAAnQmj8Qs/6QbkSvWcfhA
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000849 let mut has_record = false;
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000850 let mut features = BTreeSet::new();
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000851
Devin Jeanpierred6da7002021-10-21 12:55:20 +0000852 // For #![rustfmt::skip].
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000853 features.insert(make_rs_ident("custom_inner_attributes"));
Devin Jeanpierred6da7002021-10-21 12:55:20 +0000854
Googlerd03d05b2022-01-07 10:10:57 +0000855 // Identify all functions having overloads that we can't import (yet).
856 // TODO(b/213280424): Implement support for overloaded functions.
857 let mut seen_funcs = HashSet::new();
858 let mut overloaded_funcs = HashSet::new();
859 for func in ir.functions() {
860 if let Some((_, _, function_id)) = generate_func(func, ir)? {
861 if !seen_funcs.insert(function_id.clone()) {
862 overloaded_funcs.insert(function_id);
863 }
864 }
865 }
866
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +0000867 for item in ir.items() {
Michael Forstered642022021-10-04 09:48:25 +0000868 match item {
869 Item::Func(func) => {
Googlerd03d05b2022-01-07 10:10:57 +0000870 if let Some((snippet, thunk, function_id)) = generate_func(func, ir)? {
871 if overloaded_funcs.contains(&function_id) {
872 items.push(generate_unsupported(&UnsupportedItem {
873 name: cxx_function_name(func, ir)?,
874 message: "Cannot generate bindings for overloaded function".to_string(),
875 source_loc: func.source_loc.clone(),
876 })?);
877 continue;
878 }
879 features.extend(snippet.features);
880 features.extend(thunk.features);
881 items.push(snippet.tokens);
882 thunks.push(thunk.tokens);
883 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000884 }
Michael Forstered642022021-10-04 09:48:25 +0000885 Item::Record(record) => {
Googler6a0a5252022-01-11 14:08:09 +0000886 if !ir.is_current_target(&record.owning_target)
887 && !ir.is_stdlib_target(&record.owning_target)
888 {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +0000889 continue;
890 }
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +0000891 let (snippet, assertions_snippet) = generate_record(record, ir)?;
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000892 features.extend(snippet.features);
Michael Forsterdb8101a2021-10-08 06:56:03 +0000893 features.extend(assertions_snippet.features);
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000894 items.push(snippet.tokens);
Michael Forsterdb8101a2021-10-08 06:56:03 +0000895 assertions.push(assertions_snippet.tokens);
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000896 has_record = true;
Michael Forstered642022021-10-04 09:48:25 +0000897 }
Googler098c4582022-01-10 12:29:34 +0000898 Item::TypeAlias(type_alias) => {
Googler6a0a5252022-01-11 14:08:09 +0000899 if !ir.is_current_target(&type_alias.owning_target)
900 && !ir.is_stdlib_target(&type_alias.owning_target)
901 {
902 continue;
903 }
904 items.push(generate_type_alias(type_alias, ir)?);
Googler098c4582022-01-10 12:29:34 +0000905 }
Michael Forster523dbd42021-10-12 11:05:44 +0000906 Item::UnsupportedItem(unsupported) => items.push(generate_unsupported(unsupported)?),
Michael Forsterf1dce422021-10-13 09:50:16 +0000907 Item::Comment(comment) => items.push(generate_comment(comment)?),
Michael Forstered642022021-10-04 09:48:25 +0000908 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000909 }
910
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000911 let mod_detail = if thunks.is_empty() {
912 quote! {}
913 } else {
914 quote! {
915 mod detail {
Googler55647142022-01-11 12:37:39 +0000916 #[allow(unused_imports)]
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +0000917 use super::*;
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000918 extern "C" {
919 #( #thunks )*
920 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000921 }
922 }
923 };
924
Devin Jeanpierreea700d32021-10-06 11:33:56 +0000925 let imports = if has_record {
Googlerec648ff2021-09-23 07:19:53 +0000926 quote! {
Googleraaa0a532021-10-01 09:11:27 +0000927 use memoffset_unstable_const::offset_of;
Googlerec648ff2021-09-23 07:19:53 +0000928 }
Michael Forstered642022021-10-04 09:48:25 +0000929 } else {
930 quote! {}
Googlerec648ff2021-09-23 07:19:53 +0000931 };
932
Devin Jeanpierre273eeae2021-10-06 13:29:35 +0000933 let features = if features.is_empty() {
934 quote! {}
935 } else {
936 quote! {
937 #![feature( #(#features),* )]
938 }
939 };
940
Marcel Hlopko89547752021-12-10 09:39:41 +0000941 Ok(quote! {
Googler55647142022-01-11 12:37:39 +0000942 #features __NEWLINE__
943 #![allow(non_camel_case_types)] __NEWLINE__
944 #![allow(non_snake_case)] __NEWLINE__ __NEWLINE__
945
Michael Forsterdb8101a2021-10-08 06:56:03 +0000946 #imports __NEWLINE__ __NEWLINE__
Googlerec648ff2021-09-23 07:19:53 +0000947
Michael Forsterdb8101a2021-10-08 06:56:03 +0000948 #( #items __NEWLINE__ __NEWLINE__ )*
Marcel Hlopkob4b28742021-09-15 12:45:20 +0000949
Michael Forsterdb8101a2021-10-08 06:56:03 +0000950 #mod_detail __NEWLINE__ __NEWLINE__
951
952 #( #assertions __NEWLINE__ __NEWLINE__ )*
Marcel Hlopko89547752021-12-10 09:39:41 +0000953 })
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000954}
955
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000956/// Makes an 'Ident' to be used in the Rust source code. Escapes Rust keywords.
957fn make_rs_ident(ident: &str) -> Ident {
958 // TODO(https://github.com/dtolnay/syn/pull/1098): Remove the hardcoded list once syn recognizes
959 // 2018 and 2021 keywords.
960 if ["async", "await", "try", "dyn"].contains(&ident) {
961 return format_ident!("r#{}", ident);
962 }
963 match syn::parse_str::<syn::Ident>(ident) {
964 Ok(_) => format_ident!("{}", ident),
965 Err(_) => format_ident!("r#{}", ident),
966 }
967}
968
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +0000969/// Formats a C++ identifier. Does not escape C++ keywords.
970fn format_cc_ident(ident: &str) -> TokenStream {
971 ident.parse().unwrap()
Marcel Hlopko42abfc82021-08-09 07:03:17 +0000972}
973
Googler6a0a5252022-01-11 14:08:09 +0000974fn rs_type_name_for_target_and_identifier(
975 owning_target: &BlazeLabel,
976 identifier: &ir::Identifier,
977 ir: &IR,
978) -> Result<TokenStream> {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +0000979 let ident = make_rs_ident(identifier.identifier.as_str());
Googler6a0a5252022-01-11 14:08:09 +0000980
981 if ir.is_current_target(owning_target) || ir.is_stdlib_target(owning_target) {
982 Ok(quote! {#ident})
983 } else {
Marcel Hlopkod906b892022-01-27 08:52:36 +0000984 let owning_crate_name = owning_target.target_name()?;
985 // TODO(b/216587072): Remove this hacky escaping and use the import! macro once
986 // available
987 let escaped_owning_crate_name = owning_crate_name.replace("-", "_");
988 let owning_crate = make_rs_ident(&escaped_owning_crate_name);
Googler6a0a5252022-01-11 14:08:09 +0000989 Ok(quote! {#owning_crate::#ident})
990 }
991}
992
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +0000993#[derive(Debug, Eq, PartialEq)]
994enum Mutability {
995 Const,
996 Mut,
997}
998
999impl Mutability {
1000 fn format_for_pointer(&self) -> TokenStream {
1001 match self {
1002 Mutability::Mut => quote! {mut},
1003 Mutability::Const => quote! {const},
1004 }
1005 }
1006
1007 fn format_for_reference(&self) -> TokenStream {
1008 match self {
1009 Mutability::Mut => quote! {mut},
1010 Mutability::Const => quote! {},
1011 }
1012 }
1013}
1014
1015// TODO(b/213947473): Instead of having a separate RsTypeKind here, consider
1016// changing ir::RsType into a similar `enum`, with fields that contain
1017// references (e.g. &'ir Record`) instead of DeclIds.
1018#[derive(Debug)]
1019enum RsTypeKind<'ir> {
1020 Pointer { pointee: Box<RsTypeKind<'ir>>, mutability: Mutability },
1021 Reference { referent: Box<RsTypeKind<'ir>>, mutability: Mutability, lifetime_id: LifetimeId },
1022 Record(&'ir Record),
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001023 TypeAlias { type_alias: &'ir TypeAlias, underlying_type: Box<RsTypeKind<'ir>> },
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001024 Unit,
1025 Other { name: &'ir str, type_args: Vec<RsTypeKind<'ir>> },
1026}
1027
1028impl<'ir> RsTypeKind<'ir> {
1029 pub fn new(ty: &'ir ir::RsType, ir: &'ir IR) -> Result<Self> {
1030 // The lambdas deduplicate code needed by multiple `match` branches.
1031 let get_type_args = || -> Result<Vec<RsTypeKind<'ir>>> {
1032 ty.type_args.iter().map(|type_arg| RsTypeKind::<'ir>::new(type_arg, ir)).collect()
1033 };
1034 let get_pointee = || -> Result<Box<RsTypeKind<'ir>>> {
1035 if ty.type_args.len() != 1 {
1036 bail!("Missing pointee/referent type (need exactly 1 type argument): {:?}", ty);
1037 }
1038 Ok(Box::new(get_type_args()?.remove(0)))
1039 };
1040 let get_lifetime = || -> Result<LifetimeId> {
1041 if ty.lifetime_args.len() != 1 {
1042 bail!("Missing reference lifetime (need exactly 1 lifetime argument): {:?}", ty);
1043 }
1044 Ok(ty.lifetime_args[0])
1045 };
1046
1047 let result = match ty.name.as_deref() {
1048 None => {
1049 ensure!(
1050 ty.type_args.is_empty(),
1051 "Type arguments on records nor type aliases are not yet supported: {:?}",
1052 ty
1053 );
1054 match ir.item_for_type(ty)? {
1055 Item::Record(record) => RsTypeKind::Record(record),
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001056 Item::TypeAlias(type_alias) => RsTypeKind::TypeAlias {
1057 type_alias,
1058 underlying_type: Box::new(RsTypeKind::new(
1059 &type_alias.underlying_type.rs_type,
1060 ir,
1061 )?),
1062 },
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001063 other_item => bail!("Item does not define a type: {:?}", other_item),
1064 }
1065 }
1066 Some(name) => match name {
1067 "()" => {
1068 if !ty.type_args.is_empty() {
1069 bail!("Unit type must not have type arguments: {:?}", ty);
1070 }
1071 RsTypeKind::Unit
1072 }
1073 "*mut" => {
1074 RsTypeKind::Pointer { pointee: get_pointee()?, mutability: Mutability::Mut }
1075 }
1076 "*const" => {
1077 RsTypeKind::Pointer { pointee: get_pointee()?, mutability: Mutability::Const }
1078 }
1079 "&mut" => RsTypeKind::Reference {
1080 referent: get_pointee()?,
1081 mutability: Mutability::Mut,
1082 lifetime_id: get_lifetime()?,
1083 },
1084 "&" => RsTypeKind::Reference {
1085 referent: get_pointee()?,
1086 mutability: Mutability::Const,
1087 lifetime_id: get_lifetime()?,
1088 },
1089 name => RsTypeKind::Other { name, type_args: get_type_args()? },
1090 },
1091 };
1092 Ok(result)
1093 }
1094
1095 pub fn format(
1096 &self,
1097 ir: &IR,
1098 lifetime_to_name: &HashMap<LifetimeId, String>,
1099 ) -> Result<TokenStream> {
1100 let result = match self {
1101 RsTypeKind::Pointer { pointee, mutability } => {
1102 let mutability = mutability.format_for_pointer();
1103 let nested_type = pointee.format(ir, lifetime_to_name)?;
1104 quote! {* #mutability #nested_type}
1105 }
1106 RsTypeKind::Reference { referent, mutability, lifetime_id } => {
1107 let mutability = mutability.format_for_reference();
1108 let lifetime = Self::format_lifetime(lifetime_id, lifetime_to_name)?;
1109 let nested_type = referent.format(ir, lifetime_to_name)?;
1110 quote! {& #lifetime #mutability #nested_type}
1111 }
1112 RsTypeKind::Record(record) => rs_type_name_for_target_and_identifier(
1113 &record.owning_target,
1114 &record.identifier,
1115 ir,
1116 )?,
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001117 RsTypeKind::TypeAlias { type_alias, .. } => rs_type_name_for_target_and_identifier(
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001118 &type_alias.owning_target,
1119 &type_alias.identifier,
1120 ir,
1121 )?,
1122 RsTypeKind::Unit => quote! {()},
1123 RsTypeKind::Other { name, type_args } => {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00001124 let ident = make_rs_ident(name);
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001125 let generic_params = format_generic_params(
1126 type_args
1127 .iter()
1128 .map(|type_arg| type_arg.format(ir, lifetime_to_name))
1129 .collect::<Result<Vec<_>>>()?,
1130 );
1131 quote! {#ident #generic_params}
1132 }
1133 };
1134 Ok(result)
1135 }
1136
1137 /// Formats the Rust type of `__this` parameter of a constructor - injecting
1138 /// MaybeUninit to return something like `&'a mut MaybeUninit<SomeStruct>`.
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001139 pub fn format_as_this_param_for_constructor_thunk(
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001140 &self,
1141 ir: &IR,
1142 lifetime_to_name: &HashMap<LifetimeId, String>,
1143 ) -> Result<TokenStream> {
1144 let nested_type = match self {
1145 RsTypeKind::Pointer {
1146 pointee: pointee_or_referent,
1147 mutability: Mutability::Mut,
1148 ..
1149 }
1150 | RsTypeKind::Reference {
1151 referent: pointee_or_referent,
1152 mutability: Mutability::Mut,
1153 ..
1154 } => pointee_or_referent.format(ir, lifetime_to_name)?,
1155 _ => bail!("Unexpected type of `__this` parameter in a constructor: {:?}", self),
1156 };
1157 let lifetime = match self {
1158 RsTypeKind::Pointer { .. } => quote! {},
1159 RsTypeKind::Reference { lifetime_id, .. } => {
1160 Self::format_lifetime(lifetime_id, lifetime_to_name)?
1161 }
1162 _ => unreachable!(), // Because of the earlier `match`.
1163 };
1164 // `mut` can be hardcoded, because of the `match` patterns above.
1165 Ok(quote! { & #lifetime mut std::mem::MaybeUninit< #nested_type > })
1166 }
1167
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001168 /// Formats this RsTypeKind as either `&'a self` or `&'a mut self`.
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001169 pub fn format_as_self_param_for_instance_method(
1170 &self,
Lukasz Anforowiczce345392022-01-14 22:41:16 +00001171 func: &Func,
1172 ir: &IR,
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001173 lifetime_to_name: &HashMap<LifetimeId, String>,
Lukasz Anforowiczf9564622022-01-28 14:31:04 +00001174 ) -> Result<TokenStream> {
Lukasz Anforowicz732ca642022-02-03 20:58:38 +00001175 if func.name == UnqualifiedIdentifier::Destructor {
1176 let record = func
1177 .member_func_metadata
1178 .as_ref()
1179 .ok_or_else(|| anyhow!("Destructors must be member functions: {:?}", func))?
1180 .find_record(ir)?;
1181 if self.is_mut_ptr_to(record) {
1182 // Even in C++ it is UB to retain `this` pointer and dereference it
1183 // after a destructor runs. Therefore it is safe to use `&self` or
1184 // `&mut self` in Rust even if IR represents `__this` as a Rust
1185 // pointer (e.g. when lifetime annotations are missing - lifetime
1186 // annotations are required to represent it as a Rust reference).
1187 return Ok(quote! { &mut self });
1188 }
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001189 }
1190
1191 match self {
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001192 RsTypeKind::Reference { mutability, lifetime_id, .. } => {
1193 let mutability = mutability.format_for_reference();
1194 let lifetime = Self::format_lifetime(lifetime_id, lifetime_to_name)?;
Lukasz Anforowiczf9564622022-01-28 14:31:04 +00001195 Ok(quote! { & #lifetime #mutability self })
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001196 }
Lukasz Anforowicz732ca642022-02-03 20:58:38 +00001197 _ => bail!("Unexpected type of `self` parameter: {:?}", self),
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00001198 }
1199 }
1200
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001201 fn format_lifetime(
1202 lifetime_id: &LifetimeId,
1203 lifetime_to_name: &HashMap<LifetimeId, String>,
1204 ) -> Result<TokenStream> {
1205 let lifetime_name = lifetime_to_name.get(lifetime_id).ok_or_else(|| {
1206 anyhow!("`lifetime_to_name` doesn't have an entry for {:?}", lifetime_id)
1207 })?;
Lukasz Anforowicz95551272022-01-20 00:02:24 +00001208 Ok(format_lifetime_name(lifetime_name))
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001209 }
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001210
Lukasz Anforowicza94ab702022-01-14 22:40:25 +00001211 pub fn implements_copy(&self) -> bool {
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001212 // TODO(b/212696226): Verify results of `implements_copy` via static
1213 // assertions in the generated Rust code (because incorrect results
1214 // can silently lead to unsafe behavior).
1215 match self {
1216 RsTypeKind::Unit => true,
1217 RsTypeKind::Pointer { .. } => true,
1218 RsTypeKind::Reference { mutability: Mutability::Const, .. } => true,
1219 RsTypeKind::Reference { mutability: Mutability::Mut, .. } => false,
1220 RsTypeKind::Record(record) => should_derive_copy(record),
1221 RsTypeKind::TypeAlias { underlying_type, .. } => underlying_type.implements_copy(),
1222 RsTypeKind::Other { .. } => {
1223 // All "other" primitive types (e.g. i32) implement `Copy`.
1224 true
1225 }
1226 }
1227 }
Lukasz Anforowicza94ab702022-01-14 22:40:25 +00001228
Lukasz Anforowiczf9564622022-01-28 14:31:04 +00001229 pub fn is_mut_ptr_to(&self, expected_record: &Record) -> bool {
1230 match self {
1231 RsTypeKind::Pointer { pointee, mutability: Mutability::Mut, .. } => {
1232 pointee.is_record(expected_record)
1233 }
1234 _ => false,
1235 }
1236 }
1237
1238 pub fn is_ref_to(&self, expected_record: &Record) -> bool {
1239 match self {
1240 RsTypeKind::Reference { referent, .. } => referent.is_record(expected_record),
1241 _ => false,
1242 }
1243 }
1244
Lukasz Anforowicza94ab702022-01-14 22:40:25 +00001245 pub fn is_shared_ref_to(&self, expected_record: &Record) -> bool {
1246 match self {
1247 RsTypeKind::Reference { referent, mutability: Mutability::Const, .. } => {
Lukasz Anforowiczf9564622022-01-28 14:31:04 +00001248 referent.is_record(expected_record)
Lukasz Anforowicza94ab702022-01-14 22:40:25 +00001249 }
1250 _ => false,
1251 }
1252 }
Lukasz Anforowiczf9564622022-01-28 14:31:04 +00001253
1254 pub fn is_record(&self, expected_record: &Record) -> bool {
1255 match self {
1256 RsTypeKind::Record(actual_record) => actual_record.id == expected_record.id,
1257 _ => false,
1258 }
1259 }
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001260}
1261
Lukasz Anforowicz95551272022-01-20 00:02:24 +00001262fn format_lifetime_name(lifetime_name: &str) -> TokenStream {
1263 let lifetime =
1264 syn::Lifetime::new(&format!("'{}", lifetime_name), proc_macro2::Span::call_site());
1265 quote! { #lifetime }
1266}
1267
Googler7cced422021-12-06 11:58:39 +00001268fn format_rs_type(
1269 ty: &ir::RsType,
1270 ir: &IR,
1271 lifetime_to_name: &HashMap<LifetimeId, String>,
1272) -> Result<TokenStream> {
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00001273 RsTypeKind::new(ty, ir)
1274 .and_then(|kind| kind.format(ir, lifetime_to_name))
1275 .with_context(|| format!("Failed to format Rust type {:?}", ty))
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001276}
1277
Googler6a0a5252022-01-11 14:08:09 +00001278fn cc_type_name_for_item(item: &ir::Item) -> Result<TokenStream> {
1279 let (disambiguator_fragment, identifier) = match item {
1280 Item::Record(record) => (quote! { class }, &record.identifier),
1281 Item::TypeAlias(type_alias) => (quote! {}, &type_alias.identifier),
1282 _ => bail!("Item does not define a type: {:?}", item),
1283 };
1284
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001285 let ident = format_cc_ident(identifier.identifier.as_str());
Googler6a0a5252022-01-11 14:08:09 +00001286 Ok(quote! { #disambiguator_fragment #ident })
1287}
1288
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001289fn format_cc_type(ty: &ir::CcType, ir: &IR) -> Result<TokenStream> {
Devin Jeanpierre09c6f452021-09-29 07:34:24 +00001290 let const_fragment = if ty.is_const {
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001291 quote! {const}
1292 } else {
1293 quote! {}
1294 };
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001295 if let Some(ref name) = ty.name {
1296 match name.as_str() {
1297 "*" => {
Googlerff7fc232021-12-02 09:43:00 +00001298 if ty.type_args.len() != 1 {
1299 bail!("Invalid pointer type (need exactly 1 type argument): {:?}", ty);
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001300 }
Googlerff7fc232021-12-02 09:43:00 +00001301 assert_eq!(ty.type_args.len(), 1);
1302 let nested_type = format_cc_type(&ty.type_args[0], ir)?;
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001303 Ok(quote! {#nested_type * #const_fragment})
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001304 }
Lukasz Anforowicz275fa922022-01-05 16:13:20 +00001305 "&" => {
1306 if ty.type_args.len() != 1 {
1307 bail!("Invalid reference type (need exactly 1 type argument): {:?}", ty);
1308 }
1309 let nested_type = format_cc_type(&ty.type_args[0], ir)?;
1310 Ok(quote! {#nested_type &})
1311 }
Lukasz Anforowicz957cbf22022-01-05 16:14:05 +00001312 cc_type_name => {
Googlerff7fc232021-12-02 09:43:00 +00001313 if !ty.type_args.is_empty() {
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001314 bail!("Type not yet supported: {:?}", ty);
1315 }
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001316 let idents = cc_type_name.split_whitespace().map(format_cc_ident);
Lukasz Anforowicz957cbf22022-01-05 16:14:05 +00001317 Ok(quote! {#( #idents )* #const_fragment})
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001318 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001319 }
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001320 } else {
Googler6a0a5252022-01-11 14:08:09 +00001321 let item = ir.item_for_type(ty)?;
1322 let type_name = cc_type_name_for_item(item)?;
1323 Ok(quote! {#const_fragment #type_name})
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001324 }
1325}
1326
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001327fn cc_struct_layout_assertion(record: &Record, ir: &IR) -> TokenStream {
Googler6a0a5252022-01-11 14:08:09 +00001328 if !ir.is_current_target(&record.owning_target) && !ir.is_stdlib_target(&record.owning_target) {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001329 return quote! {};
1330 }
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001331 let record_ident = format_cc_ident(&record.identifier.identifier);
Googler5ea88642021-09-29 08:05:59 +00001332 let size = Literal::usize_unsuffixed(record.size);
1333 let alignment = Literal::usize_unsuffixed(record.alignment);
Lukasz Anforowicz74704712021-12-22 15:30:31 +00001334 let field_assertions =
1335 record.fields.iter().filter(|f| f.access == AccessSpecifier::Public).map(|field| {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001336 let field_ident = format_cc_ident(&field.identifier.identifier);
Lukasz Anforowicz74704712021-12-22 15:30:31 +00001337 let offset = Literal::usize_unsuffixed(field.offset);
1338 // The IR contains the offset in bits, while C++'s offsetof()
1339 // returns the offset in bytes, so we need to convert.
1340 quote! {
Googler972d3582022-01-11 10:17:22 +00001341 static_assert(offsetof(class #record_ident, #field_ident) * 8 == #offset);
Lukasz Anforowicz74704712021-12-22 15:30:31 +00001342 }
1343 });
Googler5ea88642021-09-29 08:05:59 +00001344 quote! {
Googler972d3582022-01-11 10:17:22 +00001345 static_assert(sizeof(class #record_ident) == #size);
1346 static_assert(alignof(class #record_ident) == #alignment);
Googler5ea88642021-09-29 08:05:59 +00001347 #( #field_assertions )*
1348 }
1349}
1350
Devin Jeanpierre56777022022-02-03 01:57:15 +00001351/// Returns the implementation of base class conversions, for converting a type
1352/// to its unambiguous public base classes.
1353///
1354/// TODO(b/216195042): Implement this in terms of a supporting trait which casts
1355/// raw pointers. Then, we would have blanket impls for reference, pinned mut
1356/// reference, etc. conversion. The current version is just enough to test the
1357/// logic in importer.
1358//
1359// TODO(b/216195042): Should this use, like, AsRef/AsMut (and some equivalent
1360// for Pin)?
1361fn cc_struct_upcast_impl(record: &Record, ir: &IR) -> Result<TokenStream> {
1362 let mut impls = Vec::with_capacity(record.unambiguous_public_bases.len());
1363 for base in &record.unambiguous_public_bases {
1364 let base_record: &Record = ir.find_decl(base.base_record_id)?.try_into()?;
1365 if let Some(offset) = base.offset {
1366 let offset = Literal::i64_unsuffixed(offset);
1367 // TODO(b/216195042): Correctly handle imported records, lifetimes.
1368 let base_name = make_rs_ident(&base_record.identifier.identifier);
1369 let derived_name = make_rs_ident(&record.identifier.identifier);
1370 impls.push(quote! {
1371 impl<'a> From<&'a #derived_name> for &'a #base_name {
1372 fn from(x: &'a #derived_name) -> Self {
1373 unsafe {
1374 &*((x as *const _ as *const u8).offset(#offset) as *const #base_name)
1375 }
1376 }
1377 }
1378 });
1379 } else {
1380 // TODO(b/216195042): determine offset dynamically / use a dynamic
1381 // cast. This requires a new C++ function to be
1382 // generated, so that we have something to call.
1383 }
1384 }
1385
1386 Ok(quote! {
1387 #(#impls)*
1388 })
1389}
1390
Googlera675ae02021-12-07 08:04:59 +00001391fn thunk_ident(func: &Func) -> Ident {
1392 format_ident!("__rust_thunk__{}", func.mangled_name)
Devin Jeanpierref2ec8712021-10-13 20:47:16 +00001393}
1394
Marcel Hlopko89547752021-12-10 09:39:41 +00001395fn generate_rs_api_impl(ir: &IR) -> Result<TokenStream> {
Michael Forsterbee84482021-10-13 08:35:38 +00001396 // This function uses quote! to generate C++ source code out of convenience.
1397 // This is a bold idea so we have to continously evaluate if it still makes
1398 // sense or the cost of working around differences in Rust and C++ tokens is
1399 // greather than the value added.
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001400 //
Michael Forsterbee84482021-10-13 08:35:38 +00001401 // See rs_bindings_from_cc/
1402 // token_stream_printer.rs for a list of supported placeholders.
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001403 let mut thunks = vec![];
Michael Forster7ef80732021-10-01 18:12:19 +00001404 for func in ir.functions() {
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001405 if can_skip_cc_thunk(&func) {
1406 continue;
1407 }
1408
Googlera675ae02021-12-07 08:04:59 +00001409 let thunk_ident = thunk_ident(func);
Devin Jeanpierref2ec8712021-10-13 20:47:16 +00001410 let implementation_function = match &func.name {
1411 UnqualifiedIdentifier::Identifier(id) => {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001412 let fn_ident = format_cc_ident(&id.identifier);
Lukasz Anforowiczaab8ad22021-12-19 20:29:26 +00001413 let static_method_metadata = func
1414 .member_func_metadata
1415 .as_ref()
1416 .filter(|meta| meta.instance_method_metadata.is_none());
1417 match static_method_metadata {
1418 None => quote! {#fn_ident},
1419 Some(meta) => {
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00001420 let record_ident =
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001421 format_cc_ident(&meta.find_record(ir)?.identifier.identifier);
Lukasz Anforowiczaab8ad22021-12-19 20:29:26 +00001422 quote! { #record_ident :: #fn_ident }
1423 }
1424 }
Devin Jeanpierref2ec8712021-10-13 20:47:16 +00001425 }
Lukasz Anforowicz7b0042d2022-01-06 23:00:19 +00001426 // Use `destroy_at` to avoid needing to spell out the class name. Destructor identiifers
Devin Jeanpierrecc6cf092021-12-16 04:31:14 +00001427 // use the name of the type itself, without namespace qualification, template
1428 // parameters, or aliases. We do not need to use that naming scheme anywhere else in
1429 // the bindings, and it can be difficult (impossible?) to spell in the general case. By
1430 // using destroy_at, we avoid needing to determine or remember what the correct spelling
Lukasz Anforowicz7b0042d2022-01-06 23:00:19 +00001431 // is. Similar arguments apply to `construct_at`.
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00001432 UnqualifiedIdentifier::Constructor => {
Lukasz Anforowicz7b0042d2022-01-06 23:00:19 +00001433 quote! { rs_api_impl_support::construct_at }
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00001434 }
Devin Jeanpierref2ec8712021-10-13 20:47:16 +00001435 UnqualifiedIdentifier::Destructor => quote! {std::destroy_at},
Devin Jeanpierref2ec8712021-10-13 20:47:16 +00001436 };
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001437 let return_type_name = format_cc_type(&func.return_type.cc_type, ir)?;
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00001438 let return_stmt = if func.return_type.cc_type.is_void() {
1439 quote! {}
1440 } else {
1441 quote! { return }
1442 };
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001443
1444 let param_idents =
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001445 func.params.iter().map(|p| format_cc_ident(&p.identifier.identifier)).collect_vec();
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001446
Devin Jeanpierre09c6f452021-09-29 07:34:24 +00001447 let param_types = func
1448 .params
1449 .iter()
Marcel Hlopkoc0956cf2021-11-29 08:31:28 +00001450 .map(|p| format_cc_type(&p.type_.cc_type, ir))
Devin Jeanpierre09c6f452021-09-29 07:34:24 +00001451 .collect::<Result<Vec<_>>>()?;
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001452
Lukasz Anforowiczb3d89aa2022-01-12 14:35:52 +00001453 let needs_this_deref = match &func.member_func_metadata {
1454 None => false,
1455 Some(meta) => match &func.name {
1456 UnqualifiedIdentifier::Constructor | UnqualifiedIdentifier::Destructor => false,
1457 UnqualifiedIdentifier::Identifier(_) => meta.instance_method_metadata.is_some(),
1458 },
1459 };
1460 let (implementation_function, arg_expressions) = if !needs_this_deref {
1461 (implementation_function, param_idents.clone())
1462 } else {
1463 let this_param = func
1464 .params
1465 .first()
1466 .ok_or_else(|| anyhow!("Instance methods must have `__this` param."))?;
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001467 let this_arg = format_cc_ident(&this_param.identifier.identifier);
Lukasz Anforowiczb3d89aa2022-01-12 14:35:52 +00001468 (
1469 quote! { #this_arg -> #implementation_function},
1470 param_idents.iter().skip(1).cloned().collect_vec(),
1471 )
1472 };
1473
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001474 thunks.push(quote! {
1475 extern "C" #return_type_name #thunk_ident( #( #param_types #param_idents ),* ) {
Lukasz Anforowiczb3d89aa2022-01-12 14:35:52 +00001476 #return_stmt #implementation_function( #( #arg_expressions ),* );
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001477 }
1478 });
1479 }
1480
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001481 let layout_assertions = ir.records().map(|record| cc_struct_layout_assertion(record, ir));
Googler5ea88642021-09-29 08:05:59 +00001482
Devin Jeanpierre231ef8d2021-10-27 10:50:44 +00001483 let mut standard_headers = <BTreeSet<Ident>>::new();
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001484 standard_headers.insert(format_ident!("memory")); // ubiquitous.
Devin Jeanpierre231ef8d2021-10-27 10:50:44 +00001485 if ir.records().next().is_some() {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00001486 standard_headers.insert(format_ident!("cstddef"));
Devin Jeanpierre231ef8d2021-10-27 10:50:44 +00001487 };
Googler5ea88642021-09-29 08:05:59 +00001488
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +00001489 let mut includes =
1490 vec!["rs_bindings_from_cc/support/cxx20_backports.h"];
1491
Michael Forsterbee84482021-10-13 08:35:38 +00001492 // In order to generate C++ thunk in all the cases Clang needs to be able to
1493 // access declarations from public headers of the C++ library.
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +00001494 includes.extend(ir.used_headers().map(|i| &i.name as &str));
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001495
Marcel Hlopko89547752021-12-10 09:39:41 +00001496 Ok(quote! {
Googler5ea88642021-09-29 08:05:59 +00001497 #( __HASH_TOKEN__ include <#standard_headers> __NEWLINE__)*
Devin Jeanpierre7c74f842022-02-03 07:08:06 +00001498 __NEWLINE__
Michael Forsterdb8101a2021-10-08 06:56:03 +00001499 #( __HASH_TOKEN__ include #includes __NEWLINE__)* __NEWLINE__
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001500
Michael Forsterdb8101a2021-10-08 06:56:03 +00001501 #( #thunks )* __NEWLINE__ __NEWLINE__
Googler5ea88642021-09-29 08:05:59 +00001502
Michael Forsterdb8101a2021-10-08 06:56:03 +00001503 #( #layout_assertions __NEWLINE__ __NEWLINE__ )*
Marcel Hlopkoc6b726c2021-10-07 06:53:09 +00001504
1505 // To satisfy http://cs/symbol:devtools.metadata.Presubmit.CheckTerminatingNewline check.
1506 __NEWLINE__
Marcel Hlopko89547752021-12-10 09:39:41 +00001507 })
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001508}
1509
Marcel Hlopko42abfc82021-08-09 07:03:17 +00001510#[cfg(test)]
1511mod tests {
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00001512 use super::*;
Michael Forstered642022021-10-04 09:48:25 +00001513 use anyhow::anyhow;
Marcel Hlopko89547752021-12-10 09:39:41 +00001514 use ir_testing::{ir_from_cc, ir_from_cc_dependency, ir_func, ir_record};
1515 use token_stream_matchers::{
1516 assert_cc_matches, assert_cc_not_matches, assert_rs_matches, assert_rs_not_matches,
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00001517 };
Michael Forsterdb8101a2021-10-08 06:56:03 +00001518 use token_stream_printer::tokens_to_string;
Marcel Hlopko42abfc82021-08-09 07:03:17 +00001519
1520 #[test]
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +00001521 // TODO(hlopko): Move this test to a more principled place where it can access
1522 // `ir_testing`.
1523 fn test_duplicate_decl_ids_err() {
1524 let mut r1 = ir_record("R1");
Marcel Hlopko264b9ad2021-12-02 21:06:44 +00001525 r1.id = DeclId(42);
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +00001526 let mut r2 = ir_record("R2");
Marcel Hlopko264b9ad2021-12-02 21:06:44 +00001527 r2.id = DeclId(42);
Marcel Hlopko3b9bf9e2021-11-29 08:25:14 +00001528 let result = make_ir_from_items([r1.into(), r2.into()]);
1529 assert!(result.is_err());
1530 assert!(result.unwrap_err().to_string().contains("Duplicate decl_id found in"));
1531 }
1532
1533 #[test]
Marcel Hlopko45fba972021-08-23 19:52:20 +00001534 fn test_simple_function() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001535 let ir = ir_from_cc("int Add(int a, int b);")?;
1536 let rs_api = generate_rs_api(&ir)?;
1537 assert_rs_matches!(
1538 rs_api,
1539 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001540 #[inline(always)]
Marcel Hlopko89547752021-12-10 09:39:41 +00001541 pub fn Add(a: i32, b: i32) -> i32 {
Googlera675ae02021-12-07 08:04:59 +00001542 unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) }
Marcel Hlopko89547752021-12-10 09:39:41 +00001543 }
1544 }
1545 );
1546 assert_rs_matches!(
1547 rs_api,
1548 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001549 mod detail {
Googler55647142022-01-11 12:37:39 +00001550 #[allow(unused_imports)]
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +00001551 use super::*;
Michael Forsterdb8101a2021-10-08 06:56:03 +00001552 extern "C" {
1553 #[link_name = "_Z3Addii"]
Googlera675ae02021-12-07 08:04:59 +00001554 pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32;
Marcel Hlopko89547752021-12-10 09:39:41 +00001555 }
1556 }
1557 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +00001558 );
Michael Forsterdb8101a2021-10-08 06:56:03 +00001559
Marcel Hlopko89547752021-12-10 09:39:41 +00001560 assert_cc_not_matches!(generate_rs_api_impl(&ir)?, quote! {__rust_thunk___Z3Addii});
Michael Forsterdb8101a2021-10-08 06:56:03 +00001561
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001562 Ok(())
1563 }
1564
1565 #[test]
1566 fn test_inline_function() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001567 let ir = ir_from_cc("inline int Add(int a, int b);")?;
1568 let rs_api = generate_rs_api(&ir)?;
1569 assert_rs_matches!(
1570 rs_api,
1571 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001572 #[inline(always)]
Marcel Hlopko89547752021-12-10 09:39:41 +00001573 pub fn Add(a: i32, b: i32) -> i32 {
Googlera675ae02021-12-07 08:04:59 +00001574 unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) }
Marcel Hlopko89547752021-12-10 09:39:41 +00001575 }
1576 }
1577 );
1578 assert_rs_matches!(
1579 rs_api,
1580 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001581 mod detail {
Googler55647142022-01-11 12:37:39 +00001582 #[allow(unused_imports)]
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +00001583 use super::*;
Michael Forsterdb8101a2021-10-08 06:56:03 +00001584 extern "C" {
Googlera675ae02021-12-07 08:04:59 +00001585 pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32;
Marcel Hlopko89547752021-12-10 09:39:41 +00001586 }
1587 }
1588 }
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001589 );
1590
Marcel Hlopko89547752021-12-10 09:39:41 +00001591 assert_cc_matches!(
1592 generate_rs_api_impl(&ir)?,
1593 quote! {
Googlera675ae02021-12-07 08:04:59 +00001594 extern "C" int __rust_thunk___Z3Addii(int a, int b) {
Marcel Hlopko89547752021-12-10 09:39:41 +00001595 return Add(a, b);
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001596 }
Marcel Hlopko89547752021-12-10 09:39:41 +00001597 }
Marcel Hlopko3164eee2021-08-24 20:09:22 +00001598 );
Marcel Hlopko42abfc82021-08-09 07:03:17 +00001599 Ok(())
1600 }
Marcel Hlopkob4b28742021-09-15 12:45:20 +00001601
1602 #[test]
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001603 fn test_simple_function_with_types_from_other_target() -> Result<()> {
1604 let ir = ir_from_cc_dependency(
1605 "inline ReturnStruct DoSomething(ParamStruct param);",
1606 "struct ReturnStruct {}; struct ParamStruct {};",
1607 )?;
1608
Marcel Hlopko89547752021-12-10 09:39:41 +00001609 let rs_api = generate_rs_api(&ir)?;
1610 assert_rs_matches!(
1611 rs_api,
1612 quote! {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001613 #[inline(always)]
1614 pub fn DoSomething(param: dependency::ParamStruct)
Marcel Hlopko89547752021-12-10 09:39:41 +00001615 -> dependency::ReturnStruct {
Googlera675ae02021-12-07 08:04:59 +00001616 unsafe { crate::detail::__rust_thunk___Z11DoSomething11ParamStruct(param) }
Marcel Hlopko89547752021-12-10 09:39:41 +00001617 }
1618 }
1619 );
1620 assert_rs_matches!(
1621 rs_api,
1622 quote! {
1623 mod detail {
Googler55647142022-01-11 12:37:39 +00001624 #[allow(unused_imports)]
Marcel Hlopko89547752021-12-10 09:39:41 +00001625 use super::*;
1626 extern "C" {
1627 pub(crate) fn __rust_thunk___Z11DoSomething11ParamStruct(param: dependency::ParamStruct)
1628 -> dependency::ReturnStruct;
1629 }
1630 }}
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001631 );
1632
Marcel Hlopko89547752021-12-10 09:39:41 +00001633 assert_cc_matches!(
1634 generate_rs_api_impl(&ir)?,
1635 quote! {
Googler972d3582022-01-11 10:17:22 +00001636 extern "C" class ReturnStruct __rust_thunk___Z11DoSomething11ParamStruct(class ParamStruct param) {
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001637 return DoSomething(param);
1638 }
Marcel Hlopko89547752021-12-10 09:39:41 +00001639 }
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001640 );
1641 Ok(())
1642 }
1643
1644 #[test]
Marcel Hlopkob4b28742021-09-15 12:45:20 +00001645 fn test_simple_struct() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001646 let ir = ir_from_cc(&tokens_to_string(quote! {
Devin Jeanpierre88343c72022-01-15 01:10:23 +00001647 struct SomeStruct final {
Marcel Hlopko89547752021-12-10 09:39:41 +00001648 int public_int;
1649 protected:
1650 int protected_int;
1651 private:
1652 int private_int;
1653 };
1654 })?)?;
Michael Forster028800b2021-10-05 12:39:59 +00001655
Marcel Hlopko89547752021-12-10 09:39:41 +00001656 let rs_api = generate_rs_api(&ir)?;
1657 assert_rs_matches!(
1658 rs_api,
1659 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001660 #[derive(Clone, Copy)]
1661 #[repr(C)]
1662 pub struct SomeStruct {
1663 pub public_int: i32,
1664 protected_int: i32,
1665 private_int: i32,
Marcel Hlopko89547752021-12-10 09:39:41 +00001666 }
1667 }
1668 );
1669 assert_rs_matches!(
1670 rs_api,
1671 quote! {
Googler454f2652021-12-06 12:53:12 +00001672 const _: () = assert!(std::mem::size_of::<Option<&i32>>() == std::mem::size_of::<&i32>());
Googler209b10a2021-12-06 09:11:57 +00001673 const _: () = assert!(std::mem::size_of::<SomeStruct>() == 12usize);
1674 const _: () = assert!(std::mem::align_of::<SomeStruct>() == 4usize);
1675 const _: () = assert!(offset_of!(SomeStruct, public_int) * 8 == 0usize);
1676 const _: () = assert!(offset_of!(SomeStruct, protected_int) * 8 == 32usize);
1677 const _: () = assert!(offset_of!(SomeStruct, private_int) * 8 == 64usize);
Marcel Hlopko89547752021-12-10 09:39:41 +00001678 }
Marcel Hlopkob4b28742021-09-15 12:45:20 +00001679 );
Marcel Hlopko89547752021-12-10 09:39:41 +00001680 let rs_api_impl = generate_rs_api_impl(&ir)?;
1681 assert_cc_matches!(
1682 rs_api_impl,
1683 quote! {
Googler972d3582022-01-11 10:17:22 +00001684 extern "C" void __rust_thunk___ZN10SomeStructD1Ev(class SomeStruct * __this) {
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00001685 std :: destroy_at (__this) ;
Marcel Hlopko89547752021-12-10 09:39:41 +00001686 }
1687 }
1688 );
1689 assert_cc_matches!(
1690 rs_api_impl,
1691 quote! {
Googler972d3582022-01-11 10:17:22 +00001692 static_assert(sizeof(class SomeStruct) == 12);
1693 static_assert(alignof(class SomeStruct) == 4);
1694 static_assert(offsetof(class SomeStruct, public_int) * 8 == 0);
Marcel Hlopko89547752021-12-10 09:39:41 +00001695 }
Googler5ea88642021-09-29 08:05:59 +00001696 );
Marcel Hlopkob4b28742021-09-15 12:45:20 +00001697 Ok(())
1698 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001699
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001700 #[test]
Lukasz Anforowicz275fa922022-01-05 16:13:20 +00001701 fn test_ref_to_struct_in_thunk_impls() -> Result<()> {
Googler972d3582022-01-11 10:17:22 +00001702 let ir = ir_from_cc("struct S{}; inline void foo(class S& s) {} ")?;
Lukasz Anforowicz275fa922022-01-05 16:13:20 +00001703 let rs_api_impl = generate_rs_api_impl(&ir)?;
1704 assert_cc_matches!(
1705 rs_api_impl,
1706 quote! {
Googler972d3582022-01-11 10:17:22 +00001707 extern "C" void __rust_thunk___Z3fooR1S(class S& s) {
Lukasz Anforowicz275fa922022-01-05 16:13:20 +00001708 foo(s);
1709 }
1710 }
1711 );
1712 Ok(())
1713 }
1714
1715 #[test]
1716 fn test_const_ref_to_struct_in_thunk_impls() -> Result<()> {
Googler972d3582022-01-11 10:17:22 +00001717 let ir = ir_from_cc("struct S{}; inline void foo(const class S& s) {} ")?;
Lukasz Anforowicz275fa922022-01-05 16:13:20 +00001718 let rs_api_impl = generate_rs_api_impl(&ir)?;
1719 assert_cc_matches!(
1720 rs_api_impl,
1721 quote! {
Googler972d3582022-01-11 10:17:22 +00001722 extern "C" void __rust_thunk___Z3fooRK1S(const class S& s) {
Lukasz Anforowicz275fa922022-01-05 16:13:20 +00001723 foo(s);
1724 }
1725 }
1726 );
1727 Ok(())
1728 }
1729
1730 #[test]
Lukasz Anforowicz957cbf22022-01-05 16:14:05 +00001731 fn test_unsigned_int_in_thunk_impls() -> Result<()> {
1732 let ir = ir_from_cc("inline void foo(unsigned int i) {} ")?;
1733 let rs_api_impl = generate_rs_api_impl(&ir)?;
1734 assert_cc_matches!(
1735 rs_api_impl,
1736 quote! {
1737 extern "C" void __rust_thunk___Z3fooj(unsigned int i) {
1738 foo(i);
1739 }
1740 }
1741 );
1742 Ok(())
1743 }
1744
1745 #[test]
Marcel Hlopkodd1fcb12021-12-22 14:13:59 +00001746 fn test_record_static_methods_qualify_call_in_thunk() -> Result<()> {
1747 let ir = ir_from_cc(&tokens_to_string(quote! {
1748 struct SomeStruct {
1749 static inline int some_func() { return 42; }
1750 };
1751 })?)?;
1752
1753 assert_cc_matches!(
1754 generate_rs_api_impl(&ir)?,
1755 quote! {
1756 extern "C" int __rust_thunk___ZN10SomeStruct9some_funcEv() {
1757 return SomeStruct::some_func();
1758 }
1759 }
1760 );
1761 Ok(())
1762 }
1763
1764 #[test]
Lukasz Anforowiczb3d89aa2022-01-12 14:35:52 +00001765 fn test_record_instance_methods_deref_this_in_thunk() -> Result<()> {
1766 let ir = ir_from_cc(&tokens_to_string(quote! {
1767 struct SomeStruct {
1768 inline int some_func(int arg) const { return 42 + arg; }
1769 };
1770 })?)?;
1771
1772 assert_cc_matches!(
1773 generate_rs_api_impl(&ir)?,
1774 quote! {
1775 extern "C" int __rust_thunk___ZNK10SomeStruct9some_funcEi(
1776 const class SomeStruct* __this, int arg) {
1777 return __this->some_func(arg);
1778 }
1779 }
1780 );
1781 Ok(())
1782 }
1783
1784 #[test]
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001785 fn test_struct_from_other_target() -> Result<()> {
1786 let ir = ir_from_cc_dependency("// intentionally empty", "struct SomeStruct {};")?;
Marcel Hlopko89547752021-12-10 09:39:41 +00001787 assert_rs_not_matches!(generate_rs_api(&ir)?, quote! { SomeStruct });
1788 assert_cc_not_matches!(generate_rs_api_impl(&ir)?, quote! { SomeStruct });
Marcel Hlopkoa0f38662021-12-03 08:45:26 +00001789 Ok(())
1790 }
1791
1792 #[test]
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001793 fn test_copy_derives() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001794 let record = ir_record("S");
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001795 assert_eq!(generate_derives(&record), &["Clone", "Copy"]);
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001796 }
1797
1798 #[test]
1799 fn test_copy_derives_not_is_trivial_abi() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001800 let mut record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001801 record.is_trivial_abi = false;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001802 assert_eq!(generate_derives(&record), &[""; 0]);
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001803 }
1804
Devin Jeanpierre88343c72022-01-15 01:10:23 +00001805 /// Even if it's trivially relocatable, !Unpin C++ type cannot be
1806 /// cloned/copied or otherwise used by value, because values would allow
1807 /// assignment into the Pin.
1808 ///
1809 /// All !Unpin C++ types, not just non trivially relocatable ones, are
1810 /// unsafe to assign in the Rust sense.
Devin Jeanpierree6e16652021-12-22 15:54:46 +00001811 #[test]
Devin Jeanpierre88343c72022-01-15 01:10:23 +00001812 fn test_copy_derives_not_final() {
Devin Jeanpierree6e16652021-12-22 15:54:46 +00001813 let mut record = ir_record("S");
1814 record.is_final = false;
Devin Jeanpierre88343c72022-01-15 01:10:23 +00001815 assert_eq!(generate_derives(&record), &[""; 0]);
Devin Jeanpierree6e16652021-12-22 15:54:46 +00001816 }
1817
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001818 #[test]
1819 fn test_copy_derives_ctor_nonpublic() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001820 let mut record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001821 for access in [ir::AccessSpecifier::Protected, ir::AccessSpecifier::Private] {
1822 record.copy_constructor.access = access;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001823 assert_eq!(generate_derives(&record), &[""; 0]);
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001824 }
1825 }
1826
1827 #[test]
1828 fn test_copy_derives_ctor_deleted() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001829 let mut record = ir_record("S");
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001830 record.copy_constructor.definition = ir::SpecialMemberDefinition::Deleted;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001831 assert_eq!(generate_derives(&record), &[""; 0]);
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001832 }
1833
1834 #[test]
Devin Jeanpierrebe2f33b2021-10-21 12:54:19 +00001835 fn test_copy_derives_ctor_nontrivial_members() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001836 let mut record = ir_record("S");
Devin Jeanpierrebe2f33b2021-10-21 12:54:19 +00001837 record.copy_constructor.definition = ir::SpecialMemberDefinition::NontrivialMembers;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001838 assert_eq!(generate_derives(&record), &[""; 0]);
Devin Jeanpierrebe2f33b2021-10-21 12:54:19 +00001839 }
1840
1841 #[test]
1842 fn test_copy_derives_ctor_nontrivial_self() {
Devin Jeanpierreccfefc82021-10-27 10:54:00 +00001843 let mut record = ir_record("S");
Devin Jeanpierre7b62e952021-12-08 21:43:30 +00001844 record.copy_constructor.definition = ir::SpecialMemberDefinition::NontrivialUserDefined;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00001845 assert_eq!(generate_derives(&record), &[""; 0]);
Devin Jeanpierre2ed14ec2021-10-06 11:32:19 +00001846 }
1847
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001848 #[test]
1849 fn test_ptr_func() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001850 let ir = ir_from_cc(&tokens_to_string(quote! {
1851 inline int* Deref(int*const* p);
1852 })?)?;
Devin Jeanpierred6da7002021-10-21 12:55:20 +00001853
Marcel Hlopko89547752021-12-10 09:39:41 +00001854 let rs_api = generate_rs_api(&ir)?;
1855 assert_rs_matches!(
1856 rs_api,
1857 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001858 #[inline(always)]
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +00001859 pub unsafe fn Deref(p: *const *mut i32) -> *mut i32 {
1860 crate::detail::__rust_thunk___Z5DerefPKPi(p)
Marcel Hlopko89547752021-12-10 09:39:41 +00001861 }
1862 }
1863 );
1864 assert_rs_matches!(
1865 rs_api,
1866 quote! {
Michael Forsterdb8101a2021-10-08 06:56:03 +00001867 mod detail {
Googler55647142022-01-11 12:37:39 +00001868 #[allow(unused_imports)]
Devin Jeanpierred4dde0e2021-10-13 20:48:25 +00001869 use super::*;
Michael Forsterdb8101a2021-10-08 06:56:03 +00001870 extern "C" {
Googlera675ae02021-12-07 08:04:59 +00001871 pub(crate) fn __rust_thunk___Z5DerefPKPi(p: *const *mut i32) -> *mut i32;
Marcel Hlopko89547752021-12-10 09:39:41 +00001872 }
1873 }
1874 }
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001875 );
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001876
Marcel Hlopko89547752021-12-10 09:39:41 +00001877 assert_cc_matches!(
1878 generate_rs_api_impl(&ir)?,
1879 quote! {
Googlera675ae02021-12-07 08:04:59 +00001880 extern "C" int* __rust_thunk___Z5DerefPKPi(int* const * p) {
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001881 return Deref(p);
1882 }
Marcel Hlopko89547752021-12-10 09:39:41 +00001883 }
Devin Jeanpierre184f9ac2021-09-17 13:47:03 +00001884 );
Devin Jeanpierre7a7328e2021-09-17 07:10:08 +00001885 Ok(())
1886 }
Michael Forstered642022021-10-04 09:48:25 +00001887
1888 #[test]
Googlerdb111532022-01-05 06:12:13 +00001889 fn test_const_char_ptr_func() -> Result<()> {
1890 // This is a regression test: We used to include the "const" in the name
1891 // of the CcType, which caused a panic in the code generator
1892 // ('"const char" is not a valid Ident').
1893 // It's therefore important that f() is inline so that we need to
1894 // generate a thunk for it (where we then process the CcType).
1895 let ir = ir_from_cc(&tokens_to_string(quote! {
1896 inline void f(const char *str);
1897 })?)?;
1898
1899 let rs_api = generate_rs_api(&ir)?;
1900 assert_rs_matches!(
1901 rs_api,
1902 quote! {
1903 #[inline(always)]
Lukasz Anforowiczf7bdd392022-01-21 00:33:39 +00001904 pub unsafe fn f(str: *const i8) {
1905 crate::detail::__rust_thunk___Z1fPKc(str)
Googlerdb111532022-01-05 06:12:13 +00001906 }
1907 }
1908 );
1909 assert_rs_matches!(
1910 rs_api,
1911 quote! {
1912 extern "C" {
1913 pub(crate) fn __rust_thunk___Z1fPKc(str: *const i8);
1914 }
1915 }
1916 );
1917
1918 assert_cc_matches!(
1919 generate_rs_api_impl(&ir)?,
1920 quote! {
1921 extern "C" void __rust_thunk___Z1fPKc(char const * str){ f(str) ; }
1922 }
1923 );
1924 Ok(())
1925 }
1926
1927 #[test]
Michael Forstered642022021-10-04 09:48:25 +00001928 fn test_item_order() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00001929 let ir = ir_from_cc(
1930 "int first_func();
1931 struct FirstStruct {};
1932 int second_func();
1933 struct SecondStruct {};",
1934 )?;
Michael Forstered642022021-10-04 09:48:25 +00001935
Marcel Hlopko89547752021-12-10 09:39:41 +00001936 let rs_api = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?;
1937
Michael Forstered642022021-10-04 09:48:25 +00001938 let idx = |s: &str| rs_api.find(s).ok_or(anyhow!("'{}' missing", s));
1939
1940 let f1 = idx("fn first_func")?;
1941 let f2 = idx("fn second_func")?;
1942 let s1 = idx("struct FirstStruct")?;
1943 let s2 = idx("struct SecondStruct")?;
Googlera675ae02021-12-07 08:04:59 +00001944 let t1 = idx("fn __rust_thunk___Z10first_funcv")?;
1945 let t2 = idx("fn __rust_thunk___Z11second_funcv")?;
Michael Forstered642022021-10-04 09:48:25 +00001946
1947 assert!(f1 < s1);
1948 assert!(s1 < f2);
1949 assert!(f2 < s2);
1950 assert!(s2 < t1);
1951 assert!(t1 < t2);
1952
1953 Ok(())
1954 }
Michael Forster028800b2021-10-05 12:39:59 +00001955
1956 #[test]
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00001957 fn test_base_class_subobject_layout() -> Result<()> {
1958 let ir = ir_from_cc(
1959 r#"
1960 // We use a class here to force `Derived::z` to live inside the tail padding of `Base`.
1961 // On the Itanium ABI, this would not happen if `Base` were a POD type.
Devin Jeanpierre56777022022-02-03 01:57:15 +00001962 class Base {__INT64_TYPE__ x; char y;};
1963 struct Derived final : Base {__INT16_TYPE__ z;};
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00001964 "#,
1965 )?;
1966 let rs_api = generate_rs_api(&ir)?;
1967 assert_rs_matches!(
1968 rs_api,
1969 quote! {
1970 #[repr(C, align(8))]
1971 pub struct Derived {
1972 __base_class_subobjects: [std::mem::MaybeUninit<u8>; 10],
1973 pub z: i16,
1974 }
1975 }
1976 );
1977 Ok(())
1978 }
1979
1980 /// The same as test_base_class_subobject_layout, but with multiple
1981 /// inheritance.
1982 #[test]
1983 fn test_base_class_multiple_inheritance_subobject_layout() -> Result<()> {
1984 let ir = ir_from_cc(
1985 r#"
Devin Jeanpierre56777022022-02-03 01:57:15 +00001986 class Base1 {__INT64_TYPE__ x;};
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00001987 class Base2 {char y;};
Devin Jeanpierre56777022022-02-03 01:57:15 +00001988 struct Derived final : Base1, Base2 {__INT16_TYPE__ z;};
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00001989 "#,
1990 )?;
1991 let rs_api = generate_rs_api(&ir)?;
1992 assert_rs_matches!(
1993 rs_api,
1994 quote! {
1995 #[repr(C, align(8))]
1996 pub struct Derived {
1997 __base_class_subobjects: [std::mem::MaybeUninit<u8>; 10],
1998 pub z: i16,
1999 }
2000 }
2001 );
2002 Ok(())
2003 }
2004
2005 /// The same as test_base_class_subobject_layout, but with a chain of
2006 /// inheritance.
2007 #[test]
2008 fn test_base_class_deep_inheritance_subobject_layout() -> Result<()> {
2009 let ir = ir_from_cc(
2010 r#"
Devin Jeanpierre56777022022-02-03 01:57:15 +00002011 class Base1 {__INT64_TYPE__ x;};
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00002012 class Base2 : Base1 {char y;};
Devin Jeanpierre56777022022-02-03 01:57:15 +00002013 struct Derived final : Base2 {__INT16_TYPE__ z;};
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00002014 "#,
2015 )?;
2016 let rs_api = generate_rs_api(&ir)?;
2017 assert_rs_matches!(
2018 rs_api,
2019 quote! {
2020 #[repr(C, align(8))]
2021 pub struct Derived {
2022 __base_class_subobjects: [std::mem::MaybeUninit<u8>; 10],
2023 pub z: i16,
2024 }
2025 }
2026 );
2027 Ok(())
2028 }
2029
2030 /// For derived classes with no data members, we can't use the offset of the
2031 /// first member to determine the size of the base class subobjects.
2032 #[test]
2033 fn test_base_class_subobject_fieldless_layout() -> Result<()> {
2034 let ir = ir_from_cc(
2035 r#"
Devin Jeanpierre56777022022-02-03 01:57:15 +00002036 class Base {__INT64_TYPE__ x; char y;};
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00002037 struct Derived final : Base {};
2038 "#,
2039 )?;
2040 let rs_api = generate_rs_api(&ir)?;
2041 assert_rs_matches!(
2042 rs_api,
2043 quote! {
2044 #[repr(C, align(8))]
2045 pub struct Derived {
2046 __base_class_subobjects: [std::mem::MaybeUninit<u8>; 9],
2047 }
2048 }
2049 );
2050 Ok(())
2051 }
2052
2053 #[test]
2054 fn test_base_class_subobject_empty_fieldless() -> Result<()> {
2055 let ir = ir_from_cc(
2056 r#"
2057 class Base {};
2058 struct Derived final : Base {};
2059 "#,
2060 )?;
2061 let rs_api = generate_rs_api(&ir)?;
2062 assert_rs_matches!(
2063 rs_api,
2064 quote! {
2065 #[repr(C)]
2066 pub struct Derived {
2067 __base_class_subobjects: [std::mem::MaybeUninit<u8>; 0],
2068 /// Prevent empty C++ struct being zero-size in Rust.
2069 placeholder: std::mem::MaybeUninit<u8>,
2070 }
2071 }
2072 );
2073 Ok(())
2074 }
2075
2076 #[test]
2077 fn test_base_class_subobject_empty() -> Result<()> {
2078 let ir = ir_from_cc(
2079 r#"
2080 class Base {};
2081 struct Derived final : Base {};
2082 "#,
2083 )?;
2084 let rs_api = generate_rs_api(&ir)?;
2085 assert_rs_matches!(
2086 rs_api,
2087 quote! {
2088 #[repr(C)]
2089 pub struct Derived {
2090 __base_class_subobjects: [std::mem::MaybeUninit<u8>; 0],
2091 /// Prevent empty C++ struct being zero-size in Rust.
2092 placeholder: std::mem::MaybeUninit<u8>,
2093 }
2094 }
2095 );
2096 Ok(())
2097 }
2098
Devin Jeanpierreb69bcae2022-02-03 09:45:50 +00002099 /// When a field is [[no_unique_address]], it occupies the space up to the
2100 /// next field.
2101 #[test]
2102 fn test_no_unique_address() -> Result<()> {
2103 let ir = ir_from_cc(
2104 r#"
2105 class Field1 {__INT64_TYPE__ x;};
2106 class Field2 {char y;};
2107 struct Struct final {
2108 [[no_unique_address]] Field1 field1;
2109 [[no_unique_address]] Field2 field2;
2110 __INT16_TYPE__ z;
2111 };
2112 "#,
2113 )?;
2114 let rs_api = generate_rs_api(&ir)?;
2115 assert_rs_matches!(
2116 rs_api,
2117 quote! {
2118 #[derive(Clone, Copy)]
2119 #[repr(C, align(8))]
2120 pub struct Struct {
2121 field1: [std::mem::MaybeUninit<u8>; 8],
2122 field2: [std::mem::MaybeUninit<u8>; 2],
2123 pub z: i16,
2124 }
2125 }
2126 );
2127 Ok(())
2128 }
2129
2130 /// When a [[no_unique_address]] field is the last one, it occupies the rest
2131 /// of the object.
2132 #[test]
2133 fn test_no_unique_address_last_field() -> Result<()> {
2134 let ir = ir_from_cc(
2135 r#"
2136 class Field1 {__INT64_TYPE__ x;};
2137 class Field2 {char y;};
2138 struct Struct final {
2139 [[no_unique_address]] Field1 field1;
2140 [[no_unique_address]] Field2 field2;
2141 };
2142 "#,
2143 )?;
2144 let rs_api = generate_rs_api(&ir)?;
2145 assert_rs_matches!(
2146 rs_api,
2147 quote! {
2148 #[derive(Clone, Copy)]
2149 #[repr(C, align(8))]
2150 pub struct Struct {
2151 field1: [std::mem::MaybeUninit<u8>; 8],
2152 field2: [std::mem::MaybeUninit<u8>; 8],
2153 }
2154 }
2155 );
2156 Ok(())
2157 }
2158
2159 #[test]
2160 fn test_no_unique_address_empty() -> Result<()> {
2161 let ir = ir_from_cc(
2162 r#"
2163 class Field {};
2164 struct Struct final {
2165 [[no_unique_address]] Field field;
2166 int x;
2167 };
2168 "#,
2169 )?;
2170 let rs_api = generate_rs_api(&ir)?;
2171 assert_rs_matches!(
2172 rs_api,
2173 quote! {
2174 #[repr(C, align(4))]
2175 pub struct Struct {
2176 field: [std::mem::MaybeUninit<u8>; 0],
2177 pub x: i32,
2178 }
2179 }
2180 );
2181 Ok(())
2182 }
2183
2184 #[test]
2185 fn test_base_class_subobject_empty_last_field() -> Result<()> {
2186 let ir = ir_from_cc(
2187 r#"
2188 class Field {};
2189 struct Struct final {
2190 [[no_unique_address]] Field field;
2191 };
2192 "#,
2193 )?;
2194 let rs_api = generate_rs_api(&ir)?;
2195 assert_rs_matches!(
2196 rs_api,
2197 quote! {
2198 #[repr(C)]
2199 pub struct Struct {
2200 field: [std::mem::MaybeUninit<u8>; 1],
2201 }
2202 }
2203 );
2204 Ok(())
2205 }
2206
Devin Jeanpierrec80e6242022-02-03 01:56:40 +00002207 #[test]
Michael Forster409d9412021-10-07 08:35:29 +00002208 fn test_doc_comment_func() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00002209 let ir = ir_from_cc(
2210 "
2211 // Doc Comment
2212 // with two lines
2213 int func();",
2214 )?;
Michael Forster409d9412021-10-07 08:35:29 +00002215
Marcel Hlopko89547752021-12-10 09:39:41 +00002216 assert_rs_matches!(
2217 generate_rs_api(&ir)?,
2218 // leading space is intentional so there is a space between /// and the text of the
2219 // comment
2220 quote! {
2221 #[doc = " Doc Comment\n with two lines"]
2222 #[inline(always)]
2223 pub fn func
2224 }
Michael Forster409d9412021-10-07 08:35:29 +00002225 );
2226
2227 Ok(())
2228 }
2229
2230 #[test]
2231 fn test_doc_comment_record() -> Result<()> {
Marcel Hlopko89547752021-12-10 09:39:41 +00002232 let ir = ir_from_cc(
2233 "// Doc Comment\n\
2234 //\n\
2235 // * with bullet\n\
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002236 struct SomeStruct final {\n\
Marcel Hlopko89547752021-12-10 09:39:41 +00002237 // Field doc\n\
2238 int field;\
2239 };",
2240 )?;
Michael Forster028800b2021-10-05 12:39:59 +00002241
Marcel Hlopko89547752021-12-10 09:39:41 +00002242 assert_rs_matches!(
2243 generate_rs_api(&ir)?,
2244 quote! {
2245 #[doc = " Doc Comment\n \n * with bullet"]
2246 #[derive(Clone, Copy)]
2247 #[repr(C)]
2248 pub struct SomeStruct {
2249 # [doc = " Field doc"]
2250 pub field: i32,
2251 }
2252 }
Michael Forstercc5941a2021-10-07 07:12:24 +00002253 );
Michael Forster028800b2021-10-05 12:39:59 +00002254 Ok(())
2255 }
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002256
Devin Jeanpierre96839c12021-12-14 00:27:38 +00002257 #[test]
Devin Jeanpierre56777022022-02-03 01:57:15 +00002258 fn test_unambiguous_public_bases() -> Result<()> {
2259 let ir = ir_from_cc_dependency(
2260 "
2261 struct VirtualBase {};
2262 struct PrivateBase {};
2263 struct ProtectedBase {};
2264 struct UnambiguousPublicBase {};
2265 struct AmbiguousPublicBase {};
2266 struct MultipleInheritance : UnambiguousPublicBase, AmbiguousPublicBase {};
2267 struct Derived : private PrivateBase, protected ProtectedBase, MultipleInheritance, AmbiguousPublicBase, virtual VirtualBase {};
2268 ",
2269 "",
2270 )?;
2271 let rs_api = generate_rs_api(&ir)?;
2272 // TODO(b/216195042): virtual bases.
2273 assert_rs_not_matches!(rs_api, quote! { From<&'a Derived> for &'a VirtualBase });
2274 assert_rs_matches!(rs_api, quote! { From<&'a Derived> for &'a UnambiguousPublicBase });
2275 assert_rs_matches!(rs_api, quote! { From<&'a Derived> for &'a MultipleInheritance });
2276 assert_rs_not_matches!(rs_api, quote! {From<&'a Derived> for &'a PrivateBase});
2277 assert_rs_not_matches!(rs_api, quote! {From<&'a Derived> for &'a ProtectedBase});
2278 assert_rs_not_matches!(rs_api, quote! {From<&'a Derived> for &'a AmbiguousPublicBase});
2279 Ok(())
2280 }
2281
2282 /// Contrary to intuitions: a base class conversion is ambiguous even if the
2283 /// ambiguity is from a private base class cast that you can't even
2284 /// perform.
2285 ///
2286 /// Explanation (courtesy James Dennett):
2287 ///
2288 /// > Once upon a time, there was a rule in C++ that changing all access
2289 /// > specifiers to "public" would not change the meaning of code.
2290 /// > That's no longer true, but some of its effects can still be seen.
2291 ///
2292 /// So, we need to be sure to not allow casting to privately-ambiguous
2293 /// bases.
2294 #[test]
2295 fn test_unambiguous_public_bases_private_ambiguity() -> Result<()> {
2296 let ir = ir_from_cc_dependency(
2297 "
2298 struct Base {};
2299 struct Intermediate : public Base {};
2300 struct Derived : Base, private Intermediate {};
2301 ",
2302 "",
2303 )?;
2304 let rs_api = generate_rs_api(&ir)?;
2305 assert_rs_not_matches!(rs_api, quote! { From<&'a Derived> for &'a Base });
2306 Ok(())
2307 }
2308
2309 #[test]
Devin Jeanpierre96839c12021-12-14 00:27:38 +00002310 fn test_virtual_thunk() -> Result<()> {
2311 let ir = ir_from_cc("struct Polymorphic { virtual void Foo(); };")?;
2312
2313 assert_cc_matches!(
2314 generate_rs_api_impl(&ir)?,
2315 quote! {
Googler972d3582022-01-11 10:17:22 +00002316 extern "C" void __rust_thunk___ZN11Polymorphic3FooEv(class Polymorphic * __this)
Devin Jeanpierre96839c12021-12-14 00:27:38 +00002317 }
2318 );
2319 Ok(())
2320 }
2321
Devin Jeanpierree6e16652021-12-22 15:54:46 +00002322 /// A trivially relocatable final struct is safe to use in Rust as normal,
2323 /// and is Unpin.
2324 #[test]
2325 fn test_no_negative_impl_unpin() -> Result<()> {
2326 let ir = ir_from_cc("struct Trivial final {};")?;
2327 let rs_api = generate_rs_api(&ir)?;
2328 assert_rs_not_matches!(rs_api, quote! {impl !Unpin});
2329 Ok(())
2330 }
2331
2332 /// A non-final struct, even if it's trivial, is not usable by mut
2333 /// reference, and so is !Unpin.
2334 #[test]
2335 fn test_negative_impl_unpin_nonfinal() -> Result<()> {
2336 let ir = ir_from_cc("struct Nonfinal {};")?;
2337 let rs_api = generate_rs_api(&ir)?;
2338 assert_rs_matches!(rs_api, quote! {impl !Unpin for Nonfinal {}});
2339 Ok(())
2340 }
2341
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002342 /// At the least, a trivial type should have no drop impl if or until we add
2343 /// empty drop impls.
2344 #[test]
2345 fn test_no_impl_drop() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00002346 let ir = ir_from_cc("struct Trivial {};")?;
Marcel Hlopko89547752021-12-10 09:39:41 +00002347 let rs_api = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?;
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002348 assert!(!rs_api.contains("impl Drop"));
2349 Ok(())
2350 }
2351
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002352 /// User-defined destructors *must* become Drop impls with ManuallyDrop
2353 /// fields
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002354 #[test]
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002355 fn test_impl_drop_user_defined_destructor() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00002356 let ir = ir_from_cc(
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002357 r#" struct NontrivialStruct { ~NontrivialStruct(); };
2358 struct UserDefinedDestructor {
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002359 ~UserDefinedDestructor();
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002360 int x;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002361 NontrivialStruct nts;
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002362 };"#,
2363 )?;
2364 let rs_api = generate_rs_api(&ir)?;
Lukasz Anforowicz6d553632022-01-06 21:36:14 +00002365 assert_rs_matches!(
2366 rs_api,
2367 quote! {
2368 impl Drop for UserDefinedDestructor {
2369 #[inline(always)]
2370 fn drop(&mut self) {
2371 unsafe { crate::detail::__rust_thunk___ZN21UserDefinedDestructorD1Ev(self) }
2372 }
2373 }
2374 }
2375 );
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002376 assert_rs_matches!(rs_api, quote! {pub x: i32,});
2377 assert_rs_matches!(rs_api, quote! {pub nts: std::mem::ManuallyDrop<NontrivialStruct>,});
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002378 Ok(())
2379 }
2380
Lukasz Anforowicz6d553632022-01-06 21:36:14 +00002381 /// nontrivial types without user-defined destructors should invoke
2382 /// the C++ destructor to preserve the order of field destructions.
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002383 #[test]
2384 fn test_impl_drop_nontrivial_member_destructor() -> Result<()> {
2385 // TODO(jeanpierreda): This would be cleaner if the UserDefinedDestructor code were
2386 // omitted. For example, we simulate it so that UserDefinedDestructor
2387 // comes from another library.
Googler7cced422021-12-06 11:58:39 +00002388 let ir = ir_from_cc(
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002389 r#"struct UserDefinedDestructor final {
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002390 ~UserDefinedDestructor();
2391 };
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002392 struct TrivialStruct final { int i; };
2393 struct NontrivialMembers final {
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002394 UserDefinedDestructor udd;
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002395 TrivialStruct ts;
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002396 int x;
2397 };"#,
2398 )?;
2399 let rs_api = generate_rs_api(&ir)?;
Lukasz Anforowicz6d553632022-01-06 21:36:14 +00002400 assert_rs_matches!(
2401 rs_api,
2402 quote! {
2403 impl Drop for NontrivialMembers {
2404 #[inline(always)]
2405 fn drop(&mut self) {
2406 unsafe { crate::detail::__rust_thunk___ZN17NontrivialMembersD1Ev(self) }
2407 }
2408 }
2409 }
2410 );
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002411 assert_rs_matches!(rs_api, quote! {pub x: i32,});
2412 assert_rs_matches!(rs_api, quote! {pub ts: TrivialStruct,});
Lukasz Anforowicz6d553632022-01-06 21:36:14 +00002413 assert_rs_matches!(
2414 rs_api,
2415 quote! {pub udd: std::mem::ManuallyDrop<UserDefinedDestructor>,}
2416 );
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002417 Ok(())
2418 }
2419
2420 /// Trivial types (at least those that are mapped to Copy rust types) do not
2421 /// get a Drop impl.
2422 #[test]
2423 fn test_impl_drop_trivial() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00002424 let ir = ir_from_cc(
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002425 r#"struct Trivial final {
Devin Jeanpierre7e9a1de2021-12-03 08:04:22 +00002426 ~Trivial() = default;
2427 int x;
2428 };"#,
2429 )?;
2430 let rs_api = generate_rs_api(&ir)?;
Marcel Hlopko89547752021-12-10 09:39:41 +00002431 assert_rs_not_matches!(rs_api, quote! {impl Drop});
2432 assert_rs_matches!(rs_api, quote! {pub x: i32});
Lukasz Anforowicz2f074162022-01-06 22:50:51 +00002433 let rs_api_impl = generate_rs_api_impl(&ir)?;
2434 // TODO(b/213326125): Avoid generating thunk impls that are never called.
2435 // (The test assertion below should be reversed once this bug is fixed.)
2436 assert_cc_matches!(rs_api_impl, quote! { std::destroy_at });
Devin Jeanpierre91de7012021-10-21 12:53:51 +00002437 Ok(())
2438 }
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00002439
2440 #[test]
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00002441 fn test_impl_default_explicitly_defaulted_constructor() -> Result<()> {
2442 let ir = ir_from_cc(
Lukasz Anforowicz95551272022-01-20 00:02:24 +00002443 r#"#pragma clang lifetime_elision
2444 struct DefaultedConstructor final {
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00002445 DefaultedConstructor() = default;
2446 };"#,
2447 )?;
2448 let rs_api = generate_rs_api(&ir)?;
2449 assert_rs_matches!(
2450 rs_api,
2451 quote! {
2452 impl Default for DefaultedConstructor {
2453 #[inline(always)]
2454 fn default() -> Self {
Lukasz Anforowiczbedbdee2022-01-05 01:14:52 +00002455 let mut tmp = std::mem::MaybeUninit::<Self>::zeroed();
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00002456 unsafe {
Lukasz Anforowicz40c2eb82022-01-11 18:22:31 +00002457 crate::detail::__rust_thunk___ZN20DefaultedConstructorC1Ev(&mut tmp);
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00002458 tmp.assume_init()
2459 }
2460 }
2461 }
2462 }
2463 );
2464 let rs_api_impl = generate_rs_api_impl(&ir)?;
2465 assert_cc_matches!(
2466 rs_api_impl,
2467 quote! {
2468 extern "C" void __rust_thunk___ZN20DefaultedConstructorC1Ev(
Googler972d3582022-01-11 10:17:22 +00002469 class DefaultedConstructor* __this) {
Lukasz Anforowicz4457baf2021-12-23 17:24:04 +00002470 rs_api_impl_support::construct_at (__this) ;
Lukasz Anforowicze643ec92021-12-22 15:45:15 +00002471 }
2472 }
2473 );
2474 Ok(())
2475 }
2476
2477 #[test]
Lukasz Anforowicz326c4e42022-01-27 14:43:00 +00002478 fn test_impl_clone_that_propagates_lifetime() -> Result<()> {
2479 // This test covers the case where a single lifetime applies to 1)
2480 // the `__this` parameter and 2) other constructor parameters. For
2481 // example, maybe the newly constructed object needs to have the
2482 // same lifetime as the constructor's parameter. (This might require
2483 // annotating the whole C++ struct with a lifetime, so maybe the
2484 // example below is not fully realistic/accurate...).
2485 let mut ir = ir_from_cc(
2486 r#"#pragma clang lifetime_elision
2487 struct Foo final {
2488 [[clang::annotate("lifetimes = a: a")]]
2489 Foo(const int& i);
2490 };"#,
2491 )?;
2492 let ctor: &mut Func = ir
2493 .items_mut()
2494 .filter_map(|item| match item {
2495 Item::Func(func) => Some(func),
2496 _ => None,
2497 })
2498 .find(|f| {
2499 matches!(&f.name, UnqualifiedIdentifier::Constructor)
2500 && f.params.get(1).map(|p| p.identifier.identifier == "i").unwrap_or_default()
2501 })
2502 .unwrap();
2503 {
2504 // Double-check that the test scenario set up above uses the same lifetime
2505 // for both of the constructor's parameters: `__this` and `i`.
2506 assert_eq!(ctor.params.len(), 2);
2507 let this_lifetime: LifetimeId =
2508 *ctor.params[0].type_.rs_type.lifetime_args.first().unwrap();
2509 let i_lifetime: LifetimeId =
2510 *ctor.params[1].type_.rs_type.lifetime_args.first_mut().unwrap();
2511 assert_eq!(i_lifetime, this_lifetime);
2512 }
2513
2514 // Before cl/423346348 the generated Rust code would incorrectly look
2515 // like this (note the mismatched 'a and 'b lifetimes):
2516 // fn from<'b>(i: &'a i32) -> Self
2517 // After this CL, this scenario will result in an explicit error.
2518 let err = generate_rs_api(&ir).unwrap_err();
2519 let msg = format!("{}", err);
2520 assert!(
2521 msg.contains("The lifetime of `__this` is unexpectedly also used by another parameter")
2522 );
2523 Ok(())
2524 }
2525
2526 #[test]
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +00002527 fn test_impl_default_non_trivial_struct() -> Result<()> {
2528 let ir = ir_from_cc(
Lukasz Anforowicz71716b72022-01-26 17:05:05 +00002529 r#"#pragma clang lifetime_elision
2530 struct NonTrivialStructWithConstructors final {
Lukasz Anforowicz9bab8352021-12-22 17:35:31 +00002531 NonTrivialStructWithConstructors();
2532 ~NonTrivialStructWithConstructors(); // Non-trivial
2533 };"#,
2534 )?;
2535 let rs_api = generate_rs_api(&ir)?;
2536 assert_rs_not_matches!(rs_api, quote! {impl Default});
2537 Ok(())
2538 }
2539
2540 #[test]
Lukasz Anforowicz71716b72022-01-26 17:05:05 +00002541 fn test_impl_from_for_explicit_conversion_constructor() -> Result<()> {
2542 let ir = ir_from_cc(
2543 r#"#pragma clang lifetime_elision
2544 struct SomeStruct final {
2545 explicit SomeStruct(int i);
2546 };"#,
2547 )?;
2548 let rs_api = generate_rs_api(&ir)?;
2549 // As discussed in b/214020567 for now we only generate `From::from` bindings
2550 // for *implicit* C++ conversion constructors.
2551 assert_rs_not_matches!(rs_api, quote! {impl From});
2552 Ok(())
2553 }
2554
2555 #[test]
2556 fn test_impl_from_for_implicit_conversion_constructor() -> Result<()> {
2557 let ir = ir_from_cc(
2558 r#"#pragma clang lifetime_elision
2559 struct SomeStruct final {
2560 SomeStruct(int i); // implicit - no `explicit` keyword
2561 };"#,
2562 )?;
2563 let rs_api = generate_rs_api(&ir)?;
2564 // As discussed in b/214020567 we generate `From::from` bindings for
2565 // *implicit* C++ conversion constructors.
2566 assert_rs_matches!(
2567 rs_api,
2568 quote! {
2569 impl From<i32> for SomeStruct {
2570 #[inline(always)]
2571 fn from(i: i32) -> Self {
2572 let mut tmp = std::mem::MaybeUninit::<Self>::zeroed();
2573 unsafe {
2574 crate::detail::__rust_thunk___ZN10SomeStructC1Ei(&mut tmp, i);
2575 tmp.assume_init()
2576 }
2577 }
2578 }
2579 }
2580 );
2581 Ok(())
2582 }
2583
2584 #[test]
Lukasz Anforowicz732ca642022-02-03 20:58:38 +00002585 fn test_impl_eq_for_member_function() -> Result<()> {
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00002586 let ir = ir_from_cc(
2587 r#"#pragma clang lifetime_elision
2588 struct SomeStruct final {
2589 inline bool operator==(const SomeStruct& other) const {
2590 return i == other.i;
2591 }
2592 int i;
2593 };"#,
2594 )?;
2595 let rs_api = generate_rs_api(&ir)?;
2596 assert_rs_matches!(
2597 rs_api,
2598 quote! {
2599 impl PartialEq<SomeStruct> for SomeStruct {
2600 #[inline(always)]
2601 fn eq<'a, 'b>(&'a self, other: &'b SomeStruct) -> bool {
2602 unsafe { crate::detail::__rust_thunk___ZNK10SomeStructeqERKS_(self, other) }
2603 }
2604 }
2605 }
2606 );
2607 let rs_api_impl = generate_rs_api_impl(&ir)?;
2608 assert_cc_matches!(
2609 rs_api_impl,
2610 quote! {
2611 extern "C" bool __rust_thunk___ZNK10SomeStructeqERKS_(
2612 const class SomeStruct* __this, const class SomeStruct& other) {
2613 return __this->operator==(other);
2614 }
2615 }
2616 );
2617 Ok(())
2618 }
2619
2620 #[test]
Lukasz Anforowicz732ca642022-02-03 20:58:38 +00002621 fn test_impl_eq_for_free_function() -> Result<()> {
2622 let ir = ir_from_cc(
2623 r#"#pragma clang lifetime_elision
2624 struct SomeStruct final { int i; };
2625 bool operator==(const SomeStruct& lhs, const SomeStruct& rhs) {
2626 return lhs.i == rhs.i;
2627 }"#,
2628 )?;
2629 let rs_api = generate_rs_api(&ir)?;
2630 assert_rs_matches!(
2631 rs_api,
2632 quote! {
2633 impl PartialEq<SomeStruct> for SomeStruct {
2634 #[inline(always)]
2635 fn eq<'a, 'b>(&'a self, rhs: &'b SomeStruct) -> bool {
2636 unsafe { crate::detail::__rust_thunk___ZeqRK10SomeStructS1_(self, rhs) }
2637 }
2638 }
2639 }
2640 );
2641 Ok(())
2642 }
2643
2644 #[test]
Lukasz Anforowiczfae90a12022-02-03 20:58:15 +00002645 fn test_impl_eq_non_const_member_function() -> Result<()> {
2646 let ir = ir_from_cc(
2647 r#"#pragma clang lifetime_elision
2648 struct SomeStruct final {
2649 bool operator==(const SomeStruct& other) /* no `const` here */;
2650 };"#,
2651 )?;
2652 let rs_api = generate_rs_api(&ir)?;
2653 assert_rs_not_matches!(rs_api, quote! {impl PartialEq});
2654 Ok(())
2655 }
2656
2657 #[test]
2658 fn test_impl_eq_rhs_by_value() -> Result<()> {
2659 let ir = ir_from_cc(
2660 r#"#pragma clang lifetime_elision
2661 struct SomeStruct final {
2662 bool operator==(SomeStruct other) const;
2663 };"#,
2664 )?;
2665 let rs_api = generate_rs_api(&ir)?;
2666 assert_rs_not_matches!(rs_api, quote! {impl PartialEq});
2667 Ok(())
2668 }
2669
2670 #[test]
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00002671 fn test_thunk_ident_function() {
2672 let func = ir_func("foo");
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00002673 assert_eq!(thunk_ident(&func), make_rs_ident("__rust_thunk___Z3foov"));
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00002674 }
2675
2676 #[test]
2677 fn test_thunk_ident_special_names() {
Marcel Hlopko4b13b962021-12-06 12:40:56 +00002678 let ir = ir_from_cc("struct Class {};").unwrap();
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00002679
Googler45ad2752021-12-06 12:12:35 +00002680 let destructor =
2681 ir.functions().find(|f| f.name == UnqualifiedIdentifier::Destructor).unwrap();
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00002682 assert_eq!(thunk_ident(&destructor), make_rs_ident("__rust_thunk___ZN5ClassD1Ev"));
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00002683
Googler45ad2752021-12-06 12:12:35 +00002684 let constructor =
2685 ir.functions().find(|f| f.name == UnqualifiedIdentifier::Constructor).unwrap();
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00002686 assert_eq!(thunk_ident(&constructor), make_rs_ident("__rust_thunk___ZN5ClassC1Ev"));
Devin Jeanpierre45cb1162021-10-27 10:54:28 +00002687 }
Googler7cced422021-12-06 11:58:39 +00002688
2689 #[test]
Marcel Hlopko89547752021-12-10 09:39:41 +00002690 fn test_elided_lifetimes() -> Result<()> {
Googler7cced422021-12-06 11:58:39 +00002691 let ir = ir_from_cc(
2692 r#"#pragma clang lifetime_elision
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002693 struct S final {
Googler7cced422021-12-06 11:58:39 +00002694 int& f(int& i);
2695 };"#,
Marcel Hlopko89547752021-12-10 09:39:41 +00002696 )?;
2697 let rs_api = generate_rs_api(&ir)?;
2698 assert_rs_matches!(
2699 rs_api,
2700 quote! {
Lukasz Anforowicz231a3bb2022-01-12 14:05:59 +00002701 pub fn f<'a, 'b>(&'a mut self, i: &'b mut i32) -> &'a mut i32 { ... }
Marcel Hlopko89547752021-12-10 09:39:41 +00002702 }
Googler7cced422021-12-06 11:58:39 +00002703 );
Marcel Hlopko89547752021-12-10 09:39:41 +00002704 assert_rs_matches!(
2705 rs_api,
2706 quote! {
Googler6804a012022-01-05 07:04:36 +00002707 pub(crate) fn __rust_thunk___ZN1S1fERi<'a, 'b>(__this: &'a mut S, i: &'b mut i32)
2708 -> &'a mut i32;
Marcel Hlopko89547752021-12-10 09:39:41 +00002709 }
Googler7cced422021-12-06 11:58:39 +00002710 );
Marcel Hlopko89547752021-12-10 09:39:41 +00002711 Ok(())
Googler7cced422021-12-06 11:58:39 +00002712 }
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +00002713
2714 #[test]
2715 fn test_format_generic_params() -> Result<()> {
2716 assert_rs_matches!(format_generic_params(std::iter::empty::<syn::Ident>()), quote! {});
2717
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00002718 let idents = ["T1", "T2"].iter().map(|s| make_rs_ident(s));
Lukasz Anforowiczdaff0402021-12-23 00:37:50 +00002719 assert_rs_matches!(format_generic_params(idents), quote! { < T1, T2 > });
2720
2721 let lifetimes = ["a", "b"]
2722 .iter()
2723 .map(|s| syn::Lifetime::new(&format!("'{}", s), proc_macro2::Span::call_site()));
2724 assert_rs_matches!(format_generic_params(lifetimes), quote! { < 'a, 'b > });
2725
2726 Ok(())
2727 }
Googlerd03d05b2022-01-07 10:10:57 +00002728
2729 #[test]
2730 fn test_overloaded_functions() -> Result<()> {
2731 // TODO(b/213280424): We don't support creating bindings for overloaded
2732 // functions yet, except in the case of overloaded constructors with a
2733 // single parameter.
2734 let ir = ir_from_cc(
Lukasz Anforowicz55673c92022-01-27 19:37:26 +00002735 r#" #pragma clang lifetime_elision
2736 void f();
Googlerd03d05b2022-01-07 10:10:57 +00002737 void f(int i);
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002738 struct S1 final {
Googlerd03d05b2022-01-07 10:10:57 +00002739 void f();
2740 void f(int i);
2741 };
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002742 struct S2 final {
Googlerd03d05b2022-01-07 10:10:57 +00002743 void f();
2744 };
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002745 struct S3 final {
Googlerd03d05b2022-01-07 10:10:57 +00002746 S3(int i);
2747 S3(double d);
2748 };
2749 "#,
2750 )?;
2751 let rs_api = generate_rs_api(&ir)?;
2752 let rs_api_str = tokens_to_string(rs_api.clone())?;
2753
2754 // Cannot overload free functions.
2755 assert!(rs_api_str.contains("Error while generating bindings for item 'f'"));
2756 assert_rs_not_matches!(rs_api, quote! {pub fn f()});
2757 assert_rs_not_matches!(rs_api, quote! {pub fn f(i: i32)});
2758
2759 // Cannot overload member functions.
2760 assert!(rs_api_str.contains("Error while generating bindings for item 'S1::f'"));
2761 assert_rs_not_matches!(rs_api, quote! {pub fn f(... S1 ...)});
2762
2763 // But we can import member functions that have the same name as a free
2764 // function.
Lukasz Anforowicz55673c92022-01-27 19:37:26 +00002765 assert_rs_matches!(rs_api, quote! {pub fn f<'a>(&'a mut self)});
Googlerd03d05b2022-01-07 10:10:57 +00002766
2767 // We can also import overloaded single-parameter constructors.
2768 assert_rs_matches!(rs_api, quote! {impl From<i32> for S3});
2769 assert_rs_matches!(rs_api, quote! {impl From<f64> for S3});
2770 Ok(())
2771 }
Googlerdcca7f72022-01-10 12:30:43 +00002772
2773 #[test]
2774 fn test_type_alias() -> Result<()> {
2775 let ir = ir_from_cc(
2776 r#"
2777 typedef int MyTypedefDecl;
2778 using MyTypeAliasDecl = int;
Googler6a0a5252022-01-11 14:08:09 +00002779 using MyTypeAliasDecl_Alias = MyTypeAliasDecl;
2780
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002781 struct S final {};
Googler6a0a5252022-01-11 14:08:09 +00002782 using S_Alias = S;
2783 using S_Alias_Alias = S_Alias;
2784
2785 inline void f(MyTypedefDecl t) {}
Googlerdcca7f72022-01-10 12:30:43 +00002786 "#,
2787 )?;
2788 let rs_api = generate_rs_api(&ir)?;
Googler6a0a5252022-01-11 14:08:09 +00002789 assert_rs_matches!(rs_api, quote! { pub type MyTypedefDecl = i32; });
2790 assert_rs_matches!(rs_api, quote! { pub type MyTypeAliasDecl = i32; });
2791 assert_rs_matches!(rs_api, quote! { pub type MyTypeAliasDecl_Alias = MyTypeAliasDecl; });
2792 assert_rs_matches!(rs_api, quote! { pub type S_Alias = S; });
2793 assert_rs_matches!(rs_api, quote! { pub type S_Alias_Alias = S_Alias; });
2794 assert_rs_matches!(rs_api, quote! { pub fn f(t: MyTypedefDecl) });
2795 assert_cc_matches!(
2796 generate_rs_api_impl(&ir)?,
2797 quote! {
2798 extern "C" void __rust_thunk___Z1fi(MyTypedefDecl t){ f (t) ; }
2799 }
2800 );
Googlerdcca7f72022-01-10 12:30:43 +00002801 Ok(())
2802 }
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002803
2804 #[test]
2805 fn test_rs_type_kind_implements_copy() -> Result<()> {
2806 let template = r#" #pragma clang lifetime_elision
Devin Jeanpierre88343c72022-01-15 01:10:23 +00002807 struct [[clang::trivial_abi]] TrivialStruct final { int i; };
2808 struct [[clang::trivial_abi]] UserDefinedCopyConstructor final {
Lukasz Anforowicze57215c2022-01-12 14:54:16 +00002809 UserDefinedCopyConstructor(const UserDefinedCopyConstructor&);
2810 };
2811 using IntAlias = int;
2812 using TrivialAlias = TrivialStruct;
2813 using NonTrivialAlias = UserDefinedCopyConstructor;
2814 void func(PARAM_TYPE some_param);
2815 "#;
2816 assert_impl_all!(i32: Copy);
2817 assert_impl_all!(&i32: Copy);
2818 assert_not_impl_all!(&mut i32: Copy);
2819 assert_impl_all!(*const i32: Copy);
2820 assert_impl_all!(*mut i32: Copy);
2821 let tests = vec![
2822 // Validity of the next few tests is verified via
2823 // `assert_[not_]impl_all!` static assertions above.
2824 ("int", true),
2825 ("const int&", true),
2826 ("int&", false),
2827 ("const int*", true),
2828 ("int*", true),
2829 // Tests below have been thought-through and verified "manually".
2830 ("TrivialStruct", true), // Trivial C++ structs are expected to derive Copy.
2831 ("UserDefinedCopyConstructor", false),
2832 ("IntAlias", true),
2833 ("TrivialAlias", true),
2834 ("NonTrivialAlias", false),
2835 ];
2836 for (type_str, is_copy_expected) in tests.iter() {
2837 let ir = ir_from_cc(&template.replace("PARAM_TYPE", type_str))?;
2838 let f = ir
2839 .functions()
2840 .find(|f| match &f.name {
2841 UnqualifiedIdentifier::Identifier(id) => id.identifier == "func",
2842 _ => false,
2843 })
2844 .expect("IR should contain a function named 'func'");
2845 let t = RsTypeKind::new(&f.params[0].type_.rs_type, &ir)?;
2846 assert_eq!(*is_copy_expected, t.implements_copy(), "Testing '{}'", type_str);
2847 }
2848 Ok(())
2849 }
Lukasz Anforowicza94ab702022-01-14 22:40:25 +00002850
2851 #[test]
2852 fn test_rs_type_kind_is_shared_ref_to_with_lifetimes() -> Result<()> {
2853 let ir = ir_from_cc(
2854 "#pragma clang lifetime_elision
2855 struct SomeStruct {};
2856 void foo(const SomeStruct& foo_param);
2857 void bar(SomeStruct& bar_param);",
2858 )?;
2859 let record = ir.records().next().unwrap();
2860 let foo_func = ir
2861 .functions()
2862 .find(|f| {
2863 matches!(&f.name, UnqualifiedIdentifier::Identifier(id)
2864 if id.identifier == "foo")
2865 })
2866 .unwrap();
2867 let bar_func = ir
2868 .functions()
2869 .find(|f| {
2870 matches!(&f.name, UnqualifiedIdentifier::Identifier(id)
2871 if id.identifier == "bar")
2872 })
2873 .unwrap();
2874
2875 // const-ref + lifetimes in C++ ===> shared-ref in Rust
2876 assert_eq!(foo_func.params.len(), 1);
2877 let foo_param = &foo_func.params[0];
2878 assert_eq!(&foo_param.identifier.identifier, "foo_param");
2879 let foo_type = RsTypeKind::new(&foo_param.type_.rs_type, &ir)?;
2880 assert!(foo_type.is_shared_ref_to(record));
2881 assert!(matches!(foo_type, RsTypeKind::Reference { mutability: Mutability::Const, .. }));
2882
2883 // non-const-ref + lifetimes in C++ ===> mutable-ref in Rust
2884 assert_eq!(bar_func.params.len(), 1);
2885 let bar_param = &bar_func.params[0];
2886 assert_eq!(&bar_param.identifier.identifier, "bar_param");
2887 let bar_type = RsTypeKind::new(&bar_param.type_.rs_type, &ir)?;
2888 assert!(!bar_type.is_shared_ref_to(record));
2889 assert!(matches!(bar_type, RsTypeKind::Reference { mutability: Mutability::Mut, .. }));
2890
2891 Ok(())
2892 }
2893
2894 #[test]
2895 fn test_rs_type_kind_is_shared_ref_to_without_lifetimes() -> Result<()> {
2896 let ir = ir_from_cc(
2897 "struct SomeStruct {};
2898 void foo(const SomeStruct& foo_param);",
2899 )?;
2900 let record = ir.records().next().unwrap();
2901 let foo_func = ir
2902 .functions()
2903 .find(|f| {
2904 matches!(&f.name, UnqualifiedIdentifier::Identifier(id)
2905 if id.identifier == "foo")
2906 })
2907 .unwrap();
2908
2909 // const-ref + *no* lifetimes in C++ ===> const-pointer in Rust
2910 assert_eq!(foo_func.params.len(), 1);
2911 let foo_param = &foo_func.params[0];
2912 assert_eq!(&foo_param.identifier.identifier, "foo_param");
2913 let foo_type = RsTypeKind::new(&foo_param.type_.rs_type, &ir)?;
2914 assert!(!foo_type.is_shared_ref_to(record));
2915 assert!(matches!(foo_type, RsTypeKind::Pointer { mutability: Mutability::Const, .. }));
2916
2917 Ok(())
2918 }
Marcel Hlopkoeaae9b72022-01-21 15:54:11 +00002919
2920 #[test]
2921 fn test_rust_keywords_are_escaped_in_rs_api_file() -> Result<()> {
2922 let ir = ir_from_cc("struct type { int dyn; };")?;
2923 let rs_api = generate_rs_api(&ir)?;
2924 assert_rs_matches!(rs_api, quote! { struct r#type { ... r#dyn: i32 ... } });
2925 Ok(())
2926 }
2927
2928 #[test]
2929 fn test_rust_keywords_are_not_escaped_in_rs_api_impl_file() -> Result<()> {
2930 let ir = ir_from_cc("struct type { int dyn; };")?;
2931 let rs_api_impl = generate_rs_api_impl(&ir)?;
2932 assert_cc_matches!(rs_api_impl, quote! { static_assert(offsetof(class type, dyn) ... ) });
2933 Ok(())
2934 }
Marcel Hlopko42abfc82021-08-09 07:03:17 +00002935}