summaryrefslogtreecommitdiff
path: root/libbindgen/src/ir/item.rs
blob: 76ab0d5531fee24311b913207f2e2aaf01cdcde3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
//! Bindgen's core intermediate representation type.

use clang;
use clangll;
use parse::{ClangItemParser, ClangSubItemParser, ParseError, ParseResult};
use std::cell::{Cell, RefCell};
use std::fmt::Write;
use std::iter;
use super::annotations::Annotations;
use super::context::{BindgenContext, ItemId};
use super::function::Function;
use super::item_kind::ItemKind;
use super::module::Module;
use super::ty::{Type, TypeKind};
use super::type_collector::{ItemSet, TypeCollector};

/// A trait to get the canonical name from an item.
///
/// This is the trait that will eventually isolate all the logic related to name
/// mangling and that kind of stuff.
///
/// This assumes no nested paths, at some point I'll have to make it a more
/// complex thing.
///
/// This name is required to be safe for Rust, that is, is not expected to
/// return any rust keyword from here.
pub trait ItemCanonicalName {
    /// Get the canonical name for this item.
    fn canonical_name(&self, ctx: &BindgenContext) -> String;
}

/// The same, but specifies the path that needs to be followed to reach an item.
///
/// To contrast with canonical_name, here's an example:
///
/// ```c++
/// namespace foo {
///     const BAR = 3;
/// }
/// ```
///
/// For bar, the canonical path is `vec!["foo", "BAR"]`, while the canonical
/// name is just `"BAR"`.
pub trait ItemCanonicalPath {
    /// Get the canonical path for this item.
    fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String>;
}

/// A trait for iterating over an item and its parents and up its ancestor chain
/// up to (but not including) the implicit root module.
pub trait ItemAncestors {
    /// Get an iterable over this item's ancestors.
    fn ancestors<'a, 'b>(&self,
                         ctx: &'a BindgenContext<'b>)
                         -> ItemAncestorsIter<'a, 'b>;
}

/// An iterator over an item and its ancestors.
pub struct ItemAncestorsIter<'a, 'b>
    where 'b: 'a,
{
    item: ItemId,
    ctx: &'a BindgenContext<'b>,
}

impl<'a, 'b> Iterator for ItemAncestorsIter<'a, 'b>
    where 'b: 'a,
{
    type Item = ItemId;

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.ctx.resolve_item(self.item);
        if item.parent_id() == self.item {
            None
        } else {
            self.item = item.parent_id();
            Some(item.id())
        }
    }
}

// Pure convenience
impl ItemCanonicalName for ItemId {
    fn canonical_name(&self, ctx: &BindgenContext) -> String {
        debug_assert!(ctx.in_codegen_phase(),
                      "You're not supposed to call this yet");
        ctx.resolve_item(*self).canonical_name(ctx)
    }
}

impl ItemCanonicalPath for ItemId {
    fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String> {
        debug_assert!(ctx.in_codegen_phase(),
                      "You're not supposed to call this yet");
        ctx.resolve_item(*self).canonical_path(ctx)
    }
}

impl ItemAncestors for ItemId {
    fn ancestors<'a, 'b>(&self,
                         ctx: &'a BindgenContext<'b>)
                         -> ItemAncestorsIter<'a, 'b> {
        ItemAncestorsIter {
            item: *self,
            ctx: ctx,
        }
    }
}

impl ItemAncestors for Item {
    fn ancestors<'a, 'b>(&self,
                         ctx: &'a BindgenContext<'b>)
                         -> ItemAncestorsIter<'a, 'b> {
        self.id().ancestors(ctx)
    }
}

impl TypeCollector for ItemId {
    type Extra = ();

    fn collect_types(&self,
                     ctx: &BindgenContext,
                     types: &mut ItemSet,
                     extra: &()) {
        ctx.resolve_item(*self).collect_types(ctx, types, extra);
    }
}

impl TypeCollector for Item {
    type Extra = ();

    fn collect_types(&self,
                     ctx: &BindgenContext,
                     types: &mut ItemSet,
                     _extra: &()) {
        if self.is_hidden(ctx) || types.contains(&self.id()) {
            return;
        }

        match *self.kind() {
            ItemKind::Type(ref ty) => {
                if !self.is_opaque(ctx) {
                    ty.collect_types(ctx, types, self);
                }
            }
            ItemKind::Function(ref fun) => {
                if !self.is_opaque(ctx) {
                    types.insert(fun.signature());
                }
            }
            _ => {} // FIXME.
        }
    }
}

/// An item is the base of the bindgen representation, it can be either a
/// module, a type, a function, or a variable (see `ItemKind` for more
/// information).
///
/// Items refer to each other by `ItemId`. Every item has its parent's
/// id. Depending on the kind of item this is, it may also refer to other items,
/// such as a compound type item referring to other types. Collectively, these
/// references form a graph.
///
/// The entry-point to this graph is the "root module": a meta-item used to hold
/// all top-level items.
///
/// An item may have a comment, and annotations (see the `annotations` module).
///
/// Note that even though we parse all the types of annotations in comments, not
/// all of them apply to every item. Those rules are described in the
/// `annotations` module.
#[derive(Debug)]
pub struct Item {
    /// This item's id.
    id: ItemId,

