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