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