    /// The item's local id, unique only amongst its siblings.  Only used for
    /// anonymous items.
    ///
    /// Lazily initialized in local_id().
    ///
    /// Note that only structs, unions, and enums get a local type id. In any
    /// case this is an implementation detail.
    local_id: Cell<Option<usize>>,

    /// The next local id to use for a child..
    next_child_local_id: Cell<usize>,

    /// A cached copy of the canonical name, as returned by `canonical_name`.
    ///
    /// This is a fairly used operation during codegen so this makes bindgen
    /// considerably faster in those cases.
    canonical_name_cache: RefCell<Option<String>>,

    /// A doc comment over the item, if any.
    comment: Option<String>,
    /// Annotations extracted from the doc comment, or the default ones
    /// otherwise.
    annotations: Annotations,
    /// An item's parent id. This will most likely be a class where this item
    /// was declared, or a module, etc.
    ///
    /// All the items have a parent, except the root module, in which case the
    /// parent id is its own id.
    parent_id: ItemId,
    /// The item kind.
    kind: ItemKind,
}

impl Item {
    /// Construct a new `Item`.
    pub fn new(id: ItemId,
               comment: Option<String>,
               annotations: Option<Annotations>,
               parent_id: ItemId,
               kind: ItemKind)
               -> Self {
        debug_assert!(id != parent_id || kind.is_module());
        Item {
            id: id,
            local_id: Cell::new(None),
            next_child_local_id: Cell::new(1),
            canonical_name_cache: RefCell::new(None),
            parent_id: parent_id,
            comment: comment,
            annotations: annotations.unwrap_or_default(),
            kind: kind,
        }
    }

    /// Get this `Item`'s identifier.
    pub fn id(&self) -> ItemId {
        self.id
    }

    /// Get this `Item`'s parent's identifier.
    ///
    /// For the root module, the parent's ID is its own ID.
    pub fn parent_id(&self) -> ItemId {
        self.parent_id
    }

    /// Get this `Item`'s comment, if it has any.
    pub fn comment(&self) -> Option<&str> {
        self.comment.as_ref().map(|c| &**c)
    }

    /// What kind of item is this?
    pub fn kind(&self) -> &ItemKind {
        &self.kind
    }

    /// Get a mutable reference to this item's kind.
    pub fn kind_mut(&mut self) -> &mut ItemKind {
        &mut self.kind
    }

    /// Get an identifier that differentiates this item from its siblings.
    ///
    /// This should stay relatively stable in the face of code motion outside or
    /// below this item's lexical scope, meaning that this can be useful for
    /// generating relatively stable identifiers within a scope.
    pub fn local_id(&self, ctx: &BindgenContext) -> usize {
        if self.local_id.get().is_none() {
            let parent = ctx.resolve_item(self.parent_id);
            let local_id = parent.next_child_local_id.get();
            parent.next_child_local_id.set(local_id + 1);
            self.local_id.set(Some(local_id));
        }
        self.local_id.get().unwrap()
    }

    /// Returns whether this item is a top-level item, from the point of view of
    /// bindgen.
    ///
    /// This point of view changes depending on whether namespaces are enabled
    /// or not. That way, in the following example:
    ///
    /// ```c++
    /// namespace foo {
    ///     static int var;
    /// }
    /// ```
    ///
    /// `var` would be a toplevel item if namespaces are disabled, but won't if
    /// they aren't.
    ///
    /// This function is used to determine when the codegen phase should call
    /// `codegen` on an item, since any item that is not top-level will be
    /// generated by its parent.
    pub fn is_toplevel(&self, ctx: &BindgenContext) -> bool {
        // FIXME: Workaround for some types falling behind when parsing weird
        // stl classes, for example.
        if ctx.options().enable_cxx_namespaces && self.kind().is_module() &&
           self.id() != ctx.root_module() {
            return false;
        }

        let mut parent = self.parent_id;
        loop {
            let parent_item = match ctx.resolve_item_fallible(parent) {
                Some(item) => item,
                None => return false,
            };

            if parent_item.id() == ctx.root_module() {
                return true;
            } else if ctx.options().enable_cxx_namespaces ||
                      !parent_item.kind().is_module() {
                return false;
            }

            parent = parent_item.parent_id();
        }
    }

    /// Get a reference to this item's underlying `Type`. Panic if this is some
    /// other kind of item.
    pub fn expect_type(&self) -> &Type {
        self.kind().expect_type()
    }

    /// Get a reference to this item's underlying `Type`, or `None` if this is
    /// some other kind of item.
    pub fn as_type(&self) -> Option<&Type> {
        self.kind().as_type()
    }

