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, crate_metadata};
20 use encoder::def_to_u64;
23 use tydecode::TyDecoder;
25 use rustc::back::svh::Svh;
26 use rustc::front::map as hir_map;
27 use rustc::util::nodemap::FnvHashMap;
30 use middle::cstore::{LOCAL_CRATE, FoundAst, InlinedItem, LinkagePreference};
31 use middle::cstore::{DefLike, DlDef, DlField, DlImpl, tls};
33 use middle::def_id::{DefId, DefIndex};
34 use middle::lang_items;
36 use middle::ty::{ImplContainer, TraitContainer};
37 use middle::ty::{self, Ty, TyCtxt, TypeFoldable, VariantKind};
39 use rustc_const_eval::ConstInt;
42 use rustc::mir::visit::MutVisitor;
45 use std::io::prelude::*;
52 use serialize::Decodable;
54 use syntax::parse::token::{self, IdentInterner};
57 use syntax::codemap::{self, Span, BytePos, NO_EXPANSION};
58 use syntax::print::pprust;
62 pub type Cmd<'a> = &'a crate_metadata;
65 fn get_item(&self, item_id: DefIndex) -> Option<rbml::Doc> {
66 self.index.lookup_item(self.data(), item_id).map(|pos| {
67 reader::doc_at(self.data(), pos as usize).unwrap().doc
71 fn lookup_item(&self, item_id: DefIndex) -> rbml::Doc {
72 match self.get_item(item_id) {
73 None => panic!("lookup_item: id not found: {:?}", item_id),
79 pub fn load_index(data: &[u8]) -> index::Index {
80 let index = reader::get_doc(rbml::Doc::new(data), tag_index);
81 index::Index::from_rbml(index)
84 pub fn crate_rustc_version(data: &[u8]) -> Option<String> {
85 let doc = rbml::Doc::new(data);
86 reader::maybe_get_doc(doc, tag_rustc_version).map(|s| s.as_str())
89 pub fn load_xrefs(data: &[u8]) -> index::DenseIndex {
90 let index = reader::get_doc(rbml::Doc::new(data), tag_xref_index);
91 index::DenseIndex::from_buf(index.data, index.start, index.end)
94 #[derive(Clone, Copy, Debug, PartialEq)]
105 Variant(VariantKind), // V, v, w
109 Struct(VariantKind), // S, s, u
115 fn item_family(item: rbml::Doc) -> Family {
116 let fam = reader::get_doc(item, tag_items_data_item_family);
117 match reader::doc_as_u8(fam) as char {
128 'V' => Variant(VariantKind::Struct),
129 'v' => Variant(VariantKind::Tuple),
130 'w' => Variant(VariantKind::Unit),
134 'S' => Struct(VariantKind::Struct),
135 's' => Struct(VariantKind::Tuple),
136 'u' => Struct(VariantKind::Unit),
138 'N' => InheritedField,
139 c => panic!("unexpected family char: {}", c)
143 fn item_visibility(item: rbml::Doc) -> hir::Visibility {
144 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
146 Some(visibility_doc) => {
147 match reader::doc_as_u8(visibility_doc) as char {
149 'i' => hir::Inherited,
150 _ => panic!("unknown visibility character")
156 fn fn_constness(item: rbml::Doc) -> hir::Constness {
157 match reader::maybe_get_doc(item, tag_items_data_item_constness) {
158 None => hir::Constness::NotConst,
159 Some(constness_doc) => {
160 match reader::doc_as_u8(constness_doc) as char {
161 'c' => hir::Constness::Const,
162 'n' => hir::Constness::NotConst,
163 _ => panic!("unknown constness character")
169 fn item_defaultness(item: rbml::Doc) -> hir::Defaultness {
170 match reader::maybe_get_doc(item, tag_items_data_item_defaultness) {
171 None => hir::Defaultness::Default, // should occur only for default impls on traits
172 Some(defaultness_doc) => {
173 match reader::doc_as_u8(defaultness_doc) as char {
174 'd' => hir::Defaultness::Default,
175 'f' => hir::Defaultness::Final,
176 _ => panic!("unknown defaultness character")
182 fn item_sort(item: rbml::Doc) -> Option<char> {
183 reader::tagged_docs(item, tag_item_trait_item_sort).nth(0).map(|doc| {
184 doc.as_str_slice().as_bytes()[0] as char
188 fn item_symbol(item: rbml::Doc) -> String {
189 reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
192 fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
193 let id = reader::doc_as_u64(d);
194 let index = DefIndex::new((id & 0xFFFF_FFFF) as usize);
195 let def_id = DefId { krate: (id >> 32) as u32, index: index };
196 translate_def_id(cdata, def_id)
199 fn item_parent_item(cdata: Cmd, d: rbml::Doc) -> Option<DefId> {
200 reader::tagged_docs(d, tag_items_data_parent_item).nth(0).map(|did| {
201 translated_def_id(cdata, did)
205 fn item_require_parent_item(cdata: Cmd, d: rbml::Doc) -> DefId {
206 translated_def_id(cdata, reader::get_doc(d, tag_items_data_parent_item))
209 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
210 translated_def_id(cdata, reader::get_doc(d, tag_def_id))
213 fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
214 reader::tagged_docs(d, tag_items_data_item_reexport)
217 fn variant_disr_val(d: rbml::Doc) -> Option<u64> {
218 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
219 reader::with_doc_data(val_doc, |data| {
220 str::from_utf8(data).ok().and_then(|s| s.parse().ok())
225 fn doc_type<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
226 let tp = reader::get_doc(doc, tag_items_data_item_type);
227 TyDecoder::with_doc(tcx, cdata.cnum, tp,
228 &mut |did| translate_def_id(cdata, did))
232 fn maybe_doc_type<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Option<Ty<'tcx>> {
233 reader::maybe_get_doc(doc, tag_items_data_item_type).map(|tp| {
234 TyDecoder::with_doc(tcx, cdata.cnum, tp,
235 &mut |did| translate_def_id(cdata, did))
240 pub fn item_type<'tcx>(_item_id: DefId, item: rbml::Doc,
241 tcx: &TyCtxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
242 doc_type(item, tcx, cdata)
245 fn doc_trait_ref<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd)
246 -> ty::TraitRef<'tcx> {
247 TyDecoder::with_doc(tcx, cdata.cnum, doc,
248 &mut |did| translate_def_id(cdata, did))
252 fn item_trait_ref<'tcx>(doc: rbml::Doc, tcx: &TyCtxt<'tcx>, cdata: Cmd)
253 -> ty::TraitRef<'tcx> {
254 let tp = reader::get_doc(doc, tag_item_trait_ref);
255 doc_trait_ref(tp, tcx, cdata)
258 fn item_path(item_doc: rbml::Doc) -> Vec<hir_map::PathElem> {
259 let path_doc = reader::get_doc(item_doc, tag_path);
260 reader::docs(path_doc).filter_map(|(tag, elt_doc)| {
261 if tag == tag_path_elem_mod {
262 let s = elt_doc.as_str_slice();
263 Some(hir_map::PathMod(token::intern(s)))
264 } else if tag == tag_path_elem_name {
265 let s = elt_doc.as_str_slice();
266 Some(hir_map::PathName(token::intern(s)))
268 // ignore tag_path_len element
274 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Name {
275 let name = reader::get_doc(item, tag_paths_data_name);
276 let string = name.as_str_slice();
277 match intr.find(string) {
278 None => token::intern(string),
283 fn family_to_variant_kind<'tcx>(family: Family) -> Option<ty::VariantKind> {
285 Struct(VariantKind::Struct) | Variant(VariantKind::Struct) =>
286 Some(ty::VariantKind::Struct),
287 Struct(VariantKind::Tuple) | Variant(VariantKind::Tuple) =>
288 Some(ty::VariantKind::Tuple),
289 Struct(VariantKind::Unit) | Variant(VariantKind::Unit) =>
290 Some(ty::VariantKind::Unit),
295 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
296 let fam = item_family(item);
299 // Check whether we have an associated const item.
300 match item_sort(item) {
301 Some('C') | Some('c') => {
302 DlDef(Def::AssociatedConst(did))
305 // Regular const item.
306 DlDef(Def::Const(did))
310 ImmStatic => DlDef(Def::Static(did, false)),
311 MutStatic => DlDef(Def::Static(did, true)),
312 Struct(..) => DlDef(Def::Struct(did)),
313 Fn => DlDef(Def::Fn(did)),
314 Method | StaticMethod => {
315 DlDef(Def::Method(did))
318 if item_sort(item) == Some('t') {
319 let trait_did = item_require_parent_item(cdata, item);
320 DlDef(Def::AssociatedTy(trait_did, did))
322 DlDef(Def::TyAlias(did))
325 Mod => DlDef(Def::Mod(did)),
326 ForeignMod => DlDef(Def::ForeignMod(did)),
328 let enum_did = item_require_parent_item(cdata, item);
329 DlDef(Def::Variant(enum_did, did))
331 Trait => DlDef(Def::Trait(did)),
332 Enum => DlDef(Def::Enum(did)),
333 Impl | DefaultImpl => DlImpl(did),
334 PublicField | InheritedField => DlField,
338 fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
339 let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
340 if reader::doc_as_u8(unsafety_doc) != 0 {
341 hir::Unsafety::Unsafe
343 hir::Unsafety::Normal
347 fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
348 let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
349 reader::doc_as_u8(paren_sugar_doc) != 0
352 fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
353 let polarity_doc = reader::get_doc(item_doc, tag_polarity);
354 if reader::doc_as_u8(polarity_doc) != 0 {
355 hir::ImplPolarity::Negative
357 hir::ImplPolarity::Positive
361 fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
362 let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
363 reader::tagged_docs(names_doc, tag_associated_type_name)
364 .map(|name_doc| token::intern(name_doc.as_str_slice()))
368 pub fn get_trait_def<'tcx>(cdata: Cmd,
370 tcx: &TyCtxt<'tcx>) -> ty::TraitDef<'tcx>
372 let item_doc = cdata.lookup_item(item_id);
373 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
374 let unsafety = parse_unsafety(item_doc);
375 let associated_type_names = parse_associated_type_names(item_doc);
376 let paren_sugar = parse_paren_sugar(item_doc);
378 ty::TraitDef::new(unsafety,
381 item_trait_ref(item_doc, tcx, cdata),
382 associated_type_names)
385 pub fn get_adt_def<'tcx>(intr: &IdentInterner,
388 tcx: &TyCtxt<'tcx>) -> ty::AdtDefMaster<'tcx>
390 fn expect_variant_kind<'tcx>(family: Family, tcx: &TyCtxt<'tcx>) -> ty::VariantKind {
391 match family_to_variant_kind(family) {
393 _ => tcx.sess.bug(&format!("unexpected family: {:?}", family)),
396 fn get_enum_variants<'tcx>(intr: &IdentInterner,
399 tcx: &TyCtxt<'tcx>) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
400 let mut disr_val = 0;
401 reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
402 let did = translated_def_id(cdata, p);
403 let item = cdata.lookup_item(did.index);
405 if let Some(disr) = variant_disr_val(item) {
409 disr_val = disr_val.wrapping_add(1);
413 name: item_name(intr, item),
414 fields: get_variant_fields(intr, cdata, item, tcx),
415 disr_val: ConstInt::Infer(disr),
416 kind: expect_variant_kind(item_family(item), tcx),
420 fn get_variant_fields<'tcx>(intr: &IdentInterner,
423 tcx: &TyCtxt<'tcx>) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
425 reader::tagged_docs(doc, tag_item_field).map(|f| {
426 let ff = item_family(f);
428 PublicField | InheritedField => {},
429 _ => tcx.sess.bug(&format!("expected field, found {:?}", ff))
431 ty::FieldDefData::new(item_def_id(f, cdata),
433 struct_field_family_to_visibility(ff))
434 }).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
435 let ff = item_family(f);
436 let name = intr.intern(&index.to_string());
438 ty::FieldDefData::new(item_def_id(f, cdata), name,
439 struct_field_family_to_visibility(ff))
442 fn get_struct_variant<'tcx>(intr: &IdentInterner,
446 tcx: &TyCtxt<'tcx>) -> ty::VariantDefData<'tcx, 'tcx> {
449 name: item_name(intr, doc),
450 fields: get_variant_fields(intr, cdata, doc, tcx),
451 disr_val: ConstInt::Infer(0),
452 kind: expect_variant_kind(item_family(doc), tcx),
456 let doc = cdata.lookup_item(item_id);
457 let did = DefId { krate: cdata.cnum, index: item_id };
458 let (kind, variants) = match item_family(doc) {
461 get_enum_variants(intr, cdata, doc, tcx))
465 reader::maybe_get_doc(doc, tag_items_data_item_struct_ctor).
466 map_or(did, |ctor_doc| translated_def_id(cdata, ctor_doc));
467 (ty::AdtKind::Struct,
468 vec![get_struct_variant(intr, cdata, doc, ctor_did, tcx)])
471 &format!("get_adt_def called on a non-ADT {:?} - {:?}",
472 item_family(doc), did))
475 let adt = tcx.intern_adt_def(did, kind, variants);
477 // this needs to be done *after* the variant is interned,
478 // to support recursive structures
479 for variant in &adt.variants {
480 if variant.kind() == ty::VariantKind::Tuple &&
481 adt.adt_kind() == ty::AdtKind::Enum {
482 // tuple-like enum variant fields aren't real items - get the types
484 debug!("evaluating the ctor-type of {:?}",
486 let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
487 debug!("evaluating the ctor-type of {:?}.. {:?}",
490 let field_tys = match ctor_ty.sty {
491 ty::TyFnDef(_, _, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
494 // tuple-struct constructors don't have escaping regions
495 assert!(!inputs.has_escaping_regions());
498 _ => tcx.sess.bug("tuple-variant ctor is not an ADT")
500 for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
501 field.fulfill_ty(ty);
504 for field in &variant.fields {
505 debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
506 let ty = get_type(cdata, field.did.index, tcx).ty;
507 field.fulfill_ty(ty);
508 debug!("evaluating the type of {:?}::{:?}: {:?}",
509 variant.name, field.name, ty);
517 pub fn get_predicates<'tcx>(cdata: Cmd,
520 -> ty::GenericPredicates<'tcx>
522 let item_doc = cdata.lookup_item(item_id);
523 doc_predicates(item_doc, tcx, cdata, tag_item_generics)
526 pub fn get_super_predicates<'tcx>(cdata: Cmd,
529 -> ty::GenericPredicates<'tcx>
531 let item_doc = cdata.lookup_item(item_id);
532 doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
535 pub fn get_type<'tcx>(cdata: Cmd, id: DefIndex, tcx: &TyCtxt<'tcx>)
536 -> ty::TypeScheme<'tcx>
538 let item_doc = cdata.lookup_item(id);
539 let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
541 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
548 pub fn get_stability(cdata: Cmd, id: DefIndex) -> Option<attr::Stability> {
549 let item = cdata.lookup_item(id);
550 reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
551 let mut decoder = reader::Decoder::new(doc);
552 Decodable::decode(&mut decoder).unwrap()
556 pub fn get_deprecation(cdata: Cmd, id: DefIndex) -> Option<attr::Deprecation> {
557 let item = cdata.lookup_item(id);
558 reader::maybe_get_doc(item, tag_items_data_item_deprecation).map(|doc| {
559 let mut decoder = reader::Decoder::new(doc);
560 Decodable::decode(&mut decoder).unwrap()
564 pub fn get_visibility(cdata: Cmd, id: DefIndex) -> hir::Visibility {
565 item_visibility(cdata.lookup_item(id))
568 pub fn get_parent_impl(cdata: Cmd, id: DefIndex) -> Option<DefId> {
569 let item = cdata.lookup_item(id);
570 reader::maybe_get_doc(item, tag_items_data_parent_impl).map(|doc| {
571 translated_def_id(cdata, doc)
575 pub fn get_repr_attrs(cdata: Cmd, id: DefIndex) -> Vec<attr::ReprAttr> {
576 let item = cdata.lookup_item(id);
577 match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
578 let mut decoder = reader::Decoder::new(doc);
579 Decodable::decode(&mut decoder).unwrap()
581 Some(attrs) => attrs,
586 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
588 -> Option<hir::ImplPolarity>
590 let item_doc = cdata.lookup_item(id);
591 let fam = item_family(item_doc);
594 Some(parse_polarity(item_doc))
600 pub fn get_custom_coerce_unsized_kind<'tcx>(
603 -> Option<ty::adjustment::CustomCoerceUnsized>
605 let item_doc = cdata.lookup_item(id);
606 reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
607 let mut decoder = reader::Decoder::new(kind_doc);
608 Decodable::decode(&mut decoder).unwrap()
612 pub fn get_impl_trait<'tcx>(cdata: Cmd,
615 -> Option<ty::TraitRef<'tcx>>
617 let item_doc = cdata.lookup_item(id);
618 let fam = item_family(item_doc);
620 Family::Impl | Family::DefaultImpl => {
621 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
622 doc_trait_ref(tp, tcx, cdata)
629 pub fn get_symbol(cdata: Cmd, id: DefIndex) -> String {
630 return item_symbol(cdata.lookup_item(id));
633 /// If you have a crate_metadata, call get_symbol instead
634 pub fn get_symbol_from_buf(data: &[u8], id: DefIndex) -> String {
635 let index = load_index(data);
636 let pos = index.lookup_item(data, id).unwrap();
637 let doc = reader::doc_at(data, pos as usize).unwrap().doc;
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>(intr: Rc<IdentInterner>,
660 mut get_crate_data: G,
661 mut callback: F) where
662 F: FnMut(DefLike, ast::Name, hir::Visibility),
663 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
665 // Iterate over all children.
666 for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
667 let child_def_id = translated_def_id(cdata, child_info_doc);
669 // This item may be in yet another crate if it was the child of a
671 let crate_data = if child_def_id.krate == cdata.cnum {
674 Some(get_crate_data(child_def_id.krate))
676 let crate_data = match crate_data {
677 Some(ref cdata) => &**cdata,
682 match crate_data.get_item(child_def_id.index) {
684 Some(child_item_doc) => {
685 // Hand off the item to the callback.
686 let child_name = item_name(&intr, child_item_doc);
687 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
688 let visibility = item_visibility(child_item_doc);
689 callback(def_like, child_name, visibility);
694 // As a special case, iterate over all static methods of
695 // associated implementations too. This is a bit of a botch.
697 for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
698 tag_items_data_item_inherent_impl) {
699 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
700 if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.index) {
701 for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
702 tag_item_impl_item) {
703 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
705 if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.index) {
706 if let StaticMethod = item_family(impl_method_doc) {
707 // Hand off the static method to the callback.
708 let static_method_name = item_name(&intr, impl_method_doc);
709 let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
711 callback(static_method_def_like,
713 item_visibility(impl_method_doc));
720 for reexport_doc in reexports(item_doc) {
721 let def_id_doc = reader::get_doc(reexport_doc,
722 tag_items_data_item_reexport_def_id);
723 let child_def_id = translated_def_id(cdata, def_id_doc);
725 let name_doc = reader::get_doc(reexport_doc,
726 tag_items_data_item_reexport_name);
727 let name = name_doc.as_str_slice();
729 // This reexport may be in yet another crate.
730 let crate_data = if child_def_id.krate == cdata.cnum {
733 Some(get_crate_data(child_def_id.krate))
735 let crate_data = match crate_data {
736 Some(ref cdata) => &**cdata,
741 if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
742 // Hand off the item to the callback.
743 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
744 // These items have a public visibility because they're part of
745 // a public re-export.
746 callback(def_like, token::intern(name), hir::Public);
751 /// Iterates over each child of the given item.
752 pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
757 F: FnMut(DefLike, ast::Name, hir::Visibility),
758 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
761 let item_doc = match cdata.get_item(id) {
763 Some(item_doc) => item_doc,
766 each_child_of_item_or_crate(intr,
773 /// Iterates over all the top-level crate items.
774 pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
778 F: FnMut(DefLike, ast::Name, hir::Visibility),
779 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
781 let root_doc = rbml::Doc::new(cdata.data());
782 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
783 let crate_items_doc = reader::get_doc(misc_info_doc,
784 tag_misc_info_crate_items);
786 each_child_of_item_or_crate(intr,
793 pub fn get_item_path(cdata: Cmd, id: DefIndex) -> Vec<hir_map::PathElem> {
794 item_path(cdata.lookup_item(id))
797 pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: DefIndex) -> ast::Name {
798 item_name(intr, cdata.lookup_item(id))
801 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &TyCtxt<'tcx>, id: DefIndex)
803 debug!("Looking up item: {:?}", id);
804 let item_doc = cdata.lookup_item(id);
805 let item_did = item_def_id(item_doc, cdata);
806 let mut parent_path = item_path(item_doc);
808 let mut parent_def_path = def_path(cdata, id);
809 parent_def_path.pop();
810 if let Some(ast_doc) = reader::maybe_get_doc(item_doc, tag_ast as usize) {
811 let ii = decode_inlined_item(cdata, tcx, parent_path,
814 return FoundAst::Found(ii);
815 } else if let Some(parent_did) = item_parent_item(cdata, item_doc) {
816 // Remove the last element from the paths, since we are now
817 // trying to inline the parent.
819 parent_def_path.pop();
820 let parent_doc = cdata.lookup_item(parent_did.index);
821 if let Some(ast_doc) = reader::maybe_get_doc(parent_doc, tag_ast as usize) {
822 let ii = decode_inlined_item(cdata, tcx, parent_path,
824 ast_doc, parent_did);
825 if let &InlinedItem::Item(ref i) = ii {
826 return FoundAst::FoundParent(parent_did, i);
833 pub fn is_item_mir_available<'tcx>(cdata: Cmd, id: DefIndex) -> bool {
834 if let Some(item_doc) = cdata.get_item(id) {
835 return reader::maybe_get_doc(item_doc, tag_mir as usize).is_some();
841 pub fn maybe_get_item_mir<'tcx>(cdata: Cmd,
844 -> Option<mir::repr::Mir<'tcx>> {
845 let item_doc = cdata.lookup_item(id);
847 return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
848 let dcx = tls_context::DecodingContext {
849 crate_metadata: cdata,
852 let mut decoder = reader::Decoder::new(mir_doc);
854 let mut mir = decoder.read_opaque(|opaque_decoder, _| {
855 tls::enter_decoding_context(&dcx, opaque_decoder, |_, opaque_decoder| {
856 Decodable::decode(opaque_decoder)
860 assert!(decoder.position() == mir_doc.end);
862 let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
863 crate_metadata: cdata,
864 codemap: tcx.sess.codemap(),
865 last_filemap_index_hint: Cell::new(0),
868 def_id_and_span_translator.visit_mir(&mut mir);
873 struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
874 crate_metadata: Cmd<'cdata>,
875 codemap: &'codemap codemap::CodeMap,
876 last_filemap_index_hint: Cell<usize>
879 impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
880 for MirDefIdAndSpanTranslator<'cdata, 'codemap>
882 fn visit_def_id(&mut self, def_id: &mut DefId) {
883 *def_id = translate_def_id(self.crate_metadata, *def_id);
886 fn visit_span(&mut self, span: &mut Span) {
887 *span = translate_span(self.crate_metadata,
889 &self.last_filemap_index_hint,
895 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
896 fn get_mutability(ch: u8) -> hir::Mutability {
898 'i' => hir::MutImmutable,
899 'm' => hir::MutMutable,
900 _ => panic!("unknown mutability character: `{}`", ch as char),
904 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
905 let string = explicit_self_doc.as_str_slice();
907 let explicit_self_kind = string.as_bytes()[0];
908 match explicit_self_kind as char {
909 's' => ty::ExplicitSelfCategory::Static,
910 'v' => ty::ExplicitSelfCategory::ByValue,
911 '~' => ty::ExplicitSelfCategory::ByBox,
912 // FIXME(#4846) expl. region
914 ty::ExplicitSelfCategory::ByReference(
916 get_mutability(string.as_bytes()[1]))
918 _ => panic!("unknown self type code: `{}`", explicit_self_kind as char)
922 /// Returns the def IDs of all the items in the given implementation.
923 pub fn get_impl_items(cdata: Cmd, impl_id: DefIndex)
924 -> Vec<ty::ImplOrTraitItemId> {
925 reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
926 let def_id = item_def_id(doc, cdata);
927 match item_sort(doc) {
928 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
929 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
930 Some('t') => ty::TypeTraitItemId(def_id),
931 _ => panic!("unknown impl item sort"),
936 pub fn get_trait_name(intr: Rc<IdentInterner>,
940 let doc = cdata.lookup_item(id);
941 item_name(&intr, doc)
944 pub fn is_static_method(cdata: Cmd, id: DefIndex) -> bool {
945 let doc = cdata.lookup_item(id);
946 match item_sort(doc) {
947 Some('r') | Some('p') => {
948 get_explicit_self(doc) == ty::ExplicitSelfCategory::Static
954 pub fn get_impl_or_trait_item<'tcx>(intr: Rc<IdentInterner>,
958 -> Option<ty::ImplOrTraitItem<'tcx>> {
959 let item_doc = cdata.lookup_item(id);
961 let def_id = item_def_id(item_doc, cdata);
963 let container_id = if let Some(id) = item_parent_item(cdata, item_doc) {
968 let container_doc = cdata.lookup_item(container_id.index);
969 let container = match item_family(container_doc) {
970 Trait => TraitContainer(container_id),
971 _ => ImplContainer(container_id),
974 let name = item_name(&intr, item_doc);
975 let vis = item_visibility(item_doc);
976 let defaultness = item_defaultness(item_doc);
978 Some(match item_sort(item_doc) {
979 sort @ Some('C') | sort @ Some('c') => {
980 let ty = doc_type(item_doc, tcx, cdata);
981 ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
985 defaultness: defaultness,
987 container: container,
988 has_value: sort == Some('C')
991 Some('r') | Some('p') => {
992 let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
993 let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
994 let ity = tcx.lookup_item_type(def_id).ty;
995 let fty = match ity.sty {
996 ty::TyFnDef(_, _, fty) => fty.clone(),
997 _ => tcx.sess.bug(&format!(
998 "the type {:?} of the method {:?} is not a function?",
1001 let explicit_self = get_explicit_self(item_doc);
1003 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
1014 let ty = maybe_doc_type(item_doc, tcx, cdata);
1015 ty::TypeTraitItem(Rc::new(ty::AssociatedType {
1019 defaultness: defaultness,
1021 container: container,
1028 pub fn get_trait_item_def_ids(cdata: Cmd, id: DefIndex)
1029 -> Vec<ty::ImplOrTraitItemId> {
1030 let item = cdata.lookup_item(id);
1031 reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
1032 let def_id = item_def_id(mth, cdata);
1033 match item_sort(mth) {
1034 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
1035 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
1036 Some('t') => ty::TypeTraitItemId(def_id),
1037 _ => panic!("unknown trait item sort"),
1042 pub fn get_item_variances(cdata: Cmd, id: DefIndex) -> ty::ItemVariances {
1043 let item_doc = cdata.lookup_item(id);
1044 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
1045 let mut decoder = reader::Decoder::new(variance_doc);
1046 Decodable::decode(&mut decoder).unwrap()
1049 pub fn get_provided_trait_methods<'tcx>(intr: Rc<IdentInterner>,
1053 -> Vec<Rc<ty::Method<'tcx>>> {
1054 let item = cdata.lookup_item(id);
1056 reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
1057 let did = item_def_id(mth_id, cdata);
1058 let mth = cdata.lookup_item(did.index);
1060 if item_sort(mth) == Some('p') {
1061 let trait_item = get_impl_or_trait_item(intr.clone(),
1065 if let Some(ty::MethodTraitItem(ref method)) = trait_item {
1066 Some((*method).clone())
1076 pub fn get_associated_consts<'tcx>(intr: Rc<IdentInterner>,
1080 -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
1081 let item = cdata.lookup_item(id);
1083 [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
1084 reader::tagged_docs(item, tag).filter_map(|ac_id| {
1085 let did = item_def_id(ac_id, cdata);
1086 let ac_doc = cdata.lookup_item(did.index);
1088 match item_sort(ac_doc) {
1089 Some('C') | Some('c') => {
1090 let trait_item = get_impl_or_trait_item(intr.clone(),
1094 if let Some(ty::ConstTraitItem(ref ac)) = trait_item {
1106 pub fn get_variant_kind(cdata: Cmd, node_id: DefIndex) -> Option<VariantKind>
1108 let item = cdata.lookup_item(node_id);
1109 family_to_variant_kind(item_family(item))
1112 pub fn get_struct_ctor_def_id(cdata: Cmd, node_id: DefIndex) -> Option<DefId>
1114 let item = cdata.lookup_item(node_id);
1115 reader::maybe_get_doc(item, tag_items_data_item_struct_ctor).
1116 map(|ctor_doc| translated_def_id(cdata, ctor_doc))
1119 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1120 /// the actual type definition, otherwise, return None
1121 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1125 let item = cdata.lookup_item(node_id);
1126 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1127 item_require_parent_item(cdata, item)
1131 pub fn get_item_attrs(cdata: Cmd,
1132 orig_node_id: DefIndex)
1133 -> Vec<ast::Attribute> {
1134 // The attributes for a tuple struct are attached to the definition, not the ctor;
1135 // we assume that someone passing in a tuple struct ctor is actually wanting to
1136 // look at the definition
1137 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1138 let node_id = node_id.map(|x| x.index).unwrap_or(orig_node_id);
1139 let item = cdata.lookup_item(node_id);
1140 get_attributes(item)
1143 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<DefId, Vec<ast::Attribute>> {
1144 let data = rbml::Doc::new(cdata.data());
1145 let fields = reader::get_doc(data, tag_struct_fields);
1146 reader::tagged_docs(fields, tag_struct_field).map(|field| {
1147 let def_id = translated_def_id(cdata, reader::get_doc(field, tag_def_id));
1148 let attrs = get_attributes(field);
1153 fn struct_field_family_to_visibility(family: Family) -> hir::Visibility {
1155 PublicField => hir::Public,
1156 InheritedField => hir::Inherited,
1161 pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: DefIndex)
1163 let item = cdata.lookup_item(id);
1165 reader::tagged_docs(item, tag_item_field).map(|an_item| {
1166 item_name(intr, an_item)
1167 }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1168 let name = intr.intern(&index.to_string());
1174 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1175 reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1176 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1177 let n = token::intern_and_get_ident(nd.as_str_slice());
1178 attr::mk_word_item(n)
1179 }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1180 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1181 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1182 let n = token::intern_and_get_ident(nd.as_str_slice());
1183 let v = token::intern_and_get_ident(vd.as_str_slice());
1184 // FIXME (#623): Should be able to decode MetaItemKind::NameValue variants,
1185 // but currently the encoder just drops them
1186 attr::mk_name_value_item_str(n, v)
1187 })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1188 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1189 let n = token::intern_and_get_ident(nd.as_str_slice());
1190 let subitems = get_meta_items(meta_item_doc);
1191 attr::mk_list_item(n, subitems)
1195 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1196 match reader::maybe_get_doc(md, tag_attributes) {
1198 reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1199 let is_sugared_doc = reader::doc_as_u8(
1200 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1202 let meta_items = get_meta_items(attr_doc);
1203 // Currently it's only possible to have a single meta item on
1205 assert_eq!(meta_items.len(), 1);
1206 let meta_item = meta_items.into_iter().nth(0).unwrap();
1208 node: ast::Attribute_ {
1209 id: attr::mk_attr_id(),
1210 style: ast::AttrStyle::Outer,
1212 is_sugared_doc: is_sugared_doc,
1214 span: codemap::DUMMY_SP
1222 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1223 out: &mut io::Write) -> io::Result<()> {
1224 write!(out, "=Crate Attributes ({})=\n", *hash)?;
1226 let r = get_attributes(md);
1228 write!(out, "{}\n", pprust::attribute_to_string(attr))?;
1234 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1235 get_attributes(rbml::Doc::new(data))
1239 pub struct CrateDep {
1240 pub cnum: ast::CrateNum,
1243 pub explicitly_linked: bool,
1246 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1247 let cratedoc = rbml::Doc::new(data);
1248 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1250 fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1251 let d = reader::get_doc(doc, tag_);
1252 d.as_str_slice().to_string()
1255 reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1256 let name = docstr(depdoc, tag_crate_dep_crate_name);
1257 let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash));
1258 let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1259 let explicitly_linked = reader::doc_as_u8(doc) != 0;
1261 cnum: crate_num as u32 + 1,
1264 explicitly_linked: explicitly_linked,
1269 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1270 write!(out, "=External Dependencies=\n")?;
1271 for dep in &get_crate_deps(data) {
1272 write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash)?;
1278 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1279 let cratedoc = rbml::Doc::new(data);
1280 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1281 Svh::new(doc.as_str_slice())
1285 pub fn get_crate_hash(data: &[u8]) -> Svh {
1286 let cratedoc = rbml::Doc::new(data);
1287 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1288 Svh::new(hashdoc.as_str_slice())
1291 pub fn maybe_get_crate_name(data: &[u8]) -> Option<&str> {
1292 let cratedoc = rbml::Doc::new(data);
1293 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1298 pub fn get_crate_disambiguator<'a>(data: &'a [u8]) -> &'a str {
1299 let crate_doc = rbml::Doc::new(data);
1300 let disambiguator_doc = reader::get_doc(crate_doc, tag_crate_disambiguator);
1301 let slice: &'a str = disambiguator_doc.as_str_slice();
1305 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1306 let cratedoc = rbml::Doc::new(data);
1307 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1308 triple_doc.map(|s| s.as_str().to_string())
1311 pub fn get_crate_name(data: &[u8]) -> &str {
1312 maybe_get_crate_name(data).expect("no crate name in crate")
1315 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1316 let hash = get_crate_hash(bytes);
1317 let md = rbml::Doc::new(bytes);
1318 list_crate_attributes(md, &hash, out)?;
1319 list_crate_deps(bytes, out)
1322 // Translates a def_id from an external crate to a def_id for the current
1323 // compilation environment. We use this when trying to load types from
1324 // external crates - if those types further refer to types in other crates
1325 // then we must translate the crate number from that encoded in the external
1326 // crate to the correct local crate number.
1327 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1329 return DefId { krate: cdata.cnum, index: did.index };
1332 match cdata.cnum_map.borrow().get(&did.krate) {
1339 None => panic!("didn't find a crate in the cnum_map")
1343 // Translate a DefId from the current compilation environment to a DefId
1344 // for an external crate.
1345 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1346 if did.krate == cdata.cnum {
1347 return Some(DefId { krate: LOCAL_CRATE, index: did.index });
1350 for (&local, &global) in cdata.cnum_map.borrow().iter() {
1351 if global == did.krate {
1352 return Some(DefId { krate: local, index: did.index });
1359 /// Translates a `Span` from an extern crate to the corresponding `Span`
1360 /// within the local crate's codemap.
1361 pub fn translate_span(cdata: Cmd,
1362 codemap: &codemap::CodeMap,
1363 last_filemap_index_hint: &Cell<usize>,
1364 span: codemap::Span)
1366 let span = if span.lo > span.hi {
1367 // Currently macro expansion sometimes produces invalid Span values
1368 // where lo > hi. In order not to crash the compiler when trying to
1369 // translate these values, let's transform them into something we
1370 // can handle (and which will produce useful debug locations at
1371 // least some of the time).
1372 // This workaround is only necessary as long as macro expansion is
1373 // not fixed. FIXME(#23480)
1374 codemap::mk_sp(span.lo, span.lo)
1379 let imported_filemaps = cdata.imported_filemaps(&codemap);
1381 // Optimize for the case that most spans within a translated item
1382 // originate from the same filemap.
1383 let last_filemap_index = last_filemap_index_hint.get();
1384 let last_filemap = &imported_filemaps[last_filemap_index];
1386 if span.lo >= last_filemap.original_start_pos &&
1387 span.lo <= last_filemap.original_end_pos &&
1388 span.hi >= last_filemap.original_start_pos &&
1389 span.hi <= last_filemap.original_end_pos {
1393 let mut b = imported_filemaps.len();
1396 let m = (a + b) / 2;
1397 if imported_filemaps[m].original_start_pos > span.lo {
1404 last_filemap_index_hint.set(a);
1405 &imported_filemaps[a]
1409 let lo = (span.lo - filemap.original_start_pos) +
1410 filemap.translated_filemap.start_pos;
1411 let hi = (span.hi - filemap.original_start_pos) +
1412 filemap.translated_filemap.start_pos;
1414 codemap::mk_sp(lo, hi)
1417 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1420 where F: FnMut(DefId),
1422 let item_doc = cdata.lookup_item(id);
1423 for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1424 if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1425 callback(item_def_id(impl_doc, cdata));
1430 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1432 mut callback: F) where
1435 // Do a reverse lookup beforehand to avoid touching the crate_num
1436 // hash map in the loop below.
1437 if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1438 let def_id_u64 = def_to_u64(crate_local_did);
1440 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1441 for trait_doc in reader::tagged_docs(impls_doc, tag_impls_trait) {
1442 let trait_def_id = reader::get_doc(trait_doc, tag_def_id);
1443 if reader::doc_as_u64(trait_def_id) != def_id_u64 {
1446 for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1447 callback(translated_def_id(cdata, impl_doc));
1453 pub fn get_trait_of_item(cdata: Cmd, id: DefIndex, tcx: &TyCtxt)
1455 let item_doc = cdata.lookup_item(id);
1456 let parent_item_id = match item_parent_item(cdata, item_doc) {
1457 None => return None,
1458 Some(item_id) => item_id,
1460 let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1461 match item_family(parent_item_doc) {
1462 Trait => Some(item_def_id(parent_item_doc, cdata)),
1463 Impl | DefaultImpl => {
1464 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1465 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1472 pub fn get_native_libraries(cdata: Cmd)
1473 -> Vec<(cstore::NativeLibraryKind, String)> {
1474 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1475 tag_native_libraries);
1476 reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1477 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1478 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1479 let kind: cstore::NativeLibraryKind =
1480 cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1481 let name = name_doc.as_str().to_string();
1486 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<DefIndex> {
1487 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1488 .map(|doc| DefIndex::from_u32(reader::doc_as_u32(doc)))
1491 pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where
1492 F: FnMut(ast::Name, Vec<ast::Attribute>, Span, String) -> bool,
1494 let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1495 for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1496 let name = item_name(intr, macro_doc);
1497 let attrs = get_attributes(macro_doc);
1498 let span = get_macro_span(macro_doc);
1499 let body = reader::get_doc(macro_doc, tag_macro_def_body);
1500 if !f(name, attrs, span, body.as_str().to_string()) {
1506 pub fn get_macro_span(doc: rbml::Doc) -> Span {
1507 let lo_doc = reader::get_doc(doc, tag_macro_def_span_lo);
1508 let lo = BytePos(reader::doc_as_u32(lo_doc));
1509 let hi_doc = reader::get_doc(doc, tag_macro_def_span_hi);
1510 let hi = BytePos(reader::doc_as_u32(hi_doc));
1511 return Span { lo: lo, hi: hi, expn_id: NO_EXPANSION };
1514 pub fn get_dylib_dependency_formats(cdata: Cmd)
1515 -> Vec<(ast::CrateNum, LinkagePreference)>
1517 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1518 tag_dylib_dependency_formats);
1519 let mut result = Vec::new();
1521 debug!("found dylib deps: {}", formats.as_str_slice());
1522 for spec in formats.as_str_slice().split(',') {
1523 if spec.is_empty() { continue }
1524 let cnum = spec.split(':').nth(0).unwrap();
1525 let link = spec.split(':').nth(1).unwrap();
1526 let cnum: ast::CrateNum = cnum.parse().unwrap();
1527 let cnum = match cdata.cnum_map.borrow().get(&cnum) {
1529 None => panic!("didn't find a crate in the cnum_map")
1531 result.push((cnum, if link == "d" {
1532 LinkagePreference::RequireDynamic
1534 LinkagePreference::RequireStatic
1540 pub fn get_missing_lang_items(cdata: Cmd)
1541 -> Vec<lang_items::LangItem>
1543 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1544 reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1545 lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1549 pub fn get_method_arg_names(cdata: Cmd, id: DefIndex) -> Vec<String> {
1550 let method_doc = cdata.lookup_item(id);
1551 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1553 reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1554 name_doc.as_str_slice().to_string()
1561 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1562 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1564 reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1567 index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1572 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1573 let item_doc = cdata.lookup_item(id);
1574 match item_family(item_doc) {
1580 pub fn is_const_fn(cdata: Cmd, id: DefIndex) -> bool {
1581 let item_doc = cdata.lookup_item(id);
1582 match fn_constness(item_doc) {
1583 hir::Constness::Const => true,
1584 hir::Constness::NotConst => false,
1588 pub fn is_extern_item(cdata: Cmd, id: DefIndex, tcx: &TyCtxt) -> bool {
1589 let item_doc = match cdata.get_item(id) {
1591 None => return false,
1593 let applicable = match item_family(item_doc) {
1594 ImmStatic | MutStatic => true,
1596 let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1597 let no_generics = generics.types.is_empty();
1599 ty::TyFnDef(_, _, fn_ty) | ty::TyFnPtr(fn_ty)
1600 if fn_ty.abi != Abi::Rust => return no_generics,
1608 attr::contains_extern_indicator(tcx.sess.diagnostic(),
1609 &get_attributes(item_doc))
1615 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1616 let item_doc = cdata.lookup_item(id);
1617 match item_family(item_doc) {
1623 fn doc_generics<'tcx>(base_doc: rbml::Doc,
1627 -> ty::Generics<'tcx>
1629 let doc = reader::get_doc(base_doc, tag);
1631 let mut types = subst::VecPerParamSpace::empty();
1632 for p in reader::tagged_docs(doc, tag_type_param_def) {
1634 TyDecoder::with_doc(tcx, cdata.cnum, p,
1635 &mut |did| translate_def_id(cdata, did))
1636 .parse_type_param_def();
1637 types.push(bd.space, bd);
1640 let mut regions = subst::VecPerParamSpace::empty();
1641 for rp_doc in reader::tagged_docs(doc, tag_region_param_def) {
1642 let ident_str_doc = reader::get_doc(rp_doc,
1643 tag_region_param_def_ident);
1644 let name = item_name(&token::get_ident_interner(), ident_str_doc);
1645 let def_id_doc = reader::get_doc(rp_doc,
1646 tag_region_param_def_def_id);
1647 let def_id = translated_def_id(cdata, def_id_doc);
1649 let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1650 let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as usize);
1652 let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1653 let index = reader::doc_as_u64(doc) as u32;
1655 let bounds = reader::tagged_docs(rp_doc, tag_items_data_region).map(|p| {
1656 TyDecoder::with_doc(tcx, cdata.cnum, p,
1657 &mut |did| translate_def_id(cdata, did))
1661 regions.push(space, ty::RegionParameterDef { name: name,
1668 ty::Generics { types: types, regions: regions }
1671 fn doc_predicate<'tcx>(cdata: Cmd,
1674 -> ty::Predicate<'tcx>
1676 let predicate_pos = cdata.xref_index.lookup(
1677 cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1679 cdata.data(), cdata.cnum, predicate_pos, tcx,
1680 &mut |did| translate_def_id(cdata, did)
1684 fn doc_predicates<'tcx>(base_doc: rbml::Doc,
1688 -> ty::GenericPredicates<'tcx>
1690 let doc = reader::get_doc(base_doc, tag);
1692 let mut predicates = subst::VecPerParamSpace::empty();
1693 for predicate_doc in reader::tagged_docs(doc, tag_type_predicate) {
1694 predicates.push(subst::TypeSpace,
1695 doc_predicate(cdata, predicate_doc, tcx));
1697 for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1698 predicates.push(subst::SelfSpace,
1699 doc_predicate(cdata, predicate_doc, tcx));
1701 for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1702 predicates.push(subst::FnSpace,
1703 doc_predicate(cdata, predicate_doc, tcx));
1706 ty::GenericPredicates { predicates: predicates }
1709 pub fn is_defaulted_trait(cdata: Cmd, trait_id: DefIndex) -> bool {
1710 let trait_doc = cdata.lookup_item(trait_id);
1711 assert!(item_family(trait_doc) == Family::Trait);
1712 let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1713 reader::doc_as_u8(defaulted_doc) != 0
1716 pub fn is_default_impl(cdata: Cmd, impl_id: DefIndex) -> bool {
1717 let impl_doc = cdata.lookup_item(impl_id);
1718 item_family(impl_doc) == Family::DefaultImpl
1721 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
1722 let crate_doc = rbml::Doc::new(metadata);
1723 let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1725 reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1726 let mut decoder = reader::Decoder::new(filemap_doc);
1727 decoder.read_opaque(|opaque_decoder, _| {
1728 Decodable::decode(opaque_decoder)
1733 pub fn closure_kind(cdata: Cmd, closure_id: DefIndex) -> ty::ClosureKind {
1734 let closure_doc = cdata.lookup_item(closure_id);
1735 let closure_kind_doc = reader::get_doc(closure_doc, tag_items_closure_kind);
1736 let mut decoder = reader::Decoder::new(closure_kind_doc);
1737 ty::ClosureKind::decode(&mut decoder).unwrap()
1740 pub fn closure_ty<'tcx>(cdata: Cmd, closure_id: DefIndex, tcx: &TyCtxt<'tcx>)
1741 -> ty::ClosureTy<'tcx> {
1742 let closure_doc = cdata.lookup_item(closure_id);
1743 let closure_ty_doc = reader::get_doc(closure_doc, tag_items_closure_ty);
1744 TyDecoder::with_doc(tcx, cdata.cnum, closure_ty_doc, &mut |did| translate_def_id(cdata, did))
1748 fn def_key(item_doc: rbml::Doc) -> hir_map::DefKey {
1749 match reader::maybe_get_doc(item_doc, tag_def_key) {
1750 Some(def_key_doc) => {
1751 let mut decoder = reader::Decoder::new(def_key_doc);
1752 hir_map::DefKey::decode(&mut decoder).unwrap()
1755 panic!("failed to find block with tag {:?} for item with family {:?}",
1757 item_family(item_doc))
1762 pub fn def_path(cdata: Cmd, id: DefIndex) -> hir_map::DefPath {
1763 debug!("def_path(id={:?})", id);
1764 hir_map::definitions::make_def_path(id, |parent| {
1765 debug!("def_path: parent={:?}", parent);
1766 let parent_doc = cdata.lookup_item(parent);