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, Ty, TypeFoldable, VariantKind};
39 use rustc::mir::visit::MutVisitor;
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, BytePos, NO_EXPANSION};
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(Clone, Copy, Debug, PartialEq)]
103 Variant(VariantKind), // V, v, w
107 Struct(VariantKind), // S, s, u
113 fn item_family(item: rbml::Doc) -> Family {
114 let fam = reader::get_doc(item, tag_items_data_item_family);
115 match reader::doc_as_u8(fam) as char {
126 'V' => Variant(VariantKind::Struct),
127 'v' => Variant(VariantKind::Tuple),
128 'w' => Variant(VariantKind::Unit),
132 'S' => Struct(VariantKind::Struct),
133 's' => Struct(VariantKind::Tuple),
134 'u' => Struct(VariantKind::Unit),
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 family_to_variant_kind<'tcx>(family: Family) -> Option<ty::VariantKind> {
270 Struct(VariantKind::Struct) | Variant(VariantKind::Struct) =>
271 Some(ty::VariantKind::Struct),
272 Struct(VariantKind::Tuple) | Variant(VariantKind::Tuple) =>
273 Some(ty::VariantKind::Tuple),
274 Struct(VariantKind::Unit) | Variant(VariantKind::Unit) =>
275 Some(ty::VariantKind::Unit),
280 fn item_to_def_like(cdata: Cmd, item: rbml::Doc, did: DefId) -> DefLike {
281 let fam = item_family(item);
284 // Check whether we have an associated const item.
285 match item_sort(item) {
286 Some('C') | Some('c') => {
287 DlDef(Def::AssociatedConst(did))
290 // Regular const item.
291 DlDef(Def::Const(did))
295 ImmStatic => DlDef(Def::Static(did, false)),
296 MutStatic => DlDef(Def::Static(did, true)),
297 Struct(..) => DlDef(Def::Struct(did)),
298 Fn => DlDef(Def::Fn(did)),
299 Method | StaticMethod => {
300 DlDef(Def::Method(did))
303 if item_sort(item) == Some('t') {
304 let trait_did = item_require_parent_item(cdata, item);
305 DlDef(Def::AssociatedTy(trait_did, did))
307 DlDef(Def::TyAlias(did))
310 Mod => DlDef(Def::Mod(did)),
311 ForeignMod => DlDef(Def::ForeignMod(did)),
313 let enum_did = item_require_parent_item(cdata, item);
314 DlDef(Def::Variant(enum_did, did))
316 Trait => DlDef(Def::Trait(did)),
317 Enum => DlDef(Def::Enum(did)),
318 Impl | DefaultImpl => DlImpl(did),
319 PublicField | InheritedField => DlField,
323 fn parse_unsafety(item_doc: rbml::Doc) -> hir::Unsafety {
324 let unsafety_doc = reader::get_doc(item_doc, tag_unsafety);
325 if reader::doc_as_u8(unsafety_doc) != 0 {
326 hir::Unsafety::Unsafe
328 hir::Unsafety::Normal
332 fn parse_paren_sugar(item_doc: rbml::Doc) -> bool {
333 let paren_sugar_doc = reader::get_doc(item_doc, tag_paren_sugar);
334 reader::doc_as_u8(paren_sugar_doc) != 0
337 fn parse_polarity(item_doc: rbml::Doc) -> hir::ImplPolarity {
338 let polarity_doc = reader::get_doc(item_doc, tag_polarity);
339 if reader::doc_as_u8(polarity_doc) != 0 {
340 hir::ImplPolarity::Negative
342 hir::ImplPolarity::Positive
346 fn parse_associated_type_names(item_doc: rbml::Doc) -> Vec<ast::Name> {
347 let names_doc = reader::get_doc(item_doc, tag_associated_type_names);
348 reader::tagged_docs(names_doc, tag_associated_type_name)
349 .map(|name_doc| token::intern(name_doc.as_str_slice()))
353 pub fn get_trait_def<'tcx>(cdata: Cmd,
355 tcx: &ty::ctxt<'tcx>) -> ty::TraitDef<'tcx>
357 let item_doc = cdata.lookup_item(item_id);
358 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
359 let unsafety = parse_unsafety(item_doc);
360 let associated_type_names = parse_associated_type_names(item_doc);
361 let paren_sugar = parse_paren_sugar(item_doc);
363 ty::TraitDef::new(unsafety,
366 item_trait_ref(item_doc, tcx, cdata),
367 associated_type_names)
370 pub fn get_adt_def<'tcx>(intr: &IdentInterner,
373 tcx: &ty::ctxt<'tcx>) -> ty::AdtDefMaster<'tcx>
375 fn expect_variant_kind<'tcx>(family: Family, tcx: &ty::ctxt<'tcx>) -> ty::VariantKind {
376 match family_to_variant_kind(family) {
378 _ => tcx.sess.bug(&format!("unexpected family: {:?}", family)),
381 fn get_enum_variants<'tcx>(intr: &IdentInterner,
384 tcx: &ty::ctxt<'tcx>) -> Vec<ty::VariantDefData<'tcx, 'tcx>> {
385 let mut disr_val = 0;
386 reader::tagged_docs(doc, tag_items_data_item_variant).map(|p| {
387 let did = translated_def_id(cdata, p);
388 let item = cdata.lookup_item(did.index);
390 if let Some(disr) = variant_disr_val(item) {
394 disr_val = disr_val.wrapping_add(1);
398 name: item_name(intr, item),
399 fields: get_variant_fields(intr, cdata, item, tcx),
401 kind: expect_variant_kind(item_family(item), tcx),
405 fn get_variant_fields<'tcx>(intr: &IdentInterner,
408 tcx: &ty::ctxt<'tcx>) -> Vec<ty::FieldDefData<'tcx, 'tcx>> {
409 reader::tagged_docs(doc, tag_item_field).map(|f| {
410 let ff = item_family(f);
412 PublicField | InheritedField => {},
413 _ => tcx.sess.bug(&format!("expected field, found {:?}", ff))
415 ty::FieldDefData::new(item_def_id(f, cdata),
417 struct_field_family_to_visibility(ff))
418 }).chain(reader::tagged_docs(doc, tag_item_unnamed_field).map(|f| {
419 let ff = item_family(f);
420 ty::FieldDefData::new(item_def_id(f, cdata),
421 special_idents::unnamed_field.name,
422 struct_field_family_to_visibility(ff))
425 fn get_struct_variant<'tcx>(intr: &IdentInterner,
429 tcx: &ty::ctxt<'tcx>) -> ty::VariantDefData<'tcx, 'tcx> {
432 name: item_name(intr, doc),
433 fields: get_variant_fields(intr, cdata, doc, tcx),
435 kind: expect_variant_kind(item_family(doc), tcx),
439 let doc = cdata.lookup_item(item_id);
440 let did = DefId { krate: cdata.cnum, index: item_id };
441 let (kind, variants) = match item_family(doc) {
444 get_enum_variants(intr, cdata, doc, tcx))
448 reader::maybe_get_doc(doc, tag_items_data_item_struct_ctor).
449 map_or(did, |ctor_doc| translated_def_id(cdata, ctor_doc));
450 (ty::AdtKind::Struct,
451 vec![get_struct_variant(intr, cdata, doc, ctor_did, tcx)])
454 &format!("get_adt_def called on a non-ADT {:?} - {:?}",
455 item_family(doc), did))
458 let adt = tcx.intern_adt_def(did, kind, variants);
460 // this needs to be done *after* the variant is interned,
461 // to support recursive structures
462 for variant in &adt.variants {
463 if variant.kind() == ty::VariantKind::Tuple &&
464 adt.adt_kind() == ty::AdtKind::Enum {
465 // tuple-like enum variant fields aren't real items - get the types
467 debug!("evaluating the ctor-type of {:?}",
469 let ctor_ty = get_type(cdata, variant.did.index, tcx).ty;
470 debug!("evaluating the ctor-type of {:?}.. {:?}",
473 let field_tys = match ctor_ty.sty {
474 ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
477 // tuple-struct constructors don't have escaping regions
478 assert!(!inputs.has_escaping_regions());
481 _ => tcx.sess.bug("tuple-variant ctor is not an ADT")
483 for (field, &ty) in variant.fields.iter().zip(field_tys.iter()) {
484 field.fulfill_ty(ty);
487 for field in &variant.fields {
488 debug!("evaluating the type of {:?}::{:?}", variant.name, field.name);
489 let ty = get_type(cdata, field.did.index, tcx).ty;
490 field.fulfill_ty(ty);
491 debug!("evaluating the type of {:?}::{:?}: {:?}",
492 variant.name, field.name, ty);
500 pub fn get_predicates<'tcx>(cdata: Cmd,
502 tcx: &ty::ctxt<'tcx>)
503 -> ty::GenericPredicates<'tcx>
505 let item_doc = cdata.lookup_item(item_id);
506 doc_predicates(item_doc, tcx, cdata, tag_item_generics)
509 pub fn get_super_predicates<'tcx>(cdata: Cmd,
511 tcx: &ty::ctxt<'tcx>)
512 -> ty::GenericPredicates<'tcx>
514 let item_doc = cdata.lookup_item(item_id);
515 doc_predicates(item_doc, tcx, cdata, tag_item_super_predicates)
518 pub fn get_type<'tcx>(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt<'tcx>)
519 -> ty::TypeScheme<'tcx>
521 let item_doc = cdata.lookup_item(id);
522 let t = item_type(DefId { krate: cdata.cnum, index: id }, item_doc, tcx,
524 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
531 pub fn get_stability(cdata: Cmd, id: DefIndex) -> Option<attr::Stability> {
532 let item = cdata.lookup_item(id);
533 reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
534 let mut decoder = reader::Decoder::new(doc);
535 Decodable::decode(&mut decoder).unwrap()
539 pub fn get_deprecation(cdata: Cmd, id: DefIndex) -> Option<attr::Deprecation> {
540 let item = cdata.lookup_item(id);
541 reader::maybe_get_doc(item, tag_items_data_item_deprecation).map(|doc| {
542 let mut decoder = reader::Decoder::new(doc);
543 Decodable::decode(&mut decoder).unwrap()
547 pub fn get_repr_attrs(cdata: Cmd, id: DefIndex) -> Vec<attr::ReprAttr> {
548 let item = cdata.lookup_item(id);
549 match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
550 let mut decoder = reader::Decoder::new(doc);
551 Decodable::decode(&mut decoder).unwrap()
553 Some(attrs) => attrs,
558 pub fn get_impl_polarity<'tcx>(cdata: Cmd,
560 -> Option<hir::ImplPolarity>
562 let item_doc = cdata.lookup_item(id);
563 let fam = item_family(item_doc);
566 Some(parse_polarity(item_doc))
572 pub fn get_custom_coerce_unsized_kind<'tcx>(
575 -> Option<ty::adjustment::CustomCoerceUnsized>
577 let item_doc = cdata.lookup_item(id);
578 reader::maybe_get_doc(item_doc, tag_impl_coerce_unsized_kind).map(|kind_doc| {
579 let mut decoder = reader::Decoder::new(kind_doc);
580 Decodable::decode(&mut decoder).unwrap()
584 pub fn get_impl_trait<'tcx>(cdata: Cmd,
586 tcx: &ty::ctxt<'tcx>)
587 -> Option<ty::TraitRef<'tcx>>
589 let item_doc = cdata.lookup_item(id);
590 let fam = item_family(item_doc);
592 Family::Impl | Family::DefaultImpl => {
593 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
594 doc_trait_ref(tp, tcx, cdata)
601 pub fn get_symbol(cdata: Cmd, id: DefIndex) -> String {
602 return item_symbol(cdata.lookup_item(id));
605 /// If you have a crate_metadata, call get_symbol instead
606 pub fn get_symbol_from_buf(data: &[u8], id: DefIndex) -> String {
607 let index = load_index(data);
608 let pos = index.lookup_item(data, id).unwrap();
609 let doc = reader::doc_at(data, pos as usize).unwrap().doc;
613 /// Iterates over the language items in the given crate.
614 pub fn each_lang_item<F>(cdata: Cmd, mut f: F) -> bool where
615 F: FnMut(DefIndex, usize) -> bool,
617 let root = rbml::Doc::new(cdata.data());
618 let lang_items = reader::get_doc(root, tag_lang_items);
619 reader::tagged_docs(lang_items, tag_lang_items_item).all(|item_doc| {
620 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
621 let id = reader::doc_as_u32(id_doc) as usize;
622 let index_doc = reader::get_doc(item_doc, tag_lang_items_item_index);
623 let index = DefIndex::from_u32(reader::doc_as_u32(index_doc));
629 fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
632 mut get_crate_data: G,
633 mut callback: F) where
634 F: FnMut(DefLike, ast::Name, hir::Visibility),
635 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
637 // Iterate over all children.
638 for child_info_doc in reader::tagged_docs(item_doc, tag_mod_child) {
639 let child_def_id = translated_def_id(cdata, child_info_doc);
641 // This item may be in yet another crate if it was the child of a
643 let crate_data = if child_def_id.krate == cdata.cnum {
646 Some(get_crate_data(child_def_id.krate))
648 let crate_data = match crate_data {
649 Some(ref cdata) => &**cdata,
654 match crate_data.get_item(child_def_id.index) {
656 Some(child_item_doc) => {
657 // Hand off the item to the callback.
658 let child_name = item_name(&intr, child_item_doc);
659 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
660 let visibility = item_visibility(child_item_doc);
661 callback(def_like, child_name, visibility);
666 // As a special case, iterate over all static methods of
667 // associated implementations too. This is a bit of a botch.
669 for inherent_impl_def_id_doc in reader::tagged_docs(item_doc,
670 tag_items_data_item_inherent_impl) {
671 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc, cdata);
672 if let Some(inherent_impl_doc) = cdata.get_item(inherent_impl_def_id.index) {
673 for impl_item_def_id_doc in reader::tagged_docs(inherent_impl_doc,
674 tag_item_impl_item) {
675 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
677 if let Some(impl_method_doc) = cdata.get_item(impl_item_def_id.index) {
678 if let StaticMethod = item_family(impl_method_doc) {
679 // Hand off the static method to the callback.
680 let static_method_name = item_name(&intr, impl_method_doc);
681 let static_method_def_like = item_to_def_like(cdata, impl_method_doc,
683 callback(static_method_def_like,
685 item_visibility(impl_method_doc));
692 for reexport_doc in reexports(item_doc) {
693 let def_id_doc = reader::get_doc(reexport_doc,
694 tag_items_data_item_reexport_def_id);
695 let child_def_id = translated_def_id(cdata, def_id_doc);
697 let name_doc = reader::get_doc(reexport_doc,
698 tag_items_data_item_reexport_name);
699 let name = name_doc.as_str_slice();
701 // This reexport may be in yet another crate.
702 let crate_data = if child_def_id.krate == cdata.cnum {
705 Some(get_crate_data(child_def_id.krate))
707 let crate_data = match crate_data {
708 Some(ref cdata) => &**cdata,
713 if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
714 // Hand off the item to the callback.
715 let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
716 // These items have a public visibility because they're part of
717 // a public re-export.
718 callback(def_like, token::intern(name), hir::Public);
723 /// Iterates over each child of the given item.
724 pub fn each_child_of_item<F, G>(intr: Rc<IdentInterner>,
729 F: FnMut(DefLike, ast::Name, hir::Visibility),
730 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
733 let item_doc = match cdata.get_item(id) {
735 Some(item_doc) => item_doc,
738 each_child_of_item_or_crate(intr,
745 /// Iterates over all the top-level crate items.
746 pub fn each_top_level_item_of_crate<F, G>(intr: Rc<IdentInterner>,
750 F: FnMut(DefLike, ast::Name, hir::Visibility),
751 G: FnMut(ast::CrateNum) -> Rc<crate_metadata>,
753 let root_doc = rbml::Doc::new(cdata.data());
754 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
755 let crate_items_doc = reader::get_doc(misc_info_doc,
756 tag_misc_info_crate_items);
758 each_child_of_item_or_crate(intr,
765 pub fn get_item_path(cdata: Cmd, id: DefIndex) -> Vec<hir_map::PathElem> {
766 item_path(cdata.lookup_item(id))
769 pub fn get_item_name(intr: &IdentInterner, cdata: Cmd, id: DefIndex) -> ast::Name {
770 item_name(intr, cdata.lookup_item(id))
773 pub type DecodeInlinedItem<'a> =
774 Box<for<'tcx> FnMut(Cmd,
776 Vec<hir_map::PathElem>, // parent_path
777 hir_map::DefPath, // parent_def_path
780 -> Result<&'tcx InlinedItem, (Vec<hir_map::PathElem>,
781 hir_map::DefPath)> + 'a>;
783 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd,
784 tcx: &ty::ctxt<'tcx>,
786 mut decode_inlined_item: DecodeInlinedItem)
788 debug!("Looking up item: {:?}", id);
789 let item_doc = cdata.lookup_item(id);
790 let item_did = item_def_id(item_doc, cdata);
792 let mut path = item_path(item_doc);
796 let parent_def_path = {
797 let mut def_path = def_path(cdata, id);
801 match decode_inlined_item(cdata,
807 Ok(ii) => FoundAst::Found(ii),
808 Err((mut parent_path, mut parent_def_path)) => {
809 match item_parent_item(cdata, item_doc) {
810 Some(parent_did) => {
811 // Remove the last element from the paths, since we are now
812 // trying to inline the parent.
814 parent_def_path.pop();
816 let parent_item = cdata.lookup_item(parent_did.index);
817 match decode_inlined_item(cdata,
823 Ok(ii) => FoundAst::FoundParent(parent_did, ii),
824 Err(_) => FoundAst::NotFound
827 None => FoundAst::NotFound
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,
842 tcx: &ty::ctxt<'tcx>,
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>,
957 tcx: &ty::ctxt<'tcx>)
958 -> 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 = item_require_parent_item(cdata, item_doc);
964 let container_doc = cdata.lookup_item(container_id.index);
965 let container = match item_family(container_doc) {
966 Trait => TraitContainer(container_id),
967 _ => ImplContainer(container_id),
970 let name = item_name(&intr, item_doc);
971 let vis = item_visibility(item_doc);
973 match item_sort(item_doc) {
974 sort @ Some('C') | sort @ Some('c') => {
975 let ty = doc_type(item_doc, tcx, cdata);
976 ty::ConstTraitItem(Rc::new(ty::AssociatedConst {
981 container: container,
982 has_value: sort == Some('C')
985 Some('r') | Some('p') => {
986 let generics = doc_generics(item_doc, tcx, cdata, tag_method_ty_generics);
987 let predicates = doc_predicates(item_doc, tcx, cdata, tag_method_ty_generics);
988 let ity = tcx.lookup_item_type(def_id).ty;
989 let fty = match ity.sty {
990 ty::TyBareFn(_, fty) => fty.clone(),
991 _ => tcx.sess.bug(&format!(
992 "the type {:?} of the method {:?} is not a function?",
995 let explicit_self = get_explicit_self(item_doc);
997 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
1007 let ty = maybe_doc_type(item_doc, tcx, cdata);
1008 ty::TypeTraitItem(Rc::new(ty::AssociatedType {
1013 container: container,
1016 _ => panic!("unknown impl/trait item sort"),
1020 pub fn get_trait_item_def_ids(cdata: Cmd, id: DefIndex)
1021 -> Vec<ty::ImplOrTraitItemId> {
1022 let item = cdata.lookup_item(id);
1023 reader::tagged_docs(item, tag_item_trait_item).map(|mth| {
1024 let def_id = item_def_id(mth, cdata);
1025 match item_sort(mth) {
1026 Some('C') | Some('c') => ty::ConstTraitItemId(def_id),
1027 Some('r') | Some('p') => ty::MethodTraitItemId(def_id),
1028 Some('t') => ty::TypeTraitItemId(def_id),
1029 _ => panic!("unknown trait item sort"),
1034 pub fn get_item_variances(cdata: Cmd, id: DefIndex) -> ty::ItemVariances {
1035 let item_doc = cdata.lookup_item(id);
1036 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
1037 let mut decoder = reader::Decoder::new(variance_doc);
1038 Decodable::decode(&mut decoder).unwrap()
1041 pub fn get_provided_trait_methods<'tcx>(intr: Rc<IdentInterner>,
1044 tcx: &ty::ctxt<'tcx>)
1045 -> Vec<Rc<ty::Method<'tcx>>> {
1046 let item = cdata.lookup_item(id);
1048 reader::tagged_docs(item, tag_item_trait_item).filter_map(|mth_id| {
1049 let did = item_def_id(mth_id, cdata);
1050 let mth = cdata.lookup_item(did.index);
1052 if item_sort(mth) == Some('p') {
1053 let trait_item = get_impl_or_trait_item(intr.clone(),
1057 if let ty::MethodTraitItem(ref method) = trait_item {
1058 Some((*method).clone())
1068 pub fn get_associated_consts<'tcx>(intr: Rc<IdentInterner>,
1071 tcx: &ty::ctxt<'tcx>)
1072 -> Vec<Rc<ty::AssociatedConst<'tcx>>> {
1073 let item = cdata.lookup_item(id);
1075 [tag_item_trait_item, tag_item_impl_item].iter().flat_map(|&tag| {
1076 reader::tagged_docs(item, tag).filter_map(|ac_id| {
1077 let did = item_def_id(ac_id, cdata);
1078 let ac_doc = cdata.lookup_item(did.index);
1080 match item_sort(ac_doc) {
1081 Some('C') | Some('c') => {
1082 let trait_item = get_impl_or_trait_item(intr.clone(),
1086 if let ty::ConstTraitItem(ref ac) = trait_item {
1098 pub fn get_variant_kind(cdata: Cmd, node_id: DefIndex) -> Option<VariantKind>
1100 let item = cdata.lookup_item(node_id);
1101 family_to_variant_kind(item_family(item))
1104 pub fn get_struct_ctor_def_id(cdata: Cmd, node_id: DefIndex) -> Option<DefId>
1106 let item = cdata.lookup_item(node_id);
1107 reader::maybe_get_doc(item, tag_items_data_item_struct_ctor).
1108 map(|ctor_doc| translated_def_id(cdata, ctor_doc))
1111 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
1112 /// the actual type definition, otherwise, return None
1113 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
1117 let item = cdata.lookup_item(node_id);
1118 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor).next().map(|_| {
1119 item_require_parent_item(cdata, item)
1123 pub fn get_item_attrs(cdata: Cmd,
1124 orig_node_id: DefIndex)
1125 -> Vec<ast::Attribute> {
1126 // The attributes for a tuple struct are attached to the definition, not the ctor;
1127 // we assume that someone passing in a tuple struct ctor is actually wanting to
1128 // look at the definition
1129 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
1130 let node_id = node_id.map(|x| x.index).unwrap_or(orig_node_id);
1131 let item = cdata.lookup_item(node_id);
1132 get_attributes(item)
1135 pub fn get_struct_field_attrs(cdata: Cmd) -> FnvHashMap<DefId, Vec<ast::Attribute>> {
1136 let data = rbml::Doc::new(cdata.data());
1137 let fields = reader::get_doc(data, tag_struct_fields);
1138 reader::tagged_docs(fields, tag_struct_field).map(|field| {
1139 let def_id = translated_def_id(cdata, reader::get_doc(field, tag_def_id));
1140 let attrs = get_attributes(field);
1145 fn struct_field_family_to_visibility(family: Family) -> hir::Visibility {
1147 PublicField => hir::Public,
1148 InheritedField => hir::Inherited,
1153 pub fn get_struct_field_names(intr: &IdentInterner, cdata: Cmd, id: DefIndex)
1155 let item = cdata.lookup_item(id);
1156 reader::tagged_docs(item, tag_item_field).map(|an_item| {
1157 item_name(intr, an_item)
1158 }).chain(reader::tagged_docs(item, tag_item_unnamed_field).map(|_| {
1159 special_idents::unnamed_field.name
1163 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1164 reader::tagged_docs(md, tag_meta_item_word).map(|meta_item_doc| {
1165 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1166 let n = token::intern_and_get_ident(nd.as_str_slice());
1167 attr::mk_word_item(n)
1168 }).chain(reader::tagged_docs(md, tag_meta_item_name_value).map(|meta_item_doc| {
1169 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1170 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1171 let n = token::intern_and_get_ident(nd.as_str_slice());
1172 let v = token::intern_and_get_ident(vd.as_str_slice());
1173 // FIXME (#623): Should be able to decode MetaItemKind::NameValue variants,
1174 // but currently the encoder just drops them
1175 attr::mk_name_value_item_str(n, v)
1176 })).chain(reader::tagged_docs(md, tag_meta_item_list).map(|meta_item_doc| {
1177 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1178 let n = token::intern_and_get_ident(nd.as_str_slice());
1179 let subitems = get_meta_items(meta_item_doc);
1180 attr::mk_list_item(n, subitems)
1184 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1185 match reader::maybe_get_doc(md, tag_attributes) {
1187 reader::tagged_docs(attrs_d, tag_attribute).map(|attr_doc| {
1188 let is_sugared_doc = reader::doc_as_u8(
1189 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1191 let meta_items = get_meta_items(attr_doc);
1192 // Currently it's only possible to have a single meta item on
1194 assert_eq!(meta_items.len(), 1);
1195 let meta_item = meta_items.into_iter().nth(0).unwrap();
1197 node: ast::Attribute_ {
1198 id: attr::mk_attr_id(),
1199 style: ast::AttrStyle::Outer,
1201 is_sugared_doc: is_sugared_doc,
1203 span: codemap::DUMMY_SP
1211 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1212 out: &mut io::Write) -> io::Result<()> {
1213 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1215 let r = get_attributes(md);
1217 try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1223 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1224 get_attributes(rbml::Doc::new(data))
1228 pub struct CrateDep {
1229 pub cnum: ast::CrateNum,
1232 pub explicitly_linked: bool,
1235 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1236 let cratedoc = rbml::Doc::new(data);
1237 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1239 fn docstr(doc: rbml::Doc, tag_: usize) -> String {
1240 let d = reader::get_doc(doc, tag_);
1241 d.as_str_slice().to_string()
1244 reader::tagged_docs(depsdoc, tag_crate_dep).enumerate().map(|(crate_num, depdoc)| {
1245 let name = docstr(depdoc, tag_crate_dep_crate_name);
1246 let hash = Svh::new(&docstr(depdoc, tag_crate_dep_hash));
1247 let doc = reader::get_doc(depdoc, tag_crate_dep_explicitly_linked);
1248 let explicitly_linked = reader::doc_as_u8(doc) != 0;
1250 cnum: crate_num as u32 + 1,
1253 explicitly_linked: explicitly_linked,
1258 fn list_crate_deps(data: &[u8], out: &mut io::Write) -> io::Result<()> {
1259 try!(write!(out, "=External Dependencies=\n"));
1260 for dep in &get_crate_deps(data) {
1261 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1263 try!(write!(out, "\n"));
1267 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1268 let cratedoc = rbml::Doc::new(data);
1269 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1270 Svh::new(doc.as_str_slice())
1274 pub fn get_crate_hash(data: &[u8]) -> Svh {
1275 let cratedoc = rbml::Doc::new(data);
1276 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1277 Svh::new(hashdoc.as_str_slice())
1280 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1281 let cratedoc = rbml::Doc::new(data);
1282 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1283 doc.as_str_slice().to_string()
1287 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1288 let cratedoc = rbml::Doc::new(data);
1289 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1290 triple_doc.map(|s| s.as_str().to_string())
1293 pub fn get_crate_name(data: &[u8]) -> String {
1294 maybe_get_crate_name(data).expect("no crate name in crate")
1297 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Write) -> io::Result<()> {
1298 let hash = get_crate_hash(bytes);
1299 let md = rbml::Doc::new(bytes);
1300 try!(list_crate_attributes(md, &hash, out));
1301 list_crate_deps(bytes, out)
1304 // Translates a def_id from an external crate to a def_id for the current
1305 // compilation environment. We use this when trying to load types from
1306 // external crates - if those types further refer to types in other crates
1307 // then we must translate the crate number from that encoded in the external
1308 // crate to the correct local crate number.
1309 pub fn translate_def_id(cdata: Cmd, did: DefId) -> DefId {
1311 return DefId { krate: cdata.cnum, index: did.index };
1314 match cdata.cnum_map.borrow().get(&did.krate) {
1321 None => panic!("didn't find a crate in the cnum_map")
1325 // Translate a DefId from the current compilation environment to a DefId
1326 // for an external crate.
1327 fn reverse_translate_def_id(cdata: Cmd, did: DefId) -> Option<DefId> {
1328 if did.krate == cdata.cnum {
1329 return Some(DefId { krate: LOCAL_CRATE, index: did.index });
1332 for (&local, &global) in cdata.cnum_map.borrow().iter() {
1333 if global == did.krate {
1334 return Some(DefId { krate: local, index: did.index });
1341 /// Translates a `Span` from an extern crate to the corresponding `Span`
1342 /// within the local crate's codemap.
1343 pub fn translate_span(cdata: Cmd,
1344 codemap: &codemap::CodeMap,
1345 last_filemap_index_hint: &Cell<usize>,
1346 span: codemap::Span)
1348 let span = if span.lo > span.hi {
1349 // Currently macro expansion sometimes produces invalid Span values
1350 // where lo > hi. In order not to crash the compiler when trying to
1351 // translate these values, let's transform them into something we
1352 // can handle (and which will produce useful debug locations at
1353 // least some of the time).
1354 // This workaround is only necessary as long as macro expansion is
1355 // not fixed. FIXME(#23480)
1356 codemap::mk_sp(span.lo, span.lo)
1361 let imported_filemaps = cdata.imported_filemaps(&codemap);
1363 // Optimize for the case that most spans within a translated item
1364 // originate from the same filemap.
1365 let last_filemap_index = last_filemap_index_hint.get();
1366 let last_filemap = &imported_filemaps[last_filemap_index];
1368 if span.lo >= last_filemap.original_start_pos &&
1369 span.lo <= last_filemap.original_end_pos &&
1370 span.hi >= last_filemap.original_start_pos &&
1371 span.hi <= last_filemap.original_end_pos {
1375 let mut b = imported_filemaps.len();
1378 let m = (a + b) / 2;
1379 if imported_filemaps[m].original_start_pos > span.lo {
1386 last_filemap_index_hint.set(a);
1387 &imported_filemaps[a]
1391 let lo = (span.lo - filemap.original_start_pos) +
1392 filemap.translated_filemap.start_pos;
1393 let hi = (span.hi - filemap.original_start_pos) +
1394 filemap.translated_filemap.start_pos;
1396 codemap::mk_sp(lo, hi)
1399 pub fn each_inherent_implementation_for_type<F>(cdata: Cmd,
1402 where F: FnMut(DefId),
1404 let item_doc = cdata.lookup_item(id);
1405 for impl_doc in reader::tagged_docs(item_doc, tag_items_data_item_inherent_impl) {
1406 if reader::maybe_get_doc(impl_doc, tag_item_trait_ref).is_none() {
1407 callback(item_def_id(impl_doc, cdata));
1412 pub fn each_implementation_for_trait<F>(cdata: Cmd,
1414 mut callback: F) where
1417 // Do a reverse lookup beforehand to avoid touching the crate_num
1418 // hash map in the loop below.
1419 if let Some(crate_local_did) = reverse_translate_def_id(cdata, def_id) {
1420 let def_id_u64 = def_to_u64(crate_local_did);
1422 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1423 for trait_doc in reader::tagged_docs(impls_doc, tag_impls_trait) {
1424 let trait_def_id = reader::get_doc(trait_doc, tag_def_id);
1425 if reader::doc_as_u64(trait_def_id) != def_id_u64 {
1428 for impl_doc in reader::tagged_docs(trait_doc, tag_impls_trait_impl) {
1429 callback(translated_def_id(cdata, impl_doc));
1435 pub fn get_trait_of_item(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt)
1437 let item_doc = cdata.lookup_item(id);
1438 let parent_item_id = match item_parent_item(cdata, item_doc) {
1439 None => return None,
1440 Some(item_id) => item_id,
1442 let parent_item_doc = cdata.lookup_item(parent_item_id.index);
1443 match item_family(parent_item_doc) {
1444 Trait => Some(item_def_id(parent_item_doc, cdata)),
1445 Impl | DefaultImpl => {
1446 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1447 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1454 pub fn get_native_libraries(cdata: Cmd)
1455 -> Vec<(cstore::NativeLibraryKind, String)> {
1456 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1457 tag_native_libraries);
1458 reader::tagged_docs(libraries, tag_native_libraries_lib).map(|lib_doc| {
1459 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1460 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1461 let kind: cstore::NativeLibraryKind =
1462 cstore::NativeLibraryKind::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1463 let name = name_doc.as_str().to_string();
1468 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<DefIndex> {
1469 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1470 .map(|doc| DefIndex::from_u32(reader::doc_as_u32(doc)))
1473 pub fn each_exported_macro<F>(data: &[u8], intr: &IdentInterner, mut f: F) where
1474 F: FnMut(ast::Name, Vec<ast::Attribute>, Span, String) -> bool,
1476 let macros = reader::get_doc(rbml::Doc::new(data), tag_macro_defs);
1477 for macro_doc in reader::tagged_docs(macros, tag_macro_def) {
1478 let name = item_name(intr, macro_doc);
1479 let attrs = get_attributes(macro_doc);
1480 let span = get_macro_span(macro_doc);
1481 let body = reader::get_doc(macro_doc, tag_macro_def_body);
1482 if !f(name, attrs, span, body.as_str().to_string()) {
1488 pub fn get_macro_span(doc: rbml::Doc) -> Span {
1489 let lo_doc = reader::get_doc(doc, tag_macro_def_span_lo);
1490 let lo = BytePos(reader::doc_as_u32(lo_doc));
1491 let hi_doc = reader::get_doc(doc, tag_macro_def_span_hi);
1492 let hi = BytePos(reader::doc_as_u32(hi_doc));
1493 return Span { lo: lo, hi: hi, expn_id: NO_EXPANSION };
1496 pub fn get_dylib_dependency_formats(cdata: Cmd)
1497 -> Vec<(ast::CrateNum, LinkagePreference)>
1499 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1500 tag_dylib_dependency_formats);
1501 let mut result = Vec::new();
1503 debug!("found dylib deps: {}", formats.as_str_slice());
1504 for spec in formats.as_str_slice().split(',') {
1505 if spec.is_empty() { continue }
1506 let cnum = spec.split(':').nth(0).unwrap();
1507 let link = spec.split(':').nth(1).unwrap();
1508 let cnum: ast::CrateNum = cnum.parse().unwrap();
1509 let cnum = match cdata.cnum_map.borrow().get(&cnum) {
1511 None => panic!("didn't find a crate in the cnum_map")
1513 result.push((cnum, if link == "d" {
1514 LinkagePreference::RequireDynamic
1516 LinkagePreference::RequireStatic
1522 pub fn get_missing_lang_items(cdata: Cmd)
1523 -> Vec<lang_items::LangItem>
1525 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1526 reader::tagged_docs(items, tag_lang_items_missing).map(|missing_docs| {
1527 lang_items::LangItem::from_u32(reader::doc_as_u32(missing_docs)).unwrap()
1531 pub fn get_method_arg_names(cdata: Cmd, id: DefIndex) -> Vec<String> {
1532 let method_doc = cdata.lookup_item(id);
1533 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1535 reader::tagged_docs(args_doc, tag_method_argument_name).map(|name_doc| {
1536 name_doc.as_str_slice().to_string()
1543 pub fn get_reachable_ids(cdata: Cmd) -> Vec<DefId> {
1544 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1546 reader::tagged_docs(items, tag_reachable_id).map(|doc| {
1549 index: DefIndex::from_u32(reader::doc_as_u32(doc)),
1554 pub fn is_typedef(cdata: Cmd, id: DefIndex) -> bool {
1555 let item_doc = cdata.lookup_item(id);
1556 match item_family(item_doc) {
1562 pub fn is_const_fn(cdata: Cmd, id: DefIndex) -> bool {
1563 let item_doc = cdata.lookup_item(id);
1564 match fn_constness(item_doc) {
1565 hir::Constness::Const => true,
1566 hir::Constness::NotConst => false,
1570 pub fn is_extern_item(cdata: Cmd, id: DefIndex, tcx: &ty::ctxt) -> bool {
1571 let item_doc = match cdata.get_item(id) {
1573 None => return false,
1575 let applicable = match item_family(item_doc) {
1576 ImmStatic | MutStatic => true,
1578 let ty::TypeScheme { generics, ty } = get_type(cdata, id, tcx);
1579 let no_generics = generics.types.is_empty();
1581 ty::TyBareFn(_, fn_ty) if fn_ty.abi != Abi::Rust => return no_generics,
1589 attr::contains_extern_indicator(tcx.sess.diagnostic(),
1590 &get_attributes(item_doc))
1596 pub fn is_impl(cdata: Cmd, id: DefIndex) -> bool {
1597 let item_doc = cdata.lookup_item(id);
1598 match item_family(item_doc) {
1604 fn doc_generics<'tcx>(base_doc: rbml::Doc,
1605 tcx: &ty::ctxt<'tcx>,
1608 -> ty::Generics<'tcx>
1610 let doc = reader::get_doc(base_doc, tag);
1612 let mut types = subst::VecPerParamSpace::empty();
1613 for p in reader::tagged_docs(doc, tag_type_param_def) {
1615 TyDecoder::with_doc(tcx, cdata.cnum, p,
1616 &mut |did| translate_def_id(cdata, did))
1617 .parse_type_param_def();
1618 types.push(bd.space, bd);
1621 let mut regions = subst::VecPerParamSpace::empty();
1622 for rp_doc in reader::tagged_docs(doc, tag_region_param_def) {
1623 let ident_str_doc = reader::get_doc(rp_doc,
1624 tag_region_param_def_ident);
1625 let name = item_name(&token::get_ident_interner(), ident_str_doc);
1626 let def_id_doc = reader::get_doc(rp_doc,
1627 tag_region_param_def_def_id);
1628 let def_id = translated_def_id(cdata, def_id_doc);
1630 let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1631 let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as usize);
1633 let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1634 let index = reader::doc_as_u64(doc) as u32;
1636 let bounds = reader::tagged_docs(rp_doc, tag_items_data_region).map(|p| {
1637 TyDecoder::with_doc(tcx, cdata.cnum, p,
1638 &mut |did| translate_def_id(cdata, did))
1642 regions.push(space, ty::RegionParameterDef { name: name,
1649 ty::Generics { types: types, regions: regions }
1652 fn doc_predicate<'tcx>(cdata: Cmd,
1654 tcx: &ty::ctxt<'tcx>)
1655 -> ty::Predicate<'tcx>
1657 let predicate_pos = cdata.xref_index.lookup(
1658 cdata.data(), reader::doc_as_u32(doc)).unwrap() as usize;
1660 cdata.data(), cdata.cnum, predicate_pos, tcx,
1661 &mut |did| translate_def_id(cdata, did)
1665 fn doc_predicates<'tcx>(base_doc: rbml::Doc,
1666 tcx: &ty::ctxt<'tcx>,
1669 -> ty::GenericPredicates<'tcx>
1671 let doc = reader::get_doc(base_doc, tag);
1673 let mut predicates = subst::VecPerParamSpace::empty();
1674 for predicate_doc in reader::tagged_docs(doc, tag_type_predicate) {
1675 predicates.push(subst::TypeSpace,
1676 doc_predicate(cdata, predicate_doc, tcx));
1678 for predicate_doc in reader::tagged_docs(doc, tag_self_predicate) {
1679 predicates.push(subst::SelfSpace,
1680 doc_predicate(cdata, predicate_doc, tcx));
1682 for predicate_doc in reader::tagged_docs(doc, tag_fn_predicate) {
1683 predicates.push(subst::FnSpace,
1684 doc_predicate(cdata, predicate_doc, tcx));
1687 ty::GenericPredicates { predicates: predicates }
1690 pub fn is_defaulted_trait(cdata: Cmd, trait_id: DefIndex) -> bool {
1691 let trait_doc = cdata.lookup_item(trait_id);
1692 assert!(item_family(trait_doc) == Family::Trait);
1693 let defaulted_doc = reader::get_doc(trait_doc, tag_defaulted_trait);
1694 reader::doc_as_u8(defaulted_doc) != 0
1697 pub fn is_default_impl(cdata: Cmd, impl_id: DefIndex) -> bool {
1698 let impl_doc = cdata.lookup_item(impl_id);
1699 item_family(impl_doc) == Family::DefaultImpl
1702 pub fn get_imported_filemaps(metadata: &[u8]) -> Vec<codemap::FileMap> {
1703 let crate_doc = rbml::Doc::new(metadata);
1704 let cm_doc = reader::get_doc(crate_doc, tag_codemap);
1706 reader::tagged_docs(cm_doc, tag_codemap_filemap).map(|filemap_doc| {
1707 let mut decoder = reader::Decoder::new(filemap_doc);
1708 decoder.read_opaque(|opaque_decoder, _| {
1709 Decodable::decode(opaque_decoder)
1714 pub fn closure_kind(cdata: Cmd, closure_id: DefIndex) -> ty::ClosureKind {
1715 let closure_doc = cdata.lookup_item(closure_id);
1716 let closure_kind_doc = reader::get_doc(closure_doc, tag_items_closure_kind);
1717 let mut decoder = reader::Decoder::new(closure_kind_doc);
1718 ty::ClosureKind::decode(&mut decoder).unwrap()
1721 pub fn closure_ty<'tcx>(cdata: Cmd, closure_id: DefIndex, tcx: &ty::ctxt<'tcx>)
1722 -> ty::ClosureTy<'tcx> {
1723 let closure_doc = cdata.lookup_item(closure_id);
1724 let closure_ty_doc = reader::get_doc(closure_doc, tag_items_closure_ty);
1725 TyDecoder::with_doc(tcx, cdata.cnum, closure_ty_doc, &mut |did| translate_def_id(cdata, did))
1729 fn def_key(item_doc: rbml::Doc) -> hir_map::DefKey {
1730 match reader::maybe_get_doc(item_doc, tag_def_key) {
1731 Some(def_key_doc) => {
1732 let mut decoder = reader::Decoder::new(def_key_doc);
1733 hir_map::DefKey::decode(&mut decoder).unwrap()
1736 panic!("failed to find block with tag {:?} for item with family {:?}",
1738 item_family(item_doc))
1743 pub fn def_path(cdata: Cmd, id: DefIndex) -> hir_map::DefPath {
1744 debug!("def_path(id={:?})", id);
1745 hir_map::definitions::make_def_path(id, |parent| {
1746 debug!("def_path: parent={:?}", parent);
1747 let parent_doc = cdata.lookup_item(parent);