    /// Get a reference to this item's underlying `Function`. Panic if this is
    /// some other kind of item.
    pub fn expect_function(&self) -> &Function {
        self.kind().expect_function()
    }

    /// Checks whether an item contains in its "type signature" some named type.
    ///
    /// This function is used to avoid unused template parameter errors in Rust
    /// when generating typedef declarations, and also to know whether we need
    /// to generate a `PhantomData` member for a template parameter.
    ///
    /// For example, in code like the following:
    ///
    /// ```c++
    /// template<typename T, typename U>
    /// struct Foo {
    ///     T bar;
    ///
    ///     struct Baz {
    ///         U bas;
    ///     };
    /// };
    /// ```
    ///
    /// Both `Foo` and `Baz` contain both `T` and `U` template parameters in
    /// their signature:
    ///
    ///  * `Foo<T, U>`
    ///  * `Bar<T, U>`
    ///
    /// But the Rust structure for `Foo` would look like:
    ///
    /// ```rust
    /// struct Foo<T, U> {
    ///     bar: T,
    ///     _phantom0: ::std::marker::PhantomData<U>,
    /// }
    /// ```
    ///
    /// because none of its member fields contained the `U` type in the
    /// signature. Similarly, `Bar` would contain a `PhantomData<T>` type, for
    /// the same reason.
    ///
    /// Note that this is somewhat similar to `applicable_template_args`, but
    /// this also takes into account other kind of types, like arrays,
    /// (`[T; 40]`), pointers: `*mut T`, etc...
    ///
    /// Normally we could do this check just in the `Type` kind, but we also
    /// need to check the `applicable_template_args` more generally, since we
    /// could need a type transitively from our parent, see the test added in
    /// commit 2a3f93074dd2898669dbbce6e97e5cc4405d7cb1.
    ///
    /// It's kind of unfortunate (in the sense that it's a sort of complex
    /// process), but I think it should get all the cases.
    fn signature_contains_named_type(&self,
                                     ctx: &BindgenContext,
                                     ty: &Type)
                                     -> bool {
        debug_assert!(ty.is_named());
        self.expect_type().signature_contains_named_type(ctx, ty) ||
        self.applicable_template_args(ctx).iter().any(|template| {
            ctx.resolve_type(*template).signature_contains_named_type(ctx, ty)
        })
    }

    /// Returns the template arguments that apply to a struct. This is a concept
    /// needed because of type declarations inside templates, for example:
    ///
    /// ```c++
    /// template<typename T>
    /// class Foo {
    ///     typedef T element_type;
    ///     typedef int Bar;
    ///
    ///     template<typename U>
    ///     class Baz {
    ///     };
    /// };
    /// ```
    ///
    /// In this case, the applicable template arguments for the different types
    /// would be:
    ///
    ///  * `Foo`: [`T`]
    ///  * `Foo::element_type`: [`T`]
    ///  * `Foo::Bar`: [`T`]
    ///  * `Foo::Baz`: [`T`, `U`]
    ///
    /// You might notice that we can't generate something like:
    ///
    /// ```rust,ignore
    /// type Foo_Bar<T> = ::std::os::raw::c_int;
    /// ```
    ///
    /// since that would be invalid Rust. Still, conceptually, `Bar` *could* use
    /// the template parameter type `T`, and that's exactly what this method
    /// represents. The unused template parameters get stripped in the
    /// `signature_contains_named_type` check.
    pub fn applicable_template_args(&self,
                                    ctx: &BindgenContext)
                                    -> Vec<ItemId> {
        let ty = match *self.kind() {
            ItemKind::Type(ref ty) => ty,
            _ => return vec![],
        };

        fn parent_contains(ctx: &BindgenContext,
                           parent_template_args: &[ItemId],
                           item: ItemId)
                           -> bool {
            let item_ty = ctx.resolve_type(item);
            parent_template_args.iter().any(|parent_item| {
                let parent_ty = ctx.resolve_type(*parent_item);
                match (parent_ty.kind(), item_ty.kind()) {
                    (&TypeKind::Named(ref n, _),
                     &TypeKind::Named(ref i, _)) => n == i,
                    _ => false,
                }
            })
        }

        match *ty.kind() {
            TypeKind::Named(..) => vec![self.id()],
            TypeKind::Array(inner, _) |
            TypeKind::Pointer(inner) |
            TypeKind::Reference(inner) |
            TypeKind::ResolvedTypeRef(inner) => {
                ctx.resolve_item(inner).applicable_template_args(ctx)
            }
            TypeKind::Alias(_, inner) => {
                let parent_args = ctx.resolve_item(self.parent_id())
                    .applicable_template_args(ctx);
                let inner = ctx.resolve_item(inner);

                // Avoid unused type parameters, sigh.
                parent_args.iter()
                    .cloned()
                    .filter(|arg| {
                        let arg = ctx.resolve_type(*arg);
                        arg.is_named() &&
                        inner.signature_contains_named_type(ctx, arg)
                    })
                    .collect()
            }
            // XXX Is this completely correct? Partial template specialization
            // is hard anyways, sigh...
            TypeKind::TemplateAlias(_, ref args) |
            TypeKind::TemplateRef(_, ref args) => args.clone(),
            // In a template specialization we've got all we want.
            TypeKind::Comp(ref ci) if ci.is_template_specialization() => {
                ci.template_args().iter().cloned().collect()
            }
            TypeKind::Comp(ref ci) => {
                let mut parent_template_args =
                    ctx.resolve_item(self.parent_id())
                        .applicable_template_args(ctx);

                for ty in ci.template_args() {
                    if !parent_contains(ctx, &parent_template_args, *ty) {
                        parent_template_args.push(*ty);
                    }
                }

                parent_template_args
            }
            _ => vec![],
        }
    }

