Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1 | // 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 | |
Devin Jeanpierre | 3a0cc5a | 2022-07-12 09:36:34 -0700 | [diff] [blame^] | 5 | use arc_anyhow::{anyhow, bail, ensure, Context, Result}; |
Marcel Hlopko | 884ae7f | 2021-08-18 13:58:22 +0000 | [diff] [blame] | 6 | use ffi_types::*; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 7 | use ir::*; |
| 8 | use itertools::Itertools; |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 9 | use proc_macro2::{Ident, Literal, TokenStream}; |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 10 | use quote::{format_ident, quote, ToTokens}; |
Devin Jeanpierre | 3a0cc5a | 2022-07-12 09:36:34 -0700 | [diff] [blame^] | 11 | use salsa_utils::PtrEq; |
Devin Jeanpierre | 9886fb4 | 2022-04-01 04:31:20 -0700 | [diff] [blame] | 12 | use std::collections::{BTreeSet, HashSet}; |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 13 | use std::ffi::{OsStr, OsString}; |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 14 | use std::iter::{self, Iterator}; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 15 | use std::panic::catch_unwind; |
| 16 | use std::process; |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 17 | use std::rc::Rc; |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 18 | use token_stream_printer::{rs_tokens_to_formatted_string, tokens_to_string, RustfmtConfig}; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 19 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 20 | /// FFI equivalent of `Bindings`. |
| 21 | #[repr(C)] |
| 22 | pub struct FfiBindings { |
| 23 | rs_api: FfiU8SliceBox, |
| 24 | rs_api_impl: FfiU8SliceBox, |
| 25 | } |
| 26 | |
| 27 | /// Deserializes IR from `json` and generates bindings source code. |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 28 | /// |
| 29 | /// This function panics on error. |
| 30 | /// |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 31 | /// # Safety |
| 32 | /// |
| 33 | /// Expectations: |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 34 | /// * `json` should be a FfiU8Slice for a valid array of bytes with the given |
| 35 | /// size. |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 36 | /// * `crubit_support_path` should be a FfiU8Slice for a valid array of bytes |
| 37 | /// representing an UTF8-encoded string |
Lukasz Anforowicz | d7d68f0 | 2022-05-26 07:41:02 -0700 | [diff] [blame] | 38 | /// * `rustfmt_exe_path` and `rustfmt_config_path` should both be a |
| 39 | /// FfiU8Slice for a valid array of bytes representing an UTF8-encoded |
| 40 | /// string (without the UTF-8 requirement, it seems that Rust doesn't offer |
| 41 | /// a way to convert to OsString on Windows) |
| 42 | /// * `json`, `crubit_support_path`, `rustfmt_exe_path`, and |
| 43 | /// `rustfmt_config_path` shouldn't change during the call. |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 44 | /// |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 45 | /// Ownership: |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 46 | /// * function doesn't take ownership of (in other words it borrows) the |
Lukasz Anforowicz | d7d68f0 | 2022-05-26 07:41:02 -0700 | [diff] [blame] | 47 | /// input params: `json`, `crubit_support_path`, `rustfmt_exe_path`, and |
| 48 | /// `rustfmt_config_path` |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 49 | /// * function passes ownership of the returned value to the caller |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 50 | #[no_mangle] |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 51 | pub unsafe extern "C" fn GenerateBindingsImpl( |
| 52 | json: FfiU8Slice, |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 53 | crubit_support_path: FfiU8Slice, |
Lukasz Anforowicz | d7d68f0 | 2022-05-26 07:41:02 -0700 | [diff] [blame] | 54 | rustfmt_exe_path: FfiU8Slice, |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 55 | rustfmt_config_path: FfiU8Slice, |
| 56 | ) -> FfiBindings { |
| 57 | let json: &[u8] = json.as_slice(); |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 58 | let crubit_support_path: &str = std::str::from_utf8(crubit_support_path.as_slice()).unwrap(); |
Lukasz Anforowicz | d7d68f0 | 2022-05-26 07:41:02 -0700 | [diff] [blame] | 59 | let rustfmt_exe_path: OsString = |
| 60 | std::str::from_utf8(rustfmt_exe_path.as_slice()).unwrap().into(); |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 61 | let rustfmt_config_path: OsString = |
| 62 | std::str::from_utf8(rustfmt_config_path.as_slice()).unwrap().into(); |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 63 | catch_unwind(|| { |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 64 | // It is ok to abort here. |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 65 | let Bindings { rs_api, rs_api_impl } = |
Devin Jeanpierre | 108e9c0 | 2022-06-02 07:10:09 -0700 | [diff] [blame] | 66 | generate_bindings(json, crubit_support_path, &rustfmt_exe_path, &rustfmt_config_path) |
| 67 | .unwrap(); |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 68 | FfiBindings { |
| 69 | rs_api: FfiU8SliceBox::from_boxed_slice(rs_api.into_bytes().into_boxed_slice()), |
| 70 | rs_api_impl: FfiU8SliceBox::from_boxed_slice( |
| 71 | rs_api_impl.into_bytes().into_boxed_slice(), |
| 72 | ), |
| 73 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 74 | }) |
| 75 | .unwrap_or_else(|_| process::abort()) |
| 76 | } |
| 77 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 78 | #[salsa::query_group(BindingsGeneratorStorage)] |
| 79 | trait BindingsGenerator { |
| 80 | #[salsa::input] |
| 81 | fn ir(&self) -> Rc<IR>; |
| 82 | |
Devin Jeanpierre | 3a0cc5a | 2022-07-12 09:36:34 -0700 | [diff] [blame^] | 83 | fn rs_type_kind(&self, rs_type: RsType) -> Result<RsTypeKind>; |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 84 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 85 | fn generate_func( |
| 86 | &self, |
| 87 | func: Rc<Func>, |
Devin Jeanpierre | 3a0cc5a | 2022-07-12 09:36:34 -0700 | [diff] [blame^] | 88 | ) -> Result<Option<PtrEq<Rc<(RsSnippet, RsSnippet, Rc<FunctionId>)>>>>; |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 89 | |
| 90 | fn overloaded_funcs(&self) -> Rc<HashSet<Rc<FunctionId>>>; |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 91 | } |
| 92 | |
| 93 | #[salsa::database(BindingsGeneratorStorage)] |
| 94 | #[derive(Default)] |
| 95 | struct Database { |
| 96 | storage: salsa::Storage<Self>, |
| 97 | } |
| 98 | |
| 99 | impl salsa::Database for Database {} |
| 100 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 101 | /// Source code for generated bindings. |
| 102 | struct Bindings { |
| 103 | // Rust source code. |
| 104 | rs_api: String, |
| 105 | // C++ source code. |
| 106 | rs_api_impl: String, |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 107 | } |
| 108 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 109 | /// Source code for generated bindings, as tokens. |
| 110 | struct BindingsTokens { |
| 111 | // Rust source code. |
| 112 | rs_api: TokenStream, |
| 113 | // C++ source code. |
| 114 | rs_api_impl: TokenStream, |
| 115 | } |
| 116 | |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 117 | fn generate_bindings( |
| 118 | json: &[u8], |
| 119 | crubit_support_path: &str, |
Lukasz Anforowicz | d7d68f0 | 2022-05-26 07:41:02 -0700 | [diff] [blame] | 120 | rustfmt_exe_path: &OsStr, |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 121 | rustfmt_config_path: &OsStr, |
| 122 | ) -> Result<Bindings> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 123 | let ir = Rc::new(deserialize_ir(json)?); |
Marcel Hlopko | ca84ff4 | 2021-12-09 14:15:14 +0000 | [diff] [blame] | 124 | |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 125 | let BindingsTokens { rs_api, rs_api_impl } = |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 126 | generate_bindings_tokens(ir.clone(), crubit_support_path)?; |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 127 | let rs_api = { |
Lukasz Anforowicz | d7d68f0 | 2022-05-26 07:41:02 -0700 | [diff] [blame] | 128 | let rustfmt_config = RustfmtConfig::new(rustfmt_exe_path, rustfmt_config_path); |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 129 | rs_tokens_to_formatted_string(rs_api, &rustfmt_config)? |
| 130 | }; |
| 131 | |
Marcel Hlopko | ca84ff4 | 2021-12-09 14:15:14 +0000 | [diff] [blame] | 132 | // The code is formatted with a non-default rustfmt configuration. Prevent |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 133 | // downstream workflows from reformatting with a different configuration by |
| 134 | // marking the output with `@generated`. See also |
| 135 | // https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#format_generated_files |
| 136 | // |
| 137 | // TODO(lukasza): It would be nice to include "by $argv[0]"" in the |
| 138 | // @generated comment below. OTOH, `std::env::current_exe()` in our |
| 139 | // current build environment returns a guid-like path... :-/ |
Lukasz Anforowicz | 72c4d22 | 2022-02-18 19:07:28 +0000 | [diff] [blame] | 140 | // |
| 141 | // TODO(lukasza): Try to remove `#![rustfmt:skip]` - in theory it shouldn't |
| 142 | // be needed when `@generated` comment/keyword is present... |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 143 | let rs_api = format!( |
Lukasz Anforowicz | 72c4d22 | 2022-02-18 19:07:28 +0000 | [diff] [blame] | 144 | "// Automatically @generated Rust bindings for C++ target\n\ |
| 145 | // {target}\n\ |
| 146 | #![rustfmt::skip]\n\ |
| 147 | {code}", |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 148 | target = ir.current_target().0, |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 149 | code = rs_api, |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 150 | ); |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 151 | let rs_api_impl = tokens_to_string(rs_api_impl)?; |
Marcel Hlopko | ca84ff4 | 2021-12-09 14:15:14 +0000 | [diff] [blame] | 152 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 153 | Ok(Bindings { rs_api, rs_api_impl }) |
| 154 | } |
| 155 | |
Devin Jeanpierre | 6d5e7cc | 2021-10-21 12:56:07 +0000 | [diff] [blame] | 156 | /// Rust source code with attached information about how to modify the parent |
| 157 | /// crate. |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 158 | /// |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 159 | /// For example, the snippet `vec![].into_raw_parts()` is not valid unless the |
| 160 | /// `vec_into_raw_parts` feature is enabled. So such a snippet should be |
| 161 | /// represented as: |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 162 | /// |
| 163 | /// ``` |
| 164 | /// RsSnippet { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 165 | /// features: btree_set![make_rs_ident("vec_into_raw_parts")], |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 166 | /// tokens: quote!{vec![].into_raw_parts()}, |
| 167 | /// } |
| 168 | /// ``` |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 169 | #[derive(Clone, Debug)] |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 170 | struct RsSnippet { |
| 171 | /// Rust feature flags used by this snippet. |
| 172 | features: BTreeSet<Ident>, |
| 173 | /// The snippet itself, as a token stream. |
| 174 | tokens: TokenStream, |
| 175 | } |
| 176 | |
| 177 | impl From<TokenStream> for RsSnippet { |
| 178 | fn from(tokens: TokenStream) -> Self { |
| 179 | RsSnippet { features: BTreeSet::new(), tokens } |
| 180 | } |
| 181 | } |
| 182 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 183 | /// If we know the original C++ function is codegenned and already compatible |
| 184 | /// with `extern "C"` calling convention we skip creating/calling the C++ thunk |
| 185 | /// since we can call the original C++ directly. |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 186 | fn can_skip_cc_thunk(func: &Func) -> bool { |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 187 | // ## Inline functions |
| 188 | // |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 189 | // Inline functions may not be codegenned in the C++ library since Clang doesn't |
| 190 | // know if Rust calls the function or not. Therefore in order to make inline |
| 191 | // functions callable from Rust we need to generate a C++ file that defines |
| 192 | // a thunk that delegates to the original inline function. When compiled, |
| 193 | // Clang will emit code for this thunk and Rust code will call the |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 194 | // thunk when the user wants to call the original inline function. |
| 195 | // |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 196 | // This is not great runtime-performance-wise in regular builds (inline function |
| 197 | // will not be inlined, there will always be a function call), but it is |
| 198 | // correct. ThinLTO builds will be able to see through the thunk and inline |
| 199 | // code across the language boundary. For non-ThinLTO builds we plan to |
| 200 | // implement <internal link> which removes the runtime performance overhead. |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 201 | if func.is_inline { |
| 202 | return false; |
| 203 | } |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 204 | // ## Member functions (or descendants) of class templates |
| 205 | // |
| 206 | // A thunk is required to force/guarantee template instantiation. |
| 207 | if func.is_member_or_descendant_of_class_template { |
| 208 | return false; |
| 209 | } |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 210 | // ## Virtual functions |
| 211 | // |
| 212 | // When calling virtual `A::Method()`, it's not necessarily the case that we'll |
| 213 | // specifically call the concrete `A::Method` impl. For example, if this is |
| 214 | // called on something whose dynamic type is some subclass `B` with an |
| 215 | // overridden `B::Method`, then we'll call that. |
| 216 | // |
| 217 | // We must reuse the C++ dynamic dispatching system. In this case, the easiest |
| 218 | // way to do it is by resorting to a C++ thunk, whose implementation will do |
| 219 | // the lookup. |
| 220 | // |
| 221 | // In terms of runtime performance, since this only occurs for virtual function |
| 222 | // calls, which are already slow, it may not be such a big deal. We can |
| 223 | // benchmark it later. :) |
| 224 | if let Some(meta) = &func.member_func_metadata { |
| 225 | if let Some(inst_meta) = &meta.instance_method_metadata { |
| 226 | if inst_meta.is_virtual { |
| 227 | return false; |
| 228 | } |
| 229 | } |
| 230 | } |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 231 | // ## Custom calling convention requires a thunk. |
| 232 | // |
| 233 | // The thunk has the "C" calling convention, and internally can call the |
| 234 | // C++ function using any of the calling conventions supported by the C++ |
| 235 | // compiler (which might not always match the set supported by Rust - e.g., |
| 236 | // abi.rs doesn't contain "swiftcall" from |
| 237 | // clang::FunctionType::getNameForCallConv) |
| 238 | if !func.has_c_calling_convention { |
| 239 | return false; |
| 240 | } |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 241 | |
| 242 | true |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 243 | } |
| 244 | |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 245 | /// Uniquely identifies a generated Rust function. |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 246 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 247 | struct FunctionId { |
| 248 | // If the function is on a trait impl, contains the name of the Self type for |
| 249 | // which the trait is being implemented. |
| 250 | self_type: Option<syn::Path>, |
| 251 | // Fully qualified path of the function. For functions in impl blocks, this |
| 252 | // includes the name of the type or trait on which the function is being |
| 253 | // implemented, e.g. `Default::default`. |
| 254 | function_path: syn::Path, |
| 255 | } |
| 256 | |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 257 | /// Returns the name of `func` in C++ syntax. |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 258 | fn cxx_function_name(func: &Func, ir: &IR) -> Result<String> { |
Devin Jeanpierre | bdfb4d9 | 2022-06-17 01:17:01 -0700 | [diff] [blame] | 259 | let record: Option<&str> = ir.record_for_member_func(func)?.map(|r| &*r.cc_name); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 260 | |
| 261 | let func_name = match &func.name { |
| 262 | UnqualifiedIdentifier::Identifier(id) => id.identifier.clone(), |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 263 | UnqualifiedIdentifier::Operator(op) => op.cc_name(), |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 264 | UnqualifiedIdentifier::Destructor => { |
| 265 | format!("~{}", record.expect("destructor must be associated with a record")) |
| 266 | } |
| 267 | UnqualifiedIdentifier::Constructor => { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 268 | record.expect("constructor must be associated with a record").to_string() |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 269 | } |
| 270 | }; |
| 271 | |
| 272 | if let Some(record_name) = record { |
| 273 | Ok(format!("{}::{}", record_name, func_name)) |
| 274 | } else { |
| 275 | Ok(func_name) |
| 276 | } |
| 277 | } |
| 278 | |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 279 | fn make_unsupported_fn(func: &Func, ir: &IR, message: impl ToString) -> Result<UnsupportedItem> { |
| 280 | Ok(UnsupportedItem { |
| 281 | name: cxx_function_name(func, ir)?, |
| 282 | message: message.to_string(), |
| 283 | source_loc: func.source_loc.clone(), |
Rosica Dejanovska | d638cf5 | 2022-03-23 15:45:01 +0000 | [diff] [blame] | 284 | id: func.id, |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 285 | }) |
| 286 | } |
| 287 | |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 288 | /// The name of a one-function trait, with extra entries for |
| 289 | /// specially-understood traits and families of traits. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 290 | enum TraitName { |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 291 | /// The constructor trait for !Unpin types, with a list of parameter types. |
| 292 | /// For example, `CtorNew(vec![])` is the default constructor. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 293 | CtorNew(Vec<RsTypeKind>), |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 294 | /// An Unpin constructor trait, e.g. From or Clone, with a list of parameter |
| 295 | /// types. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 296 | UnpinConstructor { name: TokenStream, params: Vec<RsTypeKind> }, |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 297 | /// Any other trait, e.g. Eq. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 298 | Other { name: TokenStream, params: Vec<RsTypeKind>, is_unsafe_fn: bool }, |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 299 | } |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 300 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 301 | impl TraitName { |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 302 | /// Returns the generic parameters in this trait name. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 303 | fn params(&self) -> impl Iterator<Item = &RsTypeKind> { |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 304 | match self { |
| 305 | Self::CtorNew(params) |
| 306 | | Self::UnpinConstructor { params, .. } |
| 307 | | Self::Other { params, .. } => params.iter(), |
| 308 | } |
| 309 | } |
| 310 | |
| 311 | /// Returns the lifetimes used in this trait name. |
| 312 | pub fn lifetimes(&self) -> impl Iterator<Item = LifetimeId> + '_ { |
| 313 | self.params().flat_map(|p| p.lifetimes()) |
| 314 | } |
| 315 | } |
| 316 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 317 | impl ToTokens for TraitName { |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 318 | fn to_tokens(&self, tokens: &mut TokenStream) { |
| 319 | match self { |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 320 | Self::UnpinConstructor { name, params } | Self::Other { name, params, .. } => { |
| 321 | let params = format_generic_params(params); |
| 322 | quote! {#name #params}.to_tokens(tokens) |
| 323 | } |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 324 | Self::CtorNew(arg_types) => { |
| 325 | let arg_types = format_tuple_except_singleton(arg_types); |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 326 | quote! { ::ctor::CtorNew < #arg_types > }.to_tokens(tokens) |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 327 | } |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | /// The kind of the `impl` block the function needs to be generated in. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 333 | enum ImplKind { |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 334 | /// Used for free functions for which we don't want the `impl` block. |
| 335 | None { is_unsafe: bool }, |
| 336 | /// Used for inherent methods for which we need an `impl SomeStruct { ... }` |
| 337 | /// block. |
| 338 | Struct { |
| 339 | /// For example, `SomeStruct`. Retrieved from |
| 340 | /// `func.member_func_metadata`. |
| 341 | record_name: Ident, |
| 342 | is_unsafe: bool, |
| 343 | /// Whether to format the first parameter as "self" (e.g. `__this: |
| 344 | /// &mut T` -> `&mut self`) |
| 345 | format_first_param_as_self: bool, |
| 346 | }, |
| 347 | /// Used for trait methods for which we need an `impl TraitName for |
| 348 | /// SomeStruct { ... }` block. |
| 349 | Trait { |
| 350 | /// For example, `SomeStruct`. |
| 351 | /// Note that `record_name` might *not* be from |
| 352 | /// `func.member_func_metadata`. |
| 353 | record_name: Ident, |
| 354 | /// For example, `quote!{ From<i32> }`. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 355 | trait_name: TraitName, |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 356 | |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 357 | /// The generic params of trait `impl` (e.g. `<'b>`). These start |
| 358 | /// empty and only later are mutated into the correct value. |
| 359 | trait_generic_params: TokenStream, |
| 360 | /// Whether to format the first parameter as "self" (e.g. `__this: |
| 361 | /// &mut T` -> `&mut self`) |
| 362 | format_first_param_as_self: bool, |
| 363 | }, |
| 364 | } |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 365 | impl ImplKind { |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 366 | fn new_trait( |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 367 | trait_name: TraitName, |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 368 | record_name: Ident, |
| 369 | format_first_param_as_self: bool, |
| 370 | ) -> Self { |
| 371 | ImplKind::Trait { |
| 372 | trait_name, |
| 373 | record_name, |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 374 | trait_generic_params: quote! {}, |
| 375 | format_first_param_as_self, |
| 376 | } |
| 377 | } |
| 378 | fn format_first_param_as_self(&self) -> bool { |
| 379 | matches!( |
| 380 | self, |
| 381 | Self::Trait { format_first_param_as_self: true, .. } |
| 382 | | Self::Struct { format_first_param_as_self: true, .. } |
| 383 | ) |
| 384 | } |
| 385 | /// Returns whether the function is defined as `unsafe fn ...`. |
| 386 | fn is_unsafe(&self) -> bool { |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 387 | matches!( |
| 388 | self, |
| 389 | Self::None { is_unsafe: true, .. } |
| 390 | | Self::Struct { is_unsafe: true, .. } |
| 391 | | Self::Trait { trait_name: TraitName::Other { is_unsafe_fn: true, .. }, .. } |
| 392 | ) |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 393 | } |
| 394 | } |
| 395 | |
| 396 | /// Returns the shape of the generated Rust API for a given function definition. |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 397 | /// |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 398 | /// Returns: |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 399 | /// |
| 400 | /// * `Err(_)`: something went wrong importing this function. |
| 401 | /// * `Ok(None)`: the function imported as "nothing". (For example, a defaulted |
| 402 | /// destructor might be mapped to no `Drop` impl at all.) |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 403 | /// * `Ok((func_name, impl_kind))`: The function name and ImplKind. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 404 | fn api_func_shape( |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 405 | func: &Func, |
| 406 | ir: &IR, |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 407 | param_types: &[RsTypeKind], |
| 408 | ) -> Result<Option<(Ident, ImplKind)>> { |
| 409 | let maybe_record: Option<&Rc<Record>> = ir.record_for_member_func(func)?; |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 410 | let has_pointer_params = param_types.iter().any(|p| matches!(p, RsTypeKind::Pointer { .. })); |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 411 | let impl_kind: ImplKind; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 412 | let func_name: syn::Ident; |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 413 | match &func.name { |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 414 | UnqualifiedIdentifier::Operator(op) if op.name == "==" => { |
Devin Jeanpierre | 8dd193a | 2022-06-03 10:57:21 -0700 | [diff] [blame] | 415 | assert_eq!( |
| 416 | param_types.len(), |
| 417 | 2, |
| 418 | "Unexpected number of parameters in operator==: {func:?}" |
| 419 | ); |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 420 | match (¶m_types[0], ¶m_types[1]) { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 421 | ( |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 422 | RsTypeKind::Reference { referent: lhs, mutability: Mutability::Const, .. }, |
| 423 | RsTypeKind::Reference { referent: rhs, mutability: Mutability::Const, .. }, |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 424 | ) => match &**lhs { |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 425 | RsTypeKind::Record { record: lhs_record, .. } => { |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 426 | let lhs: Ident = make_rs_ident(&lhs_record.rs_name); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 427 | func_name = make_rs_ident("eq"); |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 428 | impl_kind = ImplKind::new_trait( |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 429 | TraitName::Other { |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 430 | name: quote! {PartialEq}, |
| 431 | params: vec![(**rhs).clone()], |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 432 | is_unsafe_fn: false, |
| 433 | }, |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 434 | lhs, |
| 435 | /* format_first_param_as_self= */ true, |
| 436 | ); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 437 | } |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 438 | _ => { |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 439 | bail!("operator== where lhs doesn't refer to a record",); |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 440 | } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 441 | }, |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 442 | _ => { |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 443 | bail!("operator== where operands are not const references",); |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 444 | } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 445 | }; |
| 446 | } |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 447 | UnqualifiedIdentifier::Operator(op) if op.name == "=" => { |
| 448 | assert_eq!( |
| 449 | param_types.len(), |
| 450 | 2, |
| 451 | "Unexpected number of parameters in operator=: {func:?}" |
| 452 | ); |
| 453 | let record = |
| 454 | maybe_record.ok_or_else(|| anyhow!("operator= must be a member function."))?; |
| 455 | if record.is_unpin() { |
| 456 | bail!("operator= for Unpin types is not yet supported."); |
| 457 | } |
| 458 | let rhs = ¶m_types[1]; |
| 459 | impl_kind = ImplKind::new_trait( |
| 460 | TraitName::Other { |
| 461 | name: quote! {::ctor::Assign}, |
| 462 | params: vec![rhs.clone()], |
| 463 | is_unsafe_fn: false, |
| 464 | }, |
| 465 | make_rs_ident(&record.rs_name), |
| 466 | /* format_first_param_as_self= */ true, |
| 467 | ); |
| 468 | func_name = make_rs_ident("assign"); |
| 469 | } |
Devin Jeanpierre | dd390a5 | 2022-06-08 12:52:52 -0700 | [diff] [blame] | 470 | UnqualifiedIdentifier::Operator(op) => { |
| 471 | bail!( |
| 472 | "Bindings for this kind of operator (operator {op}) are not supported", |
| 473 | op = &op.name |
| 474 | ); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 475 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 476 | UnqualifiedIdentifier::Identifier(id) => { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 477 | func_name = make_rs_ident(&id.identifier); |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 478 | match maybe_record { |
| 479 | None => { |
Devin Jeanpierre | 7c3d8ed | 2022-03-29 03:02:04 -0700 | [diff] [blame] | 480 | impl_kind = ImplKind::None { is_unsafe: has_pointer_params }; |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 481 | } |
| 482 | Some(record) => { |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 483 | let format_first_param_as_self = if func.is_instance_method() { |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 484 | let first_param = param_types.first().ok_or_else(|| { |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 485 | anyhow!("Missing `__this` parameter in an instance method: {:?}", func) |
| 486 | })?; |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 487 | first_param.is_ref_to(record) |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 488 | } else { |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 489 | false |
| 490 | }; |
Devin Jeanpierre | 6784e5e | 2022-03-29 02:59:01 -0700 | [diff] [blame] | 491 | impl_kind = ImplKind::Struct { |
| 492 | record_name: make_rs_ident(&record.rs_name), |
| 493 | format_first_param_as_self, |
Devin Jeanpierre | 7c3d8ed | 2022-03-29 03:02:04 -0700 | [diff] [blame] | 494 | is_unsafe: has_pointer_params, |
Devin Jeanpierre | 6784e5e | 2022-03-29 02:59:01 -0700 | [diff] [blame] | 495 | }; |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 496 | } |
| 497 | }; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 498 | } |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 499 | UnqualifiedIdentifier::Destructor => { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 500 | // Note: to avoid double-destruction of the fields, they are all wrapped in |
| 501 | // ManuallyDrop in this case. See `generate_record`. |
| 502 | let record = |
| 503 | maybe_record.ok_or_else(|| anyhow!("Destructors must be member functions."))?; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 504 | if !should_implement_drop(record) { |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 505 | return Ok(None); |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 506 | } |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 507 | if record.is_unpin() { |
| 508 | impl_kind = ImplKind::new_trait( |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 509 | TraitName::Other { name: quote! {Drop}, params: vec![], is_unsafe_fn: false }, |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 510 | make_rs_ident(&record.rs_name), |
| 511 | /* format_first_param_as_self= */ true, |
| 512 | ); |
| 513 | func_name = make_rs_ident("drop"); |
| 514 | } else { |
| 515 | impl_kind = ImplKind::new_trait( |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 516 | TraitName::Other { |
| 517 | name: quote! {::ctor::PinnedDrop}, |
| 518 | params: vec![], |
| 519 | is_unsafe_fn: true, |
| 520 | }, |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 521 | make_rs_ident(&record.rs_name), |
| 522 | /* format_first_param_as_self= */ true, |
| 523 | ); |
| 524 | func_name = make_rs_ident("pinned_drop"); |
| 525 | } |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 526 | } |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 527 | UnqualifiedIdentifier::Constructor => { |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 528 | let member_func_metadata = func |
| 529 | .member_func_metadata |
| 530 | .as_ref() |
| 531 | .ok_or_else(|| anyhow!("Constructors must be member functions."))?; |
| 532 | let record = maybe_record |
| 533 | .ok_or_else(|| anyhow!("Constructors must be associated with a record."))?; |
| 534 | let instance_method_metadata = |
| 535 | member_func_metadata |
| 536 | .instance_method_metadata |
| 537 | .as_ref() |
| 538 | .ok_or_else(|| anyhow!("Constructors must be instance methods."))?; |
Devin Jeanpierre | 7c3d8ed | 2022-03-29 03:02:04 -0700 | [diff] [blame] | 539 | if has_pointer_params { |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 540 | // TODO(b/216648347): Allow this outside of traits (e.g. after supporting |
| 541 | // translating C++ constructors into static methods in Rust). |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 542 | bail!( |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 543 | "Unsafe constructors (e.g. with no elided or explicit lifetimes) \ |
| 544 | are intentionally not supported", |
| 545 | ); |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 546 | } |
| 547 | |
Devin Jeanpierre | 6784e5e | 2022-03-29 02:59:01 -0700 | [diff] [blame] | 548 | let record_name = make_rs_ident(&record.rs_name); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 549 | if !record.is_unpin() { |
| 550 | func_name = make_rs_ident("ctor_new"); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 551 | |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 552 | match param_types { |
| 553 | [] => bail!("Missing `__this` parameter in a constructor: {:?}", func), |
| 554 | [_this, params @ ..] => { |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 555 | impl_kind = ImplKind::new_trait( |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 556 | TraitName::CtorNew(params.iter().cloned().collect()), |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 557 | record_name, |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 558 | /* format_first_param_as_self= */ false, |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 559 | ); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 560 | } |
Lukasz Anforowicz | 73326af | 2022-01-05 01:13:10 +0000 | [diff] [blame] | 561 | } |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 562 | } else { |
| 563 | match func.params.len() { |
| 564 | 0 => bail!("Missing `__this` parameter in a constructor: {:?}", func), |
| 565 | 1 => { |
| 566 | impl_kind = ImplKind::new_trait( |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 567 | TraitName::UnpinConstructor { name: quote! {Default}, params: vec![] }, |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 568 | record_name, |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 569 | /* format_first_param_as_self= */ false, |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 570 | ); |
| 571 | func_name = make_rs_ident("default"); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 572 | } |
| 573 | 2 => { |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 574 | if param_types[1].is_shared_ref_to(record) { |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 575 | // Copy constructor |
| 576 | if should_derive_clone(record) { |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 577 | return Ok(None); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 578 | } else { |
| 579 | impl_kind = ImplKind::new_trait( |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 580 | TraitName::UnpinConstructor { |
| 581 | name: quote! {Clone}, |
| 582 | params: vec![], |
| 583 | }, |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 584 | record_name, |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 585 | /* format_first_param_as_self= */ true, |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 586 | ); |
| 587 | func_name = make_rs_ident("clone"); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 588 | } |
| 589 | } else if !instance_method_metadata.is_explicit_ctor { |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 590 | let param_type = ¶m_types[1]; |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 591 | impl_kind = ImplKind::new_trait( |
| 592 | TraitName::UnpinConstructor { |
| 593 | name: quote! {From}, |
| 594 | params: vec![param_type.clone()], |
| 595 | }, |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 596 | record_name, |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 597 | /* format_first_param_as_self= */ false, |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 598 | ); |
| 599 | func_name = make_rs_ident("from"); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 600 | } else { |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 601 | bail!("Not yet supported type of constructor parameter",); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 602 | } |
| 603 | } |
| 604 | _ => { |
| 605 | // TODO(b/216648347): Support bindings for other constructors. |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 606 | bail!("More than 1 constructor parameter is not supported yet",); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 607 | } |
Lukasz Anforowicz | 73326af | 2022-01-05 01:13:10 +0000 | [diff] [blame] | 608 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 609 | } |
| 610 | } |
| 611 | } |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 612 | Ok(Some((func_name, impl_kind))) |
| 613 | } |
| 614 | |
| 615 | /// Generates Rust source code for a given `Func`. |
| 616 | /// |
| 617 | /// Returns: |
| 618 | /// |
| 619 | /// * `Err(_)`: couldn't import the function, emit an `UnsupportedItem`. |
| 620 | /// * `Ok(None)`: the function imported as "nothing". (For example, a defaulted |
| 621 | /// destructor might be mapped to no `Drop` impl at all.) |
| 622 | /// * `Ok((rs_api, rs_thunk, function_id))`: The Rust function definition, |
| 623 | /// thunk FFI definition, and function ID. |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 624 | fn generate_func( |
| 625 | db: &dyn BindingsGenerator, |
| 626 | func: Rc<Func>, |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 627 | ) -> Result<Option<PtrEq<Rc<(RsSnippet, RsSnippet, Rc<FunctionId>)>>>> { |
| 628 | let ir = db.ir(); |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 629 | let param_types = func |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 630 | .params |
| 631 | .iter() |
| 632 | .map(|p| { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 633 | db.rs_type_kind(p.type_.rs_type.clone()).with_context(|| { |
Devin Jeanpierre | 9c34da6 | 2022-03-31 04:57:16 -0700 | [diff] [blame] | 634 | format!("Failed to process type of parameter {:?} on {:?}", p, func) |
| 635 | }) |
| 636 | }) |
| 637 | .collect::<Result<Vec<_>>>()?; |
| 638 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 639 | let (func_name, mut impl_kind) = if let Some(values) = api_func_shape(&func, &ir, ¶m_types)? |
| 640 | { |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 641 | values |
| 642 | } else { |
| 643 | return Ok(None); |
| 644 | }; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 645 | |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 646 | let return_type_fragment = db |
| 647 | .rs_type_kind(func.return_type.rs_type.clone()) |
Devin Jeanpierre | 3a0cc5a | 2022-07-12 09:36:34 -0700 | [diff] [blame^] | 648 | .with_context(|| format!("Failed to format return type for {:?}", &func))? |
Devin Jeanpierre | 8c6ff6d | 2022-04-06 12:57:14 -0700 | [diff] [blame] | 649 | .format_as_return_type_fragment(); |
Devin Jeanpierre | d9cecff | 2022-03-29 02:53:58 -0700 | [diff] [blame] | 650 | let param_idents = |
| 651 | func.params.iter().map(|p| make_rs_ident(&p.identifier.identifier)).collect_vec(); |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 652 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 653 | let thunk = generate_func_thunk(&func, ¶m_idents, ¶m_types, &return_type_fragment)?; |
Devin Jeanpierre | d9cecff | 2022-03-29 02:53:58 -0700 | [diff] [blame] | 654 | |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 655 | let api_func_def = { |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 656 | let mut return_type_fragment = return_type_fragment; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 657 | let mut thunk_args = param_idents.iter().map(|id| quote! { #id}).collect_vec(); |
| 658 | let mut api_params = param_idents |
| 659 | .iter() |
| 660 | .zip(param_types.iter()) |
| 661 | .map(|(ident, type_)| quote! { #ident : #type_ }) |
| 662 | .collect_vec(); |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 663 | let mut lifetimes = func.lifetime_params.iter().collect_vec(); |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 664 | let mut maybe_first_api_param = param_types.get(0); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 665 | |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 666 | if let ImplKind::Trait { |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 667 | trait_name: trait_name @ (TraitName::UnpinConstructor { .. } | TraitName::CtorNew(..)), |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 668 | .. |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 669 | } = &impl_kind |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 670 | { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 671 | return_type_fragment = quote! { -> Self }; |
| 672 | |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 673 | // Drop `__this` parameter from the public Rust API. Presence of |
| 674 | // element #0 is indirectly verified by a `Constructor`-related |
| 675 | // `match` branch a little bit above. |
| 676 | api_params.remove(0); |
| 677 | thunk_args.remove(0); |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 678 | |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 679 | // Remove the lifetime associated with `__this`. |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 680 | ensure!( |
| 681 | func.return_type.rs_type.is_unit_type(), |
| 682 | "Unexpectedly non-void return type of a constructor: {:?}", |
| 683 | func |
| 684 | ); |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 685 | let maybe_first_lifetime = func.params[0].type_.rs_type.lifetime_args.first(); |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 686 | let no_longer_needed_lifetime_id = maybe_first_lifetime |
| 687 | .ok_or_else(|| anyhow!("Missing lifetime on `__this` parameter: {:?}", func))?; |
| 688 | lifetimes.retain(|l| l.id != *no_longer_needed_lifetime_id); |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 689 | if let Some(type_still_dependent_on_removed_lifetime) = param_types |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 690 | .iter() |
| 691 | .skip(1) // Skipping `__this` |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 692 | .flat_map(|t| t.lifetimes()) |
| 693 | .find(|lifetime_id| *lifetime_id == *no_longer_needed_lifetime_id) |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 694 | { |
| 695 | bail!( |
| 696 | "The lifetime of `__this` is unexpectedly also used by another \ |
| 697 | parameter {:?} in function {:?}", |
| 698 | type_still_dependent_on_removed_lifetime, |
| 699 | func.name |
| 700 | ); |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 701 | } |
| 702 | |
| 703 | // Rebind `maybe_first_api_param` to the next param after `__this`. |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 704 | maybe_first_api_param = param_types.get(1); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 705 | |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 706 | if let TraitName::CtorNew(args_type) = trait_name { |
| 707 | // CtorNew has no self param, so this should never be used -- and we should fail |
| 708 | // if it is. |
| 709 | maybe_first_api_param = None; |
| 710 | |
| 711 | return_type_fragment = quote! { -> Self::CtorType }; |
| 712 | let args_type = format_tuple_except_singleton(args_type); |
| 713 | api_params = vec![quote! {args: #args_type}]; |
| 714 | } |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 715 | } |
| 716 | |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 717 | // Change `__this: &'a SomeStruct` into `&'a self` if needed. |
Devin Jeanpierre | d9a6e6c | 2022-03-29 02:55:41 -0700 | [diff] [blame] | 718 | if impl_kind.format_first_param_as_self() { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 719 | let first_api_param = maybe_first_api_param |
| 720 | .ok_or_else(|| anyhow!("No parameter to format as 'self': {:?}", func))?; |
Devin Jeanpierre | 8a4fa20 | 2022-06-08 12:33:11 -0700 | [diff] [blame] | 721 | let self_decl = first_api_param.format_as_self_param()?; |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 722 | // Presence of element #0 is verified by `ok_or_else` on |
| 723 | // `maybe_first_api_param` above. |
| 724 | api_params[0] = self_decl; |
| 725 | thunk_args[0] = quote! { self }; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 726 | } |
| 727 | |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 728 | // TODO(b/200067242): the Pin-wrapping code doesn't know to wrap &mut |
| 729 | // MaybeUninit<T> in Pin if T is !Unpin. It should understand |
| 730 | // 'structural pinning', so that we do not need into_inner_unchecked() |
| 731 | // here. |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 732 | let thunk_ident = thunk_ident(&func); |
Devin Jeanpierre | 7bddfdb | 2022-03-14 11:04:40 +0000 | [diff] [blame] | 733 | let func_body = match &impl_kind { |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 734 | ImplKind::Trait { trait_name: TraitName::CtorNew(..), .. } => { |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 735 | let thunk_vars = format_tuple_except_singleton(&thunk_args); |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 736 | // TODO(b/226447239): check for copy here and instead use copies in that case? |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 737 | quote! { |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 738 | let #thunk_vars = args; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 739 | ::ctor::FnCtor::new(move |dest: ::std::pin::Pin<&mut ::std::mem::MaybeUninit<Self>>| { |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 740 | unsafe { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 741 | crate::detail::#thunk_ident(::std::pin::Pin::into_inner_unchecked(dest) #( , #thunk_args )*); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 742 | } |
| 743 | }) |
| 744 | } |
| 745 | } |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 746 | ImplKind::Trait { trait_name: TraitName::UnpinConstructor { .. }, .. } => { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 747 | // SAFETY: A user-defined constructor is not guaranteed to |
| 748 | // initialize all the fields. To make the `assume_init()` call |
| 749 | // below safe, the memory is zero-initialized first. This is a |
| 750 | // bit safer, because zero-initialized memory represents a valid |
| 751 | // value for the currently supported field types (this may |
| 752 | // change once the bindings generator starts supporting |
| 753 | // reference fields). TODO(b/213243309): Double-check if |
| 754 | // zero-initialization is desirable here. |
| 755 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 756 | let mut tmp = ::std::mem::MaybeUninit::<Self>::zeroed(); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 757 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 758 | crate::detail::#thunk_ident( &mut tmp #( , #thunk_args )* ); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 759 | tmp.assume_init() |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 760 | } |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 761 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 762 | } |
Devin Jeanpierre | 7bddfdb | 2022-03-14 11:04:40 +0000 | [diff] [blame] | 763 | _ => { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 764 | let mut body = quote! { crate::detail::#thunk_ident( #( #thunk_args ),* ) }; |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 765 | // Somewhat hacky: discard the return value for operator=. |
| 766 | if let UnqualifiedIdentifier::Operator(op) = &func.name { |
| 767 | if op.name == "=" { |
| 768 | body = quote! { #body; }; |
| 769 | return_type_fragment = quote! {}; |
| 770 | } |
| 771 | } |
Devin Jeanpierre | 7bddfdb | 2022-03-14 11:04:40 +0000 | [diff] [blame] | 772 | // Only need to wrap everything in an `unsafe { ... }` block if |
| 773 | // the *whole* api function is safe. |
Devin Jeanpierre | 7c3d8ed | 2022-03-29 03:02:04 -0700 | [diff] [blame] | 774 | if !impl_kind.is_unsafe() { |
Devin Jeanpierre | 7bddfdb | 2022-03-14 11:04:40 +0000 | [diff] [blame] | 775 | body = quote! { unsafe { #body } }; |
| 776 | } |
| 777 | body |
| 778 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 779 | }; |
| 780 | |
Devin Jeanpierre | 7c3d8ed | 2022-03-29 03:02:04 -0700 | [diff] [blame] | 781 | let pub_ = match impl_kind { |
| 782 | ImplKind::None { .. } | ImplKind::Struct { .. } => quote! { pub }, |
| 783 | ImplKind::Trait { .. } => quote! {}, |
| 784 | }; |
| 785 | let unsafe_ = if impl_kind.is_unsafe() { |
| 786 | quote! { unsafe } |
| 787 | } else { |
| 788 | quote! {} |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 789 | }; |
| 790 | |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 791 | let fn_generic_params: TokenStream; |
Devin Jeanpierre | e77fa7e | 2022-06-02 14:05:58 -0700 | [diff] [blame] | 792 | if let ImplKind::Trait { trait_name, trait_generic_params, .. } = &mut impl_kind { |
| 793 | let trait_lifetimes: HashSet<LifetimeId> = trait_name.lifetimes().collect(); |
| 794 | fn_generic_params = format_generic_params( |
| 795 | lifetimes.iter().filter(|lifetime| !trait_lifetimes.contains(&lifetime.id)), |
| 796 | ); |
| 797 | *trait_generic_params = format_generic_params( |
| 798 | lifetimes.iter().filter(|lifetime| trait_lifetimes.contains(&lifetime.id)), |
| 799 | ); |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 800 | } else { |
| 801 | fn_generic_params = format_generic_params(lifetimes); |
| 802 | } |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 803 | |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 804 | quote! { |
| 805 | #[inline(always)] |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 806 | #pub_ #unsafe_ fn #func_name #fn_generic_params( |
| 807 | #( #api_params ),* ) #return_type_fragment { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 808 | #func_body |
| 809 | } |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 810 | } |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 811 | }; |
| 812 | |
Devin Jeanpierre | d9cecff | 2022-03-29 02:53:58 -0700 | [diff] [blame] | 813 | let doc_comment = generate_doc_comment(&func.doc_comment); |
| 814 | let mut features = BTreeSet::new(); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 815 | let api_func: TokenStream; |
| 816 | let function_id: FunctionId; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 817 | match impl_kind { |
Devin Jeanpierre | 7c3d8ed | 2022-03-29 03:02:04 -0700 | [diff] [blame] | 818 | ImplKind::None { .. } => { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 819 | api_func = quote! { #doc_comment #api_func_def }; |
| 820 | function_id = FunctionId { self_type: None, function_path: func_name.into() }; |
| 821 | } |
Devin Jeanpierre | 6784e5e | 2022-03-29 02:59:01 -0700 | [diff] [blame] | 822 | ImplKind::Struct { record_name, .. } => { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 823 | api_func = quote! { impl #record_name { #doc_comment #api_func_def } }; |
| 824 | function_id = FunctionId { |
| 825 | self_type: None, |
| 826 | function_path: syn::parse2(quote! { #record_name :: #func_name })?, |
| 827 | }; |
| 828 | } |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 829 | ImplKind::Trait { trait_name, record_name, trait_generic_params, .. } => { |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 830 | let extra_body; |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 831 | let extra_items; |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 832 | match &trait_name { |
| 833 | TraitName::CtorNew(params) => { |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 834 | // This feature seems destined for stabilization, and makes the code |
| 835 | // simpler. |
| 836 | features.insert(make_rs_ident("type_alias_impl_trait")); |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 837 | extra_body = quote! {type CtorType = impl ::ctor::Ctor<Output = Self>;}; |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 838 | |
| 839 | if let [single_param] = params.as_slice() { |
| 840 | extra_items = quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 841 | impl #trait_generic_params ::ctor::CtorNew<(#single_param,)> for #record_name { |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 842 | #extra_body |
| 843 | |
| 844 | #[inline (always)] |
| 845 | fn ctor_new(args: (#single_param,)) -> Self::CtorType { |
| 846 | let (arg,) = args; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 847 | <Self as ::ctor::CtorNew<#single_param>>::ctor_new(arg) |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 848 | } |
| 849 | } |
| 850 | } |
| 851 | } else { |
| 852 | extra_items = quote! {} |
| 853 | } |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 854 | } |
| 855 | _ => { |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 856 | extra_body = quote! {}; |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 857 | extra_items = quote! {}; |
| 858 | } |
| 859 | }; |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 860 | api_func = quote! { |
| 861 | #doc_comment |
| 862 | impl #trait_generic_params #trait_name for #record_name { |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 863 | #extra_body |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 864 | #api_func_def |
| 865 | } |
Devin Jeanpierre | 46d515c | 2022-05-03 02:36:54 -0700 | [diff] [blame] | 866 | #extra_items |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 867 | }; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 868 | function_id = FunctionId { |
| 869 | self_type: Some(record_name.into()), |
| 870 | function_path: syn::parse2(quote! { #trait_name :: #func_name })?, |
| 871 | }; |
| 872 | } |
| 873 | } |
| 874 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 875 | Ok(Some(PtrEq(Rc::new(( |
| 876 | RsSnippet { features, tokens: api_func }, |
| 877 | thunk.into(), |
| 878 | Rc::new(function_id), |
| 879 | ))))) |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 880 | } |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 881 | |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 882 | fn generate_func_thunk( |
| 883 | func: &Func, |
| 884 | param_idents: &[Ident], |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 885 | param_types: &[RsTypeKind], |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 886 | return_type_fragment: &TokenStream, |
| 887 | ) -> Result<TokenStream> { |
| 888 | let thunk_attr = if can_skip_cc_thunk(func) { |
| 889 | let mangled_name = &func.mangled_name; |
| 890 | quote! {#[link_name = #mangled_name]} |
| 891 | } else { |
| 892 | quote! {} |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 893 | }; |
| 894 | |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 895 | // For constructors, inject MaybeUninit into the type of `__this_` parameter. |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 896 | let mut param_types = param_types.into_iter(); |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 897 | let mut self_param = None; |
| 898 | if func.name == UnqualifiedIdentifier::Constructor { |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 899 | let first_param = param_types |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 900 | .next() |
| 901 | .ok_or_else(|| anyhow!("Constructors should have at least one parameter (__this)"))?; |
| 902 | self_param = Some(first_param.format_mut_ref_as_uninitialized().with_context(|| { |
| 903 | format!( |
| 904 | "Failed to format `__this` param for a constructor thunk: {:?}", |
| 905 | func.params.get(0) |
| 906 | ) |
| 907 | })?); |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 908 | } |
| 909 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 910 | let thunk_ident = thunk_ident(&func); |
Devin Jeanpierre | a68fdbc | 2022-05-27 04:16:36 -0700 | [diff] [blame] | 911 | let lifetimes = func.lifetime_params.iter(); |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 912 | let generic_params = format_generic_params(lifetimes); |
Devin Jeanpierre | 22f9149 | 2022-04-06 13:01:23 -0700 | [diff] [blame] | 913 | let param_types = self_param.into_iter().chain(param_types.map(|t| quote! {#t})); |
Devin Jeanpierre | 3eb5bbd | 2022-04-06 12:56:19 -0700 | [diff] [blame] | 914 | |
| 915 | Ok(quote! { |
| 916 | #thunk_attr |
| 917 | pub(crate) fn #thunk_ident #generic_params( #( #param_idents: #param_types ),* |
| 918 | ) #return_type_fragment ; |
| 919 | }) |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 920 | } |
| 921 | |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 922 | fn generate_doc_comment(comment: &Option<String>) -> TokenStream { |
| 923 | match comment { |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 924 | Some(text) => { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 925 | // token_stream_printer (and rustfmt) don't put a space between /// and the doc |
| 926 | // comment, let's add it here so our comments are pretty. |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 927 | let doc = format!(" {}", text.replace('\n', "\n ")); |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 928 | quote! {#[doc=#doc]} |
| 929 | } |
| 930 | None => quote! {}, |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 931 | } |
| 932 | } |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 933 | |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 934 | fn format_generic_params<T: ToTokens>(params: impl IntoIterator<Item = T>) -> TokenStream { |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 935 | let mut params = params.into_iter().peekable(); |
| 936 | if params.peek().is_none() { |
| 937 | quote! {} |
| 938 | } else { |
| 939 | quote! { < #( #params ),* > } |
| 940 | } |
| 941 | } |
| 942 | |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 943 | /// Formats singletons as themselves, and collections of n!=1 items as a tuple. |
| 944 | /// |
| 945 | /// In other words, this formats a collection of things as if via `#(#items),*`, |
| 946 | /// but without lint warnings. |
| 947 | /// |
| 948 | /// For example: |
| 949 | /// |
| 950 | /// * [] => () |
| 951 | /// * [x] => x // equivalent to (x), but lint-free. |
| 952 | /// * [x, y] => (x, y) |
| 953 | fn format_tuple_except_singleton<T: ToTokens>(items: &[T]) -> TokenStream { |
| 954 | match items { |
| 955 | [singleton] => quote! {#singleton}, |
| 956 | items => quote! {(#(#items),*)}, |
| 957 | } |
| 958 | } |
| 959 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 960 | fn should_implement_drop(record: &Record) -> bool { |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 961 | match record.destructor { |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 962 | // TODO(b/202258760): Only omit destructor if `Copy` is specified. |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 963 | SpecialMemberFunc::Trivial => false, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 964 | |
| 965 | // TODO(b/212690698): Avoid calling into the C++ destructor (e.g. let |
| 966 | // Rust drive `drop`-ing) to avoid (somewhat unergonomic) ManuallyDrop |
| 967 | // if we can ask Rust to preserve C++ field destruction order in |
| 968 | // NontrivialMembers case. |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 969 | SpecialMemberFunc::NontrivialMembers => true, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 970 | |
| 971 | // The `impl Drop` for NontrivialUserDefined needs to call into the |
| 972 | // user-defined destructor on C++ side. |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 973 | SpecialMemberFunc::NontrivialUserDefined => true, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 974 | |
| 975 | // TODO(b/213516512): Today the IR doesn't contain Func entries for |
| 976 | // deleted functions/destructors/etc. But, maybe we should generate |
| 977 | // `impl Drop` in this case? With `unreachable!`? With |
| 978 | // `std::mem::forget`? |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 979 | SpecialMemberFunc::Unavailable => false, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 980 | } |
| 981 | } |
| 982 | |
| 983 | /// Returns whether fields of type `ty` need to be wrapped in `ManuallyDrop<T>` |
| 984 | /// to prevent the fields from being destructed twice (once by the C++ |
| 985 | /// destructor calkled from the `impl Drop` of the struct and once by `drop` on |
| 986 | /// the Rust side). |
| 987 | /// |
| 988 | /// A type is safe to destroy twice if it implements `Copy`. Fields of such |
| 989 | /// don't need to be wrapped in `ManuallyDrop<T>` even if the struct |
| 990 | /// containing the fields provides an `impl Drop` that calles into a C++ |
| 991 | /// destructor (in addition to dropping the fields on the Rust side). |
| 992 | /// |
| 993 | /// Note that it is not enough to just be `!needs_drop<T>()`: Rust only |
| 994 | /// guarantees that it is safe to use-after-destroy for `Copy` types. See |
| 995 | /// e.g. the documentation for |
| 996 | /// [`drop_in_place`](https://doc.rust-lang.org/std/ptr/fn.drop_in_place.html): |
| 997 | /// |
| 998 | /// > if `T` is not `Copy`, using the pointed-to value after calling |
| 999 | /// > `drop_in_place` can cause undefined behavior |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 1000 | /// |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1001 | /// For non-Copy union fields, failing to use `ManuallyDrop<T>` would |
| 1002 | /// additionally cause a compile-time error until https://github.com/rust-lang/rust/issues/55149 is stabilized. |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1003 | fn needs_manually_drop(db: &Database, ty: ir::RsType) -> Result<bool> { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1004 | let ty_implements_copy = db.rs_type_kind(ty)?.implements_copy(); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1005 | Ok(!ty_implements_copy) |
| 1006 | } |
| 1007 | |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 1008 | /// Returns the namespace qualifier for the given item. |
| 1009 | fn generate_namespace_qualifier(item_id: ItemId, ir: &IR) -> Result<impl Iterator<Item = Ident>> { |
| 1010 | let mut namespaces = vec![]; |
| 1011 | let item: &Item = ir.find_decl(item_id)?; |
| 1012 | let mut enclosing_namespace_id = item.enclosing_namespace_id(); |
| 1013 | while let Some(parent_id) = enclosing_namespace_id { |
| 1014 | let namespace_item = ir.find_decl(parent_id)?; |
| 1015 | match namespace_item { |
| 1016 | Item::Namespace(ns) => { |
| 1017 | namespaces.push(make_rs_ident(&ns.name.identifier)); |
| 1018 | enclosing_namespace_id = ns.enclosing_namespace_id; |
| 1019 | } |
| 1020 | _ => { |
| 1021 | bail!("Expected namespace"); |
| 1022 | } |
| 1023 | } |
| 1024 | } |
| 1025 | Ok(namespaces.into_iter().rev()) |
| 1026 | } |
| 1027 | |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1028 | /// Generates Rust source code for a given incomplete record declaration. |
| 1029 | fn generate_incomplete_record(incomplete_record: &IncompleteRecord) -> Result<TokenStream> { |
Rosica Dejanovska | e12d717 | 2022-06-22 12:20:17 -0700 | [diff] [blame] | 1030 | let ident = make_rs_ident(&incomplete_record.rs_name); |
| 1031 | let name = &incomplete_record.rs_name; |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1032 | Ok(quote! { |
| 1033 | forward_declare::forward_declare!( |
| 1034 | pub #ident __SPACE__ = __SPACE__ forward_declare::symbol!(#name) |
| 1035 | ); |
| 1036 | }) |
| 1037 | } |
| 1038 | |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1039 | fn make_rs_field_ident(field: &Field, field_index: usize) -> Ident { |
| 1040 | match field.identifier.as_ref() { |
| 1041 | None => make_rs_ident(&format!("__unnamed_field{}", field_index)), |
| 1042 | Some(Identifier { identifier }) => make_rs_ident(identifier), |
| 1043 | } |
| 1044 | } |
| 1045 | |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1046 | /// Gets the type of `field` for layout purposes. |
| 1047 | /// |
| 1048 | /// Note that `get_field_rs_type_for_layout` may return Err (for |
| 1049 | /// `is_no_unique_address` fields) even if `field.type_` is Ok. |
| 1050 | fn get_field_rs_type_for_layout(field: &Field) -> Result<&RsType, &str> { |
| 1051 | // [[no_unique_address]] fields are replaced by a type-less, unaligned block of |
| 1052 | // memory which fills space up to the next field. |
Lukasz Anforowicz | 5765bb8 | 2022-05-17 17:21:06 -0700 | [diff] [blame] | 1053 | // See: docs/struct_layout |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1054 | if field.is_no_unique_address { |
| 1055 | return Err("`[[no_unique_address]]` attribute was present."); |
| 1056 | } |
| 1057 | |
| 1058 | field.type_.as_ref().map(|t| &t.rs_type).map_err(String::as_str) |
Lukasz Anforowicz | 5765bb8 | 2022-05-17 17:21:06 -0700 | [diff] [blame] | 1059 | } |
| 1060 | |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1061 | /// Returns the type of a type-less, unaligned block of memory that can hold a |
| 1062 | /// specified number of bits, rounded up to the next multiple of 8. |
| 1063 | fn bit_padding(padding_size_in_bits: usize) -> TokenStream { |
| 1064 | let padding_size = Literal::usize_unsuffixed((padding_size_in_bits + 7) / 8); |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1065 | quote! { [::std::mem::MaybeUninit<u8>; #padding_size] } |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1066 | } |
| 1067 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 1068 | /// Generates Rust source code for a given `Record` and associated assertions as |
| 1069 | /// a tuple. |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1070 | fn generate_record(db: &Database, record: &Rc<Record>) -> Result<GeneratedItem> { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1071 | let ir = db.ir(); |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 1072 | let ident = make_rs_ident(&record.rs_name); |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1073 | let namespace_qualifier = generate_namespace_qualifier(record.id, &ir)?; |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 1074 | let qualified_ident = { |
| 1075 | quote! { crate:: #(#namespace_qualifier::)* #ident } |
| 1076 | }; |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 1077 | let doc_comment = generate_doc_comment(&record.doc_comment); |
Lukasz Anforowicz | fed64e6 | 2022-03-22 22:39:04 +0000 | [diff] [blame] | 1078 | |
| 1079 | let mut field_copy_trait_assertions: Vec<TokenStream> = vec![]; |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1080 | |
| 1081 | let fields_with_bounds = (record.fields.iter()) |
| 1082 | .map(|field| { |
| 1083 | ( |
| 1084 | // We don't represent bitfields directly in Rust. We drop the field itself here |
| 1085 | // and only retain the offset information. Adjacent bitfields then get merged in |
| 1086 | // the next step. |
| 1087 | if field.is_bitfield { None } else { Some(field) }, |
| 1088 | field.offset, |
| 1089 | // We retain the end offset of fields only if we have a matching Rust type |
| 1090 | // to represent them. Otherwise we'll fill up all the space to the next field. |
| 1091 | // See: docs/struct_layout |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 1092 | match get_field_rs_type_for_layout(field) { |
| 1093 | // Regular field |
| 1094 | Ok(_rs_type) => Some(field.offset + field.size), |
| 1095 | // Opaque field |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1096 | Err(_error) => if record.is_union() { Some(field.size) } else { None }, |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 1097 | }, |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1098 | vec![format!( |
| 1099 | "{} : {} bits", |
| 1100 | field.identifier.as_ref().map(|i| i.identifier.clone()).unwrap_or("".into()), |
| 1101 | field.size |
| 1102 | )], |
| 1103 | ) |
| 1104 | }) |
| 1105 | // Merge consecutive bitfields. This is necessary, because they may share storage in the |
| 1106 | // same byte. |
| 1107 | .coalesce(|first, second| match (first, second) { |
| 1108 | ((None, offset, _, desc1), (None, _, end, desc2)) => { |
| 1109 | Ok((None, offset, end, [desc1, desc2].concat())) |
| 1110 | } |
| 1111 | pair => Err(pair), |
| 1112 | }); |
| 1113 | |
| 1114 | // Pair up fields with the preceeding and following fields (if any): |
| 1115 | // - the end offset of the previous field determines if we need to insert |
| 1116 | // padding. |
| 1117 | // - the start offset of the next field may be need to grow the current field to |
| 1118 | // there. |
| 1119 | // This uses two separate `map` invocations on purpose to limit available state. |
| 1120 | let field_definitions = iter::once(None) |
| 1121 | .chain(fields_with_bounds.clone().map(Some)) |
| 1122 | .chain(iter::once(None)) |
| 1123 | .tuple_windows() |
| 1124 | .map(|(prev, cur, next)| { |
| 1125 | let (field, offset, end, desc) = cur.unwrap(); |
| 1126 | let prev_end = prev.as_ref().map(|(_, _, e, _)| *e).flatten().unwrap_or(offset); |
| 1127 | let next_offset = next.map(|(_, o, _, _)| o); |
| 1128 | let end = end.or(next_offset).unwrap_or(record.size * 8); |
| 1129 | |
| 1130 | if let Some((Some(prev_field), _, Some(prev_end), _)) = prev { |
| 1131 | assert!( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1132 | record.is_union() || prev_end <= offset, |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1133 | "Unexpected offset+size for field {:?} in record {}", |
| 1134 | prev_field, |
| 1135 | record.cc_name |
| 1136 | ); |
| 1137 | } |
| 1138 | |
| 1139 | (field, prev_end, offset, end, desc) |
| 1140 | }) |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 1141 | .enumerate() |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1142 | .map(|(field_index, (field, prev_end, offset, end, desc))| { |
| 1143 | // `is_opaque_blob` and bitfield representations are always |
| 1144 | // unaligned, even though the actual C++ field might be aligned. |
| 1145 | // To put the current field at the right offset, we might need to |
| 1146 | // insert some extra padding. |
| 1147 | // |
| 1148 | // No padding should be needed if the type of the current field is |
| 1149 | // known (i.e. if the current field is correctly aligned based on |
| 1150 | // its original type). |
| 1151 | // |
| 1152 | // We also don't need padding if we're in a union. |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1153 | let padding_size_in_bits = if record.is_union() |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1154 | || (field.is_some() && get_field_rs_type_for_layout(field.unwrap()).is_ok()) |
| 1155 | { |
| 1156 | 0 |
| 1157 | } else { |
| 1158 | let padding_start = (prev_end + 7) / 8 * 8; // round up to byte boundary |
| 1159 | offset - padding_start |
| 1160 | }; |
| 1161 | |
| 1162 | let padding = if padding_size_in_bits == 0 { |
| 1163 | quote! {} |
| 1164 | } else { |
| 1165 | let padding_name = make_rs_ident(&format!("__padding{}", field_index)); |
| 1166 | let padding_type = bit_padding(padding_size_in_bits); |
| 1167 | quote! { #padding_name: #padding_type, } |
| 1168 | }; |
| 1169 | |
| 1170 | // Bitfields get represented by private padding to ensure overall |
| 1171 | // struct layout is compatible. |
| 1172 | if field.is_none() { |
| 1173 | let name = make_rs_ident(&format!("__bitfields{}", field_index)); |
| 1174 | let bitfield_padding = bit_padding(end - offset); |
| 1175 | return Ok(quote! { |
| 1176 | __NEWLINE__ #( __COMMENT__ #desc )* |
| 1177 | #padding #name: #bitfield_padding |
| 1178 | }); |
| 1179 | } |
| 1180 | let field = field.unwrap(); |
| 1181 | |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1182 | let ident = make_rs_field_ident(field, field_index); |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1183 | let doc_comment = match field.type_.as_ref() { |
| 1184 | Ok(_) => generate_doc_comment(&field.doc_comment), |
| 1185 | Err(msg) => { |
| 1186 | let supplemental_text = |
| 1187 | format!("Reason for representing this field as a blob of bytes:\n{}", msg); |
| 1188 | let new_text = match field.doc_comment.as_ref() { |
| 1189 | None => supplemental_text, |
| 1190 | Some(old_text) => format!("{}\n\n{}", old_text, supplemental_text), |
| 1191 | }; |
| 1192 | generate_doc_comment(&Some(new_text)) |
| 1193 | } |
| 1194 | }; |
| 1195 | let access = if field.access == AccessSpecifier::Public |
| 1196 | && get_field_rs_type_for_layout(field).is_ok() |
| 1197 | { |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1198 | quote! { pub } |
| 1199 | } else { |
Rosica Dejanovska | 6676ad8 | 2022-06-07 14:28:59 -0700 | [diff] [blame] | 1200 | quote! { pub(crate) } |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1201 | }; |
| 1202 | |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1203 | let field_type = match get_field_rs_type_for_layout(field) { |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1204 | Err(_) => bit_padding(end - field.offset), |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1205 | Ok(rs_type) => { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1206 | let type_kind = db.rs_type_kind(rs_type.clone()).with_context(|| { |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1207 | format!( |
| 1208 | "Failed to format type for field {:?} on record {:?}", |
| 1209 | field, record |
| 1210 | ) |
| 1211 | })?; |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1212 | let mut formatted = quote! {#type_kind}; |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1213 | if should_implement_drop(record) || record.is_union() { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1214 | if needs_manually_drop(db, rs_type.clone())? { |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1215 | // TODO(b/212690698): Avoid (somewhat unergonomic) ManuallyDrop |
| 1216 | // if we can ask Rust to preserve field destruction order if the |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 1217 | // destructor is the SpecialMemberFunc::NontrivialMembers |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1218 | // case. |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1219 | formatted = quote! { ::std::mem::ManuallyDrop<#formatted> } |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 1220 | } else { |
| 1221 | field_copy_trait_assertions.push(quote! { |
| 1222 | const _: () = { |
| 1223 | static_assertions::assert_impl_all!(#formatted: Copy); |
| 1224 | }; |
| 1225 | }); |
| 1226 | } |
| 1227 | }; |
| 1228 | formatted |
| 1229 | } |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 1230 | }; |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1231 | |
Lukasz Anforowicz | 5765bb8 | 2022-05-17 17:21:06 -0700 | [diff] [blame] | 1232 | Ok(quote! { #padding #doc_comment #access #ident: #field_type }) |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 1233 | }) |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 1234 | .collect::<Result<Vec<_>>>()?; |
Lukasz Anforowicz | fed64e6 | 2022-03-22 22:39:04 +0000 | [diff] [blame] | 1235 | |
Lukasz Anforowicz | dc37d6d | 2022-05-17 08:20:13 -0700 | [diff] [blame] | 1236 | let size = Literal::usize_unsuffixed(record.size); |
| 1237 | let alignment = Literal::usize_unsuffixed(record.alignment); |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1238 | let field_offset_assertions = if record.is_union() { |
Marcel Hlopko | fa9a395 | 2022-05-10 01:34:13 -0700 | [diff] [blame] | 1239 | // TODO(https://github.com/Gilnaa/memoffset/issues/66): generate assertions for unions once |
| 1240 | // offsetof supports them. |
| 1241 | vec![] |
| 1242 | } else { |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1243 | fields_with_bounds |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 1244 | .enumerate() |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1245 | .map(|(field_index, (field, _, _, _))| { |
| 1246 | if let Some(field) = field { |
| 1247 | let field_ident = make_rs_field_ident(field, field_index); |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 1248 | |
| 1249 | // The assertion below reinforces that the division by 8 on the next line is |
| 1250 | // justified (because the bitfields have been coallesced / filtered out |
| 1251 | // earlier). |
| 1252 | assert_eq!(field.offset % 8, 0); |
| 1253 | let expected_offset = Literal::usize_unsuffixed(field.offset / 8); |
| 1254 | |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1255 | let actual_offset_expr = quote! { |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 1256 | memoffset_unstable_const::offset_of!(#qualified_ident, #field_ident) |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 1257 | }; |
| 1258 | quote! { |
| 1259 | const _: () = assert!(#actual_offset_expr == #expected_offset); |
| 1260 | } |
| 1261 | } else { |
| 1262 | quote! {} |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 1263 | } |
| 1264 | }) |
| 1265 | .collect_vec() |
Marcel Hlopko | fa9a395 | 2022-05-10 01:34:13 -0700 | [diff] [blame] | 1266 | }; |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 1267 | // TODO(b/212696226): Generate `assert_impl_all!` or `assert_not_impl_any!` |
Lukasz Anforowicz | fed64e6 | 2022-03-22 22:39:04 +0000 | [diff] [blame] | 1268 | // assertions about the `Copy` trait - this trait should be implemented |
| 1269 | // iff `should_implement_drop(record)` is false. |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1270 | let mut record_features = BTreeSet::new(); |
| 1271 | let mut assertion_features = BTreeSet::new(); |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 1272 | |
| 1273 | // TODO(mboehme): For the time being, we're using unstable features to |
| 1274 | // be able to use offset_of!() in static assertions. This is fine for a |
| 1275 | // prototype, but longer-term we want to either get those features |
| 1276 | // stabilized or find an alternative. For more details, see |
| 1277 | // b/200120034#comment15 |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1278 | assertion_features.insert(make_rs_ident("const_ptr_offset_from")); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 1279 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1280 | let derives = generate_derives(record); |
Devin Jeanpierre | 9227d2c | 2021-10-06 12:26:05 +0000 | [diff] [blame] | 1281 | let derives = if derives.is_empty() { |
| 1282 | quote! {} |
| 1283 | } else { |
| 1284 | quote! {#[derive( #(#derives),* )]} |
| 1285 | }; |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1286 | let record_kind = if record.is_union() { |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 1287 | quote! { union } |
| 1288 | } else { |
| 1289 | quote! { struct } |
| 1290 | }; |
Devin Jeanpierre | 190b90a | 2022-05-24 06:00:34 -0700 | [diff] [blame] | 1291 | |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1292 | let recursively_pinned_attribute = if record.is_unpin() { |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 1293 | quote! {} |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 1294 | } else { |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 1295 | // negative_impls are necessary for universal initialization due to Rust's |
| 1296 | // coherence rules: PhantomPinned isn't enough to prove to Rust that a |
| 1297 | // blanket impl that requires Unpin doesn't apply. See http://<internal link>=h.f6jp8ifzgt3n |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1298 | record_features.insert(make_rs_ident("negative_impls")); |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1299 | if should_implement_drop(record) { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1300 | quote! {#[::ctor::recursively_pinned(PinnedDrop)]} |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1301 | } else { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1302 | quote! {#[::ctor::recursively_pinned]} |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 1303 | } |
| 1304 | }; |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 1305 | |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 1306 | let mut repr_attributes = vec![quote! {C}]; |
| 1307 | if record.override_alignment && record.alignment > 1 { |
| 1308 | let alignment = Literal::usize_unsuffixed(record.alignment); |
| 1309 | repr_attributes.push(quote! {align(#alignment)}); |
| 1310 | } |
| 1311 | |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 1312 | // Adjust the struct to also include base class subobjects, vtables, etc. |
| 1313 | let head_padding = if let Some(first_field) = record.fields.first() { |
| 1314 | first_field.offset / 8 |
| 1315 | } else { |
| 1316 | record.size |
| 1317 | }; |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 1318 | // Prevent direct initialization for non-aggregate structs. |
| 1319 | // |
| 1320 | // Technically, any implicit-lifetime type is going to be fine to initialize |
| 1321 | // using direct initialization of the fields, even if it is not an aggregate, |
| 1322 | // because this is "just" setting memory to the appropriate values, and |
| 1323 | // implicit-lifetime types can automatically begin their lifetime without |
| 1324 | // running a constructor at all. |
| 1325 | // |
| 1326 | // However, not all types used in interop are implicit-lifetime. For example, |
| 1327 | // while any `Unpin` C++ value is, some `!Unpin` structs (e.g. `std::list`) |
| 1328 | // will not be. So for consistency, we apply the same rule for both |
| 1329 | // implicit-lifetime and non-implicit-lifetime types: the C++ rule, that the |
| 1330 | // type must be an *aggregate* type. |
| 1331 | // |
| 1332 | // TODO(b/232969667): Protect unions from direct initialization, too. |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1333 | let allow_direct_init = record.is_aggregate || record.is_union(); |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 1334 | let head_padding = if head_padding > 0 || !allow_direct_init { |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 1335 | let n = proc_macro2::Literal::usize_unsuffixed(head_padding); |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 1336 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1337 | __non_field_data: [::std::mem::MaybeUninit<u8>; #n], |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 1338 | } |
| 1339 | } else { |
| 1340 | quote! {} |
| 1341 | }; |
| 1342 | |
Devin Jeanpierre | 2745013 | 2022-04-11 13:52:01 -0700 | [diff] [blame] | 1343 | // TODO(b/227442773): After namespace support is added, use the fully-namespaced |
| 1344 | // name. |
| 1345 | let incomplete_symbol = &record.cc_name; |
| 1346 | let incomplete_definition = quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 1347 | forward_declare::unsafe_define!(forward_declare::symbol!(#incomplete_symbol), #qualified_ident); |
Devin Jeanpierre | 2745013 | 2022-04-11 13:52:01 -0700 | [diff] [blame] | 1348 | }; |
| 1349 | |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1350 | let no_unique_address_accessors = cc_struct_no_unique_address_impl(db, record)?; |
Devin Jeanpierre | 8763a8e | 2022-04-26 15:45:13 -0700 | [diff] [blame] | 1351 | let mut record_generated_items = record |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1352 | .child_item_ids |
| 1353 | .iter() |
| 1354 | .map(|id| { |
| 1355 | let item = ir.find_decl(*id)?; |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 1356 | generate_item(db, item) |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1357 | }) |
| 1358 | .collect::<Result<Vec<_>>>()?; |
| 1359 | |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1360 | record_generated_items.push(cc_struct_upcast_impl(record, &ir)?); |
Devin Jeanpierre | 8763a8e | 2022-04-26 15:45:13 -0700 | [diff] [blame] | 1361 | |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1362 | let mut items = vec![]; |
| 1363 | let mut thunks_from_record_items = vec![]; |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1364 | let mut thunk_impls_from_record_items = vec![]; |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1365 | let mut assertions_from_record_items = vec![]; |
| 1366 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1367 | for generated in record_generated_items { |
| 1368 | items.push(generated.item); |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1369 | if !generated.thunks.is_empty() { |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1370 | thunks_from_record_items.push(generated.thunks); |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1371 | } |
| 1372 | if !generated.assertions.is_empty() { |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1373 | assertions_from_record_items.push(generated.assertions); |
| 1374 | } |
| 1375 | if !generated.thunk_impls.is_empty() { |
| 1376 | thunk_impls_from_record_items.push(generated.thunk_impls); |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1377 | } |
| 1378 | record_features.extend(generated.features.clone()); |
| 1379 | } |
| 1380 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1381 | let record_tokens = quote! { |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 1382 | #doc_comment |
Devin Jeanpierre | 9227d2c | 2021-10-06 12:26:05 +0000 | [diff] [blame] | 1383 | #derives |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1384 | #recursively_pinned_attribute |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 1385 | #[repr(#( #repr_attributes ),*)] |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 1386 | pub #record_kind #ident { |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 1387 | #head_padding |
Lukasz Anforowicz | 0dbcf0e | 2022-05-17 06:46:24 -0700 | [diff] [blame] | 1388 | #( #field_definitions, )* |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1389 | } |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 1390 | |
Devin Jeanpierre | 2745013 | 2022-04-11 13:52:01 -0700 | [diff] [blame] | 1391 | #incomplete_definition |
| 1392 | |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 1393 | #no_unique_address_accessors |
| 1394 | |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1395 | __NEWLINE__ __NEWLINE__ |
| 1396 | #( #items __NEWLINE__ __NEWLINE__)* |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 1397 | }; |
| 1398 | |
Lukasz Anforowicz | 95938f8 | 2022-03-24 13:51:54 +0000 | [diff] [blame] | 1399 | let record_trait_assertions = { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1400 | let record_type_name = RsTypeKind::new_record(record.clone(), &ir)?.to_token_stream(); |
Lukasz Anforowicz | 95938f8 | 2022-03-24 13:51:54 +0000 | [diff] [blame] | 1401 | let mut assertions: Vec<TokenStream> = vec![]; |
| 1402 | let mut add_assertion = |assert_impl_macro: TokenStream, trait_name: TokenStream| { |
| 1403 | assertions.push(quote! { |
Lukasz Anforowicz | 768bba3 | 2022-04-11 14:06:13 -0700 | [diff] [blame] | 1404 | const _: () = { static_assertions::#assert_impl_macro (#record_type_name: #trait_name); }; |
Lukasz Anforowicz | 95938f8 | 2022-03-24 13:51:54 +0000 | [diff] [blame] | 1405 | }); |
| 1406 | }; |
| 1407 | if should_derive_clone(record) { |
| 1408 | add_assertion(quote! { assert_impl_all! }, quote! { Clone }); |
| 1409 | } else { |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 1410 | // Can't `assert_not_impl_any!` here, because `Clone` may be |
Lukasz Anforowicz | 95938f8 | 2022-03-24 13:51:54 +0000 | [diff] [blame] | 1411 | // implemented rather than derived. |
| 1412 | } |
| 1413 | let mut add_conditional_assertion = |should_impl_trait: bool, trait_name: TokenStream| { |
| 1414 | let assert_impl_macro = if should_impl_trait { |
| 1415 | quote! { assert_impl_all! } |
| 1416 | } else { |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 1417 | quote! { assert_not_impl_any! } |
Lukasz Anforowicz | 95938f8 | 2022-03-24 13:51:54 +0000 | [diff] [blame] | 1418 | }; |
| 1419 | add_assertion(assert_impl_macro, trait_name); |
| 1420 | }; |
| 1421 | add_conditional_assertion(should_derive_copy(record), quote! { Copy }); |
| 1422 | add_conditional_assertion(should_implement_drop(record), quote! { Drop }); |
| 1423 | assertions |
| 1424 | }; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1425 | let assertion_tokens = quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1426 | const _: () = assert!(::std::mem::size_of::<#qualified_ident>() == #size); |
| 1427 | const _: () = assert!(::std::mem::align_of::<#qualified_ident>() == #alignment); |
Lukasz Anforowicz | 95938f8 | 2022-03-24 13:51:54 +0000 | [diff] [blame] | 1428 | #( #record_trait_assertions )* |
Lukasz Anforowicz | fed64e6 | 2022-03-22 22:39:04 +0000 | [diff] [blame] | 1429 | #( #field_offset_assertions )* |
| 1430 | #( #field_copy_trait_assertions )* |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1431 | #( #assertions_from_record_items )* |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1432 | }; |
| 1433 | |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1434 | let thunk_tokens = quote! { |
| 1435 | #( #thunks_from_record_items )* |
| 1436 | }; |
| 1437 | |
| 1438 | Ok(GeneratedItem { |
| 1439 | item: record_tokens, |
| 1440 | features: record_features.union(&assertion_features).cloned().collect(), |
| 1441 | assertions: assertion_tokens, |
| 1442 | thunks: thunk_tokens, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1443 | thunk_impls: quote! {#(#thunk_impls_from_record_items __NEWLINE__ __NEWLINE__)*}, |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1444 | has_record: true, |
| 1445 | }) |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1446 | } |
| 1447 | |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 1448 | fn should_derive_clone(record: &Record) -> bool { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 1449 | if record.is_union() { |
Lukasz Anforowicz | 2469a5e | 2022-06-02 09:44:51 -0700 | [diff] [blame] | 1450 | // `union`s (unlike `struct`s) should only derive `Clone` if they are `Copy`. |
| 1451 | should_derive_copy(record) |
| 1452 | } else { |
Devin Jeanpierre | 8a4fa20 | 2022-06-08 12:33:11 -0700 | [diff] [blame] | 1453 | record.is_unpin() && record.copy_constructor == SpecialMemberFunc::Trivial |
Lukasz Anforowicz | 2469a5e | 2022-06-02 09:44:51 -0700 | [diff] [blame] | 1454 | } |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 1455 | } |
| 1456 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1457 | fn should_derive_copy(record: &Record) -> bool { |
| 1458 | // TODO(b/202258760): Make `Copy` inclusion configurable. |
Lukasz Anforowicz | 2469a5e | 2022-06-02 09:44:51 -0700 | [diff] [blame] | 1459 | record.is_unpin() |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 1460 | && record.copy_constructor == SpecialMemberFunc::Trivial |
| 1461 | && record.destructor == ir::SpecialMemberFunc::Trivial |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1462 | } |
| 1463 | |
| 1464 | fn generate_derives(record: &Record) -> Vec<Ident> { |
| 1465 | let mut derives = vec![]; |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 1466 | if should_derive_clone(record) { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1467 | derives.push(make_rs_ident("Clone")); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 1468 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1469 | if should_derive_copy(record) { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1470 | derives.push(make_rs_ident("Copy")); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1471 | } |
| 1472 | derives |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 1473 | } |
| 1474 | |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1475 | fn generate_enum(db: &Database, enum_: &Enum) -> Result<TokenStream> { |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 1476 | let name = make_rs_ident(&enum_.identifier.identifier); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1477 | let underlying_type = db.rs_type_kind(enum_.underlying_type.rs_type.clone())?; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 1478 | let enumerator_names = |
| 1479 | enum_.enumerators.iter().map(|enumerator| make_rs_ident(&enumerator.identifier.identifier)); |
| 1480 | let enumerator_values = enum_.enumerators.iter().map(|enumerator| enumerator.value); |
| 1481 | Ok(quote! { |
| 1482 | #[repr(transparent)] |
| 1483 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 1484 | pub struct #name(#underlying_type); |
| 1485 | impl #name { |
| 1486 | #(pub const #enumerator_names: #name = #name(#enumerator_values);)* |
| 1487 | } |
| 1488 | impl From<#underlying_type> for #name { |
| 1489 | fn from(value: #underlying_type) -> #name { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 1490 | #name(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 1491 | } |
| 1492 | } |
| 1493 | impl From<#name> for #underlying_type { |
| 1494 | fn from(value: #name) -> #underlying_type { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 1495 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 1496 | } |
| 1497 | } |
| 1498 | }) |
| 1499 | } |
| 1500 | |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1501 | fn generate_type_alias(db: &Database, type_alias: &TypeAlias) -> Result<TokenStream> { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1502 | let ident = make_rs_ident(&type_alias.identifier.identifier); |
Lukasz Anforowicz | c503af4 | 2022-03-04 23:18:15 +0000 | [diff] [blame] | 1503 | let doc_comment = generate_doc_comment(&type_alias.doc_comment); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1504 | let underlying_type = db |
| 1505 | .rs_type_kind(type_alias.underlying_type.rs_type.clone()) |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1506 | .with_context(|| format!("Failed to format underlying type for {:?}", type_alias))?; |
Lukasz Anforowicz | c503af4 | 2022-03-04 23:18:15 +0000 | [diff] [blame] | 1507 | Ok(quote! { |
| 1508 | #doc_comment |
| 1509 | pub type #ident = #underlying_type; |
| 1510 | }) |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1511 | } |
| 1512 | |
Michael Forster | 523dbd4 | 2021-10-12 11:05:44 +0000 | [diff] [blame] | 1513 | /// Generates Rust source code for a given `UnsupportedItem`. |
| 1514 | fn generate_unsupported(item: &UnsupportedItem) -> Result<TokenStream> { |
Googler | 48a74dd | 2021-10-25 07:31:53 +0000 | [diff] [blame] | 1515 | let location = if item.source_loc.filename.is_empty() { |
| 1516 | "<unknown location>".to_string() |
| 1517 | } else { |
| 1518 | // TODO(forster): The "google3" prefix should probably come from a command line |
| 1519 | // argument. |
| 1520 | // TODO(forster): Consider linking to the symbol instead of to the line number |
| 1521 | // to avoid wrong links while generated files have not caught up. |
| 1522 | format!("google3/{};l={}", &item.source_loc.filename, &item.source_loc.line) |
| 1523 | }; |
Michael Forster | 6a184ad | 2021-10-12 13:04:05 +0000 | [diff] [blame] | 1524 | let message = format!( |
Googler | 48a74dd | 2021-10-25 07:31:53 +0000 | [diff] [blame] | 1525 | "{}\nError while generating bindings for item '{}':\n{}", |
| 1526 | &location, &item.name, &item.message |
Michael Forster | 6a184ad | 2021-10-12 13:04:05 +0000 | [diff] [blame] | 1527 | ); |
Michael Forster | 523dbd4 | 2021-10-12 11:05:44 +0000 | [diff] [blame] | 1528 | Ok(quote! { __COMMENT__ #message }) |
| 1529 | } |
| 1530 | |
Michael Forster | f1dce42 | 2021-10-13 09:50:16 +0000 | [diff] [blame] | 1531 | /// Generates Rust source code for a given `Comment`. |
| 1532 | fn generate_comment(comment: &Comment) -> Result<TokenStream> { |
| 1533 | let text = &comment.text; |
| 1534 | Ok(quote! { __COMMENT__ #text }) |
| 1535 | } |
| 1536 | |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1537 | fn generate_namespace(db: &Database, namespace: &Namespace) -> Result<GeneratedItem> { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1538 | let ir = db.ir(); |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1539 | let mut items = vec![]; |
| 1540 | let mut thunks = vec![]; |
| 1541 | let mut assertions = vec![]; |
| 1542 | let mut has_record = false; |
| 1543 | let mut features = BTreeSet::new(); |
| 1544 | |
| 1545 | for item_id in namespace.child_item_ids.iter() { |
| 1546 | let item = ir.find_decl(*item_id)?; |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 1547 | let generated = generate_item(db, item)?; |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1548 | items.push(generated.item); |
| 1549 | if !generated.thunks.is_empty() { |
| 1550 | thunks.push(generated.thunks); |
| 1551 | } |
| 1552 | if !generated.assertions.is_empty() { |
| 1553 | assertions.push(generated.assertions); |
| 1554 | } |
| 1555 | features.extend(generated.features); |
| 1556 | has_record = has_record || generated.has_record; |
| 1557 | } |
| 1558 | |
Rosica Dejanovska | 93aeafb | 2022-06-01 07:05:31 -0700 | [diff] [blame] | 1559 | let reopened_namespace_idx = ir.get_reopened_namespace_idx(namespace.id)?; |
| 1560 | let should_skip_index = |
| 1561 | ir.is_last_reopened_namespace(namespace.id, namespace.canonical_namespace_id)?; |
| 1562 | |
| 1563 | let name = if should_skip_index { |
| 1564 | make_rs_ident(&namespace.name.identifier) |
| 1565 | } else { |
| 1566 | make_rs_ident(&format!("{}_{}", &namespace.name.identifier, reopened_namespace_idx)) |
| 1567 | }; |
| 1568 | |
| 1569 | let use_stmt_for_previous_namespace = if reopened_namespace_idx == 0 { |
| 1570 | quote! {} |
| 1571 | } else { |
| 1572 | let previous_namespace_ident = make_rs_ident(&format!( |
| 1573 | "{}_{}", |
| 1574 | &namespace.name.identifier, |
| 1575 | reopened_namespace_idx - 1 |
| 1576 | )); |
| 1577 | quote! { pub use super::#previous_namespace_ident::*; __NEWLINE__ __NEWLINE__ } |
| 1578 | }; |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1579 | |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 1580 | let thunks_tokens = quote! { |
| 1581 | #( #thunks )* |
| 1582 | }; |
| 1583 | |
| 1584 | let assertions_tokens = quote! { |
| 1585 | #( #assertions )* |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1586 | }; |
| 1587 | |
| 1588 | let namespace_tokens = quote! { |
| 1589 | pub mod #name { |
Rosica Dejanovska | 93aeafb | 2022-06-01 07:05:31 -0700 | [diff] [blame] | 1590 | #use_stmt_for_previous_namespace |
| 1591 | |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1592 | #( #items __NEWLINE__ __NEWLINE__ )* |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1593 | } |
| 1594 | }; |
| 1595 | |
| 1596 | Ok(GeneratedItem { |
| 1597 | item: namespace_tokens, |
| 1598 | features: features, |
| 1599 | has_record: has_record, |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 1600 | thunks: thunks_tokens, |
| 1601 | assertions: assertions_tokens, |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 1602 | ..Default::default() |
| 1603 | }) |
| 1604 | } |
| 1605 | |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1606 | #[derive(Clone, Debug, Default)] |
| 1607 | struct GeneratedItem { |
| 1608 | item: TokenStream, |
| 1609 | thunks: TokenStream, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1610 | // C++ source code for helper functions. |
| 1611 | thunk_impls: TokenStream, |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1612 | assertions: TokenStream, |
| 1613 | features: BTreeSet<Ident>, |
| 1614 | has_record: bool, |
| 1615 | } |
| 1616 | |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1617 | fn generate_item(db: &Database, item: &Item) -> Result<GeneratedItem> { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1618 | let ir = db.ir(); |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 1619 | let overloaded_funcs = db.overloaded_funcs(); |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1620 | let generated_item = match item { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1621 | Item::Func(func) => match db.generate_func(func.clone()) { |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 1622 | Err(e) => GeneratedItem { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1623 | item: generate_unsupported(&make_unsupported_fn(func, &ir, format!("{e}"))?)?, |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 1624 | ..Default::default() |
| 1625 | }, |
| 1626 | Ok(None) => GeneratedItem::default(), |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1627 | Ok(Some(f)) => { |
| 1628 | let (api_func, thunk, function_id) = f.as_ref(); |
| 1629 | if overloaded_funcs.contains(function_id) { |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1630 | GeneratedItem { |
| 1631 | item: generate_unsupported(&make_unsupported_fn( |
| 1632 | func, |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1633 | &ir, |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1634 | "Cannot generate bindings for overloaded function", |
| 1635 | )?)?, |
| 1636 | ..Default::default() |
| 1637 | } |
| 1638 | } else { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1639 | // TODO(b/236687702): Use Rc for these, or else split this into a non-query |
| 1640 | // and only use the query for Function IDs. |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1641 | GeneratedItem { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1642 | item: api_func.tokens.clone(), |
| 1643 | thunks: thunk.tokens.clone(), |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1644 | features: api_func.features.union(&thunk.features).cloned().collect(), |
| 1645 | ..Default::default() |
| 1646 | } |
| 1647 | } |
| 1648 | } |
| 1649 | }, |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1650 | Item::IncompleteRecord(incomplete_record) => { |
| 1651 | if !ir.is_current_target(&incomplete_record.owning_target) |
| 1652 | && !ir.is_stdlib_target(&incomplete_record.owning_target) |
| 1653 | { |
Devin Jeanpierre | 090a987 | 2022-04-26 15:19:46 -0700 | [diff] [blame] | 1654 | GeneratedItem::default() |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1655 | } else { |
| 1656 | GeneratedItem { |
| 1657 | item: generate_incomplete_record(incomplete_record)?, |
| 1658 | ..Default::default() |
| 1659 | } |
| 1660 | } |
| 1661 | } |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1662 | Item::Record(record) => { |
| 1663 | if !ir.is_current_target(&record.owning_target) |
| 1664 | && !ir.is_stdlib_target(&record.owning_target) |
| 1665 | { |
Devin Jeanpierre | 090a987 | 2022-04-26 15:19:46 -0700 | [diff] [blame] | 1666 | GeneratedItem::default() |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1667 | } else { |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 1668 | generate_record(db, record)? |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1669 | } |
| 1670 | } |
| 1671 | Item::Enum(enum_) => { |
| 1672 | if !ir.is_current_target(&enum_.owning_target) |
| 1673 | && !ir.is_stdlib_target(&enum_.owning_target) |
| 1674 | { |
Devin Jeanpierre | 090a987 | 2022-04-26 15:19:46 -0700 | [diff] [blame] | 1675 | GeneratedItem::default() |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1676 | } else { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1677 | GeneratedItem { item: generate_enum(db, enum_)?, ..Default::default() } |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1678 | } |
| 1679 | } |
| 1680 | Item::TypeAlias(type_alias) => { |
| 1681 | if !ir.is_current_target(&type_alias.owning_target) |
| 1682 | && !ir.is_stdlib_target(&type_alias.owning_target) |
| 1683 | { |
Devin Jeanpierre | 090a987 | 2022-04-26 15:19:46 -0700 | [diff] [blame] | 1684 | GeneratedItem::default() |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1685 | } else { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1686 | GeneratedItem { item: generate_type_alias(db, type_alias)?, ..Default::default() } |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1687 | } |
| 1688 | } |
| 1689 | Item::UnsupportedItem(unsupported) => { |
| 1690 | GeneratedItem { item: generate_unsupported(unsupported)?, ..Default::default() } |
| 1691 | } |
| 1692 | Item::Comment(comment) => { |
| 1693 | GeneratedItem { item: generate_comment(comment)?, ..Default::default() } |
| 1694 | } |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 1695 | Item::Namespace(namespace) => generate_namespace(db, namespace)?, |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1696 | }; |
| 1697 | |
| 1698 | Ok(generated_item) |
| 1699 | } |
| 1700 | |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 1701 | /// Identifies all functions having overloads that we can't import (yet). |
| 1702 | /// |
| 1703 | /// TODO(b/213280424): Implement support for overloaded functions. |
| 1704 | fn overloaded_funcs(db: &dyn BindingsGenerator) -> Rc<HashSet<Rc<FunctionId>>> { |
| 1705 | let mut seen_funcs = HashSet::new(); |
| 1706 | let mut overloaded_funcs = HashSet::new(); |
| 1707 | for func in db.ir().functions() { |
| 1708 | if let Ok(Some(f)) = db.generate_func(func.clone()) { |
| 1709 | let (.., function_id) = f.as_ref(); |
| 1710 | if !seen_funcs.insert(function_id.clone()) { |
| 1711 | overloaded_funcs.insert(function_id.clone()); |
| 1712 | } |
| 1713 | } |
| 1714 | } |
| 1715 | Rc::new(overloaded_funcs) |
| 1716 | } |
| 1717 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1718 | // Returns the Rust code implementing bindings, plus any auxiliary C++ code |
| 1719 | // needed to support it. |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 1720 | fn generate_bindings_tokens(ir: Rc<IR>, crubit_support_path: &str) -> Result<BindingsTokens> { |
Devin Jeanpierre | 52a14c3 | 2022-06-29 19:12:11 -0700 | [diff] [blame] | 1721 | let mut db = Database::default(); |
| 1722 | db.set_ir(ir.clone()); |
| 1723 | |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 1724 | let mut items = vec![]; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1725 | let mut thunks = vec![]; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 1726 | let mut thunk_impls = vec![generate_rs_api_impl(&ir, crubit_support_path)?]; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1727 | let mut assertions = vec![]; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1728 | |
Googler | 454f265 | 2021-12-06 12:53:12 +0000 | [diff] [blame] | 1729 | // We import nullable pointers as an Option<&T> and assume that at the ABI |
| 1730 | // level, None is represented as a zero pointer value whereas Some is |
| 1731 | // represented as as non-zero pointer value. This seems like a pretty safe |
| 1732 | // assumption to make, but to provide some safeguard, assert that |
| 1733 | // `Option<&i32>` and `&i32` have the same size. |
| 1734 | assertions.push(quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1735 | const _: () = assert!(::std::mem::size_of::<Option<&i32>>() == ::std::mem::size_of::<&i32>()); |
Googler | 454f265 | 2021-12-06 12:53:12 +0000 | [diff] [blame] | 1736 | }); |
| 1737 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 1738 | // TODO(jeanpierreda): Delete has_record, either in favor of using RsSnippet, or not |
| 1739 | // having uses. See https://chat.google.com/room/AAAAnQmj8Qs/6QbkSvWcfhA |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 1740 | let mut has_record = false; |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 1741 | let mut features = BTreeSet::new(); |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1742 | |
Lukasz Anforowicz | 72c4d22 | 2022-02-18 19:07:28 +0000 | [diff] [blame] | 1743 | // For #![rustfmt::skip]. |
| 1744 | features.insert(make_rs_ident("custom_inner_attributes")); |
| 1745 | |
Rosica Dejanovska | b2bd59e | 2022-04-11 09:02:03 -0700 | [diff] [blame] | 1746 | for top_level_item_id in ir.top_level_item_ids() { |
| 1747 | let item = ir.find_decl(*top_level_item_id)?; |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 1748 | let generated = generate_item(&db, item)?; |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1749 | items.push(generated.item); |
Devin Jeanpierre | b5ba140 | 2022-03-29 07:29:24 -0700 | [diff] [blame] | 1750 | if !generated.thunks.is_empty() { |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1751 | thunks.push(generated.thunks); |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 1752 | } |
Devin Jeanpierre | b5ba140 | 2022-03-29 07:29:24 -0700 | [diff] [blame] | 1753 | if !generated.assertions.is_empty() { |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1754 | assertions.push(generated.assertions); |
| 1755 | } |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1756 | if !generated.thunk_impls.is_empty() { |
| 1757 | thunk_impls.push(generated.thunk_impls); |
| 1758 | } |
Rosica Dejanovska | 8da8f79 | 2022-03-29 02:02:22 -0700 | [diff] [blame] | 1759 | features.extend(generated.features); |
| 1760 | has_record = has_record || generated.has_record; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1761 | } |
| 1762 | |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1763 | let mod_detail = if thunks.is_empty() { |
| 1764 | quote! {} |
| 1765 | } else { |
| 1766 | quote! { |
| 1767 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1768 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 1769 | use super::*; |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1770 | extern "C" { |
| 1771 | #( #thunks )* |
| 1772 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1773 | } |
| 1774 | } |
| 1775 | }; |
| 1776 | |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 1777 | let features = if features.is_empty() { |
| 1778 | quote! {} |
| 1779 | } else { |
| 1780 | quote! { |
| 1781 | #![feature( #(#features),* )] |
| 1782 | } |
| 1783 | }; |
| 1784 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1785 | Ok(BindingsTokens { |
| 1786 | rs_api: quote! { |
| 1787 | #features __NEWLINE__ |
| 1788 | #![allow(non_camel_case_types)] __NEWLINE__ |
Lukasz Anforowicz | 945919c | 2022-05-12 13:08:47 -0700 | [diff] [blame] | 1789 | #![allow(non_snake_case)] __NEWLINE__ |
Lukasz Anforowicz | cc26263 | 2022-05-12 15:07:43 -0700 | [diff] [blame] | 1790 | #![allow(non_upper_case_globals)] __NEWLINE__ |
| 1791 | #![deny(warnings)] __NEWLINE__ __NEWLINE__ |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1792 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1793 | #( #items __NEWLINE__ __NEWLINE__ )* |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1794 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1795 | #mod_detail __NEWLINE__ __NEWLINE__ |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1796 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 1797 | #( #assertions __NEWLINE__ __NEWLINE__ )* |
| 1798 | }, |
| 1799 | rs_api_impl: quote! {#(#thunk_impls __NEWLINE__ __NEWLINE__ )*}, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1800 | }) |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1801 | } |
| 1802 | |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1803 | /// Makes an 'Ident' to be used in the Rust source code. Escapes Rust keywords. |
| 1804 | fn make_rs_ident(ident: &str) -> Ident { |
| 1805 | // TODO(https://github.com/dtolnay/syn/pull/1098): Remove the hardcoded list once syn recognizes |
| 1806 | // 2018 and 2021 keywords. |
| 1807 | if ["async", "await", "try", "dyn"].contains(&ident) { |
| 1808 | return format_ident!("r#{}", ident); |
| 1809 | } |
| 1810 | match syn::parse_str::<syn::Ident>(ident) { |
| 1811 | Ok(_) => format_ident!("{}", ident), |
| 1812 | Err(_) => format_ident!("r#{}", ident), |
| 1813 | } |
| 1814 | } |
| 1815 | |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1816 | /// Formats a C++ identifier. Does not escape C++ keywords. |
| 1817 | fn format_cc_ident(ident: &str) -> TokenStream { |
| 1818 | ident.parse().unwrap() |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1819 | } |
| 1820 | |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1821 | /// Returns Some(crate_ident) if this is an imported crate. |
| 1822 | fn rs_imported_crate_name(owning_target: &BazelLabel, ir: &IR) -> Option<Ident> { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1823 | if ir.is_current_target(owning_target) || ir.is_stdlib_target(owning_target) { |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1824 | None |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1825 | } else { |
Devin Jeanpierre | 084ebbd | 2022-04-01 04:32:46 -0700 | [diff] [blame] | 1826 | let owning_crate_name = owning_target.target_name(); |
Marcel Hlopko | d906b89 | 2022-01-27 08:52:36 +0000 | [diff] [blame] | 1827 | // TODO(b/216587072): Remove this hacky escaping and use the import! macro once |
| 1828 | // available |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 1829 | let escaped_owning_crate_name = owning_crate_name.replace('-', "_"); |
Marcel Hlopko | d906b89 | 2022-01-27 08:52:36 +0000 | [diff] [blame] | 1830 | let owning_crate = make_rs_ident(&escaped_owning_crate_name); |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1831 | Some(owning_crate) |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1832 | } |
| 1833 | } |
| 1834 | |
Devin Jeanpierre | 103cbb5 | 2022-04-06 12:55:16 -0700 | [diff] [blame] | 1835 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1836 | enum Mutability { |
| 1837 | Const, |
| 1838 | Mut, |
| 1839 | } |
| 1840 | |
| 1841 | impl Mutability { |
| 1842 | fn format_for_pointer(&self) -> TokenStream { |
| 1843 | match self { |
| 1844 | Mutability::Mut => quote! {mut}, |
| 1845 | Mutability::Const => quote! {const}, |
| 1846 | } |
| 1847 | } |
| 1848 | |
| 1849 | fn format_for_reference(&self) -> TokenStream { |
| 1850 | match self { |
| 1851 | Mutability::Mut => quote! {mut}, |
| 1852 | Mutability::Const => quote! {}, |
| 1853 | } |
| 1854 | } |
| 1855 | } |
| 1856 | |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 1857 | #[derive(Clone, Debug, PartialEq, Eq)] |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1858 | enum RsTypeKind { |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1859 | Pointer { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1860 | pointee: Rc<RsTypeKind>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1861 | mutability: Mutability, |
| 1862 | }, |
| 1863 | Reference { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1864 | referent: Rc<RsTypeKind>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1865 | mutability: Mutability, |
Marcel Hlopko | af682a0 | 2022-04-08 07:27:14 -0700 | [diff] [blame] | 1866 | lifetime: LifetimeName, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1867 | }, |
| 1868 | RvalueReference { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1869 | referent: Rc<RsTypeKind>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1870 | mutability: Mutability, |
Marcel Hlopko | af682a0 | 2022-04-08 07:27:14 -0700 | [diff] [blame] | 1871 | lifetime: LifetimeName, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1872 | }, |
| 1873 | FuncPtr { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1874 | abi: Rc<str>, |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1875 | return_type: Rc<RsTypeKind>, |
| 1876 | param_types: Rc<[RsTypeKind]>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1877 | }, |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1878 | /// An incomplete record type. |
| 1879 | IncompleteRecord { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1880 | incomplete_record: Rc<IncompleteRecord>, |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1881 | |
| 1882 | /// The imported crate this comes from, or None if the current crate. |
| 1883 | crate_ident: Option<Ident>, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 1884 | /// The namespace qualifier for this record. |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1885 | namespace_qualifier: Rc<[Ident]>, |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1886 | }, |
| 1887 | /// A complete record type. |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1888 | Record { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1889 | record: Rc<Record>, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 1890 | /// The namespace qualifier for this record. |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1891 | namespace_qualifier: Rc<[Ident]>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1892 | /// The imported crate this comes from, or None if the current crate. |
| 1893 | crate_ident: Option<Ident>, |
| 1894 | }, |
| 1895 | TypeAlias { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1896 | type_alias: Rc<TypeAlias>, |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1897 | underlying_type: Rc<RsTypeKind>, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 1898 | /// The namespace qualifier for this alias. |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1899 | namespace_qualifier: Rc<[Ident]>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1900 | /// The imported crate this comes from, or None if the current crate. |
| 1901 | crate_ident: Option<Ident>, |
| 1902 | }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1903 | Unit, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1904 | Other { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1905 | name: Rc<str>, |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1906 | type_args: Rc<[RsTypeKind]>, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1907 | }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1908 | } |
| 1909 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1910 | impl RsTypeKind { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1911 | pub fn new_record(record: Rc<Record>, ir: &IR) -> Result<Self> { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 1912 | let namespace_qualifier = generate_namespace_qualifier(record.id, ir)?.collect(); |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 1913 | let crate_ident = rs_imported_crate_name(&record.owning_target, ir); |
| 1914 | Ok(RsTypeKind::Record { record, namespace_qualifier, crate_ident }) |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1915 | } |
| 1916 | |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1917 | /// Returns true if the type is known to be `Unpin`, false otherwise. |
Devin Jeanpierre | f85ae59 | 2022-04-01 04:33:57 -0700 | [diff] [blame] | 1918 | pub fn is_unpin(&self) -> bool { |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1919 | match self { |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1920 | RsTypeKind::IncompleteRecord { .. } => false, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1921 | RsTypeKind::Record { record, .. } => record.is_unpin(), |
Devin Jeanpierre | f85ae59 | 2022-04-01 04:33:57 -0700 | [diff] [blame] | 1922 | RsTypeKind::TypeAlias { underlying_type, .. } => underlying_type.is_unpin(), |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1923 | _ => true, |
| 1924 | } |
| 1925 | } |
| 1926 | |
Devin Jeanpierre | 82e8e36 | 2022-04-05 11:04:55 -0700 | [diff] [blame] | 1927 | pub fn format_as_return_type_fragment(&self) -> TokenStream { |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1928 | match self { |
Devin Jeanpierre | d2b7a8f | 2022-04-01 04:37:16 -0700 | [diff] [blame] | 1929 | RsTypeKind::Unit => quote! {}, |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1930 | other_type => { |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 1931 | quote! { -> #other_type } |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1932 | } |
| 1933 | } |
| 1934 | } |
| 1935 | |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1936 | /// Formats this RsTypeKind as `&'a mut MaybeUninit<SomeStruct>`. This is |
| 1937 | /// used to format `__this` parameter in a constructor thunk. |
Devin Jeanpierre | 82e8e36 | 2022-04-05 11:04:55 -0700 | [diff] [blame] | 1938 | pub fn format_mut_ref_as_uninitialized(&self) -> Result<TokenStream> { |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1939 | match self { |
Devin Jeanpierre | d2b7a8f | 2022-04-01 04:37:16 -0700 | [diff] [blame] | 1940 | RsTypeKind::Reference { referent, lifetime, mutability: Mutability::Mut } => { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1941 | Ok(quote! { & #lifetime mut ::std::mem::MaybeUninit< #referent > }) |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1942 | } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1943 | _ => bail!("Expected reference to format as MaybeUninit, got: {:?}", self), |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1944 | } |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1945 | } |
| 1946 | |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1947 | /// Formats this RsTypeKind as the `self` parameter: usually, `&'a self` or |
| 1948 | /// `&'a mut self`. |
| 1949 | /// |
| 1950 | /// If this is !Unpin, however, it uses `self: Pin<&mut Self>` instead. |
Devin Jeanpierre | 108e9c0 | 2022-06-02 07:10:09 -0700 | [diff] [blame] | 1951 | pub fn format_as_self_param(&self) -> Result<TokenStream> { |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1952 | let referent; |
| 1953 | let mutability; |
| 1954 | let lifetime; |
| 1955 | match self { |
Devin Jeanpierre | 108e9c0 | 2022-06-02 07:10:09 -0700 | [diff] [blame] | 1956 | RsTypeKind::Pointer { .. } => { |
Devin Jeanpierre | 8a4fa20 | 2022-06-08 12:33:11 -0700 | [diff] [blame] | 1957 | // TODO(jeanpierreda): provide end-user-facing docs, and insert a link to e.g. |
| 1958 | // something like <internal link> |
| 1959 | bail!( |
| 1960 | "`self` has no lifetime. Use lifetime annotations or `#pragma clang lifetime_elision` to create bindings for this function." |
| 1961 | ) |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 1962 | } |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1963 | RsTypeKind::Reference { |
| 1964 | referent: reference_pointee, |
| 1965 | lifetime: reference_lifetime, |
| 1966 | mutability: reference_mutability, |
| 1967 | } => { |
| 1968 | referent = reference_pointee; |
| 1969 | mutability = reference_mutability; |
Devin Jeanpierre | a68fdbc | 2022-05-27 04:16:36 -0700 | [diff] [blame] | 1970 | lifetime = quote! {#reference_lifetime}; |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1971 | } |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 1972 | _ => bail!("Unexpected type of `self` parameter: {:?}", self), |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1973 | } |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1974 | let mut_ = mutability.format_for_reference(); |
| 1975 | if mutability == &Mutability::Mut && !referent.is_unpin() { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1976 | // TODO(b/200067242): Add a `use ::std::pin::Pin` to the crate, and use |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1977 | // `Pin`. |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 1978 | Ok(quote! {self: ::std::pin::Pin< & #lifetime #mut_ Self>}) |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 1979 | } else { |
| 1980 | Ok(quote! { & #lifetime #mut_ self }) |
| 1981 | } |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1982 | } |
| 1983 | |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 1984 | /// Returns whether the type represented by `self` implements the `Copy` |
| 1985 | /// trait. |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 1986 | pub fn implements_copy(&self) -> bool { |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1987 | // TODO(b/212696226): Verify results of `implements_copy` via static |
| 1988 | // assertions in the generated Rust code (because incorrect results |
| 1989 | // can silently lead to unsafe behavior). |
| 1990 | match self { |
| 1991 | RsTypeKind::Unit => true, |
| 1992 | RsTypeKind::Pointer { .. } => true, |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1993 | RsTypeKind::FuncPtr { .. } => true, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1994 | RsTypeKind::Reference { mutability: Mutability::Const, .. } => true, |
| 1995 | RsTypeKind::Reference { mutability: Mutability::Mut, .. } => false, |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 1996 | RsTypeKind::RvalueReference { .. } => false, |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 1997 | RsTypeKind::IncompleteRecord { .. } => false, |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 1998 | RsTypeKind::Record { record, .. } => should_derive_copy(record), |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1999 | RsTypeKind::TypeAlias { underlying_type, .. } => underlying_type.implements_copy(), |
Lukasz Anforowicz | d81bea9 | 2022-02-11 08:57:58 +0000 | [diff] [blame] | 2000 | RsTypeKind::Other { type_args, .. } => { |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 2001 | // All types that may appear here without `type_args` (e.g. |
| 2002 | // primitive types like `i32`) implement `Copy`. Generic types |
| 2003 | // that may be present here (e.g. Option<...>) are `Copy` if all |
| 2004 | // of their `type_args` are `Copy`. |
| 2005 | type_args.iter().all(|t| t.implements_copy()) |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2006 | } |
| 2007 | } |
| 2008 | } |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 2009 | |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 2010 | pub fn is_ref_to(&self, expected_record: &Record) -> bool { |
| 2011 | match self { |
| 2012 | RsTypeKind::Reference { referent, .. } => referent.is_record(expected_record), |
| 2013 | _ => false, |
| 2014 | } |
| 2015 | } |
| 2016 | |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 2017 | pub fn is_shared_ref_to(&self, expected_record: &Record) -> bool { |
| 2018 | match self { |
| 2019 | RsTypeKind::Reference { referent, mutability: Mutability::Const, .. } => { |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 2020 | referent.is_record(expected_record) |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 2021 | } |
| 2022 | _ => false, |
| 2023 | } |
| 2024 | } |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 2025 | |
| 2026 | pub fn is_record(&self, expected_record: &Record) -> bool { |
| 2027 | match self { |
Devin Jeanpierre | fec5bfe | 2022-04-05 10:59:10 -0700 | [diff] [blame] | 2028 | RsTypeKind::Record { record: actual_record, .. } => { |
| 2029 | actual_record.id == expected_record.id |
| 2030 | } |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 2031 | _ => false, |
| 2032 | } |
| 2033 | } |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2034 | |
| 2035 | /// Iterates over `self` and all the nested types (e.g. pointees, generic |
| 2036 | /// type args, etc.) in DFS order. |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2037 | pub fn dfs_iter<'ty>(&'ty self) -> impl Iterator<Item = &'ty RsTypeKind> + '_ { |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2038 | RsTypeKindIter::new(self) |
| 2039 | } |
| 2040 | |
| 2041 | /// Iterates over all `LifetimeId`s in `self` and in all the nested types. |
| 2042 | /// Note that the results might contain duplicate LifetimeId values (e.g. |
| 2043 | /// if the same LifetimeId is used in two `type_args`). |
| 2044 | pub fn lifetimes(&self) -> impl Iterator<Item = LifetimeId> + '_ { |
| 2045 | self.dfs_iter().filter_map(|t| match t { |
Devin Jeanpierre | d2b7a8f | 2022-04-01 04:37:16 -0700 | [diff] [blame] | 2046 | RsTypeKind::Reference { lifetime, .. } => Some(lifetime.id), |
Devin Jeanpierre | 48cb5bc | 2022-06-02 00:50:43 -0700 | [diff] [blame] | 2047 | RsTypeKind::RvalueReference { lifetime, .. } => Some(lifetime.id), |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2048 | _ => None, |
| 2049 | }) |
| 2050 | } |
| 2051 | } |
| 2052 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2053 | impl ToTokens for RsTypeKind { |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2054 | fn to_tokens(&self, tokens: &mut TokenStream) { |
| 2055 | self.to_token_stream().to_tokens(tokens) |
| 2056 | } |
| 2057 | |
| 2058 | fn to_token_stream(&self) -> TokenStream { |
| 2059 | match self { |
| 2060 | RsTypeKind::Pointer { pointee, mutability } => { |
| 2061 | let mutability = mutability.format_for_pointer(); |
| 2062 | quote! {* #mutability #pointee} |
| 2063 | } |
| 2064 | RsTypeKind::Reference { referent, mutability, lifetime } => { |
| 2065 | let mut_ = mutability.format_for_reference(); |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2066 | let reference = quote! {& #lifetime #mut_ #referent}; |
| 2067 | if mutability == &Mutability::Mut && !referent.is_unpin() { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2068 | // TODO(b/200067242): Add a `use ::std::pin::Pin` to the crate, and use |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2069 | // `Pin`. This either requires deciding how to qualify pin at |
| 2070 | // RsTypeKind-creation time, or returning an RsSnippet from here (and not |
| 2071 | // implementing ToTokens, but instead some other interface.) |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2072 | quote! {::std::pin::Pin< #reference >} |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2073 | } else { |
| 2074 | reference |
| 2075 | } |
| 2076 | } |
| 2077 | RsTypeKind::RvalueReference { referent, mutability, lifetime } => { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2078 | // TODO(b/200067242): Add a `use ::ctor::RvalueReference` (etc.) to the crate. |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2079 | if mutability == &Mutability::Mut { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2080 | quote! {::ctor::RvalueReference<#lifetime, #referent>} |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2081 | } else { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2082 | quote! {::ctor::ConstRvalueReference<#lifetime, #referent>} |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2083 | } |
| 2084 | } |
| 2085 | RsTypeKind::FuncPtr { abi, return_type, param_types } => { |
| 2086 | let return_frag = return_type.format_as_return_type_fragment(); |
| 2087 | quote! { extern #abi fn( #( #param_types ),* ) #return_frag } |
| 2088 | } |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2089 | RsTypeKind::IncompleteRecord { |
| 2090 | incomplete_record, |
| 2091 | namespace_qualifier, |
| 2092 | crate_ident, |
| 2093 | } => { |
Rosica Dejanovska | e12d717 | 2022-06-22 12:20:17 -0700 | [diff] [blame] | 2094 | let record_ident = make_rs_ident(&incomplete_record.rs_name); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2095 | let namespace_idents = namespace_qualifier.iter(); |
| 2096 | match crate_ident { |
| 2097 | Some(ci) => { |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2098 | quote! { #ci #(#namespace_idents::)* #record_ident } |
| 2099 | } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2100 | None => { |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2101 | quote! { crate:: #(#namespace_idents::)* #record_ident } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2102 | } |
| 2103 | } |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 2104 | } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2105 | RsTypeKind::Record { record, namespace_qualifier, crate_ident } => { |
| 2106 | let ident = make_rs_ident(&record.rs_name); |
| 2107 | let namespace_idents = namespace_qualifier.iter(); |
| 2108 | match crate_ident { |
| 2109 | Some(ci) => { |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2110 | quote! { #ci:: #(#namespace_idents::)* #ident } |
| 2111 | } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2112 | None => { |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2113 | quote! { crate:: #(#namespace_idents::)* #ident } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2114 | } |
| 2115 | } |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2116 | } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2117 | RsTypeKind::TypeAlias { type_alias, namespace_qualifier, crate_ident, .. } => { |
| 2118 | let ident = make_rs_ident(&type_alias.identifier.identifier); |
| 2119 | let namespace_idents = namespace_qualifier.iter(); |
| 2120 | match crate_ident { |
| 2121 | Some(ci) => { |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2122 | quote! { #ci:: #(#namespace_idents::)* #ident } |
| 2123 | } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2124 | None => { |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 2125 | quote! { crate:: #(#namespace_idents::)* #ident } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2126 | } |
| 2127 | } |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2128 | } |
| 2129 | RsTypeKind::Unit => quote! {()}, |
| 2130 | RsTypeKind::Other { name, type_args } => { |
| 2131 | let ident = make_rs_ident(name); |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 2132 | let generic_params = format_generic_params(type_args.iter()); |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 2133 | quote! {#ident #generic_params} |
| 2134 | } |
| 2135 | } |
| 2136 | } |
| 2137 | } |
| 2138 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2139 | struct RsTypeKindIter<'ty> { |
| 2140 | todo: Vec<&'ty RsTypeKind>, |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2141 | } |
| 2142 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2143 | impl<'ty> RsTypeKindIter<'ty> { |
| 2144 | pub fn new(ty: &'ty RsTypeKind) -> Self { |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2145 | Self { todo: vec![ty] } |
| 2146 | } |
| 2147 | } |
| 2148 | |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2149 | impl<'ty> Iterator for RsTypeKindIter<'ty> { |
| 2150 | type Item = &'ty RsTypeKind; |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2151 | |
| 2152 | fn next(&mut self) -> Option<Self::Item> { |
| 2153 | match self.todo.pop() { |
| 2154 | None => None, |
| 2155 | Some(curr) => { |
| 2156 | match curr { |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 2157 | RsTypeKind::Unit |
| 2158 | | RsTypeKind::IncompleteRecord { .. } |
| 2159 | | RsTypeKind::Record { .. } => {} |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2160 | RsTypeKind::Pointer { pointee, .. } => self.todo.push(pointee), |
| 2161 | RsTypeKind::Reference { referent, .. } => self.todo.push(referent), |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2162 | RsTypeKind::RvalueReference { referent, .. } => self.todo.push(referent), |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2163 | RsTypeKind::TypeAlias { underlying_type: t, .. } => self.todo.push(t), |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 2164 | RsTypeKind::FuncPtr { return_type, param_types, .. } => { |
| 2165 | self.todo.push(return_type); |
| 2166 | self.todo.extend(param_types.iter().rev()); |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 2167 | } |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 2168 | RsTypeKind::Other { type_args, .. } => self.todo.extend(type_args.iter().rev()), |
| 2169 | }; |
| 2170 | Some(curr) |
| 2171 | } |
| 2172 | } |
| 2173 | } |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 2174 | } |
| 2175 | |
Devin Jeanpierre | 3a0cc5a | 2022-07-12 09:36:34 -0700 | [diff] [blame^] | 2176 | fn rs_type_kind(db: &dyn BindingsGenerator, ty: ir::RsType) -> Result<RsTypeKind> { |
| 2177 | let ir = db.ir(); |
| 2178 | // The lambdas deduplicate code needed by multiple `match` branches. |
| 2179 | let get_type_args = || -> Result<Vec<RsTypeKind>> { |
| 2180 | ty.type_args.iter().map(|type_arg| db.rs_type_kind(type_arg.clone())).collect() |
| 2181 | }; |
| 2182 | let get_pointee = || -> Result<Rc<RsTypeKind>> { |
| 2183 | if ty.type_args.len() != 1 { |
| 2184 | bail!("Missing pointee/referent type (need exactly 1 type argument): {:?}", ty); |
| 2185 | } |
| 2186 | Ok(Rc::new(get_type_args()?.remove(0))) |
| 2187 | }; |
| 2188 | let get_lifetime = || -> Result<LifetimeName> { |
| 2189 | if ty.lifetime_args.len() != 1 { |
| 2190 | bail!("Missing reference lifetime (need exactly 1 lifetime argument): {:?}", ty); |
| 2191 | } |
| 2192 | let lifetime_id = ty.lifetime_args[0]; |
| 2193 | ir.get_lifetime(lifetime_id) |
| 2194 | .ok_or_else(|| anyhow!("no known lifetime with id {lifetime_id:?}")) |
| 2195 | .cloned() |
| 2196 | }; |
| 2197 | |
| 2198 | let result = match ty.name.as_deref() { |
| 2199 | None => { |
| 2200 | ensure!( |
| 2201 | ty.type_args.is_empty(), |
| 2202 | "Type arguments on records nor type aliases are not yet supported: {:?}", |
| 2203 | ty |
| 2204 | ); |
| 2205 | match ir.item_for_type(&ty)? { |
| 2206 | Item::IncompleteRecord(incomplete_record) => RsTypeKind::IncompleteRecord { |
| 2207 | incomplete_record: incomplete_record.clone(), |
| 2208 | namespace_qualifier: generate_namespace_qualifier(incomplete_record.id, &ir)? |
| 2209 | .collect(), |
| 2210 | crate_ident: rs_imported_crate_name(&incomplete_record.owning_target, &ir), |
| 2211 | }, |
| 2212 | Item::Record(record) => RsTypeKind::new_record(record.clone(), &ir)?, |
| 2213 | Item::TypeAlias(type_alias) => RsTypeKind::TypeAlias { |
| 2214 | type_alias: type_alias.clone(), |
| 2215 | namespace_qualifier: generate_namespace_qualifier(type_alias.id, &ir)? |
| 2216 | .collect(), |
| 2217 | crate_ident: rs_imported_crate_name(&type_alias.owning_target, &ir), |
| 2218 | underlying_type: Rc::new( |
| 2219 | db.rs_type_kind(type_alias.underlying_type.rs_type.clone())?, |
| 2220 | ), |
| 2221 | }, |
| 2222 | other_item => bail!("Item does not define a type: {:?}", other_item), |
| 2223 | } |
| 2224 | } |
| 2225 | Some(name) => match name { |
| 2226 | "()" => { |
| 2227 | if !ty.type_args.is_empty() { |
| 2228 | bail!("Unit type must not have type arguments: {:?}", ty); |
| 2229 | } |
| 2230 | RsTypeKind::Unit |
| 2231 | } |
| 2232 | "*mut" => RsTypeKind::Pointer { pointee: get_pointee()?, mutability: Mutability::Mut }, |
| 2233 | "*const" => { |
| 2234 | RsTypeKind::Pointer { pointee: get_pointee()?, mutability: Mutability::Const } |
| 2235 | } |
| 2236 | "&mut" => RsTypeKind::Reference { |
| 2237 | referent: get_pointee()?, |
| 2238 | mutability: Mutability::Mut, |
| 2239 | lifetime: get_lifetime()?, |
| 2240 | }, |
| 2241 | "&" => RsTypeKind::Reference { |
| 2242 | referent: get_pointee()?, |
| 2243 | mutability: Mutability::Const, |
| 2244 | lifetime: get_lifetime()?, |
| 2245 | }, |
| 2246 | "#RvalueReference mut" => RsTypeKind::RvalueReference { |
| 2247 | referent: get_pointee()?, |
| 2248 | mutability: Mutability::Mut, |
| 2249 | lifetime: get_lifetime()?, |
| 2250 | }, |
| 2251 | "#RvalueReference const" => RsTypeKind::RvalueReference { |
| 2252 | referent: get_pointee()?, |
| 2253 | mutability: Mutability::Const, |
| 2254 | lifetime: get_lifetime()?, |
| 2255 | }, |
| 2256 | name => { |
| 2257 | let mut type_args = get_type_args()?; |
| 2258 | match name.strip_prefix("#funcPtr ") { |
| 2259 | None => RsTypeKind::Other { name: name.into(), type_args: Rc::from(type_args) }, |
| 2260 | Some(abi) => { |
| 2261 | // TODO(b/217419782): Consider enforcing `'static` lifetime. |
| 2262 | ensure!(!type_args.is_empty(), "No return type in fn type: {:?}", ty); |
| 2263 | RsTypeKind::FuncPtr { |
| 2264 | abi: abi.into(), |
| 2265 | return_type: Rc::new(type_args.remove(type_args.len() - 1)), |
| 2266 | param_types: Rc::from(type_args), |
| 2267 | } |
| 2268 | } |
| 2269 | } |
| 2270 | } |
| 2271 | }, |
| 2272 | }; |
| 2273 | Ok(result) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2274 | } |
| 2275 | |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2276 | fn cc_type_name_for_item(item: &ir::Item, ir: &IR) -> Result<TokenStream> { |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 2277 | Ok(match item { |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 2278 | Item::Record(record) => { |
| 2279 | let ident = format_cc_ident(&record.cc_name); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2280 | let namespace_qualifier = generate_namespace_qualifier(record.id, ir)?; |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 2281 | let tag_kind = cc_tag_kind(record); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2282 | quote! { #tag_kind #(#namespace_qualifier::)* #ident } |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 2283 | } |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 2284 | Item::TypeAlias(type_alias) => { |
| 2285 | let ident = format_cc_ident(&type_alias.identifier.identifier); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2286 | let namespace_qualifier = generate_namespace_qualifier(type_alias.id, ir)?; |
| 2287 | quote! { #(#namespace_qualifier::)* #ident } |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 2288 | } |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 2289 | _ => bail!("Item does not define a type: {:?}", item), |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 2290 | }) |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 2291 | } |
| 2292 | |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 2293 | fn cc_tag_kind(record: &ir::Record) -> TokenStream { |
| 2294 | match record.record_type { |
| 2295 | RecordType::Struct => quote! { struct }, |
| 2296 | RecordType::Union => quote! { union }, |
| 2297 | RecordType::Class => quote! { class }, |
Marcel Hlopko | 4c29c6f | 2022-05-04 00:49:14 -0700 | [diff] [blame] | 2298 | } |
| 2299 | } |
| 2300 | |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 2301 | // Maps a Rust ABI [1] into a Clang attribute. See also |
| 2302 | // `ConvertCcCallConvIntoRsApi` in importer.cc. |
| 2303 | // [1] |
| 2304 | // https://doc.rust-lang.org/reference/items/functions.html#extern-function-qualifier |
| 2305 | fn format_cc_call_conv_as_clang_attribute(rs_abi: &str) -> Result<TokenStream> { |
| 2306 | match rs_abi { |
| 2307 | "cdecl" => Ok(quote! {}), |
| 2308 | "fastcall" => Ok(quote! { __attribute__((fastcall)) }), |
| 2309 | "stdcall" => Ok(quote! { __attribute__((stdcall)) }), |
| 2310 | "thiscall" => Ok(quote! { __attribute__((thiscall)) }), |
| 2311 | "vectorcall" => Ok(quote! { __attribute__((vectorcall)) }), |
| 2312 | _ => bail!("Unsupported ABI: {}", rs_abi), |
| 2313 | } |
| 2314 | } |
| 2315 | |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2316 | fn format_cc_type(ty: &ir::CcType, ir: &IR) -> Result<TokenStream> { |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 2317 | let const_fragment = if ty.is_const { |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 2318 | quote! {const} |
| 2319 | } else { |
| 2320 | quote! {} |
| 2321 | }; |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2322 | if let Some(ref name) = ty.name { |
| 2323 | match name.as_str() { |
| 2324 | "*" => { |
Googler | ff7fc23 | 2021-12-02 09:43:00 +0000 | [diff] [blame] | 2325 | if ty.type_args.len() != 1 { |
| 2326 | bail!("Invalid pointer type (need exactly 1 type argument): {:?}", ty); |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2327 | } |
Googler | ff7fc23 | 2021-12-02 09:43:00 +0000 | [diff] [blame] | 2328 | assert_eq!(ty.type_args.len(), 1); |
| 2329 | let nested_type = format_cc_type(&ty.type_args[0], ir)?; |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2330 | Ok(quote! {#nested_type * #const_fragment}) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2331 | } |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 2332 | "&" => { |
| 2333 | if ty.type_args.len() != 1 { |
| 2334 | bail!("Invalid reference type (need exactly 1 type argument): {:?}", ty); |
| 2335 | } |
| 2336 | let nested_type = format_cc_type(&ty.type_args[0], ir)?; |
| 2337 | Ok(quote! {#nested_type &}) |
| 2338 | } |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2339 | "&&" => { |
| 2340 | if ty.type_args.len() != 1 { |
| 2341 | bail!("Invalid rvalue reference type (need exactly 1 type argument): {:?}", ty); |
| 2342 | } |
| 2343 | let nested_type = format_cc_type(&ty.type_args[0], ir)?; |
| 2344 | Ok(quote! {#nested_type &&}) |
| 2345 | } |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 2346 | cc_type_name => match cc_type_name.strip_prefix("#funcValue ") { |
| 2347 | None => { |
| 2348 | if !ty.type_args.is_empty() { |
| 2349 | bail!("Type not yet supported: {:?}", ty); |
| 2350 | } |
| 2351 | let idents = cc_type_name.split_whitespace().map(format_cc_ident); |
| 2352 | Ok(quote! {#( #idents )* #const_fragment}) |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 2353 | } |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 2354 | Some(abi) => match ty.type_args.split_last() { |
| 2355 | None => bail!("funcValue type without a return type: {:?}", ty), |
| 2356 | Some((ret_type, param_types)) => { |
| 2357 | let ret_type = format_cc_type(ret_type, ir)?; |
| 2358 | let param_types = param_types |
| 2359 | .iter() |
| 2360 | .map(|t| format_cc_type(t, ir)) |
| 2361 | .collect::<Result<Vec<_>>>()?; |
| 2362 | let attr = format_cc_call_conv_as_clang_attribute(abi)?; |
| 2363 | // `type_identity_t` is used below to avoid having to |
| 2364 | // emit spiral-like syntax where some syntax elements of |
| 2365 | // an inner type (e.g. function type as below) can |
| 2366 | // surround syntax elements of an outer type (e.g. a |
| 2367 | // pointer type). Compare: `int (*foo)(int, int)` VS |
| 2368 | // `type_identity_t<int(int, int)>* foo`. |
Lukasz Anforowicz | 2317154 | 2022-04-11 15:26:17 -0700 | [diff] [blame] | 2369 | Ok(quote! { crubit::type_identity_t< |
Devin Jeanpierre | 1b8f4a1 | 2022-03-22 21:29:42 +0000 | [diff] [blame] | 2370 | #ret_type ( #( #param_types ),* ) #attr |
| 2371 | > }) |
| 2372 | } |
| 2373 | }, |
| 2374 | }, |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2375 | } |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2376 | } else { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 2377 | let item = ir.item_for_type(ty)?; |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2378 | let type_name = cc_type_name_for_item(item, ir)?; |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 2379 | Ok(quote! {#const_fragment #type_name}) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2380 | } |
| 2381 | } |
| 2382 | |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2383 | fn cc_struct_layout_assertion(record: &Record, ir: &IR) -> Result<TokenStream> { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 2384 | if !ir.is_current_target(&record.owning_target) && !ir.is_stdlib_target(&record.owning_target) { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2385 | return Ok(quote! {}); |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2386 | } |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 2387 | let record_ident = format_cc_ident(&record.cc_name); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2388 | let namespace_qualifier = generate_namespace_qualifier(record.id, ir)?; |
| 2389 | let namespace_qualifier = quote! { #(#namespace_qualifier::)* }; |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2390 | let size = Literal::usize_unsuffixed(record.size); |
| 2391 | let alignment = Literal::usize_unsuffixed(record.alignment); |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 2392 | let tag_kind = cc_tag_kind(record); |
Devin Jeanpierre | 190b90a | 2022-05-24 06:00:34 -0700 | [diff] [blame] | 2393 | let field_assertions = record |
| 2394 | .fields |
| 2395 | .iter() |
| 2396 | .filter(|f| f.access == AccessSpecifier::Public && f.identifier.is_some()) |
| 2397 | // https://en.cppreference.com/w/cpp/types/offsetof points out that "if member is [...] |
| 2398 | // a bit-field [...] the behavior [of `offsetof` macro] is undefined.". In such |
| 2399 | // scenario clang reports an error: cannot compute offset of bit-field 'field_name'. |
| 2400 | .filter(|f| !f.is_bitfield) |
| 2401 | .map(|field| { |
| 2402 | // The IR contains the offset in bits, while `CRUBIT_OFFSET_OF` returns the |
| 2403 | // offset in bytes, so we need to convert. We can assert that |
| 2404 | // `field.offset` is always at field boundaries, because the |
| 2405 | // bitfields have been filtered out earlier. |
| 2406 | assert_eq!(field.offset % 8, 0); |
| 2407 | let expected_offset = Literal::usize_unsuffixed(field.offset / 8); |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 2408 | |
Devin Jeanpierre | 190b90a | 2022-05-24 06:00:34 -0700 | [diff] [blame] | 2409 | let field_ident = format_cc_ident(&field.identifier.as_ref().unwrap().identifier); |
| 2410 | let actual_offset = quote! { |
| 2411 | CRUBIT_OFFSET_OF(#field_ident, #tag_kind #namespace_qualifier #record_ident) |
| 2412 | }; |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 2413 | |
Devin Jeanpierre | 190b90a | 2022-05-24 06:00:34 -0700 | [diff] [blame] | 2414 | quote! { static_assert( #actual_offset == #expected_offset); } |
| 2415 | }); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2416 | Ok(quote! { |
| 2417 | static_assert(sizeof(#tag_kind #namespace_qualifier #record_ident) == #size); |
| 2418 | static_assert(alignof(#tag_kind #namespace_qualifier #record_ident) == #alignment); |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2419 | #( #field_assertions )* |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2420 | }) |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2421 | } |
| 2422 | |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 2423 | // Returns the accessor functions for no_unique_address member variables. |
Devin Jeanpierre | 45b0196 | 2022-07-07 06:12:11 -0700 | [diff] [blame] | 2424 | fn cc_struct_no_unique_address_impl(db: &Database, record: &Record) -> Result<TokenStream> { |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 2425 | let mut fields = vec![]; |
| 2426 | let mut types = vec![]; |
| 2427 | for field in &record.fields { |
| 2428 | if field.access != AccessSpecifier::Public || !field.is_no_unique_address { |
| 2429 | continue; |
| 2430 | } |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 2431 | // Can't use `get_field_rs_type_for_layout` here, because we want to dig into |
| 2432 | // no_unique_address fields, despite laying them out as opaque blobs of bytes. |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 2433 | if let Ok(rs_type) = field.type_.as_ref().map(|t| t.rs_type.clone()) { |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 2434 | fields.push(make_rs_ident( |
| 2435 | &field |
| 2436 | .identifier |
| 2437 | .as_ref() |
| 2438 | .expect("Unnamed fields can't be annotated with [[no_unique_address]]") |
| 2439 | .identifier, |
| 2440 | )); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 2441 | types.push(db.rs_type_kind(rs_type).with_context(|| { |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 2442 | format!("Failed to format type for field {:?} on record {:?}", field, record) |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 2443 | })?); |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 2444 | } |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 2445 | } |
| 2446 | |
| 2447 | if fields.is_empty() { |
| 2448 | return Ok(quote! {}); |
| 2449 | } |
| 2450 | |
Lukasz Anforowicz | 4c3a2cc | 2022-03-11 00:24:49 +0000 | [diff] [blame] | 2451 | let ident = make_rs_ident(&record.rs_name); |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 2452 | Ok(quote! { |
| 2453 | impl #ident { |
| 2454 | #( |
| 2455 | pub fn #fields(&self) -> &#types { |
| 2456 | unsafe {&* (&self.#fields as *const _ as *const #types)} |
| 2457 | } |
| 2458 | )* |
| 2459 | } |
| 2460 | }) |
| 2461 | } |
| 2462 | |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2463 | /// Returns the implementation of base class conversions, for converting a type |
| 2464 | /// to its unambiguous public base classes. |
Devin Jeanpierre | 8763a8e | 2022-04-26 15:45:13 -0700 | [diff] [blame] | 2465 | fn cc_struct_upcast_impl(record: &Record, ir: &IR) -> Result<GeneratedItem> { |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2466 | let mut impls = Vec::with_capacity(record.unambiguous_public_bases.len()); |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2467 | let mut thunks = vec![]; |
| 2468 | let mut cc_impls = vec![]; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2469 | for base in &record.unambiguous_public_bases { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2470 | let base_record: &Rc<Record> = ir |
Lukasz Anforowicz | 4404725 | 2022-03-23 13:04:48 +0000 | [diff] [blame] | 2471 | .find_decl(base.base_record_id) |
| 2472 | .with_context(|| format!("Can't find a base record of {:?}", record))?; |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 2473 | let base_name = RsTypeKind::new_record(base_record.clone(), ir)?.into_token_stream(); |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2474 | let derived_name = make_rs_ident(&record.rs_name); |
| 2475 | let body; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2476 | if let Some(offset) = base.offset { |
| 2477 | let offset = Literal::i64_unsuffixed(offset); |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 2478 | body = quote! {(derived as *const _ as *const u8).offset(#offset) as *const #base_name}; |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2479 | } else { |
| 2480 | // TODO(b/216195042): use mangled names here, or otherwise guarantee |
| 2481 | // non-collision. |
| 2482 | let cast_fn_name = make_rs_ident(&format!( |
| 2483 | "__crubit_dynamic_upcast__{}__to__{}", |
| 2484 | record.rs_name, base_record.rs_name |
| 2485 | )); |
| 2486 | let base_cc_name = format_cc_ident(&base_record.cc_name); |
| 2487 | let derived_cc_name = format_cc_ident(&record.cc_name); |
| 2488 | cc_impls.push(quote! { |
| 2489 | extern "C" const #base_cc_name& #cast_fn_name(const #derived_cc_name& from) { |
| 2490 | return from; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2491 | } |
| 2492 | }); |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2493 | thunks.push(quote! { |
| 2494 | pub fn #cast_fn_name (from: *const #derived_name) -> *const #base_name; |
| 2495 | }); |
| 2496 | body = quote! { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 2497 | crate::detail::#cast_fn_name(derived) |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2498 | }; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2499 | } |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2500 | impls.push(quote! { |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 2501 | unsafe impl oops::Inherits<#base_name> for #derived_name { |
| 2502 | unsafe fn upcast_ptr(derived: *const Self) -> *const #base_name { |
| 2503 | #body |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2504 | } |
| 2505 | } |
| 2506 | }); |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2507 | } |
| 2508 | |
Devin Jeanpierre | 8763a8e | 2022-04-26 15:45:13 -0700 | [diff] [blame] | 2509 | Ok(GeneratedItem { |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 2510 | item: quote! {#(#impls)*}, |
| 2511 | thunks: quote! {#(#thunks)*}, |
| 2512 | thunk_impls: quote! {#(#cc_impls)*}, |
Devin Jeanpierre | 8763a8e | 2022-04-26 15:45:13 -0700 | [diff] [blame] | 2513 | ..Default::default() |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2514 | }) |
| 2515 | } |
| 2516 | |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2517 | fn thunk_ident(func: &Func) -> Ident { |
| 2518 | format_ident!("__rust_thunk__{}", func.mangled_name) |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 2519 | } |
| 2520 | |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 2521 | fn generate_rs_api_impl(ir: &IR, crubit_support_path: &str) -> Result<TokenStream> { |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 2522 | // This function uses quote! to generate C++ source code out of convenience. |
| 2523 | // This is a bold idea so we have to continously evaluate if it still makes |
| 2524 | // sense or the cost of working around differences in Rust and C++ tokens is |
| 2525 | // greather than the value added. |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2526 | // |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 2527 | // See rs_bindings_from_cc/ |
| 2528 | // token_stream_printer.rs for a list of supported placeholders. |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2529 | let mut thunks = vec![]; |
Michael Forster | 7ef8073 | 2021-10-01 18:12:19 +0000 | [diff] [blame] | 2530 | for func in ir.functions() { |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 2531 | if can_skip_cc_thunk(func) { |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2532 | continue; |
| 2533 | } |
| 2534 | |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2535 | let thunk_ident = thunk_ident(func); |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 2536 | let implementation_function = match &func.name { |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 2537 | UnqualifiedIdentifier::Operator(op) => { |
| 2538 | let name = syn::parse_str::<TokenStream>(&op.name)?; |
| 2539 | quote! { operator #name } |
| 2540 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 2541 | UnqualifiedIdentifier::Identifier(id) => { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 2542 | let fn_ident = format_cc_ident(&id.identifier); |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 2543 | match func.member_func_metadata.as_ref() { |
Lukasz Anforowicz | aab8ad2 | 2021-12-19 20:29:26 +0000 | [diff] [blame] | 2544 | Some(meta) => { |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 2545 | if let Some(_) = meta.instance_method_metadata { |
| 2546 | quote! { #fn_ident } |
| 2547 | } else { |
Devin Jeanpierre | ab85d44 | 2022-06-29 19:16:41 -0700 | [diff] [blame] | 2548 | let record: &Rc<Record> = ir.find_decl(meta.record_id)?; |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 2549 | let record_ident = format_cc_ident(&record.cc_name); |
| 2550 | let namespace_qualifier = generate_namespace_qualifier(record.id, ir)?; |
| 2551 | quote! { #(#namespace_qualifier::)* #record_ident :: #fn_ident } |
| 2552 | } |
| 2553 | } |
| 2554 | None => { |
| 2555 | let namespace_qualifier = generate_namespace_qualifier(func.id, ir)?; |
| 2556 | quote! { #(#namespace_qualifier::)* #fn_ident } |
Lukasz Anforowicz | aab8ad2 | 2021-12-19 20:29:26 +0000 | [diff] [blame] | 2557 | } |
| 2558 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 2559 | } |
Lukasz Anforowicz | 7b0042d | 2022-01-06 23:00:19 +0000 | [diff] [blame] | 2560 | // Use `destroy_at` to avoid needing to spell out the class name. Destructor identiifers |
Devin Jeanpierre | cc6cf09 | 2021-12-16 04:31:14 +0000 | [diff] [blame] | 2561 | // use the name of the type itself, without namespace qualification, template |
| 2562 | // parameters, or aliases. We do not need to use that naming scheme anywhere else in |
| 2563 | // the bindings, and it can be difficult (impossible?) to spell in the general case. By |
| 2564 | // using destroy_at, we avoid needing to determine or remember what the correct spelling |
Lukasz Anforowicz | 7b0042d | 2022-01-06 23:00:19 +0000 | [diff] [blame] | 2565 | // is. Similar arguments apply to `construct_at`. |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 2566 | UnqualifiedIdentifier::Constructor => { |
Lukasz Anforowicz | 2317154 | 2022-04-11 15:26:17 -0700 | [diff] [blame] | 2567 | quote! { crubit::construct_at } |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 2568 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 2569 | UnqualifiedIdentifier::Destructor => quote! {std::destroy_at}, |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 2570 | }; |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2571 | let return_type_name = format_cc_type(&func.return_type.cc_type, ir)?; |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 2572 | let return_stmt = if func.return_type.cc_type.is_void() { |
| 2573 | quote! {} |
| 2574 | } else { |
| 2575 | quote! { return } |
| 2576 | }; |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2577 | |
| 2578 | let param_idents = |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 2579 | func.params.iter().map(|p| format_cc_ident(&p.identifier.identifier)).collect_vec(); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2580 | |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 2581 | let param_types = func |
| 2582 | .params |
| 2583 | .iter() |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 2584 | .map(|p| format_cc_type(&p.type_.cc_type, ir)) |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 2585 | .collect::<Result<Vec<_>>>()?; |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2586 | |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2587 | let needs_this_deref = match &func.member_func_metadata { |
| 2588 | None => false, |
| 2589 | Some(meta) => match &func.name { |
| 2590 | UnqualifiedIdentifier::Constructor | UnqualifiedIdentifier::Destructor => false, |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 2591 | UnqualifiedIdentifier::Identifier(_) | UnqualifiedIdentifier::Operator(_) => { |
| 2592 | meta.instance_method_metadata.is_some() |
| 2593 | } |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2594 | }, |
| 2595 | }; |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2596 | |
| 2597 | let arg_expressions: Vec<_> = param_idents |
| 2598 | .iter() |
| 2599 | .map( |
| 2600 | // Forward references along. (If the parameter is a value, not a reference, this |
| 2601 | // will create an lvalue reference, and still do the right thing.) |
| 2602 | |ident| quote! {std::forward<decltype(#ident)>(#ident)}, |
| 2603 | ) |
| 2604 | .collect(); |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2605 | let (implementation_function, arg_expressions) = if !needs_this_deref { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2606 | (implementation_function, arg_expressions.clone()) |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2607 | } else { |
| 2608 | let this_param = func |
| 2609 | .params |
| 2610 | .first() |
| 2611 | .ok_or_else(|| anyhow!("Instance methods must have `__this` param."))?; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 2612 | let this_arg = format_cc_ident(&this_param.identifier.identifier); |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2613 | ( |
| 2614 | quote! { #this_arg -> #implementation_function}, |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2615 | arg_expressions.iter().skip(1).cloned().collect_vec(), |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2616 | ) |
| 2617 | }; |
| 2618 | |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2619 | thunks.push(quote! { |
| 2620 | extern "C" #return_type_name #thunk_ident( #( #param_types #param_idents ),* ) { |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2621 | #return_stmt #implementation_function( #( #arg_expressions ),* ); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2622 | } |
| 2623 | }); |
| 2624 | } |
| 2625 | |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2626 | let layout_assertions = ir |
| 2627 | .records() |
| 2628 | .map(|record| cc_struct_layout_assertion(record, ir)) |
| 2629 | .collect::<Result<Vec<_>>>()?; |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2630 | |
Devin Jeanpierre | 231ef8d | 2021-10-27 10:50:44 +0000 | [diff] [blame] | 2631 | let mut standard_headers = <BTreeSet<Ident>>::new(); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 2632 | standard_headers.insert(format_ident!("memory")); // ubiquitous. |
Devin Jeanpierre | 231ef8d | 2021-10-27 10:50:44 +0000 | [diff] [blame] | 2633 | if ir.records().next().is_some() { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 2634 | standard_headers.insert(format_ident!("cstddef")); |
Devin Jeanpierre | 231ef8d | 2021-10-27 10:50:44 +0000 | [diff] [blame] | 2635 | }; |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2636 | |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 2637 | let mut includes = vec!["cxx20_backports.h", "offsetof.h"] |
| 2638 | .into_iter() |
| 2639 | .map(|hdr| format!("{}/{}", crubit_support_path, hdr)) |
| 2640 | .collect_vec(); |
Lukasz Anforowicz | 4457baf | 2021-12-23 17:24:04 +0000 | [diff] [blame] | 2641 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 2642 | // In order to generate C++ thunk in all the cases Clang needs to be able to |
| 2643 | // access declarations from public headers of the C++ library. |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 2644 | includes.extend(ir.used_headers().map(|hdr| hdr.name.clone())); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2645 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2646 | Ok(quote! { |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2647 | #( __HASH_TOKEN__ include <#standard_headers> __NEWLINE__)* |
Devin Jeanpierre | 7c74f84 | 2022-02-03 07:08:06 +0000 | [diff] [blame] | 2648 | __NEWLINE__ |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2649 | #( __HASH_TOKEN__ include #includes __NEWLINE__)* __NEWLINE__ |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 2650 | __HASH_TOKEN__ pragma clang diagnostic push __NEWLINE__ |
| 2651 | // Disable Clang thread-safety-analysis warnings that would otherwise |
| 2652 | // complain about thunks that call mutex locking functions in an unpaired way. |
| 2653 | __HASH_TOKEN__ pragma clang diagnostic ignored "-Wthread-safety-analysis" __NEWLINE__ |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2654 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2655 | #( #thunks )* __NEWLINE__ __NEWLINE__ |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 2656 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2657 | #( #layout_assertions __NEWLINE__ __NEWLINE__ )* |
Marcel Hlopko | c6b726c | 2021-10-07 06:53:09 +0000 | [diff] [blame] | 2658 | |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 2659 | __NEWLINE__ |
| 2660 | __HASH_TOKEN__ pragma clang diagnostic pop __NEWLINE__ |
Marcel Hlopko | c6b726c | 2021-10-07 06:53:09 +0000 | [diff] [blame] | 2661 | // To satisfy http://cs/symbol:devtools.metadata.Presubmit.CheckTerminatingNewline check. |
| 2662 | __NEWLINE__ |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2663 | }) |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2664 | } |
| 2665 | |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 2666 | #[cfg(test)] |
| 2667 | mod tests { |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 2668 | use super::*; |
Lukasz Anforowicz | edabf00 | 2022-04-28 06:45:09 -0700 | [diff] [blame] | 2669 | use ir_testing::{ |
| 2670 | ir_from_cc, ir_from_cc_dependency, ir_record, make_ir_from_items, retrieve_func, |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 2671 | with_lifetime_macros, |
Lukasz Anforowicz | edabf00 | 2022-04-28 06:45:09 -0700 | [diff] [blame] | 2672 | }; |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 2673 | use static_assertions::{assert_impl_all, assert_not_impl_any}; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2674 | use token_stream_matchers::{ |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 2675 | assert_cc_matches, assert_cc_not_matches, assert_ir_matches, assert_rs_matches, |
| 2676 | assert_rs_not_matches, |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2677 | }; |
Lukasz Anforowicz | 54ff318 | 2022-05-06 07:17:58 -0700 | [diff] [blame] | 2678 | use token_stream_printer::{rs_tokens_to_formatted_string_for_tests, tokens_to_string}; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 2679 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2680 | fn generate_bindings_tokens(ir: Rc<IR>) -> Result<BindingsTokens> { |
Lukasz Anforowicz | dd90770 | 2022-05-06 09:24:07 -0700 | [diff] [blame] | 2681 | super::generate_bindings_tokens(ir, "crubit/rs_bindings_support") |
| 2682 | } |
| 2683 | |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 2684 | fn db_from_cc(cc_src: &str) -> Result<Database> { |
| 2685 | let mut db = Database::default(); |
| 2686 | db.set_ir(ir_from_cc(cc_src)?); |
| 2687 | Ok(db) |
| 2688 | } |
| 2689 | |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 2690 | #[test] |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 2691 | fn test_disable_thread_safety_warnings() -> Result<()> { |
| 2692 | let ir = ir_from_cc("inline void foo() {}")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2693 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 2694 | assert_cc_matches!( |
| 2695 | rs_api_impl, |
| 2696 | quote! { |
| 2697 | ... |
| 2698 | __HASH_TOKEN__ pragma clang diagnostic push |
| 2699 | __HASH_TOKEN__ pragma clang diagnostic ignored "-Wthread-safety-analysis" |
| 2700 | ... |
| 2701 | |
| 2702 | __HASH_TOKEN__ pragma clang diagnostic pop |
| 2703 | ... |
| 2704 | } |
| 2705 | ); |
| 2706 | Ok(()) |
| 2707 | } |
| 2708 | |
| 2709 | #[test] |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 2710 | // TODO(hlopko): Move this test to a more principled place where it can access |
| 2711 | // `ir_testing`. |
| 2712 | fn test_duplicate_decl_ids_err() { |
| 2713 | let mut r1 = ir_record("R1"); |
Lukasz Anforowicz | 14732b2 | 2022-06-02 09:11:08 -0700 | [diff] [blame] | 2714 | r1.id = ItemId::new_for_testing(42); |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 2715 | let mut r2 = ir_record("R2"); |
Lukasz Anforowicz | 14732b2 | 2022-06-02 09:11:08 -0700 | [diff] [blame] | 2716 | r2.id = ItemId::new_for_testing(42); |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 2717 | let result = make_ir_from_items([r1.into(), r2.into()]); |
| 2718 | assert!(result.is_err()); |
| 2719 | assert!(result.unwrap_err().to_string().contains("Duplicate decl_id found in")); |
| 2720 | } |
| 2721 | |
| 2722 | #[test] |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 2723 | fn test_simple_function() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2724 | let ir = ir_from_cc("int Add(int a, int b);")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2725 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2726 | assert_rs_matches!( |
| 2727 | rs_api, |
| 2728 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2729 | #[inline(always)] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2730 | pub fn Add(a: i32, b: i32) -> i32 { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 2731 | unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2732 | } |
| 2733 | } |
| 2734 | ); |
| 2735 | assert_rs_matches!( |
| 2736 | rs_api, |
| 2737 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2738 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 2739 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 2740 | use super::*; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2741 | extern "C" { |
| 2742 | #[link_name = "_Z3Addii"] |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2743 | pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2744 | } |
| 2745 | } |
| 2746 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 2747 | ); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2748 | |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 2749 | assert_cc_not_matches!(rs_api_impl, quote! {__rust_thunk___Z3Addii}); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2750 | |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2751 | Ok(()) |
| 2752 | } |
| 2753 | |
| 2754 | #[test] |
| 2755 | fn test_inline_function() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2756 | let ir = ir_from_cc("inline int Add(int a, int b);")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2757 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2758 | assert_rs_matches!( |
| 2759 | rs_api, |
| 2760 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2761 | #[inline(always)] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2762 | pub fn Add(a: i32, b: i32) -> i32 { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 2763 | unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2764 | } |
| 2765 | } |
| 2766 | ); |
| 2767 | assert_rs_matches!( |
| 2768 | rs_api, |
| 2769 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2770 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 2771 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 2772 | use super::*; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2773 | extern "C" { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2774 | pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2775 | } |
| 2776 | } |
| 2777 | } |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2778 | ); |
| 2779 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2780 | assert_cc_matches!( |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 2781 | rs_api_impl, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2782 | quote! { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2783 | extern "C" int __rust_thunk___Z3Addii(int a, int b) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2784 | return Add(std::forward<decltype(a)>(a), std::forward<decltype(b)>(b)); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2785 | } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2786 | } |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 2787 | ); |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 2788 | Ok(()) |
| 2789 | } |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 2790 | |
| 2791 | #[test] |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2792 | fn test_simple_function_with_types_from_other_target() -> Result<()> { |
| 2793 | let ir = ir_from_cc_dependency( |
| 2794 | "inline ReturnStruct DoSomething(ParamStruct param);", |
| 2795 | "struct ReturnStruct {}; struct ParamStruct {};", |
| 2796 | )?; |
| 2797 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2798 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2799 | assert_rs_matches!( |
| 2800 | rs_api, |
| 2801 | quote! { |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2802 | #[inline(always)] |
| 2803 | pub fn DoSomething(param: dependency::ParamStruct) |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2804 | -> dependency::ReturnStruct { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 2805 | unsafe { crate::detail::__rust_thunk___Z11DoSomething11ParamStruct(param) } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2806 | } |
| 2807 | } |
| 2808 | ); |
| 2809 | assert_rs_matches!( |
| 2810 | rs_api, |
| 2811 | quote! { |
| 2812 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 2813 | #[allow(unused_imports)] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2814 | use super::*; |
| 2815 | extern "C" { |
| 2816 | pub(crate) fn __rust_thunk___Z11DoSomething11ParamStruct(param: dependency::ParamStruct) |
| 2817 | -> dependency::ReturnStruct; |
| 2818 | } |
| 2819 | }} |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2820 | ); |
| 2821 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2822 | assert_cc_matches!( |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 2823 | rs_api_impl, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2824 | quote! { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 2825 | extern "C" struct ReturnStruct __rust_thunk___Z11DoSomething11ParamStruct(struct ParamStruct param) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 2826 | return DoSomething(std::forward<decltype(param)>(param)); |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2827 | } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2828 | } |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2829 | ); |
| 2830 | Ok(()) |
| 2831 | } |
| 2832 | |
| 2833 | #[test] |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2834 | fn test_template_in_dependency_and_alias_in_current_target() -> Result<()> { |
| 2835 | // See also the test with the same name in `ir_from_cc_test.rs`. |
| 2836 | let ir = { |
| 2837 | let dependency_src = r#" #pragma clang lifetime_elision |
| 2838 | template <typename T> |
| 2839 | struct MyTemplate { |
| 2840 | T GetValue() { return field; } |
| 2841 | T field; |
| 2842 | }; "#; |
| 2843 | let current_target_src = r#" #pragma clang lifetime_elision |
| 2844 | using MyAliasOfTemplate = MyTemplate<int>; "#; |
| 2845 | ir_from_cc_dependency(current_target_src, dependency_src)? |
| 2846 | }; |
| 2847 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2848 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2849 | assert_rs_matches!( |
| 2850 | rs_api, |
| 2851 | quote! { |
| 2852 | #[repr(C)] |
| 2853 | pub struct __CcTemplateInst10MyTemplateIiE { |
| 2854 | pub field: i32, |
| 2855 | } |
| 2856 | } |
| 2857 | ); |
| 2858 | assert_rs_matches!( |
| 2859 | rs_api, |
| 2860 | quote! { |
| 2861 | impl __CcTemplateInst10MyTemplateIiE { |
| 2862 | #[inline(always)] |
| 2863 | pub fn GetValue<'a>(self: ... Pin<&'a mut Self>) -> i32 { unsafe { |
Lukasz Anforowicz | 8d1e432 | 2022-06-08 07:56:06 -0700 | [diff] [blame] | 2864 | crate::detail::__rust_thunk___ZN10MyTemplateIiE8GetValueEv__2f_2ftest_3atesting_5ftarget( |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2865 | self) |
| 2866 | }} |
| 2867 | } |
| 2868 | } |
| 2869 | ); |
| 2870 | assert_rs_matches!( |
| 2871 | rs_api, |
| 2872 | quote! { |
| 2873 | pub type MyAliasOfTemplate = crate::__CcTemplateInst10MyTemplateIiE; |
| 2874 | } |
| 2875 | ); |
| 2876 | assert_rs_matches!( |
| 2877 | rs_api, |
| 2878 | quote! { |
Lukasz Anforowicz | 8d1e432 | 2022-06-08 07:56:06 -0700 | [diff] [blame] | 2879 | mod detail { ... extern "C" { |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2880 | ... |
Lukasz Anforowicz | 8d1e432 | 2022-06-08 07:56:06 -0700 | [diff] [blame] | 2881 | pub(crate) fn |
| 2882 | __rust_thunk___ZN10MyTemplateIiE8GetValueEv__2f_2ftest_3atesting_5ftarget<'a>( |
| 2883 | __this: ... Pin<&'a mut crate::__CcTemplateInst10MyTemplateIiE> |
| 2884 | ) -> i32; |
| 2885 | ... |
| 2886 | } } |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2887 | } |
| 2888 | ); |
| 2889 | assert_cc_matches!( |
| 2890 | rs_api_impl, |
| 2891 | quote! { |
Lukasz Anforowicz | 8d1e432 | 2022-06-08 07:56:06 -0700 | [diff] [blame] | 2892 | extern "C" |
| 2893 | int __rust_thunk___ZN10MyTemplateIiE8GetValueEv__2f_2ftest_3atesting_5ftarget( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 2894 | struct MyTemplate<int>* __this) { |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2895 | return __this->GetValue(); |
| 2896 | } |
| 2897 | } |
| 2898 | ); |
| 2899 | |
| 2900 | Ok(()) |
| 2901 | } |
| 2902 | |
| 2903 | #[test] |
| 2904 | fn test_template_with_out_of_line_definition() -> Result<()> { |
| 2905 | // See also an end-to-end test in the `test/templates/out_of_line_definition` |
| 2906 | // directory. |
| 2907 | let ir = ir_from_cc( |
| 2908 | r#" #pragma clang lifetime_elision |
| 2909 | template <typename T> |
| 2910 | class MyTemplate final { |
| 2911 | public: |
| 2912 | static MyTemplate Create(T value); |
| 2913 | const T& value() const; |
| 2914 | |
| 2915 | private: |
| 2916 | T value_; |
| 2917 | }; |
| 2918 | |
| 2919 | using MyTypeAlias = MyTemplate<int>; "#, |
| 2920 | )?; |
| 2921 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2922 | let BindingsTokens { rs_api_impl, .. } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2923 | |
| 2924 | // Even though the member functions above are *not* defined inline (e.g. |
| 2925 | // IR::Func::is_inline is false), they still need to have thunks generated for |
| 2926 | // them (to force/guarantee that the class template and its members get |
| 2927 | // instantiated). This is also covered in the following end-to-end |
| 2928 | // tests: |
| 2929 | // - test/templates/out_of_line_definition/ - without a thunk, the template |
| 2930 | // won't be instantiated and Rust bindings won't be able to call the member |
| 2931 | // function (there will be no instantiation of the member function in the C++ |
| 2932 | // object files) |
| 2933 | // - test/templates/definition_in_cc/ - the instantiation happens in the .cc |
| 2934 | // file and therefore the thunk is not *required* (but it doesn't hurt to have |
| 2935 | // the thunk) |
| 2936 | assert_cc_matches!( |
| 2937 | rs_api_impl, |
| 2938 | quote! { |
| 2939 | extern "C" class MyTemplate<int> |
Lukasz Anforowicz | 8d1e432 | 2022-06-08 07:56:06 -0700 | [diff] [blame] | 2940 | __rust_thunk___ZN10MyTemplateIiE6CreateEi__2f_2ftest_3atesting_5ftarget( |
| 2941 | int value) { |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2942 | return MyTemplate<int>::Create(std::forward<decltype(value)>(value)); |
| 2943 | } |
| 2944 | } |
| 2945 | ); |
| 2946 | assert_cc_matches!( |
| 2947 | rs_api_impl, |
| 2948 | quote! { |
| 2949 | extern "C" int const& |
Lukasz Anforowicz | 8d1e432 | 2022-06-08 07:56:06 -0700 | [diff] [blame] | 2950 | __rust_thunk___ZNK10MyTemplateIiE5valueEv__2f_2ftest_3atesting_5ftarget( |
Lukasz Anforowicz | b1ff2e5 | 2022-05-16 10:54:23 -0700 | [diff] [blame] | 2951 | const class MyTemplate<int>*__this) { |
| 2952 | return __this->value(); |
| 2953 | } |
| 2954 | } |
| 2955 | ); |
| 2956 | Ok(()) |
| 2957 | } |
| 2958 | |
| 2959 | #[test] |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 2960 | fn test_simple_struct() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2961 | let ir = ir_from_cc(&tokens_to_string(quote! { |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2962 | struct SomeStruct final { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2963 | int public_int; |
| 2964 | protected: |
| 2965 | int protected_int; |
| 2966 | private: |
| 2967 | int private_int; |
| 2968 | }; |
| 2969 | })?)?; |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 2970 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 2971 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2972 | assert_rs_matches!( |
| 2973 | rs_api, |
| 2974 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2975 | #[derive(Clone, Copy)] |
Lukasz Anforowicz | df8fcae | 2022-06-02 14:54:43 -0700 | [diff] [blame] | 2976 | #[repr(C, align(4))] |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2977 | pub struct SomeStruct { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2978 | __non_field_data: [::std::mem::MaybeUninit<u8>; 0], |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2979 | pub public_int: i32, |
Lukasz Anforowicz | df8fcae | 2022-06-02 14:54:43 -0700 | [diff] [blame] | 2980 | #[doc = " Reason for representing this field as a blob of bytes:\n Types of non-public C++ fields can be elided away"] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2981 | pub(crate) protected_int: [::std::mem::MaybeUninit<u8>; 4], |
Lukasz Anforowicz | df8fcae | 2022-06-02 14:54:43 -0700 | [diff] [blame] | 2982 | #[doc = " Reason for representing this field as a blob of bytes:\n Types of non-public C++ fields can be elided away"] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2983 | pub(crate) private_int: [::std::mem::MaybeUninit<u8>; 4], |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2984 | } |
| 2985 | } |
| 2986 | ); |
| 2987 | assert_rs_matches!( |
| 2988 | rs_api, |
| 2989 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 2990 | const _: () = assert!(::std::mem::size_of::<Option<&i32>>() == ::std::mem::size_of::<&i32>()); |
| 2991 | const _: () = assert!(::std::mem::size_of::<crate::SomeStruct>() == 12); |
| 2992 | const _: () = assert!(::std::mem::align_of::<crate::SomeStruct>() == 4); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 2993 | const _: () = { static_assertions::assert_impl_all!(crate::SomeStruct: Clone); }; |
| 2994 | const _: () = { static_assertions::assert_impl_all!(crate::SomeStruct: Copy); }; |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 2995 | const _: () = { static_assertions::assert_not_impl_any!(crate::SomeStruct: Drop); }; |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 2996 | const _: () = assert!(memoffset_unstable_const::offset_of!(crate::SomeStruct, public_int) == 0); |
| 2997 | const _: () = assert!(memoffset_unstable_const::offset_of!(crate::SomeStruct, protected_int) == 4); |
| 2998 | const _: () = assert!(memoffset_unstable_const::offset_of!(crate::SomeStruct, private_int) == 8); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2999 | } |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 3000 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3001 | assert_cc_matches!( |
| 3002 | rs_api_impl, |
| 3003 | quote! { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3004 | extern "C" void __rust_thunk___ZN10SomeStructD1Ev(struct SomeStruct * __this) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3005 | std :: destroy_at (std::forward<decltype(__this)>(__this)) ; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3006 | } |
| 3007 | } |
| 3008 | ); |
| 3009 | assert_cc_matches!( |
| 3010 | rs_api_impl, |
| 3011 | quote! { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3012 | static_assert(sizeof(struct SomeStruct) == 12); |
| 3013 | static_assert(alignof(struct SomeStruct) == 4); |
| 3014 | static_assert(CRUBIT_OFFSET_OF(public_int, struct SomeStruct) == 0); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3015 | } |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 3016 | ); |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 3017 | Ok(()) |
| 3018 | } |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 3019 | |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3020 | #[test] |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3021 | fn test_struct_vs_class() -> Result<()> { |
| 3022 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 3023 | struct SomeStruct final { int field; }; |
| 3024 | class SomeClass final { int field; }; |
| 3025 | })?)?; |
| 3026 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
| 3027 | |
| 3028 | // A Rust `struct` is generated for both `SomeStruct` and `SomeClass`. |
| 3029 | assert_rs_matches!(rs_api, quote! { pub struct SomeStruct },); |
| 3030 | assert_rs_matches!(rs_api, quote! { pub struct SomeClass },); |
| 3031 | |
| 3032 | // But in C++ we still should refer to `struct SomeStruct` and `class |
| 3033 | // SomeClass`. See also b/238212337. |
| 3034 | assert_cc_matches!(rs_api_impl, quote! { struct SomeStruct * __this }); |
| 3035 | assert_cc_matches!(rs_api_impl, quote! { class SomeClass * __this }); |
| 3036 | assert_cc_matches!(rs_api_impl, quote! { static_assert(sizeof(struct SomeStruct) == 4); }); |
| 3037 | assert_cc_matches!(rs_api_impl, quote! { static_assert(sizeof(class SomeClass) == 4); }); |
| 3038 | Ok(()) |
| 3039 | } |
| 3040 | |
| 3041 | #[test] |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 3042 | fn test_ref_to_struct_in_thunk_impls() -> Result<()> { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3043 | let ir = ir_from_cc("struct S{}; inline void foo(S& s) {} ")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3044 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 3045 | assert_cc_matches!( |
| 3046 | rs_api_impl, |
| 3047 | quote! { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3048 | extern "C" void __rust_thunk___Z3fooR1S(struct S& s) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3049 | foo(std::forward<decltype(s)>(s)); |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 3050 | } |
| 3051 | } |
| 3052 | ); |
| 3053 | Ok(()) |
| 3054 | } |
| 3055 | |
| 3056 | #[test] |
| 3057 | fn test_const_ref_to_struct_in_thunk_impls() -> Result<()> { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3058 | let ir = ir_from_cc("struct S{}; inline void foo(const S& s) {} ")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3059 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 3060 | assert_cc_matches!( |
| 3061 | rs_api_impl, |
| 3062 | quote! { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3063 | extern "C" void __rust_thunk___Z3fooRK1S(const struct S& s) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3064 | foo(std::forward<decltype(s)>(s)); |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 3065 | } |
| 3066 | } |
| 3067 | ); |
| 3068 | Ok(()) |
| 3069 | } |
| 3070 | |
| 3071 | #[test] |
Lukasz Anforowicz | 957cbf2 | 2022-01-05 16:14:05 +0000 | [diff] [blame] | 3072 | fn test_unsigned_int_in_thunk_impls() -> Result<()> { |
| 3073 | let ir = ir_from_cc("inline void foo(unsigned int i) {} ")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3074 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Lukasz Anforowicz | 957cbf2 | 2022-01-05 16:14:05 +0000 | [diff] [blame] | 3075 | assert_cc_matches!( |
| 3076 | rs_api_impl, |
| 3077 | quote! { |
| 3078 | extern "C" void __rust_thunk___Z3fooj(unsigned int i) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3079 | foo(std::forward<decltype(i)>(i)); |
Lukasz Anforowicz | 957cbf2 | 2022-01-05 16:14:05 +0000 | [diff] [blame] | 3080 | } |
| 3081 | } |
| 3082 | ); |
| 3083 | Ok(()) |
| 3084 | } |
| 3085 | |
| 3086 | #[test] |
Marcel Hlopko | dd1fcb1 | 2021-12-22 14:13:59 +0000 | [diff] [blame] | 3087 | fn test_record_static_methods_qualify_call_in_thunk() -> Result<()> { |
| 3088 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 3089 | struct SomeStruct { |
| 3090 | static inline int some_func() { return 42; } |
| 3091 | }; |
| 3092 | })?)?; |
| 3093 | |
| 3094 | assert_cc_matches!( |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3095 | generate_bindings_tokens(ir)?.rs_api_impl, |
Marcel Hlopko | dd1fcb1 | 2021-12-22 14:13:59 +0000 | [diff] [blame] | 3096 | quote! { |
| 3097 | extern "C" int __rust_thunk___ZN10SomeStruct9some_funcEv() { |
| 3098 | return SomeStruct::some_func(); |
| 3099 | } |
| 3100 | } |
| 3101 | ); |
| 3102 | Ok(()) |
| 3103 | } |
| 3104 | |
| 3105 | #[test] |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 3106 | fn test_record_instance_methods_deref_this_in_thunk() -> Result<()> { |
| 3107 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 3108 | struct SomeStruct { |
| 3109 | inline int some_func(int arg) const { return 42 + arg; } |
| 3110 | }; |
| 3111 | })?)?; |
| 3112 | |
| 3113 | assert_cc_matches!( |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3114 | generate_bindings_tokens(ir)?.rs_api_impl, |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 3115 | quote! { |
| 3116 | extern "C" int __rust_thunk___ZNK10SomeStruct9some_funcEi( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 3117 | const struct SomeStruct* __this, int arg) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3118 | return __this->some_func(std::forward<decltype(arg)>(arg)); |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 3119 | } |
| 3120 | } |
| 3121 | ); |
| 3122 | Ok(()) |
| 3123 | } |
| 3124 | |
| 3125 | #[test] |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 3126 | fn test_record_with_unsupported_field_type() -> Result<()> { |
| 3127 | // Using a nested struct because it's currently not supported. |
| 3128 | // But... any other unsupported type would also work for this test. |
| 3129 | let ir = ir_from_cc( |
| 3130 | r#" |
| 3131 | struct StructWithUnsupportedField { |
| 3132 | struct NestedStruct { |
| 3133 | int nested_field; |
| 3134 | }; |
| 3135 | |
| 3136 | // Doc comment for `my_field`. |
| 3137 | NestedStruct my_field; |
| 3138 | }; |
| 3139 | "#, |
| 3140 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3141 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 3142 | assert_rs_matches!( |
| 3143 | rs_api, |
| 3144 | quote! { |
| 3145 | #[repr(C, align(4))] |
| 3146 | pub struct StructWithUnsupportedField { |
| 3147 | #[doc = " Doc comment for `my_field`.\n \n Reason for representing this field as a blob of bytes:\n Unsupported type 'struct StructWithUnsupportedField::NestedStruct': No generated bindings found for 'NestedStruct'"] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3148 | pub(crate) my_field: [::std::mem::MaybeUninit<u8>; 4], |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 3149 | } |
| 3150 | ... |
| 3151 | const _: () = assert!( |
| 3152 | memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3153 | crate::StructWithUnsupportedField, my_field) == 0); |
Lukasz Anforowicz | fea0db9 | 2022-05-17 17:28:04 -0700 | [diff] [blame] | 3154 | } |
| 3155 | ); |
| 3156 | Ok(()) |
| 3157 | } |
| 3158 | |
| 3159 | #[test] |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3160 | fn test_struct_with_unnamed_bitfield_member() -> Result<()> { |
| 3161 | // This test input causes `field_decl->getName()` to return an empty string. |
| 3162 | // This example is based on `struct timex` from |
| 3163 | // /usr/grte/v5/include/bits/timex.h |
| 3164 | let ir = ir_from_cc( |
| 3165 | r#" |
| 3166 | struct SomeStruct { |
| 3167 | int first_field; |
| 3168 | int :32; |
| 3169 | int last_field; |
| 3170 | }; "#, |
| 3171 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3172 | let BindingsTokens { rs_api, .. } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3173 | assert_rs_matches!( |
| 3174 | rs_api, |
| 3175 | quote! { |
| 3176 | #[repr(C)] |
| 3177 | pub struct SomeStruct { |
Michael Forster | 82c02d3 | 2022-05-20 21:47:33 -0700 | [diff] [blame] | 3178 | pub first_field: i32, ... |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3179 | __bitfields1: [::std::mem::MaybeUninit<u8>; 4], |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3180 | pub last_field: i32, |
| 3181 | } |
| 3182 | ... |
| 3183 | const _: () = assert!(memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3184 | crate::SomeStruct, first_field) == 0); |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3185 | const _: () = assert!(memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3186 | crate::SomeStruct, last_field) == 8); |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3187 | } |
| 3188 | ); |
| 3189 | Ok(()) |
| 3190 | } |
| 3191 | |
| 3192 | #[test] |
| 3193 | fn test_struct_with_unnamed_struct_and_union_members() -> Result<()> { |
| 3194 | // This test input causes `field_decl->getName()` to return an empty string. |
| 3195 | // See also: |
| 3196 | // - https://en.cppreference.com/w/c/language/struct: "[...] an unnamed member |
| 3197 | // of a struct whose type is a struct without name is known as anonymous |
| 3198 | // struct." |
| 3199 | // - https://rust-lang.github.io/rfcs/2102-unnamed-fields.html |
| 3200 | let ir = ir_from_cc( |
| 3201 | r#" |
| 3202 | struct StructWithUnnamedMembers { |
| 3203 | int first_field; |
| 3204 | |
| 3205 | struct { |
| 3206 | int anonymous_struct_field_1; |
| 3207 | int anonymous_struct_field_2; |
| 3208 | }; |
| 3209 | union { |
| 3210 | int anonymous_union_field_1; |
| 3211 | int anonymous_union_field_2; |
| 3212 | }; |
| 3213 | |
| 3214 | int last_field; |
| 3215 | }; "#, |
| 3216 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3217 | let BindingsTokens { rs_api, .. } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3218 | // TODO(b/200067824): Once nested structs anhd unions are supported, |
| 3219 | // `__unnamed_field1` and `__unnamed_field2` should have a real, usable |
| 3220 | // type. |
| 3221 | assert_rs_matches!( |
| 3222 | rs_api, |
| 3223 | quote! { |
| 3224 | #[repr(C, align(4))] |
| 3225 | pub struct StructWithUnnamedMembers { |
| 3226 | pub first_field: i32, |
| 3227 | #[doc=" Reason for representing this field as a blob of bytes:\n Unsupported type 'struct StructWithUnnamedMembers::(anonymous at ir_from_cc_virtual_header.h:7:15)': No generated bindings found for ''"] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3228 | pub(crate) __unnamed_field1: [::std::mem::MaybeUninit<u8>; 8], |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3229 | #[doc=" Reason for representing this field as a blob of bytes:\n Unsupported type 'union StructWithUnnamedMembers::(anonymous at ir_from_cc_virtual_header.h:11:15)': No generated bindings found for ''"] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3230 | pub(crate) __unnamed_field2: [::std::mem::MaybeUninit<u8>; 4], |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3231 | pub last_field: i32, |
| 3232 | } |
| 3233 | ... |
| 3234 | const _: () = assert!(memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3235 | crate::StructWithUnnamedMembers, first_field) == 0); |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3236 | const _: () = assert!(memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3237 | crate::StructWithUnnamedMembers, __unnamed_field1) == 4); |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3238 | const _: () = assert!(memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3239 | crate::StructWithUnnamedMembers, __unnamed_field2) == 12); |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3240 | const _: () = assert!(memoffset_unstable_const::offset_of!( |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 3241 | crate::StructWithUnnamedMembers, last_field) == 16); |
Lukasz Anforowicz | e200e8a | 2022-05-18 12:36:33 -0700 | [diff] [blame] | 3242 | } |
| 3243 | ); |
| 3244 | Ok(()) |
| 3245 | } |
| 3246 | |
| 3247 | #[test] |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 3248 | fn test_struct_from_other_target() -> Result<()> { |
| 3249 | let ir = ir_from_cc_dependency("// intentionally empty", "struct SomeStruct {};")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3250 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 3251 | assert_rs_not_matches!(rs_api, quote! { SomeStruct }); |
| 3252 | assert_cc_not_matches!(rs_api_impl, quote! { SomeStruct }); |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 3253 | Ok(()) |
| 3254 | } |
| 3255 | |
| 3256 | #[test] |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3257 | fn test_copy_derives() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 3258 | let record = ir_record("S"); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3259 | assert_eq!(generate_derives(&record), &["Clone", "Copy"]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3260 | } |
| 3261 | |
| 3262 | #[test] |
| 3263 | fn test_copy_derives_not_is_trivial_abi() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 3264 | let mut record = ir_record("S"); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3265 | record.is_trivial_abi = false; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3266 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3267 | } |
| 3268 | |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3269 | /// Even if it's trivially relocatable, !Unpin C++ type cannot be |
| 3270 | /// cloned/copied or otherwise used by value, because values would allow |
| 3271 | /// assignment into the Pin. |
| 3272 | /// |
| 3273 | /// All !Unpin C++ types, not just non trivially relocatable ones, are |
| 3274 | /// unsafe to assign in the Rust sense. |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 3275 | #[test] |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3276 | fn test_copy_derives_not_final() { |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 3277 | let mut record = ir_record("S"); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 3278 | record.is_inheritable = true; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3279 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 3280 | } |
| 3281 | |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3282 | #[test] |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3283 | fn test_copy_derives_ctor_deleted() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 3284 | let mut record = ir_record("S"); |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 3285 | record.copy_constructor = ir::SpecialMemberFunc::Unavailable; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3286 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3287 | } |
| 3288 | |
| 3289 | #[test] |
Devin Jeanpierre | be2f33b | 2021-10-21 12:54:19 +0000 | [diff] [blame] | 3290 | fn test_copy_derives_ctor_nontrivial_members() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 3291 | let mut record = ir_record("S"); |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 3292 | record.copy_constructor = ir::SpecialMemberFunc::NontrivialMembers; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3293 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | be2f33b | 2021-10-21 12:54:19 +0000 | [diff] [blame] | 3294 | } |
| 3295 | |
| 3296 | #[test] |
| 3297 | fn test_copy_derives_ctor_nontrivial_self() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 3298 | let mut record = ir_record("S"); |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 3299 | record.copy_constructor = ir::SpecialMemberFunc::NontrivialUserDefined; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3300 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 3301 | } |
| 3302 | |
Devin Jeanpierre | b1e816a | 2022-04-29 20:14:22 -0700 | [diff] [blame] | 3303 | /// In Rust, a Drop type cannot be Copy. |
| 3304 | #[test] |
| 3305 | fn test_copy_derives_dtor_nontrivial_self() { |
| 3306 | let mut record = ir_record("S"); |
Lukasz Anforowicz | ff7df4a | 2022-06-02 14:27:45 -0700 | [diff] [blame] | 3307 | for definition in |
| 3308 | [ir::SpecialMemberFunc::NontrivialUserDefined, ir::SpecialMemberFunc::NontrivialMembers] |
| 3309 | { |
| 3310 | record.destructor = definition; |
Devin Jeanpierre | b1e816a | 2022-04-29 20:14:22 -0700 | [diff] [blame] | 3311 | assert_eq!(generate_derives(&record), &["Clone"]); |
| 3312 | } |
| 3313 | } |
| 3314 | |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 3315 | #[test] |
| 3316 | fn test_ptr_func() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3317 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 3318 | inline int* Deref(int*const* p); |
| 3319 | })?)?; |
Devin Jeanpierre | d6da700 | 2021-10-21 12:55:20 +0000 | [diff] [blame] | 3320 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3321 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3322 | assert_rs_matches!( |
| 3323 | rs_api, |
| 3324 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 3325 | #[inline(always)] |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 3326 | pub unsafe fn Deref(p: *const *mut i32) -> *mut i32 { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 3327 | crate::detail::__rust_thunk___Z5DerefPKPi(p) |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3328 | } |
| 3329 | } |
| 3330 | ); |
| 3331 | assert_rs_matches!( |
| 3332 | rs_api, |
| 3333 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 3334 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 3335 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 3336 | use super::*; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 3337 | extern "C" { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 3338 | pub(crate) fn __rust_thunk___Z5DerefPKPi(p: *const *mut i32) -> *mut i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3339 | } |
| 3340 | } |
| 3341 | } |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 3342 | ); |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 3343 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3344 | assert_cc_matches!( |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 3345 | rs_api_impl, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3346 | quote! { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 3347 | extern "C" int* __rust_thunk___Z5DerefPKPi(int* const * p) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3348 | return Deref(std::forward<decltype(p)>(p)); |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 3349 | } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3350 | } |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 3351 | ); |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 3352 | Ok(()) |
| 3353 | } |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 3354 | |
| 3355 | #[test] |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 3356 | fn test_const_char_ptr_func() -> Result<()> { |
| 3357 | // This is a regression test: We used to include the "const" in the name |
| 3358 | // of the CcType, which caused a panic in the code generator |
| 3359 | // ('"const char" is not a valid Ident'). |
| 3360 | // It's therefore important that f() is inline so that we need to |
| 3361 | // generate a thunk for it (where we then process the CcType). |
| 3362 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 3363 | inline void f(const char *str); |
| 3364 | })?)?; |
| 3365 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3366 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 3367 | assert_rs_matches!( |
| 3368 | rs_api, |
| 3369 | quote! { |
| 3370 | #[inline(always)] |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 3371 | pub unsafe fn f(str: *const i8) { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 3372 | crate::detail::__rust_thunk___Z1fPKc(str) |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 3373 | } |
| 3374 | } |
| 3375 | ); |
| 3376 | assert_rs_matches!( |
| 3377 | rs_api, |
| 3378 | quote! { |
| 3379 | extern "C" { |
| 3380 | pub(crate) fn __rust_thunk___Z1fPKc(str: *const i8); |
| 3381 | } |
| 3382 | } |
| 3383 | ); |
| 3384 | |
| 3385 | assert_cc_matches!( |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 3386 | rs_api_impl, |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 3387 | quote! { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 3388 | extern "C" void __rust_thunk___Z1fPKc(char const * str){ f(std::forward<decltype(str)>(str)) ; } |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 3389 | } |
| 3390 | ); |
| 3391 | Ok(()) |
| 3392 | } |
| 3393 | |
| 3394 | #[test] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3395 | fn test_func_ptr_where_params_are_primitive_types() -> Result<()> { |
| 3396 | let ir = ir_from_cc(r#" int (*get_ptr_to_func())(float, double); "#)?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3397 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3398 | assert_rs_matches!( |
| 3399 | rs_api, |
| 3400 | quote! { |
| 3401 | #[inline(always)] |
| 3402 | pub fn get_ptr_to_func() -> Option<extern "C" fn (f32, f64) -> i32> { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 3403 | unsafe { crate::detail::__rust_thunk___Z15get_ptr_to_funcv() } |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3404 | } |
| 3405 | } |
| 3406 | ); |
| 3407 | assert_rs_matches!( |
| 3408 | rs_api, |
| 3409 | quote! { |
| 3410 | mod detail { |
| 3411 | #[allow(unused_imports)] |
| 3412 | use super::*; |
| 3413 | extern "C" { |
| 3414 | #[link_name = "_Z15get_ptr_to_funcv"] |
| 3415 | pub(crate) fn __rust_thunk___Z15get_ptr_to_funcv() |
| 3416 | -> Option<extern "C" fn(f32, f64) -> i32>; |
| 3417 | } |
| 3418 | } |
| 3419 | } |
| 3420 | ); |
| 3421 | // Verify that no C++ thunk got generated. |
| 3422 | assert_cc_not_matches!(rs_api_impl, quote! { __rust_thunk___Z15get_ptr_to_funcv }); |
| 3423 | |
| 3424 | // TODO(b/217419782): Add another test for more exotic calling conventions / |
| 3425 | // abis. |
| 3426 | |
| 3427 | // TODO(b/217419782): Add another test for pointer to a function that |
| 3428 | // takes/returns non-trivially-movable types by value. See also |
| 3429 | // <internal link> |
| 3430 | |
| 3431 | Ok(()) |
| 3432 | } |
| 3433 | |
| 3434 | #[test] |
Lukasz Anforowicz | 92c81c3 | 2022-03-04 19:03:56 +0000 | [diff] [blame] | 3435 | fn test_func_ref() -> Result<()> { |
| 3436 | let ir = ir_from_cc(r#" int (&get_ref_to_func())(float, double); "#)?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3437 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 92c81c3 | 2022-03-04 19:03:56 +0000 | [diff] [blame] | 3438 | assert_rs_matches!( |
| 3439 | rs_api, |
| 3440 | quote! { |
| 3441 | #[inline(always)] |
| 3442 | pub fn get_ref_to_func() -> extern "C" fn (f32, f64) -> i32 { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 3443 | unsafe { crate::detail::__rust_thunk___Z15get_ref_to_funcv() } |
Lukasz Anforowicz | 92c81c3 | 2022-03-04 19:03:56 +0000 | [diff] [blame] | 3444 | } |
| 3445 | } |
| 3446 | ); |
| 3447 | Ok(()) |
| 3448 | } |
| 3449 | |
| 3450 | #[test] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3451 | fn test_func_ptr_with_non_static_lifetime() -> Result<()> { |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 3452 | let ir = ir_from_cc(&with_lifetime_macros( |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3453 | r#" |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 3454 | int (* $a get_ptr_to_func())(float, double); "#, |
| 3455 | ))?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3456 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3457 | assert_rs_matches!( |
| 3458 | rs_api, |
| 3459 | quote! { |
| 3460 | // Error while generating bindings for item 'get_ptr_to_func': |
| 3461 | // Return type is not supported: Function pointers with non-'static lifetimes are not supported: int (*)(float, double) |
| 3462 | } |
| 3463 | ); |
| 3464 | Ok(()) |
| 3465 | } |
| 3466 | |
| 3467 | #[test] |
| 3468 | fn test_func_ptr_where_params_are_raw_ptrs() -> Result<()> { |
| 3469 | let ir = ir_from_cc(r#" const int* (*get_ptr_to_func())(const int*); "#)?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3470 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3471 | assert_rs_matches!( |
| 3472 | rs_api, |
| 3473 | quote! { |
| 3474 | #[inline(always)] |
| 3475 | pub fn get_ptr_to_func() -> Option<extern "C" fn (*const i32) -> *const i32> { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 3476 | unsafe { crate::detail::__rust_thunk___Z15get_ptr_to_funcv() } |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3477 | } |
| 3478 | } |
| 3479 | ); |
| 3480 | assert_rs_matches!( |
| 3481 | rs_api, |
| 3482 | quote! { |
| 3483 | mod detail { |
| 3484 | #[allow(unused_imports)] |
| 3485 | use super::*; |
| 3486 | extern "C" { |
| 3487 | #[link_name = "_Z15get_ptr_to_funcv"] |
| 3488 | pub(crate) fn __rust_thunk___Z15get_ptr_to_funcv() |
| 3489 | -> Option<extern "C" fn(*const i32) -> *const i32>; |
| 3490 | } |
| 3491 | } |
| 3492 | } |
| 3493 | ); |
| 3494 | // Verify that no C++ thunk got generated. |
| 3495 | assert_cc_not_matches!(rs_api_impl, quote! { __rust_thunk___Z15get_ptr_to_funcv }); |
| 3496 | |
| 3497 | // TODO(b/217419782): Add another test where params (and the return |
| 3498 | // type) are references with lifetimes. Something like this: |
| 3499 | // #pragma clang lifetime_elision |
| 3500 | // const int& (*get_ptr_to_func())(const int&, const int&); "#)?; |
| 3501 | // 1) Need to investigate why this fails - seeing raw pointers in Rust |
| 3502 | // seems to indicate that no lifetimes are present at the `importer.cc` |
| 3503 | // level. Maybe lifetime elision doesn't support this scenario? Unclear |
Googler | 53f6594 | 2022-02-23 11:23:30 +0000 | [diff] [blame] | 3504 | // how to explicitly apply [[clang::annotate("lifetimes", "a, b -> a")]] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3505 | // to the _inner_ function. |
| 3506 | // 2) It is important to have 2 reference parameters, so see if the problem |
| 3507 | // of passing `lifetimes` by value would have been caught - see: |
| 3508 | // cl/428079010/depot/rs_bindings_from_cc/ |
| 3509 | // importer.cc?version=s6#823 |
| 3510 | |
| 3511 | // TODO(b/217419782): Decide what to do if the C++ pointer is *not* |
| 3512 | // annotated with a lifetime - emit `unsafe fn(...) -> ...` in that |
| 3513 | // case? |
| 3514 | |
| 3515 | Ok(()) |
| 3516 | } |
| 3517 | |
| 3518 | #[test] |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3519 | fn test_func_ptr_with_custom_abi() -> Result<()> { |
| 3520 | let ir = ir_from_cc(r#" int (*get_ptr_to_func())(float, double) [[clang::vectorcall]]; "#)?; |
| 3521 | |
| 3522 | // Verify that the test input correctly represents what we intend to |
| 3523 | // test - we want [[clang::vectorcall]] to apply to the returned |
| 3524 | // function pointer, but *not* apply to the `get_ptr_to_func` function. |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3525 | assert_ir_matches!( |
| 3526 | ir, |
| 3527 | quote! { |
| 3528 | Func(Func { |
| 3529 | name: "get_ptr_to_func", ... |
| 3530 | return_type: MappedType { |
| 3531 | rs_type: RsType { |
| 3532 | name: Some("Option"), ... |
| 3533 | type_args: [RsType { name: Some("#funcPtr vectorcall"), ... }], ... |
| 3534 | }, |
| 3535 | cc_type: CcType { |
| 3536 | name: Some("*"), ... |
| 3537 | type_args: [CcType { name: Some("#funcValue vectorcall"), ... }], ... |
| 3538 | }, |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 3539 | }, ... |
| 3540 | has_c_calling_convention: true, ... |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3541 | }), |
| 3542 | } |
| 3543 | ); |
| 3544 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3545 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3546 | // Check that the custom "vectorcall" ABI gets propagated into the |
| 3547 | // return type (i.e. into `extern "vectorcall" fn`). |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3548 | assert_rs_matches!( |
| 3549 | rs_api, |
| 3550 | quote! { |
| 3551 | #[inline(always)] |
| 3552 | pub fn get_ptr_to_func() -> Option<extern "vectorcall" fn (f32, f64) -> i32> { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 3553 | unsafe { crate::detail::__rust_thunk___Z15get_ptr_to_funcv() } |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3554 | } |
| 3555 | } |
| 3556 | ); |
| 3557 | |
| 3558 | // The usual `extern "C"` ABI should be used for "get_ptr_to_func". |
| 3559 | assert_rs_matches!( |
| 3560 | rs_api, |
| 3561 | quote! { |
| 3562 | mod detail { |
| 3563 | #[allow(unused_imports)] |
| 3564 | use super::*; |
| 3565 | extern "C" { |
| 3566 | #[link_name = "_Z15get_ptr_to_funcv"] |
| 3567 | pub(crate) fn __rust_thunk___Z15get_ptr_to_funcv() |
| 3568 | -> Option<extern "vectorcall" fn(f32, f64) -> i32>; |
| 3569 | } |
| 3570 | } |
| 3571 | } |
| 3572 | ); |
| 3573 | |
| 3574 | // Verify that no C++ thunk got generated. |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3575 | assert_cc_not_matches!(rs_api_impl, quote! { __rust_thunk___Z15get_ptr_to_funcv }); |
| 3576 | Ok(()) |
| 3577 | } |
| 3578 | |
| 3579 | #[test] |
| 3580 | fn test_func_ptr_thunk() -> Result<()> { |
| 3581 | // Using an `inline` keyword forces generation of a C++ thunk in |
| 3582 | // `rs_api_impl` (i.e. exercises `format_cc_type` and similar code). |
| 3583 | let ir = ir_from_cc( |
| 3584 | r#" |
| 3585 | int multiply(int x, int y); |
| 3586 | inline int (*inline_get_pointer_to_function())(int, int) { |
| 3587 | return multiply; |
| 3588 | } |
| 3589 | "#, |
| 3590 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3591 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3592 | assert_cc_matches!( |
| 3593 | rs_api_impl, |
| 3594 | quote! { |
Lukasz Anforowicz | 2317154 | 2022-04-11 15:26:17 -0700 | [diff] [blame] | 3595 | extern "C" crubit::type_identity_t<int(int , int)>* |
Lukasz Anforowicz | 71e9b59 | 2022-03-04 19:03:02 +0000 | [diff] [blame] | 3596 | __rust_thunk___Z30inline_get_pointer_to_functionv() { |
| 3597 | return inline_get_pointer_to_function(); |
| 3598 | } |
| 3599 | } |
| 3600 | ); |
| 3601 | Ok(()) |
| 3602 | } |
| 3603 | |
| 3604 | #[test] |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 3605 | fn test_func_ptr_with_custom_abi_thunk() -> Result<()> { |
| 3606 | // Using an `inline` keyword forces generation of a C++ thunk in |
| 3607 | // `rs_api_impl` (i.e. exercises `format_cc_type`, |
| 3608 | // `format_cc_call_conv_as_clang_attribute` and similar code). |
| 3609 | let ir = ir_from_cc( |
| 3610 | r#" |
| 3611 | inline int (*inline_get_ptr_to_func())(float, double) [[clang::vectorcall]]; |
| 3612 | "#, |
| 3613 | )?; |
| 3614 | |
| 3615 | // Verify that the test input correctly represents what we intend to |
| 3616 | // test - we want [[clang::vectorcall]] to apply to the returned |
| 3617 | // function pointer, but *not* apply to the `get_ptr_to_func` function. |
| 3618 | assert_ir_matches!( |
| 3619 | ir, |
| 3620 | quote! { |
| 3621 | Func(Func { |
| 3622 | name: "inline_get_ptr_to_func", ... |
| 3623 | return_type: MappedType { |
| 3624 | rs_type: RsType { |
| 3625 | name: Some("Option"), ... |
| 3626 | type_args: [RsType { name: Some("#funcPtr vectorcall"), ... }], ... |
| 3627 | }, |
| 3628 | cc_type: CcType { |
| 3629 | name: Some("*"), ... |
| 3630 | type_args: [CcType { name: Some("#funcValue vectorcall"), ... }], ... |
| 3631 | }, |
| 3632 | }, ... |
| 3633 | has_c_calling_convention: true, ... |
| 3634 | }), |
| 3635 | } |
| 3636 | ); |
| 3637 | |
| 3638 | // This test is quite similar to `test_func_ptr_thunk` - the main |
| 3639 | // difference is verification of the `__attribute__((vectorcall))` in |
| 3640 | // the expected signature of the generated thunk below. |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3641 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 3642 | assert_cc_matches!( |
| 3643 | rs_api_impl, |
| 3644 | quote! { |
Lukasz Anforowicz | 2317154 | 2022-04-11 15:26:17 -0700 | [diff] [blame] | 3645 | extern "C" crubit::type_identity_t< |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 3646 | int(float , double) __attribute__((vectorcall)) |
| 3647 | >* __rust_thunk___Z22inline_get_ptr_to_funcv() { |
| 3648 | return inline_get_ptr_to_func(); |
| 3649 | } |
| 3650 | } |
| 3651 | ); |
| 3652 | Ok(()) |
| 3653 | } |
| 3654 | |
| 3655 | #[test] |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 3656 | fn test_item_order() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3657 | let ir = ir_from_cc( |
| 3658 | "int first_func(); |
| 3659 | struct FirstStruct {}; |
| 3660 | int second_func(); |
| 3661 | struct SecondStruct {};", |
| 3662 | )?; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 3663 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3664 | let rs_api = rs_tokens_to_formatted_string_for_tests(generate_bindings_tokens(ir)?.rs_api)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3665 | |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 3666 | let idx = |s: &str| rs_api.find(s).ok_or_else(|| anyhow!("'{}' missing", s)); |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 3667 | |
| 3668 | let f1 = idx("fn first_func")?; |
| 3669 | let f2 = idx("fn second_func")?; |
| 3670 | let s1 = idx("struct FirstStruct")?; |
| 3671 | let s2 = idx("struct SecondStruct")?; |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 3672 | let t1 = idx("fn __rust_thunk___Z10first_funcv")?; |
| 3673 | let t2 = idx("fn __rust_thunk___Z11second_funcv")?; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 3674 | |
| 3675 | assert!(f1 < s1); |
| 3676 | assert!(s1 < f2); |
| 3677 | assert!(f2 < s2); |
| 3678 | assert!(s2 < t1); |
| 3679 | assert!(t1 < t2); |
| 3680 | |
| 3681 | Ok(()) |
| 3682 | } |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 3683 | |
| 3684 | #[test] |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3685 | fn test_base_class_subobject_layout() -> Result<()> { |
| 3686 | let ir = ir_from_cc( |
| 3687 | r#" |
| 3688 | // We use a class here to force `Derived::z` to live inside the tail padding of `Base`. |
| 3689 | // On the Itanium ABI, this would not happen if `Base` were a POD type. |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 3690 | class Base {__INT64_TYPE__ x; char y;}; |
| 3691 | struct Derived final : Base {__INT16_TYPE__ z;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3692 | "#, |
| 3693 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3694 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3695 | assert_rs_matches!( |
| 3696 | rs_api, |
| 3697 | quote! { |
| 3698 | #[repr(C, align(8))] |
| 3699 | pub struct Derived { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3700 | __non_field_data: [::std::mem::MaybeUninit<u8>; 10], |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3701 | pub z: i16, |
| 3702 | } |
| 3703 | } |
| 3704 | ); |
| 3705 | Ok(()) |
| 3706 | } |
| 3707 | |
| 3708 | /// The same as test_base_class_subobject_layout, but with multiple |
| 3709 | /// inheritance. |
| 3710 | #[test] |
| 3711 | fn test_base_class_multiple_inheritance_subobject_layout() -> Result<()> { |
| 3712 | let ir = ir_from_cc( |
| 3713 | r#" |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 3714 | class Base1 {__INT64_TYPE__ x;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3715 | class Base2 {char y;}; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 3716 | struct Derived final : Base1, Base2 {__INT16_TYPE__ z;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3717 | "#, |
| 3718 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3719 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3720 | assert_rs_matches!( |
| 3721 | rs_api, |
| 3722 | quote! { |
| 3723 | #[repr(C, align(8))] |
| 3724 | pub struct Derived { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3725 | __non_field_data: [::std::mem::MaybeUninit<u8>; 10], |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3726 | pub z: i16, |
| 3727 | } |
| 3728 | } |
| 3729 | ); |
| 3730 | Ok(()) |
| 3731 | } |
| 3732 | |
| 3733 | /// The same as test_base_class_subobject_layout, but with a chain of |
| 3734 | /// inheritance. |
| 3735 | #[test] |
| 3736 | fn test_base_class_deep_inheritance_subobject_layout() -> Result<()> { |
| 3737 | let ir = ir_from_cc( |
| 3738 | r#" |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 3739 | class Base1 {__INT64_TYPE__ x;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3740 | class Base2 : Base1 {char y;}; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 3741 | struct Derived final : Base2 {__INT16_TYPE__ z;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3742 | "#, |
| 3743 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3744 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3745 | assert_rs_matches!( |
| 3746 | rs_api, |
| 3747 | quote! { |
| 3748 | #[repr(C, align(8))] |
| 3749 | pub struct Derived { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3750 | __non_field_data: [::std::mem::MaybeUninit<u8>; 10], |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3751 | pub z: i16, |
| 3752 | } |
| 3753 | } |
| 3754 | ); |
| 3755 | Ok(()) |
| 3756 | } |
| 3757 | |
| 3758 | /// For derived classes with no data members, we can't use the offset of the |
| 3759 | /// first member to determine the size of the base class subobjects. |
| 3760 | #[test] |
| 3761 | fn test_base_class_subobject_fieldless_layout() -> Result<()> { |
| 3762 | let ir = ir_from_cc( |
| 3763 | r#" |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 3764 | class Base {__INT64_TYPE__ x; char y;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3765 | struct Derived final : Base {}; |
| 3766 | "#, |
| 3767 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3768 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3769 | assert_rs_matches!( |
| 3770 | rs_api, |
| 3771 | quote! { |
| 3772 | #[repr(C, align(8))] |
| 3773 | pub struct Derived { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3774 | __non_field_data: [::std::mem::MaybeUninit<u8>; 16], |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3775 | } |
| 3776 | } |
| 3777 | ); |
| 3778 | Ok(()) |
| 3779 | } |
| 3780 | |
| 3781 | #[test] |
| 3782 | fn test_base_class_subobject_empty_fieldless() -> Result<()> { |
| 3783 | let ir = ir_from_cc( |
| 3784 | r#" |
| 3785 | class Base {}; |
| 3786 | struct Derived final : Base {}; |
| 3787 | "#, |
| 3788 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3789 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3790 | assert_rs_matches!( |
| 3791 | rs_api, |
| 3792 | quote! { |
| 3793 | #[repr(C)] |
| 3794 | pub struct Derived { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3795 | __non_field_data: [::std::mem::MaybeUninit<u8>; 1], |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3796 | } |
| 3797 | } |
| 3798 | ); |
| 3799 | Ok(()) |
| 3800 | } |
| 3801 | |
| 3802 | #[test] |
| 3803 | fn test_base_class_subobject_empty() -> Result<()> { |
| 3804 | let ir = ir_from_cc( |
| 3805 | r#" |
| 3806 | class Base {}; |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 3807 | struct Derived final : Base { |
| 3808 | __INT16_TYPE__ x; |
| 3809 | }; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3810 | "#, |
| 3811 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3812 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3813 | assert_rs_matches!( |
| 3814 | rs_api, |
| 3815 | quote! { |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3816 | pub struct Derived { |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 3817 | // TODO(b/232984274): delete this. |
| 3818 | // Currently, our tests use C++14 instead of C++17. In C++14, `Derived` |
| 3819 | // is not an aggregate, because it has a base class. C++17 removed this |
| 3820 | // restriction, and allows aggregates to have base classes. |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3821 | __non_field_data: [::std::mem::MaybeUninit<u8>; 0], |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 3822 | pub x: i16, |
| 3823 | } |
| 3824 | } |
| 3825 | ); |
| 3826 | Ok(()) |
| 3827 | } |
| 3828 | |
| 3829 | /// Non-aggregate structs can't be directly initialized, because we add |
| 3830 | /// a zero-sized private field to the bindings. |
| 3831 | #[test] |
| 3832 | fn test_non_aggregate_struct_private_field() -> Result<()> { |
| 3833 | let ir = ir_from_cc( |
| 3834 | r#" |
| 3835 | struct NonAggregate { |
| 3836 | NonAggregate() {} |
| 3837 | |
| 3838 | __INT16_TYPE__ x = 0; |
| 3839 | }; |
| 3840 | "#, |
| 3841 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3842 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | a2be2a2 | 2022-05-18 18:59:05 -0700 | [diff] [blame] | 3843 | assert_rs_matches!( |
| 3844 | rs_api, |
| 3845 | quote! { |
| 3846 | pub struct NonAggregate { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3847 | __non_field_data: [::std::mem::MaybeUninit<u8>; 0], |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 3848 | pub x: i16, |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3849 | } |
| 3850 | } |
| 3851 | ); |
| 3852 | Ok(()) |
| 3853 | } |
| 3854 | |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3855 | /// When a field is [[no_unique_address]], it occupies the space up to the |
| 3856 | /// next field. |
| 3857 | #[test] |
| 3858 | fn test_no_unique_address() -> Result<()> { |
| 3859 | let ir = ir_from_cc( |
| 3860 | r#" |
| 3861 | class Field1 {__INT64_TYPE__ x;}; |
| 3862 | class Field2 {char y;}; |
| 3863 | struct Struct final { |
| 3864 | [[no_unique_address]] Field1 field1; |
| 3865 | [[no_unique_address]] Field2 field2; |
| 3866 | __INT16_TYPE__ z; |
| 3867 | }; |
| 3868 | "#, |
| 3869 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3870 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3871 | assert_rs_matches!( |
| 3872 | rs_api, |
| 3873 | quote! { |
| 3874 | #[derive(Clone, Copy)] |
| 3875 | #[repr(C, align(8))] |
| 3876 | pub struct Struct { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3877 | pub(crate) field1: [::std::mem::MaybeUninit<u8>; 8], |
| 3878 | pub(crate) field2: [::std::mem::MaybeUninit<u8>; 2], |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3879 | pub z: i16, |
| 3880 | } |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 3881 | } |
| 3882 | ); |
Devin Jeanpierre | 2745013 | 2022-04-11 13:52:01 -0700 | [diff] [blame] | 3883 | assert_rs_matches!( |
| 3884 | rs_api, |
| 3885 | quote! { |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 3886 | impl Struct { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 3887 | pub fn field1(&self) -> &crate::Field1 { |
| 3888 | unsafe {&* (&self.field1 as *const _ as *const crate::Field1)} |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 3889 | } |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 3890 | pub fn field2(&self) -> &crate::Field2 { |
| 3891 | unsafe {&* (&self.field2 as *const _ as *const crate::Field2)} |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 3892 | } |
| 3893 | } |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3894 | } |
| 3895 | ); |
| 3896 | Ok(()) |
| 3897 | } |
| 3898 | |
| 3899 | /// When a [[no_unique_address]] field is the last one, it occupies the rest |
| 3900 | /// of the object. |
| 3901 | #[test] |
| 3902 | fn test_no_unique_address_last_field() -> Result<()> { |
| 3903 | let ir = ir_from_cc( |
| 3904 | r#" |
| 3905 | class Field1 {__INT64_TYPE__ x;}; |
| 3906 | class Field2 {char y;}; |
| 3907 | struct Struct final { |
| 3908 | [[no_unique_address]] Field1 field1; |
| 3909 | [[no_unique_address]] Field2 field2; |
| 3910 | }; |
| 3911 | "#, |
| 3912 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3913 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3914 | assert_rs_matches!( |
| 3915 | rs_api, |
| 3916 | quote! { |
| 3917 | #[derive(Clone, Copy)] |
| 3918 | #[repr(C, align(8))] |
| 3919 | pub struct Struct { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3920 | pub(crate) field1: [::std::mem::MaybeUninit<u8>; 8], |
| 3921 | pub(crate) field2: [::std::mem::MaybeUninit<u8>; 8], |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3922 | } |
| 3923 | } |
| 3924 | ); |
| 3925 | Ok(()) |
| 3926 | } |
| 3927 | |
| 3928 | #[test] |
| 3929 | fn test_no_unique_address_empty() -> Result<()> { |
| 3930 | let ir = ir_from_cc( |
| 3931 | r#" |
| 3932 | class Field {}; |
| 3933 | struct Struct final { |
| 3934 | [[no_unique_address]] Field field; |
| 3935 | int x; |
| 3936 | }; |
| 3937 | "#, |
| 3938 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3939 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3940 | assert_rs_matches!( |
| 3941 | rs_api, |
| 3942 | quote! { |
| 3943 | #[repr(C, align(4))] |
| 3944 | pub struct Struct { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3945 | pub(crate) field: [::std::mem::MaybeUninit<u8>; 0], |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3946 | pub x: i32, |
| 3947 | } |
| 3948 | } |
| 3949 | ); |
| 3950 | Ok(()) |
| 3951 | } |
| 3952 | |
| 3953 | #[test] |
| 3954 | fn test_base_class_subobject_empty_last_field() -> Result<()> { |
| 3955 | let ir = ir_from_cc( |
| 3956 | r#" |
| 3957 | class Field {}; |
| 3958 | struct Struct final { |
| 3959 | [[no_unique_address]] Field field; |
| 3960 | }; |
| 3961 | "#, |
| 3962 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3963 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3964 | assert_rs_matches!( |
| 3965 | rs_api, |
| 3966 | quote! { |
| 3967 | #[repr(C)] |
| 3968 | pub struct Struct { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 3969 | pub(crate) field: [::std::mem::MaybeUninit<u8>; 1], |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 3970 | } |
| 3971 | } |
| 3972 | ); |
| 3973 | Ok(()) |
| 3974 | } |
| 3975 | |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 3976 | #[test] |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 3977 | fn test_generate_enum_basic() -> Result<()> { |
| 3978 | let ir = ir_from_cc("enum Color { kRed = 5, kBlue };")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 3979 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 3980 | assert_rs_matches!( |
| 3981 | rs_api, |
| 3982 | quote! { |
| 3983 | #[repr(transparent)] |
| 3984 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 3985 | pub struct Color(u32); |
| 3986 | impl Color { |
| 3987 | pub const kRed: Color = Color(5); |
| 3988 | pub const kBlue: Color = Color(6); |
| 3989 | } |
| 3990 | impl From<u32> for Color { |
| 3991 | fn from(value: u32) -> Color { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 3992 | Color(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 3993 | } |
| 3994 | } |
| 3995 | impl From<Color> for u32 { |
| 3996 | fn from(value: Color) -> u32 { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 3997 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 3998 | } |
| 3999 | } |
| 4000 | } |
| 4001 | ); |
| 4002 | Ok(()) |
| 4003 | } |
| 4004 | |
| 4005 | #[test] |
| 4006 | fn test_generate_scoped_enum_basic() -> Result<()> { |
| 4007 | let ir = ir_from_cc("enum class Color { kRed = -5, kBlue };")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4008 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4009 | assert_rs_matches!( |
| 4010 | rs_api, |
| 4011 | quote! { |
| 4012 | #[repr(transparent)] |
| 4013 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 4014 | pub struct Color(i32); |
| 4015 | impl Color { |
| 4016 | pub const kRed: Color = Color(-5); |
| 4017 | pub const kBlue: Color = Color(-4); |
| 4018 | } |
| 4019 | impl From<i32> for Color { |
| 4020 | fn from(value: i32) -> Color { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4021 | Color(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4022 | } |
| 4023 | } |
| 4024 | impl From<Color> for i32 { |
| 4025 | fn from(value: Color) -> i32 { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4026 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4027 | } |
| 4028 | } |
| 4029 | } |
| 4030 | ); |
| 4031 | Ok(()) |
| 4032 | } |
| 4033 | |
| 4034 | #[test] |
| 4035 | fn test_generate_enum_with_64_bit_signed_vals() -> Result<()> { |
| 4036 | let ir = ir_from_cc( |
| 4037 | "enum Color : long { kViolet = -9223372036854775807 - 1LL, kRed = -5, kBlue, kGreen = 3, kMagenta = 9223372036854775807 };", |
| 4038 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4039 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4040 | assert_rs_matches!( |
| 4041 | rs_api, |
| 4042 | quote! { |
| 4043 | #[repr(transparent)] |
| 4044 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 4045 | pub struct Color(i64); |
| 4046 | impl Color { |
| 4047 | pub const kViolet: Color = Color(-9223372036854775808); |
| 4048 | pub const kRed: Color = Color(-5); |
| 4049 | pub const kBlue: Color = Color(-4); |
| 4050 | pub const kGreen: Color = Color(3); |
| 4051 | pub const kMagenta: Color = Color(9223372036854775807); |
| 4052 | } |
| 4053 | impl From<i64> for Color { |
| 4054 | fn from(value: i64) -> Color { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4055 | Color(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4056 | } |
| 4057 | } |
| 4058 | impl From<Color> for i64 { |
| 4059 | fn from(value: Color) -> i64 { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4060 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4061 | } |
| 4062 | } |
| 4063 | } |
| 4064 | ); |
| 4065 | Ok(()) |
| 4066 | } |
| 4067 | |
| 4068 | #[test] |
| 4069 | fn test_generate_enum_with_64_bit_unsigned_vals() -> Result<()> { |
| 4070 | let ir = ir_from_cc( |
| 4071 | "enum Color: unsigned long { kRed, kBlue, kLimeGreen = 18446744073709551615 };", |
| 4072 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4073 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4074 | assert_rs_matches!( |
| 4075 | rs_api, |
| 4076 | quote! { |
| 4077 | #[repr(transparent)] |
| 4078 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 4079 | pub struct Color(u64); |
| 4080 | impl Color { |
| 4081 | pub const kRed: Color = Color(0); |
| 4082 | pub const kBlue: Color = Color(1); |
| 4083 | pub const kLimeGreen: Color = Color(18446744073709551615); |
| 4084 | } |
| 4085 | impl From<u64> for Color { |
| 4086 | fn from(value: u64) -> Color { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4087 | Color(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4088 | } |
| 4089 | } |
| 4090 | impl From<Color> for u64 { |
| 4091 | fn from(value: Color) -> u64 { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4092 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4093 | } |
| 4094 | } |
| 4095 | } |
| 4096 | ); |
| 4097 | Ok(()) |
| 4098 | } |
| 4099 | |
| 4100 | #[test] |
| 4101 | fn test_generate_enum_with_32_bit_signed_vals() -> Result<()> { |
| 4102 | let ir = ir_from_cc( |
| 4103 | "enum Color { kViolet = -2147483647 - 1, kRed = -5, kBlue, kGreen = 3, kMagenta = 2147483647 };", |
| 4104 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4105 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4106 | assert_rs_matches!( |
| 4107 | rs_api, |
| 4108 | quote! { |
| 4109 | #[repr(transparent)] |
| 4110 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 4111 | pub struct Color(i32); |
| 4112 | impl Color { |
| 4113 | pub const kViolet: Color = Color(-2147483648); |
| 4114 | pub const kRed: Color = Color(-5); |
| 4115 | pub const kBlue: Color = Color(-4); |
| 4116 | pub const kGreen: Color = Color(3); |
| 4117 | pub const kMagenta: Color = Color(2147483647); |
| 4118 | } |
| 4119 | impl From<i32> for Color { |
| 4120 | fn from(value: i32) -> Color { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4121 | Color(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4122 | } |
| 4123 | } |
| 4124 | impl From<Color> for i32 { |
| 4125 | fn from(value: Color) -> i32 { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4126 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4127 | } |
| 4128 | } |
| 4129 | } |
| 4130 | ); |
| 4131 | Ok(()) |
| 4132 | } |
| 4133 | |
| 4134 | #[test] |
| 4135 | fn test_generate_enum_with_32_bit_unsigned_vals() -> Result<()> { |
| 4136 | let ir = ir_from_cc("enum Color: unsigned int { kRed, kBlue, kLimeGreen = 4294967295 };")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4137 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4138 | assert_rs_matches!( |
| 4139 | rs_api, |
| 4140 | quote! { |
| 4141 | #[repr(transparent)] |
| 4142 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 4143 | pub struct Color(u32); |
| 4144 | impl Color { |
| 4145 | pub const kRed: Color = Color(0); |
| 4146 | pub const kBlue: Color = Color(1); |
| 4147 | pub const kLimeGreen: Color = Color(4294967295); |
| 4148 | } |
| 4149 | impl From<u32> for Color { |
| 4150 | fn from(value: u32) -> Color { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4151 | Color(value) |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4152 | } |
| 4153 | } |
| 4154 | impl From<Color> for u32 { |
| 4155 | fn from(value: Color) -> u32 { |
Marcel Hlopko | 872b41a | 2022-05-10 01:49:33 -0700 | [diff] [blame] | 4156 | value.0 |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 4157 | } |
| 4158 | } |
| 4159 | } |
| 4160 | ); |
| 4161 | Ok(()) |
| 4162 | } |
| 4163 | |
| 4164 | #[test] |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 4165 | fn test_doc_comment_func() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4166 | let ir = ir_from_cc( |
| 4167 | " |
| 4168 | // Doc Comment |
| 4169 | // with two lines |
| 4170 | int func();", |
| 4171 | )?; |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 4172 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4173 | assert_rs_matches!( |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4174 | generate_bindings_tokens(ir)?.rs_api, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4175 | // leading space is intentional so there is a space between /// and the text of the |
| 4176 | // comment |
| 4177 | quote! { |
| 4178 | #[doc = " Doc Comment\n with two lines"] |
| 4179 | #[inline(always)] |
| 4180 | pub fn func |
| 4181 | } |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 4182 | ); |
| 4183 | |
| 4184 | Ok(()) |
| 4185 | } |
| 4186 | |
| 4187 | #[test] |
| 4188 | fn test_doc_comment_record() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4189 | let ir = ir_from_cc( |
| 4190 | "// Doc Comment\n\ |
| 4191 | //\n\ |
| 4192 | // * with bullet\n\ |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 4193 | struct SomeStruct final {\n\ |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4194 | // Field doc\n\ |
| 4195 | int field;\ |
| 4196 | };", |
| 4197 | )?; |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 4198 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4199 | assert_rs_matches!( |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4200 | generate_bindings_tokens(ir)?.rs_api, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4201 | quote! { |
| 4202 | #[doc = " Doc Comment\n \n * with bullet"] |
| 4203 | #[derive(Clone, Copy)] |
| 4204 | #[repr(C)] |
| 4205 | pub struct SomeStruct { |
| 4206 | # [doc = " Field doc"] |
| 4207 | pub field: i32, |
| 4208 | } |
| 4209 | } |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 4210 | ); |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 4211 | Ok(()) |
| 4212 | } |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4213 | |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 4214 | #[test] |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4215 | fn test_basic_union() -> Result<()> { |
| 4216 | let ir = ir_from_cc( |
| 4217 | r#" |
| 4218 | union SomeUnion { |
| 4219 | int some_field; |
| 4220 | long long some_bigger_field; |
| 4221 | }; |
| 4222 | "#, |
| 4223 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4224 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4225 | |
| 4226 | assert_rs_matches!( |
| 4227 | rs_api, |
| 4228 | quote! { |
| 4229 | #[derive(Clone, Copy)] |
| 4230 | #[repr(C)] |
| 4231 | pub union SomeUnion { |
| 4232 | pub some_field: i32, |
| 4233 | pub some_bigger_field: i64, |
| 4234 | } |
| 4235 | } |
| 4236 | ); |
Marcel Hlopko | 4c29c6f | 2022-05-04 00:49:14 -0700 | [diff] [blame] | 4237 | assert_cc_matches!( |
| 4238 | rs_api_impl, |
| 4239 | quote! { |
| 4240 | extern "C" void __rust_thunk___ZN9SomeUnionC1Ev(union SomeUnion*__this) {...} |
| 4241 | } |
| 4242 | ); |
| 4243 | assert_cc_matches!( |
| 4244 | rs_api_impl, |
| 4245 | quote! { |
| 4246 | extern "C" void __rust_thunk___ZN9SomeUnionD1Ev(union SomeUnion*__this) {...} |
| 4247 | } |
| 4248 | ); |
| 4249 | assert_cc_matches!( |
| 4250 | rs_api_impl, |
| 4251 | quote! { |
| 4252 | extern "C" union SomeUnion&__rust_thunk___ZN9SomeUnionaSERKS_( |
| 4253 | union SomeUnion*__this, const union SomeUnion&__param_0) { ... } |
| 4254 | } |
| 4255 | ); |
| 4256 | assert_cc_matches!(rs_api_impl, quote! { static_assert(sizeof(union SomeUnion)==8) }); |
| 4257 | assert_cc_matches!(rs_api_impl, quote! { static_assert(alignof(union SomeUnion)==8) }); |
| 4258 | assert_cc_matches!( |
| 4259 | rs_api_impl, |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 4260 | quote! { static_assert(CRUBIT_OFFSET_OF(some_field, union SomeUnion)==0) } |
Marcel Hlopko | 4c29c6f | 2022-05-04 00:49:14 -0700 | [diff] [blame] | 4261 | ); |
| 4262 | assert_cc_matches!( |
| 4263 | rs_api_impl, |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 4264 | quote! { static_assert(CRUBIT_OFFSET_OF(some_bigger_field, union SomeUnion)==0) } |
Marcel Hlopko | 4c29c6f | 2022-05-04 00:49:14 -0700 | [diff] [blame] | 4265 | ); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4266 | Ok(()) |
| 4267 | } |
| 4268 | |
| 4269 | #[test] |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 4270 | fn test_union_with_opaque_field() -> Result<()> { |
| 4271 | let ir = ir_from_cc( |
| 4272 | r#" |
| 4273 | union MyUnion { |
| 4274 | char first_field[56]; |
| 4275 | int second_field; |
| 4276 | }; |
| 4277 | "#, |
| 4278 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4279 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 4280 | |
| 4281 | assert_rs_matches!( |
| 4282 | rs_api, |
| 4283 | quote! { |
| 4284 | #[repr(C, align(4))] |
| 4285 | pub union MyUnion { ... |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4286 | first_field: [::std::mem::MaybeUninit<u8>; 56], |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 4287 | pub second_field: i32, |
| 4288 | } |
| 4289 | } |
| 4290 | ); |
| 4291 | |
| 4292 | assert_rs_matches!( |
| 4293 | rs_api, |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4294 | quote! { const _: () = assert!(::std::mem::size_of::<crate::MyUnion>() == 56); } |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 4295 | ); |
| 4296 | assert_rs_matches!( |
| 4297 | rs_api, |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4298 | quote! { const _: () = assert!(::std::mem::align_of::<crate::MyUnion>() == 4); } |
Marcel Hlopko | f05621b | 2022-05-25 00:26:06 -0700 | [diff] [blame] | 4299 | ); |
| 4300 | Ok(()) |
| 4301 | } |
| 4302 | |
| 4303 | #[test] |
Marcel Hlopko | fa9a395 | 2022-05-10 01:34:13 -0700 | [diff] [blame] | 4304 | // TODO(https://github.com/Gilnaa/memoffset/issues/66): generate assertions for unions once |
| 4305 | // offsetof supports them. |
| 4306 | fn test_currently_no_offset_assertions_for_unions() -> Result<()> { |
| 4307 | let ir = ir_from_cc( |
| 4308 | r#" |
| 4309 | union SomeUnion { |
| 4310 | int some_field; |
| 4311 | long long some_bigger_field; |
| 4312 | }; |
| 4313 | "#, |
| 4314 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4315 | let BindingsTokens { rs_api, .. } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | fa9a395 | 2022-05-10 01:34:13 -0700 | [diff] [blame] | 4316 | |
| 4317 | assert_rs_not_matches!(rs_api, quote! { offset_of! }); |
| 4318 | Ok(()) |
| 4319 | } |
| 4320 | |
| 4321 | #[test] |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4322 | fn test_union_with_private_fields() -> Result<()> { |
| 4323 | let ir = ir_from_cc( |
| 4324 | r#" |
| 4325 | union SomeUnionWithPrivateFields { |
| 4326 | public: |
| 4327 | int public_field; |
| 4328 | private: |
| 4329 | long long private_field; |
| 4330 | }; |
| 4331 | "#, |
| 4332 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4333 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4334 | |
| 4335 | assert_rs_matches!( |
| 4336 | rs_api, |
| 4337 | quote! { |
| 4338 | #[derive(Clone, Copy)] |
Lukasz Anforowicz | df8fcae | 2022-06-02 14:54:43 -0700 | [diff] [blame] | 4339 | #[repr(C, align(8))] |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4340 | pub union SomeUnionWithPrivateFields { |
| 4341 | pub public_field: i32, |
Lukasz Anforowicz | df8fcae | 2022-06-02 14:54:43 -0700 | [diff] [blame] | 4342 | #[doc = " Reason for representing this field as a blob of bytes:\n Types of non-public C++ fields can be elided away"] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4343 | pub(crate) private_field: [::std::mem::MaybeUninit<u8>; 8], |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4344 | } |
| 4345 | } |
| 4346 | ); |
| 4347 | |
| 4348 | assert_rs_matches!( |
| 4349 | rs_api, |
| 4350 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4351 | const _: () = assert!(::std::mem::size_of::<crate::SomeUnionWithPrivateFields>() == 8); |
| 4352 | const _: () = assert!(::std::mem::align_of::<crate::SomeUnionWithPrivateFields>() == 8); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4353 | const _: () = { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4354 | static_assertions::assert_impl_all!(crate::SomeUnionWithPrivateFields: Clone); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4355 | }; |
| 4356 | const _: () = { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4357 | static_assertions::assert_impl_all!(crate::SomeUnionWithPrivateFields: Copy); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4358 | }; |
| 4359 | const _: () = { |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 4360 | static_assertions::assert_not_impl_any!(crate::SomeUnionWithPrivateFields: Drop); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4361 | }; |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4362 | } |
| 4363 | ); |
| 4364 | Ok(()) |
| 4365 | } |
| 4366 | |
| 4367 | #[test] |
Marcel Hlopko | 4546573 | 2022-05-24 00:51:04 -0700 | [diff] [blame] | 4368 | fn test_nontrivial_unions() -> Result<()> { |
| 4369 | let ir = ir_from_cc_dependency( |
| 4370 | r#" |
| 4371 | union UnionWithNontrivialField { |
| 4372 | NonTrivialStruct my_field; |
| 4373 | }; |
| 4374 | "#, |
| 4375 | r#" |
| 4376 | struct NonTrivialStruct { |
| 4377 | NonTrivialStruct(NonTrivialStruct&&); |
| 4378 | }; |
| 4379 | "#, |
| 4380 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4381 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Marcel Hlopko | 4546573 | 2022-05-24 00:51:04 -0700 | [diff] [blame] | 4382 | |
| 4383 | assert_rs_not_matches!(rs_api, quote! {derive ( ... Copy ... )}); |
| 4384 | assert_rs_not_matches!(rs_api, quote! {derive ( ... Clone ... )}); |
Devin Jeanpierre | 190b90a | 2022-05-24 06:00:34 -0700 | [diff] [blame] | 4385 | assert_rs_matches!( |
| 4386 | rs_api, |
| 4387 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4388 | #[::ctor::recursively_pinned] |
Devin Jeanpierre | 190b90a | 2022-05-24 06:00:34 -0700 | [diff] [blame] | 4389 | #[repr(C)] |
| 4390 | pub union UnionWithNontrivialField { ... } |
| 4391 | } |
| 4392 | ); |
Marcel Hlopko | 4546573 | 2022-05-24 00:51:04 -0700 | [diff] [blame] | 4393 | Ok(()) |
| 4394 | } |
| 4395 | |
| 4396 | #[test] |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 4397 | fn test_empty_struct() -> Result<()> { |
| 4398 | let ir = ir_from_cc( |
| 4399 | r#" |
| 4400 | struct EmptyStruct final {}; |
| 4401 | "#, |
| 4402 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4403 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 4404 | |
| 4405 | assert_rs_matches!( |
| 4406 | rs_api, |
| 4407 | quote! { |
| 4408 | #[derive(Clone, Copy)] |
| 4409 | #[repr(C)] |
| 4410 | pub struct EmptyStruct { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4411 | __non_field_data: [::std::mem::MaybeUninit<u8>; 1], |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 4412 | } |
| 4413 | } |
| 4414 | ); |
| 4415 | |
| 4416 | assert_rs_matches!( |
| 4417 | rs_api, |
| 4418 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4419 | const _: () = assert!(::std::mem::size_of::<crate::EmptyStruct>() == 1); |
| 4420 | const _: () = assert!(::std::mem::align_of::<crate::EmptyStruct>() == 1); |
Devin Jeanpierre | 1221c2a | 2022-05-05 22:36:22 -0700 | [diff] [blame] | 4421 | } |
| 4422 | ); |
| 4423 | |
| 4424 | Ok(()) |
| 4425 | } |
| 4426 | |
| 4427 | #[test] |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4428 | fn test_empty_union() -> Result<()> { |
| 4429 | let ir = ir_from_cc( |
| 4430 | r#" |
| 4431 | union EmptyUnion {}; |
| 4432 | "#, |
| 4433 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4434 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4435 | |
| 4436 | assert_rs_matches!( |
| 4437 | rs_api, |
| 4438 | quote! { |
| 4439 | #[derive(Clone, Copy)] |
| 4440 | #[repr(C)] |
| 4441 | pub union EmptyUnion { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4442 | __non_field_data: [::std::mem::MaybeUninit<u8>; 1], |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4443 | } |
| 4444 | } |
| 4445 | ); |
| 4446 | |
| 4447 | assert_rs_matches!( |
| 4448 | rs_api, |
| 4449 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4450 | const _: () = assert!(::std::mem::size_of::<crate::EmptyUnion>() == 1); |
| 4451 | const _: () = assert!(::std::mem::align_of::<crate::EmptyUnion>() == 1); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4452 | } |
| 4453 | ); |
| 4454 | |
| 4455 | Ok(()) |
| 4456 | } |
| 4457 | |
| 4458 | #[test] |
| 4459 | fn test_union_field_with_nontrivial_destructor() -> Result<()> { |
| 4460 | let ir = ir_from_cc( |
| 4461 | r#" |
| 4462 | struct NontrivialStruct { ~NontrivialStruct(); }; |
| 4463 | union UnionWithNontrivialField { |
| 4464 | int trivial_field; |
| 4465 | NontrivialStruct nontrivial_field; |
| 4466 | }; |
| 4467 | "#, |
| 4468 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4469 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4470 | |
| 4471 | assert_rs_matches!( |
| 4472 | rs_api, |
| 4473 | quote! { |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4474 | #[repr(C)] |
| 4475 | pub union UnionWithNontrivialField { |
| 4476 | pub trivial_field: i32, |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4477 | pub nontrivial_field: ::std::mem::ManuallyDrop<crate::NontrivialStruct>, |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4478 | } |
| 4479 | } |
| 4480 | ); |
| 4481 | |
| 4482 | assert_rs_matches!( |
| 4483 | rs_api, |
| 4484 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4485 | const _: () = assert!(::std::mem::size_of::<crate::UnionWithNontrivialField>() == 4); |
| 4486 | const _: () = assert!(::std::mem::align_of::<crate::UnionWithNontrivialField>() == 4); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4487 | } |
| 4488 | ); |
| 4489 | Ok(()) |
| 4490 | } |
| 4491 | |
| 4492 | #[test] |
| 4493 | fn test_union_with_constructors() -> Result<()> { |
| 4494 | let ir = ir_from_cc( |
| 4495 | r#" |
| 4496 | #pragma clang lifetime_elision |
| 4497 | union UnionWithDefaultConstructors { |
| 4498 | int a; |
| 4499 | }; |
| 4500 | "#, |
| 4501 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4502 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4503 | |
| 4504 | assert_rs_matches!( |
| 4505 | rs_api, |
| 4506 | quote! { |
| 4507 | #[derive(Clone, Copy)] |
| 4508 | #[repr(C)] |
| 4509 | pub union UnionWithDefaultConstructors { |
| 4510 | pub a: i32, |
| 4511 | } |
| 4512 | } |
| 4513 | ); |
| 4514 | |
| 4515 | assert_rs_matches!( |
| 4516 | rs_api, |
| 4517 | quote! { |
| 4518 | impl Default for UnionWithDefaultConstructors { |
| 4519 | #[inline(always)] |
| 4520 | fn default() -> Self { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4521 | let mut tmp = ::std::mem::MaybeUninit::<Self>::zeroed(); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4522 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4523 | crate::detail::__rust_thunk___ZN28UnionWithDefaultConstructorsC1Ev(&mut tmp); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4524 | tmp.assume_init() |
| 4525 | } |
| 4526 | } |
| 4527 | } |
| 4528 | } |
| 4529 | ); |
| 4530 | |
| 4531 | assert_rs_matches!( |
| 4532 | rs_api, |
| 4533 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4534 | impl<'b> From<::ctor::RvalueReference<'b, crate::UnionWithDefaultConstructors>> for UnionWithDefaultConstructors { |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4535 | #[inline(always)] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4536 | fn from(__param_0: ::ctor::RvalueReference<'b, crate::UnionWithDefaultConstructors>) -> Self { |
| 4537 | let mut tmp = ::std::mem::MaybeUninit::<Self>::zeroed(); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4538 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4539 | crate::detail::__rust_thunk___ZN28UnionWithDefaultConstructorsC1EOS_(&mut tmp, __param_0); |
Teddy Katz | d2cd142 | 2022-04-04 09:41:33 -0700 | [diff] [blame] | 4540 | tmp.assume_init() |
| 4541 | } |
| 4542 | } |
| 4543 | } |
| 4544 | } |
| 4545 | ); |
| 4546 | |
| 4547 | Ok(()) |
| 4548 | } |
| 4549 | |
| 4550 | #[test] |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 4551 | fn test_unambiguous_public_bases() -> Result<()> { |
| 4552 | let ir = ir_from_cc_dependency( |
| 4553 | " |
| 4554 | struct VirtualBase {}; |
| 4555 | struct PrivateBase {}; |
| 4556 | struct ProtectedBase {}; |
| 4557 | struct UnambiguousPublicBase {}; |
| 4558 | struct AmbiguousPublicBase {}; |
| 4559 | struct MultipleInheritance : UnambiguousPublicBase, AmbiguousPublicBase {}; |
| 4560 | struct Derived : private PrivateBase, protected ProtectedBase, MultipleInheritance, AmbiguousPublicBase, virtual VirtualBase {}; |
| 4561 | ", |
| 4562 | "", |
| 4563 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4564 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 4565 | assert_rs_matches!( |
| 4566 | rs_api, |
| 4567 | quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4568 | unsafe impl oops::Inherits<crate::VirtualBase> for Derived { |
| 4569 | unsafe fn upcast_ptr(derived: *const Self) -> *const crate::VirtualBase { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4570 | crate::detail::__crubit_dynamic_upcast__Derived__to__VirtualBase(derived) |
Devin Jeanpierre | f99db3e | 2022-04-27 23:10:33 -0700 | [diff] [blame] | 4571 | } |
| 4572 | } |
| 4573 | } |
| 4574 | ); |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 4575 | assert_rs_matches!( |
| 4576 | rs_api, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4577 | quote! { unsafe impl oops::Inherits<crate::UnambiguousPublicBase> for Derived } |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 4578 | ); |
| 4579 | assert_rs_matches!( |
| 4580 | rs_api, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4581 | quote! { unsafe impl oops::Inherits<crate::MultipleInheritance> for Derived } |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 4582 | ); |
| 4583 | assert_rs_not_matches!( |
| 4584 | rs_api, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4585 | quote! {unsafe impl oops::Inherits<crate::PrivateBase> for Derived} |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 4586 | ); |
| 4587 | assert_rs_not_matches!( |
| 4588 | rs_api, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4589 | quote! {unsafe impl oops::Inherits<crate::ProtectedBase> for Derived} |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 4590 | ); |
| 4591 | assert_rs_not_matches!( |
| 4592 | rs_api, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4593 | quote! {unsafe impl oops::Inherits<crate::AmbiguousPublicBase> for Derived} |
Devin Jeanpierre | b368e68 | 2022-05-03 02:23:44 -0700 | [diff] [blame] | 4594 | ); |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 4595 | Ok(()) |
| 4596 | } |
| 4597 | |
| 4598 | /// Contrary to intuitions: a base class conversion is ambiguous even if the |
| 4599 | /// ambiguity is from a private base class cast that you can't even |
| 4600 | /// perform. |
| 4601 | /// |
| 4602 | /// Explanation (courtesy James Dennett): |
| 4603 | /// |
| 4604 | /// > Once upon a time, there was a rule in C++ that changing all access |
| 4605 | /// > specifiers to "public" would not change the meaning of code. |
| 4606 | /// > That's no longer true, but some of its effects can still be seen. |
| 4607 | /// |
| 4608 | /// So, we need to be sure to not allow casting to privately-ambiguous |
| 4609 | /// bases. |
| 4610 | #[test] |
| 4611 | fn test_unambiguous_public_bases_private_ambiguity() -> Result<()> { |
| 4612 | let ir = ir_from_cc_dependency( |
| 4613 | " |
| 4614 | struct Base {}; |
| 4615 | struct Intermediate : public Base {}; |
| 4616 | struct Derived : Base, private Intermediate {}; |
| 4617 | ", |
| 4618 | "", |
| 4619 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4620 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4621 | assert_rs_not_matches!( |
| 4622 | rs_api, |
| 4623 | quote! { unsafe impl oops::Inherits<crate::Base> for Derived } |
| 4624 | ); |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 4625 | Ok(()) |
| 4626 | } |
| 4627 | |
| 4628 | #[test] |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 4629 | fn test_virtual_thunk() -> Result<()> { |
| 4630 | let ir = ir_from_cc("struct Polymorphic { virtual void Foo(); };")?; |
| 4631 | |
| 4632 | assert_cc_matches!( |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4633 | generate_bindings_tokens(ir)?.rs_api_impl, |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 4634 | quote! { |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 4635 | extern "C" void __rust_thunk___ZN11Polymorphic3FooEv(struct Polymorphic * __this) |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 4636 | } |
| 4637 | ); |
| 4638 | Ok(()) |
| 4639 | } |
| 4640 | |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 4641 | #[test] |
| 4642 | fn test_custom_abi_thunk() -> Result<()> { |
| 4643 | let ir = ir_from_cc( |
| 4644 | r#" |
| 4645 | float f_vectorcall_calling_convention(float p1, float p2) [[clang::vectorcall]]; |
| 4646 | double f_c_calling_convention(double p1, double p2); |
| 4647 | "#, |
| 4648 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4649 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 4650 | assert_rs_matches!( |
| 4651 | rs_api, |
| 4652 | quote! { |
| 4653 | #[inline(always)] |
| 4654 | pub fn f_vectorcall_calling_convention(p1: f32, p2: f32) -> f32 { |
| 4655 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4656 | crate::detail::__rust_thunk___Z31f_vectorcall_calling_conventionff(p1, p2) |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 4657 | } |
| 4658 | } |
| 4659 | } |
| 4660 | ); |
| 4661 | assert_rs_matches!( |
| 4662 | rs_api, |
| 4663 | quote! { |
| 4664 | #[inline(always)] |
| 4665 | pub fn f_c_calling_convention(p1: f64, p2: f64) -> f64 { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4666 | unsafe { crate::detail::__rust_thunk___Z22f_c_calling_conventiondd(p1, p2) } |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 4667 | } |
| 4668 | } |
| 4669 | ); |
| 4670 | // `link_name` (i.e. no thunk) for `f_c_calling_convention`. No |
| 4671 | // `link_name` (i.e. indicates presence of a thunk) for |
| 4672 | // `f_vectorcall_calling_convention`. |
| 4673 | assert_rs_matches!( |
| 4674 | rs_api, |
| 4675 | quote! { |
| 4676 | mod detail { |
| 4677 | #[allow(unused_imports)] |
| 4678 | use super::*; |
| 4679 | extern "C" { |
| 4680 | pub(crate) fn __rust_thunk___Z31f_vectorcall_calling_conventionff( |
| 4681 | p1: f32, p2: f32) -> f32; |
| 4682 | #[link_name = "_Z22f_c_calling_conventiondd"] |
| 4683 | pub(crate) fn __rust_thunk___Z22f_c_calling_conventiondd( |
| 4684 | p1: f64, p2: f64) -> f64; |
| 4685 | } |
| 4686 | } |
| 4687 | } |
| 4688 | ); |
| 4689 | // C++ thunk needed for `f_vectorcall_calling_convention`. |
| 4690 | assert_cc_matches!( |
| 4691 | rs_api_impl, |
| 4692 | quote! { |
| 4693 | extern "C" float __rust_thunk___Z31f_vectorcall_calling_conventionff( |
| 4694 | float p1, float p2) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 4695 | return f_vectorcall_calling_convention (std::forward<decltype(p1)>(p1), std::forward<decltype(p2)>(p2)); |
Lukasz Anforowicz | 0b6a6ac | 2022-03-22 22:32:23 +0000 | [diff] [blame] | 4696 | } |
| 4697 | } |
| 4698 | ); |
| 4699 | // No C++ thunk expected for `f_c_calling_convention`. |
| 4700 | assert_cc_not_matches!(rs_api_impl, quote! { f_c_calling_convention }); |
| 4701 | Ok(()) |
| 4702 | } |
| 4703 | |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 4704 | /// A trivially relocatable final struct is safe to use in Rust as normal, |
| 4705 | /// and is Unpin. |
| 4706 | #[test] |
| 4707 | fn test_no_negative_impl_unpin() -> Result<()> { |
| 4708 | let ir = ir_from_cc("struct Trivial final {};")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4709 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4710 | assert_rs_not_matches!(rs_api, quote! {#[::ctor::recursively_pinned]}); |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 4711 | Ok(()) |
| 4712 | } |
| 4713 | |
| 4714 | /// A non-final struct, even if it's trivial, is not usable by mut |
| 4715 | /// reference, and so is !Unpin. |
| 4716 | #[test] |
| 4717 | fn test_negative_impl_unpin_nonfinal() -> Result<()> { |
| 4718 | let ir = ir_from_cc("struct Nonfinal {};")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4719 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4720 | assert_rs_matches!(rs_api, quote! {#[::ctor::recursively_pinned]}); |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 4721 | Ok(()) |
| 4722 | } |
| 4723 | |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4724 | /// At the least, a trivial type should have no drop impl if or until we add |
| 4725 | /// empty drop impls. |
| 4726 | #[test] |
| 4727 | fn test_no_impl_drop() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 4728 | let ir = ir_from_cc("struct Trivial {};")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4729 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 4730 | assert_rs_not_matches!(rs_api, quote! {impl Drop}); |
| 4731 | assert_rs_not_matches!(rs_api, quote! {impl ::ctor::PinnedDrop}); |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4732 | Ok(()) |
| 4733 | } |
| 4734 | |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4735 | /// User-defined destructors *must* become Drop impls with ManuallyDrop |
| 4736 | /// fields |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4737 | #[test] |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4738 | fn test_impl_drop_user_defined_destructor() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 4739 | let ir = ir_from_cc( |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 4740 | r#" struct NontrivialStruct { ~NontrivialStruct(); }; |
| 4741 | struct UserDefinedDestructor { |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4742 | ~UserDefinedDestructor(); |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4743 | int x; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 4744 | NontrivialStruct nts; |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4745 | };"#, |
| 4746 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4747 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4748 | assert_rs_matches!( |
| 4749 | rs_api, |
| 4750 | quote! { |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 4751 | impl ::ctor::PinnedDrop for UserDefinedDestructor { |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4752 | #[inline(always)] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4753 | unsafe fn pinned_drop<'a>(self: ::std::pin::Pin<&'a mut Self>) { |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 4754 | crate::detail::__rust_thunk___ZN21UserDefinedDestructorD1Ev(self) |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4755 | } |
| 4756 | } |
| 4757 | } |
| 4758 | ); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 4759 | assert_rs_matches!(rs_api, quote! {pub x: i32,}); |
Rosica Dejanovska | accf00b | 2022-04-01 13:28:04 -0700 | [diff] [blame] | 4760 | assert_rs_matches!( |
| 4761 | rs_api, |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4762 | quote! {pub nts: ::std::mem::ManuallyDrop<crate::NontrivialStruct>,} |
Rosica Dejanovska | accf00b | 2022-04-01 13:28:04 -0700 | [diff] [blame] | 4763 | ); |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4764 | Ok(()) |
| 4765 | } |
| 4766 | |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4767 | /// nontrivial types without user-defined destructors should invoke |
| 4768 | /// the C++ destructor to preserve the order of field destructions. |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4769 | #[test] |
| 4770 | fn test_impl_drop_nontrivial_member_destructor() -> Result<()> { |
| 4771 | // TODO(jeanpierreda): This would be cleaner if the UserDefinedDestructor code were |
| 4772 | // omitted. For example, we simulate it so that UserDefinedDestructor |
| 4773 | // comes from another library. |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 4774 | let ir = ir_from_cc( |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 4775 | r#"struct UserDefinedDestructor final { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4776 | ~UserDefinedDestructor(); |
| 4777 | }; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 4778 | struct TrivialStruct final { int i; }; |
| 4779 | struct NontrivialMembers final { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4780 | UserDefinedDestructor udd; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 4781 | TrivialStruct ts; |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4782 | int x; |
| 4783 | };"#, |
| 4784 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4785 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4786 | assert_rs_matches!( |
| 4787 | rs_api, |
| 4788 | quote! { |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 4789 | impl ::ctor::PinnedDrop for NontrivialMembers { |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4790 | #[inline(always)] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4791 | unsafe fn pinned_drop<'a>(self: ::std::pin::Pin<&'a mut Self>) { |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 4792 | crate::detail::__rust_thunk___ZN17NontrivialMembersD1Ev(self) |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4793 | } |
| 4794 | } |
| 4795 | } |
| 4796 | ); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 4797 | assert_rs_matches!(rs_api, quote! {pub x: i32,}); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4798 | assert_rs_matches!(rs_api, quote! {pub ts: crate::TrivialStruct,}); |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4799 | assert_rs_matches!( |
| 4800 | rs_api, |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4801 | quote! {pub udd: ::std::mem::ManuallyDrop<crate::UserDefinedDestructor>,} |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 4802 | ); |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4803 | Ok(()) |
| 4804 | } |
| 4805 | |
| 4806 | /// Trivial types (at least those that are mapped to Copy rust types) do not |
| 4807 | /// get a Drop impl. |
| 4808 | #[test] |
| 4809 | fn test_impl_drop_trivial() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 4810 | let ir = ir_from_cc( |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 4811 | r#"struct Trivial final { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 4812 | ~Trivial() = default; |
| 4813 | int x; |
| 4814 | };"#, |
| 4815 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4816 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4817 | assert_rs_not_matches!(rs_api, quote! {impl Drop}); |
Devin Jeanpierre | 215ee8e | 2022-05-16 16:09:41 -0700 | [diff] [blame] | 4818 | assert_rs_not_matches!(rs_api, quote! {impl ::ctor::PinnedDrop}); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 4819 | assert_rs_matches!(rs_api, quote! {pub x: i32}); |
Lukasz Anforowicz | 2f07416 | 2022-01-06 22:50:51 +0000 | [diff] [blame] | 4820 | // TODO(b/213326125): Avoid generating thunk impls that are never called. |
| 4821 | // (The test assertion below should be reversed once this bug is fixed.) |
| 4822 | assert_cc_matches!(rs_api_impl, quote! { std::destroy_at }); |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 4823 | Ok(()) |
| 4824 | } |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 4825 | |
| 4826 | #[test] |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4827 | fn test_impl_default_explicitly_defaulted_constructor() -> Result<()> { |
| 4828 | let ir = ir_from_cc( |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 4829 | r#"#pragma clang lifetime_elision |
| 4830 | struct DefaultedConstructor final { |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4831 | DefaultedConstructor() = default; |
| 4832 | };"#, |
| 4833 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4834 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4835 | assert_rs_matches!( |
| 4836 | rs_api, |
| 4837 | quote! { |
| 4838 | impl Default for DefaultedConstructor { |
| 4839 | #[inline(always)] |
| 4840 | fn default() -> Self { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4841 | let mut tmp = ::std::mem::MaybeUninit::<Self>::zeroed(); |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4842 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4843 | crate::detail::__rust_thunk___ZN20DefaultedConstructorC1Ev(&mut tmp); |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4844 | tmp.assume_init() |
| 4845 | } |
| 4846 | } |
| 4847 | } |
| 4848 | } |
| 4849 | ); |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4850 | assert_cc_matches!( |
| 4851 | rs_api_impl, |
| 4852 | quote! { |
| 4853 | extern "C" void __rust_thunk___ZN20DefaultedConstructorC1Ev( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 4854 | struct DefaultedConstructor* __this) { |
Lukasz Anforowicz | 2317154 | 2022-04-11 15:26:17 -0700 | [diff] [blame] | 4855 | crubit::construct_at (std::forward<decltype(__this)>(__this)) ; |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 4856 | } |
| 4857 | } |
| 4858 | ); |
| 4859 | Ok(()) |
| 4860 | } |
| 4861 | |
| 4862 | #[test] |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4863 | fn test_impl_clone_that_propagates_lifetime() -> Result<()> { |
| 4864 | // This test covers the case where a single lifetime applies to 1) |
| 4865 | // the `__this` parameter and 2) other constructor parameters. For |
| 4866 | // example, maybe the newly constructed object needs to have the |
| 4867 | // same lifetime as the constructor's parameter. (This might require |
| 4868 | // annotating the whole C++ struct with a lifetime, so maybe the |
| 4869 | // example below is not fully realistic/accurate...). |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 4870 | let ir = ir_from_cc(&with_lifetime_macros( |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4871 | r#"#pragma clang lifetime_elision |
| 4872 | struct Foo final { |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 4873 | Foo(const int& $a i) $a; |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4874 | };"#, |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 4875 | ))?; |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 4876 | let ctor: &Func = ir |
| 4877 | .items() |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4878 | .filter_map(|item| match item { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 4879 | Item::Func(func) => Some(&**func), |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4880 | _ => None, |
| 4881 | }) |
| 4882 | .find(|f| { |
| 4883 | matches!(&f.name, UnqualifiedIdentifier::Constructor) |
| 4884 | && f.params.get(1).map(|p| p.identifier.identifier == "i").unwrap_or_default() |
| 4885 | }) |
| 4886 | .unwrap(); |
| 4887 | { |
| 4888 | // Double-check that the test scenario set up above uses the same lifetime |
| 4889 | // for both of the constructor's parameters: `__this` and `i`. |
| 4890 | assert_eq!(ctor.params.len(), 2); |
| 4891 | let this_lifetime: LifetimeId = |
| 4892 | *ctor.params[0].type_.rs_type.lifetime_args.first().unwrap(); |
| 4893 | let i_lifetime: LifetimeId = |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 4894 | *ctor.params[1].type_.rs_type.lifetime_args.first().unwrap(); |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4895 | assert_eq!(i_lifetime, this_lifetime); |
| 4896 | } |
| 4897 | |
| 4898 | // Before cl/423346348 the generated Rust code would incorrectly look |
| 4899 | // like this (note the mismatched 'a and 'b lifetimes): |
| 4900 | // fn from<'b>(i: &'a i32) -> Self |
| 4901 | // After this CL, this scenario will result in an explicit error. |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4902 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | d7b4810 | 2022-03-31 04:15:03 -0700 | [diff] [blame] | 4903 | assert_rs_not_matches!(rs_api, quote! {impl From}); |
| 4904 | let rs_api_str = tokens_to_string(rs_api)?; |
| 4905 | assert!(rs_api_str.contains( |
| 4906 | "// The lifetime of `__this` is unexpectedly also used by another parameter" |
| 4907 | )); |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 4908 | Ok(()) |
| 4909 | } |
| 4910 | |
| 4911 | #[test] |
Lukasz Anforowicz | 9bab835 | 2021-12-22 17:35:31 +0000 | [diff] [blame] | 4912 | fn test_impl_default_non_trivial_struct() -> Result<()> { |
| 4913 | let ir = ir_from_cc( |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 4914 | r#"#pragma clang lifetime_elision |
| 4915 | struct NonTrivialStructWithConstructors final { |
Lukasz Anforowicz | 9bab835 | 2021-12-22 17:35:31 +0000 | [diff] [blame] | 4916 | NonTrivialStructWithConstructors(); |
| 4917 | ~NonTrivialStructWithConstructors(); // Non-trivial |
| 4918 | };"#, |
| 4919 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4920 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 9bab835 | 2021-12-22 17:35:31 +0000 | [diff] [blame] | 4921 | assert_rs_not_matches!(rs_api, quote! {impl Default}); |
| 4922 | Ok(()) |
| 4923 | } |
| 4924 | |
| 4925 | #[test] |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 4926 | fn test_impl_from_for_explicit_conversion_constructor() -> Result<()> { |
| 4927 | let ir = ir_from_cc( |
| 4928 | r#"#pragma clang lifetime_elision |
| 4929 | struct SomeStruct final { |
| 4930 | explicit SomeStruct(int i); |
| 4931 | };"#, |
| 4932 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4933 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 4934 | // As discussed in b/214020567 for now we only generate `From::from` bindings |
| 4935 | // for *implicit* C++ conversion constructors. |
| 4936 | assert_rs_not_matches!(rs_api, quote! {impl From}); |
| 4937 | Ok(()) |
| 4938 | } |
| 4939 | |
| 4940 | #[test] |
| 4941 | fn test_impl_from_for_implicit_conversion_constructor() -> Result<()> { |
| 4942 | let ir = ir_from_cc( |
| 4943 | r#"#pragma clang lifetime_elision |
| 4944 | struct SomeStruct final { |
| 4945 | SomeStruct(int i); // implicit - no `explicit` keyword |
| 4946 | };"#, |
| 4947 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4948 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 4949 | // As discussed in b/214020567 we generate `From::from` bindings for |
| 4950 | // *implicit* C++ conversion constructors. |
| 4951 | assert_rs_matches!( |
| 4952 | rs_api, |
| 4953 | quote! { |
| 4954 | impl From<i32> for SomeStruct { |
| 4955 | #[inline(always)] |
| 4956 | fn from(i: i32) -> Self { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4957 | let mut tmp = ::std::mem::MaybeUninit::<Self>::zeroed(); |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 4958 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4959 | crate::detail::__rust_thunk___ZN10SomeStructC1Ei(&mut tmp, i); |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 4960 | tmp.assume_init() |
| 4961 | } |
| 4962 | } |
| 4963 | } |
| 4964 | } |
| 4965 | ); |
| 4966 | Ok(()) |
| 4967 | } |
| 4968 | |
| 4969 | #[test] |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 4970 | fn test_impl_from_for_implicit_conversion_from_reference() -> Result<()> { |
| 4971 | let ir = ir_from_cc( |
| 4972 | r#"#pragma clang lifetime_elision |
| 4973 | struct SomeOtherStruct final { int i; }; |
| 4974 | struct StructUnderTest final { |
| 4975 | StructUnderTest(const SomeOtherStruct& other); // implicit - no `explicit` keyword |
| 4976 | };"#, |
| 4977 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 4978 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 4979 | // This is a regression test for b/223800038: We want to ensure that the |
| 4980 | // code says `impl<'b>` (instead of incorrectly declaring that lifetime |
| 4981 | // in `fn from<'b>`). |
| 4982 | assert_rs_matches!( |
| 4983 | rs_api, |
| 4984 | quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4985 | impl<'b> From<&'b crate::SomeOtherStruct> for StructUnderTest { |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 4986 | #[inline(always)] |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 4987 | fn from(other: &'b crate::SomeOtherStruct) -> Self { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 4988 | let mut tmp = ::std::mem::MaybeUninit::<Self>::zeroed(); |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 4989 | unsafe { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 4990 | crate::detail::__rust_thunk___ZN15StructUnderTestC1ERK15SomeOtherStruct( |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 4991 | &mut tmp, other); |
| 4992 | tmp.assume_init() |
| 4993 | } |
| 4994 | } |
| 4995 | } |
| 4996 | }, |
| 4997 | ); |
| 4998 | Ok(()) |
| 4999 | } |
| 5000 | |
Devin Jeanpierre | 5ff493e | 2022-06-08 12:40:23 -0700 | [diff] [blame] | 5001 | /// Methods with missing lifetimes for `self` should give a useful error |
| 5002 | /// message. |
| 5003 | #[test] |
| 5004 | fn test_eq_nolifetime() -> Result<()> { |
| 5005 | // Missing lifetimes currently only causes hard errors for trait impls, |
| 5006 | // not For inherent methods. |
| 5007 | let ir = ir_from_cc("struct SomeStruct{SomeStruct& operator=(const SomeStruct&);};")?; |
| 5008 | |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5009 | let rs_api = rs_tokens_to_formatted_string_for_tests(generate_bindings_tokens(ir)?.rs_api)?; |
Devin Jeanpierre | 5ff493e | 2022-06-08 12:40:23 -0700 | [diff] [blame] | 5010 | assert!(rs_api.contains( |
| 5011 | "// Error while generating bindings for item 'SomeStruct::operator=':\n\ |
| 5012 | // `self` has no lifetime. Use lifetime annotations or \ |
| 5013 | `#pragma clang lifetime_elision` to create bindings for this function." |
| 5014 | )); |
| 5015 | Ok(()) |
| 5016 | } |
| 5017 | |
Lukasz Anforowicz | 5e62378 | 2022-03-14 16:52:23 +0000 | [diff] [blame] | 5018 | #[test] |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 5019 | fn test_impl_eq_for_member_function() -> Result<()> { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5020 | let ir = ir_from_cc( |
| 5021 | r#"#pragma clang lifetime_elision |
| 5022 | struct SomeStruct final { |
| 5023 | inline bool operator==(const SomeStruct& other) const { |
| 5024 | return i == other.i; |
| 5025 | } |
| 5026 | int i; |
| 5027 | };"#, |
| 5028 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5029 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5030 | assert_rs_matches!( |
| 5031 | rs_api, |
| 5032 | quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5033 | impl PartialEq<crate::SomeStruct> for SomeStruct { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5034 | #[inline(always)] |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5035 | fn eq<'a, 'b>(&'a self, other: &'b crate::SomeStruct) -> bool { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 5036 | unsafe { crate::detail::__rust_thunk___ZNK10SomeStructeqERKS_(self, other) } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5037 | } |
| 5038 | } |
| 5039 | } |
| 5040 | ); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5041 | assert_cc_matches!( |
| 5042 | rs_api_impl, |
| 5043 | quote! { |
| 5044 | extern "C" bool __rust_thunk___ZNK10SomeStructeqERKS_( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 5045 | const struct SomeStruct* __this, const struct SomeStruct& other) { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 5046 | return __this->operator==(std::forward<decltype(other)>(other)); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5047 | } |
| 5048 | } |
| 5049 | ); |
| 5050 | Ok(()) |
| 5051 | } |
| 5052 | |
| 5053 | #[test] |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 5054 | fn test_impl_eq_for_free_function() -> Result<()> { |
| 5055 | let ir = ir_from_cc( |
| 5056 | r#"#pragma clang lifetime_elision |
| 5057 | struct SomeStruct final { int i; }; |
| 5058 | bool operator==(const SomeStruct& lhs, const SomeStruct& rhs) { |
| 5059 | return lhs.i == rhs.i; |
| 5060 | }"#, |
| 5061 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5062 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 5063 | assert_rs_matches!( |
| 5064 | rs_api, |
| 5065 | quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5066 | impl PartialEq<crate::SomeStruct> for SomeStruct { |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 5067 | #[inline(always)] |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5068 | fn eq<'a, 'b>(&'a self, rhs: &'b crate::SomeStruct) -> bool { |
Rosica Dejanovska | 68c11ac | 2022-05-12 03:48:59 -0700 | [diff] [blame] | 5069 | unsafe { crate::detail::__rust_thunk___ZeqRK10SomeStructS1_(self, rhs) } |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 5070 | } |
| 5071 | } |
| 5072 | } |
| 5073 | ); |
| 5074 | Ok(()) |
| 5075 | } |
| 5076 | |
| 5077 | #[test] |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5078 | fn test_assign() -> Result<()> { |
| 5079 | let ir = ir_from_cc( |
| 5080 | r#" |
| 5081 | #pragma clang lifetime_elision |
| 5082 | struct SomeStruct { |
| 5083 | SomeStruct& operator=(const SomeStruct& other); |
| 5084 | };"#, |
| 5085 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5086 | let BindingsTokens { rs_api, .. } = generate_bindings_tokens(ir)?; |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5087 | assert_rs_matches!( |
| 5088 | rs_api, |
| 5089 | quote! { |
| 5090 | impl<'b> ::ctor::Assign<&'b crate::SomeStruct> for SomeStruct { |
| 5091 | #[inline(always)] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5092 | fn assign<'a>(self: ::std::pin::Pin<&'a mut Self>, other: &'b crate::SomeStruct) { |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5093 | unsafe { |
| 5094 | crate::detail::__rust_thunk___ZN10SomeStructaSERKS_(self, other); |
| 5095 | } |
| 5096 | } |
| 5097 | } |
| 5098 | } |
| 5099 | ); |
| 5100 | Ok(()) |
| 5101 | } |
| 5102 | |
| 5103 | #[test] |
| 5104 | fn test_assign_nonreference_other() -> Result<()> { |
| 5105 | let ir = ir_from_cc( |
| 5106 | r#" |
| 5107 | #pragma clang lifetime_elision |
| 5108 | struct SomeStruct { |
| 5109 | SomeStruct& operator=(int other); |
| 5110 | };"#, |
| 5111 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5112 | let BindingsTokens { rs_api, .. } = generate_bindings_tokens(ir)?; |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5113 | assert_rs_matches!( |
| 5114 | rs_api, |
| 5115 | quote! { |
| 5116 | impl<'b> ::ctor::Assign<&'b crate::SomeStruct> for SomeStruct { |
| 5117 | #[inline(always)] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5118 | fn assign<'a>(self: ::std::pin::Pin<&'a mut Self>, __param_0: &'b crate::SomeStruct) { |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5119 | unsafe { |
| 5120 | crate::detail::__rust_thunk___ZN10SomeStructaSERKS_(self, __param_0); |
| 5121 | } |
| 5122 | } |
| 5123 | } |
| 5124 | } |
| 5125 | ); |
| 5126 | Ok(()) |
| 5127 | } |
| 5128 | |
| 5129 | #[test] |
| 5130 | fn test_assign_nonreference_return() -> Result<()> { |
| 5131 | let ir = ir_from_cc( |
| 5132 | r#" |
| 5133 | #pragma clang lifetime_elision |
| 5134 | struct SomeStruct { |
| 5135 | int operator=(const SomeStruct& other); |
| 5136 | };"#, |
| 5137 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5138 | let BindingsTokens { rs_api, .. } = generate_bindings_tokens(ir)?; |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5139 | assert_rs_matches!( |
| 5140 | rs_api, |
| 5141 | quote! { |
| 5142 | impl<'b> ::ctor::Assign<&'b crate::SomeStruct> for SomeStruct { |
| 5143 | #[inline(always)] |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5144 | fn assign<'a>(self: ::std::pin::Pin<&'a mut Self>, other: &'b crate::SomeStruct) { |
Devin Jeanpierre | 9ced4ef | 2022-06-08 12:39:10 -0700 | [diff] [blame] | 5145 | unsafe { |
| 5146 | crate::detail::__rust_thunk___ZN10SomeStructaSERKS_(self, other); |
| 5147 | } |
| 5148 | } |
| 5149 | } |
| 5150 | } |
| 5151 | ); |
| 5152 | Ok(()) |
| 5153 | } |
| 5154 | |
| 5155 | #[test] |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5156 | fn test_impl_eq_non_const_member_function() -> Result<()> { |
| 5157 | let ir = ir_from_cc( |
| 5158 | r#"#pragma clang lifetime_elision |
| 5159 | struct SomeStruct final { |
| 5160 | bool operator==(const SomeStruct& other) /* no `const` here */; |
| 5161 | };"#, |
| 5162 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5163 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5164 | assert_rs_not_matches!(rs_api, quote! {impl PartialEq}); |
| 5165 | Ok(()) |
| 5166 | } |
| 5167 | |
| 5168 | #[test] |
| 5169 | fn test_impl_eq_rhs_by_value() -> Result<()> { |
| 5170 | let ir = ir_from_cc( |
| 5171 | r#"#pragma clang lifetime_elision |
| 5172 | struct SomeStruct final { |
| 5173 | bool operator==(SomeStruct other) const; |
| 5174 | };"#, |
| 5175 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5176 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 5177 | assert_rs_not_matches!(rs_api, quote! {impl PartialEq}); |
| 5178 | Ok(()) |
| 5179 | } |
| 5180 | |
| 5181 | #[test] |
Dmitri Gribenko | 67cbfd2 | 2022-03-24 13:39:34 +0000 | [diff] [blame] | 5182 | fn test_thunk_ident_function() -> Result<()> { |
| 5183 | let ir = ir_from_cc("inline int foo() {}")?; |
| 5184 | let func = retrieve_func(&ir, "foo"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5185 | assert_eq!(thunk_ident(&func), make_rs_ident("__rust_thunk___Z3foov")); |
Dmitri Gribenko | 67cbfd2 | 2022-03-24 13:39:34 +0000 | [diff] [blame] | 5186 | Ok(()) |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 5187 | } |
| 5188 | |
| 5189 | #[test] |
| 5190 | fn test_thunk_ident_special_names() { |
Marcel Hlopko | 4b13b96 | 2021-12-06 12:40:56 +0000 | [diff] [blame] | 5191 | let ir = ir_from_cc("struct Class {};").unwrap(); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 5192 | |
Googler | 45ad275 | 2021-12-06 12:12:35 +0000 | [diff] [blame] | 5193 | let destructor = |
| 5194 | ir.functions().find(|f| f.name == UnqualifiedIdentifier::Destructor).unwrap(); |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 5195 | assert_eq!(thunk_ident(destructor), make_rs_ident("__rust_thunk___ZN5ClassD1Ev")); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 5196 | |
Lukasz Anforowicz | 49b5bbc | 2022-02-04 23:40:10 +0000 | [diff] [blame] | 5197 | let default_constructor = ir |
| 5198 | .functions() |
| 5199 | .find(|f| f.name == UnqualifiedIdentifier::Constructor && f.params.len() == 1) |
| 5200 | .unwrap(); |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 5201 | assert_eq!(thunk_ident(default_constructor), make_rs_ident("__rust_thunk___ZN5ClassC1Ev")); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 5202 | } |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 5203 | |
| 5204 | #[test] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5205 | fn test_elided_lifetimes() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 5206 | let ir = ir_from_cc( |
| 5207 | r#"#pragma clang lifetime_elision |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 5208 | struct S final { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 5209 | int& f(int& i); |
| 5210 | };"#, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5211 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5212 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5213 | assert_rs_matches!( |
| 5214 | rs_api, |
| 5215 | quote! { |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 5216 | pub fn f<'a, 'b>(&'a mut self, i: &'b mut i32) -> &'a mut i32 { ... } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5217 | } |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 5218 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5219 | assert_rs_matches!( |
| 5220 | rs_api, |
| 5221 | quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5222 | pub(crate) fn __rust_thunk___ZN1S1fERi<'a, 'b>(__this: &'a mut crate::S, i: &'b mut i32) |
Googler | 6804a01 | 2022-01-05 07:04:36 +0000 | [diff] [blame] | 5223 | -> &'a mut i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5224 | } |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 5225 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 5226 | Ok(()) |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 5227 | } |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 5228 | |
| 5229 | #[test] |
Googler | 386e594 | 2022-02-24 08:53:29 +0000 | [diff] [blame] | 5230 | fn test_annotated_lifetimes() -> Result<()> { |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 5231 | let ir = ir_from_cc(&with_lifetime_macros( |
| 5232 | r#" |
| 5233 | int& $a f(int& $a i1, int& $a i2); |
Googler | 386e594 | 2022-02-24 08:53:29 +0000 | [diff] [blame] | 5234 | "#, |
Martin Brænne | e5ba6b6 | 2022-06-23 07:38:40 -0700 | [diff] [blame] | 5235 | ))?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5236 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Googler | 386e594 | 2022-02-24 08:53:29 +0000 | [diff] [blame] | 5237 | assert_rs_matches!( |
| 5238 | rs_api, |
| 5239 | quote! { |
| 5240 | pub fn f<'a>(i1: &'a mut i32, i2: &'a mut i32) -> &'a mut i32 { ... } |
| 5241 | } |
| 5242 | ); |
| 5243 | assert_rs_matches!( |
| 5244 | rs_api, |
| 5245 | quote! { |
| 5246 | pub(crate) fn __rust_thunk___Z1fRiS_<'a>(i1: &'a mut i32, i2: &'a mut i32) |
| 5247 | -> &'a mut i32; |
| 5248 | } |
| 5249 | ); |
| 5250 | Ok(()) |
| 5251 | } |
| 5252 | |
| 5253 | #[test] |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 5254 | fn test_format_generic_params() -> Result<()> { |
| 5255 | assert_rs_matches!(format_generic_params(std::iter::empty::<syn::Ident>()), quote! {}); |
| 5256 | |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 5257 | let idents = ["T1", "T2"].iter().map(|s| make_rs_ident(s)); |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 5258 | assert_rs_matches!(format_generic_params(idents), quote! { < T1, T2 > }); |
| 5259 | |
| 5260 | let lifetimes = ["a", "b"] |
| 5261 | .iter() |
| 5262 | .map(|s| syn::Lifetime::new(&format!("'{}", s), proc_macro2::Span::call_site())); |
| 5263 | assert_rs_matches!(format_generic_params(lifetimes), quote! { < 'a, 'b > }); |
| 5264 | |
| 5265 | Ok(()) |
| 5266 | } |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5267 | |
| 5268 | #[test] |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5269 | fn test_format_tuple_except_singleton() { |
| 5270 | fn format(xs: &[TokenStream]) -> TokenStream { |
| 5271 | format_tuple_except_singleton(xs) |
| 5272 | } |
| 5273 | assert_rs_matches!(format(&[]), quote! {()}); |
| 5274 | assert_rs_matches!(format(&[quote! {a}]), quote! {a}); |
| 5275 | assert_rs_matches!(format(&[quote! {a}, quote! {b}]), quote! {(a, b)}); |
| 5276 | } |
| 5277 | |
| 5278 | #[test] |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5279 | fn test_overloaded_functions() -> Result<()> { |
| 5280 | // TODO(b/213280424): We don't support creating bindings for overloaded |
| 5281 | // functions yet, except in the case of overloaded constructors with a |
| 5282 | // single parameter. |
| 5283 | let ir = ir_from_cc( |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 5284 | r#" #pragma clang lifetime_elision |
| 5285 | void f(); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5286 | void f(int i); |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 5287 | struct S1 final { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5288 | void f(); |
| 5289 | void f(int i); |
| 5290 | }; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 5291 | struct S2 final { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5292 | void f(); |
| 5293 | }; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 5294 | struct S3 final { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5295 | S3(int i); |
| 5296 | S3(double d); |
| 5297 | }; |
| 5298 | "#, |
| 5299 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5300 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5301 | let rs_api_str = tokens_to_string(rs_api.clone())?; |
| 5302 | |
| 5303 | // Cannot overload free functions. |
| 5304 | assert!(rs_api_str.contains("Error while generating bindings for item 'f'")); |
| 5305 | assert_rs_not_matches!(rs_api, quote! {pub fn f()}); |
| 5306 | assert_rs_not_matches!(rs_api, quote! {pub fn f(i: i32)}); |
| 5307 | |
| 5308 | // Cannot overload member functions. |
| 5309 | assert!(rs_api_str.contains("Error while generating bindings for item 'S1::f'")); |
| 5310 | assert_rs_not_matches!(rs_api, quote! {pub fn f(... S1 ...)}); |
| 5311 | |
| 5312 | // But we can import member functions that have the same name as a free |
| 5313 | // function. |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 5314 | assert_rs_matches!(rs_api, quote! {pub fn f<'a>(&'a mut self)}); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 5315 | |
| 5316 | // We can also import overloaded single-parameter constructors. |
| 5317 | assert_rs_matches!(rs_api, quote! {impl From<i32> for S3}); |
| 5318 | assert_rs_matches!(rs_api, quote! {impl From<f64> for S3}); |
| 5319 | Ok(()) |
| 5320 | } |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 5321 | |
| 5322 | #[test] |
| 5323 | fn test_type_alias() -> Result<()> { |
| 5324 | let ir = ir_from_cc( |
| 5325 | r#" |
Lukasz Anforowicz | c503af4 | 2022-03-04 23:18:15 +0000 | [diff] [blame] | 5326 | // MyTypedefDecl doc comment |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 5327 | typedef int MyTypedefDecl; |
Lukasz Anforowicz | c503af4 | 2022-03-04 23:18:15 +0000 | [diff] [blame] | 5328 | |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 5329 | using MyTypeAliasDecl = int; |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 5330 | using MyTypeAliasDecl_Alias = MyTypeAliasDecl; |
| 5331 | |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 5332 | struct S final {}; |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 5333 | using S_Alias = S; |
| 5334 | using S_Alias_Alias = S_Alias; |
| 5335 | |
| 5336 | inline void f(MyTypedefDecl t) {} |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 5337 | "#, |
| 5338 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5339 | let BindingsTokens { rs_api, rs_api_impl } = generate_bindings_tokens(ir)?; |
Lukasz Anforowicz | c503af4 | 2022-03-04 23:18:15 +0000 | [diff] [blame] | 5340 | assert_rs_matches!( |
| 5341 | rs_api, |
| 5342 | quote! { |
| 5343 | #[doc = " MyTypedefDecl doc comment"] |
| 5344 | pub type MyTypedefDecl = i32; |
| 5345 | } |
| 5346 | ); |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 5347 | assert_rs_matches!(rs_api, quote! { pub type MyTypeAliasDecl = i32; }); |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5348 | assert_rs_matches!( |
| 5349 | rs_api, |
| 5350 | quote! { pub type MyTypeAliasDecl_Alias = crate::MyTypeAliasDecl; } |
| 5351 | ); |
| 5352 | assert_rs_matches!(rs_api, quote! { pub type S_Alias = crate::S; }); |
| 5353 | assert_rs_matches!(rs_api, quote! { pub type S_Alias_Alias = crate::S_Alias; }); |
| 5354 | assert_rs_matches!(rs_api, quote! { pub fn f(t: crate::MyTypedefDecl) }); |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 5355 | assert_cc_matches!( |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5356 | rs_api_impl, |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 5357 | quote! { |
Devin Jeanpierre | deea789 | 2022-03-29 02:13:31 -0700 | [diff] [blame] | 5358 | extern "C" void __rust_thunk___Z1fi(MyTypedefDecl t){ f (std::forward<decltype(t)>(t)) ; } |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 5359 | } |
| 5360 | ); |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 5361 | Ok(()) |
| 5362 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5363 | |
| 5364 | #[test] |
| 5365 | fn test_rs_type_kind_implements_copy() -> Result<()> { |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5366 | let template = r#" LIFETIMES |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 5367 | struct [[clang::trivial_abi]] TrivialStruct final { int i; }; |
| 5368 | struct [[clang::trivial_abi]] UserDefinedCopyConstructor final { |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5369 | UserDefinedCopyConstructor(const UserDefinedCopyConstructor&); |
| 5370 | }; |
| 5371 | using IntAlias = int; |
| 5372 | using TrivialAlias = TrivialStruct; |
| 5373 | using NonTrivialAlias = UserDefinedCopyConstructor; |
| 5374 | void func(PARAM_TYPE some_param); |
| 5375 | "#; |
| 5376 | assert_impl_all!(i32: Copy); |
| 5377 | assert_impl_all!(&i32: Copy); |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 5378 | assert_not_impl_any!(&mut i32: Copy); |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5379 | assert_impl_all!(Option<&i32>: Copy); |
Lukasz Anforowicz | b4d1778 | 2022-07-07 08:09:13 -0700 | [diff] [blame] | 5380 | assert_not_impl_any!(Option<&mut i32>: Copy); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5381 | assert_impl_all!(*const i32: Copy); |
| 5382 | assert_impl_all!(*mut i32: Copy); |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5383 | struct Test { |
| 5384 | // Test inputs: |
| 5385 | cc: &'static str, |
| 5386 | lifetimes: bool, |
| 5387 | // Expected test outputs: |
| 5388 | rs: &'static str, |
| 5389 | is_copy: bool, |
| 5390 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5391 | let tests = vec![ |
| 5392 | // Validity of the next few tests is verified via |
| 5393 | // `assert_[not_]impl_all!` static assertions above. |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5394 | Test { cc: "int", lifetimes: true, rs: "i32", is_copy: true }, |
| 5395 | Test { cc: "const int&", lifetimes: true, rs: "&'a i32", is_copy: true }, |
| 5396 | Test { cc: "int&", lifetimes: true, rs: "&'a mut i32", is_copy: false }, |
| 5397 | Test { cc: "const int*", lifetimes: true, rs: "Option<&'a i32>", is_copy: true }, |
| 5398 | Test { cc: "int*", lifetimes: true, rs: "Option<&'a mut i32>", is_copy: false }, |
| 5399 | Test { cc: "const int*", lifetimes: false, rs: "*const i32", is_copy: true }, |
| 5400 | Test { cc: "int*", lifetimes: false, rs: "*mut i32", is_copy: true }, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5401 | // Tests below have been thought-through and verified "manually". |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5402 | // TrivialStruct is expected to derive Copy. |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 5403 | Test { |
| 5404 | cc: "TrivialStruct", |
| 5405 | lifetimes: true, |
| 5406 | rs: "crate::TrivialStruct", |
| 5407 | is_copy: true, |
| 5408 | }, |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5409 | Test { |
| 5410 | cc: "UserDefinedCopyConstructor", |
| 5411 | lifetimes: true, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5412 | rs: "crate::UserDefinedCopyConstructor", |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5413 | is_copy: false, |
| 5414 | }, |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5415 | Test { cc: "IntAlias", lifetimes: true, rs: "crate::IntAlias", is_copy: true }, |
| 5416 | Test { cc: "TrivialAlias", lifetimes: true, rs: "crate::TrivialAlias", is_copy: true }, |
Marcel Hlopko | 3623489 | 2022-05-10 00:39:54 -0700 | [diff] [blame] | 5417 | Test { |
| 5418 | cc: "NonTrivialAlias", |
| 5419 | lifetimes: true, |
| 5420 | rs: "crate::NonTrivialAlias", |
| 5421 | is_copy: false, |
| 5422 | }, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5423 | ]; |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5424 | for test in tests.iter() { |
| 5425 | let test_name = format!("cc='{}', lifetimes={}", test.cc, test.lifetimes); |
| 5426 | let cc_input = template.replace("PARAM_TYPE", test.cc).replace( |
| 5427 | "LIFETIMES", |
| 5428 | if test.lifetimes { "#pragma clang lifetime_elision" } else { "" }, |
| 5429 | ); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5430 | let db = db_from_cc(&cc_input)?; |
| 5431 | let ir = db.ir(); |
| 5432 | |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 5433 | let f = retrieve_func(&ir, "func"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5434 | let t = db.rs_type_kind(f.params[0].type_.rs_type.clone())?; |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5435 | |
Devin Jeanpierre | 92ca261 | 2022-04-06 11:35:13 -0700 | [diff] [blame] | 5436 | let fmt = tokens_to_string(t.to_token_stream())?; |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 5437 | assert_eq!(test.rs, fmt, "Testing: {}", test_name); |
| 5438 | |
| 5439 | assert_eq!(test.is_copy, t.implements_copy(), "Testing: {}", test_name); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5440 | } |
| 5441 | Ok(()) |
| 5442 | } |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5443 | |
| 5444 | #[test] |
| 5445 | fn test_rs_type_kind_is_shared_ref_to_with_lifetimes() -> Result<()> { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5446 | let db = db_from_cc( |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5447 | "#pragma clang lifetime_elision |
| 5448 | struct SomeStruct {}; |
| 5449 | void foo(const SomeStruct& foo_param); |
| 5450 | void bar(SomeStruct& bar_param);", |
| 5451 | )?; |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5452 | let ir = db.ir(); |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5453 | let record = ir.records().next().unwrap(); |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 5454 | let foo_func = retrieve_func(&ir, "foo"); |
| 5455 | let bar_func = retrieve_func(&ir, "bar"); |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5456 | |
| 5457 | // const-ref + lifetimes in C++ ===> shared-ref in Rust |
| 5458 | assert_eq!(foo_func.params.len(), 1); |
| 5459 | let foo_param = &foo_func.params[0]; |
| 5460 | assert_eq!(&foo_param.identifier.identifier, "foo_param"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5461 | let foo_type = db.rs_type_kind(foo_param.type_.rs_type.clone())?; |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5462 | assert!(foo_type.is_shared_ref_to(record)); |
| 5463 | assert!(matches!(foo_type, RsTypeKind::Reference { mutability: Mutability::Const, .. })); |
| 5464 | |
| 5465 | // non-const-ref + lifetimes in C++ ===> mutable-ref in Rust |
| 5466 | assert_eq!(bar_func.params.len(), 1); |
| 5467 | let bar_param = &bar_func.params[0]; |
| 5468 | assert_eq!(&bar_param.identifier.identifier, "bar_param"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5469 | let bar_type = db.rs_type_kind(bar_param.type_.rs_type.clone())?; |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5470 | assert!(!bar_type.is_shared_ref_to(record)); |
| 5471 | assert!(matches!(bar_type, RsTypeKind::Reference { mutability: Mutability::Mut, .. })); |
| 5472 | |
| 5473 | Ok(()) |
| 5474 | } |
| 5475 | |
| 5476 | #[test] |
| 5477 | fn test_rs_type_kind_is_shared_ref_to_without_lifetimes() -> Result<()> { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5478 | let db = db_from_cc( |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5479 | "struct SomeStruct {}; |
| 5480 | void foo(const SomeStruct& foo_param);", |
| 5481 | )?; |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5482 | let ir = db.ir(); |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5483 | let record = ir.records().next().unwrap(); |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 5484 | let foo_func = retrieve_func(&ir, "foo"); |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5485 | |
| 5486 | // const-ref + *no* lifetimes in C++ ===> const-pointer in Rust |
| 5487 | assert_eq!(foo_func.params.len(), 1); |
| 5488 | let foo_param = &foo_func.params[0]; |
| 5489 | assert_eq!(&foo_param.identifier.identifier, "foo_param"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5490 | let foo_type = db.rs_type_kind(foo_param.type_.rs_type.clone())?; |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 5491 | assert!(!foo_type.is_shared_ref_to(record)); |
| 5492 | assert!(matches!(foo_type, RsTypeKind::Pointer { mutability: Mutability::Const, .. })); |
| 5493 | |
| 5494 | Ok(()) |
| 5495 | } |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 5496 | |
| 5497 | #[test] |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5498 | fn test_rs_type_kind_dfs_iter_ordering() { |
| 5499 | // Set up a test input representing: A<B<C>, D<E>>. |
| 5500 | let a = { |
| 5501 | let b = { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 5502 | let c = RsTypeKind::Other { name: "C".into(), type_args: Rc::from([]) }; |
| 5503 | RsTypeKind::Other { name: "B".into(), type_args: Rc::from([c]) } |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5504 | }; |
| 5505 | let d = { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 5506 | let e = RsTypeKind::Other { name: "E".into(), type_args: Rc::from([]) }; |
| 5507 | RsTypeKind::Other { name: "D".into(), type_args: Rc::from([e]) } |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5508 | }; |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 5509 | RsTypeKind::Other { name: "A".into(), type_args: Rc::from([b, d]) } |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5510 | }; |
| 5511 | let dfs_names = a |
| 5512 | .dfs_iter() |
| 5513 | .map(|t| match t { |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 5514 | RsTypeKind::Other { name, .. } => &**name, |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5515 | _ => unreachable!("Only 'other' types are used in this test"), |
| 5516 | }) |
| 5517 | .collect_vec(); |
| 5518 | assert_eq!(vec!["A", "B", "C", "D", "E"], dfs_names); |
| 5519 | } |
| 5520 | |
| 5521 | #[test] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 5522 | fn test_rs_type_kind_dfs_iter_ordering_for_func_ptr() { |
| 5523 | // Set up a test input representing: fn(A, B) -> C |
| 5524 | let f = { |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 5525 | let a = RsTypeKind::Other { name: "A".into(), type_args: Rc::from(&[][..]) }; |
| 5526 | let b = RsTypeKind::Other { name: "B".into(), type_args: Rc::from(&[][..]) }; |
| 5527 | let c = RsTypeKind::Other { name: "C".into(), type_args: Rc::from(&[][..]) }; |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 5528 | RsTypeKind::FuncPtr { |
| 5529 | abi: "blah".into(), |
Devin Jeanpierre | b2b6cf8 | 2022-07-07 01:49:27 -0700 | [diff] [blame] | 5530 | param_types: Rc::from([a, b]), |
| 5531 | return_type: Rc::new(c), |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 5532 | } |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 5533 | }; |
| 5534 | let dfs_names = f |
| 5535 | .dfs_iter() |
| 5536 | .map(|t| match t { |
| 5537 | RsTypeKind::FuncPtr { .. } => "fn", |
Devin Jeanpierre | 8cd8ae7 | 2022-06-29 18:59:40 -0700 | [diff] [blame] | 5538 | RsTypeKind::Other { name, .. } => &**name, |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 5539 | _ => unreachable!("Only FuncPtr and Other kinds are used in this test"), |
| 5540 | }) |
| 5541 | .collect_vec(); |
| 5542 | assert_eq!(vec!["fn", "A", "B", "C"], dfs_names); |
| 5543 | } |
| 5544 | |
| 5545 | #[test] |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5546 | fn test_rs_type_kind_lifetimes() -> Result<()> { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5547 | let db = db_from_cc( |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5548 | r#" |
| 5549 | #pragma clang lifetime_elision |
| 5550 | using TypeAlias = int&; |
| 5551 | struct SomeStruct {}; |
Devin Jeanpierre | 48cb5bc | 2022-06-02 00:50:43 -0700 | [diff] [blame] | 5552 | void foo(int a, int& b, int&& c, int* d, int** e, TypeAlias f, SomeStruct g); "#, |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5553 | )?; |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5554 | let ir = db.ir(); |
Devin Jeanpierre | 48cb5bc | 2022-06-02 00:50:43 -0700 | [diff] [blame] | 5555 | let func = retrieve_func(&ir, "foo"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5556 | let ret = db.rs_type_kind(func.return_type.rs_type.clone())?; |
| 5557 | let a = db.rs_type_kind(func.params[0].type_.rs_type.clone())?; |
| 5558 | let b = db.rs_type_kind(func.params[1].type_.rs_type.clone())?; |
| 5559 | let c = db.rs_type_kind(func.params[2].type_.rs_type.clone())?; |
| 5560 | let d = db.rs_type_kind(func.params[3].type_.rs_type.clone())?; |
| 5561 | let e = db.rs_type_kind(func.params[4].type_.rs_type.clone())?; |
| 5562 | let f = db.rs_type_kind(func.params[5].type_.rs_type.clone())?; |
| 5563 | let g = db.rs_type_kind(func.params[6].type_.rs_type.clone())?; |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5564 | |
| 5565 | assert_eq!(0, ret.lifetimes().count()); // No lifetimes on `void`. |
| 5566 | assert_eq!(0, a.lifetimes().count()); // No lifetimes on `int`. |
| 5567 | assert_eq!(1, b.lifetimes().count()); // `&'a i32` has a single lifetime. |
Devin Jeanpierre | 48cb5bc | 2022-06-02 00:50:43 -0700 | [diff] [blame] | 5568 | assert_eq!(1, c.lifetimes().count()); // `RvalueReference<'a, i32>` has a single lifetime. |
| 5569 | assert_eq!(1, d.lifetimes().count()); // `Option<&'b i32>` has a single lifetime. |
| 5570 | assert_eq!(2, e.lifetimes().count()); // `&'c Option<&'d i32>` has two lifetimes. |
| 5571 | assert_eq!(1, f.lifetimes().count()); // Lifetime of underlying type should show through. |
| 5572 | assert_eq!(0, g.lifetimes().count()); // No lifetimes on structs (yet). |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5573 | Ok(()) |
| 5574 | } |
| 5575 | |
| 5576 | #[test] |
| 5577 | fn test_rs_type_kind_lifetimes_raw_ptr() -> Result<()> { |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5578 | let db = db_from_cc("void foo(int* a);")?; |
| 5579 | let ir = db.ir(); |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5580 | let f = retrieve_func(&ir, "foo"); |
Devin Jeanpierre | 409f6f6 | 2022-07-07 02:00:26 -0700 | [diff] [blame] | 5581 | let a = db.rs_type_kind(f.params[0].type_.rs_type.clone())?; |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 5582 | assert_eq!(0, a.lifetimes().count()); // No lifetimes on `int*`. |
| 5583 | Ok(()) |
| 5584 | } |
| 5585 | |
| 5586 | #[test] |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 5587 | fn test_rust_keywords_are_escaped_in_rs_api_file() -> Result<()> { |
| 5588 | let ir = ir_from_cc("struct type { int dyn; };")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5589 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 5590 | assert_rs_matches!(rs_api, quote! { struct r#type { ... r#dyn: i32 ... } }); |
| 5591 | Ok(()) |
| 5592 | } |
| 5593 | |
| 5594 | #[test] |
| 5595 | fn test_rust_keywords_are_not_escaped_in_rs_api_impl_file() -> Result<()> { |
| 5596 | let ir = ir_from_cc("struct type { int dyn; };")?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5597 | let rs_api_impl = generate_bindings_tokens(ir)?.rs_api_impl; |
Lukasz Anforowicz | 4ee9c22 | 2022-04-13 09:33:36 -0700 | [diff] [blame] | 5598 | assert_cc_matches!( |
| 5599 | rs_api_impl, |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 5600 | quote! { static_assert(CRUBIT_OFFSET_OF(dyn, struct type) ... ) } |
Lukasz Anforowicz | 4ee9c22 | 2022-04-13 09:33:36 -0700 | [diff] [blame] | 5601 | ); |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 5602 | Ok(()) |
| 5603 | } |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 5604 | |
| 5605 | #[test] |
| 5606 | fn test_no_aligned_attr() { |
| 5607 | let ir = ir_from_cc("struct SomeStruct {};").unwrap(); |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5608 | let rs_api = generate_bindings_tokens(ir).unwrap().rs_api; |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 5609 | |
| 5610 | assert_rs_matches! {rs_api, quote! { |
| 5611 | #[repr(C)] |
| 5612 | pub struct SomeStruct { ... } |
| 5613 | }}; |
| 5614 | } |
| 5615 | |
| 5616 | #[test] |
| 5617 | fn test_aligned_attr() { |
| 5618 | let ir = ir_from_cc("struct SomeStruct {} __attribute__((aligned(64)));").unwrap(); |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5619 | let rs_api = generate_bindings_tokens(ir).unwrap().rs_api; |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 5620 | |
| 5621 | assert_rs_matches! {rs_api, quote! { |
| 5622 | #[repr(C, align(64))] |
| 5623 | pub struct SomeStruct { ... } |
| 5624 | } |
| 5625 | }; |
| 5626 | } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5627 | |
| 5628 | /// !Unpin references should not be pinned. |
| 5629 | #[test] |
| 5630 | fn test_nonunpin_ref_param() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5631 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5632 | r#" |
| 5633 | #pragma clang lifetime_elision |
| 5634 | struct S {~S();}; |
| 5635 | void Function(const S& s); |
| 5636 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5637 | )?)? |
| 5638 | .rs_api; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5639 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5640 | rs_api, |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5641 | quote! { |
Rosica Dejanovska | 8283fe6 | 2022-05-09 10:04:28 -0700 | [diff] [blame] | 5642 | fn Function<'a>(s: &'a crate::S) { ... } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5643 | } |
| 5644 | ); |
| 5645 | Ok(()) |
| 5646 | } |
| 5647 | |
| 5648 | /// !Unpin mut references must be pinned. |
| 5649 | #[test] |
| 5650 | fn test_nonunpin_mut_param() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5651 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5652 | r#" |
| 5653 | #pragma clang lifetime_elision |
| 5654 | struct S {~S();}; |
| 5655 | void Function(S& s); |
| 5656 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5657 | )?)? |
| 5658 | .rs_api; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5659 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5660 | rs_api, |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5661 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5662 | fn Function<'a>(s: ::std::pin::Pin<&'a mut crate::S>) { ... } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5663 | } |
| 5664 | ); |
| 5665 | Ok(()) |
| 5666 | } |
| 5667 | |
| 5668 | /// !Unpin &self should not be pinned. |
| 5669 | #[test] |
| 5670 | fn test_nonunpin_ref_self() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5671 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5672 | r#" |
| 5673 | #pragma clang lifetime_elision |
| 5674 | struct S { |
| 5675 | ~S(); |
| 5676 | void Function() const; |
| 5677 | }; |
| 5678 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5679 | )?)? |
| 5680 | .rs_api; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5681 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5682 | rs_api, |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5683 | quote! { |
| 5684 | fn Function<'a>(&'a self) { ... } |
| 5685 | } |
| 5686 | ); |
| 5687 | Ok(()) |
| 5688 | } |
| 5689 | |
| 5690 | /// !Unpin &mut self must be pinned. |
| 5691 | #[test] |
| 5692 | fn test_nonunpin_mut_self() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5693 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5694 | r#" |
| 5695 | #pragma clang lifetime_elision |
| 5696 | struct S { |
| 5697 | ~S(); |
| 5698 | void Function(); |
| 5699 | }; |
| 5700 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5701 | )?)? |
| 5702 | .rs_api; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5703 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5704 | rs_api, |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5705 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5706 | fn Function<'a>(self: ::std::pin::Pin<&'a mut Self>) { ... } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5707 | } |
| 5708 | ); |
| 5709 | Ok(()) |
| 5710 | } |
| 5711 | |
| 5712 | /// Drop::drop must not use self : Pin<...>. |
| 5713 | #[test] |
| 5714 | fn test_nonunpin_drop() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5715 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5716 | r#" |
| 5717 | struct S {~S();}; |
| 5718 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5719 | )?)? |
| 5720 | .rs_api; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5721 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5722 | rs_api, |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5723 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5724 | unsafe fn pinned_drop<'a>(self: ::std::pin::Pin<&'a mut Self>) { ... } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 5725 | } |
| 5726 | ); |
| 5727 | Ok(()) |
| 5728 | } |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 5729 | |
| 5730 | #[test] |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5731 | fn test_nonunpin_0_arg_constructor() -> Result<()> { |
| 5732 | let ir = ir_from_cc( |
| 5733 | r#"#pragma clang lifetime_elision |
| 5734 | // This type must be `!Unpin`. |
| 5735 | struct HasConstructor {explicit HasConstructor() {}};"#, |
| 5736 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5737 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5738 | assert_rs_matches!(rs_api, quote! {#[::ctor::recursively_pinned]}); |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5739 | assert_rs_matches!( |
| 5740 | rs_api, |
| 5741 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5742 | impl ::ctor::CtorNew<()> for HasConstructor { |
| 5743 | type CtorType = impl ::ctor::Ctor<Output = Self>; |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5744 | |
| 5745 | #[inline (always)] |
| 5746 | fn ctor_new(args: ()) -> Self::CtorType { |
| 5747 | let () = args; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5748 | ::ctor::FnCtor::new(move |dest: ::std::pin::Pin<&mut ::std::mem::MaybeUninit<Self>>| { |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5749 | unsafe { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5750 | crate::detail::__rust_thunk___ZN14HasConstructorC1Ev(::std::pin::Pin::into_inner_unchecked(dest)); |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5751 | } |
| 5752 | }) |
| 5753 | } |
| 5754 | } |
| 5755 | } |
| 5756 | ); |
| 5757 | Ok(()) |
| 5758 | } |
| 5759 | |
| 5760 | #[test] |
| 5761 | fn test_nonunpin_1_arg_constructor() -> Result<()> { |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 5762 | let ir = ir_from_cc( |
| 5763 | r#"#pragma clang lifetime_elision |
| 5764 | // This type must be `!Unpin`. |
| 5765 | struct HasConstructor {explicit HasConstructor(unsigned char input) {}};"#, |
| 5766 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5767 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5768 | assert_rs_matches!(rs_api, quote! {#[::ctor::recursively_pinned]}); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 5769 | assert_rs_matches!( |
| 5770 | rs_api, |
| 5771 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5772 | impl ::ctor::CtorNew<u8> for HasConstructor { |
| 5773 | type CtorType = impl ::ctor::Ctor<Output = Self>; |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 5774 | |
| 5775 | #[inline (always)] |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5776 | fn ctor_new(args: u8) -> Self::CtorType { |
| 5777 | let input = args; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5778 | ::ctor::FnCtor::new(move |dest: ::std::pin::Pin<&mut ::std::mem::MaybeUninit<Self>>| { |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 5779 | unsafe { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5780 | crate::detail::__rust_thunk___ZN14HasConstructorC1Eh(::std::pin::Pin::into_inner_unchecked(dest), input); |
Devin Jeanpierre | 6f60737 | 2022-03-22 21:34:38 +0000 | [diff] [blame] | 5781 | } |
| 5782 | }) |
| 5783 | } |
| 5784 | } |
| 5785 | } |
| 5786 | ); |
| 5787 | Ok(()) |
| 5788 | } |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5789 | |
| 5790 | #[test] |
| 5791 | fn test_nonunpin_2_arg_constructor() -> Result<()> { |
| 5792 | let ir = ir_from_cc( |
| 5793 | r#"#pragma clang lifetime_elision |
| 5794 | // This type must be `!Unpin`. |
| 5795 | struct HasConstructor {explicit HasConstructor(unsigned char input1, signed char input2) {}};"#, |
| 5796 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5797 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5798 | assert_rs_matches!(rs_api, quote! {#[::ctor::recursively_pinned]}); |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5799 | assert_rs_matches!( |
| 5800 | rs_api, |
| 5801 | quote! { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5802 | impl ::ctor::CtorNew<(u8, i8)> for HasConstructor { |
| 5803 | type CtorType = impl ::ctor::Ctor<Output = Self>; |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5804 | |
| 5805 | #[inline (always)] |
| 5806 | fn ctor_new(args: (u8, i8)) -> Self::CtorType { |
| 5807 | let (input1, input2) = args; |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5808 | ::ctor::FnCtor::new(move |dest: ::std::pin::Pin<&mut ::std::mem::MaybeUninit<Self>>| { |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5809 | unsafe { |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5810 | crate::detail::__rust_thunk___ZN14HasConstructorC1Eha(::std::pin::Pin::into_inner_unchecked(dest), input1, input2); |
Devin Jeanpierre | ad12574 | 2022-04-11 13:50:28 -0700 | [diff] [blame] | 5811 | } |
| 5812 | }) |
| 5813 | } |
| 5814 | } |
| 5815 | } |
| 5816 | ); |
| 5817 | Ok(()) |
| 5818 | } |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5819 | |
| 5820 | #[test] |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 5821 | fn test_forward_declared() -> Result<()> { |
| 5822 | let ir = ir_from_cc( |
| 5823 | r#"#pragma clang lifetime_elision |
| 5824 | struct ForwardDeclared;"#, |
| 5825 | )?; |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5826 | let rs_api = generate_bindings_tokens(ir)?.rs_api; |
Devin Jeanpierre | c0543eb | 2022-04-20 16:00:34 -0700 | [diff] [blame] | 5827 | assert_rs_matches!( |
| 5828 | rs_api, |
| 5829 | quote! { |
| 5830 | forward_declare::forward_declare!(pub ForwardDeclared = forward_declare::symbol!("ForwardDeclared")); |
| 5831 | } |
| 5832 | ); |
| 5833 | assert_rs_not_matches!(rs_api, quote! {struct ForwardDeclared}); |
| 5834 | Ok(()) |
| 5835 | } |
| 5836 | |
| 5837 | #[test] |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5838 | fn test_namespace_module_items() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5839 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5840 | r#" |
| 5841 | namespace test_namespace_bindings { |
| 5842 | int func(); |
| 5843 | struct S {}; |
| 5844 | namespace inner { |
| 5845 | int inner_func(); |
| 5846 | struct InnerS {}; |
| 5847 | } |
| 5848 | } |
| 5849 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5850 | )?)? |
| 5851 | .rs_api; |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5852 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5853 | rs_api, |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5854 | quote! { |
| 5855 | pub mod test_namespace_bindings { |
| 5856 | ... |
| 5857 | pub fn func() -> i32 { ... } |
| 5858 | ... |
| 5859 | pub struct S { ... } |
| 5860 | ... |
| 5861 | pub mod inner { |
| 5862 | ... |
| 5863 | pub fn inner_func() -> i32 { ... } |
| 5864 | ... |
| 5865 | pub struct InnerS { ... } |
| 5866 | ... |
| 5867 | } |
| 5868 | ... |
| 5869 | } |
| 5870 | } |
| 5871 | ); |
| 5872 | Ok(()) |
| 5873 | } |
| 5874 | |
| 5875 | #[test] |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 5876 | fn test_detail_outside_of_namespace_module() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5877 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5878 | r#" |
| 5879 | namespace test_namespace_bindings { |
| 5880 | int f(); |
| 5881 | } |
| 5882 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5883 | )?)? |
| 5884 | .rs_api; |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5885 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5886 | rs_api, |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5887 | quote! { |
| 5888 | pub mod test_namespace_bindings { |
| 5889 | ... |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5890 | } |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 5891 | ... |
| 5892 | mod detail { |
| 5893 | #[allow(unused_imports)] |
| 5894 | use super::*; |
| 5895 | extern "C" { |
| 5896 | #[link_name = "_ZN23test_namespace_bindings1fEv"] |
| 5897 | pub(crate) fn __rust_thunk___ZN23test_namespace_bindings1fEv() -> i32; |
| 5898 | } |
| 5899 | } |
| 5900 | ... |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5901 | } |
| 5902 | ); |
| 5903 | Ok(()) |
| 5904 | } |
| 5905 | |
| 5906 | #[test] |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 5907 | fn test_assertions_outside_of_namespace_module() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5908 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5909 | r#" |
| 5910 | namespace test_namespace_bindings { |
| 5911 | struct S { |
| 5912 | int i; |
| 5913 | }; |
| 5914 | } |
| 5915 | "#, |
Devin Jeanpierre | 4f06f83 | 2022-04-26 15:51:30 -0700 | [diff] [blame] | 5916 | )?)? |
| 5917 | .rs_api; |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5918 | assert_rs_matches!( |
Devin Jeanpierre | 448322b | 2022-04-26 15:43:40 -0700 | [diff] [blame] | 5919 | rs_api, |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5920 | quote! { |
| 5921 | pub mod test_namespace_bindings { |
| 5922 | ... |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5923 | } |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 5924 | ... |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 5925 | const _: () = assert!(::std::mem::size_of::<crate::test_namespace_bindings::S>() == 4); |
| 5926 | const _: () = assert!(::std::mem::align_of::<crate::test_namespace_bindings::S>() == 4); |
Rosica Dejanovska | 5d9faaf | 2022-05-11 04:30:04 -0700 | [diff] [blame] | 5927 | ... |
Lukasz Anforowicz | 30360ba | 2022-05-23 12:15:12 -0700 | [diff] [blame] | 5928 | const _: () = assert!(memoffset_unstable_const::offset_of!(crate::test_namespace_bindings::S, i) == 0); |
Rosica Dejanovska | dd9a903 | 2022-04-12 07:34:41 -0700 | [diff] [blame] | 5929 | } |
| 5930 | ); |
| 5931 | Ok(()) |
| 5932 | } |
Rosica Dejanovska | 93aeafb | 2022-06-01 07:05:31 -0700 | [diff] [blame] | 5933 | |
| 5934 | #[test] |
| 5935 | fn test_reopened_namespaces() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5936 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | 93aeafb | 2022-06-01 07:05:31 -0700 | [diff] [blame] | 5937 | r#" |
| 5938 | namespace test_namespace_bindings { |
| 5939 | namespace inner {} |
| 5940 | } // namespace test_namespace_bindings |
| 5941 | |
| 5942 | namespace test_namespace_bindings { |
| 5943 | namespace inner {} |
| 5944 | } // namespace test_namespace_bindings"#, |
| 5945 | )?)? |
| 5946 | .rs_api; |
| 5947 | |
| 5948 | assert_rs_matches!( |
| 5949 | rs_api, |
| 5950 | quote! { |
| 5951 | ... |
| 5952 | pub mod test_namespace_bindings_0 { |
| 5953 | pub mod inner_0 {} ... |
| 5954 | } |
| 5955 | ... |
| 5956 | pub mod test_namespace_bindings { |
| 5957 | pub use super::test_namespace_bindings_0::*; |
| 5958 | ... |
| 5959 | pub mod inner { |
| 5960 | pub use super::inner_0::*; |
| 5961 | ... |
| 5962 | } |
| 5963 | } |
| 5964 | ... |
| 5965 | } |
| 5966 | ); |
| 5967 | Ok(()) |
| 5968 | } |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 5969 | |
| 5970 | #[test] |
| 5971 | fn test_qualified_identifiers_in_impl_file() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 5972 | let rs_api_impl = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 5973 | r#" |
| 5974 | namespace test_namespace_bindings { |
| 5975 | inline void f() {}; |
| 5976 | struct S{}; |
| 5977 | } |
| 5978 | inline void useS(test_namespace_bindings::S s) {};"#, |
| 5979 | )?)? |
| 5980 | .rs_api_impl; |
| 5981 | |
| 5982 | assert_cc_matches!( |
| 5983 | rs_api_impl, |
| 5984 | quote! { |
| 5985 | extern "C" void __rust_thunk___ZN23test_namespace_bindings1fEv() { |
| 5986 | test_namespace_bindings::f(); |
| 5987 | } |
| 5988 | ... |
| 5989 | extern "C" void __rust_thunk___ZN23test_namespace_bindings1SC1Ev( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 5990 | struct test_namespace_bindings::S* __this) {...} |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 5991 | ... |
| 5992 | extern "C" void __rust_thunk___Z4useSN23test_namespace_bindings1SE( |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 5993 | struct test_namespace_bindings::S s) { useS(std::forward<decltype(s)>(s)); } |
Rosica Dejanovska | a08b386 | 2022-06-02 08:22:49 -0700 | [diff] [blame] | 5994 | ... |
| 5995 | } |
| 5996 | ); |
| 5997 | Ok(()) |
| 5998 | } |
Rosica Dejanovska | 4180ffe | 2022-06-09 06:01:05 -0700 | [diff] [blame] | 5999 | |
| 6000 | #[test] |
| 6001 | fn test_inline_namespace() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 6002 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | 4180ffe | 2022-06-09 06:01:05 -0700 | [diff] [blame] | 6003 | r#" |
| 6004 | namespace test_namespace_bindings { |
| 6005 | inline namespace inner { |
| 6006 | struct MyStruct {}; |
| 6007 | } |
| 6008 | void processMyStruct(MyStruct s); |
| 6009 | } |
| 6010 | void processMyStructOutsideNamespace(test_namespace_bindings::inner::MyStruct s); |
| 6011 | void processMyStructSkipInlineNamespaceQualifier(test_namespace_bindings::MyStruct s); |
| 6012 | "#, |
| 6013 | )?)? |
| 6014 | .rs_api; |
| 6015 | |
| 6016 | assert_rs_matches!( |
| 6017 | rs_api, |
| 6018 | quote! { |
| 6019 | ... |
| 6020 | pub mod test_namespace_bindings { |
| 6021 | ... |
| 6022 | pub mod inner { |
| 6023 | ... |
| 6024 | pub struct MyStruct {...} ... |
| 6025 | } |
| 6026 | ... |
| 6027 | pub fn processMyStruct(s: crate::test_namespace_bindings::inner::MyStruct) |
| 6028 | ... |
| 6029 | } |
| 6030 | ... |
| 6031 | pub fn processMyStructOutsideNamespace(s: crate::test_namespace_bindings::inner::MyStruct) |
| 6032 | ... |
| 6033 | pub fn processMyStructSkipInlineNamespaceQualifier(s: crate::test_namespace_bindings::inner::MyStruct) |
| 6034 | ... |
| 6035 | } |
| 6036 | ); |
| 6037 | Ok(()) |
| 6038 | } |
Rosica Dejanovska | 2708a5f | 2022-06-22 06:54:59 -0700 | [diff] [blame] | 6039 | |
| 6040 | #[test] |
| 6041 | fn test_implicit_template_specializations_are_sorted_by_mangled_name() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 6042 | let bindings = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | 2708a5f | 2022-06-22 06:54:59 -0700 | [diff] [blame] | 6043 | r#" |
| 6044 | template <typename T> |
| 6045 | struct MyStruct { |
| 6046 | T getT(); |
| 6047 | }; |
| 6048 | |
| 6049 | using Alias1 = MyStruct<int>; |
| 6050 | using Alias2 = MyStruct<double>; |
| 6051 | |
| 6052 | namespace test_namespace_bindings { |
| 6053 | using Alias3 = MyStruct<bool>; |
| 6054 | } |
| 6055 | "#, |
| 6056 | )?)?; |
| 6057 | |
| 6058 | // Mangled name order: bool < double < int |
| 6059 | let my_struct_bool = make_rs_ident("__CcTemplateInst8MyStructIbE"); |
| 6060 | let my_struct_double = make_rs_ident("__CcTemplateInst8MyStructIdE"); |
| 6061 | let my_struct_int = make_rs_ident("__CcTemplateInst8MyStructIiE"); |
| 6062 | |
| 6063 | assert_rs_matches!( |
| 6064 | &bindings.rs_api, |
| 6065 | quote! { |
| 6066 | ... |
| 6067 | pub struct #my_struct_bool {...} |
| 6068 | ... |
| 6069 | pub struct #my_struct_double {...} |
| 6070 | ... |
| 6071 | pub struct #my_struct_int {...} |
| 6072 | ... |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 6073 | const _: () = assert!(::std::mem::size_of::<crate::#my_struct_bool>() == 1); |
Rosica Dejanovska | 2708a5f | 2022-06-22 06:54:59 -0700 | [diff] [blame] | 6074 | ... |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 6075 | const _: () = assert!(::std::mem::size_of::<crate::#my_struct_double>() == 1); |
Rosica Dejanovska | 2708a5f | 2022-06-22 06:54:59 -0700 | [diff] [blame] | 6076 | ... |
Devin Jeanpierre | cd5ebf3 | 2022-07-08 05:31:55 -0700 | [diff] [blame] | 6077 | const _: () = assert!(::std::mem::size_of::<crate::#my_struct_int>() == 1); |
Rosica Dejanovska | 2708a5f | 2022-06-22 06:54:59 -0700 | [diff] [blame] | 6078 | ... |
| 6079 | } |
| 6080 | ); |
| 6081 | |
| 6082 | // Constructors in mangled name order |
| 6083 | let my_struct_bool_constructor = |
| 6084 | make_rs_ident("__rust_thunk___ZN8MyStructIbEC1Ev__2f_2ftest_3atesting_5ftarget"); |
| 6085 | let my_struct_double_constructor = |
| 6086 | make_rs_ident("__rust_thunk___ZN8MyStructIdEC1Ev__2f_2ftest_3atesting_5ftarget"); |
| 6087 | let my_struct_int_constructor = |
| 6088 | make_rs_ident("__rust_thunk___ZN8MyStructIiEC1Ev__2f_2ftest_3atesting_5ftarget"); |
| 6089 | |
| 6090 | // User defined methods in mangled name order |
| 6091 | let my_struct_bool_method = |
| 6092 | make_rs_ident("__rust_thunk___ZN8MyStructIbE4getTEv__2f_2ftest_3atesting_5ftarget"); |
| 6093 | let my_struct_double_method = |
| 6094 | make_rs_ident("__rust_thunk___ZN8MyStructIdE4getTEv__2f_2ftest_3atesting_5ftarget"); |
| 6095 | let my_struct_int_method = |
| 6096 | make_rs_ident("__rust_thunk___ZN8MyStructIiE4getTEv__2f_2ftest_3atesting_5ftarget"); |
| 6097 | |
| 6098 | assert_cc_matches!( |
| 6099 | &bindings.rs_api_impl, |
| 6100 | quote! { |
| 6101 | ... |
Lukasz Anforowicz | d4742ff | 2022-07-11 17:05:02 -0700 | [diff] [blame] | 6102 | extern "C" void #my_struct_bool_constructor(struct MyStruct<bool>*__this) {...} ... |
| 6103 | extern "C" void #my_struct_double_constructor(struct MyStruct<double>*__this) {...} ... |
| 6104 | extern "C" void #my_struct_int_constructor(struct MyStruct<int>*__this) {...} ... |
| 6105 | extern "C" bool #my_struct_bool_method(struct MyStruct<bool>*__this) {...} ... |
| 6106 | extern "C" double #my_struct_double_method(struct MyStruct<double>*__this) {...} ... |
| 6107 | extern "C" int #my_struct_int_method(struct MyStruct<int>*__this) {...} ... |
Rosica Dejanovska | 2708a5f | 2022-06-22 06:54:59 -0700 | [diff] [blame] | 6108 | } |
| 6109 | ); |
| 6110 | Ok(()) |
| 6111 | } |
Rosica Dejanovska | f9787c9 | 2022-06-22 12:14:57 -0700 | [diff] [blame] | 6112 | |
| 6113 | #[test] |
| 6114 | fn test_implicit_template_specialization_namespace_qualifier() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 6115 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | f9787c9 | 2022-06-22 12:14:57 -0700 | [diff] [blame] | 6116 | r#" #pragma clang lifetime_elision |
| 6117 | namespace test_namespace_bindings { |
| 6118 | template <typename T> |
| 6119 | struct MyTemplate final { |
| 6120 | T value_; |
| 6121 | }; |
| 6122 | |
| 6123 | using MyTypeAlias = MyTemplate<int>; |
| 6124 | }"#, |
| 6125 | )?)? |
| 6126 | .rs_api; |
| 6127 | |
| 6128 | assert_rs_matches!( |
| 6129 | rs_api, |
| 6130 | quote! { |
| 6131 | ... |
| 6132 | pub mod test_namespace_bindings { |
| 6133 | ... |
| 6134 | pub type MyTypeAlias = crate::__CcTemplateInstN23test_namespace_bindings10MyTemplateIiEE; |
| 6135 | ... |
| 6136 | } |
| 6137 | ... |
| 6138 | pub struct __CcTemplateInstN23test_namespace_bindings10MyTemplateIiEE { |
| 6139 | pub value_: i32, |
| 6140 | } |
| 6141 | ... |
| 6142 | } |
| 6143 | ); |
| 6144 | Ok(()) |
| 6145 | } |
Rosica Dejanovska | e12d717 | 2022-06-22 12:20:17 -0700 | [diff] [blame] | 6146 | |
| 6147 | #[test] |
| 6148 | fn test_forward_declared_class_template_specialization_symbol() -> Result<()> { |
Devin Jeanpierre | e9850a7 | 2022-06-29 19:04:48 -0700 | [diff] [blame] | 6149 | let rs_api = generate_bindings_tokens(ir_from_cc( |
Rosica Dejanovska | e12d717 | 2022-06-22 12:20:17 -0700 | [diff] [blame] | 6150 | r#" |
| 6151 | namespace test_namespace_bindings { |
| 6152 | template <typename T> |
| 6153 | struct MyTemplate { |
| 6154 | void processT(T t); |
| 6155 | }; |
| 6156 | |
| 6157 | struct Param {}; |
| 6158 | |
| 6159 | template<> struct MyTemplate<Param>; |
| 6160 | }"#, |
| 6161 | )?)? |
| 6162 | .rs_api; |
| 6163 | |
| 6164 | assert_rs_matches!( |
| 6165 | rs_api, |
| 6166 | quote! { |
| 6167 | ... |
| 6168 | pub mod test_namespace_bindings { |
| 6169 | ... |
| 6170 | forward_declare::forward_declare!(pub __CcTemplateInstN23test_namespace_bindings10MyTemplateINS_5ParamEEE = forward_declare::symbol!("__CcTemplateInstN23test_namespace_bindings10MyTemplateINS_5ParamEEE")); |
| 6171 | ... |
| 6172 | } |
| 6173 | ... |
| 6174 | } |
| 6175 | ); |
| 6176 | Ok(()) |
| 6177 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 6178 | } |