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;
28 use middle::ty::{ImplContainer, TraitContainer};
31 use middle::astencode::vtable_decoder_helpers;
36 use std::io::extensions::u64_from_be_bytes;
38 use std::collections::hashmap::HashMap;
43 use serialize::Decodable;
46 use syntax::parse::token::{IdentInterner, special_idents};
47 use syntax::parse::token;
48 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)]
116 UnsafeStaticMethod, // U
131 fn item_family(item: rbml::Doc) -> Family {
132 let fam = reader::get_doc(item, tag_items_data_item_family);
133 match reader::doc_as_u8(fam) as char {
139 'U' => UnsafeStaticMethod,
146 'V' => StructVariant,
151 'N' => InheritedField,
152 c => fail!("unexpected family char: {}", c)
156 fn item_visibility(item: rbml::Doc) -> ast::Visibility {
157 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
159 Some(visibility_doc) => {
160 match reader::doc_as_u8(visibility_doc) as char {
162 'i' => ast::Inherited,
163 _ => fail!("unknown visibility character")
169 fn item_sort(item: rbml::Doc) -> char {
171 reader::tagged_docs(item, tag_item_trait_item_sort, |doc| {
172 ret = doc.as_str_slice().as_bytes()[0] as char;
178 fn item_symbol(item: rbml::Doc) -> String {
179 reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
182 fn item_parent_item(d: rbml::Doc) -> Option<ast::DefId> {
184 reader::tagged_docs(d, tag_items_data_parent_item, |did| {
185 ret = Some(reader::with_doc_data(did, parse_def_id));
191 fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
192 d: rbml::Doc) -> ast::DefId {
193 let trait_did = item_parent_item(d).expect("item without parent");
194 ast::DefId { krate: cnum, node: trait_did.node }
197 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> ast::DefId {
198 let tagdoc = reader::get_doc(d, tag_def_id);
199 return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
202 fn get_provided_source(d: rbml::Doc, cdata: Cmd) -> Option<ast::DefId> {
203 reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
204 translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
208 fn each_reexport(d: rbml::Doc, f: |rbml::Doc| -> bool) -> bool {
209 reader::tagged_docs(d, tag_items_data_item_reexport, f)
212 fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
213 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
214 reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
218 fn doc_type(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
219 let tp = reader::get_doc(doc, tag_items_data_item_type);
220 parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
221 |_, did| translate_def_id(cdata, did))
224 fn doc_method_fty(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
225 let tp = reader::get_doc(doc, tag_item_method_fty);
226 parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
227 |_, did| translate_def_id(cdata, did))
230 pub fn item_type(_item_id: ast::DefId, item: rbml::Doc,
231 tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
232 doc_type(item, tcx, cdata)
235 fn doc_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
236 parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
237 |_, did| translate_def_id(cdata, did))
240 fn item_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
241 let tp = reader::get_doc(doc, tag_item_trait_ref);
242 doc_trait_ref(tp, tcx, cdata)
245 fn doc_bounds(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::ParamBounds {
246 parse_bounds_data(doc.data, cdata.cnum, doc.start, tcx,
247 |_, did| translate_def_id(cdata, did))
250 fn trait_def_bounds(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::ParamBounds {
251 let d = reader::get_doc(doc, tag_trait_def_bounds);
252 doc_bounds(d, tcx, cdata)
255 fn enum_variant_ids(item: rbml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
256 let mut ids: Vec<ast::DefId> = Vec::new();
257 let v = tag_items_data_item_variant;
258 reader::tagged_docs(item, v, |p| {
259 let ext = reader::with_doc_data(p, parse_def_id);
260 ids.push(ast::DefId { krate: cdata.cnum, node: ext.node });
266 fn item_path(item_doc: rbml::Doc) -> Vec<ast_map::PathElem> {
267 let path_doc = reader::get_doc(item_doc, tag_path);
269 let len_doc = reader::get_doc(path_doc, tag_path_len);
270 let len = reader::doc_as_u32(len_doc) as uint;
272 let mut result = Vec::with_capacity(len);
273 reader::docs(path_doc, |tag, elt_doc| {
274 if tag == tag_path_elem_mod {
275 let s = elt_doc.as_str_slice();
276 result.push(ast_map::PathMod(token::intern(s)));
277 } else if tag == tag_path_elem_name {
278 let s = elt_doc.as_str_slice();
279 result.push(ast_map::PathName(token::intern(s)));
281 // ignore tag_path_len element
289 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Ident {
290 let name = reader::get_doc(item, tag_paths_data_name);
291 let string = name.as_str_slice();
292 match intr.find_equiv(&string) {
293 None => token::str_to_ident(string),
294 Some(val) => ast::Ident::new(val),
298 fn item_to_def_like(item: rbml::Doc, did: ast::DefId, cnum: ast::CrateNum)
300 let fam = item_family(item);
302 ImmStatic => DlDef(def::DefStatic(did, false)),
303 MutStatic => DlDef(def::DefStatic(did, true)),
304 Struct => DlDef(def::DefStruct(did)),
305 UnsafeFn => DlDef(def::DefFn(did, ast::UnsafeFn)),
306 Fn => DlDef(def::DefFn(did, ast::NormalFn)),
307 StaticMethod | UnsafeStaticMethod => {
308 let fn_style = if fam == UnsafeStaticMethod {
313 // def_static_method carries an optional field of its enclosing
314 // trait or enclosing impl (if this is an inherent static method).
315 // So we need to detect whether this is in a trait or not, which
316 // we do through the mildly hacky way of checking whether there is
317 // a trait_parent_sort.
318 let provenance = if reader::maybe_get_doc(
319 item, tag_item_trait_parent_sort).is_some() {
320 def::FromTrait(item_reqd_and_translated_parent_item(cnum,
323 def::FromImpl(item_reqd_and_translated_parent_item(cnum,
326 DlDef(def::DefStaticMethod(did, provenance, fn_style))
328 Type | ForeignType => DlDef(def::DefTy(did)),
329 Mod => DlDef(def::DefMod(did)),
330 ForeignMod => DlDef(def::DefForeignMod(did)),
332 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
333 DlDef(def::DefVariant(enum_did, did, true))
336 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
337 DlDef(def::DefVariant(enum_did, did, false))
339 Trait => DlDef(def::DefTrait(did)),
340 Enum => DlDef(def::DefTy(did)),
342 PublicField | InheritedField => DlField,
346 pub fn get_trait_def(cdata: Cmd,
347 item_id: ast::NodeId,
348 tcx: &ty::ctxt) -> ty::TraitDef
350 let item_doc = lookup_item(item_id, cdata.data());
351 let generics = doc_generics(item_doc, tcx, cdata, tag_item_generics);
352 let bounds = trait_def_bounds(item_doc, tcx, cdata);
357 trait_ref: Rc::new(item_trait_ref(item_doc, tcx, cdata))
361 pub fn get_type(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
364 let item = lookup_item(id, cdata.data());
366 let t = item_type(ast::DefId { krate: cdata.cnum, node: id }, item, tcx,
369 let generics = doc_generics(item, tcx, cdata, tag_item_generics);
377 pub fn get_stability(cdata: Cmd, id: ast::NodeId) -> Option<attr::Stability> {
378 let item = lookup_item(id, cdata.data());
379 reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
380 let mut decoder = reader::Decoder::new(doc);
381 Decodable::decode(&mut decoder).unwrap()
385 pub fn get_impl_trait(cdata: Cmd,
387 tcx: &ty::ctxt) -> Option<Rc<ty::TraitRef>>
389 let item_doc = lookup_item(id, cdata.data());
390 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
391 Rc::new(doc_trait_ref(tp, tcx, cdata))
395 pub fn get_impl_vtables(cdata: Cmd,
398 -> typeck::vtable_res
400 let item_doc = lookup_item(id, cdata.data());
401 let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables);
402 let mut decoder = reader::Decoder::new(vtables_doc);
403 decoder.read_vtable_res(tcx, cdata)
407 pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String {
408 return item_symbol(lookup_item(id, data));
411 // Something that a name can resolve to.
419 /// Iterates over the language items in the given crate.
420 pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
421 let root = rbml::Doc::new(cdata.data());
422 let lang_items = reader::get_doc(root, tag_lang_items);
423 reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
424 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
425 let id = reader::doc_as_u32(id_doc) as uint;
426 let node_id_doc = reader::get_doc(item_doc,
427 tag_lang_items_item_node_id);
428 let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
434 pub type GetCrateDataCb<'a> = |ast::CrateNum|: 'a -> Rc<crate_metadata>;
436 fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
439 get_crate_data: GetCrateDataCb,
443 // Iterate over all children.
444 let _ = reader::tagged_docs(item_doc, tag_mod_child, |child_info_doc| {
445 let child_def_id = reader::with_doc_data(child_info_doc,
447 let child_def_id = translate_def_id(cdata, child_def_id);
449 // This item may be in yet another crate if it was the child of a
451 let crate_data = if child_def_id.krate == cdata.cnum {
454 Some(get_crate_data(child_def_id.krate))
456 let crate_data = match crate_data {
457 Some(ref cdata) => &**cdata,
461 let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
464 match maybe_find_item(child_def_id.node, other_crates_items) {
466 Some(child_item_doc) => {
467 // Hand off the item to the callback.
468 let child_name = item_name(&*intr, child_item_doc);
469 let def_like = item_to_def_like(child_item_doc,
472 let visibility = item_visibility(child_item_doc);
473 callback(def_like, child_name, visibility);
481 // As a special case, iterate over all static methods of
482 // associated implementations too. This is a bit of a botch.
484 let _ = reader::tagged_docs(item_doc,
485 tag_items_data_item_inherent_impl,
486 |inherent_impl_def_id_doc| {
487 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
489 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items);
490 match maybe_find_item(inherent_impl_def_id.node, items) {
492 Some(inherent_impl_doc) => {
493 let _ = reader::tagged_docs(inherent_impl_doc,
495 |impl_item_def_id_doc| {
496 let impl_item_def_id = item_def_id(impl_item_def_id_doc,
498 match maybe_find_item(impl_item_def_id.node, items) {
500 Some(impl_method_doc) => {
501 match item_family(impl_method_doc) {
502 StaticMethod | UnsafeStaticMethod => {
503 // Hand off the static method
505 let static_method_name =
506 item_name(&*intr, impl_method_doc);
507 let static_method_def_like =
508 item_to_def_like(impl_method_doc,
511 callback(static_method_def_like,
513 item_visibility(impl_method_doc));
528 // Iterate over all reexports.
529 let _ = each_reexport(item_doc, |reexport_doc| {
530 let def_id_doc = reader::get_doc(reexport_doc,
531 tag_items_data_item_reexport_def_id);
532 let child_def_id = reader::with_doc_data(def_id_doc,
534 let child_def_id = translate_def_id(cdata, child_def_id);
536 let name_doc = reader::get_doc(reexport_doc,
537 tag_items_data_item_reexport_name);
538 let name = name_doc.as_str_slice();
540 // This reexport may be in yet another crate.
541 let crate_data = if child_def_id.krate == cdata.cnum {
544 Some(get_crate_data(child_def_id.krate))
546 let crate_data = match crate_data {
547 Some(ref cdata) => &**cdata,
551 let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
554 match maybe_find_item(child_def_id.node, other_crates_items) {
556 Some(child_item_doc) => {
557 // Hand off the item to the callback.
558 let def_like = item_to_def_like(child_item_doc,
561 // These items have a public visibility because they're part of
562 // a public re-export.
563 callback(def_like, token::str_to_ident(name), ast::Public);
571 /// Iterates over each child of the given item.
572 pub fn each_child_of_item(intr: Rc<IdentInterner>,
575 get_crate_data: GetCrateDataCb,
576 callback: |DefLike, ast::Ident, ast::Visibility|) {
578 let root_doc = rbml::Doc::new(cdata.data());
579 let items = reader::get_doc(root_doc, tag_items);
580 let item_doc = match maybe_find_item(id, items) {
582 Some(item_doc) => item_doc,
585 each_child_of_item_or_crate(intr,
592 /// Iterates over all the top-level crate items.
593 pub fn each_top_level_item_of_crate(intr: Rc<IdentInterner>,
595 get_crate_data: GetCrateDataCb,
599 let root_doc = rbml::Doc::new(cdata.data());
600 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
601 let crate_items_doc = reader::get_doc(misc_info_doc,
602 tag_misc_info_crate_items);
604 each_child_of_item_or_crate(intr,
611 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
612 item_path(lookup_item(id, cdata.data()))
615 pub type DecodeInlinedItem<'a> = |cdata: Cmd,
617 path: Vec<ast_map::PathElem>,
618 par_doc: rbml::Doc|: 'a
619 -> Result<ast::InlinedItem, Vec<ast_map::PathElem> >;
621 pub fn maybe_get_item_ast(cdata: Cmd, tcx: &ty::ctxt, id: ast::NodeId,
622 decode_inlined_item: DecodeInlinedItem)
623 -> csearch::found_ast {
624 debug!("Looking up item: {}", id);
625 let item_doc = lookup_item(id, cdata.data());
626 let path = Vec::from_slice(item_path(item_doc).init());
627 match decode_inlined_item(cdata, tcx, path, item_doc) {
628 Ok(ref ii) => csearch::found(*ii),
630 match item_parent_item(item_doc) {
632 let did = translate_def_id(cdata, did);
633 let parent_item = lookup_item(did.node, cdata.data());
634 match decode_inlined_item(cdata, tcx, path, parent_item) {
635 Ok(ref ii) => csearch::found_parent(did, *ii),
636 Err(_) => csearch::not_found
639 None => csearch::not_found
645 pub fn get_enum_variants(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
646 tcx: &ty::ctxt) -> Vec<Rc<ty::VariantInfo>> {
647 let data = cdata.data();
648 let items = reader::get_doc(rbml::Doc::new(data), tag_items);
649 let item = find_item(id, items);
650 let mut disr_val = 0;
651 enum_variant_ids(item, cdata).iter().map(|did| {
652 let item = find_item(did.node, items);
653 let ctor_ty = item_type(ast::DefId { krate: cdata.cnum, node: id},
655 let name = item_name(&*intr, item);
656 let arg_tys = match ty::get(ctor_ty).sty {
657 ty::ty_bare_fn(ref f) => f.sig.inputs.clone(),
658 _ => Vec::new(), // Nullary enum variant.
660 match variant_disr_val(item) {
661 Some(val) => { disr_val = val; }
664 let old_disr_val = disr_val;
666 Rc::new(ty::VariantInfo {
671 // I'm not even sure if we encode visibility
672 // for variants -- TEST -- tjc
674 disr_val: old_disr_val,
680 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
681 fn get_mutability(ch: u8) -> ast::Mutability {
683 'i' => ast::MutImmutable,
684 'm' => ast::MutMutable,
685 _ => fail!("unknown mutability character: `{}`", ch as char),
689 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
690 let string = explicit_self_doc.as_str_slice();
692 let explicit_self_kind = string.as_bytes()[0];
693 match explicit_self_kind as char {
694 's' => ty::StaticExplicitSelfCategory,
695 'v' => ty::ByValueExplicitSelfCategory,
696 '~' => ty::ByBoxExplicitSelfCategory,
697 // FIXME(#4846) expl. region
699 ty::ByReferenceExplicitSelfCategory(
701 get_mutability(string.as_bytes()[1]))
703 _ => fail!("unknown self type code: `{}`", explicit_self_kind as char)
707 /// Returns the def IDs of all the items in the given implementation.
708 pub fn get_impl_items(cdata: Cmd, impl_id: ast::NodeId)
709 -> Vec<ty::ImplOrTraitItemId> {
710 let mut impl_items = Vec::new();
711 reader::tagged_docs(lookup_item(impl_id, cdata.data()),
712 tag_item_impl_item, |doc| {
713 let def_id = item_def_id(doc, cdata);
714 match item_sort(doc) {
715 'r' | 'p' => impl_items.push(ty::MethodTraitItemId(def_id)),
716 _ => fail!("unknown impl item sort"),
724 pub fn get_trait_item_name_and_kind(intr: Rc<IdentInterner>,
727 -> (ast::Ident, TraitItemKind) {
728 let doc = lookup_item(id, cdata.data());
729 let name = item_name(&*intr, doc);
730 match item_sort(doc) {
732 let explicit_self = get_explicit_self(doc);
733 (name, TraitItemKind::from_explicit_self_category(explicit_self))
736 fail!("get_trait_item_name_and_kind(): unknown trait item kind \
737 in metadata: `{}`", c)
742 pub fn get_impl_or_trait_item(intr: Rc<IdentInterner>,
746 -> ty::ImplOrTraitItem {
747 let method_doc = lookup_item(id, cdata.data());
749 let def_id = item_def_id(method_doc, cdata);
751 let container_id = item_reqd_and_translated_parent_item(cdata.cnum,
753 let container_doc = lookup_item(container_id.node, cdata.data());
754 let container = match item_family(container_doc) {
755 Trait => TraitContainer(container_id),
756 _ => ImplContainer(container_id),
759 let name = item_name(&*intr, method_doc);
761 match item_sort(method_doc) {
763 let generics = doc_generics(method_doc, tcx, cdata,
764 tag_method_ty_generics);
765 let fty = doc_method_fty(method_doc, tcx, cdata);
766 let vis = item_visibility(method_doc);
767 let explicit_self = get_explicit_self(method_doc);
768 let provided_source = get_provided_source(method_doc, cdata);
770 ty::MethodTraitItem(Rc::new(ty::Method::new(name,
779 _ => fail!("unknown impl/trait item sort"),
783 pub fn get_trait_item_def_ids(cdata: Cmd, id: ast::NodeId)
784 -> Vec<ty::ImplOrTraitItemId> {
785 let data = cdata.data();
786 let item = lookup_item(id, data);
787 let mut result = Vec::new();
788 reader::tagged_docs(item, tag_item_trait_item, |mth| {
789 let def_id = item_def_id(mth, cdata);
790 match item_sort(mth) {
791 'r' | 'p' => result.push(ty::MethodTraitItemId(def_id)),
792 _ => fail!("unknown trait item sort"),
799 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
800 let data = cdata.data();
801 let item_doc = lookup_item(id, data);
802 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
803 let mut decoder = reader::Decoder::new(variance_doc);
804 Decodable::decode(&mut decoder).unwrap()
807 pub fn get_provided_trait_methods(intr: Rc<IdentInterner>,
811 -> Vec<Rc<ty::Method>> {
812 let data = cdata.data();
813 let item = lookup_item(id, data);
814 let mut result = Vec::new();
816 reader::tagged_docs(item, tag_item_trait_item, |mth_id| {
817 let did = item_def_id(mth_id, cdata);
818 let mth = lookup_item(did.node, data);
820 if item_sort(mth) == 'p' {
821 let trait_item = get_impl_or_trait_item(intr.clone(),
826 ty::MethodTraitItem(ref method) => {
827 result.push((*method).clone())
837 /// Returns the supertraits of the given trait.
838 pub fn get_supertraits(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
839 -> Vec<Rc<ty::TraitRef>> {
840 let mut results = Vec::new();
841 let item_doc = lookup_item(id, cdata.data());
842 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
843 // NB. Only reads the ones that *aren't* builtin-bounds. See also
844 // get_trait_def() for collecting the builtin bounds.
845 // FIXME(#8559): The builtin bounds shouldn't be encoded in the first place.
846 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
847 if tcx.lang_items.to_builtin_kind(trait_ref.def_id).is_none() {
848 results.push(Rc::new(trait_ref));
855 pub fn get_type_name_if_impl(cdata: Cmd,
856 node_id: ast::NodeId) -> Option<ast::Ident> {
857 let item = lookup_item(node_id, cdata.data());
858 if item_family(item) != Impl {
863 reader::tagged_docs(item, tag_item_impl_type_basename, |doc| {
864 ret = Some(token::str_to_ident(doc.as_str_slice()));
871 pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
873 node_id: ast::NodeId)
874 -> Option<Vec<StaticMethodInfo> > {
875 let item = lookup_item(node_id, cdata.data());
876 if item_family(item) != Impl {
880 // If this impl implements a trait, don't consider it.
881 let ret = reader::tagged_docs(item, tag_item_trait_ref, |_doc| {
885 if !ret { return None }
887 let mut impl_method_ids = Vec::new();
888 reader::tagged_docs(item, tag_item_impl_item, |impl_method_doc| {
889 impl_method_ids.push(item_def_id(impl_method_doc, cdata));
893 let mut static_impl_methods = Vec::new();
894 for impl_method_id in impl_method_ids.iter() {
895 let impl_method_doc = lookup_item(impl_method_id.node, cdata.data());
896 let family = item_family(impl_method_doc);
898 StaticMethod | UnsafeStaticMethod => {
900 match item_family(impl_method_doc) {
901 StaticMethod => fn_style = ast::NormalFn,
902 UnsafeStaticMethod => fn_style = ast::UnsafeFn,
906 static_impl_methods.push(StaticMethodInfo {
907 ident: item_name(&*intr, impl_method_doc),
908 def_id: item_def_id(impl_method_doc, cdata),
910 vis: item_visibility(impl_method_doc),
917 return Some(static_impl_methods);
920 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
921 /// the actual type definition, otherwise, return None
922 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
923 node_id: ast::NodeId)
924 -> Option<ast::DefId>
926 let item = lookup_item(node_id, cdata.data());
928 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
929 ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
935 pub fn get_item_attrs(cdata: Cmd,
936 orig_node_id: ast::NodeId,
937 f: |Vec<ast::Attribute>|) {
938 // The attributes for a tuple struct are attached to the definition, not the ctor;
939 // we assume that someone passing in a tuple struct ctor is actually wanting to
940 // look at the definition
941 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
942 let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id);
943 let item = lookup_item(node_id, cdata.data());
944 f(get_attributes(item));
947 pub fn get_struct_field_attrs(cdata: Cmd) -> HashMap<ast::NodeId, Vec<ast::Attribute>> {
948 let data = rbml::Doc::new(cdata.data());
949 let fields = reader::get_doc(data, tag_struct_fields);
950 let mut map = HashMap::new();
951 reader::tagged_docs(fields, tag_struct_field, |field| {
952 let id = reader::doc_as_u32(reader::get_doc(field, tag_struct_field_id));
953 let attrs = get_attributes(field);
954 map.insert(id, attrs);
960 fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
962 PublicField => ast::Public,
963 InheritedField => ast::Inherited,
968 pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
969 -> Vec<ty::field_ty> {
970 let data = cdata.data();
971 let item = lookup_item(id, data);
972 let mut result = Vec::new();
973 reader::tagged_docs(item, tag_item_field, |an_item| {
974 let f = item_family(an_item);
975 if f == PublicField || f == InheritedField {
976 // FIXME #6993: name should be of type Name, not Ident
977 let name = item_name(&*intr, an_item);
978 let did = item_def_id(an_item, cdata);
979 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
980 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
981 result.push(ty::field_ty {
984 vis: struct_field_family_to_visibility(f),
990 reader::tagged_docs(item, tag_item_unnamed_field, |an_item| {
991 let did = item_def_id(an_item, cdata);
992 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
993 let f = item_family(an_item);
994 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
995 result.push(ty::field_ty {
996 name: special_idents::unnamed_field.name,
998 vis: struct_field_family_to_visibility(f),
1006 fn get_meta_items(md: rbml::Doc) -> Vec<Gc<ast::MetaItem>> {
1007 let mut items: Vec<Gc<ast::MetaItem>> = Vec::new();
1008 reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
1009 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1010 let n = token::intern_and_get_ident(nd.as_str_slice());
1011 items.push(attr::mk_word_item(n));
1014 reader::tagged_docs(md, tag_meta_item_name_value, |meta_item_doc| {
1015 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1016 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1017 let n = token::intern_and_get_ident(nd.as_str_slice());
1018 let v = token::intern_and_get_ident(vd.as_str_slice());
1019 // FIXME (#623): Should be able to decode MetaNameValue variants,
1020 // but currently the encoder just drops them
1021 items.push(attr::mk_name_value_item_str(n, v));
1024 reader::tagged_docs(md, tag_meta_item_list, |meta_item_doc| {
1025 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1026 let n = token::intern_and_get_ident(nd.as_str_slice());
1027 let subitems = get_meta_items(meta_item_doc);
1028 items.push(attr::mk_list_item(n, subitems.move_iter().collect()));
1034 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1035 let mut attrs: Vec<ast::Attribute> = Vec::new();
1036 match reader::maybe_get_doc(md, tag_attributes) {
1038 reader::tagged_docs(attrs_d, tag_attribute, |attr_doc| {
1039 let is_sugared_doc = reader::doc_as_u8(
1040 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1042 let meta_items = get_meta_items(attr_doc);
1043 // Currently it's only possible to have a single meta item on
1045 assert_eq!(meta_items.len(), 1u);
1046 let meta_item = *meta_items.get(0);
1049 node: ast::Attribute_ {
1050 id: attr::mk_attr_id(),
1051 style: ast::AttrOuter,
1053 is_sugared_doc: is_sugared_doc,
1055 span: codemap::DUMMY_SP
1065 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1066 out: &mut io::Writer) -> io::IoResult<()> {
1067 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1069 let r = get_attributes(md);
1070 for attr in r.iter() {
1071 try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1077 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1078 get_attributes(rbml::Doc::new(data))
1082 pub struct CrateDep {
1083 pub cnum: ast::CrateNum,
1088 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1089 let mut deps: Vec<CrateDep> = Vec::new();
1090 let cratedoc = rbml::Doc::new(data);
1091 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1092 let mut crate_num = 1;
1093 fn docstr(doc: rbml::Doc, tag_: uint) -> String {
1094 let d = reader::get_doc(doc, tag_);
1095 d.as_str_slice().to_string()
1097 reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
1098 let name = docstr(depdoc, tag_crate_dep_crate_name);
1099 let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash).as_slice());
1100 deps.push(CrateDep {
1111 fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1112 try!(write!(out, "=External Dependencies=\n"));
1113 for dep in get_crate_deps(data).iter() {
1114 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1116 try!(write!(out, "\n"));
1120 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1121 let cratedoc = rbml::Doc::new(data);
1122 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1123 Svh::new(doc.as_str_slice())
1127 pub fn get_crate_hash(data: &[u8]) -> Svh {
1128 let cratedoc = rbml::Doc::new(data);
1129 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1130 Svh::new(hashdoc.as_str_slice())
1133 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1134 let cratedoc = rbml::Doc::new(data);
1135 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1136 doc.as_str_slice().to_string()
1140 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1141 let cratedoc = rbml::Doc::new(data);
1142 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1143 triple_doc.map(|s| s.as_str().to_string())
1146 pub fn get_crate_name(data: &[u8]) -> String {
1147 maybe_get_crate_name(data).expect("no crate name in crate")
1150 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1151 let hash = get_crate_hash(bytes);
1152 let md = rbml::Doc::new(bytes);
1153 try!(list_crate_attributes(md, &hash, out));
1154 list_crate_deps(bytes, out)
1157 // Translates a def_id from an external crate to a def_id for the current
1158 // compilation environment. We use this when trying to load types from
1159 // external crates - if those types further refer to types in other crates
1160 // then we must translate the crate number from that encoded in the external
1161 // crate to the correct local crate number.
1162 pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
1163 if did.krate == ast::LOCAL_CRATE {
1164 return ast::DefId { krate: cdata.cnum, node: did.node };
1167 match cdata.cnum_map.find(&did.krate) {
1174 None => fail!("didn't find a crate in the cnum_map")
1178 pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
1179 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1180 let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
1181 callback(item_def_id(impl_doc, cdata));
1186 pub fn each_implementation_for_type(cdata: Cmd,
1188 callback: |ast::DefId|) {
1189 let item_doc = lookup_item(id, cdata.data());
1190 reader::tagged_docs(item_doc,
1191 tag_items_data_item_inherent_impl,
1193 let implementation_def_id = item_def_id(impl_doc, cdata);
1194 callback(implementation_def_id);
1199 pub fn each_implementation_for_trait(cdata: Cmd,
1201 callback: |ast::DefId|) {
1202 let item_doc = lookup_item(id, cdata.data());
1204 let _ = reader::tagged_docs(item_doc,
1205 tag_items_data_item_extension_impl,
1207 let implementation_def_id = item_def_id(impl_doc, cdata);
1208 callback(implementation_def_id);
1213 pub fn get_trait_of_item(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
1214 -> Option<ast::DefId> {
1215 let item_doc = lookup_item(id, cdata.data());
1216 let parent_item_id = match item_parent_item(item_doc) {
1217 None => return None,
1218 Some(item_id) => item_id,
1220 let parent_item_id = translate_def_id(cdata, parent_item_id);
1221 let parent_item_doc = lookup_item(parent_item_id.node, cdata.data());
1222 match item_family(parent_item_doc) {
1223 Trait => Some(item_def_id(parent_item_doc, cdata)),
1225 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1226 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1233 pub fn get_native_libraries(cdata: Cmd)
1234 -> Vec<(cstore::NativeLibaryKind, String)> {
1235 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1236 tag_native_libraries);
1237 let mut result = Vec::new();
1238 reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
1239 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1240 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1241 let kind: cstore::NativeLibaryKind =
1242 FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1243 let name = name_doc.as_str().to_string();
1244 result.push((kind, name));
1250 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<ast::NodeId> {
1251 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1252 .map(|doc| FromPrimitive::from_u32(reader::doc_as_u32(doc)).unwrap())
1255 pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
1256 let macros = reader::get_doc(rbml::Doc::new(data),
1257 tag_exported_macros);
1258 let mut result = Vec::new();
1259 reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
1260 result.push(macro_doc.as_str().to_string());
1266 pub fn get_dylib_dependency_formats(cdata: Cmd)
1267 -> Vec<(ast::CrateNum, cstore::LinkagePreference)>
1269 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1270 tag_dylib_dependency_formats);
1271 let mut result = Vec::new();
1273 debug!("found dylib deps: {}", formats.as_str_slice());
1274 for spec in formats.as_str_slice().split(',') {
1275 if spec.len() == 0 { continue }
1276 let cnum = spec.split(':').nth(0).unwrap();
1277 let link = spec.split(':').nth(1).unwrap();
1278 let cnum = from_str(cnum).unwrap();
1279 let cnum = match cdata.cnum_map.find(&cnum) {
1281 None => fail!("didn't find a crate in the cnum_map")
1283 result.push((cnum, if link == "d" {
1284 cstore::RequireDynamic
1286 cstore::RequireStatic
1292 pub fn get_missing_lang_items(cdata: Cmd)
1293 -> Vec<lang_items::LangItem>
1295 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1296 let mut result = Vec::new();
1297 reader::tagged_docs(items, tag_lang_items_missing, |missing_doc| {
1298 let item: lang_items::LangItem =
1299 FromPrimitive::from_u32(reader::doc_as_u32(missing_doc)).unwrap();
1306 pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec<String> {
1307 let mut ret = Vec::new();
1308 let method_doc = lookup_item(id, cdata.data());
1309 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1311 reader::tagged_docs(args_doc, tag_method_argument_name, |name_doc| {
1312 ret.push(name_doc.as_str_slice().to_string());
1321 pub fn get_reachable_extern_fns(cdata: Cmd) -> Vec<ast::DefId> {
1322 let mut ret = Vec::new();
1323 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1324 tag_reachable_extern_fns);
1325 reader::tagged_docs(items, tag_reachable_extern_fn_id, |doc| {
1326 ret.push(ast::DefId {
1328 node: reader::doc_as_u32(doc),
1335 pub fn is_typedef(cdata: Cmd, id: ast::NodeId) -> bool {
1336 let item_doc = lookup_item(id, cdata.data());
1337 match item_family(item_doc) {
1343 fn doc_generics(base_doc: rbml::Doc,
1349 let doc = reader::get_doc(base_doc, tag);
1351 let mut types = subst::VecPerParamSpace::empty();
1352 reader::tagged_docs(doc, tag_type_param_def, |p| {
1353 let bd = parse_type_param_def_data(
1354 p.data, p.start, cdata.cnum, tcx,
1355 |_, did| translate_def_id(cdata, did));
1356 types.push(bd.space, bd);
1360 let mut regions = subst::VecPerParamSpace::empty();
1361 reader::tagged_docs(doc, tag_region_param_def, |rp_doc| {
1362 let ident_str_doc = reader::get_doc(rp_doc,
1363 tag_region_param_def_ident);
1364 let ident = item_name(&*token::get_ident_interner(), ident_str_doc);
1365 let def_id_doc = reader::get_doc(rp_doc,
1366 tag_region_param_def_def_id);
1367 let def_id = reader::with_doc_data(def_id_doc, parse_def_id);
1368 let def_id = translate_def_id(cdata, def_id);
1370 let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
1371 let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as uint);
1373 let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
1374 let index = reader::doc_as_u64(doc) as uint;
1376 let mut bounds = Vec::new();
1377 reader::tagged_docs(rp_doc, tag_items_data_region, |p| {
1380 p.data, cdata.cnum, p.start, tcx,
1381 |_, did| translate_def_id(cdata, did)));
1385 regions.push(space, ty::RegionParameterDef { name: ident.name,
1394 ty::Generics { types: types, regions: regions }