    /// Is this item a module?
    pub fn is_module(&self) -> bool {
        match self.kind {
            ItemKind::Module(..) => true,
            _ => false,
        }
    }

    /// Get this item's annotations.
    pub fn annotations(&self) -> &Annotations {
        &self.annotations
    }

    /// Whether this item should be hidden.
    ///
    /// This may be due to either annotations or to other kind of configuration.
    pub fn is_hidden(&self, ctx: &BindgenContext) -> bool {
        debug_assert!(ctx.in_codegen_phase(),
                      "You're not supposed to call this yet");
        self.annotations.hide() ||
        ctx.hidden_by_name(&self.name(ctx).for_name_checking().get(), self.id)
    }

    /// Is this item opaque?
    pub fn is_opaque(&self, ctx: &BindgenContext) -> bool {
        debug_assert!(ctx.in_codegen_phase(),
                      "You're not supposed to call this yet");
        self.annotations.opaque() ||
        ctx.opaque_by_name(&self.name(ctx).for_name_checking().get())
    }

    /// Is this a reference to another type?
    pub fn is_type_ref(&self) -> bool {
        self.as_type().map_or(false, |ty| ty.is_type_ref())
    }

    /// Is this item a var type?
    pub fn is_var(&self) -> bool {
        match *self.kind() {
            ItemKind::Var(..) => true,
            _ => false,
        }
    }

    /// Take out item NameOptions
    pub fn name<'item, 'ctx>(&'item self,
                             ctx: &'item BindgenContext<'ctx>)
                             -> NameOptions<'item, 'ctx> {
        NameOptions::new(self, ctx)
    }

    /// Get the target item id for name generation.
    fn name_target(&self,
                   ctx: &BindgenContext,
                   for_name_checking: bool)
                   -> ItemId {
        let mut item = self;
        loop {
            match *item.kind() {
                ItemKind::Type(ref ty) => {
                    match *ty.kind() {
                        // If we're a template specialization, our name is our
                        // parent's name.
                        TypeKind::Comp(ref ci)
                            if ci.is_template_specialization() => {
                            let specialized =
                                ci.specialized_template().unwrap();
                            item = ctx.resolve_item(specialized);
                        }
                        // Same as above.
                        TypeKind::ResolvedTypeRef(inner) |
                        TypeKind::TemplateRef(inner, _) => {
                            item = ctx.resolve_item(inner);
                        }
                        // Template aliases use their inner alias type's name if
                        // we are checking names for
                        // whitelisting/replacement/etc.
                        TypeKind::TemplateAlias(inner, _)
                            if for_name_checking => {
                            item = ctx.resolve_item(inner);
                        }
                        _ => return item.id(),
                    }
                }
                _ => return item.id(),
            }
        }
    }

    /// Get this function item's name, or `None` if this item is not a function.
    fn func_name(&self) -> Option<&str> {
        match *self.kind() {
            ItemKind::Function(ref func) => Some(func.name()),
            _ => None,
        }
    }

    /// Get the overload index for this method. If this is not a method, return
    /// `None`.
    fn method_overload_index(&self, ctx: &BindgenContext) -> Option<usize> {
        self.func_name().and_then(|func_name| {
            let parent = ctx.resolve_item(self.parent_id());
            if let ItemKind::Type(ref ty) = *parent.kind() {
                if let TypeKind::Comp(ref ci) = *ty.kind() {
                    return ci.methods()
                        .iter()
                        .filter(|method| {
                            let item = ctx.resolve_item(method.signature());
                            let func = item.expect_function();
                            func.name() == func_name
                        })
                        .position(|method| method.signature() == self.id());
                }
            }

            None
        })
    }

