]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/decoder.rs
track def-id for inlined items
[rust.git] / src / librustc_metadata / decoder.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Decoding metadata from a single crate's metadata
12
13 #![allow(non_camel_case_types)]
14
15 use self::Family::*;
16
17 use astencode::decode_inlined_item;
18 use cstore::{self, crate_metadata};
19 use common::*;
20 use encoder::def_to_u64;
21 use index;
22 use tls_context;
23 use tydecode::TyDecoder;
24
25 use rustc::back::svh::Svh;
26 use rustc::front::map as hir_map;
27 use rustc::util::nodemap::FnvHashMap;
28 use rustc_front::hir;
29
30 use middle::cstore::{LOCAL_CRATE, FoundAst, InlinedItem, LinkagePreference};
31 use middle::cstore::{DefLike, DlDef, DlField, DlImpl, tls};
32 use middle::def::Def;
33 use middle::def_id::{DefId, DefIndex};
34 use middle::lang_items;
35 use middle::subst;
36 use middle::ty::{ImplContainer, TraitContainer};
37 use middle::ty::{self, Ty, TyCtxt, TypeFoldable, VariantKind};
38
39 use rustc_const_eval::ConstInt;
40
41 use rustc::mir;
42 use rustc::mir::visit::MutVisitor;
43
44 use std::cell::Cell;
45 use std::io::prelude::*;
46 use std::io;
47 use std::rc::Rc;
48 use std::str;
49
50 use rbml::reader;
51 use rbml;
52 use serialize::Decodable;
53 use syntax::attr;
54 use syntax::parse::token::{self, IdentInterner};
55 use syntax::ast;
56 use syntax::abi::Abi;
57 use syntax::codemap::{self, Span, BytePos, NO_EXPANSION};
58 use syntax::print::pprust;
59 use syntax::ptr::P;
60
61
62 pub type Cmd<'a> = &'a crate_metadata;
63
64 impl crate_metadata {
65     fn get_item(&self, item_id: DefIndex) -> Option<rbml::Doc> {
66         self.index.lookup_item(self.data(), item_id).map(|pos| {
67             reader::doc_at(self.data(), pos as usize).unwrap().doc
68         })
69     }
70
71     fn lookup_item(&self, item_id: DefIndex) -> rbml::Doc {
72         match self.get_item(item_id) {
73             None => panic!("lookup_item: id not found: {:?}", item_id),
74             Some(d) => d
75         }
76     }
77 }
78
79 pub fn load_index(data: &[u8]) -> index::Index {
80     let index = reader::get_doc(rbml::Doc::new(data), tag_index);
81     index::Index::from_rbml(index)
82 }
83
84 pub fn crate_rustc_version(data: &[u8]) -> Option<String> {
85     let doc = rbml::Doc::new(data);
86     reader::maybe_get_doc(doc, tag_rustc_version).map(|s| s.as_str())
87 }
88
89 pub fn load_xrefs(data: &[u8]) -> index::DenseIndex {
90     let index = reader::get_doc(rbml::Doc::new(data), tag_xref_index);
91     index::DenseIndex::from_buf(index.data, index.start, index.end)
92 }
93
94 #[derive(Clone, Copy, Debug, PartialEq)]
95 enum Family {
96     ImmStatic,             // c
97     MutStatic,             // b
98     Fn,                    // f
99     StaticMethod,          // F
100     Method,                // h
101     Type,                  // y
102     Mod,                   // m
103     ForeignMod,            // n
104     Enum,                  // t
105     Variant(VariantKind),  // V, v, w
106     Impl,                  // i
107     DefaultImpl,           // d
108     Trait,                 // I
109     Struct(VariantKind),   // S, s, u
110     PublicField,           // g
111     InheritedField,        // N
112     Constant,              // C
113 }
114
115 fn item_family(item: rbml::Doc) -> Family {
116     let fam = reader::get_doc(item, tag_items_data_item_family);
117     match reader::doc_as_u8(fam) as char {
118       'C' => Constant,
119       'c' => ImmStatic,
120       'b' => MutStatic,
121       'f' => Fn,
122       'F' => StaticMethod,
123       'h' => Method,
124       'y' => Type,
125       'm' => Mod,
126       'n' => ForeignMod,
127       't' => Enum,
128       'V' => Variant(VariantKind::Struct),
129       'v' => Variant(VariantKind::Tuple),
130       'w' => Variant(VariantKind::Unit),
131       'i' => Impl,
132       'd' => DefaultImpl,
133       'I' => Trait,
134       'S' => Struct(VariantKind::Struct),
135       's' => Struct(VariantKind::Tuple),
136       'u' => Struct(VariantKind::Unit),
137       'g' => PublicField,
138       'N' => InheritedField,
139        c => panic!("unexpected family char: {}", c)
140     }
141 }
142
143 fn item_visibility(item: rbml::Doc) -> hir::Visibility {
144     match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
145         None => hir::Public,
146         Some(visibility_doc) => {
147             match reader::doc_as_u8(visibility_doc) as char {
148                 'y' => hir::Public,
149                 'i' => hir::Inherited,
150                 _ => panic!("unknown visibility character")
151             }
152         }
153     }
154 }
155
156 fn fn_constness(item: rbml::Doc) -> hir::Constness {
157     match reader::maybe_get_doc(item, tag_items_data_item_constness) {
158         None => hir::Constness::NotConst,
159         Some(constness_doc) => {
160             match reader::doc_as_u8(constness_doc) as char {
161                 'c' => hir::Constness::Const,
162                 'n' => hir::Constness::NotConst,
163                 _ => panic!("unknown constness character")
164             }
165         }
166     }
167 }
168
169 fn item_defaultness(item: rbml::Doc) -> hir::Defaultness {
170     match reader::maybe_get_doc(item, tag_items_data_item_defaultness) {
171         None => hir::Defaultness::Default, // should occur only for default impls on traits
172         Some(defaultness_doc) => {
173             match reader::doc_as_u8(defaultness_doc) as char {
174                 'd' => hir::Defaultness::Default,
175                 'f' => hir::Defaultness::Final,
176                 _ => panic!("unknown defaultness character")
177             }
178         }
179     }
180 }
181
182 fn item_sort(item: rbml::Doc) -> Option<char> {
183     reader::tagged_docs(item, tag_item_trait_item_sort).nth(0).map(|doc| {
184         doc.as_str_slice().as_bytes()[0] as char
185     })
186 }
187
188 fn item_symbol(item: rbml::Doc) -> String {
189     reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
190 }
191
192 fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
193     let id = reader::doc_as_u64(d);
194     let index = DefIndex::new((id & 0xFFFF_FFFF) as usize);
195     let def_id = DefId { krate: (id >> 32) as u32, index: index };
196     translate_def_id(cdata, def_id)
197 }
198
199 fn item_parent_item(cdata: Cmd, d: rbml::Doc) -> Option<DefId> {
200     reader::tagged_docs(d, tag_items_data_parent_item).nth(0).map(|did| {
201         translated_def_id(cdata, did)
202     })
203 }
204
205 fn item_require_parent_item(cdata: Cmd, d: rbml::Doc) -> DefId {
206     translated_def_id(cdata, reader::get_doc(d, tag_items_data_parent_item))
207 }
208
209 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
210     translated_def_id(cdata, reader::get_doc(d, tag_def_id))
211 }
212
213 fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
214     reader::tagged_docs(d, tag_items_data_item_reexport)
215 }
216
217 fn variant_disr_val(d: rbml::Doc) -> Option<u64> {
218     reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
219         reader::with_doc_data(val_doc, |data| {
220             str::from_utf8(data).ok().and_then(|s| s.parse().ok())
221         })
222     })
223 }
224
225 fn doc_type<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
226     let tp = reader::get_doc(doc, tag_items_data_item_type);
227     TyDecoder::with_doc(tcx, cdata.cnum, tp,
228                         &mut |did| translate_def_id(cdata, did))
229         .parse_ty()
230 }
231
232 fn maybe_doc_type<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Option<Ty<'tcx>> {
233     reader::maybe_get_doc(doc, tag_items_data_item_type).map(|tp| {
234         TyDecoder::with_doc(tcx, cdata.cnum, tp,
235                             &mut |did| translate_def_id(cdata, did))
236             .parse_ty()
237     })
238 }
239
240 pub fn item_type<'tcx>(_item_id: DefId, item: rbml::Doc,
241                        tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
242     doc_type(item, tcx, cdata)
243 }
244
245 fn doc_trait_ref<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd)
246                        -> ty::TraitRef<'tcx> {
247     TyDecoder::with_doc(tcx, cdata.cnum, doc,
248                         &mut |did| translate_def_id(cdata, did))
249         .parse_trait_ref()
250 }
251
252 fn item_trait_ref<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd)
253                         -> ty::TraitRef<'tcx> {
254     let tp = reader::get_doc(doc, tag_item_trait_ref);
255     doc_trait_ref(tp, tcx, cdata)
256 }
257
258 fn item_path(item_doc: rbml::Doc) -> Vec<hir_map::PathElem> {
259     let path_doc = reader::get_doc(item_doc, tag_path);
260     reader::docs(path_doc).filter_map(|(tag, elt_doc)| {
261         if tag == tag_path_elem_mod {
262             let s = elt_doc.as_str_slice();
263             Some(hir_map::PathMod(token::intern(s)))
264         } else if tag == tag_path_elem_name {
265             let s = elt_doc.as_str_slice();
266             Some(hir_map::PathName(token::intern(s)))
267         } else {
268             // ignore tag_path_len element
269             None
270         }
271     }).collect()
272 }
273
274 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Name {
275     let name = reader::get_doc(item, tag_paths_data_name);
276     let string = name.as_str_slice();
277     match intr.find(string) {
278         None => token::intern(string),
279         Some(val) => val,
280     }
281 }
282
283 fn family_to_variant_kind<'tcx>(family: Family) -> Option<ty::VariantKind> {
284     match family {
285         Struct(VariantKind::Struct) | Variant(VariantKind::Struct) =>
286             Some(ty::VariantKind::Struct),
287         Struct(VariantKind::Tuple) | Variant(VariantKind::Tuple) =>
288             Some(ty::VariantKind::Tuple),
289         Struct(VariantKind::Unit) | Variant(VariantKind::Unit) =>
290             Some(ty::VariantKind::Unit),
291         _ => None,
292     }
293 }
294
295 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
296     let fam = item_family(item);
297     match fam {
298         Constant  => {
299             // Check whether we have an associated const item.
300             match item_sort(item) {
301                 Some('C') | Some('c') => {
302                     DlDef(Def::AssociatedConst(did))
303                 }
304                 _ => {
305                     // Regular const item.
306                     DlDef(Def::Const(did))
307                 }
308             }
309         }
310         ImmStatic => DlDef(Def::Static(did, false)),
311         MutStatic => DlDef(Def::Static(did, true)),
312         Struct(..) => DlDef(Def::Struct(did)),
313         Fn        => DlDef(Def::Fn(did)),
314         Method | StaticMethod => {
315             DlDef(Def::Method(did))
316         }
317         Type => {
318             if item_sort(item) == Some('t') {
319                 let trait_did = item_require_parent_item(cdata, item);
320                 DlDef(Def::AssociatedTy(trait_did, did))
321             } else {
322                 DlDef(Def::TyAlias(did))
323             }
324         }
325         Mod => DlDef(Def::Mod(did)),
326         ForeignMod => DlDef(Def::ForeignMod(did)),
327         Variant(..) => {
328             let enum_did = item_require_parent_item(cdata, item);
329             DlDef(Def::Variant(enum_did, did))
330         }
331         Trait => DlDef(Def::Trait(did)),
332         Enum => DlDef(Def::Enum(did)),
333         Impl | DefaultImpl => DlImpl(did),
334         PublicField | InheritedField => DlField,
335     }
336 }
337
338 fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
339     let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
340     if reader::doc_as_u8(unsafety_doc) != 0 {
341         hir::Unsafety::Unsafe
342     } else {
343         hir::Unsafety::Normal
344     }
345 }
346
347 fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
348     let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
349     reader::doc_as_u8(paren_sugar_doc) != 0
350 }
351
352 fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
353     let polarity_doc = reader::get_doc(item_doc, tag_polarity);
354     if reader::doc_as_u8(polarity_doc) != 0 {
355         hir::ImplPolarity::Negative
356     } else {
357         hir::ImplPolarity::Positive
358     }
359 }
360
361 fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
362     let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
363     reader::tagged_docs(names_doc, tag_associated_type_name)
364         .map(|name_doc| token::intern(name_doc.as_str_slice()))
365         .collect()
366 }
367
368 pub fn get_trait_def<'tcx>(cdata: Cmd,
369                            item_id: DefIndex,
370                            tcx: &TyCtxt<'tcx>) -> ty::TraitDef<'tcx>
371 {
372     let item_doc = cdata.lookup_item(item_id);
373     let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
374     let unsafety = parse_unsafety(item_doc);
375     let associated_type_names = parse_associated_type_names(item_doc);
376     let paren_sugar = parse_paren_sugar(item_doc);
377
378     ty::TraitDef::new(unsafety,
379                       paren_sugar,
380                       generics,
381                       item_trait_ref(item_doc, tcx, cdata),
382                       associated_type_names)
383 }
384
385 pub fn get_adt_def<'tcx>(intr: &IdentInterner,
386                          cdata: Cmd,
387                          item_id: DefIndex,
388                          tcx: &TyCtxt<'tcx>) -> ty::AdtDefMaster<'tcx>
389 {
390     fn expect_variant_kind<'tcx>(family: Family, tcx: &TyCtxt<'tcx>) -> ty::VariantKind {
391         match family_to_variant_kind(family) {
392             Some(kind) => kind,
393             _ => tcx.sess.bug(&format!("unexpected family: {:?}", family)),
394         }
395     }
396     fn get_enum_variants<'tcx>(intr: &IdentInterner,
397                                cdata: Cmd,
398                                doc: rbml::Doc,
399                                tcx: &TyCtxt<'tcx>) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
400         let mut disr_val = 0;
401         reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
402             let did = translated_def_id(cdata, p);
403             let item = cdata.lookup_item(did.index);
404
405             if let Some(disr) = variant_disr_val(item) {
406                 disr_val = disr;
407             }
408             let disr = disr_val;
409             disr_val = disr_val.wrapping_add(1);
410
411             ty::VariantDefData {
412                 did: did,
413                 name: item_name(intr, item),
414                 fields: get_variant_fields(intr, cdata, item, tcx),
415                 disr_val: ConstInt::Infer(disr),
416                 kind: expect_variant_kind(item_family(item), tcx),
417             }
418         }).collect()
419     }
420     fn get_variant_fields<'tcx>(intr: &IdentInterner,
421                                 cdata: Cmd,
422                                 doc: rbml::Doc,
423                                 tcx: &TyCtxt<'tcx>) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
424         let mut index = 0;
425         reader::tagged_docs(doc, tag_item_field).map(|f| {
426             let ff = item_family(f);
427             match ff {
428                 PublicField | InheritedField => {},
429                 _ => tcx.sess.bug(&format!("expected field, found {:?}", ff))
430             };
431             ty::FieldDefData::new(item_def_id(f, cdata),
432                                   item_name(intr, f),
433                                   struct_field_family_to_visibility(ff))
434         }).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
435             let ff = item_family(f);
436             let name = intr.intern(&index.to_string());
437             index += 1;
438             ty::FieldDefData::new(item_def_id(f, cdata), name,
439                                   struct_field_family_to_visibility(ff))
440         })).collect()
441     }
442     fn get_struct_variant<'tcx>(intr: &IdentInterner,
443                                 cdata: Cmd,
444                                 doc: rbml::Doc,
445                                 did: DefId,
446                                 tcx: &TyCtxt<'tcx>) -> ty::VariantDefData<'tcx, 'tcx> {
447         ty::VariantDefData {
448             did: did,
449             name: item_name(intr, doc),
450             fields: get_variant_fields(intr, cdata, doc, tcx),
451             disr_val: ConstInt::Infer(0),
452             kind: expect_variant_kind(item_family(doc), tcx),
453         }
454     }
455
456     let doc = cdata.lookup_item(item_id);
457     let did = DefId { krate: cdata.cnum, index: item_id };
458     let (kind, variants) = match item_family(doc) {
459         Enum => {
460             (ty::AdtKind::Enum,
461              get_enum_variants(intr, cdata, doc, tcx))
462         }
463         Struct(..) => {
464             let ctor_did =
465                 reader::maybe_get_doc(doc, tag_items_data_item_struct_ctor).
466                 map_or(did, |ctor_doc| translated_def_id(cdata, ctor_doc));
467             (ty::AdtKind::Struct,
468              vec![get_struct_variant(intr, cdata, doc, ctor_did, tcx)])
469         }
470         _ => tcx.sess.bug(
471             &format!("get_adt_def called on a non-ADT {:?} - {:?}",
472                      item_family(doc), did))
473     };
474
475     let adt = tcx.intern_adt_def(did, kind, variants);
476
477     // this needs to be done *after* the variant is interned,
478     // to support recursive structures
479     for variant in &adt.variants {
480         if variant.kind() == ty::VariantKind::Tuple &&
481             adt.adt_kind() == ty::AdtKind::Enum {
482             // tuple-like enum variant fields aren't real items - get the types
483             // from the ctor.
484             debug!("evaluating the ctor-type of {:?}",
485                    variant.name);
486             let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
487             debug!("evaluating the ctor-type of {:?}.. {:?}",
488                    variant.name,
489                    ctor_ty);
490             let field_tys = match ctor_ty.sty {
491                 ty::TyFnDef(_, _, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
492                     ref inputs, ..
493                 }), ..}) => {
494                     // tuple-struct constructors don't have escaping regions
495                     assert!(!inputs.has_escaping_regions());
496                     inputs
497                 },
498                 _ => tcx.sess.bug("tuple-variant ctor is not an ADT")
499             };
500             for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
501                 field.fulfill_ty(ty);
502             }
503         } else {
504             for field in &variant.fields {
505                 debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
506                 let ty = get_type(cdata, field.did.index, tcx).ty;
507                 field.fulfill_ty(ty);
508                 debug!("evaluating the type of {:?}::{:?}: {:?}",
509                        variant.name, field.name, ty);
510             }
511         }
512     }
513
514     adt
515 }
516
517 pub fn get_predicates<'tcx>(cdata: Cmd,
518                             item_id: DefIndex,
519                             tcx: &TyCtxt<'tcx>)
520                             -> ty::GenericPredicates<'tcx>
521 {
522     let item_doc = cdata.lookup_item(item_id);
523     doc_predicates(item_doc, tcx, cdata, tag_item_generics)
524 }
525
526 pub fn get_super_predicates<'tcx>(cdata: Cmd,
527                                   item_id: DefIndex,
528                                   tcx: &TyCtxt<'tcx>)
529                                   -> ty::GenericPredicates<'tcx>
530 {
531     let item_doc = cdata.lookup_item(item_id);
532     doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
533 }
534
535 pub fn get_type<'tcx>(cdata: Cmd, id: DefIndex, tcx: &TyCtxt<'tcx>)
536                       -> ty::TypeScheme<'tcx>
537 {
538     let item_doc = cdata.lookup_item(id);
539     let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
540                       cdata);
541     let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
542     ty::TypeScheme {
543         generics: generics,
544         ty: t
545     }
546 }
547
548 pub fn get_stability(cdata: Cmd, id: DefIndex) -> Option<attr::Stability> {
549     let item = cdata.lookup_item(id);
550     reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
551         let mut decoder = reader::Decoder::new(doc);
552         Decodable::decode(&mut decoder).unwrap()
553     })
554 }
555
556 pub fn get_deprecation(cdata: Cmd, id: DefIndex) -> Option<attr::Deprecation> {
557     let item = cdata.lookup_item(id);
558     reader::maybe_get_doc(item, tag_items_data_item_deprecation).map(|doc| {
559         let mut decoder = reader::Decoder::new(doc);
560         Decodable::decode(&mut decoder).unwrap()
561     })
562 }
563
564 pub fn get_visibility(cdata: Cmd, id: DefIndex) -> hir::Visibility {
565     item_visibility(cdata.lookup_item(id))
566 }
567
568 pub fn get_parent_impl(cdata: Cmd, id: DefIndex) -> Option<DefId> {
569     let item = cdata.lookup_item(id);
570     reader::maybe_get_doc(item, tag_items_data_parent_impl).map(|doc| {
571         translated_def_id(cdata, doc)
572     })
573 }
574
575 pub fn get_repr_attrs(cdata: Cmd, id: DefIndex) -> Vec<attr::ReprAttr> {
576     let item = cdata.lookup_item(id);
577     match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
578         let mut decoder = reader::Decoder::new(doc);
579         Decodable::decode(&mut decoder).unwrap()
580     }) {
581         Some(attrs) => attrs,
582         None => Vec::new(),
583     }
584 }
585
586 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
587                                id: DefIndex)
588                                -> Option<hir::ImplPolarity>
589 {
590     let item_doc = cdata.lookup_item(id);
591     let fam = item_family(item_doc);
592     match fam {
593         Family::Impl => {
594             Some(parse_polarity(item_doc))
595         }
596         _ => None
597     }
598 }
599
600 pub fn get_custom_coerce_unsized_kind<'tcx>(
601     cdata: Cmd,
602     id: DefIndex)
603     -> Option<ty::adjustment::CustomCoerceUnsized>
604 {
605     let item_doc = cdata.lookup_item(id);
606     reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
607         let mut decoder = reader::Decoder::new(kind_doc);
608         Decodable::decode(&mut decoder).unwrap()
609     })
610 }
611
612 pub fn get_impl_trait<'tcx>(cdata: Cmd,
613                             id: DefIndex,
614                             tcx: &TyCtxt<'tcx>)
615                             -> Option<ty::TraitRef<'tcx>>
616 {
617     let item_doc = cdata.lookup_item(id);
618     let fam = item_family(item_doc);
619     match fam {
620         Family::Impl | Family::DefaultImpl => {
621             reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
622                 doc_trait_ref(tp, tcx, cdata)
623             })
624         }
625         _ => None
626     }
627 }
628
629 pub fn get_symbol(cdata: Cmd, id: DefIndex) -> String {
630     return item_symbol(cdata.lookup_item(id));
631 }
632
633 /// If you have a crate_metadata, call get_symbol instead
634 pub fn get_symbol_from_buf(data: &[u8], id: DefIndex) -> String {
635     let index = load_index(data);
636     let pos = index.lookup_item(data, id).unwrap();
637     let doc = reader::doc_at(data, pos as usize).unwrap().doc;
638     item_symbol(doc)
639 }
640
641 /// Iterates over the language items in the given crate.
642 pub fn each_lang_item<F>(cdata: Cmd, mut f: F) -> bool where
643     F: FnMut(DefIndex, usize) -> bool,
644 {
645     let root = rbml::Doc::new(cdata.data());
646     let lang_items = reader::get_doc(root, tag_lang_items);
647     reader::tagged_docs(lang_items, tag_lang_items_item).all(|item_doc| {
648         let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
649         let id = reader::doc_as_u32(id_doc) as usize;
650         let index_doc = reader::get_doc(item_doc, tag_lang_items_item_index);
651         let index = DefIndex::from_u32(reader::doc_as_u32(index_doc));
652
653         f(index, id)
654     })
655 }
656
657 fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
658                                      cdata: Cmd,
659                                      item_doc: rbml::Doc,
660                                      mut get_crate_data: G,
661                                      mut callback: F) where
662     F: FnMut(DefLike, ast::Name, hir::Visibility),
663     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
664 {
665     // Iterate over all children.
666     for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
667         let child_def_id = translated_def_id(cdata, child_info_doc);
668
669         // This item may be in yet another crate if it was the child of a
670         // reexport.
671         let crate_data = if child_def_id.krate == cdata.cnum {
672             None
673         } else {
674             Some(get_crate_data(child_def_id.krate))
675         };
676         let crate_data = match crate_data {
677             Some(ref cdata) => &**cdata,
678             None => cdata
679         };
680
681         // Get the item.
682         match crate_data.get_item(child_def_id.index) {
683             None => {}
684             Some(child_item_doc) => {
685                 // Hand off the item to the callback.
686                 let child_name = item_name(&intr, child_item_doc);
687                 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
688                 let visibility = item_visibility(child_item_doc);
689                 callback(def_like, child_name, visibility);
690             }
691         }
692     }
693
694     // As a special case, iterate over all static methods of
695     // associated implementations too. This is a bit of a botch.
696     // --pcwalton
697     for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
698                                                              tag_items_data_item_inherent_impl) {
699         let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
700         if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.index) {
701             for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
702                                                                  tag_item_impl_item) {
703                 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
704                                                    cdata);
705                 if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.index) {
706                     if let StaticMethod = item_family(impl_method_doc) {
707                         // Hand off the static method to the callback.
708                         let static_method_name = item_name(&intr, impl_method_doc);
709                         let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
710                                                                       impl_item_def_id);
711                         callback(static_method_def_like,
712                                  static_method_name,
713                                  item_visibility(impl_method_doc));
714                     }
715                 }
716             }
717         }
718     }
719
720     for reexport_doc in reexports(item_doc) {
721         let def_id_doc = reader::get_doc(reexport_doc,
722                                          tag_items_data_item_reexport_def_id);
723         let child_def_id = translated_def_id(cdata, def_id_doc);
724
725         let name_doc = reader::get_doc(reexport_doc,
726                                        tag_items_data_item_reexport_name);
727         let name = name_doc.as_str_slice();
728
729         // This reexport may be in yet another crate.
730         let crate_data = if child_def_id.krate == cdata.cnum {
731             None
732         } else {
733             Some(get_crate_data(child_def_id.krate))
734         };
735         let crate_data = match crate_data {
736             Some(ref cdata) => &**cdata,
737             None => cdata
738         };
739
740         // Get the item.
741         if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
742             // Hand off the item to the callback.
743             let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
744             // These items have a public visibility because they're part of
745             // a public re-export.
746             callback(def_like, token::intern(name), hir::Public);
747         }
748     }
749 }
750
751 /// Iterates over each child of the given item.
752 pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
753                                cdata: Cmd,
754                                id: DefIndex,
755                                get_crate_data: G,
756                                callback: F) where
757     F: FnMut(DefLike, ast::Name, hir::Visibility),
758     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
759 {
760     // Find the item.
761     let item_doc = match cdata.get_item(id) {
762         None => return,
763         Some(item_doc) => item_doc,
764     };
765
766     each_child_of_item_or_crate(intr,
767                                 cdata,
768                                 item_doc,
769                                 get_crate_data,
770                                 callback)
771 }
772
773 /// Iterates over all the top-level crate items.
774 pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
775                                           cdata: Cmd,
776                                           get_crate_data: G,
777                                           callback: F) where
778     F: FnMut(DefLike, ast::Name, hir::Visibility),
779     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
780 {
781     let root_doc = rbml::Doc::new(cdata.data());
782     let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
783     let crate_items_doc = reader::get_doc(misc_info_doc,
784                                           tag_misc_info_crate_items);
785
786     each_child_of_item_or_crate(intr,
787                                 cdata,
788                                 crate_items_doc,
789                                 get_crate_data,
790                                 callback)
791 }
792
793 pub fn get_item_path(cdata: Cmd, id: DefIndex) -> Vec<hir_map::PathElem> {
794     item_path(cdata.lookup_item(id))
795 }
796
797 pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: DefIndex) -> ast::Name {
798     item_name(intr, cdata.lookup_item(id))
799 }
800
801 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &TyCtxt<'tcx>, id: DefIndex)
802                                 -> FoundAst<'tcx> {
803     debug!("Looking up item: {:?}", id);
804     let item_doc = cdata.lookup_item(id);
805     let item_did = item_def_id(item_doc, cdata);
806     let parent_def_id = DefId {
807         krate: cdata.cnum,
808         index: def_key(cdata, id).parent.unwrap()
809     };
810     let mut parent_path = item_path(item_doc);
811     parent_path.pop();
812     let mut parent_def_path = def_path(cdata, id);
813     parent_def_path.pop();
814     if let Some(ast_doc) = reader::maybe_get_doc(item_doc, tag_ast as usize) {
815         let ii = decode_inlined_item(cdata,
816                                      tcx,
817                                      parent_path,
818                                      parent_def_path,
819                                      parent_def_id,
820                                      ast_doc,
821                                      item_did);
822         return FoundAst::Found(ii);
823     } else if let Some(parent_did) = item_parent_item(cdata, item_doc) {
824         // Remove the last element from the paths, since we are now
825         // trying to inline the parent.
826         let grandparent_def_id = DefId {
827             krate: cdata.cnum,
828             index: def_key(cdata, parent_def_id.index).parent.unwrap()
829         };
830         let mut grandparent_path = parent_path;
831         grandparent_path.pop();
832         let mut grandparent_def_path = parent_def_path;
833         grandparent_def_path.pop();
834         let parent_doc = cdata.lookup_item(parent_did.index);
835         if let Some(ast_doc) = reader::maybe_get_doc(parent_doc, tag_ast as usize) {
836             let ii = decode_inlined_item(cdata,
837                                          tcx,
838                                          grandparent_path,
839                                          grandparent_def_path,
840                                          grandparent_def_id,
841                                          ast_doc,
842                                          parent_did);
843             if let &InlinedItem::Item(ref i) = ii {
844                 return FoundAst::FoundParent(parent_did, i);
845             }
846         }
847     }
848     FoundAst::NotFound
849 }
850
851 pub fn is_item_mir_available<'tcx>(cdata: Cmd, id: DefIndex) -> bool {
852     if let Some(item_doc) = cdata.get_item(id) {
853         return reader::maybe_get_doc(item_doc, tag_mir as usize).is_some();
854     }
855
856     false
857 }
858
859 pub fn maybe_get_item_mir<'tcx>(cdata: Cmd,
860                                 tcx: &TyCtxt<'tcx>,
861                                 id: DefIndex)
862                                 -> Option<mir::repr::Mir<'tcx>> {
863     let item_doc = cdata.lookup_item(id);
864
865     return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
866         let dcx = tls_context::DecodingContext {
867             crate_metadata: cdata,
868             tcx: tcx,
869         };
870         let mut decoder = reader::Decoder::new(mir_doc);
871
872         let mut mir = decoder.read_opaque(|opaque_decoder, _| {
873             tls::enter_decoding_context(&dcx, opaque_decoder, |_, opaque_decoder| {
874                 Decodable::decode(opaque_decoder)
875             })
876         }).unwrap();
877
878         assert!(decoder.position() == mir_doc.end);
879
880         let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
881             crate_metadata: cdata,
882             codemap: tcx.sess.codemap(),
883             last_filemap_index_hint: Cell::new(0),
884         };
885
886         def_id_and_span_translator.visit_mir(&mut mir);
887
888         mir
889     });
890
891     struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
892         crate_metadata: Cmd<'cdata>,
893         codemap: &'codemap codemap::CodeMap,
894         last_filemap_index_hint: Cell<usize>
895     }
896
897     impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
898         for MirDefIdAndSpanTranslator<'cdata, 'codemap>
899     {
900         fn visit_def_id(&mut self, def_id: &mut DefId) {
901             *def_id = translate_def_id(self.crate_metadata, *def_id);
902         }
903
904         fn visit_span(&mut self, span: &mut Span) {
905             *span = translate_span(self.crate_metadata,
906                                    self.codemap,
907                                    &self.last_filemap_index_hint,
908                                    *span);
909         }
910     }
911 }
912
913 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
914     fn get_mutability(ch: u8) -> hir::Mutability {
915         match ch as char {
916             'i' => hir::MutImmutable,
917             'm' => hir::MutMutable,
918             _ => panic!("unknown mutability character: `{}`", ch as char),
919         }
920     }
921
922     let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
923     let string = explicit_self_doc.as_str_slice();
924
925     let explicit_self_kind = string.as_bytes()[0];
926     match explicit_self_kind as char {
927         's' => ty::ExplicitSelfCategory::Static,
928         'v' => ty::ExplicitSelfCategory::ByValue,
929         '~' => ty::ExplicitSelfCategory::ByBox,
930         // FIXME(#4846) expl. region
931         '&' => {
932             ty::ExplicitSelfCategory::ByReference(
933                 ty::ReEmpty,
934                 get_mutability(string.as_bytes()[1]))
935         }
936         _ => panic!("unknown self type code: `{}`", explicit_self_kind as char)
937     }
938 }
939
940 /// Returns the def IDs of all the items in the given implementation.
941 pub fn get_impl_items(cdata: Cmd, impl_id: DefIndex)
942                       -> Vec<ty::ImplOrTraitItemId> {
943     reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
944         let def_id = item_def_id(doc, cdata);
945         match item_sort(doc) {
946             Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
947             Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
948             Some('t') => ty::TypeTraitItemId(def_id),
949             _ => panic!("unknown impl item sort"),
950         }
951     }).collect()
952 }
953
954 pub fn get_trait_name(intr: Rc<IdentInterner>,
955                       cdata: Cmd,
956                       id: DefIndex)
957                       -> ast::Name {
958     let doc = cdata.lookup_item(id);
959     item_name(&intr, doc)
960 }
961
962 pub fn is_static_method(cdata: Cmd, id: DefIndex) -> bool {
963     let doc = cdata.lookup_item(id);
964     match item_sort(doc) {
965         Some('r') | Some('p') => {
966             get_explicit_self(doc) == ty::ExplicitSelfCategory::Static
967         }
968         _ => false
969     }
970 }
971
972 pub fn get_impl_or_trait_item<'tcx>(intr: Rc<IdentInterner>,
973                                     cdata: Cmd,
974                                     id: DefIndex,
975                                     tcx: &TyCtxt<'tcx>)
976                                     -> Option<ty::ImplOrTraitItem<'tcx>> {
977     let item_doc = cdata.lookup_item(id);
978
979     let def_id = item_def_id(item_doc, cdata);
980
981     let container_id = if let Some(id) = item_parent_item(cdata, item_doc) {
982         id
983     } else {
984         return None;
985     };
986     let container_doc = cdata.lookup_item(container_id.index);
987     let container = match item_family(container_doc) {
988         Trait => TraitContainer(container_id),
989         _ => ImplContainer(container_id),
990     };
991
992     let name = item_name(&intr, item_doc);
993     let vis = item_visibility(item_doc);
994     let defaultness = item_defaultness(item_doc);
995
996     Some(match item_sort(item_doc) {
997         sort @ Some('C') | sort @ Some('c') => {
998             let ty = doc_type(item_doc, tcx, cdata);
999             ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
1000                 name: name,
1001                 ty: ty,
1002                 vis: vis,
1003                 defaultness: defaultness,
1004                 def_id: def_id,
1005                 container: container,
1006                 has_value: sort == Some('C')
1007             }))
1008         }
1009         Some('r') | Some('p') => {
1010             let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
1011             let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
1012             let ity = tcx.lookup_item_type(def_id).ty;
1013             let fty = match ity.sty {
1014                 ty::TyFnDef(_, _, fty) => fty.clone(),
1015                 _ => tcx.sess.bug(&format!(
1016                     "the type {:?} of the method {:?} is not a function?",
1017                     ity, name))
1018             };
1019             let explicit_self = get_explicit_self(item_doc);
1020
1021             ty::MethodTraitItem(Rc::new(ty::Method::new(name,
1022                                                         generics,
1023                                                         predicates,
1024                                                         fty,
1025                                                         explicit_self,
1026                                                         vis,
1027                                                         defaultness,
1028                                                         def_id,
1029                                                         container)))
1030         }
1031         Some('t') => {
1032             let ty = maybe_doc_type(item_doc, tcx, cdata);
1033             ty::TypeTraitItem(Rc::new(ty::AssociatedType {
1034                 name: name,
1035                 ty: ty,
1036                 vis: vis,
1037                 defaultness: defaultness,
1038                 def_id: def_id,
1039                 container: container,
1040             }))
1041         }
1042         _ => return None
1043     })
1044 }
1045
1046 pub fn get_trait_item_def_ids(cdata: Cmd, id: DefIndex)
1047                               -> Vec<ty::ImplOrTraitItemId> {
1048     let item = cdata.lookup_item(id);
1049     reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
1050         let def_id = item_def_id(mth, cdata);
1051         match item_sort(mth) {
1052             Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
1053             Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
1054             Some('t') => ty::TypeTraitItemId(def_id),
1055             _ => panic!("unknown trait item sort"),
1056         }
1057     }).collect()
1058 }
1059
1060 pub fn get_item_variances(cdata: Cmd, id: DefIndex) -> ty::ItemVariances {
1061     let item_doc = cdata.lookup_item(id);
1062     let variance_doc = reader::get_doc(item_doc, tag_item_variances);
1063     let mut decoder = reader::Decoder::new(variance_doc);
1064     Decodable::decode(&mut decoder).unwrap()
1065 }
1066
1067 pub fn get_provided_trait_methods<'tcx>(intr: Rc<IdentInterner>,
1068                                         cdata: Cmd,
1069                                         id: DefIndex,
1070                                         tcx: &TyCtxt<'tcx>)
1071                                         -> Vec<Rc<ty::Method<'tcx>>> {
1072     let item = cdata.lookup_item(id);
1073
1074     reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
1075         let did = item_def_id(mth_id, cdata);
1076         let mth = cdata.lookup_item(did.index);
1077
1078         if item_sort(mth) == Some('p') {
1079             let trait_item = get_impl_or_trait_item(intr.clone(),
1080                                                     cdata,
1081                                                     did.index,
1082                                                     tcx);
1083             if let Some(ty::MethodTraitItem(ref method)) = trait_item {
1084                 Some((*method).clone())
1085             } else {
1086                 None
1087             }
1088         } else {
1089             None
1090         }
1091     }).collect()
1092 }
1093
1094 pub fn get_associated_consts<'tcx>(intr: Rc<IdentInterner>,
1095                                    cdata: Cmd,
1096                                    id: DefIndex,
1097                                    tcx: &TyCtxt<'tcx>)
1098                                    -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
1099     let item = cdata.lookup_item(id);
1100
1101     [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
1102         reader::tagged_docs(item, tag).filter_map(|ac_id| {
1103             let did = item_def_id(ac_id, cdata);
1104             let ac_doc = cdata.lookup_item(did.index);
1105
1106             match item_sort(ac_doc) {
1107                 Some('C') | Some('c') => {
1108                     let trait_item = get_impl_or_trait_item(intr.clone(),
1109                                                             cdata,
1110                                                             did.index,
1111                                                             tcx);
1112                     if let Some(ty::ConstTraitItem(ref ac)) = trait_item {
1113                         Some((*ac).clone())
1114                     } else {
1115                         None
1116                     }
1117                 }
1118                 _ => None
1119             }
1120         })
1121     }).collect()
1122 }
1123
1124 pub fn get_variant_kind(cdata: Cmd, node_id: DefIndex) -> Option<VariantKind>
1125 {
1126     let item = cdata.lookup_item(node_id);
1127     family_to_variant_kind(item_family(item))
1128 }
1129
1130 pub fn get_struct_ctor_def_id(cdata: Cmd, node_id: DefIndex) -> Option<DefId>
1131 {
1132     let item = cdata.lookup_item(node_id);
1133     reader::maybe_get_doc(item, tag_items_data_item_struct_ctor).
1134         map(|ctor_doc| translated_def_id(cdata, ctor_doc))
1135 }
1136
1137 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1138 /// the actual type definition, otherwise, return None
1139 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1140                                            node_id: DefIndex)
1141     -> Option<DefId>
1142 {
1143     let item = cdata.lookup_item(node_id);
1144     reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1145         item_require_parent_item(cdata, item)
1146     })
1147 }
1148
1149 pub fn get_item_attrs(cdata: Cmd,
1150                       orig_node_id: DefIndex)
1151                       -> Vec<ast::Attribute> {
1152     // The attributes for a tuple struct are attached to the definition, not the ctor;
1153     // we assume that someone passing in a tuple struct ctor is actually wanting to
1154     // look at the definition
1155     let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1156     let node_id = node_id.map(|x| x.index).unwrap_or(orig_node_id);
1157     let item = cdata.lookup_item(node_id);
1158     get_attributes(item)
1159 }
1160
1161 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<DefId, Vec<ast::Attribute>> {
1162     let data = rbml::Doc::new(cdata.data());
1163     let fields = reader::get_doc(data, tag_struct_fields);
1164     reader::tagged_docs(fields, tag_struct_field).map(|field| {
1165         let def_id = translated_def_id(cdata, reader::get_doc(field, tag_def_id));
1166         let attrs = get_attributes(field);
1167         (def_id, attrs)
1168     }).collect()
1169 }
1170
1171 fn struct_field_family_to_visibility(family: Family) -> hir::Visibility {
1172     match family {
1173       PublicField => hir::Public,
1174       InheritedField => hir::Inherited,
1175       _ => panic!()
1176     }
1177 }
1178
1179 pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: DefIndex)
1180     -> Vec<ast::Name> {
1181     let item = cdata.lookup_item(id);
1182     let mut index = 0;
1183     reader::tagged_docs(item, tag_item_field).map(|an_item| {
1184         item_name(intr, an_item)
1185     }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1186         let name = intr.intern(&index.to_string());
1187         index += 1;
1188         name
1189     })).collect()
1190 }
1191
1192 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1193     reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1194         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1195         let n = token::intern_and_get_ident(nd.as_str_slice());
1196         attr::mk_word_item(n)
1197     }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1198         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1199         let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1200         let n = token::intern_and_get_ident(nd.as_str_slice());
1201         let v = token::intern_and_get_ident(vd.as_str_slice());
1202         // FIXME (#623): Should be able to decode MetaItemKind::NameValue variants,
1203         // but currently the encoder just drops them
1204         attr::mk_name_value_item_str(n, v)
1205     })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1206         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1207         let n = token::intern_and_get_ident(nd.as_str_slice());
1208         let subitems = get_meta_items(meta_item_doc);
1209         attr::mk_list_item(n, subitems)
1210     })).collect()
1211 }
1212
1213 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1214     match reader::maybe_get_doc(md, tag_attributes) {
1215         Some(attrs_d) => {
1216             reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1217                 let is_sugared_doc = reader::doc_as_u8(
1218                     reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1219                 ) == 1;
1220                 let meta_items = get_meta_items(attr_doc);
1221                 // Currently it's only possible to have a single meta item on
1222                 // an attribute
1223                 assert_eq!(meta_items.len(), 1);
1224                 let meta_item = meta_items.into_iter().nth(0).unwrap();
1225                 codemap::Spanned {
1226                     node: ast::Attribute_ {
1227                         id: attr::mk_attr_id(),
1228                         style: ast::AttrStyle::Outer,
1229                         value: meta_item,
1230                         is_sugared_doc: is_sugared_doc,
1231                     },
1232                     span: codemap::DUMMY_SP
1233                 }
1234             }).collect()
1235         },
1236         None => vec![],
1237     }
1238 }
1239
1240 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1241                          out: &mut io::Write) -> io::Result<()> {
1242     write!(out, "=Crate Attributes ({})=\n", *hash)?;
1243
1244     let r = get_attributes(md);
1245     for attr in &r {
1246         write!(out, "{}\n", pprust::attribute_to_string(attr))?;
1247     }
1248
1249     write!(out, "\n\n")
1250 }
1251
1252 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1253     get_attributes(rbml::Doc::new(data))
1254 }
1255
1256 #[derive(Clone)]
1257 pub struct CrateDep {
1258     pub cnum: ast::CrateNum,
1259     pub name: String,
1260     pub hash: Svh,
1261     pub explicitly_linked: bool,
1262 }
1263
1264 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1265     let cratedoc = rbml::Doc::new(data);
1266     let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1267
1268     fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1269         let d = reader::get_doc(doc, tag_);
1270         d.as_str_slice().to_string()
1271     }
1272
1273     reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1274         let name = docstr(depdoc, tag_crate_dep_crate_name);
1275         let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash));
1276         let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1277         let explicitly_linked = reader::doc_as_u8(doc) != 0;
1278         CrateDep {
1279             cnum: crate_num as u32 + 1,
1280             name: name,
1281             hash: hash,
1282             explicitly_linked: explicitly_linked,
1283         }
1284     }).collect()
1285 }
1286
1287 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1288     write!(out, "=External Dependencies=\n")?;
1289     for dep in &get_crate_deps(data) {
1290         write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash)?;
1291     }
1292     write!(out, "\n")?;
1293     Ok(())
1294 }
1295
1296 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1297     let cratedoc = rbml::Doc::new(data);
1298     reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1299         Svh::new(doc.as_str_slice())
1300     })
1301 }
1302
1303 pub fn get_crate_hash(data: &[u8]) -> Svh {
1304     let cratedoc = rbml::Doc::new(data);
1305     let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1306     Svh::new(hashdoc.as_str_slice())
1307 }
1308
1309 pub fn maybe_get_crate_name(data: &[u8]) -> Option<&str> {
1310     let cratedoc = rbml::Doc::new(data);
1311     reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1312         doc.as_str_slice()
1313     })
1314 }
1315
1316 pub fn get_crate_disambiguator<'a>(data: &'a [u8]) -> &'a str {
1317     let crate_doc = rbml::Doc::new(data);
1318     let disambiguator_doc = reader::get_doc(crate_doc, tag_crate_disambiguator);
1319     let slice: &'a str = disambiguator_doc.as_str_slice();
1320     slice
1321 }
1322
1323 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1324     let cratedoc = rbml::Doc::new(data);
1325     let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1326     triple_doc.map(|s| s.as_str().to_string())
1327 }
1328
1329 pub fn get_crate_name(data: &[u8]) -> &str {
1330     maybe_get_crate_name(data).expect("no crate name in crate")
1331 }
1332
1333 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1334     let hash = get_crate_hash(bytes);
1335     let md = rbml::Doc::new(bytes);
1336     list_crate_attributes(md, &hash, out)?;
1337     list_crate_deps(bytes, out)
1338 }
1339
1340 // Translates a def_id from an external crate to a def_id for the current
1341 // compilation environment. We use this when trying to load types from
1342 // external crates - if those types further refer to types in other crates
1343 // then we must translate the crate number from that encoded in the external
1344 // crate to the correct local crate number.
1345 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1346     if did.is_local() {
1347         return DefId { krate: cdata.cnum, index: did.index };
1348     }
1349
1350     match cdata.cnum_map.borrow().get(&did.krate) {
1351         Some(&n) => {
1352             DefId {
1353                 krate: n,
1354                 index: did.index,
1355             }
1356         }
1357         None => panic!("didn't find a crate in the cnum_map")
1358     }
1359 }
1360
1361 // Translate a DefId from the current compilation environment to a DefId
1362 // for an external crate.
1363 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1364     if did.krate == cdata.cnum {
1365         return Some(DefId { krate: LOCAL_CRATE, index: did.index });
1366     }
1367
1368     for (&local, &global) in cdata.cnum_map.borrow().iter() {
1369         if global == did.krate {
1370             return Some(DefId { krate: local, index: did.index });
1371         }
1372     }
1373
1374     None
1375 }
1376
1377 /// Translates a `Span` from an extern crate to the corresponding `Span`
1378 /// within the local crate's codemap.
1379 pub fn translate_span(cdata: Cmd,
1380                       codemap: &codemap::CodeMap,
1381                       last_filemap_index_hint: &Cell<usize>,
1382                       span: codemap::Span)
1383                       -> codemap::Span {
1384     let span = if span.lo > span.hi {
1385         // Currently macro expansion sometimes produces invalid Span values
1386         // where lo > hi. In order not to crash the compiler when trying to
1387         // translate these values, let's transform them into something we
1388         // can handle (and which will produce useful debug locations at
1389         // least some of the time).
1390         // This workaround is only necessary as long as macro expansion is
1391         // not fixed. FIXME(#23480)
1392         codemap::mk_sp(span.lo, span.lo)
1393     } else {
1394         span
1395     };
1396
1397     let imported_filemaps = cdata.imported_filemaps(&codemap);
1398     let filemap = {
1399         // Optimize for the case that most spans within a translated item
1400         // originate from the same filemap.
1401         let last_filemap_index = last_filemap_index_hint.get();
1402         let last_filemap = &imported_filemaps[last_filemap_index];
1403
1404         if span.lo >= last_filemap.original_start_pos &&
1405            span.lo <= last_filemap.original_end_pos &&
1406            span.hi >= last_filemap.original_start_pos &&
1407            span.hi <= last_filemap.original_end_pos {
1408             last_filemap
1409         } else {
1410             let mut a = 0;
1411             let mut b = imported_filemaps.len();
1412
1413             while b - a > 1 {
1414                 let m = (a + b) / 2;
1415                 if imported_filemaps[m].original_start_pos > span.lo {
1416                     b = m;
1417                 } else {
1418                     a = m;
1419                 }
1420             }
1421
1422             last_filemap_index_hint.set(a);
1423             &imported_filemaps[a]
1424         }
1425     };
1426
1427     let lo = (span.lo - filemap.original_start_pos) +
1428               filemap.translated_filemap.start_pos;
1429     let hi = (span.hi - filemap.original_start_pos) +
1430               filemap.translated_filemap.start_pos;
1431
1432     codemap::mk_sp(lo, hi)
1433 }
1434
1435 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1436                                                 id: DefIndex,
1437                                                 mut callback: F)
1438     where F: FnMut(DefId),
1439 {
1440     let item_doc = cdata.lookup_item(id);
1441     for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1442         if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1443             callback(item_def_id(impl_doc, cdata));
1444         }
1445     }
1446 }
1447
1448 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1449                                         def_id: DefId,
1450                                         mut callback: F) where
1451     F: FnMut(DefId),
1452 {
1453     // Do a reverse lookup beforehand to avoid touching the crate_num
1454     // hash map in the loop below.
1455     if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1456         let def_id_u64 = def_to_u64(crate_local_did);
1457
1458         let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1459         for trait_doc in reader::tagged_docs(impls_doc, tag_impls_trait) {
1460             let trait_def_id = reader::get_doc(trait_doc, tag_def_id);
1461             if reader::doc_as_u64(trait_def_id) != def_id_u64 {
1462                 continue;
1463             }
1464             for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1465                 callback(translated_def_id(cdata, impl_doc));
1466             }
1467         }
1468     }
1469 }
1470
1471 pub fn get_trait_of_item(cdata: Cmd, id: DefIndex, tcx: &TyCtxt)
1472                          -> Option<DefId> {
1473     let item_doc = cdata.lookup_item(id);
1474     let parent_item_id = match item_parent_item(cdata, item_doc) {
1475         None => return None,
1476         Some(item_id) => item_id,
1477     };
1478     let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1479     match item_family(parent_item_doc) {
1480         Trait => Some(item_def_id(parent_item_doc, cdata)),
1481         Impl | DefaultImpl => {
1482             reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1483                 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1484         }
1485         _ => None
1486     }
1487 }
1488
1489
1490 pub fn get_native_libraries(cdata: Cmd)
1491                             -> Vec<(cstore::NativeLibraryKind, String)> {
1492     let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1493                                     tag_native_libraries);
1494     reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1495         let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1496         let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1497         let kind: cstore::NativeLibraryKind =
1498             cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1499         let name = name_doc.as_str().to_string();
1500         (kind, name)
1501     }).collect()
1502 }
1503
1504 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<DefIndex> {
1505     reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1506         .map(|doc| DefIndex::from_u32(reader::doc_as_u32(doc)))
1507 }
1508
1509 pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where
1510     F: FnMut(ast::Name, Vec<ast::Attribute>, Span, String) -> bool,
1511 {
1512     let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1513     for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1514         let name = item_name(intr, macro_doc);
1515         let attrs = get_attributes(macro_doc);
1516         let span = get_macro_span(macro_doc);
1517         let body = reader::get_doc(macro_doc, tag_macro_def_body);
1518         if !f(name, attrs, span, body.as_str().to_string()) {
1519             break;
1520         }
1521     }
1522 }
1523
1524 pub fn get_macro_span(doc: rbml::Doc) -> Span {
1525     let lo_doc = reader::get_doc(doc, tag_macro_def_span_lo);
1526     let lo = BytePos(reader::doc_as_u32(lo_doc));
1527     let hi_doc = reader::get_doc(doc, tag_macro_def_span_hi);
1528     let hi = BytePos(reader::doc_as_u32(hi_doc));
1529     return Span { lo: lo, hi: hi, expn_id: NO_EXPANSION };
1530 }
1531
1532 pub fn get_dylib_dependency_formats(cdata: Cmd)
1533     -> Vec<(ast::CrateNum, LinkagePreference)>
1534 {
1535     let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1536                                   tag_dylib_dependency_formats);
1537     let mut result = Vec::new();
1538
1539     debug!("found dylib deps: {}", formats.as_str_slice());
1540     for spec in formats.as_str_slice().split(',') {
1541         if spec.is_empty() { continue }
1542         let cnum = spec.split(':').nth(0).unwrap();
1543         let link = spec.split(':').nth(1).unwrap();
1544         let cnum: ast::CrateNum = cnum.parse().unwrap();
1545         let cnum = match cdata.cnum_map.borrow().get(&cnum) {
1546             Some(&n) => n,
1547             None => panic!("didn't find a crate in the cnum_map")
1548         };
1549         result.push((cnum, if link == "d" {
1550             LinkagePreference::RequireDynamic
1551         } else {
1552             LinkagePreference::RequireStatic
1553         }));
1554     }
1555     return result;
1556 }
1557
1558 pub fn get_missing_lang_items(cdata: Cmd)
1559     -> Vec<lang_items::LangItem>
1560 {
1561     let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1562     reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1563         lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1564     }).collect()
1565 }
1566
1567 pub fn get_method_arg_names(cdata: Cmd, id: DefIndex) -> Vec<String> {
1568     let method_doc = cdata.lookup_item(id);
1569     match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1570         Some(args_doc) => {
1571             reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1572                 name_doc.as_str_slice().to_string()
1573             }).collect()
1574         },
1575         None => vec![],
1576     }
1577 }
1578
1579 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1580     let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1581                                 tag_reachable_ids);
1582     reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1583         DefId {
1584             krate: cdata.cnum,
1585             index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1586         }
1587     }).collect()
1588 }
1589
1590 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1591     let item_doc = cdata.lookup_item(id);
1592     match item_family(item_doc) {
1593         Type => true,
1594         _ => false,
1595     }
1596 }
1597
1598 pub fn is_const_fn(cdata: Cmd, id: DefIndex) -> bool {
1599     let item_doc = cdata.lookup_item(id);
1600     match fn_constness(item_doc) {
1601         hir::Constness::Const => true,
1602         hir::Constness::NotConst => false,
1603     }
1604 }
1605
1606 pub fn is_extern_item(cdata: Cmd, id: DefIndex, tcx: &TyCtxt) -> bool {
1607     let item_doc = match cdata.get_item(id) {
1608         Some(doc) => doc,
1609         None => return false,
1610     };
1611     let applicable = match item_family(item_doc) {
1612         ImmStatic | MutStatic => true,
1613         Fn => {
1614             let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1615             let no_generics = generics.types.is_empty();
1616             match ty.sty {
1617                 ty::TyFnDef(_, _, fn_ty) | ty::TyFnPtr(fn_ty)
1618                     if fn_ty.abi != Abi::Rust => return no_generics,
1619                 _ => no_generics,
1620             }
1621         },
1622         _ => false,
1623     };
1624
1625     if applicable {
1626         attr::contains_extern_indicator(tcx.sess.diagnostic(),
1627                                         &get_attributes(item_doc))
1628     } else {
1629         false
1630     }
1631 }
1632
1633 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1634     let item_doc = cdata.lookup_item(id);
1635     match item_family(item_doc) {
1636         Impl => true,
1637         _ => false,
1638     }
1639 }
1640
1641 fn doc_generics<'tcx>(base_doc: rbml::Doc,
1642                       tcx: &TyCtxt<'tcx>,
1643                       cdata: Cmd,
1644                       tag: usize)
1645                       -> ty::Generics<'tcx>
1646 {
1647     let doc = reader::get_doc(base_doc, tag);
1648
1649     let mut types = subst::VecPerParamSpace::empty();
1650     for p in reader::tagged_docs(doc, tag_type_param_def) {
1651         let bd =
1652             TyDecoder::with_doc(tcx, cdata.cnum, p,
1653                                 &mut |did| translate_def_id(cdata, did))
1654             .parse_type_param_def();
1655         types.push(bd.space, bd);
1656     }
1657
1658     let mut regions = subst::VecPerParamSpace::empty();
1659     for rp_doc in reader::tagged_docs(doc, tag_region_param_def) {
1660         let ident_str_doc = reader::get_doc(rp_doc,
1661                                             tag_region_param_def_ident);
1662         let name = item_name(&token::get_ident_interner(), ident_str_doc);
1663         let def_id_doc = reader::get_doc(rp_doc,
1664                                          tag_region_param_def_def_id);
1665         let def_id = translated_def_id(cdata, def_id_doc);
1666
1667         let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1668         let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as usize);
1669
1670         let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1671         let index = reader::doc_as_u64(doc) as u32;
1672
1673         let bounds = reader::tagged_docs(rp_doc, tag_items_data_region).map(|p| {
1674             TyDecoder::with_doc(tcx, cdata.cnum, p,
1675                                 &mut |did| translate_def_id(cdata, did))
1676             .parse_region()
1677         }).collect();
1678
1679         regions.push(space, ty::RegionParameterDef { name: name,
1680                                                      def_id: def_id,
1681                                                      space: space,
1682                                                      index: index,
1683                                                      bounds: bounds });
1684     }
1685
1686     ty::Generics { types: types, regions: regions }
1687 }
1688
1689 fn doc_predicate<'tcx>(cdata: Cmd,
1690                        doc: rbml::Doc,
1691                        tcx: &TyCtxt<'tcx>)
1692                        -> ty::Predicate<'tcx>
1693 {
1694     let predicate_pos = cdata.xref_index.lookup(
1695         cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1696     TyDecoder::new(
1697         cdata.data(), cdata.cnum, predicate_pos, tcx,
1698         &mut |did| translate_def_id(cdata, did)
1699     ).parse_predicate()
1700 }
1701
1702 fn doc_predicates<'tcx>(base_doc: rbml::Doc,
1703                         tcx: &TyCtxt<'tcx>,
1704                         cdata: Cmd,
1705                         tag: usize)
1706                         -> ty::GenericPredicates<'tcx>
1707 {
1708     let doc = reader::get_doc(base_doc, tag);
1709
1710     let mut predicates = subst::VecPerParamSpace::empty();
1711     for predicate_doc in reader::tagged_docs(doc, tag_type_predicate) {
1712         predicates.push(subst::TypeSpace,
1713                         doc_predicate(cdata, predicate_doc, tcx));
1714     }
1715     for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1716         predicates.push(subst::SelfSpace,
1717                         doc_predicate(cdata, predicate_doc, tcx));
1718     }
1719     for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1720         predicates.push(subst::FnSpace,
1721                         doc_predicate(cdata, predicate_doc, tcx));
1722     }
1723
1724     ty::GenericPredicates { predicates: predicates }
1725 }
1726
1727 pub fn is_defaulted_trait(cdata: Cmd, trait_id: DefIndex) -> bool {
1728     let trait_doc = cdata.lookup_item(trait_id);
1729     assert!(item_family(trait_doc) == Family::Trait);
1730     let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1731     reader::doc_as_u8(defaulted_doc) != 0
1732 }
1733
1734 pub fn is_default_impl(cdata: Cmd, impl_id: DefIndex) -> bool {
1735     let impl_doc = cdata.lookup_item(impl_id);
1736     item_family(impl_doc) == Family::DefaultImpl
1737 }
1738
1739 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
1740     let crate_doc = rbml::Doc::new(metadata);
1741     let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1742
1743     reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1744         let mut decoder = reader::Decoder::new(filemap_doc);
1745         decoder.read_opaque(|opaque_decoder, _| {
1746             Decodable::decode(opaque_decoder)
1747         }).unwrap()
1748     }).collect()
1749 }
1750
1751 pub fn closure_kind(cdata: Cmd, closure_id: DefIndex) -> ty::ClosureKind {
1752     let closure_doc = cdata.lookup_item(closure_id);
1753     let closure_kind_doc = reader::get_doc(closure_doc, tag_items_closure_kind);
1754     let mut decoder = reader::Decoder::new(closure_kind_doc);
1755     ty::ClosureKind::decode(&mut decoder).unwrap()
1756 }
1757
1758 pub fn closure_ty<'tcx>(cdata: Cmd, closure_id: DefIndex, tcx: &TyCtxt<'tcx>)
1759                         -> ty::ClosureTy<'tcx> {
1760     let closure_doc = cdata.lookup_item(closure_id);
1761     let closure_ty_doc = reader::get_doc(closure_doc, tag_items_closure_ty);
1762     TyDecoder::with_doc(tcx, cdata.cnum, closure_ty_doc, &mut |did| translate_def_id(cdata, did))
1763         .parse_closure_ty()
1764 }
1765
1766 fn def_key(item_doc: rbml::Doc) -> hir_map::DefKey {
1767     match reader::maybe_get_doc(item_doc, tag_def_key) {
1768         Some(def_key_doc) => {
1769             let mut decoder = reader::Decoder::new(def_key_doc);
1770             hir_map::DefKey::decode(&mut decoder).unwrap()
1771         }
1772         None => {
1773             panic!("failed to find block with tag {:?} for item with family {:?}",
1774                    tag_def_key,
1775                    item_family(item_doc))
1776         }
1777     }
1778 }
1779
1780 pub fn def_path(cdata: Cmd, id: DefIndex) -> hir_map::DefPath {
1781     debug!("def_path(id={:?})", id);
1782     hir_map::definitions::make_def_path(id, |parent| {
1783         debug!("def_path: parent={:?}", parent);
1784         let parent_doc = cdata.lookup_item(parent);
1785         def_key(parent_doc)
1786     })
1787 }