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