    /// Get this item's base name (aka non-namespaced name).
    ///
    /// The `for_name_checking` boolean parameter informs us whether we are
    /// asking for the name in order to do a whitelisting/replacement/etc check
    /// or if we are instead using it for code generation.
    fn base_name(&self,
                 ctx: &BindgenContext,
                 for_name_checking: bool)
                 -> String {
        match *self.kind() {
            ItemKind::Var(ref var) => var.name().to_owned(),
            ItemKind::Module(ref module) => {
                module.name()
                    .map(ToOwned::to_owned)
                    .unwrap_or_else(|| {
                        format!("_bindgen_mod_{}", self.exposed_id(ctx))
                    })
            }
            ItemKind::Type(ref ty) => {
                let name = match *ty.kind() {
                    TypeKind::ResolvedTypeRef(..) => panic!("should have resolved this in name_target()"),
                    TypeKind::TemplateAlias(..) => {
                        if for_name_checking { None } else { Some("") }
                    }
                    _ => ty.name(),
                };
                name.map(ToOwned::to_owned)
                    .unwrap_or_else(|| {
                        format!("_bindgen_ty_{}", self.exposed_id(ctx))
                    })
            }
            ItemKind::Function(ref fun) => {
                let mut name = fun.name().to_owned();

                if let Some(idx) = self.method_overload_index(ctx) {
                    if idx > 0 {
                        write!(&mut name, "{}", idx).unwrap();
                    }
                }

                name
            }
        }
    }

    /// Get the canonical name without taking into account the replaces
    /// annotation.
    ///
    /// This is the base logic used to implement hiding and replacing via
    /// annotations, and also to implement proper name mangling.
    ///
    /// The idea is that each generated type in the same "level" (read: module
    /// or namespace) has a unique canonical name.
    ///
    /// This name should be derived from the immutable state contained in the
    /// type and the parent chain, since it should be consistent.
    pub fn real_canonical_name(&self,
                               ctx: &BindgenContext,
                               opt: &NameOptions)
                               -> String {
        let target =
            ctx.resolve_item(self.name_target(ctx, opt.for_name_checking));

        // Short-circuit if the target has an override, and just use that.
        if !opt.for_name_checking {
            if let Some(other) = target.annotations.use_instead_of() {
                return other.to_owned();
            }
        }

        let base_name = target.base_name(ctx, opt.for_name_checking);

        // Named template type arguments are never namespaced, and never
        // mangled.
        if target.as_type().map_or(false, |ty| ty.is_named()) {
            return base_name;
        }

        // Concatenate this item's ancestors' names together.
        let mut names: Vec<_> = target.parent_id()
            .ancestors(ctx)
            .filter(|id| *id != ctx.root_module())
            .take_while(|id| {
                // Stop iterating ancestors once we reach a namespace.
                !opt.within_namespaces || !ctx.resolve_item(*id).is_module()
            })
            .map(|id| {
                let item = ctx.resolve_item(id);
                let target = ctx.resolve_item(item.name_target(ctx, false));
                target.base_name(ctx, false)
            })
            .filter(|name| !name.is_empty())
            .collect();

        names.reverse();

        if !base_name.is_empty() {
            names.push(base_name);
        }

        let name = names.join("_");

        ctx.rust_mangle(&name).into_owned()
    }

    fn exposed_id(&self, ctx: &BindgenContext) -> String {
        // Only use local ids for enums, classes, structs and union types.  All
        // other items use their global id.
        let ty_kind = self.kind().as_type().map(|t| t.kind());
        if let Some(ty_kind) = ty_kind {
            match *ty_kind {
                TypeKind::Comp(..) |
                TypeKind::Enum(..) => return self.local_id(ctx).to_string(),
                _ => {}
            }
        }

        // Note that this `id_` prefix prevents (really unlikely) collisions
        // between the global id and the local id of an item with the same
        // parent.
        format!("id_{}", self.id().as_usize())
    }

    /// Get a mutable reference to this item's `Module`, or `None` if this is
    /// not a `Module` item.
    pub fn as_module_mut(&mut self) -> Option<&mut Module> {
        match self.kind {
            ItemKind::Module(ref mut module) => Some(module),
            _ => None,
        }
    }

    /// Can we derive an implementation of the `Copy` trait for this type?
    pub fn can_derive_copy(&self, ctx: &BindgenContext) -> bool {
        self.expect_type().can_derive_copy(ctx, self)
    }

    /// Can we derive an implementation of the `Copy` trait for an array of this
    /// type?
    ///
    /// See `Type::can_derive_copy_in_array` for details.
    pub fn can_derive_copy_in_array(&self, ctx: &BindgenContext) -> bool {
        self.expect_type().can_derive_copy_in_array(ctx, self)
    }
}

// An utility function to handle recursing inside nested types.
fn visit_child(cur: clang::Cursor,
               id: ItemId,
               ty: &clang::Type,
               parent_id: Option<ItemId>,
               ctx: &mut BindgenContext,
               result: &mut Result<ItemId, ParseError>)
               -> clangll::Enum_CXChildVisitResult {
    use clangll::*;
    if result.is_ok() {
        return CXChildVisit_Break;
    }

    *result = Item::from_ty_with_id(id, ty, Some(cur), parent_id, ctx);

    match *result {
        Ok(..) => CXChildVisit_Break,
        Err(ParseError::Recurse) => {
            cur.visit(|c| visit_child(c, id, ty, parent_id, ctx, result));
            CXChildVisit_Continue
        }
        Err(ParseError::Continue) => CXChildVisit_Continue,
    }
}

