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