Debian Codegraph @

third_party/rust/bindgen/ir/item.rs

raw
1 //! Bindgen's core intermediate representation type.
2
3 use super::super::codegen::{EnumVariation, CONSTIFIED_ENUM_MODULE_REPR_NAME};
4 use super::analysis::{HasVtable, HasVtableResult, Sizedness, SizednessResult};
5 use super::annotations::Annotations;
6 use super::comp::{CompKind, MethodKind};
7 use super::context::{BindgenContext, ItemId, PartialType, TypeId};
8 use super::derive::{
9 CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq,
10 CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd,
11 };
12 use super::dot::DotAttributes;
13 use super::function::{Function, FunctionKind};
14 use super::item_kind::ItemKind;
15 use super::layout::Opaque;
16 use super::module::Module;
17 use super::template::{AsTemplateParam, TemplateParameters};
18 use super::traversal::{EdgeKind, Trace, Tracer};
19 use super::ty::{Type, TypeKind};
20 use crate::clang;
21 use crate::parse::{ClangSubItemParser, ParseError, ParseResult};
22
23 use lazycell::LazyCell;
24
25 use std::cell::Cell;
26 use std::collections::BTreeSet;
27 use std::fmt::Write;
28 use std::io;
29 use std::iter;
30
31 /// A trait to get the canonical name from an item.
32 ///
33 /// This is the trait that will eventually isolate all the logic related to name
34 /// mangling and that kind of stuff.
35 ///
36 /// This assumes no nested paths, at some point I'll have to make it a more
37 /// complex thing.
38 ///
39 /// This name is required to be safe for Rust, that is, is not expected to
40 /// return any rust keyword from here.
41 pub(crate) trait ItemCanonicalName {
42 /// Get the canonical name for this item.
43 fn canonical_name(&self, ctx: &BindgenContext) -> String;
44 }
45
46 /// The same, but specifies the path that needs to be followed to reach an item.
47 ///
48 /// To contrast with canonical_name, here's an example:
49 ///
50 /// ```c++
51 /// namespace foo {
52 /// const BAR = 3;
53 /// }
54 /// ```
55 ///
56 /// For bar, the canonical path is `vec!["foo", "BAR"]`, while the canonical
57 /// name is just `"BAR"`.
58 pub(crate) trait ItemCanonicalPath {
59 /// Get the namespace-aware canonical path for this item. This means that if
60 /// namespaces are disabled, you'll get a single item, and otherwise you get
61 /// the whole path.
62 fn namespace_aware_canonical_path(
63 &self,
64 ctx: &BindgenContext,
65 ) -> Vec<String>;
66
67 /// Get the canonical path for this item.
68 fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String>;
69 }
70
71 /// A trait for determining if some IR thing is opaque or not.
72 pub(crate) trait IsOpaque {
73 /// Extra context the IR thing needs to determine if it is opaque or not.
74 type Extra;
75
76 /// Returns `true` if the thing is opaque, and `false` otherwise.
77 ///
78 /// May only be called when `ctx` is in the codegen phase.
79 fn is_opaque(&self, ctx: &BindgenContext, extra: &Self::Extra) -> bool;
80 }
81
82 /// A trait for determining if some IR thing has type parameter in array or not.
83 pub(crate) trait HasTypeParamInArray {
84 /// Returns `true` if the thing has Array, and `false` otherwise.
85 fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool;
86 }
87
88 #[allow(dead_code)]
89 /// A trait for determining if some IR thing has float or not.
90 pub(crate) trait HasFloat {
91 /// Returns `true` if the thing has float, and `false` otherwise.
92 fn has_float(&self, ctx: &BindgenContext) -> bool;
93 }
94
95 /// A trait for iterating over an item and its parents and up its ancestor chain
96 /// up to (but not including) the implicit root module.
97 pub(crate) trait ItemAncestors {
98 /// Get an iterable over this item's ancestors.
99 fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a>;
100 }
101
102 #[cfg(feature = "__testing_only_extra_assertions")]
103 type DebugOnlyItemSet = ItemSet;
104
105 #[cfg(not(feature = "__testing_only_extra_assertions"))]
106 struct DebugOnlyItemSet;
107
108 #[cfg(not(feature = "__testing_only_extra_assertions"))]
109 impl DebugOnlyItemSet {
110 fn new() -> Self {
111 DebugOnlyItemSet
112 }
113
114 fn contains(&self, _id: &ItemId) -> bool {
115 false
116 }
117
118 fn insert(&mut self, _id: ItemId) {}
119 }
120
121 /// An iterator over an item and its ancestors.
122 pub(crate) struct ItemAncestorsIter<'a> {
123 item: ItemId,
124 ctx: &'a BindgenContext,
125 seen: DebugOnlyItemSet,
126 }
127
128 impl<'a> ItemAncestorsIter<'a> {
129 fn new<Id: Into<ItemId>>(ctx: &'a BindgenContext, id: Id) -> Self {
130 ItemAncestorsIter {
131 item: id.into(),
132 ctx,
133 seen: DebugOnlyItemSet::new(),
134 }
135 }
136 }
137
138 impl<'a> Iterator for ItemAncestorsIter<'a> {
139 type Item = ItemId;
140
141 fn next(&mut self) -> Option<Self::Item> {
142 let item = self.ctx.resolve_item(self.item);
143
144 if item.parent_id() == self.item {
145 None
146 } else {
147 self.item = item.parent_id();
148
149 extra_assert!(!self.seen.contains(&item.id()));
150 self.seen.insert(item.id());
151
152 Some(item.id())
153 }
154 }
155 }
156
157 impl<T> AsTemplateParam for T
158 where
159 T: Copy + Into<ItemId>,
160 {
161 type Extra = ();
162
163 fn as_template_param(
164 &self,
165 ctx: &BindgenContext,
166 _: &(),
167 ) -> Option<TypeId> {
168 ctx.resolve_item((*self).into()).as_template_param(ctx, &())
169 }
170 }
171
172 impl AsTemplateParam for Item {
173 type Extra = ();
174
175 fn as_template_param(
176 &self,
177 ctx: &BindgenContext,
178 _: &(),
179 ) -> Option<TypeId> {
180 self.kind.as_template_param(ctx, self)
181 }
182 }
183
184 impl AsTemplateParam for ItemKind {
185 type Extra = Item;
186
187 fn as_template_param(
188 &self,
189 ctx: &BindgenContext,
190 item: &Item,
191 ) -> Option<TypeId> {
192 match *self {
193 ItemKind::Type(ref ty) => ty.as_template_param(ctx, item),
194 ItemKind::Module(..) |
195 ItemKind::Function(..) |
196 ItemKind::Var(..) => None,
197 }
198 }
199 }
200
201 impl<T> ItemCanonicalName for T
202 where
203 T: Copy + Into<ItemId>,
204 {
205 fn canonical_name(&self, ctx: &BindgenContext) -> String {
206 debug_assert!(
207 ctx.in_codegen_phase(),
208 "You're not supposed to call this yet"
209 );
210 ctx.resolve_item(*self).canonical_name(ctx)
211 }
212 }
213
214 impl<T> ItemCanonicalPath for T
215 where
216 T: Copy + Into<ItemId>,
217 {
218 fn namespace_aware_canonical_path(
219 &self,
220 ctx: &BindgenContext,
221 ) -> Vec<String> {
222 debug_assert!(
223 ctx.in_codegen_phase(),
224 "You're not supposed to call this yet"
225 );
226 ctx.resolve_item(*self).namespace_aware_canonical_path(ctx)
227 }
228
229 fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String> {
230 debug_assert!(
231 ctx.in_codegen_phase(),
232 "You're not supposed to call this yet"
233 );
234 ctx.resolve_item(*self).canonical_path(ctx)
235 }
236 }
237
238 impl<T> ItemAncestors for T
239 where
240 T: Copy + Into<ItemId>,
241 {
242 fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a> {
243 ItemAncestorsIter::new(ctx, *self)
244 }
245 }
246
247 impl ItemAncestors for Item {
248 fn ancestors<'a>(&self, ctx: &'a BindgenContext) -> ItemAncestorsIter<'a> {
249 self.id().ancestors(ctx)
250 }
251 }
252
253 impl<Id> Trace for Id
254 where
255 Id: Copy + Into<ItemId>,
256 {
257 type Extra = ();
258
259 fn trace<T>(&self, ctx: &BindgenContext, tracer: &mut T, extra: &())
260 where
261 T: Tracer,
262 {
263 ctx.resolve_item(*self).trace(ctx, tracer, extra);
264 }
265 }
266
267 impl Trace for Item {
268 type Extra = ();
269
270 fn trace<T>(&self, ctx: &BindgenContext, tracer: &mut T, _extra: &())
271 where
272 T: Tracer,
273 {
274 // Even if this item is blocklisted/hidden, we want to trace it. It is
275 // traversal iterators' consumers' responsibility to filter items as
276 // needed. Generally, this filtering happens in the implementation of
277 // `Iterator` for `allowlistedItems`. Fully tracing blocklisted items is
278 // necessary for things like the template parameter usage analysis to
279 // function correctly.
280
281 match *self.kind() {
282 ItemKind::Type(ref ty) => {
283 // There are some types, like resolved type references, where we
284 // don't want to stop collecting types even though they may be
285 // opaque.
286 if ty.should_be_traced_unconditionally() ||
287 !self.is_opaque(ctx, &())
288 {
289 ty.trace(ctx, tracer, self);
290 }
291 }
292 ItemKind::Function(ref fun) => {
293 // Just the same way, it has not real meaning for a function to
294 // be opaque, so we trace across it.
295 tracer.visit(fun.signature().into());
296 }
297 ItemKind::Var(ref var) => {
298 tracer.visit_kind(var.ty().into(), EdgeKind::VarType);
299 }
300 ItemKind::Module(_) => {
301 // Module -> children edges are "weak", and we do not want to
302 // trace them. If we did, then allowlisting wouldn't work as
303 // expected: everything in every module would end up
304 // allowlisted.
305 //
306 // TODO: make a new edge kind for module -> children edges and
307 // filter them during allowlisting traversals.
308 }
309 }
310 }
311 }
312
313 impl CanDeriveDebug for Item {
314 fn can_derive_debug(&self, ctx: &BindgenContext) -> bool {
315 self.id().can_derive_debug(ctx)
316 }
317 }
318
319 impl CanDeriveDefault for Item {
320 fn can_derive_default(&self, ctx: &BindgenContext) -> bool {
321 self.id().can_derive_default(ctx)
322 }
323 }
324
325 impl CanDeriveCopy for Item {
326 fn can_derive_copy(&self, ctx: &BindgenContext) -> bool {
327 self.id().can_derive_copy(ctx)
328 }
329 }
330
331 impl CanDeriveHash for Item {
332 fn can_derive_hash(&self, ctx: &BindgenContext) -> bool {
333 self.id().can_derive_hash(ctx)
334 }
335 }
336
337 impl CanDerivePartialOrd for Item {
338 fn can_derive_partialord(&self, ctx: &BindgenContext) -> bool {
339 self.id().can_derive_partialord(ctx)
340 }
341 }
342
343 impl CanDerivePartialEq for Item {
344 fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool {
345 self.id().can_derive_partialeq(ctx)
346 }
347 }
348
349 impl CanDeriveEq for Item {
350 fn can_derive_eq(&self, ctx: &BindgenContext) -> bool {
351 self.id().can_derive_eq(ctx)
352 }
353 }
354
355 impl CanDeriveOrd for Item {
356 fn can_derive_ord(&self, ctx: &BindgenContext) -> bool {
357 self.id().can_derive_ord(ctx)
358 }
359 }
360
361 /// An item is the base of the bindgen representation, it can be either a
362 /// module, a type, a function, or a variable (see `ItemKind` for more
363 /// information).
364 ///
365 /// Items refer to each other by `ItemId`. Every item has its parent's
366 /// ID. Depending on the kind of item this is, it may also refer to other items,
367 /// such as a compound type item referring to other types. Collectively, these
368 /// references form a graph.
369 ///
370 /// The entry-point to this graph is the "root module": a meta-item used to hold
371 /// all top-level items.
372 ///
373 /// An item may have a comment, and annotations (see the `annotations` module).
374 ///
375 /// Note that even though we parse all the types of annotations in comments, not
376 /// all of them apply to every item. Those rules are described in the
377 /// `annotations` module.
378 #[derive(Debug)]
379 pub(crate) struct Item {
380 /// This item's ID.
381 id: ItemId,
382
383 /// The item's local ID, unique only amongst its siblings. Only used for
384 /// anonymous items.
385 ///
386 /// Lazily initialized in local_id().
387 ///
388 /// Note that only structs, unions, and enums get a local type ID. In any
389 /// case this is an implementation detail.
390 local_id: LazyCell<usize>,
391
392 /// The next local ID to use for a child or template instantiation.
393 next_child_local_id: Cell<usize>,
394
395 /// A cached copy of the canonical name, as returned by `canonical_name`.
396 ///
397 /// This is a fairly used operation during codegen so this makes bindgen
398 /// considerably faster in those cases.
399 canonical_name: LazyCell<String>,
400
401 /// The path to use for allowlisting and other name-based checks, as
402 /// returned by `path_for_allowlisting`, lazily constructed.
403 path_for_allowlisting: LazyCell<Vec<String>>,
404
405 /// A doc comment over the item, if any.
406 comment: Option<String>,
407 /// Annotations extracted from the doc comment, or the default ones
408 /// otherwise.
409 annotations: Annotations,
410 /// An item's parent ID. This will most likely be a class where this item
411 /// was declared, or a module, etc.
412 ///
413 /// All the items have a parent, except the root module, in which case the
414 /// parent ID is its own ID.
415 parent_id: ItemId,
416 /// The item kind.
417 kind: ItemKind,
418 /// The source location of the item.
419 location: Option<clang::SourceLocation>,
420 }
421
422 impl AsRef<ItemId> for Item {
423 fn as_ref(&self) -> &ItemId {
424 &self.id
425 }
426 }
427
428 impl Item {
429 /// Construct a new `Item`.
430 pub(crate) fn new(
431 id: ItemId,
432 comment: Option<String>,
433 annotations: Option<Annotations>,
434 parent_id: ItemId,
435 kind: ItemKind,
436 location: Option<clang::SourceLocation>,
437 ) -> Self {
438 debug_assert!(id != parent_id || kind.is_module());
439 Item {
440 id,
441 local_id: LazyCell::new(),
442 next_child_local_id: Cell::new(1),
443 canonical_name: LazyCell::new(),
444 path_for_allowlisting: LazyCell::new(),
445 parent_id,
446 comment,
447 annotations: annotations.unwrap_or_default(),
448 kind,
449 location,
450 }
451 }
452
453 /// Construct a new opaque item type.
454 pub(crate) fn new_opaque_type(
455 with_id: ItemId,
456 ty: &clang::Type,
457 ctx: &mut BindgenContext,
458 ) -> TypeId {
459 let location = ty.declaration().location();
460 let ty = Opaque::from_clang_ty(ty, ctx);
461 let kind = ItemKind::Type(ty);
462 let parent = ctx.root_module().into();
463 ctx.add_item(
464 Item::new(with_id, None, None, parent, kind, Some(location)),
465 None,
466 None,
467 );
468 with_id.as_type_id_unchecked()
469 }
470
471 /// Get this `Item`'s identifier.
472 pub(crate) fn id(&self) -> ItemId {
473 self.id
474 }
475
476 /// Get this `Item`'s parent's identifier.
477 ///
478 /// For the root module, the parent's ID is its own ID.
479 pub(crate) fn parent_id(&self) -> ItemId {
480 self.parent_id
481 }
482
483 /// Set this item's parent ID.
484 ///
485 /// This is only used so replacements get generated in the proper module.
486 pub(crate) fn set_parent_for_replacement<Id: Into<ItemId>>(
487 &mut self,
488 id: Id,
489 ) {
490 self.parent_id = id.into();
491 }
492
493 /// Returns the depth this item is indented to.
494 ///
495 /// FIXME(emilio): This may need fixes for the enums within modules stuff.
496 pub(crate) fn codegen_depth(&self, ctx: &BindgenContext) -> usize {
497 if !ctx.options().enable_cxx_namespaces {
498 return 0;
499 }
500
501 self.ancestors(ctx)
502 .filter(|id| {
503 ctx.resolve_item(*id).as_module().map_or(false, |module| {
504 !module.is_inline() ||
505 ctx.options().conservative_inline_namespaces
506 })
507 })
508 .count() +
509 1
510 }
511
512 /// Get this `Item`'s comment, if it has any, already preprocessed and with
513 /// the right indentation.
514 pub(crate) fn comment(&self, ctx: &BindgenContext) -> Option<String> {
515 if !ctx.options().generate_comments {
516 return None;
517 }
518
519 self.comment
520 .as_ref()
521 .map(|comment| ctx.options().process_comment(comment))
522 }
523
524 /// What kind of item is this?
525 pub(crate) fn kind(&self) -> &ItemKind {
526 &self.kind
527 }
528
529 /// Get a mutable reference to this item's kind.
530 pub(crate) fn kind_mut(&mut self) -> &mut ItemKind {
531 &mut self.kind
532 }
533
534 /// Where in the source is this item located?
535 pub(crate) fn location(&self) -> Option<&clang::SourceLocation> {
536 self.location.as_ref()
537 }
538
539 /// Get an identifier that differentiates this item from its siblings.
540 ///
541 /// This should stay relatively stable in the face of code motion outside or
542 /// below this item's lexical scope, meaning that this can be useful for
543 /// generating relatively stable identifiers within a scope.
544 pub(crate) fn local_id(&self, ctx: &BindgenContext) -> usize {
545 *self.local_id.borrow_with(|| {
546 let parent = ctx.resolve_item(self.parent_id);
547 parent.next_child_local_id()
548 })
549 }
550
551 /// Get an identifier that differentiates a child of this item of other
552 /// related items.
553 ///
554 /// This is currently used for anonymous items, and template instantiation
555 /// tests, in both cases in order to reduce noise when system headers are at
556 /// place.
557 pub(crate) fn next_child_local_id(&self) -> usize {
558 let local_id = self.next_child_local_id.get();
559 self.next_child_local_id.set(local_id + 1);
560 local_id
561 }
562
563 /// Returns whether this item is a top-level item, from the point of view of
564 /// bindgen.
565 ///
566 /// This point of view changes depending on whether namespaces are enabled
567 /// or not. That way, in the following example:
568 ///
569 /// ```c++
570 /// namespace foo {
571 /// static int var;
572 /// }
573 /// ```
574 ///
575 /// `var` would be a toplevel item if namespaces are disabled, but won't if
576 /// they aren't.
577 ///
578 /// This function is used to determine when the codegen phase should call
579 /// `codegen` on an item, since any item that is not top-level will be
580 /// generated by its parent.
581 pub(crate) fn is_toplevel(&self, ctx: &BindgenContext) -> bool {
582 // FIXME: Workaround for some types falling behind when parsing weird
583 // stl classes, for example.
584 if ctx.options().enable_cxx_namespaces &&
585 self.kind().is_module() &&
586 self.id() != ctx.root_module()
587 {
588 return false;
589 }
590
591 let mut parent = self.parent_id;
592 loop {
593 let parent_item = match ctx.resolve_item_fallible(parent) {
594 Some(item) => item,
595 None => return false,
596 };
597
598 if parent_item.id() == ctx.root_module() {
599 return true;
600 } else if ctx.options().enable_cxx_namespaces ||
601 !parent_item.kind().is_module()
602 {
603 return false;
604 }
605
606 parent = parent_item.parent_id();
607 }
608 }
609
610 /// Get a reference to this item's underlying `Type`. Panic if this is some
611 /// other kind of item.
612 pub(crate) fn expect_type(&self) -> &Type {
613 self.kind().expect_type()
614 }
615
616 /// Get a reference to this item's underlying `Type`, or `None` if this is
617 /// some other kind of item.
618 pub(crate) fn as_type(&self) -> Option<&Type> {
619 self.kind().as_type()
620 }
621
622 /// Get a reference to this item's underlying `Function`. Panic if this is
623 /// some other kind of item.
624 pub(crate) fn expect_function(&self) -> &Function {
625 self.kind().expect_function()
626 }
627
628 /// Is this item a module?
629 pub(crate) fn is_module(&self) -> bool {
630 matches!(self.kind, ItemKind::Module(..))
631 }
632
633 /// Get this item's annotations.
634 pub(crate) fn annotations(&self) -> &Annotations {
635 &self.annotations
636 }
637
638 /// Whether this item should be blocklisted.
639 ///
640 /// This may be due to either annotations or to other kind of configuration.
641 pub(crate) fn is_blocklisted(&self, ctx: &BindgenContext) -> bool {
642 debug_assert!(
643 ctx.in_codegen_phase(),
644 "You're not supposed to call this yet"
645 );
646 if self.annotations.hide() {
647 return true;
648 }
649
650 if !ctx.options().blocklisted_files.is_empty() {
651 if let Some(location) = &self.location {
652 let (file, _, _, _) = location.location();
653 if let Some(filename) = file.name() {
654 if ctx.options().blocklisted_files.matches(filename) {
655 return true;
656 }
657 }
658 }
659 }
660
661 let path = self.path_for_allowlisting(ctx);
662 let name = path[1..].join("::");
663 ctx.options().blocklisted_items.matches(&name) ||
664 match self.kind {
665 ItemKind::Type(..) => {
666 ctx.options().blocklisted_types.matches(&name) ||
667 ctx.is_replaced_type(path, self.id)
668 }
669 ItemKind::Function(..) => {
670 ctx.options().blocklisted_functions.matches(&name)
671 }
672 ItemKind::Var(..) => {
673 ctx.options().blocklisted_vars.matches(&name)
674 }
675 // TODO: Add namespace blocklisting?
676 ItemKind::Module(..) => false,
677 }
678 }
679
680 /// Take out item NameOptions
681 pub(crate) fn name<'a>(
682 &'a self,
683 ctx: &'a BindgenContext,
684 ) -> NameOptions<'a> {
685 NameOptions::new(self, ctx)
686 }
687
688 /// Get the target item ID for name generation.
689 fn name_target(&self, ctx: &BindgenContext) -> ItemId {
690 let mut targets_seen = DebugOnlyItemSet::new();
691 let mut item = self;
692
693 loop {
694 extra_assert!(!targets_seen.contains(&item.id()));
695 targets_seen.insert(item.id());
696
697 if self.annotations().use_instead_of().is_some() {
698 return self.id();
699 }
700
701 match *item.kind() {
702 ItemKind::Type(ref ty) => match *ty.kind() {
703 TypeKind::ResolvedTypeRef(inner) => {
704 item = ctx.resolve_item(inner);
705 }
706 TypeKind::TemplateInstantiation(ref inst) => {
707 item = ctx.resolve_item(inst.template_definition());
708 }
709 _ => return item.id(),
710 },
711 _ => return item.id(),
712 }
713 }
714 }
715
716 /// Create a fully disambiguated name for an item, including template
717 /// parameters if it is a type
718 pub(crate) fn full_disambiguated_name(
719 &self,
720 ctx: &BindgenContext,
721 ) -> String {
722 let mut s = String::new();
723 let level = 0;
724 self.push_disambiguated_name(ctx, &mut s, level);
725 s
726 }
727
728 /// Helper function for full_disambiguated_name
729 fn push_disambiguated_name(
730 &self,
731 ctx: &BindgenContext,
732 to: &mut String,
733 level: u8,
734 ) {
735 to.push_str(&self.canonical_name(ctx));
736 if let ItemKind::Type(ref ty) = *self.kind() {
737 if let TypeKind::TemplateInstantiation(ref inst) = *ty.kind() {
738 to.push_str(&format!("_open{}_", level));
739 for arg in inst.template_arguments() {
740 arg.into_resolver()
741 .through_type_refs()
742 .resolve(ctx)
743 .push_disambiguated_name(ctx, to, level + 1);
744 to.push('_');
745 }
746 to.push_str(&format!("close{}", level));
747 }
748 }
749 }
750
751 /// Get this function item's name, or `None` if this item is not a function.
752 fn func_name(&self) -> Option<&str> {
753 match *self.kind() {
754 ItemKind::Function(ref func) => Some(func.name()),
755 _ => None,
756 }
757 }
758
759 /// Get the overload index for this method. If this is not a method, return
760 /// `None`.
761 fn overload_index(&self, ctx: &BindgenContext) -> Option<usize> {
762 self.func_name().and_then(|func_name| {
763 let parent = ctx.resolve_item(self.parent_id());
764 if let ItemKind::Type(ref ty) = *parent.kind() {
765 if let TypeKind::Comp(ref ci) = *ty.kind() {
766 // All the constructors have the same name, so no need to
767 // resolve and check.
768 return ci
769 .constructors()
770 .iter()
771 .position(|c| *c == self.id())
772 .or_else(|| {
773 ci.methods()
774 .iter()
775 .filter(|m| {
776 let item = ctx.resolve_item(m.signature());
777 let func = item.expect_function();
778 func.name() == func_name
779 })
780 .position(|m| m.signature() == self.id())
781 });
782 }
783 }
784
785 None
786 })
787 }
788
789 /// Get this item's base name (aka non-namespaced name).
790 fn base_name(&self, ctx: &BindgenContext) -> String {
791 if let Some(path) = self.annotations().use_instead_of() {
792 return path.last().unwrap().clone();
793 }
794
795 match *self.kind() {
796 ItemKind::Var(ref var) => var.name().to_owned(),
797 ItemKind::Module(ref module) => {
798 module.name().map(ToOwned::to_owned).unwrap_or_else(|| {
799 format!("_bindgen_mod_{}", self.exposed_id(ctx))
800 })
801 }
802 ItemKind::Type(ref ty) => {
803 ty.sanitized_name(ctx).map(Into::into).unwrap_or_else(|| {
804 format!("_bindgen_ty_{}", self.exposed_id(ctx))
805 })
806 }
807 ItemKind::Function(ref fun) => {
808 let mut name = fun.name().to_owned();
809
810 if let Some(idx) = self.overload_index(ctx) {
811 if idx > 0 {
812 write!(&mut name, "{}", idx).unwrap();
813 }
814 }
815
816 name
817 }
818 }
819 }
820
821 fn is_anon(&self) -> bool {
822 match self.kind() {
823 ItemKind::Module(module) => module.name().is_none(),
824 ItemKind::Type(ty) => ty.name().is_none(),
825 ItemKind::Function(_) => false,
826 ItemKind::Var(_) => false,
827 }
828 }
829
830 /// Get the canonical name without taking into account the replaces
831 /// annotation.
832 ///
833 /// This is the base logic used to implement hiding and replacing via
834 /// annotations, and also to implement proper name mangling.
835 ///
836 /// The idea is that each generated type in the same "level" (read: module
837 /// or namespace) has a unique canonical name.
838 ///
839 /// This name should be derived from the immutable state contained in the
840 /// type and the parent chain, since it should be consistent.
841 ///
842 /// If `BindgenOptions::disable_nested_struct_naming` is true then returned
843 /// name is the inner most non-anonymous name plus all the anonymous base names
844 /// that follows.
845 pub(crate) fn real_canonical_name(
846 &self,
847 ctx: &BindgenContext,
848 opt: &NameOptions,
849 ) -> String {
850 let target = ctx.resolve_item(self.name_target(ctx));
851
852 // Short-circuit if the target has an override, and just use that.
853 if let Some(path) = target.annotations.use_instead_of() {
854 if ctx.options().enable_cxx_namespaces {
855 return path.last().unwrap().clone();
856 }
857 return path.join("_");
858 }
859
860 let base_name = target.base_name(ctx);
861
862 // Named template type arguments are never namespaced, and never
863 // mangled.
864 if target.is_template_param(ctx, &()) {
865 return base_name;
866 }
867
868 // Ancestors' ID iter
869 let mut ids_iter = target
870 .parent_id()
871 .ancestors(ctx)
872 .filter(|id| *id != ctx.root_module())
873 .take_while(|id| {
874 // Stop iterating ancestors once we reach a non-inline namespace
875 // when opt.within_namespaces is set.
876 !opt.within_namespaces || !ctx.resolve_item(*id).is_module()
877 })
878 .filter(|id| {
879 if !ctx.options().conservative_inline_namespaces {
880 if let ItemKind::Module(ref module) =
881 *ctx.resolve_item(*id).kind()
882 {
883 return !module.is_inline();
884 }
885 }
886
887 true
888 });
889
890 let ids: Vec<_> = if ctx.options().disable_nested_struct_naming {
891 let mut ids = Vec::new();
892
893 // If target is anonymous we need find its first named ancestor.
894 if target.is_anon() {
895 for id in ids_iter.by_ref() {
896 ids.push(id);
897
898 if !ctx.resolve_item(id).is_anon() {
899 break;
900 }
901 }
902 }
903
904 ids
905 } else {
906 ids_iter.collect()
907 };
908
909 // Concatenate this item's ancestors' names together.
910 let mut names: Vec<_> = ids
911 .into_iter()
912 .map(|id| {
913 let item = ctx.resolve_item(id);
914 let target = ctx.resolve_item(item.name_target(ctx));
915 target.base_name(ctx)
916 })
917 .filter(|name| !name.is_empty())
918 .collect();
919
920 names.reverse();
921
922 if !base_name.is_empty() {
923 names.push(base_name);
924 }
925
926 if ctx.options().c_naming {
927 if let Some(prefix) = self.c_naming_prefix() {
928 names.insert(0, prefix.to_string());
929 }
930 }
931
932 let name = names.join("_");
933
934 let name = if opt.user_mangled == UserMangled::Yes {
935 ctx.options()
936 .last_callback(|callbacks| callbacks.item_name(&name))
937 .unwrap_or(name)
938 } else {
939 name
940 };
941
942 ctx.rust_mangle(&name).into_owned()
943 }
944
945 /// The exposed ID that represents an unique ID among the siblings of a
946 /// given item.
947 pub(crate) fn exposed_id(&self, ctx: &BindgenContext) -> String {
948 // Only use local ids for enums, classes, structs and union types. All
949 // other items use their global ID.
950 let ty_kind = self.kind().as_type().map(|t| t.kind());
951 if let Some(ty_kind) = ty_kind {
952 match *ty_kind {
953 TypeKind::Comp(..) |
954 TypeKind::TemplateInstantiation(..) |
955 TypeKind::Enum(..) => return self.local_id(ctx).to_string(),
956 _ => {}
957 }
958 }
959
960 // Note that this `id_` prefix prevents (really unlikely) collisions
961 // between the global ID and the local ID of an item with the same
962 // parent.
963 format!("id_{}", self.id().as_usize())
964 }
965
966 /// Get a reference to this item's `Module`, or `None` if this is not a
967 /// `Module` item.
968 pub(crate) fn as_module(&self) -> Option<&Module> {
969 match self.kind {
970 ItemKind::Module(ref module) => Some(module),
971 _ => None,
972 }
973 }
974
975 /// Get a mutable reference to this item's `Module`, or `None` if this is
976 /// not a `Module` item.
977 pub(crate) fn as_module_mut(&mut self) -> Option<&mut Module> {
978 match self.kind {
979 ItemKind::Module(ref mut module) => Some(module),
980 _ => None,
981 }
982 }
983
984 /// Returns whether the item is a constified module enum
985 fn is_constified_enum_module(&self, ctx: &BindgenContext) -> bool {
986 // Do not jump through aliases, except for aliases that point to a type
987 // with the same name, since we dont generate coe for them.
988 let item = self.id.into_resolver().through_type_refs().resolve(ctx);
989 let type_ = match *item.kind() {
990 ItemKind::Type(ref type_) => type_,
991 _ => return false,
992 };
993
994 match *type_.kind() {
995 TypeKind::Enum(ref enum_) => {
996 enum_.computed_enum_variation(ctx, self) ==
997 EnumVariation::ModuleConsts
998 }
999 TypeKind::Alias(inner_id) => {
1000 // TODO(emilio): Make this "hop through type aliases that aren't
1001 // really generated" an option in `ItemResolver`?
1002 let inner_item = ctx.resolve_item(inner_id);
1003 let name = item.canonical_name(ctx);
1004
1005 if inner_item.canonical_name(ctx) == name {
1006 inner_item.is_constified_enum_module(ctx)
1007 } else {
1008 false
1009 }
1010 }
1011 _ => false,
1012 }
1013 }
1014
1015 /// Is this item of a kind that is enabled for code generation?
1016 pub(crate) fn is_enabled_for_codegen(&self, ctx: &BindgenContext) -> bool {
1017 let cc = &ctx.options().codegen_config;
1018 match *self.kind() {
1019 ItemKind::Module(..) => true,
1020 ItemKind::Var(_) => cc.vars(),
1021 ItemKind::Type(_) => cc.types(),
1022 ItemKind::Function(ref f) => match f.kind() {
1023 FunctionKind::Function => cc.functions(),
1024 FunctionKind::Method(MethodKind::Constructor) => {
1025 cc.constructors()
1026 }
1027 FunctionKind::Method(MethodKind::Destructor) |
1028 FunctionKind::Method(MethodKind::VirtualDestructor {
1029 ..
1030 }) => cc.destructors(),
1031 FunctionKind::Method(MethodKind::Static) |
1032 FunctionKind::Method(MethodKind::Normal) |
1033 FunctionKind::Method(MethodKind::Virtual { .. }) => {
1034 cc.methods()
1035 }
1036 },
1037 }
1038 }
1039
1040 /// Returns the path we should use for allowlisting / blocklisting, which
1041 /// doesn't include user-mangling.
1042 pub(crate) fn path_for_allowlisting(
1043 &self,
1044 ctx: &BindgenContext,
1045 ) -> &Vec<String> {
1046 self.path_for_allowlisting
1047 .borrow_with(|| self.compute_path(ctx, UserMangled::No))
1048 }
1049
1050 fn compute_path(
1051 &self,
1052 ctx: &BindgenContext,
1053 mangled: UserMangled,
1054 ) -> Vec<String> {
1055 if let Some(path) = self.annotations().use_instead_of() {
1056 let mut ret =
1057 vec![ctx.resolve_item(ctx.root_module()).name(ctx).get()];
1058 ret.extend_from_slice(path);
1059 return ret;
1060 }
1061
1062 let target = ctx.resolve_item(self.name_target(ctx));
1063 let mut path: Vec<_> = target
1064 .ancestors(ctx)
1065 .chain(iter::once(ctx.root_module().into()))
1066 .map(|id| ctx.resolve_item(id))
1067 .filter(|item| {
1068 item.id() == target.id() ||
1069 item.as_module().map_or(false, |module| {
1070 !module.is_inline() ||
1071 ctx.options().conservative_inline_namespaces
1072 })
1073 })
1074 .map(|item| {
1075 ctx.resolve_item(item.name_target(ctx))
1076 .name(ctx)
1077 .within_namespaces()
1078 .user_mangled(mangled)
1079 .get()
1080 })
1081 .collect();
1082 path.reverse();
1083 path
1084 }
1085
1086 /// Returns a prefix for the canonical name when C naming is enabled.
1087 fn c_naming_prefix(&self) -> Option<&str> {
1088 let ty = match self.kind {
1089 ItemKind::Type(ref ty) => ty,
1090 _ => return None,
1091 };
1092
1093 Some(match ty.kind() {
1094 TypeKind::Comp(ref ci) => match ci.kind() {
1095 CompKind::Struct => "struct",
1096 CompKind::Union => "union",
1097 },
1098 TypeKind::Enum(..) => "enum",
1099 _ => return None,
1100 })
1101 }
1102
1103 /// Whether this is a `#[must_use]` type.
1104 pub(crate) fn must_use(&self, ctx: &BindgenContext) -> bool {
1105 self.annotations().must_use_type() || ctx.must_use_type_by_name(self)
1106 }
1107 }
1108
1109 impl<T> IsOpaque for T
1110 where
1111 T: Copy + Into<ItemId>,
1112 {
1113 type Extra = ();
1114
1115 fn is_opaque(&self, ctx: &BindgenContext, _: &()) -> bool {
1116 debug_assert!(
1117 ctx.in_codegen_phase(),
1118 "You're not supposed to call this yet"
1119 );
1120 ctx.resolve_item((*self).into()).is_opaque(ctx, &())
1121 }
1122 }
1123
1124 impl IsOpaque for Item {
1125 type Extra = ();
1126
1127 fn is_opaque(&self, ctx: &BindgenContext, _: &()) -> bool {
1128 debug_assert!(
1129 ctx.in_codegen_phase(),
1130 "You're not supposed to call this yet"
1131 );
1132 self.annotations.opaque() ||
1133 self.as_type().map_or(false, |ty| ty.is_opaque(ctx, self)) ||
1134 ctx.opaque_by_name(self.path_for_allowlisting(ctx))
1135 }
1136 }
1137
1138 impl<T> HasVtable for T
1139 where
1140 T: Copy + Into<ItemId>,
1141 {
1142 fn has_vtable(&self, ctx: &BindgenContext) -> bool {
1143 let id: ItemId = (*self).into();
1144 id.as_type_id(ctx).map_or(false, |id| {
1145 !matches!(ctx.lookup_has_vtable(id), HasVtableResult::No)
1146 })
1147 }
1148
1149 fn has_vtable_ptr(&self, ctx: &BindgenContext) -> bool {
1150 let id: ItemId = (*self).into();
1151 id.as_type_id(ctx).map_or(false, |id| {
1152 matches!(ctx.lookup_has_vtable(id), HasVtableResult::SelfHasVtable)
1153 })
1154 }
1155 }
1156
1157 impl HasVtable for Item {
1158 fn has_vtable(&self, ctx: &BindgenContext) -> bool {
1159 self.id().has_vtable(ctx)
1160 }
1161
1162 fn has_vtable_ptr(&self, ctx: &BindgenContext) -> bool {
1163 self.id().has_vtable_ptr(ctx)
1164 }
1165 }
1166
1167 impl<T> Sizedness for T
1168 where
1169 T: Copy + Into<ItemId>,
1170 {
1171 fn sizedness(&self, ctx: &BindgenContext) -> SizednessResult {
1172 let id: ItemId = (*self).into();
1173 id.as_type_id(ctx)
1174 .map_or(SizednessResult::default(), |id| ctx.lookup_sizedness(id))
1175 }
1176 }
1177
1178 impl Sizedness for Item {
1179 fn sizedness(&self, ctx: &BindgenContext) -> SizednessResult {
1180 self.id().sizedness(ctx)
1181 }
1182 }
1183
1184 impl<T> HasTypeParamInArray for T
1185 where
1186 T: Copy + Into<ItemId>,
1187 {
1188 fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool {
1189 debug_assert!(
1190 ctx.in_codegen_phase(),
1191 "You're not supposed to call this yet"
1192 );
1193 ctx.lookup_has_type_param_in_array(*self)
1194 }
1195 }
1196
1197 impl HasTypeParamInArray for Item {
1198 fn has_type_param_in_array(&self, ctx: &BindgenContext) -> bool {
1199 debug_assert!(
1200 ctx.in_codegen_phase(),
1201 "You're not supposed to call this yet"
1202 );
1203 ctx.lookup_has_type_param_in_array(self.id())
1204 }
1205 }
1206
1207 impl<T> HasFloat for T
1208 where
1209 T: Copy + Into<ItemId>,
1210 {
1211 fn has_float(&self, ctx: &BindgenContext) -> bool {
1212 debug_assert!(
1213 ctx.in_codegen_phase(),
1214 "You're not supposed to call this yet"
1215 );
1216 ctx.lookup_has_float(*self)
1217 }
1218 }
1219
1220 impl HasFloat for Item {
1221 fn has_float(&self, ctx: &BindgenContext) -> bool {
1222 debug_assert!(
1223 ctx.in_codegen_phase(),
1224 "You're not supposed to call this yet"
1225 );
1226 ctx.lookup_has_float(self.id())
1227 }
1228 }
1229
1230 /// A set of items.
1231 pub(crate) type ItemSet = BTreeSet<ItemId>;
1232
1233 impl DotAttributes for Item {
1234 fn dot_attributes<W>(
1235 &self,
1236 ctx: &BindgenContext,
1237 out: &mut W,
1238 ) -> io::Result<()>
1239 where
1240 W: io::Write,
1241 {
1242 writeln!(
1243 out,
1244 "<tr><td>{:?}</td></tr>
1245 <tr><td>name</td><td>{}</td></tr>",
1246 self.id,
1247 self.name(ctx).get()
1248 )?;
1249
1250 if self.is_opaque(ctx, &()) {
1251 writeln!(out, "<tr><td>opaque</td><td>true</td></tr>")?;
1252 }
1253
1254 self.kind.dot_attributes(ctx, out)
1255 }
1256 }
1257
1258 impl<T> TemplateParameters for T
1259 where
1260 T: Copy + Into<ItemId>,
1261 {
1262 fn self_template_params(&self, ctx: &BindgenContext) -> Vec<TypeId> {
1263 ctx.resolve_item_fallible(*self)
1264 .map_or(vec![], |item| item.self_template_params(ctx))
1265 }
1266 }
1267
1268 impl TemplateParameters for Item {
1269 fn self_template_params(&self, ctx: &BindgenContext) -> Vec<TypeId> {
1270 self.kind.self_template_params(ctx)
1271 }
1272 }
1273
1274 impl TemplateParameters for ItemKind {
1275 fn self_template_params(&self, ctx: &BindgenContext) -> Vec<TypeId> {
1276 match *self {
1277 ItemKind::Type(ref ty) => ty.self_template_params(ctx),
1278 // If we start emitting bindings to explicitly instantiated
1279 // functions, then we'll need to check ItemKind::Function for
1280 // template params.
1281 ItemKind::Function(_) | ItemKind::Module(_) | ItemKind::Var(_) => {
1282 vec![]
1283 }
1284 }
1285 }
1286 }
1287
1288 // An utility function to handle recursing inside nested types.
1289 fn visit_child(
1290 cur: clang::Cursor,
1291 id: ItemId,
1292 ty: &clang::Type,
1293 parent_id: Option<ItemId>,
1294 ctx: &mut BindgenContext,
1295 result: &mut Result<TypeId, ParseError>,
1296 ) -> clang_sys::CXChildVisitResult {
1297 use clang_sys::*;
1298 if result.is_ok() {
1299 return CXChildVisit_Break;
1300 }
1301
1302 *result = Item::from_ty_with_id(id, ty, cur, parent_id, ctx);
1303
1304 match *result {
1305 Ok(..) => CXChildVisit_Break,
1306 Err(ParseError::Recurse) => {
1307 cur.visit(|c| visit_child(c, id, ty, parent_id, ctx, result));
1308 CXChildVisit_Continue
1309 }
1310 Err(ParseError::Continue) => CXChildVisit_Continue,
1311 }
1312 }
1313
1314 impl Item {
1315 /// Create a builtin type.
1316 pub(crate) fn builtin_type(
1317 kind: TypeKind,
1318 is_const: bool,
1319 ctx: &mut BindgenContext,
1320 ) -> TypeId {
1321 // Feel free to add more here, I'm just lazy.
1322 match kind {
1323 TypeKind::Void |
1324 TypeKind::Int(..) |
1325 TypeKind::Pointer(..) |
1326 TypeKind::Float(..) => {}
1327 _ => panic!("Unsupported builtin type"),
1328 }
1329
1330 let ty = Type::new(None, None, kind, is_const);
1331 let id = ctx.next_item_id();
1332 let module = ctx.root_module().into();
1333 ctx.add_item(
1334 Item::new(id, None, None, module, ItemKind::Type(ty), None),
1335 None,
1336 None,
1337 );
1338 id.as_type_id_unchecked()
1339 }
1340
1341 /// Parse this item from the given Clang cursor.
1342 pub(crate) fn parse(
1343 cursor: clang::Cursor,
1344 parent_id: Option<ItemId>,
1345 ctx: &mut BindgenContext,
1346 ) -> Result<ItemId, ParseError> {
1347 use crate::ir::var::Var;
1348 use clang_sys::*;
1349
1350 if !cursor.is_valid() {
1351 return Err(ParseError::Continue);
1352 }
1353
1354 let comment = cursor.raw_comment();
1355 let annotations = Annotations::new(&cursor);
1356
1357 let current_module = ctx.current_module().into();
1358 let relevant_parent_id = parent_id.unwrap_or(current_module);
1359
1360 #[allow(clippy::missing_docs_in_private_items)]
1361 macro_rules! try_parse {
1362 ($what:ident) => {
1363 match $what::parse(cursor, ctx) {
1364 Ok(ParseResult::New(item, declaration)) => {
1365 let id = ctx.next_item_id();
1366
1367 ctx.add_item(
1368 Item::new(
1369 id,
1370 comment,
1371 annotations,
1372 relevant_parent_id,
1373 ItemKind::$what(item),
1374 Some(cursor.location()),
1375 ),
1376 declaration,
1377 Some(cursor),
1378 );
1379 return Ok(id);
1380 }
1381 Ok(ParseResult::AlreadyResolved(id)) => {
1382 return Ok(id);
1383 }
1384 Err(ParseError::Recurse) => return Err(ParseError::Recurse),
1385 Err(ParseError::Continue) => {}
1386 }
1387 };
1388 }
1389
1390 try_parse!(Module);
1391
1392 // NOTE: Is extremely important to parse functions and vars **before**
1393 // types. Otherwise we can parse a function declaration as a type
1394 // (which is legal), and lose functions to generate.
1395 //
1396 // In general, I'm not totally confident this split between
1397 // ItemKind::Function and TypeKind::FunctionSig is totally worth it, but
1398 // I guess we can try.
1399 try_parse!(Function);
1400 try_parse!(Var);
1401
1402 // Types are sort of special, so to avoid parsing template classes
1403 // twice, handle them separately.
1404 {
1405 let definition = cursor.definition();
1406 let applicable_cursor = definition.unwrap_or(cursor);
1407
1408 let relevant_parent_id = match definition {
1409 Some(definition) => {
1410 if definition != cursor {
1411 ctx.add_semantic_parent(definition, relevant_parent_id);
1412 return Ok(Item::from_ty_or_ref(
1413 applicable_cursor.cur_type(),
1414 cursor,
1415 parent_id,
1416 ctx,
1417 )
1418 .into());
1419 }
1420 ctx.known_semantic_parent(definition)
1421 .or(parent_id)
1422 .unwrap_or_else(|| ctx.current_module().into())
1423 }
1424 None => relevant_parent_id,
1425 };
1426
1427 match Item::from_ty(
1428 &applicable_cursor.cur_type(),
1429 applicable_cursor,
1430 Some(relevant_parent_id),
1431 ctx,
1432 ) {
1433 Ok(ty) => return Ok(ty.into()),
1434 Err(ParseError::Recurse) => return Err(ParseError::Recurse),
1435 Err(ParseError::Continue) => {}
1436 }
1437 }
1438
1439 match cursor.kind() {
1440 // On Clang 18+, extern "C" is reported accurately as a LinkageSpec.
1441 // Older LLVM treat it as UnexposedDecl.
1442 CXCursor_LinkageSpec | CXCursor_UnexposedDecl => {
1443 Err(ParseError::Recurse)
1444 }
1445
1446 // We allowlist cursors here known to be unhandled, to prevent being
1447 // too noisy about this.
1448 CXCursor_MacroDefinition |
1449 CXCursor_MacroExpansion |
1450 CXCursor_UsingDeclaration |
1451 CXCursor_UsingDirective |
1452 CXCursor_StaticAssert |
1453 CXCursor_FunctionTemplate => {
1454 debug!(
1455 "Unhandled cursor kind {:?}: {:?}",
1456 cursor.kind(),
1457 cursor
1458 );
1459 Err(ParseError::Continue)
1460 }
1461
1462 CXCursor_InclusionDirective => {
1463 let file = cursor.get_included_file_name();
1464 match file {
1465 None => {
1466 warn!("Inclusion of a nameless file in {:?}", cursor);
1467 }
1468 Some(included_file) => {
1469 for cb in &ctx.options().parse_callbacks {
1470 cb.include_file(&included_file);
1471 }
1472
1473 ctx.add_dep(included_file.into_boxed_str());
1474 }
1475 }
1476 Err(ParseError::Continue)
1477 }
1478
1479 _ => {
1480 // ignore toplevel operator overloads
1481 let spelling = cursor.spelling();
1482 if !spelling.starts_with("operator") {
1483 warn!(
1484 "Unhandled cursor kind {:?}: {:?}",
1485 cursor.kind(),
1486 cursor
1487 );
1488 }
1489 Err(ParseError::Continue)
1490 }
1491 }
1492 }
1493
1494 /// Parse this item from the given Clang type, or if we haven't resolved all
1495 /// the other items this one depends on, an unresolved reference.
1496 pub(crate) fn from_ty_or_ref(
1497 ty: clang::Type,
1498 location: clang::Cursor,
1499 parent_id: Option<ItemId>,
1500 ctx: &mut BindgenContext,
1501 ) -> TypeId {
1502 let id = ctx.next_item_id();
1503 Self::from_ty_or_ref_with_id(id, ty, location, parent_id, ctx)
1504 }
1505
1506 /// Parse a C++ type. If we find a reference to a type that has not been
1507 /// defined yet, use `UnresolvedTypeRef` as a placeholder.
1508 ///
1509 /// This logic is needed to avoid parsing items with the incorrect parent
1510 /// and it's sort of complex to explain, so I'll just point to
1511 /// `tests/headers/typeref.hpp` to see the kind of constructs that forced
1512 /// this.
1513 ///
1514 /// Typerefs are resolved once parsing is completely done, see
1515 /// `BindgenContext::resolve_typerefs`.
1516 pub(crate) fn from_ty_or_ref_with_id(
1517 potential_id: ItemId,
1518 ty: clang::Type,
1519 location: clang::Cursor,
1520 parent_id: Option<ItemId>,
1521 ctx: &mut BindgenContext,
1522 ) -> TypeId {
1523 debug!(
1524 "from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}",
1525 potential_id, ty, location, parent_id
1526 );
1527
1528 if ctx.collected_typerefs() {
1529 debug!("refs already collected, resolving directly");
1530 return Item::from_ty_with_id(
1531 potential_id,
1532 &ty,
1533 location,
1534 parent_id,
1535 ctx,
1536 )
1537 .unwrap_or_else(|_| Item::new_opaque_type(potential_id, &ty, ctx));
1538 }
1539
1540 if let Some(ty) = ctx.builtin_or_resolved_ty(
1541 potential_id,
1542 parent_id,
1543 &ty,
1544 Some(location),
1545 ) {
1546 debug!("{:?} already resolved: {:?}", ty, location);
1547 return ty;
1548 }
1549
1550 debug!("New unresolved type reference: {:?}, {:?}", ty, location);
1551
1552 let is_const = ty.is_const();
1553 let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id);
1554 let current_module = ctx.current_module();
1555
1556 ctx.add_item(
1557 Item::new(
1558 potential_id,
1559 None,
1560 None,
1561 parent_id.unwrap_or_else(|| current_module.into()),
1562 ItemKind::Type(Type::new(None, None, kind, is_const)),
1563 Some(location.location()),
1564 ),
1565 None,
1566 None,
1567 );
1568 potential_id.as_type_id_unchecked()
1569 }
1570
1571 /// Parse this item from the given Clang type. See [`Item::from_ty_with_id`].
1572 pub(crate) fn from_ty(
1573 ty: &clang::Type,
1574 location: clang::Cursor,
1575 parent_id: Option<ItemId>,
1576 ctx: &mut BindgenContext,
1577 ) -> Result<TypeId, ParseError> {
1578 let id = ctx.next_item_id();
1579 Item::from_ty_with_id(id, ty, location, parent_id, ctx)
1580 }
1581
1582 /// This is one of the trickiest methods you'll find (probably along with
1583 /// some of the ones that handle templates in `BindgenContext`).
1584 ///
1585 /// This method parses a type, given the potential ID of that type (if
1586 /// parsing it was correct), an optional location we're scanning, which is
1587 /// critical some times to obtain information, an optional parent item ID,
1588 /// that will, if it's `None`, become the current module ID, and the
1589 /// context.
1590 pub(crate) fn from_ty_with_id(
1591 id: ItemId,
1592 ty: &clang::Type,
1593 location: clang::Cursor,
1594 parent_id: Option<ItemId>,
1595 ctx: &mut BindgenContext,
1596 ) -> Result<TypeId, ParseError> {
1597 use clang_sys::*;
1598
1599 debug!(
1600 "Item::from_ty_with_id: {:?}\n\
1601 \tty = {:?},\n\
1602 \tlocation = {:?}",
1603 id, ty, location
1604 );
1605
1606 if ty.kind() == clang_sys::CXType_Unexposed ||
1607 location.cur_type().kind() == clang_sys::CXType_Unexposed
1608 {
1609 if ty.is_associated_type() ||
1610 location.cur_type().is_associated_type()
1611 {
1612 return Ok(Item::new_opaque_type(id, ty, ctx));
1613 }
1614
1615 if let Some(param_id) = Item::type_param(None, location, ctx) {
1616 return Ok(ctx.build_ty_wrapper(id, param_id, None, ty));
1617 }
1618 }
1619
1620 // Treat all types that are declared inside functions as opaque. The Rust binding
1621 // won't be able to do anything with them anyway.
1622 //
1623 // (If we don't do this check here, we can have subtle logic bugs because we generally
1624 // ignore function bodies. See issue #2036.)
1625 if let Some(ref parent) = ty.declaration().fallible_semantic_parent() {
1626 if FunctionKind::from_cursor(parent).is_some() {
1627 debug!("Skipping type declared inside function: {:?}", ty);
1628 return Ok(Item::new_opaque_type(id, ty, ctx));
1629 }
1630 }
1631
1632 let decl = {
1633 let canonical_def = ty.canonical_type().declaration().definition();
1634 canonical_def.unwrap_or_else(|| ty.declaration())
1635 };
1636
1637 let comment = location
1638 .raw_comment()
1639 .or_else(|| decl.raw_comment())
1640 .or_else(|| location.raw_comment());
1641
1642 let annotations =
1643 Annotations::new(&decl).or_else(|| Annotations::new(&location));
1644
1645 if let Some(ref annotations) = annotations {
1646 if let Some(replaced) = annotations.use_instead_of() {
1647 ctx.replace(replaced, id);
1648 }
1649 }
1650
1651 if let Some(ty) =
1652 ctx.builtin_or_resolved_ty(id, parent_id, ty, Some(location))
1653 {
1654 return Ok(ty);
1655 }
1656
1657 // First, check we're not recursing.
1658 let mut valid_decl = decl.kind() != CXCursor_NoDeclFound;
1659 let declaration_to_look_for = if valid_decl {
1660 decl.canonical()
1661 } else if location.kind() == CXCursor_ClassTemplate {
1662 valid_decl = true;
1663 location
1664 } else {
1665 decl
1666 };
1667
1668 if valid_decl {
1669 if let Some(partial) = ctx
1670 .currently_parsed_types()
1671 .iter()
1672 .find(|ty| *ty.decl() == declaration_to_look_for)
1673 {
1674 debug!("Avoiding recursion parsing type: {:?}", ty);
1675 // Unchecked because we haven't finished this type yet.
1676 return Ok(partial.id().as_type_id_unchecked());
1677 }
1678 }
1679
1680 let current_module = ctx.current_module().into();
1681 let partial_ty = PartialType::new(declaration_to_look_for, id);
1682 if valid_decl {
1683 ctx.begin_parsing(partial_ty);
1684 }
1685
1686 let result = Type::from_clang_ty(id, ty, location, parent_id, ctx);
1687 let relevant_parent_id = parent_id.unwrap_or(current_module);
1688 let ret = match result {
1689 Ok(ParseResult::AlreadyResolved(ty)) => {
1690 Ok(ty.as_type_id_unchecked())
1691 }
1692 Ok(ParseResult::New(item, declaration)) => {
1693 ctx.add_item(
1694 Item::new(
1695 id,
1696 comment,
1697 annotations,
1698 relevant_parent_id,
1699 ItemKind::Type(item),
1700 Some(location.location()),
1701 ),
1702 declaration,
1703 Some(location),
1704 );
1705 Ok(id.as_type_id_unchecked())
1706 }
1707 Err(ParseError::Continue) => Err(ParseError::Continue),
1708 Err(ParseError::Recurse) => {
1709 debug!("Item::from_ty recursing in the ast");
1710 let mut result = Err(ParseError::Recurse);
1711
1712 // Need to pop here, otherwise we'll get stuck.
1713 //
1714 // TODO: Find a nicer interface, really. Also, the
1715 // declaration_to_look_for suspiciously shares a lot of
1716 // logic with ir::context, so we should refactor that.
1717 if valid_decl {
1718 let finished = ctx.finish_parsing();
1719 assert_eq!(*finished.decl(), declaration_to_look_for);
1720 }
1721
1722 location.visit(|cur| {
1723 visit_child(cur, id, ty, parent_id, ctx, &mut result)
1724 });
1725
1726 if valid_decl {
1727 let partial_ty =
1728 PartialType::new(declaration_to_look_for, id);
1729 ctx.begin_parsing(partial_ty);
1730 }
1731
1732 // If we have recursed into the AST all we know, and we still
1733 // haven't found what we've got, let's just try and make a named
1734 // type.
1735 //
1736 // This is what happens with some template members, for example.
1737 if let Err(ParseError::Recurse) = result {
1738 warn!(
1739 "Unknown type, assuming named template type: \
1740 id = {:?}; spelling = {}",
1741 id,
1742 ty.spelling()
1743 );
1744 Item::type_param(Some(id), location, ctx)
1745 .map(Ok)
1746 .unwrap_or(Err(ParseError::Recurse))
1747 } else {
1748 result
1749 }
1750 }
1751 };
1752
1753 if valid_decl {
1754 let partial_ty = ctx.finish_parsing();
1755 assert_eq!(*partial_ty.decl(), declaration_to_look_for);
1756 }
1757
1758 ret
1759 }
1760
1761 /// A named type is a template parameter, e.g., the `T` in `Foo<T>`. They're always local so
1762 /// it's the only exception when there's no declaration for a type.
1763 pub(crate) fn type_param(
1764 with_id: Option<ItemId>,
1765 location: clang::Cursor,
1766 ctx: &mut BindgenContext,
1767 ) -> Option<TypeId> {
1768 let ty = location.cur_type();
1769
1770 debug!(
1771 "Item::type_param:\n\
1772 \twith_id = {:?},\n\
1773 \tty = {} {:?},\n\
1774 \tlocation: {:?}",
1775 with_id,
1776 ty.spelling(),
1777 ty,
1778 location
1779 );
1780
1781 if ty.kind() != clang_sys::CXType_Unexposed {
1782 // If the given cursor's type's kind is not Unexposed, then we
1783 // aren't looking at a template parameter. This check may need to be
1784 // updated in the future if they start properly exposing template
1785 // type parameters.
1786 return None;
1787 }
1788
1789 let ty_spelling = ty.spelling();
1790
1791 // Clang does not expose any information about template type parameters
1792 // via their clang::Type, nor does it give us their canonical cursors
1793 // the straightforward way. However, there are three situations from
1794 // which we can find the definition of the template type parameter, if
1795 // the cursor is indeed looking at some kind of a template type
1796 // parameter or use of one:
1797 //
1798 // 1. The cursor is pointing at the template type parameter's
1799 // definition. This is the trivial case.
1800 //
1801 // (kind = TemplateTypeParameter, ...)
1802 //
1803 // 2. The cursor is pointing at a TypeRef whose referenced() cursor is
1804 // situation (1).
1805 //
1806 // (kind = TypeRef,
1807 // referenced = (kind = TemplateTypeParameter, ...),
1808 // ...)
1809 //
1810 // 3. The cursor is pointing at some use of a template type parameter
1811 // (for example, in a FieldDecl), and this cursor has a child cursor
1812 // whose spelling is the same as the parent's type's spelling, and whose
1813 // kind is a TypeRef of the situation (2) variety.
1814 //
1815 // (kind = FieldDecl,
1816 // type = (kind = Unexposed,
1817 // spelling = "T",
1818 // ...),
1819 // children =
1820 // (kind = TypeRef,
1821 // spelling = "T",
1822 // referenced = (kind = TemplateTypeParameter,
1823 // spelling = "T",
1824 // ...),
1825 // ...)
1826 // ...)
1827 //
1828 // TODO: The alternative to this hacky pattern matching would be to
1829 // maintain proper scopes of template parameters while parsing and use
1830 // de Brujin indices to access template parameters, which clang exposes
1831 // in the cursor's type's canonical type's spelling:
1832 // "type-parameter-x-y". That is probably a better approach long-term,
1833 // but maintaining these scopes properly would require more changes to
1834 // the whole libclang -> IR parsing code.
1835
1836 fn is_template_with_spelling(
1837 refd: &clang::Cursor,
1838 spelling: &str,
1839 ) -> bool {
1840 lazy_static! {
1841 static ref ANON_TYPE_PARAM_RE: regex::Regex =
1842 regex::Regex::new(r"^type\-parameter\-\d+\-\d+$").unwrap();
1843 }
1844
1845 if refd.kind() != clang_sys::CXCursor_TemplateTypeParameter {
1846 return false;
1847 }
1848
1849 let refd_spelling = refd.spelling();
1850 refd_spelling == spelling ||
1851 // Allow for anonymous template parameters.
1852 (refd_spelling.is_empty() && ANON_TYPE_PARAM_RE.is_match(spelling.as_ref()))
1853 }
1854
1855 let definition = if is_template_with_spelling(&location, &ty_spelling) {
1856 // Situation (1)
1857 location
1858 } else if location.kind() == clang_sys::CXCursor_TypeRef {
1859 // Situation (2)
1860 match location.referenced() {
1861 Some(refd)
1862 if is_template_with_spelling(&refd, &ty_spelling) =>
1863 {
1864 refd
1865 }
1866 _ => return None,
1867 }
1868 } else {
1869 // Situation (3)
1870 let mut definition = None;
1871
1872 location.visit(|child| {
1873 let child_ty = child.cur_type();
1874 if child_ty.kind() == clang_sys::CXCursor_TypeRef &&
1875 child_ty.spelling() == ty_spelling
1876 {
1877 match child.referenced() {
1878 Some(refd)
1879 if is_template_with_spelling(
1880 &refd,
1881 &ty_spelling,
1882 ) =>
1883 {
1884 definition = Some(refd);
1885 return clang_sys::CXChildVisit_Break;
1886 }
1887 _ => {}
1888 }
1889 }
1890
1891 clang_sys::CXChildVisit_Continue
1892 });
1893
1894 definition?
1895 };
1896 assert!(is_template_with_spelling(&definition, &ty_spelling));
1897
1898 // Named types are always parented to the root module. They are never
1899 // referenced with namespace prefixes, and they can't inherit anything
1900 // from their parent either, so it is simplest to just hang them off
1901 // something we know will always exist.
1902 let parent = ctx.root_module().into();
1903
1904 if let Some(id) = ctx.get_type_param(&definition) {
1905 if let Some(with_id) = with_id {
1906 return Some(ctx.build_ty_wrapper(
1907 with_id,
1908 id,
1909 Some(parent),
1910 &ty,
1911 ));
1912 } else {
1913 return Some(id);
1914 }
1915 }
1916
1917 // See tests/headers/const_tparam.hpp and
1918 // tests/headers/variadic_tname.hpp.
1919 let name = ty_spelling.replace("const ", "").replace('.', "");
1920
1921 let id = with_id.unwrap_or_else(|| ctx.next_item_id());
1922 let item = Item::new(
1923 id,
1924 None,
1925 None,
1926 parent,
1927 ItemKind::Type(Type::named(name)),
1928 Some(location.location()),
1929 );
1930 ctx.add_type_param(item, definition);
1931 Some(id.as_type_id_unchecked())
1932 }
1933 }
1934
1935 impl ItemCanonicalName for Item {
1936 fn canonical_name(&self, ctx: &BindgenContext) -> String {
1937 debug_assert!(
1938 ctx.in_codegen_phase(),
1939 "You're not supposed to call this yet"
1940 );
1941 self.canonical_name
1942 .borrow_with(|| {
1943 let in_namespace = ctx.options().enable_cxx_namespaces ||
1944 ctx.options().disable_name_namespacing;
1945
1946 if in_namespace {
1947 self.name(ctx).within_namespaces().get()
1948 } else {
1949 self.name(ctx).get()
1950 }
1951 })
1952 .clone()
1953 }
1954 }
1955
1956 impl ItemCanonicalPath for Item {
1957 fn namespace_aware_canonical_path(
1958 &self,
1959 ctx: &BindgenContext,
1960 ) -> Vec<String> {
1961 let mut path = self.canonical_path(ctx);
1962
1963 // ASSUMPTION: (disable_name_namespacing && cxx_namespaces)
1964 // is equivalent to
1965 // disable_name_namespacing
1966 if ctx.options().disable_name_namespacing {
1967 // Only keep the last item in path
1968 let split_idx = path.len() - 1;
1969 path = path.split_off(split_idx);
1970 } else if !ctx.options().enable_cxx_namespaces {
1971 // Ignore first item "root"
1972 path = vec![path[1..].join("_")];
1973 }
1974
1975 if self.is_constified_enum_module(ctx) {
1976 path.push(CONSTIFIED_ENUM_MODULE_REPR_NAME.into());
1977 }
1978
1979 path
1980 }
1981
1982 fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String> {
1983 self.compute_path(ctx, UserMangled::Yes)
1984 }
1985 }
1986
1987 /// Whether to use the user-mangled name (mangled by the `item_name` callback or
1988 /// not.
1989 ///
1990 /// Most of the callers probably want just yes, but the ones dealing with
1991 /// allowlisting and blocklisting don't.
1992 #[derive(Copy, Clone, Debug, PartialEq)]
1993 enum UserMangled {
1994 No,
1995 Yes,
1996 }
1997
1998 /// Builder struct for naming variations, which hold inside different
1999 /// flags for naming options.
2000 #[derive(Debug)]
2001 pub(crate) struct NameOptions<'a> {
2002 item: &'a Item,
2003 ctx: &'a BindgenContext,
2004 within_namespaces: bool,
2005 user_mangled: UserMangled,
2006 }
2007
2008 impl<'a> NameOptions<'a> {
2009 /// Construct a new `NameOptions`
2010 pub(crate) fn new(item: &'a Item, ctx: &'a BindgenContext) -> Self {
2011 NameOptions {
2012 item,
2013 ctx,
2014 within_namespaces: false,
2015 user_mangled: UserMangled::Yes,
2016 }
2017 }
2018
2019 /// Construct the name without the item's containing C++ namespaces mangled
2020 /// into it. In other words, the item's name within the item's namespace.
2021 pub(crate) fn within_namespaces(&mut self) -> &mut Self {
2022 self.within_namespaces = true;
2023 self
2024 }
2025
2026 fn user_mangled(&mut self, user_mangled: UserMangled) -> &mut Self {
2027 self.user_mangled = user_mangled;
2028 self
2029 }
2030
2031 /// Construct a name `String`
2032 pub(crate) fn get(&self) -> String {
2033 self.item.real_canonical_name(self.ctx, self)
2034 }
2035 }