impl ClangItemParser for Item {
    fn builtin_type(kind: TypeKind,
                    is_const: bool,
                    ctx: &mut BindgenContext)
                    -> ItemId {
        // Feel free to add more here, I'm just lazy.
        match kind {
            TypeKind::Void |
            TypeKind::Int(..) |
            TypeKind::Pointer(..) |
            TypeKind::Float(..) => {}
            _ => panic!("Unsupported builtin type"),
        }

        let ty = Type::new(None, None, kind, is_const);
        let id = ctx.next_item_id();
        let module = ctx.root_module();
        ctx.add_item(Item::new(id, None, None, module, ItemKind::Type(ty)),
                     None,
                     None);
        id
    }


    fn parse(cursor: clang::Cursor,
             parent_id: Option<ItemId>,
             ctx: &mut BindgenContext)
             -> Result<ItemId, ParseError> {
        use ir::function::Function;
        use ir::module::Module;
        use ir::var::Var;
        use clangll::*;

        if !cursor.is_valid() {
            return Err(ParseError::Continue);
        }

        let comment = cursor.raw_comment();
        let annotations = Annotations::new(&cursor);

        let current_module = ctx.current_module();
        let relevant_parent_id = parent_id.unwrap_or(current_module);

        macro_rules! try_parse {
            ($what:ident) => {
                match $what::parse(cursor, ctx) {
                    Ok(ParseResult::New(item, declaration)) => {
                        let id = ctx.next_item_id();

                        ctx.add_item(Item::new(id, comment, annotations,
                                               relevant_parent_id,
                                               ItemKind::$what(item)),
                                         declaration,
                                         Some(cursor));
                        return Ok(id);
                    }
                    Ok(ParseResult::AlreadyResolved(id)) => {
                        return Ok(id);
                    }
                    Err(ParseError::Recurse) => return Err(ParseError::Recurse),
                    Err(ParseError::Continue) => {},
                }
            }
        }

        try_parse!(Module);

        // NOTE: Is extremely important to parse functions and vars **before**
        // types.  Otherwise we can parse a function declaration as a type
        // (which is legal), and lose functions to generate.
        //
        // In general, I'm not totally confident this split between
        // ItemKind::Function and TypeKind::FunctionSig is totally worth it, but
        // I guess we can try.
        try_parse!(Function);
        try_parse!(Var);

        // Types are sort of special, so to avoid parsing template classes
        // twice, handle them separately.
        {
            let applicable_cursor = cursor.definition().unwrap_or(cursor);
            match Self::from_ty(&applicable_cursor.cur_type(),
                                Some(applicable_cursor),
                                parent_id,
                                ctx) {
                Ok(ty) => return Ok(ty),
                Err(ParseError::Recurse) => return Err(ParseError::Recurse),
                Err(ParseError::Continue) => {}
            }
        }

        // Guess how does clang treat extern "C" blocks?
        if cursor.kind() == CXCursor_UnexposedDecl {
            Err(ParseError::Recurse)
        } else {
            // We whitelist cursors here known to be unhandled, to prevent being
            // too noisy about this.
            match cursor.kind() {
                CXCursor_MacroDefinition |
                CXCursor_MacroExpansion |
                CXCursor_UsingDeclaration |
                CXCursor_StaticAssert |
                CXCursor_InclusionDirective => {
                    debug!("Unhandled cursor kind {:?}: {:?}",
                           cursor.kind(),
                           cursor);
                }
                _ => {
                    error!("Unhandled cursor kind {:?}: {:?}",
                           cursor.kind(),
                           cursor);
                }
            }

            Err(ParseError::Continue)
        }
    }

    fn from_ty_or_ref(ty: clang::Type,
                      location: Option<clang::Cursor>,
                      parent_id: Option<ItemId>,
                      ctx: &mut BindgenContext)
                      -> ItemId {
        let id = ctx.next_item_id();
        Self::from_ty_or_ref_with_id(id, ty, location, parent_id, ctx)
    }

