-
Notifications
You must be signed in to change notification settings - Fork 741
/
Copy pathcontext.rs
2759 lines (2453 loc) · 97.1 KB
/
context.rs
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
//! Common context that is passed around during parsing and codegen.
use super::super::time::Timer;
use super::analysis::{
analyze, as_cannot_derive_set, CannotDerive, DeriveTrait,
HasDestructorAnalysis, HasFloat, HasTypeParameterInArray,
HasVtableAnalysis, HasVtableResult, SizednessAnalysis, SizednessResult,
UsedTemplateParameters,
};
use super::derive::{
CanDerive, CanDeriveCopy, CanDeriveDebug, CanDeriveDefault, CanDeriveEq,
CanDeriveHash, CanDeriveOrd, CanDerivePartialEq, CanDerivePartialOrd,
};
use super::function::Function;
use super::int::IntKind;
use super::item::{IsOpaque, Item, ItemAncestors, ItemSet};
use super::item_kind::ItemKind;
use super::module::{Module, ModuleKind};
use super::template::{TemplateInstantiation, TemplateParameters};
use super::traversal::{self, Edge, ItemTraversal};
use super::ty::{FloatKind, Type, TypeKind};
use callbacks::ParseCallbacks;
use cexpr;
use clang::{self, Cursor};
use clang_sys;
use parse::ClangItemParser;
use proc_macro2::{Ident, Span};
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::HashMap as StdHashMap;
use std::iter::IntoIterator;
use std::mem;
use BindgenOptions;
use {Entry, HashMap, HashSet};
/// An identifier for some kind of IR item.
#[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)]
pub struct ItemId(usize);
macro_rules! item_id_newtype {
(
$( #[$attr:meta] )*
pub struct $name:ident(ItemId)
where
$( #[$checked_attr:meta] )*
checked = $checked:ident with $check_method:ident,
$( #[$expected_attr:meta] )*
expected = $expected:ident,
$( #[$unchecked_attr:meta] )*
unchecked = $unchecked:ident;
) => {
$( #[$attr] )*
#[derive(Debug, Copy, Clone, Eq, PartialOrd, Ord, Hash)]
pub struct $name(ItemId);
impl $name {
/// Create an `ItemResolver` from this id.
pub fn into_resolver(self) -> ItemResolver {
let id: ItemId = self.into();
id.into()
}
}
impl<T> ::std::cmp::PartialEq<T> for $name
where
T: Copy + Into<ItemId>
{
fn eq(&self, rhs: &T) -> bool {
let rhs: ItemId = (*rhs).into();
self.0 == rhs
}
}
impl From<$name> for ItemId {
fn from(id: $name) -> ItemId {
id.0
}
}
impl<'a> From<&'a $name> for ItemId {
fn from(id: &'a $name) -> ItemId {
id.0
}
}
impl ItemId {
$( #[$checked_attr] )*
pub fn $checked(&self, ctx: &BindgenContext) -> Option<$name> {
if ctx.resolve_item(*self).kind().$check_method() {
Some($name(*self))
} else {
None
}
}
$( #[$expected_attr] )*
pub fn $expected(&self, ctx: &BindgenContext) -> $name {
self.$checked(ctx)
.expect(concat!(
stringify!($expected),
" called with ItemId that points to the wrong ItemKind"
))
}
$( #[$unchecked_attr] )*
pub fn $unchecked(&self) -> $name {
$name(*self)
}
}
}
}
item_id_newtype! {
/// An identifier for an `Item` whose `ItemKind` is known to be
/// `ItemKind::Type`.
pub struct TypeId(ItemId)
where
/// Convert this `ItemId` into a `TypeId` if its associated item is a type,
/// otherwise return `None`.
checked = as_type_id with is_type,
/// Convert this `ItemId` into a `TypeId`.
///
/// If this `ItemId` does not point to a type, then panic.
expected = expect_type_id,
/// Convert this `ItemId` into a `TypeId` without actually checking whether
/// this id actually points to a `Type`.
unchecked = as_type_id_unchecked;
}
item_id_newtype! {
/// An identifier for an `Item` whose `ItemKind` is known to be
/// `ItemKind::Module`.
pub struct ModuleId(ItemId)
where
/// Convert this `ItemId` into a `ModuleId` if its associated item is a
/// module, otherwise return `None`.
checked = as_module_id with is_module,
/// Convert this `ItemId` into a `ModuleId`.
///
/// If this `ItemId` does not point to a module, then panic.
expected = expect_module_id,
/// Convert this `ItemId` into a `ModuleId` without actually checking
/// whether this id actually points to a `Module`.
unchecked = as_module_id_unchecked;
}
item_id_newtype! {
/// An identifier for an `Item` whose `ItemKind` is known to be
/// `ItemKind::Var`.
pub struct VarId(ItemId)
where
/// Convert this `ItemId` into a `VarId` if its associated item is a var,
/// otherwise return `None`.
checked = as_var_id with is_var,
/// Convert this `ItemId` into a `VarId`.
///
/// If this `ItemId` does not point to a var, then panic.
expected = expect_var_id,
/// Convert this `ItemId` into a `VarId` without actually checking whether
/// this id actually points to a `Var`.
unchecked = as_var_id_unchecked;
}
item_id_newtype! {
/// An identifier for an `Item` whose `ItemKind` is known to be
/// `ItemKind::Function`.
pub struct FunctionId(ItemId)
where
/// Convert this `ItemId` into a `FunctionId` if its associated item is a function,
/// otherwise return `None`.
checked = as_function_id with is_function,
/// Convert this `ItemId` into a `FunctionId`.
///
/// If this `ItemId` does not point to a function, then panic.
expected = expect_function_id,
/// Convert this `ItemId` into a `FunctionId` without actually checking whether
/// this id actually points to a `Function`.
unchecked = as_function_id_unchecked;
}
impl From<ItemId> for usize {
fn from(id: ItemId) -> usize {
id.0
}
}
impl ItemId {
/// Get a numeric representation of this id.
pub fn as_usize(&self) -> usize {
(*self).into()
}
}
impl<T> ::std::cmp::PartialEq<T> for ItemId
where
T: Copy + Into<ItemId>,
{
fn eq(&self, rhs: &T) -> bool {
let rhs: ItemId = (*rhs).into();
self.0 == rhs.0
}
}
impl<T> CanDeriveDebug for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_debug(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_debug && ctx.lookup_can_derive_debug(*self)
}
}
impl<T> CanDeriveDefault for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_default(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_default && ctx.lookup_can_derive_default(*self)
}
}
impl<T> CanDeriveCopy for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_copy(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_copy && ctx.lookup_can_derive_copy(*self)
}
}
impl<T> CanDeriveHash for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_hash(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_hash && ctx.lookup_can_derive_hash(*self)
}
}
impl<T> CanDerivePartialOrd for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_partialord(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_partialord &&
ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
CanDerive::Yes
}
}
impl<T> CanDerivePartialEq for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_partialeq &&
ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
CanDerive::Yes
}
}
impl<T> CanDeriveEq for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_eq(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_eq &&
ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
CanDerive::Yes &&
!ctx.lookup_has_float(*self)
}
}
impl<T> CanDeriveOrd for T
where
T: Copy + Into<ItemId>,
{
fn can_derive_ord(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_ord &&
ctx.lookup_can_derive_partialeq_or_partialord(*self) ==
CanDerive::Yes &&
!ctx.lookup_has_float(*self)
}
}
/// A key used to index a resolved type, so we only process it once.
///
/// This is almost always a USR string (an unique identifier generated by
/// clang), but it can also be the canonical declaration if the type is unnamed,
/// in which case clang may generate the same USR for multiple nested unnamed
/// types.
#[derive(Eq, PartialEq, Hash, Debug)]
enum TypeKey {
USR(String),
Declaration(Cursor),
}
/// A context used during parsing and generation of structs.
#[derive(Debug)]
pub struct BindgenContext {
/// The map of all the items parsed so far, keyed off ItemId.
items: Vec<Option<Item>>,
/// Clang USR to type map. This is needed to be able to associate types with
/// item ids during parsing.
types: HashMap<TypeKey, TypeId>,
/// Maps from a cursor to the item id of the named template type parameter
/// for that cursor.
type_params: HashMap<clang::Cursor, TypeId>,
/// A cursor to module map. Similar reason than above.
modules: HashMap<Cursor, ModuleId>,
/// The root module, this is guaranteed to be an item of kind Module.
root_module: ModuleId,
/// Current module being traversed.
current_module: ModuleId,
/// A HashMap keyed on a type definition, and whose value is the parent id
/// of the declaration.
///
/// This is used to handle the cases where the semantic and the lexical
/// parents of the cursor differ, like when a nested class is defined
/// outside of the parent class.
semantic_parents: HashMap<clang::Cursor, ItemId>,
/// A stack with the current type declarations and types we're parsing. This
/// is needed to avoid infinite recursion when parsing a type like:
///
/// struct c { struct c* next; };
///
/// This means effectively, that a type has a potential ID before knowing if
/// it's a correct type. But that's not important in practice.
///
/// We could also use the `types` HashMap, but my intention with it is that
/// only valid types and declarations end up there, and this could
/// potentially break that assumption.
currently_parsed_types: Vec<PartialType>,
/// A map with all the already parsed macro names. This is done to avoid
/// hard errors while parsing duplicated macros, as well to allow macro
/// expression parsing.
///
/// This needs to be an std::HashMap because the cexpr API requires it.
parsed_macros: StdHashMap<Vec<u8>, cexpr::expr::EvalResult>,
/// The active replacements collected from replaces="xxx" annotations.
replacements: HashMap<Vec<String>, ItemId>,
collected_typerefs: bool,
in_codegen: bool,
/// The clang index for parsing.
index: clang::Index,
/// The translation unit for parsing.
translation_unit: clang::TranslationUnit,
/// Target information that can be useful for some stuff.
target_info: Option<clang::TargetInfo>,
/// The options given by the user via cli or other medium.
options: BindgenOptions,
/// Whether a bindgen complex was generated
generated_bindgen_complex: Cell<bool>,
/// The set of `ItemId`s that are whitelisted. This the very first thing
/// computed after parsing our IR, and before running any of our analyses.
whitelisted: Option<ItemSet>,
/// The set of `ItemId`s that are whitelisted for code generation _and_ that
/// we should generate accounting for the codegen options.
///
/// It's computed right after computing the whitelisted items.
codegen_items: Option<ItemSet>,
/// Map from an item's id to the set of template parameter items that it
/// uses. See `ir::named` for more details. Always `Some` during the codegen
/// phase.
used_template_parameters: Option<HashMap<ItemId, ItemSet>>,
/// The set of `TypeKind::Comp` items found during parsing that need their
/// bitfield allocation units computed. Drained in `compute_bitfield_units`.
need_bitfield_allocation: Vec<ItemId>,
/// The set of (`ItemId`s of) types that can't derive debug.
///
/// This is populated when we enter codegen by `compute_cannot_derive_debug`
/// and is always `None` before that and `Some` after.
cannot_derive_debug: Option<HashSet<ItemId>>,
/// The set of (`ItemId`s of) types that can't derive default.
///
/// This is populated when we enter codegen by `compute_cannot_derive_default`
/// and is always `None` before that and `Some` after.
cannot_derive_default: Option<HashSet<ItemId>>,
/// The set of (`ItemId`s of) types that can't derive copy.
///
/// This is populated when we enter codegen by `compute_cannot_derive_copy`
/// and is always `None` before that and `Some` after.
cannot_derive_copy: Option<HashSet<ItemId>>,
/// The set of (`ItemId`s of) types that can't derive copy in array.
///
/// This is populated when we enter codegen by `compute_cannot_derive_copy`
/// and is always `None` before that and `Some` after.
cannot_derive_copy_in_array: Option<HashSet<ItemId>>,
/// The set of (`ItemId`s of) types that can't derive hash.
///
/// This is populated when we enter codegen by `compute_can_derive_hash`
/// and is always `None` before that and `Some` after.
cannot_derive_hash: Option<HashSet<ItemId>>,
/// The map why specified `ItemId`s of) types that can't derive hash.
///
/// This is populated when we enter codegen by
/// `compute_cannot_derive_partialord_partialeq_or_eq` and is always `None`
/// before that and `Some` after.
cannot_derive_partialeq_or_partialord: Option<HashMap<ItemId, CanDerive>>,
/// The sizedness of types.
///
/// This is populated by `compute_sizedness` and is always `None` before
/// that function is invoked and `Some` afterwards.
sizedness: Option<HashMap<TypeId, SizednessResult>>,
/// The set of (`ItemId's of`) types that has vtable.
///
/// Populated when we enter codegen by `compute_has_vtable`; always `None`
/// before that and `Some` after.
have_vtable: Option<HashMap<ItemId, HasVtableResult>>,
/// The set of (`ItemId's of`) types that has destructor.
///
/// Populated when we enter codegen by `compute_has_destructor`; always `None`
/// before that and `Some` after.
have_destructor: Option<HashSet<ItemId>>,
/// The set of (`ItemId's of`) types that has array.
///
/// Populated when we enter codegen by `compute_has_type_param_in_array`; always `None`
/// before that and `Some` after.
has_type_param_in_array: Option<HashSet<ItemId>>,
/// The set of (`ItemId's of`) types that has float.
///
/// Populated when we enter codegen by `compute_has_float`; always `None`
/// before that and `Some` after.
has_float: Option<HashSet<ItemId>>,
}
/// A traversal of whitelisted items.
struct WhitelistedItemsTraversal<'ctx> {
ctx: &'ctx BindgenContext,
traversal: ItemTraversal<
'ctx,
ItemSet,
Vec<ItemId>,
for<'a> fn(&'a BindgenContext, Edge) -> bool,
>,
}
impl<'ctx> Iterator for WhitelistedItemsTraversal<'ctx> {
type Item = ItemId;
fn next(&mut self) -> Option<ItemId> {
loop {
let id = self.traversal.next()?;
if self.ctx.resolve_item(id).is_blacklisted(self.ctx) {
continue;
}
return Some(id);
}
}
}
impl<'ctx> WhitelistedItemsTraversal<'ctx> {
/// Construct a new whitelisted items traversal.
pub fn new<R>(
ctx: &'ctx BindgenContext,
roots: R,
predicate: for<'a> fn(&'a BindgenContext, Edge) -> bool,
) -> Self
where
R: IntoIterator<Item = ItemId>,
{
WhitelistedItemsTraversal {
ctx,
traversal: ItemTraversal::new(ctx, roots, predicate),
}
}
}
const HOST_TARGET: &'static str =
include_str!(concat!(env!("OUT_DIR"), "/host-target.txt"));
/// Returns the effective target, and whether it was explicitly specified on the
/// clang flags.
fn find_effective_target(clang_args: &[String]) -> (String, bool) {
use std::env;
let mut args = clang_args.iter();
while let Some(opt) = args.next() {
if opt.starts_with("--target=") {
let mut split = opt.split('=');
split.next();
return (split.next().unwrap().to_owned(), true);
}
if opt == "-target" {
if let Some(target) = args.next() {
return (target.clone(), true);
}
}
}
// If we're running from a build script, try to find the cargo target.
if let Ok(t) = env::var("TARGET") {
return (t, false);
}
(HOST_TARGET.to_owned(), false)
}
impl BindgenContext {
/// Construct the context for the given `options`.
pub(crate) fn new(options: BindgenOptions) -> Self {
// TODO(emilio): Use the CXTargetInfo here when available.
//
// see: https://reviews.llvm.org/D32389
let (effective_target, explicit_target) =
find_effective_target(&options.clang_args);
let index = clang::Index::new(false, true);
let parse_options =
clang_sys::CXTranslationUnit_DetailedPreprocessingRecord;
let translation_unit = {
let _t =
Timer::new("translation_unit").with_output(options.time_phases);
let clang_args = if explicit_target {
Cow::Borrowed(&options.clang_args)
} else {
let mut args = Vec::with_capacity(options.clang_args.len() + 1);
args.push(format!("--target={}", effective_target));
args.extend_from_slice(&options.clang_args);
Cow::Owned(args)
};
clang::TranslationUnit::parse(
&index,
"",
&clang_args,
&options.input_unsaved_files,
parse_options,
).expect("libclang error; possible causes include:
- Invalid flag syntax
- Unrecognized flags
- Invalid flag arguments
- File I/O errors
If you encounter an error missing from this list, please file an issue or a PR!")
};
let target_info = clang::TargetInfo::new(&translation_unit);
#[cfg(debug_assertions)]
{
if let Some(ref ti) = target_info {
if effective_target == HOST_TARGET {
assert_eq!(
ti.pointer_width / 8,
mem::size_of::<*mut ()>(),
"{:?} {:?}",
effective_target,
HOST_TARGET
);
}
}
}
let root_module = Self::build_root_module(ItemId(0));
let root_module_id = root_module.id().as_module_id_unchecked();
BindgenContext {
items: vec![Some(root_module)],
types: Default::default(),
type_params: Default::default(),
modules: Default::default(),
root_module: root_module_id,
current_module: root_module_id,
semantic_parents: Default::default(),
currently_parsed_types: vec![],
parsed_macros: Default::default(),
replacements: Default::default(),
collected_typerefs: false,
in_codegen: false,
index,
translation_unit,
target_info,
options,
generated_bindgen_complex: Cell::new(false),
whitelisted: None,
codegen_items: None,
used_template_parameters: None,
need_bitfield_allocation: Default::default(),
cannot_derive_debug: None,
cannot_derive_default: None,
cannot_derive_copy: None,
cannot_derive_copy_in_array: None,
cannot_derive_hash: None,
cannot_derive_partialeq_or_partialord: None,
sizedness: None,
have_vtable: None,
have_destructor: None,
has_type_param_in_array: None,
has_float: None,
}
}
/// Creates a timer for the current bindgen phase. If time_phases is `true`,
/// the timer will print to stderr when it is dropped, otherwise it will do
/// nothing.
pub fn timer<'a>(&self, name: &'a str) -> Timer<'a> {
Timer::new(name).with_output(self.options.time_phases)
}
/// Returns the pointer width to use for the target for the current
/// translation.
pub fn target_pointer_size(&self) -> usize {
if let Some(ref ti) = self.target_info {
return ti.pointer_width / 8;
}
mem::size_of::<*mut ()>()
}
/// Get the stack of partially parsed types that we are in the middle of
/// parsing.
pub fn currently_parsed_types(&self) -> &[PartialType] {
&self.currently_parsed_types[..]
}
/// Begin parsing the given partial type, and push it onto the
/// `currently_parsed_types` stack so that we won't infinite recurse if we
/// run into a reference to it while parsing it.
pub fn begin_parsing(&mut self, partial_ty: PartialType) {
self.currently_parsed_types.push(partial_ty);
}
/// Finish parsing the current partial type, pop it off the
/// `currently_parsed_types` stack, and return it.
pub fn finish_parsing(&mut self) -> PartialType {
self.currently_parsed_types.pop().expect(
"should have been parsing a type, if we finished parsing a type",
)
}
/// Get the user-provided callbacks by reference, if any.
pub fn parse_callbacks(&self) -> Option<&dyn ParseCallbacks> {
self.options().parse_callbacks.as_ref().map(|t| &**t)
}
/// Define a new item.
///
/// This inserts it into the internal items set, and its type into the
/// internal types set.
pub fn add_item(
&mut self,
item: Item,
declaration: Option<Cursor>,
location: Option<Cursor>,
) {
debug!(
"BindgenContext::add_item({:?}, declaration: {:?}, loc: {:?}",
item, declaration, location
);
debug_assert!(
declaration.is_some() ||
!item.kind().is_type() ||
item.kind().expect_type().is_builtin_or_type_param() ||
item.kind().expect_type().is_opaque(self, &item) ||
item.kind().expect_type().is_unresolved_ref(),
"Adding a type without declaration?"
);
let id = item.id();
let is_type = item.kind().is_type();
let is_unnamed = is_type && item.expect_type().name().is_none();
let is_template_instantiation =
is_type && item.expect_type().is_template_instantiation();
if item.id() != self.root_module {
self.add_item_to_module(&item);
}
if is_type && item.expect_type().is_comp() {
self.need_bitfield_allocation.push(id);
}
let old_item = mem::replace(&mut self.items[id.0], Some(item));
assert!(
old_item.is_none(),
"should not have already associated an item with the given id"
);
// Unnamed items can have an USR, but they can't be referenced from
// other sites explicitly and the USR can match if the unnamed items are
// nested, so don't bother tracking them.
if is_type && !is_template_instantiation && declaration.is_some() {
let mut declaration = declaration.unwrap();
if !declaration.is_valid() {
if let Some(location) = location {
if location.is_template_like() {
declaration = location;
}
}
}
declaration = declaration.canonical();
if !declaration.is_valid() {
// This could happen, for example, with types like `int*` or
// similar.
//
// Fortunately, we don't care about those types being
// duplicated, so we can just ignore them.
debug!(
"Invalid declaration {:?} found for type {:?}",
declaration,
self.resolve_item_fallible(id)
.unwrap()
.kind()
.expect_type()
);
return;
}
let key = if is_unnamed {
TypeKey::Declaration(declaration)
} else if let Some(usr) = declaration.usr() {
TypeKey::USR(usr)
} else {
warn!(
"Valid declaration with no USR: {:?}, {:?}",
declaration, location
);
TypeKey::Declaration(declaration)
};
let old = self.types.insert(key, id.as_type_id_unchecked());
debug_assert_eq!(old, None);
}
}
/// Ensure that every item (other than the root module) is in a module's
/// children list. This is to make sure that every whitelisted item get's
/// codegen'd, even if its parent is not whitelisted. See issue #769 for
/// details.
fn add_item_to_module(&mut self, item: &Item) {
assert!(item.id() != self.root_module);
assert!(self.resolve_item_fallible(item.id()).is_none());
if let Some(ref mut parent) = self.items[item.parent_id().0] {
if let Some(module) = parent.as_module_mut() {
debug!(
"add_item_to_module: adding {:?} as child of parent module {:?}",
item.id(),
item.parent_id()
);
module.children_mut().insert(item.id());
return;
}
}
debug!(
"add_item_to_module: adding {:?} as child of current module {:?}",
item.id(),
self.current_module
);
self.items[(self.current_module.0).0]
.as_mut()
.expect("Should always have an item for self.current_module")
.as_module_mut()
.expect("self.current_module should always be a module")
.children_mut()
.insert(item.id());
}
/// Add a new named template type parameter to this context's item set.
pub fn add_type_param(&mut self, item: Item, definition: clang::Cursor) {
debug!(
"BindgenContext::add_type_param: item = {:?}; definition = {:?}",
item, definition
);
assert!(
item.expect_type().is_type_param(),
"Should directly be a named type, not a resolved reference or anything"
);
assert_eq!(
definition.kind(),
clang_sys::CXCursor_TemplateTypeParameter
);
self.add_item_to_module(&item);
let id = item.id();
let old_item = mem::replace(&mut self.items[id.0], Some(item));
assert!(
old_item.is_none(),
"should not have already associated an item with the given id"
);
let old_named_ty = self
.type_params
.insert(definition, id.as_type_id_unchecked());
assert!(
old_named_ty.is_none(),
"should not have already associated a named type with this id"
);
}
/// Get the named type defined at the given cursor location, if we've
/// already added one.
pub fn get_type_param(&self, definition: &clang::Cursor) -> Option<TypeId> {
assert_eq!(
definition.kind(),
clang_sys::CXCursor_TemplateTypeParameter
);
self.type_params.get(definition).cloned()
}
// TODO: Move all this syntax crap to other part of the code.
/// Mangles a name so it doesn't conflict with any keyword.
pub fn rust_mangle<'a>(&self, name: &'a str) -> Cow<'a, str> {
if name.contains("@") ||
name.contains("?") ||
name.contains("$") ||
match name {
"abstract" | "alignof" | "as" | "async" | "become" |
"box" | "break" | "const" | "continue" | "crate" | "do" |
"else" | "enum" | "extern" | "false" | "final" | "fn" |
"for" | "if" | "impl" | "in" | "let" | "loop" | "macro" |
"match" | "mod" | "move" | "mut" | "offsetof" |
"override" | "priv" | "proc" | "pub" | "pure" | "ref" |
"return" | "Self" | "self" | "sizeof" | "static" |
"struct" | "super" | "trait" | "true" | "type" | "typeof" |
"unsafe" | "unsized" | "use" | "virtual" | "where" |
"while" | "yield" | "bool" | "_" => true,
_ => false,
}
{
let mut s = name.to_owned();
s = s.replace("@", "_");
s = s.replace("?", "_");
s = s.replace("$", "_");
s.push_str("_");
return Cow::Owned(s);
}
Cow::Borrowed(name)
}
/// Returns a mangled name as a rust identifier.
pub fn rust_ident<S>(&self, name: S) -> Ident
where
S: AsRef<str>,
{
self.rust_ident_raw(self.rust_mangle(name.as_ref()))
}
/// Returns a mangled name as a rust identifier.
pub fn rust_ident_raw<T>(&self, name: T) -> Ident
where
T: AsRef<str>,
{
Ident::new(name.as_ref(), Span::call_site())
}
/// Iterate over all items that have been defined.
pub fn items(&self) -> impl Iterator<Item = (ItemId, &Item)> {
self.items.iter().enumerate().filter_map(|(index, item)| {
let item = item.as_ref()?;
Some((ItemId(index), item))
})
}
/// Have we collected all unresolved type references yet?
pub fn collected_typerefs(&self) -> bool {
self.collected_typerefs
}
/// Gather all the unresolved type references.
fn collect_typerefs(
&mut self,
) -> Vec<(ItemId, clang::Type, clang::Cursor, Option<ItemId>)> {
debug_assert!(!self.collected_typerefs);
self.collected_typerefs = true;
let mut typerefs = vec![];
for (id, item) in self.items() {
let kind = item.kind();
let ty = match kind.as_type() {
Some(ty) => ty,
None => continue,
};
match *ty.kind() {
TypeKind::UnresolvedTypeRef(ref ty, loc, parent_id) => {
typerefs.push((id, ty.clone(), loc, parent_id));
}
_ => {}
};
}
typerefs
}
/// Collect all of our unresolved type references and resolve them.
fn resolve_typerefs(&mut self) {
let _t = self.timer("resolve_typerefs");
let typerefs = self.collect_typerefs();
for (id, ty, loc, parent_id) in typerefs {
let _resolved =
{
let resolved = Item::from_ty(&ty, loc, parent_id, self)
.unwrap_or_else(|_| {
warn!("Could not resolve type reference, falling back \
to opaque blob");
Item::new_opaque_type(self.next_item_id(), &ty, self)
});
let item = self.items[id.0].as_mut().unwrap();
*item.kind_mut().as_type_mut().unwrap().kind_mut() =
TypeKind::ResolvedTypeRef(resolved);
resolved
};
// Something in the STL is trolling me. I don't need this assertion
// right now, but worth investigating properly once this lands.
//
// debug_assert!(self.items.get(&resolved).is_some(), "How?");
//
// if let Some(parent_id) = parent_id {
// assert_eq!(self.items[&resolved].parent_id(), parent_id);
// }
}
}
/// Temporarily loan `Item` with the given `ItemId`. This provides means to
/// mutably borrow `Item` while having a reference to `BindgenContext`.
///
/// `Item` with the given `ItemId` is removed from the context, given
/// closure is executed and then `Item` is placed back.
///
/// # Panics
///
/// Panics if attempt to resolve given `ItemId` inside the given
/// closure is made.
fn with_loaned_item<F, T>(&mut self, id: ItemId, f: F) -> T
where
F: (FnOnce(&BindgenContext, &mut Item) -> T),
{
let mut item = self.items[id.0].take().unwrap();
let result = f(self, &mut item);
let existing = mem::replace(&mut self.items[id.0], Some(item));
assert!(existing.is_none());
result
}
/// Compute the bitfield allocation units for all `TypeKind::Comp` items we
/// parsed.
fn compute_bitfield_units(&mut self) {
let _t = self.timer("compute_bitfield_units");
assert!(self.collected_typerefs());
let need_bitfield_allocation =
mem::replace(&mut self.need_bitfield_allocation, vec![]);
for id in need_bitfield_allocation {