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 // As a special case, iterate over all static methods of
691 // associated implementations too. This is a bit of a botch.
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,
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,
707 callback(static_method_def_like,
709 item_visibility(impl_method_doc));
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);
721 let name_doc = reader::get_doc(reexport_doc,
722 tag_items_data_item_reexport_name);
723 let name = name_doc.as_str_slice();
725 // This reexport may be in yet another crate.
726 let crate_data = if child_def_id.krate == cdata.cnum {
729 Some(get_crate_data(child_def_id.krate))
731 let crate_data = match crate_data {
732 Some(ref cdata) => &**cdata,
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);
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>,
753 let item_doc = match cdata.get_item(id) {
755 Some(item_doc) => item_doc,
758 each_child_of_item_or_crate(cdata, item_doc, get_crate_data, callback)
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>,
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);
771 each_child_of_item_or_crate(cdata,
777 pub fn get_item_name(cdata: Cmd, id: DefIndex) -> ast::Name {
778 item_name(cdata.lookup_item(id))
781 pub fn maybe_get_item_name(cdata: Cmd, id: DefIndex) -> Option<ast::Name> {
782 maybe_item_name(cdata.lookup_item(id))
785 pub fn maybe_get_item_ast<'a, 'tcx>(cdata: Cmd, tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefIndex)
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 {
792 index: def_key(cdata, id).parent.unwrap()
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,
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 {
809 index: def_key(cdata, parent_def_id.index).parent.unwrap()
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,
817 grandparent_def_path,
821 if let &InlinedItem::Item(ref i) = ii {
822 return FoundAst::FoundParent(parent_did, i);
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();
837 pub fn maybe_get_item_mir<'a, 'tcx>(cdata: Cmd,
838 tcx: TyCtxt<'a, 'tcx, 'tcx>,
840 -> Option<mir::repr::Mir<'tcx>> {
841 let item_doc = cdata.lookup_item(id);
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,
848 let mut decoder = reader::Decoder::new(mir_doc);
850 let mut mir = decoder.read_opaque(|opaque_decoder, _| {
851 tls::enter_decoding_context(&dcx, opaque_decoder, |_, opaque_decoder| {
852 Decodable::decode(opaque_decoder)
856 assert!(decoder.position() == mir_doc.end);
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),
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);
872 struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
873 crate_metadata: Cmd<'cdata>,
874 codemap: &'codemap codemap::CodeMap,
875 last_filemap_index_hint: Cell<usize>
878 impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
879 for MirDefIdAndSpanTranslator<'cdata, 'codemap>
881 fn visit_def_id(&mut self, def_id: &mut DefId) {
882 *def_id = translate_def_id(self.crate_metadata, *def_id);
885 fn visit_span(&mut self, span: &mut Span) {
886 *span = translate_span(self.crate_metadata,
888 &self.last_filemap_index_hint,
894 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
895 fn get_mutability(ch: u8) -> hir::Mutability {
897 'i' => hir::MutImmutable,
898 'm' => hir::MutMutable,
899 _ => bug!("unknown mutability character: `{}`", ch as char),
903 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
904 let string = explicit_self_doc.as_str_slice();
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
913 ty::ExplicitSelfCategory::ByReference(
915 get_mutability(string.as_bytes()[1]))
917 _ => bug!("unknown self type code: `{}`", explicit_self_kind as char)
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"),
935 pub fn get_trait_name(cdata: Cmd, id: DefIndex) -> ast::Name {
936 let doc = cdata.lookup_item(id);
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
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);
954 let def_id = item_def_id(item_doc, cdata);
956 let container_id = if let Some(id) = item_parent_item(cdata, item_doc) {
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),
967 let name = item_name(item_doc);
968 let vis = item_visibility(item_doc);
969 let defaultness = item_defaultness(item_doc);
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 {
978 defaultness: defaultness,
980 container: container,
981 has_value: sort == Some('C')
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,
991 "the type {:?} of the method {:?} is not a function?",
994 let explicit_self = get_explicit_self(item_doc);
996 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
1007 let ty = maybe_doc_type(item_doc, tcx, cdata);
1008 ty::TypeTraitItem(Rc::new(ty::AssociatedType {
1012 defaultness: defaultness,
1014 container: container,
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"),
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()
1042 pub fn get_provided_trait_methods<'a, 'tcx>(cdata: Cmd,
1044 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1045 -> Vec<Rc<ty::Method<'tcx>>> {
1046 let item = cdata.lookup_item(id);
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);
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())
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);
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);
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 {
1089 pub fn get_variant_kind(cdata: Cmd, node_id: DefIndex) -> Option<VariantKind>
1091 let item = cdata.lookup_item(node_id);
1092 family_to_variant_kind(item_family(item))
1095 pub fn get_struct_ctor_def_id(cdata: Cmd, node_id: DefIndex) -> Option<DefId>
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))
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,
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)
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)
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);
1136 fn struct_field_family_to_visibility(family: Family) -> ty::Visibility {
1138 PublicField => ty::Visibility::Public,
1139 InheritedField => ty::Visibility::PrivateExternal,
1144 pub fn get_struct_field_names(cdata: Cmd, id: DefIndex) -> Vec<ast::Name> {
1145 let item = cdata.lookup_item(id);
1147 reader::tagged_docs(item, tag_item_field).map(|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()));
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)
1177 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1178 match reader::maybe_get_doc(md, tag_attributes) {
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)
1184 let meta_items = get_meta_items(attr_doc);
1185 // Currently it's only possible to have a single meta item on
1187 assert_eq!(meta_items.len(), 1);
1188 let meta_item = meta_items.into_iter().nth(0).unwrap();
1190 node: ast::Attribute_ {
1191 id: attr::mk_attr_id(),
1192 style: ast::AttrStyle::Outer,
1194 is_sugared_doc: is_sugared_doc,
1196 span: syntax_pos::DUMMY_SP
1204 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1205 out: &mut io::Write) -> io::Result<()> {
1206 write!(out, "=Crate Attributes ({})=\n", *hash)?;
1208 let r = get_attributes(md);
1210 write!(out, "{}\n", pprust::attribute_to_string(attr))?;
1216 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1217 get_attributes(rbml::Doc::new(data))
1221 pub struct CrateDep {
1222 pub cnum: ast::CrateNum,
1225 pub explicitly_linked: bool,
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);
1232 fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1233 let d = reader::get_doc(doc, tag_);
1234 d.as_str_slice().to_string()
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;
1243 cnum: crate_num as u32 + 1,
1246 explicitly_linked: explicitly_linked,
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)?;
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))
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))
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| {
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();
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())
1293 pub fn get_crate_name(data: &[u8]) -> &str {
1294 maybe_get_crate_name(data).expect("no crate name in crate")
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)
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 {
1311 return DefId { krate: cdata.cnum, index: did.index };
1315 krate: cdata.cnum_map.borrow()[did.krate],
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 });
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)
1352 let imported_filemaps = cdata.imported_filemaps(&codemap);
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];
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 {
1366 let mut b = imported_filemaps.len();
1369 let m = (a + b) / 2;
1370 if imported_filemaps[m].original_start_pos > span.lo {
1377 last_filemap_index_hint.set(a);
1378 &imported_filemaps[a]
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;
1387 syntax_pos::mk_sp(lo, hi)
1390 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1393 where F: FnMut(DefId),
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));
1403 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1405 mut callback: F) where
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);
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 {
1419 for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1420 callback(translated_def_id(cdata, impl_doc));
1426 pub fn get_trait_of_item<'a, 'tcx>(cdata: Cmd,
1428 tcx: TyCtxt<'a, 'tcx, 'tcx>)
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,
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)
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();
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)))
1466 pub fn each_exported_macro<F>(data: &[u8], mut f: F) where
1467 F: FnMut(ast::Name, Vec<ast::Attribute>, Span, String) -> bool,
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()) {
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 };
1489 pub fn get_dylib_dependency_formats(cdata: Cmd)
1490 -> Vec<(ast::CrateNum, LinkagePreference)>
1492 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1493 tag_dylib_dependency_formats);
1494 let mut result = Vec::new();
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
1506 LinkagePreference::RequireStatic
1512 pub fn get_missing_lang_items(cdata: Cmd)
1513 -> Vec<lang_items::LangItem>
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()
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) {
1525 reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1526 name_doc.as_str_slice().to_string()
1533 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1534 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1536 reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1539 index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1544 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1545 let item_doc = cdata.lookup_item(id);
1546 match item_family(item_doc) {
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,
1560 pub fn is_extern_item<'a, 'tcx>(cdata: Cmd,
1562 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1564 let item_doc = match cdata.get_item(id) {
1566 None => return false,
1568 let applicable = match item_family(item_doc) {
1569 ImmStatic | MutStatic => true,
1571 let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1572 let no_generics = generics.types.is_empty();
1574 ty::TyFnDef(_, _, fn_ty) | ty::TyFnPtr(fn_ty)
1575 if fn_ty.abi != Abi::Rust => return no_generics,
1583 attr::contains_extern_indicator(tcx.sess.diagnostic(),
1584 &get_attributes(item_doc))
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,
1596 let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1597 item_family(parent_item_doc) == ForeignMod
1600 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1601 let item_doc = cdata.lookup_item(id);
1602 match item_family(item_doc) {
1608 fn doc_generics<'a, 'tcx>(base_doc: rbml::Doc,
1609 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1612 -> ty::Generics<'tcx>
1614 let doc = reader::get_doc(base_doc, tag);
1616 let mut types = subst::VecPerParamSpace::empty();
1617 for p in reader::tagged_docs(doc, tag_type_param_def) {
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);
1625 let mut regions = subst::VecPerParamSpace::empty();
1626 for p in reader::tagged_docs(doc, tag_region_param_def) {
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);
1634 ty::Generics { types: types, regions: regions }
1637 fn doc_predicate<'a, 'tcx>(cdata: Cmd,
1639 tcx: TyCtxt<'a, 'tcx, 'tcx>)
1640 -> ty::Predicate<'tcx>
1642 let predicate_pos = cdata.xref_index.lookup(
1643 cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1645 cdata.data(), cdata.cnum, predicate_pos, tcx,
1646 &mut |did| translate_def_id(cdata, did)
1650 fn doc_predicates<'a, 'tcx>(base_doc: rbml::Doc,
1651 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1654 -> ty::GenericPredicates<'tcx>
1656 let doc = reader::get_doc(base_doc, tag);
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));
1663 for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1664 predicates.push(subst::SelfSpace,
1665 doc_predicate(cdata, predicate_doc, tcx));
1667 for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1668 predicates.push(subst::FnSpace,
1669 doc_predicate(cdata, predicate_doc, tcx));
1672 ty::GenericPredicates { predicates: predicates }
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
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
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);
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)
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()
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))
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)
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())
1728 def_key::recover_def_key(simple_key, name)
1731 bug!("failed to find block with tag {:?} for item with family {:?}",
1733 item_family(item_doc))
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))
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),