    /// Parse a C++ type. If we find a reference to a type that has not been
    /// defined yet, use `UnresolvedTypeRef` as a placeholder.
    ///
    /// This logic is needed to avoid parsing items with the incorrect parent
    /// and it's sort of complex to explain, so I'll just point to
    /// `tests/headers/typeref.hpp` to see the kind of constructs that forced
    /// this.
    ///
    /// Typerefs are resolved once parsing is completely done, see
    /// `BindgenContext::resolve_typerefs`.
    fn from_ty_or_ref_with_id(potential_id: ItemId,
                              ty: clang::Type,
                              location: Option<clang::Cursor>,
                              parent_id: Option<ItemId>,
                              ctx: &mut BindgenContext)
                              -> ItemId {
        debug!("from_ty_or_ref_with_id: {:?} {:?}, {:?}, {:?}",
               potential_id,
               ty,
               location,
               parent_id);

        if ctx.collected_typerefs() {
            debug!("refs already collected, resolving directly");
            return Self::from_ty_with_id(potential_id,
                                         &ty,
                                         location,
                                         parent_id,
                                         ctx)
                .expect("Unable to resolve type");
        }

        if let Some(ty) =
            ctx.builtin_or_resolved_ty(potential_id, parent_id, &ty, location) {
            debug!("{:?} already resolved: {:?}", ty, location);
            return ty;
        }

        debug!("New unresolved type reference: {:?}, {:?}", ty, location);

        let is_const = ty.is_const();
        let kind = TypeKind::UnresolvedTypeRef(ty, location, parent_id);
        let current_module = ctx.current_module();
        ctx.add_item(Item::new(potential_id,
                               None,
                               None,
                               parent_id.unwrap_or(current_module),
                               ItemKind::Type(Type::new(None,
                                                        None,
                                                        kind,
                                                        is_const))),
                     Some(clang::Cursor::null()),
                     None);
        potential_id
    }


    fn from_ty(ty: &clang::Type,
               location: Option<clang::Cursor>,
               parent_id: Option<ItemId>,
               ctx: &mut BindgenContext)
               -> Result<ItemId, ParseError> {
        let id = ctx.next_item_id();
        Self::from_ty_with_id(id, ty, location, parent_id, ctx)
    }

    /// This is one of the trickiest methods you'll find (probably along with
    /// some of the ones that handle templates in `BindgenContext`).
    ///
    /// This method parses a type, given the potential id of that type (if
    /// parsing it was correct), an optional location we're scanning, which is
    /// critical some times to obtain information, an optional parent item id,
    /// that will, if it's `None`, become the current module id, and the
    /// context.
    fn from_ty_with_id(id: ItemId,
                       ty: &clang::Type,
                       location: Option<clang::Cursor>,
                       parent_id: Option<ItemId>,
                       ctx: &mut BindgenContext)
                       -> Result<ItemId, ParseError> {
        use clangll::*;

        let decl = {
            let decl = ty.declaration();
            decl.definition().unwrap_or(decl)
        };

        let comment = decl.raw_comment()
            .or_else(|| location.as_ref().and_then(|l| l.raw_comment()));
        let annotations = Annotations::new(&decl)
            .or_else(|| location.as_ref().and_then(|l| Annotations::new(l)));

        if let Some(ref annotations) = annotations {
            if let Some(ref replaced) = annotations.use_instead_of() {
                ctx.replace(replaced, id);
            }
        }

        if let Some(ty) =
            ctx.builtin_or_resolved_ty(id, parent_id, ty, location) {
            return Ok(ty);
        }

        // First, check we're not recursing.
        let mut valid_decl = decl.kind() != CXCursor_NoDeclFound;
        let declaration_to_look_for = if valid_decl {
            decl.canonical()
        } else if location.is_some() &&
                                                location.unwrap().kind() ==
                                                CXCursor_ClassTemplate {
            valid_decl = true;
            location.unwrap()
        } else {
            decl
        };

        if valid_decl {
            if let Some(&(_, item_id)) =
                ctx.currently_parsed_types
                    .iter()
                    .find(|&&(d, _)| d == declaration_to_look_for) {
                debug!("Avoiding recursion parsing type: {:?}", ty);
                return Ok(item_id);
            }
        }

        let current_module = ctx.current_module();
        if valid_decl {
            ctx.currently_parsed_types.push((declaration_to_look_for, id));
        }

        let result = Type::from_clang_ty(id, ty, location, parent_id, ctx);
        let relevant_parent_id = parent_id.unwrap_or(current_module);
        let ret = match result {
            Ok(ParseResult::AlreadyResolved(ty)) => Ok(ty),
            Ok(ParseResult::New(item, declaration)) => {
                ctx.add_item(Item::new(id,
                                       comment,
                                       annotations,
                                       relevant_parent_id,
                                       ItemKind::Type(item)),
                             declaration,
                             location);
                Ok(id)
            }
            Err(ParseError::Continue) => Err(ParseError::Continue),
            Err(ParseError::Recurse) => {
                debug!("Item::from_ty recursing in the ast");
                let mut result = Err(ParseError::Recurse);
                if let Some(ref location) = location {
                    // Need to pop here, otherwise we'll get stuck.
                    //
                    // TODO: Find a nicer interface, really. Also, the
                    // declaration_to_look_for suspiciously shares a lot of
                    // logic with ir::context, so we should refactor that.
                    if valid_decl {
                        let (popped_decl, _) =
                            ctx.currently_parsed_types.pop().unwrap();
                        assert_eq!(popped_decl, declaration_to_look_for);
                    }

                    location.visit(|cur| {
                        visit_child(cur, id, ty, parent_id, ctx, &mut result)
                    });

                    if valid_decl {
                        ctx.currently_parsed_types
                            .push((declaration_to_look_for, id));
                    }
                }
                // If we have recursed into the AST all we know, and we still
                // haven't found what we've got, let's just make a named type.
                //
                // This is what happens with some template members, for example.
                //
                // FIXME: Maybe we should restrict this to things with parent?
                // It's harmless, but if we restrict that, then
                // tests/headers/nsStyleAutoArray.hpp crashes.
                if let Err(ParseError::Recurse) = result {
                    warn!("Unknown type, assuming named template type: \
                          id = {:?}; spelling = {}",
                          id,
                          ty.spelling());
                    Ok(Self::named_type_with_id(id,
                                                ty.spelling(),
                                                None,
                                                relevant_parent_id,
                                                ctx))
                } else {
                    result
                }
            }
        };

        if valid_decl {
            let (popped_decl, _) = ctx.currently_parsed_types.pop().unwrap();
            assert_eq!(popped_decl, declaration_to_look_for);
        }

        ret
    }

