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 cstore::{self, crate_metadata};
19 use encoder::def_to_u64;
22 use tydecode::TyDecoder;
24 use rustc::back::svh::Svh;
25 use rustc::front::map as hir_map;
26 use rustc::util::nodemap::FnvHashMap;
29 use middle::cstore::{LOCAL_CRATE, FoundAst, InlinedItem, LinkagePreference};
30 use middle::cstore::{DefLike, DlDef, DlField, DlImpl, tls};
32 use middle::def_id::{DefId, DefIndex};
33 use middle::lang_items;
35 use middle::ty::{ImplContainer, TraitContainer};
36 use middle::ty::{self, RegionEscape, Ty};
39 use rustc::mir::visit::MutVisitor;
41 use std::cell::{Cell, RefCell};
42 use std::io::prelude::*;
49 use serialize::Decodable;
51 use syntax::parse::token::{IdentInterner, special_idents};
52 use syntax::parse::token;
55 use syntax::codemap::{self, Span};
56 use syntax::print::pprust;
60 pub type Cmd<'a> = &'a crate_metadata;
63 fn get_item(&self, item_id: DefIndex) -> Option<rbml::Doc> {
64 self.index.lookup_item(self.data(), item_id).map(|pos| {
65 reader::doc_at(self.data(), pos as usize).unwrap().doc
69 fn lookup_item(&self, item_id: DefIndex) -> rbml::Doc {
70 match self.get_item(item_id) {
71 None => panic!("lookup_item: id not found: {:?}", item_id),
77 pub fn load_index(data: &[u8]) -> index::Index {
78 let index = reader::get_doc(rbml::Doc::new(data), tag_index);
79 index::Index::from_rbml(index)
82 pub fn crate_rustc_version(data: &[u8]) -> Option<String> {
83 let doc = rbml::Doc::new(data);
84 reader::maybe_get_doc(doc, tag_rustc_version).map(|s| s.as_str())
87 pub fn load_xrefs(data: &[u8]) -> index::DenseIndex {
88 let index = reader::get_doc(rbml::Doc::new(data), tag_xref_index);
89 index::DenseIndex::from_buf(index.data, index.start, index.end)
92 #[derive(Debug, PartialEq)]
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 {
130 'V' => StructVariant,
136 'N' => InheritedField,
137 c => panic!("unexpected family char: {}", c)
141 fn item_visibility(item: rbml::Doc) -> hir::Visibility {
142 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
144 Some(visibility_doc) => {
145 match reader::doc_as_u8(visibility_doc) as char {
147 'i' => hir::Inherited,
148 _ => panic!("unknown visibility character")
154 fn fn_constness(item: rbml::Doc) -> hir::Constness {
155 match reader::maybe_get_doc(item, tag_items_data_item_constness) {
156 None => hir::Constness::NotConst,
157 Some(constness_doc) => {
158 match reader::doc_as_u8(constness_doc) as char {
159 'c' => hir::Constness::Const,
160 'n' => hir::Constness::NotConst,
161 _ => panic!("unknown constness character")
167 fn item_sort(item: rbml::Doc) -> Option<char> {
168 reader::tagged_docs(item, tag_item_trait_item_sort).nth(0).map(|doc| {
169 doc.as_str_slice().as_bytes()[0] as char
173 fn item_symbol(item: rbml::Doc) -> String {
174 reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
177 fn translated_def_id(cdata: Cmd, d: rbml::Doc) -> DefId {
178 let id = reader::doc_as_u64(d);
179 let index = DefIndex::new((id & 0xFFFF_FFFF) as usize);
180 let def_id = DefId { krate: (id >> 32) as u32, index: index };
181 translate_def_id(cdata, def_id)
184 fn item_parent_item(cdata: Cmd, d: rbml::Doc) -> Option<DefId> {
185 reader::tagged_docs(d, tag_items_data_parent_item).nth(0).map(|did| {
186 translated_def_id(cdata, did)
190 fn item_require_parent_item(cdata: Cmd, d: rbml::Doc) -> DefId {
191 translated_def_id(cdata, reader::get_doc(d, tag_items_data_parent_item))
194 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> DefId {
195 translated_def_id(cdata, reader::get_doc(d, tag_def_id))
198 fn reexports<'a>(d: rbml::Doc<'a>) -> reader::TaggedDocsIterator<'a> {
199 reader::tagged_docs(d, tag_items_data_item_reexport)
202 fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
203 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
204 reader::with_doc_data(val_doc, |data| {
205 str::from_utf8(data).ok().and_then(|s| s.parse().ok())
210 fn doc_type<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
211 let tp = reader::get_doc(doc, tag_items_data_item_type);
212 TyDecoder::with_doc(tcx, cdata.cnum, tp,
213 &mut |did| translate_def_id(cdata, did))
217 fn maybe_doc_type<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Option<Ty<'tcx>> {
218 reader::maybe_get_doc(doc, tag_items_data_item_type).map(|tp| {
219 TyDecoder::with_doc(tcx, cdata.cnum, tp,
220 &mut |did| translate_def_id(cdata, did))
225 pub fn item_type<'tcx>(_item_id: DefId, item: rbml::Doc,
226 tcx: &ty::ctxt<'tcx>, cdata: Cmd) -> Ty<'tcx> {
227 doc_type(item, tcx, cdata)
230 fn doc_trait_ref<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd)
231 -> ty::TraitRef<'tcx> {
232 TyDecoder::with_doc(tcx, cdata.cnum, doc,
233 &mut |did| translate_def_id(cdata, did))
237 fn item_trait_ref<'tcx>(doc: rbml::Doc, tcx: &ty::ctxt<'tcx>, cdata: Cmd)
238 -> ty::TraitRef<'tcx> {
239 let tp = reader::get_doc(doc, tag_item_trait_ref);
240 doc_trait_ref(tp, tcx, cdata)
243 fn item_path(item_doc: rbml::Doc) -> Vec<hir_map::PathElem> {
244 let path_doc = reader::get_doc(item_doc, tag_path);
245 reader::docs(path_doc).filter_map(|(tag, elt_doc)| {
246 if tag == tag_path_elem_mod {
247 let s = elt_doc.as_str_slice();
248 Some(hir_map::PathMod(token::intern(s)))
249 } else if tag == tag_path_elem_name {
250 let s = elt_doc.as_str_slice();
251 Some(hir_map::PathName(token::intern(s)))
253 // ignore tag_path_len element
259 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Name {
260 let name = reader::get_doc(item, tag_paths_data_name);
261 let string = name.as_str_slice();
262 match intr.find(string) {
263 None => token::intern(string),
268 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
269 let fam = item_family(item);
272 // Check whether we have an associated const item.
273 match item_sort(item) {
274 Some('C') | Some('c') => {
275 DlDef(def::DefAssociatedConst(did))
278 // Regular const item.
279 DlDef(def::DefConst(did))
283 ImmStatic => DlDef(def::DefStatic(did, false)),
284 MutStatic => DlDef(def::DefStatic(did, true)),
285 Struct => DlDef(def::DefStruct(did)),
286 Fn => DlDef(def::DefFn(did, false)),
287 CtorFn => DlDef(def::DefFn(did, true)),
288 Method | StaticMethod => {
289 DlDef(def::DefMethod(did))
292 if item_sort(item) == Some('t') {
293 let trait_did = item_require_parent_item(cdata, item);
294 DlDef(def::DefAssociatedTy(trait_did, did))
296 DlDef(def::DefTy(did, false))
299 Mod => DlDef(def::DefMod(did)),
300 ForeignMod => DlDef(def::DefForeignMod(did)),
302 let enum_did = item_require_parent_item(cdata, item);
303 DlDef(def::DefVariant(enum_did, did, true))
306 let enum_did = item_require_parent_item(cdata, item);
307 DlDef(def::DefVariant(enum_did, did, false))
309 Trait => DlDef(def::DefTrait(did)),
310 Enum => DlDef(def::DefTy(did, true)),
311 Impl | DefaultImpl => DlImpl(did),
312 PublicField | InheritedField => DlField,
316 fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
317 let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
318 if reader::doc_as_u8(unsafety_doc) != 0 {
319 hir::Unsafety::Unsafe
321 hir::Unsafety::Normal
325 fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
326 let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
327 reader::doc_as_u8(paren_sugar_doc) != 0
330 fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
331 let polarity_doc = reader::get_doc(item_doc, tag_polarity);
332 if reader::doc_as_u8(polarity_doc) != 0 {
333 hir::ImplPolarity::Negative
335 hir::ImplPolarity::Positive
339 fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
340 let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
341 reader::tagged_docs(names_doc, tag_associated_type_name)
342 .map(|name_doc| token::intern(name_doc.as_str_slice()))
346 pub fn get_trait_def<'tcx>(cdata: Cmd,
348 tcx: &ty::ctxt<'tcx>) -> ty::TraitDef<'tcx>
350 let item_doc = cdata.lookup_item(item_id);
351 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
352 let unsafety = parse_unsafety(item_doc);
353 let associated_type_names = parse_associated_type_names(item_doc);
354 let paren_sugar = parse_paren_sugar(item_doc);
357 paren_sugar: paren_sugar,
360 trait_ref: item_trait_ref(item_doc, tcx, cdata),
361 associated_type_names: associated_type_names,
362 nonblanket_impls: RefCell::new(FnvHashMap()),
363 blanket_impls: RefCell::new(vec![]),
364 flags: Cell::new(ty::TraitFlags::NO_TRAIT_FLAGS)
368 pub fn get_adt_def<'tcx>(intr: &IdentInterner,
371 tcx: &ty::ctxt<'tcx>) -> ty::AdtDefMaster<'tcx>
373 fn get_enum_variants<'tcx>(intr: &IdentInterner,
376 tcx: &ty::ctxt<'tcx>) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
377 let mut disr_val = 0;
378 reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
379 let did = translated_def_id(cdata, p);
380 let item = cdata.lookup_item(did.index);
382 if let Some(disr) = variant_disr_val(item) {
386 disr_val = disr_val.wrapping_add(1);
390 name: item_name(intr, item),
391 fields: get_variant_fields(intr, cdata, item, tcx),
396 fn get_variant_fields<'tcx>(intr: &IdentInterner,
399 tcx: &ty::ctxt<'tcx>) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
400 reader::tagged_docs(doc, tag_item_field).map(|f| {
401 let ff = item_family(f);
403 PublicField | InheritedField => {},
404 _ => tcx.sess.bug(&format!("expected field, found {:?}", ff))
406 ty::FieldDefData::new(item_def_id(f, cdata),
408 struct_field_family_to_visibility(ff))
409 }).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
410 let ff = item_family(f);
411 ty::FieldDefData::new(item_def_id(f, cdata),
412 special_idents::unnamed_field.name,
413 struct_field_family_to_visibility(ff))
416 fn get_struct_variant<'tcx>(intr: &IdentInterner,
420 tcx: &ty::ctxt<'tcx>) -> ty::VariantDefData<'tcx, 'tcx> {
423 name: item_name(intr, doc),
424 fields: get_variant_fields(intr, cdata, doc, tcx),
429 let doc = cdata.lookup_item(item_id);
430 let did = DefId { krate: cdata.cnum, index: item_id };
431 let (kind, variants) = match item_family(doc) {
434 get_enum_variants(intr, cdata, doc, tcx))
438 reader::maybe_get_doc(doc, tag_items_data_item_struct_ctor).
439 map_or(did, |ctor_doc| translated_def_id(cdata, ctor_doc));
440 (ty::AdtKind::Struct,
441 vec![get_struct_variant(intr, cdata, doc, ctor_did, tcx)])
444 &format!("get_adt_def called on a non-ADT {:?} - {:?}",
445 item_family(doc), did))
448 let adt = tcx.intern_adt_def(did, kind, variants);
450 // this needs to be done *after* the variant is interned,
451 // to support recursive structures
452 for variant in &adt.variants {
453 if variant.kind() == ty::VariantKind::Tuple &&
454 adt.adt_kind() == ty::AdtKind::Enum {
455 // tuple-like enum variant fields aren't real items - get the types
457 debug!("evaluating the ctor-type of {:?}",
459 let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
460 debug!("evaluating the ctor-type of {:?}.. {:?}",
463 let field_tys = match ctor_ty.sty {
464 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
467 // tuple-struct constructors don't have escaping regions
468 assert!(!inputs.has_escaping_regions());
471 _ => tcx.sess.bug("tuple-variant ctor is not an ADT")
473 for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
474 field.fulfill_ty(ty);
477 for field in &variant.fields {
478 debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
479 let ty = get_type(cdata, field.did.index, tcx).ty;
480 field.fulfill_ty(ty);
481 debug!("evaluating the type of {:?}::{:?}: {:?}",
482 variant.name, field.name, ty);
490 pub fn get_predicates<'tcx>(cdata: Cmd,
492 tcx: &ty::ctxt<'tcx>)
493 -> ty::GenericPredicates<'tcx>
495 let item_doc = cdata.lookup_item(item_id);
496 doc_predicates(item_doc, tcx, cdata, tag_item_generics)
499 pub fn get_super_predicates<'tcx>(cdata: Cmd,
501 tcx: &ty::ctxt<'tcx>)
502 -> ty::GenericPredicates<'tcx>
504 let item_doc = cdata.lookup_item(item_id);
505 doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
508 pub fn get_type<'tcx>(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt<'tcx>)
509 -> ty::TypeScheme<'tcx>
511 let item_doc = cdata.lookup_item(id);
512 let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
514 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
521 pub fn get_stability(cdata: Cmd, id: DefIndex) -> Option<attr::Stability> {
522 let item = cdata.lookup_item(id);
523 reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
524 let mut decoder = reader::Decoder::new(doc);
525 Decodable::decode(&mut decoder).unwrap()
529 pub fn get_deprecation(cdata: Cmd, id: DefIndex) -> Option<attr::Deprecation> {
530 let item = cdata.lookup_item(id);
531 reader::maybe_get_doc(item, tag_items_data_item_deprecation).map(|doc| {
532 let mut decoder = reader::Decoder::new(doc);
533 Decodable::decode(&mut decoder).unwrap()
537 pub fn get_repr_attrs(cdata: Cmd, id: DefIndex) -> Vec<attr::ReprAttr> {
538 let item = cdata.lookup_item(id);
539 match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
540 let mut decoder = reader::Decoder::new(doc);
541 Decodable::decode(&mut decoder).unwrap()
543 Some(attrs) => attrs,
548 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
550 -> Option<hir::ImplPolarity>
552 let item_doc = cdata.lookup_item(id);
553 let fam = item_family(item_doc);
556 Some(parse_polarity(item_doc))
562 pub fn get_custom_coerce_unsized_kind<'tcx>(
565 -> Option<ty::adjustment::CustomCoerceUnsized>
567 let item_doc = cdata.lookup_item(id);
568 reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
569 let mut decoder = reader::Decoder::new(kind_doc);
570 Decodable::decode(&mut decoder).unwrap()
574 pub fn get_impl_trait<'tcx>(cdata: Cmd,
576 tcx: &ty::ctxt<'tcx>)
577 -> Option<ty::TraitRef<'tcx>>
579 let item_doc = cdata.lookup_item(id);
580 let fam = item_family(item_doc);
582 Family::Impl | Family::DefaultImpl => {
583 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
584 doc_trait_ref(tp, tcx, cdata)
591 pub fn get_symbol(cdata: Cmd, id: DefIndex) -> String {
592 return item_symbol(cdata.lookup_item(id));
595 /// If you have a crate_metadata, call get_symbol instead
596 pub fn get_symbol_from_buf(data: &[u8], id: DefIndex) -> String {
597 let index = load_index(data);
598 let pos = index.lookup_item(data, id).unwrap();
599 let doc = reader::doc_at(data, pos as usize).unwrap().doc;
603 /// Iterates over the language items in the given crate.
604 pub fn each_lang_item<F>(cdata: Cmd, mut f: F) -> bool where
605 F: FnMut(DefIndex, usize) -> bool,
607 let root = rbml::Doc::new(cdata.data());
608 let lang_items = reader::get_doc(root, tag_lang_items);
609 reader::tagged_docs(lang_items, tag_lang_items_item).all(|item_doc| {
610 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
611 let id = reader::doc_as_u32(id_doc) as usize;
612 let index_doc = reader::get_doc(item_doc, tag_lang_items_item_index);
613 let index = DefIndex::from_u32(reader::doc_as_u32(index_doc));
619 fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
622 mut get_crate_data: G,
623 mut callback: F) where
624 F: FnMut(DefLike, ast::Name, hir::Visibility),
625 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
627 // Iterate over all children.
628 for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
629 let child_def_id = translated_def_id(cdata, child_info_doc);
631 // This item may be in yet another crate if it was the child of a
633 let crate_data = if child_def_id.krate == cdata.cnum {
636 Some(get_crate_data(child_def_id.krate))
638 let crate_data = match crate_data {
639 Some(ref cdata) => &**cdata,
644 match crate_data.get_item(child_def_id.index) {
646 Some(child_item_doc) => {
647 // Hand off the item to the callback.
648 let child_name = item_name(&*intr, child_item_doc);
649 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
650 let visibility = item_visibility(child_item_doc);
651 callback(def_like, child_name, visibility);
656 // As a special case, iterate over all static methods of
657 // associated implementations too. This is a bit of a botch.
659 for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
660 tag_items_data_item_inherent_impl) {
661 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
662 if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.index) {
663 for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
664 tag_item_impl_item) {
665 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
667 if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.index) {
668 if let StaticMethod = item_family(impl_method_doc) {
669 // Hand off the static method to the callback.
670 let static_method_name = item_name(&*intr, impl_method_doc);
671 let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
673 callback(static_method_def_like,
675 item_visibility(impl_method_doc));
682 for reexport_doc in reexports(item_doc) {
683 let def_id_doc = reader::get_doc(reexport_doc,
684 tag_items_data_item_reexport_def_id);
685 let child_def_id = translated_def_id(cdata, def_id_doc);
687 let name_doc = reader::get_doc(reexport_doc,
688 tag_items_data_item_reexport_name);
689 let name = name_doc.as_str_slice();
691 // This reexport may be in yet another crate.
692 let crate_data = if child_def_id.krate == cdata.cnum {
695 Some(get_crate_data(child_def_id.krate))
697 let crate_data = match crate_data {
698 Some(ref cdata) => &**cdata,
703 if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
704 // Hand off the item to the callback.
705 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
706 // These items have a public visibility because they're part of
707 // a public re-export.
708 callback(def_like, token::intern(name), hir::Public);
713 /// Iterates over each child of the given item.
714 pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
719 F: FnMut(DefLike, ast::Name, hir::Visibility),
720 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
723 let item_doc = match cdata.get_item(id) {
725 Some(item_doc) => item_doc,
728 each_child_of_item_or_crate(intr,
735 /// Iterates over all the top-level crate items.
736 pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
740 F: FnMut(DefLike, ast::Name, hir::Visibility),
741 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
743 let root_doc = rbml::Doc::new(cdata.data());
744 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
745 let crate_items_doc = reader::get_doc(misc_info_doc,
746 tag_misc_info_crate_items);
748 each_child_of_item_or_crate(intr,
755 pub fn get_item_path(cdata: Cmd, id: DefIndex) -> Vec<hir_map::PathElem> {
756 item_path(cdata.lookup_item(id))
759 pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: DefIndex) -> ast::Name {
760 item_name(intr, cdata.lookup_item(id))
763 pub type DecodeInlinedItem<'a> =
764 Box<for<'tcx> FnMut(Cmd,
766 Vec<hir_map::PathElem>, // parent_path
767 hir_map::DefPath, // parent_def_path
770 -> Result<&'tcx InlinedItem, (Vec<hir_map::PathElem>,
771 hir_map::DefPath)> + 'a>;
773 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd,
774 tcx: &ty::ctxt<'tcx>,
776 mut decode_inlined_item: DecodeInlinedItem)
778 debug!("Looking up item: {:?}", id);
779 let item_doc = cdata.lookup_item(id);
780 let item_did = item_def_id(item_doc, cdata);
782 let mut path = item_path(item_doc);
786 let parent_def_path = {
787 let mut def_path = def_path(cdata, id);
791 match decode_inlined_item(cdata,
797 Ok(ii) => FoundAst::Found(ii),
798 Err((mut parent_path, mut parent_def_path)) => {
799 match item_parent_item(cdata, item_doc) {
800 Some(parent_did) => {
801 // Remove the last element from the paths, since we are now
802 // trying to inline the parent.
804 parent_def_path.pop();
806 let parent_item = cdata.lookup_item(parent_did.index);
807 match decode_inlined_item(cdata,
813 Ok(ii) => FoundAst::FoundParent(parent_did, ii),
814 Err(_) => FoundAst::NotFound
817 None => FoundAst::NotFound
823 pub fn maybe_get_item_mir<'tcx>(cdata: Cmd,
824 tcx: &ty::ctxt<'tcx>,
826 -> Option<mir::repr::Mir<'tcx>> {
827 let item_doc = cdata.lookup_item(id);
829 return reader::maybe_get_doc(item_doc, tag_mir as usize).map(|mir_doc| {
830 let dcx = tls_context::DecodingContext {
831 crate_metadata: cdata,
834 let mut decoder = reader::Decoder::new(mir_doc);
836 let mut mir = tls::enter_decoding_context(&dcx, &mut decoder, |_, decoder| {
837 Decodable::decode(decoder).unwrap()
840 let mut def_id_and_span_translator = MirDefIdAndSpanTranslator {
841 crate_metadata: cdata,
842 codemap: tcx.sess.codemap(),
843 last_filemap_index_hint: Cell::new(0),
846 def_id_and_span_translator.visit_mir(&mut mir);
851 struct MirDefIdAndSpanTranslator<'cdata, 'codemap> {
852 crate_metadata: Cmd<'cdata>,
853 codemap: &'codemap codemap::CodeMap,
854 last_filemap_index_hint: Cell<usize>
857 impl<'v, 'cdata, 'codemap> mir::visit::MutVisitor<'v>
858 for MirDefIdAndSpanTranslator<'cdata, 'codemap>
860 fn visit_def_id(&mut self, def_id: &mut DefId) {
861 *def_id = translate_def_id(self.crate_metadata, *def_id);
864 fn visit_span(&mut self, span: &mut Span) {
865 *span = translate_span(self.crate_metadata,
867 &self.last_filemap_index_hint,
873 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
874 fn get_mutability(ch: u8) -> hir::Mutability {
876 'i' => hir::MutImmutable,
877 'm' => hir::MutMutable,
878 _ => panic!("unknown mutability character: `{}`", ch as char),
882 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
883 let string = explicit_self_doc.as_str_slice();
885 let explicit_self_kind = string.as_bytes()[0];
886 match explicit_self_kind as char {
887 's' => ty::ExplicitSelfCategory::Static,
888 'v' => ty::ExplicitSelfCategory::ByValue,
889 '~' => ty::ExplicitSelfCategory::ByBox,
890 // FIXME(#4846) expl. region
892 ty::ExplicitSelfCategory::ByReference(
894 get_mutability(string.as_bytes()[1]))
896 _ => panic!("unknown self type code: `{}`", explicit_self_kind as char)
900 /// Returns the def IDs of all the items in the given implementation.
901 pub fn get_impl_items(cdata: Cmd, impl_id: DefIndex)
902 -> Vec<ty::ImplOrTraitItemId> {
903 reader::tagged_docs(cdata.lookup_item(impl_id), tag_item_impl_item).map(|doc| {
904 let def_id = item_def_id(doc, cdata);
905 match item_sort(doc) {
906 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
907 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
908 Some('t') => ty::TypeTraitItemId(def_id),
909 _ => panic!("unknown impl item sort"),
914 pub fn get_trait_name(intr: Rc<IdentInterner>,
918 let doc = cdata.lookup_item(id);
919 item_name(&*intr, doc)
922 pub fn is_static_method(cdata: Cmd, id: DefIndex) -> bool {
923 let doc = cdata.lookup_item(id);
924 match item_sort(doc) {
925 Some('r') | Some('p') => {
926 get_explicit_self(doc) == ty::ExplicitSelfCategory::Static
932 pub fn get_impl_or_trait_item<'tcx>(intr: Rc<IdentInterner>,
935 tcx: &ty::ctxt<'tcx>)
936 -> ty::ImplOrTraitItem<'tcx> {
937 let item_doc = cdata.lookup_item(id);
939 let def_id = item_def_id(item_doc, cdata);
941 let container_id = item_require_parent_item(cdata, item_doc);
942 let container_doc = cdata.lookup_item(container_id.index);
943 let container = match item_family(container_doc) {
944 Trait => TraitContainer(container_id),
945 _ => ImplContainer(container_id),
948 let name = item_name(&*intr, item_doc);
949 let vis = item_visibility(item_doc);
951 match item_sort(item_doc) {
952 sort @ Some('C') | sort @ Some('c') => {
953 let ty = doc_type(item_doc, tcx, cdata);
954 ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
959 container: container,
960 has_value: sort == Some('C')
963 Some('r') | Some('p') => {
964 let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
965 let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
966 let ity = tcx.lookup_item_type(def_id).ty;
967 let fty = match ity.sty {
968 ty::TyBareFn(_, fty) => fty.clone(),
969 _ => tcx.sess.bug(&format!(
970 "the type {:?} of the method {:?} is not a function?",
973 let explicit_self = get_explicit_self(item_doc);
975 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
985 let ty = maybe_doc_type(item_doc, tcx, cdata);
986 ty::TypeTraitItem(Rc::new(ty::AssociatedType {
991 container: container,
994 _ => panic!("unknown impl/trait item sort"),
998 pub fn get_trait_item_def_ids(cdata: Cmd, id: DefIndex)
999 -> Vec<ty::ImplOrTraitItemId> {
1000 let item = cdata.lookup_item(id);
1001 reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
1002 let def_id = item_def_id(mth, cdata);
1003 match item_sort(mth) {
1004 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
1005 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
1006 Some('t') => ty::TypeTraitItemId(def_id),
1007 _ => panic!("unknown trait item sort"),
1012 pub fn get_item_variances(cdata: Cmd, id: DefIndex) -> ty::ItemVariances {
1013 let item_doc = cdata.lookup_item(id);
1014 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
1015 let mut decoder = reader::Decoder::new(variance_doc);
1016 Decodable::decode(&mut decoder).unwrap()
1019 pub fn get_provided_trait_methods<'tcx>(intr: Rc<IdentInterner>,
1022 tcx: &ty::ctxt<'tcx>)
1023 -> Vec<Rc<ty::Method<'tcx>>> {
1024 let item = cdata.lookup_item(id);
1026 reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
1027 let did = item_def_id(mth_id, cdata);
1028 let mth = cdata.lookup_item(did.index);
1030 if item_sort(mth) == Some('p') {
1031 let trait_item = get_impl_or_trait_item(intr.clone(),
1035 if let ty::MethodTraitItem(ref method) = trait_item {
1036 Some((*method).clone())
1046 pub fn get_associated_consts<'tcx>(intr: Rc<IdentInterner>,
1049 tcx: &ty::ctxt<'tcx>)
1050 -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
1051 let item = cdata.lookup_item(id);
1053 [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
1054 reader::tagged_docs(item, tag).filter_map(|ac_id| {
1055 let did = item_def_id(ac_id, cdata);
1056 let ac_doc = cdata.lookup_item(did.index);
1058 match item_sort(ac_doc) {
1059 Some('C') | Some('c') => {
1060 let trait_item = get_impl_or_trait_item(intr.clone(),
1064 if let ty::ConstTraitItem(ref ac) = trait_item {
1076 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1077 /// the actual type definition, otherwise, return None
1078 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1082 let item = cdata.lookup_item(node_id);
1083 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1084 item_require_parent_item(cdata, item)
1088 pub fn get_item_attrs(cdata: Cmd,
1089 orig_node_id: DefIndex)
1090 -> Vec<ast::Attribute> {
1091 // The attributes for a tuple struct are attached to the definition, not the ctor;
1092 // we assume that someone passing in a tuple struct ctor is actually wanting to
1093 // look at the definition
1094 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1095 let node_id = node_id.map(|x| x.index).unwrap_or(orig_node_id);
1096 let item = cdata.lookup_item(node_id);
1097 get_attributes(item)
1100 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<DefId, Vec<ast::Attribute>> {
1101 let data = rbml::Doc::new(cdata.data());
1102 let fields = reader::get_doc(data, tag_struct_fields);
1103 reader::tagged_docs(fields, tag_struct_field).map(|field| {
1104 let def_id = translated_def_id(cdata, reader::get_doc(field, tag_def_id));
1105 let attrs = get_attributes(field);
1110 fn struct_field_family_to_visibility(family: Family) -> hir::Visibility {
1112 PublicField => hir::Public,
1113 InheritedField => hir::Inherited,
1118 pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: DefIndex)
1120 let item = cdata.lookup_item(id);
1121 reader::tagged_docs(item, tag_item_field).map(|an_item| {
1122 item_name(intr, an_item)
1123 }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1124 special_idents::unnamed_field.name
1128 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1129 reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1130 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1131 let n = token::intern_and_get_ident(nd.as_str_slice());
1132 attr::mk_word_item(n)
1133 }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1134 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1135 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1136 let n = token::intern_and_get_ident(nd.as_str_slice());
1137 let v = token::intern_and_get_ident(vd.as_str_slice());
1138 // FIXME (#623): Should be able to decode MetaNameValue variants,
1139 // but currently the encoder just drops them
1140 attr::mk_name_value_item_str(n, v)
1141 })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1142 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1143 let n = token::intern_and_get_ident(nd.as_str_slice());
1144 let subitems = get_meta_items(meta_item_doc);
1145 attr::mk_list_item(n, subitems)
1149 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1150 match reader::maybe_get_doc(md, tag_attributes) {
1152 reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1153 let is_sugared_doc = reader::doc_as_u8(
1154 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1156 let meta_items = get_meta_items(attr_doc);
1157 // Currently it's only possible to have a single meta item on
1159 assert_eq!(meta_items.len(), 1);
1160 let meta_item = meta_items.into_iter().nth(0).unwrap();
1162 node: ast::Attribute_ {
1163 id: attr::mk_attr_id(),
1164 style: ast::AttrStyle::Outer,
1166 is_sugared_doc: is_sugared_doc,
1168 span: codemap::DUMMY_SP
1176 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1177 out: &mut io::Write) -> io::Result<()> {
1178 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1180 let r = get_attributes(md);
1182 try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1188 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1189 get_attributes(rbml::Doc::new(data))
1193 pub struct CrateDep {
1194 pub cnum: ast::CrateNum,
1197 pub explicitly_linked: bool,
1200 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1201 let cratedoc = rbml::Doc::new(data);
1202 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1204 fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1205 let d = reader::get_doc(doc, tag_);
1206 d.as_str_slice().to_string()
1209 reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1210 let name = docstr(depdoc, tag_crate_dep_crate_name);
1211 let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash));
1212 let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1213 let explicitly_linked = reader::doc_as_u8(doc) != 0;
1215 cnum: crate_num as u32 + 1,
1218 explicitly_linked: explicitly_linked,
1223 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1224 try!(write!(out, "=External Dependencies=\n"));
1225 for dep in &get_crate_deps(data) {
1226 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1228 try!(write!(out, "\n"));
1232 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1233 let cratedoc = rbml::Doc::new(data);
1234 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1235 Svh::new(doc.as_str_slice())
1239 pub fn get_crate_hash(data: &[u8]) -> Svh {
1240 let cratedoc = rbml::Doc::new(data);
1241 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1242 Svh::new(hashdoc.as_str_slice())
1245 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1246 let cratedoc = rbml::Doc::new(data);
1247 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1248 doc.as_str_slice().to_string()
1252 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1253 let cratedoc = rbml::Doc::new(data);
1254 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1255 triple_doc.map(|s| s.as_str().to_string())
1258 pub fn get_crate_name(data: &[u8]) -> String {
1259 maybe_get_crate_name(data).expect("no crate name in crate")
1262 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1263 let hash = get_crate_hash(bytes);
1264 let md = rbml::Doc::new(bytes);
1265 try!(list_crate_attributes(md, &hash, out));
1266 list_crate_deps(bytes, out)
1269 // Translates a def_id from an external crate to a def_id for the current
1270 // compilation environment. We use this when trying to load types from
1271 // external crates - if those types further refer to types in other crates
1272 // then we must translate the crate number from that encoded in the external
1273 // crate to the correct local crate number.
1274 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1276 return DefId { krate: cdata.cnum, index: did.index };
1279 match cdata.cnum_map.borrow().get(&did.krate) {
1286 None => panic!("didn't find a crate in the cnum_map")
1290 // Translate a DefId from the current compilation environment to a DefId
1291 // for an external crate.
1292 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1293 if did.krate == cdata.cnum {
1294 return Some(DefId { krate: LOCAL_CRATE, index: did.index });
1297 for (&local, &global) in cdata.cnum_map.borrow().iter() {
1298 if global == did.krate {
1299 return Some(DefId { krate: local, index: did.index });
1306 /// Translates a `Span` from an extern crate to the corresponding `Span`
1307 /// within the local crate's codemap.
1308 pub fn translate_span(cdata: Cmd,
1309 codemap: &codemap::CodeMap,
1310 last_filemap_index_hint: &Cell<usize>,
1311 span: codemap::Span)
1313 let span = if span.lo > span.hi {
1314 // Currently macro expansion sometimes produces invalid Span values
1315 // where lo > hi. In order not to crash the compiler when trying to
1316 // translate these values, let's transform them into something we
1317 // can handle (and which will produce useful debug locations at
1318 // least some of the time).
1319 // This workaround is only necessary as long as macro expansion is
1320 // not fixed. FIXME(#23480)
1321 codemap::mk_sp(span.lo, span.lo)
1326 let imported_filemaps = cdata.imported_filemaps(&codemap);
1328 // Optimize for the case that most spans within a translated item
1329 // originate from the same filemap.
1330 let last_filemap_index = last_filemap_index_hint.get();
1331 let last_filemap = &imported_filemaps[last_filemap_index];
1333 if span.lo >= last_filemap.original_start_pos &&
1334 span.lo <= last_filemap.original_end_pos &&
1335 span.hi >= last_filemap.original_start_pos &&
1336 span.hi <= last_filemap.original_end_pos {
1340 let mut b = imported_filemaps.len();
1343 let m = (a + b) / 2;
1344 if imported_filemaps[m].original_start_pos > span.lo {
1351 last_filemap_index_hint.set(a);
1352 &imported_filemaps[a]
1356 let lo = (span.lo - filemap.original_start_pos) +
1357 filemap.translated_filemap.start_pos;
1358 let hi = (span.hi - filemap.original_start_pos) +
1359 filemap.translated_filemap.start_pos;
1361 codemap::mk_sp(lo, hi)
1364 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1367 where F: FnMut(DefId),
1369 let item_doc = cdata.lookup_item(id);
1370 for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1371 if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1372 callback(item_def_id(impl_doc, cdata));
1377 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1379 mut callback: F) where
1382 // Do a reverse lookup beforehand to avoid touching the crate_num
1383 // hash map in the loop below.
1384 if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1385 let def_id_u64 = def_to_u64(crate_local_did);
1387 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1388 for trait_doc in reader::tagged_docs(impls_doc, tag_impls_trait) {
1389 let trait_def_id = reader::get_doc(trait_doc, tag_def_id);
1390 if reader::doc_as_u64(trait_def_id) != def_id_u64 {
1393 for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1394 callback(translated_def_id(cdata, impl_doc));
1400 pub fn get_trait_of_item(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt)
1402 let item_doc = cdata.lookup_item(id);
1403 let parent_item_id = match item_parent_item(cdata, item_doc) {
1404 None => return None,
1405 Some(item_id) => item_id,
1407 let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1408 match item_family(parent_item_doc) {
1409 Trait => Some(item_def_id(parent_item_doc, cdata)),
1410 Impl | DefaultImpl => {
1411 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1412 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1419 pub fn get_native_libraries(cdata: Cmd)
1420 -> Vec<(cstore::NativeLibraryKind, String)> {
1421 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1422 tag_native_libraries);
1423 reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1424 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1425 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1426 let kind: cstore::NativeLibraryKind =
1427 cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1428 let name = name_doc.as_str().to_string();
1433 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<DefIndex> {
1434 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1435 .map(|doc| DefIndex::from_u32(reader::doc_as_u32(doc)))
1438 pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where
1439 F: FnMut(ast::Name, Vec<ast::Attribute>, String) -> bool,
1441 let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1442 for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1443 let name = item_name(intr, macro_doc);
1444 let attrs = get_attributes(macro_doc);
1445 let body = reader::get_doc(macro_doc, tag_macro_def_body);
1446 if !f(name, attrs, body.as_str().to_string()) {
1452 pub fn get_dylib_dependency_formats(cdata: Cmd)
1453 -> Vec<(ast::CrateNum, LinkagePreference)>
1455 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1456 tag_dylib_dependency_formats);
1457 let mut result = Vec::new();
1459 debug!("found dylib deps: {}", formats.as_str_slice());
1460 for spec in formats.as_str_slice().split(',') {
1461 if spec.is_empty() { continue }
1462 let cnum = spec.split(':').nth(0).unwrap();
1463 let link = spec.split(':').nth(1).unwrap();
1464 let cnum: ast::CrateNum = cnum.parse().unwrap();
1465 let cnum = match cdata.cnum_map.borrow().get(&cnum) {
1467 None => panic!("didn't find a crate in the cnum_map")
1469 result.push((cnum, if link == "d" {
1470 LinkagePreference::RequireDynamic
1472 LinkagePreference::RequireStatic
1478 pub fn get_missing_lang_items(cdata: Cmd)
1479 -> Vec<lang_items::LangItem>
1481 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1482 reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1483 lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1487 pub fn get_method_arg_names(cdata: Cmd, id: DefIndex) -> Vec<String> {
1488 let method_doc = cdata.lookup_item(id);
1489 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1491 reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1492 name_doc.as_str_slice().to_string()
1499 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1500 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1502 reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1505 index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1510 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1511 let item_doc = cdata.lookup_item(id);
1512 match item_family(item_doc) {
1518 pub fn is_const_fn(cdata: Cmd, id: DefIndex) -> bool {
1519 let item_doc = cdata.lookup_item(id);
1520 match fn_constness(item_doc) {
1521 hir::Constness::Const => true,
1522 hir::Constness::NotConst => false,
1526 pub fn is_static(cdata: Cmd, id: DefIndex) -> bool {
1527 let item_doc = cdata.lookup_item(id);
1528 match item_family(item_doc) {
1529 ImmStatic | MutStatic => true,
1534 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1535 let item_doc = cdata.lookup_item(id);
1536 match item_family(item_doc) {
1542 fn doc_generics<'tcx>(base_doc: rbml::Doc,
1543 tcx: &ty::ctxt<'tcx>,
1546 -> ty::Generics<'tcx>
1548 let doc = reader::get_doc(base_doc, tag);
1550 let mut types = subst::VecPerParamSpace::empty();
1551 for p in reader::tagged_docs(doc, tag_type_param_def) {
1553 TyDecoder::with_doc(tcx, cdata.cnum, p,
1554 &mut |did| translate_def_id(cdata, did))
1555 .parse_type_param_def();
1556 types.push(bd.space, bd);
1559 let mut regions = subst::VecPerParamSpace::empty();
1560 for rp_doc in reader::tagged_docs(doc, tag_region_param_def) {
1561 let ident_str_doc = reader::get_doc(rp_doc,
1562 tag_region_param_def_ident);
1563 let name = item_name(&*token::get_ident_interner(), ident_str_doc);
1564 let def_id_doc = reader::get_doc(rp_doc,
1565 tag_region_param_def_def_id);
1566 let def_id = translated_def_id(cdata, def_id_doc);
1568 let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1569 let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as usize);
1571 let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1572 let index = reader::doc_as_u64(doc) as u32;
1574 let bounds = reader::tagged_docs(rp_doc, tag_items_data_region).map(|p| {
1575 TyDecoder::with_doc(tcx, cdata.cnum, p,
1576 &mut |did| translate_def_id(cdata, did))
1580 regions.push(space, ty::RegionParameterDef { name: name,
1587 ty::Generics { types: types, regions: regions }
1590 fn doc_predicate<'tcx>(cdata: Cmd,
1592 tcx: &ty::ctxt<'tcx>)
1593 -> ty::Predicate<'tcx>
1595 let predicate_pos = cdata.xref_index.lookup(
1596 cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1598 cdata.data(), cdata.cnum, predicate_pos, tcx,
1599 &mut |did| translate_def_id(cdata, did)
1603 fn doc_predicates<'tcx>(base_doc: rbml::Doc,
1604 tcx: &ty::ctxt<'tcx>,
1607 -> ty::GenericPredicates<'tcx>
1609 let doc = reader::get_doc(base_doc, tag);
1611 let mut predicates = subst::VecPerParamSpace::empty();
1612 for predicate_doc in reader::tagged_docs(doc, tag_type_predicate) {
1613 predicates.push(subst::TypeSpace,
1614 doc_predicate(cdata, predicate_doc, tcx));
1616 for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1617 predicates.push(subst::SelfSpace,
1618 doc_predicate(cdata, predicate_doc, tcx));
1620 for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1621 predicates.push(subst::FnSpace,
1622 doc_predicate(cdata, predicate_doc, tcx));
1625 ty::GenericPredicates { predicates: predicates }
1628 pub fn is_defaulted_trait(cdata: Cmd, trait_id: DefIndex) -> bool {
1629 let trait_doc = cdata.lookup_item(trait_id);
1630 assert!(item_family(trait_doc) == Family::Trait);
1631 let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1632 reader::doc_as_u8(defaulted_doc) != 0
1635 pub fn is_default_impl(cdata: Cmd, impl_id: DefIndex) -> bool {
1636 let impl_doc = cdata.lookup_item(impl_id);
1637 item_family(impl_doc) == Family::DefaultImpl
1640 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
1641 let crate_doc = rbml::Doc::new(metadata);
1642 let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1644 reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1645 let mut decoder = reader::Decoder::new(filemap_doc);
1646 Decodable::decode(&mut decoder).unwrap()
1650 pub fn is_extern_fn(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt) -> bool {
1651 let item_doc = match cdata.get_item(id) {
1653 None => return false,
1655 if let Fn = item_family(item_doc) {
1656 let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1657 generics.types.is_empty() && match ty.sty {
1658 ty::TyBareFn(_, fn_ty) => fn_ty.abi != abi::Rust,
1666 pub fn closure_kind(cdata: Cmd, closure_id: DefIndex) -> ty::ClosureKind {
1667 let closure_doc = cdata.lookup_item(closure_id);
1668 let closure_kind_doc = reader::get_doc(closure_doc, tag_items_closure_kind);
1669 let mut decoder = reader::Decoder::new(closure_kind_doc);
1670 ty::ClosureKind::decode(&mut decoder).unwrap()
1673 pub fn closure_ty<'tcx>(cdata: Cmd, closure_id: DefIndex, tcx: &ty::ctxt<'tcx>)
1674 -> ty::ClosureTy<'tcx> {
1675 let closure_doc = cdata.lookup_item(closure_id);
1676 let closure_ty_doc = reader::get_doc(closure_doc, tag_items_closure_ty);
1677 TyDecoder::with_doc(tcx, cdata.cnum, closure_ty_doc, &mut |did| translate_def_id(cdata, did))
1681 fn def_key(item_doc: rbml::Doc) -> hir_map::DefKey {
1682 match reader::maybe_get_doc(item_doc, tag_def_key) {
1683 Some(def_key_doc) => {
1684 let mut decoder = reader::Decoder::new(def_key_doc);
1685 hir_map::DefKey::decode(&mut decoder).unwrap()
1688 panic!("failed to find block with tag {:?} for item with family {:?}",
1690 item_family(item_doc))
1695 pub fn def_path(cdata: Cmd, id: DefIndex) -> hir_map::DefPath {
1696 debug!("def_path(id={:?})", id);
1697 hir_map::definitions::make_def_path(id, |parent| {
1698 debug!("def_path: parent={:?}", parent);
1699 let parent_doc = cdata.lookup_item(parent);