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.
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.
11 // Decoding metadata from a single crate's metadata
13 #![allow(non_camel_case_types)]
17 use astencode::decode_inlined_item;
18 use cstore::{self, CrateMetadata};
21 use encoder::def_to_u64;
24 use tydecode::TyDecoder;
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;
31 use rustc::session::config::PanicStrategy;
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;
39 use rustc::ty::{ImplContainer, TraitContainer};
40 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, VariantKind};
42 use rustc_const_math::ConstInt;
45 use rustc::mir::visit::MutVisitor;
54 use rustc_serialize::Decodable;
56 use syntax::parse::token;
60 use syntax::print::pprust;
62 use syntax_pos::{self, Span, BytePos, NO_EXPANSION};
64 pub type Cmd<'a> = &'a 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
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 {}",
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)
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())
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)
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);
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
122 #[derive(Clone, Copy, Debug, PartialEq)]
133 Variant(VariantKind), // V, v, w
137 Struct(VariantKind), // S, s, u
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 {
156 'V' => Variant(VariantKind::Struct),
157 'v' => Variant(VariantKind::Tuple),
158 'w' => Variant(VariantKind::Unit),
162 'S' => Struct(VariantKind::Struct),
163 's' => Struct(VariantKind::Tuple),
164 'u' => Struct(VariantKind::Unit),
166 'N' => InheritedField,
167 c => bug!("unexpected family char: {}", c)
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")
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")
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")
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
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 }
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)
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)
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))
237 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
238 translated_def_id(cdata, reader::get_doc(d, tag_def_id))
241 fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
242 reader::tagged_docs(d, tag_items_data_item_reexport)
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())
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))
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))
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)
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))
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)
287 fn item_name(item: rbml::Doc) -> ast::Name {
288 maybe_item_name(item).expect("no item in item_name")
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)
298 fn family_to_variant_kind<'tcx>(family: Family) -> Option<ty::VariantKind> {
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),
310 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
311 let fam = item_family(item);
314 // Check whether we have an associated const item.
315 match item_sort(item) {
316 Some('C') | Some('c') => {
317 DlDef(Def::AssociatedConst(did))
320 // Regular const item.
321 DlDef(Def::Const(did))
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))
333 if item_sort(item) == Some('t') {
334 let trait_did = item_require_parent_item(cdata, item);
335 DlDef(Def::AssociatedTy(trait_did, did))
337 DlDef(Def::TyAlias(did))
340 Mod => DlDef(Def::Mod(did)),
341 ForeignMod => DlDef(Def::ForeignMod(did)),
343 let enum_did = item_require_parent_item(cdata, item);
344 DlDef(Def::Variant(enum_did, did))
346 Trait => DlDef(Def::Trait(did)),
347 Enum => DlDef(Def::Enum(did)),
348 Impl | DefaultImpl => DlImpl(did),
349 PublicField | InheritedField => DlField,
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
358 hir::Unsafety::Normal
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
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
372 hir::ImplPolarity::Positive
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()))
383 pub fn get_trait_def<'a, 'tcx>(cdata: Cmd,
385 tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::TraitDef<'tcx>
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);
393 ty::TraitDef::new(unsafety,
396 item_trait_ref(item_doc, tcx, cdata),
397 associated_type_names)
400 pub fn get_adt_def<'a, 'tcx>(cdata: Cmd,
402 tcx: TyCtxt<'a, 'tcx, 'tcx>)
403 -> ty::AdtDefMaster<'tcx>
405 fn expect_variant_kind(family: Family) -> ty::VariantKind {
406 match family_to_variant_kind(family) {
408 _ => bug!("unexpected family: {:?}", family),
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);
417 if let Some(disr) = variant_disr_val(item) {
421 disr_val = disr_val.wrapping_add(1);
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)),
432 fn get_variant_fields<'tcx>(cdata: Cmd, doc: rbml::Doc) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
434 reader::tagged_docs(doc, tag_item_field).map(|f| {
435 let ff = item_family(f);
437 PublicField | InheritedField => {},
438 _ => bug!("expected field, found {:?}", ff)
440 ty::FieldDefData::new(item_def_id(f, cdata),
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()));
447 ty::FieldDefData::new(item_def_id(f, cdata), name,
448 struct_field_family_to_visibility(ff))
451 fn get_struct_variant<'tcx>(cdata: Cmd,
453 did: DefId) -> ty::VariantDefData<'tcx, 'tcx> {
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)),
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) {
469 get_enum_variants(cdata, doc))
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)
476 (ty::AdtKind::Struct,
477 vec![get_struct_variant(cdata, doc, ctor_did.unwrap_or(did))])
479 _ => bug!("get_adt_def called on a non-ADT {:?} - {:?}",
480 item_family(doc), did)
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);
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
496 debug!("evaluating the ctor-type of {:?}",
498 let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
499 debug!("evaluating the ctor-type of {:?}.. {:?}",
502 let field_tys = match ctor_ty.sty {
503 ty::TyFnDef(_, _, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
506 // tuple-struct constructors don't have escaping regions
507 assert!(!inputs.has_escaping_regions());
510 _ => bug!("tuple-variant ctor is not an ADT")
512 for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
513 field.fulfill_ty(ty);
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);
529 pub fn get_predicates<'a, 'tcx>(cdata: Cmd,
531 tcx: TyCtxt<'a, 'tcx, 'tcx>)
532 -> ty::GenericPredicates<'tcx>
534 let item_doc = cdata.lookup_item(item_id);
535 doc_predicates(item_doc, tcx, cdata, tag_item_generics)
538 pub fn get_super_predicates<'a, 'tcx>(cdata: Cmd,
540 tcx: TyCtxt<'a, 'tcx, 'tcx>)
541 -> ty::GenericPredicates<'tcx>
543 let item_doc = cdata.lookup_item(item_id);
544 doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
547 pub fn get_type<'a, 'tcx>(cdata: Cmd, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>)
548 -> ty::TypeScheme<'tcx>
550 let item_doc = cdata.lookup_item(id);
551 let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
553 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
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()
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()
576 pub fn get_visibility(cdata: Cmd, id: DefIndex) -> ty::Visibility {
577 item_visibility(cdata.lookup_item(id))
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)
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()
593 Some(attrs) => attrs,
598 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
600 -> Option<hir::ImplPolarity>
602 let item_doc = cdata.lookup_item(id);
603 let fam = item_family(item_doc);
606 Some(parse_polarity(item_doc))
612 pub fn get_custom_coerce_unsized_kind<'tcx>(
615 -> Option<ty::adjustment::CustomCoerceUnsized>
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()
624 pub fn get_impl_trait<'a, 'tcx>(cdata: Cmd,
626 tcx: TyCtxt<'a, 'tcx, 'tcx>)
627 -> Option<ty::TraitRef<'tcx>>
629 let item_doc = cdata.lookup_item(id);
630 let fam = item_family(item_doc);
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)
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,
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));
657 fn each_child_of_item_or_crate<F, G>(cdata: Cmd,
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>,
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);
668 // This item may be in yet another crate if it was the child of a
670 let crate_data = if child_def_id.krate == cdata.cnum {
673 Some(get_crate_data(child_def_id.krate))
675 let crate_data = match crate_data {
676 Some(ref cdata) => &**cdata,
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);
690 for reexport_doc in reexports(item_doc) {
691 let def_id_doc = reader::get_doc(reexport_doc,
692 tag_items_data_item_reexport_def_id);
693 let child_def_id = translated_def_id(cdata, def_id_doc);
695 let name_doc = reader::get_doc(reexport_doc,
696 tag_items_data_item_reexport_name);
697 let name = name_doc.as_str_slice();
699 // This reexport may be in yet another crate.
700 let crate_data = if child_def_id.krate == cdata.cnum {
703 Some(get_crate_data(child_def_id.krate))
705 let crate_data = match crate_data {
706 Some(ref cdata) => &**cdata,
711 if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
712 // Hand off the item to the callback.
713 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
714 // These items have a public visibility because they're part of
715 // a public re-export.
716 callback(def_like, token::intern(name), ty::Visibility::Public);
721 /// Iterates over each child of the given item.
722 pub fn each_child_of_item<F, G>(cdata: Cmd, id: DefIndex, get_crate_data: G, callback: F)
723 where F: FnMut(DefLike, ast::Name, ty::Visibility),
724 G: FnMut(ast::CrateNum) -> Rc<CrateMetadata>,
727 let item_doc = match cdata.get_item(id) {
729 Some(item_doc) => item_doc,
732 each_child_of_item_or_crate(cdata, item_doc, get_crate_data, callback)
735 /// Iterates over all the top-level crate items.
736 pub fn each_top_level_item_of_crate<F, G>(cdata: Cmd, get_crate_data: G, callback: F)
737 where F: FnMut(DefLike, ast::Name, ty::Visibility),
738 G: FnMut(ast::CrateNum) -> Rc<CrateMetadata>,
740 let root_doc = rbml::Doc::new(cdata.data());
741 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
742 let crate_items_doc = reader::get_doc(misc_info_doc,
743 tag_misc_info_crate_items);
745 each_child_of_item_or_crate(cdata,
751 pub fn get_item_name(cdata: Cmd, id: DefIndex) -> ast::Name {
752 item_name(cdata.lookup_item(id))
755 pub fn maybe_get_item_name(cdata: Cmd, id: DefIndex) -> Option<ast::Name> {
756 maybe_item_name(cdata.lookup_item(id))
759 pub fn maybe_get_item_ast<'a, 'tcx>(cdata: Cmd, tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefIndex)
761 debug!("Looking up item: {:?}", id);
762 let item_doc = cdata.lookup_item(id);
763 let item_did = item_def_id(item_doc, cdata);
764 let parent_def_id = DefId {
766 index: def_key(cdata, id).parent.unwrap()
768 let mut parent_def_path = def_path(cdata, id);
769 parent_def_path.data.pop();
770 if let Some(ast_doc) = reader::maybe_get_doc(item_doc, tag_ast as usize) {
771 let ii = decode_inlined_item(cdata,
777 return FoundAst::Found(ii);
778 } else if let Some(parent_did) = item_parent_item(cdata, item_doc) {
779 // Remove the last element from the paths, since we are now
780 // trying to inline the parent.
781 let grandparent_def_id = DefId {
783 index: def_key(cdata, parent_def_id.index).parent.unwrap()
785 let mut grandparent_def_path = parent_def_path;
786 grandparent_def_path.data.pop();
787 let parent_doc = cdata.lookup_item(parent_did.index);
788 if let Some(ast_doc) = reader::maybe_get_doc(parent_doc, tag_ast as usize) {
789 let ii = decode_inlined_item(cdata,
791 grandparent_def_path,
795 if let &InlinedItem::Item(ref i) = ii {
796 return FoundAst::FoundParent(parent_did, i);
803 pub fn is_item_mir_available<'tcx>(cdata: Cmd, id: DefIndex) -> bool {
804 if let Some(item_doc) = cdata.get_item(id) {
805 return reader::maybe_get_doc(item_doc, tag_mir as usize).is_some();
811 pub fn maybe_get_item_mir<'a, 'tcx>(cdata: Cmd,
812 tcx: TyCtxt<'a, 'tcx, 'tcx>,
814 -> Option<mir::repr::Mir<'tcx>> {
815 let item_doc = cdata.lookup_item(id);
817 return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
818 let dcx = tls_context::DecodingContext {
819 crate_metadata: cdata,
822 let mut decoder = reader::Decoder::new(mir_doc);
824 let mut mir = decoder.read_opaque(|opaque_decoder, _| {
825 tls::enter_decoding_context(&dcx, opaque_decoder, |_, opaque_decoder| {
826 Decodable::decode(opaque_decoder)
830 assert!(decoder.position() == mir_doc.end);
832 let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
833 crate_metadata: cdata,
834 codemap: tcx.sess.codemap(),
835 last_filemap_index_hint: Cell::new(0),
838 def_id_and_span_translator.visit_mir(&mut mir);
839 for promoted in &mut mir.promoted {
840 def_id_and_span_translator.visit_mir(promoted);
846 struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
847 crate_metadata: Cmd<'cdata>,
848 codemap: &'codemap codemap::CodeMap,
849 last_filemap_index_hint: Cell<usize>
852 impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
853 for MirDefIdAndSpanTranslator<'cdata, 'codemap>
855 fn visit_def_id(&mut self, def_id: &mut DefId) {
856 *def_id = translate_def_id(self.crate_metadata, *def_id);
859 fn visit_span(&mut self, span: &mut Span) {
860 *span = translate_span(self.crate_metadata,
862 &self.last_filemap_index_hint,
868 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
869 fn get_mutability(ch: u8) -> hir::Mutability {
871 'i' => hir::MutImmutable,
872 'm' => hir::MutMutable,
873 _ => bug!("unknown mutability character: `{}`", ch as char),
877 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
878 let string = explicit_self_doc.as_str_slice();
880 let explicit_self_kind = string.as_bytes()[0];
881 match explicit_self_kind as char {
882 's' => ty::ExplicitSelfCategory::Static,
883 'v' => ty::ExplicitSelfCategory::ByValue,
884 '~' => ty::ExplicitSelfCategory::ByBox,
885 // FIXME(#4846) expl. region
887 ty::ExplicitSelfCategory::ByReference(
889 get_mutability(string.as_bytes()[1]))
891 _ => bug!("unknown self type code: `{}`", explicit_self_kind as char)
895 /// Returns the def IDs of all the items in the given implementation.
896 pub fn get_impl_items(cdata: Cmd, impl_id: DefIndex)
897 -> Vec<ty::ImplOrTraitItemId> {
898 reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
899 let def_id = item_def_id(doc, cdata);
900 match item_sort(doc) {
901 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
902 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
903 Some('t') => ty::TypeTraitItemId(def_id),
904 _ => bug!("unknown impl item sort"),
909 pub fn get_trait_name(cdata: Cmd, id: DefIndex) -> ast::Name {
910 let doc = cdata.lookup_item(id);
914 pub fn is_static_method(cdata: Cmd, id: DefIndex) -> bool {
915 let doc = cdata.lookup_item(id);
916 match item_sort(doc) {
917 Some('r') | Some('p') => {
918 get_explicit_self(doc) == ty::ExplicitSelfCategory::Static
924 pub fn get_impl_or_trait_item<'a, 'tcx>(cdata: Cmd, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>)
925 -> Option<ty::ImplOrTraitItem<'tcx>> {
926 let item_doc = cdata.lookup_item(id);
928 let def_id = item_def_id(item_doc, cdata);
930 let container_id = if let Some(id) = item_parent_item(cdata, item_doc) {
935 let container_doc = cdata.lookup_item(container_id.index);
936 let container = match item_family(container_doc) {
937 Trait => TraitContainer(container_id),
938 _ => ImplContainer(container_id),
941 let name = item_name(item_doc);
942 let vis = item_visibility(item_doc);
943 let defaultness = item_defaultness(item_doc);
945 Some(match item_sort(item_doc) {
946 sort @ Some('C') | sort @ Some('c') => {
947 let ty = doc_type(item_doc, tcx, cdata);
948 ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
952 defaultness: defaultness,
954 container: container,
955 has_value: sort == Some('C')
958 Some('r') | Some('p') => {
959 let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
960 let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
961 let ity = tcx.lookup_item_type(def_id).ty;
962 let fty = match ity.sty {
963 ty::TyFnDef(_, _, fty) => fty,
965 "the type {:?} of the method {:?} is not a function?",
968 let explicit_self = get_explicit_self(item_doc);
970 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
981 let ty = maybe_doc_type(item_doc, tcx, cdata);
982 ty::TypeTraitItem(Rc::new(ty::AssociatedType {
986 defaultness: defaultness,
988 container: container,
995 pub fn get_trait_item_def_ids(cdata: Cmd, id: DefIndex)
996 -> Vec<ty::ImplOrTraitItemId> {
997 let item = cdata.lookup_item(id);
998 reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
999 let def_id = item_def_id(mth, cdata);
1000 match item_sort(mth) {
1001 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
1002 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
1003 Some('t') => ty::TypeTraitItemId(def_id),
1004 _ => bug!("unknown trait item sort"),
1009 pub fn get_item_variances(cdata: Cmd, id: DefIndex) -> ty::ItemVariances {
1010 let item_doc = cdata.lookup_item(id);
1011 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
1012 let mut decoder = reader::Decoder::new(variance_doc);
1013 Decodable::decode(&mut decoder).unwrap()
1016 pub fn get_provided_trait_methods<'a, 'tcx>(cdata: Cmd,
1018 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1019 -> Vec<Rc<ty::Method<'tcx>>> {
1020 let item = cdata.lookup_item(id);
1022 reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
1023 let did = item_def_id(mth_id, cdata);
1024 let mth = cdata.lookup_item(did.index);
1026 if item_sort(mth) == Some('p') {
1027 let trait_item = get_impl_or_trait_item(cdata, did.index, tcx);
1028 if let Some(ty::MethodTraitItem(ref method)) = trait_item {
1029 Some((*method).clone())
1039 pub fn get_associated_consts<'a, 'tcx>(cdata: Cmd, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>)
1040 -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
1041 let item = cdata.lookup_item(id);
1043 [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
1044 reader::tagged_docs(item, tag).filter_map(|ac_id| {
1045 let did = item_def_id(ac_id, cdata);
1046 let ac_doc = cdata.lookup_item(did.index);
1048 match item_sort(ac_doc) {
1049 Some('C') | Some('c') => {
1050 let trait_item = get_impl_or_trait_item(cdata, did.index, tcx);
1051 if let Some(ty::ConstTraitItem(ref ac)) = trait_item {
1063 pub fn get_variant_kind(cdata: Cmd, node_id: DefIndex) -> Option<VariantKind>
1065 let item = cdata.lookup_item(node_id);
1066 family_to_variant_kind(item_family(item))
1069 pub fn get_struct_ctor_def_id(cdata: Cmd, node_id: DefIndex) -> Option<DefId>
1071 let item = cdata.lookup_item(node_id);
1072 reader::maybe_get_doc(item, tag_items_data_item_struct_ctor).
1073 map(|ctor_doc| translated_def_id(cdata, ctor_doc))
1076 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1077 /// the actual type definition, otherwise, return None
1078 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1082 let item = cdata.lookup_item(node_id);
1083 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1084 item_require_parent_item(cdata, item)
1088 pub fn get_item_attrs(cdata: Cmd,
1089 orig_node_id: DefIndex)
1090 -> Vec<ast::Attribute> {
1091 // The attributes for a tuple struct are attached to the definition, not the ctor;
1092 // we assume that someone passing in a tuple struct ctor is actually wanting to
1093 // look at the definition
1094 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1095 let node_id = node_id.map(|x| x.index).unwrap_or(orig_node_id);
1096 let item = cdata.lookup_item(node_id);
1097 get_attributes(item)
1100 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<DefId, Vec<ast::Attribute>> {
1101 let data = rbml::Doc::new(cdata.data());
1102 let fields = reader::get_doc(data, tag_struct_fields);
1103 reader::tagged_docs(fields, tag_struct_field).map(|field| {
1104 let def_id = translated_def_id(cdata, reader::get_doc(field, tag_def_id));
1105 let attrs = get_attributes(field);
1110 fn struct_field_family_to_visibility(family: Family) -> ty::Visibility {
1112 PublicField => ty::Visibility::Public,
1113 InheritedField => ty::Visibility::PrivateExternal,
1118 pub fn get_struct_field_names(cdata: Cmd, id: DefIndex) -> Vec<ast::Name> {
1119 let item = cdata.lookup_item(id);
1121 reader::tagged_docs(item, tag_item_field).map(|an_item| {
1123 }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1124 let name = token::with_ident_interner(|interner| interner.intern(index.to_string()));
1130 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1131 reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1132 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1133 let n = token::intern_and_get_ident(nd.as_str_slice());
1134 attr::mk_word_item(n)
1135 }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1136 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1137 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1138 let n = token::intern_and_get_ident(nd.as_str_slice());
1139 let v = token::intern_and_get_ident(vd.as_str_slice());
1140 // FIXME (#623): Should be able to decode MetaItemKind::NameValue variants,
1141 // but currently the encoder just drops them
1142 attr::mk_name_value_item_str(n, v)
1143 })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1144 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1145 let n = token::intern_and_get_ident(nd.as_str_slice());
1146 let subitems = get_meta_items(meta_item_doc);
1147 attr::mk_list_item(n, subitems)
1151 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1152 match reader::maybe_get_doc(md, tag_attributes) {
1154 reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1155 let is_sugared_doc = reader::doc_as_u8(
1156 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1158 let meta_items = get_meta_items(attr_doc);
1159 // Currently it's only possible to have a single meta item on
1161 assert_eq!(meta_items.len(), 1);
1162 let meta_item = meta_items.into_iter().nth(0).unwrap();
1164 node: ast::Attribute_ {
1165 id: attr::mk_attr_id(),
1166 style: ast::AttrStyle::Outer,
1168 is_sugared_doc: is_sugared_doc,
1170 span: syntax_pos::DUMMY_SP
1178 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1179 out: &mut io::Write) -> io::Result<()> {
1180 write!(out, "=Crate Attributes ({})=\n", *hash)?;
1182 let r = get_attributes(md);
1184 write!(out, "{}\n", pprust::attribute_to_string(attr))?;
1190 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1191 get_attributes(rbml::Doc::new(data))
1195 pub struct CrateDep {
1196 pub cnum: ast::CrateNum,
1199 pub explicitly_linked: bool,
1202 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1203 let cratedoc = rbml::Doc::new(data);
1204 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1206 fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1207 let d = reader::get_doc(doc, tag_);
1208 d.as_str_slice().to_string()
1211 reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1212 let name = docstr(depdoc, tag_crate_dep_crate_name);
1213 let hash = Svh::new(reader::doc_as_u64(reader::get_doc(depdoc, tag_crate_dep_hash)));
1214 let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1215 let explicitly_linked = reader::doc_as_u8(doc) != 0;
1217 cnum: crate_num as u32 + 1,
1220 explicitly_linked: explicitly_linked,
1225 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1226 write!(out, "=External Dependencies=\n")?;
1227 for dep in &get_crate_deps(data) {
1228 write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash)?;
1234 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1235 let cratedoc = rbml::Doc::new(data);
1236 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1237 Svh::new(reader::doc_as_u64(doc))
1241 pub fn get_crate_hash(data: &[u8]) -> Svh {
1242 let cratedoc = rbml::Doc::new(data);
1243 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1244 Svh::new(reader::doc_as_u64(hashdoc))
1247 pub fn maybe_get_crate_name(data: &[u8]) -> Option<&str> {
1248 let cratedoc = rbml::Doc::new(data);
1249 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1254 pub fn get_crate_disambiguator<'a>(data: &'a [u8]) -> &'a str {
1255 let crate_doc = rbml::Doc::new(data);
1256 let disambiguator_doc = reader::get_doc(crate_doc, tag_crate_disambiguator);
1257 let slice: &'a str = disambiguator_doc.as_str_slice();
1261 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1262 let cratedoc = rbml::Doc::new(data);
1263 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1264 triple_doc.map(|s| s.as_str().to_string())
1267 pub fn get_crate_name(data: &[u8]) -> &str {
1268 maybe_get_crate_name(data).expect("no crate name in crate")
1271 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1272 let hash = get_crate_hash(bytes);
1273 let md = rbml::Doc::new(bytes);
1274 list_crate_attributes(md, &hash, out)?;
1275 list_crate_deps(bytes, out)
1278 // Translates a def_id from an external crate to a def_id for the current
1279 // compilation environment. We use this when trying to load types from
1280 // external crates - if those types further refer to types in other crates
1281 // then we must translate the crate number from that encoded in the external
1282 // crate to the correct local crate number.
1283 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1285 return DefId { krate: cdata.cnum, index: did.index };
1289 krate: cdata.cnum_map.borrow()[did.krate],
1294 // Translate a DefId from the current compilation environment to a DefId
1295 // for an external crate.
1296 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1297 for (local, &global) in cdata.cnum_map.borrow().iter_enumerated() {
1298 if global == did.krate {
1299 return Some(DefId { krate: local, index: did.index });
1306 /// Translates a `Span` from an extern crate to the corresponding `Span`
1307 /// within the local crate's codemap.
1308 pub fn translate_span(cdata: Cmd,
1309 codemap: &codemap::CodeMap,
1310 last_filemap_index_hint: &Cell<usize>,
1311 span: syntax_pos::Span)
1312 -> syntax_pos::Span {
1313 let span = if span.lo > span.hi {
1314 // Currently macro expansion sometimes produces invalid Span values
1315 // where lo > hi. In order not to crash the compiler when trying to
1316 // translate these values, let's transform them into something we
1317 // can handle (and which will produce useful debug locations at
1318 // least some of the time).
1319 // This workaround is only necessary as long as macro expansion is
1320 // not fixed. FIXME(#23480)
1321 syntax_pos::mk_sp(span.lo, span.lo)
1326 let imported_filemaps = cdata.imported_filemaps(&codemap);
1328 // Optimize for the case that most spans within a translated item
1329 // originate from the same filemap.
1330 let last_filemap_index = last_filemap_index_hint.get();
1331 let last_filemap = &imported_filemaps[last_filemap_index];
1333 if span.lo >= last_filemap.original_start_pos &&
1334 span.lo <= last_filemap.original_end_pos &&
1335 span.hi >= last_filemap.original_start_pos &&
1336 span.hi <= last_filemap.original_end_pos {
1340 let mut b = imported_filemaps.len();
1343 let m = (a + b) / 2;
1344 if imported_filemaps[m].original_start_pos > span.lo {
1351 last_filemap_index_hint.set(a);
1352 &imported_filemaps[a]
1356 let lo = (span.lo - filemap.original_start_pos) +
1357 filemap.translated_filemap.start_pos;
1358 let hi = (span.hi - filemap.original_start_pos) +
1359 filemap.translated_filemap.start_pos;
1361 syntax_pos::mk_sp(lo, hi)
1364 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1367 where F: FnMut(DefId),
1369 let item_doc = cdata.lookup_item(id);
1370 for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1371 if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1372 callback(item_def_id(impl_doc, cdata));
1377 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1379 mut callback: F) where
1382 // Do a reverse lookup beforehand to avoid touching the crate_num
1383 // hash map in the loop below.
1384 if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1385 let def_id_u64 = def_to_u64(crate_local_did);
1387 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1388 for trait_doc in reader::tagged_docs(impls_doc, tag_impls_trait) {
1389 let trait_def_id = reader::get_doc(trait_doc, tag_def_id);
1390 if reader::doc_as_u64(trait_def_id) != def_id_u64 {
1393 for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1394 callback(translated_def_id(cdata, impl_doc));
1400 pub fn get_trait_of_item<'a, 'tcx>(cdata: Cmd,
1402 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1404 let item_doc = cdata.lookup_item(id);
1405 let parent_item_id = match item_parent_item(cdata, item_doc) {
1406 None => return None,
1407 Some(item_id) => item_id,
1409 let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1410 match item_family(parent_item_doc) {
1411 Trait => Some(item_def_id(parent_item_doc, cdata)),
1412 Impl | DefaultImpl => {
1413 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1414 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1421 pub fn get_native_libraries(cdata: Cmd)
1422 -> Vec<(cstore::NativeLibraryKind, String)> {
1423 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1424 tag_native_libraries);
1425 reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1426 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1427 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1428 let kind: cstore::NativeLibraryKind =
1429 cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1430 let name = name_doc.as_str().to_string();
1435 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<DefIndex> {
1436 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1437 .map(|doc| DefIndex::from_u32(reader::doc_as_u32(doc)))
1440 pub fn each_exported_macro<F>(data: &[u8], mut f: F) where
1441 F: FnMut(ast::Name, Vec<ast::Attribute>, Span, String) -> bool,
1443 let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1444 for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1445 let name = item_name(macro_doc);
1446 let attrs = get_attributes(macro_doc);
1447 let span = get_macro_span(macro_doc);
1448 let body = reader::get_doc(macro_doc, tag_macro_def_body);
1449 if !f(name, attrs, span, body.as_str().to_string()) {
1455 pub fn get_macro_span(doc: rbml::Doc) -> Span {
1456 let lo_doc = reader::get_doc(doc, tag_macro_def_span_lo);
1457 let lo = BytePos(reader::doc_as_u32(lo_doc));
1458 let hi_doc = reader::get_doc(doc, tag_macro_def_span_hi);
1459 let hi = BytePos(reader::doc_as_u32(hi_doc));
1460 return Span { lo: lo, hi: hi, expn_id: NO_EXPANSION };
1463 pub fn get_dylib_dependency_formats(cdata: Cmd)
1464 -> Vec<(ast::CrateNum, LinkagePreference)>
1466 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1467 tag_dylib_dependency_formats);
1468 let mut result = Vec::new();
1470 debug!("found dylib deps: {}", formats.as_str_slice());
1471 for spec in formats.as_str_slice().split(',') {
1472 if spec.is_empty() { continue }
1473 let cnum = spec.split(':').nth(0).unwrap();
1474 let link = spec.split(':').nth(1).unwrap();
1475 let cnum: ast::CrateNum = cnum.parse().unwrap();
1476 let cnum = cdata.cnum_map.borrow()[cnum];
1477 result.push((cnum, if link == "d" {
1478 LinkagePreference::RequireDynamic
1480 LinkagePreference::RequireStatic
1486 pub fn get_missing_lang_items(cdata: Cmd)
1487 -> Vec<lang_items::LangItem>
1489 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1490 reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1491 lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1495 pub fn get_method_arg_names(cdata: Cmd, id: DefIndex) -> Vec<String> {
1496 let method_doc = cdata.lookup_item(id);
1497 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1499 reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1500 name_doc.as_str_slice().to_string()
1507 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1508 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1510 reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1513 index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1518 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1519 let item_doc = cdata.lookup_item(id);
1520 match item_family(item_doc) {
1526 pub fn is_const_fn(cdata: Cmd, id: DefIndex) -> bool {
1527 let item_doc = cdata.lookup_item(id);
1528 match fn_constness(item_doc) {
1529 hir::Constness::Const => true,
1530 hir::Constness::NotConst => false,
1534 pub fn is_extern_item<'a, 'tcx>(cdata: Cmd,
1536 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1538 let item_doc = match cdata.get_item(id) {
1540 None => return false,
1542 let applicable = match item_family(item_doc) {
1543 ImmStatic | MutStatic => true,
1545 let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1546 let no_generics = generics.types.is_empty();
1548 ty::TyFnDef(_, _, fn_ty) | ty::TyFnPtr(fn_ty)
1549 if fn_ty.abi != Abi::Rust => return no_generics,
1557 attr::contains_extern_indicator(tcx.sess.diagnostic(),
1558 &get_attributes(item_doc))
1564 pub fn is_foreign_item(cdata: Cmd, id: DefIndex) -> bool {
1565 let item_doc = cdata.lookup_item(id);
1566 let parent_item_id = match item_parent_item(cdata, item_doc) {
1567 None => return false,
1568 Some(item_id) => item_id,
1570 let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1571 item_family(parent_item_doc) == ForeignMod
1574 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1575 let item_doc = cdata.lookup_item(id);
1576 match item_family(item_doc) {
1582 fn doc_generics<'a, 'tcx>(base_doc: rbml::Doc,
1583 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1586 -> ty::Generics<'tcx>
1588 let doc = reader::get_doc(base_doc, tag);
1590 let mut types = subst::VecPerParamSpace::empty();
1591 for p in reader::tagged_docs(doc, tag_type_param_def) {
1593 TyDecoder::with_doc(tcx, cdata.cnum, p,
1594 &mut |did| translate_def_id(cdata, did))
1595 .parse_type_param_def();
1596 types.push(bd.space, bd);
1599 let mut regions = subst::VecPerParamSpace::empty();
1600 for p in reader::tagged_docs(doc, tag_region_param_def) {
1602 TyDecoder::with_doc(tcx, cdata.cnum, p,
1603 &mut |did| translate_def_id(cdata, did))
1604 .parse_region_param_def();
1605 regions.push(bd.space, bd);
1608 ty::Generics { types: types, regions: regions }
1611 fn doc_predicate<'a, 'tcx>(cdata: Cmd,
1613 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1614 -> ty::Predicate<'tcx>
1616 let predicate_pos = cdata.xref_index.lookup(
1617 cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1619 cdata.data(), cdata.cnum, predicate_pos, tcx,
1620 &mut |did| translate_def_id(cdata, did)
1624 fn doc_predicates<'a, 'tcx>(base_doc: rbml::Doc,
1625 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1628 -> ty::GenericPredicates<'tcx>
1630 let doc = reader::get_doc(base_doc, tag);
1632 let mut predicates = subst::VecPerParamSpace::empty();
1633 for predicate_doc in reader::tagged_docs(doc, tag_type_predicate) {
1634 predicates.push(subst::TypeSpace,
1635 doc_predicate(cdata, predicate_doc, tcx));
1637 for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1638 predicates.push(subst::SelfSpace,
1639 doc_predicate(cdata, predicate_doc, tcx));
1641 for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1642 predicates.push(subst::FnSpace,
1643 doc_predicate(cdata, predicate_doc, tcx));
1646 ty::GenericPredicates { predicates: predicates }
1649 pub fn is_defaulted_trait(cdata: Cmd, trait_id: DefIndex) -> bool {
1650 let trait_doc = cdata.lookup_item(trait_id);
1651 assert!(item_family(trait_doc) == Family::Trait);
1652 let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1653 reader::doc_as_u8(defaulted_doc) != 0
1656 pub fn is_default_impl(cdata: Cmd, impl_id: DefIndex) -> bool {
1657 let impl_doc = cdata.lookup_item(impl_id);
1658 item_family(impl_doc) == Family::DefaultImpl
1661 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<syntax_pos::FileMap> {
1662 let crate_doc = rbml::Doc::new(metadata);
1663 let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1665 reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1666 let mut decoder = reader::Decoder::new(filemap_doc);
1667 decoder.read_opaque(|opaque_decoder, _| {
1668 Decodable::decode(opaque_decoder)
1673 pub fn closure_kind(cdata: Cmd, closure_id: DefIndex) -> ty::ClosureKind {
1674 let closure_doc = cdata.lookup_item(closure_id);
1675 let closure_kind_doc = reader::get_doc(closure_doc, tag_items_closure_kind);
1676 let mut decoder = reader::Decoder::new(closure_kind_doc);
1677 ty::ClosureKind::decode(&mut decoder).unwrap()
1680 pub fn closure_ty<'a, 'tcx>(cdata: Cmd, closure_id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>)
1681 -> ty::ClosureTy<'tcx> {
1682 let closure_doc = cdata.lookup_item(closure_id);
1683 let closure_ty_doc = reader::get_doc(closure_doc, tag_items_closure_ty);
1684 TyDecoder::with_doc(tcx, cdata.cnum, closure_ty_doc, &mut |did| translate_def_id(cdata, did))
1688 pub fn def_key(cdata: Cmd, id: DefIndex) -> hir_map::DefKey {
1689 debug!("def_key: id={:?}", id);
1690 let item_doc = cdata.lookup_item(id);
1691 item_def_key(item_doc)
1694 fn item_def_key(item_doc: rbml::Doc) -> hir_map::DefKey {
1695 match reader::maybe_get_doc(item_doc, tag_def_key) {
1696 Some(def_key_doc) => {
1697 let mut decoder = reader::Decoder::new(def_key_doc);
1698 let simple_key = def_key::DefKey::decode(&mut decoder).unwrap();
1699 let name = reader::maybe_get_doc(item_doc, tag_paths_data_name).map(|name| {
1700 token::intern(name.as_str_slice())
1702 def_key::recover_def_key(simple_key, name)
1705 bug!("failed to find block with tag {:?} for item with family {:?}",
1707 item_family(item_doc))
1712 pub fn def_path(cdata: Cmd, id: DefIndex) -> hir_map::DefPath {
1713 debug!("def_path(id={:?})", id);
1714 hir_map::DefPath::make(cdata.cnum, id, |parent| def_key(cdata, parent))
1717 pub fn get_panic_strategy(data: &[u8]) -> PanicStrategy {
1718 let crate_doc = rbml::Doc::new(data);
1719 let strat_doc = reader::get_doc(crate_doc, tag_panic_strategy);
1720 match reader::doc_as_u8(strat_doc) {
1721 b'U' => PanicStrategy::Unwind,
1722 b'A' => PanicStrategy::Abort,
1723 b => panic!("unknown panic strategy in metadata: {}", b),