    /// A named type is a template parameter, e.g., the "T" in Foo<T>. They're
    /// always local so it's the only exception when there's no declaration for
    /// a type.
    ///
    /// It must have an id, and must not be the current module id. Ideally we
    /// could assert the parent id is a Comp(..) type, but that info isn't
    /// available yet.
    fn named_type_with_id<S>(id: ItemId,
                             name: S,
                             default: Option<ItemId>,
                             parent_id: ItemId,
                             ctx: &mut BindgenContext)
                             -> ItemId
        where S: Into<String>,
    {
        // see tests/headers/const_tparam.hpp
        // and tests/headers/variadic_tname.hpp
        let name = name.into().replace("const ", "").replace(".", "");

        ctx.add_item(Item::new(id,
                               None,
                               None,
                               parent_id,
                               ItemKind::Type(Type::named(name, default))),
                     None,
                     None);

        id
    }

    fn named_type<S>(name: S,
                     default: Option<ItemId>,
                     parent_id: ItemId,
                     ctx: &mut BindgenContext)
                     -> ItemId
        where S: Into<String>,
    {
        let id = ctx.next_item_id();
        Self::named_type_with_id(id, name, default, parent_id, ctx)
    }
}

impl ItemCanonicalName for Item {
    fn canonical_name(&self, ctx: &BindgenContext) -> String {
        debug_assert!(ctx.in_codegen_phase(),
                      "You're not supposed to call this yet");
        if self.canonical_name_cache.borrow().is_none() {
            let in_namespace = ctx.options().enable_cxx_namespaces ||
                               ctx.options().disable_name_namespacing;

            *self.canonical_name_cache.borrow_mut() = if in_namespace {
                Some(self.name(ctx).within_namespaces().get())
            } else {
                Some(self.name(ctx).get())
            };
        }
        return self.canonical_name_cache.borrow().as_ref().unwrap().clone();
    }
}

impl ItemCanonicalPath for Item {
    fn canonical_path(&self, ctx: &BindgenContext) -> Vec<String> {
        if !ctx.options().enable_cxx_namespaces {
            return vec![self.canonical_name(ctx)];
        }

        let target = ctx.resolve_item(self.name_target(ctx, false));
        let mut path: Vec<_> = target.ancestors(ctx)
            .chain(iter::once(ctx.root_module()))
            .map(|id| ctx.resolve_item(id))
            .filter(|item| item.is_module() || item.id() == target.id())
            .map(|item| item.name(ctx).within_namespaces().get())
            .collect();
        path.reverse();
        path
    }
}

/// Builder struct for naming variations, which hold inside different
/// flags for naming options.
#[derive(Debug)]
pub struct NameOptions<'item, 'ctx>
    where 'ctx: 'item,
{
    item: &'item Item,
    ctx: &'item BindgenContext<'ctx>,
    for_name_checking: bool,
    within_namespaces: bool,
}

impl<'item, 'ctx> NameOptions<'item, 'ctx> {
    /// Construct a new `NameOptions`
    pub fn new(item: &'item Item, ctx: &'item BindgenContext<'ctx>) -> Self {
        NameOptions {
            item: item,
            ctx: ctx,
            for_name_checking: false,
            within_namespaces: false,
        }
    }

    /// Construct a name that is suitable for replacements/whitelisting/opaque-
    /// ness look ups.
    pub fn for_name_checking(&mut self) -> &mut Self {
        self.for_name_checking = true;
        self
    }

    /// Construct the name without the item's containing C++ namespaces mangled
    /// into it. In other words, the item's name within the item's namespace.
    pub fn within_namespaces(&mut self) -> &mut Self {
        self.within_namespaces = true;
        self
    }

    /// Construct a name `String`
    pub fn get(&self) -> String {
        self.item.real_canonical_name(self.ctx, self)
    }
}