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