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