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;
37 use serialize::ebml::reader;
39 use serialize::Decodable;
42 use syntax::parse::token::{IdentInterner, special_idents};
43 use syntax::parse::token;
44 use syntax::print::pprust;
47 use syntax::crateid::CrateId;
49 pub type Cmd = @crate_metadata;
51 // A function that takes a def_id relative to the crate being searched and
52 // returns a def_id relative to the compilation environment, i.e. if we hit a
53 // def_id for an item defined in another crate, somebody needs to figure out
54 // what crate that's in and give us a def_id that makes sense for the current
57 fn lookup_hash<'a>(d: ebml::Doc<'a>, eq_fn: |&[u8]| -> bool,
58 hash: u64) -> Option<ebml::Doc<'a>> {
59 let index = reader::get_doc(d, tag_index);
60 let table = reader::get_doc(index, tag_index_table);
61 let hash_pos = table.start + (hash % 256 * 4) as uint;
62 let pos = u64_from_be_bytes(d.data, hash_pos, 4) as uint;
63 let tagged_doc = reader::doc_at(d.data, pos);
65 let belt = tag_index_buckets_bucket_elt;
68 reader::tagged_docs(tagged_doc.doc, belt, |elt| {
69 let pos = u64_from_be_bytes(elt.data, elt.start, 4) as uint;
70 if eq_fn(elt.data.slice(elt.start + 4, elt.end)) {
71 ret = Some(reader::doc_at(d.data, pos).doc);
80 pub type GetCrateDataCb<'a> = 'a |ast::CrateNum| -> Cmd;
82 pub fn maybe_find_item<'a>(item_id: ast::NodeId,
83 items: ebml::Doc<'a>) -> Option<ebml::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: ebml::Doc<'a>) -> ebml::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 ebml doc pointing
103 fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> ebml::Doc<'a> {
104 let items = reader::get_doc(reader::Doc(data), tag_items);
105 find_item(item_id, items)
115 UnsafeStaticMethod, // U
132 fn item_family(item: ebml::Doc) -> Family {
133 let fam = reader::get_doc(item, tag_items_data_item_family);
134 match reader::doc_as_u8(fam) as char {
140 'U' => UnsafeStaticMethod,
148 'V' => StructVariant,
154 'N' => InheritedField,
155 c => fail!("unexpected family char: {}", c)
159 fn item_visibility(item: ebml::Doc) -> ast::Visibility {
160 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
162 Some(visibility_doc) => {
163 match reader::doc_as_u8(visibility_doc) as char {
166 'i' => ast::Inherited,
167 _ => fail!("unknown visibility character")
173 fn item_method_sort(item: ebml::Doc) -> char {
175 reader::tagged_docs(item, tag_item_trait_method_sort, |doc| {
176 ret = doc.as_str_slice()[0] as char;
182 fn item_symbol(item: ebml::Doc) -> ~str {
183 reader::get_doc(item, tag_items_data_item_symbol).as_str()
186 fn item_parent_item(d: ebml::Doc) -> Option<ast::DefId> {
188 reader::tagged_docs(d, tag_items_data_parent_item, |did| {
189 ret = Some(reader::with_doc_data(did, parse_def_id));
195 fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
196 d: ebml::Doc) -> ast::DefId {
197 let trait_did = item_parent_item(d).expect("item without parent");
198 ast::DefId { krate: cnum, node: trait_did.node }
201 fn item_def_id(d: ebml::Doc, cdata: Cmd) -> ast::DefId {
202 let tagdoc = reader::get_doc(d, tag_def_id);
203 return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
206 fn get_provided_source(d: ebml::Doc, cdata: Cmd) -> Option<ast::DefId> {
207 reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
208 translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
212 fn each_reexport(d: ebml::Doc, f: |ebml::Doc| -> bool) -> bool {
213 reader::tagged_docs(d, tag_items_data_item_reexport, f)
216 fn variant_disr_val(d: ebml::Doc) -> Option<ty::Disr> {
217 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
218 reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
222 fn doc_type(doc: ebml::Doc, tcx: ty::ctxt, cdata: Cmd) -> ty::t {
223 let tp = reader::get_doc(doc, tag_items_data_item_type);
224 parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
225 |_, did| translate_def_id(cdata, did))
228 fn doc_method_fty(doc: ebml::Doc, tcx: ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
229 let tp = reader::get_doc(doc, tag_item_method_fty);
230 parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
231 |_, did| translate_def_id(cdata, did))
234 pub fn item_type(_item_id: ast::DefId, item: ebml::Doc,
235 tcx: ty::ctxt, cdata: Cmd) -> ty::t {
236 doc_type(item, tcx, cdata)
239 fn doc_trait_ref(doc: ebml::Doc, tcx: ty::ctxt, cdata: Cmd) -> ty::TraitRef {
240 parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
241 |_, did| translate_def_id(cdata, did))
244 fn item_trait_ref(doc: ebml::Doc, tcx: ty::ctxt, cdata: Cmd) -> ty::TraitRef {
245 let tp = reader::get_doc(doc, tag_item_trait_ref);
246 doc_trait_ref(tp, tcx, cdata)
249 fn item_ty_param_defs(item: ebml::Doc,
253 -> Rc<Vec<ty::TypeParameterDef> > {
254 let mut bounds = Vec::new();
255 reader::tagged_docs(item, tag, |p| {
256 let bd = parse_type_param_def_data(
257 p.data, p.start, cdata.cnum, tcx,
258 |_, did| translate_def_id(cdata, did));
265 fn item_region_param_defs(item_doc: ebml::Doc, cdata: Cmd)
266 -> Rc<Vec<ty::RegionParameterDef> > {
267 let mut v = Vec::new();
268 reader::tagged_docs(item_doc, tag_region_param_def, |rp_doc| {
269 let ident_str_doc = reader::get_doc(rp_doc,
270 tag_region_param_def_ident);
271 let ident = item_name(token::get_ident_interner(), ident_str_doc);
272 let def_id_doc = reader::get_doc(rp_doc,
273 tag_region_param_def_def_id);
274 let def_id = reader::with_doc_data(def_id_doc, parse_def_id);
275 let def_id = translate_def_id(cdata, def_id);
276 v.push(ty::RegionParameterDef { ident: ident.name,
283 fn item_ty_param_count(item: ebml::Doc) -> uint {
285 reader::tagged_docs(item, tag_items_data_item_ty_param_bounds,
286 |_p| { n += 1u; true } );
290 fn enum_variant_ids(item: ebml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
291 let mut ids: Vec<ast::DefId> = Vec::new();
292 let v = tag_items_data_item_variant;
293 reader::tagged_docs(item, v, |p| {
294 let ext = reader::with_doc_data(p, parse_def_id);
295 ids.push(ast::DefId { krate: cdata.cnum, node: ext.node });
301 fn item_path(item_doc: ebml::Doc) -> Vec<ast_map::PathElem> {
302 let path_doc = reader::get_doc(item_doc, tag_path);
304 let len_doc = reader::get_doc(path_doc, tag_path_len);
305 let len = reader::doc_as_u32(len_doc) as uint;
307 let mut result = vec::with_capacity(len);
308 reader::docs(path_doc, |tag, elt_doc| {
309 if tag == tag_path_elem_mod {
310 let s = elt_doc.as_str_slice();
311 result.push(ast_map::PathMod(token::intern(s)));
312 } else if tag == tag_path_elem_name {
313 let s = elt_doc.as_str_slice();
314 result.push(ast_map::PathName(token::intern(s)));
316 // ignore tag_path_len element
324 fn item_name(intr: &IdentInterner, item: ebml::Doc) -> ast::Ident {
325 let name = reader::get_doc(item, tag_paths_data_name);
326 let string = name.as_str_slice();
327 match intr.find_equiv(&string) {
328 None => token::str_to_ident(string),
329 Some(val) => ast::Ident::new(val as ast::Name),
333 fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum)
335 let fam = item_family(item);
337 ImmStatic => DlDef(ast::DefStatic(did, false)),
338 MutStatic => DlDef(ast::DefStatic(did, true)),
339 Struct => DlDef(ast::DefStruct(did)),
340 UnsafeFn => DlDef(ast::DefFn(did, ast::UnsafeFn)),
341 Fn => DlDef(ast::DefFn(did, ast::ImpureFn)),
342 ForeignFn => DlDef(ast::DefFn(did, ast::ExternFn)),
343 StaticMethod | UnsafeStaticMethod => {
344 let purity = if fam == UnsafeStaticMethod { ast::UnsafeFn } else
346 // def_static_method carries an optional field of its enclosing
347 // trait or enclosing impl (if this is an inherent static method).
348 // So we need to detect whether this is in a trait or not, which
349 // we do through the mildly hacky way of checking whether there is
350 // a trait_method_sort.
351 let provenance = if reader::maybe_get_doc(
352 item, tag_item_trait_method_sort).is_some() {
353 ast::FromTrait(item_reqd_and_translated_parent_item(cnum,
356 ast::FromImpl(item_reqd_and_translated_parent_item(cnum,
359 DlDef(ast::DefStaticMethod(did, provenance, purity))
361 Type | ForeignType => DlDef(ast::DefTy(did)),
362 Mod => DlDef(ast::DefMod(did)),
363 ForeignMod => DlDef(ast::DefForeignMod(did)),
365 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
366 DlDef(ast::DefVariant(enum_did, did, true))
369 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
370 DlDef(ast::DefVariant(enum_did, did, false))
372 Trait => DlDef(ast::DefTrait(did)),
373 Enum => DlDef(ast::DefTy(did)),
375 PublicField | PrivateField | InheritedField => DlField,
379 pub fn get_trait_def(cdata: Cmd,
380 item_id: ast::NodeId,
381 tcx: ty::ctxt) -> ty::TraitDef
383 let item_doc = lookup_item(item_id, cdata.data());
384 let tp_defs = item_ty_param_defs(item_doc, tcx, cdata,
385 tag_items_data_item_ty_param_bounds);
386 let rp_defs = item_region_param_defs(item_doc, cdata);
387 let mut bounds = ty::EmptyBuiltinBounds();
388 // Collect the builtin bounds from the encoded supertraits.
389 // FIXME(#8559): They should be encoded directly.
390 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
391 // NB. Bypasses real supertraits. See get_supertraits() if you wanted them.
392 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
393 tcx.lang_items.to_builtin_kind(trait_ref.def_id).map(|bound| {
399 generics: ty::Generics {type_param_defs: tp_defs,
400 region_param_defs: rp_defs},
402 trait_ref: @item_trait_ref(item_doc, tcx, cdata)
406 pub fn get_type(cdata: Cmd, id: ast::NodeId, tcx: ty::ctxt)
407 -> ty::ty_param_bounds_and_ty {
409 let item = lookup_item(id, cdata.data());
411 let t = item_type(ast::DefId { krate: cdata.cnum, node: id }, item, tcx,
414 let tp_defs = item_ty_param_defs(item, tcx, cdata, tag_items_data_item_ty_param_bounds);
415 let rp_defs = item_region_param_defs(item, cdata);
417 ty::ty_param_bounds_and_ty {
418 generics: ty::Generics {type_param_defs: tp_defs,
419 region_param_defs: rp_defs},
424 pub fn get_type_param_count(data: &[u8], id: ast::NodeId) -> uint {
425 item_ty_param_count(lookup_item(id, data))
428 pub fn get_impl_trait(cdata: Cmd,
430 tcx: ty::ctxt) -> Option<@ty::TraitRef>
432 let item_doc = lookup_item(id, cdata.data());
433 reader::maybe_get_doc(item_doc, tag_item_trait_ref).map(|tp| {
434 @doc_trait_ref(tp, tcx, cdata)
438 pub fn get_impl_vtables(cdata: Cmd,
440 tcx: ty::ctxt) -> typeck::impl_res
442 let item_doc = lookup_item(id, cdata.data());
443 let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables);
444 let mut decoder = reader::Decoder(vtables_doc);
447 trait_vtables: decoder.read_vtable_res(tcx, cdata),
448 self_vtables: decoder.read_vtable_param_res(tcx, cdata)
453 pub fn get_impl_method(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId,
454 name: ast::Ident) -> Option<ast::DefId> {
455 let items = reader::get_doc(reader::Doc(cdata.data()), tag_items);
456 let mut found = None;
457 reader::tagged_docs(find_item(id, items), tag_item_impl_method, |mid| {
458 let m_did = reader::with_doc_data(mid, parse_def_id);
459 if item_name(intr, find_item(m_did.node, items)) == name {
460 found = Some(translate_def_id(cdata, m_did));
467 pub fn get_symbol(data: &[u8], id: ast::NodeId) -> ~str {
468 return item_symbol(lookup_item(id, data));
471 // Something that a name can resolve to.
479 pub fn def_like_to_def(def_like: DefLike) -> ast::Def {
481 DlDef(def) => return def,
482 DlImpl(..) => fail!("found impl in def_like_to_def"),
483 DlField => fail!("found field in def_like_to_def")
487 /// Iterates over the language items in the given crate.
488 pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
489 let root = reader::Doc(cdata.data());
490 let lang_items = reader::get_doc(root, tag_lang_items);
491 reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
492 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
493 let id = reader::doc_as_u32(id_doc) as uint;
494 let node_id_doc = reader::get_doc(item_doc,
495 tag_lang_items_item_node_id);
496 let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
502 fn each_child_of_item_or_crate(intr: @IdentInterner,
505 get_crate_data: GetCrateDataCb,
509 // Iterate over all children.
510 let _ = reader::tagged_docs(item_doc, tag_mod_child, |child_info_doc| {
511 let child_def_id = reader::with_doc_data(child_info_doc,
513 let child_def_id = translate_def_id(cdata, child_def_id);
515 // This item may be in yet another crate if it was the child of a
517 let other_crates_items = if child_def_id.krate == cdata.cnum {
518 reader::get_doc(reader::Doc(cdata.data()), tag_items)
520 let crate_data = get_crate_data(child_def_id.krate);
521 reader::get_doc(reader::Doc(crate_data.data()), tag_items)
525 match maybe_find_item(child_def_id.node, other_crates_items) {
527 Some(child_item_doc) => {
528 // Hand off the item to the callback.
529 let child_name = item_name(intr, child_item_doc);
530 let def_like = item_to_def_like(child_item_doc,
533 let visibility = item_visibility(child_item_doc);
534 callback(def_like, child_name, visibility);
542 // As a special case, iterate over all static methods of
543 // associated implementations too. This is a bit of a botch.
545 let _ = reader::tagged_docs(item_doc,
546 tag_items_data_item_inherent_impl,
547 |inherent_impl_def_id_doc| {
548 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
550 let items = reader::get_doc(reader::Doc(cdata.data()), tag_items);
551 match maybe_find_item(inherent_impl_def_id.node, items) {
553 Some(inherent_impl_doc) => {
554 let _ = reader::tagged_docs(inherent_impl_doc,
555 tag_item_impl_method,
556 |impl_method_def_id_doc| {
557 let impl_method_def_id =
558 reader::with_doc_data(impl_method_def_id_doc,
560 let impl_method_def_id =
561 translate_def_id(cdata, impl_method_def_id);
562 match maybe_find_item(impl_method_def_id.node, items) {
564 Some(impl_method_doc) => {
565 match item_family(impl_method_doc) {
566 StaticMethod | UnsafeStaticMethod => {
567 // Hand off the static method
569 let static_method_name =
570 item_name(intr, impl_method_doc);
571 let static_method_def_like =
572 item_to_def_like(impl_method_doc,
575 callback(static_method_def_like,
577 item_visibility(impl_method_doc));
592 // Iterate over all reexports.
593 let _ = each_reexport(item_doc, |reexport_doc| {
594 let def_id_doc = reader::get_doc(reexport_doc,
595 tag_items_data_item_reexport_def_id);
596 let child_def_id = reader::with_doc_data(def_id_doc,
598 let child_def_id = translate_def_id(cdata, child_def_id);
600 let name_doc = reader::get_doc(reexport_doc,
601 tag_items_data_item_reexport_name);
602 let name = name_doc.as_str_slice();
604 // This reexport may be in yet another crate.
605 let other_crates_items = if child_def_id.krate == cdata.cnum {
606 reader::get_doc(reader::Doc(cdata.data()), tag_items)
608 let crate_data = get_crate_data(child_def_id.krate);
609 reader::get_doc(reader::Doc(crate_data.data()), tag_items)
613 match maybe_find_item(child_def_id.node, other_crates_items) {
615 Some(child_item_doc) => {
616 // Hand off the item to the callback.
617 let def_like = item_to_def_like(child_item_doc,
620 // These items have a public visibility because they're part of
621 // a public re-export.
622 callback(def_like, token::str_to_ident(name), ast::Public);
630 /// Iterates over each child of the given item.
631 pub fn each_child_of_item(intr: @IdentInterner,
634 get_crate_data: GetCrateDataCb,
635 callback: |DefLike, ast::Ident, ast::Visibility|) {
637 let root_doc = reader::Doc(cdata.data());
638 let items = reader::get_doc(root_doc, tag_items);
639 let item_doc = match maybe_find_item(id, items) {
641 Some(item_doc) => item_doc,
644 each_child_of_item_or_crate(intr,
651 /// Iterates over all the top-level crate items.
652 pub fn each_top_level_item_of_crate(intr: @IdentInterner,
654 get_crate_data: GetCrateDataCb,
658 let root_doc = reader::Doc(cdata.data());
659 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
660 let crate_items_doc = reader::get_doc(misc_info_doc,
661 tag_misc_info_crate_items);
663 each_child_of_item_or_crate(intr,
670 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
671 item_path(lookup_item(id, cdata.data()))
674 pub type DecodeInlinedItem<'a> = 'a |cdata: @cstore::crate_metadata,
676 path: Vec<ast_map::PathElem> ,
678 -> Result<ast::InlinedItem, Vec<ast_map::PathElem> >;
680 pub fn maybe_get_item_ast(cdata: Cmd, tcx: ty::ctxt, id: ast::NodeId,
681 decode_inlined_item: DecodeInlinedItem)
682 -> csearch::found_ast {
683 debug!("Looking up item: {}", id);
684 let item_doc = lookup_item(id, cdata.data());
685 let path = item_path(item_doc).init().to_owned();
686 match decode_inlined_item(cdata, tcx, path, item_doc) {
687 Ok(ref ii) => csearch::found(*ii),
689 match item_parent_item(item_doc) {
691 let did = translate_def_id(cdata, did);
692 let parent_item = lookup_item(did.node, cdata.data());
693 match decode_inlined_item(cdata, tcx, path, parent_item) {
694 Ok(ref ii) => csearch::found_parent(did, *ii),
695 Err(_) => csearch::not_found
698 None => csearch::not_found
704 pub fn get_enum_variants(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId,
705 tcx: ty::ctxt) -> Vec<@ty::VariantInfo> {
706 let data = cdata.data();
707 let items = reader::get_doc(reader::Doc(data), tag_items);
708 let item = find_item(id, items);
709 let mut infos: Vec<@ty::VariantInfo> = Vec::new();
710 let variant_ids = enum_variant_ids(item, cdata);
711 let mut disr_val = 0;
712 for did in variant_ids.iter() {
713 let item = find_item(did.node, items);
714 let ctor_ty = item_type(ast::DefId { krate: cdata.cnum, node: id},
716 let name = item_name(intr, item);
717 let arg_tys = match ty::get(ctor_ty).sty {
718 ty::ty_bare_fn(ref f) => f.sig.inputs.clone(),
719 _ => Vec::new(), // Nullary enum variant.
721 match variant_disr_val(item) {
722 Some(val) => { disr_val = val; }
725 infos.push(@ty::VariantInfo{
730 // I'm not even sure if we encode visibility
731 // for variants -- TEST -- tjc
734 vis: ast::Inherited});
740 fn get_explicit_self(item: ebml::Doc) -> ast::ExplicitSelf_ {
741 fn get_mutability(ch: u8) -> ast::Mutability {
743 'i' => ast::MutImmutable,
744 'm' => ast::MutMutable,
745 _ => fail!("unknown mutability character: `{}`", ch as char),
749 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
750 let string = explicit_self_doc.as_str_slice();
752 let explicit_self_kind = string[0];
753 match explicit_self_kind as char {
754 's' => ast::SelfStatic,
755 'v' => ast::SelfValue,
756 '~' => ast::SelfUniq,
757 // FIXME(#4846) expl. region
758 '&' => ast::SelfRegion(None, get_mutability(string[1])),
759 _ => fail!("unknown self type code: `{}`", explicit_self_kind as char)
763 fn item_impl_methods(intr: @IdentInterner, cdata: Cmd, item: ebml::Doc,
764 tcx: ty::ctxt) -> Vec<@ty::Method> {
765 let mut rslt = Vec::new();
766 reader::tagged_docs(item, tag_item_impl_method, |doc| {
767 let m_did = reader::with_doc_data(doc, parse_def_id);
768 rslt.push(@get_method(intr, cdata, m_did.node, tcx));
775 /// Returns information about the given implementation.
776 pub fn get_impl(intr: @IdentInterner, cdata: Cmd, impl_id: ast::NodeId,
779 let data = cdata.data();
780 let impl_item = lookup_item(impl_id, data);
786 ident: item_name(intr, impl_item),
787 methods: item_impl_methods(intr, cdata, impl_item, tcx),
791 pub fn get_method_name_and_explicit_self(
792 intr: @IdentInterner,
794 id: ast::NodeId) -> (ast::Ident, ast::ExplicitSelf_)
796 let method_doc = lookup_item(id, cdata.data());
797 let name = item_name(intr, method_doc);
798 let explicit_self = get_explicit_self(method_doc);
799 (name, explicit_self)
802 pub fn get_method(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId,
803 tcx: ty::ctxt) -> ty::Method
805 let method_doc = lookup_item(id, cdata.data());
806 let def_id = item_def_id(method_doc, cdata);
808 let container_id = item_reqd_and_translated_parent_item(cdata.cnum,
810 let container_doc = lookup_item(container_id.node, cdata.data());
811 let container = match item_family(container_doc) {
812 Trait => TraitContainer(container_id),
813 _ => ImplContainer(container_id),
816 let name = item_name(intr, method_doc);
817 let type_param_defs = item_ty_param_defs(method_doc, tcx, cdata,
818 tag_item_method_tps);
819 let rp_defs = item_region_param_defs(method_doc, cdata);
820 let fty = doc_method_fty(method_doc, tcx, cdata);
821 let vis = item_visibility(method_doc);
822 let explicit_self = get_explicit_self(method_doc);
823 let provided_source = get_provided_source(method_doc, cdata);
828 type_param_defs: type_param_defs,
829 region_param_defs: rp_defs,
840 pub fn get_trait_method_def_ids(cdata: Cmd,
841 id: ast::NodeId) -> Vec<ast::DefId> {
842 let data = cdata.data();
843 let item = lookup_item(id, data);
844 let mut result = Vec::new();
845 reader::tagged_docs(item, tag_item_trait_method, |mth| {
846 result.push(item_def_id(mth, cdata));
852 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
853 let data = cdata.data();
854 let item_doc = lookup_item(id, data);
855 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
856 let mut decoder = reader::Decoder(variance_doc);
857 Decodable::decode(&mut decoder)
860 pub fn get_provided_trait_methods(intr: @IdentInterner, cdata: Cmd,
861 id: ast::NodeId, tcx: ty::ctxt) ->
863 let data = cdata.data();
864 let item = lookup_item(id, data);
865 let mut result = Vec::new();
867 reader::tagged_docs(item, tag_item_trait_method, |mth_id| {
868 let did = item_def_id(mth_id, cdata);
869 let mth = lookup_item(did.node, data);
871 if item_method_sort(mth) == 'p' {
872 result.push(@get_method(intr, cdata, did.node, tcx));
880 /// Returns the supertraits of the given trait.
881 pub fn get_supertraits(cdata: Cmd, id: ast::NodeId, tcx: ty::ctxt)
882 -> Vec<@ty::TraitRef> {
883 let mut results = Vec::new();
884 let item_doc = lookup_item(id, cdata.data());
885 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
886 // NB. Only reads the ones that *aren't* builtin-bounds. See also
887 // get_trait_def() for collecting the builtin bounds.
888 // FIXME(#8559): The builtin bounds shouldn't be encoded in the first place.
889 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
890 if tcx.lang_items.to_builtin_kind(trait_ref.def_id).is_none() {
891 results.push(@trait_ref);
898 pub fn get_type_name_if_impl(cdata: Cmd,
899 node_id: ast::NodeId) -> Option<ast::Ident> {
900 let item = lookup_item(node_id, cdata.data());
901 if item_family(item) != Impl {
906 reader::tagged_docs(item, tag_item_impl_type_basename, |doc| {
907 ret = Some(token::str_to_ident(doc.as_str_slice()));
914 pub fn get_static_methods_if_impl(intr: @IdentInterner,
916 node_id: ast::NodeId)
917 -> Option<Vec<StaticMethodInfo> > {
918 let item = lookup_item(node_id, cdata.data());
919 if item_family(item) != Impl {
923 // If this impl implements a trait, don't consider it.
924 let ret = reader::tagged_docs(item, tag_item_trait_ref, |_doc| {
928 if !ret { return None }
930 let mut impl_method_ids = Vec::new();
931 reader::tagged_docs(item, tag_item_impl_method, |impl_method_doc| {
932 impl_method_ids.push(reader::with_doc_data(impl_method_doc, parse_def_id));
936 let mut static_impl_methods = Vec::new();
937 for impl_method_id in impl_method_ids.iter() {
938 let impl_method_doc = lookup_item(impl_method_id.node, cdata.data());
939 let family = item_family(impl_method_doc);
941 StaticMethod | UnsafeStaticMethod => {
943 match item_family(impl_method_doc) {
944 StaticMethod => purity = ast::ImpureFn,
945 UnsafeStaticMethod => purity = ast::UnsafeFn,
949 static_impl_methods.push(StaticMethodInfo {
950 ident: item_name(intr, impl_method_doc),
951 def_id: item_def_id(impl_method_doc, cdata),
953 vis: item_visibility(impl_method_doc),
960 return Some(static_impl_methods);
963 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
964 /// the actual type definition, otherwise, return None
965 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
966 node_id: ast::NodeId) -> Option<ast::NodeId> {
967 let item = lookup_item(node_id, cdata.data());
969 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
970 ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
976 pub fn get_item_attrs(cdata: Cmd,
977 node_id: ast::NodeId,
978 f: |Vec<@ast::MetaItem> |) {
979 // The attributes for a tuple struct are attached to the definition, not the ctor;
980 // we assume that someone passing in a tuple struct ctor is actually wanting to
981 // look at the definition
982 let node_id = get_tuple_struct_definition_if_ctor(cdata, node_id).unwrap_or(node_id);
983 let item = lookup_item(node_id, cdata.data());
984 reader::tagged_docs(item, tag_attributes, |attributes| {
985 reader::tagged_docs(attributes, tag_attribute, |attribute| {
986 f(get_meta_items(attribute));
993 fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
995 PublicField => ast::Public,
996 PrivateField => ast::Private,
997 InheritedField => ast::Inherited,
1002 pub fn get_struct_fields(intr: @IdentInterner, cdata: Cmd, id: ast::NodeId)
1003 -> Vec<ty::field_ty> {
1004 let data = cdata.data();
1005 let item = lookup_item(id, data);
1006 let mut result = Vec::new();
1007 reader::tagged_docs(item, tag_item_field, |an_item| {
1008 let f = item_family(an_item);
1009 if f == PublicField || f == PrivateField || f == InheritedField {
1010 // FIXME #6993: name should be of type Name, not Ident
1011 let name = item_name(intr, an_item);
1012 let did = item_def_id(an_item, cdata);
1013 result.push(ty::field_ty {
1016 struct_field_family_to_visibility(f),
1021 reader::tagged_docs(item, tag_item_unnamed_field, |an_item| {
1022 let did = item_def_id(an_item, cdata);
1023 result.push(ty::field_ty {
1024 name: special_idents::unnamed_field.name,
1026 vis: ast::Inherited,
1033 pub fn get_item_visibility(cdata: Cmd, id: ast::NodeId)
1034 -> ast::Visibility {
1035 item_visibility(lookup_item(id, cdata.data()))
1038 fn get_meta_items(md: ebml::Doc) -> Vec<@ast::MetaItem> {
1039 let mut items: Vec<@ast::MetaItem> = Vec::new();
1040 reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
1041 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1042 let n = token::intern_and_get_ident(nd.as_str_slice());
1043 items.push(attr::mk_word_item(n));
1046 reader::tagged_docs(md, tag_meta_item_name_value, |meta_item_doc| {
1047 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1048 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1049 let n = token::intern_and_get_ident(nd.as_str_slice());
1050 let v = token::intern_and_get_ident(vd.as_str_slice());
1051 // FIXME (#623): Should be able to decode MetaNameValue variants,
1052 // but currently the encoder just drops them
1053 items.push(attr::mk_name_value_item_str(n, v));
1056 reader::tagged_docs(md, tag_meta_item_list, |meta_item_doc| {
1057 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1058 let n = token::intern_and_get_ident(nd.as_str_slice());
1059 let subitems = get_meta_items(meta_item_doc);
1060 items.push(attr::mk_list_item(n, subitems.move_iter().collect()));
1066 fn get_attributes(md: ebml::Doc) -> Vec<ast::Attribute> {
1067 let mut attrs: Vec<ast::Attribute> = Vec::new();
1068 match reader::maybe_get_doc(md, tag_attributes) {
1069 option::Some(attrs_d) => {
1070 reader::tagged_docs(attrs_d, tag_attribute, |attr_doc| {
1071 let meta_items = get_meta_items(attr_doc);
1072 // Currently it's only possible to have a single meta item on
1074 assert_eq!(meta_items.len(), 1u);
1075 let meta_item = meta_items[0];
1078 node: ast::Attribute_ {
1079 style: ast::AttrOuter,
1081 is_sugared_doc: false,
1083 span: codemap::DUMMY_SP
1093 fn list_crate_attributes(md: ebml::Doc, hash: &Svh,
1094 out: &mut io::Writer) -> io::IoResult<()> {
1095 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1097 let r = get_attributes(md);
1098 for attr in r.iter() {
1099 try!(write!(out, "{}\n", pprust::attribute_to_str(attr)));
1105 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1106 return get_attributes(reader::Doc(data));
1110 pub struct CrateDep {
1111 cnum: ast::CrateNum,
1116 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1117 let mut deps: Vec<CrateDep> = Vec::new();
1118 let cratedoc = reader::Doc(data);
1119 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1120 let mut crate_num = 1;
1121 fn docstr(doc: ebml::Doc, tag_: uint) -> ~str {
1122 let d = reader::get_doc(doc, tag_);
1123 d.as_str_slice().to_str()
1125 reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
1126 let crate_id = from_str(docstr(depdoc, tag_crate_dep_crateid)).unwrap();
1127 let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash));
1128 deps.push(CrateDep {
1139 fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1140 try!(write!(out, "=External Dependencies=\n"));
1141 for dep in get_crate_deps(data).iter() {
1142 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.crate_id, dep.hash));
1144 try!(write!(out, "\n"));
1148 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1149 let cratedoc = reader::Doc(data);
1150 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1151 Svh::new(doc.as_str_slice())
1155 pub fn get_crate_hash(data: &[u8]) -> Svh {
1156 let cratedoc = reader::Doc(data);
1157 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1158 Svh::new(hashdoc.as_str_slice())
1161 pub fn maybe_get_crate_id(data: &[u8]) -> Option<CrateId> {
1162 let cratedoc = reader::Doc(data);
1163 reader::maybe_get_doc(cratedoc, tag_crate_crateid).map(|doc| {
1164 from_str(doc.as_str_slice()).unwrap()
1168 pub fn get_crate_id(data: &[u8]) -> CrateId {
1169 let cratedoc = reader::Doc(data);
1170 let hashdoc = reader::get_doc(cratedoc, tag_crate_crateid);
1171 from_str(hashdoc.as_str_slice()).unwrap()
1174 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1175 let hash = get_crate_hash(bytes);
1176 let md = reader::Doc(bytes);
1177 try!(list_crate_attributes(md, &hash, out));
1178 list_crate_deps(bytes, out)
1181 // Translates a def_id from an external crate to a def_id for the current
1182 // compilation environment. We use this when trying to load types from
1183 // external crates - if those types further refer to types in other crates
1184 // then we must translate the crate number from that encoded in the external
1185 // crate to the correct local crate number.
1186 pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
1187 if did.krate == ast::LOCAL_CRATE {
1188 return ast::DefId { krate: cdata.cnum, node: did.node };
1191 let cnum_map = cdata.cnum_map.borrow();
1192 match cnum_map.get().find(&did.krate) {
1199 None => fail!("didn't find a crate in the cnum_map")
1203 pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
1204 let impls_doc = reader::get_doc(reader::Doc(cdata.data()), tag_impls);
1205 let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
1206 callback(item_def_id(impl_doc, cdata));
1211 pub fn each_implementation_for_type(cdata: Cmd,
1213 callback: |ast::DefId|) {
1214 let item_doc = lookup_item(id, cdata.data());
1215 reader::tagged_docs(item_doc,
1216 tag_items_data_item_inherent_impl,
1218 let implementation_def_id = item_def_id(impl_doc, cdata);
1219 callback(implementation_def_id);
1224 pub fn each_implementation_for_trait(cdata: Cmd,
1226 callback: |ast::DefId|) {
1227 let item_doc = lookup_item(id, cdata.data());
1229 let _ = reader::tagged_docs(item_doc,
1230 tag_items_data_item_extension_impl,
1232 let implementation_def_id = item_def_id(impl_doc, cdata);
1233 callback(implementation_def_id);
1238 pub fn get_trait_of_method(cdata: Cmd, id: ast::NodeId, tcx: ty::ctxt)
1239 -> Option<ast::DefId> {
1240 let item_doc = lookup_item(id, cdata.data());
1241 let parent_item_id = match item_parent_item(item_doc) {
1242 None => return None,
1243 Some(item_id) => item_id,
1245 let parent_item_id = translate_def_id(cdata, parent_item_id);
1246 let parent_item_doc = lookup_item(parent_item_id.node, cdata.data());
1247 match item_family(parent_item_doc) {
1248 Trait => Some(item_def_id(parent_item_doc, cdata)),
1250 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1251 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1258 pub fn get_native_libraries(cdata: Cmd) -> Vec<(cstore::NativeLibaryKind, ~str)> {
1259 let libraries = reader::get_doc(reader::Doc(cdata.data()),
1260 tag_native_libraries);
1261 let mut result = Vec::new();
1262 reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
1263 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1264 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1265 let kind: cstore::NativeLibaryKind =
1266 FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1267 let name = name_doc.as_str();
1268 result.push((kind, name));
1274 pub fn get_macro_registrar_fn(cdata: Cmd) -> Option<ast::DefId> {
1275 reader::maybe_get_doc(reader::Doc(cdata.data()), tag_macro_registrar_fn)
1276 .map(|doc| item_def_id(doc, cdata))
1279 pub fn get_exported_macros(cdata: Cmd) -> Vec<~str> {
1280 let macros = reader::get_doc(reader::Doc(cdata.data()),
1281 tag_exported_macros);
1282 let mut result = Vec::new();
1283 reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
1284 result.push(macro_doc.as_str());