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