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