]> git.lizzy.rs Git - rust.git/blob - src/librustc/metadata/decoder.rs
Fix stability
[rust.git] / src / librustc / metadata / decoder.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Decoding metadata from a single crate's metadata
12
13 #![allow(non_camel_case_types)]
14
15 pub use self::DefLike::*;
16 use self::Family::*;
17
18 use front::map as hir_map;
19 use rustc_front::hir;
20
21 use back::svh::Svh;
22 use metadata::cstore::crate_metadata;
23 use metadata::cstore::LOCAL_CRATE;
24 use metadata::common::*;
25 use metadata::csearch::MethodInfo;
26 use metadata::csearch;
27 use metadata::cstore;
28 use metadata::encoder::def_to_u64;
29 use metadata::index;
30 use metadata::inline::InlinedItem;
31 use metadata::tydecode::TyDecoder;
32 use middle::def;
33 use middle::def_id::{DefId, DefIndex};
34 use middle::lang_items;
35 use middle::subst;
36 use middle::ty::{ImplContainer, TraitContainer};
37 use middle::ty::{self, RegionEscape, Ty};
38 use util::nodemap::FnvHashMap;
39
40 use std::cell::{Cell, RefCell};
41 use std::io::prelude::*;
42 use std::io;
43 use std::rc::Rc;
44 use std::str;
45
46 use rbml::reader;
47 use rbml;
48 use serialize::Decodable;
49 use syntax::attr;
50 use syntax::parse::token::{IdentInterner, special_idents};
51 use syntax::parse::token;
52 use syntax::ast;
53 use syntax::abi;
54 use syntax::codemap;
55 use syntax::print::pprust;
56 use syntax::ptr::P;
57
58
59 pub type Cmd<'a> = &'a crate_metadata;
60
61 impl crate_metadata {
62     fn get_item(&self, item_id: DefIndex) -> Option<rbml::Doc> {
63         self.index.lookup_item(self.data(), item_id).map(|pos| {
64             reader::doc_at(self.data(), pos as usize).unwrap().doc
65         })
66     }
67
68     fn lookup_item(&self, item_id: DefIndex) -> rbml::Doc {
69         match self.get_item(item_id) {
70             None => panic!("lookup_item: id not found: {:?}", item_id),
71             Some(d) => d
72         }
73     }
74 }
75
76 pub fn load_index(data: &[u8]) -> index::Index {
77     let index = reader::get_doc(rbml::Doc::new(data), tag_index);
78     index::Index::from_rbml(index)
79 }
80
81 pub fn crate_rustc_version(data: &[u8]) -> Option<String> {
82     let doc = rbml::Doc::new(data);
83     reader::maybe_get_doc(doc, tag_rustc_version).map(|s| s.as_str())
84 }
85
86 pub fn load_xrefs(data: &[u8]) -> index::DenseIndex {
87     let index = reader::get_doc(rbml::Doc::new(data), tag_xref_index);
88     index::DenseIndex::from_buf(index.data, index.start, index.end)
89 }
90
91 #[derive(Debug, PartialEq)]
92 enum Family {
93     ImmStatic,             // c
94     MutStatic,             // b
95     Fn,                    // f
96     CtorFn,                // o
97     StaticMethod,          // F
98     Method,                // h
99     Type,                  // y
100     Mod,                   // m
101     ForeignMod,            // n
102     Enum,                  // t
103     TupleVariant,          // v
104     StructVariant,         // V
105     Impl,                  // i
106     DefaultImpl,              // d
107     Trait,                 // I
108     Struct,                // S
109     PublicField,           // g
110     InheritedField,        // N
111     Constant,              // C
112 }
113
114 fn item_family(item: rbml::Doc) -> Family {
115     let fam = reader::get_doc(item, tag_items_data_item_family);
116     match reader::doc_as_u8(fam) as char {
117       'C' => Constant,
118       'c' => ImmStatic,
119       'b' => MutStatic,
120       'f' => Fn,
121       'o' => CtorFn,
122       'F' => StaticMethod,
123       'h' => Method,
124       'y' => Type,
125       'm' => Mod,
126       'n' => ForeignMod,
127       't' => Enum,
128       'v' => TupleVariant,
129       'V' => StructVariant,
130       'i' => Impl,
131       'd' => DefaultImpl,
132       'I' => Trait,
133       'S' => Struct,
134       'g' => PublicField,
135       'N' => InheritedField,
136        c => panic!("unexpected family char: {}", c)
137     }
138 }
139
140 fn item_visibility(item: rbml::Doc) -> hir::Visibility {
141     match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
142         None => hir::Public,
143         Some(visibility_doc) => {
144             match reader::doc_as_u8(visibility_doc) as char {
145                 'y' => hir::Public,
146                 'i' => hir::Inherited,
147                 _ => panic!("unknown visibility character")
148             }
149         }
150     }
151 }
152
153 fn fn_constness(item: rbml::Doc) -> hir::Constness {
154     match reader::maybe_get_doc(item, tag_items_data_item_constness) {
155         None => hir::Constness::NotConst,
156         Some(constness_doc) => {
157             match reader::doc_as_u8(constness_doc) as char {
158                 'c' => hir::Constness::Const,
159                 'n' => hir::Constness::NotConst,
160                 _ => panic!("unknown constness character")
161             }
162         }
163     }
164 }
165
166 fn item_sort(item: rbml::Doc) -> Option<char> {
167     reader::tagged_docs(item, tag_item_trait_item_sort).nth(0).map(|doc| {
168         doc.as_str_slice().as_bytes()[0] as char
169     })
170 }
171
172 fn item_symbol(item: rbml::Doc) -> String {
173     reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
174 }
175
176 fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
177     let id = reader::doc_as_u64(d);
178     let index = DefIndex::new((id & 0xFFFF_FFFF) as usize);
179     let def_id = DefId { krate: (id >> 32) as u32, index: index };
180     translate_def_id(cdata, def_id)
181 }
182
183 fn item_parent_item(cdata: Cmd, d: rbml::Doc) -> Option<DefId> {
184     reader::tagged_docs(d, tag_items_data_parent_item).nth(0).map(|did| {
185         translated_def_id(cdata, did)
186     })
187 }
188
189 fn item_require_parent_item(cdata: Cmd, d: rbml::Doc) -> DefId {
190     translated_def_id(cdata, reader::get_doc(d, tag_items_data_parent_item))
191 }
192
193 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
194     translated_def_id(cdata, reader::get_doc(d, tag_def_id))
195 }
196
197 fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
198     reader::tagged_docs(d, tag_items_data_item_reexport)
199 }
200
201 fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
202     reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
203         reader::with_doc_data(val_doc, |data| {
204             str::from_utf8(data).ok().and_then(|s| s.parse().ok())
205         })
206     })
207 }
208
209 fn doc_type<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
210     let tp = reader::get_doc(doc, tag_items_data_item_type);
211     TyDecoder::with_doc(tcx, cdata.cnum, tp,
212                         &mut |did| translate_def_id(cdata, did))
213         .parse_ty()
214 }
215
216 fn maybe_doc_type<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Option<Ty<'tcx>> {
217     reader::maybe_get_doc(doc, tag_items_data_item_type).map(|tp| {
218         TyDecoder::with_doc(tcx, cdata.cnum, tp,
219                             &mut |did| translate_def_id(cdata, did))
220             .parse_ty()
221     })
222 }
223
224 pub fn item_type<'tcx>(_item_id: DefId, item: rbml::Doc,
225                        tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
226     doc_type(item, tcx, cdata)
227 }
228
229 fn doc_trait_ref<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd)
230                        -> ty::TraitRef<'tcx> {
231     TyDecoder::with_doc(tcx, cdata.cnum, doc,
232                         &mut |did| translate_def_id(cdata, did))
233         .parse_trait_ref()
234 }
235
236 fn item_trait_ref<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd)
237                         -> ty::TraitRef<'tcx> {
238     let tp = reader::get_doc(doc, tag_item_trait_ref);
239     doc_trait_ref(tp, tcx, cdata)
240 }
241
242 fn item_path(item_doc: rbml::Doc) -> Vec<hir_map::PathElem> {
243     let path_doc = reader::get_doc(item_doc, tag_path);
244     reader::docs(path_doc).filter_map(|(tag, elt_doc)| {
245         if tag == tag_path_elem_mod {
246             let s = elt_doc.as_str_slice();
247             Some(hir_map::PathMod(token::intern(s)))
248         } else if tag == tag_path_elem_name {
249             let s = elt_doc.as_str_slice();
250             Some(hir_map::PathName(token::intern(s)))
251         } else {
252             // ignore tag_path_len element
253             None
254         }
255     }).collect()
256 }
257
258 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Name {
259     let name = reader::get_doc(item, tag_paths_data_name);
260     let string = name.as_str_slice();
261     match intr.find(string) {
262         None => token::intern(string),
263         Some(val) => val,
264     }
265 }
266
267 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
268     let fam = item_family(item);
269     match fam {
270         Constant  => {
271             // Check whether we have an associated const item.
272             match item_sort(item) {
273                 Some('C') | Some('c') => {
274                     DlDef(def::DefAssociatedConst(did))
275                 }
276                 _ => {
277                     // Regular const item.
278                     DlDef(def::DefConst(did))
279                 }
280             }
281         }
282         ImmStatic => DlDef(def::DefStatic(did, false)),
283         MutStatic => DlDef(def::DefStatic(did, true)),
284         Struct    => DlDef(def::DefStruct(did)),
285         Fn        => DlDef(def::DefFn(did, false)),
286         CtorFn    => DlDef(def::DefFn(did, true)),
287         Method | StaticMethod => {
288             DlDef(def::DefMethod(did))
289         }
290         Type => {
291             if item_sort(item) == Some('t') {
292                 let trait_did = item_require_parent_item(cdata, item);
293                 DlDef(def::DefAssociatedTy(trait_did, did))
294             } else {
295                 DlDef(def::DefTy(did, false))
296             }
297         }
298         Mod => DlDef(def::DefMod(did)),
299         ForeignMod => DlDef(def::DefForeignMod(did)),
300         StructVariant => {
301             let enum_did = item_require_parent_item(cdata, item);
302             DlDef(def::DefVariant(enum_did, did, true))
303         }
304         TupleVariant => {
305             let enum_did = item_require_parent_item(cdata, item);
306             DlDef(def::DefVariant(enum_did, did, false))
307         }
308         Trait => DlDef(def::DefTrait(did)),
309         Enum => DlDef(def::DefTy(did, true)),
310         Impl | DefaultImpl => DlImpl(did),
311         PublicField | InheritedField => DlField,
312     }
313 }
314
315 fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
316     let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
317     if reader::doc_as_u8(unsafety_doc) != 0 {
318         hir::Unsafety::Unsafe
319     } else {
320         hir::Unsafety::Normal
321     }
322 }
323
324 fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
325     let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
326     reader::doc_as_u8(paren_sugar_doc) != 0
327 }
328
329 fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
330     let polarity_doc = reader::get_doc(item_doc, tag_polarity);
331     if reader::doc_as_u8(polarity_doc) != 0 {
332         hir::ImplPolarity::Negative
333     } else {
334         hir::ImplPolarity::Positive
335     }
336 }
337
338 fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
339     let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
340     reader::tagged_docs(names_doc, tag_associated_type_name)
341         .map(|name_doc| token::intern(name_doc.as_str_slice()))
342         .collect()
343 }
344
345 pub fn get_trait_def<'tcx>(cdata: Cmd,
346                            item_id: DefIndex,
347                            tcx: &ty::ctxt<'tcx>) -> ty::TraitDef<'tcx>
348 {
349     let item_doc = cdata.lookup_item(item_id);
350     let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
351     let unsafety = parse_unsafety(item_doc);
352     let associated_type_names = parse_associated_type_names(item_doc);
353     let paren_sugar = parse_paren_sugar(item_doc);
354
355     ty::TraitDef {
356         paren_sugar: paren_sugar,
357         unsafety: unsafety,
358         generics: generics,
359         trait_ref: item_trait_ref(item_doc, tcx, cdata),
360         associated_type_names: associated_type_names,
361         nonblanket_impls: RefCell::new(FnvHashMap()),
362         blanket_impls: RefCell::new(vec![]),
363         flags: Cell::new(ty::TraitFlags::NO_TRAIT_FLAGS)
364     }
365 }
366
367 pub fn get_adt_def<'tcx>(intr: &IdentInterner,
368                          cdata: Cmd,
369                          item_id: DefIndex,
370                          tcx: &ty::ctxt<'tcx>) -> ty::AdtDefMaster<'tcx>
371 {
372     fn get_enum_variants<'tcx>(intr: &IdentInterner,
373                                cdata: Cmd,
374                                doc: rbml::Doc,
375                                tcx: &ty::ctxt<'tcx>) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
376         let mut disr_val = 0;
377         reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
378             let did = translated_def_id(cdata, p);
379             let item = cdata.lookup_item(did.index);
380
381             if let Some(disr) = variant_disr_val(item) {
382                 disr_val = disr;
383             }
384             let disr = disr_val;
385             disr_val = disr_val.wrapping_add(1);
386
387             ty::VariantDefData {
388                 did: did,
389                 name: item_name(intr, item),
390                 fields: get_variant_fields(intr, cdata, item, tcx),
391                 ctor_id: did,
392                 disr_val: disr
393             }
394         }).collect()
395     }
396     fn get_variant_fields<'tcx>(intr: &IdentInterner,
397                                 cdata: Cmd,
398                                 doc: rbml::Doc,
399                                 tcx: &ty::ctxt<'tcx>) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
400         reader::tagged_docs(doc, tag_item_field).map(|f| {
401             let ff = item_family(f);
402             match ff {
403                 PublicField | InheritedField => {},
404                 _ => tcx.sess.bug(&format!("expected field, found {:?}", ff))
405             };
406             ty::FieldDefData::new(item_def_id(f, cdata),
407                                   item_name(intr, f),
408                                   struct_field_family_to_visibility(ff))
409         }).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
410             let ff = item_family(f);
411             ty::FieldDefData::new(item_def_id(f, cdata),
412                                   special_idents::unnamed_field.name,
413                                   struct_field_family_to_visibility(ff))
414         })).collect()
415     }
416     fn get_struct_variant<'tcx>(intr: &IdentInterner,
417                                 cdata: Cmd,
418                                 doc: rbml::Doc,
419                                 did: DefId,
420                                 ctor_id: DefId,
421                                 tcx: &ty::ctxt<'tcx>) -> ty::VariantDefData<'tcx, 'tcx> {
422         ty::VariantDefData {
423             did: did,
424             name: item_name(intr, doc),
425             fields: get_variant_fields(intr, cdata, doc, tcx),
426             ctor_id: ctor_id,
427             disr_val: 0
428         }
429     }
430
431     let doc = cdata.lookup_item(item_id);
432     let did = DefId { krate: cdata.cnum, index: item_id };
433     let (kind, variants) = match item_family(doc) {
434         Enum => {
435             (ty::AdtKind::Enum,
436              get_enum_variants(intr, cdata, doc, tcx))
437         }
438         Struct => {
439             let ctor_did =
440                 reader::maybe_get_doc(doc, tag_items_data_item_struct_ctor).
441                 map_or(did, |ctor_doc| translated_def_id(cdata, ctor_doc));
442             (ty::AdtKind::Struct,
443              vec![get_struct_variant(intr, cdata, doc, did, ctor_did, tcx)])
444         }
445         _ => tcx.sess.bug(
446             &format!("get_adt_def called on a non-ADT {:?} - {:?}",
447                      item_family(doc), did))
448     };
449
450     let adt = tcx.intern_adt_def(did, kind, variants);
451
452     // this needs to be done *after* the variant is interned,
453     // to support recursive structures
454     for variant in &adt.variants {
455         if variant.kind() == ty::VariantKind::Tuple &&
456             adt.adt_kind() == ty::AdtKind::Enum {
457             // tuple-like enum variant fields aren't real items - get the types
458             // from the ctor.
459             debug!("evaluating the ctor-type of {:?}",
460                    variant.name);
461             let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
462             debug!("evaluating the ctor-type of {:?}.. {:?}",
463                    variant.name,
464                    ctor_ty);
465             let field_tys = match ctor_ty.sty {
466                 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
467                     ref inputs, ..
468                 }), ..}) => {
469                     // tuple-struct constructors don't have escaping regions
470                     assert!(!inputs.has_escaping_regions());
471                     inputs
472                 },
473                 _ => tcx.sess.bug("tuple-variant ctor is not an ADT")
474             };
475             for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
476                 field.fulfill_ty(ty);
477             }
478         } else {
479             for field in &variant.fields {
480                 debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
481                 let ty = get_type(cdata, field.did.index, tcx).ty;
482                 field.fulfill_ty(ty);
483                 debug!("evaluating the type of {:?}::{:?}: {:?}",
484                        variant.name, field.name, ty);
485             }
486         }
487     }
488
489     adt
490 }
491
492 pub fn get_predicates<'tcx>(cdata: Cmd,
493                             item_id: DefIndex,
494                             tcx: &ty::ctxt<'tcx>)
495                             -> ty::GenericPredicates<'tcx>
496 {
497     let item_doc = cdata.lookup_item(item_id);
498     doc_predicates(item_doc, tcx, cdata, tag_item_generics)
499 }
500
501 pub fn get_super_predicates<'tcx>(cdata: Cmd,
502                                   item_id: DefIndex,
503                                   tcx: &ty::ctxt<'tcx>)
504                                   -> ty::GenericPredicates<'tcx>
505 {
506     let item_doc = cdata.lookup_item(item_id);
507     doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
508 }
509
510 pub fn get_type<'tcx>(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt<'tcx>)
511                       -> ty::TypeScheme<'tcx>
512 {
513     let item_doc = cdata.lookup_item(id);
514     let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
515                       cdata);
516     let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
517     ty::TypeScheme {
518         generics: generics,
519         ty: t
520     }
521 }
522
523 pub fn get_stability(cdata: Cmd, id: DefIndex) -> Option<attr::Stability> {
524     let item = cdata.lookup_item(id);
525     reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
526         let mut decoder = reader::Decoder::new(doc);
527         Decodable::decode(&mut decoder).unwrap()
528     })
529 }
530
531 pub fn get_repr_attrs(cdata: Cmd, id: DefIndex) -> Vec<attr::ReprAttr> {
532     let item = cdata.lookup_item(id);
533     match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
534         let mut decoder = reader::Decoder::new(doc);
535         Decodable::decode(&mut decoder).unwrap()
536     }) {
537         Some(attrs) => attrs,
538         None => Vec::new(),
539     }
540 }
541
542 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
543                                id: DefIndex)
544                                -> Option<hir::ImplPolarity>
545 {
546     let item_doc = cdata.lookup_item(id);
547     let fam = item_family(item_doc);
548     match fam {
549         Family::Impl => {
550             Some(parse_polarity(item_doc))
551         }
552         _ => None
553     }
554 }
555
556 pub fn get_custom_coerce_unsized_kind<'tcx>(
557     cdata: Cmd,
558     id: DefIndex)
559     -> Option<ty::adjustment::CustomCoerceUnsized>
560 {
561     let item_doc = cdata.lookup_item(id);
562     reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
563         let mut decoder = reader::Decoder::new(kind_doc);
564         Decodable::decode(&mut decoder).unwrap()
565     })
566 }
567
568 pub fn get_impl_trait<'tcx>(cdata: Cmd,
569                             id: DefIndex,
570                             tcx: &ty::ctxt<'tcx>)
571                             -> Option<ty::TraitRef<'tcx>>
572 {
573     let item_doc = cdata.lookup_item(id);
574     let fam = item_family(item_doc);
575     match fam {
576         Family::Impl | Family::DefaultImpl => {
577             reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
578                 doc_trait_ref(tp, tcx, cdata)
579             })
580         }
581         _ => None
582     }
583 }
584
585 pub fn get_symbol(cdata: Cmd, id: DefIndex) -> String {
586     return item_symbol(cdata.lookup_item(id));
587 }
588
589 /// If you have a crate_metadata, call get_symbol instead
590 pub fn get_symbol_from_buf(data: &[u8], id: DefIndex) -> String {
591     let index = load_index(data);
592     let pos = index.lookup_item(data, id).unwrap();
593     let doc = reader::doc_at(data, pos as usize).unwrap().doc;
594     item_symbol(doc)
595 }
596
597 // Something that a name can resolve to.
598 #[derive(Copy, Clone, Debug)]
599 pub enum DefLike {
600     DlDef(def::Def),
601     DlImpl(DefId),
602     DlField
603 }
604
605 /// Iterates over the language items in the given crate.
606 pub fn each_lang_item<F>(cdata: Cmd, mut f: F) -> bool where
607     F: FnMut(DefIndex, usize) -> bool,
608 {
609     let root = rbml::Doc::new(cdata.data());
610     let lang_items = reader::get_doc(root, tag_lang_items);
611     reader::tagged_docs(lang_items, tag_lang_items_item).all(|item_doc| {
612         let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
613         let id = reader::doc_as_u32(id_doc) as usize;
614         let index_doc = reader::get_doc(item_doc, tag_lang_items_item_index);
615         let index = DefIndex::from_u32(reader::doc_as_u32(index_doc));
616
617         f(index, id)
618     })
619 }
620
621 fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
622                                      cdata: Cmd,
623                                      item_doc: rbml::Doc,
624                                      mut get_crate_data: G,
625                                      mut callback: F) where
626     F: FnMut(DefLike, ast::Name, hir::Visibility),
627     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
628 {
629     // Iterate over all children.
630     for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
631         let child_def_id = translated_def_id(cdata, child_info_doc);
632
633         // This item may be in yet another crate if it was the child of a
634         // reexport.
635         let crate_data = if child_def_id.krate == cdata.cnum {
636             None
637         } else {
638             Some(get_crate_data(child_def_id.krate))
639         };
640         let crate_data = match crate_data {
641             Some(ref cdata) => &**cdata,
642             None => cdata
643         };
644
645         // Get the item.
646         match crate_data.get_item(child_def_id.index) {
647             None => {}
648             Some(child_item_doc) => {
649                 // Hand off the item to the callback.
650                 let child_name = item_name(&*intr, child_item_doc);
651                 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
652                 let visibility = item_visibility(child_item_doc);
653                 callback(def_like, child_name, visibility);
654             }
655         }
656     }
657
658     // As a special case, iterate over all static methods of
659     // associated implementations too. This is a bit of a botch.
660     // --pcwalton
661     for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
662                                                              tag_items_data_item_inherent_impl) {
663         let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
664         if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.index) {
665             for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
666                                                                  tag_item_impl_item) {
667                 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
668                                                    cdata);
669                 if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.index) {
670                     if let StaticMethod = item_family(impl_method_doc) {
671                         // Hand off the static method to the callback.
672                         let static_method_name = item_name(&*intr, impl_method_doc);
673                         let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
674                                                                       impl_item_def_id);
675                         callback(static_method_def_like,
676                                  static_method_name,
677                                  item_visibility(impl_method_doc));
678                     }
679                 }
680             }
681         }
682     }
683
684     for reexport_doc in reexports(item_doc) {
685         let def_id_doc = reader::get_doc(reexport_doc,
686                                          tag_items_data_item_reexport_def_id);
687         let child_def_id = translated_def_id(cdata, def_id_doc);
688
689         let name_doc = reader::get_doc(reexport_doc,
690                                        tag_items_data_item_reexport_name);
691         let name = name_doc.as_str_slice();
692
693         // This reexport may be in yet another crate.
694         let crate_data = if child_def_id.krate == cdata.cnum {
695             None
696         } else {
697             Some(get_crate_data(child_def_id.krate))
698         };
699         let crate_data = match crate_data {
700             Some(ref cdata) => &**cdata,
701             None => cdata
702         };
703
704         // Get the item.
705         if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
706             // Hand off the item to the callback.
707             let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
708             // These items have a public visibility because they're part of
709             // a public re-export.
710             callback(def_like, token::intern(name), hir::Public);
711         }
712     }
713 }
714
715 /// Iterates over each child of the given item.
716 pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
717                                cdata: Cmd,
718                                id: DefIndex,
719                                get_crate_data: G,
720                                callback: F) where
721     F: FnMut(DefLike, ast::Name, hir::Visibility),
722     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
723 {
724     // Find the item.
725     let item_doc = match cdata.get_item(id) {
726         None => return,
727         Some(item_doc) => item_doc,
728     };
729
730     each_child_of_item_or_crate(intr,
731                                 cdata,
732                                 item_doc,
733                                 get_crate_data,
734                                 callback)
735 }
736
737 /// Iterates over all the top-level crate items.
738 pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
739                                           cdata: Cmd,
740                                           get_crate_data: G,
741                                           callback: F) where
742     F: FnMut(DefLike, ast::Name, hir::Visibility),
743     G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
744 {
745     let root_doc = rbml::Doc::new(cdata.data());
746     let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
747     let crate_items_doc = reader::get_doc(misc_info_doc,
748                                           tag_misc_info_crate_items);
749
750     each_child_of_item_or_crate(intr,
751                                 cdata,
752                                 crate_items_doc,
753                                 get_crate_data,
754                                 callback)
755 }
756
757 pub fn get_item_path(cdata: Cmd, id: DefIndex) -> Vec<hir_map::PathElem> {
758     item_path(cdata.lookup_item(id))
759 }
760
761 pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: DefIndex) -> ast::Name {
762     item_name(intr, cdata.lookup_item(id))
763 }
764
765 pub type DecodeInlinedItem<'a> =
766     Box<for<'tcx> FnMut(Cmd,
767                         &ty::ctxt<'tcx>,
768                         Vec<hir_map::PathElem>,
769                         hir_map::DefPath,
770                         rbml::Doc,
771                         DefId)
772                         -> Result<&'tcx InlinedItem, (Vec<hir_map::PathElem>,
773                                                       hir_map::DefPath)> + 'a>;
774
775 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: DefIndex,
776                                 mut decode_inlined_item: DecodeInlinedItem)
777                                 -> csearch::FoundAst<'tcx> {
778     debug!("Looking up item: {:?}", id);
779     let item_doc = cdata.lookup_item(id);
780     let item_did = item_def_id(item_doc, cdata);
781     let path = item_path(item_doc).split_last().unwrap().1.to_vec();
782     let def_path = def_path(cdata, id);
783     match decode_inlined_item(cdata, tcx, path, def_path, item_doc, item_did) {
784         Ok(ii) => csearch::FoundAst::Found(ii),
785         Err((path, def_path)) => {
786             match item_parent_item(cdata, item_doc) {
787                 Some(did) => {
788                     let parent_item = cdata.lookup_item(did.index);
789                     match decode_inlined_item(cdata, tcx, path, def_path, parent_item, did) {
790                         Ok(ii) => csearch::FoundAst::FoundParent(did, ii),
791                         Err(_) => csearch::FoundAst::NotFound
792                     }
793                 }
794                 None => csearch::FoundAst::NotFound
795             }
796         }
797     }
798 }
799
800 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
801     fn get_mutability(ch: u8) -> hir::Mutability {
802         match ch as char {
803             'i' => hir::MutImmutable,
804             'm' => hir::MutMutable,
805             _ => panic!("unknown mutability character: `{}`", ch as char),
806         }
807     }
808
809     let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
810     let string = explicit_self_doc.as_str_slice();
811
812     let explicit_self_kind = string.as_bytes()[0];
813     match explicit_self_kind as char {
814         's' => ty::StaticExplicitSelfCategory,
815         'v' => ty::ByValueExplicitSelfCategory,
816         '~' => ty::ByBoxExplicitSelfCategory,
817         // FIXME(#4846) expl. region
818         '&' => {
819             ty::ByReferenceExplicitSelfCategory(
820                 ty::ReEmpty,
821                 get_mutability(string.as_bytes()[1]))
822         }
823         _ => panic!("unknown self type code: `{}`", explicit_self_kind as char)
824     }
825 }
826
827 /// Returns the def IDs of all the items in the given implementation.
828 pub fn get_impl_items(cdata: Cmd, impl_id: DefIndex)
829                       -> Vec<ty::ImplOrTraitItemId> {
830     reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
831         let def_id = item_def_id(doc, cdata);
832         match item_sort(doc) {
833             Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
834             Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
835             Some('t') => ty::TypeTraitItemId(def_id),
836             _ => panic!("unknown impl item sort"),
837         }
838     }).collect()
839 }
840
841 pub fn get_trait_name(intr: Rc<IdentInterner>,
842                       cdata: Cmd,
843                       id: DefIndex)
844                       -> ast::Name {
845     let doc = cdata.lookup_item(id);
846     item_name(&*intr, doc)
847 }
848
849 pub fn is_static_method(cdata: Cmd, id: DefIndex) -> bool {
850     let doc = cdata.lookup_item(id);
851     match item_sort(doc) {
852         Some('r') | Some('p') => {
853             get_explicit_self(doc) == ty::StaticExplicitSelfCategory
854         }
855         _ => false
856     }
857 }
858
859 pub fn get_impl_or_trait_item<'tcx>(intr: Rc<IdentInterner>,
860                                     cdata: Cmd,
861                                     id: DefIndex,
862                                     tcx: &ty::ctxt<'tcx>)
863                                     -> ty::ImplOrTraitItem<'tcx> {
864     let item_doc = cdata.lookup_item(id);
865
866     let def_id = item_def_id(item_doc, cdata);
867
868     let container_id = item_require_parent_item(cdata, item_doc);
869     let container_doc = cdata.lookup_item(container_id.index);
870     let container = match item_family(container_doc) {
871         Trait => TraitContainer(container_id),
872         _ => ImplContainer(container_id),
873     };
874
875     let name = item_name(&*intr, item_doc);
876     let vis = item_visibility(item_doc);
877
878     match item_sort(item_doc) {
879         sort @ Some('C') | sort @ Some('c') => {
880             let ty = doc_type(item_doc, tcx, cdata);
881             ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
882                 name: name,
883                 ty: ty,
884                 vis: vis,
885                 def_id: def_id,
886                 container: container,
887                 has_value: sort == Some('C')
888             }))
889         }
890         Some('r') | Some('p') => {
891             let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
892             let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
893             let ity = tcx.lookup_item_type(def_id).ty;
894             let fty = match ity.sty {
895                 ty::TyBareFn(_, fty) => fty.clone(),
896                 _ => tcx.sess.bug(&format!(
897                     "the type {:?} of the method {:?} is not a function?",
898                     ity, name))
899             };
900             let explicit_self = get_explicit_self(item_doc);
901
902             ty::MethodTraitItem(Rc::new(ty::Method::new(name,
903                                                         generics,
904                                                         predicates,
905                                                         fty,
906                                                         explicit_self,
907                                                         vis,
908                                                         def_id,
909                                                         container)))
910         }
911         Some('t') => {
912             let ty = maybe_doc_type(item_doc, tcx, cdata);
913             ty::TypeTraitItem(Rc::new(ty::AssociatedType {
914                 name: name,
915                 ty: ty,
916                 vis: vis,
917                 def_id: def_id,
918                 container: container,
919             }))
920         }
921         _ => panic!("unknown impl/trait item sort"),
922     }
923 }
924
925 pub fn get_trait_item_def_ids(cdata: Cmd, id: DefIndex)
926                               -> Vec<ty::ImplOrTraitItemId> {
927     let item = cdata.lookup_item(id);
928     reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
929         let def_id = item_def_id(mth, cdata);
930         match item_sort(mth) {
931             Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
932             Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
933             Some('t') => ty::TypeTraitItemId(def_id),
934             _ => panic!("unknown trait item sort"),
935         }
936     }).collect()
937 }
938
939 pub fn get_item_variances(cdata: Cmd, id: DefIndex) -> ty::ItemVariances {
940     let item_doc = cdata.lookup_item(id);
941     let variance_doc = reader::get_doc(item_doc, tag_item_variances);
942     let mut decoder = reader::Decoder::new(variance_doc);
943     Decodable::decode(&mut decoder).unwrap()
944 }
945
946 pub fn get_provided_trait_methods<'tcx>(intr: Rc<IdentInterner>,
947                                         cdata: Cmd,
948                                         id: DefIndex,
949                                         tcx: &ty::ctxt<'tcx>)
950                                         -> Vec<Rc<ty::Method<'tcx>>> {
951     let item = cdata.lookup_item(id);
952
953     reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
954         let did = item_def_id(mth_id, cdata);
955         let mth = cdata.lookup_item(did.index);
956
957         if item_sort(mth) == Some('p') {
958             let trait_item = get_impl_or_trait_item(intr.clone(),
959                                                     cdata,
960                                                     did.index,
961                                                     tcx);
962             if let ty::MethodTraitItem(ref method) = trait_item {
963                 Some((*method).clone())
964             } else {
965                 None
966             }
967         } else {
968             None
969         }
970     }).collect()
971 }
972
973 pub fn get_associated_consts<'tcx>(intr: Rc<IdentInterner>,
974                                    cdata: Cmd,
975                                    id: DefIndex,
976                                    tcx: &ty::ctxt<'tcx>)
977                                    -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
978     let item = cdata.lookup_item(id);
979
980     [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
981         reader::tagged_docs(item, tag).filter_map(|ac_id| {
982             let did = item_def_id(ac_id, cdata);
983             let ac_doc = cdata.lookup_item(did.index);
984
985             match item_sort(ac_doc) {
986                 Some('C') | Some('c') => {
987                     let trait_item = get_impl_or_trait_item(intr.clone(),
988                                                             cdata,
989                                                             did.index,
990                                                             tcx);
991                     if let ty::ConstTraitItem(ref ac) = trait_item {
992                         Some((*ac).clone())
993                     } else {
994                         None
995                     }
996                 }
997                 _ => None
998             }
999         })
1000     }).collect()
1001 }
1002
1003 pub fn get_methods_if_impl(intr: Rc<IdentInterner>,
1004                                   cdata: Cmd,
1005                                   node_id: DefIndex)
1006                                -> Option<Vec<MethodInfo> > {
1007     let item = cdata.lookup_item(node_id);
1008     if item_family(item) != Impl {
1009         return None;
1010     }
1011
1012     // If this impl implements a trait, don't consider it.
1013     if reader::tagged_docs(item, tag_item_trait_ref).next().is_some() {
1014         return None;
1015     }
1016
1017     let impl_method_ids = reader::tagged_docs(item, tag_item_impl_item)
1018         .map(|impl_method_doc| item_def_id(impl_method_doc, cdata));
1019
1020     let mut impl_methods = Vec::new();
1021     for impl_method_id in impl_method_ids {
1022         let impl_method_doc = cdata.lookup_item(impl_method_id.index);
1023         let family = item_family(impl_method_doc);
1024         match family {
1025             StaticMethod | Method => {
1026                 impl_methods.push(MethodInfo {
1027                     name: item_name(&*intr, impl_method_doc),
1028                     def_id: item_def_id(impl_method_doc, cdata),
1029                     vis: item_visibility(impl_method_doc),
1030                 });
1031             }
1032             _ => {}
1033         }
1034     }
1035
1036     return Some(impl_methods);
1037 }
1038
1039 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1040 /// the actual type definition, otherwise, return None
1041 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1042                                            node_id: DefIndex)
1043     -> Option<DefId>
1044 {
1045     let item = cdata.lookup_item(node_id);
1046     reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1047         item_require_parent_item(cdata, item)
1048     })
1049 }
1050
1051 pub fn get_item_attrs(cdata: Cmd,
1052                       orig_node_id: DefIndex)
1053                       -> Vec<ast::Attribute> {
1054     // The attributes for a tuple struct are attached to the definition, not the ctor;
1055     // we assume that someone passing in a tuple struct ctor is actually wanting to
1056     // look at the definition
1057     let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1058     let node_id = node_id.map(|x| x.index).unwrap_or(orig_node_id);
1059     let item = cdata.lookup_item(node_id);
1060     get_attributes(item)
1061 }
1062
1063 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<DefId, Vec<ast::Attribute>> {
1064     let data = rbml::Doc::new(cdata.data());
1065     let fields = reader::get_doc(data, tag_struct_fields);
1066     reader::tagged_docs(fields, tag_struct_field).map(|field| {
1067         let def_id = translated_def_id(cdata, reader::get_doc(field, tag_def_id));
1068         let attrs = get_attributes(field);
1069         (def_id, attrs)
1070     }).collect()
1071 }
1072
1073 fn struct_field_family_to_visibility(family: Family) -> hir::Visibility {
1074     match family {
1075       PublicField => hir::Public,
1076       InheritedField => hir::Inherited,
1077       _ => panic!()
1078     }
1079 }
1080
1081 pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: DefIndex)
1082     -> Vec<ast::Name> {
1083     let item = cdata.lookup_item(id);
1084     reader::tagged_docs(item, tag_item_field).map(|an_item| {
1085         item_name(intr, an_item)
1086     }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1087         special_idents::unnamed_field.name
1088     })).collect()
1089 }
1090
1091 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1092     reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1093         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1094         let n = token::intern_and_get_ident(nd.as_str_slice());
1095         attr::mk_word_item(n)
1096     }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1097         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1098         let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1099         let n = token::intern_and_get_ident(nd.as_str_slice());
1100         let v = token::intern_and_get_ident(vd.as_str_slice());
1101         // FIXME (#623): Should be able to decode MetaNameValue variants,
1102         // but currently the encoder just drops them
1103         attr::mk_name_value_item_str(n, v)
1104     })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1105         let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1106         let n = token::intern_and_get_ident(nd.as_str_slice());
1107         let subitems = get_meta_items(meta_item_doc);
1108         attr::mk_list_item(n, subitems)
1109     })).collect()
1110 }
1111
1112 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1113     match reader::maybe_get_doc(md, tag_attributes) {
1114         Some(attrs_d) => {
1115             reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1116                 let is_sugared_doc = reader::doc_as_u8(
1117                     reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1118                 ) == 1;
1119                 let meta_items = get_meta_items(attr_doc);
1120                 // Currently it's only possible to have a single meta item on
1121                 // an attribute
1122                 assert_eq!(meta_items.len(), 1);
1123                 let meta_item = meta_items.into_iter().nth(0).unwrap();
1124                 codemap::Spanned {
1125                     node: ast::Attribute_ {
1126                         id: attr::mk_attr_id(),
1127                         style: ast::AttrStyle::Outer,
1128                         value: meta_item,
1129                         is_sugared_doc: is_sugared_doc,
1130                     },
1131                     span: codemap::DUMMY_SP
1132                 }
1133             }).collect()
1134         },
1135         None => vec![],
1136     }
1137 }
1138
1139 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1140                          out: &mut io::Write) -> io::Result<()> {
1141     try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1142
1143     let r = get_attributes(md);
1144     for attr in &r {
1145         try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1146     }
1147
1148     write!(out, "\n\n")
1149 }
1150
1151 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1152     get_attributes(rbml::Doc::new(data))
1153 }
1154
1155 #[derive(Clone)]
1156 pub struct CrateDep {
1157     pub cnum: ast::CrateNum,
1158     pub name: String,
1159     pub hash: Svh,
1160     pub explicitly_linked: bool,
1161 }
1162
1163 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1164     let cratedoc = rbml::Doc::new(data);
1165     let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1166
1167     fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1168         let d = reader::get_doc(doc, tag_);
1169         d.as_str_slice().to_string()
1170     }
1171
1172     reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1173         let name = docstr(depdoc, tag_crate_dep_crate_name);
1174         let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash));
1175         let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1176         let explicitly_linked = reader::doc_as_u8(doc) != 0;
1177         CrateDep {
1178             cnum: crate_num as u32 + 1,
1179             name: name,
1180             hash: hash,
1181             explicitly_linked: explicitly_linked,
1182         }
1183     }).collect()
1184 }
1185
1186 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1187     try!(write!(out, "=External Dependencies=\n"));
1188     for dep in &get_crate_deps(data) {
1189         try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1190     }
1191     try!(write!(out, "\n"));
1192     Ok(())
1193 }
1194
1195 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1196     let cratedoc = rbml::Doc::new(data);
1197     reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1198         Svh::new(doc.as_str_slice())
1199     })
1200 }
1201
1202 pub fn get_crate_hash(data: &[u8]) -> Svh {
1203     let cratedoc = rbml::Doc::new(data);
1204     let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1205     Svh::new(hashdoc.as_str_slice())
1206 }
1207
1208 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1209     let cratedoc = rbml::Doc::new(data);
1210     reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1211         doc.as_str_slice().to_string()
1212     })
1213 }
1214
1215 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1216     let cratedoc = rbml::Doc::new(data);
1217     let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1218     triple_doc.map(|s| s.as_str().to_string())
1219 }
1220
1221 pub fn get_crate_name(data: &[u8]) -> String {
1222     maybe_get_crate_name(data).expect("no crate name in crate")
1223 }
1224
1225 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1226     let hash = get_crate_hash(bytes);
1227     let md = rbml::Doc::new(bytes);
1228     try!(list_crate_attributes(md, &hash, out));
1229     list_crate_deps(bytes, out)
1230 }
1231
1232 // Translates a def_id from an external crate to a def_id for the current
1233 // compilation environment. We use this when trying to load types from
1234 // external crates - if those types further refer to types in other crates
1235 // then we must translate the crate number from that encoded in the external
1236 // crate to the correct local crate number.
1237 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1238     if did.is_local() {
1239         return DefId { krate: cdata.cnum, index: did.index };
1240     }
1241
1242     match cdata.cnum_map.borrow().get(&did.krate) {
1243         Some(&n) => {
1244             DefId {
1245                 krate: n,
1246                 index: did.index,
1247             }
1248         }
1249         None => panic!("didn't find a crate in the cnum_map")
1250     }
1251 }
1252
1253 // Translate a DefId from the current compilation environment to a DefId
1254 // for an external crate.
1255 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1256     if did.krate == cdata.cnum {
1257         return Some(DefId { krate: LOCAL_CRATE, index: did.index });
1258     }
1259
1260     for (&local, &global) in cdata.cnum_map.borrow().iter() {
1261         if global == did.krate {
1262             return Some(DefId { krate: local, index: did.index });
1263         }
1264     }
1265
1266     None
1267 }
1268
1269 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1270                                                 id: DefIndex,
1271                                                 mut callback: F)
1272     where F: FnMut(DefId),
1273 {
1274     let item_doc = cdata.lookup_item(id);
1275     for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1276         if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1277             callback(item_def_id(impl_doc, cdata));
1278         }
1279     }
1280 }
1281
1282 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1283                                         def_id: DefId,
1284                                         mut callback: F) where
1285     F: FnMut(DefId),
1286 {
1287     // Do a reverse lookup beforehand to avoid touching the crate_num
1288     // hash map in the loop below.
1289     if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1290         let def_id_u64 = def_to_u64(crate_local_did);
1291
1292         let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1293         for trait_doc in reader::tagged_docs(impls_doc, tag_impls_trait) {
1294             let trait_def_id = reader::get_doc(trait_doc, tag_def_id);
1295             if reader::doc_as_u64(trait_def_id) != def_id_u64 {
1296                 continue;
1297             }
1298             for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1299                 callback(translated_def_id(cdata, impl_doc));
1300             }
1301         }
1302     }
1303 }
1304
1305 pub fn get_trait_of_item(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt)
1306                          -> Option<DefId> {
1307     let item_doc = cdata.lookup_item(id);
1308     let parent_item_id = match item_parent_item(cdata, item_doc) {
1309         None => return None,
1310         Some(item_id) => item_id,
1311     };
1312     let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1313     match item_family(parent_item_doc) {
1314         Trait => Some(item_def_id(parent_item_doc, cdata)),
1315         Impl | DefaultImpl => {
1316             reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1317                 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1318         }
1319         _ => None
1320     }
1321 }
1322
1323
1324 pub fn get_native_libraries(cdata: Cmd)
1325                             -> Vec<(cstore::NativeLibraryKind, String)> {
1326     let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1327                                     tag_native_libraries);
1328     reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1329         let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1330         let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1331         let kind: cstore::NativeLibraryKind =
1332             cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1333         let name = name_doc.as_str().to_string();
1334         (kind, name)
1335     }).collect()
1336 }
1337
1338 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<DefIndex> {
1339     reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1340         .map(|doc| DefIndex::from_u32(reader::doc_as_u32(doc)))
1341 }
1342
1343 pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where
1344     F: FnMut(ast::Name, Vec<ast::Attribute>, String) -> bool,
1345 {
1346     let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1347     for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1348         let name = item_name(intr, macro_doc);
1349         let attrs = get_attributes(macro_doc);
1350         let body = reader::get_doc(macro_doc, tag_macro_def_body);
1351         if !f(name, attrs, body.as_str().to_string()) {
1352             break;
1353         }
1354     }
1355 }
1356
1357 pub fn get_dylib_dependency_formats(cdata: Cmd)
1358     -> Vec<(ast::CrateNum, cstore::LinkagePreference)>
1359 {
1360     let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1361                                   tag_dylib_dependency_formats);
1362     let mut result = Vec::new();
1363
1364     debug!("found dylib deps: {}", formats.as_str_slice());
1365     for spec in formats.as_str_slice().split(',') {
1366         if spec.is_empty() { continue }
1367         let cnum = spec.split(':').nth(0).unwrap();
1368         let link = spec.split(':').nth(1).unwrap();
1369         let cnum: ast::CrateNum = cnum.parse().unwrap();
1370         let cnum = match cdata.cnum_map.borrow().get(&cnum) {
1371             Some(&n) => n,
1372             None => panic!("didn't find a crate in the cnum_map")
1373         };
1374         result.push((cnum, if link == "d" {
1375             cstore::RequireDynamic
1376         } else {
1377             cstore::RequireStatic
1378         }));
1379     }
1380     return result;
1381 }
1382
1383 pub fn get_missing_lang_items(cdata: Cmd)
1384     -> Vec<lang_items::LangItem>
1385 {
1386     let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1387     reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1388         lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1389     }).collect()
1390 }
1391
1392 pub fn get_method_arg_names(cdata: Cmd, id: DefIndex) -> Vec<String> {
1393     let method_doc = cdata.lookup_item(id);
1394     match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1395         Some(args_doc) => {
1396             reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1397                 name_doc.as_str_slice().to_string()
1398             }).collect()
1399         },
1400         None => vec![],
1401     }
1402 }
1403
1404 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1405     let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1406                                 tag_reachable_ids);
1407     reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1408         DefId {
1409             krate: cdata.cnum,
1410             index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1411         }
1412     }).collect()
1413 }
1414
1415 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1416     let item_doc = cdata.lookup_item(id);
1417     match item_family(item_doc) {
1418         Type => true,
1419         _ => false,
1420     }
1421 }
1422
1423 pub fn is_const_fn(cdata: Cmd, id: DefIndex) -> bool {
1424     let item_doc = cdata.lookup_item(id);
1425     match fn_constness(item_doc) {
1426         hir::Constness::Const => true,
1427         hir::Constness::NotConst => false,
1428     }
1429 }
1430
1431 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1432     let item_doc = cdata.lookup_item(id);
1433     match item_family(item_doc) {
1434         Impl => true,
1435         _ => false,
1436     }
1437 }
1438
1439 fn doc_generics<'tcx>(base_doc: rbml::Doc,
1440                       tcx: &ty::ctxt<'tcx>,
1441                       cdata: Cmd,
1442                       tag: usize)
1443                       -> ty::Generics<'tcx>
1444 {
1445     let doc = reader::get_doc(base_doc, tag);
1446
1447     let mut types = subst::VecPerParamSpace::empty();
1448     for p in reader::tagged_docs(doc, tag_type_param_def) {
1449         let bd =
1450             TyDecoder::with_doc(tcx, cdata.cnum, p,
1451                                 &mut |did| translate_def_id(cdata, did))
1452             .parse_type_param_def();
1453         types.push(bd.space, bd);
1454     }
1455
1456     let mut regions = subst::VecPerParamSpace::empty();
1457     for rp_doc in reader::tagged_docs(doc, tag_region_param_def) {
1458         let ident_str_doc = reader::get_doc(rp_doc,
1459                                             tag_region_param_def_ident);
1460         let name = item_name(&*token::get_ident_interner(), ident_str_doc);
1461         let def_id_doc = reader::get_doc(rp_doc,
1462                                          tag_region_param_def_def_id);
1463         let def_id = translated_def_id(cdata, def_id_doc);
1464
1465         let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1466         let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as usize);
1467
1468         let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1469         let index = reader::doc_as_u64(doc) as u32;
1470
1471         let bounds = reader::tagged_docs(rp_doc, tag_items_data_region).map(|p| {
1472             TyDecoder::with_doc(tcx, cdata.cnum, p,
1473                                 &mut |did| translate_def_id(cdata, did))
1474             .parse_region()
1475         }).collect();
1476
1477         regions.push(space, ty::RegionParameterDef { name: name,
1478                                                      def_id: def_id,
1479                                                      space: space,
1480                                                      index: index,
1481                                                      bounds: bounds });
1482     }
1483
1484     ty::Generics { types: types, regions: regions }
1485 }
1486
1487 fn doc_predicate<'tcx>(cdata: Cmd,
1488                        doc: rbml::Doc,
1489                        tcx: &ty::ctxt<'tcx>)
1490                        -> ty::Predicate<'tcx>
1491 {
1492     let predicate_pos = cdata.xref_index.lookup(
1493         cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1494     TyDecoder::new(
1495         cdata.data(), cdata.cnum, predicate_pos, tcx,
1496         &mut |did| translate_def_id(cdata, did)
1497     ).parse_predicate()
1498 }
1499
1500 fn doc_predicates<'tcx>(base_doc: rbml::Doc,
1501                         tcx: &ty::ctxt<'tcx>,
1502                         cdata: Cmd,
1503                         tag: usize)
1504                         -> ty::GenericPredicates<'tcx>
1505 {
1506     let doc = reader::get_doc(base_doc, tag);
1507
1508     let mut predicates = subst::VecPerParamSpace::empty();
1509     for predicate_doc in reader::tagged_docs(doc, tag_type_predicate) {
1510         predicates.push(subst::TypeSpace,
1511                         doc_predicate(cdata, predicate_doc, tcx));
1512     }
1513     for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1514         predicates.push(subst::SelfSpace,
1515                         doc_predicate(cdata, predicate_doc, tcx));
1516     }
1517     for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1518         predicates.push(subst::FnSpace,
1519                         doc_predicate(cdata, predicate_doc, tcx));
1520     }
1521
1522     ty::GenericPredicates { predicates: predicates }
1523 }
1524
1525 pub fn is_defaulted_trait(cdata: Cmd, trait_id: DefIndex) -> bool {
1526     let trait_doc = cdata.lookup_item(trait_id);
1527     assert!(item_family(trait_doc) == Family::Trait);
1528     let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1529     reader::doc_as_u8(defaulted_doc) != 0
1530 }
1531
1532 pub fn is_default_impl(cdata: Cmd, impl_id: DefIndex) -> bool {
1533     let impl_doc = cdata.lookup_item(impl_id);
1534     item_family(impl_doc) == Family::DefaultImpl
1535 }
1536
1537 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
1538     let crate_doc = rbml::Doc::new(metadata);
1539     let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1540
1541     reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1542         let mut decoder = reader::Decoder::new(filemap_doc);
1543         Decodable::decode(&mut decoder).unwrap()
1544     }).collect()
1545 }
1546
1547 pub fn is_extern_fn(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt) -> bool {
1548     let item_doc = match cdata.get_item(id) {
1549         Some(doc) => doc,
1550         None => return false,
1551     };
1552     if let Fn = item_family(item_doc) {
1553         let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1554         generics.types.is_empty() && match ty.sty {
1555             ty::TyBareFn(_, fn_ty) => fn_ty.abi != abi::Rust,
1556             _ => false,
1557         }
1558     } else {
1559         false
1560     }
1561 }
1562
1563 pub fn closure_kind(cdata: Cmd, closure_id: DefIndex) -> ty::ClosureKind {
1564     let closure_doc = cdata.lookup_item(closure_id);
1565     let closure_kind_doc = reader::get_doc(closure_doc, tag_items_closure_kind);
1566     let mut decoder = reader::Decoder::new(closure_kind_doc);
1567     ty::ClosureKind::decode(&mut decoder).unwrap()
1568 }
1569
1570 pub fn closure_ty<'tcx>(cdata: Cmd, closure_id: DefIndex, tcx: &ty::ctxt<'tcx>)
1571                         -> ty::ClosureTy<'tcx> {
1572     let closure_doc = cdata.lookup_item(closure_id);
1573     let closure_ty_doc = reader::get_doc(closure_doc, tag_items_closure_ty);
1574     TyDecoder::with_doc(tcx, cdata.cnum, closure_ty_doc, &mut |did| translate_def_id(cdata, did))
1575         .parse_closure_ty()
1576 }
1577
1578 fn def_key(item_doc: rbml::Doc) -> hir_map::DefKey {
1579     match reader::maybe_get_doc(item_doc, tag_def_key) {
1580         Some(def_key_doc) => {
1581             let mut decoder = reader::Decoder::new(def_key_doc);
1582             hir_map::DefKey::decode(&mut decoder).unwrap()
1583         }
1584         None => {
1585             panic!("failed to find block with tag {:?} for item with family {:?}",
1586                    tag_def_key,
1587                    item_family(item_doc))
1588         }
1589     }
1590 }
1591
1592 pub fn def_path(cdata: Cmd, id: DefIndex) -> hir_map::DefPath {
1593     debug!("def_path(id={:?})", id);
1594     hir_map::definitions::make_def_path(id, |parent| {
1595         debug!("def_path: parent={:?}", parent);
1596         let parent_doc = cdata.lookup_item(parent);
1597         def_key(parent_doc)
1598     })
1599 }