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::ty::{ImplContainer, TraitContainer};
27 use middle::astencode::vtable_decoder_helpers;
33 use std::io::extensions::u64_from_be_bytes;
36 use serialize::ebml::reader;
38 use serialize::Decodable;
41 use syntax::parse::token::{IdentInterner, special_idents};
42 use syntax::parse::token;
43 use syntax::print::pprust;
46 use syntax::crateid::CrateId;
48 pub type Cmd = @crate_metadata;
50 // FIXME: remove unwrap_ after a snapshot
52 fn unwrap_<T>(t: T) -> T {
57 fn unwrap_<T, E>(r: Result<T, E>) -> T {
61 // A function that takes a def_id relative to the crate being searched and
62 // returns a def_id relative to the compilation environment, i.e. if we hit a
63 // def_id for an item defined in another crate, somebody needs to figure out
64 // what crate that's in and give us a def_id that makes sense for the current
67 fn lookup_hash<'a>(d: ebml::Doc<'a>, eq_fn: |&[u8]| -> bool,
68 hash: u64) -> Option<ebml::Doc<'a>> {
69 let index = reader::get_doc(d, tag_index);
70 let table = reader::get_doc(index, tag_index_table);
71 let hash_pos = table.start + (hash % 256 * 4) as uint;
72 let pos = u64_from_be_bytes(d.data, hash_pos, 4) as uint;
73 let tagged_doc = unwrap_(reader::doc_at(d.data, pos));
75 let belt = tag_index_buckets_bucket_elt;
78 reader::tagged_docs(tagged_doc.doc, belt, |elt| {
79 let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint;
80 if eq_fn(elt.data.slice(elt.start + 4, elt.end)) {
81 ret = Some(unwrap_(reader::doc_at(d.data, pos)).doc);
90 pub type GetCrateDataCb<'a> = 'a |ast::CrateNum| -> Cmd;
92 pub fn maybe_find_item<'a>(item_id: ast::NodeId,
93 items: ebml::Doc<'a>) -> Option<ebml::Doc<'a>> {
94 fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
95 return u64_from_be_bytes(
96 bytes.slice(0u, 4u), 0u, 4u) as ast::NodeId
100 |a| eq_item(a, item_id),
101 hash::hash(&(item_id as i64)))
104 fn find_item<'a>(item_id: ast::NodeId, items: ebml::Doc<'a>) -> ebml::Doc<'a> {
105 match maybe_find_item(item_id, items) {
106 None => fail!("lookup_item: id not found: {}", item_id),
111 // Looks up an item in the given metadata and returns an ebml doc pointing
113 fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> ebml::Doc<'a> {
114 let items = reader::get_doc(reader::Doc(data), tag_items);
115 find_item(item_id, items)
125 UnsafeStaticMethod, // U
142 fn item_family(item: ebml::Doc) -> Family {
143 let fam = reader::get_doc(item, tag_items_data_item_family);
144 match reader::doc_as_u8(fam) as char {
150 'U' => UnsafeStaticMethod,
158 'V' => StructVariant,
164 'N' => InheritedField,
165 c => fail!("unexpected family char: {}", c)
169 fn item_visibility(item: ebml::Doc) -> ast::Visibility {
170 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
172 Some(visibility_doc) => {
173 match reader::doc_as_u8(visibility_doc) as char {
176 'i' => ast::Inherited,
177 _ => fail!("unknown visibility character")
183 fn item_method_sort(item: ebml::Doc) -> char {
185 reader::tagged_docs(item, tag_item_trait_method_sort, |doc| {
186 ret = doc.as_str_slice()[0] as char;
192 fn item_symbol(item: ebml::Doc) -> ~str {
193 reader::get_doc(item, tag_items_data_item_symbol).as_str()
196 fn item_parent_item(d: ebml::Doc) -> Option<ast::DefId> {
198 reader::tagged_docs(d, tag_items_data_parent_item, |did| {
199 ret = Some(reader::with_doc_data(did, parse_def_id));
205 fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
206 d: ebml::Doc) -> ast::DefId {
207 let trait_did = item_parent_item(d).expect("item without parent");
208 ast::DefId { krate: cnum, node: trait_did.node }
211 fn item_def_id(d: ebml::Doc, cdata: Cmd) -> ast::DefId {
212 let tagdoc = reader::get_doc(d, tag_def_id);
213 return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
216 fn get_provided_source(d: ebml::Doc, cdata: Cmd) -> Option<ast::DefId> {
217 reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
218 translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
222 fn each_reexport(d: ebml::Doc, f: |ebml::Doc| -> bool) -> bool {
223 reader::tagged_docs(d, tag_items_data_item_reexport, f)
226 fn variant_disr_val(d: ebml::Doc) -> Option<ty::Disr> {
227 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
228 reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
232 fn doc_type(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
233 let tp = reader::get_doc(doc, tag_items_data_item_type);
234 parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
235 |_, did| translate_def_id(cdata, did))
238 fn doc_method_fty(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
239 let tp = reader::get_doc(doc, tag_item_method_fty);
240 parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
241 |_, did| translate_def_id(cdata, did))
244 pub fn item_type(_item_id: ast::DefId, item: ebml::Doc,
245 tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
246 doc_type(item, tcx, cdata)
249 fn doc_trait_ref(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
250 parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
251 |_, did| translate_def_id(cdata, did))
254 fn item_trait_ref(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
255 let tp = reader::get_doc(doc, tag_item_trait_ref);
256 doc_trait_ref(tp, tcx, cdata)
259 fn item_ty_param_defs(item: ebml::Doc,
263 -> Rc<Vec<ty::TypeParameterDef> > {
264 let mut bounds = Vec::new();
265 reader::tagged_docs(item, tag, |p| {
266 let bd = parse_type_param_def_data(
267 p.data, p.start, cdata.cnum, tcx,
268 |_, did| translate_def_id(cdata, did));
275 fn item_region_param_defs(item_doc: ebml::Doc, cdata: Cmd)
276 -> Rc<Vec<ty::RegionParameterDef> > {
277 let mut v = Vec::new();
278 reader::tagged_docs(item_doc, tag_region_param_def, |rp_doc| {
279 let ident_str_doc = reader::get_doc(rp_doc,
280 tag_region_param_def_ident);
281 let ident = item_name(token::get_ident_interner(), ident_str_doc);
282 let def_id_doc = reader::get_doc(rp_doc,
283 tag_region_param_def_def_id);
284 let def_id = reader::with_doc_data(def_id_doc, parse_def_id);
285 let def_id = translate_def_id(cdata, def_id);
286 v.push(ty::RegionParameterDef { name: ident.name,
293 fn item_ty_param_count(item: ebml::Doc) -> uint {
295 reader::tagged_docs(item, tag_items_data_item_ty_param_bounds,
296 |_p| { n += 1u; true } );
300 fn enum_variant_ids(item: ebml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
301 let mut ids: Vec<ast::DefId> = Vec::new();
302 let v = tag_items_data_item_variant;
303 reader::tagged_docs(item, v, |p| {
304 let ext = reader::with_doc_data(p, parse_def_id);
305 ids.push(ast::DefId { krate: cdata.cnum, node: ext.node });
311 fn item_path(item_doc: ebml::Doc) -> Vec<ast_map::PathElem> {
312 let path_doc = reader::get_doc(item_doc, tag_path);
314 let len_doc = reader::get_doc(path_doc, tag_path_len);
315 let len = reader::doc_as_u32(len_doc) as uint;
317 let mut result = Vec::with_capacity(len);
318 reader::docs(path_doc, |tag, elt_doc| {
319 if tag == tag_path_elem_mod {
320 let s = elt_doc.as_str_slice();
321 result.push(ast_map::PathMod(token::intern(s)));
322 } else if tag == tag_path_elem_name {
323 let s = elt_doc.as_str_slice();
324 result.push(ast_map::PathName(token::intern(s)));
326 // ignore tag_path_len element
334 fn item_name(intr: &IdentInterner, item: ebml::Doc) -> ast::Ident {
335 let name = reader::get_doc(item, tag_paths_data_name);
336 let string = name.as_str_slice();
337 match intr.find_equiv(&string) {
338 None => token::str_to_ident(string),
339 Some(val) => ast::Ident::new(val as ast::Name),
343 fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum)
345 let fam = item_family(item);
347 ImmStatic => DlDef(ast::DefStatic(did, false)),
348 MutStatic => DlDef(ast::DefStatic(did, true)),
349 Struct => DlDef(ast::DefStruct(did)),
350 UnsafeFn => DlDef(ast::DefFn(did, ast::UnsafeFn)),
351 Fn => DlDef(ast::DefFn(did, ast::ImpureFn)),
352 ForeignFn => DlDef(ast::DefFn(did, ast::ExternFn)),
353 StaticMethod | UnsafeStaticMethod => {
354 let purity = if fam == UnsafeStaticMethod { ast::UnsafeFn } else
356 // def_static_method carries an optional field of its enclosing
357 // trait or enclosing impl (if this is an inherent static method).
358 // So we need to detect whether this is in a trait or not, which
359 // we do through the mildly hacky way of checking whether there is
360 // a trait_method_sort.
361 let provenance = if reader::maybe_get_doc(
362 item, tag_item_trait_method_sort).is_some() {
363 ast::FromTrait(item_reqd_and_translated_parent_item(cnum,
366 ast::FromImpl(item_reqd_and_translated_parent_item(cnum,
369 DlDef(ast::DefStaticMethod(did, provenance, purity))
371 Type | ForeignType => DlDef(ast::DefTy(did)),
372 Mod => DlDef(ast::DefMod(did)),
373 ForeignMod => DlDef(ast::DefForeignMod(did)),
375 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
376 DlDef(ast::DefVariant(enum_did, did, true))
379 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
380 DlDef(ast::DefVariant(enum_did, did, false))
382 Trait => DlDef(ast::DefTrait(did)),
383 Enum => DlDef(ast::DefTy(did)),
385 PublicField | PrivateField | InheritedField => DlField,
389 pub fn get_trait_def(cdata: Cmd,
390 item_id: ast::NodeId,
391 tcx: &ty::ctxt) -> ty::TraitDef
393 let item_doc = lookup_item(item_id, cdata.data());
394 let tp_defs = item_ty_param_defs(item_doc, tcx, cdata,
395 tag_items_data_item_ty_param_bounds);
396 let rp_defs = item_region_param_defs(item_doc, cdata);
397 let mut bounds = ty::EmptyBuiltinBounds();
398 // Collect the builtin bounds from the encoded supertraits.
399 // FIXME(#8559): They should be encoded directly.
400 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
401 // NB. Bypasses real supertraits. See get_supertraits() if you wanted them.
402 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
403 tcx.lang_items.to_builtin_kind(trait_ref.def_id).map(|bound| {
409 generics: ty::Generics {type_param_defs: tp_defs,
410 region_param_defs: rp_defs},
412 trait_ref: @item_trait_ref(item_doc, tcx, cdata)
416 pub fn get_type(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
417 -> ty::ty_param_bounds_and_ty {
419 let item = lookup_item(id, cdata.data());
421 let t = item_type(ast::DefId { krate: cdata.cnum, node: id }, item, tcx,
424 let tp_defs = item_ty_param_defs(item, tcx, cdata, tag_items_data_item_ty_param_bounds);
425 let rp_defs = item_region_param_defs(item, cdata);
427 ty::ty_param_bounds_and_ty {
428 generics: ty::Generics {type_param_defs: tp_defs,
429 region_param_defs: rp_defs},
434 pub fn get_type_param_count(data: &[u8], id: ast::NodeId) -> uint {
435 item_ty_param_count(lookup_item(id, data))
438 pub fn get_impl_trait(cdata: Cmd,
440 tcx: &ty::ctxt) -> Option<@ty::TraitRef>
442 let item_doc = lookup_item(id, cdata.data());
443 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
444 @doc_trait_ref(tp, tcx, cdata)
448 pub fn get_impl_vtables(cdata: Cmd,
450 tcx: &ty::ctxt) -> typeck::impl_res
452 let item_doc = lookup_item(id, cdata.data());
453 let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables);
454 let mut decoder = reader::Decoder(vtables_doc);
457 trait_vtables: decoder.read_vtable_res(tcx, cdata),
458 self_vtables: decoder.read_vtable_param_res(tcx, cdata)
463 pub fn get_impl_method(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId,
464 name: ast::Ident) -> Option<ast::DefId> {
465 let items = reader::get_doc(reader::Doc(cdata.data()), tag_items);
466 let mut found = None;
467 reader::tagged_docs(find_item(id, items), tag_item_impl_method, |mid| {
468 let m_did = reader::with_doc_data(mid, parse_def_id);
469 if item_name(intr, find_item(m_did.node, items)) == name {
470 found = Some(translate_def_id(cdata, m_did));
477 pub fn get_symbol(data: &[u8], id: ast::NodeId) -> ~str {
478 return item_symbol(lookup_item(id, data));
481 // Something that a name can resolve to.
489 pub fn def_like_to_def(def_like: DefLike) -> ast::Def {
491 DlDef(def) => return def,
492 DlImpl(..) => fail!("found impl in def_like_to_def"),
493 DlField => fail!("found field in def_like_to_def")
497 /// Iterates over the language items in the given crate.
498 pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
499 let root = reader::Doc(cdata.data());
500 let lang_items = reader::get_doc(root, tag_lang_items);
501 reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
502 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
503 let id = reader::doc_as_u32(id_doc) as uint;
504 let node_id_doc = reader::get_doc(item_doc,
505 tag_lang_items_item_node_id);
506 let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
512 fn each_child_of_item_or_crate(intr: @IdentInterner,
515 get_crate_data: GetCrateDataCb,
519 // Iterate over all children.
520 let _ = reader::tagged_docs(item_doc, tag_mod_child, |child_info_doc| {
521 let child_def_id = reader::with_doc_data(child_info_doc,
523 let child_def_id = translate_def_id(cdata, child_def_id);
525 // This item may be in yet another crate if it was the child of a
527 let other_crates_items = if child_def_id.krate == cdata.cnum {
528 reader::get_doc(reader::Doc(cdata.data()), tag_items)
530 let crate_data = get_crate_data(child_def_id.krate);
531 reader::get_doc(reader::Doc(crate_data.data()), tag_items)
535 match maybe_find_item(child_def_id.node, other_crates_items) {
537 Some(child_item_doc) => {
538 // Hand off the item to the callback.
539 let child_name = item_name(intr, child_item_doc);
540 let def_like = item_to_def_like(child_item_doc,
543 let visibility = item_visibility(child_item_doc);
544 callback(def_like, child_name, visibility);
552 // As a special case, iterate over all static methods of
553 // associated implementations too. This is a bit of a botch.
555 let _ = reader::tagged_docs(item_doc,
556 tag_items_data_item_inherent_impl,
557 |inherent_impl_def_id_doc| {
558 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
560 let items = reader::get_doc(reader::Doc(cdata.data()), tag_items);
561 match maybe_find_item(inherent_impl_def_id.node, items) {
563 Some(inherent_impl_doc) => {
564 let _ = reader::tagged_docs(inherent_impl_doc,
565 tag_item_impl_method,
566 |impl_method_def_id_doc| {
567 let impl_method_def_id =
568 reader::with_doc_data(impl_method_def_id_doc,
570 let impl_method_def_id =
571 translate_def_id(cdata, impl_method_def_id);
572 match maybe_find_item(impl_method_def_id.node, items) {
574 Some(impl_method_doc) => {
575 match item_family(impl_method_doc) {
576 StaticMethod | UnsafeStaticMethod => {
577 // Hand off the static method
579 let static_method_name =
580 item_name(intr, impl_method_doc);
581 let static_method_def_like =
582 item_to_def_like(impl_method_doc,
585 callback(static_method_def_like,
587 item_visibility(impl_method_doc));
602 // Iterate over all reexports.
603 let _ = each_reexport(item_doc, |reexport_doc| {
604 let def_id_doc = reader::get_doc(reexport_doc,
605 tag_items_data_item_reexport_def_id);
606 let child_def_id = reader::with_doc_data(def_id_doc,
608 let child_def_id = translate_def_id(cdata, child_def_id);
610 let name_doc = reader::get_doc(reexport_doc,
611 tag_items_data_item_reexport_name);
612 let name = name_doc.as_str_slice();
614 // This reexport may be in yet another crate.
615 let other_crates_items = if child_def_id.krate == cdata.cnum {
616 reader::get_doc(reader::Doc(cdata.data()), tag_items)
618 let crate_data = get_crate_data(child_def_id.krate);
619 reader::get_doc(reader::Doc(crate_data.data()), tag_items)
623 match maybe_find_item(child_def_id.node, other_crates_items) {
625 Some(child_item_doc) => {
626 // Hand off the item to the callback.
627 let def_like = item_to_def_like(child_item_doc,
630 // These items have a public visibility because they're part of
631 // a public re-export.
632 callback(def_like, token::str_to_ident(name), ast::Public);
640 /// Iterates over each child of the given item.
641 pub fn each_child_of_item(intr: @IdentInterner,
644 get_crate_data: GetCrateDataCb,
645 callback: |DefLike, ast::Ident, ast::Visibility|) {
647 let root_doc = reader::Doc(cdata.data());
648 let items = reader::get_doc(root_doc, tag_items);
649 let item_doc = match maybe_find_item(id, items) {
651 Some(item_doc) => item_doc,
654 each_child_of_item_or_crate(intr,
661 /// Iterates over all the top-level crate items.
662 pub fn each_top_level_item_of_crate(intr: @IdentInterner,
664 get_crate_data: GetCrateDataCb,
668 let root_doc = reader::Doc(cdata.data());
669 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
670 let crate_items_doc = reader::get_doc(misc_info_doc,
671 tag_misc_info_crate_items);
673 each_child_of_item_or_crate(intr,
680 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
681 item_path(lookup_item(id, cdata.data()))
684 pub type DecodeInlinedItem<'a> = 'a |cdata: @cstore::crate_metadata,
686 path: Vec<ast_map::PathElem>,
688 -> Result<ast::InlinedItem, Vec<ast_map::PathElem> >;
690 pub fn maybe_get_item_ast(cdata: Cmd, tcx: &ty::ctxt, id: ast::NodeId,
691 decode_inlined_item: DecodeInlinedItem)
692 -> csearch::found_ast {
693 debug!("Looking up item: {}", id);
694 let item_doc = lookup_item(id, cdata.data());
695 let path = Vec::from_slice(item_path(item_doc).init());
696 match decode_inlined_item(cdata, tcx, path, item_doc) {
697 Ok(ref ii) => csearch::found(*ii),
699 match item_parent_item(item_doc) {
701 let did = translate_def_id(cdata, did);
702 let parent_item = lookup_item(did.node, cdata.data());
703 match decode_inlined_item(cdata, tcx, path, parent_item) {
704 Ok(ref ii) => csearch::found_parent(did, *ii),
705 Err(_) => csearch::not_found
708 None => csearch::not_found
714 pub fn get_enum_variants(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId,
715 tcx: &ty::ctxt) -> Vec<@ty::VariantInfo> {
716 let data = cdata.data();
717 let items = reader::get_doc(reader::Doc(data), tag_items);
718 let item = find_item(id, items);
719 let mut infos: Vec<@ty::VariantInfo> = Vec::new();
720 let variant_ids = enum_variant_ids(item, cdata);
721 let mut disr_val = 0;
722 for did in variant_ids.iter() {
723 let item = find_item(did.node, items);
724 let ctor_ty = item_type(ast::DefId { krate: cdata.cnum, node: id},
726 let name = item_name(intr, item);
727 let arg_tys = match ty::get(ctor_ty).sty {
728 ty::ty_bare_fn(ref f) => f.sig.inputs.clone(),
729 _ => Vec::new(), // Nullary enum variant.
731 match variant_disr_val(item) {
732 Some(val) => { disr_val = val; }
735 infos.push(@ty::VariantInfo{
740 // I'm not even sure if we encode visibility
741 // for variants -- TEST -- tjc
744 vis: ast::Inherited});
750 fn get_explicit_self(item: ebml::Doc) -> ast::ExplicitSelf_ {
751 fn get_mutability(ch: u8) -> ast::Mutability {
753 'i' => ast::MutImmutable,
754 'm' => ast::MutMutable,
755 _ => fail!("unknown mutability character: `{}`", ch as char),
759 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
760 let string = explicit_self_doc.as_str_slice();
762 let explicit_self_kind = string[0];
763 match explicit_self_kind as char {
764 's' => ast::SelfStatic,
765 'v' => ast::SelfValue,
766 '~' => ast::SelfUniq,
767 // FIXME(#4846) expl. region
768 '&' => ast::SelfRegion(None, get_mutability(string[1])),
769 _ => fail!("unknown self type code: `{}`", explicit_self_kind as char)
773 fn item_impl_methods(intr: @IdentInterner, cdata: Cmd, item: ebml::Doc,
774 tcx: &ty::ctxt) -> Vec<@ty::Method> {
775 let mut rslt = Vec::new();
776 reader::tagged_docs(item, tag_item_impl_method, |doc| {
777 let m_did = reader::with_doc_data(doc, parse_def_id);
778 rslt.push(@get_method(intr, cdata, m_did.node, tcx));
785 /// Returns information about the given implementation.
786 pub fn get_impl(intr: @IdentInterner, cdata: Cmd, impl_id: ast::NodeId,
789 let data = cdata.data();
790 let impl_item = lookup_item(impl_id, data);
796 ident: item_name(intr, impl_item),
797 methods: item_impl_methods(intr, cdata, impl_item, tcx),
801 pub fn get_method_name_and_explicit_self(
802 intr: @IdentInterner,
804 id: ast::NodeId) -> (ast::Ident, ast::ExplicitSelf_)
806 let method_doc = lookup_item(id, cdata.data());
807 let name = item_name(intr, method_doc);
808 let explicit_self = get_explicit_self(method_doc);
809 (name, explicit_self)
812 pub fn get_method(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId,
813 tcx: &ty::ctxt) -> ty::Method
815 let method_doc = lookup_item(id, cdata.data());
816 let def_id = item_def_id(method_doc, cdata);
818 let container_id = item_reqd_and_translated_parent_item(cdata.cnum,
820 let container_doc = lookup_item(container_id.node, cdata.data());
821 let container = match item_family(container_doc) {
822 Trait => TraitContainer(container_id),
823 _ => ImplContainer(container_id),
826 let name = item_name(intr, method_doc);
827 let type_param_defs = item_ty_param_defs(method_doc, tcx, cdata,
828 tag_item_method_tps);
829 let rp_defs = item_region_param_defs(method_doc, cdata);
830 let fty = doc_method_fty(method_doc, tcx, cdata);
831 let vis = item_visibility(method_doc);
832 let explicit_self = get_explicit_self(method_doc);
833 let provided_source = get_provided_source(method_doc, cdata);
838 type_param_defs: type_param_defs,
839 region_param_defs: rp_defs,
850 pub fn get_trait_method_def_ids(cdata: Cmd,
851 id: ast::NodeId) -> Vec<ast::DefId> {
852 let data = cdata.data();
853 let item = lookup_item(id, data);
854 let mut result = Vec::new();
855 reader::tagged_docs(item, tag_item_trait_method, |mth| {
856 result.push(item_def_id(mth, cdata));
862 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
863 let data = cdata.data();
864 let item_doc = lookup_item(id, data);
865 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
866 let mut decoder = reader::Decoder(variance_doc);
867 unwrap_(Decodable::decode(&mut decoder))
870 pub fn get_provided_trait_methods(intr: @IdentInterner, cdata: Cmd,
871 id: ast::NodeId, tcx: &ty::ctxt) ->
873 let data = cdata.data();
874 let item = lookup_item(id, data);
875 let mut result = Vec::new();
877 reader::tagged_docs(item, tag_item_trait_method, |mth_id| {
878 let did = item_def_id(mth_id, cdata);
879 let mth = lookup_item(did.node, data);
881 if item_method_sort(mth) == 'p' {
882 result.push(@get_method(intr, cdata, did.node, tcx));
890 /// Returns the supertraits of the given trait.
891 pub fn get_supertraits(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
892 -> Vec<@ty::TraitRef> {
893 let mut results = Vec::new();
894 let item_doc = lookup_item(id, cdata.data());
895 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
896 // NB. Only reads the ones that *aren't* builtin-bounds. See also
897 // get_trait_def() for collecting the builtin bounds.
898 // FIXME(#8559): The builtin bounds shouldn't be encoded in the first place.
899 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
900 if tcx.lang_items.to_builtin_kind(trait_ref.def_id).is_none() {
901 results.push(@trait_ref);
908 pub fn get_type_name_if_impl(cdata: Cmd,
909 node_id: ast::NodeId) -> Option<ast::Ident> {
910 let item = lookup_item(node_id, cdata.data());
911 if item_family(item) != Impl {
916 reader::tagged_docs(item, tag_item_impl_type_basename, |doc| {
917 ret = Some(token::str_to_ident(doc.as_str_slice()));
924 pub fn get_static_methods_if_impl(intr: @IdentInterner,
926 node_id: ast::NodeId)
927 -> Option<Vec<StaticMethodInfo> > {
928 let item = lookup_item(node_id, cdata.data());
929 if item_family(item) != Impl {
933 // If this impl implements a trait, don't consider it.
934 let ret = reader::tagged_docs(item, tag_item_trait_ref, |_doc| {
938 if !ret { return None }
940 let mut impl_method_ids = Vec::new();
941 reader::tagged_docs(item, tag_item_impl_method, |impl_method_doc| {
942 impl_method_ids.push(reader::with_doc_data(impl_method_doc, parse_def_id));
946 let mut static_impl_methods = Vec::new();
947 for impl_method_id in impl_method_ids.iter() {
948 let impl_method_doc = lookup_item(impl_method_id.node, cdata.data());
949 let family = item_family(impl_method_doc);
951 StaticMethod | UnsafeStaticMethod => {
953 match item_family(impl_method_doc) {
954 StaticMethod => purity = ast::ImpureFn,
955 UnsafeStaticMethod => purity = ast::UnsafeFn,
959 static_impl_methods.push(StaticMethodInfo {
960 ident: item_name(intr, impl_method_doc),
961 def_id: item_def_id(impl_method_doc, cdata),
963 vis: item_visibility(impl_method_doc),
970 return Some(static_impl_methods);
973 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
974 /// the actual type definition, otherwise, return None
975 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
976 node_id: ast::NodeId) -> Option<ast::NodeId> {
977 let item = lookup_item(node_id, cdata.data());
979 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
980 ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
986 pub fn get_item_attrs(cdata: Cmd,
987 node_id: ast::NodeId,
988 f: |Vec<@ast::MetaItem> |) {
989 // The attributes for a tuple struct are attached to the definition, not the ctor;
990 // we assume that someone passing in a tuple struct ctor is actually wanting to
991 // look at the definition
992 let node_id = get_tuple_struct_definition_if_ctor(cdata, node_id).unwrap_or(node_id);
993 let item = lookup_item(node_id, cdata.data());
994 reader::tagged_docs(item, tag_attributes, |attributes| {
995 reader::tagged_docs(attributes, tag_attribute, |attribute| {
996 f(get_meta_items(attribute));
1003 fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
1005 PublicField => ast::Public,
1006 PrivateField => ast::Private,
1007 InheritedField => ast::Inherited,
1012 pub fn get_struct_fields(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId)
1013 -> Vec<ty::field_ty> {
1014 let data = cdata.data();
1015 let item = lookup_item(id, data);
1016 let mut result = Vec::new();
1017 reader::tagged_docs(item, tag_item_field, |an_item| {
1018 let f = item_family(an_item);
1019 if f == PublicField || f == PrivateField || f == InheritedField {
1020 // FIXME #6993: name should be of type Name, not Ident
1021 let name = item_name(intr, an_item);
1022 let did = item_def_id(an_item, cdata);
1023 result.push(ty::field_ty {
1026 struct_field_family_to_visibility(f),
1031 reader::tagged_docs(item, tag_item_unnamed_field, |an_item| {
1032 let did = item_def_id(an_item, cdata);
1033 let f = item_family(an_item);
1034 result.push(ty::field_ty {
1035 name: special_idents::unnamed_field.name,
1037 vis: struct_field_family_to_visibility(f),
1044 pub fn get_item_visibility(cdata: Cmd, id: ast::NodeId)
1045 -> ast::Visibility {
1046 item_visibility(lookup_item(id, cdata.data()))
1049 fn get_meta_items(md: ebml::Doc) -> Vec<@ast::MetaItem> {
1050 let mut items: Vec<@ast::MetaItem> = Vec::new();
1051 reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
1052 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1053 let n = token::intern_and_get_ident(nd.as_str_slice());
1054 items.push(attr::mk_word_item(n));
1057 reader::tagged_docs(md, tag_meta_item_name_value, |meta_item_doc| {
1058 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1059 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1060 let n = token::intern_and_get_ident(nd.as_str_slice());
1061 let v = token::intern_and_get_ident(vd.as_str_slice());
1062 // FIXME (#623): Should be able to decode MetaNameValue variants,
1063 // but currently the encoder just drops them
1064 items.push(attr::mk_name_value_item_str(n, v));
1067 reader::tagged_docs(md, tag_meta_item_list, |meta_item_doc| {
1068 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1069 let n = token::intern_and_get_ident(nd.as_str_slice());
1070 let subitems = get_meta_items(meta_item_doc);
1071 items.push(attr::mk_list_item(n, subitems.move_iter().collect()));
1077 fn get_attributes(md: ebml::Doc) -> Vec<ast::Attribute> {
1078 let mut attrs: Vec<ast::Attribute> = Vec::new();
1079 match reader::maybe_get_doc(md, tag_attributes) {
1080 option::Some(attrs_d) => {
1081 reader::tagged_docs(attrs_d, tag_attribute, |attr_doc| {
1082 let meta_items = get_meta_items(attr_doc);
1083 // Currently it's only possible to have a single meta item on
1085 assert_eq!(meta_items.len(), 1u);
1086 let meta_item = *meta_items.get(0);
1089 node: ast::Attribute_ {
1090 style: ast::AttrOuter,
1092 is_sugared_doc: false,
1094 span: codemap::DUMMY_SP
1104 fn list_crate_attributes(md: ebml::Doc, hash: &Svh,
1105 out: &mut io::Writer) -> io::IoResult<()> {
1106 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1108 let r = get_attributes(md);
1109 for attr in r.iter() {
1110 try!(write!(out, "{}\n", pprust::attribute_to_str(attr)));
1116 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1117 return get_attributes(reader::Doc(data));
1121 pub struct CrateDep {
1122 cnum: ast::CrateNum,
1127 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1128 let mut deps: Vec<CrateDep> = Vec::new();
1129 let cratedoc = reader::Doc(data);
1130 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1131 let mut crate_num = 1;
1132 fn docstr(doc: ebml::Doc, tag_: uint) -> ~str {
1133 let d = reader::get_doc(doc, tag_);
1134 d.as_str_slice().to_str()
1136 reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
1137 let crate_id = from_str(docstr(depdoc, tag_crate_dep_crateid)).unwrap();
1138 let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash));
1139 deps.push(CrateDep {
1150 fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1151 try!(write!(out, "=External Dependencies=\n"));
1152 for dep in get_crate_deps(data).iter() {
1153 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.crate_id, dep.hash));
1155 try!(write!(out, "\n"));
1159 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1160 let cratedoc = reader::Doc(data);
1161 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1162 Svh::new(doc.as_str_slice())
1166 pub fn get_crate_hash(data: &[u8]) -> Svh {
1167 let cratedoc = reader::Doc(data);
1168 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1169 Svh::new(hashdoc.as_str_slice())
1172 pub fn maybe_get_crate_id(data: &[u8]) -> Option<CrateId> {
1173 let cratedoc = reader::Doc(data);
1174 reader::maybe_get_doc(cratedoc, tag_crate_crateid).map(|doc| {
1175 from_str(doc.as_str_slice()).unwrap()
1179 pub fn get_crate_id(data: &[u8]) -> CrateId {
1180 let cratedoc = reader::Doc(data);
1181 let hashdoc = reader::get_doc(cratedoc, tag_crate_crateid);
1182 from_str(hashdoc.as_str_slice()).unwrap()
1185 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1186 let hash = get_crate_hash(bytes);
1187 let md = reader::Doc(bytes);
1188 try!(list_crate_attributes(md, &hash, out));
1189 list_crate_deps(bytes, out)
1192 // Translates a def_id from an external crate to a def_id for the current
1193 // compilation environment. We use this when trying to load types from
1194 // external crates - if those types further refer to types in other crates
1195 // then we must translate the crate number from that encoded in the external
1196 // crate to the correct local crate number.
1197 pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
1198 if did.krate == ast::LOCAL_CRATE {
1199 return ast::DefId { krate: cdata.cnum, node: did.node };
1202 match cdata.cnum_map.borrow().find(&did.krate) {
1209 None => fail!("didn't find a crate in the cnum_map")
1213 pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
1214 let impls_doc = reader::get_doc(reader::Doc(cdata.data()), tag_impls);
1215 let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
1216 callback(item_def_id(impl_doc, cdata));
1221 pub fn each_implementation_for_type(cdata: Cmd,
1223 callback: |ast::DefId|) {
1224 let item_doc = lookup_item(id, cdata.data());
1225 reader::tagged_docs(item_doc,
1226 tag_items_data_item_inherent_impl,
1228 let implementation_def_id = item_def_id(impl_doc, cdata);
1229 callback(implementation_def_id);
1234 pub fn each_implementation_for_trait(cdata: Cmd,
1236 callback: |ast::DefId|) {
1237 let item_doc = lookup_item(id, cdata.data());
1239 let _ = reader::tagged_docs(item_doc,
1240 tag_items_data_item_extension_impl,
1242 let implementation_def_id = item_def_id(impl_doc, cdata);
1243 callback(implementation_def_id);
1248 pub fn get_trait_of_method(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
1249 -> Option<ast::DefId> {
1250 let item_doc = lookup_item(id, cdata.data());
1251 let parent_item_id = match item_parent_item(item_doc) {
1252 None => return None,
1253 Some(item_id) => item_id,
1255 let parent_item_id = translate_def_id(cdata, parent_item_id);
1256 let parent_item_doc = lookup_item(parent_item_id.node, cdata.data());
1257 match item_family(parent_item_doc) {
1258 Trait => Some(item_def_id(parent_item_doc, cdata)),
1260 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1261 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1268 pub fn get_native_libraries(cdata: Cmd) -> Vec<(cstore::NativeLibaryKind, ~str)> {
1269 let libraries = reader::get_doc(reader::Doc(cdata.data()),
1270 tag_native_libraries);
1271 let mut result = Vec::new();
1272 reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
1273 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1274 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1275 let kind: cstore::NativeLibaryKind =
1276 FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1277 let name = name_doc.as_str();
1278 result.push((kind, name));
1284 pub fn get_macro_registrar_fn(cdata: Cmd) -> Option<ast::DefId> {
1285 reader::maybe_get_doc(reader::Doc(cdata.data()), tag_macro_registrar_fn)
1286 .map(|doc| item_def_id(doc, cdata))
1289 pub fn get_exported_macros(cdata: Cmd) -> Vec<~str> {
1290 let macros = reader::get_doc(reader::Doc(cdata.data()),
1291 tag_exported_macros);
1292 let mut result = Vec::new();
1293 reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
1294 result.push(macro_doc.as_str());