/
decoder.rs
1781 lines (1591 loc) · 63.4 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
#![allow(non_camel_case_types)]
use self::Family::*;
use astencode::decode_inlined_item;
use cstore::{self, crate_metadata};
use common::*;
use encoder::def_to_u64;
use index;
use tls_context;
use tydecode::TyDecoder;
use rustc::back::svh::Svh;
use rustc::front::map as hir_map;
use rustc::util::nodemap::FnvHashMap;
use rustc_front::hir;
use middle::cstore::{LOCAL_CRATE, FoundAst, InlinedItem, LinkagePreference};
use middle::cstore::{DefLike, DlDef, DlField, DlImpl, tls};
use middle::def::Def;
use middle::def_id::{DefId, DefIndex};
use middle::lang_items;
use rustc::ty::subst;
use rustc::ty::{ImplContainer, TraitContainer};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, VariantKind};
use rustc_const_math::ConstInt;
use rustc::mir;
use rustc::mir::visit::MutVisitor;
use std::cell::Cell;
use std::io::prelude::*;
use std::io;
use std::rc::Rc;
use std::str;
use rbml::reader;
use rbml;
use serialize::Decodable;
use syntax::attr;
use syntax::parse::token::{self, IdentInterner};
use syntax::ast;
use syntax::abi::Abi;
use syntax::codemap::{self, Span, BytePos, NO_EXPANSION};
use syntax::print::pprust;
use syntax::ptr::P;
pub type Cmd<'a> = &'a crate_metadata;
impl crate_metadata {
fn get_item(&self, item_id: DefIndex) -> Option<rbml::Doc> {
self.index.lookup_item(self.data(), item_id).map(|pos| {
reader::doc_at(self.data(), pos as usize).unwrap().doc
})
}
fn lookup_item(&self, item_id: DefIndex) -> rbml::Doc {
match self.get_item(item_id) {
None => bug!("lookup_item: id not found: {:?}", item_id),
Some(d) => d
}
}
}
pub fn load_index(data: &[u8]) -> index::Index {
let index = reader::get_doc(rbml::Doc::new(data), tag_index);
index::Index::from_rbml(index)
}
pub fn crate_rustc_version(data: &[u8]) -> Option<String> {
let doc = rbml::Doc::new(data);
reader::maybe_get_doc(doc, tag_rustc_version).map(|s| s.as_str())
}
pub fn load_xrefs(data: &[u8]) -> index::DenseIndex {
let index = reader::get_doc(rbml::Doc::new(data), tag_xref_index);
index::DenseIndex::from_buf(index.data, index.start, index.end)
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum Family {
ImmStatic, // c
MutStatic, // b
Fn, // f
StaticMethod, // F
Method, // h
Type, // y
Mod, // m
ForeignMod, // n
Enum, // t
Variant(VariantKind), // V, v, w
Impl, // i
DefaultImpl, // d
Trait, // I
Struct(VariantKind), // S, s, u
PublicField, // g
InheritedField, // N
Constant, // C
}
fn item_family(item: rbml::Doc) -> Family {
let fam = reader::get_doc(item, tag_items_data_item_family);
match reader::doc_as_u8(fam) as char {
'C' => Constant,
'c' => ImmStatic,
'b' => MutStatic,
'f' => Fn,
'F' => StaticMethod,
'h' => Method,
'y' => Type,
'm' => Mod,
'n' => ForeignMod,
't' => Enum,
'V' => Variant(VariantKind::Struct),
'v' => Variant(VariantKind::Tuple),
'w' => Variant(VariantKind::Unit),
'i' => Impl,
'd' => DefaultImpl,
'I' => Trait,
'S' => Struct(VariantKind::Struct),
's' => Struct(VariantKind::Tuple),
'u' => Struct(VariantKind::Unit),
'g' => PublicField,
'N' => InheritedField,
c => bug!("unexpected family char: {}", c)
}
}
fn item_visibility(item: rbml::Doc) -> hir::Visibility {
match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
None => hir::Public,
Some(visibility_doc) => {
match reader::doc_as_u8(visibility_doc) as char {
'y' => hir::Public,
'i' => hir::Inherited,
_ => bug!("unknown visibility character")
}
}
}
}
fn fn_constness(item: rbml::Doc) -> hir::Constness {
match reader::maybe_get_doc(item, tag_items_data_item_constness) {
None => hir::Constness::NotConst,
Some(constness_doc) => {
match reader::doc_as_u8(constness_doc) as char {
'c' => hir::Constness::Const,
'n' => hir::Constness::NotConst,
_ => bug!("unknown constness character")
}
}
}
}
fn item_defaultness(item: rbml::Doc) -> hir::Defaultness {
match reader::maybe_get_doc(item, tag_items_data_item_defaultness) {
None => hir::Defaultness::Default, // should occur only for default impls on traits
Some(defaultness_doc) => {
match reader::doc_as_u8(defaultness_doc) as char {
'd' => hir::Defaultness::Default,
'f' => hir::Defaultness::Final,
_ => bug!("unknown defaultness character")
}
}
}
}
fn item_sort(item: rbml::Doc) -> Option<char> {
reader::tagged_docs(item, tag_item_trait_item_sort).nth(0).map(|doc| {
doc.as_str_slice().as_bytes()[0] as char
})
}
fn item_symbol(item: rbml::Doc) -> String {
reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
}
fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
let id = reader::doc_as_u64(d);
let index = DefIndex::new((id & 0xFFFF_FFFF) as usize);
let def_id = DefId { krate: (id >> 32) as u32, index: index };
translate_def_id(cdata, def_id)
}
fn item_parent_item(cdata: Cmd, d: rbml::Doc) -> Option<DefId> {
reader::tagged_docs(d, tag_items_data_parent_item).nth(0).map(|did| {
translated_def_id(cdata, did)
})
}
fn item_require_parent_item(cdata: Cmd, d: rbml::Doc) -> DefId {
translated_def_id(cdata, reader::get_doc(d, tag_items_data_parent_item))
}
fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
translated_def_id(cdata, reader::get_doc(d, tag_def_id))
}
fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
reader::tagged_docs(d, tag_items_data_item_reexport)
}
fn variant_disr_val(d: rbml::Doc) -> Option<u64> {
reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
reader::with_doc_data(val_doc, |data| {
str::from_utf8(data).ok().and_then(|s| s.parse().ok())
})
})
}
fn doc_type<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
let tp = reader::get_doc(doc, tag_items_data_item_type);
TyDecoder::with_doc(tcx, cdata.cnum, tp,
&mut |did| translate_def_id(cdata, did))
.parse_ty()
}
fn maybe_doc_type<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Option<Ty<'tcx>> {
reader::maybe_get_doc(doc, tag_items_data_item_type).map(|tp| {
TyDecoder::with_doc(tcx, cdata.cnum, tp,
&mut |did| translate_def_id(cdata, did))
.parse_ty()
})
}
pub fn item_type<'tcx>(_item_id: DefId, item: rbml::Doc,
tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
doc_type(item, tcx, cdata)
}
fn doc_trait_ref<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd)
-> ty::TraitRef<'tcx> {
TyDecoder::with_doc(tcx, cdata.cnum, doc,
&mut |did| translate_def_id(cdata, did))
.parse_trait_ref()
}
fn item_trait_ref<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd)
-> ty::TraitRef<'tcx> {
let tp = reader::get_doc(doc, tag_item_trait_ref);
doc_trait_ref(tp, tcx, cdata)
}
fn item_path(item_doc: rbml::Doc) -> Vec<hir_map::PathElem> {
let path_doc = reader::get_doc(item_doc, tag_path);
reader::docs(path_doc).filter_map(|(tag, elt_doc)| {
if tag == tag_path_elem_mod {
let s = elt_doc.as_str_slice();
Some(hir_map::PathMod(token::intern(s)))
} else if tag == tag_path_elem_name {
let s = elt_doc.as_str_slice();
Some(hir_map::PathName(token::intern(s)))
} else {
// ignore tag_path_len element
None
}
}).collect()
}
fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Name {
let name = reader::get_doc(item, tag_paths_data_name);
let string = name.as_str_slice();
match intr.find(string) {
None => token::intern(string),
Some(val) => val,
}
}
fn family_to_variant_kind<'tcx>(family: Family) -> Option<ty::VariantKind> {
match family {
Struct(VariantKind::Struct) | Variant(VariantKind::Struct) =>
Some(ty::VariantKind::Struct),
Struct(VariantKind::Tuple) | Variant(VariantKind::Tuple) =>
Some(ty::VariantKind::Tuple),
Struct(VariantKind::Unit) | Variant(VariantKind::Unit) =>
Some(ty::VariantKind::Unit),
_ => None,
}
}
fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
let fam = item_family(item);
match fam {
Constant => {
// Check whether we have an associated const item.
match item_sort(item) {
Some('C') | Some('c') => {
DlDef(Def::AssociatedConst(did))
}
_ => {
// Regular const item.
DlDef(Def::Const(did))
}
}
}
ImmStatic => DlDef(Def::Static(did, false)),
MutStatic => DlDef(Def::Static(did, true)),
Struct(..) => DlDef(Def::Struct(did)),
Fn => DlDef(Def::Fn(did)),
Method | StaticMethod => {
DlDef(Def::Method(did))
}
Type => {
if item_sort(item) == Some('t') {
let trait_did = item_require_parent_item(cdata, item);
DlDef(Def::AssociatedTy(trait_did, did))
} else {
DlDef(Def::TyAlias(did))
}
}
Mod => DlDef(Def::Mod(did)),
ForeignMod => DlDef(Def::ForeignMod(did)),
Variant(..) => {
let enum_did = item_require_parent_item(cdata, item);
DlDef(Def::Variant(enum_did, did))
}
Trait => DlDef(Def::Trait(did)),
Enum => DlDef(Def::Enum(did)),
Impl | DefaultImpl => DlImpl(did),
PublicField | InheritedField => DlField,
}
}
fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
if reader::doc_as_u8(unsafety_doc) != 0 {
hir::Unsafety::Unsafe
} else {
hir::Unsafety::Normal
}
}
fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
reader::doc_as_u8(paren_sugar_doc) != 0
}
fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
let polarity_doc = reader::get_doc(item_doc, tag_polarity);
if reader::doc_as_u8(polarity_doc) != 0 {
hir::ImplPolarity::Negative
} else {
hir::ImplPolarity::Positive
}
}
fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
reader::tagged_docs(names_doc, tag_associated_type_name)
.map(|name_doc| token::intern(name_doc.as_str_slice()))
.collect()
}
pub fn get_trait_def<'tcx>(cdata: Cmd,
item_id: DefIndex,
tcx: &TyCtxt<'tcx>) -> ty::TraitDef<'tcx>
{
let item_doc = cdata.lookup_item(item_id);
let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
let unsafety = parse_unsafety(item_doc);
let associated_type_names = parse_associated_type_names(item_doc);
let paren_sugar = parse_paren_sugar(item_doc);
ty::TraitDef::new(unsafety,
paren_sugar,
generics,
item_trait_ref(item_doc, tcx, cdata),
associated_type_names)
}
pub fn get_adt_def<'tcx>(intr: &IdentInterner,
cdata: Cmd,
item_id: DefIndex,
tcx: &TyCtxt<'tcx>) -> ty::AdtDefMaster<'tcx>
{
fn expect_variant_kind(family: Family) -> ty::VariantKind {
match family_to_variant_kind(family) {
Some(kind) => kind,
_ => bug!("unexpected family: {:?}", family),
}
}
fn get_enum_variants<'tcx>(intr: &IdentInterner,
cdata: Cmd,
doc: rbml::Doc) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
let mut disr_val = 0;
reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
let did = translated_def_id(cdata, p);
let item = cdata.lookup_item(did.index);
if let Some(disr) = variant_disr_val(item) {
disr_val = disr;
}
let disr = disr_val;
disr_val = disr_val.wrapping_add(1);
ty::VariantDefData {
did: did,
name: item_name(intr, item),
fields: get_variant_fields(intr, cdata, item),
disr_val: ConstInt::Infer(disr),
kind: expect_variant_kind(item_family(item)),
}
}).collect()
}
fn get_variant_fields<'tcx>(intr: &IdentInterner,
cdata: Cmd,
doc: rbml::Doc) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
let mut index = 0;
reader::tagged_docs(doc, tag_item_field).map(|f| {
let ff = item_family(f);
match ff {
PublicField | InheritedField => {},
_ => bug!("expected field, found {:?}", ff)
};
ty::FieldDefData::new(item_def_id(f, cdata),
item_name(intr, f),
struct_field_family_to_visibility(ff))
}).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
let ff = item_family(f);
let name = intr.intern(&index.to_string());
index += 1;
ty::FieldDefData::new(item_def_id(f, cdata), name,
struct_field_family_to_visibility(ff))
})).collect()
}
fn get_struct_variant<'tcx>(intr: &IdentInterner,
cdata: Cmd,
doc: rbml::Doc,
did: DefId) -> ty::VariantDefData<'tcx, 'tcx> {
ty::VariantDefData {
did: did,
name: item_name(intr, doc),
fields: get_variant_fields(intr, cdata, doc),
disr_val: ConstInt::Infer(0),
kind: expect_variant_kind(item_family(doc)),
}
}
let doc = cdata.lookup_item(item_id);
let did = DefId { krate: cdata.cnum, index: item_id };
let (kind, variants) = match item_family(doc) {
Enum => {
(ty::AdtKind::Enum,
get_enum_variants(intr, cdata, doc))
}
Struct(..) => {
let ctor_did =
reader::maybe_get_doc(doc, tag_items_data_item_struct_ctor).
map_or(did, |ctor_doc| translated_def_id(cdata, ctor_doc));
(ty::AdtKind::Struct,
vec![get_struct_variant(intr, cdata, doc, ctor_did)])
}
_ => bug!("get_adt_def called on a non-ADT {:?} - {:?}",
item_family(doc), did)
};
let adt = tcx.intern_adt_def(did, kind, variants);
// this needs to be done *after* the variant is interned,
// to support recursive structures
for variant in &adt.variants {
if variant.kind() == ty::VariantKind::Tuple &&
adt.adt_kind() == ty::AdtKind::Enum {
// tuple-like enum variant fields aren't real items - get the types
// from the ctor.
debug!("evaluating the ctor-type of {:?}",
variant.name);
let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
debug!("evaluating the ctor-type of {:?}.. {:?}",
variant.name,
ctor_ty);
let field_tys = match ctor_ty.sty {
ty::TyFnDef(_, _, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
ref inputs, ..
}), ..}) => {
// tuple-struct constructors don't have escaping regions
assert!(!inputs.has_escaping_regions());
inputs
},
_ => bug!("tuple-variant ctor is not an ADT")
};
for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
field.fulfill_ty(ty);
}
} else {
for field in &variant.fields {
debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
let ty = get_type(cdata, field.did.index, tcx).ty;
field.fulfill_ty(ty);
debug!("evaluating the type of {:?}::{:?}: {:?}",
variant.name, field.name, ty);
}
}
}
adt
}
pub fn get_predicates<'tcx>(cdata: Cmd,
item_id: DefIndex,
tcx: &TyCtxt<'tcx>)
-> ty::GenericPredicates<'tcx>
{
let item_doc = cdata.lookup_item(item_id);
doc_predicates(item_doc, tcx, cdata, tag_item_generics)
}
pub fn get_super_predicates<'tcx>(cdata: Cmd,
item_id: DefIndex,
tcx: &TyCtxt<'tcx>)
-> ty::GenericPredicates<'tcx>
{
let item_doc = cdata.lookup_item(item_id);
doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
}
pub fn get_type<'tcx>(cdata: Cmd, id: DefIndex, tcx: &TyCtxt<'tcx>)
-> ty::TypeScheme<'tcx>
{
let item_doc = cdata.lookup_item(id);
let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
cdata);
let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
ty::TypeScheme {
generics: generics,
ty: t
}
}
pub fn get_stability(cdata: Cmd, id: DefIndex) -> Option<attr::Stability> {
let item = cdata.lookup_item(id);
reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
let mut decoder = reader::Decoder::new(doc);
Decodable::decode(&mut decoder).unwrap()
})
}
pub fn get_deprecation(cdata: Cmd, id: DefIndex) -> Option<attr::Deprecation> {
let item = cdata.lookup_item(id);
reader::maybe_get_doc(item, tag_items_data_item_deprecation).map(|doc| {
let mut decoder = reader::Decoder::new(doc);
Decodable::decode(&mut decoder).unwrap()
})
}
pub fn get_visibility(cdata: Cmd, id: DefIndex) -> hir::Visibility {
item_visibility(cdata.lookup_item(id))
}
pub fn get_parent_impl(cdata: Cmd, id: DefIndex) -> Option<DefId> {
let item = cdata.lookup_item(id);
reader::maybe_get_doc(item, tag_items_data_parent_impl).map(|doc| {
translated_def_id(cdata, doc)
})
}
pub fn get_repr_attrs(cdata: Cmd, id: DefIndex) -> Vec<attr::ReprAttr> {
let item = cdata.lookup_item(id);
match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
let mut decoder = reader::Decoder::new(doc);
Decodable::decode(&mut decoder).unwrap()
}) {
Some(attrs) => attrs,
None => Vec::new(),
}
}
pub fn get_impl_polarity<'tcx>(cdata: Cmd,
id: DefIndex)
-> Option<hir::ImplPolarity>
{
let item_doc = cdata.lookup_item(id);
let fam = item_family(item_doc);
match fam {
Family::Impl => {
Some(parse_polarity(item_doc))
}
_ => None
}
}
pub fn get_custom_coerce_unsized_kind<'tcx>(
cdata: Cmd,
id: DefIndex)
-> Option<ty::adjustment::CustomCoerceUnsized>
{
let item_doc = cdata.lookup_item(id);
reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
let mut decoder = reader::Decoder::new(kind_doc);
Decodable::decode(&mut decoder).unwrap()
})
}
pub fn get_impl_trait<'tcx>(cdata: Cmd,
id: DefIndex,
tcx: &TyCtxt<'tcx>)
-> Option<ty::TraitRef<'tcx>>
{
let item_doc = cdata.lookup_item(id);
let fam = item_family(item_doc);
match fam {
Family::Impl | Family::DefaultImpl => {
reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
doc_trait_ref(tp, tcx, cdata)
})
}
_ => None
}
}
pub fn get_symbol(cdata: Cmd, id: DefIndex) -> String {
return item_symbol(cdata.lookup_item(id));
}
/// If you have a crate_metadata, call get_symbol instead
pub fn get_symbol_from_buf(data: &[u8], id: DefIndex) -> String {
let index = load_index(data);
let pos = index.lookup_item(data, id).unwrap();
let doc = reader::doc_at(data, pos as usize).unwrap().doc;
item_symbol(doc)
}
/// Iterates over the language items in the given crate.
pub fn each_lang_item<F>(cdata: Cmd, mut f: F) -> bool where
F: FnMut(DefIndex, usize) -> bool,
{
let root = rbml::Doc::new(cdata.data());
let lang_items = reader::get_doc(root, tag_lang_items);
reader::tagged_docs(lang_items, tag_lang_items_item).all(|item_doc| {
let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
let id = reader::doc_as_u32(id_doc) as usize;
let index_doc = reader::get_doc(item_doc, tag_lang_items_item_index);
let index = DefIndex::from_u32(reader::doc_as_u32(index_doc));
f(index, id)
})
}
fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
cdata: Cmd,
item_doc: rbml::Doc,
mut get_crate_data: G,
mut callback: F) where
F: FnMut(DefLike, ast::Name, hir::Visibility),
G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
{
// Iterate over all children.
for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
let child_def_id = translated_def_id(cdata, child_info_doc);
// This item may be in yet another crate if it was the child of a
// reexport.
let crate_data = if child_def_id.krate == cdata.cnum {
None
} else {
Some(get_crate_data(child_def_id.krate))
};
let crate_data = match crate_data {
Some(ref cdata) => &**cdata,
None => cdata
};
// Get the item.
match crate_data.get_item(child_def_id.index) {
None => {}
Some(child_item_doc) => {
// Hand off the item to the callback.
let child_name = item_name(&intr, child_item_doc);
let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
let visibility = item_visibility(child_item_doc);
callback(def_like, child_name, visibility);
}
}
}
// As a special case, iterate over all static methods of
// associated implementations too. This is a bit of a botch.
// --pcwalton
for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
tag_items_data_item_inherent_impl) {
let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.index) {
for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
tag_item_impl_item) {
let impl_item_def_id = item_def_id(impl_item_def_id_doc,
cdata);
if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.index) {
if let StaticMethod = item_family(impl_method_doc) {
// Hand off the static method to the callback.
let static_method_name = item_name(&intr, impl_method_doc);
let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
impl_item_def_id);
callback(static_method_def_like,
static_method_name,
item_visibility(impl_method_doc));
}
}
}
}
}
for reexport_doc in reexports(item_doc) {
let def_id_doc = reader::get_doc(reexport_doc,
tag_items_data_item_reexport_def_id);
let child_def_id = translated_def_id(cdata, def_id_doc);
let name_doc = reader::get_doc(reexport_doc,
tag_items_data_item_reexport_name);
let name = name_doc.as_str_slice();
// This reexport may be in yet another crate.
let crate_data = if child_def_id.krate == cdata.cnum {
None
} else {
Some(get_crate_data(child_def_id.krate))
};
let crate_data = match crate_data {
Some(ref cdata) => &**cdata,
None => cdata
};
// Get the item.
if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
// Hand off the item to the callback.
let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
// These items have a public visibility because they're part of
// a public re-export.
callback(def_like, token::intern(name), hir::Public);
}
}
}
/// Iterates over each child of the given item.
pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
cdata: Cmd,
id: DefIndex,
get_crate_data: G,
callback: F) where
F: FnMut(DefLike, ast::Name, hir::Visibility),
G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
{
// Find the item.
let item_doc = match cdata.get_item(id) {
None => return,
Some(item_doc) => item_doc,
};
each_child_of_item_or_crate(intr,
cdata,
item_doc,
get_crate_data,
callback)
}
/// Iterates over all the top-level crate items.
pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
cdata: Cmd,
get_crate_data: G,
callback: F) where
F: FnMut(DefLike, ast::Name, hir::Visibility),
G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
{
let root_doc = rbml::Doc::new(cdata.data());
let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
let crate_items_doc = reader::get_doc(misc_info_doc,
tag_misc_info_crate_items);
each_child_of_item_or_crate(intr,
cdata,
crate_items_doc,
get_crate_data,
callback)
}
pub fn get_item_path(cdata: Cmd, id: DefIndex) -> Vec<hir_map::PathElem> {
item_path(cdata.lookup_item(id))
}
pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: DefIndex) -> ast::Name {
item_name(intr, cdata.lookup_item(id))
}
pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &TyCtxt<'tcx>, id: DefIndex)
-> FoundAst<'tcx> {
debug!("Looking up item: {:?}", id);
let item_doc = cdata.lookup_item(id);
let item_did = item_def_id(item_doc, cdata);
let parent_def_id = DefId {
krate: cdata.cnum,
index: def_key(cdata, id).parent.unwrap()
};
let mut parent_path = item_path(item_doc);
parent_path.pop();
let mut parent_def_path = def_path(cdata, id);
parent_def_path.data.pop();
if let Some(ast_doc) = reader::maybe_get_doc(item_doc, tag_ast as usize) {
let ii = decode_inlined_item(cdata,
tcx,
parent_path,
parent_def_path,
parent_def_id,
ast_doc,
item_did);
return FoundAst::Found(ii);
} else if let Some(parent_did) = item_parent_item(cdata, item_doc) {
// Remove the last element from the paths, since we are now
// trying to inline the parent.
let grandparent_def_id = DefId {
krate: cdata.cnum,
index: def_key(cdata, parent_def_id.index).parent.unwrap()
};
let mut grandparent_path = parent_path;
grandparent_path.pop();
let mut grandparent_def_path = parent_def_path;
grandparent_def_path.data.pop();
let parent_doc = cdata.lookup_item(parent_did.index);
if let Some(ast_doc) = reader::maybe_get_doc(parent_doc, tag_ast as usize) {
let ii = decode_inlined_item(cdata,
tcx,
grandparent_path,
grandparent_def_path,
grandparent_def_id,
ast_doc,
parent_did);
if let &InlinedItem::Item(ref i) = ii {
return FoundAst::FoundParent(parent_did, i);
}
}
}
FoundAst::NotFound
}
pub fn is_item_mir_available<'tcx>(cdata: Cmd, id: DefIndex) -> bool {
if let Some(item_doc) = cdata.get_item(id) {
return reader::maybe_get_doc(item_doc, tag_mir as usize).is_some();
}
false
}
pub fn maybe_get_item_mir<'tcx>(cdata: Cmd,
tcx: &TyCtxt<'tcx>,
id: DefIndex)
-> Option<mir::repr::Mir<'tcx>> {
let item_doc = cdata.lookup_item(id);
return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
let dcx = tls_context::DecodingContext {
crate_metadata: cdata,
tcx: tcx,
};
let mut decoder = reader::Decoder::new(mir_doc);
let mut mir = decoder.read_opaque(|opaque_decoder, _| {
tls::enter_decoding_context(&dcx, opaque_decoder, |_, opaque_decoder| {
Decodable::decode(opaque_decoder)
})
}).unwrap();
assert!(decoder.position() == mir_doc.end);
let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
crate_metadata: cdata,
codemap: tcx.sess.codemap(),
last_filemap_index_hint: Cell::new(0),
};
def_id_and_span_translator.visit_mir(&mut mir);
mir
});
struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
crate_metadata: Cmd<'cdata>,
codemap: &'codemap codemap::CodeMap,
last_filemap_index_hint: Cell<usize>
}
impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
for MirDefIdAndSpanTranslator<'cdata, 'codemap>
{
fn visit_def_id(&mut self, def_id: &mut DefId) {
*def_id = translate_def_id(self.crate_metadata, *def_id);
}
fn visit_span(&mut self, span: &mut Span) {
*span = translate_span(self.crate_metadata,
self.codemap,
&self.last_filemap_index_hint,
*span);
}
}
}
fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
fn get_mutability(ch: u8) -> hir::Mutability {
match ch as char {
'i' => hir::MutImmutable,
'm' => hir::MutMutable,
_ => bug!("unknown mutability character: `{}`", ch as char),
}
}
let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
let string = explicit_self_doc.as_str_slice();
let explicit_self_kind = string.as_bytes()[0];
match explicit_self_kind as char {
's' => ty::ExplicitSelfCategory::Static,
'v' => ty::ExplicitSelfCategory::ByValue,
'~' => ty::ExplicitSelfCategory::ByBox,
// FIXME(#4846) expl. region
'&' => {
ty::ExplicitSelfCategory::ByReference(
ty::ReEmpty,
get_mutability(string.as_bytes()[1]))
}
_ => bug!("unknown self type code: `{}`", explicit_self_kind as char)
}
}
/// Returns the def IDs of all the items in the given implementation.
pub fn get_impl_items(cdata: Cmd, impl_id: DefIndex)
-> Vec<ty::ImplOrTraitItemId> {
reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
let def_id = item_def_id(doc, cdata);
match item_sort(doc) {
Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
Some('t') => ty::TypeTraitItemId(def_id),
_ => bug!("unknown impl item sort"),
}
}).collect()
}
pub fn get_trait_name(intr: Rc<IdentInterner>,
cdata: Cmd,
id: DefIndex)
-> ast::Name {
let doc = cdata.lookup_item(id);
item_name(&intr, doc)
}
pub fn is_static_method(cdata: Cmd, id: DefIndex) -> bool {
let doc = cdata.lookup_item(id);
match item_sort(doc) {
Some('r') | Some('p') => {
get_explicit_self(doc) == ty::ExplicitSelfCategory::Static
}
_ => false
}
}
pub fn get_impl_or_trait_item<'tcx>(intr: Rc<IdentInterner>,
cdata: Cmd,
id: DefIndex,
tcx: &TyCtxt<'tcx>)
-> Option<ty::ImplOrTraitItem<'tcx>> {
let item_doc = cdata.lookup_item(id);
let def_id = item_def_id(item_doc, cdata);
let container_id = if let Some(id) = item_parent_item(cdata, item_doc) {
id
} else {
return None;
};
let container_doc = cdata.lookup_item(container_id.index);
let container = match item_family(container_doc) {
Trait => TraitContainer(container_id),
_ => ImplContainer(container_id),
};
let name = item_name(&intr, item_doc);
let vis = item_visibility(item_doc);
let defaultness = item_defaultness(item_doc);
Some(match item_sort(item_doc) {
sort @ Some('C') | sort @ Some('c') => {
let ty = doc_type(item_doc, tcx, cdata);
ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
name: name,
ty: ty,
vis: vis,
defaultness: defaultness,
def_id: def_id,