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