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