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