-
Notifications
You must be signed in to change notification settings - Fork 707
/
context.rs
2288 lines (2029 loc) · 82.5 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::analysis::{CannotDeriveCopy, CannotDeriveDebug,
CannotDeriveDefault, CannotDeriveHash,
CannotDerivePartialEq, HasTypeParameterInArray,
HasVtableAnalysis, HasDestructorAnalysis, UsedTemplateParameters,
HasFloat, analyze};
use super::derive::{CanDeriveCopy, CanDeriveDebug, CanDeriveDefault,
CanDeriveHash, CanDerivePartialEq, CanDeriveEq};
use super::int::IntKind;
use super::item::{HasTypeParamInArray, IsOpaque, Item, ItemAncestors,
ItemCanonicalPath, 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 super::super::time::Timer;
use BindgenOptions;
use callbacks::ParseCallbacks;
use cexpr;
use clang::{self, Cursor};
use clang_sys;
use parse::ClangItemParser;
use std::borrow::Cow;
use std::cell::Cell;
use std::collections::{HashMap, HashSet, hash_map};
use std::collections::btree_map::{self, BTreeMap};
use std::fmt;
use std::iter::IntoIterator;
use std::mem;
use syntax::ast::Ident;
use syntax::codemap::{DUMMY_SP, Span};
use syntax::ext::base::ExtCtxt;
/// A single identifier for an item.
///
/// TODO: Build stronger abstractions on top of this, like TypeId(ItemId)?
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ItemId(usize);
impl ItemId {
/// Get a numeric representation of this id.
pub fn as_usize(&self) -> usize {
self.0
}
}
impl CanDeriveDebug for ItemId {
fn can_derive_debug(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_debug && ctx.lookup_item_id_can_derive_debug(*self)
}
}
impl CanDeriveDefault for ItemId {
fn can_derive_default(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_default &&
ctx.lookup_item_id_can_derive_default(*self)
}
}
impl<'a> CanDeriveCopy<'a> for ItemId {
fn can_derive_copy(&self, ctx: &BindgenContext) -> bool {
ctx.lookup_item_id_can_derive_copy(*self)
}
}
impl CanDeriveHash for ItemId {
fn can_derive_hash(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_hash && ctx.lookup_item_id_can_derive_hash(*self)
}
}
impl CanDerivePartialEq for ItemId {
fn can_derive_partialeq(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_partialeq &&
ctx.lookup_item_id_can_derive_partialeq(*self)
}
}
impl CanDeriveEq for ItemId {
fn can_derive_eq(&self, ctx: &BindgenContext) -> bool {
ctx.options().derive_eq &&
ctx.lookup_item_id_can_derive_partialeq(*self) &&
!ctx.lookup_item_id_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),
}
// This is just convenience to avoid creating a manual debug impl for the
// context.
struct GenContext<'ctx>(ExtCtxt<'ctx>);
impl<'ctx> fmt::Debug for GenContext<'ctx> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "GenContext {{ ... }}")
}
}
/// A context used during parsing and generation of structs.
#[derive(Debug)]
pub struct BindgenContext<'ctx> {
/// The map of all the items parsed so far.
///
/// It's a BTreeMap because we want the keys to be sorted to have consistent
/// output.
items: BTreeMap<ItemId, Item>,
/// The next item id to use during this bindings regeneration.
next_item_id: ItemId,
/// Clang USR to type map. This is needed to be able to associate types with
/// item ids during parsing.
types: HashMap<TypeKey, ItemId>,
/// Maps from a cursor to the item id of the named template type parameter
/// for that cursor.
type_params: HashMap<clang::Cursor, ItemId>,
/// A cursor to module map. Similar reason than above.
modules: HashMap<Cursor, ItemId>,
/// The root module, this is guaranteed to be an item of kind Module.
root_module: ItemId,
/// Current module being traversed.
current_module: 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 HashSet 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.
parsed_macros: HashMap<Vec<u8>, cexpr::expr::EvalResult>,
/// The active replacements collected from replaces="xxx" annotations.
replacements: HashMap<Vec<String>, ItemId>,
collected_typerefs: bool,
/// Dummy structures for code generation.
gen_ctx: Option<&'ctx GenContext<'ctx>>,
span: Span,
/// The clang index for parsing.
index: clang::Index,
/// The translation unit for parsing.
translation_unit: clang::TranslationUnit,
/// The options given by the user via cli or other medium.
options: BindgenOptions,
/// Whether a bindgen complex was generated
generated_bindegen_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>,
/// Whether we need the mangling hack which removes the prefixing underscore.
needs_mangling_hack: bool,
/// 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 set of (`ItemId`s of) types that can't derive hash.
///
/// This is populated when we enter codegen by `compute_can_derive_partialeq`
/// and is always `None` before that and `Some` after.
cannot_derive_partialeq: Option<HashSet<ItemId>>,
/// 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<HashSet<ItemId>>,
/// 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, 'gen>
where
'gen: 'ctx,
{
ctx: &'ctx BindgenContext<'gen>,
traversal: ItemTraversal<
'ctx,
'gen,
ItemSet,
Vec<ItemId>,
for<'a> fn(&'a BindgenContext, Edge) -> bool,
>,
}
impl<'ctx, 'gen> Iterator for WhitelistedItemsTraversal<'ctx, 'gen>
where
'gen: 'ctx,
{
type Item = ItemId;
fn next(&mut self) -> Option<ItemId> {
loop {
match self.traversal.next() {
None => return None,
Some(id) if self.ctx.resolve_item(id).is_hidden(self.ctx) => {
continue
}
Some(id) => return Some(id),
}
}
}
}
impl<'ctx, 'gen> WhitelistedItemsTraversal<'ctx, 'gen>
where
'gen: 'ctx,
{
/// Construct a new whitelisted items traversal.
pub fn new<R>(
ctx: &'ctx BindgenContext<'gen>,
roots: R,
predicate: for<'a> fn(&'a BindgenContext, Edge) -> bool,
) -> Self
where
R: IntoIterator<Item = ItemId>,
{
WhitelistedItemsTraversal {
ctx: ctx,
traversal: ItemTraversal::new(ctx, roots, predicate),
}
}
}
impl<'ctx> BindgenContext<'ctx> {
/// Construct the context for the given `options`.
pub fn new(options: BindgenOptions) -> Self {
use clang_sys;
let index = clang::Index::new(false, true);
let parse_options =
clang_sys::CXTranslationUnit_DetailedPreprocessingRecord;
let translation_unit = clang::TranslationUnit::parse(
&index,
"",
&options.clang_args,
&options.input_unsaved_files,
parse_options,
).expect("TranslationUnit::parse failed");
// TODO(emilio): Use the CXTargetInfo here when available.
//
// see: https://reviews.llvm.org/D32389
let mut effective_target = None;
for opt in &options.clang_args {
if opt.starts_with("--target=") {
let mut split = opt.split('=');
split.next();
effective_target = Some(split.next().unwrap().to_owned());
break;
}
}
if effective_target.is_none() {
use std::env;
// If we're running from a build script, try to find the cargo
// target.
effective_target = env::var("TARGET").ok();
}
if effective_target.is_none() {
const HOST_TARGET: &'static str =
include_str!(concat!(env!("OUT_DIR"), "/host-target.txt"));
effective_target = Some(HOST_TARGET.to_owned());
}
// Mac os, iOS and Win32 need __ for mangled symbols but rust will automatically
// prepend the extra _.
//
// We need to make sure that we don't include __ because rust will turn into
// ___.
let effective_target = effective_target.unwrap();
let needs_mangling_hack = effective_target.contains("darwin") ||
effective_target.contains("ios") ||
effective_target == "i686-pc-win32";
let root_module = Self::build_root_module(ItemId(0));
let mut me = BindgenContext {
items: Default::default(),
types: Default::default(),
type_params: Default::default(),
modules: Default::default(),
next_item_id: ItemId(1),
root_module: root_module.id(),
current_module: root_module.id(),
currently_parsed_types: vec![],
parsed_macros: Default::default(),
replacements: Default::default(),
collected_typerefs: false,
gen_ctx: None,
span: DUMMY_SP,
index: index,
translation_unit: translation_unit,
options: options,
generated_bindegen_complex: Cell::new(false),
whitelisted: None,
codegen_items: None,
used_template_parameters: None,
need_bitfield_allocation: Default::default(),
needs_mangling_hack: needs_mangling_hack,
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: None,
have_vtable: None,
have_destructor: None,
has_type_param_in_array: None,
has_float: None,
};
me.add_item(root_module, None, None);
me
}
/// 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)
}
/// 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<&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),
"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 = self.items.insert(id, 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.items.get(&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);
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.items.contains_key(&item.id()));
if let Some(parent) = self.items.get_mut(&item.parent_id()) {
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
.get_mut(&self.current_module)
.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 = self.items.insert(id, 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);
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<ItemId> {
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.
/// Given that we are in the codegen phase, get the syntex context.
pub fn ext_cx(&self) -> &ExtCtxt<'ctx> {
&self.gen_ctx.expect("Not in gen phase").0
}
/// Given that we are in the codegen phase, get the current syntex span.
pub fn span(&self) -> Span {
self.span
}
/// Mangles a name so it doesn't conflict with any keyword.
pub fn rust_mangle<'a>(&self, name: &'a str) -> Cow<'a, str> {
use syntax::parse::token;
let ident = self.rust_ident_raw(name);
let token = token::Ident(ident);
if token.is_any_keyword() || name.contains("@") ||
name.contains("?") || name.contains("$") ||
"bool" == name
{
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(&self, name: &str) -> Ident {
self.rust_ident_raw(&self.rust_mangle(name))
}
/// Returns a mangled name as a rust identifier.
pub fn rust_ident_raw(&self, name: &str) -> Ident {
self.ext_cx().ident_of(name)
}
/// Iterate over all items that have been defined.
pub fn items<'a>(&'a self) -> btree_map::Iter<'a, ItemId, Item> {
self.items.iter()
}
/// 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, ref mut item) in &mut 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 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.get_mut(&id).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?");
}
}
/// Compute the bitfield allocation units for all `TypeKind::Comp` items we
/// parsed.
fn compute_bitfield_units(&mut self) {
assert!(self.collected_typerefs());
let need_bitfield_allocation =
mem::replace(&mut self.need_bitfield_allocation, vec![]);
for id in need_bitfield_allocation {
// To appease the borrow checker, we temporarily remove this item
// from the context, and then replace it once we are done computing
// its bitfield units. We will never try and resolve this
// `TypeKind::Comp` item's id (which would now cause a panic) during
// bitfield unit computation because it is a non-scalar by
// definition, and non-scalar types may not be used as bitfields.
let mut item = self.items.remove(&id).unwrap();
item.kind_mut()
.as_type_mut()
.unwrap()
.as_comp_mut()
.unwrap()
.compute_bitfield_units(&*self);
self.items.insert(id, item);
}
}
/// Iterate over all items and replace any item that has been named in a
/// `replaces="SomeType"` annotation with the replacement type.
fn process_replacements(&mut self) {
let _t = self.timer("process_replacements");
if self.replacements.is_empty() {
debug!("No replacements to process");
return;
}
// FIXME: This is linear, but the replaces="xxx" annotation was already
// there, and for better or worse it's useful, sigh...
//
// We leverage the ResolvedTypeRef thing, though, which is cool :P.
let mut replacements = vec![];
for (id, item) in self.items.iter() {
if item.annotations().use_instead_of().is_some() {
continue;
}
// Calls to `canonical_name` are expensive, so eagerly filter out
// items that cannot be replaced.
let ty = match item.kind().as_type() {
Some(ty) => ty,
None => continue,
};
match *ty.kind() {
TypeKind::Comp(..) |
TypeKind::TemplateAlias(..) |
TypeKind::Alias(..) => {}
_ => continue,
}
let path = item.canonical_path(self);
let replacement = self.replacements.get(&path[1..]);
if let Some(replacement) = replacement {
if replacement != id {
// We set this just after parsing the annotation. It's
// very unlikely, but this can happen.
if self.items.get(replacement).is_some() {
replacements.push((*id, *replacement));
}
}
}
}
for (id, replacement) in replacements {
debug!("Replacing {:?} with {:?}", id, replacement);
let new_parent = {
let item = self.items.get_mut(&id).unwrap();
*item.kind_mut().as_type_mut().unwrap().kind_mut() =
TypeKind::ResolvedTypeRef(replacement);
item.parent_id()
};
// Relocate the replacement item from where it was declared, to
// where the thing it is replacing was declared.
//
// First, we'll make sure that its parent id is correct.
let old_parent = self.resolve_item(replacement).parent_id();
if new_parent == old_parent {
// Same parent and therefore also same containing
// module. Nothing to do here.
continue;
}
self.items
.get_mut(&replacement)
.unwrap()
.set_parent_for_replacement(new_parent);
// Second, make sure that it is in the correct module's children
// set.
let old_module = {
let immut_self = &*self;
old_parent
.ancestors(immut_self)
.chain(Some(immut_self.root_module))
.find(|id| {
let item = immut_self.resolve_item(*id);
item.as_module().map_or(false, |m| {
m.children().contains(&replacement)
})
})
};
let old_module = old_module.expect(
"Every replacement item should be in a module",
);
let new_module = {
let immut_self = &*self;
new_parent.ancestors(immut_self).find(|id| {
immut_self.resolve_item(*id).is_module()
})
};
let new_module = new_module.unwrap_or(self.root_module);
if new_module == old_module {
// Already in the correct module.
continue;
}
self.items
.get_mut(&old_module)
.unwrap()
.as_module_mut()
.unwrap()
.children_mut()
.remove(&replacement);
self.items
.get_mut(&new_module)
.unwrap()
.as_module_mut()
.unwrap()
.children_mut()
.insert(replacement);
}
}
/// Enter the code generation phase, invoke the given callback `cb`, and
/// leave the code generation phase.
pub fn gen<F, Out>(&mut self, cb: F) -> Out
where
F: FnOnce(&Self) -> Out,
{
use aster::symbol::ToSymbol;
use syntax::ext::expand::ExpansionConfig;
use syntax::codemap::{ExpnInfo, MacroBang, NameAndSpan};
use syntax::ext::base;
use syntax::parse;
use std::mem;
let cfg = ExpansionConfig::default("xxx".to_owned());
let sess = parse::ParseSess::new();
let mut loader = base::DummyResolver;
let mut ctx = GenContext(base::ExtCtxt::new(&sess, cfg, &mut loader));
ctx.0.bt_push(ExpnInfo {
call_site: self.span,
callee: NameAndSpan {
format: MacroBang("".to_symbol()),
allow_internal_unstable: false,
span: None,
},
});
// FIXME: This is evil, we should move code generation to use a wrapper
// of BindgenContext instead, I guess. Even though we know it's fine
// because we remove it before the end of this function.
self.gen_ctx = Some(unsafe { mem::transmute(&ctx) });
self.assert_no_dangling_references();
if !self.collected_typerefs() {
self.resolve_typerefs();
self.compute_bitfield_units();
self.process_replacements();
}
// And assert once again, because resolving type refs and processing
// replacements both mutate the IR graph.
self.assert_no_dangling_references();
// Compute the whitelisted set after processing replacements and
// resolving type refs, as those are the final mutations of the IR
// graph, and their completion means that the IR graph is now frozen.
self.compute_whitelisted_and_codegen_items();
// Make sure to do this after processing replacements, since that messes
// with the parentage and module children, and we want to assert that it
// messes with them correctly.
self.assert_every_item_in_a_module();
self.compute_has_vtable();
self.compute_has_destructor();
self.find_used_template_parameters();
self.compute_cannot_derive_debug();
self.compute_cannot_derive_default();
self.compute_cannot_derive_copy();
self.compute_has_type_param_in_array();
self.compute_has_float();
self.compute_cannot_derive_hash();
self.compute_cannot_derive_partialeq_or_eq();
let ret = cb(self);
self.gen_ctx = None;
ret
}
/// When the `testing_only_extra_assertions` feature is enabled, this
/// function walks the IR graph and asserts that we do not have any edges
/// referencing an ItemId for which we do not have an associated IR item.
fn assert_no_dangling_references(&self) {
if cfg!(feature = "testing_only_extra_assertions") {
for _ in self.assert_no_dangling_item_traversal() {
// The iterator's next method does the asserting for us.
}
}
}
fn assert_no_dangling_item_traversal<'me>(
&'me self,
) -> traversal::AssertNoDanglingItemsTraversal<'me, 'ctx> {
assert!(self.in_codegen_phase());
assert!(self.current_module == self.root_module);
let roots = self.items().map(|(&id, _)| id);
traversal::AssertNoDanglingItemsTraversal::new(
self,
roots,
traversal::all_edges,
)
}
/// When the `testing_only_extra_assertions` feature is enabled, walk over
/// every item and ensure that it is in the children set of one of its
/// module ancestors.
fn assert_every_item_in_a_module(&self) {
if cfg!(feature = "testing_only_extra_assertions") {
assert!(self.in_codegen_phase());
assert!(self.current_module == self.root_module);
for (&id, _item) in self.items() {
if id == self.root_module {
continue;
}
assert!(
{
let id = id.into_resolver()
.through_type_refs()
.through_type_aliases()
.resolve(self)
.id();
id.ancestors(self).chain(Some(self.root_module)).any(
|ancestor| {
debug!(
"Checking if {:?} is a child of {:?}",
id,
ancestor
);
self.resolve_item(ancestor).as_module().map_or(
false,
|m| {
m.children().contains(&id)
},
)
},
)
},
"{:?} should be in some ancestor module's children set",
id
);
}
}