Debian Codegraph @

.cargo/vendor/bindgen/ir/context.rs

raw
1 //! Common context that is passed around during parsing and codegen.
2
3 use super::super::time::Timer;
4 use super::analysis::{
5 analyze, as_cannot_derive_set, CannotDerive, DeriveTrait,
6 HasDestructorAnalysis, HasFloat, HasTypeParameterInArray,
7 HasVtableAnalysis, HasVtableResult, SizednessAnalysis, SizednessResult,
8 UsedTemplateParameters,
9 };
10 use super::derive::{
11 CanDerive, CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq,
12 CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd,
13 };
14 use super::function::Function;
15 use super::int::IntKind;
16 use super::item::{IsOpaque, Item, ItemAncestors, ItemSet};
17 use super::item_kind::ItemKind;
18 use super::module::{Module, ModuleKind};
19 use super::template::{TemplateInstantiation, TemplateParameters};
20 use super::traversal::{self, Edge, ItemTraversal};
21 use super::ty::{FloatKind, Type, TypeKind};
22 use crate::clang::{self, Cursor};
23 use crate::codegen::CodegenError;
24 use crate::BindgenOptions;
25 use crate::{Entry, HashMap, HashSet};
26
27 use proc_macro2::{Ident, Span, TokenStream};
28 use quote::ToTokens;
29 use std::borrow::Cow;
30 use std::cell::{Cell, RefCell};
31 use std::collections::{BTreeSet, HashMap as StdHashMap};
32 use std::iter::IntoIterator;
33 use std::mem;
34
35 /// An identifier for some kind of IR item.
36 #[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)]
37 pub(crate) struct ItemId(usize);
38
39 /// Declare a newtype around `ItemId` with convesion methods.
40 macro_rules! item_id_newtype {
41 (
42 $( #[$attr:meta] )*
43 pub(crate) struct $name:ident(ItemId)
44 where
45 $( #[$checked_attr:meta] )*
46 checked = $checked:ident with $check_method:ident,
47 $( #[$expected_attr:meta] )*
48 expected = $expected:ident,
49 $( #[$unchecked_attr:meta] )*
50 unchecked = $unchecked:ident;
51 ) => {
52 $( #[$attr] )*
53 #[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)]
54 pub(crate) struct $name(ItemId);
55
56 impl $name {
57 /// Create an `ItemResolver` from this ID.
58 #[allow(dead_code)]
59 pub(crate) fn into_resolver(self) -> ItemResolver {
60 let id: ItemId = self.into();
61 id.into()
62 }
63 }
64
65 impl<T> ::std::cmp::PartialEq<T> for $name
66 where
67 T: Copy + Into<ItemId>
68 {
69 fn eq(&self, rhs: &T) -> bool {
70 let rhs: ItemId = (*rhs).into();
71 self.0 == rhs
72 }
73 }
74
75 impl From<$name> for ItemId {
76 fn from(id: $name) -> ItemId {
77 id.0
78 }
79 }
80
81 impl<'a> From<&'a $name> for ItemId {
82 fn from(id: &'a $name) -> ItemId {
83 id.0
84 }
85 }
86
87 #[allow(dead_code)]
88 impl ItemId {
89 $( #[$checked_attr] )*
90 pub(crate) fn $checked(&self, ctx: &BindgenContext) -> Option<$name> {
91 if ctx.resolve_item(*self).kind().$check_method() {
92 Some($name(*self))
93 } else {
94 None
95 }
96 }
97
98 $( #[$expected_attr] )*
99 pub(crate) fn $expected(&self, ctx: &BindgenContext) -> $name {
100 self.$checked(ctx)
101 .expect(concat!(
102 stringify!($expected),
103 " called with ItemId that points to the wrong ItemKind"
104 ))
105 }
106
107 $( #[$unchecked_attr] )*
108 pub(crate) fn $unchecked(&self) -> $name {
109 $name(*self)
110 }
111 }
112 }
113 }
114
115 item_id_newtype! {
116 /// An identifier for an `Item` whose `ItemKind` is known to be
117 /// `ItemKind::Type`.
118 pub(crate) struct TypeId(ItemId)
119 where
120 /// Convert this `ItemId` into a `TypeId` if its associated item is a type,
121 /// otherwise return `None`.
122 checked = as_type_id with is_type,
123
124 /// Convert this `ItemId` into a `TypeId`.
125 ///
126 /// If this `ItemId` does not point to a type, then panic.
127 expected = expect_type_id,
128
129 /// Convert this `ItemId` into a `TypeId` without actually checking whether
130 /// this ID actually points to a `Type`.
131 unchecked = as_type_id_unchecked;
132 }
133
134 item_id_newtype! {
135 /// An identifier for an `Item` whose `ItemKind` is known to be
136 /// `ItemKind::Module`.
137 pub(crate) struct ModuleId(ItemId)
138 where
139 /// Convert this `ItemId` into a `ModuleId` if its associated item is a
140 /// module, otherwise return `None`.
141 checked = as_module_id with is_module,
142
143 /// Convert this `ItemId` into a `ModuleId`.
144 ///
145 /// If this `ItemId` does not point to a module, then panic.
146 expected = expect_module_id,
147
148 /// Convert this `ItemId` into a `ModuleId` without actually checking
149 /// whether this ID actually points to a `Module`.
150 unchecked = as_module_id_unchecked;
151 }
152
153 item_id_newtype! {
154 /// An identifier for an `Item` whose `ItemKind` is known to be
155 /// `ItemKind::Var`.
156 pub(crate) struct VarId(ItemId)
157 where
158 /// Convert this `ItemId` into a `VarId` if its associated item is a var,
159 /// otherwise return `None`.
160 checked = as_var_id with is_var,
161
162 /// Convert this `ItemId` into a `VarId`.
163 ///
164 /// If this `ItemId` does not point to a var, then panic.
165 expected = expect_var_id,
166
167 /// Convert this `ItemId` into a `VarId` without actually checking whether
168 /// this ID actually points to a `Var`.
169 unchecked = as_var_id_unchecked;
170 }
171
172 item_id_newtype! {
173 /// An identifier for an `Item` whose `ItemKind` is known to be
174 /// `ItemKind::Function`.
175 pub(crate) struct FunctionId(ItemId)
176 where
177 /// Convert this `ItemId` into a `FunctionId` if its associated item is a function,
178 /// otherwise return `None`.
179 checked = as_function_id with is_function,
180
181 /// Convert this `ItemId` into a `FunctionId`.
182 ///
183 /// If this `ItemId` does not point to a function, then panic.
184 expected = expect_function_id,
185
186 /// Convert this `ItemId` into a `FunctionId` without actually checking whether
187 /// this ID actually points to a `Function`.
188 unchecked = as_function_id_unchecked;
189 }
190
191 impl From<ItemId> for usize {
192 fn from(id: ItemId) -> usize {
193 id.0
194 }
195 }
196
197 impl ItemId {
198 /// Get a numeric representation of this ID.
199 pub(crate) fn as_usize(&self) -> usize {
200 (*self).into()
201 }
202 }
203
204 impl<T> ::std::cmp::PartialEq<T> for ItemId
205 where
206 T: Copy + Into<ItemId>,
207 {
208 fn eq(&self, rhs: &T) -> bool {
209 let rhs: ItemId = (*rhs).into();
210 self.0 == rhs.0
211 }
212 }
213
214 impl<T> CanDeriveDebug for T
215 where
216 T: Copy + Into<ItemId>,
217 {
218 fn can_derive_debug(&self, ctx: &BindgenContext) -> bool {
219 ctx.options().derive_debug && ctx.lookup_can_derive_debug(*self)
220 }
221 }
222
223 impl<T> CanDeriveDefault for T
224 where
225 T: Copy + Into<ItemId>,
226 {
227 fn can_derive_default(&self, ctx: &BindgenContext) -> bool {
228 ctx.options().derive_default && ctx.lookup_can_derive_default(*self)
229 }
230 }
231
232 impl<T> CanDeriveCopy for T
233 where
234 T: Copy + Into<ItemId>,
235 {
236 fn can_derive_copy(&self, ctx: &BindgenContext) -> bool {
237 ctx.options().derive_copy && ctx.lookup_can_derive_copy(*self)
238 }
239 }
240
241 impl<T> CanDeriveHash for T
242 where
243 T: Copy + Into<ItemId>,
244 {
245 fn can_derive_hash(&self, ctx: &BindgenContext) -> bool {
246 ctx.options().derive_hash && ctx.lookup_can_derive_hash(*self)
247 }
248 }
249
250 impl<T> CanDerivePartialOrd for T
251 where
252 T: Copy + Into<ItemId>,
253 {
254 fn can_derive_partialord(&self, ctx: &BindgenContext) -> bool {
255 ctx.options().derive_partialord &&
256 ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
257 CanDerive::Yes
258 }
259 }
260
261 impl<T> CanDerivePartialEq for T
262 where
263 T: Copy + Into<ItemId>,
264 {
265 fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool {
266 ctx.options().derive_partialeq &&
267 ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
268 CanDerive::Yes
269 }
270 }
271
272 impl<T> CanDeriveEq for T
273 where
274 T: Copy + Into<ItemId>,
275 {
276 fn can_derive_eq(&self, ctx: &BindgenContext) -> bool {
277 ctx.options().derive_eq &&
278 ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
279 CanDerive::Yes &&
280 !ctx.lookup_has_float(*self)
281 }
282 }
283
284 impl<T> CanDeriveOrd for T
285 where
286 T: Copy + Into<ItemId>,
287 {
288 fn can_derive_ord(&self, ctx: &BindgenContext) -> bool {
289 ctx.options().derive_ord &&
290 ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
291 CanDerive::Yes &&
292 !ctx.lookup_has_float(*self)
293 }
294 }
295
296 /// A key used to index a resolved type, so we only process it once.
297 ///
298 /// This is almost always a USR string (an unique identifier generated by
299 /// clang), but it can also be the canonical declaration if the type is unnamed,
300 /// in which case clang may generate the same USR for multiple nested unnamed
301 /// types.
302 #[derive(Eq, PartialEq, Hash, Debug)]
303 enum TypeKey {
304 Usr(String),
305 Declaration(Cursor),
306 }
307
308 /// A context used during parsing and generation of structs.
309 #[derive(Debug)]
310 pub(crate) struct BindgenContext {
311 /// The map of all the items parsed so far, keyed off ItemId.
312 items: Vec<Option<Item>>,
313
314 /// Clang USR to type map. This is needed to be able to associate types with
315 /// item ids during parsing.
316 types: HashMap<TypeKey, TypeId>,
317
318 /// Maps from a cursor to the item ID of the named template type parameter
319 /// for that cursor.
320 type_params: HashMap<clang::Cursor, TypeId>,
321
322 /// A cursor to module map. Similar reason than above.
323 modules: HashMap<Cursor, ModuleId>,
324
325 /// The root module, this is guaranteed to be an item of kind Module.
326 root_module: ModuleId,
327
328 /// Current module being traversed.
329 current_module: ModuleId,
330
331 /// A HashMap keyed on a type definition, and whose value is the parent ID
332 /// of the declaration.
333 ///
334 /// This is used to handle the cases where the semantic and the lexical
335 /// parents of the cursor differ, like when a nested class is defined
336 /// outside of the parent class.
337 semantic_parents: HashMap<clang::Cursor, ItemId>,
338
339 /// A stack with the current type declarations and types we're parsing. This
340 /// is needed to avoid infinite recursion when parsing a type like:
341 ///
342 /// struct c { struct c* next; };
343 ///
344 /// This means effectively, that a type has a potential ID before knowing if
345 /// it's a correct type. But that's not important in practice.
346 ///
347 /// We could also use the `types` HashMap, but my intention with it is that
348 /// only valid types and declarations end up there, and this could
349 /// potentially break that assumption.
350 currently_parsed_types: Vec<PartialType>,
351
352 /// A map with all the already parsed macro names. This is done to avoid
353 /// hard errors while parsing duplicated macros, as well to allow macro
354 /// expression parsing.
355 ///
356 /// This needs to be an std::HashMap because the cexpr API requires it.
357 parsed_macros: StdHashMap<Vec<u8>, cexpr::expr::EvalResult>,
358
359 /// A set of all the included filenames.
360 deps: BTreeSet<String>,
361
362 /// The active replacements collected from replaces="xxx" annotations.
363 replacements: HashMap<Vec<String>, ItemId>,
364
365 collected_typerefs: bool,
366
367 in_codegen: bool,
368
369 /// The translation unit for parsing.
370 translation_unit: clang::TranslationUnit,
371
372 /// Target information that can be useful for some stuff.
373 target_info: clang::TargetInfo,
374
375 /// The options given by the user via cli or other medium.
376 options: BindgenOptions,
377
378 /// Whether a bindgen complex was generated
379 generated_bindgen_complex: Cell<bool>,
380
381 /// The set of `ItemId`s that are allowlisted. This the very first thing
382 /// computed after parsing our IR, and before running any of our analyses.
383 allowlisted: Option<ItemSet>,
384
385 /// Cache for calls to `ParseCallbacks::blocklisted_type_implements_trait`
386 blocklisted_types_implement_traits:
387 RefCell<HashMap<DeriveTrait, HashMap<ItemId, CanDerive>>>,
388
389 /// The set of `ItemId`s that are allowlisted for code generation _and_ that
390 /// we should generate accounting for the codegen options.
391 ///
392 /// It's computed right after computing the allowlisted items.
393 codegen_items: Option<ItemSet>,
394
395 /// Map from an item's ID to the set of template parameter items that it
396 /// uses. See `ir::named` for more details. Always `Some` during the codegen
397 /// phase.
398 used_template_parameters: Option<HashMap<ItemId, ItemSet>>,
399
400 /// The set of `TypeKind::Comp` items found during parsing that need their
401 /// bitfield allocation units computed. Drained in `compute_bitfield_units`.
402 need_bitfield_allocation: Vec<ItemId>,
403
404 /// The set of enums that are defined by a pair of `enum` and `typedef`,
405 /// which is legal in C (but not C++).
406 ///
407 /// ```c++
408 /// // in either order
409 /// enum Enum { Variants... };
410 /// typedef int16_t Enum;
411 /// ```
412 ///
413 /// The stored `ItemId` is that of the `TypeKind::Enum`, not of the
414 /// `TypeKind::Alias`.
415 ///
416 /// This is populated when we enter codegen by `compute_enum_typedef_combos`
417 /// and is always `None` before that and `Some` after.
418 enum_typedef_combos: Option<HashSet<ItemId>>,
419
420 /// The set of (`ItemId`s of) types that can't derive debug.
421 ///
422 /// This is populated when we enter codegen by `compute_cannot_derive_debug`
423 /// and is always `None` before that and `Some` after.
424 cannot_derive_debug: Option<HashSet<ItemId>>,
425
426 /// The set of (`ItemId`s of) types that can't derive default.
427 ///
428 /// This is populated when we enter codegen by `compute_cannot_derive_default`
429 /// and is always `None` before that and `Some` after.
430 cannot_derive_default: Option<HashSet<ItemId>>,
431
432 /// The set of (`ItemId`s of) types that can't derive copy.
433 ///
434 /// This is populated when we enter codegen by `compute_cannot_derive_copy`
435 /// and is always `None` before that and `Some` after.
436 cannot_derive_copy: Option<HashSet<ItemId>>,
437
438 /// The set of (`ItemId`s of) types that can't derive hash.
439 ///
440 /// This is populated when we enter codegen by `compute_can_derive_hash`
441 /// and is always `None` before that and `Some` after.
442 cannot_derive_hash: Option<HashSet<ItemId>>,
443
444 /// The map why specified `ItemId`s of) types that can't derive hash.
445 ///
446 /// This is populated when we enter codegen by
447 /// `compute_cannot_derive_partialord_partialeq_or_eq` and is always `None`
448 /// before that and `Some` after.
449 cannot_derive_partialeq_or_partialord: Option<HashMap<ItemId, CanDerive>>,
450
451 /// The sizedness of types.
452 ///
453 /// This is populated by `compute_sizedness` and is always `None` before
454 /// that function is invoked and `Some` afterwards.
455 sizedness: Option<HashMap<TypeId, SizednessResult>>,
456
457 /// The set of (`ItemId's of`) types that has vtable.
458 ///
459 /// Populated when we enter codegen by `compute_has_vtable`; always `None`
460 /// before that and `Some` after.
461 have_vtable: Option<HashMap<ItemId, HasVtableResult>>,
462
463 /// The set of (`ItemId's of`) types that has destructor.
464 ///
465 /// Populated when we enter codegen by `compute_has_destructor`; always `None`
466 /// before that and `Some` after.
467 have_destructor: Option<HashSet<ItemId>>,
468
469 /// The set of (`ItemId's of`) types that has array.
470 ///
471 /// Populated when we enter codegen by `compute_has_type_param_in_array`; always `None`
472 /// before that and `Some` after.
473 has_type_param_in_array: Option<HashSet<ItemId>>,
474
475 /// The set of (`ItemId's of`) types that has float.
476 ///
477 /// Populated when we enter codegen by `compute_has_float`; always `None`
478 /// before that and `Some` after.
479 has_float: Option<HashSet<ItemId>>,
480 }
481
482 /// A traversal of allowlisted items.
483 struct AllowlistedItemsTraversal<'ctx> {
484 ctx: &'ctx BindgenContext,
485 traversal: ItemTraversal<'ctx, ItemSet, Vec<ItemId>>,
486 }
487
488 impl<'ctx> Iterator for AllowlistedItemsTraversal<'ctx> {
489 type Item = ItemId;
490
491 fn next(&mut self) -> Option<ItemId> {
492 loop {
493 let id = self.traversal.next()?;
494
495 if self.ctx.resolve_item(id).is_blocklisted(self.ctx) {
496 continue;
497 }
498
499 return Some(id);
500 }
501 }
502 }
503
504 impl<'ctx> AllowlistedItemsTraversal<'ctx> {
505 /// Construct a new allowlisted items traversal.
506 pub(crate) fn new<R>(
507 ctx: &'ctx BindgenContext,
508 roots: R,
509 predicate: for<'a> fn(&'a BindgenContext, Edge) -> bool,
510 ) -> Self
511 where
512 R: IntoIterator<Item = ItemId>,
513 {
514 AllowlistedItemsTraversal {
515 ctx,
516 traversal: ItemTraversal::new(ctx, roots, predicate),
517 }
518 }
519 }
520
521 impl BindgenContext {
522 /// Construct the context for the given `options`.
523 pub(crate) fn new(
524 options: BindgenOptions,
525 input_unsaved_files: &[clang::UnsavedFile],
526 ) -> Self {
527 // TODO(emilio): Use the CXTargetInfo here when available.
528 //
529 // see: https://reviews.llvm.org/D32389
530 let index = clang::Index::new(false, true);
531
532 let parse_options =
533 clang_sys::CXTranslationUnit_DetailedPreprocessingRecord;
534
535 let translation_unit = {
536 let _t =
537 Timer::new("translation_unit").with_output(options.time_phases);
538
539 clang::TranslationUnit::parse(
540 &index,
541 "",
542 &options.clang_args,
543 input_unsaved_files,
544 parse_options,
545 ).expect("libclang error; possible causes include:
546 - Invalid flag syntax
547 - Unrecognized flags
548 - Invalid flag arguments
549 - File I/O errors
550 - Host vs. target architecture mismatch
551 If you encounter an error missing from this list, please file an issue or a PR!")
552 };
553
554 let target_info = clang::TargetInfo::new(&translation_unit);
555 let root_module = Self::build_root_module(ItemId(0));
556 let root_module_id = root_module.id().as_module_id_unchecked();
557
558 // depfiles need to include the explicitly listed headers too
559 let deps = options.input_headers.iter().cloned().collect();
560
561 BindgenContext {
562 items: vec![Some(root_module)],
563 deps,
564 types: Default::default(),
565 type_params: Default::default(),
566 modules: Default::default(),
567 root_module: root_module_id,
568 current_module: root_module_id,
569 semantic_parents: Default::default(),
570 currently_parsed_types: vec![],
571 parsed_macros: Default::default(),
572 replacements: Default::default(),
573 collected_typerefs: false,
574 in_codegen: false,
575 translation_unit,
576 target_info,
577 options,
578 generated_bindgen_complex: Cell::new(false),
579 allowlisted: None,
580 blocklisted_types_implement_traits: Default::default(),
581 codegen_items: None,
582 used_template_parameters: None,
583 need_bitfield_allocation: Default::default(),
584 enum_typedef_combos: None,
585 cannot_derive_debug: None,
586 cannot_derive_default: None,
587 cannot_derive_copy: None,
588 cannot_derive_hash: None,
589 cannot_derive_partialeq_or_partialord: None,
590 sizedness: None,
591 have_vtable: None,
592 have_destructor: None,
593 has_type_param_in_array: None,
594 has_float: None,
595 }
596 }
597
598 /// Returns `true` if the target architecture is wasm32
599 pub(crate) fn is_target_wasm32(&self) -> bool {
600 self.target_info.triple.starts_with("wasm32-")
601 }
602
603 /// Creates a timer for the current bindgen phase. If time_phases is `true`,
604 /// the timer will print to stderr when it is dropped, otherwise it will do
605 /// nothing.
606 pub(crate) fn timer<'a>(&self, name: &'a str) -> Timer<'a> {
607 Timer::new(name).with_output(self.options.time_phases)
608 }
609
610 /// Returns the pointer width to use for the target for the current
611 /// translation.
612 pub(crate) fn target_pointer_size(&self) -> usize {
613 self.target_info.pointer_width / 8
614 }
615
616 /// Get the stack of partially parsed types that we are in the middle of
617 /// parsing.
618 pub(crate) fn currently_parsed_types(&self) -> &[PartialType] {
619 &self.currently_parsed_types[..]
620 }
621
622 /// Begin parsing the given partial type, and push it onto the
623 /// `currently_parsed_types` stack so that we won't infinite recurse if we
624 /// run into a reference to it while parsing it.
625 pub(crate) fn begin_parsing(&mut self, partial_ty: PartialType) {
626 self.currently_parsed_types.push(partial_ty);
627 }
628
629 /// Finish parsing the current partial type, pop it off the
630 /// `currently_parsed_types` stack, and return it.
631 pub(crate) fn finish_parsing(&mut self) -> PartialType {
632 self.currently_parsed_types.pop().expect(
633 "should have been parsing a type, if we finished parsing a type",
634 )
635 }
636
637 /// Add another path to the set of included files.
638 pub(crate) fn include_file(&mut self, filename: String) {
639 for cb in &self.options().parse_callbacks {
640 cb.include_file(&filename);
641 }
642 self.deps.insert(filename);
643 }
644
645 /// Get any included files.
646 pub(crate) fn deps(&self) -> &BTreeSet<String> {
647 &self.deps
648 }
649
650 /// Define a new item.
651 ///
652 /// This inserts it into the internal items set, and its type into the
653 /// internal types set.
654 pub(crate) fn add_item(
655 &mut self,
656 item: Item,
657 declaration: Option<Cursor>,
658 location: Option<Cursor>,
659 ) {
660 debug!(
661 "BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}",
662 item, declaration, location
663 );
664 debug_assert!(
665 declaration.is_some() ||
666 !item.kind().is_type() ||
667 item.kind().expect_type().is_builtin_or_type_param() ||
668 item.kind().expect_type().is_opaque(self, &item) ||
669 item.kind().expect_type().is_unresolved_ref(),
670 "Adding a type without declaration?"
671 );
672
673 let id = item.id();
674 let is_type = item.kind().is_type();
675 let is_unnamed = is_type && item.expect_type().name().is_none();
676 let is_template_instantiation =
677 is_type && item.expect_type().is_template_instantiation();
678
679 if item.id() != self.root_module {
680 self.add_item_to_module(&item);
681 }
682
683 if is_type && item.expect_type().is_comp() {
684 self.need_bitfield_allocation.push(id);
685 }
686
687 let old_item = mem::replace(&mut self.items[id.0], Some(item));
688 assert!(
689 old_item.is_none(),
690 "should not have already associated an item with the given id"
691 );
692
693 // Unnamed items can have an USR, but they can't be referenced from
694 // other sites explicitly and the USR can match if the unnamed items are
695 // nested, so don't bother tracking them.
696 if !is_type || is_template_instantiation {
697 return;
698 }
699 if let Some(mut declaration) = declaration {
700 if !declaration.is_valid() {
701 if let Some(location) = location {
702 if location.is_template_like() {
703 declaration = location;
704 }
705 }
706 }
707 declaration = declaration.canonical();
708 if !declaration.is_valid() {
709 // This could happen, for example, with types like `int*` or
710 // similar.
711 //
712 // Fortunately, we don't care about those types being
713 // duplicated, so we can just ignore them.
714 debug!(
715 "Invalid declaration {:?} found for type {:?}",
716 declaration,
717 self.resolve_item_fallible(id)
718 .unwrap()
719 .kind()
720 .expect_type()
721 );
722 return;
723 }
724
725 let key = if is_unnamed {
726 TypeKey::Declaration(declaration)
727 } else if let Some(usr) = declaration.usr() {
728 TypeKey::Usr(usr)
729 } else {
730 warn!(
731 "Valid declaration with no USR: {:?}, {:?}",
732 declaration, location
733 );
734 TypeKey::Declaration(declaration)
735 };
736
737 let old = self.types.insert(key, id.as_type_id_unchecked());
738 debug_assert_eq!(old, None);
739 }
740 }
741
742 /// Ensure that every item (other than the root module) is in a module's
743 /// children list. This is to make sure that every allowlisted item get's
744 /// codegen'd, even if its parent is not allowlisted. See issue #769 for
745 /// details.
746 fn add_item_to_module(&mut self, item: &Item) {
747 assert!(item.id() != self.root_module);
748 assert!(self.resolve_item_fallible(item.id()).is_none());
749
750 if let Some(ref mut parent) = self.items[item.parent_id().0] {
751 if let Some(module) = parent.as_module_mut() {
752 debug!(
753 "add_item_to_module: adding {:?} as child of parent module {:?}",
754 item.id(),
755 item.parent_id()
756 );
757
758 module.children_mut().insert(item.id());
759 return;
760 }
761 }
762
763 debug!(
764 "add_item_to_module: adding {:?} as child of current module {:?}",
765 item.id(),
766 self.current_module
767 );
768
769 self.items[(self.current_module.0).0]
770 .as_mut()
771 .expect("Should always have an item for self.current_module")
772 .as_module_mut()
773 .expect("self.current_module should always be a module")
774 .children_mut()
775 .insert(item.id());
776 }
777
778 /// Add a new named template type parameter to this context's item set.
779 pub(crate) fn add_type_param(
780 &mut self,
781 item: Item,
782 definition: clang::Cursor,
783 ) {
784 debug!(
785 "BindgenContext::add_type_param: item = {:?}; definition = {:?}",
786 item, definition
787 );
788
789 assert!(
790 item.expect_type().is_type_param(),
791 "Should directly be a named type, not a resolved reference or anything"
792 );
793 assert_eq!(
794 definition.kind(),
795 clang_sys::CXCursor_TemplateTypeParameter
796 );
797
798 self.add_item_to_module(&item);
799
800 let id = item.id();
801 let old_item = mem::replace(&mut self.items[id.0], Some(item));
802 assert!(
803 old_item.is_none(),
804 "should not have already associated an item with the given id"
805 );
806
807 let old_named_ty = self
808 .type_params
809 .insert(definition, id.as_type_id_unchecked());
810 assert!(
811 old_named_ty.is_none(),
812 "should not have already associated a named type with this id"
813 );
814 }
815
816 /// Get the named type defined at the given cursor location, if we've
817 /// already added one.
818 pub(crate) fn get_type_param(
819 &self,
820 definition: &clang::Cursor,
821 ) -> Option<TypeId> {
822 assert_eq!(
823 definition.kind(),
824 clang_sys::CXCursor_TemplateTypeParameter
825 );
826 self.type_params.get(definition).cloned()
827 }
828
829 // TODO: Move all this syntax crap to other part of the code.
830
831 /// Mangles a name so it doesn't conflict with any keyword.
832 #[rustfmt::skip]
833 pub(crate) fn rust_mangle<'a>(&self, name: &'a str) -> Cow<'a, str> {
834 if name.contains('@') ||
835 name.contains('?') ||
836 name.contains('$') ||
837 matches!(
838 name,
839 "abstract" | "alignof" | "as" | "async" | "await" | "become" |
840 "box" | "break" | "const" | "continue" | "crate" | "do" |
841 "dyn" | "else" | "enum" | "extern" | "false" | "final" |
842 "fn" | "for" | "if" | "impl" | "in" | "let" | "loop" |
843 "macro" | "match" | "mod" | "move" | "mut" | "offsetof" |
844 "override" | "priv" | "proc" | "pub" | "pure" | "ref" |
845 "return" | "Self" | "self" | "sizeof" | "static" |
846 "struct" | "super" | "trait" | "true" | "try" | "type" | "typeof" |
847 "unsafe" | "unsized" | "use" | "virtual" | "where" |
848 "while" | "yield" | "str" | "bool" | "f32" | "f64" |
849 "usize" | "isize" | "u128" | "i128" | "u64" | "i64" |
850 "u32" | "i32" | "u16" | "i16" | "u8" | "i8" | "_"
851 )
852 {
853 let mut s = name.to_owned();
854 s = s.replace('@', "_");
855 s = s.replace('?', "_");
856 s = s.replace('$', "_");
857 s.push('_');
858 return Cow::Owned(s);
859 }
860 Cow::Borrowed(name)
861 }
862
863 /// Returns a mangled name as a rust identifier.
864 pub(crate) fn rust_ident<S>(&self, name: S) -> Ident
865 where
866 S: AsRef<str>,
867 {
868 self.rust_ident_raw(self.rust_mangle(name.as_ref()))
869 }
870
871 /// Returns a mangled name as a rust identifier.
872 pub(crate) fn rust_ident_raw<T>(&self, name: T) -> Ident
873 where
874 T: AsRef<str>,
875 {
876 Ident::new(name.as_ref(), Span::call_site())
877 }
878
879 /// Iterate over all items that have been defined.
880 pub(crate) fn items(&self) -> impl Iterator<Item = (ItemId, &Item)> {
881 self.items.iter().enumerate().filter_map(|(index, item)| {
882 let item = item.as_ref()?;
883 Some((ItemId(index), item))
884 })
885 }
886
887 /// Have we collected all unresolved type references yet?
888 pub(crate) fn collected_typerefs(&self) -> bool {
889 self.collected_typerefs
890 }
891
892 /// Gather all the unresolved type references.
893 fn collect_typerefs(
894 &mut self,
895 ) -> Vec<(ItemId, clang::Type, clang::Cursor, Option<ItemId>)> {
896 debug_assert!(!self.collected_typerefs);
897 self.collected_typerefs = true;
898 let mut typerefs = vec![];
899
900 for (id, item) in self.items() {
901 let kind = item.kind();
902 let ty = match kind.as_type() {
903 Some(ty) => ty,
904 None => continue,
905 };
906
907 if let TypeKind::UnresolvedTypeRef(ref ty, loc, parent_id) =
908 *ty.kind()
909 {
910 typerefs.push((id, *ty, loc, parent_id));
911 };
912 }
913 typerefs
914 }
915
916 /// Collect all of our unresolved type references and resolve them.
917 fn resolve_typerefs(&mut self) {
918 let _t = self.timer("resolve_typerefs");
919
920 let typerefs = self.collect_typerefs();
921
922 for (id, ty, loc, parent_id) in typerefs {
923 let _resolved =
924 {
925 let resolved = Item::from_ty(&ty, loc, parent_id, self)
926 .unwrap_or_else(|_| {
927 warn!("Could not resolve type reference, falling back \
928 to opaque blob");
929 Item::new_opaque_type(self.next_item_id(), &ty, self)
930 });
931
932 let item = self.items[id.0].as_mut().unwrap();
933 *item.kind_mut().as_type_mut().unwrap().kind_mut() =
934 TypeKind::ResolvedTypeRef(resolved);
935 resolved
936 };
937
938 // Something in the STL is trolling me. I don't need this assertion
939 // right now, but worth investigating properly once this lands.
940 //
941 // debug_assert!(self.items.get(&resolved).is_some(), "How?");
942 //
943 // if let Some(parent_id) = parent_id {
944 // assert_eq!(self.items[&resolved].parent_id(), parent_id);
945 // }
946 }
947 }
948
949 /// Temporarily loan `Item` with the given `ItemId`. This provides means to
950 /// mutably borrow `Item` while having a reference to `BindgenContext`.
951 ///
952 /// `Item` with the given `ItemId` is removed from the context, given
953 /// closure is executed and then `Item` is placed back.
954 ///
955 /// # Panics
956 ///
957 /// Panics if attempt to resolve given `ItemId` inside the given
958 /// closure is made.
959 fn with_loaned_item<F, T>(&mut self, id: ItemId, f: F) -> T
960 where
961 F: (FnOnce(&BindgenContext, &mut Item) -> T),
962 {
963 let mut item = self.items[id.0].take().unwrap();
964
965 let result = f(self, &mut item);
966
967 let existing = mem::replace(&mut self.items[id.0], Some(item));
968 assert!(existing.is_none());
969
970 result
971 }
972
973 /// Compute the bitfield allocation units for all `TypeKind::Comp` items we
974 /// parsed.
975 fn compute_bitfield_units(&mut self) {
976 let _t = self.timer("compute_bitfield_units");
977
978 assert!(self.collected_typerefs());
979
980 let need_bitfield_allocation =
981 mem::take(&mut self.need_bitfield_allocation);
982 for id in need_bitfield_allocation {
983 self.with_loaned_item(id, |ctx, item| {
984 let ty = item.kind_mut().as_type_mut().unwrap();
985 let layout = ty.layout(ctx);
986 ty.as_comp_mut()
987 .unwrap()
988 .compute_bitfield_units(ctx, layout.as_ref());
989 });
990 }
991 }
992
993 /// Assign a new generated name for each anonymous field.
994 fn deanonymize_fields(&mut self) {
995 let _t = self.timer("deanonymize_fields");
996
997 let comp_item_ids: Vec<ItemId> = self
998 .items()
999 .filter_map(|(id, item)| {
1000 if item.kind().as_type()?.is_comp() {
1001 return Some(id);
1002 }
1003 None
1004 })
1005 .collect();
1006
1007 for id in comp_item_ids {
1008 self.with_loaned_item(id, |ctx, item| {
1009 item.kind_mut()
1010 .as_type_mut()
1011 .unwrap()
1012 .as_comp_mut()
1013 .unwrap()
1014 .deanonymize_fields(ctx);
1015 });
1016 }
1017 }
1018
1019 /// Iterate over all items and replace any item that has been named in a
1020 /// `replaces="SomeType"` annotation with the replacement type.
1021 fn process_replacements(&mut self) {
1022 let _t = self.timer("process_replacements");
1023 if self.replacements.is_empty() {
1024 debug!("No replacements to process");
1025 return;
1026 }
1027
1028 // FIXME: This is linear, but the replaces="xxx" annotation was already
1029 // there, and for better or worse it's useful, sigh...
1030 //
1031 // We leverage the ResolvedTypeRef thing, though, which is cool :P.
1032
1033 let mut replacements = vec![];
1034
1035 for (id, item) in self.items() {
1036 if item.annotations().use_instead_of().is_some() {
1037 continue;
1038 }
1039
1040 // Calls to `canonical_name` are expensive, so eagerly filter out
1041 // items that cannot be replaced.
1042 let ty = match item.kind().as_type() {
1043 Some(ty) => ty,
1044 None => continue,
1045 };
1046
1047 match *ty.kind() {
1048 TypeKind::Comp(..) |
1049 TypeKind::TemplateAlias(..) |
1050 TypeKind::Enum(..) |
1051 TypeKind::Alias(..) => {}
1052 _ => continue,
1053 }
1054
1055 let path = item.path_for_allowlisting(self);
1056 let replacement = self.replacements.get(&path[1..]);
1057
1058 if let Some(replacement) = replacement {
1059 if *replacement != id {
1060 // We set this just after parsing the annotation. It's
1061 // very unlikely, but this can happen.
1062 if self.resolve_item_fallible(*replacement).is_some() {
1063 replacements.push((
1064 id.expect_type_id(self),
1065 replacement.expect_type_id(self),
1066 ));
1067 }
1068 }
1069 }
1070 }
1071
1072 for (id, replacement_id) in replacements {
1073 debug!("Replacing {:?} with {:?}", id, replacement_id);
1074 let new_parent = {
1075 let item_id: ItemId = id.into();
1076 let item = self.items[item_id.0].as_mut().unwrap();
1077 *item.kind_mut().as_type_mut().unwrap().kind_mut() =
1078 TypeKind::ResolvedTypeRef(replacement_id);
1079 item.parent_id()
1080 };
1081
1082 // Relocate the replacement item from where it was declared, to
1083 // where the thing it is replacing was declared.
1084 //
1085 // First, we'll make sure that its parent ID is correct.
1086
1087 let old_parent = self.resolve_item(replacement_id).parent_id();
1088 if new_parent == old_parent {
1089 // Same parent and therefore also same containing
1090 // module. Nothing to do here.
1091 continue;
1092 }
1093
1094 let replacement_item_id: ItemId = replacement_id.into();
1095 self.items[replacement_item_id.0]
1096 .as_mut()
1097 .unwrap()
1098 .set_parent_for_replacement(new_parent);
1099
1100 // Second, make sure that it is in the correct module's children
1101 // set.
1102
1103 let old_module = {
1104 let immut_self = &*self;
1105 old_parent
1106 .ancestors(immut_self)
1107 .chain(Some(immut_self.root_module.into()))
1108 .find(|id| {
1109 let item = immut_self.resolve_item(*id);
1110 item.as_module().map_or(false, |m| {
1111 m.children().contains(&replacement_id.into())
1112 })
1113 })
1114 };
1115 let old_module = old_module
1116 .expect("Every replacement item should be in a module");
1117
1118 let new_module = {
1119 let immut_self = &*self;
1120 new_parent
1121 .ancestors(immut_self)
1122 .find(|id| immut_self.resolve_item(*id).is_module())
1123 };
1124 let new_module =
1125 new_module.unwrap_or_else(|| self.root_module.into());
1126
1127 if new_module == old_module {
1128 // Already in the correct module.
1129 continue;
1130 }
1131
1132 self.items[old_module.0]
1133 .as_mut()
1134 .unwrap()
1135 .as_module_mut()
1136 .unwrap()
1137 .children_mut()
1138 .remove(&replacement_id.into());
1139
1140 self.items[new_module.0]
1141 .as_mut()
1142 .unwrap()
1143 .as_module_mut()
1144 .unwrap()
1145 .children_mut()
1146 .insert(replacement_id.into());
1147 }
1148 }
1149
1150 /// Enter the code generation phase, invoke the given callback `cb`, and
1151 /// leave the code generation phase.
1152 pub(crate) fn gen<F, Out>(
1153 mut self,
1154 cb: F,
1155 ) -> Result<(Out, BindgenOptions), CodegenError>
1156 where
1157 F: FnOnce(&Self) -> Result<Out, CodegenError>,
1158 {
1159 self.in_codegen = true;
1160
1161 self.resolve_typerefs();
1162 self.compute_bitfield_units();
1163 self.process_replacements();
1164
1165 self.deanonymize_fields();
1166
1167 self.assert_no_dangling_references();
1168
1169 // Compute the allowlisted set after processing replacements and
1170 // resolving type refs, as those are the final mutations of the IR
1171 // graph, and their completion means that the IR graph is now frozen.
1172 self.compute_allowlisted_and_codegen_items();
1173
1174 // Make sure to do this after processing replacements, since that messes
1175 // with the parentage and module children, and we want to assert that it
1176 // messes with them correctly.
1177 self.assert_every_item_in_a_module();
1178
1179 self.compute_has_vtable();
1180 self.compute_sizedness();
1181 self.compute_has_destructor();
1182 self.find_used_template_parameters();
1183 self.compute_enum_typedef_combos();
1184 self.compute_cannot_derive_debug();
1185 self.compute_cannot_derive_default();
1186 self.compute_cannot_derive_copy();
1187 self.compute_has_type_param_in_array();
1188 self.compute_has_float();
1189 self.compute_cannot_derive_hash();
1190 self.compute_cannot_derive_partialord_partialeq_or_eq();
1191
1192 let ret = cb(&self)?;
1193 Ok((ret, self.options))
1194 }
1195
1196 /// When the `testing_only_extra_assertions` feature is enabled, this
1197 /// function walks the IR graph and asserts that we do not have any edges
1198 /// referencing an ItemId for which we do not have an associated IR item.
1199 fn assert_no_dangling_references(&self) {
1200 if cfg!(feature = "testing_only_extra_assertions") {
1201 for _ in self.assert_no_dangling_item_traversal() {
1202 // The iterator's next method does the asserting for us.
1203 }
1204 }
1205 }
1206
1207 fn assert_no_dangling_item_traversal(
1208 &self,
1209 ) -> traversal::AssertNoDanglingItemsTraversal {
1210 assert!(self.in_codegen_phase());
1211 assert!(self.current_module == self.root_module);
1212
1213 let roots = self.items().map(|(id, _)| id);
1214 traversal::AssertNoDanglingItemsTraversal::new(
1215 self,
1216 roots,
1217 traversal::all_edges,
1218 )
1219 }
1220
1221 /// When the `testing_only_extra_assertions` feature is enabled, walk over
1222 /// every item and ensure that it is in the children set of one of its
1223 /// module ancestors.
1224 fn assert_every_item_in_a_module(&self) {
1225 if cfg!(feature = "testing_only_extra_assertions") {
1226 assert!(self.in_codegen_phase());
1227 assert!(self.current_module == self.root_module);
1228
1229 for (id, _item) in self.items() {
1230 if id == self.root_module {
1231 continue;
1232 }
1233
1234 assert!(
1235 {
1236 let id = id
1237 .into_resolver()
1238 .through_type_refs()
1239 .through_type_aliases()
1240 .resolve(self)
1241 .id();
1242 id.ancestors(self)
1243 .chain(Some(self.root_module.into()))
1244 .any(|ancestor| {
1245 debug!(
1246 "Checking if {:?} is a child of {:?}",
1247 id, ancestor
1248 );
1249 self.resolve_item(ancestor)
1250 .as_module()
1251 .map_or(false, |m| {
1252 m.children().contains(&id)
1253 })
1254 })
1255 },
1256 "{:?} should be in some ancestor module's children set",
1257 id
1258 );
1259 }
1260 }
1261 }
1262
1263 /// Compute for every type whether it is sized or not, and whether it is
1264 /// sized or not as a base class.
1265 fn compute_sizedness(&mut self) {
1266 let _t = self.timer("compute_sizedness");
1267 assert!(self.sizedness.is_none());
1268 self.sizedness = Some(analyze::<SizednessAnalysis>(self));
1269 }
1270
1271 /// Look up whether the type with the given ID is sized or not.
1272 pub(crate) fn lookup_sizedness(&self, id: TypeId) -> SizednessResult {
1273 assert!(
1274 self.in_codegen_phase(),
1275 "We only compute sizedness after we've entered codegen"
1276 );
1277
1278 self.sizedness
1279 .as_ref()
1280 .unwrap()
1281 .get(&id)
1282 .cloned()
1283 .unwrap_or(SizednessResult::ZeroSized)
1284 }
1285
1286 /// Compute whether the type has vtable.
1287 fn compute_has_vtable(&mut self) {
1288 let _t = self.timer("compute_has_vtable");
1289 assert!(self.have_vtable.is_none());
1290 self.have_vtable = Some(analyze::<HasVtableAnalysis>(self));
1291 }
1292
1293 /// Look up whether the item with `id` has vtable or not.
1294 pub(crate) fn lookup_has_vtable(&self, id: TypeId) -> HasVtableResult {
1295 assert!(
1296 self.in_codegen_phase(),
1297 "We only compute vtables when we enter codegen"
1298 );
1299
1300 // Look up the computed value for whether the item with `id` has a
1301 // vtable or not.
1302 self.have_vtable
1303 .as_ref()
1304 .unwrap()
1305 .get(&id.into())
1306 .cloned()
1307 .unwrap_or(HasVtableResult::No)
1308 }
1309
1310 /// Compute whether the type has a destructor.
1311 fn compute_has_destructor(&mut self) {
1312 let _t = self.timer("compute_has_destructor");
1313 assert!(self.have_destructor.is_none());
1314 self.have_destructor = Some(analyze::<HasDestructorAnalysis>(self));
1315 }
1316
1317 /// Look up whether the item with `id` has a destructor.
1318 pub(crate) fn lookup_has_destructor(&self, id: TypeId) -> bool {
1319 assert!(
1320 self.in_codegen_phase(),
1321 "We only compute destructors when we enter codegen"
1322 );
1323
1324 self.have_destructor.as_ref().unwrap().contains(&id.into())
1325 }
1326
1327 fn find_used_template_parameters(&mut self) {
1328 let _t = self.timer("find_used_template_parameters");
1329 if self.options.allowlist_recursively {
1330 let used_params = analyze::<UsedTemplateParameters>(self);
1331 self.used_template_parameters = Some(used_params);
1332 } else {
1333 // If you aren't recursively allowlisting, then we can't really make
1334 // any sense of template parameter usage, and you're on your own.
1335 let mut used_params = HashMap::default();
1336 for &id in self.allowlisted_items() {
1337 used_params.entry(id).or_insert_with(|| {
1338 id.self_template_params(self)
1339 .into_iter()
1340 .map(|p| p.into())
1341 .collect()
1342 });
1343 }
1344 self.used_template_parameters = Some(used_params);
1345 }
1346 }
1347
1348 /// Return `true` if `item` uses the given `template_param`, `false`
1349 /// otherwise.
1350 ///
1351 /// This method may only be called during the codegen phase, because the
1352 /// template usage information is only computed as we enter the codegen
1353 /// phase.
1354 ///
1355 /// If the item is blocklisted, then we say that it always uses the template
1356 /// parameter. This is a little subtle. The template parameter usage
1357 /// analysis only considers allowlisted items, and if any blocklisted item
1358 /// shows up in the generated bindings, it is the user's responsibility to
1359 /// manually provide a definition for them. To give them the most
1360 /// flexibility when doing that, we assume that they use every template
1361 /// parameter and always pass template arguments through in instantiations.
1362 pub(crate) fn uses_template_parameter(
1363 &self,
1364 item: ItemId,
1365 template_param: TypeId,
1366 ) -> bool {
1367 assert!(
1368 self.in_codegen_phase(),
1369 "We only compute template parameter usage as we enter codegen"
1370 );
1371
1372 if self.resolve_item(item).is_blocklisted(self) {
1373 return true;
1374 }
1375
1376 let template_param = template_param
1377 .into_resolver()
1378 .through_type_refs()
1379 .through_type_aliases()
1380 .resolve(self)
1381 .id();
1382
1383 self.used_template_parameters
1384 .as_ref()
1385 .expect("should have found template parameter usage if we're in codegen")
1386 .get(&item)
1387 .map_or(false, |items_used_params| items_used_params.contains(&template_param))
1388 }
1389
1390 /// Return `true` if `item` uses any unbound, generic template parameters,
1391 /// `false` otherwise.
1392 ///
1393 /// Has the same restrictions that `uses_template_parameter` has.
1394 pub(crate) fn uses_any_template_parameters(&self, item: ItemId) -> bool {
1395 assert!(
1396 self.in_codegen_phase(),
1397 "We only compute template parameter usage as we enter codegen"
1398 );
1399
1400 self.used_template_parameters
1401 .as_ref()
1402 .expect(
1403 "should have template parameter usage info in codegen phase",
1404 )
1405 .get(&item)
1406 .map_or(false, |used| !used.is_empty())
1407 }
1408
1409 // This deserves a comment. Builtin types don't get a valid declaration, so
1410 // we can't add it to the cursor->type map.
1411 //
1412 // That being said, they're not generated anyway, and are few, so the
1413 // duplication and special-casing is fine.
1414 //
1415 // If at some point we care about the memory here, probably a map TypeKind
1416 // -> builtin type ItemId would be the best to improve that.
1417 fn add_builtin_item(&mut self, item: Item) {
1418 debug!("add_builtin_item: item = {:?}", item);
1419 debug_assert!(item.kind().is_type());
1420 self.add_item_to_module(&item);
1421 let id = item.id();
1422 let old_item = mem::replace(&mut self.items[id.0], Some(item));
1423 assert!(old_item.is_none(), "Inserted type twice?");
1424 }
1425
1426 fn build_root_module(id: ItemId) -> Item {
1427 let module = Module::new(Some("root".into()), ModuleKind::Normal);
1428 Item::new(id, None, None, id, ItemKind::Module(module), None)
1429 }
1430
1431 /// Get the root module.
1432 pub(crate) fn root_module(&self) -> ModuleId {
1433 self.root_module
1434 }
1435
1436 /// Resolve a type with the given ID.
1437 ///
1438 /// Panics if there is no item for the given `TypeId` or if the resolved
1439 /// item is not a `Type`.
1440 pub(crate) fn resolve_type(&self, type_id: TypeId) -> &Type {
1441 self.resolve_item(type_id).kind().expect_type()
1442 }
1443
1444 /// Resolve a function with the given ID.
1445 ///
1446 /// Panics if there is no item for the given `FunctionId` or if the resolved
1447 /// item is not a `Function`.
1448 pub(crate) fn resolve_func(&self, func_id: FunctionId) -> &Function {
1449 self.resolve_item(func_id).kind().expect_function()
1450 }
1451
1452 /// Resolve the given `ItemId` as a type, or `None` if there is no item with
1453 /// the given ID.
1454 ///
1455 /// Panics if the ID resolves to an item that is not a type.
1456 pub(crate) fn safe_resolve_type(&self, type_id: TypeId) -> Option<&Type> {
1457 self.resolve_item_fallible(type_id)
1458 .map(|t| t.kind().expect_type())
1459 }
1460
1461 /// Resolve the given `ItemId` into an `Item`, or `None` if no such item
1462 /// exists.
1463 pub(crate) fn resolve_item_fallible<Id: Into<ItemId>>(
1464 &self,
1465 id: Id,
1466 ) -> Option<&Item> {
1467 self.items.get(id.into().0)?.as_ref()
1468 }
1469
1470 /// Resolve the given `ItemId` into an `Item`.
1471 ///
1472 /// Panics if the given ID does not resolve to any item.
1473 pub(crate) fn resolve_item<Id: Into<ItemId>>(&self, item_id: Id) -> &Item {
1474 let item_id = item_id.into();
1475 match self.resolve_item_fallible(item_id) {
1476 Some(item) => item,
1477 None => panic!("Not an item: {:?}", item_id),
1478 }
1479 }
1480
1481 /// Get the current module.
1482 pub(crate) fn current_module(&self) -> ModuleId {
1483 self.current_module
1484 }
1485
1486 /// Add a semantic parent for a given type definition.
1487 ///
1488 /// We do this from the type declaration, in order to be able to find the
1489 /// correct type definition afterwards.
1490 ///
1491 /// TODO(emilio): We could consider doing this only when
1492 /// declaration.lexical_parent() != definition.lexical_parent(), but it's
1493 /// not sure it's worth it.
1494 pub(crate) fn add_semantic_parent(
1495 &mut self,
1496 definition: clang::Cursor,
1497 parent_id: ItemId,
1498 ) {
1499 self.semantic_parents.insert(definition, parent_id);
1500 }
1501
1502 /// Returns a known semantic parent for a given definition.
1503 pub(crate) fn known_semantic_parent(
1504 &self,
1505 definition: clang::Cursor,
1506 ) -> Option<ItemId> {
1507 self.semantic_parents.get(&definition).cloned()
1508 }
1509
1510 /// Given a cursor pointing to the location of a template instantiation,
1511 /// return a tuple of the form `(declaration_cursor, declaration_id,
1512 /// num_expected_template_args)`.
1513 ///
1514 /// Note that `declaration_id` is not guaranteed to be in the context's item
1515 /// set! It is possible that it is a partial type that we are still in the
1516 /// middle of parsing.
1517 fn get_declaration_info_for_template_instantiation(
1518 &self,
1519 instantiation: &Cursor,
1520 ) -> Option<(Cursor, ItemId, usize)> {
1521 instantiation
1522 .cur_type()
1523 .canonical_declaration(Some(instantiation))
1524 .and_then(|canon_decl| {
1525 self.get_resolved_type(&canon_decl).and_then(
1526 |template_decl_id| {
1527 let num_params =
1528 template_decl_id.num_self_template_params(self);
1529 if num_params == 0 {
1530 None
1531 } else {
1532 Some((
1533 *canon_decl.cursor(),
1534 template_decl_id.into(),
1535 num_params,
1536 ))
1537 }
1538 },
1539 )
1540 })
1541 .or_else(|| {
1542 // If we haven't already parsed the declaration of
1543 // the template being instantiated, then it *must*
1544 // be on the stack of types we are currently
1545 // parsing. If it wasn't then clang would have
1546 // already errored out before we started
1547 // constructing our IR because you can't instantiate
1548 // a template until it is fully defined.
1549 instantiation
1550 .referenced()
1551 .and_then(|referenced| {
1552 self.currently_parsed_types()
1553 .iter()
1554 .find(|partial_ty| *partial_ty.decl() == referenced)
1555 .cloned()
1556 })
1557 .and_then(|template_decl| {
1558 let num_template_params =
1559 template_decl.num_self_template_params(self);
1560 if num_template_params == 0 {
1561 None
1562 } else {
1563 Some((
1564 *template_decl.decl(),
1565 template_decl.id(),
1566 num_template_params,
1567 ))
1568 }
1569 })
1570 })
1571 }
1572
1573 /// Parse a template instantiation, eg `Foo<int>`.
1574 ///
1575 /// This is surprisingly difficult to do with libclang, due to the fact that
1576 /// it doesn't provide explicit template argument information, except for
1577 /// function template declarations(!?!??!).
1578 ///
1579 /// The only way to do this is manually inspecting the AST and looking for
1580 /// TypeRefs and TemplateRefs inside. This, unfortunately, doesn't work for
1581 /// more complex cases, see the comment on the assertion below.
1582 ///
1583 /// To add insult to injury, the AST itself has structure that doesn't make
1584 /// sense. Sometimes `Foo<Bar<int>>` has an AST with nesting like you might
1585 /// expect: `(Foo (Bar (int)))`. Other times, the AST we get is completely
1586 /// flat: `(Foo Bar int)`.
1587 ///
1588 /// To see an example of what this method handles:
1589 ///
1590 /// ```c++
1591 /// template<typename T>
1592 /// class Incomplete {
1593 /// T p;
1594 /// };
1595 ///
1596 /// template<typename U>
1597 /// class Foo {
1598 /// Incomplete<U> bar;
1599 /// };
1600 /// ```
1601 ///
1602 /// Finally, template instantiations are always children of the current
1603 /// module. They use their template's definition for their name, so the
1604 /// parent is only useful for ensuring that their layout tests get
1605 /// codegen'd.
1606 fn instantiate_template(
1607 &mut self,
1608 with_id: ItemId,
1609 template: TypeId,
1610 ty: &clang::Type,
1611 location: clang::Cursor,
1612 ) -> Option<TypeId> {
1613 let num_expected_args =
1614 self.resolve_type(template).num_self_template_params(self);
1615 if num_expected_args == 0 {
1616 warn!(
1617 "Tried to instantiate a template for which we could not \
1618 determine any template parameters"
1619 );
1620 return None;
1621 }
1622
1623 let mut args = vec![];
1624 let mut found_const_arg = false;
1625 let mut children = location.collect_children();
1626
1627 if children.iter().all(|c| !c.has_children()) {
1628 // This is insanity... If clang isn't giving us a properly nested
1629 // AST for which template arguments belong to which template we are
1630 // instantiating, we'll need to construct it ourselves. However,
1631 // there is an extra `NamespaceRef, NamespaceRef, ..., TemplateRef`
1632 // representing a reference to the outermost template declaration
1633 // that we need to filter out of the children. We need to do this
1634 // filtering because we already know which template declaration is
1635 // being specialized via the `location`'s type, and if we do not
1636 // filter it out, we'll add an extra layer of template instantiation
1637 // on accident.
1638 let idx = children
1639 .iter()
1640 .position(|c| c.kind() == clang_sys::CXCursor_TemplateRef);
1641 if let Some(idx) = idx {
1642 if children
1643 .iter()
1644 .take(idx)
1645 .all(|c| c.kind() == clang_sys::CXCursor_NamespaceRef)
1646 {
1647 children = children.into_iter().skip(idx + 1).collect();
1648 }
1649 }
1650 }
1651
1652 for child in children.iter().rev() {
1653 match child.kind() {
1654 clang_sys::CXCursor_TypeRef |
1655 clang_sys::CXCursor_TypedefDecl |
1656 clang_sys::CXCursor_TypeAliasDecl => {
1657 // The `with_id` ID will potentially end up unused if we give up
1658 // on this type (for example, because it has const value
1659 // template args), so if we pass `with_id` as the parent, it is
1660 // potentially a dangling reference. Instead, use the canonical
1661 // template declaration as the parent. It is already parsed and
1662 // has a known-resolvable `ItemId`.
1663 let ty = Item::from_ty_or_ref(
1664 child.cur_type(),
1665 *child,
1666 Some(template.into()),
1667 self,
1668 );
1669 args.push(ty);
1670 }
1671 clang_sys::CXCursor_TemplateRef => {
1672 let (
1673 template_decl_cursor,
1674 template_decl_id,
1675 num_expected_template_args,
1676 ) = self.get_declaration_info_for_template_instantiation(
1677 child,
1678 )?;
1679
1680 if num_expected_template_args == 0 ||
1681 child.has_at_least_num_children(
1682 num_expected_template_args,
1683 )
1684 {
1685 // Do a happy little parse. See comment in the TypeRef
1686 // match arm about parent IDs.
1687 let ty = Item::from_ty_or_ref(
1688 child.cur_type(),
1689 *child,
1690 Some(template.into()),
1691 self,
1692 );
1693 args.push(ty);
1694 } else {
1695 // This is the case mentioned in the doc comment where
1696 // clang gives us a flattened AST and we have to
1697 // reconstruct which template arguments go to which
1698 // instantiation :(
1699 let args_len = args.len();
1700 if args_len < num_expected_template_args {
1701 warn!(
1702 "Found a template instantiation without \
1703 enough template arguments"
1704 );
1705 return None;
1706 }
1707
1708 let mut sub_args: Vec<_> = args
1709 .drain(args_len - num_expected_template_args..)
1710 .collect();
1711 sub_args.reverse();
1712
1713 let sub_name = Some(template_decl_cursor.spelling());
1714 let sub_inst = TemplateInstantiation::new(
1715 // This isn't guaranteed to be a type that we've
1716 // already finished parsing yet.
1717 template_decl_id.as_type_id_unchecked(),
1718 sub_args,
1719 );
1720 let sub_kind =
1721 TypeKind::TemplateInstantiation(sub_inst);
1722 let sub_ty = Type::new(
1723 sub_name,
1724 template_decl_cursor
1725 .cur_type()
1726 .fallible_layout(self)
1727 .ok(),
1728 sub_kind,
1729 false,
1730 );
1731 let sub_id = self.next_item_id();
1732 let sub_item = Item::new(
1733 sub_id,
1734 None,
1735 None,
1736 self.current_module.into(),
1737 ItemKind::Type(sub_ty),
1738 Some(child.location()),
1739 );
1740
1741 // Bypass all the validations in add_item explicitly.
1742 debug!(
1743 "instantiate_template: inserting nested \
1744 instantiation item: {:?}",
1745 sub_item
1746 );
1747 self.add_item_to_module(&sub_item);
1748 debug_assert_eq!(sub_id, sub_item.id());
1749 self.items[sub_id.0] = Some(sub_item);
1750 args.push(sub_id.as_type_id_unchecked());
1751 }
1752 }
1753 _ => {
1754 warn!(
1755 "Found template arg cursor we can't handle: {:?}",
1756 child
1757 );
1758 found_const_arg = true;
1759 }
1760 }
1761 }
1762
1763 if found_const_arg {
1764 // This is a dependently typed template instantiation. That is, an
1765 // instantiation of a template with one or more const values as
1766 // template arguments, rather than only types as template
1767 // arguments. For example, `Foo<true, 5>` versus `Bar<bool, int>`.
1768 // We can't handle these instantiations, so just punt in this
1769 // situation...
1770 warn!(
1771 "Found template instantiated with a const value; \
1772 bindgen can't handle this kind of template instantiation!"
1773 );
1774 return None;
1775 }
1776
1777 if args.len() != num_expected_args {
1778 warn!(
1779 "Found a template with an unexpected number of template \
1780 arguments"
1781 );
1782 return None;
1783 }
1784
1785 args.reverse();
1786 let type_kind = TypeKind::TemplateInstantiation(
1787 TemplateInstantiation::new(template, args),
1788 );
1789 let name = ty.spelling();
1790 let name = if name.is_empty() { None } else { Some(name) };
1791 let ty = Type::new(
1792 name,
1793 ty.fallible_layout(self).ok(),
1794 type_kind,
1795 ty.is_const(),
1796 );
1797 let item = Item::new(
1798 with_id,
1799 None,
1800 None,
1801 self.current_module.into(),
1802 ItemKind::Type(ty),
1803 Some(location.location()),
1804 );
1805
1806 // Bypass all the validations in add_item explicitly.
1807 debug!("instantiate_template: inserting item: {:?}", item);
1808 self.add_item_to_module(&item);
1809 debug_assert_eq!(with_id, item.id());
1810 self.items[with_id.0] = Some(item);
1811 Some(with_id.as_type_id_unchecked())
1812 }
1813
1814 /// If we have already resolved the type for the given type declaration,
1815 /// return its `ItemId`. Otherwise, return `None`.
1816 pub(crate) fn get_resolved_type(
1817 &self,
1818 decl: &clang::CanonicalTypeDeclaration,
1819 ) -> Option<TypeId> {
1820 self.types
1821 .get(&TypeKey::Declaration(*decl.cursor()))
1822 .or_else(|| {
1823 decl.cursor()
1824 .usr()
1825 .and_then(|usr| self.types.get(&TypeKey::Usr(usr)))
1826 })
1827 .cloned()
1828 }
1829
1830 /// Looks up for an already resolved type, either because it's builtin, or
1831 /// because we already have it in the map.
1832 pub(crate) fn builtin_or_resolved_ty(
1833 &mut self,
1834 with_id: ItemId,
1835 parent_id: Option<ItemId>,
1836 ty: &clang::Type,
1837 location: Option<clang::Cursor>,
1838 ) -> Option<TypeId> {
1839 use clang_sys::{CXCursor_TypeAliasTemplateDecl, CXCursor_TypeRef};
1840 debug!(
1841 "builtin_or_resolved_ty: {:?}, {:?}, {:?}, {:?}",
1842 ty, location, with_id, parent_id
1843 );
1844
1845 if let Some(decl) = ty.canonical_declaration(location.as_ref()) {
1846 if let Some(id) = self.get_resolved_type(&decl) {
1847 debug!(
1848 "Already resolved ty {:?}, {:?}, {:?} {:?}",
1849 id, decl, ty, location
1850 );
1851 // If the declaration already exists, then either:
1852 //
1853 // * the declaration is a template declaration of some sort,
1854 // and we are looking at an instantiation or specialization
1855 // of it, or
1856 // * we have already parsed and resolved this type, and
1857 // there's nothing left to do.
1858 if let Some(location) = location {
1859 if decl.cursor().is_template_like() &&
1860 *ty != decl.cursor().cur_type()
1861 {
1862 // For specialized type aliases, there's no way to get the
1863 // template parameters as of this writing (for a struct
1864 // specialization we wouldn't be in this branch anyway).
1865 //
1866 // Explicitly return `None` if there aren't any
1867 // unspecialized parameters (contains any `TypeRef`) so we
1868 // resolve the canonical type if there is one and it's
1869 // exposed.
1870 //
1871 // This is _tricky_, I know :(
1872 if decl.cursor().kind() ==
1873 CXCursor_TypeAliasTemplateDecl &&
1874 !location.contains_cursor(CXCursor_TypeRef) &&
1875 ty.canonical_type().is_valid_and_exposed()
1876 {
1877 return None;
1878 }
1879
1880 return self
1881 .instantiate_template(with_id, id, ty, location)
1882 .or(Some(id));
1883 }
1884 }
1885
1886 return Some(self.build_ty_wrapper(with_id, id, parent_id, ty));
1887 }
1888 }
1889
1890 debug!("Not resolved, maybe builtin?");
1891 self.build_builtin_ty(ty)
1892 }
1893
1894 /// Make a new item that is a resolved type reference to the `wrapped_id`.
1895 ///
1896 /// This is unfortunately a lot of bloat, but is needed to properly track
1897 /// constness et al.
1898 ///
1899 /// We should probably make the constness tracking separate, so it doesn't
1900 /// bloat that much, but hey, we already bloat the heck out of builtin
1901 /// types.
1902 pub(crate) fn build_ty_wrapper(
1903 &mut self,
1904 with_id: ItemId,
1905 wrapped_id: TypeId,
1906 parent_id: Option<ItemId>,
1907 ty: &clang::Type,
1908 ) -> TypeId {
1909 self.build_wrapper(with_id, wrapped_id, parent_id, ty, ty.is_const())
1910 }
1911
1912 /// A wrapper over a type that adds a const qualifier explicitly.
1913 ///
1914 /// Needed to handle const methods in C++, wrapping the type .
1915 pub(crate) fn build_const_wrapper(
1916 &mut self,
1917 with_id: ItemId,
1918 wrapped_id: TypeId,
1919 parent_id: Option<ItemId>,
1920 ty: &clang::Type,
1921 ) -> TypeId {
1922 self.build_wrapper(
1923 with_id, wrapped_id, parent_id, ty, /* is_const = */ true,
1924 )
1925 }
1926
1927 fn build_wrapper(
1928 &mut self,
1929 with_id: ItemId,
1930 wrapped_id: TypeId,
1931 parent_id: Option<ItemId>,
1932 ty: &clang::Type,
1933 is_const: bool,
1934 ) -> TypeId {
1935 let spelling = ty.spelling();
1936 let layout = ty.fallible_layout(self).ok();
1937 let location = ty.declaration().location();
1938 let type_kind = TypeKind::ResolvedTypeRef(wrapped_id);
1939 let ty = Type::new(Some(spelling), layout, type_kind, is_const);
1940 let item = Item::new(
1941 with_id,
1942 None,
1943 None,
1944 parent_id.unwrap_or_else(|| self.current_module.into()),
1945 ItemKind::Type(ty),
1946 Some(location),
1947 );
1948 self.add_builtin_item(item);
1949 with_id.as_type_id_unchecked()
1950 }
1951
1952 /// Returns the next item ID to be used for an item.
1953 pub(crate) fn next_item_id(&mut self) -> ItemId {
1954 let ret = ItemId(self.items.len());
1955 self.items.push(None);
1956 ret
1957 }
1958
1959 fn build_builtin_ty(&mut self, ty: &clang::Type) -> Option<TypeId> {
1960 use clang_sys::*;
1961 let type_kind = match ty.kind() {
1962 CXType_NullPtr => TypeKind::NullPtr,
1963 CXType_Void => TypeKind::Void,
1964 CXType_Bool => TypeKind::Int(IntKind::Bool),
1965 CXType_Int => TypeKind::Int(IntKind::Int),
1966 CXType_UInt => TypeKind::Int(IntKind::UInt),
1967 CXType_Char_S => TypeKind::Int(IntKind::Char { is_signed: true }),
1968 CXType_Char_U => TypeKind::Int(IntKind::Char { is_signed: false }),
1969 CXType_SChar => TypeKind::Int(IntKind::SChar),
1970 CXType_UChar => TypeKind::Int(IntKind::UChar),
1971 CXType_Short => TypeKind::Int(IntKind::Short),
1972 CXType_UShort => TypeKind::Int(IntKind::UShort),
1973 CXType_WChar => TypeKind::Int(IntKind::WChar),
1974 CXType_Char16 => TypeKind::Int(IntKind::U16),
1975 CXType_Char32 => TypeKind::Int(IntKind::U32),
1976 CXType_Long => TypeKind::Int(IntKind::Long),
1977 CXType_ULong => TypeKind::Int(IntKind::ULong),
1978 CXType_LongLong => TypeKind::Int(IntKind::LongLong),
1979 CXType_ULongLong => TypeKind::Int(IntKind::ULongLong),
1980 CXType_Int128 => TypeKind::Int(IntKind::I128),
1981 CXType_UInt128 => TypeKind::Int(IntKind::U128),
1982 CXType_Float => TypeKind::Float(FloatKind::Float),
1983 CXType_Double => TypeKind::Float(FloatKind::Double),
1984 CXType_LongDouble => TypeKind::Float(FloatKind::LongDouble),
1985 CXType_Float128 => TypeKind::Float(FloatKind::Float128),
1986 CXType_Complex => {
1987 let float_type =
1988 ty.elem_type().expect("Not able to resolve complex type?");
1989 let float_kind = match float_type.kind() {
1990 CXType_Float => FloatKind::Float,
1991 CXType_Double => FloatKind::Double,
1992 CXType_LongDouble => FloatKind::LongDouble,
1993 CXType_Float128 => FloatKind::Float128,
1994 _ => panic!(
1995 "Non floating-type complex? {:?}, {:?}",
1996 ty, float_type,
1997 ),
1998 };
1999 TypeKind::Complex(float_kind)
2000 }
2001 _ => return None,
2002 };
2003
2004 let spelling = ty.spelling();
2005 let is_const = ty.is_const();
2006 let layout = ty.fallible_layout(self).ok();
2007 let location = ty.declaration().location();
2008 let ty = Type::new(Some(spelling), layout, type_kind, is_const);
2009 let id = self.next_item_id();
2010 let item = Item::new(
2011 id,
2012 None,
2013 None,
2014 self.root_module.into(),
2015 ItemKind::Type(ty),
2016 Some(location),
2017 );
2018 self.add_builtin_item(item);
2019 Some(id.as_type_id_unchecked())
2020 }
2021
2022 /// Get the current Clang translation unit that is being processed.
2023 pub(crate) fn translation_unit(&self) -> &clang::TranslationUnit {
2024 &self.translation_unit
2025 }
2026
2027 /// Have we parsed the macro named `macro_name` already?
2028 pub(crate) fn parsed_macro(&self, macro_name: &[u8]) -> bool {
2029 self.parsed_macros.contains_key(macro_name)
2030 }
2031
2032 /// Get the currently parsed macros.
2033 pub(crate) fn parsed_macros(
2034 &self,
2035 ) -> &StdHashMap<Vec<u8>, cexpr::expr::EvalResult> {
2036 debug_assert!(!self.in_codegen_phase());
2037 &self.parsed_macros
2038 }
2039
2040 /// Mark the macro named `macro_name` as parsed.
2041 pub(crate) fn note_parsed_macro(
2042 &mut self,
2043 id: Vec<u8>,
2044 value: cexpr::expr::EvalResult,
2045 ) {
2046 self.parsed_macros.insert(id, value);
2047 }
2048
2049 /// Are we in the codegen phase?
2050 pub(crate) fn in_codegen_phase(&self) -> bool {
2051 self.in_codegen
2052 }
2053
2054 /// Mark the type with the given `name` as replaced by the type with ID
2055 /// `potential_ty`.
2056 ///
2057 /// Replacement types are declared using the `replaces="xxx"` annotation,
2058 /// and implies that the original type is hidden.
2059 pub(crate) fn replace(&mut self, name: &[String], potential_ty: ItemId) {
2060 match self.replacements.entry(name.into()) {
2061 Entry::Vacant(entry) => {
2062 debug!(
2063 "Defining replacement for {:?} as {:?}",
2064 name, potential_ty
2065 );
2066 entry.insert(potential_ty);
2067 }
2068 Entry::Occupied(occupied) => {
2069 warn!(
2070 "Replacement for {:?} already defined as {:?}; \
2071 ignoring duplicate replacement definition as {:?}",
2072 name,
2073 occupied.get(),
2074 potential_ty
2075 );
2076 }
2077 }
2078 }
2079
2080 /// Has the item with the given `name` and `id` been replaced by another
2081 /// type?
2082 pub(crate) fn is_replaced_type<Id: Into<ItemId>>(
2083 &self,
2084 path: &[String],
2085 id: Id,
2086 ) -> bool {
2087 let id = id.into();
2088 matches!(self.replacements.get(path), Some(replaced_by) if *replaced_by != id)
2089 }
2090
2091 /// Is the type with the given `name` marked as opaque?
2092 pub(crate) fn opaque_by_name(&self, path: &[String]) -> bool {
2093 debug_assert!(
2094 self.in_codegen_phase(),
2095 "You're not supposed to call this yet"
2096 );
2097 self.options.opaque_types.matches(path[1..].join("::"))
2098 }
2099
2100 /// Get the options used to configure this bindgen context.
2101 pub(crate) fn options(&self) -> &BindgenOptions {
2102 &self.options
2103 }
2104
2105 /// Tokenizes a namespace cursor in order to get the name and kind of the
2106 /// namespace.
2107 fn tokenize_namespace(
2108 &self,
2109 cursor: &clang::Cursor,
2110 ) -> (Option<String>, ModuleKind) {
2111 assert_eq!(
2112 cursor.kind(),
2113 ::clang_sys::CXCursor_Namespace,
2114 "Be a nice person"
2115 );
2116
2117 let mut module_name = None;
2118 let spelling = cursor.spelling();
2119 if !spelling.is_empty() {
2120 module_name = Some(spelling)
2121 }
2122
2123 let mut kind = ModuleKind::Normal;
2124 let mut looking_for_name = false;
2125 for token in cursor.tokens().iter() {
2126 match token.spelling() {
2127 b"inline" => {
2128 debug_assert!(
2129 kind != ModuleKind::Inline,
2130 "Multiple inline keywords?"
2131 );
2132 kind = ModuleKind::Inline;
2133 // When hitting a nested inline namespace we get a spelling
2134 // that looks like ["inline", "foo"]. Deal with it properly.
2135 looking_for_name = true;
2136 }
2137 // The double colon allows us to handle nested namespaces like
2138 // namespace foo::bar { }
2139 //
2140 // libclang still gives us two namespace cursors, which is cool,
2141 // but the tokenization of the second begins with the double
2142 // colon. That's ok, so we only need to handle the weird
2143 // tokenization here.
2144 b"namespace" | b"::" => {
2145 looking_for_name = true;
2146 }
2147 b"{" => {
2148 // This should be an anonymous namespace.
2149 assert!(looking_for_name);
2150 break;
2151 }
2152 name => {
2153 if looking_for_name {
2154 if module_name.is_none() {
2155 module_name = Some(
2156 String::from_utf8_lossy(name).into_owned(),
2157 );
2158 }
2159 break;
2160 } else {
2161 // This is _likely_, but not certainly, a macro that's
2162 // been placed just before the namespace keyword.
2163 // Unfortunately, clang tokens don't let us easily see
2164 // through the ifdef tokens, so we don't know what this
2165 // token should really be. Instead of panicking though,
2166 // we warn the user that we assumed the token was blank,
2167 // and then move on.
2168 //
2169 // See also https://github.com/rust-lang/rust-bindgen/issues/1676.
2170 warn!(
2171 "Ignored unknown namespace prefix '{}' at {:?} in {:?}",
2172 String::from_utf8_lossy(name),
2173 token,
2174 cursor
2175 );
2176 }
2177 }
2178 }
2179 }
2180
2181 (module_name, kind)
2182 }
2183
2184 /// Given a CXCursor_Namespace cursor, return the item ID of the
2185 /// corresponding module, or create one on the fly.
2186 pub(crate) fn module(&mut self, cursor: clang::Cursor) -> ModuleId {
2187 use clang_sys::*;
2188 assert_eq!(cursor.kind(), CXCursor_Namespace, "Be a nice person");
2189 let cursor = cursor.canonical();
2190 if let Some(id) = self.modules.get(&cursor) {
2191 return *id;
2192 }
2193
2194 let (module_name, kind) = self.tokenize_namespace(&cursor);
2195
2196 let module_id = self.next_item_id();
2197 let module = Module::new(module_name, kind);
2198 let module = Item::new(
2199 module_id,
2200 None,
2201 None,
2202 self.current_module.into(),
2203 ItemKind::Module(module),
2204 Some(cursor.location()),
2205 );
2206
2207 let module_id = module.id().as_module_id_unchecked();
2208 self.modules.insert(cursor, module_id);
2209
2210 self.add_item(module, None, None);
2211
2212 module_id
2213 }
2214
2215 /// Start traversing the module with the given `module_id`, invoke the
2216 /// callback `cb`, and then return to traversing the original module.
2217 pub(crate) fn with_module<F>(&mut self, module_id: ModuleId, cb: F)
2218 where
2219 F: FnOnce(&mut Self),
2220 {
2221 debug_assert!(self.resolve_item(module_id).kind().is_module(), "Wat");
2222
2223 let previous_id = self.current_module;
2224 self.current_module = module_id;
2225
2226 cb(self);
2227
2228 self.current_module = previous_id;
2229 }
2230
2231 /// Iterate over all (explicitly or transitively) allowlisted items.
2232 ///
2233 /// If no items are explicitly allowlisted, then all items are considered
2234 /// allowlisted.
2235 pub(crate) fn allowlisted_items(&self) -> &ItemSet {
2236 assert!(self.in_codegen_phase());
2237 assert!(self.current_module == self.root_module);
2238
2239 self.allowlisted.as_ref().unwrap()
2240 }
2241
2242 /// Check whether a particular blocklisted type implements a trait or not.
2243 /// Results may be cached.
2244 pub(crate) fn blocklisted_type_implements_trait(
2245 &self,
2246 item: &Item,
2247 derive_trait: DeriveTrait,
2248 ) -> CanDerive {
2249 assert!(self.in_codegen_phase());
2250 assert!(self.current_module == self.root_module);
2251
2252 *self
2253 .blocklisted_types_implement_traits
2254 .borrow_mut()
2255 .entry(derive_trait)
2256 .or_default()
2257 .entry(item.id())
2258 .or_insert_with(|| {
2259 item.expect_type()
2260 .name()
2261 .and_then(|name| {
2262 if self.options.parse_callbacks.is_empty() {
2263 // Sized integer types from <stdint.h> get mapped to Rust primitive
2264 // types regardless of whether they are blocklisted, so ensure that
2265 // standard traits are considered derivable for them too.
2266 if self.is_stdint_type(name) {
2267 Some(CanDerive::Yes)
2268 } else {
2269 Some(CanDerive::No)
2270 }
2271 } else {
2272 self.options.last_callback(|cb| {
2273 cb.blocklisted_type_implements_trait(
2274 name,
2275 derive_trait,
2276 )
2277 })
2278 }
2279 })
2280 .unwrap_or(CanDerive::No)
2281 })
2282 }
2283
2284 /// Is the given type a type from <stdint.h> that corresponds to a Rust primitive type?
2285 pub(crate) fn is_stdint_type(&self, name: &str) -> bool {
2286 match name {
2287 "int8_t" | "uint8_t" | "int16_t" | "uint16_t" | "int32_t" |
2288 "uint32_t" | "int64_t" | "uint64_t" | "uintptr_t" |
2289 "intptr_t" | "ptrdiff_t" => true,
2290 "size_t" | "ssize_t" => self.options.size_t_is_usize,
2291 _ => false,
2292 }
2293 }
2294
2295 /// Get a reference to the set of items we should generate.
2296 pub(crate) fn codegen_items(&self) -> &ItemSet {
2297 assert!(self.in_codegen_phase());
2298 assert!(self.current_module == self.root_module);
2299 self.codegen_items.as_ref().unwrap()
2300 }
2301
2302 /// Compute the allowlisted items set and populate `self.allowlisted`.
2303 fn compute_allowlisted_and_codegen_items(&mut self) {
2304 assert!(self.in_codegen_phase());
2305 assert!(self.current_module == self.root_module);
2306 assert!(self.allowlisted.is_none());
2307 let _t = self.timer("compute_allowlisted_and_codegen_items");
2308
2309 let roots = {
2310 let mut roots = self
2311 .items()
2312 // Only consider roots that are enabled for codegen.
2313 .filter(|&(_, item)| item.is_enabled_for_codegen(self))
2314 .filter(|&(_, item)| {
2315 // If nothing is explicitly allowlisted, then everything is fair
2316 // game.
2317 if self.options().allowlisted_types.is_empty() &&
2318 self.options().allowlisted_functions.is_empty() &&
2319 self.options().allowlisted_vars.is_empty() &&
2320 self.options().allowlisted_files.is_empty()
2321 {
2322 return true;
2323 }
2324
2325 // If this is a type that explicitly replaces another, we assume
2326 // you know what you're doing.
2327 if item.annotations().use_instead_of().is_some() {
2328 return true;
2329 }
2330
2331 // Items with a source location in an explicitly allowlisted file
2332 // are always included.
2333 if !self.options().allowlisted_files.is_empty() {
2334 if let Some(location) = item.location() {
2335 let (file, _, _, _) = location.location();
2336 if let Some(filename) = file.name() {
2337 if self
2338 .options()
2339 .allowlisted_files
2340 .matches(filename)
2341 {
2342 return true;
2343 }
2344 }
2345 }
2346 }
2347
2348 let name = item.path_for_allowlisting(self)[1..].join("::");
2349 debug!("allowlisted_items: testing {:?}", name);
2350 match *item.kind() {
2351 ItemKind::Module(..) => true,
2352 ItemKind::Function(_) => {
2353 self.options().allowlisted_functions.matches(&name)
2354 }
2355 ItemKind::Var(_) => {
2356 self.options().allowlisted_vars.matches(&name)
2357 }
2358 ItemKind::Type(ref ty) => {
2359 if self.options().allowlisted_types.matches(&name) {
2360 return true;
2361 }
2362
2363 // Auto-allowlist types that don't need code
2364 // generation if not allowlisting recursively, to
2365 // make the #[derive] analysis not be lame.
2366 if !self.options().allowlist_recursively {
2367 match *ty.kind() {
2368 TypeKind::Void |
2369 TypeKind::NullPtr |
2370 TypeKind::Int(..) |
2371 TypeKind::Float(..) |
2372 TypeKind::Complex(..) |
2373 TypeKind::Array(..) |
2374 TypeKind::Vector(..) |
2375 TypeKind::Pointer(..) |
2376 TypeKind::Reference(..) |
2377 TypeKind::Function(..) |
2378 TypeKind::ResolvedTypeRef(..) |
2379 TypeKind::Opaque |
2380 TypeKind::TypeParam => return true,
2381 _ => {}
2382 }
2383 if self.is_stdint_type(&name) {
2384 return true;
2385 }
2386 }
2387
2388 // Unnamed top-level enums are special and we
2389 // allowlist them via the `allowlisted_vars` filter,
2390 // since they're effectively top-level constants,
2391 // and there's no way for them to be referenced
2392 // consistently.
2393 let parent = self.resolve_item(item.parent_id());
2394 if !parent.is_module() {
2395 return false;
2396 }
2397
2398 let enum_ = match *ty.kind() {
2399 TypeKind::Enum(ref e) => e,
2400 _ => return false,
2401 };
2402
2403 if ty.name().is_some() {
2404 return false;
2405 }
2406
2407 let mut prefix_path =
2408 parent.path_for_allowlisting(self).clone();
2409 enum_.variants().iter().any(|variant| {
2410 prefix_path.push(
2411 variant.name_for_allowlisting().into(),
2412 );
2413 let name = prefix_path[1..].join("::");
2414 prefix_path.pop().unwrap();
2415 self.options().allowlisted_vars.matches(name)
2416 })
2417 }
2418 }
2419 })
2420 .map(|(id, _)| id)
2421 .collect::<Vec<_>>();
2422
2423 // The reversal preserves the expected ordering of traversal,
2424 // resulting in more stable-ish bindgen-generated names for
2425 // anonymous types (like unions).
2426 roots.reverse();
2427 roots
2428 };
2429
2430 let allowlisted_items_predicate =
2431 if self.options().allowlist_recursively {
2432 traversal::all_edges
2433 } else {
2434 // Only follow InnerType edges from the allowlisted roots.
2435 // Such inner types (e.g. anonymous structs/unions) are
2436 // always emitted by codegen, and they need to be allowlisted
2437 // to make sure they are processed by e.g. the derive analysis.
2438 traversal::only_inner_type_edges
2439 };
2440
2441 let allowlisted = AllowlistedItemsTraversal::new(
2442 self,
2443 roots.clone(),
2444 allowlisted_items_predicate,
2445 )
2446 .collect::<ItemSet>();
2447
2448 let codegen_items = if self.options().allowlist_recursively {
2449 AllowlistedItemsTraversal::new(
2450 self,
2451 roots,
2452 traversal::codegen_edges,
2453 )
2454 .collect::<ItemSet>()
2455 } else {
2456 allowlisted.clone()
2457 };
2458
2459 self.allowlisted = Some(allowlisted);
2460 self.codegen_items = Some(codegen_items);
2461
2462 for item in self.options().allowlisted_functions.unmatched_items() {
2463 unused_regex_diagnostic(item, "--allowlist-function", self);
2464 }
2465
2466 for item in self.options().allowlisted_vars.unmatched_items() {
2467 unused_regex_diagnostic(item, "--allowlist-var", self);
2468 }
2469
2470 for item in self.options().allowlisted_types.unmatched_items() {
2471 unused_regex_diagnostic(item, "--allowlist-type", self);
2472 }
2473 }
2474
2475 /// Convenient method for getting the prefix to use for most traits in
2476 /// codegen depending on the `use_core` option.
2477 pub(crate) fn trait_prefix(&self) -> Ident {
2478 if self.options().use_core {
2479 self.rust_ident_raw("core")
2480 } else {
2481 self.rust_ident_raw("std")
2482 }
2483 }
2484
2485 /// Call if a bindgen complex is generated
2486 pub(crate) fn generated_bindgen_complex(&self) {
2487 self.generated_bindgen_complex.set(true)
2488 }
2489
2490 /// Whether we need to generate the bindgen complex type
2491 pub(crate) fn need_bindgen_complex_type(&self) -> bool {
2492 self.generated_bindgen_complex.get()
2493 }
2494
2495 /// Compute which `enum`s have an associated `typedef` definition.
2496 fn compute_enum_typedef_combos(&mut self) {
2497 let _t = self.timer("compute_enum_typedef_combos");
2498 assert!(self.enum_typedef_combos.is_none());
2499
2500 let mut enum_typedef_combos = HashSet::default();
2501 for item in &self.items {
2502 if let Some(ItemKind::Module(module)) =
2503 item.as_ref().map(Item::kind)
2504 {
2505 // Find typedefs in this module, and build set of their names.
2506 let mut names_of_typedefs = HashSet::default();
2507 for child_id in module.children() {
2508 if let Some(ItemKind::Type(ty)) =
2509 self.items[child_id.0].as_ref().map(Item::kind)
2510 {
2511 if let (Some(name), TypeKind::Alias(type_id)) =
2512 (ty.name(), ty.kind())
2513 {
2514 // We disregard aliases that refer to the enum
2515 // itself, such as in `typedef enum { ... } Enum;`.
2516 if type_id
2517 .into_resolver()
2518 .through_type_refs()
2519 .through_type_aliases()
2520 .resolve(self)
2521 .expect_type()
2522 .is_int()
2523 {
2524 names_of_typedefs.insert(name);
2525 }
2526 }
2527 }
2528 }
2529
2530 // Find enums in this module, and record the ID of each one that
2531 // has a typedef.
2532 for child_id in module.children() {
2533 if let Some(ItemKind::Type(ty)) =
2534 self.items[child_id.0].as_ref().map(Item::kind)
2535 {
2536 if let (Some(name), true) = (ty.name(), ty.is_enum()) {
2537 if names_of_typedefs.contains(name) {
2538 enum_typedef_combos.insert(*child_id);
2539 }
2540 }
2541 }
2542 }
2543 }
2544 }
2545
2546 self.enum_typedef_combos = Some(enum_typedef_combos);
2547 }
2548
2549 /// Look up whether `id` refers to an `enum` whose underlying type is
2550 /// defined by a `typedef`.
2551 pub(crate) fn is_enum_typedef_combo(&self, id: ItemId) -> bool {
2552 assert!(
2553 self.in_codegen_phase(),
2554 "We only compute enum_typedef_combos when we enter codegen",
2555 );
2556 self.enum_typedef_combos.as_ref().unwrap().contains(&id)
2557 }
2558
2559 /// Compute whether we can derive debug.
2560 fn compute_cannot_derive_debug(&mut self) {
2561 let _t = self.timer("compute_cannot_derive_debug");
2562 assert!(self.cannot_derive_debug.is_none());
2563 if self.options.derive_debug {
2564 self.cannot_derive_debug =
2565 Some(as_cannot_derive_set(analyze::<CannotDerive>((
2566 self,
2567 DeriveTrait::Debug,
2568 ))));
2569 }
2570 }
2571
2572 /// Look up whether the item with `id` can
2573 /// derive debug or not.
2574 pub(crate) fn lookup_can_derive_debug<Id: Into<ItemId>>(
2575 &self,
2576 id: Id,
2577 ) -> bool {
2578 let id = id.into();
2579 assert!(
2580 self.in_codegen_phase(),
2581 "We only compute can_derive_debug when we enter codegen"
2582 );
2583
2584 // Look up the computed value for whether the item with `id` can
2585 // derive debug or not.
2586 !self.cannot_derive_debug.as_ref().unwrap().contains(&id)
2587 }
2588
2589 /// Compute whether we can derive default.
2590 fn compute_cannot_derive_default(&mut self) {
2591 let _t = self.timer("compute_cannot_derive_default");
2592 assert!(self.cannot_derive_default.is_none());
2593 if self.options.derive_default {
2594 self.cannot_derive_default =
2595 Some(as_cannot_derive_set(analyze::<CannotDerive>((
2596 self,
2597 DeriveTrait::Default,
2598 ))));
2599 }
2600 }
2601
2602 /// Look up whether the item with `id` can
2603 /// derive default or not.
2604 pub(crate) fn lookup_can_derive_default<Id: Into<ItemId>>(
2605 &self,
2606 id: Id,
2607 ) -> bool {
2608 let id = id.into();
2609 assert!(
2610 self.in_codegen_phase(),
2611 "We only compute can_derive_default when we enter codegen"
2612 );
2613
2614 // Look up the computed value for whether the item with `id` can
2615 // derive default or not.
2616 !self.cannot_derive_default.as_ref().unwrap().contains(&id)
2617 }
2618
2619 /// Compute whether we can derive copy.
2620 fn compute_cannot_derive_copy(&mut self) {
2621 let _t = self.timer("compute_cannot_derive_copy");
2622 assert!(self.cannot_derive_copy.is_none());
2623 self.cannot_derive_copy =
2624 Some(as_cannot_derive_set(analyze::<CannotDerive>((
2625 self,
2626 DeriveTrait::Copy,
2627 ))));
2628 }
2629
2630 /// Compute whether we can derive hash.
2631 fn compute_cannot_derive_hash(&mut self) {
2632 let _t = self.timer("compute_cannot_derive_hash");
2633 assert!(self.cannot_derive_hash.is_none());
2634 if self.options.derive_hash {
2635 self.cannot_derive_hash =
2636 Some(as_cannot_derive_set(analyze::<CannotDerive>((
2637 self,
2638 DeriveTrait::Hash,
2639 ))));
2640 }
2641 }
2642
2643 /// Look up whether the item with `id` can
2644 /// derive hash or not.
2645 pub(crate) fn lookup_can_derive_hash<Id: Into<ItemId>>(
2646 &self,
2647 id: Id,
2648 ) -> bool {
2649 let id = id.into();
2650 assert!(
2651 self.in_codegen_phase(),
2652 "We only compute can_derive_debug when we enter codegen"
2653 );
2654
2655 // Look up the computed value for whether the item with `id` can
2656 // derive hash or not.
2657 !self.cannot_derive_hash.as_ref().unwrap().contains(&id)
2658 }
2659
2660 /// Compute whether we can derive PartialOrd, PartialEq or Eq.
2661 fn compute_cannot_derive_partialord_partialeq_or_eq(&mut self) {
2662 let _t = self.timer("compute_cannot_derive_partialord_partialeq_or_eq");
2663 assert!(self.cannot_derive_partialeq_or_partialord.is_none());
2664 if self.options.derive_partialord ||
2665 self.options.derive_partialeq ||
2666 self.options.derive_eq
2667 {
2668 self.cannot_derive_partialeq_or_partialord =
2669 Some(analyze::<CannotDerive>((
2670 self,
2671 DeriveTrait::PartialEqOrPartialOrd,
2672 )));
2673 }
2674 }
2675
2676 /// Look up whether the item with `id` can derive `Partial{Eq,Ord}`.
2677 pub(crate) fn lookup_can_derive_partialeq_or_partialord<
2678 Id: Into<ItemId>,
2679 >(
2680 &self,
2681 id: Id,
2682 ) -> CanDerive {
2683 let id = id.into();
2684 assert!(
2685 self.in_codegen_phase(),
2686 "We only compute can_derive_partialeq_or_partialord when we enter codegen"
2687 );
2688
2689 // Look up the computed value for whether the item with `id` can
2690 // derive partialeq or not.
2691 self.cannot_derive_partialeq_or_partialord
2692 .as_ref()
2693 .unwrap()
2694 .get(&id)
2695 .cloned()
2696 .unwrap_or(CanDerive::Yes)
2697 }
2698
2699 /// Look up whether the item with `id` can derive `Copy` or not.
2700 pub(crate) fn lookup_can_derive_copy<Id: Into<ItemId>>(
2701 &self,
2702 id: Id,
2703 ) -> bool {
2704 assert!(
2705 self.in_codegen_phase(),
2706 "We only compute can_derive_debug when we enter codegen"
2707 );
2708
2709 // Look up the computed value for whether the item with `id` can
2710 // derive `Copy` or not.
2711 let id = id.into();
2712
2713 !self.lookup_has_type_param_in_array(id) &&
2714 !self.cannot_derive_copy.as_ref().unwrap().contains(&id)
2715 }
2716
2717 /// Compute whether the type has type parameter in array.
2718 fn compute_has_type_param_in_array(&mut self) {
2719 let _t = self.timer("compute_has_type_param_in_array");
2720 assert!(self.has_type_param_in_array.is_none());
2721 self.has_type_param_in_array =
2722 Some(analyze::<HasTypeParameterInArray>(self));
2723 }
2724
2725 /// Look up whether the item with `id` has type parameter in array or not.
2726 pub(crate) fn lookup_has_type_param_in_array<Id: Into<ItemId>>(
2727 &self,
2728 id: Id,
2729 ) -> bool {
2730 assert!(
2731 self.in_codegen_phase(),
2732 "We only compute has array when we enter codegen"
2733 );
2734
2735 // Look up the computed value for whether the item with `id` has
2736 // type parameter in array or not.
2737 self.has_type_param_in_array
2738 .as_ref()
2739 .unwrap()
2740 .contains(&id.into())
2741 }
2742
2743 /// Compute whether the type has float.
2744 fn compute_has_float(&mut self) {
2745 let _t = self.timer("compute_has_float");
2746 assert!(self.has_float.is_none());
2747 if self.options.derive_eq || self.options.derive_ord {
2748 self.has_float = Some(analyze::<HasFloat>(self));
2749 }
2750 }
2751
2752 /// Look up whether the item with `id` has array or not.
2753 pub(crate) fn lookup_has_float<Id: Into<ItemId>>(&self, id: Id) -> bool {
2754 assert!(
2755 self.in_codegen_phase(),
2756 "We only compute has float when we enter codegen"
2757 );
2758
2759 // Look up the computed value for whether the item with `id` has
2760 // float or not.
2761 self.has_float.as_ref().unwrap().contains(&id.into())
2762 }
2763
2764 /// Check if `--no-partialeq` flag is enabled for this item.
2765 pub(crate) fn no_partialeq_by_name(&self, item: &Item) -> bool {
2766 let name = item.path_for_allowlisting(self)[1..].join("::");
2767 self.options().no_partialeq_types.matches(name)
2768 }
2769
2770 /// Check if `--no-copy` flag is enabled for this item.
2771 pub(crate) fn no_copy_by_name(&self, item: &Item) -> bool {
2772 let name = item.path_for_allowlisting(self)[1..].join("::");
2773 self.options().no_copy_types.matches(name)
2774 }
2775
2776 /// Check if `--no-debug` flag is enabled for this item.
2777 pub(crate) fn no_debug_by_name(&self, item: &Item) -> bool {
2778 let name = item.path_for_allowlisting(self)[1..].join("::");
2779 self.options().no_debug_types.matches(name)
2780 }
2781
2782 /// Check if `--no-default` flag is enabled for this item.
2783 pub(crate) fn no_default_by_name(&self, item: &Item) -> bool {
2784 let name = item.path_for_allowlisting(self)[1..].join("::");
2785 self.options().no_default_types.matches(name)
2786 }
2787
2788 /// Check if `--no-hash` flag is enabled for this item.
2789 pub(crate) fn no_hash_by_name(&self, item: &Item) -> bool {
2790 let name = item.path_for_allowlisting(self)[1..].join("::");
2791 self.options().no_hash_types.matches(name)
2792 }
2793
2794 /// Check if `--must-use-type` flag is enabled for this item.
2795 pub(crate) fn must_use_type_by_name(&self, item: &Item) -> bool {
2796 let name = item.path_for_allowlisting(self)[1..].join("::");
2797 self.options().must_use_types.matches(name)
2798 }
2799
2800 /// Wrap some tokens in an `unsafe` block if the `--wrap-unsafe-ops` option is enabled.
2801 pub(crate) fn wrap_unsafe_ops(&self, tokens: impl ToTokens) -> TokenStream {
2802 if self.options.wrap_unsafe_ops {
2803 quote!(unsafe { #tokens })
2804 } else {
2805 tokens.into_token_stream()
2806 }
2807 }
2808
2809 /// Get the suffix to be added to `static` functions if the `--wrap-static-fns` option is
2810 /// enabled.
2811 pub(crate) fn wrap_static_fns_suffix(&self) -> &str {
2812 self.options()
2813 .wrap_static_fns_suffix
2814 .as_deref()
2815 .unwrap_or(crate::DEFAULT_NON_EXTERN_FNS_SUFFIX)
2816 }
2817 }
2818
2819 /// A builder struct for configuring item resolution options.
2820 #[derive(Debug, Copy, Clone)]
2821 pub(crate) struct ItemResolver {
2822 id: ItemId,
2823 through_type_refs: bool,
2824 through_type_aliases: bool,
2825 }
2826
2827 impl ItemId {
2828 /// Create an `ItemResolver` from this item ID.
2829 pub(crate) fn into_resolver(self) -> ItemResolver {
2830 self.into()
2831 }
2832 }
2833
2834 impl<T> From<T> for ItemResolver
2835 where
2836 T: Into<ItemId>,
2837 {
2838 fn from(id: T) -> ItemResolver {
2839 ItemResolver::new(id)
2840 }
2841 }
2842
2843 impl ItemResolver {
2844 /// Construct a new `ItemResolver` from the given ID.
2845 pub(crate) fn new<Id: Into<ItemId>>(id: Id) -> ItemResolver {
2846 let id = id.into();
2847 ItemResolver {
2848 id,
2849 through_type_refs: false,
2850 through_type_aliases: false,
2851 }
2852 }
2853
2854 /// Keep resolving through `Type::TypeRef` items.
2855 pub(crate) fn through_type_refs(mut self) -> ItemResolver {
2856 self.through_type_refs = true;
2857 self
2858 }
2859
2860 /// Keep resolving through `Type::Alias` items.
2861 pub(crate) fn through_type_aliases(mut self) -> ItemResolver {
2862 self.through_type_aliases = true;
2863 self
2864 }
2865
2866 /// Finish configuring and perform the actual item resolution.
2867 pub(crate) fn resolve(self, ctx: &BindgenContext) -> &Item {
2868 assert!(ctx.collected_typerefs());
2869
2870 let mut id = self.id;
2871 let mut seen_ids = HashSet::default();
2872 loop {
2873 let item = ctx.resolve_item(id);
2874
2875 // Detect cycles and bail out. These can happen in certain cases
2876 // involving incomplete qualified dependent types (#2085).
2877 if !seen_ids.insert(id) {
2878 return item;
2879 }
2880
2881 let ty_kind = item.as_type().map(|t| t.kind());
2882 match ty_kind {
2883 Some(&TypeKind::ResolvedTypeRef(next_id))
2884 if self.through_type_refs =>
2885 {
2886 id = next_id.into();
2887 }
2888 // We intentionally ignore template aliases here, as they are
2889 // more complicated, and don't represent a simple renaming of
2890 // some type.
2891 Some(&TypeKind::Alias(next_id))
2892 if self.through_type_aliases =>
2893 {
2894 id = next_id.into();
2895 }
2896 _ => return item,
2897 }
2898 }
2899 }
2900 }
2901
2902 /// A type that we are in the middle of parsing.
2903 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
2904 pub(crate) struct PartialType {
2905 decl: Cursor,
2906 // Just an ItemId, and not a TypeId, because we haven't finished this type
2907 // yet, so there's still time for things to go wrong.
2908 id: ItemId,
2909 }
2910
2911 impl PartialType {
2912 /// Construct a new `PartialType`.
2913 pub(crate) fn new(decl: Cursor, id: ItemId) -> PartialType {
2914 // assert!(decl == decl.canonical());
2915 PartialType { decl, id }
2916 }
2917
2918 /// The cursor pointing to this partial type's declaration location.
2919 pub(crate) fn decl(&self) -> &Cursor {
2920 &self.decl
2921 }
2922
2923 /// The item ID allocated for this type. This is *NOT* a key for an entry in
2924 /// the context's item set yet!
2925 pub(crate) fn id(&self) -> ItemId {
2926 self.id
2927 }
2928 }
2929
2930 impl TemplateParameters for PartialType {
2931 fn self_template_params(&self, _ctx: &BindgenContext) -> Vec<TypeId> {
2932 // Maybe at some point we will eagerly parse named types, but for now we
2933 // don't and this information is unavailable.
2934 vec![]
2935 }
2936
2937 fn num_self_template_params(&self, _ctx: &BindgenContext) -> usize {
2938 // Wouldn't it be nice if libclang would reliably give us this
2939 // information‽
2940 match self.decl().kind() {
2941 clang_sys::CXCursor_ClassTemplate |
2942 clang_sys::CXCursor_FunctionTemplate |
2943 clang_sys::CXCursor_TypeAliasTemplateDecl => {
2944 let mut num_params = 0;
2945 self.decl().visit(|c| {
2946 match c.kind() {
2947 clang_sys::CXCursor_TemplateTypeParameter |
2948 clang_sys::CXCursor_TemplateTemplateParameter |
2949 clang_sys::CXCursor_NonTypeTemplateParameter => {
2950 num_params += 1;
2951 }
2952 _ => {}
2953 };
2954 clang_sys::CXChildVisit_Continue
2955 });
2956 num_params
2957 }
2958 _ => 0,
2959 }
2960 }
2961 }
2962
2963 fn unused_regex_diagnostic(item: &str, name: &str, _ctx: &BindgenContext) {
2964 warn!("unused option: {} {}", name, item);
2965
2966 #[cfg(feature = "experimental")]
2967 if _ctx.options().emit_diagnostics {
2968 use crate::diagnostics::{Diagnostic, Level};
2969
2970 Diagnostic::default()
2971 .with_title(
2972 format!("Unused regular expression: `{}`.", item),
2973 Level::Warn,
2974 )
2975 .add_annotation(
2976 format!("This regular expression was passed to `{}`.", name),
2977 Level::Note,
2978 )
2979 .display();
2980 }
2981 }