| 1 |
mod dyngen; |
| 2 |
mod error; |
| 3 |
mod helpers; |
| 4 |
mod impl_debug; |
| 5 |
mod impl_partialeq; |
| 6 |
mod postprocessing; |
| 7 |
mod serialize; |
| 8 |
pub(crate) mod struct_layout; |
| 9 |
|
| 10 |
#[cfg(test)] |
| 11 |
#[allow(warnings)] |
| 12 |
pub(crate) mod bitfield_unit; |
| 13 |
#[cfg(all(test, target_endian = "little"))] |
| 14 |
mod bitfield_unit_tests; |
| 15 |
|
| 16 |
use self::dyngen::DynamicItems; |
| 17 |
use self::helpers::attributes; |
| 18 |
use self::struct_layout::StructLayoutTracker; |
| 19 |
|
| 20 |
use super::BindgenOptions; |
| 21 |
|
| 22 |
use crate::callbacks::{DeriveInfo, TypeKind as DeriveTypeKind}; |
| 23 |
use crate::ir::analysis::{HasVtable, Sizedness}; |
| 24 |
use crate::ir::annotations::{ |
| 25 |
Annotations, FieldAccessorKind, FieldVisibilityKind, |
| 26 |
}; |
| 27 |
use crate::ir::comp::{ |
| 28 |
Bitfield, BitfieldUnit, CompInfo, CompKind, Field, FieldData, FieldMethods, |
| 29 |
Method, MethodKind, |
| 30 |
}; |
| 31 |
use crate::ir::context::{BindgenContext, ItemId}; |
| 32 |
use crate::ir::derive::{ |
| 33 |
CanDerive, CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq, |
| 34 |
CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd, |
| 35 |
}; |
| 36 |
use crate::ir::dot; |
| 37 |
use crate::ir::enum_ty::{Enum, EnumVariant, EnumVariantValue}; |
| 38 |
use crate::ir::function::{ |
| 39 |
Abi, ClangAbi, Function, FunctionKind, FunctionSig, Linkage, |
| 40 |
}; |
| 41 |
use crate::ir::int::IntKind; |
| 42 |
use crate::ir::item::{IsOpaque, Item, ItemCanonicalName, ItemCanonicalPath}; |
| 43 |
use crate::ir::item_kind::ItemKind; |
| 44 |
use crate::ir::layout::Layout; |
| 45 |
use crate::ir::module::Module; |
| 46 |
use crate::ir::objc::{ObjCInterface, ObjCMethod}; |
| 47 |
use crate::ir::template::{ |
| 48 |
AsTemplateParam, TemplateInstantiation, TemplateParameters, |
| 49 |
}; |
| 50 |
use crate::ir::ty::{Type, TypeKind}; |
| 51 |
use crate::ir::var::Var; |
| 52 |
|
| 53 |
use proc_macro2::{self, Ident, Span}; |
| 54 |
use quote::TokenStreamExt; |
| 55 |
|
| 56 |
use crate::{Entry, HashMap, HashSet}; |
| 57 |
use std::borrow::Cow; |
| 58 |
use std::cell::Cell; |
| 59 |
use std::collections::VecDeque; |
| 60 |
use std::fmt::{self, Write}; |
| 61 |
use std::ops; |
| 62 |
use std::str::FromStr; |
| 63 |
|
| 64 |
#[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 65 |
pub enum CodegenError { |
| 66 |
Serialize { msg: String, loc: String }, |
| 67 |
Io(String), |
| 68 |
} |
| 69 |
|
| 70 |
impl From<std::io::Error> for CodegenError { |
| 71 |
fn from(err: std::io::Error) -> Self { |
| 72 |
Self::Io(err.to_string()) |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
impl fmt::Display for CodegenError { |
| 77 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 78 |
match self { |
| 79 |
Self::Serialize { msg, loc } => { |
| 80 |
write!(f, "serialization error at {}: {}", loc, msg) |
| 81 |
} |
| 82 |
Self::Io(err) => err.fmt(f), |
| 83 |
} |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
// Name of type defined in constified enum module |
| 88 |
pub(crate) static CONSTIFIED_ENUM_MODULE_REPR_NAME: &str = "Type"; |
| 89 |
|
| 90 |
fn top_level_path( |
| 91 |
ctx: &BindgenContext, |
| 92 |
item: &Item, |
| 93 |
) -> Vec<proc_macro2::TokenStream> { |
| 94 |
let mut path = vec![quote! { self }]; |
| 95 |
|
| 96 |
if ctx.options().enable_cxx_namespaces { |
| 97 |
for _ in 0..item.codegen_depth(ctx) { |
| 98 |
path.push(quote! { super }); |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
path |
| 103 |
} |
| 104 |
|
| 105 |
fn root_import( |
| 106 |
ctx: &BindgenContext, |
| 107 |
module: &Item, |
| 108 |
) -> proc_macro2::TokenStream { |
| 109 |
assert!(ctx.options().enable_cxx_namespaces, "Somebody messed it up"); |
| 110 |
assert!(module.is_module()); |
| 111 |
|
| 112 |
let mut path = top_level_path(ctx, module); |
| 113 |
|
| 114 |
let root = ctx.root_module().canonical_name(ctx); |
| 115 |
let root_ident = ctx.rust_ident(root); |
| 116 |
path.push(quote! { #root_ident }); |
| 117 |
|
| 118 |
let mut tokens = quote! {}; |
| 119 |
tokens.append_separated(path, quote!(::)); |
| 120 |
|
| 121 |
quote! { |
| 122 |
#[allow(unused_imports)] |
| 123 |
use #tokens ; |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
bitflags! { |
| 128 |
struct DerivableTraits: u16 { |
| 129 |
const DEBUG = 1 << 0; |
| 130 |
const DEFAULT = 1 << 1; |
| 131 |
const COPY = 1 << 2; |
| 132 |
const CLONE = 1 << 3; |
| 133 |
const HASH = 1 << 4; |
| 134 |
const PARTIAL_ORD = 1 << 5; |
| 135 |
const ORD = 1 << 6; |
| 136 |
const PARTIAL_EQ = 1 << 7; |
| 137 |
const EQ = 1 << 8; |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
fn derives_of_item( |
| 142 |
item: &Item, |
| 143 |
ctx: &BindgenContext, |
| 144 |
packed: bool, |
| 145 |
) -> DerivableTraits { |
| 146 |
let mut derivable_traits = DerivableTraits::empty(); |
| 147 |
|
| 148 |
let all_template_params = item.all_template_params(ctx); |
| 149 |
|
| 150 |
if item.can_derive_copy(ctx) && !item.annotations().disallow_copy() { |
| 151 |
derivable_traits |= DerivableTraits::COPY; |
| 152 |
|
| 153 |
if ctx.options().rust_features().builtin_clone_impls || |
| 154 |
!all_template_params.is_empty() |
| 155 |
{ |
| 156 |
// FIXME: This requires extra logic if you have a big array in a |
| 157 |
// templated struct. The reason for this is that the magic: |
| 158 |
// fn clone(&self) -> Self { *self } |
| 159 |
// doesn't work for templates. |
| 160 |
// |
| 161 |
// It's not hard to fix though. |
| 162 |
derivable_traits |= DerivableTraits::CLONE; |
| 163 |
} |
| 164 |
} else if packed { |
| 165 |
// If the struct or union is packed, deriving from Copy is required for |
| 166 |
// deriving from any other trait. |
| 167 |
return derivable_traits; |
| 168 |
} |
| 169 |
|
| 170 |
if item.can_derive_debug(ctx) && !item.annotations().disallow_debug() { |
| 171 |
derivable_traits |= DerivableTraits::DEBUG; |
| 172 |
} |
| 173 |
|
| 174 |
if item.can_derive_default(ctx) && !item.annotations().disallow_default() { |
| 175 |
derivable_traits |= DerivableTraits::DEFAULT; |
| 176 |
} |
| 177 |
|
| 178 |
if item.can_derive_hash(ctx) { |
| 179 |
derivable_traits |= DerivableTraits::HASH; |
| 180 |
} |
| 181 |
|
| 182 |
if item.can_derive_partialord(ctx) { |
| 183 |
derivable_traits |= DerivableTraits::PARTIAL_ORD; |
| 184 |
} |
| 185 |
|
| 186 |
if item.can_derive_ord(ctx) { |
| 187 |
derivable_traits |= DerivableTraits::ORD; |
| 188 |
} |
| 189 |
|
| 190 |
if item.can_derive_partialeq(ctx) { |
| 191 |
derivable_traits |= DerivableTraits::PARTIAL_EQ; |
| 192 |
} |
| 193 |
|
| 194 |
if item.can_derive_eq(ctx) { |
| 195 |
derivable_traits |= DerivableTraits::EQ; |
| 196 |
} |
| 197 |
|
| 198 |
derivable_traits |
| 199 |
} |
| 200 |
|
| 201 |
impl From<DerivableTraits> for Vec<&'static str> { |
| 202 |
fn from(derivable_traits: DerivableTraits) -> Vec<&'static str> { |
| 203 |
[ |
| 204 |
(DerivableTraits::DEBUG, "Debug"), |
| 205 |
(DerivableTraits::DEFAULT, "Default"), |
| 206 |
(DerivableTraits::COPY, "Copy"), |
| 207 |
(DerivableTraits::CLONE, "Clone"), |
| 208 |
(DerivableTraits::HASH, "Hash"), |
| 209 |
(DerivableTraits::PARTIAL_ORD, "PartialOrd"), |
| 210 |
(DerivableTraits::ORD, "Ord"), |
| 211 |
(DerivableTraits::PARTIAL_EQ, "PartialEq"), |
| 212 |
(DerivableTraits::EQ, "Eq"), |
| 213 |
] |
| 214 |
.iter() |
| 215 |
.filter_map(|&(flag, derive)| { |
| 216 |
Some(derive).filter(|_| derivable_traits.contains(flag)) |
| 217 |
}) |
| 218 |
.collect() |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
struct CodegenResult<'a> { |
| 223 |
items: Vec<proc_macro2::TokenStream>, |
| 224 |
dynamic_items: DynamicItems, |
| 225 |
|
| 226 |
/// A monotonic counter used to add stable unique ID's to stuff that doesn't |
| 227 |
/// need to be referenced by anything. |
| 228 |
codegen_id: &'a Cell<usize>, |
| 229 |
|
| 230 |
/// Whether a bindgen union has been generated at least once. |
| 231 |
saw_bindgen_union: bool, |
| 232 |
|
| 233 |
/// Whether an incomplete array has been generated at least once. |
| 234 |
saw_incomplete_array: bool, |
| 235 |
|
| 236 |
/// Whether Objective C types have been seen at least once. |
| 237 |
saw_objc: bool, |
| 238 |
|
| 239 |
/// Whether Apple block types have been seen at least once. |
| 240 |
saw_block: bool, |
| 241 |
|
| 242 |
/// Whether a bitfield allocation unit has been seen at least once. |
| 243 |
saw_bitfield_unit: bool, |
| 244 |
|
| 245 |
items_seen: HashSet<ItemId>, |
| 246 |
/// The set of generated function/var names, needed because in C/C++ is |
| 247 |
/// legal to do something like: |
| 248 |
/// |
| 249 |
/// ```c++ |
| 250 |
/// extern "C" { |
| 251 |
/// void foo(); |
| 252 |
/// extern int bar; |
| 253 |
/// } |
| 254 |
/// |
| 255 |
/// extern "C" { |
| 256 |
/// void foo(); |
| 257 |
/// extern int bar; |
| 258 |
/// } |
| 259 |
/// ``` |
| 260 |
/// |
| 261 |
/// Being these two different declarations. |
| 262 |
functions_seen: HashSet<String>, |
| 263 |
vars_seen: HashSet<String>, |
| 264 |
|
| 265 |
/// Used for making bindings to overloaded functions. Maps from a canonical |
| 266 |
/// function name to the number of overloads we have already codegen'd for |
| 267 |
/// that name. This lets us give each overload a unique suffix. |
| 268 |
overload_counters: HashMap<String, u32>, |
| 269 |
|
| 270 |
items_to_serialize: Vec<ItemId>, |
| 271 |
} |
| 272 |
|
| 273 |
impl<'a> CodegenResult<'a> { |
| 274 |
fn new(codegen_id: &'a Cell<usize>) -> Self { |
| 275 |
CodegenResult { |
| 276 |
items: vec![], |
| 277 |
dynamic_items: DynamicItems::new(), |
| 278 |
saw_bindgen_union: false, |
| 279 |
saw_incomplete_array: false, |
| 280 |
saw_objc: false, |
| 281 |
saw_block: false, |
| 282 |
saw_bitfield_unit: false, |
| 283 |
codegen_id, |
| 284 |
items_seen: Default::default(), |
| 285 |
functions_seen: Default::default(), |
| 286 |
vars_seen: Default::default(), |
| 287 |
overload_counters: Default::default(), |
| 288 |
items_to_serialize: Default::default(), |
| 289 |
} |
| 290 |
} |
| 291 |
|
| 292 |
fn dynamic_items(&mut self) -> &mut DynamicItems { |
| 293 |
&mut self.dynamic_items |
| 294 |
} |
| 295 |
|
| 296 |
fn saw_bindgen_union(&mut self) { |
| 297 |
self.saw_bindgen_union = true; |
| 298 |
} |
| 299 |
|
| 300 |
fn saw_incomplete_array(&mut self) { |
| 301 |
self.saw_incomplete_array = true; |
| 302 |
} |
| 303 |
|
| 304 |
fn saw_objc(&mut self) { |
| 305 |
self.saw_objc = true; |
| 306 |
} |
| 307 |
|
| 308 |
fn saw_block(&mut self) { |
| 309 |
self.saw_block = true; |
| 310 |
} |
| 311 |
|
| 312 |
fn saw_bitfield_unit(&mut self) { |
| 313 |
self.saw_bitfield_unit = true; |
| 314 |
} |
| 315 |
|
| 316 |
fn seen<Id: Into<ItemId>>(&self, item: Id) -> bool { |
| 317 |
self.items_seen.contains(&item.into()) |
| 318 |
} |
| 319 |
|
| 320 |
fn set_seen<Id: Into<ItemId>>(&mut self, item: Id) { |
| 321 |
self.items_seen.insert(item.into()); |
| 322 |
} |
| 323 |
|
| 324 |
fn seen_function(&self, name: &str) -> bool { |
| 325 |
self.functions_seen.contains(name) |
| 326 |
} |
| 327 |
|
| 328 |
fn saw_function(&mut self, name: &str) { |
| 329 |
self.functions_seen.insert(name.into()); |
| 330 |
} |
| 331 |
|
| 332 |
/// Get the overload number for the given function name. Increments the |
| 333 |
/// counter internally so the next time we ask for the overload for this |
| 334 |
/// name, we get the incremented value, and so on. |
| 335 |
fn overload_number(&mut self, name: &str) -> u32 { |
| 336 |
let counter = self.overload_counters.entry(name.into()).or_insert(0); |
| 337 |
let number = *counter; |
| 338 |
*counter += 1; |
| 339 |
number |
| 340 |
} |
| 341 |
|
| 342 |
fn seen_var(&self, name: &str) -> bool { |
| 343 |
self.vars_seen.contains(name) |
| 344 |
} |
| 345 |
|
| 346 |
fn saw_var(&mut self, name: &str) { |
| 347 |
self.vars_seen.insert(name.into()); |
| 348 |
} |
| 349 |
|
| 350 |
fn inner<F>(&mut self, cb: F) -> Vec<proc_macro2::TokenStream> |
| 351 |
where |
| 352 |
F: FnOnce(&mut Self), |
| 353 |
{ |
| 354 |
let mut new = Self::new(self.codegen_id); |
| 355 |
|
| 356 |
cb(&mut new); |
| 357 |
|
| 358 |
self.saw_incomplete_array |= new.saw_incomplete_array; |
| 359 |
self.saw_objc |= new.saw_objc; |
| 360 |
self.saw_block |= new.saw_block; |
| 361 |
self.saw_bitfield_unit |= new.saw_bitfield_unit; |
| 362 |
self.saw_bindgen_union |= new.saw_bindgen_union; |
| 363 |
|
| 364 |
new.items |
| 365 |
} |
| 366 |
} |
| 367 |
|
| 368 |
impl<'a> ops::Deref for CodegenResult<'a> { |
| 369 |
type Target = Vec<proc_macro2::TokenStream>; |
| 370 |
|
| 371 |
fn deref(&self) -> &Self::Target { |
| 372 |
&self.items |
| 373 |
} |
| 374 |
} |
| 375 |
|
| 376 |
impl<'a> ops::DerefMut for CodegenResult<'a> { |
| 377 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 378 |
&mut self.items |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
/// A trait to convert a rust type into a pointer, optionally const, to the same |
| 383 |
/// type. |
| 384 |
trait ToPtr { |
| 385 |
fn to_ptr(self, is_const: bool) -> proc_macro2::TokenStream; |
| 386 |
} |
| 387 |
|
| 388 |
impl ToPtr for proc_macro2::TokenStream { |
| 389 |
fn to_ptr(self, is_const: bool) -> proc_macro2::TokenStream { |
| 390 |
if is_const { |
| 391 |
quote! { *const #self } |
| 392 |
} else { |
| 393 |
quote! { *mut #self } |
| 394 |
} |
| 395 |
} |
| 396 |
} |
| 397 |
|
| 398 |
/// An extension trait for `proc_macro2::TokenStream` that lets us append any implicit |
| 399 |
/// template parameters that exist for some type, if necessary. |
| 400 |
trait AppendImplicitTemplateParams { |
| 401 |
fn append_implicit_template_params( |
| 402 |
&mut self, |
| 403 |
ctx: &BindgenContext, |
| 404 |
item: &Item, |
| 405 |
); |
| 406 |
} |
| 407 |
|
| 408 |
impl AppendImplicitTemplateParams for proc_macro2::TokenStream { |
| 409 |
fn append_implicit_template_params( |
| 410 |
&mut self, |
| 411 |
ctx: &BindgenContext, |
| 412 |
item: &Item, |
| 413 |
) { |
| 414 |
let item = item.id().into_resolver().through_type_refs().resolve(ctx); |
| 415 |
|
| 416 |
match *item.expect_type().kind() { |
| 417 |
TypeKind::UnresolvedTypeRef(..) => { |
| 418 |
unreachable!("already resolved unresolved type refs") |
| 419 |
} |
| 420 |
TypeKind::ResolvedTypeRef(..) => { |
| 421 |
unreachable!("we resolved item through type refs") |
| 422 |
} |
| 423 |
|
| 424 |
// None of these types ever have implicit template parameters. |
| 425 |
TypeKind::Void | |
| 426 |
TypeKind::NullPtr | |
| 427 |
TypeKind::Pointer(..) | |
| 428 |
TypeKind::Reference(..) | |
| 429 |
TypeKind::Int(..) | |
| 430 |
TypeKind::Float(..) | |
| 431 |
TypeKind::Complex(..) | |
| 432 |
TypeKind::Array(..) | |
| 433 |
TypeKind::TypeParam | |
| 434 |
TypeKind::Opaque | |
| 435 |
TypeKind::Function(..) | |
| 436 |
TypeKind::Enum(..) | |
| 437 |
TypeKind::ObjCId | |
| 438 |
TypeKind::ObjCSel | |
| 439 |
TypeKind::TemplateInstantiation(..) => return, |
| 440 |
_ => {} |
| 441 |
} |
| 442 |
|
| 443 |
let params: Vec<_> = item |
| 444 |
.used_template_params(ctx) |
| 445 |
.iter() |
| 446 |
.map(|p| { |
| 447 |
p.try_to_rust_ty(ctx, &()) |
| 448 |
.expect("template params cannot fail to be a rust type") |
| 449 |
}) |
| 450 |
.collect(); |
| 451 |
if !params.is_empty() { |
| 452 |
self.append_all(quote! { |
| 453 |
< #( #params ),* > |
| 454 |
}); |
| 455 |
} |
| 456 |
} |
| 457 |
} |
| 458 |
|
| 459 |
trait CodeGenerator { |
| 460 |
/// Extra information from the caller. |
| 461 |
type Extra; |
| 462 |
|
| 463 |
/// Extra information returned to the caller. |
| 464 |
type Return; |
| 465 |
|
| 466 |
fn codegen( |
| 467 |
&self, |
| 468 |
ctx: &BindgenContext, |
| 469 |
result: &mut CodegenResult<'_>, |
| 470 |
extra: &Self::Extra, |
| 471 |
) -> Self::Return; |
| 472 |
} |
| 473 |
|
| 474 |
impl Item { |
| 475 |
fn process_before_codegen( |
| 476 |
&self, |
| 477 |
ctx: &BindgenContext, |
| 478 |
result: &mut CodegenResult, |
| 479 |
) -> bool { |
| 480 |
if !self.is_enabled_for_codegen(ctx) { |
| 481 |
return false; |
| 482 |
} |
| 483 |
|
| 484 |
if self.is_blocklisted(ctx) || result.seen(self.id()) { |
| 485 |
debug!( |
| 486 |
"<Item as CodeGenerator>::process_before_codegen: Ignoring hidden or seen: \ |
| 487 |
self = {:?}", |
| 488 |
self |
| 489 |
); |
| 490 |
return false; |
| 491 |
} |
| 492 |
|
| 493 |
if !ctx.codegen_items().contains(&self.id()) { |
| 494 |
// TODO(emilio, #453): Figure out what to do when this happens |
| 495 |
// legitimately, we could track the opaque stuff and disable the |
| 496 |
// assertion there I guess. |
| 497 |
warn!("Found non-allowlisted item in code generation: {:?}", self); |
| 498 |
} |
| 499 |
|
| 500 |
result.set_seen(self.id()); |
| 501 |
true |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
impl CodeGenerator for Item { |
| 506 |
type Extra = (); |
| 507 |
type Return = (); |
| 508 |
|
| 509 |
fn codegen( |
| 510 |
&self, |
| 511 |
ctx: &BindgenContext, |
| 512 |
result: &mut CodegenResult<'_>, |
| 513 |
_extra: &(), |
| 514 |
) { |
| 515 |
debug!("<Item as CodeGenerator>::codegen: self = {:?}", self); |
| 516 |
if !self.process_before_codegen(ctx, result) { |
| 517 |
return; |
| 518 |
} |
| 519 |
|
| 520 |
match *self.kind() { |
| 521 |
ItemKind::Module(ref module) => { |
| 522 |
module.codegen(ctx, result, self); |
| 523 |
} |
| 524 |
ItemKind::Function(ref fun) => { |
| 525 |
fun.codegen(ctx, result, self); |
| 526 |
} |
| 527 |
ItemKind::Var(ref var) => { |
| 528 |
var.codegen(ctx, result, self); |
| 529 |
} |
| 530 |
ItemKind::Type(ref ty) => { |
| 531 |
ty.codegen(ctx, result, self); |
| 532 |
} |
| 533 |
} |
| 534 |
} |
| 535 |
} |
| 536 |
|
| 537 |
impl CodeGenerator for Module { |
| 538 |
type Extra = Item; |
| 539 |
type Return = (); |
| 540 |
|
| 541 |
fn codegen( |
| 542 |
&self, |
| 543 |
ctx: &BindgenContext, |
| 544 |
result: &mut CodegenResult<'_>, |
| 545 |
item: &Item, |
| 546 |
) { |
| 547 |
debug!("<Module as CodeGenerator>::codegen: item = {:?}", item); |
| 548 |
|
| 549 |
let codegen_self = |result: &mut CodegenResult, |
| 550 |
found_any: &mut bool| { |
| 551 |
for child in self.children() { |
| 552 |
if ctx.codegen_items().contains(child) { |
| 553 |
*found_any = true; |
| 554 |
ctx.resolve_item(*child).codegen(ctx, result, &()); |
| 555 |
} |
| 556 |
} |
| 557 |
|
| 558 |
if item.id() == ctx.root_module() { |
| 559 |
if result.saw_block { |
| 560 |
utils::prepend_block_header(ctx, &mut *result); |
| 561 |
} |
| 562 |
if result.saw_bindgen_union { |
| 563 |
utils::prepend_union_types(ctx, &mut *result); |
| 564 |
} |
| 565 |
if result.saw_incomplete_array { |
| 566 |
utils::prepend_incomplete_array_types(ctx, &mut *result); |
| 567 |
} |
| 568 |
if ctx.need_bindgen_complex_type() { |
| 569 |
utils::prepend_complex_type(&mut *result); |
| 570 |
} |
| 571 |
if result.saw_objc { |
| 572 |
utils::prepend_objc_header(ctx, &mut *result); |
| 573 |
} |
| 574 |
if result.saw_bitfield_unit { |
| 575 |
utils::prepend_bitfield_unit_type(ctx, &mut *result); |
| 576 |
} |
| 577 |
} |
| 578 |
}; |
| 579 |
|
| 580 |
if !ctx.options().enable_cxx_namespaces || |
| 581 |
(self.is_inline() && |
| 582 |
!ctx.options().conservative_inline_namespaces) |
| 583 |
{ |
| 584 |
codegen_self(result, &mut false); |
| 585 |
return; |
| 586 |
} |
| 587 |
|
| 588 |
let mut found_any = false; |
| 589 |
let inner_items = result.inner(|result| { |
| 590 |
result.push(root_import(ctx, item)); |
| 591 |
|
| 592 |
let path = item.namespace_aware_canonical_path(ctx).join("::"); |
| 593 |
if let Some(raw_lines) = ctx.options().module_lines.get(&path) { |
| 594 |
for raw_line in raw_lines { |
| 595 |
found_any = true; |
| 596 |
result.push( |
| 597 |
proc_macro2::TokenStream::from_str(raw_line).unwrap(), |
| 598 |
); |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
codegen_self(result, &mut found_any); |
| 603 |
}); |
| 604 |
|
| 605 |
// Don't bother creating an empty module. |
| 606 |
if !found_any { |
| 607 |
return; |
| 608 |
} |
| 609 |
|
| 610 |
let name = item.canonical_name(ctx); |
| 611 |
let ident = ctx.rust_ident(name); |
| 612 |
result.push(if item.id() == ctx.root_module() { |
| 613 |
quote! { |
| 614 |
#[allow(non_snake_case, non_camel_case_types, non_upper_case_globals)] |
| 615 |
pub mod #ident { |
| 616 |
#( #inner_items )* |
| 617 |
} |
| 618 |
} |
| 619 |
} else { |
| 620 |
quote! { |
| 621 |
pub mod #ident { |
| 622 |
#( #inner_items )* |
| 623 |
} |
| 624 |
} |
| 625 |
}); |
| 626 |
} |
| 627 |
} |
| 628 |
|
| 629 |
impl CodeGenerator for Var { |
| 630 |
type Extra = Item; |
| 631 |
type Return = (); |
| 632 |
|
| 633 |
fn codegen( |
| 634 |
&self, |
| 635 |
ctx: &BindgenContext, |
| 636 |
result: &mut CodegenResult<'_>, |
| 637 |
item: &Item, |
| 638 |
) { |
| 639 |
use crate::ir::var::VarType; |
| 640 |
debug!("<Var as CodeGenerator>::codegen: item = {:?}", item); |
| 641 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 642 |
|
| 643 |
let canonical_name = item.canonical_name(ctx); |
| 644 |
|
| 645 |
if result.seen_var(&canonical_name) { |
| 646 |
return; |
| 647 |
} |
| 648 |
result.saw_var(&canonical_name); |
| 649 |
|
| 650 |
let canonical_ident = ctx.rust_ident(&canonical_name); |
| 651 |
|
| 652 |
// We can't generate bindings to static variables of templates. The |
| 653 |
// number of actual variables for a single declaration are open ended |
| 654 |
// and we don't know what instantiations do or don't exist. |
| 655 |
if !item.all_template_params(ctx).is_empty() { |
| 656 |
return; |
| 657 |
} |
| 658 |
|
| 659 |
let mut attrs = vec![]; |
| 660 |
if let Some(comment) = item.comment(ctx) { |
| 661 |
attrs.push(attributes::doc(comment)); |
| 662 |
} |
| 663 |
|
| 664 |
let ty = self.ty().to_rust_ty_or_opaque(ctx, &()); |
| 665 |
|
| 666 |
if let Some(val) = self.val() { |
| 667 |
match *val { |
| 668 |
VarType::Bool(val) => { |
| 669 |
result.push(quote! { |
| 670 |
#(#attrs)* |
| 671 |
pub const #canonical_ident : #ty = #val ; |
| 672 |
}); |
| 673 |
} |
| 674 |
VarType::Int(val) => { |
| 675 |
let int_kind = self |
| 676 |
.ty() |
| 677 |
.into_resolver() |
| 678 |
.through_type_aliases() |
| 679 |
.through_type_refs() |
| 680 |
.resolve(ctx) |
| 681 |
.expect_type() |
| 682 |
.as_integer() |
| 683 |
.unwrap(); |
| 684 |
let val = if int_kind.is_signed() { |
| 685 |
helpers::ast_ty::int_expr(val) |
| 686 |
} else { |
| 687 |
helpers::ast_ty::uint_expr(val as _) |
| 688 |
}; |
| 689 |
result.push(quote! { |
| 690 |
#(#attrs)* |
| 691 |
pub const #canonical_ident : #ty = #val ; |
| 692 |
}); |
| 693 |
} |
| 694 |
VarType::String(ref bytes) => { |
| 695 |
// Account the trailing zero. |
| 696 |
// |
| 697 |
// TODO: Here we ignore the type we just made up, probably |
| 698 |
// we should refactor how the variable type and ty ID work. |
| 699 |
let len = bytes.len() + 1; |
| 700 |
let ty = quote! { |
| 701 |
[u8; #len] |
| 702 |
}; |
| 703 |
|
| 704 |
match String::from_utf8(bytes.clone()) { |
| 705 |
Ok(string) => { |
| 706 |
let cstr = helpers::ast_ty::cstr_expr(string); |
| 707 |
if ctx |
| 708 |
.options() |
| 709 |
.rust_features |
| 710 |
.static_lifetime_elision |
| 711 |
{ |
| 712 |
result.push(quote! { |
| 713 |
#(#attrs)* |
| 714 |
pub const #canonical_ident : &#ty = #cstr ; |
| 715 |
}); |
| 716 |
} else { |
| 717 |
result.push(quote! { |
| 718 |
#(#attrs)* |
| 719 |
pub const #canonical_ident : &'static #ty = #cstr ; |
| 720 |
}); |
| 721 |
} |
| 722 |
} |
| 723 |
Err(..) => { |
| 724 |
let bytes = helpers::ast_ty::byte_array_expr(bytes); |
| 725 |
result.push(quote! { |
| 726 |
#(#attrs)* |
| 727 |
pub const #canonical_ident : #ty = #bytes ; |
| 728 |
}); |
| 729 |
} |
| 730 |
} |
| 731 |
} |
| 732 |
VarType::Float(f) => { |
| 733 |
if let Ok(expr) = helpers::ast_ty::float_expr(ctx, f) { |
| 734 |
result.push(quote! { |
| 735 |
#(#attrs)* |
| 736 |
pub const #canonical_ident : #ty = #expr ; |
| 737 |
}); |
| 738 |
} |
| 739 |
} |
| 740 |
VarType::Char(c) => { |
| 741 |
result.push(quote! { |
| 742 |
#(#attrs)* |
| 743 |
pub const #canonical_ident : #ty = #c ; |
| 744 |
}); |
| 745 |
} |
| 746 |
} |
| 747 |
} else { |
| 748 |
// If necessary, apply a `#[link_name]` attribute |
| 749 |
if let Some(link_name) = self.link_name() { |
| 750 |
attrs.push(attributes::link_name::<false>(link_name)); |
| 751 |
} else { |
| 752 |
let link_name = |
| 753 |
self.mangled_name().unwrap_or_else(|| self.name()); |
| 754 |
if !utils::names_will_be_identical_after_mangling( |
| 755 |
&canonical_name, |
| 756 |
link_name, |
| 757 |
None, |
| 758 |
) { |
| 759 |
attrs.push(attributes::link_name::<false>(link_name)); |
| 760 |
} |
| 761 |
} |
| 762 |
|
| 763 |
let maybe_mut = if self.is_const() { |
| 764 |
quote! {} |
| 765 |
} else { |
| 766 |
quote! { mut } |
| 767 |
}; |
| 768 |
|
| 769 |
let tokens = quote!( |
| 770 |
extern "C" { |
| 771 |
#(#attrs)* |
| 772 |
pub static #maybe_mut #canonical_ident: #ty; |
| 773 |
} |
| 774 |
); |
| 775 |
|
| 776 |
result.push(tokens); |
| 777 |
} |
| 778 |
} |
| 779 |
} |
| 780 |
|
| 781 |
impl CodeGenerator for Type { |
| 782 |
type Extra = Item; |
| 783 |
type Return = (); |
| 784 |
|
| 785 |
fn codegen( |
| 786 |
&self, |
| 787 |
ctx: &BindgenContext, |
| 788 |
result: &mut CodegenResult<'_>, |
| 789 |
item: &Item, |
| 790 |
) { |
| 791 |
debug!("<Type as CodeGenerator>::codegen: item = {:?}", item); |
| 792 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 793 |
|
| 794 |
match *self.kind() { |
| 795 |
TypeKind::Void | |
| 796 |
TypeKind::NullPtr | |
| 797 |
TypeKind::Int(..) | |
| 798 |
TypeKind::Float(..) | |
| 799 |
TypeKind::Complex(..) | |
| 800 |
TypeKind::Array(..) | |
| 801 |
TypeKind::Vector(..) | |
| 802 |
TypeKind::Pointer(..) | |
| 803 |
TypeKind::Reference(..) | |
| 804 |
TypeKind::Function(..) | |
| 805 |
TypeKind::ResolvedTypeRef(..) | |
| 806 |
TypeKind::Opaque | |
| 807 |
TypeKind::TypeParam => { |
| 808 |
// These items don't need code generation, they only need to be |
| 809 |
// converted to rust types in fields, arguments, and such. |
| 810 |
// NOTE(emilio): If you add to this list, make sure to also add |
| 811 |
// it to BindgenContext::compute_allowlisted_and_codegen_items. |
| 812 |
} |
| 813 |
TypeKind::TemplateInstantiation(ref inst) => { |
| 814 |
inst.codegen(ctx, result, item) |
| 815 |
} |
| 816 |
TypeKind::BlockPointer(inner) => { |
| 817 |
if !ctx.options().generate_block { |
| 818 |
return; |
| 819 |
} |
| 820 |
|
| 821 |
let inner_item = |
| 822 |
inner.into_resolver().through_type_refs().resolve(ctx); |
| 823 |
let name = item.canonical_name(ctx); |
| 824 |
|
| 825 |
let inner_rust_type = { |
| 826 |
if let TypeKind::Function(fnsig) = |
| 827 |
inner_item.kind().expect_type().kind() |
| 828 |
{ |
| 829 |
utils::fnsig_block(ctx, fnsig) |
| 830 |
} else { |
| 831 |
panic!("invalid block typedef: {:?}", inner_item) |
| 832 |
} |
| 833 |
}; |
| 834 |
|
| 835 |
let rust_name = ctx.rust_ident(name); |
| 836 |
|
| 837 |
let mut tokens = if let Some(comment) = item.comment(ctx) { |
| 838 |
attributes::doc(comment) |
| 839 |
} else { |
| 840 |
quote! {} |
| 841 |
}; |
| 842 |
|
| 843 |
tokens.append_all(quote! { |
| 844 |
pub type #rust_name = #inner_rust_type ; |
| 845 |
}); |
| 846 |
|
| 847 |
result.push(tokens); |
| 848 |
result.saw_block(); |
| 849 |
} |
| 850 |
TypeKind::Comp(ref ci) => ci.codegen(ctx, result, item), |
| 851 |
TypeKind::TemplateAlias(inner, _) | TypeKind::Alias(inner) => { |
| 852 |
let inner_item = |
| 853 |
inner.into_resolver().through_type_refs().resolve(ctx); |
| 854 |
let name = item.canonical_name(ctx); |
| 855 |
let path = item.canonical_path(ctx); |
| 856 |
|
| 857 |
{ |
| 858 |
let through_type_aliases = inner |
| 859 |
.into_resolver() |
| 860 |
.through_type_refs() |
| 861 |
.through_type_aliases() |
| 862 |
.resolve(ctx); |
| 863 |
|
| 864 |
// Try to catch the common pattern: |
| 865 |
// |
| 866 |
// typedef struct foo { ... } foo; |
| 867 |
// |
| 868 |
// here, and also other more complex cases like #946. |
| 869 |
if through_type_aliases.canonical_path(ctx) == path { |
| 870 |
return; |
| 871 |
} |
| 872 |
} |
| 873 |
|
| 874 |
// If this is a known named type, disallow generating anything |
| 875 |
// for it too. If size_t -> usize conversions are enabled, we |
| 876 |
// need to check that these conversions are permissible, but |
| 877 |
// nothing needs to be generated, still. |
| 878 |
let spelling = self.name().expect("Unnamed alias?"); |
| 879 |
if utils::type_from_named(ctx, spelling).is_some() { |
| 880 |
if let "size_t" | "ssize_t" = spelling { |
| 881 |
let layout = inner_item |
| 882 |
.kind() |
| 883 |
.expect_type() |
| 884 |
.layout(ctx) |
| 885 |
.expect("No layout?"); |
| 886 |
assert_eq!( |
| 887 |
layout.size, |
| 888 |
ctx.target_pointer_size(), |
| 889 |
"Target platform requires `--no-size_t-is-usize`. The size of `{}` ({}) does not match the target pointer size ({})", |
| 890 |
spelling, |
| 891 |
layout.size, |
| 892 |
ctx.target_pointer_size(), |
| 893 |
); |
| 894 |
assert_eq!( |
| 895 |
layout.align, |
| 896 |
ctx.target_pointer_size(), |
| 897 |
"Target platform requires `--no-size_t-is-usize`. The alignment of `{}` ({}) does not match the target pointer size ({})", |
| 898 |
spelling, |
| 899 |
layout.align, |
| 900 |
ctx.target_pointer_size(), |
| 901 |
); |
| 902 |
} |
| 903 |
return; |
| 904 |
} |
| 905 |
|
| 906 |
let mut outer_params = item.used_template_params(ctx); |
| 907 |
|
| 908 |
let is_opaque = item.is_opaque(ctx, &()); |
| 909 |
let inner_rust_type = if is_opaque { |
| 910 |
outer_params = vec![]; |
| 911 |
self.to_opaque(ctx, item) |
| 912 |
} else { |
| 913 |
// Its possible that we have better layout information than |
| 914 |
// the inner type does, so fall back to an opaque blob based |
| 915 |
// on our layout if converting the inner item fails. |
| 916 |
let mut inner_ty = inner_item |
| 917 |
.try_to_rust_ty_or_opaque(ctx, &()) |
| 918 |
.unwrap_or_else(|_| self.to_opaque(ctx, item)); |
| 919 |
inner_ty.append_implicit_template_params(ctx, inner_item); |
| 920 |
inner_ty |
| 921 |
}; |
| 922 |
|
| 923 |
{ |
| 924 |
// FIXME(emilio): This is a workaround to avoid generating |
| 925 |
// incorrect type aliases because of types that we haven't |
| 926 |
// been able to resolve (because, eg, they depend on a |
| 927 |
// template parameter). |
| 928 |
// |
| 929 |
// It's kind of a shame not generating them even when they |
| 930 |
// could be referenced, but we already do the same for items |
| 931 |
// with invalid template parameters, and at least this way |
| 932 |
// they can be replaced, instead of generating plain invalid |
| 933 |
// code. |
| 934 |
let inner_canon_type = |
| 935 |
inner_item.expect_type().canonical_type(ctx); |
| 936 |
if inner_canon_type.is_invalid_type_param() { |
| 937 |
warn!( |
| 938 |
"Item contained invalid named type, skipping: \ |
| 939 |
{:?}, {:?}", |
| 940 |
item, inner_item |
| 941 |
); |
| 942 |
return; |
| 943 |
} |
| 944 |
} |
| 945 |
|
| 946 |
let rust_name = ctx.rust_ident(&name); |
| 947 |
|
| 948 |
let mut tokens = if let Some(comment) = item.comment(ctx) { |
| 949 |
attributes::doc(comment) |
| 950 |
} else { |
| 951 |
quote! {} |
| 952 |
}; |
| 953 |
|
| 954 |
let alias_style = if ctx.options().type_alias.matches(&name) { |
| 955 |
AliasVariation::TypeAlias |
| 956 |
} else if ctx.options().new_type_alias.matches(&name) { |
| 957 |
AliasVariation::NewType |
| 958 |
} else if ctx.options().new_type_alias_deref.matches(&name) { |
| 959 |
AliasVariation::NewTypeDeref |
| 960 |
} else { |
| 961 |
ctx.options().default_alias_style |
| 962 |
}; |
| 963 |
|
| 964 |
// We prefer using `pub use` over `pub type` because of: |
| 965 |
// https://github.com/rust-lang/rust/issues/26264 |
| 966 |
// These are the only characters allowed in simple |
| 967 |
// paths, eg `good::dogs::Bront`. |
| 968 |
if inner_rust_type.to_string().chars().all(|c| matches!(c, 'A'..='Z' | 'a'..='z' | '0'..='9' | ':' | '_' | ' ')) && outer_params.is_empty() && |
| 969 |
!is_opaque && |
| 970 |
alias_style == AliasVariation::TypeAlias && |
| 971 |
inner_item.expect_type().canonical_type(ctx).is_enum() |
| 972 |
{ |
| 973 |
tokens.append_all(quote! { |
| 974 |
pub use |
| 975 |
}); |
| 976 |
let path = top_level_path(ctx, item); |
| 977 |
tokens.append_separated(path, quote!(::)); |
| 978 |
tokens.append_all(quote! { |
| 979 |
:: #inner_rust_type as #rust_name ; |
| 980 |
}); |
| 981 |
result.push(tokens); |
| 982 |
return; |
| 983 |
} |
| 984 |
|
| 985 |
tokens.append_all(match alias_style { |
| 986 |
AliasVariation::TypeAlias => quote! { |
| 987 |
pub type #rust_name |
| 988 |
}, |
| 989 |
AliasVariation::NewType | AliasVariation::NewTypeDeref => { |
| 990 |
assert!( |
| 991 |
ctx.options().rust_features().repr_transparent, |
| 992 |
"repr_transparent feature is required to use {:?}", |
| 993 |
alias_style |
| 994 |
); |
| 995 |
|
| 996 |
let mut attributes = |
| 997 |
vec![attributes::repr("transparent")]; |
| 998 |
let packed = false; // Types can't be packed in Rust. |
| 999 |
let derivable_traits = |
| 1000 |
derives_of_item(item, ctx, packed); |
| 1001 |
if !derivable_traits.is_empty() { |
| 1002 |
let derives: Vec<_> = derivable_traits.into(); |
| 1003 |
attributes.push(attributes::derives(&derives)) |
| 1004 |
} |
| 1005 |
|
| 1006 |
quote! { |
| 1007 |
#( #attributes )* |
| 1008 |
pub struct #rust_name |
| 1009 |
} |
| 1010 |
} |
| 1011 |
}); |
| 1012 |
|
| 1013 |
let params: Vec<_> = outer_params |
| 1014 |
.into_iter() |
| 1015 |
.filter_map(|p| p.as_template_param(ctx, &())) |
| 1016 |
.collect(); |
| 1017 |
if params |
| 1018 |
.iter() |
| 1019 |
.any(|p| ctx.resolve_type(*p).is_invalid_type_param()) |
| 1020 |
{ |
| 1021 |
warn!( |
| 1022 |
"Item contained invalid template \ |
| 1023 |
parameter: {:?}", |
| 1024 |
item |
| 1025 |
); |
| 1026 |
return; |
| 1027 |
} |
| 1028 |
let params: Vec<_> = params |
| 1029 |
.iter() |
| 1030 |
.map(|p| { |
| 1031 |
p.try_to_rust_ty(ctx, &()).expect( |
| 1032 |
"type parameters can always convert to rust ty OK", |
| 1033 |
) |
| 1034 |
}) |
| 1035 |
.collect(); |
| 1036 |
|
| 1037 |
if !params.is_empty() { |
| 1038 |
tokens.append_all(quote! { |
| 1039 |
< #( #params ),* > |
| 1040 |
}); |
| 1041 |
} |
| 1042 |
|
| 1043 |
let access_spec = |
| 1044 |
access_specifier(ctx.options().default_visibility); |
| 1045 |
tokens.append_all(match alias_style { |
| 1046 |
AliasVariation::TypeAlias => quote! { |
| 1047 |
= #inner_rust_type ; |
| 1048 |
}, |
| 1049 |
AliasVariation::NewType | AliasVariation::NewTypeDeref => { |
| 1050 |
quote! { |
| 1051 |
(#access_spec #inner_rust_type) ; |
| 1052 |
} |
| 1053 |
} |
| 1054 |
}); |
| 1055 |
|
| 1056 |
if alias_style == AliasVariation::NewTypeDeref { |
| 1057 |
let prefix = ctx.trait_prefix(); |
| 1058 |
tokens.append_all(quote! { |
| 1059 |
impl ::#prefix::ops::Deref for #rust_name { |
| 1060 |
type Target = #inner_rust_type; |
| 1061 |
#[inline] |
| 1062 |
fn deref(&self) -> &Self::Target { |
| 1063 |
&self.0 |
| 1064 |
} |
| 1065 |
} |
| 1066 |
impl ::#prefix::ops::DerefMut for #rust_name { |
| 1067 |
#[inline] |
| 1068 |
fn deref_mut(&mut self) -> &mut Self::Target { |
| 1069 |
&mut self.0 |
| 1070 |
} |
| 1071 |
} |
| 1072 |
}); |
| 1073 |
} |
| 1074 |
|
| 1075 |
result.push(tokens); |
| 1076 |
} |
| 1077 |
TypeKind::Enum(ref ei) => ei.codegen(ctx, result, item), |
| 1078 |
TypeKind::ObjCId | TypeKind::ObjCSel => { |
| 1079 |
result.saw_objc(); |
| 1080 |
} |
| 1081 |
TypeKind::ObjCInterface(ref interface) => { |
| 1082 |
interface.codegen(ctx, result, item) |
| 1083 |
} |
| 1084 |
ref u @ TypeKind::UnresolvedTypeRef(..) => { |
| 1085 |
unreachable!("Should have been resolved after parsing {:?}!", u) |
| 1086 |
} |
| 1087 |
} |
| 1088 |
} |
| 1089 |
} |
| 1090 |
|
| 1091 |
struct Vtable<'a> { |
| 1092 |
item_id: ItemId, |
| 1093 |
/// A reference to the originating compound object. |
| 1094 |
#[allow(dead_code)] |
| 1095 |
comp_info: &'a CompInfo, |
| 1096 |
} |
| 1097 |
|
| 1098 |
impl<'a> Vtable<'a> { |
| 1099 |
fn new(item_id: ItemId, comp_info: &'a CompInfo) -> Self { |
| 1100 |
Vtable { item_id, comp_info } |
| 1101 |
} |
| 1102 |
} |
| 1103 |
|
| 1104 |
impl<'a> CodeGenerator for Vtable<'a> { |
| 1105 |
type Extra = Item; |
| 1106 |
type Return = (); |
| 1107 |
|
| 1108 |
fn codegen( |
| 1109 |
&self, |
| 1110 |
ctx: &BindgenContext, |
| 1111 |
result: &mut CodegenResult<'_>, |
| 1112 |
item: &Item, |
| 1113 |
) { |
| 1114 |
assert_eq!(item.id(), self.item_id); |
| 1115 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 1116 |
let name = ctx.rust_ident(self.canonical_name(ctx)); |
| 1117 |
|
| 1118 |
// For now, we will only generate vtables for classes that: |
| 1119 |
// - do not inherit from others (compilers merge VTable from primary parent class). |
| 1120 |
// - do not contain a virtual destructor (requires ordering; platforms generate different vtables). |
| 1121 |
if ctx.options().vtable_generation && |
| 1122 |
self.comp_info.base_members().is_empty() && |
| 1123 |
self.comp_info.destructor().is_none() |
| 1124 |
{ |
| 1125 |
let class_ident = ctx.rust_ident(self.item_id.canonical_name(ctx)); |
| 1126 |
|
| 1127 |
let methods = self |
| 1128 |
.comp_info |
| 1129 |
.methods() |
| 1130 |
.iter() |
| 1131 |
.filter_map(|m| { |
| 1132 |
if !m.is_virtual() { |
| 1133 |
return None; |
| 1134 |
} |
| 1135 |
|
| 1136 |
let function_item = ctx.resolve_item(m.signature()); |
| 1137 |
let function = function_item.expect_function(); |
| 1138 |
let signature_item = ctx.resolve_item(function.signature()); |
| 1139 |
let signature = match signature_item.expect_type().kind() { |
| 1140 |
TypeKind::Function(ref sig) => sig, |
| 1141 |
_ => panic!("Function signature type mismatch"), |
| 1142 |
}; |
| 1143 |
|
| 1144 |
// FIXME: Is there a canonical name without the class prepended? |
| 1145 |
let function_name = function_item.canonical_name(ctx); |
| 1146 |
|
| 1147 |
// FIXME: Need to account for overloading with times_seen (separately from regular function path). |
| 1148 |
let function_name = ctx.rust_ident(function_name); |
| 1149 |
let mut args = utils::fnsig_arguments(ctx, signature); |
| 1150 |
let ret = utils::fnsig_return_ty(ctx, signature); |
| 1151 |
|
| 1152 |
args[0] = if m.is_const() { |
| 1153 |
quote! { this: *const #class_ident } |
| 1154 |
} else { |
| 1155 |
quote! { this: *mut #class_ident } |
| 1156 |
}; |
| 1157 |
|
| 1158 |
Some(quote! { |
| 1159 |
pub #function_name : unsafe extern "C" fn( #( #args ),* ) #ret |
| 1160 |
}) |
| 1161 |
}) |
| 1162 |
.collect::<Vec<_>>(); |
| 1163 |
|
| 1164 |
result.push(quote! { |
| 1165 |
#[repr(C)] |
| 1166 |
pub struct #name { |
| 1167 |
#( #methods ),* |
| 1168 |
} |
| 1169 |
}) |
| 1170 |
} else { |
| 1171 |
// For the cases we don't support, simply generate an empty struct. |
| 1172 |
let void = helpers::ast_ty::c_void(ctx); |
| 1173 |
|
| 1174 |
result.push(quote! { |
| 1175 |
#[repr(C)] |
| 1176 |
pub struct #name ( #void ); |
| 1177 |
}); |
| 1178 |
} |
| 1179 |
} |
| 1180 |
} |
| 1181 |
|
| 1182 |
impl<'a> ItemCanonicalName for Vtable<'a> { |
| 1183 |
fn canonical_name(&self, ctx: &BindgenContext) -> String { |
| 1184 |
format!("{}__bindgen_vtable", self.item_id.canonical_name(ctx)) |
| 1185 |
} |
| 1186 |
} |
| 1187 |
|
| 1188 |
impl<'a> TryToRustTy for Vtable<'a> { |
| 1189 |
type Extra = (); |
| 1190 |
|
| 1191 |
fn try_to_rust_ty( |
| 1192 |
&self, |
| 1193 |
ctx: &BindgenContext, |
| 1194 |
_: &(), |
| 1195 |
) -> error::Result<proc_macro2::TokenStream> { |
| 1196 |
let name = ctx.rust_ident(self.canonical_name(ctx)); |
| 1197 |
Ok(quote! { |
| 1198 |
#name |
| 1199 |
}) |
| 1200 |
} |
| 1201 |
} |
| 1202 |
|
| 1203 |
impl CodeGenerator for TemplateInstantiation { |
| 1204 |
type Extra = Item; |
| 1205 |
type Return = (); |
| 1206 |
|
| 1207 |
fn codegen( |
| 1208 |
&self, |
| 1209 |
ctx: &BindgenContext, |
| 1210 |
result: &mut CodegenResult<'_>, |
| 1211 |
item: &Item, |
| 1212 |
) { |
| 1213 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 1214 |
|
| 1215 |
// Although uses of instantiations don't need code generation, and are |
| 1216 |
// just converted to rust types in fields, vars, etc, we take this |
| 1217 |
// opportunity to generate tests for their layout here. If the |
| 1218 |
// instantiation is opaque, then its presumably because we don't |
| 1219 |
// properly understand it (maybe because of specializations), and so we |
| 1220 |
// shouldn't emit layout tests either. |
| 1221 |
if !ctx.options().layout_tests || self.is_opaque(ctx, item) { |
| 1222 |
return; |
| 1223 |
} |
| 1224 |
|
| 1225 |
// If there are any unbound type parameters, then we can't generate a |
| 1226 |
// layout test because we aren't dealing with a concrete type with a |
| 1227 |
// concrete size and alignment. |
| 1228 |
if ctx.uses_any_template_parameters(item.id()) { |
| 1229 |
return; |
| 1230 |
} |
| 1231 |
|
| 1232 |
let layout = item.kind().expect_type().layout(ctx); |
| 1233 |
|
| 1234 |
if let Some(layout) = layout { |
| 1235 |
let size = layout.size; |
| 1236 |
let align = layout.align; |
| 1237 |
|
| 1238 |
let name = item.full_disambiguated_name(ctx); |
| 1239 |
let mut fn_name = |
| 1240 |
format!("__bindgen_test_layout_{}_instantiation", name); |
| 1241 |
let times_seen = result.overload_number(&fn_name); |
| 1242 |
if times_seen > 0 { |
| 1243 |
write!(&mut fn_name, "_{}", times_seen).unwrap(); |
| 1244 |
} |
| 1245 |
|
| 1246 |
let fn_name = ctx.rust_ident_raw(fn_name); |
| 1247 |
|
| 1248 |
let prefix = ctx.trait_prefix(); |
| 1249 |
let ident = item.to_rust_ty_or_opaque(ctx, &()); |
| 1250 |
let size_of_expr = quote! { |
| 1251 |
::#prefix::mem::size_of::<#ident>() |
| 1252 |
}; |
| 1253 |
let align_of_expr = quote! { |
| 1254 |
::#prefix::mem::align_of::<#ident>() |
| 1255 |
}; |
| 1256 |
|
| 1257 |
let item = quote! { |
| 1258 |
#[test] |
| 1259 |
fn #fn_name() { |
| 1260 |
assert_eq!(#size_of_expr, #size, |
| 1261 |
concat!("Size of template specialization: ", |
| 1262 |
stringify!(#ident))); |
| 1263 |
assert_eq!(#align_of_expr, #align, |
| 1264 |
concat!("Alignment of template specialization: ", |
| 1265 |
stringify!(#ident))); |
| 1266 |
} |
| 1267 |
}; |
| 1268 |
|
| 1269 |
result.push(item); |
| 1270 |
} |
| 1271 |
} |
| 1272 |
} |
| 1273 |
|
| 1274 |
/// Trait for implementing the code generation of a struct or union field. |
| 1275 |
trait FieldCodegen<'a> { |
| 1276 |
type Extra; |
| 1277 |
|
| 1278 |
#[allow(clippy::too_many_arguments)] |
| 1279 |
fn codegen<F, M>( |
| 1280 |
&self, |
| 1281 |
ctx: &BindgenContext, |
| 1282 |
visibility_kind: FieldVisibilityKind, |
| 1283 |
accessor_kind: FieldAccessorKind, |
| 1284 |
parent: &CompInfo, |
| 1285 |
result: &mut CodegenResult, |
| 1286 |
struct_layout: &mut StructLayoutTracker, |
| 1287 |
fields: &mut F, |
| 1288 |
methods: &mut M, |
| 1289 |
extra: Self::Extra, |
| 1290 |
) where |
| 1291 |
F: Extend<proc_macro2::TokenStream>, |
| 1292 |
M: Extend<proc_macro2::TokenStream>; |
| 1293 |
} |
| 1294 |
|
| 1295 |
impl<'a> FieldCodegen<'a> for Field { |
| 1296 |
type Extra = (); |
| 1297 |
|
| 1298 |
fn codegen<F, M>( |
| 1299 |
&self, |
| 1300 |
ctx: &BindgenContext, |
| 1301 |
visibility_kind: FieldVisibilityKind, |
| 1302 |
accessor_kind: FieldAccessorKind, |
| 1303 |
parent: &CompInfo, |
| 1304 |
result: &mut CodegenResult, |
| 1305 |
struct_layout: &mut StructLayoutTracker, |
| 1306 |
fields: &mut F, |
| 1307 |
methods: &mut M, |
| 1308 |
_: (), |
| 1309 |
) where |
| 1310 |
F: Extend<proc_macro2::TokenStream>, |
| 1311 |
M: Extend<proc_macro2::TokenStream>, |
| 1312 |
{ |
| 1313 |
match *self { |
| 1314 |
Field::DataMember(ref data) => { |
| 1315 |
data.codegen( |
| 1316 |
ctx, |
| 1317 |
visibility_kind, |
| 1318 |
accessor_kind, |
| 1319 |
parent, |
| 1320 |
result, |
| 1321 |
struct_layout, |
| 1322 |
fields, |
| 1323 |
methods, |
| 1324 |
(), |
| 1325 |
); |
| 1326 |
} |
| 1327 |
Field::Bitfields(ref unit) => { |
| 1328 |
unit.codegen( |
| 1329 |
ctx, |
| 1330 |
visibility_kind, |
| 1331 |
accessor_kind, |
| 1332 |
parent, |
| 1333 |
result, |
| 1334 |
struct_layout, |
| 1335 |
fields, |
| 1336 |
methods, |
| 1337 |
(), |
| 1338 |
); |
| 1339 |
} |
| 1340 |
} |
| 1341 |
} |
| 1342 |
} |
| 1343 |
|
| 1344 |
fn wrap_union_field_if_needed( |
| 1345 |
ctx: &BindgenContext, |
| 1346 |
struct_layout: &StructLayoutTracker, |
| 1347 |
ty: proc_macro2::TokenStream, |
| 1348 |
result: &mut CodegenResult, |
| 1349 |
) -> proc_macro2::TokenStream { |
| 1350 |
if struct_layout.is_rust_union() { |
| 1351 |
if struct_layout.can_copy_union_fields() { |
| 1352 |
ty |
| 1353 |
} else { |
| 1354 |
let prefix = ctx.trait_prefix(); |
| 1355 |
quote! { |
| 1356 |
::#prefix::mem::ManuallyDrop<#ty> |
| 1357 |
} |
| 1358 |
} |
| 1359 |
} else { |
| 1360 |
result.saw_bindgen_union(); |
| 1361 |
if ctx.options().enable_cxx_namespaces { |
| 1362 |
quote! { |
| 1363 |
root::__BindgenUnionField<#ty> |
| 1364 |
} |
| 1365 |
} else { |
| 1366 |
quote! { |
| 1367 |
__BindgenUnionField<#ty> |
| 1368 |
} |
| 1369 |
} |
| 1370 |
} |
| 1371 |
} |
| 1372 |
|
| 1373 |
impl<'a> FieldCodegen<'a> for FieldData { |
| 1374 |
type Extra = (); |
| 1375 |
|
| 1376 |
fn codegen<F, M>( |
| 1377 |
&self, |
| 1378 |
ctx: &BindgenContext, |
| 1379 |
parent_visibility_kind: FieldVisibilityKind, |
| 1380 |
accessor_kind: FieldAccessorKind, |
| 1381 |
parent: &CompInfo, |
| 1382 |
result: &mut CodegenResult, |
| 1383 |
struct_layout: &mut StructLayoutTracker, |
| 1384 |
fields: &mut F, |
| 1385 |
methods: &mut M, |
| 1386 |
_: (), |
| 1387 |
) where |
| 1388 |
F: Extend<proc_macro2::TokenStream>, |
| 1389 |
M: Extend<proc_macro2::TokenStream>, |
| 1390 |
{ |
| 1391 |
// Bitfields are handled by `FieldCodegen` implementations for |
| 1392 |
// `BitfieldUnit` and `Bitfield`. |
| 1393 |
assert!(self.bitfield_width().is_none()); |
| 1394 |
|
| 1395 |
let field_item = |
| 1396 |
self.ty().into_resolver().through_type_refs().resolve(ctx); |
| 1397 |
let field_ty = field_item.expect_type(); |
| 1398 |
let mut ty = self.ty().to_rust_ty_or_opaque(ctx, &()); |
| 1399 |
ty.append_implicit_template_params(ctx, field_item); |
| 1400 |
|
| 1401 |
// NB: If supported, we use proper `union` types. |
| 1402 |
let ty = if parent.is_union() { |
| 1403 |
wrap_union_field_if_needed(ctx, struct_layout, ty, result) |
| 1404 |
} else if let Some(item) = field_ty.is_incomplete_array(ctx) { |
| 1405 |
result.saw_incomplete_array(); |
| 1406 |
|
| 1407 |
let inner = item.to_rust_ty_or_opaque(ctx, &()); |
| 1408 |
|
| 1409 |
if ctx.options().enable_cxx_namespaces { |
| 1410 |
quote! { |
| 1411 |
root::__IncompleteArrayField<#inner> |
| 1412 |
} |
| 1413 |
} else { |
| 1414 |
quote! { |
| 1415 |
__IncompleteArrayField<#inner> |
| 1416 |
} |
| 1417 |
} |
| 1418 |
} else { |
| 1419 |
ty |
| 1420 |
}; |
| 1421 |
|
| 1422 |
let mut field = quote! {}; |
| 1423 |
if ctx.options().generate_comments { |
| 1424 |
if let Some(raw_comment) = self.comment() { |
| 1425 |
let comment = ctx.options().process_comment(raw_comment); |
| 1426 |
field = attributes::doc(comment); |
| 1427 |
} |
| 1428 |
} |
| 1429 |
|
| 1430 |
let field_name = self |
| 1431 |
.name() |
| 1432 |
.map(|name| ctx.rust_mangle(name).into_owned()) |
| 1433 |
.expect("Each field should have a name in codegen!"); |
| 1434 |
let field_ident = ctx.rust_ident_raw(field_name.as_str()); |
| 1435 |
|
| 1436 |
if let Some(padding_field) = |
| 1437 |
struct_layout.saw_field(&field_name, field_ty, self.offset()) |
| 1438 |
{ |
| 1439 |
fields.extend(Some(padding_field)); |
| 1440 |
} |
| 1441 |
|
| 1442 |
let visibility = compute_visibility( |
| 1443 |
ctx, |
| 1444 |
self.is_public(), |
| 1445 |
Some(self.annotations()), |
| 1446 |
parent_visibility_kind, |
| 1447 |
); |
| 1448 |
let accessor_kind = |
| 1449 |
self.annotations().accessor_kind().unwrap_or(accessor_kind); |
| 1450 |
|
| 1451 |
match visibility { |
| 1452 |
FieldVisibilityKind::Private => { |
| 1453 |
field.append_all(quote! { |
| 1454 |
#field_ident : #ty , |
| 1455 |
}); |
| 1456 |
} |
| 1457 |
FieldVisibilityKind::PublicCrate => { |
| 1458 |
field.append_all(quote! { |
| 1459 |
pub(crate) #field_ident : #ty , |
| 1460 |
}); |
| 1461 |
} |
| 1462 |
FieldVisibilityKind::Public => { |
| 1463 |
field.append_all(quote! { |
| 1464 |
pub #field_ident : #ty , |
| 1465 |
}); |
| 1466 |
} |
| 1467 |
} |
| 1468 |
|
| 1469 |
fields.extend(Some(field)); |
| 1470 |
|
| 1471 |
// TODO: Factor the following code out, please! |
| 1472 |
if accessor_kind == FieldAccessorKind::None { |
| 1473 |
return; |
| 1474 |
} |
| 1475 |
|
| 1476 |
let getter_name = ctx.rust_ident_raw(format!("get_{}", field_name)); |
| 1477 |
let mutable_getter_name = |
| 1478 |
ctx.rust_ident_raw(format!("get_{}_mut", field_name)); |
| 1479 |
let field_name = ctx.rust_ident_raw(field_name); |
| 1480 |
|
| 1481 |
methods.extend(Some(match accessor_kind { |
| 1482 |
FieldAccessorKind::None => unreachable!(), |
| 1483 |
FieldAccessorKind::Regular => { |
| 1484 |
quote! { |
| 1485 |
#[inline] |
| 1486 |
pub fn #getter_name(&self) -> & #ty { |
| 1487 |
&self.#field_name |
| 1488 |
} |
| 1489 |
|
| 1490 |
#[inline] |
| 1491 |
pub fn #mutable_getter_name(&mut self) -> &mut #ty { |
| 1492 |
&mut self.#field_name |
| 1493 |
} |
| 1494 |
} |
| 1495 |
} |
| 1496 |
FieldAccessorKind::Unsafe => { |
| 1497 |
quote! { |
| 1498 |
#[inline] |
| 1499 |
pub unsafe fn #getter_name(&self) -> & #ty { |
| 1500 |
&self.#field_name |
| 1501 |
} |
| 1502 |
|
| 1503 |
#[inline] |
| 1504 |
pub unsafe fn #mutable_getter_name(&mut self) -> &mut #ty { |
| 1505 |
&mut self.#field_name |
| 1506 |
} |
| 1507 |
} |
| 1508 |
} |
| 1509 |
FieldAccessorKind::Immutable => { |
| 1510 |
quote! { |
| 1511 |
#[inline] |
| 1512 |
pub fn #getter_name(&self) -> & #ty { |
| 1513 |
&self.#field_name |
| 1514 |
} |
| 1515 |
} |
| 1516 |
} |
| 1517 |
})); |
| 1518 |
} |
| 1519 |
} |
| 1520 |
|
| 1521 |
impl BitfieldUnit { |
| 1522 |
/// Get the constructor name for this bitfield unit. |
| 1523 |
fn ctor_name(&self) -> proc_macro2::TokenStream { |
| 1524 |
let ctor_name = Ident::new( |
| 1525 |
&format!("new_bitfield_{}", self.nth()), |
| 1526 |
Span::call_site(), |
| 1527 |
); |
| 1528 |
quote! { |
| 1529 |
#ctor_name |
| 1530 |
} |
| 1531 |
} |
| 1532 |
} |
| 1533 |
|
| 1534 |
impl Bitfield { |
| 1535 |
/// Extend an under construction bitfield unit constructor with this |
| 1536 |
/// bitfield. This sets the relevant bits on the `__bindgen_bitfield_unit` |
| 1537 |
/// variable that's being constructed. |
| 1538 |
fn extend_ctor_impl( |
| 1539 |
&self, |
| 1540 |
ctx: &BindgenContext, |
| 1541 |
param_name: proc_macro2::TokenStream, |
| 1542 |
mut ctor_impl: proc_macro2::TokenStream, |
| 1543 |
) -> proc_macro2::TokenStream { |
| 1544 |
let bitfield_ty = ctx.resolve_type(self.ty()); |
| 1545 |
let bitfield_ty_layout = bitfield_ty |
| 1546 |
.layout(ctx) |
| 1547 |
.expect("Bitfield without layout? Gah!"); |
| 1548 |
let bitfield_int_ty = helpers::integer_type(ctx, bitfield_ty_layout) |
| 1549 |
.expect( |
| 1550 |
"Should already have verified that the bitfield is \ |
| 1551 |
representable as an int", |
| 1552 |
); |
| 1553 |
|
| 1554 |
let offset = self.offset_into_unit(); |
| 1555 |
let width = self.width() as u8; |
| 1556 |
let prefix = ctx.trait_prefix(); |
| 1557 |
|
| 1558 |
ctor_impl.append_all(quote! { |
| 1559 |
__bindgen_bitfield_unit.set( |
| 1560 |
#offset, |
| 1561 |
#width, |
| 1562 |
{ |
| 1563 |
let #param_name: #bitfield_int_ty = unsafe { |
| 1564 |
::#prefix::mem::transmute(#param_name) |
| 1565 |
}; |
| 1566 |
#param_name as u64 |
| 1567 |
} |
| 1568 |
); |
| 1569 |
}); |
| 1570 |
|
| 1571 |
ctor_impl |
| 1572 |
} |
| 1573 |
} |
| 1574 |
|
| 1575 |
fn access_specifier( |
| 1576 |
visibility: FieldVisibilityKind, |
| 1577 |
) -> proc_macro2::TokenStream { |
| 1578 |
match visibility { |
| 1579 |
FieldVisibilityKind::Private => quote! {}, |
| 1580 |
FieldVisibilityKind::PublicCrate => quote! { pub(crate) }, |
| 1581 |
FieldVisibilityKind::Public => quote! { pub }, |
| 1582 |
} |
| 1583 |
} |
| 1584 |
|
| 1585 |
/// Compute a fields or structs visibility based on multiple conditions. |
| 1586 |
/// 1. If the element was declared public, and we respect such CXX accesses specs |
| 1587 |
/// (context option) => By default Public, but this can be overruled by an `annotation`. |
| 1588 |
/// |
| 1589 |
/// 2. If the element was declared private, and we respect such CXX accesses specs |
| 1590 |
/// (context option) => By default Private, but this can be overruled by an `annotation`. |
| 1591 |
/// |
| 1592 |
/// 3. If we do not respect visibility modifiers, the result depends on the `annotation`, |
| 1593 |
/// if any, or the passed `default_kind`. |
| 1594 |
/// |
| 1595 |
fn compute_visibility( |
| 1596 |
ctx: &BindgenContext, |
| 1597 |
is_declared_public: bool, |
| 1598 |
annotations: Option<&Annotations>, |
| 1599 |
default_kind: FieldVisibilityKind, |
| 1600 |
) -> FieldVisibilityKind { |
| 1601 |
match ( |
| 1602 |
is_declared_public, |
| 1603 |
ctx.options().respect_cxx_access_specs, |
| 1604 |
annotations.and_then(|e| e.visibility_kind()), |
| 1605 |
) { |
| 1606 |
(true, true, annotated_visibility) => { |
| 1607 |
// declared as public, cxx specs are respected |
| 1608 |
annotated_visibility.unwrap_or(FieldVisibilityKind::Public) |
| 1609 |
} |
| 1610 |
(false, true, annotated_visibility) => { |
| 1611 |
// declared as private, cxx specs are respected |
| 1612 |
annotated_visibility.unwrap_or(FieldVisibilityKind::Private) |
| 1613 |
} |
| 1614 |
(_, false, annotated_visibility) => { |
| 1615 |
// cxx specs are not respected, declaration does not matter. |
| 1616 |
annotated_visibility.unwrap_or(default_kind) |
| 1617 |
} |
| 1618 |
} |
| 1619 |
} |
| 1620 |
|
| 1621 |
impl<'a> FieldCodegen<'a> for BitfieldUnit { |
| 1622 |
type Extra = (); |
| 1623 |
|
| 1624 |
fn codegen<F, M>( |
| 1625 |
&self, |
| 1626 |
ctx: &BindgenContext, |
| 1627 |
visibility_kind: FieldVisibilityKind, |
| 1628 |
accessor_kind: FieldAccessorKind, |
| 1629 |
parent: &CompInfo, |
| 1630 |
result: &mut CodegenResult, |
| 1631 |
struct_layout: &mut StructLayoutTracker, |
| 1632 |
fields: &mut F, |
| 1633 |
methods: &mut M, |
| 1634 |
_: (), |
| 1635 |
) where |
| 1636 |
F: Extend<proc_macro2::TokenStream>, |
| 1637 |
M: Extend<proc_macro2::TokenStream>, |
| 1638 |
{ |
| 1639 |
use crate::ir::ty::RUST_DERIVE_IN_ARRAY_LIMIT; |
| 1640 |
|
| 1641 |
result.saw_bitfield_unit(); |
| 1642 |
|
| 1643 |
let layout = self.layout(); |
| 1644 |
let unit_field_ty = helpers::bitfield_unit(ctx, layout); |
| 1645 |
let field_ty = { |
| 1646 |
let unit_field_ty = unit_field_ty.clone(); |
| 1647 |
if parent.is_union() { |
| 1648 |
wrap_union_field_if_needed( |
| 1649 |
ctx, |
| 1650 |
struct_layout, |
| 1651 |
unit_field_ty, |
| 1652 |
result, |
| 1653 |
) |
| 1654 |
} else { |
| 1655 |
unit_field_ty |
| 1656 |
} |
| 1657 |
}; |
| 1658 |
|
| 1659 |
{ |
| 1660 |
let align_field_name = format!("_bitfield_align_{}", self.nth()); |
| 1661 |
let align_field_ident = ctx.rust_ident(align_field_name); |
| 1662 |
let align_ty = match self.layout().align { |
| 1663 |
n if n >= 8 => quote! { u64 }, |
| 1664 |
4 => quote! { u32 }, |
| 1665 |
2 => quote! { u16 }, |
| 1666 |
_ => quote! { u8 }, |
| 1667 |
}; |
| 1668 |
let access_spec = access_specifier(visibility_kind); |
| 1669 |
let align_field = quote! { |
| 1670 |
#access_spec #align_field_ident: [#align_ty; 0], |
| 1671 |
}; |
| 1672 |
fields.extend(Some(align_field)); |
| 1673 |
} |
| 1674 |
|
| 1675 |
let unit_field_name = format!("_bitfield_{}", self.nth()); |
| 1676 |
let unit_field_ident = ctx.rust_ident(&unit_field_name); |
| 1677 |
|
| 1678 |
let ctor_name = self.ctor_name(); |
| 1679 |
let mut ctor_params = vec![]; |
| 1680 |
let mut ctor_impl = quote! {}; |
| 1681 |
|
| 1682 |
// We cannot generate any constructor if the underlying storage can't |
| 1683 |
// implement AsRef<[u8]> / AsMut<[u8]> / etc, or can't derive Default. |
| 1684 |
// |
| 1685 |
// We don't check `larger_arrays` here because Default does still have |
| 1686 |
// the 32 items limitation. |
| 1687 |
let mut generate_ctor = layout.size <= RUST_DERIVE_IN_ARRAY_LIMIT; |
| 1688 |
|
| 1689 |
let mut all_fields_declared_as_public = true; |
| 1690 |
for bf in self.bitfields() { |
| 1691 |
// Codegen not allowed for anonymous bitfields |
| 1692 |
if bf.name().is_none() { |
| 1693 |
continue; |
| 1694 |
} |
| 1695 |
|
| 1696 |
if layout.size > RUST_DERIVE_IN_ARRAY_LIMIT && |
| 1697 |
!ctx.options().rust_features().larger_arrays |
| 1698 |
{ |
| 1699 |
continue; |
| 1700 |
} |
| 1701 |
|
| 1702 |
all_fields_declared_as_public &= bf.is_public(); |
| 1703 |
let mut bitfield_representable_as_int = true; |
| 1704 |
bf.codegen( |
| 1705 |
ctx, |
| 1706 |
visibility_kind, |
| 1707 |
accessor_kind, |
| 1708 |
parent, |
| 1709 |
result, |
| 1710 |
struct_layout, |
| 1711 |
fields, |
| 1712 |
methods, |
| 1713 |
(&unit_field_name, &mut bitfield_representable_as_int), |
| 1714 |
); |
| 1715 |
|
| 1716 |
// Generating a constructor requires the bitfield to be representable as an integer. |
| 1717 |
if !bitfield_representable_as_int { |
| 1718 |
generate_ctor = false; |
| 1719 |
continue; |
| 1720 |
} |
| 1721 |
|
| 1722 |
let param_name = bitfield_getter_name(ctx, bf); |
| 1723 |
let bitfield_ty_item = ctx.resolve_item(bf.ty()); |
| 1724 |
let bitfield_ty = bitfield_ty_item.expect_type(); |
| 1725 |
let bitfield_ty = |
| 1726 |
bitfield_ty.to_rust_ty_or_opaque(ctx, bitfield_ty_item); |
| 1727 |
|
| 1728 |
ctor_params.push(quote! { |
| 1729 |
#param_name : #bitfield_ty |
| 1730 |
}); |
| 1731 |
ctor_impl = bf.extend_ctor_impl(ctx, param_name, ctor_impl); |
| 1732 |
} |
| 1733 |
|
| 1734 |
let visibility_kind = compute_visibility( |
| 1735 |
ctx, |
| 1736 |
all_fields_declared_as_public, |
| 1737 |
None, |
| 1738 |
visibility_kind, |
| 1739 |
); |
| 1740 |
let access_spec = access_specifier(visibility_kind); |
| 1741 |
|
| 1742 |
let field = quote! { |
| 1743 |
#access_spec #unit_field_ident : #field_ty , |
| 1744 |
}; |
| 1745 |
fields.extend(Some(field)); |
| 1746 |
|
| 1747 |
if generate_ctor { |
| 1748 |
methods.extend(Some(quote! { |
| 1749 |
#[inline] |
| 1750 |
#access_spec fn #ctor_name ( #( #ctor_params ),* ) -> #unit_field_ty { |
| 1751 |
let mut __bindgen_bitfield_unit: #unit_field_ty = Default::default(); |
| 1752 |
#ctor_impl |
| 1753 |
__bindgen_bitfield_unit |
| 1754 |
} |
| 1755 |
})); |
| 1756 |
} |
| 1757 |
|
| 1758 |
struct_layout.saw_bitfield_unit(layout); |
| 1759 |
} |
| 1760 |
} |
| 1761 |
|
| 1762 |
fn bitfield_getter_name( |
| 1763 |
ctx: &BindgenContext, |
| 1764 |
bitfield: &Bitfield, |
| 1765 |
) -> proc_macro2::TokenStream { |
| 1766 |
let name = bitfield.getter_name(); |
| 1767 |
let name = ctx.rust_ident_raw(name); |
| 1768 |
quote! { #name } |
| 1769 |
} |
| 1770 |
|
| 1771 |
fn bitfield_setter_name( |
| 1772 |
ctx: &BindgenContext, |
| 1773 |
bitfield: &Bitfield, |
| 1774 |
) -> proc_macro2::TokenStream { |
| 1775 |
let setter = bitfield.setter_name(); |
| 1776 |
let setter = ctx.rust_ident_raw(setter); |
| 1777 |
quote! { #setter } |
| 1778 |
} |
| 1779 |
|
| 1780 |
impl<'a> FieldCodegen<'a> for Bitfield { |
| 1781 |
type Extra = (&'a str, &'a mut bool); |
| 1782 |
|
| 1783 |
fn codegen<F, M>( |
| 1784 |
&self, |
| 1785 |
ctx: &BindgenContext, |
| 1786 |
visibility_kind: FieldVisibilityKind, |
| 1787 |
_accessor_kind: FieldAccessorKind, |
| 1788 |
parent: &CompInfo, |
| 1789 |
_result: &mut CodegenResult, |
| 1790 |
struct_layout: &mut StructLayoutTracker, |
| 1791 |
_fields: &mut F, |
| 1792 |
methods: &mut M, |
| 1793 |
(unit_field_name, bitfield_representable_as_int): (&'a str, &mut bool), |
| 1794 |
) where |
| 1795 |
F: Extend<proc_macro2::TokenStream>, |
| 1796 |
M: Extend<proc_macro2::TokenStream>, |
| 1797 |
{ |
| 1798 |
let prefix = ctx.trait_prefix(); |
| 1799 |
let getter_name = bitfield_getter_name(ctx, self); |
| 1800 |
let setter_name = bitfield_setter_name(ctx, self); |
| 1801 |
let unit_field_ident = Ident::new(unit_field_name, Span::call_site()); |
| 1802 |
|
| 1803 |
let bitfield_ty_item = ctx.resolve_item(self.ty()); |
| 1804 |
let bitfield_ty = bitfield_ty_item.expect_type(); |
| 1805 |
|
| 1806 |
let bitfield_ty_layout = bitfield_ty |
| 1807 |
.layout(ctx) |
| 1808 |
.expect("Bitfield without layout? Gah!"); |
| 1809 |
let bitfield_int_ty = |
| 1810 |
match helpers::integer_type(ctx, bitfield_ty_layout) { |
| 1811 |
Some(int_ty) => { |
| 1812 |
*bitfield_representable_as_int = true; |
| 1813 |
int_ty |
| 1814 |
} |
| 1815 |
None => { |
| 1816 |
*bitfield_representable_as_int = false; |
| 1817 |
return; |
| 1818 |
} |
| 1819 |
}; |
| 1820 |
|
| 1821 |
let bitfield_ty = |
| 1822 |
bitfield_ty.to_rust_ty_or_opaque(ctx, bitfield_ty_item); |
| 1823 |
|
| 1824 |
let offset = self.offset_into_unit(); |
| 1825 |
let width = self.width() as u8; |
| 1826 |
|
| 1827 |
let visibility_kind = compute_visibility( |
| 1828 |
ctx, |
| 1829 |
self.is_public(), |
| 1830 |
Some(self.annotations()), |
| 1831 |
visibility_kind, |
| 1832 |
); |
| 1833 |
let access_spec = access_specifier(visibility_kind); |
| 1834 |
|
| 1835 |
if parent.is_union() && !struct_layout.is_rust_union() { |
| 1836 |
methods.extend(Some(quote! { |
| 1837 |
#[inline] |
| 1838 |
#access_spec fn #getter_name(&self) -> #bitfield_ty { |
| 1839 |
unsafe { |
| 1840 |
::#prefix::mem::transmute( |
| 1841 |
self.#unit_field_ident.as_ref().get(#offset, #width) |
| 1842 |
as #bitfield_int_ty |
| 1843 |
) |
| 1844 |
} |
| 1845 |
} |
| 1846 |
|
| 1847 |
#[inline] |
| 1848 |
#access_spec fn #setter_name(&mut self, val: #bitfield_ty) { |
| 1849 |
unsafe { |
| 1850 |
let val: #bitfield_int_ty = ::#prefix::mem::transmute(val); |
| 1851 |
self.#unit_field_ident.as_mut().set( |
| 1852 |
#offset, |
| 1853 |
#width, |
| 1854 |
val as u64 |
| 1855 |
) |
| 1856 |
} |
| 1857 |
} |
| 1858 |
})); |
| 1859 |
} else { |
| 1860 |
methods.extend(Some(quote! { |
| 1861 |
#[inline] |
| 1862 |
#access_spec fn #getter_name(&self) -> #bitfield_ty { |
| 1863 |
unsafe { |
| 1864 |
::#prefix::mem::transmute( |
| 1865 |
self.#unit_field_ident.get(#offset, #width) |
| 1866 |
as #bitfield_int_ty |
| 1867 |
) |
| 1868 |
} |
| 1869 |
} |
| 1870 |
|
| 1871 |
#[inline] |
| 1872 |
#access_spec fn #setter_name(&mut self, val: #bitfield_ty) { |
| 1873 |
unsafe { |
| 1874 |
let val: #bitfield_int_ty = ::#prefix::mem::transmute(val); |
| 1875 |
self.#unit_field_ident.set( |
| 1876 |
#offset, |
| 1877 |
#width, |
| 1878 |
val as u64 |
| 1879 |
) |
| 1880 |
} |
| 1881 |
} |
| 1882 |
})); |
| 1883 |
} |
| 1884 |
} |
| 1885 |
} |
| 1886 |
|
| 1887 |
impl CodeGenerator for CompInfo { |
| 1888 |
type Extra = Item; |
| 1889 |
type Return = (); |
| 1890 |
|
| 1891 |
fn codegen( |
| 1892 |
&self, |
| 1893 |
ctx: &BindgenContext, |
| 1894 |
result: &mut CodegenResult<'_>, |
| 1895 |
item: &Item, |
| 1896 |
) { |
| 1897 |
debug!("<CompInfo as CodeGenerator>::codegen: item = {:?}", item); |
| 1898 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 1899 |
|
| 1900 |
// Don't output classes with template parameters that aren't types, and |
| 1901 |
// also don't output template specializations, neither total or partial. |
| 1902 |
if self.has_non_type_template_params() { |
| 1903 |
return; |
| 1904 |
} |
| 1905 |
|
| 1906 |
let ty = item.expect_type(); |
| 1907 |
let layout = ty.layout(ctx); |
| 1908 |
let mut packed = self.is_packed(ctx, layout.as_ref()); |
| 1909 |
|
| 1910 |
let canonical_name = item.canonical_name(ctx); |
| 1911 |
let canonical_ident = ctx.rust_ident(&canonical_name); |
| 1912 |
|
| 1913 |
// Generate the vtable from the method list if appropriate. |
| 1914 |
// |
| 1915 |
// TODO: I don't know how this could play with virtual methods that are |
| 1916 |
// not in the list of methods found by us, we'll see. Also, could the |
| 1917 |
// order of the vtable pointers vary? |
| 1918 |
// |
| 1919 |
// FIXME: Once we generate proper vtables, we need to codegen the |
| 1920 |
// vtable, but *not* generate a field for it in the case that |
| 1921 |
// HasVtable::has_vtable_ptr is false but HasVtable::has_vtable is true. |
| 1922 |
// |
| 1923 |
// Also, we need to generate the vtable in such a way it "inherits" from |
| 1924 |
// the parent too. |
| 1925 |
let is_opaque = item.is_opaque(ctx, &()); |
| 1926 |
let mut fields = vec![]; |
| 1927 |
let mut struct_layout = |
| 1928 |
StructLayoutTracker::new(ctx, self, ty, &canonical_name); |
| 1929 |
|
| 1930 |
if !is_opaque { |
| 1931 |
if item.has_vtable_ptr(ctx) { |
| 1932 |
let vtable = Vtable::new(item.id(), self); |
| 1933 |
vtable.codegen(ctx, result, item); |
| 1934 |
|
| 1935 |
let vtable_type = vtable |
| 1936 |
.try_to_rust_ty(ctx, &()) |
| 1937 |
.expect("vtable to Rust type conversion is infallible") |
| 1938 |
.to_ptr(true); |
| 1939 |
|
| 1940 |
fields.push(quote! { |
| 1941 |
pub vtable_: #vtable_type , |
| 1942 |
}); |
| 1943 |
|
| 1944 |
struct_layout.saw_vtable(); |
| 1945 |
} |
| 1946 |
|
| 1947 |
for base in self.base_members() { |
| 1948 |
if !base.requires_storage(ctx) { |
| 1949 |
continue; |
| 1950 |
} |
| 1951 |
|
| 1952 |
let inner_item = ctx.resolve_item(base.ty); |
| 1953 |
let mut inner = inner_item.to_rust_ty_or_opaque(ctx, &()); |
| 1954 |
inner.append_implicit_template_params(ctx, inner_item); |
| 1955 |
let field_name = ctx.rust_ident(&base.field_name); |
| 1956 |
|
| 1957 |
struct_layout.saw_base(inner_item.expect_type()); |
| 1958 |
|
| 1959 |
let visibility = match ( |
| 1960 |
base.is_public(), |
| 1961 |
ctx.options().respect_cxx_access_specs, |
| 1962 |
) { |
| 1963 |
(true, true) => FieldVisibilityKind::Public, |
| 1964 |
(false, true) => FieldVisibilityKind::Private, |
| 1965 |
_ => ctx.options().default_visibility, |
| 1966 |
}; |
| 1967 |
|
| 1968 |
let access_spec = access_specifier(visibility); |
| 1969 |
fields.push(quote! { |
| 1970 |
#access_spec #field_name: #inner, |
| 1971 |
}); |
| 1972 |
} |
| 1973 |
} |
| 1974 |
|
| 1975 |
let mut methods = vec![]; |
| 1976 |
if !is_opaque { |
| 1977 |
let visibility = item |
| 1978 |
.annotations() |
| 1979 |
.visibility_kind() |
| 1980 |
.unwrap_or(ctx.options().default_visibility); |
| 1981 |
let struct_accessor_kind = item |
| 1982 |
.annotations() |
| 1983 |
.accessor_kind() |
| 1984 |
.unwrap_or(FieldAccessorKind::None); |
| 1985 |
for field in self.fields() { |
| 1986 |
field.codegen( |
| 1987 |
ctx, |
| 1988 |
visibility, |
| 1989 |
struct_accessor_kind, |
| 1990 |
self, |
| 1991 |
result, |
| 1992 |
&mut struct_layout, |
| 1993 |
&mut fields, |
| 1994 |
&mut methods, |
| 1995 |
(), |
| 1996 |
); |
| 1997 |
} |
| 1998 |
// Check whether an explicit padding field is needed |
| 1999 |
// at the end. |
| 2000 |
if let Some(comp_layout) = layout { |
| 2001 |
fields.extend( |
| 2002 |
struct_layout |
| 2003 |
.add_tail_padding(&canonical_name, comp_layout), |
| 2004 |
); |
| 2005 |
} |
| 2006 |
} |
| 2007 |
|
| 2008 |
if is_opaque { |
| 2009 |
// Opaque item should not have generated methods, fields. |
| 2010 |
debug_assert!(fields.is_empty()); |
| 2011 |
debug_assert!(methods.is_empty()); |
| 2012 |
} |
| 2013 |
|
| 2014 |
let is_union = self.kind() == CompKind::Union; |
| 2015 |
let layout = item.kind().expect_type().layout(ctx); |
| 2016 |
let zero_sized = item.is_zero_sized(ctx); |
| 2017 |
let forward_decl = self.is_forward_declaration(); |
| 2018 |
|
| 2019 |
let mut explicit_align = None; |
| 2020 |
|
| 2021 |
// C++ requires every struct to be addressable, so what C++ compilers do |
| 2022 |
// is making the struct 1-byte sized. |
| 2023 |
// |
| 2024 |
// This is apparently not the case for C, see: |
| 2025 |
// https://github.com/rust-lang/rust-bindgen/issues/551 |
| 2026 |
// |
| 2027 |
// Just get the layout, and assume C++ if not. |
| 2028 |
// |
| 2029 |
// NOTE: This check is conveniently here to avoid the dummy fields we |
| 2030 |
// may add for unused template parameters. |
| 2031 |
if !forward_decl && zero_sized { |
| 2032 |
let has_address = if is_opaque { |
| 2033 |
// Generate the address field if it's an opaque type and |
| 2034 |
// couldn't determine the layout of the blob. |
| 2035 |
layout.is_none() |
| 2036 |
} else { |
| 2037 |
layout.map_or(true, |l| l.size != 0) |
| 2038 |
}; |
| 2039 |
|
| 2040 |
if has_address { |
| 2041 |
let layout = Layout::new(1, 1); |
| 2042 |
let ty = helpers::blob(ctx, Layout::new(1, 1)); |
| 2043 |
struct_layout.saw_field_with_layout( |
| 2044 |
"_address", |
| 2045 |
layout, |
| 2046 |
/* offset = */ Some(0), |
| 2047 |
); |
| 2048 |
fields.push(quote! { |
| 2049 |
pub _address: #ty, |
| 2050 |
}); |
| 2051 |
} |
| 2052 |
} |
| 2053 |
|
| 2054 |
if is_opaque { |
| 2055 |
match layout { |
| 2056 |
Some(l) => { |
| 2057 |
explicit_align = Some(l.align); |
| 2058 |
|
| 2059 |
let ty = helpers::blob(ctx, l); |
| 2060 |
fields.push(quote! { |
| 2061 |
pub _bindgen_opaque_blob: #ty , |
| 2062 |
}); |
| 2063 |
} |
| 2064 |
None => { |
| 2065 |
warn!("Opaque type without layout! Expect dragons!"); |
| 2066 |
} |
| 2067 |
} |
| 2068 |
} else if !is_union && !zero_sized { |
| 2069 |
if let Some(padding_field) = |
| 2070 |
layout.and_then(|layout| struct_layout.pad_struct(layout)) |
| 2071 |
{ |
| 2072 |
fields.push(padding_field); |
| 2073 |
} |
| 2074 |
|
| 2075 |
if let Some(layout) = layout { |
| 2076 |
if struct_layout.requires_explicit_align(layout) { |
| 2077 |
if layout.align == 1 { |
| 2078 |
packed = true; |
| 2079 |
} else { |
| 2080 |
explicit_align = Some(layout.align); |
| 2081 |
if !ctx.options().rust_features.repr_align { |
| 2082 |
let ty = helpers::blob( |
| 2083 |
ctx, |
| 2084 |
Layout::new(0, layout.align), |
| 2085 |
); |
| 2086 |
fields.push(quote! { |
| 2087 |
pub __bindgen_align: #ty , |
| 2088 |
}); |
| 2089 |
} |
| 2090 |
} |
| 2091 |
} |
| 2092 |
} |
| 2093 |
} else if is_union && !forward_decl { |
| 2094 |
// TODO(emilio): It'd be nice to unify this with the struct path |
| 2095 |
// above somehow. |
| 2096 |
let layout = layout.expect("Unable to get layout information?"); |
| 2097 |
if struct_layout.requires_explicit_align(layout) { |
| 2098 |
explicit_align = Some(layout.align); |
| 2099 |
} |
| 2100 |
|
| 2101 |
if !struct_layout.is_rust_union() { |
| 2102 |
let ty = helpers::blob(ctx, layout); |
| 2103 |
fields.push(quote! { |
| 2104 |
pub bindgen_union_field: #ty , |
| 2105 |
}) |
| 2106 |
} |
| 2107 |
} |
| 2108 |
|
| 2109 |
if forward_decl { |
| 2110 |
fields.push(quote! { |
| 2111 |
_unused: [u8; 0], |
| 2112 |
}); |
| 2113 |
} |
| 2114 |
|
| 2115 |
let mut generic_param_names = vec![]; |
| 2116 |
|
| 2117 |
for (idx, ty) in item.used_template_params(ctx).iter().enumerate() { |
| 2118 |
let param = ctx.resolve_type(*ty); |
| 2119 |
let name = param.name().unwrap(); |
| 2120 |
let ident = ctx.rust_ident(name); |
| 2121 |
generic_param_names.push(ident.clone()); |
| 2122 |
|
| 2123 |
let prefix = ctx.trait_prefix(); |
| 2124 |
let field_name = ctx.rust_ident(format!("_phantom_{}", idx)); |
| 2125 |
fields.push(quote! { |
| 2126 |
pub #field_name : ::#prefix::marker::PhantomData< |
| 2127 |
::#prefix::cell::UnsafeCell<#ident> |
| 2128 |
> , |
| 2129 |
}); |
| 2130 |
} |
| 2131 |
|
| 2132 |
let generics = if !generic_param_names.is_empty() { |
| 2133 |
let generic_param_names = generic_param_names.clone(); |
| 2134 |
quote! { |
| 2135 |
< #( #generic_param_names ),* > |
| 2136 |
} |
| 2137 |
} else { |
| 2138 |
quote! {} |
| 2139 |
}; |
| 2140 |
|
| 2141 |
let mut attributes = vec![]; |
| 2142 |
let mut needs_clone_impl = false; |
| 2143 |
let mut needs_default_impl = false; |
| 2144 |
let mut needs_debug_impl = false; |
| 2145 |
let mut needs_partialeq_impl = false; |
| 2146 |
if let Some(comment) = item.comment(ctx) { |
| 2147 |
attributes.push(attributes::doc(comment)); |
| 2148 |
} |
| 2149 |
if packed && !is_opaque { |
| 2150 |
let n = layout.map_or(1, |l| l.align); |
| 2151 |
assert!(ctx.options().rust_features().repr_packed_n || n == 1); |
| 2152 |
let packed_repr = if n == 1 { |
| 2153 |
"packed".to_string() |
| 2154 |
} else { |
| 2155 |
format!("packed({})", n) |
| 2156 |
}; |
| 2157 |
attributes.push(attributes::repr_list(&["C", &packed_repr])); |
| 2158 |
} else { |
| 2159 |
attributes.push(attributes::repr("C")); |
| 2160 |
} |
| 2161 |
|
| 2162 |
if ctx.options().rust_features().repr_align { |
| 2163 |
if let Some(explicit) = explicit_align { |
| 2164 |
// Ensure that the struct has the correct alignment even in |
| 2165 |
// presence of alignas. |
| 2166 |
let explicit = helpers::ast_ty::int_expr(explicit as i64); |
| 2167 |
attributes.push(quote! { |
| 2168 |
#[repr(align(#explicit))] |
| 2169 |
}); |
| 2170 |
} |
| 2171 |
} |
| 2172 |
|
| 2173 |
let derivable_traits = derives_of_item(item, ctx, packed); |
| 2174 |
if !derivable_traits.contains(DerivableTraits::DEBUG) { |
| 2175 |
needs_debug_impl = ctx.options().derive_debug && |
| 2176 |
ctx.options().impl_debug && |
| 2177 |
!ctx.no_debug_by_name(item) && |
| 2178 |
!item.annotations().disallow_debug(); |
| 2179 |
} |
| 2180 |
|
| 2181 |
if !derivable_traits.contains(DerivableTraits::DEFAULT) { |
| 2182 |
needs_default_impl = ctx.options().derive_default && |
| 2183 |
!self.is_forward_declaration() && |
| 2184 |
!ctx.no_default_by_name(item) && |
| 2185 |
!item.annotations().disallow_default(); |
| 2186 |
} |
| 2187 |
|
| 2188 |
let all_template_params = item.all_template_params(ctx); |
| 2189 |
|
| 2190 |
if derivable_traits.contains(DerivableTraits::COPY) && |
| 2191 |
!derivable_traits.contains(DerivableTraits::CLONE) |
| 2192 |
{ |
| 2193 |
needs_clone_impl = true; |
| 2194 |
} |
| 2195 |
|
| 2196 |
if !derivable_traits.contains(DerivableTraits::PARTIAL_EQ) { |
| 2197 |
needs_partialeq_impl = ctx.options().derive_partialeq && |
| 2198 |
ctx.options().impl_partialeq && |
| 2199 |
ctx.lookup_can_derive_partialeq_or_partialord(item.id()) == |
| 2200 |
CanDerive::Manually; |
| 2201 |
} |
| 2202 |
|
| 2203 |
let mut derives: Vec<_> = derivable_traits.into(); |
| 2204 |
derives.extend(item.annotations().derives().iter().map(String::as_str)); |
| 2205 |
|
| 2206 |
let is_rust_union = is_union && struct_layout.is_rust_union(); |
| 2207 |
|
| 2208 |
// The custom derives callback may return a list of derive attributes; |
| 2209 |
// add them to the end of the list. |
| 2210 |
let custom_derives = ctx.options().all_callbacks(|cb| { |
| 2211 |
cb.add_derives(&DeriveInfo { |
| 2212 |
name: &canonical_name, |
| 2213 |
kind: if is_rust_union { |
| 2214 |
DeriveTypeKind::Union |
| 2215 |
} else { |
| 2216 |
DeriveTypeKind::Struct |
| 2217 |
}, |
| 2218 |
}) |
| 2219 |
}); |
| 2220 |
// In most cases this will be a no-op, since custom_derives will be empty. |
| 2221 |
derives.extend(custom_derives.iter().map(|s| s.as_str())); |
| 2222 |
|
| 2223 |
if !derives.is_empty() { |
| 2224 |
attributes.push(attributes::derives(&derives)) |
| 2225 |
} |
| 2226 |
|
| 2227 |
if item.must_use(ctx) { |
| 2228 |
attributes.push(attributes::must_use()); |
| 2229 |
} |
| 2230 |
|
| 2231 |
let mut tokens = if is_rust_union { |
| 2232 |
quote! { |
| 2233 |
#( #attributes )* |
| 2234 |
pub union #canonical_ident |
| 2235 |
} |
| 2236 |
} else { |
| 2237 |
quote! { |
| 2238 |
#( #attributes )* |
| 2239 |
pub struct #canonical_ident |
| 2240 |
} |
| 2241 |
}; |
| 2242 |
|
| 2243 |
tokens.append_all(quote! { |
| 2244 |
#generics { |
| 2245 |
#( #fields )* |
| 2246 |
} |
| 2247 |
}); |
| 2248 |
result.push(tokens); |
| 2249 |
|
| 2250 |
// Generate the inner types and all that stuff. |
| 2251 |
// |
| 2252 |
// TODO: In the future we might want to be smart, and use nested |
| 2253 |
// modules, and whatnot. |
| 2254 |
for ty in self.inner_types() { |
| 2255 |
let child_item = ctx.resolve_item(*ty); |
| 2256 |
// assert_eq!(child_item.parent_id(), item.id()); |
| 2257 |
child_item.codegen(ctx, result, &()); |
| 2258 |
} |
| 2259 |
|
| 2260 |
// NOTE: Some unexposed attributes (like alignment attributes) may |
| 2261 |
// affect layout, so we're bad and pray to the gods for avoid sending |
| 2262 |
// all the tests to shit when parsing things like max_align_t. |
| 2263 |
if self.found_unknown_attr() { |
| 2264 |
warn!( |
| 2265 |
"Type {} has an unknown attribute that may affect layout", |
| 2266 |
canonical_ident |
| 2267 |
); |
| 2268 |
} |
| 2269 |
|
| 2270 |
if all_template_params.is_empty() { |
| 2271 |
if !is_opaque { |
| 2272 |
for var in self.inner_vars() { |
| 2273 |
ctx.resolve_item(*var).codegen(ctx, result, &()); |
| 2274 |
} |
| 2275 |
} |
| 2276 |
|
| 2277 |
if ctx.options().layout_tests && !self.is_forward_declaration() { |
| 2278 |
if let Some(layout) = layout { |
| 2279 |
let fn_name = |
| 2280 |
format!("bindgen_test_layout_{}", canonical_ident); |
| 2281 |
let fn_name = ctx.rust_ident_raw(fn_name); |
| 2282 |
let prefix = ctx.trait_prefix(); |
| 2283 |
let size_of_expr = quote! { |
| 2284 |
::#prefix::mem::size_of::<#canonical_ident>() |
| 2285 |
}; |
| 2286 |
let align_of_expr = quote! { |
| 2287 |
::#prefix::mem::align_of::<#canonical_ident>() |
| 2288 |
}; |
| 2289 |
let size = layout.size; |
| 2290 |
let align = layout.align; |
| 2291 |
|
| 2292 |
let check_struct_align = if align > |
| 2293 |
ctx.target_pointer_size() && |
| 2294 |
!ctx.options().rust_features().repr_align |
| 2295 |
{ |
| 2296 |
None |
| 2297 |
} else { |
| 2298 |
Some(quote! { |
| 2299 |
assert_eq!(#align_of_expr, |
| 2300 |
#align, |
| 2301 |
concat!("Alignment of ", stringify!(#canonical_ident))); |
| 2302 |
|
| 2303 |
}) |
| 2304 |
}; |
| 2305 |
|
| 2306 |
let should_skip_field_offset_checks = is_opaque; |
| 2307 |
|
| 2308 |
let check_field_offset = if should_skip_field_offset_checks |
| 2309 |
{ |
| 2310 |
vec![] |
| 2311 |
} else { |
| 2312 |
self.fields() |
| 2313 |
.iter() |
| 2314 |
.filter_map(|field| match *field { |
| 2315 |
Field::DataMember(ref f) if f.name().is_some() => Some(f), |
| 2316 |
_ => None, |
| 2317 |
}) |
| 2318 |
.flat_map(|field| { |
| 2319 |
let name = field.name().unwrap(); |
| 2320 |
field.offset().map(|offset| { |
| 2321 |
let field_offset = offset / 8; |
| 2322 |
let field_name = ctx.rust_ident(name); |
| 2323 |
quote! { |
| 2324 |
assert_eq!( |
| 2325 |
unsafe { |
| 2326 |
::#prefix::ptr::addr_of!((*ptr).#field_name) as usize - ptr as usize |
| 2327 |
}, |
| 2328 |
#field_offset, |
| 2329 |
concat!("Offset of field: ", stringify!(#canonical_ident), "::", stringify!(#field_name)) |
| 2330 |
); |
| 2331 |
} |
| 2332 |
}) |
| 2333 |
}) |
| 2334 |
.collect() |
| 2335 |
}; |
| 2336 |
|
| 2337 |
let uninit_decl = if !check_field_offset.is_empty() { |
| 2338 |
// FIXME: When MSRV >= 1.59.0, we can use |
| 2339 |
// > const PTR: *const #canonical_ident = ::#prefix::mem::MaybeUninit::uninit().as_ptr(); |
| 2340 |
Some(quote! { |
| 2341 |
// Use a shared MaybeUninit so that rustc with |
| 2342 |
// opt-level=0 doesn't take too much stack space, |
| 2343 |
// see #2218. |
| 2344 |
const UNINIT: ::#prefix::mem::MaybeUninit<#canonical_ident> = ::#prefix::mem::MaybeUninit::uninit(); |
| 2345 |
let ptr = UNINIT.as_ptr(); |
| 2346 |
}) |
| 2347 |
} else { |
| 2348 |
None |
| 2349 |
}; |
| 2350 |
|
| 2351 |
let item = quote! { |
| 2352 |
#[test] |
| 2353 |
fn #fn_name() { |
| 2354 |
#uninit_decl |
| 2355 |
assert_eq!(#size_of_expr, |
| 2356 |
#size, |
| 2357 |
concat!("Size of: ", stringify!(#canonical_ident))); |
| 2358 |
#check_struct_align |
| 2359 |
#( #check_field_offset )* |
| 2360 |
} |
| 2361 |
}; |
| 2362 |
result.push(item); |
| 2363 |
} |
| 2364 |
} |
| 2365 |
|
| 2366 |
let mut method_names = Default::default(); |
| 2367 |
if ctx.options().codegen_config.methods() { |
| 2368 |
for method in self.methods() { |
| 2369 |
assert!(method.kind() != MethodKind::Constructor); |
| 2370 |
method.codegen_method( |
| 2371 |
ctx, |
| 2372 |
&mut methods, |
| 2373 |
&mut method_names, |
| 2374 |
result, |
| 2375 |
self, |
| 2376 |
); |
| 2377 |
} |
| 2378 |
} |
| 2379 |
|
| 2380 |
if ctx.options().codegen_config.constructors() { |
| 2381 |
for sig in self.constructors() { |
| 2382 |
Method::new( |
| 2383 |
MethodKind::Constructor, |
| 2384 |
*sig, |
| 2385 |
/* const */ |
| 2386 |
false, |
| 2387 |
) |
| 2388 |
.codegen_method( |
| 2389 |
ctx, |
| 2390 |
&mut methods, |
| 2391 |
&mut method_names, |
| 2392 |
result, |
| 2393 |
self, |
| 2394 |
); |
| 2395 |
} |
| 2396 |
} |
| 2397 |
|
| 2398 |
if ctx.options().codegen_config.destructors() { |
| 2399 |
if let Some((kind, destructor)) = self.destructor() { |
| 2400 |
debug_assert!(kind.is_destructor()); |
| 2401 |
Method::new(kind, destructor, false).codegen_method( |
| 2402 |
ctx, |
| 2403 |
&mut methods, |
| 2404 |
&mut method_names, |
| 2405 |
result, |
| 2406 |
self, |
| 2407 |
); |
| 2408 |
} |
| 2409 |
} |
| 2410 |
} |
| 2411 |
|
| 2412 |
// NB: We can't use to_rust_ty here since for opaque types this tries to |
| 2413 |
// use the specialization knowledge to generate a blob field. |
| 2414 |
let ty_for_impl = quote! { |
| 2415 |
#canonical_ident #generics |
| 2416 |
}; |
| 2417 |
|
| 2418 |
if needs_clone_impl { |
| 2419 |
result.push(quote! { |
| 2420 |
impl #generics Clone for #ty_for_impl { |
| 2421 |
fn clone(&self) -> Self { *self } |
| 2422 |
} |
| 2423 |
}); |
| 2424 |
} |
| 2425 |
|
| 2426 |
if needs_default_impl { |
| 2427 |
let prefix = ctx.trait_prefix(); |
| 2428 |
let body = if ctx.options().rust_features().maybe_uninit { |
| 2429 |
quote! { |
| 2430 |
let mut s = ::#prefix::mem::MaybeUninit::<Self>::uninit(); |
| 2431 |
unsafe { |
| 2432 |
::#prefix::ptr::write_bytes(s.as_mut_ptr(), 0, 1); |
| 2433 |
s.assume_init() |
| 2434 |
} |
| 2435 |
} |
| 2436 |
} else { |
| 2437 |
quote! { |
| 2438 |
unsafe { |
| 2439 |
let mut s: Self = ::#prefix::mem::uninitialized(); |
| 2440 |
::#prefix::ptr::write_bytes(&mut s, 0, 1); |
| 2441 |
s |
| 2442 |
} |
| 2443 |
} |
| 2444 |
}; |
| 2445 |
// Note we use `ptr::write_bytes()` instead of `mem::zeroed()` because the latter does |
| 2446 |
// not necessarily ensure padding bytes are zeroed. Some C libraries are sensitive to |
| 2447 |
// non-zero padding bytes, especially when forwards/backwards compatability is |
| 2448 |
// involved. |
| 2449 |
result.push(quote! { |
| 2450 |
impl #generics Default for #ty_for_impl { |
| 2451 |
fn default() -> Self { |
| 2452 |
#body |
| 2453 |
} |
| 2454 |
} |
| 2455 |
}); |
| 2456 |
} |
| 2457 |
|
| 2458 |
if needs_debug_impl { |
| 2459 |
let impl_ = impl_debug::gen_debug_impl( |
| 2460 |
ctx, |
| 2461 |
self.fields(), |
| 2462 |
item, |
| 2463 |
self.kind(), |
| 2464 |
); |
| 2465 |
|
| 2466 |
let prefix = ctx.trait_prefix(); |
| 2467 |
|
| 2468 |
result.push(quote! { |
| 2469 |
impl #generics ::#prefix::fmt::Debug for #ty_for_impl { |
| 2470 |
#impl_ |
| 2471 |
} |
| 2472 |
}); |
| 2473 |
} |
| 2474 |
|
| 2475 |
if needs_partialeq_impl { |
| 2476 |
if let Some(impl_) = impl_partialeq::gen_partialeq_impl( |
| 2477 |
ctx, |
| 2478 |
self, |
| 2479 |
item, |
| 2480 |
&ty_for_impl, |
| 2481 |
) { |
| 2482 |
let partialeq_bounds = if !generic_param_names.is_empty() { |
| 2483 |
let bounds = generic_param_names.iter().map(|t| { |
| 2484 |
quote! { #t: PartialEq } |
| 2485 |
}); |
| 2486 |
quote! { where #( #bounds ),* } |
| 2487 |
} else { |
| 2488 |
quote! {} |
| 2489 |
}; |
| 2490 |
|
| 2491 |
let prefix = ctx.trait_prefix(); |
| 2492 |
result.push(quote! { |
| 2493 |
impl #generics ::#prefix::cmp::PartialEq for #ty_for_impl #partialeq_bounds { |
| 2494 |
#impl_ |
| 2495 |
} |
| 2496 |
}); |
| 2497 |
} |
| 2498 |
} |
| 2499 |
|
| 2500 |
if !methods.is_empty() { |
| 2501 |
result.push(quote! { |
| 2502 |
impl #generics #ty_for_impl { |
| 2503 |
#( #methods )* |
| 2504 |
} |
| 2505 |
}); |
| 2506 |
} |
| 2507 |
} |
| 2508 |
} |
| 2509 |
|
| 2510 |
impl Method { |
| 2511 |
fn codegen_method( |
| 2512 |
&self, |
| 2513 |
ctx: &BindgenContext, |
| 2514 |
methods: &mut Vec<proc_macro2::TokenStream>, |
| 2515 |
method_names: &mut HashSet<String>, |
| 2516 |
result: &mut CodegenResult<'_>, |
| 2517 |
_parent: &CompInfo, |
| 2518 |
) { |
| 2519 |
assert!({ |
| 2520 |
let cc = &ctx.options().codegen_config; |
| 2521 |
match self.kind() { |
| 2522 |
MethodKind::Constructor => cc.constructors(), |
| 2523 |
MethodKind::Destructor => cc.destructors(), |
| 2524 |
MethodKind::VirtualDestructor { .. } => cc.destructors(), |
| 2525 |
MethodKind::Static | |
| 2526 |
MethodKind::Normal | |
| 2527 |
MethodKind::Virtual { .. } => cc.methods(), |
| 2528 |
} |
| 2529 |
}); |
| 2530 |
|
| 2531 |
// TODO(emilio): We could generate final stuff at least. |
| 2532 |
if self.is_virtual() { |
| 2533 |
return; // FIXME |
| 2534 |
} |
| 2535 |
|
| 2536 |
// First of all, output the actual function. |
| 2537 |
let function_item = ctx.resolve_item(self.signature()); |
| 2538 |
if !function_item.process_before_codegen(ctx, result) { |
| 2539 |
return; |
| 2540 |
} |
| 2541 |
let function = function_item.expect_function(); |
| 2542 |
let times_seen = function.codegen(ctx, result, function_item); |
| 2543 |
let times_seen = match times_seen { |
| 2544 |
Some(seen) => seen, |
| 2545 |
None => return, |
| 2546 |
}; |
| 2547 |
let signature_item = ctx.resolve_item(function.signature()); |
| 2548 |
let mut name = match self.kind() { |
| 2549 |
MethodKind::Constructor => "new".into(), |
| 2550 |
MethodKind::Destructor => "destruct".into(), |
| 2551 |
_ => function.name().to_owned(), |
| 2552 |
}; |
| 2553 |
|
| 2554 |
let signature = match *signature_item.expect_type().kind() { |
| 2555 |
TypeKind::Function(ref sig) => sig, |
| 2556 |
_ => panic!("How in the world?"), |
| 2557 |
}; |
| 2558 |
|
| 2559 |
let supported_abi = match signature.abi(ctx, Some(&*name)) { |
| 2560 |
ClangAbi::Known(Abi::ThisCall) => { |
| 2561 |
ctx.options().rust_features().thiscall_abi |
| 2562 |
} |
| 2563 |
ClangAbi::Known(Abi::Vectorcall) => { |
| 2564 |
ctx.options().rust_features().vectorcall_abi |
| 2565 |
} |
| 2566 |
ClangAbi::Known(Abi::CUnwind) => { |
| 2567 |
ctx.options().rust_features().c_unwind_abi |
| 2568 |
} |
| 2569 |
ClangAbi::Known(Abi::EfiApi) => { |
| 2570 |
ctx.options().rust_features().abi_efiapi |
| 2571 |
} |
| 2572 |
_ => true, |
| 2573 |
}; |
| 2574 |
|
| 2575 |
if !supported_abi { |
| 2576 |
return; |
| 2577 |
} |
| 2578 |
|
| 2579 |
// Do not generate variadic methods, since rust does not allow |
| 2580 |
// implementing them, and we don't do a good job at it anyway. |
| 2581 |
if signature.is_variadic() { |
| 2582 |
return; |
| 2583 |
} |
| 2584 |
|
| 2585 |
if method_names.contains(&name) { |
| 2586 |
let mut count = 1; |
| 2587 |
let mut new_name; |
| 2588 |
|
| 2589 |
while { |
| 2590 |
new_name = format!("{}{}", name, count); |
| 2591 |
method_names.contains(&new_name) |
| 2592 |
} { |
| 2593 |
count += 1; |
| 2594 |
} |
| 2595 |
|
| 2596 |
name = new_name; |
| 2597 |
} |
| 2598 |
|
| 2599 |
method_names.insert(name.clone()); |
| 2600 |
|
| 2601 |
let mut function_name = function_item.canonical_name(ctx); |
| 2602 |
if times_seen > 0 { |
| 2603 |
write!(&mut function_name, "{}", times_seen).unwrap(); |
| 2604 |
} |
| 2605 |
let function_name = ctx.rust_ident(function_name); |
| 2606 |
let mut args = utils::fnsig_arguments(ctx, signature); |
| 2607 |
let mut ret = utils::fnsig_return_ty(ctx, signature); |
| 2608 |
|
| 2609 |
if !self.is_static() && !self.is_constructor() { |
| 2610 |
args[0] = if self.is_const() { |
| 2611 |
quote! { &self } |
| 2612 |
} else { |
| 2613 |
quote! { &mut self } |
| 2614 |
}; |
| 2615 |
} |
| 2616 |
|
| 2617 |
// If it's a constructor, we always return `Self`, and we inject the |
| 2618 |
// "this" parameter, so there's no need to ask the user for it. |
| 2619 |
// |
| 2620 |
// Note that constructors in Clang are represented as functions with |
| 2621 |
// return-type = void. |
| 2622 |
if self.is_constructor() { |
| 2623 |
args.remove(0); |
| 2624 |
ret = quote! { -> Self }; |
| 2625 |
} |
| 2626 |
|
| 2627 |
let mut exprs = |
| 2628 |
helpers::ast_ty::arguments_from_signature(signature, ctx); |
| 2629 |
|
| 2630 |
let mut stmts = vec![]; |
| 2631 |
|
| 2632 |
// If it's a constructor, we need to insert an extra parameter with a |
| 2633 |
// variable called `__bindgen_tmp` we're going to create. |
| 2634 |
if self.is_constructor() { |
| 2635 |
let prefix = ctx.trait_prefix(); |
| 2636 |
let tmp_variable_decl = if ctx |
| 2637 |
.options() |
| 2638 |
.rust_features() |
| 2639 |
.maybe_uninit |
| 2640 |
{ |
| 2641 |
exprs[0] = quote! { |
| 2642 |
__bindgen_tmp.as_mut_ptr() |
| 2643 |
}; |
| 2644 |
quote! { |
| 2645 |
let mut __bindgen_tmp = ::#prefix::mem::MaybeUninit::uninit() |
| 2646 |
} |
| 2647 |
} else { |
| 2648 |
exprs[0] = quote! { |
| 2649 |
&mut __bindgen_tmp |
| 2650 |
}; |
| 2651 |
quote! { |
| 2652 |
let mut __bindgen_tmp = ::#prefix::mem::uninitialized() |
| 2653 |
} |
| 2654 |
}; |
| 2655 |
stmts.push(tmp_variable_decl); |
| 2656 |
} else if !self.is_static() { |
| 2657 |
assert!(!exprs.is_empty()); |
| 2658 |
exprs[0] = quote! { |
| 2659 |
self |
| 2660 |
}; |
| 2661 |
}; |
| 2662 |
|
| 2663 |
let call = quote! { |
| 2664 |
#function_name (#( #exprs ),* ) |
| 2665 |
}; |
| 2666 |
|
| 2667 |
stmts.push(call); |
| 2668 |
|
| 2669 |
if self.is_constructor() { |
| 2670 |
stmts.push(if ctx.options().rust_features().maybe_uninit { |
| 2671 |
quote! { |
| 2672 |
__bindgen_tmp.assume_init() |
| 2673 |
} |
| 2674 |
} else { |
| 2675 |
quote! { |
| 2676 |
__bindgen_tmp |
| 2677 |
} |
| 2678 |
}) |
| 2679 |
} |
| 2680 |
|
| 2681 |
let block = ctx.wrap_unsafe_ops(quote! ( #( #stmts );*)); |
| 2682 |
|
| 2683 |
let mut attrs = vec![attributes::inline()]; |
| 2684 |
|
| 2685 |
if signature.must_use() && |
| 2686 |
ctx.options().rust_features().must_use_function |
| 2687 |
{ |
| 2688 |
attrs.push(attributes::must_use()); |
| 2689 |
} |
| 2690 |
|
| 2691 |
let name = ctx.rust_ident(&name); |
| 2692 |
methods.push(quote! { |
| 2693 |
#(#attrs)* |
| 2694 |
pub unsafe fn #name ( #( #args ),* ) #ret { |
| 2695 |
#block |
| 2696 |
} |
| 2697 |
}); |
| 2698 |
} |
| 2699 |
} |
| 2700 |
|
| 2701 |
/// A helper type that represents different enum variations. |
| 2702 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 2703 |
pub enum EnumVariation { |
| 2704 |
/// The code for this enum will use a Rust enum. Note that creating this in unsafe code |
| 2705 |
/// (including FFI) with an invalid value will invoke undefined behaviour, whether or not |
| 2706 |
/// its marked as non_exhaustive. |
| 2707 |
Rust { |
| 2708 |
/// Indicates whether the generated struct should be `#[non_exhaustive]` |
| 2709 |
non_exhaustive: bool, |
| 2710 |
}, |
| 2711 |
/// The code for this enum will use a newtype |
| 2712 |
NewType { |
| 2713 |
/// Indicates whether the newtype will have bitwise operators |
| 2714 |
is_bitfield: bool, |
| 2715 |
/// Indicates whether the variants will be represented as global constants |
| 2716 |
is_global: bool, |
| 2717 |
}, |
| 2718 |
/// The code for this enum will use consts |
| 2719 |
Consts, |
| 2720 |
/// The code for this enum will use a module containing consts |
| 2721 |
ModuleConsts, |
| 2722 |
} |
| 2723 |
|
| 2724 |
impl EnumVariation { |
| 2725 |
fn is_rust(&self) -> bool { |
| 2726 |
matches!(*self, EnumVariation::Rust { .. }) |
| 2727 |
} |
| 2728 |
|
| 2729 |
/// Both the `Const` and `ModuleConsts` variants will cause this to return |
| 2730 |
/// true. |
| 2731 |
fn is_const(&self) -> bool { |
| 2732 |
matches!(*self, EnumVariation::Consts | EnumVariation::ModuleConsts) |
| 2733 |
} |
| 2734 |
} |
| 2735 |
|
| 2736 |
impl Default for EnumVariation { |
| 2737 |
fn default() -> EnumVariation { |
| 2738 |
EnumVariation::Consts |
| 2739 |
} |
| 2740 |
} |
| 2741 |
|
| 2742 |
impl fmt::Display for EnumVariation { |
| 2743 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 2744 |
let s = match self { |
| 2745 |
Self::Rust { |
| 2746 |
non_exhaustive: false, |
| 2747 |
} => "rust", |
| 2748 |
Self::Rust { |
| 2749 |
non_exhaustive: true, |
| 2750 |
} => "rust_non_exhaustive", |
| 2751 |
Self::NewType { |
| 2752 |
is_bitfield: true, .. |
| 2753 |
} => "bitfield", |
| 2754 |
Self::NewType { |
| 2755 |
is_bitfield: false, |
| 2756 |
is_global, |
| 2757 |
} => { |
| 2758 |
if *is_global { |
| 2759 |
"newtype_global" |
| 2760 |
} else { |
| 2761 |
"newtype" |
| 2762 |
} |
| 2763 |
} |
| 2764 |
Self::Consts => "consts", |
| 2765 |
Self::ModuleConsts => "moduleconsts", |
| 2766 |
}; |
| 2767 |
s.fmt(f) |
| 2768 |
} |
| 2769 |
} |
| 2770 |
|
| 2771 |
impl std::str::FromStr for EnumVariation { |
| 2772 |
type Err = std::io::Error; |
| 2773 |
|
| 2774 |
/// Create a `EnumVariation` from a string. |
| 2775 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 2776 |
match s { |
| 2777 |
"rust" => Ok(EnumVariation::Rust { |
| 2778 |
non_exhaustive: false, |
| 2779 |
}), |
| 2780 |
"rust_non_exhaustive" => Ok(EnumVariation::Rust { |
| 2781 |
non_exhaustive: true, |
| 2782 |
}), |
| 2783 |
"bitfield" => Ok(EnumVariation::NewType { |
| 2784 |
is_bitfield: true, |
| 2785 |
is_global: false, |
| 2786 |
}), |
| 2787 |
"consts" => Ok(EnumVariation::Consts), |
| 2788 |
"moduleconsts" => Ok(EnumVariation::ModuleConsts), |
| 2789 |
"newtype" => Ok(EnumVariation::NewType { |
| 2790 |
is_bitfield: false, |
| 2791 |
is_global: false, |
| 2792 |
}), |
| 2793 |
"newtype_global" => Ok(EnumVariation::NewType { |
| 2794 |
is_bitfield: false, |
| 2795 |
is_global: true, |
| 2796 |
}), |
| 2797 |
_ => Err(std::io::Error::new( |
| 2798 |
std::io::ErrorKind::InvalidInput, |
| 2799 |
concat!( |
| 2800 |
"Got an invalid EnumVariation. Accepted values ", |
| 2801 |
"are 'rust', 'rust_non_exhaustive', 'bitfield', 'consts',", |
| 2802 |
"'moduleconsts', 'newtype' and 'newtype_global'." |
| 2803 |
), |
| 2804 |
)), |
| 2805 |
} |
| 2806 |
} |
| 2807 |
} |
| 2808 |
|
| 2809 |
/// A helper type to construct different enum variations. |
| 2810 |
enum EnumBuilder<'a> { |
| 2811 |
Rust { |
| 2812 |
attrs: Vec<proc_macro2::TokenStream>, |
| 2813 |
ident: Ident, |
| 2814 |
tokens: proc_macro2::TokenStream, |
| 2815 |
emitted_any_variants: bool, |
| 2816 |
}, |
| 2817 |
NewType { |
| 2818 |
canonical_name: &'a str, |
| 2819 |
tokens: proc_macro2::TokenStream, |
| 2820 |
is_bitfield: bool, |
| 2821 |
is_global: bool, |
| 2822 |
}, |
| 2823 |
Consts { |
| 2824 |
variants: Vec<proc_macro2::TokenStream>, |
| 2825 |
}, |
| 2826 |
ModuleConsts { |
| 2827 |
module_name: &'a str, |
| 2828 |
module_items: Vec<proc_macro2::TokenStream>, |
| 2829 |
}, |
| 2830 |
} |
| 2831 |
|
| 2832 |
impl<'a> EnumBuilder<'a> { |
| 2833 |
/// Returns true if the builder is for a rustified enum. |
| 2834 |
fn is_rust_enum(&self) -> bool { |
| 2835 |
matches!(*self, EnumBuilder::Rust { .. }) |
| 2836 |
} |
| 2837 |
|
| 2838 |
/// Create a new enum given an item builder, a canonical name, a name for |
| 2839 |
/// the representation, and which variation it should be generated as. |
| 2840 |
fn new( |
| 2841 |
name: &'a str, |
| 2842 |
mut attrs: Vec<proc_macro2::TokenStream>, |
| 2843 |
repr: proc_macro2::TokenStream, |
| 2844 |
enum_variation: EnumVariation, |
| 2845 |
has_typedef: bool, |
| 2846 |
) -> Self { |
| 2847 |
let ident = Ident::new(name, Span::call_site()); |
| 2848 |
|
| 2849 |
match enum_variation { |
| 2850 |
EnumVariation::NewType { |
| 2851 |
is_bitfield, |
| 2852 |
is_global, |
| 2853 |
} => EnumBuilder::NewType { |
| 2854 |
canonical_name: name, |
| 2855 |
tokens: quote! { |
| 2856 |
#( #attrs )* |
| 2857 |
pub struct #ident (pub #repr); |
| 2858 |
}, |
| 2859 |
is_bitfield, |
| 2860 |
is_global, |
| 2861 |
}, |
| 2862 |
|
| 2863 |
EnumVariation::Rust { .. } => { |
| 2864 |
// `repr` is guaranteed to be Rustified in Enum::codegen |
| 2865 |
attrs.insert(0, quote! { #[repr( #repr )] }); |
| 2866 |
let tokens = quote!(); |
| 2867 |
EnumBuilder::Rust { |
| 2868 |
attrs, |
| 2869 |
ident, |
| 2870 |
tokens, |
| 2871 |
emitted_any_variants: false, |
| 2872 |
} |
| 2873 |
} |
| 2874 |
|
| 2875 |
EnumVariation::Consts => { |
| 2876 |
let mut variants = Vec::new(); |
| 2877 |
|
| 2878 |
if !has_typedef { |
| 2879 |
variants.push(quote! { |
| 2880 |
#( #attrs )* |
| 2881 |
pub type #ident = #repr; |
| 2882 |
}); |
| 2883 |
} |
| 2884 |
|
| 2885 |
EnumBuilder::Consts { variants } |
| 2886 |
} |
| 2887 |
|
| 2888 |
EnumVariation::ModuleConsts => { |
| 2889 |
let ident = Ident::new( |
| 2890 |
CONSTIFIED_ENUM_MODULE_REPR_NAME, |
| 2891 |
Span::call_site(), |
| 2892 |
); |
| 2893 |
let type_definition = quote! { |
| 2894 |
#( #attrs )* |
| 2895 |
pub type #ident = #repr; |
| 2896 |
}; |
| 2897 |
|
| 2898 |
EnumBuilder::ModuleConsts { |
| 2899 |
module_name: name, |
| 2900 |
module_items: vec![type_definition], |
| 2901 |
} |
| 2902 |
} |
| 2903 |
} |
| 2904 |
} |
| 2905 |
|
| 2906 |
/// Add a variant to this enum. |
| 2907 |
fn with_variant( |
| 2908 |
self, |
| 2909 |
ctx: &BindgenContext, |
| 2910 |
variant: &EnumVariant, |
| 2911 |
mangling_prefix: Option<&str>, |
| 2912 |
rust_ty: proc_macro2::TokenStream, |
| 2913 |
result: &mut CodegenResult<'_>, |
| 2914 |
is_ty_named: bool, |
| 2915 |
) -> Self { |
| 2916 |
let variant_name = ctx.rust_mangle(variant.name()); |
| 2917 |
let is_rust_enum = self.is_rust_enum(); |
| 2918 |
let expr = match variant.val() { |
| 2919 |
EnumVariantValue::Boolean(v) if is_rust_enum => { |
| 2920 |
helpers::ast_ty::uint_expr(v as u64) |
| 2921 |
} |
| 2922 |
EnumVariantValue::Boolean(v) => quote!(#v), |
| 2923 |
EnumVariantValue::Signed(v) => helpers::ast_ty::int_expr(v), |
| 2924 |
EnumVariantValue::Unsigned(v) => helpers::ast_ty::uint_expr(v), |
| 2925 |
}; |
| 2926 |
|
| 2927 |
let mut doc = quote! {}; |
| 2928 |
if ctx.options().generate_comments { |
| 2929 |
if let Some(raw_comment) = variant.comment() { |
| 2930 |
let comment = ctx.options().process_comment(raw_comment); |
| 2931 |
doc = attributes::doc(comment); |
| 2932 |
} |
| 2933 |
} |
| 2934 |
|
| 2935 |
match self { |
| 2936 |
EnumBuilder::Rust { |
| 2937 |
attrs, |
| 2938 |
ident, |
| 2939 |
tokens, |
| 2940 |
emitted_any_variants: _, |
| 2941 |
} => { |
| 2942 |
let name = ctx.rust_ident(variant_name); |
| 2943 |
EnumBuilder::Rust { |
| 2944 |
attrs, |
| 2945 |
ident, |
| 2946 |
tokens: quote! { |
| 2947 |
#tokens |
| 2948 |
#doc |
| 2949 |
#name = #expr, |
| 2950 |
}, |
| 2951 |
emitted_any_variants: true, |
| 2952 |
} |
| 2953 |
} |
| 2954 |
|
| 2955 |
EnumBuilder::NewType { |
| 2956 |
canonical_name, |
| 2957 |
is_global, |
| 2958 |
.. |
| 2959 |
} => { |
| 2960 |
if ctx.options().rust_features().associated_const && |
| 2961 |
is_ty_named && |
| 2962 |
!is_global |
| 2963 |
{ |
| 2964 |
let enum_ident = ctx.rust_ident(canonical_name); |
| 2965 |
let variant_ident = ctx.rust_ident(variant_name); |
| 2966 |
|
| 2967 |
result.push(quote! { |
| 2968 |
impl #enum_ident { |
| 2969 |
#doc |
| 2970 |
pub const #variant_ident : #rust_ty = #rust_ty ( #expr ); |
| 2971 |
} |
| 2972 |
}); |
| 2973 |
} else { |
| 2974 |
let ident = ctx.rust_ident(match mangling_prefix { |
| 2975 |
Some(prefix) => { |
| 2976 |
Cow::Owned(format!("{}_{}", prefix, variant_name)) |
| 2977 |
} |
| 2978 |
None => variant_name, |
| 2979 |
}); |
| 2980 |
result.push(quote! { |
| 2981 |
#doc |
| 2982 |
pub const #ident : #rust_ty = #rust_ty ( #expr ); |
| 2983 |
}); |
| 2984 |
} |
| 2985 |
|
| 2986 |
self |
| 2987 |
} |
| 2988 |
|
| 2989 |
EnumBuilder::Consts { .. } => { |
| 2990 |
let constant_name = match mangling_prefix { |
| 2991 |
Some(prefix) => { |
| 2992 |
Cow::Owned(format!("{}_{}", prefix, variant_name)) |
| 2993 |
} |
| 2994 |
None => variant_name, |
| 2995 |
}; |
| 2996 |
|
| 2997 |
let ident = ctx.rust_ident(constant_name); |
| 2998 |
result.push(quote! { |
| 2999 |
#doc |
| 3000 |
pub const #ident : #rust_ty = #expr ; |
| 3001 |
}); |
| 3002 |
|
| 3003 |
self |
| 3004 |
} |
| 3005 |
EnumBuilder::ModuleConsts { |
| 3006 |
module_name, |
| 3007 |
mut module_items, |
| 3008 |
} => { |
| 3009 |
let name = ctx.rust_ident(variant_name); |
| 3010 |
let ty = ctx.rust_ident(CONSTIFIED_ENUM_MODULE_REPR_NAME); |
| 3011 |
module_items.push(quote! { |
| 3012 |
#doc |
| 3013 |
pub const #name : #ty = #expr ; |
| 3014 |
}); |
| 3015 |
|
| 3016 |
EnumBuilder::ModuleConsts { |
| 3017 |
module_name, |
| 3018 |
module_items, |
| 3019 |
} |
| 3020 |
} |
| 3021 |
} |
| 3022 |
} |
| 3023 |
|
| 3024 |
fn build( |
| 3025 |
self, |
| 3026 |
ctx: &BindgenContext, |
| 3027 |
rust_ty: proc_macro2::TokenStream, |
| 3028 |
result: &mut CodegenResult<'_>, |
| 3029 |
) -> proc_macro2::TokenStream { |
| 3030 |
match self { |
| 3031 |
EnumBuilder::Rust { |
| 3032 |
attrs, |
| 3033 |
ident, |
| 3034 |
tokens, |
| 3035 |
emitted_any_variants, |
| 3036 |
.. |
| 3037 |
} => { |
| 3038 |
let variants = if !emitted_any_variants { |
| 3039 |
quote!(__bindgen_cannot_repr_c_on_empty_enum = 0) |
| 3040 |
} else { |
| 3041 |
tokens |
| 3042 |
}; |
| 3043 |
|
| 3044 |
quote! { |
| 3045 |
#( #attrs )* |
| 3046 |
pub enum #ident { |
| 3047 |
#variants |
| 3048 |
} |
| 3049 |
} |
| 3050 |
} |
| 3051 |
EnumBuilder::NewType { |
| 3052 |
canonical_name, |
| 3053 |
tokens, |
| 3054 |
is_bitfield, |
| 3055 |
.. |
| 3056 |
} => { |
| 3057 |
if !is_bitfield { |
| 3058 |
return tokens; |
| 3059 |
} |
| 3060 |
|
| 3061 |
let rust_ty_name = ctx.rust_ident_raw(canonical_name); |
| 3062 |
let prefix = ctx.trait_prefix(); |
| 3063 |
|
| 3064 |
result.push(quote! { |
| 3065 |
impl ::#prefix::ops::BitOr<#rust_ty> for #rust_ty { |
| 3066 |
type Output = Self; |
| 3067 |
|
| 3068 |
#[inline] |
| 3069 |
fn bitor(self, other: Self) -> Self { |
| 3070 |
#rust_ty_name(self.0 | other.0) |
| 3071 |
} |
| 3072 |
} |
| 3073 |
}); |
| 3074 |
|
| 3075 |
result.push(quote! { |
| 3076 |
impl ::#prefix::ops::BitOrAssign for #rust_ty { |
| 3077 |
#[inline] |
| 3078 |
fn bitor_assign(&mut self, rhs: #rust_ty) { |
| 3079 |
self.0 |= rhs.0; |
| 3080 |
} |
| 3081 |
} |
| 3082 |
}); |
| 3083 |
|
| 3084 |
result.push(quote! { |
| 3085 |
impl ::#prefix::ops::BitAnd<#rust_ty> for #rust_ty { |
| 3086 |
type Output = Self; |
| 3087 |
|
| 3088 |
#[inline] |
| 3089 |
fn bitand(self, other: Self) -> Self { |
| 3090 |
#rust_ty_name(self.0 & other.0) |
| 3091 |
} |
| 3092 |
} |
| 3093 |
}); |
| 3094 |
|
| 3095 |
result.push(quote! { |
| 3096 |
impl ::#prefix::ops::BitAndAssign for #rust_ty { |
| 3097 |
#[inline] |
| 3098 |
fn bitand_assign(&mut self, rhs: #rust_ty) { |
| 3099 |
self.0 &= rhs.0; |
| 3100 |
} |
| 3101 |
} |
| 3102 |
}); |
| 3103 |
|
| 3104 |
tokens |
| 3105 |
} |
| 3106 |
EnumBuilder::Consts { variants, .. } => quote! { #( #variants )* }, |
| 3107 |
EnumBuilder::ModuleConsts { |
| 3108 |
module_items, |
| 3109 |
module_name, |
| 3110 |
.. |
| 3111 |
} => { |
| 3112 |
let ident = ctx.rust_ident(module_name); |
| 3113 |
quote! { |
| 3114 |
pub mod #ident { |
| 3115 |
#( #module_items )* |
| 3116 |
} |
| 3117 |
} |
| 3118 |
} |
| 3119 |
} |
| 3120 |
} |
| 3121 |
} |
| 3122 |
|
| 3123 |
impl CodeGenerator for Enum { |
| 3124 |
type Extra = Item; |
| 3125 |
type Return = (); |
| 3126 |
|
| 3127 |
fn codegen( |
| 3128 |
&self, |
| 3129 |
ctx: &BindgenContext, |
| 3130 |
result: &mut CodegenResult<'_>, |
| 3131 |
item: &Item, |
| 3132 |
) { |
| 3133 |
debug!("<Enum as CodeGenerator>::codegen: item = {:?}", item); |
| 3134 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 3135 |
|
| 3136 |
let name = item.canonical_name(ctx); |
| 3137 |
let ident = ctx.rust_ident(&name); |
| 3138 |
let enum_ty = item.expect_type(); |
| 3139 |
let layout = enum_ty.layout(ctx); |
| 3140 |
let variation = self.computed_enum_variation(ctx, item); |
| 3141 |
|
| 3142 |
let repr_translated; |
| 3143 |
let repr = match self.repr().map(|repr| ctx.resolve_type(repr)) { |
| 3144 |
Some(repr) |
| 3145 |
if !ctx.options().translate_enum_integer_types && |
| 3146 |
!variation.is_rust() => |
| 3147 |
{ |
| 3148 |
repr |
| 3149 |
} |
| 3150 |
repr => { |
| 3151 |
// An enum's integer type is translated to a native Rust |
| 3152 |
// integer type in 3 cases: |
| 3153 |
// * the enum is Rustified and we need a translated type for |
| 3154 |
// the repr attribute |
| 3155 |
// * the representation couldn't be determined from the C source |
| 3156 |
// * it was explicitly requested as a bindgen option |
| 3157 |
|
| 3158 |
let kind = match repr { |
| 3159 |
Some(repr) => match *repr.canonical_type(ctx).kind() { |
| 3160 |
TypeKind::Int(int_kind) => int_kind, |
| 3161 |
_ => panic!("Unexpected type as enum repr"), |
| 3162 |
}, |
| 3163 |
None => { |
| 3164 |
warn!( |
| 3165 |
"Guessing type of enum! Forward declarations of enums \ |
| 3166 |
shouldn't be legal!" |
| 3167 |
); |
| 3168 |
IntKind::Int |
| 3169 |
} |
| 3170 |
}; |
| 3171 |
|
| 3172 |
let signed = kind.is_signed(); |
| 3173 |
let size = layout |
| 3174 |
.map(|l| l.size) |
| 3175 |
.or_else(|| kind.known_size()) |
| 3176 |
.unwrap_or(0); |
| 3177 |
|
| 3178 |
let translated = match (signed, size) { |
| 3179 |
(true, 1) => IntKind::I8, |
| 3180 |
(false, 1) => IntKind::U8, |
| 3181 |
(true, 2) => IntKind::I16, |
| 3182 |
(false, 2) => IntKind::U16, |
| 3183 |
(true, 4) => IntKind::I32, |
| 3184 |
(false, 4) => IntKind::U32, |
| 3185 |
(true, 8) => IntKind::I64, |
| 3186 |
(false, 8) => IntKind::U64, |
| 3187 |
_ => { |
| 3188 |
warn!( |
| 3189 |
"invalid enum decl: signed: {}, size: {}", |
| 3190 |
signed, size |
| 3191 |
); |
| 3192 |
IntKind::I32 |
| 3193 |
} |
| 3194 |
}; |
| 3195 |
|
| 3196 |
repr_translated = |
| 3197 |
Type::new(None, None, TypeKind::Int(translated), false); |
| 3198 |
&repr_translated |
| 3199 |
} |
| 3200 |
}; |
| 3201 |
|
| 3202 |
let mut attrs = vec![]; |
| 3203 |
|
| 3204 |
// TODO(emilio): Delegate this to the builders? |
| 3205 |
match variation { |
| 3206 |
EnumVariation::Rust { non_exhaustive } => { |
| 3207 |
if non_exhaustive && |
| 3208 |
ctx.options().rust_features().non_exhaustive |
| 3209 |
{ |
| 3210 |
attrs.push(attributes::non_exhaustive()); |
| 3211 |
} else if non_exhaustive && |
| 3212 |
!ctx.options().rust_features().non_exhaustive |
| 3213 |
{ |
| 3214 |
panic!("The rust target you're using doesn't seem to support non_exhaustive enums"); |
| 3215 |
} |
| 3216 |
} |
| 3217 |
EnumVariation::NewType { .. } => { |
| 3218 |
if ctx.options().rust_features.repr_transparent { |
| 3219 |
attrs.push(attributes::repr("transparent")); |
| 3220 |
} else { |
| 3221 |
attrs.push(attributes::repr("C")); |
| 3222 |
} |
| 3223 |
} |
| 3224 |
_ => {} |
| 3225 |
}; |
| 3226 |
|
| 3227 |
if let Some(comment) = item.comment(ctx) { |
| 3228 |
attrs.push(attributes::doc(comment)); |
| 3229 |
} |
| 3230 |
|
| 3231 |
if item.must_use(ctx) { |
| 3232 |
attrs.push(attributes::must_use()); |
| 3233 |
} |
| 3234 |
|
| 3235 |
if !variation.is_const() { |
| 3236 |
let packed = false; // Enums can't be packed in Rust. |
| 3237 |
let mut derives = derives_of_item(item, ctx, packed); |
| 3238 |
// For backwards compat, enums always derive |
| 3239 |
// Clone/Eq/PartialEq/Hash, even if we don't generate those by |
| 3240 |
// default. |
| 3241 |
derives.insert( |
| 3242 |
DerivableTraits::CLONE | |
| 3243 |
DerivableTraits::HASH | |
| 3244 |
DerivableTraits::PARTIAL_EQ | |
| 3245 |
DerivableTraits::EQ, |
| 3246 |
); |
| 3247 |
let mut derives: Vec<_> = derives.into(); |
| 3248 |
for derive in item.annotations().derives().iter() { |
| 3249 |
if !derives.contains(&derive.as_str()) { |
| 3250 |
derives.push(derive); |
| 3251 |
} |
| 3252 |
} |
| 3253 |
|
| 3254 |
// The custom derives callback may return a list of derive attributes; |
| 3255 |
// add them to the end of the list. |
| 3256 |
let custom_derives = ctx.options().all_callbacks(|cb| { |
| 3257 |
cb.add_derives(&DeriveInfo { |
| 3258 |
name: &name, |
| 3259 |
kind: DeriveTypeKind::Enum, |
| 3260 |
}) |
| 3261 |
}); |
| 3262 |
// In most cases this will be a no-op, since custom_derives will be empty. |
| 3263 |
derives.extend(custom_derives.iter().map(|s| s.as_str())); |
| 3264 |
|
| 3265 |
attrs.push(attributes::derives(&derives)); |
| 3266 |
} |
| 3267 |
|
| 3268 |
fn add_constant( |
| 3269 |
ctx: &BindgenContext, |
| 3270 |
enum_: &Type, |
| 3271 |
// Only to avoid recomputing every time. |
| 3272 |
enum_canonical_name: &Ident, |
| 3273 |
// May be the same as "variant" if it's because the |
| 3274 |
// enum is unnamed and we still haven't seen the |
| 3275 |
// value. |
| 3276 |
variant_name: &Ident, |
| 3277 |
referenced_name: &Ident, |
| 3278 |
enum_rust_ty: proc_macro2::TokenStream, |
| 3279 |
result: &mut CodegenResult<'_>, |
| 3280 |
) { |
| 3281 |
let constant_name = if enum_.name().is_some() { |
| 3282 |
if ctx.options().prepend_enum_name { |
| 3283 |
format!("{}_{}", enum_canonical_name, variant_name) |
| 3284 |
} else { |
| 3285 |
format!("{}", variant_name) |
| 3286 |
} |
| 3287 |
} else { |
| 3288 |
format!("{}", variant_name) |
| 3289 |
}; |
| 3290 |
let constant_name = ctx.rust_ident(constant_name); |
| 3291 |
|
| 3292 |
result.push(quote! { |
| 3293 |
pub const #constant_name : #enum_rust_ty = |
| 3294 |
#enum_canonical_name :: #referenced_name ; |
| 3295 |
}); |
| 3296 |
} |
| 3297 |
|
| 3298 |
let repr = repr.to_rust_ty_or_opaque(ctx, item); |
| 3299 |
let has_typedef = ctx.is_enum_typedef_combo(item.id()); |
| 3300 |
|
| 3301 |
let mut builder = |
| 3302 |
EnumBuilder::new(&name, attrs, repr, variation, has_typedef); |
| 3303 |
|
| 3304 |
// A map where we keep a value -> variant relation. |
| 3305 |
let mut seen_values = HashMap::<_, Ident>::default(); |
| 3306 |
let enum_rust_ty = item.to_rust_ty_or_opaque(ctx, &()); |
| 3307 |
let is_toplevel = item.is_toplevel(ctx); |
| 3308 |
|
| 3309 |
// Used to mangle the constants we generate in the unnamed-enum case. |
| 3310 |
let parent_canonical_name = if is_toplevel { |
| 3311 |
None |
| 3312 |
} else { |
| 3313 |
Some(item.parent_id().canonical_name(ctx)) |
| 3314 |
}; |
| 3315 |
|
| 3316 |
let constant_mangling_prefix = if ctx.options().prepend_enum_name { |
| 3317 |
if enum_ty.name().is_none() { |
| 3318 |
parent_canonical_name.as_deref() |
| 3319 |
} else { |
| 3320 |
Some(&*name) |
| 3321 |
} |
| 3322 |
} else { |
| 3323 |
None |
| 3324 |
}; |
| 3325 |
|
| 3326 |
// NB: We defer the creation of constified variants, in case we find |
| 3327 |
// another variant with the same value (which is the common thing to |
| 3328 |
// do). |
| 3329 |
let mut constified_variants = VecDeque::new(); |
| 3330 |
|
| 3331 |
let mut iter = self.variants().iter().peekable(); |
| 3332 |
while let Some(variant) = |
| 3333 |
iter.next().or_else(|| constified_variants.pop_front()) |
| 3334 |
{ |
| 3335 |
if variant.hidden() { |
| 3336 |
continue; |
| 3337 |
} |
| 3338 |
|
| 3339 |
if variant.force_constification() && iter.peek().is_some() { |
| 3340 |
constified_variants.push_back(variant); |
| 3341 |
continue; |
| 3342 |
} |
| 3343 |
|
| 3344 |
match seen_values.entry(variant.val()) { |
| 3345 |
Entry::Occupied(ref entry) => { |
| 3346 |
if variation.is_rust() { |
| 3347 |
let variant_name = ctx.rust_mangle(variant.name()); |
| 3348 |
let mangled_name = |
| 3349 |
if is_toplevel || enum_ty.name().is_some() { |
| 3350 |
variant_name |
| 3351 |
} else { |
| 3352 |
let parent_name = |
| 3353 |
parent_canonical_name.as_ref().unwrap(); |
| 3354 |
|
| 3355 |
Cow::Owned(format!( |
| 3356 |
"{}_{}", |
| 3357 |
parent_name, variant_name |
| 3358 |
)) |
| 3359 |
}; |
| 3360 |
|
| 3361 |
let existing_variant_name = entry.get(); |
| 3362 |
// Use associated constants for named enums. |
| 3363 |
if enum_ty.name().is_some() && |
| 3364 |
ctx.options().rust_features().associated_const |
| 3365 |
{ |
| 3366 |
let enum_canonical_name = &ident; |
| 3367 |
let variant_name = |
| 3368 |
ctx.rust_ident_raw(&*mangled_name); |
| 3369 |
result.push(quote! { |
| 3370 |
impl #enum_rust_ty { |
| 3371 |
pub const #variant_name : #enum_rust_ty = |
| 3372 |
#enum_canonical_name :: #existing_variant_name ; |
| 3373 |
} |
| 3374 |
}); |
| 3375 |
} else { |
| 3376 |
add_constant( |
| 3377 |
ctx, |
| 3378 |
enum_ty, |
| 3379 |
&ident, |
| 3380 |
&Ident::new(&mangled_name, Span::call_site()), |
| 3381 |
existing_variant_name, |
| 3382 |
enum_rust_ty.clone(), |
| 3383 |
result, |
| 3384 |
); |
| 3385 |
} |
| 3386 |
} else { |
| 3387 |
builder = builder.with_variant( |
| 3388 |
ctx, |
| 3389 |
variant, |
| 3390 |
constant_mangling_prefix, |
| 3391 |
enum_rust_ty.clone(), |
| 3392 |
result, |
| 3393 |
enum_ty.name().is_some(), |
| 3394 |
); |
| 3395 |
} |
| 3396 |
} |
| 3397 |
Entry::Vacant(entry) => { |
| 3398 |
builder = builder.with_variant( |
| 3399 |
ctx, |
| 3400 |
variant, |
| 3401 |
constant_mangling_prefix, |
| 3402 |
enum_rust_ty.clone(), |
| 3403 |
result, |
| 3404 |
enum_ty.name().is_some(), |
| 3405 |
); |
| 3406 |
|
| 3407 |
let variant_name = ctx.rust_ident(variant.name()); |
| 3408 |
|
| 3409 |
// If it's an unnamed enum, or constification is enforced, |
| 3410 |
// we also generate a constant so it can be properly |
| 3411 |
// accessed. |
| 3412 |
if (variation.is_rust() && enum_ty.name().is_none()) || |
| 3413 |
variant.force_constification() |
| 3414 |
{ |
| 3415 |
let mangled_name = if is_toplevel { |
| 3416 |
variant_name.clone() |
| 3417 |
} else { |
| 3418 |
let parent_name = |
| 3419 |
parent_canonical_name.as_ref().unwrap(); |
| 3420 |
|
| 3421 |
Ident::new( |
| 3422 |
&format!("{}_{}", parent_name, variant_name), |
| 3423 |
Span::call_site(), |
| 3424 |
) |
| 3425 |
}; |
| 3426 |
|
| 3427 |
add_constant( |
| 3428 |
ctx, |
| 3429 |
enum_ty, |
| 3430 |
&ident, |
| 3431 |
&mangled_name, |
| 3432 |
&variant_name, |
| 3433 |
enum_rust_ty.clone(), |
| 3434 |
result, |
| 3435 |
); |
| 3436 |
} |
| 3437 |
|
| 3438 |
entry.insert(variant_name); |
| 3439 |
} |
| 3440 |
} |
| 3441 |
} |
| 3442 |
|
| 3443 |
let item = builder.build(ctx, enum_rust_ty, result); |
| 3444 |
result.push(item); |
| 3445 |
} |
| 3446 |
} |
| 3447 |
|
| 3448 |
/// Enum for the default type of macro constants. |
| 3449 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 3450 |
pub enum MacroTypeVariation { |
| 3451 |
/// Use i32 or i64 |
| 3452 |
Signed, |
| 3453 |
/// Use u32 or u64 |
| 3454 |
Unsigned, |
| 3455 |
} |
| 3456 |
|
| 3457 |
impl fmt::Display for MacroTypeVariation { |
| 3458 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 3459 |
let s = match self { |
| 3460 |
Self::Signed => "signed", |
| 3461 |
Self::Unsigned => "unsigned", |
| 3462 |
}; |
| 3463 |
s.fmt(f) |
| 3464 |
} |
| 3465 |
} |
| 3466 |
|
| 3467 |
impl Default for MacroTypeVariation { |
| 3468 |
fn default() -> MacroTypeVariation { |
| 3469 |
MacroTypeVariation::Unsigned |
| 3470 |
} |
| 3471 |
} |
| 3472 |
|
| 3473 |
impl std::str::FromStr for MacroTypeVariation { |
| 3474 |
type Err = std::io::Error; |
| 3475 |
|
| 3476 |
/// Create a `MacroTypeVariation` from a string. |
| 3477 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 3478 |
match s { |
| 3479 |
"signed" => Ok(MacroTypeVariation::Signed), |
| 3480 |
"unsigned" => Ok(MacroTypeVariation::Unsigned), |
| 3481 |
_ => Err(std::io::Error::new( |
| 3482 |
std::io::ErrorKind::InvalidInput, |
| 3483 |
concat!( |
| 3484 |
"Got an invalid MacroTypeVariation. Accepted values ", |
| 3485 |
"are 'signed' and 'unsigned'" |
| 3486 |
), |
| 3487 |
)), |
| 3488 |
} |
| 3489 |
} |
| 3490 |
} |
| 3491 |
|
| 3492 |
/// Enum for how aliases should be translated. |
| 3493 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 3494 |
pub enum AliasVariation { |
| 3495 |
/// Convert to regular Rust alias |
| 3496 |
TypeAlias, |
| 3497 |
/// Create a new type by wrapping the old type in a struct and using #[repr(transparent)] |
| 3498 |
NewType, |
| 3499 |
/// Same as NewStruct but also impl Deref to be able to use the methods of the wrapped type |
| 3500 |
NewTypeDeref, |
| 3501 |
} |
| 3502 |
|
| 3503 |
impl fmt::Display for AliasVariation { |
| 3504 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 3505 |
let s = match self { |
| 3506 |
Self::TypeAlias => "type_alias", |
| 3507 |
Self::NewType => "new_type", |
| 3508 |
Self::NewTypeDeref => "new_type_deref", |
| 3509 |
}; |
| 3510 |
|
| 3511 |
s.fmt(f) |
| 3512 |
} |
| 3513 |
} |
| 3514 |
|
| 3515 |
impl Default for AliasVariation { |
| 3516 |
fn default() -> AliasVariation { |
| 3517 |
AliasVariation::TypeAlias |
| 3518 |
} |
| 3519 |
} |
| 3520 |
|
| 3521 |
impl std::str::FromStr for AliasVariation { |
| 3522 |
type Err = std::io::Error; |
| 3523 |
|
| 3524 |
/// Create an `AliasVariation` from a string. |
| 3525 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 3526 |
match s { |
| 3527 |
"type_alias" => Ok(AliasVariation::TypeAlias), |
| 3528 |
"new_type" => Ok(AliasVariation::NewType), |
| 3529 |
"new_type_deref" => Ok(AliasVariation::NewTypeDeref), |
| 3530 |
_ => Err(std::io::Error::new( |
| 3531 |
std::io::ErrorKind::InvalidInput, |
| 3532 |
concat!( |
| 3533 |
"Got an invalid AliasVariation. Accepted values ", |
| 3534 |
"are 'type_alias', 'new_type', and 'new_type_deref'" |
| 3535 |
), |
| 3536 |
)), |
| 3537 |
} |
| 3538 |
} |
| 3539 |
} |
| 3540 |
|
| 3541 |
/// Enum for how non-`Copy` `union`s should be translated. |
| 3542 |
#[derive(Copy, Clone, PartialEq, Eq, Debug)] |
| 3543 |
pub enum NonCopyUnionStyle { |
| 3544 |
/// Wrap members in a type generated by `bindgen`. |
| 3545 |
BindgenWrapper, |
| 3546 |
/// Wrap members in [`::core::mem::ManuallyDrop`]. |
| 3547 |
/// |
| 3548 |
/// Note: `ManuallyDrop` was stabilized in Rust 1.20.0, do not use it if your |
| 3549 |
/// MSRV is lower. |
| 3550 |
ManuallyDrop, |
| 3551 |
} |
| 3552 |
|
| 3553 |
impl fmt::Display for NonCopyUnionStyle { |
| 3554 |
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 3555 |
let s = match self { |
| 3556 |
Self::BindgenWrapper => "bindgen_wrapper", |
| 3557 |
Self::ManuallyDrop => "manually_drop", |
| 3558 |
}; |
| 3559 |
|
| 3560 |
s.fmt(f) |
| 3561 |
} |
| 3562 |
} |
| 3563 |
|
| 3564 |
impl Default for NonCopyUnionStyle { |
| 3565 |
fn default() -> Self { |
| 3566 |
Self::BindgenWrapper |
| 3567 |
} |
| 3568 |
} |
| 3569 |
|
| 3570 |
impl std::str::FromStr for NonCopyUnionStyle { |
| 3571 |
type Err = std::io::Error; |
| 3572 |
|
| 3573 |
fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 3574 |
match s { |
| 3575 |
"bindgen_wrapper" => Ok(Self::BindgenWrapper), |
| 3576 |
"manually_drop" => Ok(Self::ManuallyDrop), |
| 3577 |
_ => Err(std::io::Error::new( |
| 3578 |
std::io::ErrorKind::InvalidInput, |
| 3579 |
concat!( |
| 3580 |
"Got an invalid NonCopyUnionStyle. Accepted values ", |
| 3581 |
"are 'bindgen_wrapper' and 'manually_drop'" |
| 3582 |
), |
| 3583 |
)), |
| 3584 |
} |
| 3585 |
} |
| 3586 |
} |
| 3587 |
|
| 3588 |
/// Fallible conversion to an opaque blob. |
| 3589 |
/// |
| 3590 |
/// Implementors of this trait should provide the `try_get_layout` method to |
| 3591 |
/// fallibly get this thing's layout, which the provided `try_to_opaque` trait |
| 3592 |
/// method will use to convert the `Layout` into an opaque blob Rust type. |
| 3593 |
trait TryToOpaque { |
| 3594 |
type Extra; |
| 3595 |
|
| 3596 |
/// Get the layout for this thing, if one is available. |
| 3597 |
fn try_get_layout( |
| 3598 |
&self, |
| 3599 |
ctx: &BindgenContext, |
| 3600 |
extra: &Self::Extra, |
| 3601 |
) -> error::Result<Layout>; |
| 3602 |
|
| 3603 |
/// Do not override this provided trait method. |
| 3604 |
fn try_to_opaque( |
| 3605 |
&self, |
| 3606 |
ctx: &BindgenContext, |
| 3607 |
extra: &Self::Extra, |
| 3608 |
) -> error::Result<proc_macro2::TokenStream> { |
| 3609 |
self.try_get_layout(ctx, extra) |
| 3610 |
.map(|layout| helpers::blob(ctx, layout)) |
| 3611 |
} |
| 3612 |
} |
| 3613 |
|
| 3614 |
/// Infallible conversion of an IR thing to an opaque blob. |
| 3615 |
/// |
| 3616 |
/// The resulting layout is best effort, and is unfortunately not guaranteed to |
| 3617 |
/// be correct. When all else fails, we fall back to a single byte layout as a |
| 3618 |
/// last resort, because C++ does not permit zero-sized types. See the note in |
| 3619 |
/// the `ToRustTyOrOpaque` doc comment about fallible versus infallible traits |
| 3620 |
/// and when each is appropriate. |
| 3621 |
/// |
| 3622 |
/// Don't implement this directly. Instead implement `TryToOpaque`, and then |
| 3623 |
/// leverage the blanket impl for this trait. |
| 3624 |
trait ToOpaque: TryToOpaque { |
| 3625 |
fn get_layout(&self, ctx: &BindgenContext, extra: &Self::Extra) -> Layout { |
| 3626 |
self.try_get_layout(ctx, extra) |
| 3627 |
.unwrap_or_else(|_| Layout::for_size(ctx, 1)) |
| 3628 |
} |
| 3629 |
|
| 3630 |
fn to_opaque( |
| 3631 |
&self, |
| 3632 |
ctx: &BindgenContext, |
| 3633 |
extra: &Self::Extra, |
| 3634 |
) -> proc_macro2::TokenStream { |
| 3635 |
let layout = self.get_layout(ctx, extra); |
| 3636 |
helpers::blob(ctx, layout) |
| 3637 |
} |
| 3638 |
} |
| 3639 |
|
| 3640 |
impl<T> ToOpaque for T where T: TryToOpaque {} |
| 3641 |
|
| 3642 |
/// Fallible conversion from an IR thing to an *equivalent* Rust type. |
| 3643 |
/// |
| 3644 |
/// If the C/C++ construct represented by the IR thing cannot (currently) be |
| 3645 |
/// represented in Rust (for example, instantiations of templates with |
| 3646 |
/// const-value generic parameters) then the impl should return an `Err`. It |
| 3647 |
/// should *not* attempt to return an opaque blob with the correct size and |
| 3648 |
/// alignment. That is the responsibility of the `TryToOpaque` trait. |
| 3649 |
trait TryToRustTy { |
| 3650 |
type Extra; |
| 3651 |
|
| 3652 |
fn try_to_rust_ty( |
| 3653 |
&self, |
| 3654 |
ctx: &BindgenContext, |
| 3655 |
extra: &Self::Extra, |
| 3656 |
) -> error::Result<proc_macro2::TokenStream>; |
| 3657 |
} |
| 3658 |
|
| 3659 |
/// Fallible conversion to a Rust type or an opaque blob with the correct size |
| 3660 |
/// and alignment. |
| 3661 |
/// |
| 3662 |
/// Don't implement this directly. Instead implement `TryToRustTy` and |
| 3663 |
/// `TryToOpaque`, and then leverage the blanket impl for this trait below. |
| 3664 |
trait TryToRustTyOrOpaque: TryToRustTy + TryToOpaque { |
| 3665 |
type Extra; |
| 3666 |
|
| 3667 |
fn try_to_rust_ty_or_opaque( |
| 3668 |
&self, |
| 3669 |
ctx: &BindgenContext, |
| 3670 |
extra: &<Self as TryToRustTyOrOpaque>::Extra, |
| 3671 |
) -> error::Result<proc_macro2::TokenStream>; |
| 3672 |
} |
| 3673 |
|
| 3674 |
impl<E, T> TryToRustTyOrOpaque for T |
| 3675 |
where |
| 3676 |
T: TryToRustTy<Extra = E> + TryToOpaque<Extra = E>, |
| 3677 |
{ |
| 3678 |
type Extra = E; |
| 3679 |
|
| 3680 |
fn try_to_rust_ty_or_opaque( |
| 3681 |
&self, |
| 3682 |
ctx: &BindgenContext, |
| 3683 |
extra: &E, |
| 3684 |
) -> error::Result<proc_macro2::TokenStream> { |
| 3685 |
self.try_to_rust_ty(ctx, extra).or_else(|_| { |
| 3686 |
if let Ok(layout) = self.try_get_layout(ctx, extra) { |
| 3687 |
Ok(helpers::blob(ctx, layout)) |
| 3688 |
} else { |
| 3689 |
Err(error::Error::NoLayoutForOpaqueBlob) |
| 3690 |
} |
| 3691 |
}) |
| 3692 |
} |
| 3693 |
} |
| 3694 |
|
| 3695 |
/// Infallible conversion to a Rust type, or an opaque blob with a best effort |
| 3696 |
/// of correct size and alignment. |
| 3697 |
/// |
| 3698 |
/// Don't implement this directly. Instead implement `TryToRustTy` and |
| 3699 |
/// `TryToOpaque`, and then leverage the blanket impl for this trait below. |
| 3700 |
/// |
| 3701 |
/// ### Fallible vs. Infallible Conversions to Rust Types |
| 3702 |
/// |
| 3703 |
/// When should one use this infallible `ToRustTyOrOpaque` trait versus the |
| 3704 |
/// fallible `TryTo{RustTy, Opaque, RustTyOrOpaque}` triats? All fallible trait |
| 3705 |
/// implementations that need to convert another thing into a Rust type or |
| 3706 |
/// opaque blob in a nested manner should also use fallible trait methods and |
| 3707 |
/// propagate failure up the stack. Only infallible functions and methods like |
| 3708 |
/// CodeGenerator implementations should use the infallible |
| 3709 |
/// `ToRustTyOrOpaque`. The further out we push error recovery, the more likely |
| 3710 |
/// we are to get a usable `Layout` even if we can't generate an equivalent Rust |
| 3711 |
/// type for a C++ construct. |
| 3712 |
trait ToRustTyOrOpaque: TryToRustTy + ToOpaque { |
| 3713 |
type Extra; |
| 3714 |
|
| 3715 |
fn to_rust_ty_or_opaque( |
| 3716 |
&self, |
| 3717 |
ctx: &BindgenContext, |
| 3718 |
extra: &<Self as ToRustTyOrOpaque>::Extra, |
| 3719 |
) -> proc_macro2::TokenStream; |
| 3720 |
} |
| 3721 |
|
| 3722 |
impl<E, T> ToRustTyOrOpaque for T |
| 3723 |
where |
| 3724 |
T: TryToRustTy<Extra = E> + ToOpaque<Extra = E>, |
| 3725 |
{ |
| 3726 |
type Extra = E; |
| 3727 |
|
| 3728 |
fn to_rust_ty_or_opaque( |
| 3729 |
&self, |
| 3730 |
ctx: &BindgenContext, |
| 3731 |
extra: &E, |
| 3732 |
) -> proc_macro2::TokenStream { |
| 3733 |
self.try_to_rust_ty(ctx, extra) |
| 3734 |
.unwrap_or_else(|_| self.to_opaque(ctx, extra)) |
| 3735 |
} |
| 3736 |
} |
| 3737 |
|
| 3738 |
impl<T> TryToOpaque for T |
| 3739 |
where |
| 3740 |
T: Copy + Into<ItemId>, |
| 3741 |
{ |
| 3742 |
type Extra = (); |
| 3743 |
|
| 3744 |
fn try_get_layout( |
| 3745 |
&self, |
| 3746 |
ctx: &BindgenContext, |
| 3747 |
_: &(), |
| 3748 |
) -> error::Result<Layout> { |
| 3749 |
ctx.resolve_item((*self).into()).try_get_layout(ctx, &()) |
| 3750 |
} |
| 3751 |
} |
| 3752 |
|
| 3753 |
impl<T> TryToRustTy for T |
| 3754 |
where |
| 3755 |
T: Copy + Into<ItemId>, |
| 3756 |
{ |
| 3757 |
type Extra = (); |
| 3758 |
|
| 3759 |
fn try_to_rust_ty( |
| 3760 |
&self, |
| 3761 |
ctx: &BindgenContext, |
| 3762 |
_: &(), |
| 3763 |
) -> error::Result<proc_macro2::TokenStream> { |
| 3764 |
ctx.resolve_item((*self).into()).try_to_rust_ty(ctx, &()) |
| 3765 |
} |
| 3766 |
} |
| 3767 |
|
| 3768 |
impl TryToOpaque for Item { |
| 3769 |
type Extra = (); |
| 3770 |
|
| 3771 |
fn try_get_layout( |
| 3772 |
&self, |
| 3773 |
ctx: &BindgenContext, |
| 3774 |
_: &(), |
| 3775 |
) -> error::Result<Layout> { |
| 3776 |
self.kind().expect_type().try_get_layout(ctx, self) |
| 3777 |
} |
| 3778 |
} |
| 3779 |
|
| 3780 |
impl TryToRustTy for Item { |
| 3781 |
type Extra = (); |
| 3782 |
|
| 3783 |
fn try_to_rust_ty( |
| 3784 |
&self, |
| 3785 |
ctx: &BindgenContext, |
| 3786 |
_: &(), |
| 3787 |
) -> error::Result<proc_macro2::TokenStream> { |
| 3788 |
self.kind().expect_type().try_to_rust_ty(ctx, self) |
| 3789 |
} |
| 3790 |
} |
| 3791 |
|
| 3792 |
impl TryToOpaque for Type { |
| 3793 |
type Extra = Item; |
| 3794 |
|
| 3795 |
fn try_get_layout( |
| 3796 |
&self, |
| 3797 |
ctx: &BindgenContext, |
| 3798 |
_: &Item, |
| 3799 |
) -> error::Result<Layout> { |
| 3800 |
self.layout(ctx).ok_or(error::Error::NoLayoutForOpaqueBlob) |
| 3801 |
} |
| 3802 |
} |
| 3803 |
|
| 3804 |
impl TryToRustTy for Type { |
| 3805 |
type Extra = Item; |
| 3806 |
|
| 3807 |
fn try_to_rust_ty( |
| 3808 |
&self, |
| 3809 |
ctx: &BindgenContext, |
| 3810 |
item: &Item, |
| 3811 |
) -> error::Result<proc_macro2::TokenStream> { |
| 3812 |
use self::helpers::ast_ty::*; |
| 3813 |
|
| 3814 |
match *self.kind() { |
| 3815 |
TypeKind::Void => Ok(c_void(ctx)), |
| 3816 |
// TODO: we should do something smart with nullptr, or maybe *const |
| 3817 |
// c_void is enough? |
| 3818 |
TypeKind::NullPtr => Ok(c_void(ctx).to_ptr(true)), |
| 3819 |
TypeKind::Int(ik) => { |
| 3820 |
match ik { |
| 3821 |
IntKind::Bool => Ok(quote! { bool }), |
| 3822 |
IntKind::Char { .. } => Ok(raw_type(ctx, "c_char")), |
| 3823 |
IntKind::SChar => Ok(raw_type(ctx, "c_schar")), |
| 3824 |
IntKind::UChar => Ok(raw_type(ctx, "c_uchar")), |
| 3825 |
IntKind::Short => Ok(raw_type(ctx, "c_short")), |
| 3826 |
IntKind::UShort => Ok(raw_type(ctx, "c_ushort")), |
| 3827 |
IntKind::Int => Ok(raw_type(ctx, "c_int")), |
| 3828 |
IntKind::UInt => Ok(raw_type(ctx, "c_uint")), |
| 3829 |
IntKind::Long => Ok(raw_type(ctx, "c_long")), |
| 3830 |
IntKind::ULong => Ok(raw_type(ctx, "c_ulong")), |
| 3831 |
IntKind::LongLong => Ok(raw_type(ctx, "c_longlong")), |
| 3832 |
IntKind::ULongLong => Ok(raw_type(ctx, "c_ulonglong")), |
| 3833 |
IntKind::WChar => { |
| 3834 |
let layout = self |
| 3835 |
.layout(ctx) |
| 3836 |
.expect("Couldn't compute wchar_t's layout?"); |
| 3837 |
let ty = Layout::known_type_for_size(ctx, layout.size) |
| 3838 |
.expect("Non-representable wchar_t?"); |
| 3839 |
let ident = ctx.rust_ident_raw(ty); |
| 3840 |
Ok(quote! { #ident }) |
| 3841 |
} |
| 3842 |
|
| 3843 |
IntKind::I8 => Ok(quote! { i8 }), |
| 3844 |
IntKind::U8 => Ok(quote! { u8 }), |
| 3845 |
IntKind::I16 => Ok(quote! { i16 }), |
| 3846 |
IntKind::U16 => Ok(quote! { u16 }), |
| 3847 |
IntKind::I32 => Ok(quote! { i32 }), |
| 3848 |
IntKind::U32 => Ok(quote! { u32 }), |
| 3849 |
IntKind::I64 => Ok(quote! { i64 }), |
| 3850 |
IntKind::U64 => Ok(quote! { u64 }), |
| 3851 |
IntKind::Custom { name, .. } => { |
| 3852 |
Ok(proc_macro2::TokenStream::from_str(name).unwrap()) |
| 3853 |
} |
| 3854 |
IntKind::U128 => { |
| 3855 |
Ok(if ctx.options().rust_features.i128_and_u128 { |
| 3856 |
quote! { u128 } |
| 3857 |
} else { |
| 3858 |
// Best effort thing, but wrong alignment |
| 3859 |
// unfortunately. |
| 3860 |
quote! { [u64; 2] } |
| 3861 |
}) |
| 3862 |
} |
| 3863 |
IntKind::I128 => { |
| 3864 |
Ok(if ctx.options().rust_features.i128_and_u128 { |
| 3865 |
quote! { i128 } |
| 3866 |
} else { |
| 3867 |
quote! { [u64; 2] } |
| 3868 |
}) |
| 3869 |
} |
| 3870 |
} |
| 3871 |
} |
| 3872 |
TypeKind::Float(fk) => { |
| 3873 |
Ok(float_kind_rust_type(ctx, fk, self.layout(ctx))) |
| 3874 |
} |
| 3875 |
TypeKind::Complex(fk) => { |
| 3876 |
let float_path = |
| 3877 |
float_kind_rust_type(ctx, fk, self.layout(ctx)); |
| 3878 |
|
| 3879 |
ctx.generated_bindgen_complex(); |
| 3880 |
Ok(if ctx.options().enable_cxx_namespaces { |
| 3881 |
quote! { |
| 3882 |
root::__BindgenComplex<#float_path> |
| 3883 |
} |
| 3884 |
} else { |
| 3885 |
quote! { |
| 3886 |
__BindgenComplex<#float_path> |
| 3887 |
} |
| 3888 |
}) |
| 3889 |
} |
| 3890 |
TypeKind::Function(ref fs) => { |
| 3891 |
// We can't rely on the sizeof(Option<NonZero<_>>) == |
| 3892 |
// sizeof(NonZero<_>) optimization with opaque blobs (because |
| 3893 |
// they aren't NonZero), so don't *ever* use an or_opaque |
| 3894 |
// variant here. |
| 3895 |
let ty = fs.try_to_rust_ty(ctx, &())?; |
| 3896 |
|
| 3897 |
let prefix = ctx.trait_prefix(); |
| 3898 |
Ok(quote! { |
| 3899 |
::#prefix::option::Option<#ty> |
| 3900 |
}) |
| 3901 |
} |
| 3902 |
TypeKind::Array(item, len) | TypeKind::Vector(item, len) => { |
| 3903 |
let ty = item.try_to_rust_ty(ctx, &())?; |
| 3904 |
Ok(quote! { |
| 3905 |
[ #ty ; #len ] |
| 3906 |
}) |
| 3907 |
} |
| 3908 |
TypeKind::Enum(..) => { |
| 3909 |
let path = item.namespace_aware_canonical_path(ctx); |
| 3910 |
let path = proc_macro2::TokenStream::from_str(&path.join("::")) |
| 3911 |
.unwrap(); |
| 3912 |
Ok(quote!(#path)) |
| 3913 |
} |
| 3914 |
TypeKind::TemplateInstantiation(ref inst) => { |
| 3915 |
inst.try_to_rust_ty(ctx, item) |
| 3916 |
} |
| 3917 |
TypeKind::ResolvedTypeRef(inner) => inner.try_to_rust_ty(ctx, &()), |
| 3918 |
TypeKind::TemplateAlias(..) | |
| 3919 |
TypeKind::Alias(..) | |
| 3920 |
TypeKind::BlockPointer(..) => { |
| 3921 |
if self.is_block_pointer() && !ctx.options().generate_block { |
| 3922 |
let void = c_void(ctx); |
| 3923 |
return Ok(void.to_ptr(/* is_const = */ false)); |
| 3924 |
} |
| 3925 |
|
| 3926 |
if item.is_opaque(ctx, &()) && |
| 3927 |
item.used_template_params(ctx) |
| 3928 |
.into_iter() |
| 3929 |
.any(|param| param.is_template_param(ctx, &())) |
| 3930 |
{ |
| 3931 |
self.try_to_opaque(ctx, item) |
| 3932 |
} else if let Some(ty) = self |
| 3933 |
.name() |
| 3934 |
.and_then(|name| utils::type_from_named(ctx, name)) |
| 3935 |
{ |
| 3936 |
Ok(ty) |
| 3937 |
} else { |
| 3938 |
utils::build_path(item, ctx) |
| 3939 |
} |
| 3940 |
} |
| 3941 |
TypeKind::Comp(ref info) => { |
| 3942 |
let template_params = item.all_template_params(ctx); |
| 3943 |
if info.has_non_type_template_params() || |
| 3944 |
(item.is_opaque(ctx, &()) && !template_params.is_empty()) |
| 3945 |
{ |
| 3946 |
return self.try_to_opaque(ctx, item); |
| 3947 |
} |
| 3948 |
|
| 3949 |
utils::build_path(item, ctx) |
| 3950 |
} |
| 3951 |
TypeKind::Opaque => self.try_to_opaque(ctx, item), |
| 3952 |
TypeKind::Pointer(inner) | TypeKind::Reference(inner) => { |
| 3953 |
let is_const = ctx.resolve_type(inner).is_const(); |
| 3954 |
|
| 3955 |
let inner = |
| 3956 |
inner.into_resolver().through_type_refs().resolve(ctx); |
| 3957 |
let inner_ty = inner.expect_type(); |
| 3958 |
|
| 3959 |
let is_objc_pointer = |
| 3960 |
matches!(inner_ty.kind(), TypeKind::ObjCInterface(..)); |
| 3961 |
|
| 3962 |
// Regardless if we can properly represent the inner type, we |
| 3963 |
// should always generate a proper pointer here, so use |
| 3964 |
// infallible conversion of the inner type. |
| 3965 |
let mut ty = inner.to_rust_ty_or_opaque(ctx, &()); |
| 3966 |
ty.append_implicit_template_params(ctx, inner); |
| 3967 |
|
| 3968 |
// Avoid the first function pointer level, since it's already |
| 3969 |
// represented in Rust. |
| 3970 |
if inner_ty.canonical_type(ctx).is_function() || is_objc_pointer |
| 3971 |
{ |
| 3972 |
Ok(ty) |
| 3973 |
} else { |
| 3974 |
Ok(ty.to_ptr(is_const)) |
| 3975 |
} |
| 3976 |
} |
| 3977 |
TypeKind::TypeParam => { |
| 3978 |
let name = item.canonical_name(ctx); |
| 3979 |
let ident = ctx.rust_ident(name); |
| 3980 |
Ok(quote! { |
| 3981 |
#ident |
| 3982 |
}) |
| 3983 |
} |
| 3984 |
TypeKind::ObjCSel => Ok(quote! { |
| 3985 |
objc::runtime::Sel |
| 3986 |
}), |
| 3987 |
TypeKind::ObjCId => Ok(quote! { |
| 3988 |
id |
| 3989 |
}), |
| 3990 |
TypeKind::ObjCInterface(ref interface) => { |
| 3991 |
let name = ctx.rust_ident(interface.name()); |
| 3992 |
Ok(quote! { |
| 3993 |
#name |
| 3994 |
}) |
| 3995 |
} |
| 3996 |
ref u @ TypeKind::UnresolvedTypeRef(..) => { |
| 3997 |
unreachable!("Should have been resolved after parsing {:?}!", u) |
| 3998 |
} |
| 3999 |
} |
| 4000 |
} |
| 4001 |
} |
| 4002 |
|
| 4003 |
impl TryToOpaque for TemplateInstantiation { |
| 4004 |
type Extra = Item; |
| 4005 |
|
| 4006 |
fn try_get_layout( |
| 4007 |
&self, |
| 4008 |
ctx: &BindgenContext, |
| 4009 |
item: &Item, |
| 4010 |
) -> error::Result<Layout> { |
| 4011 |
item.expect_type() |
| 4012 |
.layout(ctx) |
| 4013 |
.ok_or(error::Error::NoLayoutForOpaqueBlob) |
| 4014 |
} |
| 4015 |
} |
| 4016 |
|
| 4017 |
impl TryToRustTy for TemplateInstantiation { |
| 4018 |
type Extra = Item; |
| 4019 |
|
| 4020 |
fn try_to_rust_ty( |
| 4021 |
&self, |
| 4022 |
ctx: &BindgenContext, |
| 4023 |
item: &Item, |
| 4024 |
) -> error::Result<proc_macro2::TokenStream> { |
| 4025 |
if self.is_opaque(ctx, item) { |
| 4026 |
return Err(error::Error::InstantiationOfOpaqueType); |
| 4027 |
} |
| 4028 |
|
| 4029 |
let def = self |
| 4030 |
.template_definition() |
| 4031 |
.into_resolver() |
| 4032 |
.through_type_refs() |
| 4033 |
.resolve(ctx); |
| 4034 |
|
| 4035 |
let mut ty = quote! {}; |
| 4036 |
let def_path = def.namespace_aware_canonical_path(ctx); |
| 4037 |
ty.append_separated( |
| 4038 |
def_path.into_iter().map(|p| ctx.rust_ident(p)), |
| 4039 |
quote!(::), |
| 4040 |
); |
| 4041 |
|
| 4042 |
let def_params = def.self_template_params(ctx); |
| 4043 |
if def_params.is_empty() { |
| 4044 |
// This can happen if we generated an opaque type for a partial |
| 4045 |
// template specialization, and we've hit an instantiation of |
| 4046 |
// that partial specialization. |
| 4047 |
extra_assert!(def.is_opaque(ctx, &())); |
| 4048 |
return Err(error::Error::InstantiationOfOpaqueType); |
| 4049 |
} |
| 4050 |
|
| 4051 |
// TODO: If the definition type is a template class/struct |
| 4052 |
// definition's member template definition, it could rely on |
| 4053 |
// generic template parameters from its outer template |
| 4054 |
// class/struct. When we emit bindings for it, it could require |
| 4055 |
// *more* type arguments than we have here, and we will need to |
| 4056 |
// reconstruct them somehow. We don't have any means of doing |
| 4057 |
// that reconstruction at this time. |
| 4058 |
|
| 4059 |
let template_args = self |
| 4060 |
.template_arguments() |
| 4061 |
.iter() |
| 4062 |
.zip(def_params.iter()) |
| 4063 |
// Only pass type arguments for the type parameters that |
| 4064 |
// the def uses. |
| 4065 |
.filter(|&(_, param)| ctx.uses_template_parameter(def.id(), *param)) |
| 4066 |
.map(|(arg, _)| { |
| 4067 |
let arg = arg.into_resolver().through_type_refs().resolve(ctx); |
| 4068 |
let mut ty = arg.try_to_rust_ty(ctx, &())?; |
| 4069 |
ty.append_implicit_template_params(ctx, arg); |
| 4070 |
Ok(ty) |
| 4071 |
}) |
| 4072 |
.collect::<error::Result<Vec<_>>>()?; |
| 4073 |
|
| 4074 |
if template_args.is_empty() { |
| 4075 |
return Ok(ty); |
| 4076 |
} |
| 4077 |
|
| 4078 |
Ok(quote! { |
| 4079 |
#ty < #( #template_args ),* > |
| 4080 |
}) |
| 4081 |
} |
| 4082 |
} |
| 4083 |
|
| 4084 |
impl TryToRustTy for FunctionSig { |
| 4085 |
type Extra = (); |
| 4086 |
|
| 4087 |
fn try_to_rust_ty( |
| 4088 |
&self, |
| 4089 |
ctx: &BindgenContext, |
| 4090 |
_: &(), |
| 4091 |
) -> error::Result<proc_macro2::TokenStream> { |
| 4092 |
// TODO: we might want to consider ignoring the reference return value. |
| 4093 |
let ret = utils::fnsig_return_ty(ctx, self); |
| 4094 |
let arguments = utils::fnsig_arguments(ctx, self); |
| 4095 |
|
| 4096 |
match self.abi(ctx, None) { |
| 4097 |
ClangAbi::Known(Abi::ThisCall) |
| 4098 |
if !ctx.options().rust_features().thiscall_abi => |
| 4099 |
{ |
| 4100 |
warn!("Skipping function with thiscall ABI that isn't supported by the configured Rust target"); |
| 4101 |
Ok(proc_macro2::TokenStream::new()) |
| 4102 |
} |
| 4103 |
ClangAbi::Known(Abi::Vectorcall) |
| 4104 |
if !ctx.options().rust_features().vectorcall_abi => |
| 4105 |
{ |
| 4106 |
warn!("Skipping function with vectorcall ABI that isn't supported by the configured Rust target"); |
| 4107 |
Ok(proc_macro2::TokenStream::new()) |
| 4108 |
} |
| 4109 |
ClangAbi::Known(Abi::CUnwind) |
| 4110 |
if !ctx.options().rust_features().c_unwind_abi => |
| 4111 |
{ |
| 4112 |
warn!("Skipping function with C-unwind ABI that isn't supported by the configured Rust target"); |
| 4113 |
Ok(proc_macro2::TokenStream::new()) |
| 4114 |
} |
| 4115 |
ClangAbi::Known(Abi::EfiApi) |
| 4116 |
if !ctx.options().rust_features().abi_efiapi => |
| 4117 |
{ |
| 4118 |
warn!("Skipping function with efiapi ABI that isn't supported by the configured Rust target"); |
| 4119 |
Ok(proc_macro2::TokenStream::new()) |
| 4120 |
} |
| 4121 |
abi => Ok(quote! { |
| 4122 |
unsafe extern #abi fn ( #( #arguments ),* ) #ret |
| 4123 |
}), |
| 4124 |
} |
| 4125 |
} |
| 4126 |
} |
| 4127 |
|
| 4128 |
impl CodeGenerator for Function { |
| 4129 |
type Extra = Item; |
| 4130 |
|
| 4131 |
/// If we've actually generated the symbol, the number of times we've seen |
| 4132 |
/// it. |
| 4133 |
type Return = Option<u32>; |
| 4134 |
|
| 4135 |
fn codegen( |
| 4136 |
&self, |
| 4137 |
ctx: &BindgenContext, |
| 4138 |
result: &mut CodegenResult<'_>, |
| 4139 |
item: &Item, |
| 4140 |
) -> Self::Return { |
| 4141 |
debug!("<Function as CodeGenerator>::codegen: item = {:?}", item); |
| 4142 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 4143 |
|
| 4144 |
let is_internal = matches!(self.linkage(), Linkage::Internal); |
| 4145 |
|
| 4146 |
if is_internal && !ctx.options().wrap_static_fns { |
| 4147 |
// We can't do anything with Internal functions if we are not wrapping them so just |
| 4148 |
// avoid generating anything for them. |
| 4149 |
return None; |
| 4150 |
} |
| 4151 |
|
| 4152 |
// Pure virtual methods have no actual symbol, so we can't generate |
| 4153 |
// something meaningful for them. |
| 4154 |
let is_dynamic_function = match self.kind() { |
| 4155 |
FunctionKind::Method(ref method_kind) |
| 4156 |
if method_kind.is_pure_virtual() => |
| 4157 |
{ |
| 4158 |
return None; |
| 4159 |
} |
| 4160 |
FunctionKind::Function => { |
| 4161 |
ctx.options().dynamic_library_name.is_some() |
| 4162 |
} |
| 4163 |
_ => false, |
| 4164 |
}; |
| 4165 |
|
| 4166 |
// Similar to static member variables in a class template, we can't |
| 4167 |
// generate bindings to template functions, because the set of |
| 4168 |
// instantiations is open ended and we have no way of knowing which |
| 4169 |
// monomorphizations actually exist. |
| 4170 |
if !item.all_template_params(ctx).is_empty() { |
| 4171 |
return None; |
| 4172 |
} |
| 4173 |
|
| 4174 |
let name = self.name(); |
| 4175 |
let mut canonical_name = item.canonical_name(ctx); |
| 4176 |
let mangled_name = self.mangled_name(); |
| 4177 |
|
| 4178 |
{ |
| 4179 |
let seen_symbol_name = mangled_name.unwrap_or(&canonical_name); |
| 4180 |
|
| 4181 |
// TODO: Maybe warn here if there's a type/argument mismatch, or |
| 4182 |
// something? |
| 4183 |
if result.seen_function(seen_symbol_name) { |
| 4184 |
return None; |
| 4185 |
} |
| 4186 |
result.saw_function(seen_symbol_name); |
| 4187 |
} |
| 4188 |
|
| 4189 |
let signature_item = ctx.resolve_item(self.signature()); |
| 4190 |
let signature = signature_item.kind().expect_type().canonical_type(ctx); |
| 4191 |
let signature = match *signature.kind() { |
| 4192 |
TypeKind::Function(ref sig) => sig, |
| 4193 |
_ => panic!("Signature kind is not a Function: {:?}", signature), |
| 4194 |
}; |
| 4195 |
|
| 4196 |
let args = utils::fnsig_arguments(ctx, signature); |
| 4197 |
let ret = utils::fnsig_return_ty(ctx, signature); |
| 4198 |
|
| 4199 |
let mut attributes = vec![]; |
| 4200 |
|
| 4201 |
if ctx.options().rust_features().must_use_function { |
| 4202 |
let must_use = signature.must_use() || { |
| 4203 |
let ret_ty = signature |
| 4204 |
.return_type() |
| 4205 |
.into_resolver() |
| 4206 |
.through_type_refs() |
| 4207 |
.resolve(ctx); |
| 4208 |
ret_ty.must_use(ctx) |
| 4209 |
}; |
| 4210 |
|
| 4211 |
if must_use { |
| 4212 |
attributes.push(attributes::must_use()); |
| 4213 |
} |
| 4214 |
} |
| 4215 |
|
| 4216 |
if let Some(comment) = item.comment(ctx) { |
| 4217 |
attributes.push(attributes::doc(comment)); |
| 4218 |
} |
| 4219 |
|
| 4220 |
let abi = match signature.abi(ctx, Some(name)) { |
| 4221 |
ClangAbi::Known(Abi::ThisCall) |
| 4222 |
if !ctx.options().rust_features().thiscall_abi => |
| 4223 |
{ |
| 4224 |
unsupported_abi_diagnostic::<false>( |
| 4225 |
name, |
| 4226 |
item.location(), |
| 4227 |
"thiscall", |
| 4228 |
ctx, |
| 4229 |
); |
| 4230 |
return None; |
| 4231 |
} |
| 4232 |
ClangAbi::Known(Abi::Vectorcall) |
| 4233 |
if !ctx.options().rust_features().vectorcall_abi => |
| 4234 |
{ |
| 4235 |
unsupported_abi_diagnostic::<false>( |
| 4236 |
name, |
| 4237 |
item.location(), |
| 4238 |
"vectorcall", |
| 4239 |
ctx, |
| 4240 |
); |
| 4241 |
return None; |
| 4242 |
} |
| 4243 |
ClangAbi::Known(Abi::CUnwind) |
| 4244 |
if !ctx.options().rust_features().c_unwind_abi => |
| 4245 |
{ |
| 4246 |
unsupported_abi_diagnostic::<false>( |
| 4247 |
name, |
| 4248 |
item.location(), |
| 4249 |
"C-unwind", |
| 4250 |
ctx, |
| 4251 |
); |
| 4252 |
return None; |
| 4253 |
} |
| 4254 |
ClangAbi::Known(Abi::EfiApi) |
| 4255 |
if !ctx.options().rust_features().abi_efiapi => |
| 4256 |
{ |
| 4257 |
unsupported_abi_diagnostic::<true>( |
| 4258 |
name, |
| 4259 |
item.location(), |
| 4260 |
"efiapi", |
| 4261 |
ctx, |
| 4262 |
); |
| 4263 |
return None; |
| 4264 |
} |
| 4265 |
ClangAbi::Known(Abi::Win64) if signature.is_variadic() => { |
| 4266 |
unsupported_abi_diagnostic::<true>( |
| 4267 |
name, |
| 4268 |
item.location(), |
| 4269 |
"Win64", |
| 4270 |
ctx, |
| 4271 |
); |
| 4272 |
return None; |
| 4273 |
} |
| 4274 |
ClangAbi::Unknown(unknown_abi) => { |
| 4275 |
panic!( |
| 4276 |
"Invalid or unknown abi {:?} for function {:?} ({:?})", |
| 4277 |
unknown_abi, canonical_name, self |
| 4278 |
); |
| 4279 |
} |
| 4280 |
abi => abi, |
| 4281 |
}; |
| 4282 |
|
| 4283 |
if is_internal && ctx.options().wrap_static_fns { |
| 4284 |
result.items_to_serialize.push(item.id()); |
| 4285 |
} |
| 4286 |
|
| 4287 |
// Handle overloaded functions by giving each overload its own unique |
| 4288 |
// suffix. |
| 4289 |
let times_seen = result.overload_number(&canonical_name); |
| 4290 |
if times_seen > 0 { |
| 4291 |
write!(&mut canonical_name, "{}", times_seen).unwrap(); |
| 4292 |
} |
| 4293 |
|
| 4294 |
let mut has_link_name_attr = false; |
| 4295 |
if let Some(link_name) = self.link_name() { |
| 4296 |
attributes.push(attributes::link_name::<false>(link_name)); |
| 4297 |
has_link_name_attr = true; |
| 4298 |
} else { |
| 4299 |
let link_name = mangled_name.unwrap_or(name); |
| 4300 |
if !is_dynamic_function && |
| 4301 |
!utils::names_will_be_identical_after_mangling( |
| 4302 |
&canonical_name, |
| 4303 |
link_name, |
| 4304 |
Some(abi), |
| 4305 |
) |
| 4306 |
{ |
| 4307 |
attributes.push(attributes::link_name::<false>(link_name)); |
| 4308 |
has_link_name_attr = true; |
| 4309 |
} |
| 4310 |
} |
| 4311 |
|
| 4312 |
// Unfortunately this can't piggyback on the `attributes` list because |
| 4313 |
// the #[link(wasm_import_module)] needs to happen before the `extern |
| 4314 |
// "C"` block. It doesn't get picked up properly otherwise |
| 4315 |
let wasm_link_attribute = |
| 4316 |
ctx.options().wasm_import_module_name.as_ref().map(|name| { |
| 4317 |
quote! { #[link(wasm_import_module = #name)] } |
| 4318 |
}); |
| 4319 |
|
| 4320 |
if is_internal && ctx.options().wrap_static_fns && !has_link_name_attr { |
| 4321 |
let name = canonical_name.clone() + ctx.wrap_static_fns_suffix(); |
| 4322 |
attributes.push(attributes::link_name::<true>(&name)); |
| 4323 |
} |
| 4324 |
|
| 4325 |
let ident = ctx.rust_ident(canonical_name); |
| 4326 |
let tokens = quote! { |
| 4327 |
#wasm_link_attribute |
| 4328 |
extern #abi { |
| 4329 |
#(#attributes)* |
| 4330 |
pub fn #ident ( #( #args ),* ) #ret; |
| 4331 |
} |
| 4332 |
}; |
| 4333 |
|
| 4334 |
// If we're doing dynamic binding generation, add to the dynamic items. |
| 4335 |
if is_dynamic_function { |
| 4336 |
let args_identifiers = |
| 4337 |
utils::fnsig_argument_identifiers(ctx, signature); |
| 4338 |
let ret_ty = utils::fnsig_return_ty(ctx, signature); |
| 4339 |
result.dynamic_items().push( |
| 4340 |
ident, |
| 4341 |
abi, |
| 4342 |
signature.is_variadic(), |
| 4343 |
ctx.options().dynamic_link_require_all, |
| 4344 |
args, |
| 4345 |
args_identifiers, |
| 4346 |
ret, |
| 4347 |
ret_ty, |
| 4348 |
attributes, |
| 4349 |
ctx, |
| 4350 |
); |
| 4351 |
} else { |
| 4352 |
result.push(tokens); |
| 4353 |
} |
| 4354 |
Some(times_seen) |
| 4355 |
} |
| 4356 |
} |
| 4357 |
|
| 4358 |
fn unsupported_abi_diagnostic<const VARIADIC: bool>( |
| 4359 |
fn_name: &str, |
| 4360 |
_location: Option<&crate::clang::SourceLocation>, |
| 4361 |
abi: &str, |
| 4362 |
_ctx: &BindgenContext, |
| 4363 |
) { |
| 4364 |
warn!( |
| 4365 |
"Skipping {}function `{}` with the {} ABI that isn't supported by the configured Rust target", |
| 4366 |
if VARIADIC { "variadic " } else { "" }, |
| 4367 |
fn_name, |
| 4368 |
abi |
| 4369 |
); |
| 4370 |
|
| 4371 |
#[cfg(feature = "experimental")] |
| 4372 |
if _ctx.options().emit_diagnostics { |
| 4373 |
use crate::diagnostics::{get_line, Diagnostic, Level, Slice}; |
| 4374 |
|
| 4375 |
let mut diag = Diagnostic::default(); |
| 4376 |
diag |
| 4377 |
.with_title(format!( |
| 4378 |
"The `{}` {}function uses the {} ABI which is not supported by the configured Rust target.", |
| 4379 |
fn_name, |
| 4380 |
if VARIADIC { "variadic " } else { "" }, |
| 4381 |
abi), Level::Warn) |
| 4382 |
.add_annotation("No code will be generated for this function.", Level::Warn) |
| 4383 |
.add_annotation(format!("The configured Rust version is {}.", String::from(_ctx.options().rust_target)), Level::Note); |
| 4384 |
|
| 4385 |
if let Some(loc) = _location { |
| 4386 |
let (file, line, col, _) = loc.location(); |
| 4387 |
|
| 4388 |
if let Some(filename) = file.name() { |
| 4389 |
if let Ok(Some(source)) = get_line(&filename, line) { |
| 4390 |
let mut slice = Slice::default(); |
| 4391 |
slice |
| 4392 |
.with_source(source) |
| 4393 |
.with_location(filename, line, col); |
| 4394 |
diag.add_slice(slice); |
| 4395 |
} |
| 4396 |
} |
| 4397 |
} |
| 4398 |
|
| 4399 |
diag.display() |
| 4400 |
} |
| 4401 |
} |
| 4402 |
|
| 4403 |
fn objc_method_codegen( |
| 4404 |
ctx: &BindgenContext, |
| 4405 |
method: &ObjCMethod, |
| 4406 |
methods: &mut Vec<proc_macro2::TokenStream>, |
| 4407 |
class_name: Option<&str>, |
| 4408 |
rust_class_name: &str, |
| 4409 |
prefix: &str, |
| 4410 |
) { |
| 4411 |
// This would ideally resolve the method into an Item, and use |
| 4412 |
// Item::process_before_codegen; however, ObjC methods are not currently |
| 4413 |
// made into function items. |
| 4414 |
let name = format!("{}::{}{}", rust_class_name, prefix, method.rust_name()); |
| 4415 |
if ctx.options().blocklisted_items.matches(name) { |
| 4416 |
return; |
| 4417 |
} |
| 4418 |
|
| 4419 |
let signature = method.signature(); |
| 4420 |
let fn_args = utils::fnsig_arguments(ctx, signature); |
| 4421 |
let fn_ret = utils::fnsig_return_ty(ctx, signature); |
| 4422 |
|
| 4423 |
let sig = if method.is_class_method() { |
| 4424 |
quote! { |
| 4425 |
( #( #fn_args ),* ) #fn_ret |
| 4426 |
} |
| 4427 |
} else { |
| 4428 |
let self_arr = [quote! { &self }]; |
| 4429 |
let args = self_arr.iter().chain(fn_args.iter()); |
| 4430 |
quote! { |
| 4431 |
( #( #args ),* ) #fn_ret |
| 4432 |
} |
| 4433 |
}; |
| 4434 |
|
| 4435 |
let methods_and_args = method.format_method_call(&fn_args); |
| 4436 |
|
| 4437 |
let body = { |
| 4438 |
let body = if method.is_class_method() { |
| 4439 |
let class_name = ctx.rust_ident( |
| 4440 |
class_name |
| 4441 |
.expect("Generating a class method without class name?"), |
| 4442 |
); |
| 4443 |
quote!(msg_send!(class!(#class_name), #methods_and_args)) |
| 4444 |
} else { |
| 4445 |
quote!(msg_send!(*self, #methods_and_args)) |
| 4446 |
}; |
| 4447 |
|
| 4448 |
ctx.wrap_unsafe_ops(body) |
| 4449 |
}; |
| 4450 |
|
| 4451 |
let method_name = |
| 4452 |
ctx.rust_ident(format!("{}{}", prefix, method.rust_name())); |
| 4453 |
|
| 4454 |
methods.push(quote! { |
| 4455 |
unsafe fn #method_name #sig where <Self as std::ops::Deref>::Target: objc::Message + Sized { |
| 4456 |
#body |
| 4457 |
} |
| 4458 |
}); |
| 4459 |
} |
| 4460 |
|
| 4461 |
impl CodeGenerator for ObjCInterface { |
| 4462 |
type Extra = Item; |
| 4463 |
type Return = (); |
| 4464 |
|
| 4465 |
fn codegen( |
| 4466 |
&self, |
| 4467 |
ctx: &BindgenContext, |
| 4468 |
result: &mut CodegenResult<'_>, |
| 4469 |
item: &Item, |
| 4470 |
) { |
| 4471 |
debug_assert!(item.is_enabled_for_codegen(ctx)); |
| 4472 |
|
| 4473 |
let mut impl_items = vec![]; |
| 4474 |
let rust_class_name = item.path_for_allowlisting(ctx)[1..].join("::"); |
| 4475 |
|
| 4476 |
for method in self.methods() { |
| 4477 |
objc_method_codegen( |
| 4478 |
ctx, |
| 4479 |
method, |
| 4480 |
&mut impl_items, |
| 4481 |
None, |
| 4482 |
&rust_class_name, |
| 4483 |
"", |
| 4484 |
); |
| 4485 |
} |
| 4486 |
|
| 4487 |
for class_method in self.class_methods() { |
| 4488 |
let ambiquity = self |
| 4489 |
.methods() |
| 4490 |
.iter() |
| 4491 |
.map(|m| m.rust_name()) |
| 4492 |
.any(|x| x == class_method.rust_name()); |
| 4493 |
let prefix = if ambiquity { "class_" } else { "" }; |
| 4494 |
objc_method_codegen( |
| 4495 |
ctx, |
| 4496 |
class_method, |
| 4497 |
&mut impl_items, |
| 4498 |
Some(self.name()), |
| 4499 |
&rust_class_name, |
| 4500 |
prefix, |
| 4501 |
); |
| 4502 |
} |
| 4503 |
|
| 4504 |
let trait_name = ctx.rust_ident(self.rust_name()); |
| 4505 |
let trait_constraints = quote! { |
| 4506 |
Sized + std::ops::Deref |
| 4507 |
}; |
| 4508 |
let trait_block = if self.is_template() { |
| 4509 |
let template_names: Vec<Ident> = self |
| 4510 |
.template_names |
| 4511 |
.iter() |
| 4512 |
.map(|g| ctx.rust_ident(g)) |
| 4513 |
.collect(); |
| 4514 |
|
| 4515 |
quote! { |
| 4516 |
pub trait #trait_name <#(#template_names:'static),*> : #trait_constraints { |
| 4517 |
#( #impl_items )* |
| 4518 |
} |
| 4519 |
} |
| 4520 |
} else { |
| 4521 |
quote! { |
| 4522 |
pub trait #trait_name : #trait_constraints { |
| 4523 |
#( #impl_items )* |
| 4524 |
} |
| 4525 |
} |
| 4526 |
}; |
| 4527 |
|
| 4528 |
let class_name = ctx.rust_ident(self.name()); |
| 4529 |
if !self.is_category() && !self.is_protocol() { |
| 4530 |
let struct_block = quote! { |
| 4531 |
#[repr(transparent)] |
| 4532 |
#[derive(Debug, Copy, Clone)] |
| 4533 |
pub struct #class_name(pub id); |
| 4534 |
impl std::ops::Deref for #class_name { |
| 4535 |
type Target = objc::runtime::Object; |
| 4536 |
fn deref(&self) -> &Self::Target { |
| 4537 |
unsafe { |
| 4538 |
&*self.0 |
| 4539 |
} |
| 4540 |
} |
| 4541 |
} |
| 4542 |
unsafe impl objc::Message for #class_name { } |
| 4543 |
impl #class_name { |
| 4544 |
pub fn alloc() -> Self { |
| 4545 |
Self(unsafe { |
| 4546 |
msg_send!(class!(#class_name), alloc) |
| 4547 |
}) |
| 4548 |
} |
| 4549 |
} |
| 4550 |
}; |
| 4551 |
result.push(struct_block); |
| 4552 |
let mut protocol_set: HashSet<ItemId> = Default::default(); |
| 4553 |
for protocol_id in self.conforms_to.iter() { |
| 4554 |
protocol_set.insert(*protocol_id); |
| 4555 |
let protocol_name = ctx.rust_ident( |
| 4556 |
ctx.resolve_type(protocol_id.expect_type_id(ctx)) |
| 4557 |
.name() |
| 4558 |
.unwrap(), |
| 4559 |
); |
| 4560 |
let impl_trait = quote! { |
| 4561 |
impl #protocol_name for #class_name { } |
| 4562 |
}; |
| 4563 |
result.push(impl_trait); |
| 4564 |
} |
| 4565 |
let mut parent_class = self.parent_class; |
| 4566 |
while let Some(parent_id) = parent_class { |
| 4567 |
let parent = parent_id |
| 4568 |
.expect_type_id(ctx) |
| 4569 |
.into_resolver() |
| 4570 |
.through_type_refs() |
| 4571 |
.resolve(ctx) |
| 4572 |
.expect_type() |
| 4573 |
.kind(); |
| 4574 |
|
| 4575 |
let parent = match parent { |
| 4576 |
TypeKind::ObjCInterface(ref parent) => parent, |
| 4577 |
_ => break, |
| 4578 |
}; |
| 4579 |
parent_class = parent.parent_class; |
| 4580 |
|
| 4581 |
let parent_name = ctx.rust_ident(parent.rust_name()); |
| 4582 |
let impl_trait = if parent.is_template() { |
| 4583 |
let template_names: Vec<Ident> = parent |
| 4584 |
.template_names |
| 4585 |
.iter() |
| 4586 |
.map(|g| ctx.rust_ident(g)) |
| 4587 |
.collect(); |
| 4588 |
quote! { |
| 4589 |
impl <#(#template_names :'static),*> #parent_name <#(#template_names),*> for #class_name { |
| 4590 |
} |
| 4591 |
} |
| 4592 |
} else { |
| 4593 |
quote! { |
| 4594 |
impl #parent_name for #class_name { } |
| 4595 |
} |
| 4596 |
}; |
| 4597 |
result.push(impl_trait); |
| 4598 |
for protocol_id in parent.conforms_to.iter() { |
| 4599 |
if protocol_set.insert(*protocol_id) { |
| 4600 |
let protocol_name = ctx.rust_ident( |
| 4601 |
ctx.resolve_type(protocol_id.expect_type_id(ctx)) |
| 4602 |
.name() |
| 4603 |
.unwrap(), |
| 4604 |
); |
| 4605 |
let impl_trait = quote! { |
| 4606 |
impl #protocol_name for #class_name { } |
| 4607 |
}; |
| 4608 |
result.push(impl_trait); |
| 4609 |
} |
| 4610 |
} |
| 4611 |
if !parent.is_template() { |
| 4612 |
let parent_struct_name = parent.name(); |
| 4613 |
let child_struct_name = self.name(); |
| 4614 |
let parent_struct = ctx.rust_ident(parent_struct_name); |
| 4615 |
let from_block = quote! { |
| 4616 |
impl From<#class_name> for #parent_struct { |
| 4617 |
fn from(child: #class_name) -> #parent_struct { |
| 4618 |
#parent_struct(child.0) |
| 4619 |
} |
| 4620 |
} |
| 4621 |
}; |
| 4622 |
result.push(from_block); |
| 4623 |
|
| 4624 |
let error_msg = format!( |
| 4625 |
"This {} cannot be downcasted to {}", |
| 4626 |
parent_struct_name, child_struct_name |
| 4627 |
); |
| 4628 |
let try_into_block = quote! { |
| 4629 |
impl std::convert::TryFrom<#parent_struct> for #class_name { |
| 4630 |
type Error = &'static str; |
| 4631 |
fn try_from(parent: #parent_struct) -> Result<#class_name, Self::Error> { |
| 4632 |
let is_kind_of : bool = unsafe { msg_send!(parent, isKindOfClass:class!(#class_name))}; |
| 4633 |
if is_kind_of { |
| 4634 |
Ok(#class_name(parent.0)) |
| 4635 |
} else { |
| 4636 |
Err(#error_msg) |
| 4637 |
} |
| 4638 |
} |
| 4639 |
} |
| 4640 |
}; |
| 4641 |
result.push(try_into_block); |
| 4642 |
} |
| 4643 |
} |
| 4644 |
} |
| 4645 |
|
| 4646 |
if !self.is_protocol() { |
| 4647 |
let impl_block = if self.is_template() { |
| 4648 |
let template_names: Vec<Ident> = self |
| 4649 |
.template_names |
| 4650 |
.iter() |
| 4651 |
.map(|g| ctx.rust_ident(g)) |
| 4652 |
.collect(); |
| 4653 |
quote! { |
| 4654 |
impl <#(#template_names :'static),*> #trait_name <#(#template_names),*> for #class_name { |
| 4655 |
} |
| 4656 |
} |
| 4657 |
} else { |
| 4658 |
quote! { |
| 4659 |
impl #trait_name for #class_name { |
| 4660 |
} |
| 4661 |
} |
| 4662 |
}; |
| 4663 |
result.push(impl_block); |
| 4664 |
} |
| 4665 |
|
| 4666 |
result.push(trait_block); |
| 4667 |
result.saw_objc(); |
| 4668 |
} |
| 4669 |
} |
| 4670 |
|
| 4671 |
pub(crate) fn codegen( |
| 4672 |
context: BindgenContext, |
| 4673 |
) -> Result<(proc_macro2::TokenStream, BindgenOptions), CodegenError> { |
| 4674 |
context.gen(|context| { |
| 4675 |
let _t = context.timer("codegen"); |
| 4676 |
let counter = Cell::new(0); |
| 4677 |
let mut result = CodegenResult::new(&counter); |
| 4678 |
|
| 4679 |
debug!("codegen: {:?}", context.options()); |
| 4680 |
|
| 4681 |
if context.options().emit_ir { |
| 4682 |
let codegen_items = context.codegen_items(); |
| 4683 |
for (id, item) in context.items() { |
| 4684 |
if codegen_items.contains(&id) { |
| 4685 |
println!("ir: {:?} = {:#?}", id, item); |
| 4686 |
} |
| 4687 |
} |
| 4688 |
} |
| 4689 |
|
| 4690 |
if let Some(path) = context.options().emit_ir_graphviz.as_ref() { |
| 4691 |
match dot::write_dot_file(context, path) { |
| 4692 |
Ok(()) => info!( |
| 4693 |
"Your dot file was generated successfully into: {}", |
| 4694 |
path |
| 4695 |
), |
| 4696 |
Err(e) => warn!("{}", e), |
| 4697 |
} |
| 4698 |
} |
| 4699 |
|
| 4700 |
if let Some(spec) = context.options().depfile.as_ref() { |
| 4701 |
match spec.write(context.deps()) { |
| 4702 |
Ok(()) => info!( |
| 4703 |
"Your depfile was generated successfully into: {}", |
| 4704 |
spec.depfile_path.display() |
| 4705 |
), |
| 4706 |
Err(e) => warn!("{}", e), |
| 4707 |
} |
| 4708 |
} |
| 4709 |
|
| 4710 |
context.resolve_item(context.root_module()).codegen( |
| 4711 |
context, |
| 4712 |
&mut result, |
| 4713 |
&(), |
| 4714 |
); |
| 4715 |
|
| 4716 |
if let Some(ref lib_name) = context.options().dynamic_library_name { |
| 4717 |
let lib_ident = context.rust_ident(lib_name); |
| 4718 |
let dynamic_items_tokens = |
| 4719 |
result.dynamic_items().get_tokens(lib_ident, context); |
| 4720 |
result.push(dynamic_items_tokens); |
| 4721 |
} |
| 4722 |
|
| 4723 |
utils::serialize_items(&result, context)?; |
| 4724 |
|
| 4725 |
Ok(postprocessing::postprocessing( |
| 4726 |
result.items, |
| 4727 |
context.options(), |
| 4728 |
)) |
| 4729 |
}) |
| 4730 |
} |
| 4731 |
|
| 4732 |
pub(crate) mod utils { |
| 4733 |
use super::serialize::CSerialize; |
| 4734 |
use super::{error, CodegenError, CodegenResult, ToRustTyOrOpaque}; |
| 4735 |
use crate::ir::context::BindgenContext; |
| 4736 |
use crate::ir::function::{Abi, ClangAbi, FunctionSig}; |
| 4737 |
use crate::ir::item::{Item, ItemCanonicalPath}; |
| 4738 |
use crate::ir::ty::TypeKind; |
| 4739 |
use crate::{args_are_cpp, file_is_cpp}; |
| 4740 |
use std::borrow::Cow; |
| 4741 |
use std::io::Write; |
| 4742 |
use std::mem; |
| 4743 |
use std::path::PathBuf; |
| 4744 |
use std::str::FromStr; |
| 4745 |
|
| 4746 |
pub(super) fn serialize_items( |
| 4747 |
result: &CodegenResult, |
| 4748 |
context: &BindgenContext, |
| 4749 |
) -> Result<(), CodegenError> { |
| 4750 |
if result.items_to_serialize.is_empty() { |
| 4751 |
return Ok(()); |
| 4752 |
} |
| 4753 |
|
| 4754 |
let path = context |
| 4755 |
.options() |
| 4756 |
.wrap_static_fns_path |
| 4757 |
.as_ref() |
| 4758 |
.map(PathBuf::from) |
| 4759 |
.unwrap_or_else(|| { |
| 4760 |
std::env::temp_dir().join("bindgen").join("extern") |
| 4761 |
}); |
| 4762 |
|
| 4763 |
let dir = path.parent().unwrap(); |
| 4764 |
|
| 4765 |
if !dir.exists() { |
| 4766 |
std::fs::create_dir_all(dir)?; |
| 4767 |
} |
| 4768 |
|
| 4769 |
let is_cpp = args_are_cpp(&context.options().clang_args) || |
| 4770 |
context |
| 4771 |
.options() |
| 4772 |
.input_headers |
| 4773 |
.iter() |
| 4774 |
.any(|h| file_is_cpp(h)); |
| 4775 |
|
| 4776 |
let source_path = path.with_extension(if is_cpp { "cpp" } else { "c" }); |
| 4777 |
|
| 4778 |
let mut code = Vec::new(); |
| 4779 |
|
| 4780 |
if !context.options().input_headers.is_empty() { |
| 4781 |
for header in &context.options().input_headers { |
| 4782 |
writeln!(code, "#include \"{}\"", header)?; |
| 4783 |
} |
| 4784 |
|
| 4785 |
writeln!(code)?; |
| 4786 |
} |
| 4787 |
|
| 4788 |
if !context.options().input_header_contents.is_empty() { |
| 4789 |
for (name, contents) in &context.options().input_header_contents { |
| 4790 |
writeln!(code, "// {}\n{}", name, contents)?; |
| 4791 |
} |
| 4792 |
|
| 4793 |
writeln!(code)?; |
| 4794 |
} |
| 4795 |
|
| 4796 |
writeln!(code, "// Static wrappers\n")?; |
| 4797 |
|
| 4798 |
for &id in &result.items_to_serialize { |
| 4799 |
let item = context.resolve_item(id); |
| 4800 |
item.serialize(context, (), &mut vec![], &mut code)?; |
| 4801 |
} |
| 4802 |
|
| 4803 |
std::fs::write(source_path, code)?; |
| 4804 |
|
| 4805 |
Ok(()) |
| 4806 |
} |
| 4807 |
|
| 4808 |
pub(crate) fn prepend_bitfield_unit_type( |
| 4809 |
ctx: &BindgenContext, |
| 4810 |
result: &mut Vec<proc_macro2::TokenStream>, |
| 4811 |
) { |
| 4812 |
let bitfield_unit_src = include_str!("./bitfield_unit.rs"); |
| 4813 |
let bitfield_unit_src = if ctx.options().rust_features().min_const_fn { |
| 4814 |
Cow::Borrowed(bitfield_unit_src) |
| 4815 |
} else { |
| 4816 |
Cow::Owned(bitfield_unit_src.replace("const fn ", "fn ")) |
| 4817 |
}; |
| 4818 |
let bitfield_unit_type = |
| 4819 |
proc_macro2::TokenStream::from_str(&bitfield_unit_src).unwrap(); |
| 4820 |
let bitfield_unit_type = quote!(#bitfield_unit_type); |
| 4821 |
|
| 4822 |
let items = vec![bitfield_unit_type]; |
| 4823 |
let old_items = mem::replace(result, items); |
| 4824 |
result.extend(old_items); |
| 4825 |
} |
| 4826 |
|
| 4827 |
pub(crate) fn prepend_objc_header( |
| 4828 |
ctx: &BindgenContext, |
| 4829 |
result: &mut Vec<proc_macro2::TokenStream>, |
| 4830 |
) { |
| 4831 |
let use_objc = if ctx.options().objc_extern_crate { |
| 4832 |
quote! { |
| 4833 |
#[macro_use] |
| 4834 |
extern crate objc; |
| 4835 |
} |
| 4836 |
} else { |
| 4837 |
quote! { |
| 4838 |
use objc::{self, msg_send, sel, sel_impl, class}; |
| 4839 |
} |
| 4840 |
}; |
| 4841 |
|
| 4842 |
let id_type = quote! { |
| 4843 |
#[allow(non_camel_case_types)] |
| 4844 |
pub type id = *mut objc::runtime::Object; |
| 4845 |
}; |
| 4846 |
|
| 4847 |
let items = vec![use_objc, id_type]; |
| 4848 |
let old_items = mem::replace(result, items); |
| 4849 |
result.extend(old_items.into_iter()); |
| 4850 |
} |
| 4851 |
|
| 4852 |
pub(crate) fn prepend_block_header( |
| 4853 |
ctx: &BindgenContext, |
| 4854 |
result: &mut Vec<proc_macro2::TokenStream>, |
| 4855 |
) { |
| 4856 |
let use_block = if ctx.options().block_extern_crate { |
| 4857 |
quote! { |
| 4858 |
extern crate block; |
| 4859 |
} |
| 4860 |
} else { |
| 4861 |
quote! { |
| 4862 |
use block; |
| 4863 |
} |
| 4864 |
}; |
| 4865 |
|
| 4866 |
let items = vec![use_block]; |
| 4867 |
let old_items = mem::replace(result, items); |
| 4868 |
result.extend(old_items.into_iter()); |
| 4869 |
} |
| 4870 |
|
| 4871 |
pub(crate) fn prepend_union_types( |
| 4872 |
ctx: &BindgenContext, |
| 4873 |
result: &mut Vec<proc_macro2::TokenStream>, |
| 4874 |
) { |
| 4875 |
let prefix = ctx.trait_prefix(); |
| 4876 |
|
| 4877 |
// If the target supports `const fn`, declare eligible functions |
| 4878 |
// as `const fn` else just `fn`. |
| 4879 |
let const_fn = if ctx.options().rust_features().min_const_fn { |
| 4880 |
quote! { const fn } |
| 4881 |
} else { |
| 4882 |
quote! { fn } |
| 4883 |
}; |
| 4884 |
|
| 4885 |
// TODO(emilio): The fmt::Debug impl could be way nicer with |
| 4886 |
// std::intrinsics::type_name, but... |
| 4887 |
let union_field_decl = quote! { |
| 4888 |
#[repr(C)] |
| 4889 |
pub struct __BindgenUnionField<T>(::#prefix::marker::PhantomData<T>); |
| 4890 |
}; |
| 4891 |
|
| 4892 |
let transmute = |
| 4893 |
ctx.wrap_unsafe_ops(quote!(::#prefix::mem::transmute(self))); |
| 4894 |
|
| 4895 |
let union_field_impl = quote! { |
| 4896 |
impl<T> __BindgenUnionField<T> { |
| 4897 |
#[inline] |
| 4898 |
pub #const_fn new() -> Self { |
| 4899 |
__BindgenUnionField(::#prefix::marker::PhantomData) |
| 4900 |
} |
| 4901 |
|
| 4902 |
#[inline] |
| 4903 |
pub unsafe fn as_ref(&self) -> &T { |
| 4904 |
#transmute |
| 4905 |
} |
| 4906 |
|
| 4907 |
#[inline] |
| 4908 |
pub unsafe fn as_mut(&mut self) -> &mut T { |
| 4909 |
#transmute |
| 4910 |
} |
| 4911 |
} |
| 4912 |
}; |
| 4913 |
|
| 4914 |
let union_field_default_impl = quote! { |
| 4915 |
impl<T> ::#prefix::default::Default for __BindgenUnionField<T> { |
| 4916 |
#[inline] |
| 4917 |
fn default() -> Self { |
| 4918 |
Self::new() |
| 4919 |
} |
| 4920 |
} |
| 4921 |
}; |
| 4922 |
|
| 4923 |
let union_field_clone_impl = quote! { |
| 4924 |
impl<T> ::#prefix::clone::Clone for __BindgenUnionField<T> { |
| 4925 |
#[inline] |
| 4926 |
fn clone(&self) -> Self { |
| 4927 |
Self::new() |
| 4928 |
} |
| 4929 |
} |
| 4930 |
}; |
| 4931 |
|
| 4932 |
let union_field_copy_impl = quote! { |
| 4933 |
impl<T> ::#prefix::marker::Copy for __BindgenUnionField<T> {} |
| 4934 |
}; |
| 4935 |
|
| 4936 |
let union_field_debug_impl = quote! { |
| 4937 |
impl<T> ::#prefix::fmt::Debug for __BindgenUnionField<T> { |
| 4938 |
fn fmt(&self, fmt: &mut ::#prefix::fmt::Formatter<'_>) |
| 4939 |
-> ::#prefix::fmt::Result { |
| 4940 |
fmt.write_str("__BindgenUnionField") |
| 4941 |
} |
| 4942 |
} |
| 4943 |
}; |
| 4944 |
|
| 4945 |
// The actual memory of the filed will be hashed, so that's why these |
| 4946 |
// field doesn't do anything with the hash. |
| 4947 |
let union_field_hash_impl = quote! { |
| 4948 |
impl<T> ::#prefix::hash::Hash for __BindgenUnionField<T> { |
| 4949 |
fn hash<H: ::#prefix::hash::Hasher>(&self, _state: &mut H) { |
| 4950 |
} |
| 4951 |
} |
| 4952 |
}; |
| 4953 |
|
| 4954 |
let union_field_partialeq_impl = quote! { |
| 4955 |
impl<T> ::#prefix::cmp::PartialEq for __BindgenUnionField<T> { |
| 4956 |
fn eq(&self, _other: &__BindgenUnionField<T>) -> bool { |
| 4957 |
true |
| 4958 |
} |
| 4959 |
} |
| 4960 |
}; |
| 4961 |
|
| 4962 |
let union_field_eq_impl = quote! { |
| 4963 |
impl<T> ::#prefix::cmp::Eq for __BindgenUnionField<T> { |
| 4964 |
} |
| 4965 |
}; |
| 4966 |
|
| 4967 |
let items = vec![ |
| 4968 |
union_field_decl, |
| 4969 |
union_field_impl, |
| 4970 |
union_field_default_impl, |
| 4971 |
union_field_clone_impl, |
| 4972 |
union_field_copy_impl, |
| 4973 |
union_field_debug_impl, |
| 4974 |
union_field_hash_impl, |
| 4975 |
union_field_partialeq_impl, |
| 4976 |
union_field_eq_impl, |
| 4977 |
]; |
| 4978 |
|
| 4979 |
let old_items = mem::replace(result, items); |
| 4980 |
result.extend(old_items.into_iter()); |
| 4981 |
} |
| 4982 |
|
| 4983 |
pub(crate) fn prepend_incomplete_array_types( |
| 4984 |
ctx: &BindgenContext, |
| 4985 |
result: &mut Vec<proc_macro2::TokenStream>, |
| 4986 |
) { |
| 4987 |
let prefix = ctx.trait_prefix(); |
| 4988 |
|
| 4989 |
// If the target supports `const fn`, declare eligible functions |
| 4990 |
// as `const fn` else just `fn`. |
| 4991 |
let const_fn = if ctx.options().rust_features().min_const_fn { |
| 4992 |
quote! { const fn } |
| 4993 |
} else { |
| 4994 |
quote! { fn } |
| 4995 |
}; |
| 4996 |
|
| 4997 |
let incomplete_array_decl = quote! { |
| 4998 |
#[repr(C)] |
| 4999 |
#[derive(Default)] |
| 5000 |
pub struct __IncompleteArrayField<T>( |
| 5001 |
::#prefix::marker::PhantomData<T>, [T; 0]); |
| 5002 |
}; |
| 5003 |
|
| 5004 |
let from_raw_parts = ctx.wrap_unsafe_ops(quote! ( |
| 5005 |
::#prefix::slice::from_raw_parts(self.as_ptr(), len) |
| 5006 |
)); |
| 5007 |
let from_raw_parts_mut = ctx.wrap_unsafe_ops(quote! ( |
| 5008 |
::#prefix::slice::from_raw_parts_mut(self.as_mut_ptr(), len) |
| 5009 |
)); |
| 5010 |
|
| 5011 |
let incomplete_array_impl = quote! { |
| 5012 |
impl<T> __IncompleteArrayField<T> { |
| 5013 |
#[inline] |
| 5014 |
pub #const_fn new() -> Self { |
| 5015 |
__IncompleteArrayField(::#prefix::marker::PhantomData, []) |
| 5016 |
} |
| 5017 |
|
| 5018 |
#[inline] |
| 5019 |
pub fn as_ptr(&self) -> *const T { |
| 5020 |
self as *const _ as *const T |
| 5021 |
} |
| 5022 |
|
| 5023 |
#[inline] |
| 5024 |
pub fn as_mut_ptr(&mut self) -> *mut T { |
| 5025 |
self as *mut _ as *mut T |
| 5026 |
} |
| 5027 |
|
| 5028 |
#[inline] |
| 5029 |
pub unsafe fn as_slice(&self, len: usize) -> &[T] { |
| 5030 |
#from_raw_parts |
| 5031 |
} |
| 5032 |
|
| 5033 |
#[inline] |
| 5034 |
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] { |
| 5035 |
#from_raw_parts_mut |
| 5036 |
} |
| 5037 |
} |
| 5038 |
}; |
| 5039 |
|
| 5040 |
let incomplete_array_debug_impl = quote! { |
| 5041 |
impl<T> ::#prefix::fmt::Debug for __IncompleteArrayField<T> { |
| 5042 |
fn fmt(&self, fmt: &mut ::#prefix::fmt::Formatter<'_>) |
| 5043 |
-> ::#prefix::fmt::Result { |
| 5044 |
fmt.write_str("__IncompleteArrayField") |
| 5045 |
} |
| 5046 |
} |
| 5047 |
}; |
| 5048 |
|
| 5049 |
let items = vec![ |
| 5050 |
incomplete_array_decl, |
| 5051 |
incomplete_array_impl, |
| 5052 |
incomplete_array_debug_impl, |
| 5053 |
]; |
| 5054 |
|
| 5055 |
let old_items = mem::replace(result, items); |
| 5056 |
result.extend(old_items.into_iter()); |
| 5057 |
} |
| 5058 |
|
| 5059 |
pub(crate) fn prepend_complex_type( |
| 5060 |
result: &mut Vec<proc_macro2::TokenStream>, |
| 5061 |
) { |
| 5062 |
let complex_type = quote! { |
| 5063 |
#[derive(PartialEq, Copy, Clone, Hash, Debug, Default)] |
| 5064 |
#[repr(C)] |
| 5065 |
pub struct __BindgenComplex<T> { |
| 5066 |
pub re: T, |
| 5067 |
pub im: T |
| 5068 |
} |
| 5069 |
}; |
| 5070 |
|
| 5071 |
let items = vec![complex_type]; |
| 5072 |
let old_items = mem::replace(result, items); |
| 5073 |
result.extend(old_items.into_iter()); |
| 5074 |
} |
| 5075 |
|
| 5076 |
pub(crate) fn build_path( |
| 5077 |
item: &Item, |
| 5078 |
ctx: &BindgenContext, |
| 5079 |
) -> error::Result<proc_macro2::TokenStream> { |
| 5080 |
let path = item.namespace_aware_canonical_path(ctx); |
| 5081 |
let tokens = |
| 5082 |
proc_macro2::TokenStream::from_str(&path.join("::")).unwrap(); |
| 5083 |
|
| 5084 |
Ok(tokens) |
| 5085 |
} |
| 5086 |
|
| 5087 |
fn primitive_ty( |
| 5088 |
ctx: &BindgenContext, |
| 5089 |
name: &str, |
| 5090 |
) -> proc_macro2::TokenStream { |
| 5091 |
let ident = ctx.rust_ident_raw(name); |
| 5092 |
quote! { |
| 5093 |
#ident |
| 5094 |
} |
| 5095 |
} |
| 5096 |
|
| 5097 |
pub(crate) fn type_from_named( |
| 5098 |
ctx: &BindgenContext, |
| 5099 |
name: &str, |
| 5100 |
) -> Option<proc_macro2::TokenStream> { |
| 5101 |
// FIXME: We could use the inner item to check this is really a |
| 5102 |
// primitive type but, who the heck overrides these anyway? |
| 5103 |
Some(match name { |
| 5104 |
"int8_t" => primitive_ty(ctx, "i8"), |
| 5105 |
"uint8_t" => primitive_ty(ctx, "u8"), |
| 5106 |
"int16_t" => primitive_ty(ctx, "i16"), |
| 5107 |
"uint16_t" => primitive_ty(ctx, "u16"), |
| 5108 |
"int32_t" => primitive_ty(ctx, "i32"), |
| 5109 |
"uint32_t" => primitive_ty(ctx, "u32"), |
| 5110 |
"int64_t" => primitive_ty(ctx, "i64"), |
| 5111 |
"uint64_t" => primitive_ty(ctx, "u64"), |
| 5112 |
|
| 5113 |
"size_t" if ctx.options().size_t_is_usize => { |
| 5114 |
primitive_ty(ctx, "usize") |
| 5115 |
} |
| 5116 |
"uintptr_t" => primitive_ty(ctx, "usize"), |
| 5117 |
|
| 5118 |
"ssize_t" if ctx.options().size_t_is_usize => { |
| 5119 |
primitive_ty(ctx, "isize") |
| 5120 |
} |
| 5121 |
"intptr_t" | "ptrdiff_t" => primitive_ty(ctx, "isize"), |
| 5122 |
_ => return None, |
| 5123 |
}) |
| 5124 |
} |
| 5125 |
|
| 5126 |
fn fnsig_return_ty_internal( |
| 5127 |
ctx: &BindgenContext, |
| 5128 |
sig: &FunctionSig, |
| 5129 |
include_arrow: bool, |
| 5130 |
) -> proc_macro2::TokenStream { |
| 5131 |
if sig.is_divergent() { |
| 5132 |
return if include_arrow { |
| 5133 |
quote! { -> ! } |
| 5134 |
} else { |
| 5135 |
quote! { ! } |
| 5136 |
}; |
| 5137 |
} |
| 5138 |
|
| 5139 |
let canonical_type_kind = sig |
| 5140 |
.return_type() |
| 5141 |
.into_resolver() |
| 5142 |
.through_type_refs() |
| 5143 |
.through_type_aliases() |
| 5144 |
.resolve(ctx) |
| 5145 |
.kind() |
| 5146 |
.expect_type() |
| 5147 |
.kind(); |
| 5148 |
|
| 5149 |
if let TypeKind::Void = canonical_type_kind { |
| 5150 |
return if include_arrow { |
| 5151 |
quote! {} |
| 5152 |
} else { |
| 5153 |
quote! { () } |
| 5154 |
}; |
| 5155 |
} |
| 5156 |
|
| 5157 |
let ret_ty = sig.return_type().to_rust_ty_or_opaque(ctx, &()); |
| 5158 |
if include_arrow { |
| 5159 |
quote! { -> #ret_ty } |
| 5160 |
} else { |
| 5161 |
ret_ty |
| 5162 |
} |
| 5163 |
} |
| 5164 |
|
| 5165 |
pub(crate) fn fnsig_return_ty( |
| 5166 |
ctx: &BindgenContext, |
| 5167 |
sig: &FunctionSig, |
| 5168 |
) -> proc_macro2::TokenStream { |
| 5169 |
fnsig_return_ty_internal(ctx, sig, /* include_arrow = */ true) |
| 5170 |
} |
| 5171 |
|
| 5172 |
pub(crate) fn fnsig_arguments( |
| 5173 |
ctx: &BindgenContext, |
| 5174 |
sig: &FunctionSig, |
| 5175 |
) -> Vec<proc_macro2::TokenStream> { |
| 5176 |
use super::ToPtr; |
| 5177 |
|
| 5178 |
let mut unnamed_arguments = 0; |
| 5179 |
let mut args = sig |
| 5180 |
.argument_types() |
| 5181 |
.iter() |
| 5182 |
.map(|&(ref name, ty)| { |
| 5183 |
let arg_item = ctx.resolve_item(ty); |
| 5184 |
let arg_ty = arg_item.kind().expect_type(); |
| 5185 |
|
| 5186 |
// From the C90 standard[1]: |
| 5187 |
// |
| 5188 |
// A declaration of a parameter as "array of type" shall be |
| 5189 |
// adjusted to "qualified pointer to type", where the type |
| 5190 |
// qualifiers (if any) are those specified within the [ and ] of |
| 5191 |
// the array type derivation. |
| 5192 |
// |
| 5193 |
// [1]: http://c0x.coding-guidelines.com/6.7.5.3.html |
| 5194 |
let arg_ty = match *arg_ty.canonical_type(ctx).kind() { |
| 5195 |
TypeKind::Array(t, _) => { |
| 5196 |
let stream = |
| 5197 |
if ctx.options().array_pointers_in_arguments { |
| 5198 |
arg_ty.to_rust_ty_or_opaque(ctx, arg_item) |
| 5199 |
} else { |
| 5200 |
t.to_rust_ty_or_opaque(ctx, &()) |
| 5201 |
}; |
| 5202 |
stream.to_ptr(ctx.resolve_type(t).is_const()) |
| 5203 |
} |
| 5204 |
TypeKind::Pointer(inner) => { |
| 5205 |
let inner = ctx.resolve_item(inner); |
| 5206 |
let inner_ty = inner.expect_type(); |
| 5207 |
if let TypeKind::ObjCInterface(ref interface) = |
| 5208 |
*inner_ty.canonical_type(ctx).kind() |
| 5209 |
{ |
| 5210 |
let name = ctx.rust_ident(interface.name()); |
| 5211 |
quote! { |
| 5212 |
#name |
| 5213 |
} |
| 5214 |
} else { |
| 5215 |
arg_item.to_rust_ty_or_opaque(ctx, &()) |
| 5216 |
} |
| 5217 |
} |
| 5218 |
_ => arg_item.to_rust_ty_or_opaque(ctx, &()), |
| 5219 |
}; |
| 5220 |
|
| 5221 |
let arg_name = match *name { |
| 5222 |
Some(ref name) => ctx.rust_mangle(name).into_owned(), |
| 5223 |
None => { |
| 5224 |
unnamed_arguments += 1; |
| 5225 |
format!("arg{}", unnamed_arguments) |
| 5226 |
} |
| 5227 |
}; |
| 5228 |
|
| 5229 |
assert!(!arg_name.is_empty()); |
| 5230 |
let arg_name = ctx.rust_ident(arg_name); |
| 5231 |
|
| 5232 |
quote! { |
| 5233 |
#arg_name : #arg_ty |
| 5234 |
} |
| 5235 |
}) |
| 5236 |
.collect::<Vec<_>>(); |
| 5237 |
|
| 5238 |
if sig.is_variadic() { |
| 5239 |
args.push(quote! { ... }) |
| 5240 |
} |
| 5241 |
|
| 5242 |
args |
| 5243 |
} |
| 5244 |
|
| 5245 |
pub(crate) fn fnsig_argument_identifiers( |
| 5246 |
ctx: &BindgenContext, |
| 5247 |
sig: &FunctionSig, |
| 5248 |
) -> Vec<proc_macro2::TokenStream> { |
| 5249 |
let mut unnamed_arguments = 0; |
| 5250 |
let args = sig |
| 5251 |
.argument_types() |
| 5252 |
.iter() |
| 5253 |
.map(|&(ref name, _ty)| { |
| 5254 |
let arg_name = match *name { |
| 5255 |
Some(ref name) => ctx.rust_mangle(name).into_owned(), |
| 5256 |
None => { |
| 5257 |
unnamed_arguments += 1; |
| 5258 |
format!("arg{}", unnamed_arguments) |
| 5259 |
} |
| 5260 |
}; |
| 5261 |
|
| 5262 |
assert!(!arg_name.is_empty()); |
| 5263 |
let arg_name = ctx.rust_ident(arg_name); |
| 5264 |
|
| 5265 |
quote! { |
| 5266 |
#arg_name |
| 5267 |
} |
| 5268 |
}) |
| 5269 |
.collect::<Vec<_>>(); |
| 5270 |
|
| 5271 |
args |
| 5272 |
} |
| 5273 |
|
| 5274 |
pub(crate) fn fnsig_block( |
| 5275 |
ctx: &BindgenContext, |
| 5276 |
sig: &FunctionSig, |
| 5277 |
) -> proc_macro2::TokenStream { |
| 5278 |
let args = sig.argument_types().iter().map(|&(_, ty)| { |
| 5279 |
let arg_item = ctx.resolve_item(ty); |
| 5280 |
|
| 5281 |
arg_item.to_rust_ty_or_opaque(ctx, &()) |
| 5282 |
}); |
| 5283 |
|
| 5284 |
let ret_ty = fnsig_return_ty_internal( |
| 5285 |
ctx, sig, /* include_arrow = */ false, |
| 5286 |
); |
| 5287 |
quote! { |
| 5288 |
*const ::block::Block<(#(#args,)*), #ret_ty> |
| 5289 |
} |
| 5290 |
} |
| 5291 |
|
| 5292 |
// Returns true if `canonical_name` will end up as `mangled_name` at the |
| 5293 |
// machine code level, i.e. after LLVM has applied any target specific |
| 5294 |
// mangling. |
| 5295 |
pub(crate) fn names_will_be_identical_after_mangling( |
| 5296 |
canonical_name: &str, |
| 5297 |
mangled_name: &str, |
| 5298 |
call_conv: Option<ClangAbi>, |
| 5299 |
) -> bool { |
| 5300 |
// If the mangled name and the canonical name are the same then no |
| 5301 |
// mangling can have happened between the two versions. |
| 5302 |
if canonical_name == mangled_name { |
| 5303 |
return true; |
| 5304 |
} |
| 5305 |
|
| 5306 |
// Working with &[u8] makes indexing simpler than with &str |
| 5307 |
let canonical_name = canonical_name.as_bytes(); |
| 5308 |
let mangled_name = mangled_name.as_bytes(); |
| 5309 |
|
| 5310 |
let (mangling_prefix, expect_suffix) = match call_conv { |
| 5311 |
Some(ClangAbi::Known(Abi::C)) | |
| 5312 |
// None is the case for global variables |
| 5313 |
None => { |
| 5314 |
(b'_', false) |
| 5315 |
} |
| 5316 |
Some(ClangAbi::Known(Abi::Stdcall)) => (b'_', true), |
| 5317 |
Some(ClangAbi::Known(Abi::Fastcall)) => (b'@', true), |
| 5318 |
|
| 5319 |
// This is something we don't recognize, stay on the safe side |
| 5320 |
// by emitting the `#[link_name]` attribute |
| 5321 |
Some(_) => return false, |
| 5322 |
}; |
| 5323 |
|
| 5324 |
// Check that the mangled name is long enough to at least contain the |
| 5325 |
// canonical name plus the expected prefix. |
| 5326 |
if mangled_name.len() < canonical_name.len() + 1 { |
| 5327 |
return false; |
| 5328 |
} |
| 5329 |
|
| 5330 |
// Return if the mangled name does not start with the prefix expected |
| 5331 |
// for the given calling convention. |
| 5332 |
if mangled_name[0] != mangling_prefix { |
| 5333 |
return false; |
| 5334 |
} |
| 5335 |
|
| 5336 |
// Check that the mangled name contains the canonical name after the |
| 5337 |
// prefix |
| 5338 |
if &mangled_name[1..canonical_name.len() + 1] != canonical_name { |
| 5339 |
return false; |
| 5340 |
} |
| 5341 |
|
| 5342 |
// If the given calling convention also prescribes a suffix, check that |
| 5343 |
// it exists too |
| 5344 |
if expect_suffix { |
| 5345 |
let suffix = &mangled_name[canonical_name.len() + 1..]; |
| 5346 |
|
| 5347 |
// The shortest suffix is "@0" |
| 5348 |
if suffix.len() < 2 { |
| 5349 |
return false; |
| 5350 |
} |
| 5351 |
|
| 5352 |
// Check that the suffix starts with '@' and is all ASCII decimals |
| 5353 |
// after that. |
| 5354 |
if suffix[0] != b'@' || !suffix[1..].iter().all(u8::is_ascii_digit) |
| 5355 |
{ |
| 5356 |
return false; |
| 5357 |
} |
| 5358 |
} else if mangled_name.len() != canonical_name.len() + 1 { |
| 5359 |
// If we don't expect a prefix but there is one, we need the |
| 5360 |
// #[link_name] attribute |
| 5361 |
return false; |
| 5362 |
} |
| 5363 |
|
| 5364 |
true |
| 5365 |
} |
| 5366 |
} |