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