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