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