-
Notifications
You must be signed in to change notification settings - Fork 12.9k
/
decoder.rs
1203 lines (1058 loc) · 43.7 KB
/
decoder.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
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Decoding metadata from a single crate's metadata
use cstore::{self, CrateMetadata, MetadataBlob, NativeLibrary};
use schema::*;
use rustc::dep_graph::{DepGraph, DepNode, DepKind};
use rustc::hir::map::{DefKey, DefPath, DefPathData, DefPathHash};
use rustc::hir::map::definitions::GlobalMetaDataKind;
use rustc::hir;
use rustc::middle::cstore::LinkagePreference;
use rustc::hir::def::{self, Def, CtorKind};
use rustc::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
use rustc::middle::lang_items;
use rustc::session::Session;
use rustc::ty::{self, Ty, TyCtxt};
use rustc::ty::subst::Substs;
use rustc::mir::Mir;
use std::borrow::Cow;
use std::cell::Ref;
use std::collections::BTreeMap;
use std::io;
use std::mem;
use std::rc::Rc;
use std::str;
use std::u32;
use rustc_serialize::{Decodable, Decoder, SpecializedDecoder, opaque};
use syntax::attr;
use syntax::ast::{self, Ident};
use syntax::codemap;
use syntax::ext::base::MacroKind;
use syntax_pos::{self, Span, BytePos, Pos, DUMMY_SP, NO_EXPANSION};
pub struct DecodeContext<'a, 'tcx: 'a> {
opaque: opaque::Decoder<'a>,
cdata: Option<&'a CrateMetadata>,
sess: Option<&'a Session>,
tcx: Option<TyCtxt<'a, 'tcx, 'tcx>>,
// Cache the last used filemap for translating spans as an optimization.
last_filemap_index: usize,
lazy_state: LazyState,
}
/// Abstract over the various ways one can create metadata decoders.
pub trait Metadata<'a, 'tcx>: Copy {
fn raw_bytes(self) -> &'a [u8];
fn cdata(self) -> Option<&'a CrateMetadata> { None }
fn sess(self) -> Option<&'a Session> { None }
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None }
fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
let tcx = self.tcx();
DecodeContext {
opaque: opaque::Decoder::new(self.raw_bytes(), pos),
cdata: self.cdata(),
sess: self.sess().or(tcx.map(|tcx| tcx.sess)),
tcx: tcx,
last_filemap_index: 0,
lazy_state: LazyState::NoNode,
}
}
}
impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
fn raw_bytes(self) -> &'a [u8] {
&self.0
}
}
impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
fn raw_bytes(self) -> &'a [u8] {
self.blob.raw_bytes()
}
fn cdata(self) -> Option<&'a CrateMetadata> {
Some(self)
}
}
impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, &'a Session) {
fn raw_bytes(self) -> &'a [u8] {
self.0.raw_bytes()
}
fn cdata(self) -> Option<&'a CrateMetadata> {
Some(self.0)
}
fn sess(self) -> Option<&'a Session> {
Some(&self.1)
}
}
impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
fn raw_bytes(self) -> &'a [u8] {
self.0.raw_bytes()
}
fn cdata(self) -> Option<&'a CrateMetadata> {
Some(self.0)
}
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
Some(self.1)
}
}
impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> T {
let mut dcx = meta.decoder(self.position);
dcx.lazy_state = LazyState::NodeStart(self.position);
T::decode(&mut dcx).unwrap()
}
}
impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item = T> + 'a {
let mut dcx = meta.decoder(self.position);
dcx.lazy_state = LazyState::NodeStart(self.position);
(0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
}
}
impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
pub fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> {
self.tcx.expect("missing TyCtxt in DecodeContext")
}
pub fn cdata(&self) -> &'a CrateMetadata {
self.cdata.expect("missing CrateMetadata in DecodeContext")
}
fn with_position<F: FnOnce(&mut Self) -> R, R>(&mut self, pos: usize, f: F) -> R {
let new_opaque = opaque::Decoder::new(self.opaque.data, pos);
let old_opaque = mem::replace(&mut self.opaque, new_opaque);
let old_state = mem::replace(&mut self.lazy_state, LazyState::NoNode);
let r = f(self);
self.opaque = old_opaque;
self.lazy_state = old_state;
r
}
fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
let distance = self.read_usize()?;
let position = match self.lazy_state {
LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
LazyState::NodeStart(start) => {
assert!(distance + min_size <= start);
start - distance - min_size
}
LazyState::Previous(last_min_end) => last_min_end + distance,
};
self.lazy_state = LazyState::Previous(position + min_size);
Ok(position)
}
}
macro_rules! decoder_methods {
($($name:ident -> $ty:ty;)*) => {
$(fn $name(&mut self) -> Result<$ty, Self::Error> {
self.opaque.$name()
})*
}
}
impl<'doc, 'tcx> Decoder for DecodeContext<'doc, 'tcx> {
type Error = <opaque::Decoder<'doc> as Decoder>::Error;
decoder_methods! {
read_nil -> ();
read_u128 -> u128;
read_u64 -> u64;
read_u32 -> u32;
read_u16 -> u16;
read_u8 -> u8;
read_usize -> usize;
read_i128 -> i128;
read_i64 -> i64;
read_i32 -> i32;
read_i16 -> i16;
read_i8 -> i8;
read_isize -> isize;
read_bool -> bool;
read_f64 -> f64;
read_f32 -> f32;
read_char -> char;
read_str -> Cow<str>;
}
fn error(&mut self, err: &str) -> Self::Error {
self.opaque.error(err)
}
}
impl<'a, 'tcx, T> SpecializedDecoder<Lazy<T>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<Lazy<T>, Self::Error> {
Ok(Lazy::with_position(self.read_lazy_distance(Lazy::<T>::min_size())?))
}
}
impl<'a, 'tcx, T> SpecializedDecoder<LazySeq<T>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<LazySeq<T>, Self::Error> {
let len = self.read_usize()?;
let position = if len == 0 {
0
} else {
self.read_lazy_distance(LazySeq::<T>::min_size(len))?
};
Ok(LazySeq::with_position_and_length(position, len))
}
}
impl<'a, 'tcx> SpecializedDecoder<CrateNum> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<CrateNum, Self::Error> {
let cnum = CrateNum::from_u32(u32::decode(self)?);
if cnum == LOCAL_CRATE {
Ok(self.cdata().cnum)
} else {
Ok(self.cdata().cnum_map.borrow()[cnum])
}
}
}
impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<Span, Self::Error> {
let lo = BytePos::decode(self)?;
let hi = BytePos::decode(self)?;
let sess = if let Some(sess) = self.sess {
sess
} else {
return Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION });
};
let (lo, hi) = if lo > hi {
// Currently macro expansion sometimes produces invalid Span values
// where lo > hi. In order not to crash the compiler when trying to
// translate these values, let's transform them into something we
// can handle (and which will produce useful debug locations at
// least some of the time).
// This workaround is only necessary as long as macro expansion is
// not fixed. FIXME(#23480)
(lo, lo)
} else {
(lo, hi)
};
let imported_filemaps = self.cdata().imported_filemaps(&sess.codemap());
let filemap = {
// Optimize for the case that most spans within a translated item
// originate from the same filemap.
let last_filemap = &imported_filemaps[self.last_filemap_index];
if lo >= last_filemap.original_start_pos && lo <= last_filemap.original_end_pos &&
hi >= last_filemap.original_start_pos &&
hi <= last_filemap.original_end_pos {
last_filemap
} else {
let mut a = 0;
let mut b = imported_filemaps.len();
while b - a > 1 {
let m = (a + b) / 2;
if imported_filemaps[m].original_start_pos > lo {
b = m;
} else {
a = m;
}
}
self.last_filemap_index = a;
&imported_filemaps[a]
}
};
let lo = (lo - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
let hi = (hi - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
Ok(Span { lo: lo, hi: hi, ctxt: NO_EXPANSION })
}
}
// FIXME(#36588) These impls are horribly unsound as they allow
// the caller to pick any lifetime for 'tcx, including 'static,
// by using the unspecialized proxies to them.
impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<Ty<'tcx>, Self::Error> {
let tcx = self.tcx();
// Handle shorthands first, if we have an usize > 0x80.
if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
let pos = self.read_usize()?;
assert!(pos >= SHORTHAND_OFFSET);
let key = ty::CReaderCacheKey {
cnum: self.cdata().cnum,
pos: pos - SHORTHAND_OFFSET,
};
if let Some(ty) = tcx.rcache.borrow().get(&key).cloned() {
return Ok(ty);
}
let ty = self.with_position(key.pos, Ty::decode)?;
tcx.rcache.borrow_mut().insert(key, ty);
Ok(ty)
} else {
Ok(tcx.mk_ty(ty::TypeVariants::decode(self)?))
}
}
}
impl<'a, 'tcx> SpecializedDecoder<ty::GenericPredicates<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<ty::GenericPredicates<'tcx>, Self::Error> {
Ok(ty::GenericPredicates {
parent: Decodable::decode(self)?,
predicates: (0..self.read_usize()?).map(|_| {
// Handle shorthands first, if we have an usize > 0x80.
if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
let pos = self.read_usize()?;
assert!(pos >= SHORTHAND_OFFSET);
let pos = pos - SHORTHAND_OFFSET;
self.with_position(pos, ty::Predicate::decode)
} else {
ty::Predicate::decode(self)
}
})
.collect::<Result<Vec<_>, _>>()?,
})
}
}
impl<'a, 'tcx> SpecializedDecoder<&'tcx Substs<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<&'tcx Substs<'tcx>, Self::Error> {
Ok(self.tcx().mk_substs((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
}
}
impl<'a, 'tcx> SpecializedDecoder<ty::Region<'tcx>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<ty::Region<'tcx>, Self::Error> {
Ok(self.tcx().mk_region(Decodable::decode(self)?))
}
}
impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<Ty<'tcx>>> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<&'tcx ty::Slice<Ty<'tcx>>, Self::Error> {
Ok(self.tcx().mk_type_list((0..self.read_usize()?).map(|_| Decodable::decode(self)))?)
}
}
impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::AdtDef> for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self) -> Result<&'tcx ty::AdtDef, Self::Error> {
let def_id = DefId::decode(self)?;
Ok(self.tcx().adt_def(def_id))
}
}
impl<'a, 'tcx> SpecializedDecoder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>
for DecodeContext<'a, 'tcx> {
fn specialized_decode(&mut self)
-> Result<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>, Self::Error> {
Ok(self.tcx().mk_existential_predicates((0..self.read_usize()?)
.map(|_| Decodable::decode(self)))?)
}
}
impl<'a, 'tcx> MetadataBlob {
pub fn is_compatible(&self) -> bool {
self.raw_bytes().starts_with(METADATA_HEADER)
}
pub fn get_rustc_version(&self) -> String {
Lazy::with_position(METADATA_HEADER.len() + 4).decode(self)
}
pub fn get_root(&self) -> CrateRoot {
let slice = self.raw_bytes();
let offset = METADATA_HEADER.len();
let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
((slice[offset + 2] as u32) << 8) |
((slice[offset + 3] as u32) << 0)) as usize;
Lazy::with_position(pos).decode(self)
}
pub fn list_crate_metadata(&self,
out: &mut io::Write) -> io::Result<()> {
write!(out, "=External Dependencies=\n")?;
let root = self.get_root();
for (i, dep) in root.crate_deps
.get_untracked()
.decode(self)
.enumerate() {
write!(out, "{} {}-{}\n", i + 1, dep.name, dep.hash)?;
}
write!(out, "\n")?;
Ok(())
}
}
impl<'tcx> EntryKind<'tcx> {
fn to_def(&self, did: DefId) -> Option<Def> {
Some(match *self {
EntryKind::Const(_) => Def::Const(did),
EntryKind::AssociatedConst(..) => Def::AssociatedConst(did),
EntryKind::ImmStatic |
EntryKind::ForeignImmStatic => Def::Static(did, false),
EntryKind::MutStatic |
EntryKind::ForeignMutStatic => Def::Static(did, true),
EntryKind::Struct(_, _) => Def::Struct(did),
EntryKind::Union(_, _) => Def::Union(did),
EntryKind::Fn(_) |
EntryKind::ForeignFn(_) => Def::Fn(did),
EntryKind::Method(_) => Def::Method(did),
EntryKind::Type => Def::TyAlias(did),
EntryKind::AssociatedType(_) => Def::AssociatedTy(did),
EntryKind::Mod(_) => Def::Mod(did),
EntryKind::Variant(_) => Def::Variant(did),
EntryKind::Trait(_) => Def::Trait(did),
EntryKind::Enum(..) => Def::Enum(did),
EntryKind::MacroDef(_) => Def::Macro(did, MacroKind::Bang),
EntryKind::GlobalAsm => Def::GlobalAsm(did),
EntryKind::ForeignMod |
EntryKind::Impl(_) |
EntryKind::DefaultImpl(_) |
EntryKind::Field |
EntryKind::Closure(_) => return None,
})
}
}
impl<'a, 'tcx> CrateMetadata {
fn is_proc_macro(&self, id: DefIndex) -> bool {
self.proc_macros.is_some() && id != CRATE_DEF_INDEX
}
fn maybe_entry(&self, item_id: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
assert!(!self.is_proc_macro(item_id));
self.root.index.lookup(self.blob.raw_bytes(), item_id)
}
fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
match self.maybe_entry(item_id) {
None => {
bug!("entry: id not found: {:?} in crate {:?} with number {}",
item_id,
self.name,
self.cnum)
}
Some(d) => d.decode(self),
}
}
fn local_def_id(&self, index: DefIndex) -> DefId {
DefId {
krate: self.cnum,
index: index,
}
}
fn item_name(&self, item_index: DefIndex) -> ast::Name {
self.def_key(item_index)
.disambiguated_data
.data
.get_opt_name()
.expect("no name in item_name")
}
pub fn get_def(&self, index: DefIndex) -> Option<Def> {
if !self.is_proc_macro(index) {
self.entry(index).kind.to_def(self.local_def_id(index))
} else {
let kind = self.proc_macros.as_ref().unwrap()[index.as_usize() - 1].1.kind();
Some(Def::Macro(self.local_def_id(index), kind))
}
}
pub fn get_span(&self, index: DefIndex, sess: &Session) -> Span {
match self.is_proc_macro(index) {
true => DUMMY_SP,
false => self.entry(index).span.decode((self, sess)),
}
}
pub fn get_trait_def(&self, item_id: DefIndex) -> ty::TraitDef {
let data = match self.entry(item_id).kind {
EntryKind::Trait(data) => data.decode(self),
_ => bug!(),
};
ty::TraitDef::new(self.local_def_id(item_id),
data.unsafety,
data.paren_sugar,
data.has_default_impl,
self.def_path_table.def_path_hash(item_id))
}
fn get_variant(&self, item: &Entry, index: DefIndex) -> ty::VariantDef {
let data = match item.kind {
EntryKind::Variant(data) |
EntryKind::Struct(data, _) |
EntryKind::Union(data, _) => data.decode(self),
_ => bug!(),
};
ty::VariantDef {
did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
name: self.item_name(index),
fields: item.children.decode(self).map(|index| {
let f = self.entry(index);
ty::FieldDef {
did: self.local_def_id(index),
name: self.item_name(index),
vis: f.visibility.decode(self)
}
}).collect(),
discr: data.discr,
ctor_kind: data.ctor_kind,
}
}
pub fn get_adt_def(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> &'tcx ty::AdtDef {
let item = self.entry(item_id);
let did = self.local_def_id(item_id);
let kind = match item.kind {
EntryKind::Enum(_) => ty::AdtKind::Enum,
EntryKind::Struct(_, _) => ty::AdtKind::Struct,
EntryKind::Union(_, _) => ty::AdtKind::Union,
_ => bug!("get_adt_def called on a non-ADT {:?}", did),
};
let variants = if let ty::AdtKind::Enum = kind {
item.children
.decode(self)
.map(|index| {
self.get_variant(&self.entry(index), index)
})
.collect()
} else {
vec![self.get_variant(&item, item_id)]
};
let (kind, repr) = match item.kind {
EntryKind::Enum(repr) => (ty::AdtKind::Enum, repr),
EntryKind::Struct(_, repr) => (ty::AdtKind::Struct, repr),
EntryKind::Union(_, repr) => (ty::AdtKind::Union, repr),
_ => bug!("get_adt_def called on a non-ADT {:?}", did),
};
tcx.alloc_adt_def(did, kind, variants, repr)
}
pub fn get_predicates(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::GenericPredicates<'tcx> {
self.entry(item_id).predicates.unwrap().decode((self, tcx))
}
pub fn get_super_predicates(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::GenericPredicates<'tcx> {
match self.entry(item_id).kind {
EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
_ => bug!(),
}
}
pub fn get_generics(&self, item_id: DefIndex) -> ty::Generics {
self.entry(item_id).generics.unwrap().decode(self)
}
pub fn get_type(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Ty<'tcx> {
self.entry(id).ty.unwrap().decode((self, tcx))
}
pub fn get_stability(&self, id: DefIndex) -> Option<attr::Stability> {
match self.is_proc_macro(id) {
true => None,
false => self.entry(id).stability.map(|stab| stab.decode(self)),
}
}
pub fn get_deprecation(&self, id: DefIndex) -> Option<attr::Deprecation> {
match self.is_proc_macro(id) {
true => None,
false => self.entry(id).deprecation.map(|depr| depr.decode(self)),
}
}
pub fn get_visibility(&self, id: DefIndex) -> ty::Visibility {
match self.is_proc_macro(id) {
true => ty::Visibility::Public,
false => self.entry(id).visibility.decode(self),
}
}
fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
match self.entry(id).kind {
EntryKind::Impl(data) => data.decode(self),
_ => bug!(),
}
}
pub fn get_parent_impl(&self, id: DefIndex) -> Option<DefId> {
self.get_impl_data(id).parent_impl
}
pub fn get_impl_polarity(&self, id: DefIndex) -> hir::ImplPolarity {
self.get_impl_data(id).polarity
}
pub fn get_impl_defaultness(&self, id: DefIndex) -> hir::Defaultness {
self.get_impl_data(id).defaultness
}
pub fn get_coerce_unsized_info(&self,
id: DefIndex)
-> Option<ty::adjustment::CoerceUnsizedInfo> {
self.get_impl_data(id).coerce_unsized_info
}
pub fn get_impl_trait(&self,
id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> Option<ty::TraitRef<'tcx>> {
self.get_impl_data(id).trait_ref.map(|tr| tr.decode((self, tcx)))
}
/// Iterates over the language items in the given crate.
pub fn get_lang_items(&self, dep_graph: &DepGraph) -> Vec<(DefIndex, usize)> {
let dep_node = self.metadata_dep_node(GlobalMetaDataKind::LangItems);
self.root
.lang_items
.get(dep_graph, dep_node)
.decode(self)
.collect()
}
/// Iterates over each child of the given item.
pub fn each_child_of_item<F>(&self, id: DefIndex, mut callback: F, sess: &Session)
where F: FnMut(def::Export)
{
if let Some(ref proc_macros) = self.proc_macros {
if id == CRATE_DEF_INDEX {
for (id, &(name, ref ext)) in proc_macros.iter().enumerate() {
let def = Def::Macro(
DefId {
krate: self.cnum,
index: DefIndex::new(id + 1)
},
ext.kind()
);
let ident = Ident::with_empty_ctxt(name);
callback(def::Export { ident: ident, def: def, span: DUMMY_SP });
}
}
return
}
// Find the item.
let item = match self.maybe_entry(id) {
None => return,
Some(item) => item.decode((self, sess)),
};
// Iterate over all children.
let macros_only = self.dep_kind.get().macros_only();
for child_index in item.children.decode((self, sess)) {
if macros_only {
continue
}
// Get the item.
if let Some(child) = self.maybe_entry(child_index) {
let child = child.decode((self, sess));
match child.kind {
EntryKind::MacroDef(..) => {}
_ if macros_only => continue,
_ => {}
}
// Hand off the item to the callback.
match child.kind {
// FIXME(eddyb) Don't encode these in children.
EntryKind::ForeignMod => {
for child_index in child.children.decode((self, sess)) {
if let Some(def) = self.get_def(child_index) {
callback(def::Export {
def: def,
ident: Ident::with_empty_ctxt(self.item_name(child_index)),
span: self.entry(child_index).span.decode((self, sess)),
});
}
}
continue;
}
EntryKind::Impl(_) |
EntryKind::DefaultImpl(_) => continue,
_ => {}
}
let def_key = self.def_key(child_index);
let span = child.span.decode((self, sess));
if let (Some(def), Some(name)) =
(self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
let ident = Ident::with_empty_ctxt(name);
callback(def::Export { def: def, ident: ident, span: span });
// For non-reexport structs and variants add their constructors to children.
// Reexport lists automatically contain constructors when necessary.
match def {
Def::Struct(..) => {
if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
let ctor_kind = self.get_ctor_kind(child_index);
let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
callback(def::Export { def: ctor_def, ident: ident, span: span });
}
}
Def::Variant(def_id) => {
// Braced variants, unlike structs, generate unusable names in
// value namespace, they are reserved for possible future use.
let ctor_kind = self.get_ctor_kind(child_index);
let ctor_def = Def::VariantCtor(def_id, ctor_kind);
callback(def::Export { def: ctor_def, ident: ident, span: span });
}
_ => {}
}
}
}
}
if let EntryKind::Mod(data) = item.kind {
for exp in data.decode((self, sess)).reexports.decode((self, sess)) {
match exp.def {
Def::Macro(..) => {}
_ if macros_only => continue,
_ => {}
}
callback(exp);
}
}
}
pub fn item_body(&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
id: DefIndex)
-> &'tcx hir::Body {
assert!(!self.is_proc_macro(id));
let ast = self.entry(id).ast.unwrap();
let def_id = self.local_def_id(id);
let body = ast.decode(self).body.decode(self);
tcx.hir.intern_inlined_body(def_id, body)
}
pub fn item_body_tables(&self,
id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> &'tcx ty::TypeckTables<'tcx> {
let ast = self.entry(id).ast.unwrap().decode(self);
tcx.alloc_tables(ast.tables.decode((self, tcx)))
}
pub fn item_body_nested_bodies(&self, id: DefIndex) -> BTreeMap<hir::BodyId, hir::Body> {
self.entry(id).ast.into_iter().flat_map(|ast| {
ast.decode(self).nested_bodies.decode(self).map(|body| (body.id(), body))
}).collect()
}
pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool {
self.entry(id).ast.expect("const item missing `ast`")
.decode(self).rvalue_promotable_to_static
}
pub fn is_item_mir_available(&self, id: DefIndex) -> bool {
!self.is_proc_macro(id) &&
self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
}
pub fn maybe_get_optimized_mir(&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
id: DefIndex)
-> Option<Mir<'tcx>> {
match self.is_proc_macro(id) {
true => None,
false => self.entry(id).mir.map(|mir| mir.decode((self, tcx))),
}
}
pub fn mir_const_qualif(&self, id: DefIndex) -> u8 {
match self.entry(id).kind {
EntryKind::Const(qualif) |
EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif) |
EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif) => {
qualif
}
_ => bug!(),
}
}
pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem {
let item = self.entry(id);
let def_key = self.def_key(id);
let parent = self.local_def_id(def_key.parent.unwrap());
let name = def_key.disambiguated_data.data.get_opt_name().unwrap();
let (kind, container, has_self) = match item.kind {
EntryKind::AssociatedConst(container, _) => {
(ty::AssociatedKind::Const, container, false)
}
EntryKind::Method(data) => {
let data = data.decode(self);
(ty::AssociatedKind::Method, data.container, data.has_self)
}
EntryKind::AssociatedType(container) => {
(ty::AssociatedKind::Type, container, false)
}
_ => bug!("cannot get associated-item of `{:?}`", def_key)
};
ty::AssociatedItem {
name: name,
kind: kind,
vis: item.visibility.decode(self),
defaultness: container.defaultness(),
def_id: self.local_def_id(id),
container: container.with_def_id(parent),
method_has_self_argument: has_self
}
}
pub fn get_item_variances(&self, id: DefIndex) -> Vec<ty::Variance> {
self.entry(id).variances.decode(self).collect()
}
pub fn get_ctor_kind(&self, node_id: DefIndex) -> CtorKind {
match self.entry(node_id).kind {
EntryKind::Struct(data, _) |
EntryKind::Union(data, _) |
EntryKind::Variant(data) => data.decode(self).ctor_kind,
_ => CtorKind::Fictive,
}
}
pub fn get_struct_ctor_def_id(&self, node_id: DefIndex) -> Option<DefId> {
match self.entry(node_id).kind {
EntryKind::Struct(data, _) => {
data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
}
_ => None,
}
}
pub fn get_item_attrs(&self,
node_id: DefIndex,
dep_graph: &DepGraph) -> Rc<[ast::Attribute]> {
let (node_as, node_index) =
(node_id.address_space().index(), node_id.as_array_index());
if self.is_proc_macro(node_id) {
return Rc::new([]);
}
let dep_node = self.def_path_hash(node_id).to_dep_node(DepKind::MetaData);
dep_graph.read(dep_node);
if let Some(&Some(ref val)) =
self.attribute_cache.borrow()[node_as].get(node_index) {
return val.clone();
}
// The attributes for a tuple struct are attached to the definition, not the ctor;
// we assume that someone passing in a tuple struct ctor is actually wanting to
// look at the definition
let mut item = self.entry(node_id);
let def_key = self.def_key(node_id);
if def_key.disambiguated_data.data == DefPathData::StructCtor {
item = self.entry(def_key.parent.unwrap());
}
let result = Rc::__from_array(self.get_attributes(&item).into_boxed_slice());
let vec_ = &mut self.attribute_cache.borrow_mut()[node_as];
if vec_.len() < node_index + 1 {
vec_.resize(node_index + 1, None);
}
vec_[node_index] = Some(result.clone());
result
}
pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
self.entry(id)
.children
.decode(self)
.map(|index| self.item_name(index))
.collect()
}
fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
item.attributes
.decode(self)
.map(|mut attr| {
// Need new unique IDs: old thread-local IDs won't map to new threads.
attr.id = attr::mk_attr_id();
attr
})
.collect()
}
// Translate a DefId from the current compilation environment to a DefId
// for an external crate.
fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
if global == did.krate {
return Some(DefId {
krate: local,
index: did.index,
});
}
}
None
}
pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
self.entry(id)
.inherent_impls
.decode(self)
.map(|index| self.local_def_id(index))
.collect()
}
pub fn get_implementations_for_trait(&self,
filter: Option<DefId>,
dep_graph: &DepGraph,
result: &mut Vec<DefId>) {
// Do a reverse lookup beforehand to avoid touching the crate_num
// hash map in the loop below.
let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
Some(None) => return,
None if self.proc_macros.is_some() => return,
None => None,
};
let dep_node = self.metadata_dep_node(GlobalMetaDataKind::Impls);
if let Some(filter) = filter {
if let Some(impls) = self.trait_impls
.get(dep_graph, dep_node)
.get(&filter) {
result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
}
} else {
for impls in self.trait_impls.get(dep_graph, dep_node).values() {
result.extend(impls.decode(self).map(|idx| self.local_def_id(idx)));
}
}
}
pub fn get_trait_of_item(&self, id: DefIndex) -> Option<DefId> {
self.def_key(id).parent.and_then(|parent_index| {
match self.entry(parent_index).kind {
EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
_ => None,
}
})
}
pub fn get_native_libraries(&self,
dep_graph: &DepGraph)
-> Vec<NativeLibrary> {
let dep_node = self.metadata_dep_node(GlobalMetaDataKind::NativeLibraries);
self.root
.native_libraries
.get(dep_graph, dep_node)
.decode(self)
.collect()
}
pub fn get_dylib_dependency_formats(&self,
dep_graph: &DepGraph)
-> Vec<(CrateNum, LinkagePreference)> {
let dep_node =
self.metadata_dep_node(GlobalMetaDataKind::DylibDependencyFormats);
self.root