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