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 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 5 | #[cfg(test)] |
| 6 | #[macro_use] |
| 7 | extern crate static_assertions; |
| 8 | |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 9 | use anyhow::{anyhow, bail, ensure, Context, Result}; |
Marcel Hlopko | 884ae7f | 2021-08-18 13:58:22 +0000 | [diff] [blame] | 10 | use ffi_types::*; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 11 | use ir::*; |
| 12 | use itertools::Itertools; |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 13 | use proc_macro2::{Ident, Literal, TokenStream}; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 14 | use quote::format_ident; |
| 15 | use quote::quote; |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 16 | use std::collections::{BTreeSet, HashMap, HashSet}; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 17 | use std::iter::Iterator; |
| 18 | use std::panic::catch_unwind; |
| 19 | use std::process; |
Marcel Hlopko | 65d05f0 | 2021-12-09 12:29:24 +0000 | [diff] [blame] | 20 | use token_stream_printer::{rs_tokens_to_formatted_string, tokens_to_string}; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 21 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 22 | /// FFI equivalent of `Bindings`. |
| 23 | #[repr(C)] |
| 24 | pub struct FfiBindings { |
| 25 | rs_api: FfiU8SliceBox, |
| 26 | rs_api_impl: FfiU8SliceBox, |
| 27 | } |
| 28 | |
| 29 | /// Deserializes IR from `json` and generates bindings source code. |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 30 | /// |
| 31 | /// This function panics on error. |
| 32 | /// |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 33 | /// # Safety |
| 34 | /// |
| 35 | /// Expectations: |
| 36 | /// * function expects that param `json` is a FfiU8Slice for a valid array of |
| 37 | /// bytes with the given size. |
| 38 | /// * function expects that param `json` doesn't change during the call. |
| 39 | /// |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 40 | /// Ownership: |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 41 | /// * function doesn't take ownership of (in other words it borrows) the |
| 42 | /// param `json` |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 43 | /// * function passes ownership of the returned value to the caller |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 44 | #[no_mangle] |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 45 | pub unsafe extern "C" fn GenerateBindingsImpl(json: FfiU8Slice) -> FfiBindings { |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 46 | catch_unwind(|| { |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 47 | // It is ok to abort here. |
| 48 | let Bindings { rs_api, rs_api_impl } = generate_bindings(json.as_slice()).unwrap(); |
| 49 | |
| 50 | FfiBindings { |
| 51 | rs_api: FfiU8SliceBox::from_boxed_slice(rs_api.into_bytes().into_boxed_slice()), |
| 52 | rs_api_impl: FfiU8SliceBox::from_boxed_slice( |
| 53 | rs_api_impl.into_bytes().into_boxed_slice(), |
| 54 | ), |
| 55 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 56 | }) |
| 57 | .unwrap_or_else(|_| process::abort()) |
| 58 | } |
| 59 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 60 | /// Source code for generated bindings. |
| 61 | struct Bindings { |
| 62 | // Rust source code. |
| 63 | rs_api: String, |
| 64 | // C++ source code. |
| 65 | rs_api_impl: String, |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 66 | } |
| 67 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 68 | fn generate_bindings(json: &[u8]) -> Result<Bindings> { |
| 69 | let ir = deserialize_ir(json)?; |
Marcel Hlopko | ca84ff4 | 2021-12-09 14:15:14 +0000 | [diff] [blame] | 70 | |
| 71 | // The code is formatted with a non-default rustfmt configuration. Prevent |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 72 | // downstream workflows from reformatting with a different configuration by |
| 73 | // marking the output with `@generated`. See also |
| 74 | // https://rust-lang.github.io/rustfmt/?version=v1.4.38&search=#format_generated_files |
| 75 | // |
| 76 | // TODO(lukasza): It would be nice to include "by $argv[0]"" in the |
| 77 | // @generated comment below. OTOH, `std::env::current_exe()` in our |
| 78 | // current build environment returns a guid-like path... :-/ |
Lukasz Anforowicz | 72c4d22 | 2022-02-18 19:07:28 +0000 | [diff] [blame] | 79 | // |
| 80 | // TODO(lukasza): Try to remove `#![rustfmt:skip]` - in theory it shouldn't |
| 81 | // be needed when `@generated` comment/keyword is present... |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 82 | let rs_api = format!( |
Lukasz Anforowicz | 72c4d22 | 2022-02-18 19:07:28 +0000 | [diff] [blame] | 83 | "// Automatically @generated Rust bindings for C++ target\n\ |
| 84 | // {target}\n\ |
| 85 | #![rustfmt::skip]\n\ |
| 86 | {code}", |
Lukasz Anforowicz | 5b3f530 | 2022-02-07 01:04:47 +0000 | [diff] [blame] | 87 | target = ir.current_target().0, |
| 88 | code = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)? |
| 89 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 90 | let rs_api_impl = tokens_to_string(generate_rs_api_impl(&ir)?)?; |
Marcel Hlopko | ca84ff4 | 2021-12-09 14:15:14 +0000 | [diff] [blame] | 91 | |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 92 | Ok(Bindings { rs_api, rs_api_impl }) |
| 93 | } |
| 94 | |
Devin Jeanpierre | 6d5e7cc | 2021-10-21 12:56:07 +0000 | [diff] [blame] | 95 | /// Rust source code with attached information about how to modify the parent |
| 96 | /// crate. |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 97 | /// |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 98 | /// For example, the snippet `vec![].into_raw_parts()` is not valid unless the |
| 99 | /// `vec_into_raw_parts` feature is enabled. So such a snippet should be |
| 100 | /// represented as: |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 101 | /// |
| 102 | /// ``` |
| 103 | /// RsSnippet { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 104 | /// features: btree_set![make_rs_ident("vec_into_raw_parts")], |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 105 | /// tokens: quote!{vec![].into_raw_parts()}, |
| 106 | /// } |
| 107 | /// ``` |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 108 | #[derive(Clone, Debug)] |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 109 | struct RsSnippet { |
| 110 | /// Rust feature flags used by this snippet. |
| 111 | features: BTreeSet<Ident>, |
| 112 | /// The snippet itself, as a token stream. |
| 113 | tokens: TokenStream, |
| 114 | } |
| 115 | |
| 116 | impl From<TokenStream> for RsSnippet { |
| 117 | fn from(tokens: TokenStream) -> Self { |
| 118 | RsSnippet { features: BTreeSet::new(), tokens } |
| 119 | } |
| 120 | } |
| 121 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 122 | /// If we know the original C++ function is codegenned and already compatible |
| 123 | /// with `extern "C"` calling convention we skip creating/calling the C++ thunk |
| 124 | /// since we can call the original C++ directly. |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 125 | fn can_skip_cc_thunk(func: &Func) -> bool { |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 126 | // ## Inline functions |
| 127 | // |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 128 | // Inline functions may not be codegenned in the C++ library since Clang doesn't |
| 129 | // know if Rust calls the function or not. Therefore in order to make inline |
| 130 | // functions callable from Rust we need to generate a C++ file that defines |
| 131 | // a thunk that delegates to the original inline function. When compiled, |
| 132 | // 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] | 133 | // thunk when the user wants to call the original inline function. |
| 134 | // |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 135 | // This is not great runtime-performance-wise in regular builds (inline function |
| 136 | // will not be inlined, there will always be a function call), but it is |
| 137 | // correct. ThinLTO builds will be able to see through the thunk and inline |
| 138 | // code across the language boundary. For non-ThinLTO builds we plan to |
| 139 | // implement <internal link> which removes the runtime performance overhead. |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 140 | if func.is_inline { |
| 141 | return false; |
| 142 | } |
| 143 | // ## Virtual functions |
| 144 | // |
| 145 | // When calling virtual `A::Method()`, it's not necessarily the case that we'll |
| 146 | // specifically call the concrete `A::Method` impl. For example, if this is |
| 147 | // called on something whose dynamic type is some subclass `B` with an |
| 148 | // overridden `B::Method`, then we'll call that. |
| 149 | // |
| 150 | // We must reuse the C++ dynamic dispatching system. In this case, the easiest |
| 151 | // way to do it is by resorting to a C++ thunk, whose implementation will do |
| 152 | // the lookup. |
| 153 | // |
| 154 | // In terms of runtime performance, since this only occurs for virtual function |
| 155 | // calls, which are already slow, it may not be such a big deal. We can |
| 156 | // benchmark it later. :) |
| 157 | if let Some(meta) = &func.member_func_metadata { |
| 158 | if let Some(inst_meta) = &meta.instance_method_metadata { |
| 159 | if inst_meta.is_virtual { |
| 160 | return false; |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | true |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 166 | } |
| 167 | |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 168 | /// Uniquely identifies a generated Rust function. |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 169 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 170 | struct FunctionId { |
| 171 | // If the function is on a trait impl, contains the name of the Self type for |
| 172 | // which the trait is being implemented. |
| 173 | self_type: Option<syn::Path>, |
| 174 | // Fully qualified path of the function. For functions in impl blocks, this |
| 175 | // includes the name of the type or trait on which the function is being |
| 176 | // implemented, e.g. `Default::default`. |
| 177 | function_path: syn::Path, |
| 178 | } |
| 179 | |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 180 | /// Returns the name of `func` in C++ syntax. |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 181 | fn cxx_function_name(func: &Func, ir: &IR) -> Result<String> { |
| 182 | let record: Option<&str> = func |
| 183 | .member_func_metadata |
| 184 | .as_ref() |
| 185 | .map(|meta| meta.find_record(ir)) |
| 186 | .transpose()? |
| 187 | .map(|r| &*r.identifier.identifier); |
| 188 | |
| 189 | let func_name = match &func.name { |
| 190 | UnqualifiedIdentifier::Identifier(id) => id.identifier.clone(), |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 191 | UnqualifiedIdentifier::Operator(op) => op.cc_name(), |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 192 | UnqualifiedIdentifier::Destructor => { |
| 193 | format!("~{}", record.expect("destructor must be associated with a record")) |
| 194 | } |
| 195 | UnqualifiedIdentifier::Constructor => { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 196 | record.expect("constructor must be associated with a record").to_string() |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 197 | } |
| 198 | }; |
| 199 | |
| 200 | if let Some(record_name) = record { |
| 201 | Ok(format!("{}::{}", record_name, func_name)) |
| 202 | } else { |
| 203 | Ok(func_name) |
| 204 | } |
| 205 | } |
| 206 | |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 207 | fn make_unsupported_fn(func: &Func, ir: &IR, message: impl ToString) -> Result<UnsupportedItem> { |
| 208 | Ok(UnsupportedItem { |
| 209 | name: cxx_function_name(func, ir)?, |
| 210 | message: message.to_string(), |
| 211 | source_loc: func.source_loc.clone(), |
| 212 | }) |
| 213 | } |
| 214 | |
| 215 | #[derive(Clone, Debug)] |
| 216 | enum GeneratedFunc { |
| 217 | None, // No explicit function needed (e.g. when deriving Drop). |
| 218 | Unsupported(UnsupportedItem), |
| 219 | Some { api_func: RsSnippet, thunk: RsSnippet, function_id: FunctionId }, |
| 220 | } |
| 221 | |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 222 | /// Generates Rust source code for a given `Func`. |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 223 | fn generate_func(func: &Func, ir: &IR) -> Result<GeneratedFunc> { |
| 224 | let make_unsupported_result = |msg: &str| -> Result<GeneratedFunc> { |
| 225 | Ok(GeneratedFunc::Unsupported(make_unsupported_fn(func, ir, msg)?)) |
| 226 | }; |
| 227 | |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 228 | let mangled_name = &func.mangled_name; |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 229 | let thunk_ident = thunk_ident(func); |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 230 | let doc_comment = generate_doc_comment(&func.doc_comment); |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 231 | let lifetime_to_name = HashMap::<LifetimeId, String>::from_iter( |
| 232 | func.lifetime_params.iter().map(|l| (l.id, l.name.clone())), |
| 233 | ); |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 234 | let return_type_fragment = RsTypeKind::new(&func.return_type.rs_type, ir) |
| 235 | .and_then(|t| t.format_as_return_type_fragment(ir, &lifetime_to_name)) |
Googler | b7e361d | 2022-01-04 14:02:59 +0000 | [diff] [blame] | 236 | .with_context(|| format!("Failed to format return type for {:?}", func))?; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 237 | |
| 238 | let param_idents = |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 239 | func.params.iter().map(|p| make_rs_ident(&p.identifier.identifier)).collect_vec(); |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 240 | |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 241 | let param_type_kinds = func |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 242 | .params |
| 243 | .iter() |
Googler | b7e361d | 2022-01-04 14:02:59 +0000 | [diff] [blame] | 244 | .map(|p| { |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 245 | RsTypeKind::new(&p.type_.rs_type, ir).with_context(|| { |
| 246 | format!("Failed to process type of parameter {:?} on {:?}", p, func) |
Googler | b7e361d | 2022-01-04 14:02:59 +0000 | [diff] [blame] | 247 | }) |
| 248 | }) |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 249 | .collect::<Result<Vec<_>>>()?; |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 250 | let param_types = param_type_kinds |
| 251 | .iter() |
| 252 | .map(|t| { |
| 253 | t.format(ir, &lifetime_to_name) |
| 254 | .with_context(|| format!("Failed to format parameter type {:?} on {:?}", t, func)) |
| 255 | }) |
| 256 | .collect::<Result<Vec<_>>>()?; |
Devin Jeanpierre | 55298ac | 2022-02-24 01:37:37 +0000 | [diff] [blame] | 257 | let is_unsafe = param_type_kinds.iter().any(|p| matches!(p, RsTypeKind::Pointer { .. })) |
| 258 | && func.name != UnqualifiedIdentifier::Destructor; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 259 | |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 260 | let maybe_record: Option<&Record> = |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 261 | func.member_func_metadata.as_ref().map(|meta| meta.find_record(ir)).transpose()?; |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 262 | let maybe_record_name = maybe_record.map(|r| make_rs_ident(&r.identifier.identifier)); |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 263 | |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 264 | // Find 1) the `func_name` and `impl_kind` of the API function to generate |
| 265 | // and 2) whether to `format_first_param_as_self` (`&self` or `&mut self`). |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 266 | enum ImplKind { |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 267 | None, // No `impl` needed |
| 268 | Struct, // e.g. `impl SomeStruct { ... }` (SomeStruct based on func.member_func_metadata) |
| 269 | Trait { |
| 270 | trait_name: TokenStream, // e.g. quote!{ From<int> } |
| 271 | record_name: Ident, /* e.g. SomeStruct (might *not* be from |
| 272 | * func.member_func_metadata) */ |
| 273 | }, |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 274 | } |
| 275 | let impl_kind: ImplKind; |
| 276 | let func_name: syn::Ident; |
| 277 | let format_first_param_as_self: bool; |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 278 | match &func.name { |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 279 | UnqualifiedIdentifier::Operator(op) if op.name == "==" => { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 280 | if param_type_kinds.len() != 2 { |
| 281 | bail!("Unexpected number of parameters in operator==: {:?}", func); |
| 282 | } |
| 283 | match (¶m_type_kinds[0], ¶m_type_kinds[1]) { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 284 | ( |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 285 | RsTypeKind::Reference { referent: lhs, mutability: Mutability::Const, .. }, |
| 286 | RsTypeKind::Reference { referent: rhs, mutability: Mutability::Const, .. }, |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 287 | ) => match **lhs { |
| 288 | RsTypeKind::Record(lhs_record) => { |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 289 | let lhs: Ident = make_rs_ident(&lhs_record.identifier.identifier); |
| 290 | let rhs: TokenStream = rhs.format(ir, &lifetime_to_name)?; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 291 | format_first_param_as_self = true; |
| 292 | func_name = make_rs_ident("eq"); |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 293 | impl_kind = ImplKind::Trait { |
| 294 | trait_name: quote! {PartialEq<#rhs>}, |
| 295 | record_name: lhs, |
| 296 | }; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 297 | } |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 298 | _ => { |
| 299 | return make_unsupported_result( |
| 300 | "operator== where lhs doesn't refer to a record", |
| 301 | ); |
| 302 | } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 303 | }, |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 304 | _ => { |
| 305 | return make_unsupported_result( |
| 306 | "operator== where operands are not const references", |
| 307 | ); |
| 308 | } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 309 | }; |
| 310 | } |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 311 | UnqualifiedIdentifier::Operator(_) => { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 312 | return make_unsupported_result("Bindings for this kind of operator are not supported"); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 313 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 314 | UnqualifiedIdentifier::Identifier(id) => { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 315 | func_name = make_rs_ident(&id.identifier); |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 316 | match maybe_record { |
| 317 | None => { |
| 318 | impl_kind = ImplKind::None; |
| 319 | format_first_param_as_self = false; |
| 320 | } |
| 321 | Some(record) => { |
| 322 | impl_kind = ImplKind::Struct; |
| 323 | if func.is_instance_method() { |
| 324 | let first_param = param_type_kinds.first().ok_or_else(|| { |
| 325 | anyhow!("Missing `__this` parameter in an instance method: {:?}", func) |
| 326 | })?; |
| 327 | format_first_param_as_self = first_param.is_ref_to(record) |
| 328 | } else { |
| 329 | format_first_param_as_self = false; |
| 330 | } |
| 331 | } |
| 332 | }; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 333 | } |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 334 | UnqualifiedIdentifier::Destructor => { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 335 | // Note: to avoid double-destruction of the fields, they are all wrapped in |
| 336 | // ManuallyDrop in this case. See `generate_record`. |
| 337 | let record = |
| 338 | maybe_record.ok_or_else(|| anyhow!("Destructors must be member functions."))?; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 339 | if !should_implement_drop(record) { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 340 | return Ok(GeneratedFunc::None); |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 341 | } |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 342 | let record_name = maybe_record_name |
| 343 | .clone() |
| 344 | .ok_or_else(|| anyhow!("Destructors must be member functions."))?; |
| 345 | impl_kind = ImplKind::Trait { trait_name: quote! {Drop}, record_name }; |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 346 | func_name = make_rs_ident("drop"); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 347 | format_first_param_as_self = true; |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 348 | } |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 349 | UnqualifiedIdentifier::Constructor => { |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 350 | let member_func_metadata = func |
| 351 | .member_func_metadata |
| 352 | .as_ref() |
| 353 | .ok_or_else(|| anyhow!("Constructors must be member functions."))?; |
| 354 | let record = maybe_record |
| 355 | .ok_or_else(|| anyhow!("Constructors must be associated with a record."))?; |
| 356 | let instance_method_metadata = |
| 357 | member_func_metadata |
| 358 | .instance_method_metadata |
| 359 | .as_ref() |
| 360 | .ok_or_else(|| anyhow!("Constructors must be instance methods."))?; |
| 361 | |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 362 | if !record.is_unpin() { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 363 | // TODO: Handle <internal link> |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 364 | return make_unsupported_result( |
| 365 | "Bindings for constructors of non-trivial types are not supported yet", |
| 366 | ); |
Lukasz Anforowicz | 9bab835 | 2021-12-22 17:35:31 +0000 | [diff] [blame] | 367 | } |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 368 | if is_unsafe { |
| 369 | // TODO(b/216648347): Allow this outside of traits (e.g. after supporting |
| 370 | // translating C++ constructors into static methods in Rust). |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 371 | return make_unsupported_result( |
| 372 | "Unsafe constructors (e.g. with no elided or explicit lifetimes) \ |
| 373 | are intentionally not supported", |
| 374 | ); |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 375 | } |
| 376 | |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 377 | let record_name = maybe_record_name |
| 378 | .clone() |
| 379 | .ok_or_else(|| anyhow!("Constructors must be member functions."))?; |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 380 | match func.params.len() { |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 381 | 0 => bail!("Missing `__this` parameter in a constructor: {:?}", func), |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 382 | 1 => { |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 383 | impl_kind = ImplKind::Trait { trait_name: quote! {Default}, record_name }; |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 384 | func_name = make_rs_ident("default"); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 385 | format_first_param_as_self = false; |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 386 | } |
Lukasz Anforowicz | 73326af | 2022-01-05 01:13:10 +0000 | [diff] [blame] | 387 | 2 => { |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 388 | // TODO(lukasza): Do something smart with move constructor. |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 389 | if param_type_kinds[1].is_shared_ref_to(record) { |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 390 | // Copy constructor |
| 391 | if should_derive_clone(record) { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 392 | return Ok(GeneratedFunc::None); |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 393 | } else { |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 394 | impl_kind = ImplKind::Trait { trait_name: quote! {Clone}, record_name }; |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 395 | func_name = make_rs_ident("clone"); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 396 | format_first_param_as_self = true; |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 397 | } |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 398 | } else if !instance_method_metadata.is_explicit_ctor { |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 399 | let param_type = ¶m_types[1]; |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 400 | impl_kind = ImplKind::Trait { |
| 401 | trait_name: quote! {From< #param_type >}, |
| 402 | record_name, |
| 403 | }; |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 404 | func_name = make_rs_ident("from"); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 405 | format_first_param_as_self = false; |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 406 | } else { |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 407 | return make_unsupported_result( |
| 408 | "Not yet supported type of constructor parameter", |
| 409 | ); |
Lukasz Anforowicz | 73326af | 2022-01-05 01:13:10 +0000 | [diff] [blame] | 410 | } |
| 411 | } |
| 412 | _ => { |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 413 | // TODO(b/216648347): Support bindings for other constructors. |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 414 | return make_unsupported_result( |
| 415 | "More than 1 constructor parameter is not supported yet", |
| 416 | ); |
Lukasz Anforowicz | 73326af | 2022-01-05 01:13:10 +0000 | [diff] [blame] | 417 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 418 | } |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | let api_func_def = { |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 423 | // Clone params, return type, etc - we may need to mutate them in the |
| 424 | // API func, but we want to retain the originals for the thunk. |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 425 | let mut return_type_fragment = return_type_fragment.clone(); |
| 426 | let mut thunk_args = param_idents.iter().map(|id| quote! { #id}).collect_vec(); |
| 427 | let mut api_params = param_idents |
| 428 | .iter() |
| 429 | .zip(param_types.iter()) |
| 430 | .map(|(ident, type_)| quote! { #ident : #type_ }) |
| 431 | .collect_vec(); |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 432 | let mut lifetimes = func.lifetime_params.iter().collect_vec(); |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 433 | let mut maybe_first_api_param = param_type_kinds.get(0); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 434 | |
| 435 | if func.name == UnqualifiedIdentifier::Constructor { |
| 436 | return_type_fragment = quote! { -> Self }; |
| 437 | |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 438 | // Drop `__this` parameter from the public Rust API. Presence of |
| 439 | // element #0 is indirectly verified by a `Constructor`-related |
| 440 | // `match` branch a little bit above. |
| 441 | api_params.remove(0); |
| 442 | thunk_args.remove(0); |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 443 | |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 444 | // Remove the lifetime associated with `__this`. |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 445 | ensure!(func.return_type.rs_type.is_unit_type(), |
| 446 | "Unexpectedly non-void return type of a constructor: {:?}", func); |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 447 | 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] | 448 | let no_longer_needed_lifetime_id = maybe_first_lifetime |
| 449 | .ok_or_else(|| anyhow!("Missing lifetime on `__this` parameter: {:?}", func))?; |
| 450 | lifetimes.retain(|l| l.id != *no_longer_needed_lifetime_id); |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 451 | if let Some(type_still_dependent_on_removed_lifetime) = param_type_kinds |
| 452 | .iter() |
| 453 | .skip(1) // Skipping `__this` |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 454 | .flat_map(|t| t.lifetimes()) |
| 455 | .find(|lifetime_id| *lifetime_id == *no_longer_needed_lifetime_id) |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 456 | { |
| 457 | bail!( |
| 458 | "The lifetime of `__this` is unexpectedly also used by another \ |
| 459 | parameter {:?} in function {:?}", |
| 460 | type_still_dependent_on_removed_lifetime, |
| 461 | func.name |
| 462 | ); |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 463 | } |
| 464 | |
| 465 | // Rebind `maybe_first_api_param` to the next param after `__this`. |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 466 | maybe_first_api_param = param_type_kinds.get(1); |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 467 | } |
| 468 | |
| 469 | // Change `__this: &'a SomeStruct` into `&'a self` if needed. |
| 470 | if format_first_param_as_self { |
| 471 | let first_api_param = maybe_first_api_param |
| 472 | .ok_or_else(|| anyhow!("No parameter to format as 'self': {:?}", func))?; |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 473 | let self_decl = |
| 474 | first_api_param.format_as_self_param(func, ir, &lifetime_to_name).with_context( |
| 475 | || format!("Failed to format as `self` param: {:?}", first_api_param), |
| 476 | )?; |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 477 | // Presence of element #0 is verified by `ok_or_else` on |
| 478 | // `maybe_first_api_param` above. |
| 479 | api_params[0] = self_decl; |
| 480 | thunk_args[0] = quote! { self }; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 481 | } |
| 482 | |
| 483 | let func_body = match &func.name { |
Devin Jeanpierre | 55298ac | 2022-02-24 01:37:37 +0000 | [diff] [blame] | 484 | UnqualifiedIdentifier::Identifier(_) | UnqualifiedIdentifier::Operator(_) | UnqualifiedIdentifier::Destructor => { |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 485 | let mut body = quote! { crate::detail::#thunk_ident( #( #thunk_args ),* ) }; |
| 486 | // Only need to wrap everything in an `unsafe { ... }` block if |
| 487 | // the *whole* api function is safe. |
| 488 | if !is_unsafe { |
| 489 | body = quote! { unsafe { #body } }; |
| 490 | } |
| 491 | body |
| 492 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 493 | UnqualifiedIdentifier::Constructor => { |
| 494 | // SAFETY: A user-defined constructor is not guaranteed to |
| 495 | // initialize all the fields. To make the `assume_init()` call |
| 496 | // below safe, the memory is zero-initialized first. This is a |
| 497 | // bit safer, because zero-initialized memory represents a valid |
| 498 | // value for the currently supported field types (this may |
| 499 | // change once the bindings generator starts supporting |
| 500 | // reference fields). TODO(b/213243309): Double-check if |
| 501 | // zero-initialization is desirable here. |
| 502 | quote! { |
| 503 | let mut tmp = std::mem::MaybeUninit::<Self>::zeroed(); |
| 504 | unsafe { |
| 505 | crate::detail::#thunk_ident( &mut tmp #( , #thunk_args )* ); |
| 506 | tmp.assume_init() |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 507 | } |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 508 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 509 | } |
| 510 | }; |
| 511 | |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 512 | let (pub_, unsafe_) = match impl_kind { |
| 513 | ImplKind::None | ImplKind::Struct => ( |
| 514 | quote! { pub }, |
| 515 | if is_unsafe { |
| 516 | quote! {unsafe} |
| 517 | } else { |
| 518 | quote! {} |
| 519 | }, |
| 520 | ), |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 521 | ImplKind::Trait { .. } => { |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 522 | // Currently supported bindings have no unsafe trait functions. |
Devin Jeanpierre | 55298ac | 2022-02-24 01:37:37 +0000 | [diff] [blame] | 523 | assert!(!is_unsafe); |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 524 | (quote! {}, quote! {}) |
| 525 | } |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 526 | }; |
| 527 | |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 528 | let lifetimes = lifetimes.into_iter().map(|l| format_lifetime_name(&l.name)); |
| 529 | let generic_params = format_generic_params(lifetimes); |
| 530 | |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 531 | quote! { |
| 532 | #[inline(always)] |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 533 | #pub_ #unsafe_ fn #func_name #generic_params( #( #api_params ),* ) #return_type_fragment { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 534 | #func_body |
| 535 | } |
Lukasz Anforowicz | 13cf749 | 2021-12-22 15:29:52 +0000 | [diff] [blame] | 536 | } |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 537 | }; |
| 538 | |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 539 | let api_func: TokenStream; |
| 540 | let function_id: FunctionId; |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 541 | match impl_kind { |
| 542 | ImplKind::None => { |
| 543 | api_func = quote! { #doc_comment #api_func_def }; |
| 544 | function_id = FunctionId { self_type: None, function_path: func_name.into() }; |
| 545 | } |
| 546 | ImplKind::Struct => { |
| 547 | let record_name = |
| 548 | maybe_record_name.ok_or_else(|| anyhow!("Struct methods must have records"))?; |
| 549 | api_func = quote! { impl #record_name { #doc_comment #api_func_def } }; |
| 550 | function_id = FunctionId { |
| 551 | self_type: None, |
| 552 | function_path: syn::parse2(quote! { #record_name :: #func_name })?, |
| 553 | }; |
| 554 | } |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 555 | ImplKind::Trait { trait_name, record_name } => { |
Lukasz Anforowicz | ab65e29 | 2022-01-14 23:04:21 +0000 | [diff] [blame] | 556 | api_func = quote! { #doc_comment impl #trait_name for #record_name { #api_func_def } }; |
| 557 | function_id = FunctionId { |
| 558 | self_type: Some(record_name.into()), |
| 559 | function_path: syn::parse2(quote! { #trait_name :: #func_name })?, |
| 560 | }; |
| 561 | } |
| 562 | } |
| 563 | |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 564 | let thunk = { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 565 | let thunk_attr = if can_skip_cc_thunk(func) { |
| 566 | quote! {#[link_name = #mangled_name]} |
| 567 | } else { |
| 568 | quote! {} |
| 569 | }; |
| 570 | |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 571 | // For constructors inject MaybeUninit into the type of `__this_` parameter. |
| 572 | let mut param_types = param_types; |
| 573 | if func.name == UnqualifiedIdentifier::Constructor { |
| 574 | if param_types.is_empty() || func.params.is_empty() { |
| 575 | bail!("Constructors should have at least one parameter (__this)"); |
| 576 | } |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 577 | param_types[0] = param_type_kinds[0] |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 578 | .format_mut_ref_as_uninitialized(ir, &lifetime_to_name) |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 579 | .with_context(|| { |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 580 | format!("Failed to format `__this` param for a constructor thunk: {:?}", func.params[0]) |
| 581 | })?; |
| 582 | } else if func.name == UnqualifiedIdentifier::Destructor { |
| 583 | if param_types.is_empty() || func.params.is_empty() { |
| 584 | bail!("Destructors should have at least one parameter (__this)"); |
| 585 | } |
| 586 | param_types[0] = param_type_kinds[0] |
| 587 | .format_ref_as_raw_ptr(ir, &lifetime_to_name) |
| 588 | .with_context(|| { |
| 589 | format!("Failed to format `__this` param for a destructor thunk: {:?}", func.params[0]) |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 590 | })?; |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 591 | } |
| 592 | |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 593 | let lifetimes = func.lifetime_params.iter().map(|l| format_lifetime_name(&l.name)); |
| 594 | let generic_params = format_generic_params(lifetimes); |
| 595 | |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 596 | quote! { |
| 597 | #thunk_attr |
Lukasz Anforowicz | 4ad012b | 2021-12-15 18:13:40 +0000 | [diff] [blame] | 598 | pub(crate) fn #thunk_ident #generic_params( #( #param_idents: #param_types ),* |
| 599 | ) #return_type_fragment ; |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 600 | } |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 601 | }; |
| 602 | |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 603 | Ok(GeneratedFunc::Some { api_func: api_func.into(), thunk: thunk.into(), function_id }) |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 604 | } |
| 605 | |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 606 | fn generate_doc_comment(comment: &Option<String>) -> TokenStream { |
| 607 | match comment { |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 608 | Some(text) => { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 609 | // token_stream_printer (and rustfmt) don't put a space between /// and the doc |
| 610 | // comment, let's add it here so our comments are pretty. |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 611 | let doc = format!(" {}", text.replace('\n', "\n ")); |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 612 | quote! {#[doc=#doc]} |
| 613 | } |
| 614 | None => quote! {}, |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 615 | } |
| 616 | } |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 617 | |
| 618 | fn format_generic_params<T: quote::ToTokens>(params: impl IntoIterator<Item = T>) -> TokenStream { |
| 619 | let mut params = params.into_iter().peekable(); |
| 620 | if params.peek().is_none() { |
| 621 | quote! {} |
| 622 | } else { |
| 623 | quote! { < #( #params ),* > } |
| 624 | } |
| 625 | } |
| 626 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 627 | fn should_implement_drop(record: &Record) -> bool { |
| 628 | match record.destructor.definition { |
| 629 | // TODO(b/202258760): Only omit destructor if `Copy` is specified. |
| 630 | SpecialMemberDefinition::Trivial => false, |
| 631 | |
| 632 | // TODO(b/212690698): Avoid calling into the C++ destructor (e.g. let |
| 633 | // Rust drive `drop`-ing) to avoid (somewhat unergonomic) ManuallyDrop |
| 634 | // if we can ask Rust to preserve C++ field destruction order in |
| 635 | // NontrivialMembers case. |
| 636 | SpecialMemberDefinition::NontrivialMembers => true, |
| 637 | |
| 638 | // The `impl Drop` for NontrivialUserDefined needs to call into the |
| 639 | // user-defined destructor on C++ side. |
| 640 | SpecialMemberDefinition::NontrivialUserDefined => true, |
| 641 | |
| 642 | // TODO(b/213516512): Today the IR doesn't contain Func entries for |
| 643 | // deleted functions/destructors/etc. But, maybe we should generate |
| 644 | // `impl Drop` in this case? With `unreachable!`? With |
| 645 | // `std::mem::forget`? |
| 646 | SpecialMemberDefinition::Deleted => false, |
| 647 | } |
| 648 | } |
| 649 | |
| 650 | /// Returns whether fields of type `ty` need to be wrapped in `ManuallyDrop<T>` |
| 651 | /// to prevent the fields from being destructed twice (once by the C++ |
| 652 | /// destructor calkled from the `impl Drop` of the struct and once by `drop` on |
| 653 | /// the Rust side). |
| 654 | /// |
| 655 | /// A type is safe to destroy twice if it implements `Copy`. Fields of such |
| 656 | /// don't need to be wrapped in `ManuallyDrop<T>` even if the struct |
| 657 | /// containing the fields provides an `impl Drop` that calles into a C++ |
| 658 | /// destructor (in addition to dropping the fields on the Rust side). |
| 659 | /// |
| 660 | /// Note that it is not enough to just be `!needs_drop<T>()`: Rust only |
| 661 | /// guarantees that it is safe to use-after-destroy for `Copy` types. See |
| 662 | /// e.g. the documentation for |
| 663 | /// [`drop_in_place`](https://doc.rust-lang.org/std/ptr/fn.drop_in_place.html): |
| 664 | /// |
| 665 | /// > if `T` is not `Copy`, using the pointed-to value after calling |
| 666 | /// > `drop_in_place` can cause undefined behavior |
| 667 | fn needs_manually_drop(ty: &ir::RsType, ir: &IR) -> Result<bool> { |
| 668 | let ty_implements_copy = RsTypeKind::new(ty, ir)?.implements_copy(); |
| 669 | Ok(!ty_implements_copy) |
| 670 | } |
| 671 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 672 | /// Generates Rust source code for a given `Record` and associated assertions as |
| 673 | /// a tuple. |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 674 | fn generate_record(record: &Record, ir: &IR) -> Result<(RsSnippet, RsSnippet)> { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 675 | let ident = make_rs_ident(&record.identifier.identifier); |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 676 | let doc_comment = generate_doc_comment(&record.doc_comment); |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 677 | let field_idents = |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 678 | record.fields.iter().map(|f| make_rs_ident(&f.identifier.identifier)).collect_vec(); |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 679 | let field_doc_coments = |
| 680 | record.fields.iter().map(|f| generate_doc_comment(&f.doc_comment)).collect_vec(); |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 681 | let field_types = record |
| 682 | .fields |
| 683 | .iter() |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 684 | .enumerate() |
| 685 | .map(|(i, f)| { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 686 | // [[no_unique_address]] fields are replaced by an unaligned block of memory |
| 687 | // which fills space up to the next field. |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 688 | // See: docs/struct_layout |
| 689 | if f.is_no_unique_address { |
| 690 | let next_offset = if let Some(next) = record.fields.get(i + 1) { |
| 691 | next.offset |
| 692 | } else { |
| 693 | record.size * 8 |
| 694 | }; |
| 695 | let width = Literal::usize_unsuffixed((next_offset - f.offset) / 8); |
| 696 | return Ok(quote! {[std::mem::MaybeUninit<u8>; #width]}); |
| 697 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 698 | let mut formatted = format_rs_type(&f.type_.rs_type, ir, &HashMap::new()) |
| 699 | .with_context(|| { |
Googler | b7e361d | 2022-01-04 14:02:59 +0000 | [diff] [blame] | 700 | format!("Failed to format type for field {:?} on record {:?}", f, record) |
| 701 | })?; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 702 | // TODO(b/212696226): Verify cases where ManuallyDrop<T> is skipped |
| 703 | // via static asserts in the generated code. |
| 704 | if should_implement_drop(record) && needs_manually_drop(&f.type_.rs_type, ir)? { |
| 705 | // TODO(b/212690698): Avoid (somewhat unergonomic) ManuallyDrop |
| 706 | // if we can ask Rust to preserve field destruction order if the |
| 707 | // destructor is the SpecialMemberDefinition::NontrivialMembers |
| 708 | // case. |
| 709 | formatted = quote! { std::mem::ManuallyDrop<#formatted> } |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 710 | }; |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 711 | Ok(formatted) |
| 712 | }) |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 713 | .collect::<Result<Vec<_>>>()?; |
Googler | ec589eb | 2021-09-17 07:45:39 +0000 | [diff] [blame] | 714 | let field_accesses = record |
| 715 | .fields |
| 716 | .iter() |
| 717 | .map(|f| { |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 718 | if f.access == AccessSpecifier::Public && !f.is_no_unique_address { |
Googler | ec589eb | 2021-09-17 07:45:39 +0000 | [diff] [blame] | 719 | quote! { pub } |
| 720 | } else { |
| 721 | quote! {} |
| 722 | } |
| 723 | }) |
| 724 | .collect_vec(); |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 725 | let size = record.size; |
| 726 | let alignment = record.alignment; |
Googler | aaa0a53 | 2021-10-01 09:11:27 +0000 | [diff] [blame] | 727 | let field_assertions = |
| 728 | record.fields.iter().zip(field_idents.iter()).map(|(field, field_ident)| { |
| 729 | let offset = field.offset; |
| 730 | quote! { |
| 731 | // The IR contains the offset in bits, while offset_of!() |
| 732 | // returns the offset in bytes, so we need to convert. |
Googler | 209b10a | 2021-12-06 09:11:57 +0000 | [diff] [blame] | 733 | const _: () = assert!(offset_of!(#ident, #field_ident) * 8 == #offset); |
Googler | aaa0a53 | 2021-10-01 09:11:27 +0000 | [diff] [blame] | 734 | } |
| 735 | }); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 736 | let mut record_features = BTreeSet::new(); |
| 737 | let mut assertion_features = BTreeSet::new(); |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 738 | |
| 739 | // TODO(mboehme): For the time being, we're using unstable features to |
| 740 | // be able to use offset_of!() in static assertions. This is fine for a |
| 741 | // prototype, but longer-term we want to either get those features |
| 742 | // stabilized or find an alternative. For more details, see |
| 743 | // b/200120034#comment15 |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 744 | assertion_features.insert(make_rs_ident("const_ptr_offset_from")); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 745 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 746 | let derives = generate_derives(record); |
Devin Jeanpierre | 9227d2c | 2021-10-06 12:26:05 +0000 | [diff] [blame] | 747 | let derives = if derives.is_empty() { |
| 748 | quote! {} |
| 749 | } else { |
| 750 | quote! {#[derive( #(#derives),* )]} |
| 751 | }; |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 752 | let unpin_impl = if record.is_unpin() { |
| 753 | quote! {} |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 754 | } else { |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 755 | // negative_impls are necessary for universal initialization due to Rust's |
| 756 | // coherence rules: PhantomPinned isn't enough to prove to Rust that a |
| 757 | // 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] | 758 | record_features.insert(make_rs_ident("negative_impls")); |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 759 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 760 | __NEWLINE__ __NEWLINE__ |
| 761 | impl !Unpin for #ident {} |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 762 | } |
| 763 | }; |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 764 | |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 765 | let mut repr_attributes = vec![quote! {C}]; |
| 766 | if record.override_alignment && record.alignment > 1 { |
| 767 | let alignment = Literal::usize_unsuffixed(record.alignment); |
| 768 | repr_attributes.push(quote! {align(#alignment)}); |
| 769 | } |
| 770 | |
| 771 | // Adjust the struct to also include base class subobjects. We use an opaque |
| 772 | // field because subobjects can live in the alignment of base class |
| 773 | // subobjects. |
| 774 | let base_subobjects_field = if let Some(base_size) = record.base_size { |
| 775 | let n = proc_macro2::Literal::usize_unsuffixed(base_size); |
| 776 | quote! { |
| 777 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; #n], |
| 778 | } |
| 779 | } else { |
| 780 | quote! {} |
| 781 | }; |
| 782 | |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 783 | let empty_struct_placeholder_field = |
| 784 | if record.fields.is_empty() && record.base_size.unwrap_or(0) == 0 { |
| 785 | quote! { |
| 786 | /// Prevent empty C++ struct being zero-size in Rust. |
| 787 | placeholder: std::mem::MaybeUninit<u8>, |
| 788 | } |
| 789 | } else { |
| 790 | quote! {} |
| 791 | }; |
Googler | f479206 | 2021-10-20 07:21:21 +0000 | [diff] [blame] | 792 | |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 793 | let no_unique_address_accessors = cc_struct_no_unique_address_impl(record, ir)?; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 794 | let base_class_into = cc_struct_upcast_impl(record, ir)?; |
| 795 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 796 | let record_tokens = quote! { |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 797 | #doc_comment |
Devin Jeanpierre | 9227d2c | 2021-10-06 12:26:05 +0000 | [diff] [blame] | 798 | #derives |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 799 | #[repr(#( #repr_attributes ),*)] |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 800 | pub struct #ident { |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 801 | #base_subobjects_field |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 802 | #( #field_doc_coments #field_accesses #field_idents: #field_types, )* |
Googler | f479206 | 2021-10-20 07:21:21 +0000 | [diff] [blame] | 803 | #empty_struct_placeholder_field |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 804 | } |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 805 | |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 806 | #no_unique_address_accessors |
| 807 | |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 808 | #base_class_into |
| 809 | |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 810 | #unpin_impl |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 811 | }; |
| 812 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 813 | let assertion_tokens = quote! { |
Googler | 209b10a | 2021-12-06 09:11:57 +0000 | [diff] [blame] | 814 | const _: () = assert!(std::mem::size_of::<#ident>() == #size); |
| 815 | const _: () = assert!(std::mem::align_of::<#ident>() == #alignment); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 816 | #( #field_assertions )* |
| 817 | }; |
| 818 | |
| 819 | Ok(( |
| 820 | RsSnippet { features: record_features, tokens: record_tokens }, |
| 821 | RsSnippet { features: assertion_features, tokens: assertion_tokens }, |
| 822 | )) |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 823 | } |
| 824 | |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 825 | fn should_derive_clone(record: &Record) -> bool { |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 826 | record.is_unpin() |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 827 | && record.copy_constructor.access == ir::AccessSpecifier::Public |
| 828 | && record.copy_constructor.definition == SpecialMemberDefinition::Trivial |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 829 | } |
| 830 | |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 831 | fn should_derive_copy(record: &Record) -> bool { |
| 832 | // TODO(b/202258760): Make `Copy` inclusion configurable. |
| 833 | should_derive_clone(record) |
| 834 | } |
| 835 | |
| 836 | fn generate_derives(record: &Record) -> Vec<Ident> { |
| 837 | let mut derives = vec![]; |
Lukasz Anforowicz | 2e41bb6 | 2022-01-11 18:23:07 +0000 | [diff] [blame] | 838 | if should_derive_clone(record) { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 839 | derives.push(make_rs_ident("Clone")); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 840 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 841 | if should_derive_copy(record) { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 842 | derives.push(make_rs_ident("Copy")); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 843 | } |
| 844 | derives |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 845 | } |
| 846 | |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 847 | fn generate_enum(enum_: &Enum, ir: &IR) -> Result<TokenStream> { |
| 848 | let name = make_rs_ident(&enum_.identifier.identifier); |
| 849 | let underlying_type = format_rs_type(&enum_.underlying_type.rs_type, ir, &HashMap::new())?; |
| 850 | let enumerator_names = |
| 851 | enum_.enumerators.iter().map(|enumerator| make_rs_ident(&enumerator.identifier.identifier)); |
| 852 | let enumerator_values = enum_.enumerators.iter().map(|enumerator| enumerator.value); |
| 853 | Ok(quote! { |
| 854 | #[repr(transparent)] |
| 855 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 856 | pub struct #name(#underlying_type); |
| 857 | impl #name { |
| 858 | #(pub const #enumerator_names: #name = #name(#enumerator_values);)* |
| 859 | } |
| 860 | impl From<#underlying_type> for #name { |
| 861 | fn from(value: #underlying_type) -> #name { |
| 862 | #name(v) |
| 863 | } |
| 864 | } |
| 865 | impl From<#name> for #underlying_type { |
| 866 | fn from(value: #name) -> #underlying_type { |
| 867 | v.0 |
| 868 | } |
| 869 | } |
| 870 | }) |
| 871 | } |
| 872 | |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 873 | fn generate_type_alias(type_alias: &TypeAlias, ir: &IR) -> Result<TokenStream> { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 874 | let ident = make_rs_ident(&type_alias.identifier.identifier); |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 875 | let underlying_type = format_rs_type(&type_alias.underlying_type.rs_type, ir, &HashMap::new()) |
| 876 | .with_context(|| format!("Failed to format underlying type for {:?}", type_alias))?; |
| 877 | Ok(quote! {pub type #ident = #underlying_type;}) |
| 878 | } |
| 879 | |
Michael Forster | 523dbd4 | 2021-10-12 11:05:44 +0000 | [diff] [blame] | 880 | /// Generates Rust source code for a given `UnsupportedItem`. |
| 881 | fn generate_unsupported(item: &UnsupportedItem) -> Result<TokenStream> { |
Googler | 48a74dd | 2021-10-25 07:31:53 +0000 | [diff] [blame] | 882 | let location = if item.source_loc.filename.is_empty() { |
| 883 | "<unknown location>".to_string() |
| 884 | } else { |
| 885 | // TODO(forster): The "google3" prefix should probably come from a command line |
| 886 | // argument. |
| 887 | // TODO(forster): Consider linking to the symbol instead of to the line number |
| 888 | // to avoid wrong links while generated files have not caught up. |
| 889 | format!("google3/{};l={}", &item.source_loc.filename, &item.source_loc.line) |
| 890 | }; |
Michael Forster | 6a184ad | 2021-10-12 13:04:05 +0000 | [diff] [blame] | 891 | let message = format!( |
Googler | 48a74dd | 2021-10-25 07:31:53 +0000 | [diff] [blame] | 892 | "{}\nError while generating bindings for item '{}':\n{}", |
| 893 | &location, &item.name, &item.message |
Michael Forster | 6a184ad | 2021-10-12 13:04:05 +0000 | [diff] [blame] | 894 | ); |
Michael Forster | 523dbd4 | 2021-10-12 11:05:44 +0000 | [diff] [blame] | 895 | Ok(quote! { __COMMENT__ #message }) |
| 896 | } |
| 897 | |
Michael Forster | f1dce42 | 2021-10-13 09:50:16 +0000 | [diff] [blame] | 898 | /// Generates Rust source code for a given `Comment`. |
| 899 | fn generate_comment(comment: &Comment) -> Result<TokenStream> { |
| 900 | let text = &comment.text; |
| 901 | Ok(quote! { __COMMENT__ #text }) |
| 902 | } |
| 903 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 904 | fn generate_rs_api(ir: &IR) -> Result<TokenStream> { |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 905 | let mut items = vec![]; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 906 | let mut thunks = vec![]; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 907 | let mut assertions = vec![]; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 908 | |
Googler | 454f265 | 2021-12-06 12:53:12 +0000 | [diff] [blame] | 909 | // We import nullable pointers as an Option<&T> and assume that at the ABI |
| 910 | // level, None is represented as a zero pointer value whereas Some is |
| 911 | // represented as as non-zero pointer value. This seems like a pretty safe |
| 912 | // assumption to make, but to provide some safeguard, assert that |
| 913 | // `Option<&i32>` and `&i32` have the same size. |
| 914 | assertions.push(quote! { |
| 915 | const _: () = assert!(std::mem::size_of::<Option<&i32>>() == std::mem::size_of::<&i32>()); |
| 916 | }); |
| 917 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 918 | // TODO(jeanpierreda): Delete has_record, either in favor of using RsSnippet, or not |
| 919 | // having uses. See https://chat.google.com/room/AAAAnQmj8Qs/6QbkSvWcfhA |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 920 | let mut has_record = false; |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 921 | let mut features = BTreeSet::new(); |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 922 | |
Lukasz Anforowicz | 72c4d22 | 2022-02-18 19:07:28 +0000 | [diff] [blame] | 923 | // For #![rustfmt::skip]. |
| 924 | features.insert(make_rs_ident("custom_inner_attributes")); |
| 925 | |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 926 | // Identify all functions having overloads that we can't import (yet). |
| 927 | // TODO(b/213280424): Implement support for overloaded functions. |
| 928 | let mut seen_funcs = HashSet::new(); |
| 929 | let mut overloaded_funcs = HashSet::new(); |
| 930 | for func in ir.functions() { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 931 | if let GeneratedFunc::Some { function_id, .. } = generate_func(func, ir)? { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 932 | if !seen_funcs.insert(function_id.clone()) { |
| 933 | overloaded_funcs.insert(function_id); |
| 934 | } |
| 935 | } |
| 936 | } |
| 937 | |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 938 | for item in ir.items() { |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 939 | match item { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 940 | Item::Func(func) => match generate_func(func, ir)? { |
| 941 | GeneratedFunc::None => (), |
| 942 | GeneratedFunc::Unsupported(unsupported) => { |
| 943 | items.push(generate_unsupported(&unsupported)?) |
| 944 | } |
| 945 | GeneratedFunc::Some { api_func, thunk, function_id } => { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 946 | if overloaded_funcs.contains(&function_id) { |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 947 | items.push(generate_unsupported(&make_unsupported_fn( |
| 948 | func, |
| 949 | ir, |
| 950 | "Cannot generate bindings for overloaded function", |
| 951 | )?)?); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 952 | continue; |
| 953 | } |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 954 | features.extend(api_func.features); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 955 | features.extend(thunk.features); |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 956 | items.push(api_func.tokens); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 957 | thunks.push(thunk.tokens); |
| 958 | } |
Lukasz Anforowicz | eb19ac6 | 2022-02-05 00:10:16 +0000 | [diff] [blame] | 959 | }, |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 960 | Item::Record(record) => { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 961 | if !ir.is_current_target(&record.owning_target) |
| 962 | && !ir.is_stdlib_target(&record.owning_target) |
| 963 | { |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 964 | continue; |
| 965 | } |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 966 | let (snippet, assertions_snippet) = generate_record(record, ir)?; |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 967 | features.extend(snippet.features); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 968 | features.extend(assertions_snippet.features); |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 969 | items.push(snippet.tokens); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 970 | assertions.push(assertions_snippet.tokens); |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 971 | has_record = true; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 972 | } |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 973 | Item::Enum(enum_) => { |
| 974 | if !ir.is_current_target(&enum_.owning_target) |
| 975 | && !ir.is_stdlib_target(&enum_.owning_target) |
| 976 | { |
| 977 | continue; |
| 978 | } |
| 979 | items.push(generate_enum(enum_, ir)?); |
| 980 | continue; |
| 981 | } |
Googler | 098c458 | 2022-01-10 12:29:34 +0000 | [diff] [blame] | 982 | Item::TypeAlias(type_alias) => { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 983 | if !ir.is_current_target(&type_alias.owning_target) |
| 984 | && !ir.is_stdlib_target(&type_alias.owning_target) |
| 985 | { |
| 986 | continue; |
| 987 | } |
| 988 | items.push(generate_type_alias(type_alias, ir)?); |
Googler | 098c458 | 2022-01-10 12:29:34 +0000 | [diff] [blame] | 989 | } |
Michael Forster | 523dbd4 | 2021-10-12 11:05:44 +0000 | [diff] [blame] | 990 | Item::UnsupportedItem(unsupported) => items.push(generate_unsupported(unsupported)?), |
Michael Forster | f1dce42 | 2021-10-13 09:50:16 +0000 | [diff] [blame] | 991 | Item::Comment(comment) => items.push(generate_comment(comment)?), |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 992 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 993 | } |
| 994 | |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 995 | let mod_detail = if thunks.is_empty() { |
| 996 | quote! {} |
| 997 | } else { |
| 998 | quote! { |
| 999 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1000 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 1001 | use super::*; |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1002 | extern "C" { |
| 1003 | #( #thunks )* |
| 1004 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1005 | } |
| 1006 | } |
| 1007 | }; |
| 1008 | |
Devin Jeanpierre | ea700d3 | 2021-10-06 11:33:56 +0000 | [diff] [blame] | 1009 | let imports = if has_record { |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 1010 | quote! { |
Googler | aaa0a53 | 2021-10-01 09:11:27 +0000 | [diff] [blame] | 1011 | use memoffset_unstable_const::offset_of; |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 1012 | } |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 1013 | } else { |
| 1014 | quote! {} |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 1015 | }; |
| 1016 | |
Devin Jeanpierre | 273eeae | 2021-10-06 13:29:35 +0000 | [diff] [blame] | 1017 | let features = if features.is_empty() { |
| 1018 | quote! {} |
| 1019 | } else { |
| 1020 | quote! { |
| 1021 | #![feature( #(#features),* )] |
| 1022 | } |
| 1023 | }; |
| 1024 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1025 | Ok(quote! { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1026 | #features __NEWLINE__ |
| 1027 | #![allow(non_camel_case_types)] __NEWLINE__ |
| 1028 | #![allow(non_snake_case)] __NEWLINE__ __NEWLINE__ |
| 1029 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1030 | #imports __NEWLINE__ __NEWLINE__ |
Googler | ec648ff | 2021-09-23 07:19:53 +0000 | [diff] [blame] | 1031 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1032 | #( #items __NEWLINE__ __NEWLINE__ )* |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1033 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1034 | #mod_detail __NEWLINE__ __NEWLINE__ |
| 1035 | |
| 1036 | #( #assertions __NEWLINE__ __NEWLINE__ )* |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1037 | }) |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1038 | } |
| 1039 | |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1040 | /// Makes an 'Ident' to be used in the Rust source code. Escapes Rust keywords. |
| 1041 | fn make_rs_ident(ident: &str) -> Ident { |
| 1042 | // TODO(https://github.com/dtolnay/syn/pull/1098): Remove the hardcoded list once syn recognizes |
| 1043 | // 2018 and 2021 keywords. |
| 1044 | if ["async", "await", "try", "dyn"].contains(&ident) { |
| 1045 | return format_ident!("r#{}", ident); |
| 1046 | } |
| 1047 | match syn::parse_str::<syn::Ident>(ident) { |
| 1048 | Ok(_) => format_ident!("{}", ident), |
| 1049 | Err(_) => format_ident!("r#{}", ident), |
| 1050 | } |
| 1051 | } |
| 1052 | |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1053 | /// Formats a C++ identifier. Does not escape C++ keywords. |
| 1054 | fn format_cc_ident(ident: &str) -> TokenStream { |
| 1055 | ident.parse().unwrap() |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1056 | } |
| 1057 | |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1058 | fn rs_type_name_for_target_and_identifier( |
| 1059 | owning_target: &BlazeLabel, |
| 1060 | identifier: &ir::Identifier, |
| 1061 | ir: &IR, |
| 1062 | ) -> Result<TokenStream> { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1063 | let ident = make_rs_ident(identifier.identifier.as_str()); |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1064 | |
| 1065 | if ir.is_current_target(owning_target) || ir.is_stdlib_target(owning_target) { |
| 1066 | Ok(quote! {#ident}) |
| 1067 | } else { |
Marcel Hlopko | d906b89 | 2022-01-27 08:52:36 +0000 | [diff] [blame] | 1068 | let owning_crate_name = owning_target.target_name()?; |
| 1069 | // TODO(b/216587072): Remove this hacky escaping and use the import! macro once |
| 1070 | // available |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 1071 | let escaped_owning_crate_name = owning_crate_name.replace('-', "_"); |
Marcel Hlopko | d906b89 | 2022-01-27 08:52:36 +0000 | [diff] [blame] | 1072 | let owning_crate = make_rs_ident(&escaped_owning_crate_name); |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1073 | Ok(quote! {#owning_crate::#ident}) |
| 1074 | } |
| 1075 | } |
| 1076 | |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1077 | #[derive(Debug, Eq, PartialEq)] |
| 1078 | enum Mutability { |
| 1079 | Const, |
| 1080 | Mut, |
| 1081 | } |
| 1082 | |
| 1083 | impl Mutability { |
| 1084 | fn format_for_pointer(&self) -> TokenStream { |
| 1085 | match self { |
| 1086 | Mutability::Mut => quote! {mut}, |
| 1087 | Mutability::Const => quote! {const}, |
| 1088 | } |
| 1089 | } |
| 1090 | |
| 1091 | fn format_for_reference(&self) -> TokenStream { |
| 1092 | match self { |
| 1093 | Mutability::Mut => quote! {mut}, |
| 1094 | Mutability::Const => quote! {}, |
| 1095 | } |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | // TODO(b/213947473): Instead of having a separate RsTypeKind here, consider |
| 1100 | // changing ir::RsType into a similar `enum`, with fields that contain |
| 1101 | // references (e.g. &'ir Record`) instead of DeclIds. |
| 1102 | #[derive(Debug)] |
| 1103 | enum RsTypeKind<'ir> { |
| 1104 | Pointer { pointee: Box<RsTypeKind<'ir>>, mutability: Mutability }, |
| 1105 | Reference { referent: Box<RsTypeKind<'ir>>, mutability: Mutability, lifetime_id: LifetimeId }, |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1106 | FuncPtr { abi: &'ir str, return_type: Box<RsTypeKind<'ir>>, param_types: Vec<RsTypeKind<'ir>> }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1107 | Record(&'ir Record), |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1108 | TypeAlias { type_alias: &'ir TypeAlias, underlying_type: Box<RsTypeKind<'ir>> }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1109 | Unit, |
| 1110 | Other { name: &'ir str, type_args: Vec<RsTypeKind<'ir>> }, |
| 1111 | } |
| 1112 | |
| 1113 | impl<'ir> RsTypeKind<'ir> { |
| 1114 | pub fn new(ty: &'ir ir::RsType, ir: &'ir IR) -> Result<Self> { |
| 1115 | // The lambdas deduplicate code needed by multiple `match` branches. |
| 1116 | let get_type_args = || -> Result<Vec<RsTypeKind<'ir>>> { |
| 1117 | ty.type_args.iter().map(|type_arg| RsTypeKind::<'ir>::new(type_arg, ir)).collect() |
| 1118 | }; |
| 1119 | let get_pointee = || -> Result<Box<RsTypeKind<'ir>>> { |
| 1120 | if ty.type_args.len() != 1 { |
| 1121 | bail!("Missing pointee/referent type (need exactly 1 type argument): {:?}", ty); |
| 1122 | } |
| 1123 | Ok(Box::new(get_type_args()?.remove(0))) |
| 1124 | }; |
| 1125 | let get_lifetime = || -> Result<LifetimeId> { |
| 1126 | if ty.lifetime_args.len() != 1 { |
| 1127 | bail!("Missing reference lifetime (need exactly 1 lifetime argument): {:?}", ty); |
| 1128 | } |
| 1129 | Ok(ty.lifetime_args[0]) |
| 1130 | }; |
| 1131 | |
| 1132 | let result = match ty.name.as_deref() { |
| 1133 | None => { |
| 1134 | ensure!( |
| 1135 | ty.type_args.is_empty(), |
| 1136 | "Type arguments on records nor type aliases are not yet supported: {:?}", |
| 1137 | ty |
| 1138 | ); |
| 1139 | match ir.item_for_type(ty)? { |
| 1140 | Item::Record(record) => RsTypeKind::Record(record), |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1141 | Item::TypeAlias(type_alias) => RsTypeKind::TypeAlias { |
| 1142 | type_alias, |
| 1143 | underlying_type: Box::new(RsTypeKind::new( |
| 1144 | &type_alias.underlying_type.rs_type, |
| 1145 | ir, |
| 1146 | )?), |
| 1147 | }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1148 | other_item => bail!("Item does not define a type: {:?}", other_item), |
| 1149 | } |
| 1150 | } |
| 1151 | Some(name) => match name { |
| 1152 | "()" => { |
| 1153 | if !ty.type_args.is_empty() { |
| 1154 | bail!("Unit type must not have type arguments: {:?}", ty); |
| 1155 | } |
| 1156 | RsTypeKind::Unit |
| 1157 | } |
| 1158 | "*mut" => { |
| 1159 | RsTypeKind::Pointer { pointee: get_pointee()?, mutability: Mutability::Mut } |
| 1160 | } |
| 1161 | "*const" => { |
| 1162 | RsTypeKind::Pointer { pointee: get_pointee()?, mutability: Mutability::Const } |
| 1163 | } |
| 1164 | "&mut" => RsTypeKind::Reference { |
| 1165 | referent: get_pointee()?, |
| 1166 | mutability: Mutability::Mut, |
| 1167 | lifetime_id: get_lifetime()?, |
| 1168 | }, |
| 1169 | "&" => RsTypeKind::Reference { |
| 1170 | referent: get_pointee()?, |
| 1171 | mutability: Mutability::Const, |
| 1172 | lifetime_id: get_lifetime()?, |
| 1173 | }, |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1174 | name => { |
| 1175 | let mut type_args = get_type_args()?; |
| 1176 | match name.strip_prefix("#funcPtr ") { |
| 1177 | None => RsTypeKind::Other { name, type_args }, |
| 1178 | Some(abi) => { |
| 1179 | // TODO(b/217419782): Consider enforcing `'static` lifetime. |
| 1180 | ensure!(!type_args.is_empty(), "No return type in fn type: {:?}", ty); |
| 1181 | RsTypeKind::FuncPtr { |
| 1182 | abi, |
| 1183 | return_type: Box::new(type_args.remove(type_args.len() - 1)), |
| 1184 | param_types: type_args, |
| 1185 | } |
| 1186 | }, |
| 1187 | } |
| 1188 | }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1189 | }, |
| 1190 | }; |
| 1191 | Ok(result) |
| 1192 | } |
| 1193 | |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1194 | /// Returns true if the type is known to be `Unpin`, false otherwise. |
| 1195 | pub fn is_unpin(&self, ir: &IR) -> bool { |
| 1196 | match self { |
| 1197 | RsTypeKind::Record(record) => record.is_unpin(), |
| 1198 | RsTypeKind::TypeAlias { underlying_type, .. } => underlying_type.is_unpin(ir), |
| 1199 | _ => true, |
| 1200 | } |
| 1201 | } |
| 1202 | |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1203 | pub fn format( |
| 1204 | &self, |
| 1205 | ir: &IR, |
| 1206 | lifetime_to_name: &HashMap<LifetimeId, String>, |
| 1207 | ) -> Result<TokenStream> { |
| 1208 | let result = match self { |
| 1209 | RsTypeKind::Pointer { pointee, mutability } => { |
| 1210 | let mutability = mutability.format_for_pointer(); |
| 1211 | let nested_type = pointee.format(ir, lifetime_to_name)?; |
| 1212 | quote! {* #mutability #nested_type} |
| 1213 | } |
| 1214 | RsTypeKind::Reference { referent, mutability, lifetime_id } => { |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1215 | let mut_ = mutability.format_for_reference(); |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1216 | let lifetime = Self::format_lifetime(lifetime_id, lifetime_to_name)?; |
| 1217 | let nested_type = referent.format(ir, lifetime_to_name)?; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1218 | let reference = quote! {& #lifetime #mut_ #nested_type}; |
| 1219 | if mutability == &Mutability::Mut && !referent.is_unpin(ir) { |
| 1220 | // TODO(b/200067242): Add a `use std::pin::Pin` to the crate, and use `Pin`. |
| 1221 | // Probably format needs to return an RsSnippet, and RsSnippet needs a `uses` |
| 1222 | // field. |
| 1223 | quote! {std::pin::Pin< #reference >} |
| 1224 | } else { |
| 1225 | reference |
| 1226 | } |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1227 | } |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1228 | RsTypeKind::FuncPtr { abi, return_type, param_types } => { |
| 1229 | let return_frag = return_type.format_as_return_type_fragment(ir, lifetime_to_name)?; |
| 1230 | let param_types = param_types |
| 1231 | .iter() |
| 1232 | .map(|t| t.format(ir, lifetime_to_name)) |
| 1233 | .collect::<Result<Vec<_>>>()?; |
| 1234 | quote!{ extern #abi fn( #( #param_types ),* ) #return_frag } |
| 1235 | }, |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1236 | RsTypeKind::Record(record) => rs_type_name_for_target_and_identifier( |
| 1237 | &record.owning_target, |
| 1238 | &record.identifier, |
| 1239 | ir, |
| 1240 | )?, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1241 | RsTypeKind::TypeAlias { type_alias, .. } => rs_type_name_for_target_and_identifier( |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1242 | &type_alias.owning_target, |
| 1243 | &type_alias.identifier, |
| 1244 | ir, |
| 1245 | )?, |
| 1246 | RsTypeKind::Unit => quote! {()}, |
| 1247 | RsTypeKind::Other { name, type_args } => { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1248 | let ident = make_rs_ident(name); |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1249 | let generic_params = format_generic_params( |
| 1250 | type_args |
| 1251 | .iter() |
| 1252 | .map(|type_arg| type_arg.format(ir, lifetime_to_name)) |
| 1253 | .collect::<Result<Vec<_>>>()?, |
| 1254 | ); |
| 1255 | quote! {#ident #generic_params} |
| 1256 | } |
| 1257 | }; |
| 1258 | Ok(result) |
| 1259 | } |
| 1260 | |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1261 | pub fn format_as_return_type_fragment( |
| 1262 | &self, |
| 1263 | ir: &IR, |
| 1264 | lifetime_to_name: &HashMap<LifetimeId, String>, |
| 1265 | ) -> Result<TokenStream> { |
| 1266 | match self { |
| 1267 | RsTypeKind::Unit => Ok(quote! {}), |
| 1268 | other_type => { |
| 1269 | let return_type = other_type.format(ir, lifetime_to_name)?; |
| 1270 | Ok(quote! { -> #return_type }) |
| 1271 | } |
| 1272 | } |
| 1273 | } |
| 1274 | |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1275 | /// Formats this RsTypeKind as `&'a mut MaybeUninit<SomeStruct>`. This is |
| 1276 | /// used to format `__this` parameter in a constructor thunk. |
| 1277 | pub fn format_mut_ref_as_uninitialized( |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1278 | &self, |
| 1279 | ir: &IR, |
| 1280 | lifetime_to_name: &HashMap<LifetimeId, String>, |
| 1281 | ) -> Result<TokenStream> { |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1282 | match self { |
| 1283 | RsTypeKind::Reference { referent, lifetime_id, mutability: Mutability::Mut } => { |
| 1284 | let nested_type = referent.format(ir, lifetime_to_name)?; |
| 1285 | let lifetime = Self::format_lifetime(lifetime_id, lifetime_to_name)?; |
| 1286 | Ok(quote! { & #lifetime mut std::mem::MaybeUninit< #nested_type > }) |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1287 | } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1288 | _ => bail!("Expected reference to format as MaybeUninit, got: {:?}", self), |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1289 | } |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1290 | } |
| 1291 | |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1292 | /// Formats a reference or pointer as a raw pointer. |
| 1293 | pub fn format_ref_as_raw_ptr( |
| 1294 | &self, |
| 1295 | ir: &IR, |
| 1296 | lifetime_to_name: &HashMap<LifetimeId, String>, |
| 1297 | ) -> Result<TokenStream> { |
| 1298 | match self { |
| 1299 | RsTypeKind::Reference { referent: pointee, mutability, .. } |
| 1300 | | RsTypeKind::Pointer { pointee, mutability } => { |
| 1301 | let nested_type = pointee.format(ir, lifetime_to_name)?; |
| 1302 | let mut_ = mutability.format_for_pointer(); |
| 1303 | Ok(quote! { * #mut_ #nested_type }) |
| 1304 | } |
| 1305 | _ => bail!("Expected reference to format as raw ptr, got: {:?}", self), |
| 1306 | } |
| 1307 | } |
| 1308 | |
| 1309 | /// Formats this RsTypeKind as the `self` parameter: usually, `&'a self` or |
| 1310 | /// `&'a mut self`. |
| 1311 | /// |
| 1312 | /// If this is !Unpin, however, it uses `self: Pin<&mut Self>` instead. |
Lukasz Anforowicz | cde4b1b | 2022-02-03 21:20:55 +0000 | [diff] [blame] | 1313 | pub fn format_as_self_param( |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1314 | &self, |
Lukasz Anforowicz | ce34539 | 2022-01-14 22:41:16 +0000 | [diff] [blame] | 1315 | func: &Func, |
| 1316 | ir: &IR, |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1317 | lifetime_to_name: &HashMap<LifetimeId, String>, |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 1318 | ) -> Result<TokenStream> { |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 1319 | if func.name == UnqualifiedIdentifier::Destructor { |
| 1320 | let record = func |
| 1321 | .member_func_metadata |
| 1322 | .as_ref() |
| 1323 | .ok_or_else(|| anyhow!("Destructors must be member functions: {:?}", func))? |
| 1324 | .find_record(ir)?; |
| 1325 | if self.is_mut_ptr_to(record) { |
| 1326 | // Even in C++ it is UB to retain `this` pointer and dereference it |
| 1327 | // after a destructor runs. Therefore it is safe to use `&self` or |
| 1328 | // `&mut self` in Rust even if IR represents `__this` as a Rust |
| 1329 | // pointer (e.g. when lifetime annotations are missing - lifetime |
| 1330 | // annotations are required to represent it as a Rust reference). |
| 1331 | return Ok(quote! { &mut self }); |
| 1332 | } |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1333 | } |
| 1334 | |
| 1335 | match self { |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1336 | RsTypeKind::Reference { referent, lifetime_id, mutability } => { |
| 1337 | let mut_ = mutability.format_for_reference(); |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1338 | let lifetime = Self::format_lifetime(lifetime_id, lifetime_to_name)?; |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 1339 | if mutability == &Mutability::Mut && !referent.is_unpin(ir) && func.name != UnqualifiedIdentifier::Destructor { |
| 1340 | // TODO(b/200067242): Add a `use std::pin::Pin` to the crate, and use `Pin`. |
| 1341 | Ok(quote! {self: std::pin::Pin< & #lifetime #mut_ Self>}) |
| 1342 | } else { |
| 1343 | Ok(quote! { & #lifetime #mut_ self }) |
| 1344 | } |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1345 | } |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 1346 | _ => bail!("Unexpected type of `self` parameter: {:?}", self), |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 1347 | } |
| 1348 | } |
| 1349 | |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1350 | fn format_lifetime( |
| 1351 | lifetime_id: &LifetimeId, |
| 1352 | lifetime_to_name: &HashMap<LifetimeId, String>, |
| 1353 | ) -> Result<TokenStream> { |
| 1354 | let lifetime_name = lifetime_to_name.get(lifetime_id).ok_or_else(|| { |
| 1355 | anyhow!("`lifetime_to_name` doesn't have an entry for {:?}", lifetime_id) |
| 1356 | })?; |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 1357 | Ok(format_lifetime_name(lifetime_name)) |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1358 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1359 | |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 1360 | /// Returns whether the type represented by `self` implements the `Copy` |
| 1361 | /// trait. |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 1362 | pub fn implements_copy(&self) -> bool { |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1363 | // TODO(b/212696226): Verify results of `implements_copy` via static |
| 1364 | // assertions in the generated Rust code (because incorrect results |
| 1365 | // can silently lead to unsafe behavior). |
| 1366 | match self { |
| 1367 | RsTypeKind::Unit => true, |
| 1368 | RsTypeKind::Pointer { .. } => true, |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1369 | RsTypeKind::FuncPtr { .. } => true, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1370 | RsTypeKind::Reference { mutability: Mutability::Const, .. } => true, |
| 1371 | RsTypeKind::Reference { mutability: Mutability::Mut, .. } => false, |
| 1372 | RsTypeKind::Record(record) => should_derive_copy(record), |
| 1373 | RsTypeKind::TypeAlias { underlying_type, .. } => underlying_type.implements_copy(), |
Lukasz Anforowicz | d81bea9 | 2022-02-11 08:57:58 +0000 | [diff] [blame] | 1374 | RsTypeKind::Other { type_args, .. } => { |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 1375 | // All types that may appear here without `type_args` (e.g. |
| 1376 | // primitive types like `i32`) implement `Copy`. Generic types |
| 1377 | // that may be present here (e.g. Option<...>) are `Copy` if all |
| 1378 | // of their `type_args` are `Copy`. |
| 1379 | type_args.iter().all(|t| t.implements_copy()) |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 1380 | } |
| 1381 | } |
| 1382 | } |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 1383 | |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 1384 | pub fn is_mut_ptr_to(&self, expected_record: &Record) -> bool { |
| 1385 | match self { |
| 1386 | RsTypeKind::Pointer { pointee, mutability: Mutability::Mut, .. } => { |
| 1387 | pointee.is_record(expected_record) |
| 1388 | } |
| 1389 | _ => false, |
| 1390 | } |
| 1391 | } |
| 1392 | |
| 1393 | pub fn is_ref_to(&self, expected_record: &Record) -> bool { |
| 1394 | match self { |
| 1395 | RsTypeKind::Reference { referent, .. } => referent.is_record(expected_record), |
| 1396 | _ => false, |
| 1397 | } |
| 1398 | } |
| 1399 | |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 1400 | pub fn is_shared_ref_to(&self, expected_record: &Record) -> bool { |
| 1401 | match self { |
| 1402 | RsTypeKind::Reference { referent, mutability: Mutability::Const, .. } => { |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 1403 | referent.is_record(expected_record) |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 1404 | } |
| 1405 | _ => false, |
| 1406 | } |
| 1407 | } |
Lukasz Anforowicz | f956462 | 2022-01-28 14:31:04 +0000 | [diff] [blame] | 1408 | |
| 1409 | pub fn is_record(&self, expected_record: &Record) -> bool { |
| 1410 | match self { |
| 1411 | RsTypeKind::Record(actual_record) => actual_record.id == expected_record.id, |
| 1412 | _ => false, |
| 1413 | } |
| 1414 | } |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 1415 | |
| 1416 | /// Iterates over `self` and all the nested types (e.g. pointees, generic |
| 1417 | /// type args, etc.) in DFS order. |
| 1418 | pub fn dfs_iter<'ty>(&'ty self) -> impl Iterator<Item = &'ty RsTypeKind<'ir>> + '_ { |
| 1419 | RsTypeKindIter::new(self) |
| 1420 | } |
| 1421 | |
| 1422 | /// Iterates over all `LifetimeId`s in `self` and in all the nested types. |
| 1423 | /// Note that the results might contain duplicate LifetimeId values (e.g. |
| 1424 | /// if the same LifetimeId is used in two `type_args`). |
| 1425 | pub fn lifetimes(&self) -> impl Iterator<Item = LifetimeId> + '_ { |
| 1426 | self.dfs_iter().filter_map(|t| match t { |
| 1427 | RsTypeKind::Reference { lifetime_id, .. } => Some(*lifetime_id), |
| 1428 | _ => None, |
| 1429 | }) |
| 1430 | } |
| 1431 | } |
| 1432 | |
| 1433 | struct RsTypeKindIter<'ty, 'ir> { |
| 1434 | todo: Vec<&'ty RsTypeKind<'ir>>, |
| 1435 | } |
| 1436 | |
| 1437 | impl<'ty, 'ir> RsTypeKindIter<'ty, 'ir> { |
| 1438 | pub fn new(ty: &'ty RsTypeKind<'ir>) -> Self { |
| 1439 | Self { todo: vec![ty] } |
| 1440 | } |
| 1441 | } |
| 1442 | |
| 1443 | impl<'ty, 'ir> Iterator for RsTypeKindIter<'ty, 'ir> { |
| 1444 | type Item = &'ty RsTypeKind<'ir>; |
| 1445 | |
| 1446 | fn next(&mut self) -> Option<Self::Item> { |
| 1447 | match self.todo.pop() { |
| 1448 | None => None, |
| 1449 | Some(curr) => { |
| 1450 | match curr { |
| 1451 | RsTypeKind::Unit | RsTypeKind::Record(_) => (), |
| 1452 | RsTypeKind::Pointer { pointee, .. } => self.todo.push(pointee), |
| 1453 | RsTypeKind::Reference { referent, .. } => self.todo.push(referent), |
| 1454 | RsTypeKind::TypeAlias { underlying_type: t, .. } => self.todo.push(t), |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 1455 | RsTypeKind::FuncPtr { return_type, param_types, .. } => { |
| 1456 | self.todo.push(return_type); |
| 1457 | self.todo.extend(param_types.iter().rev()); |
| 1458 | }, |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 1459 | RsTypeKind::Other { type_args, .. } => self.todo.extend(type_args.iter().rev()), |
| 1460 | }; |
| 1461 | Some(curr) |
| 1462 | } |
| 1463 | } |
| 1464 | } |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1465 | } |
| 1466 | |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 1467 | fn format_lifetime_name(lifetime_name: &str) -> TokenStream { |
| 1468 | let lifetime = |
| 1469 | syn::Lifetime::new(&format!("'{}", lifetime_name), proc_macro2::Span::call_site()); |
| 1470 | quote! { #lifetime } |
| 1471 | } |
| 1472 | |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 1473 | fn format_rs_type( |
| 1474 | ty: &ir::RsType, |
| 1475 | ir: &IR, |
| 1476 | lifetime_to_name: &HashMap<LifetimeId, String>, |
| 1477 | ) -> Result<TokenStream> { |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 1478 | RsTypeKind::new(ty, ir) |
| 1479 | .and_then(|kind| kind.format(ir, lifetime_to_name)) |
| 1480 | .with_context(|| format!("Failed to format Rust type {:?}", ty)) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 1481 | } |
| 1482 | |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1483 | fn cc_type_name_for_item(item: &ir::Item) -> Result<TokenStream> { |
| 1484 | let (disambiguator_fragment, identifier) = match item { |
| 1485 | Item::Record(record) => (quote! { class }, &record.identifier), |
| 1486 | Item::TypeAlias(type_alias) => (quote! {}, &type_alias.identifier), |
| 1487 | _ => bail!("Item does not define a type: {:?}", item), |
| 1488 | }; |
| 1489 | |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1490 | let ident = format_cc_ident(identifier.identifier.as_str()); |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1491 | Ok(quote! { #disambiguator_fragment #ident }) |
| 1492 | } |
| 1493 | |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1494 | fn format_cc_type(ty: &ir::CcType, ir: &IR) -> Result<TokenStream> { |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 1495 | let const_fragment = if ty.is_const { |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 1496 | quote! {const} |
| 1497 | } else { |
| 1498 | quote! {} |
| 1499 | }; |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1500 | if let Some(ref name) = ty.name { |
| 1501 | match name.as_str() { |
| 1502 | "*" => { |
Googler | ff7fc23 | 2021-12-02 09:43:00 +0000 | [diff] [blame] | 1503 | if ty.type_args.len() != 1 { |
| 1504 | bail!("Invalid pointer type (need exactly 1 type argument): {:?}", ty); |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1505 | } |
Googler | ff7fc23 | 2021-12-02 09:43:00 +0000 | [diff] [blame] | 1506 | assert_eq!(ty.type_args.len(), 1); |
| 1507 | let nested_type = format_cc_type(&ty.type_args[0], ir)?; |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1508 | Ok(quote! {#nested_type * #const_fragment}) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 1509 | } |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 1510 | "&" => { |
| 1511 | if ty.type_args.len() != 1 { |
| 1512 | bail!("Invalid reference type (need exactly 1 type argument): {:?}", ty); |
| 1513 | } |
| 1514 | let nested_type = format_cc_type(&ty.type_args[0], ir)?; |
| 1515 | Ok(quote! {#nested_type &}) |
| 1516 | } |
Lukasz Anforowicz | 957cbf2 | 2022-01-05 16:14:05 +0000 | [diff] [blame] | 1517 | cc_type_name => { |
Googler | ff7fc23 | 2021-12-02 09:43:00 +0000 | [diff] [blame] | 1518 | if !ty.type_args.is_empty() { |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1519 | bail!("Type not yet supported: {:?}", ty); |
| 1520 | } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1521 | let idents = cc_type_name.split_whitespace().map(format_cc_ident); |
Lukasz Anforowicz | 957cbf2 | 2022-01-05 16:14:05 +0000 | [diff] [blame] | 1522 | Ok(quote! {#( #idents )* #const_fragment}) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 1523 | } |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 1524 | } |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1525 | } else { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1526 | let item = ir.item_for_type(ty)?; |
| 1527 | let type_name = cc_type_name_for_item(item)?; |
| 1528 | Ok(quote! {#const_fragment #type_name}) |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 1529 | } |
| 1530 | } |
| 1531 | |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1532 | fn cc_struct_layout_assertion(record: &Record, ir: &IR) -> TokenStream { |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 1533 | if !ir.is_current_target(&record.owning_target) && !ir.is_stdlib_target(&record.owning_target) { |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1534 | return quote! {}; |
| 1535 | } |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1536 | let record_ident = format_cc_ident(&record.identifier.identifier); |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1537 | let size = Literal::usize_unsuffixed(record.size); |
| 1538 | let alignment = Literal::usize_unsuffixed(record.alignment); |
Lukasz Anforowicz | 7470471 | 2021-12-22 15:30:31 +0000 | [diff] [blame] | 1539 | let field_assertions = |
| 1540 | record.fields.iter().filter(|f| f.access == AccessSpecifier::Public).map(|field| { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1541 | let field_ident = format_cc_ident(&field.identifier.identifier); |
Lukasz Anforowicz | 7470471 | 2021-12-22 15:30:31 +0000 | [diff] [blame] | 1542 | let offset = Literal::usize_unsuffixed(field.offset); |
| 1543 | // The IR contains the offset in bits, while C++'s offsetof() |
| 1544 | // returns the offset in bytes, so we need to convert. |
| 1545 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1546 | static_assert(offsetof(class #record_ident, #field_ident) * 8 == #offset); |
Lukasz Anforowicz | 7470471 | 2021-12-22 15:30:31 +0000 | [diff] [blame] | 1547 | } |
| 1548 | }); |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1549 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1550 | static_assert(sizeof(class #record_ident) == #size); |
| 1551 | static_assert(alignof(class #record_ident) == #alignment); |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1552 | #( #field_assertions )* |
| 1553 | } |
| 1554 | } |
| 1555 | |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 1556 | // Returns the accessor functions for no_unique_address member variables. |
| 1557 | fn cc_struct_no_unique_address_impl(record: &Record, ir: &IR) -> Result<TokenStream> { |
| 1558 | let mut fields = vec![]; |
| 1559 | let mut types = vec![]; |
| 1560 | for field in &record.fields { |
| 1561 | if field.access != AccessSpecifier::Public || !field.is_no_unique_address { |
| 1562 | continue; |
| 1563 | } |
| 1564 | fields.push(make_rs_ident(&field.identifier.identifier)); |
| 1565 | types.push(format_rs_type(&field.type_.rs_type, ir, &HashMap::new()).with_context( |
| 1566 | || format!("Failed to format type for field {:?} on record {:?}", field, record), |
| 1567 | )?) |
| 1568 | } |
| 1569 | |
| 1570 | if fields.is_empty() { |
| 1571 | return Ok(quote! {}); |
| 1572 | } |
| 1573 | |
| 1574 | let ident = make_rs_ident(&record.identifier.identifier); |
| 1575 | Ok(quote! { |
| 1576 | impl #ident { |
| 1577 | #( |
| 1578 | pub fn #fields(&self) -> &#types { |
| 1579 | unsafe {&* (&self.#fields as *const _ as *const #types)} |
| 1580 | } |
| 1581 | )* |
| 1582 | } |
| 1583 | }) |
| 1584 | } |
| 1585 | |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 1586 | /// Returns the implementation of base class conversions, for converting a type |
| 1587 | /// to its unambiguous public base classes. |
| 1588 | /// |
| 1589 | /// TODO(b/216195042): Implement this in terms of a supporting trait which casts |
| 1590 | /// raw pointers. Then, we would have blanket impls for reference, pinned mut |
| 1591 | /// reference, etc. conversion. The current version is just enough to test the |
| 1592 | /// logic in importer. |
| 1593 | // |
| 1594 | // TODO(b/216195042): Should this use, like, AsRef/AsMut (and some equivalent |
| 1595 | // for Pin)? |
| 1596 | fn cc_struct_upcast_impl(record: &Record, ir: &IR) -> Result<TokenStream> { |
| 1597 | let mut impls = Vec::with_capacity(record.unambiguous_public_bases.len()); |
| 1598 | for base in &record.unambiguous_public_bases { |
| 1599 | let base_record: &Record = ir.find_decl(base.base_record_id)?.try_into()?; |
| 1600 | if let Some(offset) = base.offset { |
| 1601 | let offset = Literal::i64_unsuffixed(offset); |
| 1602 | // TODO(b/216195042): Correctly handle imported records, lifetimes. |
| 1603 | let base_name = make_rs_ident(&base_record.identifier.identifier); |
| 1604 | let derived_name = make_rs_ident(&record.identifier.identifier); |
| 1605 | impls.push(quote! { |
| 1606 | impl<'a> From<&'a #derived_name> for &'a #base_name { |
| 1607 | fn from(x: &'a #derived_name) -> Self { |
| 1608 | unsafe { |
| 1609 | &*((x as *const _ as *const u8).offset(#offset) as *const #base_name) |
| 1610 | } |
| 1611 | } |
| 1612 | } |
| 1613 | }); |
| 1614 | } else { |
| 1615 | // TODO(b/216195042): determine offset dynamically / use a dynamic |
| 1616 | // cast. This requires a new C++ function to be |
| 1617 | // generated, so that we have something to call. |
| 1618 | } |
| 1619 | } |
| 1620 | |
| 1621 | Ok(quote! { |
| 1622 | #(#impls)* |
| 1623 | }) |
| 1624 | } |
| 1625 | |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1626 | fn thunk_ident(func: &Func) -> Ident { |
| 1627 | format_ident!("__rust_thunk__{}", func.mangled_name) |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 1628 | } |
| 1629 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1630 | fn generate_rs_api_impl(ir: &IR) -> Result<TokenStream> { |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 1631 | // This function uses quote! to generate C++ source code out of convenience. |
| 1632 | // This is a bold idea so we have to continously evaluate if it still makes |
| 1633 | // sense or the cost of working around differences in Rust and C++ tokens is |
| 1634 | // greather than the value added. |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1635 | // |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 1636 | // See rs_bindings_from_cc/ |
| 1637 | // token_stream_printer.rs for a list of supported placeholders. |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1638 | let mut thunks = vec![]; |
Michael Forster | 7ef8073 | 2021-10-01 18:12:19 +0000 | [diff] [blame] | 1639 | for func in ir.functions() { |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 1640 | if can_skip_cc_thunk(func) { |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1641 | continue; |
| 1642 | } |
| 1643 | |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1644 | let thunk_ident = thunk_ident(func); |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 1645 | let implementation_function = match &func.name { |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 1646 | UnqualifiedIdentifier::Operator(op) => { |
| 1647 | let name = syn::parse_str::<TokenStream>(&op.name)?; |
| 1648 | quote! { operator #name } |
| 1649 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 1650 | UnqualifiedIdentifier::Identifier(id) => { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1651 | let fn_ident = format_cc_ident(&id.identifier); |
Lukasz Anforowicz | aab8ad2 | 2021-12-19 20:29:26 +0000 | [diff] [blame] | 1652 | let static_method_metadata = func |
| 1653 | .member_func_metadata |
| 1654 | .as_ref() |
| 1655 | .filter(|meta| meta.instance_method_metadata.is_none()); |
| 1656 | match static_method_metadata { |
| 1657 | None => quote! {#fn_ident}, |
| 1658 | Some(meta) => { |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 1659 | let record_ident = |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1660 | format_cc_ident(&meta.find_record(ir)?.identifier.identifier); |
Lukasz Anforowicz | aab8ad2 | 2021-12-19 20:29:26 +0000 | [diff] [blame] | 1661 | quote! { #record_ident :: #fn_ident } |
| 1662 | } |
| 1663 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 1664 | } |
Lukasz Anforowicz | 7b0042d | 2022-01-06 23:00:19 +0000 | [diff] [blame] | 1665 | // 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] | 1666 | // use the name of the type itself, without namespace qualification, template |
| 1667 | // parameters, or aliases. We do not need to use that naming scheme anywhere else in |
| 1668 | // the bindings, and it can be difficult (impossible?) to spell in the general case. By |
| 1669 | // 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] | 1670 | // is. Similar arguments apply to `construct_at`. |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 1671 | UnqualifiedIdentifier::Constructor => { |
Lukasz Anforowicz | 7b0042d | 2022-01-06 23:00:19 +0000 | [diff] [blame] | 1672 | quote! { rs_api_impl_support::construct_at } |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 1673 | } |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 1674 | UnqualifiedIdentifier::Destructor => quote! {std::destroy_at}, |
Devin Jeanpierre | f2ec871 | 2021-10-13 20:47:16 +0000 | [diff] [blame] | 1675 | }; |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1676 | 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] | 1677 | let return_stmt = if func.return_type.cc_type.is_void() { |
| 1678 | quote! {} |
| 1679 | } else { |
| 1680 | quote! { return } |
| 1681 | }; |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1682 | |
| 1683 | let param_idents = |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1684 | 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] | 1685 | |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 1686 | let param_types = func |
| 1687 | .params |
| 1688 | .iter() |
Marcel Hlopko | c0956cf | 2021-11-29 08:31:28 +0000 | [diff] [blame] | 1689 | .map(|p| format_cc_type(&p.type_.cc_type, ir)) |
Devin Jeanpierre | 09c6f45 | 2021-09-29 07:34:24 +0000 | [diff] [blame] | 1690 | .collect::<Result<Vec<_>>>()?; |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1691 | |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 1692 | let needs_this_deref = match &func.member_func_metadata { |
| 1693 | None => false, |
| 1694 | Some(meta) => match &func.name { |
| 1695 | UnqualifiedIdentifier::Constructor | UnqualifiedIdentifier::Destructor => false, |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 1696 | UnqualifiedIdentifier::Identifier(_) | UnqualifiedIdentifier::Operator(_) => { |
| 1697 | meta.instance_method_metadata.is_some() |
| 1698 | } |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 1699 | }, |
| 1700 | }; |
| 1701 | let (implementation_function, arg_expressions) = if !needs_this_deref { |
| 1702 | (implementation_function, param_idents.clone()) |
| 1703 | } else { |
| 1704 | let this_param = func |
| 1705 | .params |
| 1706 | .first() |
| 1707 | .ok_or_else(|| anyhow!("Instance methods must have `__this` param."))?; |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1708 | let this_arg = format_cc_ident(&this_param.identifier.identifier); |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 1709 | ( |
| 1710 | quote! { #this_arg -> #implementation_function}, |
| 1711 | param_idents.iter().skip(1).cloned().collect_vec(), |
| 1712 | ) |
| 1713 | }; |
| 1714 | |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1715 | thunks.push(quote! { |
| 1716 | extern "C" #return_type_name #thunk_ident( #( #param_types #param_idents ),* ) { |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 1717 | #return_stmt #implementation_function( #( #arg_expressions ),* ); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1718 | } |
| 1719 | }); |
| 1720 | } |
| 1721 | |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1722 | let layout_assertions = ir.records().map(|record| cc_struct_layout_assertion(record, ir)); |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1723 | |
Devin Jeanpierre | 231ef8d | 2021-10-27 10:50:44 +0000 | [diff] [blame] | 1724 | let mut standard_headers = <BTreeSet<Ident>>::new(); |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1725 | standard_headers.insert(format_ident!("memory")); // ubiquitous. |
Devin Jeanpierre | 231ef8d | 2021-10-27 10:50:44 +0000 | [diff] [blame] | 1726 | if ir.records().next().is_some() { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 1727 | standard_headers.insert(format_ident!("cstddef")); |
Devin Jeanpierre | 231ef8d | 2021-10-27 10:50:44 +0000 | [diff] [blame] | 1728 | }; |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1729 | |
Lukasz Anforowicz | 4457baf | 2021-12-23 17:24:04 +0000 | [diff] [blame] | 1730 | let mut includes = |
| 1731 | vec!["rs_bindings_from_cc/support/cxx20_backports.h"]; |
| 1732 | |
Michael Forster | bee8448 | 2021-10-13 08:35:38 +0000 | [diff] [blame] | 1733 | // In order to generate C++ thunk in all the cases Clang needs to be able to |
| 1734 | // access declarations from public headers of the C++ library. |
Lukasz Anforowicz | 4457baf | 2021-12-23 17:24:04 +0000 | [diff] [blame] | 1735 | includes.extend(ir.used_headers().map(|i| &i.name as &str)); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1736 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1737 | Ok(quote! { |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1738 | #( __HASH_TOKEN__ include <#standard_headers> __NEWLINE__)* |
Devin Jeanpierre | 7c74f84 | 2022-02-03 07:08:06 +0000 | [diff] [blame] | 1739 | __NEWLINE__ |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1740 | #( __HASH_TOKEN__ include #includes __NEWLINE__)* __NEWLINE__ |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 1741 | __HASH_TOKEN__ pragma clang diagnostic push __NEWLINE__ |
| 1742 | // Disable Clang thread-safety-analysis warnings that would otherwise |
| 1743 | // complain about thunks that call mutex locking functions in an unpaired way. |
| 1744 | __HASH_TOKEN__ pragma clang diagnostic ignored "-Wthread-safety-analysis" __NEWLINE__ |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1745 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1746 | #( #thunks )* __NEWLINE__ __NEWLINE__ |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1747 | |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1748 | #( #layout_assertions __NEWLINE__ __NEWLINE__ )* |
Marcel Hlopko | c6b726c | 2021-10-07 06:53:09 +0000 | [diff] [blame] | 1749 | |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 1750 | __NEWLINE__ |
| 1751 | __HASH_TOKEN__ pragma clang diagnostic pop __NEWLINE__ |
Marcel Hlopko | c6b726c | 2021-10-07 06:53:09 +0000 | [diff] [blame] | 1752 | // To satisfy http://cs/symbol:devtools.metadata.Presubmit.CheckTerminatingNewline check. |
| 1753 | __NEWLINE__ |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1754 | }) |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1755 | } |
| 1756 | |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1757 | #[cfg(test)] |
| 1758 | mod tests { |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 1759 | use super::*; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 1760 | use anyhow::anyhow; |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 1761 | use ir_testing::{ir_from_cc, ir_from_cc_dependency, ir_func, ir_record, retrieve_func}; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1762 | use token_stream_matchers::{ |
| 1763 | assert_cc_matches, assert_cc_not_matches, assert_rs_matches, assert_rs_not_matches, |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 1764 | }; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1765 | use token_stream_printer::tokens_to_string; |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1766 | |
| 1767 | #[test] |
Marcel Hlopko | b8069ae | 2022-02-19 09:31:00 +0000 | [diff] [blame] | 1768 | fn test_disable_thread_safety_warnings() -> Result<()> { |
| 1769 | let ir = ir_from_cc("inline void foo() {}")?; |
| 1770 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 1771 | assert_cc_matches!( |
| 1772 | rs_api_impl, |
| 1773 | quote! { |
| 1774 | ... |
| 1775 | __HASH_TOKEN__ pragma clang diagnostic push |
| 1776 | __HASH_TOKEN__ pragma clang diagnostic ignored "-Wthread-safety-analysis" |
| 1777 | ... |
| 1778 | |
| 1779 | __HASH_TOKEN__ pragma clang diagnostic pop |
| 1780 | ... |
| 1781 | } |
| 1782 | ); |
| 1783 | Ok(()) |
| 1784 | } |
| 1785 | |
| 1786 | #[test] |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 1787 | // TODO(hlopko): Move this test to a more principled place where it can access |
| 1788 | // `ir_testing`. |
| 1789 | fn test_duplicate_decl_ids_err() { |
| 1790 | let mut r1 = ir_record("R1"); |
Marcel Hlopko | 264b9ad | 2021-12-02 21:06:44 +0000 | [diff] [blame] | 1791 | r1.id = DeclId(42); |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 1792 | let mut r2 = ir_record("R2"); |
Marcel Hlopko | 264b9ad | 2021-12-02 21:06:44 +0000 | [diff] [blame] | 1793 | r2.id = DeclId(42); |
Marcel Hlopko | 3b9bf9e | 2021-11-29 08:25:14 +0000 | [diff] [blame] | 1794 | let result = make_ir_from_items([r1.into(), r2.into()]); |
| 1795 | assert!(result.is_err()); |
| 1796 | assert!(result.unwrap_err().to_string().contains("Duplicate decl_id found in")); |
| 1797 | } |
| 1798 | |
| 1799 | #[test] |
Marcel Hlopko | 45fba97 | 2021-08-23 19:52:20 +0000 | [diff] [blame] | 1800 | fn test_simple_function() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1801 | let ir = ir_from_cc("int Add(int a, int b);")?; |
| 1802 | let rs_api = generate_rs_api(&ir)?; |
| 1803 | assert_rs_matches!( |
| 1804 | rs_api, |
| 1805 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1806 | #[inline(always)] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1807 | pub fn Add(a: i32, b: i32) -> i32 { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1808 | unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1809 | } |
| 1810 | } |
| 1811 | ); |
| 1812 | assert_rs_matches!( |
| 1813 | rs_api, |
| 1814 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1815 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1816 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 1817 | use super::*; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1818 | extern "C" { |
| 1819 | #[link_name = "_Z3Addii"] |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1820 | pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1821 | } |
| 1822 | } |
| 1823 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1824 | ); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1825 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1826 | assert_cc_not_matches!(generate_rs_api_impl(&ir)?, quote! {__rust_thunk___Z3Addii}); |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1827 | |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1828 | Ok(()) |
| 1829 | } |
| 1830 | |
| 1831 | #[test] |
| 1832 | fn test_inline_function() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1833 | let ir = ir_from_cc("inline int Add(int a, int b);")?; |
| 1834 | let rs_api = generate_rs_api(&ir)?; |
| 1835 | assert_rs_matches!( |
| 1836 | rs_api, |
| 1837 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1838 | #[inline(always)] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1839 | pub fn Add(a: i32, b: i32) -> i32 { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1840 | unsafe { crate::detail::__rust_thunk___Z3Addii(a, b) } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1841 | } |
| 1842 | } |
| 1843 | ); |
| 1844 | assert_rs_matches!( |
| 1845 | rs_api, |
| 1846 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1847 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1848 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 1849 | use super::*; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1850 | extern "C" { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1851 | pub(crate) fn __rust_thunk___Z3Addii(a: i32, b: i32) -> i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1852 | } |
| 1853 | } |
| 1854 | } |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1855 | ); |
| 1856 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1857 | assert_cc_matches!( |
| 1858 | generate_rs_api_impl(&ir)?, |
| 1859 | quote! { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1860 | extern "C" int __rust_thunk___Z3Addii(int a, int b) { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1861 | return Add(a, b); |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1862 | } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1863 | } |
Marcel Hlopko | 3164eee | 2021-08-24 20:09:22 +0000 | [diff] [blame] | 1864 | ); |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 1865 | Ok(()) |
| 1866 | } |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1867 | |
| 1868 | #[test] |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1869 | fn test_simple_function_with_types_from_other_target() -> Result<()> { |
| 1870 | let ir = ir_from_cc_dependency( |
| 1871 | "inline ReturnStruct DoSomething(ParamStruct param);", |
| 1872 | "struct ReturnStruct {}; struct ParamStruct {};", |
| 1873 | )?; |
| 1874 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1875 | let rs_api = generate_rs_api(&ir)?; |
| 1876 | assert_rs_matches!( |
| 1877 | rs_api, |
| 1878 | quote! { |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1879 | #[inline(always)] |
| 1880 | pub fn DoSomething(param: dependency::ParamStruct) |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1881 | -> dependency::ReturnStruct { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 1882 | unsafe { crate::detail::__rust_thunk___Z11DoSomething11ParamStruct(param) } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1883 | } |
| 1884 | } |
| 1885 | ); |
| 1886 | assert_rs_matches!( |
| 1887 | rs_api, |
| 1888 | quote! { |
| 1889 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 1890 | #[allow(unused_imports)] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1891 | use super::*; |
| 1892 | extern "C" { |
| 1893 | pub(crate) fn __rust_thunk___Z11DoSomething11ParamStruct(param: dependency::ParamStruct) |
| 1894 | -> dependency::ReturnStruct; |
| 1895 | } |
| 1896 | }} |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1897 | ); |
| 1898 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1899 | assert_cc_matches!( |
| 1900 | generate_rs_api_impl(&ir)?, |
| 1901 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1902 | extern "C" class ReturnStruct __rust_thunk___Z11DoSomething11ParamStruct(class ParamStruct param) { |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1903 | return DoSomething(param); |
| 1904 | } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1905 | } |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 1906 | ); |
| 1907 | Ok(()) |
| 1908 | } |
| 1909 | |
| 1910 | #[test] |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1911 | fn test_simple_struct() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1912 | let ir = ir_from_cc(&tokens_to_string(quote! { |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 1913 | struct SomeStruct final { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1914 | int public_int; |
| 1915 | protected: |
| 1916 | int protected_int; |
| 1917 | private: |
| 1918 | int private_int; |
| 1919 | }; |
| 1920 | })?)?; |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 1921 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1922 | let rs_api = generate_rs_api(&ir)?; |
| 1923 | assert_rs_matches!( |
| 1924 | rs_api, |
| 1925 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 1926 | #[derive(Clone, Copy)] |
| 1927 | #[repr(C)] |
| 1928 | pub struct SomeStruct { |
| 1929 | pub public_int: i32, |
| 1930 | protected_int: i32, |
| 1931 | private_int: i32, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1932 | } |
| 1933 | } |
| 1934 | ); |
| 1935 | assert_rs_matches!( |
| 1936 | rs_api, |
| 1937 | quote! { |
Googler | 454f265 | 2021-12-06 12:53:12 +0000 | [diff] [blame] | 1938 | const _: () = assert!(std::mem::size_of::<Option<&i32>>() == std::mem::size_of::<&i32>()); |
Googler | 209b10a | 2021-12-06 09:11:57 +0000 | [diff] [blame] | 1939 | const _: () = assert!(std::mem::size_of::<SomeStruct>() == 12usize); |
| 1940 | const _: () = assert!(std::mem::align_of::<SomeStruct>() == 4usize); |
| 1941 | const _: () = assert!(offset_of!(SomeStruct, public_int) * 8 == 0usize); |
| 1942 | const _: () = assert!(offset_of!(SomeStruct, protected_int) * 8 == 32usize); |
| 1943 | const _: () = assert!(offset_of!(SomeStruct, private_int) * 8 == 64usize); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1944 | } |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1945 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1946 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 1947 | assert_cc_matches!( |
| 1948 | rs_api_impl, |
| 1949 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1950 | extern "C" void __rust_thunk___ZN10SomeStructD1Ev(class SomeStruct * __this) { |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 1951 | std :: destroy_at (__this) ; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1952 | } |
| 1953 | } |
| 1954 | ); |
| 1955 | assert_cc_matches!( |
| 1956 | rs_api_impl, |
| 1957 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1958 | static_assert(sizeof(class SomeStruct) == 12); |
| 1959 | static_assert(alignof(class SomeStruct) == 4); |
| 1960 | static_assert(offsetof(class SomeStruct, public_int) * 8 == 0); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 1961 | } |
Googler | 5ea8864 | 2021-09-29 08:05:59 +0000 | [diff] [blame] | 1962 | ); |
Marcel Hlopko | b4b2874 | 2021-09-15 12:45:20 +0000 | [diff] [blame] | 1963 | Ok(()) |
| 1964 | } |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 1965 | |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 1966 | #[test] |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 1967 | fn test_ref_to_struct_in_thunk_impls() -> Result<()> { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1968 | let ir = ir_from_cc("struct S{}; inline void foo(class S& s) {} ")?; |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 1969 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 1970 | assert_cc_matches!( |
| 1971 | rs_api_impl, |
| 1972 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1973 | extern "C" void __rust_thunk___Z3fooR1S(class S& s) { |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 1974 | foo(s); |
| 1975 | } |
| 1976 | } |
| 1977 | ); |
| 1978 | Ok(()) |
| 1979 | } |
| 1980 | |
| 1981 | #[test] |
| 1982 | fn test_const_ref_to_struct_in_thunk_impls() -> Result<()> { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1983 | let ir = ir_from_cc("struct S{}; inline void foo(const class S& s) {} ")?; |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 1984 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 1985 | assert_cc_matches!( |
| 1986 | rs_api_impl, |
| 1987 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 1988 | extern "C" void __rust_thunk___Z3fooRK1S(const class S& s) { |
Lukasz Anforowicz | 275fa92 | 2022-01-05 16:13:20 +0000 | [diff] [blame] | 1989 | foo(s); |
| 1990 | } |
| 1991 | } |
| 1992 | ); |
| 1993 | Ok(()) |
| 1994 | } |
| 1995 | |
| 1996 | #[test] |
Lukasz Anforowicz | 957cbf2 | 2022-01-05 16:14:05 +0000 | [diff] [blame] | 1997 | fn test_unsigned_int_in_thunk_impls() -> Result<()> { |
| 1998 | let ir = ir_from_cc("inline void foo(unsigned int i) {} ")?; |
| 1999 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 2000 | assert_cc_matches!( |
| 2001 | rs_api_impl, |
| 2002 | quote! { |
| 2003 | extern "C" void __rust_thunk___Z3fooj(unsigned int i) { |
| 2004 | foo(i); |
| 2005 | } |
| 2006 | } |
| 2007 | ); |
| 2008 | Ok(()) |
| 2009 | } |
| 2010 | |
| 2011 | #[test] |
Marcel Hlopko | dd1fcb1 | 2021-12-22 14:13:59 +0000 | [diff] [blame] | 2012 | fn test_record_static_methods_qualify_call_in_thunk() -> Result<()> { |
| 2013 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 2014 | struct SomeStruct { |
| 2015 | static inline int some_func() { return 42; } |
| 2016 | }; |
| 2017 | })?)?; |
| 2018 | |
| 2019 | assert_cc_matches!( |
| 2020 | generate_rs_api_impl(&ir)?, |
| 2021 | quote! { |
| 2022 | extern "C" int __rust_thunk___ZN10SomeStruct9some_funcEv() { |
| 2023 | return SomeStruct::some_func(); |
| 2024 | } |
| 2025 | } |
| 2026 | ); |
| 2027 | Ok(()) |
| 2028 | } |
| 2029 | |
| 2030 | #[test] |
Lukasz Anforowicz | b3d89aa | 2022-01-12 14:35:52 +0000 | [diff] [blame] | 2031 | fn test_record_instance_methods_deref_this_in_thunk() -> Result<()> { |
| 2032 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 2033 | struct SomeStruct { |
| 2034 | inline int some_func(int arg) const { return 42 + arg; } |
| 2035 | }; |
| 2036 | })?)?; |
| 2037 | |
| 2038 | assert_cc_matches!( |
| 2039 | generate_rs_api_impl(&ir)?, |
| 2040 | quote! { |
| 2041 | extern "C" int __rust_thunk___ZNK10SomeStruct9some_funcEi( |
| 2042 | const class SomeStruct* __this, int arg) { |
| 2043 | return __this->some_func(arg); |
| 2044 | } |
| 2045 | } |
| 2046 | ); |
| 2047 | Ok(()) |
| 2048 | } |
| 2049 | |
| 2050 | #[test] |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2051 | fn test_struct_from_other_target() -> Result<()> { |
| 2052 | let ir = ir_from_cc_dependency("// intentionally empty", "struct SomeStruct {};")?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2053 | assert_rs_not_matches!(generate_rs_api(&ir)?, quote! { SomeStruct }); |
| 2054 | assert_cc_not_matches!(generate_rs_api_impl(&ir)?, quote! { SomeStruct }); |
Marcel Hlopko | a0f3866 | 2021-12-03 08:45:26 +0000 | [diff] [blame] | 2055 | Ok(()) |
| 2056 | } |
| 2057 | |
| 2058 | #[test] |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2059 | fn test_copy_derives() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 2060 | let record = ir_record("S"); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2061 | assert_eq!(generate_derives(&record), &["Clone", "Copy"]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2062 | } |
| 2063 | |
| 2064 | #[test] |
| 2065 | fn test_copy_derives_not_is_trivial_abi() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 2066 | let mut record = ir_record("S"); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2067 | record.is_trivial_abi = false; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2068 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2069 | } |
| 2070 | |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2071 | /// Even if it's trivially relocatable, !Unpin C++ type cannot be |
| 2072 | /// cloned/copied or otherwise used by value, because values would allow |
| 2073 | /// assignment into the Pin. |
| 2074 | /// |
| 2075 | /// All !Unpin C++ types, not just non trivially relocatable ones, are |
| 2076 | /// unsafe to assign in the Rust sense. |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 2077 | #[test] |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2078 | fn test_copy_derives_not_final() { |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 2079 | let mut record = ir_record("S"); |
| 2080 | record.is_final = false; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2081 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 2082 | } |
| 2083 | |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2084 | #[test] |
| 2085 | fn test_copy_derives_ctor_nonpublic() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 2086 | let mut record = ir_record("S"); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2087 | for access in [ir::AccessSpecifier::Protected, ir::AccessSpecifier::Private] { |
| 2088 | record.copy_constructor.access = access; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2089 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2090 | } |
| 2091 | } |
| 2092 | |
| 2093 | #[test] |
| 2094 | fn test_copy_derives_ctor_deleted() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 2095 | let mut record = ir_record("S"); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2096 | record.copy_constructor.definition = ir::SpecialMemberDefinition::Deleted; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2097 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2098 | } |
| 2099 | |
| 2100 | #[test] |
Devin Jeanpierre | be2f33b | 2021-10-21 12:54:19 +0000 | [diff] [blame] | 2101 | fn test_copy_derives_ctor_nontrivial_members() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 2102 | let mut record = ir_record("S"); |
Devin Jeanpierre | be2f33b | 2021-10-21 12:54:19 +0000 | [diff] [blame] | 2103 | record.copy_constructor.definition = ir::SpecialMemberDefinition::NontrivialMembers; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2104 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | be2f33b | 2021-10-21 12:54:19 +0000 | [diff] [blame] | 2105 | } |
| 2106 | |
| 2107 | #[test] |
| 2108 | fn test_copy_derives_ctor_nontrivial_self() { |
Devin Jeanpierre | ccfefc8 | 2021-10-27 10:54:00 +0000 | [diff] [blame] | 2109 | let mut record = ir_record("S"); |
Devin Jeanpierre | 7b62e95 | 2021-12-08 21:43:30 +0000 | [diff] [blame] | 2110 | record.copy_constructor.definition = ir::SpecialMemberDefinition::NontrivialUserDefined; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2111 | assert_eq!(generate_derives(&record), &[""; 0]); |
Devin Jeanpierre | 2ed14ec | 2021-10-06 11:32:19 +0000 | [diff] [blame] | 2112 | } |
| 2113 | |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2114 | #[test] |
| 2115 | fn test_ptr_func() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2116 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 2117 | inline int* Deref(int*const* p); |
| 2118 | })?)?; |
Devin Jeanpierre | d6da700 | 2021-10-21 12:55:20 +0000 | [diff] [blame] | 2119 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2120 | let rs_api = generate_rs_api(&ir)?; |
| 2121 | assert_rs_matches!( |
| 2122 | rs_api, |
| 2123 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2124 | #[inline(always)] |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 2125 | pub unsafe fn Deref(p: *const *mut i32) -> *mut i32 { |
| 2126 | crate::detail::__rust_thunk___Z5DerefPKPi(p) |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2127 | } |
| 2128 | } |
| 2129 | ); |
| 2130 | assert_rs_matches!( |
| 2131 | rs_api, |
| 2132 | quote! { |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2133 | mod detail { |
Googler | 5564714 | 2022-01-11 12:37:39 +0000 | [diff] [blame] | 2134 | #[allow(unused_imports)] |
Devin Jeanpierre | d4dde0e | 2021-10-13 20:48:25 +0000 | [diff] [blame] | 2135 | use super::*; |
Michael Forster | db8101a | 2021-10-08 06:56:03 +0000 | [diff] [blame] | 2136 | extern "C" { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2137 | pub(crate) fn __rust_thunk___Z5DerefPKPi(p: *const *mut i32) -> *mut i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2138 | } |
| 2139 | } |
| 2140 | } |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2141 | ); |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 2142 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2143 | assert_cc_matches!( |
| 2144 | generate_rs_api_impl(&ir)?, |
| 2145 | quote! { |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2146 | extern "C" int* __rust_thunk___Z5DerefPKPi(int* const * p) { |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 2147 | return Deref(p); |
| 2148 | } |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2149 | } |
Devin Jeanpierre | 184f9ac | 2021-09-17 13:47:03 +0000 | [diff] [blame] | 2150 | ); |
Devin Jeanpierre | 7a7328e | 2021-09-17 07:10:08 +0000 | [diff] [blame] | 2151 | Ok(()) |
| 2152 | } |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 2153 | |
| 2154 | #[test] |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 2155 | fn test_const_char_ptr_func() -> Result<()> { |
| 2156 | // This is a regression test: We used to include the "const" in the name |
| 2157 | // of the CcType, which caused a panic in the code generator |
| 2158 | // ('"const char" is not a valid Ident'). |
| 2159 | // It's therefore important that f() is inline so that we need to |
| 2160 | // generate a thunk for it (where we then process the CcType). |
| 2161 | let ir = ir_from_cc(&tokens_to_string(quote! { |
| 2162 | inline void f(const char *str); |
| 2163 | })?)?; |
| 2164 | |
| 2165 | let rs_api = generate_rs_api(&ir)?; |
| 2166 | assert_rs_matches!( |
| 2167 | rs_api, |
| 2168 | quote! { |
| 2169 | #[inline(always)] |
Lukasz Anforowicz | f7bdd39 | 2022-01-21 00:33:39 +0000 | [diff] [blame] | 2170 | pub unsafe fn f(str: *const i8) { |
| 2171 | crate::detail::__rust_thunk___Z1fPKc(str) |
Googler | db11153 | 2022-01-05 06:12:13 +0000 | [diff] [blame] | 2172 | } |
| 2173 | } |
| 2174 | ); |
| 2175 | assert_rs_matches!( |
| 2176 | rs_api, |
| 2177 | quote! { |
| 2178 | extern "C" { |
| 2179 | pub(crate) fn __rust_thunk___Z1fPKc(str: *const i8); |
| 2180 | } |
| 2181 | } |
| 2182 | ); |
| 2183 | |
| 2184 | assert_cc_matches!( |
| 2185 | generate_rs_api_impl(&ir)?, |
| 2186 | quote! { |
| 2187 | extern "C" void __rust_thunk___Z1fPKc(char const * str){ f(str) ; } |
| 2188 | } |
| 2189 | ); |
| 2190 | Ok(()) |
| 2191 | } |
| 2192 | |
| 2193 | #[test] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 2194 | fn test_func_ptr_where_params_are_primitive_types() -> Result<()> { |
| 2195 | let ir = ir_from_cc(r#" int (*get_ptr_to_func())(float, double); "#)?; |
| 2196 | let rs_api = generate_rs_api(&ir)?; |
| 2197 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 2198 | assert_rs_matches!( |
| 2199 | rs_api, |
| 2200 | quote! { |
| 2201 | #[inline(always)] |
| 2202 | pub fn get_ptr_to_func() -> Option<extern "C" fn (f32, f64) -> i32> { |
| 2203 | unsafe { crate::detail::__rust_thunk___Z15get_ptr_to_funcv() } |
| 2204 | } |
| 2205 | } |
| 2206 | ); |
| 2207 | assert_rs_matches!( |
| 2208 | rs_api, |
| 2209 | quote! { |
| 2210 | mod detail { |
| 2211 | #[allow(unused_imports)] |
| 2212 | use super::*; |
| 2213 | extern "C" { |
| 2214 | #[link_name = "_Z15get_ptr_to_funcv"] |
| 2215 | pub(crate) fn __rust_thunk___Z15get_ptr_to_funcv() |
| 2216 | -> Option<extern "C" fn(f32, f64) -> i32>; |
| 2217 | } |
| 2218 | } |
| 2219 | } |
| 2220 | ); |
| 2221 | // Verify that no C++ thunk got generated. |
| 2222 | assert_cc_not_matches!(rs_api_impl, quote! { __rust_thunk___Z15get_ptr_to_funcv }); |
| 2223 | |
| 2224 | // TODO(b/217419782): Add another test for more exotic calling conventions / |
| 2225 | // abis. |
| 2226 | |
| 2227 | // TODO(b/217419782): Add another test for pointer to a function that |
| 2228 | // takes/returns non-trivially-movable types by value. See also |
| 2229 | // <internal link> |
| 2230 | |
| 2231 | Ok(()) |
| 2232 | } |
| 2233 | |
| 2234 | #[test] |
| 2235 | fn test_func_ptr_with_non_static_lifetime() -> Result<()> { |
| 2236 | let ir = ir_from_cc( |
| 2237 | r#" |
Googler | 53f6594 | 2022-02-23 11:23:30 +0000 | [diff] [blame] | 2238 | [[clang::annotate("lifetimes", "-> a")]] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 2239 | int (*get_ptr_to_func())(float, double); "#, |
| 2240 | )?; |
| 2241 | let rs_api = generate_rs_api(&ir)?; |
| 2242 | assert_rs_matches!( |
| 2243 | rs_api, |
| 2244 | quote! { |
| 2245 | // Error while generating bindings for item 'get_ptr_to_func': |
| 2246 | // Return type is not supported: Function pointers with non-'static lifetimes are not supported: int (*)(float, double) |
| 2247 | } |
| 2248 | ); |
| 2249 | Ok(()) |
| 2250 | } |
| 2251 | |
| 2252 | #[test] |
| 2253 | fn test_func_ptr_where_params_are_raw_ptrs() -> Result<()> { |
| 2254 | let ir = ir_from_cc(r#" const int* (*get_ptr_to_func())(const int*); "#)?; |
| 2255 | let rs_api = generate_rs_api(&ir)?; |
| 2256 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 2257 | assert_rs_matches!( |
| 2258 | rs_api, |
| 2259 | quote! { |
| 2260 | #[inline(always)] |
| 2261 | pub fn get_ptr_to_func() -> Option<extern "C" fn (*const i32) -> *const i32> { |
| 2262 | unsafe { crate::detail::__rust_thunk___Z15get_ptr_to_funcv() } |
| 2263 | } |
| 2264 | } |
| 2265 | ); |
| 2266 | assert_rs_matches!( |
| 2267 | rs_api, |
| 2268 | quote! { |
| 2269 | mod detail { |
| 2270 | #[allow(unused_imports)] |
| 2271 | use super::*; |
| 2272 | extern "C" { |
| 2273 | #[link_name = "_Z15get_ptr_to_funcv"] |
| 2274 | pub(crate) fn __rust_thunk___Z15get_ptr_to_funcv() |
| 2275 | -> Option<extern "C" fn(*const i32) -> *const i32>; |
| 2276 | } |
| 2277 | } |
| 2278 | } |
| 2279 | ); |
| 2280 | // Verify that no C++ thunk got generated. |
| 2281 | assert_cc_not_matches!(rs_api_impl, quote! { __rust_thunk___Z15get_ptr_to_funcv }); |
| 2282 | |
| 2283 | // TODO(b/217419782): Add another test where params (and the return |
| 2284 | // type) are references with lifetimes. Something like this: |
| 2285 | // #pragma clang lifetime_elision |
| 2286 | // const int& (*get_ptr_to_func())(const int&, const int&); "#)?; |
| 2287 | // 1) Need to investigate why this fails - seeing raw pointers in Rust |
| 2288 | // seems to indicate that no lifetimes are present at the `importer.cc` |
| 2289 | // level. Maybe lifetime elision doesn't support this scenario? Unclear |
Googler | 53f6594 | 2022-02-23 11:23:30 +0000 | [diff] [blame] | 2290 | // how to explicitly apply [[clang::annotate("lifetimes", "a, b -> a")]] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 2291 | // to the _inner_ function. |
| 2292 | // 2) It is important to have 2 reference parameters, so see if the problem |
| 2293 | // of passing `lifetimes` by value would have been caught - see: |
| 2294 | // cl/428079010/depot/rs_bindings_from_cc/ |
| 2295 | // importer.cc?version=s6#823 |
| 2296 | |
| 2297 | // TODO(b/217419782): Decide what to do if the C++ pointer is *not* |
| 2298 | // annotated with a lifetime - emit `unsafe fn(...) -> ...` in that |
| 2299 | // case? |
| 2300 | |
| 2301 | Ok(()) |
| 2302 | } |
| 2303 | |
| 2304 | #[test] |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 2305 | fn test_item_order() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2306 | let ir = ir_from_cc( |
| 2307 | "int first_func(); |
| 2308 | struct FirstStruct {}; |
| 2309 | int second_func(); |
| 2310 | struct SecondStruct {};", |
| 2311 | )?; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 2312 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2313 | let rs_api = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?; |
| 2314 | |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 2315 | 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] | 2316 | |
| 2317 | let f1 = idx("fn first_func")?; |
| 2318 | let f2 = idx("fn second_func")?; |
| 2319 | let s1 = idx("struct FirstStruct")?; |
| 2320 | let s2 = idx("struct SecondStruct")?; |
Googler | a675ae0 | 2021-12-07 08:04:59 +0000 | [diff] [blame] | 2321 | let t1 = idx("fn __rust_thunk___Z10first_funcv")?; |
| 2322 | let t2 = idx("fn __rust_thunk___Z11second_funcv")?; |
Michael Forster | ed64202 | 2021-10-04 09:48:25 +0000 | [diff] [blame] | 2323 | |
| 2324 | assert!(f1 < s1); |
| 2325 | assert!(s1 < f2); |
| 2326 | assert!(f2 < s2); |
| 2327 | assert!(s2 < t1); |
| 2328 | assert!(t1 < t2); |
| 2329 | |
| 2330 | Ok(()) |
| 2331 | } |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 2332 | |
| 2333 | #[test] |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2334 | fn test_base_class_subobject_layout() -> Result<()> { |
| 2335 | let ir = ir_from_cc( |
| 2336 | r#" |
| 2337 | // We use a class here to force `Derived::z` to live inside the tail padding of `Base`. |
| 2338 | // 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] | 2339 | class Base {__INT64_TYPE__ x; char y;}; |
| 2340 | struct Derived final : Base {__INT16_TYPE__ z;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2341 | "#, |
| 2342 | )?; |
| 2343 | let rs_api = generate_rs_api(&ir)?; |
| 2344 | assert_rs_matches!( |
| 2345 | rs_api, |
| 2346 | quote! { |
| 2347 | #[repr(C, align(8))] |
| 2348 | pub struct Derived { |
| 2349 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; 10], |
| 2350 | pub z: i16, |
| 2351 | } |
| 2352 | } |
| 2353 | ); |
| 2354 | Ok(()) |
| 2355 | } |
| 2356 | |
| 2357 | /// The same as test_base_class_subobject_layout, but with multiple |
| 2358 | /// inheritance. |
| 2359 | #[test] |
| 2360 | fn test_base_class_multiple_inheritance_subobject_layout() -> Result<()> { |
| 2361 | let ir = ir_from_cc( |
| 2362 | r#" |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2363 | class Base1 {__INT64_TYPE__ x;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2364 | class Base2 {char y;}; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2365 | struct Derived final : Base1, Base2 {__INT16_TYPE__ z;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2366 | "#, |
| 2367 | )?; |
| 2368 | let rs_api = generate_rs_api(&ir)?; |
| 2369 | assert_rs_matches!( |
| 2370 | rs_api, |
| 2371 | quote! { |
| 2372 | #[repr(C, align(8))] |
| 2373 | pub struct Derived { |
| 2374 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; 10], |
| 2375 | pub z: i16, |
| 2376 | } |
| 2377 | } |
| 2378 | ); |
| 2379 | Ok(()) |
| 2380 | } |
| 2381 | |
| 2382 | /// The same as test_base_class_subobject_layout, but with a chain of |
| 2383 | /// inheritance. |
| 2384 | #[test] |
| 2385 | fn test_base_class_deep_inheritance_subobject_layout() -> Result<()> { |
| 2386 | let ir = ir_from_cc( |
| 2387 | r#" |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2388 | class Base1 {__INT64_TYPE__ x;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2389 | class Base2 : Base1 {char y;}; |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2390 | struct Derived final : Base2 {__INT16_TYPE__ z;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2391 | "#, |
| 2392 | )?; |
| 2393 | let rs_api = generate_rs_api(&ir)?; |
| 2394 | assert_rs_matches!( |
| 2395 | rs_api, |
| 2396 | quote! { |
| 2397 | #[repr(C, align(8))] |
| 2398 | pub struct Derived { |
| 2399 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; 10], |
| 2400 | pub z: i16, |
| 2401 | } |
| 2402 | } |
| 2403 | ); |
| 2404 | Ok(()) |
| 2405 | } |
| 2406 | |
| 2407 | /// For derived classes with no data members, we can't use the offset of the |
| 2408 | /// first member to determine the size of the base class subobjects. |
| 2409 | #[test] |
| 2410 | fn test_base_class_subobject_fieldless_layout() -> Result<()> { |
| 2411 | let ir = ir_from_cc( |
| 2412 | r#" |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2413 | class Base {__INT64_TYPE__ x; char y;}; |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2414 | struct Derived final : Base {}; |
| 2415 | "#, |
| 2416 | )?; |
| 2417 | let rs_api = generate_rs_api(&ir)?; |
| 2418 | assert_rs_matches!( |
| 2419 | rs_api, |
| 2420 | quote! { |
| 2421 | #[repr(C, align(8))] |
| 2422 | pub struct Derived { |
| 2423 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; 9], |
| 2424 | } |
| 2425 | } |
| 2426 | ); |
| 2427 | Ok(()) |
| 2428 | } |
| 2429 | |
| 2430 | #[test] |
| 2431 | fn test_base_class_subobject_empty_fieldless() -> Result<()> { |
| 2432 | let ir = ir_from_cc( |
| 2433 | r#" |
| 2434 | class Base {}; |
| 2435 | struct Derived final : Base {}; |
| 2436 | "#, |
| 2437 | )?; |
| 2438 | let rs_api = generate_rs_api(&ir)?; |
| 2439 | assert_rs_matches!( |
| 2440 | rs_api, |
| 2441 | quote! { |
| 2442 | #[repr(C)] |
| 2443 | pub struct Derived { |
| 2444 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; 0], |
| 2445 | /// Prevent empty C++ struct being zero-size in Rust. |
| 2446 | placeholder: std::mem::MaybeUninit<u8>, |
| 2447 | } |
| 2448 | } |
| 2449 | ); |
| 2450 | Ok(()) |
| 2451 | } |
| 2452 | |
| 2453 | #[test] |
| 2454 | fn test_base_class_subobject_empty() -> Result<()> { |
| 2455 | let ir = ir_from_cc( |
| 2456 | r#" |
| 2457 | class Base {}; |
| 2458 | struct Derived final : Base {}; |
| 2459 | "#, |
| 2460 | )?; |
| 2461 | let rs_api = generate_rs_api(&ir)?; |
| 2462 | assert_rs_matches!( |
| 2463 | rs_api, |
| 2464 | quote! { |
| 2465 | #[repr(C)] |
| 2466 | pub struct Derived { |
| 2467 | __base_class_subobjects: [std::mem::MaybeUninit<u8>; 0], |
| 2468 | /// Prevent empty C++ struct being zero-size in Rust. |
| 2469 | placeholder: std::mem::MaybeUninit<u8>, |
| 2470 | } |
| 2471 | } |
| 2472 | ); |
| 2473 | Ok(()) |
| 2474 | } |
| 2475 | |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 2476 | /// When a field is [[no_unique_address]], it occupies the space up to the |
| 2477 | /// next field. |
| 2478 | #[test] |
| 2479 | fn test_no_unique_address() -> Result<()> { |
| 2480 | let ir = ir_from_cc( |
| 2481 | r#" |
| 2482 | class Field1 {__INT64_TYPE__ x;}; |
| 2483 | class Field2 {char y;}; |
| 2484 | struct Struct final { |
| 2485 | [[no_unique_address]] Field1 field1; |
| 2486 | [[no_unique_address]] Field2 field2; |
| 2487 | __INT16_TYPE__ z; |
| 2488 | }; |
| 2489 | "#, |
| 2490 | )?; |
| 2491 | let rs_api = generate_rs_api(&ir)?; |
| 2492 | assert_rs_matches!( |
| 2493 | rs_api, |
| 2494 | quote! { |
| 2495 | #[derive(Clone, Copy)] |
| 2496 | #[repr(C, align(8))] |
| 2497 | pub struct Struct { |
| 2498 | field1: [std::mem::MaybeUninit<u8>; 8], |
| 2499 | field2: [std::mem::MaybeUninit<u8>; 2], |
| 2500 | pub z: i16, |
| 2501 | } |
Devin Jeanpierre | 58181ac | 2022-02-14 21:30:05 +0000 | [diff] [blame] | 2502 | |
| 2503 | impl Struct { |
| 2504 | pub fn field1(&self) -> &Field1 { |
| 2505 | unsafe {&* (&self.field1 as *const _ as *const Field1)} |
| 2506 | } |
| 2507 | pub fn field2(&self) -> &Field2 { |
| 2508 | unsafe {&* (&self.field2 as *const _ as *const Field2)} |
| 2509 | } |
| 2510 | } |
Devin Jeanpierre | b69bcae | 2022-02-03 09:45:50 +0000 | [diff] [blame] | 2511 | } |
| 2512 | ); |
| 2513 | Ok(()) |
| 2514 | } |
| 2515 | |
| 2516 | /// When a [[no_unique_address]] field is the last one, it occupies the rest |
| 2517 | /// of the object. |
| 2518 | #[test] |
| 2519 | fn test_no_unique_address_last_field() -> Result<()> { |
| 2520 | let ir = ir_from_cc( |
| 2521 | r#" |
| 2522 | class Field1 {__INT64_TYPE__ x;}; |
| 2523 | class Field2 {char y;}; |
| 2524 | struct Struct final { |
| 2525 | [[no_unique_address]] Field1 field1; |
| 2526 | [[no_unique_address]] Field2 field2; |
| 2527 | }; |
| 2528 | "#, |
| 2529 | )?; |
| 2530 | let rs_api = generate_rs_api(&ir)?; |
| 2531 | assert_rs_matches!( |
| 2532 | rs_api, |
| 2533 | quote! { |
| 2534 | #[derive(Clone, Copy)] |
| 2535 | #[repr(C, align(8))] |
| 2536 | pub struct Struct { |
| 2537 | field1: [std::mem::MaybeUninit<u8>; 8], |
| 2538 | field2: [std::mem::MaybeUninit<u8>; 8], |
| 2539 | } |
| 2540 | } |
| 2541 | ); |
| 2542 | Ok(()) |
| 2543 | } |
| 2544 | |
| 2545 | #[test] |
| 2546 | fn test_no_unique_address_empty() -> Result<()> { |
| 2547 | let ir = ir_from_cc( |
| 2548 | r#" |
| 2549 | class Field {}; |
| 2550 | struct Struct final { |
| 2551 | [[no_unique_address]] Field field; |
| 2552 | int x; |
| 2553 | }; |
| 2554 | "#, |
| 2555 | )?; |
| 2556 | let rs_api = generate_rs_api(&ir)?; |
| 2557 | assert_rs_matches!( |
| 2558 | rs_api, |
| 2559 | quote! { |
| 2560 | #[repr(C, align(4))] |
| 2561 | pub struct Struct { |
| 2562 | field: [std::mem::MaybeUninit<u8>; 0], |
| 2563 | pub x: i32, |
| 2564 | } |
| 2565 | } |
| 2566 | ); |
| 2567 | Ok(()) |
| 2568 | } |
| 2569 | |
| 2570 | #[test] |
| 2571 | fn test_base_class_subobject_empty_last_field() -> Result<()> { |
| 2572 | let ir = ir_from_cc( |
| 2573 | r#" |
| 2574 | class Field {}; |
| 2575 | struct Struct final { |
| 2576 | [[no_unique_address]] Field field; |
| 2577 | }; |
| 2578 | "#, |
| 2579 | )?; |
| 2580 | let rs_api = generate_rs_api(&ir)?; |
| 2581 | assert_rs_matches!( |
| 2582 | rs_api, |
| 2583 | quote! { |
| 2584 | #[repr(C)] |
| 2585 | pub struct Struct { |
| 2586 | field: [std::mem::MaybeUninit<u8>; 1], |
| 2587 | } |
| 2588 | } |
| 2589 | ); |
| 2590 | Ok(()) |
| 2591 | } |
| 2592 | |
Devin Jeanpierre | c80e624 | 2022-02-03 01:56:40 +0000 | [diff] [blame] | 2593 | #[test] |
Teddy Katz | 76fa42b | 2022-02-23 01:22:56 +0000 | [diff] [blame] | 2594 | fn test_generate_enum_basic() -> Result<()> { |
| 2595 | let ir = ir_from_cc("enum Color { kRed = 5, kBlue };")?; |
| 2596 | let rs_api = generate_rs_api(&ir)?; |
| 2597 | assert_rs_matches!( |
| 2598 | rs_api, |
| 2599 | quote! { |
| 2600 | #[repr(transparent)] |
| 2601 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 2602 | pub struct Color(u32); |
| 2603 | impl Color { |
| 2604 | pub const kRed: Color = Color(5); |
| 2605 | pub const kBlue: Color = Color(6); |
| 2606 | } |
| 2607 | impl From<u32> for Color { |
| 2608 | fn from(value: u32) -> Color { |
| 2609 | Color(v) |
| 2610 | } |
| 2611 | } |
| 2612 | impl From<Color> for u32 { |
| 2613 | fn from(value: Color) -> u32 { |
| 2614 | v.0 |
| 2615 | } |
| 2616 | } |
| 2617 | } |
| 2618 | ); |
| 2619 | Ok(()) |
| 2620 | } |
| 2621 | |
| 2622 | #[test] |
| 2623 | fn test_generate_scoped_enum_basic() -> Result<()> { |
| 2624 | let ir = ir_from_cc("enum class Color { kRed = -5, kBlue };")?; |
| 2625 | let rs_api = generate_rs_api(&ir)?; |
| 2626 | assert_rs_matches!( |
| 2627 | rs_api, |
| 2628 | quote! { |
| 2629 | #[repr(transparent)] |
| 2630 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 2631 | pub struct Color(i32); |
| 2632 | impl Color { |
| 2633 | pub const kRed: Color = Color(-5); |
| 2634 | pub const kBlue: Color = Color(-4); |
| 2635 | } |
| 2636 | impl From<i32> for Color { |
| 2637 | fn from(value: i32) -> Color { |
| 2638 | Color(v) |
| 2639 | } |
| 2640 | } |
| 2641 | impl From<Color> for i32 { |
| 2642 | fn from(value: Color) -> i32 { |
| 2643 | v.0 |
| 2644 | } |
| 2645 | } |
| 2646 | } |
| 2647 | ); |
| 2648 | Ok(()) |
| 2649 | } |
| 2650 | |
| 2651 | #[test] |
| 2652 | fn test_generate_enum_with_64_bit_signed_vals() -> Result<()> { |
| 2653 | let ir = ir_from_cc( |
| 2654 | "enum Color : long { kViolet = -9223372036854775807 - 1LL, kRed = -5, kBlue, kGreen = 3, kMagenta = 9223372036854775807 };", |
| 2655 | )?; |
| 2656 | let rs_api = generate_rs_api(&ir)?; |
| 2657 | assert_rs_matches!( |
| 2658 | rs_api, |
| 2659 | quote! { |
| 2660 | #[repr(transparent)] |
| 2661 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 2662 | pub struct Color(i64); |
| 2663 | impl Color { |
| 2664 | pub const kViolet: Color = Color(-9223372036854775808); |
| 2665 | pub const kRed: Color = Color(-5); |
| 2666 | pub const kBlue: Color = Color(-4); |
| 2667 | pub const kGreen: Color = Color(3); |
| 2668 | pub const kMagenta: Color = Color(9223372036854775807); |
| 2669 | } |
| 2670 | impl From<i64> for Color { |
| 2671 | fn from(value: i64) -> Color { |
| 2672 | Color(v) |
| 2673 | } |
| 2674 | } |
| 2675 | impl From<Color> for i64 { |
| 2676 | fn from(value: Color) -> i64 { |
| 2677 | v.0 |
| 2678 | } |
| 2679 | } |
| 2680 | } |
| 2681 | ); |
| 2682 | Ok(()) |
| 2683 | } |
| 2684 | |
| 2685 | #[test] |
| 2686 | fn test_generate_enum_with_64_bit_unsigned_vals() -> Result<()> { |
| 2687 | let ir = ir_from_cc( |
| 2688 | "enum Color: unsigned long { kRed, kBlue, kLimeGreen = 18446744073709551615 };", |
| 2689 | )?; |
| 2690 | let rs_api = generate_rs_api(&ir)?; |
| 2691 | assert_rs_matches!( |
| 2692 | rs_api, |
| 2693 | quote! { |
| 2694 | #[repr(transparent)] |
| 2695 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 2696 | pub struct Color(u64); |
| 2697 | impl Color { |
| 2698 | pub const kRed: Color = Color(0); |
| 2699 | pub const kBlue: Color = Color(1); |
| 2700 | pub const kLimeGreen: Color = Color(18446744073709551615); |
| 2701 | } |
| 2702 | impl From<u64> for Color { |
| 2703 | fn from(value: u64) -> Color { |
| 2704 | Color(v) |
| 2705 | } |
| 2706 | } |
| 2707 | impl From<Color> for u64 { |
| 2708 | fn from(value: Color) -> u64 { |
| 2709 | v.0 |
| 2710 | } |
| 2711 | } |
| 2712 | } |
| 2713 | ); |
| 2714 | Ok(()) |
| 2715 | } |
| 2716 | |
| 2717 | #[test] |
| 2718 | fn test_generate_enum_with_32_bit_signed_vals() -> Result<()> { |
| 2719 | let ir = ir_from_cc( |
| 2720 | "enum Color { kViolet = -2147483647 - 1, kRed = -5, kBlue, kGreen = 3, kMagenta = 2147483647 };", |
| 2721 | )?; |
| 2722 | let rs_api = generate_rs_api(&ir)?; |
| 2723 | assert_rs_matches!( |
| 2724 | rs_api, |
| 2725 | quote! { |
| 2726 | #[repr(transparent)] |
| 2727 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 2728 | pub struct Color(i32); |
| 2729 | impl Color { |
| 2730 | pub const kViolet: Color = Color(-2147483648); |
| 2731 | pub const kRed: Color = Color(-5); |
| 2732 | pub const kBlue: Color = Color(-4); |
| 2733 | pub const kGreen: Color = Color(3); |
| 2734 | pub const kMagenta: Color = Color(2147483647); |
| 2735 | } |
| 2736 | impl From<i32> for Color { |
| 2737 | fn from(value: i32) -> Color { |
| 2738 | Color(v) |
| 2739 | } |
| 2740 | } |
| 2741 | impl From<Color> for i32 { |
| 2742 | fn from(value: Color) -> i32 { |
| 2743 | v.0 |
| 2744 | } |
| 2745 | } |
| 2746 | } |
| 2747 | ); |
| 2748 | Ok(()) |
| 2749 | } |
| 2750 | |
| 2751 | #[test] |
| 2752 | fn test_generate_enum_with_32_bit_unsigned_vals() -> Result<()> { |
| 2753 | let ir = ir_from_cc("enum Color: unsigned int { kRed, kBlue, kLimeGreen = 4294967295 };")?; |
| 2754 | let rs_api = generate_rs_api(&ir)?; |
| 2755 | assert_rs_matches!( |
| 2756 | rs_api, |
| 2757 | quote! { |
| 2758 | #[repr(transparent)] |
| 2759 | #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash, PartialOrd, Ord)] |
| 2760 | pub struct Color(u32); |
| 2761 | impl Color { |
| 2762 | pub const kRed: Color = Color(0); |
| 2763 | pub const kBlue: Color = Color(1); |
| 2764 | pub const kLimeGreen: Color = Color(4294967295); |
| 2765 | } |
| 2766 | impl From<u32> for Color { |
| 2767 | fn from(value: u32) -> Color { |
| 2768 | Color(v) |
| 2769 | } |
| 2770 | } |
| 2771 | impl From<Color> for u32 { |
| 2772 | fn from(value: Color) -> u32 { |
| 2773 | v.0 |
| 2774 | } |
| 2775 | } |
| 2776 | } |
| 2777 | ); |
| 2778 | Ok(()) |
| 2779 | } |
| 2780 | |
| 2781 | #[test] |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 2782 | fn test_doc_comment_func() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2783 | let ir = ir_from_cc( |
| 2784 | " |
| 2785 | // Doc Comment |
| 2786 | // with two lines |
| 2787 | int func();", |
| 2788 | )?; |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 2789 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2790 | assert_rs_matches!( |
| 2791 | generate_rs_api(&ir)?, |
| 2792 | // leading space is intentional so there is a space between /// and the text of the |
| 2793 | // comment |
| 2794 | quote! { |
| 2795 | #[doc = " Doc Comment\n with two lines"] |
| 2796 | #[inline(always)] |
| 2797 | pub fn func |
| 2798 | } |
Michael Forster | 409d941 | 2021-10-07 08:35:29 +0000 | [diff] [blame] | 2799 | ); |
| 2800 | |
| 2801 | Ok(()) |
| 2802 | } |
| 2803 | |
| 2804 | #[test] |
| 2805 | fn test_doc_comment_record() -> Result<()> { |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2806 | let ir = ir_from_cc( |
| 2807 | "// Doc Comment\n\ |
| 2808 | //\n\ |
| 2809 | // * with bullet\n\ |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2810 | struct SomeStruct final {\n\ |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2811 | // Field doc\n\ |
| 2812 | int field;\ |
| 2813 | };", |
| 2814 | )?; |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 2815 | |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2816 | assert_rs_matches!( |
| 2817 | generate_rs_api(&ir)?, |
| 2818 | quote! { |
| 2819 | #[doc = " Doc Comment\n \n * with bullet"] |
| 2820 | #[derive(Clone, Copy)] |
| 2821 | #[repr(C)] |
| 2822 | pub struct SomeStruct { |
| 2823 | # [doc = " Field doc"] |
| 2824 | pub field: i32, |
| 2825 | } |
| 2826 | } |
Michael Forster | cc5941a | 2021-10-07 07:12:24 +0000 | [diff] [blame] | 2827 | ); |
Michael Forster | 028800b | 2021-10-05 12:39:59 +0000 | [diff] [blame] | 2828 | Ok(()) |
| 2829 | } |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 2830 | |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 2831 | #[test] |
Devin Jeanpierre | 5677702 | 2022-02-03 01:57:15 +0000 | [diff] [blame] | 2832 | fn test_unambiguous_public_bases() -> Result<()> { |
| 2833 | let ir = ir_from_cc_dependency( |
| 2834 | " |
| 2835 | struct VirtualBase {}; |
| 2836 | struct PrivateBase {}; |
| 2837 | struct ProtectedBase {}; |
| 2838 | struct UnambiguousPublicBase {}; |
| 2839 | struct AmbiguousPublicBase {}; |
| 2840 | struct MultipleInheritance : UnambiguousPublicBase, AmbiguousPublicBase {}; |
| 2841 | struct Derived : private PrivateBase, protected ProtectedBase, MultipleInheritance, AmbiguousPublicBase, virtual VirtualBase {}; |
| 2842 | ", |
| 2843 | "", |
| 2844 | )?; |
| 2845 | let rs_api = generate_rs_api(&ir)?; |
| 2846 | // TODO(b/216195042): virtual bases. |
| 2847 | assert_rs_not_matches!(rs_api, quote! { From<&'a Derived> for &'a VirtualBase }); |
| 2848 | assert_rs_matches!(rs_api, quote! { From<&'a Derived> for &'a UnambiguousPublicBase }); |
| 2849 | assert_rs_matches!(rs_api, quote! { From<&'a Derived> for &'a MultipleInheritance }); |
| 2850 | assert_rs_not_matches!(rs_api, quote! {From<&'a Derived> for &'a PrivateBase}); |
| 2851 | assert_rs_not_matches!(rs_api, quote! {From<&'a Derived> for &'a ProtectedBase}); |
| 2852 | assert_rs_not_matches!(rs_api, quote! {From<&'a Derived> for &'a AmbiguousPublicBase}); |
| 2853 | Ok(()) |
| 2854 | } |
| 2855 | |
| 2856 | /// Contrary to intuitions: a base class conversion is ambiguous even if the |
| 2857 | /// ambiguity is from a private base class cast that you can't even |
| 2858 | /// perform. |
| 2859 | /// |
| 2860 | /// Explanation (courtesy James Dennett): |
| 2861 | /// |
| 2862 | /// > Once upon a time, there was a rule in C++ that changing all access |
| 2863 | /// > specifiers to "public" would not change the meaning of code. |
| 2864 | /// > That's no longer true, but some of its effects can still be seen. |
| 2865 | /// |
| 2866 | /// So, we need to be sure to not allow casting to privately-ambiguous |
| 2867 | /// bases. |
| 2868 | #[test] |
| 2869 | fn test_unambiguous_public_bases_private_ambiguity() -> Result<()> { |
| 2870 | let ir = ir_from_cc_dependency( |
| 2871 | " |
| 2872 | struct Base {}; |
| 2873 | struct Intermediate : public Base {}; |
| 2874 | struct Derived : Base, private Intermediate {}; |
| 2875 | ", |
| 2876 | "", |
| 2877 | )?; |
| 2878 | let rs_api = generate_rs_api(&ir)?; |
| 2879 | assert_rs_not_matches!(rs_api, quote! { From<&'a Derived> for &'a Base }); |
| 2880 | Ok(()) |
| 2881 | } |
| 2882 | |
| 2883 | #[test] |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 2884 | fn test_virtual_thunk() -> Result<()> { |
| 2885 | let ir = ir_from_cc("struct Polymorphic { virtual void Foo(); };")?; |
| 2886 | |
| 2887 | assert_cc_matches!( |
| 2888 | generate_rs_api_impl(&ir)?, |
| 2889 | quote! { |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 2890 | extern "C" void __rust_thunk___ZN11Polymorphic3FooEv(class Polymorphic * __this) |
Devin Jeanpierre | 96839c1 | 2021-12-14 00:27:38 +0000 | [diff] [blame] | 2891 | } |
| 2892 | ); |
| 2893 | Ok(()) |
| 2894 | } |
| 2895 | |
Devin Jeanpierre | e6e1665 | 2021-12-22 15:54:46 +0000 | [diff] [blame] | 2896 | /// A trivially relocatable final struct is safe to use in Rust as normal, |
| 2897 | /// and is Unpin. |
| 2898 | #[test] |
| 2899 | fn test_no_negative_impl_unpin() -> Result<()> { |
| 2900 | let ir = ir_from_cc("struct Trivial final {};")?; |
| 2901 | let rs_api = generate_rs_api(&ir)?; |
| 2902 | assert_rs_not_matches!(rs_api, quote! {impl !Unpin}); |
| 2903 | Ok(()) |
| 2904 | } |
| 2905 | |
| 2906 | /// A non-final struct, even if it's trivial, is not usable by mut |
| 2907 | /// reference, and so is !Unpin. |
| 2908 | #[test] |
| 2909 | fn test_negative_impl_unpin_nonfinal() -> Result<()> { |
| 2910 | let ir = ir_from_cc("struct Nonfinal {};")?; |
| 2911 | let rs_api = generate_rs_api(&ir)?; |
| 2912 | assert_rs_matches!(rs_api, quote! {impl !Unpin for Nonfinal {}}); |
| 2913 | Ok(()) |
| 2914 | } |
| 2915 | |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 2916 | /// At the least, a trivial type should have no drop impl if or until we add |
| 2917 | /// empty drop impls. |
| 2918 | #[test] |
| 2919 | fn test_no_impl_drop() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 2920 | let ir = ir_from_cc("struct Trivial {};")?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 2921 | let rs_api = rs_tokens_to_formatted_string(generate_rs_api(&ir)?)?; |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 2922 | assert!(!rs_api.contains("impl Drop")); |
| 2923 | Ok(()) |
| 2924 | } |
| 2925 | |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2926 | /// User-defined destructors *must* become Drop impls with ManuallyDrop |
| 2927 | /// fields |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 2928 | #[test] |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2929 | fn test_impl_drop_user_defined_destructor() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 2930 | let ir = ir_from_cc( |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2931 | r#" struct NontrivialStruct { ~NontrivialStruct(); }; |
| 2932 | struct UserDefinedDestructor { |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 2933 | ~UserDefinedDestructor(); |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2934 | int x; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2935 | NontrivialStruct nts; |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 2936 | };"#, |
| 2937 | )?; |
| 2938 | let rs_api = generate_rs_api(&ir)?; |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 2939 | assert_rs_matches!( |
| 2940 | rs_api, |
| 2941 | quote! { |
| 2942 | impl Drop for UserDefinedDestructor { |
| 2943 | #[inline(always)] |
| 2944 | fn drop(&mut self) { |
| 2945 | unsafe { crate::detail::__rust_thunk___ZN21UserDefinedDestructorD1Ev(self) } |
| 2946 | } |
| 2947 | } |
| 2948 | } |
| 2949 | ); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2950 | assert_rs_matches!(rs_api, quote! {pub x: i32,}); |
| 2951 | assert_rs_matches!(rs_api, quote! {pub nts: std::mem::ManuallyDrop<NontrivialStruct>,}); |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2952 | Ok(()) |
| 2953 | } |
| 2954 | |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 2955 | /// nontrivial types without user-defined destructors should invoke |
| 2956 | /// the C++ destructor to preserve the order of field destructions. |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2957 | #[test] |
| 2958 | fn test_impl_drop_nontrivial_member_destructor() -> Result<()> { |
| 2959 | // TODO(jeanpierreda): This would be cleaner if the UserDefinedDestructor code were |
| 2960 | // omitted. For example, we simulate it so that UserDefinedDestructor |
| 2961 | // comes from another library. |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 2962 | let ir = ir_from_cc( |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2963 | r#"struct UserDefinedDestructor final { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2964 | ~UserDefinedDestructor(); |
| 2965 | }; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2966 | struct TrivialStruct final { int i; }; |
| 2967 | struct NontrivialMembers final { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2968 | UserDefinedDestructor udd; |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2969 | TrivialStruct ts; |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2970 | int x; |
| 2971 | };"#, |
| 2972 | )?; |
| 2973 | let rs_api = generate_rs_api(&ir)?; |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 2974 | assert_rs_matches!( |
| 2975 | rs_api, |
| 2976 | quote! { |
| 2977 | impl Drop for NontrivialMembers { |
| 2978 | #[inline(always)] |
| 2979 | fn drop(&mut self) { |
| 2980 | unsafe { crate::detail::__rust_thunk___ZN17NontrivialMembersD1Ev(self) } |
| 2981 | } |
| 2982 | } |
| 2983 | } |
| 2984 | ); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 2985 | assert_rs_matches!(rs_api, quote! {pub x: i32,}); |
| 2986 | assert_rs_matches!(rs_api, quote! {pub ts: TrivialStruct,}); |
Lukasz Anforowicz | 6d55363 | 2022-01-06 21:36:14 +0000 | [diff] [blame] | 2987 | assert_rs_matches!( |
| 2988 | rs_api, |
| 2989 | quote! {pub udd: std::mem::ManuallyDrop<UserDefinedDestructor>,} |
| 2990 | ); |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 2991 | Ok(()) |
| 2992 | } |
| 2993 | |
| 2994 | /// Trivial types (at least those that are mapped to Copy rust types) do not |
| 2995 | /// get a Drop impl. |
| 2996 | #[test] |
| 2997 | fn test_impl_drop_trivial() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 2998 | let ir = ir_from_cc( |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 2999 | r#"struct Trivial final { |
Devin Jeanpierre | 7e9a1de | 2021-12-03 08:04:22 +0000 | [diff] [blame] | 3000 | ~Trivial() = default; |
| 3001 | int x; |
| 3002 | };"#, |
| 3003 | )?; |
| 3004 | let rs_api = generate_rs_api(&ir)?; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3005 | assert_rs_not_matches!(rs_api, quote! {impl Drop}); |
| 3006 | assert_rs_matches!(rs_api, quote! {pub x: i32}); |
Lukasz Anforowicz | 2f07416 | 2022-01-06 22:50:51 +0000 | [diff] [blame] | 3007 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 3008 | // TODO(b/213326125): Avoid generating thunk impls that are never called. |
| 3009 | // (The test assertion below should be reversed once this bug is fixed.) |
| 3010 | assert_cc_matches!(rs_api_impl, quote! { std::destroy_at }); |
Devin Jeanpierre | 91de701 | 2021-10-21 12:53:51 +0000 | [diff] [blame] | 3011 | Ok(()) |
| 3012 | } |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 3013 | |
| 3014 | #[test] |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 3015 | fn test_impl_default_explicitly_defaulted_constructor() -> Result<()> { |
| 3016 | let ir = ir_from_cc( |
Lukasz Anforowicz | 9555127 | 2022-01-20 00:02:24 +0000 | [diff] [blame] | 3017 | r#"#pragma clang lifetime_elision |
| 3018 | struct DefaultedConstructor final { |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 3019 | DefaultedConstructor() = default; |
| 3020 | };"#, |
| 3021 | )?; |
| 3022 | let rs_api = generate_rs_api(&ir)?; |
| 3023 | assert_rs_matches!( |
| 3024 | rs_api, |
| 3025 | quote! { |
| 3026 | impl Default for DefaultedConstructor { |
| 3027 | #[inline(always)] |
| 3028 | fn default() -> Self { |
Lukasz Anforowicz | bedbdee | 2022-01-05 01:14:52 +0000 | [diff] [blame] | 3029 | let mut tmp = std::mem::MaybeUninit::<Self>::zeroed(); |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 3030 | unsafe { |
Lukasz Anforowicz | 40c2eb8 | 2022-01-11 18:22:31 +0000 | [diff] [blame] | 3031 | crate::detail::__rust_thunk___ZN20DefaultedConstructorC1Ev(&mut tmp); |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 3032 | tmp.assume_init() |
| 3033 | } |
| 3034 | } |
| 3035 | } |
| 3036 | } |
| 3037 | ); |
| 3038 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 3039 | assert_cc_matches!( |
| 3040 | rs_api_impl, |
| 3041 | quote! { |
| 3042 | extern "C" void __rust_thunk___ZN20DefaultedConstructorC1Ev( |
Googler | 972d358 | 2022-01-11 10:17:22 +0000 | [diff] [blame] | 3043 | class DefaultedConstructor* __this) { |
Lukasz Anforowicz | 4457baf | 2021-12-23 17:24:04 +0000 | [diff] [blame] | 3044 | rs_api_impl_support::construct_at (__this) ; |
Lukasz Anforowicz | e643ec9 | 2021-12-22 15:45:15 +0000 | [diff] [blame] | 3045 | } |
| 3046 | } |
| 3047 | ); |
| 3048 | Ok(()) |
| 3049 | } |
| 3050 | |
| 3051 | #[test] |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 3052 | fn test_impl_clone_that_propagates_lifetime() -> Result<()> { |
| 3053 | // This test covers the case where a single lifetime applies to 1) |
| 3054 | // the `__this` parameter and 2) other constructor parameters. For |
| 3055 | // example, maybe the newly constructed object needs to have the |
| 3056 | // same lifetime as the constructor's parameter. (This might require |
| 3057 | // annotating the whole C++ struct with a lifetime, so maybe the |
| 3058 | // example below is not fully realistic/accurate...). |
| 3059 | let mut ir = ir_from_cc( |
| 3060 | r#"#pragma clang lifetime_elision |
| 3061 | struct Foo final { |
Googler | 53f6594 | 2022-02-23 11:23:30 +0000 | [diff] [blame] | 3062 | [[clang::annotate("lifetimes", "a: a")]] |
Lukasz Anforowicz | 326c4e4 | 2022-01-27 14:43:00 +0000 | [diff] [blame] | 3063 | Foo(const int& i); |
| 3064 | };"#, |
| 3065 | )?; |
| 3066 | let ctor: &mut Func = ir |
| 3067 | .items_mut() |
| 3068 | .filter_map(|item| match item { |
| 3069 | Item::Func(func) => Some(func), |
| 3070 | _ => None, |
| 3071 | }) |
| 3072 | .find(|f| { |
| 3073 | matches!(&f.name, UnqualifiedIdentifier::Constructor) |
| 3074 | && f.params.get(1).map(|p| p.identifier.identifier == "i").unwrap_or_default() |
| 3075 | }) |
| 3076 | .unwrap(); |
| 3077 | { |
| 3078 | // Double-check that the test scenario set up above uses the same lifetime |
| 3079 | // for both of the constructor's parameters: `__this` and `i`. |
| 3080 | assert_eq!(ctor.params.len(), 2); |
| 3081 | let this_lifetime: LifetimeId = |
| 3082 | *ctor.params[0].type_.rs_type.lifetime_args.first().unwrap(); |
| 3083 | let i_lifetime: LifetimeId = |
| 3084 | *ctor.params[1].type_.rs_type.lifetime_args.first_mut().unwrap(); |
| 3085 | assert_eq!(i_lifetime, this_lifetime); |
| 3086 | } |
| 3087 | |
| 3088 | // Before cl/423346348 the generated Rust code would incorrectly look |
| 3089 | // like this (note the mismatched 'a and 'b lifetimes): |
| 3090 | // fn from<'b>(i: &'a i32) -> Self |
| 3091 | // After this CL, this scenario will result in an explicit error. |
| 3092 | let err = generate_rs_api(&ir).unwrap_err(); |
| 3093 | let msg = format!("{}", err); |
| 3094 | assert!( |
| 3095 | msg.contains("The lifetime of `__this` is unexpectedly also used by another parameter") |
| 3096 | ); |
| 3097 | Ok(()) |
| 3098 | } |
| 3099 | |
| 3100 | #[test] |
Lukasz Anforowicz | 9bab835 | 2021-12-22 17:35:31 +0000 | [diff] [blame] | 3101 | fn test_impl_default_non_trivial_struct() -> Result<()> { |
| 3102 | let ir = ir_from_cc( |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 3103 | r#"#pragma clang lifetime_elision |
| 3104 | struct NonTrivialStructWithConstructors final { |
Lukasz Anforowicz | 9bab835 | 2021-12-22 17:35:31 +0000 | [diff] [blame] | 3105 | NonTrivialStructWithConstructors(); |
| 3106 | ~NonTrivialStructWithConstructors(); // Non-trivial |
| 3107 | };"#, |
| 3108 | )?; |
| 3109 | let rs_api = generate_rs_api(&ir)?; |
| 3110 | assert_rs_not_matches!(rs_api, quote! {impl Default}); |
| 3111 | Ok(()) |
| 3112 | } |
| 3113 | |
| 3114 | #[test] |
Lukasz Anforowicz | 71716b7 | 2022-01-26 17:05:05 +0000 | [diff] [blame] | 3115 | fn test_impl_from_for_explicit_conversion_constructor() -> Result<()> { |
| 3116 | let ir = ir_from_cc( |
| 3117 | r#"#pragma clang lifetime_elision |
| 3118 | struct SomeStruct final { |
| 3119 | explicit SomeStruct(int i); |
| 3120 | };"#, |
| 3121 | )?; |
| 3122 | let rs_api = generate_rs_api(&ir)?; |
| 3123 | // As discussed in b/214020567 for now we only generate `From::from` bindings |
| 3124 | // for *implicit* C++ conversion constructors. |
| 3125 | assert_rs_not_matches!(rs_api, quote! {impl From}); |
| 3126 | Ok(()) |
| 3127 | } |
| 3128 | |
| 3129 | #[test] |
| 3130 | fn test_impl_from_for_implicit_conversion_constructor() -> Result<()> { |
| 3131 | let ir = ir_from_cc( |
| 3132 | r#"#pragma clang lifetime_elision |
| 3133 | struct SomeStruct final { |
| 3134 | SomeStruct(int i); // implicit - no `explicit` keyword |
| 3135 | };"#, |
| 3136 | )?; |
| 3137 | let rs_api = generate_rs_api(&ir)?; |
| 3138 | // As discussed in b/214020567 we generate `From::from` bindings for |
| 3139 | // *implicit* C++ conversion constructors. |
| 3140 | assert_rs_matches!( |
| 3141 | rs_api, |
| 3142 | quote! { |
| 3143 | impl From<i32> for SomeStruct { |
| 3144 | #[inline(always)] |
| 3145 | fn from(i: i32) -> Self { |
| 3146 | let mut tmp = std::mem::MaybeUninit::<Self>::zeroed(); |
| 3147 | unsafe { |
| 3148 | crate::detail::__rust_thunk___ZN10SomeStructC1Ei(&mut tmp, i); |
| 3149 | tmp.assume_init() |
| 3150 | } |
| 3151 | } |
| 3152 | } |
| 3153 | } |
| 3154 | ); |
| 3155 | Ok(()) |
| 3156 | } |
| 3157 | |
| 3158 | #[test] |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 3159 | fn test_impl_eq_for_member_function() -> Result<()> { |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 3160 | let ir = ir_from_cc( |
| 3161 | r#"#pragma clang lifetime_elision |
| 3162 | struct SomeStruct final { |
| 3163 | inline bool operator==(const SomeStruct& other) const { |
| 3164 | return i == other.i; |
| 3165 | } |
| 3166 | int i; |
| 3167 | };"#, |
| 3168 | )?; |
| 3169 | let rs_api = generate_rs_api(&ir)?; |
| 3170 | assert_rs_matches!( |
| 3171 | rs_api, |
| 3172 | quote! { |
| 3173 | impl PartialEq<SomeStruct> for SomeStruct { |
| 3174 | #[inline(always)] |
| 3175 | fn eq<'a, 'b>(&'a self, other: &'b SomeStruct) -> bool { |
| 3176 | unsafe { crate::detail::__rust_thunk___ZNK10SomeStructeqERKS_(self, other) } |
| 3177 | } |
| 3178 | } |
| 3179 | } |
| 3180 | ); |
| 3181 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 3182 | assert_cc_matches!( |
| 3183 | rs_api_impl, |
| 3184 | quote! { |
| 3185 | extern "C" bool __rust_thunk___ZNK10SomeStructeqERKS_( |
| 3186 | const class SomeStruct* __this, const class SomeStruct& other) { |
| 3187 | return __this->operator==(other); |
| 3188 | } |
| 3189 | } |
| 3190 | ); |
| 3191 | Ok(()) |
| 3192 | } |
| 3193 | |
| 3194 | #[test] |
Lukasz Anforowicz | 732ca64 | 2022-02-03 20:58:38 +0000 | [diff] [blame] | 3195 | fn test_impl_eq_for_free_function() -> Result<()> { |
| 3196 | let ir = ir_from_cc( |
| 3197 | r#"#pragma clang lifetime_elision |
| 3198 | struct SomeStruct final { int i; }; |
| 3199 | bool operator==(const SomeStruct& lhs, const SomeStruct& rhs) { |
| 3200 | return lhs.i == rhs.i; |
| 3201 | }"#, |
| 3202 | )?; |
| 3203 | let rs_api = generate_rs_api(&ir)?; |
| 3204 | assert_rs_matches!( |
| 3205 | rs_api, |
| 3206 | quote! { |
| 3207 | impl PartialEq<SomeStruct> for SomeStruct { |
| 3208 | #[inline(always)] |
| 3209 | fn eq<'a, 'b>(&'a self, rhs: &'b SomeStruct) -> bool { |
| 3210 | unsafe { crate::detail::__rust_thunk___ZeqRK10SomeStructS1_(self, rhs) } |
| 3211 | } |
| 3212 | } |
| 3213 | } |
| 3214 | ); |
| 3215 | Ok(()) |
| 3216 | } |
| 3217 | |
| 3218 | #[test] |
Lukasz Anforowicz | fae90a1 | 2022-02-03 20:58:15 +0000 | [diff] [blame] | 3219 | fn test_impl_eq_non_const_member_function() -> Result<()> { |
| 3220 | let ir = ir_from_cc( |
| 3221 | r#"#pragma clang lifetime_elision |
| 3222 | struct SomeStruct final { |
| 3223 | bool operator==(const SomeStruct& other) /* no `const` here */; |
| 3224 | };"#, |
| 3225 | )?; |
| 3226 | let rs_api = generate_rs_api(&ir)?; |
| 3227 | assert_rs_not_matches!(rs_api, quote! {impl PartialEq}); |
| 3228 | Ok(()) |
| 3229 | } |
| 3230 | |
| 3231 | #[test] |
| 3232 | fn test_impl_eq_rhs_by_value() -> Result<()> { |
| 3233 | let ir = ir_from_cc( |
| 3234 | r#"#pragma clang lifetime_elision |
| 3235 | struct SomeStruct final { |
| 3236 | bool operator==(SomeStruct other) const; |
| 3237 | };"#, |
| 3238 | )?; |
| 3239 | let rs_api = generate_rs_api(&ir)?; |
| 3240 | assert_rs_not_matches!(rs_api, quote! {impl PartialEq}); |
| 3241 | Ok(()) |
| 3242 | } |
| 3243 | |
| 3244 | #[test] |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 3245 | fn test_thunk_ident_function() { |
| 3246 | let func = ir_func("foo"); |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 3247 | assert_eq!(thunk_ident(&func), make_rs_ident("__rust_thunk___Z3foov")); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 3248 | } |
| 3249 | |
| 3250 | #[test] |
| 3251 | fn test_thunk_ident_special_names() { |
Marcel Hlopko | 4b13b96 | 2021-12-06 12:40:56 +0000 | [diff] [blame] | 3252 | let ir = ir_from_cc("struct Class {};").unwrap(); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 3253 | |
Googler | 45ad275 | 2021-12-06 12:12:35 +0000 | [diff] [blame] | 3254 | let destructor = |
| 3255 | ir.functions().find(|f| f.name == UnqualifiedIdentifier::Destructor).unwrap(); |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 3256 | assert_eq!(thunk_ident(destructor), make_rs_ident("__rust_thunk___ZN5ClassD1Ev")); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 3257 | |
Lukasz Anforowicz | 49b5bbc | 2022-02-04 23:40:10 +0000 | [diff] [blame] | 3258 | let default_constructor = ir |
| 3259 | .functions() |
| 3260 | .find(|f| f.name == UnqualifiedIdentifier::Constructor && f.params.len() == 1) |
| 3261 | .unwrap(); |
Lukasz Anforowicz | dd9ae0f | 2022-02-17 15:52:53 +0000 | [diff] [blame] | 3262 | assert_eq!(thunk_ident(default_constructor), make_rs_ident("__rust_thunk___ZN5ClassC1Ev")); |
Devin Jeanpierre | 45cb116 | 2021-10-27 10:54:28 +0000 | [diff] [blame] | 3263 | } |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 3264 | |
| 3265 | #[test] |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3266 | fn test_elided_lifetimes() -> Result<()> { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 3267 | let ir = ir_from_cc( |
| 3268 | r#"#pragma clang lifetime_elision |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3269 | struct S final { |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 3270 | int& f(int& i); |
| 3271 | };"#, |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3272 | )?; |
| 3273 | let rs_api = generate_rs_api(&ir)?; |
| 3274 | assert_rs_matches!( |
| 3275 | rs_api, |
| 3276 | quote! { |
Lukasz Anforowicz | 231a3bb | 2022-01-12 14:05:59 +0000 | [diff] [blame] | 3277 | 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] | 3278 | } |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 3279 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3280 | assert_rs_matches!( |
| 3281 | rs_api, |
| 3282 | quote! { |
Googler | 6804a01 | 2022-01-05 07:04:36 +0000 | [diff] [blame] | 3283 | pub(crate) fn __rust_thunk___ZN1S1fERi<'a, 'b>(__this: &'a mut S, i: &'b mut i32) |
| 3284 | -> &'a mut i32; |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3285 | } |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 3286 | ); |
Marcel Hlopko | 8954775 | 2021-12-10 09:39:41 +0000 | [diff] [blame] | 3287 | Ok(()) |
Googler | 7cced42 | 2021-12-06 11:58:39 +0000 | [diff] [blame] | 3288 | } |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 3289 | |
| 3290 | #[test] |
Googler | 386e594 | 2022-02-24 08:53:29 +0000 | [diff] [blame^] | 3291 | fn test_annotated_lifetimes() -> Result<()> { |
| 3292 | let ir = ir_from_cc( |
| 3293 | r#"[[clang::annotate("lifetimes", "a, a -> a")]] |
| 3294 | int& f(int& i1, int& i2); |
| 3295 | "#, |
| 3296 | )?; |
| 3297 | let rs_api = generate_rs_api(&ir)?; |
| 3298 | assert_rs_matches!( |
| 3299 | rs_api, |
| 3300 | quote! { |
| 3301 | pub fn f<'a>(i1: &'a mut i32, i2: &'a mut i32) -> &'a mut i32 { ... } |
| 3302 | } |
| 3303 | ); |
| 3304 | assert_rs_matches!( |
| 3305 | rs_api, |
| 3306 | quote! { |
| 3307 | pub(crate) fn __rust_thunk___Z1fRiS_<'a>(i1: &'a mut i32, i2: &'a mut i32) |
| 3308 | -> &'a mut i32; |
| 3309 | } |
| 3310 | ); |
| 3311 | Ok(()) |
| 3312 | } |
| 3313 | |
| 3314 | #[test] |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 3315 | fn test_format_generic_params() -> Result<()> { |
| 3316 | assert_rs_matches!(format_generic_params(std::iter::empty::<syn::Ident>()), quote! {}); |
| 3317 | |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 3318 | let idents = ["T1", "T2"].iter().map(|s| make_rs_ident(s)); |
Lukasz Anforowicz | daff040 | 2021-12-23 00:37:50 +0000 | [diff] [blame] | 3319 | assert_rs_matches!(format_generic_params(idents), quote! { < T1, T2 > }); |
| 3320 | |
| 3321 | let lifetimes = ["a", "b"] |
| 3322 | .iter() |
| 3323 | .map(|s| syn::Lifetime::new(&format!("'{}", s), proc_macro2::Span::call_site())); |
| 3324 | assert_rs_matches!(format_generic_params(lifetimes), quote! { < 'a, 'b > }); |
| 3325 | |
| 3326 | Ok(()) |
| 3327 | } |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 3328 | |
| 3329 | #[test] |
| 3330 | fn test_overloaded_functions() -> Result<()> { |
| 3331 | // TODO(b/213280424): We don't support creating bindings for overloaded |
| 3332 | // functions yet, except in the case of overloaded constructors with a |
| 3333 | // single parameter. |
| 3334 | let ir = ir_from_cc( |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 3335 | r#" #pragma clang lifetime_elision |
| 3336 | void f(); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 3337 | void f(int i); |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3338 | struct S1 final { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 3339 | void f(); |
| 3340 | void f(int i); |
| 3341 | }; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3342 | struct S2 final { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 3343 | void f(); |
| 3344 | }; |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3345 | struct S3 final { |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 3346 | S3(int i); |
| 3347 | S3(double d); |
| 3348 | }; |
| 3349 | "#, |
| 3350 | )?; |
| 3351 | let rs_api = generate_rs_api(&ir)?; |
| 3352 | let rs_api_str = tokens_to_string(rs_api.clone())?; |
| 3353 | |
| 3354 | // Cannot overload free functions. |
| 3355 | assert!(rs_api_str.contains("Error while generating bindings for item 'f'")); |
| 3356 | assert_rs_not_matches!(rs_api, quote! {pub fn f()}); |
| 3357 | assert_rs_not_matches!(rs_api, quote! {pub fn f(i: i32)}); |
| 3358 | |
| 3359 | // Cannot overload member functions. |
| 3360 | assert!(rs_api_str.contains("Error while generating bindings for item 'S1::f'")); |
| 3361 | assert_rs_not_matches!(rs_api, quote! {pub fn f(... S1 ...)}); |
| 3362 | |
| 3363 | // But we can import member functions that have the same name as a free |
| 3364 | // function. |
Lukasz Anforowicz | 55673c9 | 2022-01-27 19:37:26 +0000 | [diff] [blame] | 3365 | assert_rs_matches!(rs_api, quote! {pub fn f<'a>(&'a mut self)}); |
Googler | d03d05b | 2022-01-07 10:10:57 +0000 | [diff] [blame] | 3366 | |
| 3367 | // We can also import overloaded single-parameter constructors. |
| 3368 | assert_rs_matches!(rs_api, quote! {impl From<i32> for S3}); |
| 3369 | assert_rs_matches!(rs_api, quote! {impl From<f64> for S3}); |
| 3370 | Ok(()) |
| 3371 | } |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 3372 | |
| 3373 | #[test] |
| 3374 | fn test_type_alias() -> Result<()> { |
| 3375 | let ir = ir_from_cc( |
| 3376 | r#" |
| 3377 | typedef int MyTypedefDecl; |
| 3378 | using MyTypeAliasDecl = int; |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 3379 | using MyTypeAliasDecl_Alias = MyTypeAliasDecl; |
| 3380 | |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3381 | struct S final {}; |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 3382 | using S_Alias = S; |
| 3383 | using S_Alias_Alias = S_Alias; |
| 3384 | |
| 3385 | inline void f(MyTypedefDecl t) {} |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 3386 | "#, |
| 3387 | )?; |
| 3388 | let rs_api = generate_rs_api(&ir)?; |
Googler | 6a0a525 | 2022-01-11 14:08:09 +0000 | [diff] [blame] | 3389 | assert_rs_matches!(rs_api, quote! { pub type MyTypedefDecl = i32; }); |
| 3390 | assert_rs_matches!(rs_api, quote! { pub type MyTypeAliasDecl = i32; }); |
| 3391 | assert_rs_matches!(rs_api, quote! { pub type MyTypeAliasDecl_Alias = MyTypeAliasDecl; }); |
| 3392 | assert_rs_matches!(rs_api, quote! { pub type S_Alias = S; }); |
| 3393 | assert_rs_matches!(rs_api, quote! { pub type S_Alias_Alias = S_Alias; }); |
| 3394 | assert_rs_matches!(rs_api, quote! { pub fn f(t: MyTypedefDecl) }); |
| 3395 | assert_cc_matches!( |
| 3396 | generate_rs_api_impl(&ir)?, |
| 3397 | quote! { |
| 3398 | extern "C" void __rust_thunk___Z1fi(MyTypedefDecl t){ f (t) ; } |
| 3399 | } |
| 3400 | ); |
Googler | dcca7f7 | 2022-01-10 12:30:43 +0000 | [diff] [blame] | 3401 | Ok(()) |
| 3402 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3403 | |
| 3404 | #[test] |
| 3405 | fn test_rs_type_kind_implements_copy() -> Result<()> { |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3406 | let template = r#" LIFETIMES |
Devin Jeanpierre | 88343c7 | 2022-01-15 01:10:23 +0000 | [diff] [blame] | 3407 | struct [[clang::trivial_abi]] TrivialStruct final { int i; }; |
| 3408 | struct [[clang::trivial_abi]] UserDefinedCopyConstructor final { |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3409 | UserDefinedCopyConstructor(const UserDefinedCopyConstructor&); |
| 3410 | }; |
| 3411 | using IntAlias = int; |
| 3412 | using TrivialAlias = TrivialStruct; |
| 3413 | using NonTrivialAlias = UserDefinedCopyConstructor; |
| 3414 | void func(PARAM_TYPE some_param); |
| 3415 | "#; |
| 3416 | assert_impl_all!(i32: Copy); |
| 3417 | assert_impl_all!(&i32: Copy); |
| 3418 | assert_not_impl_all!(&mut i32: Copy); |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3419 | assert_impl_all!(Option<&i32>: Copy); |
| 3420 | assert_not_impl_all!(Option<&mut i32>: Copy); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3421 | assert_impl_all!(*const i32: Copy); |
| 3422 | assert_impl_all!(*mut i32: Copy); |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3423 | struct Test { |
| 3424 | // Test inputs: |
| 3425 | cc: &'static str, |
| 3426 | lifetimes: bool, |
| 3427 | // Expected test outputs: |
| 3428 | rs: &'static str, |
| 3429 | is_copy: bool, |
| 3430 | } |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3431 | let tests = vec![ |
| 3432 | // Validity of the next few tests is verified via |
| 3433 | // `assert_[not_]impl_all!` static assertions above. |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3434 | Test { cc: "int", lifetimes: true, rs: "i32", is_copy: true }, |
| 3435 | Test { cc: "const int&", lifetimes: true, rs: "&'a i32", is_copy: true }, |
| 3436 | Test { cc: "int&", lifetimes: true, rs: "&'a mut i32", is_copy: false }, |
| 3437 | Test { cc: "const int*", lifetimes: true, rs: "Option<&'a i32>", is_copy: true }, |
| 3438 | Test { cc: "int*", lifetimes: true, rs: "Option<&'a mut i32>", is_copy: false }, |
| 3439 | Test { cc: "const int*", lifetimes: false, rs: "*const i32", is_copy: true }, |
| 3440 | Test { cc: "int*", lifetimes: false, rs: "*mut i32", is_copy: true }, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3441 | // Tests below have been thought-through and verified "manually". |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3442 | // TrivialStruct is expected to derive Copy. |
| 3443 | Test { cc: "TrivialStruct", lifetimes: true, rs: "TrivialStruct", is_copy: true }, |
| 3444 | Test { |
| 3445 | cc: "UserDefinedCopyConstructor", |
| 3446 | lifetimes: true, |
| 3447 | rs: "UserDefinedCopyConstructor", |
| 3448 | is_copy: false, |
| 3449 | }, |
| 3450 | Test { cc: "IntAlias", lifetimes: true, rs: "IntAlias", is_copy: true }, |
| 3451 | Test { cc: "TrivialAlias", lifetimes: true, rs: "TrivialAlias", is_copy: true }, |
| 3452 | Test { cc: "NonTrivialAlias", lifetimes: true, rs: "NonTrivialAlias", is_copy: false }, |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3453 | ]; |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3454 | for test in tests.iter() { |
| 3455 | let test_name = format!("cc='{}', lifetimes={}", test.cc, test.lifetimes); |
| 3456 | let cc_input = template.replace("PARAM_TYPE", test.cc).replace( |
| 3457 | "LIFETIMES", |
| 3458 | if test.lifetimes { "#pragma clang lifetime_elision" } else { "" }, |
| 3459 | ); |
| 3460 | let ir = ir_from_cc(&cc_input)?; |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 3461 | let f = retrieve_func(&ir, "func"); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3462 | let t = RsTypeKind::new(&f.params[0].type_.rs_type, &ir)?; |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3463 | |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 3464 | let lifetime_to_name: HashMap::<LifetimeId, String> = t.lifetimes().map( |
| 3465 | |lifetime_id| (lifetime_id, "a".to_string())).collect(); |
| 3466 | |
Lukasz Anforowicz | 20651e3 | 2022-02-10 14:52:15 +0000 | [diff] [blame] | 3467 | let fmt = tokens_to_string(t.format(&ir, &lifetime_to_name)?)?; |
| 3468 | assert_eq!(test.rs, fmt, "Testing: {}", test_name); |
| 3469 | |
| 3470 | assert_eq!(test.is_copy, t.implements_copy(), "Testing: {}", test_name); |
Lukasz Anforowicz | e57215c | 2022-01-12 14:54:16 +0000 | [diff] [blame] | 3471 | } |
| 3472 | Ok(()) |
| 3473 | } |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 3474 | |
| 3475 | #[test] |
| 3476 | fn test_rs_type_kind_is_shared_ref_to_with_lifetimes() -> Result<()> { |
| 3477 | let ir = ir_from_cc( |
| 3478 | "#pragma clang lifetime_elision |
| 3479 | struct SomeStruct {}; |
| 3480 | void foo(const SomeStruct& foo_param); |
| 3481 | void bar(SomeStruct& bar_param);", |
| 3482 | )?; |
| 3483 | let record = ir.records().next().unwrap(); |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 3484 | let foo_func = retrieve_func(&ir, "foo"); |
| 3485 | let bar_func = retrieve_func(&ir, "bar"); |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 3486 | |
| 3487 | // const-ref + lifetimes in C++ ===> shared-ref in Rust |
| 3488 | assert_eq!(foo_func.params.len(), 1); |
| 3489 | let foo_param = &foo_func.params[0]; |
| 3490 | assert_eq!(&foo_param.identifier.identifier, "foo_param"); |
| 3491 | let foo_type = RsTypeKind::new(&foo_param.type_.rs_type, &ir)?; |
| 3492 | assert!(foo_type.is_shared_ref_to(record)); |
| 3493 | assert!(matches!(foo_type, RsTypeKind::Reference { mutability: Mutability::Const, .. })); |
| 3494 | |
| 3495 | // non-const-ref + lifetimes in C++ ===> mutable-ref in Rust |
| 3496 | assert_eq!(bar_func.params.len(), 1); |
| 3497 | let bar_param = &bar_func.params[0]; |
| 3498 | assert_eq!(&bar_param.identifier.identifier, "bar_param"); |
| 3499 | let bar_type = RsTypeKind::new(&bar_param.type_.rs_type, &ir)?; |
| 3500 | assert!(!bar_type.is_shared_ref_to(record)); |
| 3501 | assert!(matches!(bar_type, RsTypeKind::Reference { mutability: Mutability::Mut, .. })); |
| 3502 | |
| 3503 | Ok(()) |
| 3504 | } |
| 3505 | |
| 3506 | #[test] |
| 3507 | fn test_rs_type_kind_is_shared_ref_to_without_lifetimes() -> Result<()> { |
| 3508 | let ir = ir_from_cc( |
| 3509 | "struct SomeStruct {}; |
| 3510 | void foo(const SomeStruct& foo_param);", |
| 3511 | )?; |
| 3512 | let record = ir.records().next().unwrap(); |
Lukasz Anforowicz | 9c663ca | 2022-02-09 01:33:31 +0000 | [diff] [blame] | 3513 | let foo_func = retrieve_func(&ir, "foo"); |
Lukasz Anforowicz | a94ab70 | 2022-01-14 22:40:25 +0000 | [diff] [blame] | 3514 | |
| 3515 | // const-ref + *no* lifetimes in C++ ===> const-pointer in Rust |
| 3516 | assert_eq!(foo_func.params.len(), 1); |
| 3517 | let foo_param = &foo_func.params[0]; |
| 3518 | assert_eq!(&foo_param.identifier.identifier, "foo_param"); |
| 3519 | let foo_type = RsTypeKind::new(&foo_param.type_.rs_type, &ir)?; |
| 3520 | assert!(!foo_type.is_shared_ref_to(record)); |
| 3521 | assert!(matches!(foo_type, RsTypeKind::Pointer { mutability: Mutability::Const, .. })); |
| 3522 | |
| 3523 | Ok(()) |
| 3524 | } |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 3525 | |
| 3526 | #[test] |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 3527 | fn test_rs_type_kind_dfs_iter_ordering() { |
| 3528 | // Set up a test input representing: A<B<C>, D<E>>. |
| 3529 | let a = { |
| 3530 | let b = { |
| 3531 | let c = RsTypeKind::Other { name: "C", type_args: vec![] }; |
| 3532 | RsTypeKind::Other { name: "B", type_args: vec![c] } |
| 3533 | }; |
| 3534 | let d = { |
| 3535 | let e = RsTypeKind::Other { name: "E", type_args: vec![] }; |
| 3536 | RsTypeKind::Other { name: "D", type_args: vec![e] } |
| 3537 | }; |
| 3538 | RsTypeKind::Other { name: "A", type_args: vec![b, d] } |
| 3539 | }; |
| 3540 | let dfs_names = a |
| 3541 | .dfs_iter() |
| 3542 | .map(|t| match t { |
| 3543 | RsTypeKind::Other { name, .. } => *name, |
| 3544 | _ => unreachable!("Only 'other' types are used in this test"), |
| 3545 | }) |
| 3546 | .collect_vec(); |
| 3547 | assert_eq!(vec!["A", "B", "C", "D", "E"], dfs_names); |
| 3548 | } |
| 3549 | |
| 3550 | #[test] |
Lukasz Anforowicz | cf230fd | 2022-02-18 19:20:39 +0000 | [diff] [blame] | 3551 | fn test_rs_type_kind_dfs_iter_ordering_for_func_ptr() { |
| 3552 | // Set up a test input representing: fn(A, B) -> C |
| 3553 | let f = { |
| 3554 | let a = RsTypeKind::Other { name: "A", type_args: vec![] }; |
| 3555 | let b = RsTypeKind::Other { name: "B", type_args: vec![] }; |
| 3556 | let c = RsTypeKind::Other { name: "C", type_args: vec![] }; |
| 3557 | RsTypeKind::FuncPtr { abi: "blah", param_types: vec![a, b], return_type: Box::new(c) } |
| 3558 | }; |
| 3559 | let dfs_names = f |
| 3560 | .dfs_iter() |
| 3561 | .map(|t| match t { |
| 3562 | RsTypeKind::FuncPtr { .. } => "fn", |
| 3563 | RsTypeKind::Other { name, .. } => *name, |
| 3564 | _ => unreachable!("Only FuncPtr and Other kinds are used in this test"), |
| 3565 | }) |
| 3566 | .collect_vec(); |
| 3567 | assert_eq!(vec!["fn", "A", "B", "C"], dfs_names); |
| 3568 | } |
| 3569 | |
| 3570 | #[test] |
Lukasz Anforowicz | 90bdb96 | 2022-02-14 21:07:45 +0000 | [diff] [blame] | 3571 | fn test_rs_type_kind_lifetimes() -> Result<()> { |
| 3572 | let ir = ir_from_cc( |
| 3573 | r#" |
| 3574 | #pragma clang lifetime_elision |
| 3575 | using TypeAlias = int&; |
| 3576 | struct SomeStruct {}; |
| 3577 | void foo(int a, int& b, int* c, int** d, TypeAlias e, SomeStruct f); "#, |
| 3578 | )?; |
| 3579 | let f = retrieve_func(&ir, "foo"); |
| 3580 | let ret = RsTypeKind::new(&f.return_type.rs_type, &ir)?; |
| 3581 | let a = RsTypeKind::new(&f.params[0].type_.rs_type, &ir)?; |
| 3582 | let b = RsTypeKind::new(&f.params[1].type_.rs_type, &ir)?; |
| 3583 | let c = RsTypeKind::new(&f.params[2].type_.rs_type, &ir)?; |
| 3584 | let d = RsTypeKind::new(&f.params[3].type_.rs_type, &ir)?; |
| 3585 | let e = RsTypeKind::new(&f.params[4].type_.rs_type, &ir)?; |
| 3586 | let f = RsTypeKind::new(&f.params[5].type_.rs_type, &ir)?; |
| 3587 | |
| 3588 | assert_eq!(0, ret.lifetimes().count()); // No lifetimes on `void`. |
| 3589 | assert_eq!(0, a.lifetimes().count()); // No lifetimes on `int`. |
| 3590 | assert_eq!(1, b.lifetimes().count()); // `&'a i32` has a single lifetime. |
| 3591 | assert_eq!(1, c.lifetimes().count()); // `Option<&'b i32>` has a single lifetime. |
| 3592 | assert_eq!(2, d.lifetimes().count()); // `&'c Option<&'d i32>` has two lifetimes. |
| 3593 | assert_eq!(1, e.lifetimes().count()); // Lifetime of underlying type should show through. |
| 3594 | assert_eq!(0, f.lifetimes().count()); // No lifetimes on structs (yet). |
| 3595 | Ok(()) |
| 3596 | } |
| 3597 | |
| 3598 | #[test] |
| 3599 | fn test_rs_type_kind_lifetimes_raw_ptr() -> Result<()> { |
| 3600 | let ir = ir_from_cc("void foo(int* a);")?; |
| 3601 | let f = retrieve_func(&ir, "foo"); |
| 3602 | let a = RsTypeKind::new(&f.params[0].type_.rs_type, &ir)?; |
| 3603 | assert_eq!(0, a.lifetimes().count()); // No lifetimes on `int*`. |
| 3604 | Ok(()) |
| 3605 | } |
| 3606 | |
| 3607 | #[test] |
Marcel Hlopko | eaae9b7 | 2022-01-21 15:54:11 +0000 | [diff] [blame] | 3608 | fn test_rust_keywords_are_escaped_in_rs_api_file() -> Result<()> { |
| 3609 | let ir = ir_from_cc("struct type { int dyn; };")?; |
| 3610 | let rs_api = generate_rs_api(&ir)?; |
| 3611 | assert_rs_matches!(rs_api, quote! { struct r#type { ... r#dyn: i32 ... } }); |
| 3612 | Ok(()) |
| 3613 | } |
| 3614 | |
| 3615 | #[test] |
| 3616 | fn test_rust_keywords_are_not_escaped_in_rs_api_impl_file() -> Result<()> { |
| 3617 | let ir = ir_from_cc("struct type { int dyn; };")?; |
| 3618 | let rs_api_impl = generate_rs_api_impl(&ir)?; |
| 3619 | assert_cc_matches!(rs_api_impl, quote! { static_assert(offsetof(class type, dyn) ... ) }); |
| 3620 | Ok(()) |
| 3621 | } |
Marcel Hlopko | 14ee3c8 | 2022-02-09 09:46:23 +0000 | [diff] [blame] | 3622 | |
| 3623 | #[test] |
| 3624 | fn test_no_aligned_attr() { |
| 3625 | let ir = ir_from_cc("struct SomeStruct {};").unwrap(); |
| 3626 | let rs_api = generate_rs_api(&ir).unwrap(); |
| 3627 | |
| 3628 | assert_rs_matches! {rs_api, quote! { |
| 3629 | #[repr(C)] |
| 3630 | pub struct SomeStruct { ... } |
| 3631 | }}; |
| 3632 | } |
| 3633 | |
| 3634 | #[test] |
| 3635 | fn test_aligned_attr() { |
| 3636 | let ir = ir_from_cc("struct SomeStruct {} __attribute__((aligned(64)));").unwrap(); |
| 3637 | let rs_api = generate_rs_api(&ir).unwrap(); |
| 3638 | |
| 3639 | assert_rs_matches! {rs_api, quote! { |
| 3640 | #[repr(C, align(64))] |
| 3641 | pub struct SomeStruct { ... } |
| 3642 | } |
| 3643 | }; |
| 3644 | } |
Devin Jeanpierre | 149950d | 2022-02-22 21:02:02 +0000 | [diff] [blame] | 3645 | |
| 3646 | /// !Unpin references should not be pinned. |
| 3647 | #[test] |
| 3648 | fn test_nonunpin_ref_param() -> Result<()> { |
| 3649 | let rs_api_impl = generate_rs_api(&ir_from_cc( |
| 3650 | r#" |
| 3651 | #pragma clang lifetime_elision |
| 3652 | struct S {~S();}; |
| 3653 | void Function(const S& s); |
| 3654 | "#, |
| 3655 | )?)?; |
| 3656 | assert_rs_matches!( |
| 3657 | rs_api_impl, |
| 3658 | quote! { |
| 3659 | fn Function<'a>(s: &'a S) { ... } |
| 3660 | } |
| 3661 | ); |
| 3662 | Ok(()) |
| 3663 | } |
| 3664 | |
| 3665 | /// !Unpin mut references must be pinned. |
| 3666 | #[test] |
| 3667 | fn test_nonunpin_mut_param() -> Result<()> { |
| 3668 | let rs_api_impl = generate_rs_api(&ir_from_cc( |
| 3669 | r#" |
| 3670 | #pragma clang lifetime_elision |
| 3671 | struct S {~S();}; |
| 3672 | void Function(S& s); |
| 3673 | "#, |
| 3674 | )?)?; |
| 3675 | assert_rs_matches!( |
| 3676 | rs_api_impl, |
| 3677 | quote! { |
| 3678 | fn Function<'a>(s: std::pin::Pin<&'a mut S>) { ... } |
| 3679 | } |
| 3680 | ); |
| 3681 | Ok(()) |
| 3682 | } |
| 3683 | |
| 3684 | /// !Unpin &self should not be pinned. |
| 3685 | #[test] |
| 3686 | fn test_nonunpin_ref_self() -> Result<()> { |
| 3687 | let rs_api_impl = generate_rs_api(&ir_from_cc( |
| 3688 | r#" |
| 3689 | #pragma clang lifetime_elision |
| 3690 | struct S { |
| 3691 | ~S(); |
| 3692 | void Function() const; |
| 3693 | }; |
| 3694 | "#, |
| 3695 | )?)?; |
| 3696 | assert_rs_matches!( |
| 3697 | rs_api_impl, |
| 3698 | quote! { |
| 3699 | fn Function<'a>(&'a self) { ... } |
| 3700 | } |
| 3701 | ); |
| 3702 | Ok(()) |
| 3703 | } |
| 3704 | |
| 3705 | /// !Unpin &mut self must be pinned. |
| 3706 | #[test] |
| 3707 | fn test_nonunpin_mut_self() -> Result<()> { |
| 3708 | let rs_api_impl = generate_rs_api(&ir_from_cc( |
| 3709 | r#" |
| 3710 | #pragma clang lifetime_elision |
| 3711 | struct S { |
| 3712 | ~S(); |
| 3713 | void Function(); |
| 3714 | }; |
| 3715 | "#, |
| 3716 | )?)?; |
| 3717 | assert_rs_matches!( |
| 3718 | rs_api_impl, |
| 3719 | quote! { |
| 3720 | fn Function<'a>(self: std::pin::Pin<&'a mut Self>) { ... } |
| 3721 | } |
| 3722 | ); |
| 3723 | Ok(()) |
| 3724 | } |
| 3725 | |
| 3726 | /// Drop::drop must not use self : Pin<...>. |
| 3727 | #[test] |
| 3728 | fn test_nonunpin_drop() -> Result<()> { |
| 3729 | let rs_api_impl = generate_rs_api(&ir_from_cc( |
| 3730 | r#" |
| 3731 | struct S {~S();}; |
| 3732 | "#, |
| 3733 | )?)?; |
| 3734 | assert_rs_matches!( |
| 3735 | rs_api_impl, |
| 3736 | quote! { |
| 3737 | fn drop(&mut self) { ... } |
| 3738 | } |
| 3739 | ); |
| 3740 | Ok(()) |
| 3741 | } |
Marcel Hlopko | 42abfc8 | 2021-08-09 07:03:17 +0000 | [diff] [blame] | 3742 | } |