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