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)]
16 use metadata::cstore::crate_metadata;
17 use metadata::common::*;
18 use metadata::csearch::StaticMethodInfo;
19 use metadata::csearch;
21 use metadata::tydecode::{parse_ty_data, parse_region_data, parse_def_id,
22 parse_type_param_def_data, parse_bounds_data,
23 parse_bare_fn_ty_data, parse_trait_ref_data};
25 use middle::lang_items;
26 use middle::resolve::{TraitItemKind, TypeTraitItemKind};
28 use middle::ty::{ImplContainer, TraitContainer};
31 use middle::astencode::vtable_decoder_helpers;
35 use std::io::extensions::u64_from_be_bytes;
37 use std::collections::hashmap::HashMap;
42 use serialize::Decodable;
45 use syntax::parse::token::{IdentInterner, special_idents};
46 use syntax::parse::token;
47 use syntax::print::pprust;
52 pub type Cmd<'a> = &'a crate_metadata;
54 // A function that takes a def_id relative to the crate being searched and
55 // returns a def_id relative to the compilation environment, i.e. if we hit a
56 // def_id for an item defined in another crate, somebody needs to figure out
57 // what crate that's in and give us a def_id that makes sense for the current
60 fn lookup_hash<'a>(d: rbml::Doc<'a>, eq_fn: |&[u8]| -> bool,
61 hash: u64) -> Option<rbml::Doc<'a>> {
62 let index = reader::get_doc(d, tag_index);
63 let table = reader::get_doc(index, tag_index_table);
64 let hash_pos = table.start + (hash % 256 * 4) as uint;
65 let pos = u64_from_be_bytes(d.data, hash_pos, 4) as uint;
66 let tagged_doc = reader::doc_at(d.data, pos).unwrap();
68 let belt = tag_index_buckets_bucket_elt;
71 reader::tagged_docs(tagged_doc.doc, belt, |elt| {
72 let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint;
73 if eq_fn(elt.data.slice(elt.start + 4, elt.end)) {
74 ret = Some(reader::doc_at(d.data, pos).unwrap().doc);
83 pub fn maybe_find_item<'a>(item_id: ast::NodeId,
84 items: rbml::Doc<'a>) -> Option<rbml::Doc<'a>> {
85 fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
86 return u64_from_be_bytes(
87 bytes.slice(0u, 4u), 0u, 4u) as ast::NodeId
91 |a| eq_item(a, item_id),
92 hash::hash(&(item_id as i64)))
95 fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> {
96 match maybe_find_item(item_id, items) {
97 None => fail!("lookup_item: id not found: {}", item_id),
102 // Looks up an item in the given metadata and returns an rbml doc pointing
104 fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> rbml::Doc<'a> {
105 let items = reader::get_doc(rbml::Doc::new(data), tag_items);
106 find_item(item_id, items)
109 #[deriving(PartialEq)]
117 UnsafeStaticMethod, // U
132 fn item_family(item: rbml::Doc) -> Family {
133 let fam = reader::get_doc(item, tag_items_data_item_family);
134 match reader::doc_as_u8(fam) as char {
141 'U' => UnsafeStaticMethod,
148 'V' => StructVariant,
153 'N' => InheritedField,
154 c => fail!("unexpected family char: {}", c)
158 fn item_visibility(item: rbml::Doc) -> ast::Visibility {
159 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
161 Some(visibility_doc) => {
162 match reader::doc_as_u8(visibility_doc) as char {
164 'i' => ast::Inherited,
165 _ => fail!("unknown visibility character")
171 fn item_sort(item: rbml::Doc) -> char {
172 // NB(pcwalton): The default of 'r' here is relied upon in
173 // `is_associated_type` below.
175 reader::tagged_docs(item, tag_item_trait_item_sort, |doc| {
176 ret = doc.as_str_slice().as_bytes()[0] as char;
182 fn item_symbol(item: rbml::Doc) -> String {
183 reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
186 fn item_parent_item(d: rbml::Doc) -> Option<ast::DefId> {
188 reader::tagged_docs(d, tag_items_data_parent_item, |did| {
189 ret = Some(reader::with_doc_data(did, parse_def_id));
195 fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
196 d: rbml::Doc) -> ast::DefId {
197 let trait_did = item_parent_item(d).expect("item without parent");
198 ast::DefId { krate: cnum, node: trait_did.node }
201 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> ast::DefId {
202 let tagdoc = reader::get_doc(d, tag_def_id);
203 return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
206 fn get_provided_source(d: rbml::Doc, cdata: Cmd) -> Option<ast::DefId> {
207 reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
208 translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
212 fn each_reexport(d: rbml::Doc, f: |rbml::Doc| -> bool) -> bool {
213 reader::tagged_docs(d, tag_items_data_item_reexport, f)
216 fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
217 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
218 reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
222 fn doc_type(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
223 let tp = reader::get_doc(doc, tag_items_data_item_type);
224 parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
225 |_, did| translate_def_id(cdata, did))
228 fn doc_method_fty(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
229 let tp = reader::get_doc(doc, tag_item_method_fty);
230 parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
231 |_, did| translate_def_id(cdata, did))
234 pub fn item_type(_item_id: ast::DefId, item: rbml::Doc,
235 tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
236 doc_type(item, tcx, cdata)
239 fn doc_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
240 parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
241 |_, did| translate_def_id(cdata, did))
244 fn item_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
245 let tp = reader::get_doc(doc, tag_item_trait_ref);
246 doc_trait_ref(tp, tcx, cdata)
249 fn doc_bounds(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::ParamBounds {
250 parse_bounds_data(doc.data, cdata.cnum, doc.start, tcx,
251 |_, did| translate_def_id(cdata, did))
254 fn trait_def_bounds(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::ParamBounds {
255 let d = reader::get_doc(doc, tag_trait_def_bounds);
256 doc_bounds(d, tcx, cdata)
259 fn enum_variant_ids(item: rbml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
260 let mut ids: Vec<ast::DefId> = Vec::new();
261 let v = tag_items_data_item_variant;
262 reader::tagged_docs(item, v, |p| {
263 let ext = reader::with_doc_data(p, parse_def_id);
264 ids.push(ast::DefId { krate: cdata.cnum, node: ext.node });
270 fn item_path(item_doc: rbml::Doc) -> Vec<ast_map::PathElem> {
271 let path_doc = reader::get_doc(item_doc, tag_path);
273 let len_doc = reader::get_doc(path_doc, tag_path_len);
274 let len = reader::doc_as_u32(len_doc) as uint;
276 let mut result = Vec::with_capacity(len);
277 reader::docs(path_doc, |tag, elt_doc| {
278 if tag == tag_path_elem_mod {
279 let s = elt_doc.as_str_slice();
280 result.push(ast_map::PathMod(token::intern(s)));
281 } else if tag == tag_path_elem_name {
282 let s = elt_doc.as_str_slice();
283 result.push(ast_map::PathName(token::intern(s)));
285 // ignore tag_path_len element
293 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Ident {
294 let name = reader::get_doc(item, tag_paths_data_name);
295 let string = name.as_str_slice();
296 match intr.find_equiv(&string) {
297 None => token::str_to_ident(string),
298 Some(val) => ast::Ident::new(val),
302 fn item_to_def_like(item: rbml::Doc, did: ast::DefId, cnum: ast::CrateNum)
304 let fam = item_family(item);
306 ImmStatic => DlDef(def::DefStatic(did, false)),
307 MutStatic => DlDef(def::DefStatic(did, true)),
308 Struct => DlDef(def::DefStruct(did)),
309 UnsafeFn => DlDef(def::DefFn(did, ast::UnsafeFn, false)),
310 Fn => DlDef(def::DefFn(did, ast::NormalFn, false)),
311 CtorFn => DlDef(def::DefFn(did, ast::NormalFn, true)),
312 StaticMethod | UnsafeStaticMethod => {
313 let fn_style = if fam == UnsafeStaticMethod {
318 // def_static_method carries an optional field of its enclosing
319 // trait or enclosing impl (if this is an inherent static method).
320 // So we need to detect whether this is in a trait or not, which
321 // we do through the mildly hacky way of checking whether there is
322 // a trait_parent_sort.
323 let provenance = if reader::maybe_get_doc(
324 item, tag_item_trait_parent_sort).is_some() {
325 def::FromTrait(item_reqd_and_translated_parent_item(cnum,
328 def::FromImpl(item_reqd_and_translated_parent_item(cnum,
331 DlDef(def::DefStaticMethod(did, provenance, fn_style))
333 Type | ForeignType => DlDef(def::DefTy(did, false)),
334 Mod => DlDef(def::DefMod(did)),
335 ForeignMod => DlDef(def::DefForeignMod(did)),
337 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
338 DlDef(def::DefVariant(enum_did, did, true))
341 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
342 DlDef(def::DefVariant(enum_did, did, false))
344 Trait => DlDef(def::DefTrait(did)),
345 Enum => DlDef(def::DefTy(did, true)),
347 PublicField | InheritedField => DlField,
351 pub fn get_trait_def(cdata: Cmd,
352 item_id: ast::NodeId,
353 tcx: &ty::ctxt) -> ty::TraitDef
355 let item_doc = lookup_item(item_id, cdata.data());
356 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
357 let bounds = trait_def_bounds(item_doc, tcx, cdata);
362 trait_ref: Rc::new(item_trait_ref(item_doc, tcx, cdata))
366 pub fn get_type(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
369 let item = lookup_item(id, cdata.data());
371 let t = item_type(ast::DefId { krate: cdata.cnum, node: id }, item, tcx,
374 let generics = doc_generics(item, tcx, cdata, tag_item_generics);
382 pub fn get_stability(cdata: Cmd, id: ast::NodeId) -> Option<attr::Stability> {
383 let item = lookup_item(id, cdata.data());
384 reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
385 let mut decoder = reader::Decoder::new(doc);
386 Decodable::decode(&mut decoder).unwrap()
390 pub fn get_repr_attrs(cdata: Cmd, id: ast::NodeId) -> Vec<attr::ReprAttr> {
391 let item = lookup_item(id, cdata.data());
392 match reader::maybe_get_doc(item, tag_items_data_item_repr).map(|doc| {
393 let mut decoder = reader::Decoder::new(doc);
394 Decodable::decode(&mut decoder).unwrap()
396 Some(attrs) => attrs,
401 pub fn get_impl_trait(cdata: Cmd,
403 tcx: &ty::ctxt) -> Option<Rc<ty::TraitRef>>
405 let item_doc = lookup_item(id, cdata.data());
406 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
407 Rc::new(doc_trait_ref(tp, tcx, cdata))
411 pub fn get_impl_vtables(cdata: Cmd,
414 -> typeck::vtable_res
416 let item_doc = lookup_item(id, cdata.data());
417 let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables);
418 let mut decoder = reader::Decoder::new(vtables_doc);
419 decoder.read_vtable_res(tcx, cdata)
423 pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String {
424 return item_symbol(lookup_item(id, data));
427 // Something that a name can resolve to.
435 /// Iterates over the language items in the given crate.
436 pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
437 let root = rbml::Doc::new(cdata.data());
438 let lang_items = reader::get_doc(root, tag_lang_items);
439 reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
440 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
441 let id = reader::doc_as_u32(id_doc) as uint;
442 let node_id_doc = reader::get_doc(item_doc,
443 tag_lang_items_item_node_id);
444 let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
450 pub type GetCrateDataCb<'a> = |ast::CrateNum|: 'a -> Rc<crate_metadata>;
452 fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
455 get_crate_data: GetCrateDataCb,
459 // Iterate over all children.
460 let _ = reader::tagged_docs(item_doc, tag_mod_child, |child_info_doc| {
461 let child_def_id = reader::with_doc_data(child_info_doc,
463 let child_def_id = translate_def_id(cdata, child_def_id);
465 // This item may be in yet another crate if it was the child of a
467 let crate_data = if child_def_id.krate == cdata.cnum {
470 Some(get_crate_data(child_def_id.krate))
472 let crate_data = match crate_data {
473 Some(ref cdata) => &**cdata,
477 let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
480 match maybe_find_item(child_def_id.node, other_crates_items) {
482 Some(child_item_doc) => {
483 // Hand off the item to the callback.
484 let child_name = item_name(&*intr, child_item_doc);
485 let def_like = item_to_def_like(child_item_doc,
488 let visibility = item_visibility(child_item_doc);
489 callback(def_like, child_name, visibility);
497 // As a special case, iterate over all static methods of
498 // associated implementations too. This is a bit of a botch.
500 let _ = reader::tagged_docs(item_doc,
501 tag_items_data_item_inherent_impl,
502 |inherent_impl_def_id_doc| {
503 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
505 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items);
506 match maybe_find_item(inherent_impl_def_id.node, items) {
508 Some(inherent_impl_doc) => {
509 let _ = reader::tagged_docs(inherent_impl_doc,
511 |impl_item_def_id_doc| {
512 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
514 match maybe_find_item(impl_item_def_id.node, items) {
516 Some(impl_method_doc) => {
517 match item_family(impl_method_doc) {
518 StaticMethod | UnsafeStaticMethod => {
519 // Hand off the static method
521 let static_method_name =
522 item_name(&*intr, impl_method_doc);
523 let static_method_def_like =
524 item_to_def_like(impl_method_doc,
527 callback(static_method_def_like,
529 item_visibility(impl_method_doc));
544 // Iterate over all reexports.
545 let _ = each_reexport(item_doc, |reexport_doc| {
546 let def_id_doc = reader::get_doc(reexport_doc,
547 tag_items_data_item_reexport_def_id);
548 let child_def_id = reader::with_doc_data(def_id_doc,
550 let child_def_id = translate_def_id(cdata, child_def_id);
552 let name_doc = reader::get_doc(reexport_doc,
553 tag_items_data_item_reexport_name);
554 let name = name_doc.as_str_slice();
556 // This reexport may be in yet another crate.
557 let crate_data = if child_def_id.krate == cdata.cnum {
560 Some(get_crate_data(child_def_id.krate))
562 let crate_data = match crate_data {
563 Some(ref cdata) => &**cdata,
567 let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
570 match maybe_find_item(child_def_id.node, other_crates_items) {
572 Some(child_item_doc) => {
573 // Hand off the item to the callback.
574 let def_like = item_to_def_like(child_item_doc,
577 // These items have a public visibility because they're part of
578 // a public re-export.
579 callback(def_like, token::str_to_ident(name), ast::Public);
587 /// Iterates over each child of the given item.
588 pub fn each_child_of_item(intr: Rc<IdentInterner>,
591 get_crate_data: GetCrateDataCb,
592 callback: |DefLike, ast::Ident, ast::Visibility|) {
594 let root_doc = rbml::Doc::new(cdata.data());
595 let items = reader::get_doc(root_doc, tag_items);
596 let item_doc = match maybe_find_item(id, items) {
598 Some(item_doc) => item_doc,
601 each_child_of_item_or_crate(intr,
608 /// Iterates over all the top-level crate items.
609 pub fn each_top_level_item_of_crate(intr: Rc<IdentInterner>,
611 get_crate_data: GetCrateDataCb,
615 let root_doc = rbml::Doc::new(cdata.data());
616 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
617 let crate_items_doc = reader::get_doc(misc_info_doc,
618 tag_misc_info_crate_items);
620 each_child_of_item_or_crate(intr,
627 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
628 item_path(lookup_item(id, cdata.data()))
631 pub type DecodeInlinedItem<'a> = <'tcx> |cdata: Cmd,
632 tcx: &ty::ctxt<'tcx>,
633 path: Vec<ast_map::PathElem>,
634 par_doc: rbml::Doc|: 'a
635 -> Result<&'tcx ast::InlinedItem,
636 Vec<ast_map::PathElem>>;
638 pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: ast::NodeId,
639 decode_inlined_item: DecodeInlinedItem)
640 -> csearch::found_ast<'tcx> {
641 debug!("Looking up item: {}", id);
642 let item_doc = lookup_item(id, cdata.data());
643 let path = Vec::from_slice(item_path(item_doc).init());
644 match decode_inlined_item(cdata, tcx, path, item_doc) {
645 Ok(ii) => csearch::found(ii),
647 match item_parent_item(item_doc) {
649 let did = translate_def_id(cdata, did);
650 let parent_item = lookup_item(did.node, cdata.data());
651 match decode_inlined_item(cdata, tcx, path, parent_item) {
652 Ok(ii) => csearch::found_parent(did, ii),
653 Err(_) => csearch::not_found
656 None => csearch::not_found
662 pub fn get_enum_variants(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
663 tcx: &ty::ctxt) -> Vec<Rc<ty::VariantInfo>> {
664 let data = cdata.data();
665 let items = reader::get_doc(rbml::Doc::new(data), tag_items);
666 let item = find_item(id, items);
667 let mut disr_val = 0;
668 enum_variant_ids(item, cdata).iter().map(|did| {
669 let item = find_item(did.node, items);
670 let ctor_ty = item_type(ast::DefId { krate: cdata.cnum, node: id},
672 let name = item_name(&*intr, item);
673 let arg_tys = match ty::get(ctor_ty).sty {
674 ty::ty_bare_fn(ref f) => f.sig.inputs.clone(),
675 _ => Vec::new(), // Nullary enum variant.
677 match variant_disr_val(item) {
678 Some(val) => { disr_val = val; }
681 let old_disr_val = disr_val;
683 Rc::new(ty::VariantInfo {
688 // I'm not even sure if we encode visibility
689 // for variants -- TEST -- tjc
691 disr_val: old_disr_val,
697 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
698 fn get_mutability(ch: u8) -> ast::Mutability {
700 'i' => ast::MutImmutable,
701 'm' => ast::MutMutable,
702 _ => fail!("unknown mutability character: `{}`", ch as char),
706 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
707 let string = explicit_self_doc.as_str_slice();
709 let explicit_self_kind = string.as_bytes()[0];
710 match explicit_self_kind as char {
711 's' => ty::StaticExplicitSelfCategory,
712 'v' => ty::ByValueExplicitSelfCategory,
713 '~' => ty::ByBoxExplicitSelfCategory,
714 // FIXME(#4846) expl. region
716 ty::ByReferenceExplicitSelfCategory(
718 get_mutability(string.as_bytes()[1]))
720 _ => fail!("unknown self type code: `{}`", explicit_self_kind as char)
724 /// Returns the def IDs of all the items in the given implementation.
725 pub fn get_impl_items(cdata: Cmd, impl_id: ast::NodeId)
726 -> Vec<ty::ImplOrTraitItemId> {
727 let mut impl_items = Vec::new();
728 reader::tagged_docs(lookup_item(impl_id, cdata.data()),
729 tag_item_impl_item, |doc| {
730 let def_id = item_def_id(doc, cdata);
731 match item_sort(doc) {
732 'r' | 'p' => impl_items.push(ty::MethodTraitItemId(def_id)),
733 't' => impl_items.push(ty::TypeTraitItemId(def_id)),
734 _ => fail!("unknown impl item sort"),
742 pub fn get_trait_item_name_and_kind(intr: Rc<IdentInterner>,
745 -> (ast::Ident, TraitItemKind) {
746 let doc = lookup_item(id, cdata.data());
747 let name = item_name(&*intr, doc);
748 match item_sort(doc) {
750 let explicit_self = get_explicit_self(doc);
751 (name, TraitItemKind::from_explicit_self_category(explicit_self))
753 't' => (name, TypeTraitItemKind),
755 fail!("get_trait_item_name_and_kind(): unknown trait item kind \
756 in metadata: `{}`", c)
761 pub fn get_impl_or_trait_item(intr: Rc<IdentInterner>,
765 -> ty::ImplOrTraitItem {
766 let method_doc = lookup_item(id, cdata.data());
768 let def_id = item_def_id(method_doc, cdata);
770 let container_id = item_reqd_and_translated_parent_item(cdata.cnum,
772 let container_doc = lookup_item(container_id.node, cdata.data());
773 let container = match item_family(container_doc) {
774 Trait => TraitContainer(container_id),
775 _ => ImplContainer(container_id),
778 let name = item_name(&*intr, method_doc);
779 let vis = item_visibility(method_doc);
781 match item_sort(method_doc) {
783 let generics = doc_generics(method_doc, tcx, cdata,
784 tag_method_ty_generics);
785 let fty = doc_method_fty(method_doc, tcx, cdata);
786 let explicit_self = get_explicit_self(method_doc);
787 let provided_source = get_provided_source(method_doc, cdata);
789 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
799 ty::TypeTraitItem(Rc::new(ty::AssociatedType {
803 container: container,
806 _ => fail!("unknown impl/trait item sort"),
810 pub fn get_trait_item_def_ids(cdata: Cmd, id: ast::NodeId)
811 -> Vec<ty::ImplOrTraitItemId> {
812 let data = cdata.data();
813 let item = lookup_item(id, data);
814 let mut result = Vec::new();
815 reader::tagged_docs(item, tag_item_trait_item, |mth| {
816 let def_id = item_def_id(mth, cdata);
817 match item_sort(mth) {
818 'r' | 'p' => result.push(ty::MethodTraitItemId(def_id)),
819 't' => result.push(ty::TypeTraitItemId(def_id)),
820 _ => fail!("unknown trait item sort"),
827 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
828 let data = cdata.data();
829 let item_doc = lookup_item(id, data);
830 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
831 let mut decoder = reader::Decoder::new(variance_doc);
832 Decodable::decode(&mut decoder).unwrap()
835 pub fn get_provided_trait_methods(intr: Rc<IdentInterner>,
839 -> Vec<Rc<ty::Method>> {
840 let data = cdata.data();
841 let item = lookup_item(id, data);
842 let mut result = Vec::new();
844 reader::tagged_docs(item, tag_item_trait_item, |mth_id| {
845 let did = item_def_id(mth_id, cdata);
846 let mth = lookup_item(did.node, data);
848 if item_sort(mth) == 'p' {
849 let trait_item = get_impl_or_trait_item(intr.clone(),
854 ty::MethodTraitItem(ref method) => {
855 result.push((*method).clone())
857 ty::TypeTraitItem(_) => {}
866 /// Returns the supertraits of the given trait.
867 pub fn get_supertraits(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
868 -> Vec<Rc<ty::TraitRef>> {
869 let mut results = Vec::new();
870 let item_doc = lookup_item(id, cdata.data());
871 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
872 // NB. Only reads the ones that *aren't* builtin-bounds. See also
873 // get_trait_def() for collecting the builtin bounds.
874 // FIXME(#8559): The builtin bounds shouldn't be encoded in the first place.
875 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
876 if tcx.lang_items.to_builtin_kind(trait_ref.def_id).is_none() {
877 results.push(Rc::new(trait_ref));
884 pub fn get_type_name_if_impl(cdata: Cmd,
885 node_id: ast::NodeId) -> Option<ast::Ident> {
886 let item = lookup_item(node_id, cdata.data());
887 if item_family(item) != Impl {
892 reader::tagged_docs(item, tag_item_impl_type_basename, |doc| {
893 ret = Some(token::str_to_ident(doc.as_str_slice()));
900 pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
902 node_id: ast::NodeId)
903 -> Option<Vec<StaticMethodInfo> > {
904 let item = lookup_item(node_id, cdata.data());
905 if item_family(item) != Impl {
909 // If this impl implements a trait, don't consider it.
910 let ret = reader::tagged_docs(item, tag_item_trait_ref, |_doc| {
914 if !ret { return None }
916 let mut impl_method_ids = Vec::new();
917 reader::tagged_docs(item, tag_item_impl_item, |impl_method_doc| {
918 impl_method_ids.push(item_def_id(impl_method_doc, cdata));
922 let mut static_impl_methods = Vec::new();
923 for impl_method_id in impl_method_ids.iter() {
924 let impl_method_doc = lookup_item(impl_method_id.node, cdata.data());
925 let family = item_family(impl_method_doc);
927 StaticMethod | UnsafeStaticMethod => {
929 match item_family(impl_method_doc) {
930 StaticMethod => fn_style = ast::NormalFn,
931 UnsafeStaticMethod => fn_style = ast::UnsafeFn,
935 static_impl_methods.push(StaticMethodInfo {
936 ident: item_name(&*intr, impl_method_doc),
937 def_id: item_def_id(impl_method_doc, cdata),
939 vis: item_visibility(impl_method_doc),
946 return Some(static_impl_methods);
949 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
950 /// the actual type definition, otherwise, return None
951 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
952 node_id: ast::NodeId)
953 -> Option<ast::DefId>
955 let item = lookup_item(node_id, cdata.data());
957 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
958 ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
964 pub fn get_item_attrs(cdata: Cmd,
965 orig_node_id: ast::NodeId,
966 f: |Vec<ast::Attribute>|) {
967 // The attributes for a tuple struct are attached to the definition, not the ctor;
968 // we assume that someone passing in a tuple struct ctor is actually wanting to
969 // look at the definition
970 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
971 let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id);
972 let item = lookup_item(node_id, cdata.data());
973 f(get_attributes(item));
976 pub fn get_struct_field_attrs(cdata: Cmd) -> HashMap<ast::NodeId, Vec<ast::Attribute>> {
977 let data = rbml::Doc::new(cdata.data());
978 let fields = reader::get_doc(data, tag_struct_fields);
979 let mut map = HashMap::new();
980 reader::tagged_docs(fields, tag_struct_field, |field| {
981 let id = reader::doc_as_u32(reader::get_doc(field, tag_struct_field_id));
982 let attrs = get_attributes(field);
983 map.insert(id, attrs);
989 fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
991 PublicField => ast::Public,
992 InheritedField => ast::Inherited,
997 pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
998 -> Vec<ty::field_ty> {
999 let data = cdata.data();
1000 let item = lookup_item(id, data);
1001 let mut result = Vec::new();
1002 reader::tagged_docs(item, tag_item_field, |an_item| {
1003 let f = item_family(an_item);
1004 if f == PublicField || f == InheritedField {
1005 // FIXME #6993: name should be of type Name, not Ident
1006 let name = item_name(&*intr, an_item);
1007 let did = item_def_id(an_item, cdata);
1008 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
1009 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
1010 result.push(ty::field_ty {
1013 vis: struct_field_family_to_visibility(f),
1019 reader::tagged_docs(item, tag_item_unnamed_field, |an_item| {
1020 let did = item_def_id(an_item, cdata);
1021 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
1022 let f = item_family(an_item);
1023 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
1024 result.push(ty::field_ty {
1025 name: special_idents::unnamed_field.name,
1027 vis: struct_field_family_to_visibility(f),
1035 fn get_meta_items(md: rbml::Doc) -> Vec<P<ast::MetaItem>> {
1036 let mut items: Vec<P<ast::MetaItem>> = Vec::new();
1037 reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
1038 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1039 let n = token::intern_and_get_ident(nd.as_str_slice());
1040 items.push(attr::mk_word_item(n));
1043 reader::tagged_docs(md, tag_meta_item_name_value, |meta_item_doc| {
1044 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1045 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1046 let n = token::intern_and_get_ident(nd.as_str_slice());
1047 let v = token::intern_and_get_ident(vd.as_str_slice());
1048 // FIXME (#623): Should be able to decode MetaNameValue variants,
1049 // but currently the encoder just drops them
1050 items.push(attr::mk_name_value_item_str(n, v));
1053 reader::tagged_docs(md, tag_meta_item_list, |meta_item_doc| {
1054 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1055 let n = token::intern_and_get_ident(nd.as_str_slice());
1056 let subitems = get_meta_items(meta_item_doc);
1057 items.push(attr::mk_list_item(n, subitems.into_iter().collect()));
1063 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1064 let mut attrs: Vec<ast::Attribute> = Vec::new();
1065 match reader::maybe_get_doc(md, tag_attributes) {
1067 reader::tagged_docs(attrs_d, tag_attribute, |attr_doc| {
1068 let is_sugared_doc = reader::doc_as_u8(
1069 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1071 let meta_items = get_meta_items(attr_doc);
1072 // Currently it's only possible to have a single meta item on
1074 assert_eq!(meta_items.len(), 1u);
1075 let meta_item = meta_items.into_iter().nth(0).unwrap();
1078 node: ast::Attribute_ {
1079 id: attr::mk_attr_id(),
1080 style: ast::AttrOuter,
1082 is_sugared_doc: is_sugared_doc,
1084 span: codemap::DUMMY_SP
1094 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1095 out: &mut io::Writer) -> io::IoResult<()> {
1096 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1098 let r = get_attributes(md);
1099 for attr in r.iter() {
1100 try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1106 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1107 get_attributes(rbml::Doc::new(data))
1111 pub struct CrateDep {
1112 pub cnum: ast::CrateNum,
1117 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1118 let mut deps: Vec<CrateDep> = Vec::new();
1119 let cratedoc = rbml::Doc::new(data);
1120 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1121 let mut crate_num = 1;
1122 fn docstr(doc: rbml::Doc, tag_: uint) -> String {
1123 let d = reader::get_doc(doc, tag_);
1124 d.as_str_slice().to_string()
1126 reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
1127 let name = docstr(depdoc, tag_crate_dep_crate_name);
1128 let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash).as_slice());
1129 deps.push(CrateDep {
1140 fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1141 try!(write!(out, "=External Dependencies=\n"));
1142 for dep in get_crate_deps(data).iter() {
1143 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1145 try!(write!(out, "\n"));
1149 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1150 let cratedoc = rbml::Doc::new(data);
1151 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1152 Svh::new(doc.as_str_slice())
1156 pub fn get_crate_hash(data: &[u8]) -> Svh {
1157 let cratedoc = rbml::Doc::new(data);
1158 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1159 Svh::new(hashdoc.as_str_slice())
1162 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1163 let cratedoc = rbml::Doc::new(data);
1164 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1165 doc.as_str_slice().to_string()
1169 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1170 let cratedoc = rbml::Doc::new(data);
1171 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1172 triple_doc.map(|s| s.as_str().to_string())
1175 pub fn get_crate_name(data: &[u8]) -> String {
1176 maybe_get_crate_name(data).expect("no crate name in crate")
1179 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1180 let hash = get_crate_hash(bytes);
1181 let md = rbml::Doc::new(bytes);
1182 try!(list_crate_attributes(md, &hash, out));
1183 list_crate_deps(bytes, out)
1186 // Translates a def_id from an external crate to a def_id for the current
1187 // compilation environment. We use this when trying to load types from
1188 // external crates - if those types further refer to types in other crates
1189 // then we must translate the crate number from that encoded in the external
1190 // crate to the correct local crate number.
1191 pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
1192 if did.krate == ast::LOCAL_CRATE {
1193 return ast::DefId { krate: cdata.cnum, node: did.node };
1196 match cdata.cnum_map.find(&did.krate) {
1203 None => fail!("didn't find a crate in the cnum_map")
1207 pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
1208 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1209 let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
1210 callback(item_def_id(impl_doc, cdata));
1215 pub fn each_implementation_for_type(cdata: Cmd,
1217 callback: |ast::DefId|) {
1218 let item_doc = lookup_item(id, cdata.data());
1219 reader::tagged_docs(item_doc,
1220 tag_items_data_item_inherent_impl,
1222 let implementation_def_id = item_def_id(impl_doc, cdata);
1223 callback(implementation_def_id);
1228 pub fn each_implementation_for_trait(cdata: Cmd,
1230 callback: |ast::DefId|) {
1231 let item_doc = lookup_item(id, cdata.data());
1233 let _ = reader::tagged_docs(item_doc,
1234 tag_items_data_item_extension_impl,
1236 let implementation_def_id = item_def_id(impl_doc, cdata);
1237 callback(implementation_def_id);
1242 pub fn get_trait_of_item(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
1243 -> Option<ast::DefId> {
1244 let item_doc = lookup_item(id, cdata.data());
1245 let parent_item_id = match item_parent_item(item_doc) {
1246 None => return None,
1247 Some(item_id) => item_id,
1249 let parent_item_id = translate_def_id(cdata, parent_item_id);
1250 let parent_item_doc = lookup_item(parent_item_id.node, cdata.data());
1251 match item_family(parent_item_doc) {
1252 Trait => Some(item_def_id(parent_item_doc, cdata)),
1254 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1255 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1262 pub fn get_native_libraries(cdata: Cmd)
1263 -> Vec<(cstore::NativeLibaryKind, String)> {
1264 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1265 tag_native_libraries);
1266 let mut result = Vec::new();
1267 reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
1268 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1269 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1270 let kind: cstore::NativeLibaryKind =
1271 FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1272 let name = name_doc.as_str().to_string();
1273 result.push((kind, name));
1279 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<ast::NodeId> {
1280 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1281 .map(|doc| FromPrimitive::from_u32(reader::doc_as_u32(doc)).unwrap())
1284 pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
1285 let macros = reader::get_doc(rbml::Doc::new(data),
1286 tag_exported_macros);
1287 let mut result = Vec::new();
1288 reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
1289 result.push(macro_doc.as_str().to_string());
1295 pub fn get_dylib_dependency_formats(cdata: Cmd)
1296 -> Vec<(ast::CrateNum, cstore::LinkagePreference)>
1298 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1299 tag_dylib_dependency_formats);
1300 let mut result = Vec::new();
1302 debug!("found dylib deps: {}", formats.as_str_slice());
1303 for spec in formats.as_str_slice().split(',') {
1304 if spec.len() == 0 { continue }
1305 let cnum = spec.split(':').nth(0).unwrap();
1306 let link = spec.split(':').nth(1).unwrap();
1307 let cnum = from_str(cnum).unwrap();
1308 let cnum = match cdata.cnum_map.find(&cnum) {
1310 None => fail!("didn't find a crate in the cnum_map")
1312 result.push((cnum, if link == "d" {
1313 cstore::RequireDynamic
1315 cstore::RequireStatic
1321 pub fn get_missing_lang_items(cdata: Cmd)
1322 -> Vec<lang_items::LangItem>
1324 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1325 let mut result = Vec::new();
1326 reader::tagged_docs(items, tag_lang_items_missing, |missing_doc| {
1327 let item: lang_items::LangItem =
1328 FromPrimitive::from_u32(reader::doc_as_u32(missing_doc)).unwrap();
1335 pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec<String> {
1336 let mut ret = Vec::new();
1337 let method_doc = lookup_item(id, cdata.data());
1338 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1340 reader::tagged_docs(args_doc, tag_method_argument_name, |name_doc| {
1341 ret.push(name_doc.as_str_slice().to_string());
1350 pub fn get_reachable_extern_fns(cdata: Cmd) -> Vec<ast::DefId> {
1351 let mut ret = Vec::new();
1352 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1353 tag_reachable_extern_fns);
1354 reader::tagged_docs(items, tag_reachable_extern_fn_id, |doc| {
1355 ret.push(ast::DefId {
1357 node: reader::doc_as_u32(doc),
1364 pub fn is_typedef(cdata: Cmd, id: ast::NodeId) -> bool {
1365 let item_doc = lookup_item(id, cdata.data());
1366 match item_family(item_doc) {
1372 fn doc_generics(base_doc: rbml::Doc,
1378 let doc = reader::get_doc(base_doc, tag);
1380 let mut types = subst::VecPerParamSpace::empty();
1381 reader::tagged_docs(doc, tag_type_param_def, |p| {
1382 let bd = parse_type_param_def_data(
1383 p.data, p.start, cdata.cnum, tcx,
1384 |_, did| translate_def_id(cdata, did));
1385 types.push(bd.space, bd);
1389 let mut regions = subst::VecPerParamSpace::empty();
1390 reader::tagged_docs(doc, tag_region_param_def, |rp_doc| {
1391 let ident_str_doc = reader::get_doc(rp_doc,
1392 tag_region_param_def_ident);
1393 let ident = item_name(&*token::get_ident_interner(), ident_str_doc);
1394 let def_id_doc = reader::get_doc(rp_doc,
1395 tag_region_param_def_def_id);
1396 let def_id = reader::with_doc_data(def_id_doc, parse_def_id);
1397 let def_id = translate_def_id(cdata, def_id);
1399 let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1400 let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as uint);
1402 let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1403 let index = reader::doc_as_u64(doc) as uint;
1405 let mut bounds = Vec::new();
1406 reader::tagged_docs(rp_doc, tag_items_data_region, |p| {
1409 p.data, cdata.cnum, p.start, tcx,
1410 |_, did| translate_def_id(cdata, did)));
1414 regions.push(space, ty::RegionParameterDef { name: ident.name,
1423 ty::Generics { types: types, regions: regions }
1426 pub fn is_associated_type(cdata: Cmd, id: ast::NodeId) -> bool {
1427 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items);
1428 match maybe_find_item(id, items) {
1430 Some(item) => item_sort(item) == 't',