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