]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/decoder.rs
Rollup merge of #28191 - llogiq:iter, r=Manishearth
[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 pub use self::DefLike::*;
16 use self::Family::*;
17
18 use front::map as ast_map;
19 use rustc_front::print::pprust;
20 use rustc_front::hir;
21
22 use back::svh::Svh;
23 use metadata::cstore::crate_metadata;
24 use metadata::common::*;
25 use metadata::csearch::MethodInfo;
26 use metadata::csearch;
27 use metadata::cstore;
28 use metadata::encoder::def_to_u64;
29 use metadata::index;
30 use metadata::inline::InlinedItem;
31 use metadata::tydecode::TyDecoder;
32 use middle::def;
33 use middle::def_id::{DefId, LOCAL_CRATE};
34 use middle::lang_items;
35 use middle::subst;
36 use middle::ty::{ImplContainer, TraitContainer};
37 use middle::ty::{self, RegionEscape, Ty};
38 use util::nodemap::FnvHashMap;
39
40 use std::cell::{Cell, RefCell};
41 use std::io::prelude::*;
42 use std::io;
43 use std::rc::Rc;
44 use std::str;
45
46 use rbml::reader;
47 use rbml;
48 use serialize::Decodable;
49 use rustc_front::attr;
50 use syntax::parse::token::{IdentInterner, special_idents};
51 use syntax::parse::token;
52 use syntax::ast;
53 use syntax::abi;
54 use syntax::codemap;
55 use syntax::ptr::P;
56
57
58 pub type Cmd<'a> = &'a crate_metadata;
59
60 impl crate_metadata {
61     fn get_item(&self, item_id: ast::NodeId) -> Option<rbml::Doc> {
62         self.index.lookup_item(self.data(), item_id).map(|pos| {
63             reader::doc_at(self.data(), pos as usize).unwrap().doc
64         })
65     }
66
67     fn lookup_item(&self, item_id: ast::NodeId) -> rbml::Doc {
68         match self.get_item(item_id) {
69             None => panic!("lookup_item: id not found: {}", item_id),
70             Some(d) => d
71         }
72     }
73 }
74
75 pub fn load_index(data: &[u8]) -> index::Index {
76     let index = reader::get_doc(rbml::Doc::new(data), tag_index);
77     index::Index::from_buf(index.data, index.start, index.end)
78 }
79
80 #[derive(Debug, PartialEq)]
81 enum Family {
82     ImmStatic,             // c
83     MutStatic,             // b
84     Fn,                    // f
85     CtorFn,                // o
86     StaticMethod,          // F
87     Method,                // h
88     Type,                  // y
89     Mod,                   // m
90     ForeignMod,            // n
91     Enum,                  // t
92     TupleVariant,          // v
93     StructVariant,         // V
94     Impl,                  // i
95     DefaultImpl,              // d
96     Trait,                 // I
97     Struct,                // S
98     PublicField,           // g
99     InheritedField,        // N
100     Constant,              // C
101 }
102
103 fn item_family(item: rbml::Doc) -> Family {
104     let fam = reader::get_doc(item, tag_items_data_item_family);
105     match reader::doc_as_u8(fam) as char {
106       'C' => Constant,
107       'c' => ImmStatic,
108       'b' => MutStatic,
109       'f' => Fn,
110       'o' => CtorFn,
111       'F' => StaticMethod,
112       'h' => Method,
113       'y' => Type,
114       'm' => Mod,
115       'n' => ForeignMod,
116       't' => Enum,
117       'v' => TupleVariant,
118       'V' => StructVariant,
119       'i' => Impl,
120       'd' => DefaultImpl,
121       'I' => Trait,
122       'S' => Struct,
123       'g' => PublicField,
124       'N' => InheritedField,
125        c => panic!("unexpected family char: {}", c)
126     }
127 }
128
129 fn item_visibility(item: rbml::Doc) -> hir::Visibility {
130     match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
131         None => hir::Public,
132         Some(visibility_doc) => {
133             match reader::doc_as_u8(visibility_doc) as char {
134                 'y' => hir::Public,
135                 'i' => hir::Inherited,
136                 _ => panic!("unknown visibility character")
137             }
138         }
139     }
140 }
141
142 fn fn_constness(item: rbml::Doc) -> hir::Constness {
143     match reader::maybe_get_doc(item, tag_items_data_item_constness) {
144         None => hir::Constness::NotConst,
145         Some(constness_doc) => {
146             match reader::doc_as_u8(constness_doc) as char {
147                 'c' => hir::Constness::Const,
148                 'n' => hir::Constness::NotConst,
149                 _ => panic!("unknown constness character")
150             }
151         }
152     }
153 }
154
155 fn item_sort(item: rbml::Doc) -> Option<char> {
156     reader::tagged_docs(item, tag_item_trait_item_sort).nth(0).map(|doc| {
157         doc.as_str_slice().as_bytes()[0] as char
158     })
159 }
160
161 fn item_symbol(item: rbml::Doc) -> String {
162     reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
163 }
164
165 fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
166     let id = reader::doc_as_u64(d);
167     let def_id = DefId { krate: (id >> 32) as u32, node: id as u32 };
168     translate_def_id(cdata, def_id)
169 }
170
171 fn item_parent_item(cdata: Cmd, d: rbml::Doc) -> Option<DefId> {
172     reader::tagged_docs(d, tag_items_data_parent_item).nth(0).map(|did| {
173         translated_def_id(cdata, did)
174     })
175 }
176
177 fn item_require_parent_item(cdata: Cmd, d: rbml::Doc) -> DefId {
178     translated_def_id(cdata, reader::get_doc(d, tag_items_data_parent_item))
179 }
180
181 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
182     translated_def_id(cdata, reader::get_doc(d, tag_def_id))
183 }
184
185 fn get_provided_source(d: rbml::Doc, cdata: Cmd) -> Option<DefId> {
186     reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
187         translated_def_id(cdata, doc)
188     })
189 }
190
191 fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
192     reader::tagged_docs(d, tag_items_data_item_reexport)
193 }
194
195 fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
196     reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
197         reader::with_doc_data(val_doc, |data| {
198             str::from_utf8(data).ok().and_then(|s| s.parse().ok())
199         })
200     })
201 }
202
203 fn doc_type<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
204     let tp = reader::get_doc(doc, tag_items_data_item_type);
205     TyDecoder::with_doc(tcx, cdata.cnum, tp,
206                         &mut |_, did| translate_def_id(cdata, did))
207         .parse_ty()
208 }
209
210 fn maybe_doc_type<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Option<Ty<'tcx>> {
211     reader::maybe_get_doc(doc, tag_items_data_item_type).map(|tp| {
212         TyDecoder::with_doc(tcx, cdata.cnum, tp,
213                             &mut |_, did| translate_def_id(cdata, did))
214             .parse_ty()
215     })
216 }
217
218 fn doc_method_fty<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>,
219                         cdata: Cmd) -> ty::BareFnTy<'tcx> {
220     let tp = reader::get_doc(doc, tag_item_method_fty);
221     TyDecoder::with_doc(tcx, cdata.cnum, tp,
222                         &mut |_, did| translate_def_id(cdata, did))
223         .parse_bare_fn_ty()
224 }
225
226 pub fn item_type<'tcx>(_item_id: DefId, item: rbml::Doc,
227                        tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
228     doc_type(item, tcx, cdata)
229 }
230
231 fn doc_trait_ref<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd)
232                        -> ty::TraitRef<'tcx> {
233     TyDecoder::with_doc(tcx, cdata.cnum, doc,
234                         &mut |_, did| translate_def_id(cdata, did))
235         .parse_trait_ref()
236 }
237
238 fn item_trait_ref<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd)
239                         -> ty::TraitRef<'tcx> {
240     let tp = reader::get_doc(doc, tag_item_trait_ref);
241     doc_trait_ref(tp, tcx, cdata)
242 }
243
244 fn item_path(item_doc: rbml::Doc) -> Vec<ast_map::PathElem> {
245     let path_doc = reader::get_doc(item_doc, tag_path);
246     reader::docs(path_doc).filter_map(|(tag, elt_doc)| {
247         if tag == tag_path_elem_mod {
248             let s = elt_doc.as_str_slice();
249             Some(ast_map::PathMod(token::intern(s)))
250         } else if tag == tag_path_elem_name {
251             let s = elt_doc.as_str_slice();
252             Some(ast_map::PathName(token::intern(s)))
253         } else {
254             // ignore tag_path_len element
255             None
256         }
257     }).collect()
258 }
259
260 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Name {
261     let name = reader::get_doc(item, tag_paths_data_name);
262     let string = name.as_str_slice();
263     match intr.find(string) {
264         None => token::intern(string),
265         Some(val) => val,
266     }
267 }
268
269 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
270     let fam = item_family(item);
271     match fam {
272         Constant  => {
273             // Check whether we have an associated const item.
274             if item_sort(item) == Some('C') {
275                 DlDef(def::DefAssociatedConst(did))
276             } else {
277                 // Regular const item.
278                 DlDef(def::DefConst(did))
279             }
280         }
281         ImmStatic => DlDef(def::DefStatic(did, false)),
282         MutStatic => DlDef(def::DefStatic(did, true)),
283         Struct    => DlDef(def::DefStruct(did)),
284         Fn        => DlDef(def::DefFn(did, false)),
285         CtorFn    => DlDef(def::DefFn(did, true)),
286         Method | StaticMethod => {
287             DlDef(def::DefMethod(did))
288         }
289         Type => {
290             if item_sort(item) == Some('t') {
291                 let trait_did = item_require_parent_item(cdata, item);
292                 DlDef(def::DefAssociatedTy(trait_did, did))
293             } else {
294                 DlDef(def::DefTy(did, false))
295             }
296         }
297         Mod => DlDef(def::DefMod(did)),
298         ForeignMod => DlDef(def::DefForeignMod(did)),
299         StructVariant => {
300             let enum_did = item_require_parent_item(cdata, item);
301             DlDef(def::DefVariant(enum_did, did, true))
302         }
303         TupleVariant => {
304             let enum_did = item_require_parent_item(cdata, item);
305             DlDef(def::DefVariant(enum_did, did, false))
306         }
307         Trait => DlDef(def::DefTrait(did)),
308         Enum => DlDef(def::DefTy(did, true)),
309         Impl | DefaultImpl => DlImpl(did),
310         PublicField | InheritedField => DlField,
311     }
312 }
313
314 fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
315     let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
316     if reader::doc_as_u8(unsafety_doc) != 0 {
317         hir::Unsafety::Unsafe
318     } else {
319         hir::Unsafety::Normal
320     }
321 }
322
323 fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
324     let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
325     reader::doc_as_u8(paren_sugar_doc) != 0
326 }
327
328 fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
329     let polarity_doc = reader::get_doc(item_doc, tag_polarity);
330     if reader::doc_as_u8(polarity_doc) != 0 {
331         hir::ImplPolarity::Negative
332     } else {
333         hir::ImplPolarity::Positive
334     }
335 }
336
337 fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
338     let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
339     reader::tagged_docs(names_doc, tag_associated_type_name)
340         .map(|name_doc| token::intern(name_doc.as_str_slice()))
341         .collect()
342 }
343
344 pub fn get_trait_def<'tcx>(cdata: Cmd,
345                            item_id: ast::NodeId,
346                            tcx: &ty::ctxt<'tcx>) -> ty::TraitDef<'tcx>
347 {
348     let item_doc = cdata.lookup_item(item_id);
349     let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
350     let unsafety = parse_unsafety(item_doc);
351     let associated_type_names = parse_associated_type_names(item_doc);
352     let paren_sugar = parse_paren_sugar(item_doc);
353
354     ty::TraitDef {
355         paren_sugar: paren_sugar,
356         unsafety: unsafety,
357         generics: generics,
358         trait_ref: item_trait_ref(item_doc, tcx, cdata),
359         associated_type_names: associated_type_names,
360         nonblanket_impls: RefCell::new(FnvHashMap()),
361         blanket_impls: RefCell::new(vec![]),
362         flags: Cell::new(ty::TraitFlags::NO_TRAIT_FLAGS)
363     }
364 }
365
366 pub fn get_adt_def<'tcx>(intr: &IdentInterner,
367                          cdata: Cmd,
368                          item_id: ast::NodeId,
369                          tcx: &ty::ctxt<'tcx>) -> ty::AdtDefMaster<'tcx>
370 {
371     fn get_enum_variants<'tcx>(intr: &IdentInterner,
372                                cdata: Cmd,
373                                doc: rbml::Doc,
374                                tcx: &ty::ctxt<'tcx>) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
375         let mut disr_val = 0;
376         reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
377             let did = translated_def_id(cdata, p);
378             let item = cdata.lookup_item(did.node);
379
380             if let Some(disr) = variant_disr_val(item) {
381                 disr_val = disr;
382             }
383             let disr = disr_val;
384             disr_val = disr_val.wrapping_add(1);
385
386             ty::VariantDefData {
387                 did: did,
388                 name: item_name(intr, item),
389                 fields: get_variant_fields(intr, cdata, item, tcx),
390                 disr_val: disr
391             }
392         }).collect()
393     }
394     fn get_variant_fields<'tcx>(intr: &IdentInterner,
395                                 cdata: Cmd,
396                                 doc: rbml::Doc,
397                                 tcx: &ty::ctxt<'tcx>) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
398         reader::tagged_docs(doc, tag_item_field).map(|f| {
399             let ff = item_family(f);
400             match ff {
401                 PublicField | InheritedField => {},
402                 _ => tcx.sess.bug(&format!("expected field, found {:?}", ff))
403             };
404             ty::FieldDefData::new(item_def_id(f, cdata),
405                                   item_name(intr, f),
406                                   struct_field_family_to_visibility(ff))
407         }).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
408             let ff = item_family(f);
409             ty::FieldDefData::new(item_def_id(f, cdata),
410                                   special_idents::unnamed_field.name,
411                                   struct_field_family_to_visibility(ff))
412         })).collect()
413     }
414     fn get_struct_variant<'tcx>(intr: &IdentInterner,
415                                 cdata: Cmd,
416                                 doc: rbml::Doc,
417                                 did: DefId,
418                                 tcx: &ty::ctxt<'tcx>) -> ty::VariantDefData<'tcx, 'tcx> {
419         ty::VariantDefData {
420             did: did,
421             name: item_name(intr, doc),
422             fields: get_variant_fields(intr, cdata, doc, tcx),
423             disr_val: 0
424         }
425     }
426
427     let doc = cdata.lookup_item(item_id);
428     let did = DefId { krate: cdata.cnum, node: item_id };
429     let (kind, variants) = match item_family(doc) {
430         Enum => (ty::AdtKind::Enum,
431                  get_enum_variants(intr, cdata, doc, tcx)),
432         Struct => (ty::AdtKind::Struct,
433                    vec![get_struct_variant(intr, cdata, doc, did, tcx)]),
434         _ => tcx.sess.bug("get_adt_def called on a non-ADT")
435     };
436
437     let adt = tcx.intern_adt_def(did, kind, variants);
438
439     // this needs to be done *after* the variant is interned,
440     // to support recursive structures
441     for variant in &adt.variants {
442         if variant.kind() == ty::VariantKind::Tuple &&
443             adt.adt_kind() == ty::AdtKind::Enum {
444             // tuple-like enum variant fields aren't real items - get the types
445             // from the ctor.
446             debug!("evaluating the ctor-type of {:?}",
447                    variant.name);
448             let ctor_ty = get_type(cdata, variant.did.node, tcx).ty;
449             debug!("evaluating the ctor-type of {:?}.. {:?}",
450                    variant.name,
451                    ctor_ty);
452             let field_tys = match ctor_ty.sty {
453                 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
454                     ref inputs, ..
455                 }), ..}) => {
456                     // tuple-struct constructors don't have escaping regions
457                     assert!(!inputs.has_escaping_regions());
458                     inputs
459                 },
460                 _ => tcx.sess.bug("tuple-variant ctor is not an ADT")
461             };
462             for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
463                 field.fulfill_ty(ty);
464             }
465         } else {
466             for field in &variant.fields {
467                 debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
468                 let ty = get_type(cdata, field.did.node, tcx).ty;
469                 field.fulfill_ty(ty);
470                 debug!("evaluating the type of {:?}::{:?}: {:?}",
471                        variant.name, field.name, ty);
472             }
473         }
474     }
475
476     adt
477 }
478
479 pub fn get_predicates<'tcx>(cdata: Cmd,
480                             item_id: ast::NodeId,
481                             tcx: &ty::ctxt<'tcx>)
482                             -> ty::GenericPredicates<'tcx>
483 {
484     let item_doc = cdata.lookup_item(item_id);
485     doc_predicates(item_doc, tcx, cdata, tag_item_generics)
486 }
487
488 pub fn get_super_predicates<'tcx>(cdata: Cmd,
489                                   item_id: ast::NodeId,
490                                   tcx: &ty::ctxt<'tcx>)
491                                   -> ty::GenericPredicates<'tcx>
492 {
493     let item_doc = cdata.lookup_item(item_id);
494     doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
495 }
496
497 pub fn get_type<'tcx>(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt<'tcx>)
498                       -> ty::TypeScheme<'tcx>
499 {
500     let item_doc = cdata.lookup_item(id);
501     let t = item_type(DefId { krate: cdata.cnum, node: id }, item_doc, tcx,
502                       cdata);
503     let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
504     ty::TypeScheme {
505         generics: generics,
506         ty: t
507     }
508 }
509
510 pub fn get_stability(cdata: Cmd, id: ast::NodeId) -> Option<attr::Stability> {
511     let item = cdata.lookup_item(id);
512     reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
513         let mut decoder = reader::Decoder::new(doc);
514         Decodable::decode(&mut decoder).unwrap()
515     })
516 }
517
518 pub fn get_repr_attrs(cdata: Cmd, id: ast::NodeId) -> Vec<attr::ReprAttr> {
519     let item = cdata.lookup_item(id);
520     match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
521         let mut decoder = reader::Decoder::new(doc);
522         Decodable::decode(&mut decoder).unwrap()
523     }) {
524         Some(attrs) => attrs,
525         None => Vec::new(),
526     }
527 }
528
529 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
530                                id: ast::NodeId)
531                                -> Option<hir::ImplPolarity>
532 {
533     let item_doc = cdata.lookup_item(id);
534     let fam = item_family(item_doc);
535     match fam {
536         Family::Impl => {
537             Some(parse_polarity(item_doc))
538         }
539         _ => None
540     }
541 }
542
543 pub fn get_custom_coerce_unsized_kind<'tcx>(cdata: Cmd,
544                                             id: ast::NodeId)
545                                             -> Option<ty::CustomCoerceUnsized> {
546     let item_doc = cdata.lookup_item(id);
547     reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
548         let mut decoder = reader::Decoder::new(kind_doc);
549         Decodable::decode(&mut decoder).unwrap()
550     })
551 }
552
553 pub fn get_impl_trait<'tcx>(cdata: Cmd,
554                             id: ast::NodeId,
555                             tcx: &ty::ctxt<'tcx>)
556                             -> Option<ty::TraitRef<'tcx>>
557 {
558     let item_doc = cdata.lookup_item(id);
559     let fam = item_family(item_doc);
560     match fam {
561         Family::Impl | Family::DefaultImpl => {
562             reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
563                 doc_trait_ref(tp, tcx, cdata)
564             })
565         }
566         _ => None
567     }
568 }
569
570 pub fn get_symbol(cdata: Cmd, id: ast::NodeId) -> String {
571     return item_symbol(cdata.lookup_item(id));
572 }
573
574 /// If you have a crate_metadata, call get_symbol instead
575 pub fn get_symbol_from_buf(data: &[u8], id: ast::NodeId) -> String {
576     let index = load_index(data);
577     let pos = index.lookup_item(data, id).unwrap();
578     let doc = reader::doc_at(data, pos as usize).unwrap().doc;
579     item_symbol(doc)
580 }
581
582 // Something that a name can resolve to.
583 #[derive(Copy, Clone, Debug)]
584 pub enum DefLike {
585     DlDef(def::Def),
586     DlImpl(DefId),
587     DlField
588 }
589
590 /// Iterates over the language items in the given crate.
591 pub fn each_lang_item<F>(cdata: Cmd, mut f: F) -> bool where
592     F: FnMut(ast::NodeId, usize) -> bool,
593 {
594     let root = rbml::Doc::new(cdata.data());
595     let lang_items = reader::get_doc(root, tag_lang_items);
596     reader::tagged_docs(lang_items, tag_lang_items_item).all(|item_doc| {
597         let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
598         let id = reader::doc_as_u32(id_doc) as usize;
599         let node_id_doc = reader::get_doc(item_doc,
600                                           tag_lang_items_item_node_id);
601         let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
602
603         f(node_id, id)
604     })
605 }
606
607 fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
608                                      cdata: Cmd,
609                                      item_doc: rbml::Doc,
610                                      mut get_crate_data: G,
611                                      mut callback: F) where
612     F: FnMut(DefLike, ast::Name, hir::Visibility),
613     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
614 {
615     // Iterate over all children.
616     for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
617         let child_def_id = translated_def_id(cdata, child_info_doc);
618
619         // This item may be in yet another crate if it was the child of a
620         // reexport.
621         let crate_data = if child_def_id.krate == cdata.cnum {
622             None
623         } else {
624             Some(get_crate_data(child_def_id.krate))
625         };
626         let crate_data = match crate_data {
627             Some(ref cdata) => &**cdata,
628             None => cdata
629         };
630
631         // Get the item.
632         match crate_data.get_item(child_def_id.node) {
633             None => {}
634             Some(child_item_doc) => {
635                 // Hand off the item to the callback.
636                 let child_name = item_name(&*intr, child_item_doc);
637                 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
638                 let visibility = item_visibility(child_item_doc);
639                 callback(def_like, child_name, visibility);
640             }
641         }
642     }
643
644     // As a special case, iterate over all static methods of
645     // associated implementations too. This is a bit of a botch.
646     // --pcwalton
647     for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
648                                                              tag_items_data_item_inherent_impl) {
649         let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
650         if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.node) {
651             for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
652                                                                  tag_item_impl_item) {
653                 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
654                                                    cdata);
655                 if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.node) {
656                     if let StaticMethod = item_family(impl_method_doc) {
657                         // Hand off the static method to the callback.
658                         let static_method_name = item_name(&*intr, impl_method_doc);
659                         let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
660                                                                       impl_item_def_id);
661                         callback(static_method_def_like,
662                                  static_method_name,
663                                  item_visibility(impl_method_doc));
664                     }
665                 }
666             }
667         }
668     }
669
670     for reexport_doc in reexports(item_doc) {
671         let def_id_doc = reader::get_doc(reexport_doc,
672                                          tag_items_data_item_reexport_def_id);
673         let child_def_id = translated_def_id(cdata, def_id_doc);
674
675         let name_doc = reader::get_doc(reexport_doc,
676                                        tag_items_data_item_reexport_name);
677         let name = name_doc.as_str_slice();
678
679         // This reexport may be in yet another crate.
680         let crate_data = if child_def_id.krate == cdata.cnum {
681             None
682         } else {
683             Some(get_crate_data(child_def_id.krate))
684         };
685         let crate_data = match crate_data {
686             Some(ref cdata) => &**cdata,
687             None => cdata
688         };
689
690         // Get the item.
691         if let Some(child_item_doc) = crate_data.get_item(child_def_id.node) {
692             // Hand off the item to the callback.
693             let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
694             // These items have a public visibility because they're part of
695             // a public re-export.
696             callback(def_like, token::intern(name), hir::Public);
697         }
698     }
699 }
700
701 /// Iterates over each child of the given item.
702 pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
703                                cdata: Cmd,
704                                id: ast::NodeId,
705                                get_crate_data: G,
706                                callback: F) where
707     F: FnMut(DefLike, ast::Name, hir::Visibility),
708     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
709 {
710     // Find the item.
711     let item_doc = match cdata.get_item(id) {
712         None => return,
713         Some(item_doc) => item_doc,
714     };
715
716     each_child_of_item_or_crate(intr,
717                                 cdata,
718                                 item_doc,
719                                 get_crate_data,
720                                 callback)
721 }
722
723 /// Iterates over all the top-level crate items.
724 pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
725                                           cdata: Cmd,
726                                           get_crate_data: G,
727                                           callback: F) where
728     F: FnMut(DefLike, ast::Name, hir::Visibility),
729     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
730 {
731     let root_doc = rbml::Doc::new(cdata.data());
732     let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
733     let crate_items_doc = reader::get_doc(misc_info_doc,
734                                           tag_misc_info_crate_items);
735
736     each_child_of_item_or_crate(intr,
737                                 cdata,
738                                 crate_items_doc,
739                                 get_crate_data,
740                                 callback)
741 }
742
743 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
744     item_path(cdata.lookup_item(id))
745 }
746
747 pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: ast::NodeId) -> ast::Name {
748     item_name(intr, cdata.lookup_item(id))
749 }
750
751 pub type DecodeInlinedItem<'a> =
752     Box<for<'tcx> FnMut(Cmd,
753                         &ty::ctxt<'tcx>,
754                         Vec<ast_map::PathElem>,
755                         rbml::Doc)
756                         -> Result<&'tcx InlinedItem, Vec<ast_map::PathElem>> + 'a>;
757
758 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: ast::NodeId,
759                                 mut decode_inlined_item: DecodeInlinedItem)
760                                 -> csearch::FoundAst<'tcx> {
761     debug!("Looking up item: {}", id);
762     let item_doc = cdata.lookup_item(id);
763     let path = item_path(item_doc).split_last().unwrap().1.to_vec();
764     match decode_inlined_item(cdata, tcx, path, item_doc) {
765         Ok(ii) => csearch::FoundAst::Found(ii),
766         Err(path) => {
767             match item_parent_item(cdata, item_doc) {
768                 Some(did) => {
769                     let parent_item = cdata.lookup_item(did.node);
770                     match decode_inlined_item(cdata, tcx, path, parent_item) {
771                         Ok(ii) => csearch::FoundAst::FoundParent(did, ii),
772                         Err(_) => csearch::FoundAst::NotFound
773                     }
774                 }
775                 None => csearch::FoundAst::NotFound
776             }
777         }
778     }
779 }
780
781 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
782     fn get_mutability(ch: u8) -> hir::Mutability {
783         match ch as char {
784             'i' => hir::MutImmutable,
785             'm' => hir::MutMutable,
786             _ => panic!("unknown mutability character: `{}`", ch as char),
787         }
788     }
789
790     let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
791     let string = explicit_self_doc.as_str_slice();
792
793     let explicit_self_kind = string.as_bytes()[0];
794     match explicit_self_kind as char {
795         's' => ty::StaticExplicitSelfCategory,
796         'v' => ty::ByValueExplicitSelfCategory,
797         '~' => ty::ByBoxExplicitSelfCategory,
798         // FIXME(#4846) expl. region
799         '&' => {
800             ty::ByReferenceExplicitSelfCategory(
801                 ty::ReEmpty,
802                 get_mutability(string.as_bytes()[1]))
803         }
804         _ => panic!("unknown self type code: `{}`", explicit_self_kind as char)
805     }
806 }
807
808 /// Returns the def IDs of all the items in the given implementation.
809 pub fn get_impl_items(cdata: Cmd, impl_id: ast::NodeId)
810                       -> Vec<ty::ImplOrTraitItemId> {
811     reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
812         let def_id = item_def_id(doc, cdata);
813         match item_sort(doc) {
814             Some('C') => ty::ConstTraitItemId(def_id),
815             Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
816             Some('t') => ty::TypeTraitItemId(def_id),
817             _ => panic!("unknown impl item sort"),
818         }
819     }).collect()
820 }
821
822 pub fn get_trait_name(intr: Rc<IdentInterner>,
823                       cdata: Cmd,
824                       id: ast::NodeId)
825                       -> ast::Name {
826     let doc = cdata.lookup_item(id);
827     item_name(&*intr, doc)
828 }
829
830 pub fn is_static_method(cdata: Cmd, id: ast::NodeId) -> bool {
831     let doc = cdata.lookup_item(id);
832     match item_sort(doc) {
833         Some('r') | Some('p') => {
834             get_explicit_self(doc) == ty::StaticExplicitSelfCategory
835         }
836         _ => false
837     }
838 }
839
840 pub fn get_impl_or_trait_item<'tcx>(intr: Rc<IdentInterner>,
841                                     cdata: Cmd,
842                                     id: ast::NodeId,
843                                     tcx: &ty::ctxt<'tcx>)
844                                     -> ty::ImplOrTraitItem<'tcx> {
845     let item_doc = cdata.lookup_item(id);
846
847     let def_id = item_def_id(item_doc, cdata);
848
849     let container_id = item_require_parent_item(cdata, item_doc);
850     let container_doc = cdata.lookup_item(container_id.node);
851     let container = match item_family(container_doc) {
852         Trait => TraitContainer(container_id),
853         _ => ImplContainer(container_id),
854     };
855
856     let name = item_name(&*intr, item_doc);
857     let vis = item_visibility(item_doc);
858
859     match item_sort(item_doc) {
860         Some('C') => {
861             let ty = doc_type(item_doc, tcx, cdata);
862             let default = get_provided_source(item_doc, cdata);
863             ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
864                 name: name,
865                 ty: ty,
866                 vis: vis,
867                 def_id: def_id,
868                 container: container,
869                 default: default,
870             }))
871         }
872         Some('r') | Some('p') => {
873             let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
874             let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
875             let fty = doc_method_fty(item_doc, tcx, cdata);
876             let explicit_self = get_explicit_self(item_doc);
877             let provided_source = get_provided_source(item_doc, cdata);
878
879             ty::MethodTraitItem(Rc::new(ty::Method::new(name,
880                                                         generics,
881                                                         predicates,
882                                                         fty,
883                                                         explicit_self,
884                                                         vis,
885                                                         def_id,
886                                                         container,
887                                                         provided_source)))
888         }
889         Some('t') => {
890             let ty = maybe_doc_type(item_doc, tcx, cdata);
891             ty::TypeTraitItem(Rc::new(ty::AssociatedType {
892                 name: name,
893                 ty: ty,
894                 vis: vis,
895                 def_id: def_id,
896                 container: container,
897             }))
898         }
899         _ => panic!("unknown impl/trait item sort"),
900     }
901 }
902
903 pub fn get_trait_item_def_ids(cdata: Cmd, id: ast::NodeId)
904                               -> Vec<ty::ImplOrTraitItemId> {
905     let item = cdata.lookup_item(id);
906     reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
907         let def_id = item_def_id(mth, cdata);
908         match item_sort(mth) {
909             Some('C') => ty::ConstTraitItemId(def_id),
910             Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
911             Some('t') => ty::TypeTraitItemId(def_id),
912             _ => panic!("unknown trait item sort"),
913         }
914     }).collect()
915 }
916
917 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
918     let item_doc = cdata.lookup_item(id);
919     let variance_doc = reader::get_doc(item_doc, tag_item_variances);
920     let mut decoder = reader::Decoder::new(variance_doc);
921     Decodable::decode(&mut decoder).unwrap()
922 }
923
924 pub fn get_provided_trait_methods<'tcx>(intr: Rc<IdentInterner>,
925                                         cdata: Cmd,
926                                         id: ast::NodeId,
927                                         tcx: &ty::ctxt<'tcx>)
928                                         -> Vec<Rc<ty::Method<'tcx>>> {
929     let item = cdata.lookup_item(id);
930
931     reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
932         let did = item_def_id(mth_id, cdata);
933         let mth = cdata.lookup_item(did.node);
934
935         if item_sort(mth) == Some('p') {
936             let trait_item = get_impl_or_trait_item(intr.clone(),
937                                                     cdata,
938                                                     did.node,
939                                                     tcx);
940             if let ty::MethodTraitItem(ref method) = trait_item {
941                 Some((*method).clone())
942             } else {
943                 None
944             }
945         } else {
946             None
947         }
948     }).collect()
949 }
950
951 pub fn get_associated_consts<'tcx>(intr: Rc<IdentInterner>,
952                                    cdata: Cmd,
953                                    id: ast::NodeId,
954                                    tcx: &ty::ctxt<'tcx>)
955                                    -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
956     let item = cdata.lookup_item(id);
957
958     [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
959         reader::tagged_docs(item, tag).filter_map(|ac_id| {
960             let did = item_def_id(ac_id, cdata);
961             let ac_doc = cdata.lookup_item(did.node);
962
963             if item_sort(ac_doc) == Some('C') {
964                 let trait_item = get_impl_or_trait_item(intr.clone(),
965                                                         cdata,
966                                                         did.node,
967                                                         tcx);
968                 if let ty::ConstTraitItem(ref ac) = trait_item {
969                     Some((*ac).clone())
970                 } else {
971                     None
972                 }
973             } else {
974                 None
975             }
976         })
977     }).collect()
978 }
979
980 pub fn get_type_name_if_impl(cdata: Cmd,
981                              node_id: ast::NodeId) -> Option<ast::Name> {
982     let item = cdata.lookup_item(node_id);
983     if item_family(item) != Impl {
984         return None;
985     }
986
987     reader::tagged_docs(item, tag_item_impl_type_basename).nth(0).map(|doc| {
988         token::intern(doc.as_str_slice())
989     })
990 }
991
992 pub fn get_methods_if_impl(intr: Rc<IdentInterner>,
993                                   cdata: Cmd,
994                                   node_id: ast::NodeId)
995                                -> Option<Vec<MethodInfo> > {
996     let item = cdata.lookup_item(node_id);
997     if item_family(item) != Impl {
998         return None;
999     }
1000
1001     // If this impl implements a trait, don't consider it.
1002     if reader::tagged_docs(item, tag_item_trait_ref).next().is_some() {
1003         return None;
1004     }
1005
1006     let impl_method_ids = reader::tagged_docs(item, tag_item_impl_item)
1007         .map(|impl_method_doc| item_def_id(impl_method_doc, cdata));
1008
1009     let mut impl_methods = Vec::new();
1010     for impl_method_id in impl_method_ids {
1011         let impl_method_doc = cdata.lookup_item(impl_method_id.node);
1012         let family = item_family(impl_method_doc);
1013         match family {
1014             StaticMethod | Method => {
1015                 impl_methods.push(MethodInfo {
1016                     name: item_name(&*intr, impl_method_doc),
1017                     def_id: item_def_id(impl_method_doc, cdata),
1018                     vis: item_visibility(impl_method_doc),
1019                 });
1020             }
1021             _ => {}
1022         }
1023     }
1024
1025     return Some(impl_methods);
1026 }
1027
1028 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1029 /// the actual type definition, otherwise, return None
1030 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1031                                            node_id: ast::NodeId)
1032     -> Option<DefId>
1033 {
1034     let item = cdata.lookup_item(node_id);
1035     reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1036         item_require_parent_item(cdata, item)
1037     })
1038 }
1039
1040 pub fn get_item_attrs(cdata: Cmd,
1041                       orig_node_id: ast::NodeId)
1042                       -> Vec<hir::Attribute> {
1043     // The attributes for a tuple struct are attached to the definition, not the ctor;
1044     // we assume that someone passing in a tuple struct ctor is actually wanting to
1045     // look at the definition
1046     let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1047     let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id);
1048     let item = cdata.lookup_item(node_id);
1049     get_attributes(item)
1050 }
1051
1052 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<ast::NodeId, Vec<hir::Attribute>> {
1053     let data = rbml::Doc::new(cdata.data());
1054     let fields = reader::get_doc(data, tag_struct_fields);
1055     reader::tagged_docs(fields, tag_struct_field).map(|field| {
1056         let id = reader::doc_as_u32(reader::get_doc(field, tag_struct_field_id));
1057         let attrs = get_attributes(field);
1058         (id, attrs)
1059     }).collect()
1060 }
1061
1062 fn struct_field_family_to_visibility(family: Family) -> hir::Visibility {
1063     match family {
1064       PublicField => hir::Public,
1065       InheritedField => hir::Inherited,
1066       _ => panic!()
1067     }
1068 }
1069
1070 pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: ast::NodeId)
1071     -> Vec<ast::Name> {
1072     let item = cdata.lookup_item(id);
1073     reader::tagged_docs(item, tag_item_field).map(|an_item| {
1074         item_name(intr, an_item)
1075     }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1076         special_idents::unnamed_field.name
1077     })).collect()
1078 }
1079
1080 fn get_meta_items(md: rbml::Doc) -> Vec<P<hir::MetaItem>> {
1081     reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1082         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1083         let n = token::intern_and_get_ident(nd.as_str_slice());
1084         attr::mk_word_item(n)
1085     }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1086         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1087         let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1088         let n = token::intern_and_get_ident(nd.as_str_slice());
1089         let v = token::intern_and_get_ident(vd.as_str_slice());
1090         // FIXME (#623): Should be able to decode MetaNameValue variants,
1091         // but currently the encoder just drops them
1092         attr::mk_name_value_item_str(n, v)
1093     })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1094         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1095         let n = token::intern_and_get_ident(nd.as_str_slice());
1096         let subitems = get_meta_items(meta_item_doc);
1097         attr::mk_list_item(n, subitems)
1098     })).collect()
1099 }
1100
1101 fn get_attributes(md: rbml::Doc) -> Vec<hir::Attribute> {
1102     match reader::maybe_get_doc(md, tag_attributes) {
1103         Some(attrs_d) => {
1104             reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1105                 let is_sugared_doc = reader::doc_as_u8(
1106                     reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1107                 ) == 1;
1108                 let meta_items = get_meta_items(attr_doc);
1109                 // Currently it's only possible to have a single meta item on
1110                 // an attribute
1111                 assert_eq!(meta_items.len(), 1);
1112                 let meta_item = meta_items.into_iter().nth(0).unwrap();
1113                 codemap::Spanned {
1114                     node: hir::Attribute_ {
1115                         id: attr::mk_attr_id(),
1116                         style: hir::AttrOuter,
1117                         value: meta_item,
1118                         is_sugared_doc: is_sugared_doc,
1119                     },
1120                     span: codemap::DUMMY_SP
1121                 }
1122             }).collect()
1123         },
1124         None => vec![],
1125     }
1126 }
1127
1128 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1129                          out: &mut io::Write) -> io::Result<()> {
1130     try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1131
1132     let r = get_attributes(md);
1133     for attr in &r {
1134         try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1135     }
1136
1137     write!(out, "\n\n")
1138 }
1139
1140 pub fn get_crate_attributes(data: &[u8]) -> Vec<hir::Attribute> {
1141     get_attributes(rbml::Doc::new(data))
1142 }
1143
1144 #[derive(Clone)]
1145 pub struct CrateDep {
1146     pub cnum: ast::CrateNum,
1147     pub name: String,
1148     pub hash: Svh,
1149     pub explicitly_linked: bool,
1150 }
1151
1152 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1153     let cratedoc = rbml::Doc::new(data);
1154     let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1155
1156     fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1157         let d = reader::get_doc(doc, tag_);
1158         d.as_str_slice().to_string()
1159     }
1160
1161     reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1162         let name = docstr(depdoc, tag_crate_dep_crate_name);
1163         let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash));
1164         let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1165         let explicitly_linked = reader::doc_as_u8(doc) != 0;
1166         CrateDep {
1167             cnum: crate_num as u32 + 1,
1168             name: name,
1169             hash: hash,
1170             explicitly_linked: explicitly_linked,
1171         }
1172     }).collect()
1173 }
1174
1175 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1176     try!(write!(out, "=External Dependencies=\n"));
1177     for dep in &get_crate_deps(data) {
1178         try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1179     }
1180     try!(write!(out, "\n"));
1181     Ok(())
1182 }
1183
1184 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1185     let cratedoc = rbml::Doc::new(data);
1186     reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1187         Svh::new(doc.as_str_slice())
1188     })
1189 }
1190
1191 pub fn get_crate_hash(data: &[u8]) -> Svh {
1192     let cratedoc = rbml::Doc::new(data);
1193     let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1194     Svh::new(hashdoc.as_str_slice())
1195 }
1196
1197 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1198     let cratedoc = rbml::Doc::new(data);
1199     reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1200         doc.as_str_slice().to_string()
1201     })
1202 }
1203
1204 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1205     let cratedoc = rbml::Doc::new(data);
1206     let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1207     triple_doc.map(|s| s.as_str().to_string())
1208 }
1209
1210 pub fn get_crate_name(data: &[u8]) -> String {
1211     maybe_get_crate_name(data).expect("no crate name in crate")
1212 }
1213
1214 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1215     let hash = get_crate_hash(bytes);
1216     let md = rbml::Doc::new(bytes);
1217     try!(list_crate_attributes(md, &hash, out));
1218     list_crate_deps(bytes, out)
1219 }
1220
1221 // Translates a def_id from an external crate to a def_id for the current
1222 // compilation environment. We use this when trying to load types from
1223 // external crates - if those types further refer to types in other crates
1224 // then we must translate the crate number from that encoded in the external
1225 // crate to the correct local crate number.
1226 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1227     if did.is_local() {
1228         return DefId { krate: cdata.cnum, node: did.node };
1229     }
1230
1231     match cdata.cnum_map.borrow().get(&did.krate) {
1232         Some(&n) => {
1233             DefId {
1234                 krate: n,
1235                 node: did.node,
1236             }
1237         }
1238         None => panic!("didn't find a crate in the cnum_map")
1239     }
1240 }
1241
1242 // Translate a DefId from the current compilation environment to a DefId
1243 // for an external crate.
1244 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1245     if did.krate == cdata.cnum {
1246         return Some(DefId { krate: LOCAL_CRATE, node: did.node });
1247     }
1248
1249     for (&local, &global) in cdata.cnum_map.borrow().iter() {
1250         if global == did.krate {
1251             return Some(DefId { krate: local, node: did.node });
1252         }
1253     }
1254
1255     None
1256 }
1257
1258 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1259                                                 id: ast::NodeId,
1260                                                 mut callback: F)
1261     where F: FnMut(DefId),
1262 {
1263     let item_doc = cdata.lookup_item(id);
1264     for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1265         if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1266             callback(item_def_id(impl_doc, cdata));
1267         }
1268     }
1269 }
1270
1271 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1272                                         def_id: DefId,
1273                                         mut callback: F) where
1274     F: FnMut(DefId),
1275 {
1276     if cdata.cnum == def_id.krate {
1277         let item_doc = cdata.lookup_item(def_id.node);
1278         for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_extension_impl) {
1279             callback(item_def_id(impl_doc, cdata));
1280         }
1281         return;
1282     }
1283
1284     // Do a reverse lookup beforehand to avoid touching the crate_num
1285     // hash map in the loop below.
1286     if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1287         let def_id_u64 = def_to_u64(crate_local_did);
1288
1289         let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1290         for impl_doc in reader::tagged_docs(impls_doc, tag_impls_impl) {
1291             let impl_trait = reader::get_doc(impl_doc, tag_impls_impl_trait_def_id);
1292             if reader::doc_as_u64(impl_trait) == def_id_u64 {
1293                 callback(item_def_id(impl_doc, cdata));
1294             }
1295         }
1296     }
1297 }
1298
1299 pub fn get_trait_of_item(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
1300                          -> Option<DefId> {
1301     let item_doc = cdata.lookup_item(id);
1302     let parent_item_id = match item_parent_item(cdata, item_doc) {
1303         None => return None,
1304         Some(item_id) => item_id,
1305     };
1306     let parent_item_doc = cdata.lookup_item(parent_item_id.node);
1307     match item_family(parent_item_doc) {
1308         Trait => Some(item_def_id(parent_item_doc, cdata)),
1309         Impl | DefaultImpl => {
1310             reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1311                 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1312         }
1313         _ => None
1314     }
1315 }
1316
1317
1318 pub fn get_native_libraries(cdata: Cmd)
1319                             -> Vec<(cstore::NativeLibraryKind, String)> {
1320     let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1321                                     tag_native_libraries);
1322     reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1323         let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1324         let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1325         let kind: cstore::NativeLibraryKind =
1326             cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1327         let name = name_doc.as_str().to_string();
1328         (kind, name)
1329     }).collect()
1330 }
1331
1332 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<ast::NodeId> {
1333     reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1334         .map(|doc| reader::doc_as_u32(doc))
1335 }
1336
1337 pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where
1338     F: FnMut(ast::Name, Vec<hir::Attribute>, String) -> bool,
1339 {
1340     let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1341     for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1342         let name = item_name(intr, macro_doc);
1343         let attrs = get_attributes(macro_doc);
1344         let body = reader::get_doc(macro_doc, tag_macro_def_body);
1345         if !f(name, attrs, body.as_str().to_string()) {
1346             break;
1347         }
1348     }
1349 }
1350
1351 pub fn get_dylib_dependency_formats(cdata: Cmd)
1352     -> Vec<(ast::CrateNum, cstore::LinkagePreference)>
1353 {
1354     let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1355                                   tag_dylib_dependency_formats);
1356     let mut result = Vec::new();
1357
1358     debug!("found dylib deps: {}", formats.as_str_slice());
1359     for spec in formats.as_str_slice().split(',') {
1360         if spec.is_empty() { continue }
1361         let cnum = spec.split(':').nth(0).unwrap();
1362         let link = spec.split(':').nth(1).unwrap();
1363         let cnum: ast::CrateNum = cnum.parse().unwrap();
1364         let cnum = match cdata.cnum_map.borrow().get(&cnum) {
1365             Some(&n) => n,
1366             None => panic!("didn't find a crate in the cnum_map")
1367         };
1368         result.push((cnum, if link == "d" {
1369             cstore::RequireDynamic
1370         } else {
1371             cstore::RequireStatic
1372         }));
1373     }
1374     return result;
1375 }
1376
1377 pub fn get_missing_lang_items(cdata: Cmd)
1378     -> Vec<lang_items::LangItem>
1379 {
1380     let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1381     reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1382         lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1383     }).collect()
1384 }
1385
1386 pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec<String> {
1387     let method_doc = cdata.lookup_item(id);
1388     match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1389         Some(args_doc) => {
1390             reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1391                 name_doc.as_str_slice().to_string()
1392             }).collect()
1393         },
1394         None => vec![],
1395     }
1396 }
1397
1398 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1399     let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1400                                 tag_reachable_ids);
1401     reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1402         DefId {
1403             krate: cdata.cnum,
1404             node: reader::doc_as_u32(doc),
1405         }
1406     }).collect()
1407 }
1408
1409 pub fn is_typedef(cdata: Cmd, id: ast::NodeId) -> bool {
1410     let item_doc = cdata.lookup_item(id);
1411     match item_family(item_doc) {
1412         Type => true,
1413         _ => false,
1414     }
1415 }
1416
1417 pub fn is_const_fn(cdata: Cmd, id: ast::NodeId) -> bool {
1418     let item_doc = cdata.lookup_item(id);
1419     match fn_constness(item_doc) {
1420         hir::Constness::Const => true,
1421         hir::Constness::NotConst => false,
1422     }
1423 }
1424
1425 pub fn is_impl(cdata: Cmd, id: ast::NodeId) -> bool {
1426     let item_doc = cdata.lookup_item(id);
1427     match item_family(item_doc) {
1428         Impl => true,
1429         _ => false,
1430     }
1431 }
1432
1433 fn doc_generics<'tcx>(base_doc: rbml::Doc,
1434                       tcx: &ty::ctxt<'tcx>,
1435                       cdata: Cmd,
1436                       tag: usize)
1437                       -> ty::Generics<'tcx>
1438 {
1439     let doc = reader::get_doc(base_doc, tag);
1440
1441     let mut types = subst::VecPerParamSpace::empty();
1442     for p in reader::tagged_docs(doc, tag_type_param_def) {
1443         let bd =
1444             TyDecoder::with_doc(tcx, cdata.cnum, p,
1445                                 &mut |_, did| translate_def_id(cdata, did))
1446             .parse_type_param_def();
1447         types.push(bd.space, bd);
1448     }
1449
1450     let mut regions = subst::VecPerParamSpace::empty();
1451     for rp_doc in reader::tagged_docs(doc, tag_region_param_def) {
1452         let ident_str_doc = reader::get_doc(rp_doc,
1453                                             tag_region_param_def_ident);
1454         let name = item_name(&*token::get_ident_interner(), ident_str_doc);
1455         let def_id_doc = reader::get_doc(rp_doc,
1456                                          tag_region_param_def_def_id);
1457         let def_id = translated_def_id(cdata, def_id_doc);
1458
1459         let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1460         let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as usize);
1461
1462         let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1463         let index = reader::doc_as_u64(doc) as u32;
1464
1465         let bounds = reader::tagged_docs(rp_doc, tag_items_data_region).map(|p| {
1466             TyDecoder::with_doc(tcx, cdata.cnum, p,
1467                                 &mut |_, did| translate_def_id(cdata, did))
1468             .parse_region()
1469         }).collect();
1470
1471         regions.push(space, ty::RegionParameterDef { name: name,
1472                                                      def_id: def_id,
1473                                                      space: space,
1474                                                      index: index,
1475                                                      bounds: bounds });
1476     }
1477
1478     ty::Generics { types: types, regions: regions }
1479 }
1480
1481 fn doc_predicates<'tcx>(base_doc: rbml::Doc,
1482                         tcx: &ty::ctxt<'tcx>,
1483                         cdata: Cmd,
1484                         tag: usize)
1485                         -> ty::GenericPredicates<'tcx>
1486 {
1487     let doc = reader::get_doc(base_doc, tag);
1488
1489     let mut predicates = subst::VecPerParamSpace::empty();
1490     for predicate_doc in reader::tagged_docs(doc, tag_predicate) {
1491         let space_doc = reader::get_doc(predicate_doc, tag_predicate_space);
1492         let space = subst::ParamSpace::from_uint(reader::doc_as_u8(space_doc) as usize);
1493
1494         let data_doc = reader::get_doc(predicate_doc, tag_predicate_data);
1495         let data =
1496             TyDecoder::with_doc(tcx, cdata.cnum, data_doc,
1497                                 &mut |_, did| translate_def_id(cdata, did))
1498             .parse_predicate();
1499
1500         predicates.push(space, data);
1501     }
1502
1503     ty::GenericPredicates { predicates: predicates }
1504 }
1505
1506 pub fn is_defaulted_trait(cdata: Cmd, trait_id: ast::NodeId) -> bool {
1507     let trait_doc = cdata.lookup_item(trait_id);
1508     assert!(item_family(trait_doc) == Family::Trait);
1509     let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1510     reader::doc_as_u8(defaulted_doc) != 0
1511 }
1512
1513 pub fn is_default_impl(cdata: Cmd, impl_id: ast::NodeId) -> bool {
1514     let impl_doc = cdata.lookup_item(impl_id);
1515     item_family(impl_doc) == Family::DefaultImpl
1516 }
1517
1518 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
1519     let crate_doc = rbml::Doc::new(metadata);
1520     let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1521
1522     reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1523         let mut decoder = reader::Decoder::new(filemap_doc);
1524         Decodable::decode(&mut decoder).unwrap()
1525     }).collect()
1526 }
1527
1528 pub fn is_extern_fn(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt) -> bool {
1529     let item_doc = match cdata.get_item(id) {
1530         Some(doc) => doc,
1531         None => return false,
1532     };
1533     if let Fn = item_family(item_doc) {
1534         let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1535         generics.types.is_empty() && match ty.sty {
1536             ty::TyBareFn(_, fn_ty) => fn_ty.abi != abi::Rust,
1537             _ => false,
1538         }
1539     } else {
1540         false
1541     }
1542 }