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_def_id,
22 parse_type_param_def_data,
23 parse_bare_fn_ty_data, parse_trait_ref_data};
24 use middle::lang_items;
27 use middle::ty::{ImplContainer, TraitContainer};
30 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;
51 pub type Cmd<'a> = &'a crate_metadata;
53 // A function that takes a def_id relative to the crate being searched and
54 // returns a def_id relative to the compilation environment, i.e. if we hit a
55 // def_id for an item defined in another crate, somebody needs to figure out
56 // what crate that's in and give us a def_id that makes sense for the current
59 fn lookup_hash<'a>(d: rbml::Doc<'a>, eq_fn: |&[u8]| -> bool,
60 hash: u64) -> Option<rbml::Doc<'a>> {
61 let index = reader::get_doc(d, tag_index);
62 let table = reader::get_doc(index, tag_index_table);
63 let hash_pos = table.start + (hash % 256 * 4) as uint;
64 let pos = u64_from_be_bytes(d.data, hash_pos, 4) as uint;
65 let tagged_doc = reader::doc_at(d.data, pos).unwrap();
67 let belt = tag_index_buckets_bucket_elt;
70 reader::tagged_docs(tagged_doc.doc, belt, |elt| {
71 let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint;
72 if eq_fn(elt.data.slice(elt.start + 4, elt.end)) {
73 ret = Some(reader::doc_at(d.data, pos).unwrap().doc);
82 pub fn maybe_find_item<'a>(item_id: ast::NodeId,
83 items: rbml::Doc<'a>) -> Option<rbml::Doc<'a>> {
84 fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
85 return u64_from_be_bytes(
86 bytes.slice(0u, 4u), 0u, 4u) as ast::NodeId
90 |a| eq_item(a, item_id),
91 hash::hash(&(item_id as i64)))
94 fn find_item<'a>(item_id: ast::NodeId, items: rbml::Doc<'a>) -> rbml::Doc<'a> {
95 match maybe_find_item(item_id, items) {
96 None => fail!("lookup_item: id not found: {}", item_id),
101 // Looks up an item in the given metadata and returns an rbml doc pointing
103 fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> rbml::Doc<'a> {
104 let items = reader::get_doc(rbml::Doc::new(data), tag_items);
105 find_item(item_id, items)
108 #[deriving(PartialEq)]
115 UnsafeStaticMethod, // U
130 fn item_family(item: rbml::Doc) -> Family {
131 let fam = reader::get_doc(item, tag_items_data_item_family);
132 match reader::doc_as_u8(fam) as char {
138 'U' => UnsafeStaticMethod,
145 'V' => StructVariant,
150 'N' => InheritedField,
151 c => fail!("unexpected family char: {}", c)
155 fn item_visibility(item: rbml::Doc) -> ast::Visibility {
156 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
158 Some(visibility_doc) => {
159 match reader::doc_as_u8(visibility_doc) as char {
161 'i' => ast::Inherited,
162 _ => fail!("unknown visibility character")
168 fn item_method_sort(item: rbml::Doc) -> char {
170 reader::tagged_docs(item, tag_item_trait_method_sort, |doc| {
171 ret = doc.as_str_slice().as_bytes()[0] as char;
177 fn item_symbol(item: rbml::Doc) -> String {
178 reader::get_doc(item, tag_items_data_item_symbol).as_str().to_string()
181 fn item_parent_item(d: rbml::Doc) -> Option<ast::DefId> {
183 reader::tagged_docs(d, tag_items_data_parent_item, |did| {
184 ret = Some(reader::with_doc_data(did, parse_def_id));
190 fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
191 d: rbml::Doc) -> ast::DefId {
192 let trait_did = item_parent_item(d).expect("item without parent");
193 ast::DefId { krate: cnum, node: trait_did.node }
196 fn item_def_id(d: rbml::Doc, cdata: Cmd) -> ast::DefId {
197 let tagdoc = reader::get_doc(d, tag_def_id);
198 return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
201 fn get_provided_source(d: rbml::Doc, cdata: Cmd) -> Option<ast::DefId> {
202 reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
203 translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
207 fn each_reexport(d: rbml::Doc, f: |rbml::Doc| -> bool) -> bool {
208 reader::tagged_docs(d, tag_items_data_item_reexport, f)
211 fn variant_disr_val(d: rbml::Doc) -> Option<ty::Disr> {
212 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
213 reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
217 fn doc_type(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
218 let tp = reader::get_doc(doc, tag_items_data_item_type);
219 parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
220 |_, did| translate_def_id(cdata, did))
223 fn doc_method_fty(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
224 let tp = reader::get_doc(doc, tag_item_method_fty);
225 parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
226 |_, did| translate_def_id(cdata, did))
229 pub fn item_type(_item_id: ast::DefId, item: rbml::Doc,
230 tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
231 doc_type(item, tcx, cdata)
234 fn doc_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
235 parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
236 |_, did| translate_def_id(cdata, did))
239 fn item_trait_ref(doc: rbml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
240 let tp = reader::get_doc(doc, tag_item_trait_ref);
241 doc_trait_ref(tp, tcx, cdata)
244 fn item_ty_param_defs(item: rbml::Doc,
248 -> subst::VecPerParamSpace<ty::TypeParameterDef> {
249 let mut bounds = subst::VecPerParamSpace::empty();
250 reader::tagged_docs(item, tag, |p| {
251 let bd = parse_type_param_def_data(
252 p.data, p.start, cdata.cnum, tcx,
253 |_, did| translate_def_id(cdata, did));
254 bounds.push(bd.space, bd);
260 fn item_region_param_defs(item_doc: rbml::Doc, cdata: Cmd)
261 -> subst::VecPerParamSpace<ty::RegionParameterDef>
263 let mut v = subst::VecPerParamSpace::empty();
264 reader::tagged_docs(item_doc, tag_region_param_def, |rp_doc| {
265 let ident_str_doc = reader::get_doc(rp_doc,
266 tag_region_param_def_ident);
267 let ident = item_name(&*token::get_ident_interner(), ident_str_doc);
268 let def_id_doc = reader::get_doc(rp_doc,
269 tag_region_param_def_def_id);
270 let def_id = reader::with_doc_data(def_id_doc, parse_def_id);
271 let def_id = translate_def_id(cdata, def_id);
273 let doc = reader::get_doc(rp_doc, tag_region_param_def_space);
274 let space = subst::ParamSpace::from_uint(reader::doc_as_u64(doc) as uint);
276 let doc = reader::get_doc(rp_doc, tag_region_param_def_index);
277 let index = reader::doc_as_u64(doc) as uint;
279 v.push(space, ty::RegionParameterDef { name: ident.name,
288 fn enum_variant_ids(item: rbml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
289 let mut ids: Vec<ast::DefId> = Vec::new();
290 let v = tag_items_data_item_variant;
291 reader::tagged_docs(item, v, |p| {
292 let ext = reader::with_doc_data(p, parse_def_id);
293 ids.push(ast::DefId { krate: cdata.cnum, node: ext.node });
299 fn item_path(item_doc: rbml::Doc) -> Vec<ast_map::PathElem> {
300 let path_doc = reader::get_doc(item_doc, tag_path);
302 let len_doc = reader::get_doc(path_doc, tag_path_len);
303 let len = reader::doc_as_u32(len_doc) as uint;
305 let mut result = Vec::with_capacity(len);
306 reader::docs(path_doc, |tag, elt_doc| {
307 if tag == tag_path_elem_mod {
308 let s = elt_doc.as_str_slice();
309 result.push(ast_map::PathMod(token::intern(s)));
310 } else if tag == tag_path_elem_name {
311 let s = elt_doc.as_str_slice();
312 result.push(ast_map::PathName(token::intern(s)));
314 // ignore tag_path_len element
322 fn item_name(intr: &IdentInterner, item: rbml::Doc) -> ast::Ident {
323 let name = reader::get_doc(item, tag_paths_data_name);
324 let string = name.as_str_slice();
325 match intr.find_equiv(&string) {
326 None => token::str_to_ident(string),
327 Some(val) => ast::Ident::new(val),
331 fn item_to_def_like(item: rbml::Doc, did: ast::DefId, cnum: ast::CrateNum)
333 let fam = item_family(item);
335 ImmStatic => DlDef(def::DefStatic(did, false)),
336 MutStatic => DlDef(def::DefStatic(did, true)),
337 Struct => DlDef(def::DefStruct(did)),
338 UnsafeFn => DlDef(def::DefFn(did, ast::UnsafeFn)),
339 Fn => DlDef(def::DefFn(did, ast::NormalFn)),
340 StaticMethod | UnsafeStaticMethod => {
341 let fn_style = if fam == UnsafeStaticMethod { ast::UnsafeFn } else
343 // def_static_method carries an optional field of its enclosing
344 // trait or enclosing impl (if this is an inherent static method).
345 // So we need to detect whether this is in a trait or not, which
346 // we do through the mildly hacky way of checking whether there is
347 // a trait_method_sort.
348 let provenance = if reader::maybe_get_doc(
349 item, tag_item_trait_method_sort).is_some() {
350 def::FromTrait(item_reqd_and_translated_parent_item(cnum,
353 def::FromImpl(item_reqd_and_translated_parent_item(cnum,
356 DlDef(def::DefStaticMethod(did, provenance, fn_style))
358 Type | ForeignType => DlDef(def::DefTy(did)),
359 Mod => DlDef(def::DefMod(did)),
360 ForeignMod => DlDef(def::DefForeignMod(did)),
362 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
363 DlDef(def::DefVariant(enum_did, did, true))
366 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
367 DlDef(def::DefVariant(enum_did, did, false))
369 Trait => DlDef(def::DefTrait(did)),
370 Enum => DlDef(def::DefTy(did)),
372 PublicField | InheritedField => DlField,
376 pub fn get_trait_def(cdata: Cmd,
377 item_id: ast::NodeId,
378 tcx: &ty::ctxt) -> ty::TraitDef
380 let item_doc = lookup_item(item_id, cdata.data());
381 let tp_defs = item_ty_param_defs(item_doc, tcx, cdata,
382 tag_items_data_item_ty_param_bounds);
383 let rp_defs = item_region_param_defs(item_doc, cdata);
384 let mut bounds = ty::empty_builtin_bounds();
385 // Collect the builtin bounds from the encoded supertraits.
386 // FIXME(#8559): They should be encoded directly.
387 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
388 // NB. Bypasses real supertraits. See get_supertraits() if you wanted them.
389 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
390 tcx.lang_items.to_builtin_kind(trait_ref.def_id).map(|bound| {
397 generics: ty::Generics {types: tp_defs,
400 trait_ref: Rc::new(item_trait_ref(item_doc, tcx, cdata))
404 pub fn get_type(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
407 let item = lookup_item(id, cdata.data());
409 let t = item_type(ast::DefId { krate: cdata.cnum, node: id }, item, tcx,
412 let tp_defs = item_ty_param_defs(item, tcx, cdata, tag_items_data_item_ty_param_bounds);
413 let rp_defs = item_region_param_defs(item, cdata);
416 generics: ty::Generics {types: tp_defs,
422 pub fn get_stability(cdata: Cmd, id: ast::NodeId) -> Option<attr::Stability> {
423 let item = lookup_item(id, cdata.data());
424 reader::maybe_get_doc(item, tag_items_data_item_stability).map(|doc| {
425 let mut decoder = reader::Decoder::new(doc);
426 Decodable::decode(&mut decoder).unwrap()
430 pub fn get_impl_trait(cdata: Cmd,
432 tcx: &ty::ctxt) -> Option<Rc<ty::TraitRef>>
434 let item_doc = lookup_item(id, cdata.data());
435 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
436 Rc::new(doc_trait_ref(tp, tcx, cdata))
440 pub fn get_impl_vtables(cdata: Cmd,
443 -> typeck::vtable_res
445 let item_doc = lookup_item(id, cdata.data());
446 let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables);
447 let mut decoder = reader::Decoder::new(vtables_doc);
448 decoder.read_vtable_res(tcx, cdata)
452 pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String {
453 return item_symbol(lookup_item(id, data));
456 // Something that a name can resolve to.
464 /// Iterates over the language items in the given crate.
465 pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
466 let root = rbml::Doc::new(cdata.data());
467 let lang_items = reader::get_doc(root, tag_lang_items);
468 reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
469 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
470 let id = reader::doc_as_u32(id_doc) as uint;
471 let node_id_doc = reader::get_doc(item_doc,
472 tag_lang_items_item_node_id);
473 let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
479 pub type GetCrateDataCb<'a> = |ast::CrateNum|: 'a -> Rc<crate_metadata>;
481 fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
484 get_crate_data: GetCrateDataCb,
488 // Iterate over all children.
489 let _ = reader::tagged_docs(item_doc, tag_mod_child, |child_info_doc| {
490 let child_def_id = reader::with_doc_data(child_info_doc,
492 let child_def_id = translate_def_id(cdata, child_def_id);
494 // This item may be in yet another crate if it was the child of a
496 let crate_data = if child_def_id.krate == cdata.cnum {
499 Some(get_crate_data(child_def_id.krate))
501 let crate_data = match crate_data {
502 Some(ref cdata) => &**cdata,
506 let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
509 match maybe_find_item(child_def_id.node, other_crates_items) {
511 Some(child_item_doc) => {
512 // Hand off the item to the callback.
513 let child_name = item_name(&*intr, child_item_doc);
514 let def_like = item_to_def_like(child_item_doc,
517 let visibility = item_visibility(child_item_doc);
518 callback(def_like, child_name, visibility);
526 // As a special case, iterate over all static methods of
527 // associated implementations too. This is a bit of a botch.
529 let _ = reader::tagged_docs(item_doc,
530 tag_items_data_item_inherent_impl,
531 |inherent_impl_def_id_doc| {
532 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
534 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_items);
535 match maybe_find_item(inherent_impl_def_id.node, items) {
537 Some(inherent_impl_doc) => {
538 let _ = reader::tagged_docs(inherent_impl_doc,
539 tag_item_impl_method,
540 |impl_method_def_id_doc| {
541 let impl_method_def_id =
542 reader::with_doc_data(impl_method_def_id_doc,
544 let impl_method_def_id =
545 translate_def_id(cdata, impl_method_def_id);
546 match maybe_find_item(impl_method_def_id.node, items) {
548 Some(impl_method_doc) => {
549 match item_family(impl_method_doc) {
550 StaticMethod | UnsafeStaticMethod => {
551 // Hand off the static method
553 let static_method_name =
554 item_name(&*intr, impl_method_doc);
555 let static_method_def_like =
556 item_to_def_like(impl_method_doc,
559 callback(static_method_def_like,
561 item_visibility(impl_method_doc));
576 // Iterate over all reexports.
577 let _ = each_reexport(item_doc, |reexport_doc| {
578 let def_id_doc = reader::get_doc(reexport_doc,
579 tag_items_data_item_reexport_def_id);
580 let child_def_id = reader::with_doc_data(def_id_doc,
582 let child_def_id = translate_def_id(cdata, child_def_id);
584 let name_doc = reader::get_doc(reexport_doc,
585 tag_items_data_item_reexport_name);
586 let name = name_doc.as_str_slice();
588 // This reexport may be in yet another crate.
589 let crate_data = if child_def_id.krate == cdata.cnum {
592 Some(get_crate_data(child_def_id.krate))
594 let crate_data = match crate_data {
595 Some(ref cdata) => &**cdata,
599 let other_crates_items = reader::get_doc(rbml::Doc::new(crate_data.data()), tag_items);
602 match maybe_find_item(child_def_id.node, other_crates_items) {
604 Some(child_item_doc) => {
605 // Hand off the item to the callback.
606 let def_like = item_to_def_like(child_item_doc,
609 // These items have a public visibility because they're part of
610 // a public re-export.
611 callback(def_like, token::str_to_ident(name), ast::Public);
619 /// Iterates over each child of the given item.
620 pub fn each_child_of_item(intr: Rc<IdentInterner>,
623 get_crate_data: GetCrateDataCb,
624 callback: |DefLike, ast::Ident, ast::Visibility|) {
626 let root_doc = rbml::Doc::new(cdata.data());
627 let items = reader::get_doc(root_doc, tag_items);
628 let item_doc = match maybe_find_item(id, items) {
630 Some(item_doc) => item_doc,
633 each_child_of_item_or_crate(intr,
640 /// Iterates over all the top-level crate items.
641 pub fn each_top_level_item_of_crate(intr: Rc<IdentInterner>,
643 get_crate_data: GetCrateDataCb,
647 let root_doc = rbml::Doc::new(cdata.data());
648 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
649 let crate_items_doc = reader::get_doc(misc_info_doc,
650 tag_misc_info_crate_items);
652 each_child_of_item_or_crate(intr,
659 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
660 item_path(lookup_item(id, cdata.data()))
663 pub type DecodeInlinedItem<'a> = |cdata: Cmd,
665 path: Vec<ast_map::PathElem>,
666 par_doc: rbml::Doc|: 'a
667 -> Result<ast::InlinedItem, Vec<ast_map::PathElem> >;
669 pub fn maybe_get_item_ast(cdata: Cmd, tcx: &ty::ctxt, id: ast::NodeId,
670 decode_inlined_item: DecodeInlinedItem)
671 -> csearch::found_ast {
672 debug!("Looking up item: {}", id);
673 let item_doc = lookup_item(id, cdata.data());
674 let path = Vec::from_slice(item_path(item_doc).init());
675 match decode_inlined_item(cdata, tcx, path, item_doc) {
676 Ok(ref ii) => csearch::found(*ii),
678 match item_parent_item(item_doc) {
680 let did = translate_def_id(cdata, did);
681 let parent_item = lookup_item(did.node, cdata.data());
682 match decode_inlined_item(cdata, tcx, path, parent_item) {
683 Ok(ref ii) => csearch::found_parent(did, *ii),
684 Err(_) => csearch::not_found
687 None => csearch::not_found
693 pub fn get_enum_variants(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
694 tcx: &ty::ctxt) -> Vec<Rc<ty::VariantInfo>> {
695 let data = cdata.data();
696 let items = reader::get_doc(rbml::Doc::new(data), tag_items);
697 let item = find_item(id, items);
698 let mut disr_val = 0;
699 enum_variant_ids(item, cdata).iter().map(|did| {
700 let item = find_item(did.node, items);
701 let ctor_ty = item_type(ast::DefId { krate: cdata.cnum, node: id},
703 let name = item_name(&*intr, item);
704 let arg_tys = match ty::get(ctor_ty).sty {
705 ty::ty_bare_fn(ref f) => f.sig.inputs.clone(),
706 _ => Vec::new(), // Nullary enum variant.
708 match variant_disr_val(item) {
709 Some(val) => { disr_val = val; }
712 let old_disr_val = disr_val;
714 Rc::new(ty::VariantInfo {
719 // I'm not even sure if we encode visibility
720 // for variants -- TEST -- tjc
722 disr_val: old_disr_val,
728 fn get_explicit_self(item: rbml::Doc) -> ty::ExplicitSelfCategory {
729 fn get_mutability(ch: u8) -> ast::Mutability {
731 'i' => ast::MutImmutable,
732 'm' => ast::MutMutable,
733 _ => fail!("unknown mutability character: `{}`", ch as char),
737 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
738 let string = explicit_self_doc.as_str_slice();
740 let explicit_self_kind = string.as_bytes()[0];
741 match explicit_self_kind as char {
742 's' => ty::StaticExplicitSelfCategory,
743 'v' => ty::ByValueExplicitSelfCategory,
744 '~' => ty::ByBoxExplicitSelfCategory,
745 // FIXME(#4846) expl. region
747 ty::ByReferenceExplicitSelfCategory(
749 get_mutability(string.as_bytes()[1]))
751 _ => fail!("unknown self type code: `{}`", explicit_self_kind as char)
755 /// Returns information about the given implementation.
756 pub fn get_impl_methods(cdata: Cmd, impl_id: ast::NodeId) -> Vec<ast::DefId> {
757 let mut methods = Vec::new();
758 reader::tagged_docs(lookup_item(impl_id, cdata.data()),
759 tag_item_impl_method, |doc| {
760 let m_did = reader::with_doc_data(doc, parse_def_id);
761 methods.push(translate_def_id(cdata, m_did));
768 pub fn get_method_name_and_explicit_self(intr: Rc<IdentInterner>,
772 ty::ExplicitSelfCategory) {
773 let method_doc = lookup_item(id, cdata.data());
774 let name = item_name(&*intr, method_doc);
775 let explicit_self = get_explicit_self(method_doc);
776 (name, explicit_self)
779 pub fn get_method(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
780 tcx: &ty::ctxt) -> ty::Method
782 let method_doc = lookup_item(id, cdata.data());
783 let def_id = item_def_id(method_doc, cdata);
785 let container_id = item_reqd_and_translated_parent_item(cdata.cnum,
787 let container_doc = lookup_item(container_id.node, cdata.data());
788 let container = match item_family(container_doc) {
789 Trait => TraitContainer(container_id),
790 _ => ImplContainer(container_id),
793 let name = item_name(&*intr, method_doc);
794 let type_param_defs = item_ty_param_defs(method_doc, tcx, cdata,
795 tag_item_method_tps);
796 let rp_defs = item_region_param_defs(method_doc, cdata);
797 let fty = doc_method_fty(method_doc, tcx, cdata);
798 let vis = item_visibility(method_doc);
799 let explicit_self = get_explicit_self(method_doc);
800 let provided_source = get_provided_source(method_doc, cdata);
805 types: type_param_defs,
817 pub fn get_trait_method_def_ids(cdata: Cmd,
818 id: ast::NodeId) -> Vec<ast::DefId> {
819 let data = cdata.data();
820 let item = lookup_item(id, data);
821 let mut result = Vec::new();
822 reader::tagged_docs(item, tag_item_trait_method, |mth| {
823 result.push(item_def_id(mth, cdata));
829 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
830 let data = cdata.data();
831 let item_doc = lookup_item(id, data);
832 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
833 let mut decoder = reader::Decoder::new(variance_doc);
834 Decodable::decode(&mut decoder).unwrap()
837 pub fn get_provided_trait_methods(intr: Rc<IdentInterner>, cdata: Cmd,
838 id: ast::NodeId, tcx: &ty::ctxt)
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_method, |mth_id| {
845 let did = item_def_id(mth_id, cdata);
846 let mth = lookup_item(did.node, data);
848 if item_method_sort(mth) == 'p' {
849 result.push(Rc::new(get_method(intr.clone(), cdata, did.node, tcx)));
857 /// Returns the supertraits of the given trait.
858 pub fn get_supertraits(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
859 -> Vec<Rc<ty::TraitRef>> {
860 let mut results = Vec::new();
861 let item_doc = lookup_item(id, cdata.data());
862 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
863 // NB. Only reads the ones that *aren't* builtin-bounds. See also
864 // get_trait_def() for collecting the builtin bounds.
865 // FIXME(#8559): The builtin bounds shouldn't be encoded in the first place.
866 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
867 if tcx.lang_items.to_builtin_kind(trait_ref.def_id).is_none() {
868 results.push(Rc::new(trait_ref));
875 pub fn get_type_name_if_impl(cdata: Cmd,
876 node_id: ast::NodeId) -> Option<ast::Ident> {
877 let item = lookup_item(node_id, cdata.data());
878 if item_family(item) != Impl {
883 reader::tagged_docs(item, tag_item_impl_type_basename, |doc| {
884 ret = Some(token::str_to_ident(doc.as_str_slice()));
891 pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
893 node_id: ast::NodeId)
894 -> Option<Vec<StaticMethodInfo> > {
895 let item = lookup_item(node_id, cdata.data());
896 if item_family(item) != Impl {
900 // If this impl implements a trait, don't consider it.
901 let ret = reader::tagged_docs(item, tag_item_trait_ref, |_doc| {
905 if !ret { return None }
907 let mut impl_method_ids = Vec::new();
908 reader::tagged_docs(item, tag_item_impl_method, |impl_method_doc| {
909 impl_method_ids.push(reader::with_doc_data(impl_method_doc, parse_def_id));
913 let mut static_impl_methods = Vec::new();
914 for impl_method_id in impl_method_ids.iter() {
915 let impl_method_doc = lookup_item(impl_method_id.node, cdata.data());
916 let family = item_family(impl_method_doc);
918 StaticMethod | UnsafeStaticMethod => {
920 match item_family(impl_method_doc) {
921 StaticMethod => fn_style = ast::NormalFn,
922 UnsafeStaticMethod => fn_style = ast::UnsafeFn,
926 static_impl_methods.push(StaticMethodInfo {
927 ident: item_name(&*intr, impl_method_doc),
928 def_id: item_def_id(impl_method_doc, cdata),
930 vis: item_visibility(impl_method_doc),
937 return Some(static_impl_methods);
940 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
941 /// the actual type definition, otherwise, return None
942 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
943 node_id: ast::NodeId)
944 -> Option<ast::DefId>
946 let item = lookup_item(node_id, cdata.data());
948 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
949 ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
955 pub fn get_item_attrs(cdata: Cmd,
956 orig_node_id: ast::NodeId,
957 f: |Vec<ast::Attribute>|) {
958 // The attributes for a tuple struct are attached to the definition, not the ctor;
959 // we assume that someone passing in a tuple struct ctor is actually wanting to
960 // look at the definition
961 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
962 let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id);
963 let item = lookup_item(node_id, cdata.data());
964 f(get_attributes(item));
967 pub fn get_struct_field_attrs(cdata: Cmd) -> HashMap<ast::NodeId, Vec<ast::Attribute>> {
968 let data = rbml::Doc::new(cdata.data());
969 let fields = reader::get_doc(data, tag_struct_fields);
970 let mut map = HashMap::new();
971 reader::tagged_docs(fields, tag_struct_field, |field| {
972 let id = reader::doc_as_u32(reader::get_doc(field, tag_struct_field_id));
973 let attrs = get_attributes(field);
974 map.insert(id, attrs);
980 fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
982 PublicField => ast::Public,
983 InheritedField => ast::Inherited,
988 pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
989 -> Vec<ty::field_ty> {
990 let data = cdata.data();
991 let item = lookup_item(id, data);
992 let mut result = Vec::new();
993 reader::tagged_docs(item, tag_item_field, |an_item| {
994 let f = item_family(an_item);
995 if f == PublicField || f == InheritedField {
996 // FIXME #6993: name should be of type Name, not Ident
997 let name = item_name(&*intr, an_item);
998 let did = item_def_id(an_item, cdata);
999 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
1000 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
1001 result.push(ty::field_ty {
1004 vis: struct_field_family_to_visibility(f),
1010 reader::tagged_docs(item, tag_item_unnamed_field, |an_item| {
1011 let did = item_def_id(an_item, cdata);
1012 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
1013 let f = item_family(an_item);
1014 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
1015 result.push(ty::field_ty {
1016 name: special_idents::unnamed_field.name,
1018 vis: struct_field_family_to_visibility(f),
1026 fn get_meta_items(md: rbml::Doc) -> Vec<Gc<ast::MetaItem>> {
1027 let mut items: Vec<Gc<ast::MetaItem>> = Vec::new();
1028 reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
1029 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1030 let n = token::intern_and_get_ident(nd.as_str_slice());
1031 items.push(attr::mk_word_item(n));
1034 reader::tagged_docs(md, tag_meta_item_name_value, |meta_item_doc| {
1035 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1036 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1037 let n = token::intern_and_get_ident(nd.as_str_slice());
1038 let v = token::intern_and_get_ident(vd.as_str_slice());
1039 // FIXME (#623): Should be able to decode MetaNameValue variants,
1040 // but currently the encoder just drops them
1041 items.push(attr::mk_name_value_item_str(n, v));
1044 reader::tagged_docs(md, tag_meta_item_list, |meta_item_doc| {
1045 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1046 let n = token::intern_and_get_ident(nd.as_str_slice());
1047 let subitems = get_meta_items(meta_item_doc);
1048 items.push(attr::mk_list_item(n, subitems.move_iter().collect()));
1054 fn get_attributes(md: rbml::Doc) -> Vec<ast::Attribute> {
1055 let mut attrs: Vec<ast::Attribute> = Vec::new();
1056 match reader::maybe_get_doc(md, tag_attributes) {
1058 reader::tagged_docs(attrs_d, tag_attribute, |attr_doc| {
1059 let is_sugared_doc = reader::doc_as_u8(
1060 reader::get_doc(attr_doc, tag_attribute_is_sugared_doc)
1062 let meta_items = get_meta_items(attr_doc);
1063 // Currently it's only possible to have a single meta item on
1065 assert_eq!(meta_items.len(), 1u);
1066 let meta_item = *meta_items.get(0);
1069 node: ast::Attribute_ {
1070 id: attr::mk_attr_id(),
1071 style: ast::AttrOuter,
1073 is_sugared_doc: is_sugared_doc,
1075 span: codemap::DUMMY_SP
1085 fn list_crate_attributes(md: rbml::Doc, hash: &Svh,
1086 out: &mut io::Writer) -> io::IoResult<()> {
1087 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1089 let r = get_attributes(md);
1090 for attr in r.iter() {
1091 try!(write!(out, "{}\n", pprust::attribute_to_string(attr)));
1097 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1098 get_attributes(rbml::Doc::new(data))
1102 pub struct CrateDep {
1103 pub cnum: ast::CrateNum,
1108 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1109 let mut deps: Vec<CrateDep> = Vec::new();
1110 let cratedoc = rbml::Doc::new(data);
1111 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1112 let mut crate_num = 1;
1113 fn docstr(doc: rbml::Doc, tag_: uint) -> String {
1114 let d = reader::get_doc(doc, tag_);
1115 d.as_str_slice().to_string()
1117 reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
1118 let name = docstr(depdoc, tag_crate_dep_crate_name);
1119 let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash).as_slice());
1120 deps.push(CrateDep {
1131 fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1132 try!(write!(out, "=External Dependencies=\n"));
1133 for dep in get_crate_deps(data).iter() {
1134 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.name, dep.hash));
1136 try!(write!(out, "\n"));
1140 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1141 let cratedoc = rbml::Doc::new(data);
1142 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1143 Svh::new(doc.as_str_slice())
1147 pub fn get_crate_hash(data: &[u8]) -> Svh {
1148 let cratedoc = rbml::Doc::new(data);
1149 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1150 Svh::new(hashdoc.as_str_slice())
1153 pub fn maybe_get_crate_name(data: &[u8]) -> Option<String> {
1154 let cratedoc = rbml::Doc::new(data);
1155 reader::maybe_get_doc(cratedoc, tag_crate_crate_name).map(|doc| {
1156 doc.as_str_slice().to_string()
1160 pub fn get_crate_triple(data: &[u8]) -> Option<String> {
1161 let cratedoc = rbml::Doc::new(data);
1162 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1163 triple_doc.map(|s| s.as_str().to_string())
1166 pub fn get_crate_name(data: &[u8]) -> String {
1167 maybe_get_crate_name(data).expect("no crate name in crate")
1170 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1171 let hash = get_crate_hash(bytes);
1172 let md = rbml::Doc::new(bytes);
1173 try!(list_crate_attributes(md, &hash, out));
1174 list_crate_deps(bytes, out)
1177 // Translates a def_id from an external crate to a def_id for the current
1178 // compilation environment. We use this when trying to load types from
1179 // external crates - if those types further refer to types in other crates
1180 // then we must translate the crate number from that encoded in the external
1181 // crate to the correct local crate number.
1182 pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
1183 if did.krate == ast::LOCAL_CRATE {
1184 return ast::DefId { krate: cdata.cnum, node: did.node };
1187 match cdata.cnum_map.find(&did.krate) {
1194 None => fail!("didn't find a crate in the cnum_map")
1198 pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
1199 let impls_doc = reader::get_doc(rbml::Doc::new(cdata.data()), tag_impls);
1200 let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
1201 callback(item_def_id(impl_doc, cdata));
1206 pub fn each_implementation_for_type(cdata: Cmd,
1208 callback: |ast::DefId|) {
1209 let item_doc = lookup_item(id, cdata.data());
1210 reader::tagged_docs(item_doc,
1211 tag_items_data_item_inherent_impl,
1213 let implementation_def_id = item_def_id(impl_doc, cdata);
1214 callback(implementation_def_id);
1219 pub fn each_implementation_for_trait(cdata: Cmd,
1221 callback: |ast::DefId|) {
1222 let item_doc = lookup_item(id, cdata.data());
1224 let _ = reader::tagged_docs(item_doc,
1225 tag_items_data_item_extension_impl,
1227 let implementation_def_id = item_def_id(impl_doc, cdata);
1228 callback(implementation_def_id);
1233 pub fn get_trait_of_method(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
1234 -> Option<ast::DefId> {
1235 let item_doc = lookup_item(id, cdata.data());
1236 let parent_item_id = match item_parent_item(item_doc) {
1237 None => return None,
1238 Some(item_id) => item_id,
1240 let parent_item_id = translate_def_id(cdata, parent_item_id);
1241 let parent_item_doc = lookup_item(parent_item_id.node, cdata.data());
1242 match item_family(parent_item_doc) {
1243 Trait => Some(item_def_id(parent_item_doc, cdata)),
1245 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1246 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1253 pub fn get_native_libraries(cdata: Cmd)
1254 -> Vec<(cstore::NativeLibaryKind, String)> {
1255 let libraries = reader::get_doc(rbml::Doc::new(cdata.data()),
1256 tag_native_libraries);
1257 let mut result = Vec::new();
1258 reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
1259 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1260 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1261 let kind: cstore::NativeLibaryKind =
1262 FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1263 let name = name_doc.as_str().to_string();
1264 result.push((kind, name));
1270 pub fn get_plugin_registrar_fn(data: &[u8]) -> Option<ast::NodeId> {
1271 reader::maybe_get_doc(rbml::Doc::new(data), tag_plugin_registrar_fn)
1272 .map(|doc| FromPrimitive::from_u32(reader::doc_as_u32(doc)).unwrap())
1275 pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
1276 let macros = reader::get_doc(rbml::Doc::new(data),
1277 tag_exported_macros);
1278 let mut result = Vec::new();
1279 reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
1280 result.push(macro_doc.as_str().to_string());
1286 pub fn get_dylib_dependency_formats(cdata: Cmd)
1287 -> Vec<(ast::CrateNum, cstore::LinkagePreference)>
1289 let formats = reader::get_doc(rbml::Doc::new(cdata.data()),
1290 tag_dylib_dependency_formats);
1291 let mut result = Vec::new();
1293 debug!("found dylib deps: {}", formats.as_str_slice());
1294 for spec in formats.as_str_slice().split(',') {
1295 if spec.len() == 0 { continue }
1296 let cnum = spec.split(':').nth(0).unwrap();
1297 let link = spec.split(':').nth(1).unwrap();
1298 let cnum = from_str(cnum).unwrap();
1299 let cnum = match cdata.cnum_map.find(&cnum) {
1301 None => fail!("didn't find a crate in the cnum_map")
1303 result.push((cnum, if link == "d" {
1304 cstore::RequireDynamic
1306 cstore::RequireStatic
1312 pub fn get_missing_lang_items(cdata: Cmd)
1313 -> Vec<lang_items::LangItem>
1315 let items = reader::get_doc(rbml::Doc::new(cdata.data()), tag_lang_items);
1316 let mut result = Vec::new();
1317 reader::tagged_docs(items, tag_lang_items_missing, |missing_doc| {
1318 let item: lang_items::LangItem =
1319 FromPrimitive::from_u32(reader::doc_as_u32(missing_doc)).unwrap();
1326 pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec<String> {
1327 let mut ret = Vec::new();
1328 let method_doc = lookup_item(id, cdata.data());
1329 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1331 reader::tagged_docs(args_doc, tag_method_argument_name, |name_doc| {
1332 ret.push(name_doc.as_str_slice().to_string());
1341 pub fn get_reachable_extern_fns(cdata: Cmd) -> Vec<ast::DefId> {
1342 let mut ret = Vec::new();
1343 let items = reader::get_doc(rbml::Doc::new(cdata.data()),
1344 tag_reachable_extern_fns);
1345 reader::tagged_docs(items, tag_reachable_extern_fn_id, |doc| {
1346 ret.push(ast::DefId {
1348 node: reader::doc_as_u32(doc),
1355 pub fn is_typedef(cdata: Cmd, id: ast::NodeId) -> bool {
1356 let item_doc = lookup_item(id, cdata.data());
1357 match item_family(item_doc) {