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