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