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