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