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;
25 use middle::ty::{ImplContainer, TraitContainer};
28 use middle::astencode::vtable_decoder_helpers;
34 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<'a> = &'a 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).unwrap();
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).unwrap().doc);
80 pub fn maybe_find_item<'a>(item_id: ast::NodeId,
81 items: ebml::Doc<'a>) -> Option<ebml::Doc<'a>> {
82 fn eq_item(bytes: &[u8], item_id: ast::NodeId) -> bool {
83 return u64_from_be_bytes(
84 bytes.slice(0u, 4u), 0u, 4u) as ast::NodeId
88 |a| eq_item(a, item_id),
89 hash::hash(&(item_id as i64)))
92 fn find_item<'a>(item_id: ast::NodeId, items: ebml::Doc<'a>) -> ebml::Doc<'a> {
93 match maybe_find_item(item_id, items) {
94 None => fail!("lookup_item: id not found: {}", item_id),
99 // Looks up an item in the given metadata and returns an ebml doc pointing
101 fn lookup_item<'a>(item_id: ast::NodeId, data: &'a [u8]) -> ebml::Doc<'a> {
102 let items = reader::get_doc(reader::Doc(data), tag_items);
103 find_item(item_id, items)
113 UnsafeStaticMethod, // U
128 fn item_family(item: ebml::Doc) -> Family {
129 let fam = reader::get_doc(item, tag_items_data_item_family);
130 match reader::doc_as_u8(fam) as char {
136 'U' => UnsafeStaticMethod,
143 'V' => StructVariant,
148 'N' => InheritedField,
149 c => fail!("unexpected family char: {}", c)
153 fn item_visibility(item: ebml::Doc) -> ast::Visibility {
154 match reader::maybe_get_doc(item, tag_items_data_item_visibility) {
156 Some(visibility_doc) => {
157 match reader::doc_as_u8(visibility_doc) as char {
159 'i' => ast::Inherited,
160 _ => fail!("unknown visibility character")
166 fn item_sized(item: ebml::Doc) -> ast::Sized {
167 match reader::maybe_get_doc(item, tag_items_data_item_sized) {
168 None => ast::StaticSize,
170 match reader::doc_as_u8(sized_doc) as char {
172 's' => ast::StaticSize,
173 _ => fail!("unknown sized-ness character")
179 fn item_method_sort(item: ebml::Doc) -> char {
181 reader::tagged_docs(item, tag_item_trait_method_sort, |doc| {
182 ret = doc.as_str_slice()[0] as char;
188 fn item_symbol(item: ebml::Doc) -> String {
189 reader::get_doc(item, tag_items_data_item_symbol).as_str().to_strbuf()
192 fn item_parent_item(d: ebml::Doc) -> Option<ast::DefId> {
194 reader::tagged_docs(d, tag_items_data_parent_item, |did| {
195 ret = Some(reader::with_doc_data(did, parse_def_id));
201 fn item_reqd_and_translated_parent_item(cnum: ast::CrateNum,
202 d: ebml::Doc) -> ast::DefId {
203 let trait_did = item_parent_item(d).expect("item without parent");
204 ast::DefId { krate: cnum, node: trait_did.node }
207 fn item_def_id(d: ebml::Doc, cdata: Cmd) -> ast::DefId {
208 let tagdoc = reader::get_doc(d, tag_def_id);
209 return translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
212 fn get_provided_source(d: ebml::Doc, cdata: Cmd) -> Option<ast::DefId> {
213 reader::maybe_get_doc(d, tag_item_method_provided_source).map(|doc| {
214 translate_def_id(cdata, reader::with_doc_data(doc, parse_def_id))
218 fn each_reexport(d: ebml::Doc, f: |ebml::Doc| -> bool) -> bool {
219 reader::tagged_docs(d, tag_items_data_item_reexport, f)
222 fn variant_disr_val(d: ebml::Doc) -> Option<ty::Disr> {
223 reader::maybe_get_doc(d, tag_disr_val).and_then(|val_doc| {
224 reader::with_doc_data(val_doc, |data| u64::parse_bytes(data, 10u))
228 fn doc_type(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
229 let tp = reader::get_doc(doc, tag_items_data_item_type);
230 parse_ty_data(tp.data, cdata.cnum, tp.start, tcx,
231 |_, did| translate_def_id(cdata, did))
234 fn doc_method_fty(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::BareFnTy {
235 let tp = reader::get_doc(doc, tag_item_method_fty);
236 parse_bare_fn_ty_data(tp.data, cdata.cnum, tp.start, tcx,
237 |_, did| translate_def_id(cdata, did))
240 pub fn item_type(_item_id: ast::DefId, item: ebml::Doc,
241 tcx: &ty::ctxt, cdata: Cmd) -> ty::t {
242 doc_type(item, tcx, cdata)
245 fn doc_trait_ref(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
246 parse_trait_ref_data(doc.data, cdata.cnum, doc.start, tcx,
247 |_, did| translate_def_id(cdata, did))
250 fn item_trait_ref(doc: ebml::Doc, tcx: &ty::ctxt, cdata: Cmd) -> ty::TraitRef {
251 let tp = reader::get_doc(doc, tag_item_trait_ref);
252 doc_trait_ref(tp, tcx, cdata)
255 fn item_ty_param_defs(item: ebml::Doc,
259 -> Rc<Vec<ty::TypeParameterDef> > {
260 let mut bounds = Vec::new();
261 reader::tagged_docs(item, tag, |p| {
262 let bd = parse_type_param_def_data(
263 p.data, p.start, cdata.cnum, tcx,
264 |_, did| translate_def_id(cdata, did));
271 fn item_region_param_defs(item_doc: ebml::Doc, cdata: Cmd)
272 -> Rc<Vec<ty::RegionParameterDef> > {
273 let mut v = Vec::new();
274 reader::tagged_docs(item_doc, tag_region_param_def, |rp_doc| {
275 let ident_str_doc = reader::get_doc(rp_doc,
276 tag_region_param_def_ident);
277 let ident = item_name(&*token::get_ident_interner(), ident_str_doc);
278 let def_id_doc = reader::get_doc(rp_doc,
279 tag_region_param_def_def_id);
280 let def_id = reader::with_doc_data(def_id_doc, parse_def_id);
281 let def_id = translate_def_id(cdata, def_id);
282 v.push(ty::RegionParameterDef { name: ident.name,
289 fn enum_variant_ids(item: ebml::Doc, cdata: Cmd) -> Vec<ast::DefId> {
290 let mut ids: Vec<ast::DefId> = Vec::new();
291 let v = tag_items_data_item_variant;
292 reader::tagged_docs(item, v, |p| {
293 let ext = reader::with_doc_data(p, parse_def_id);
294 ids.push(ast::DefId { krate: cdata.cnum, node: ext.node });
300 fn item_path(item_doc: ebml::Doc) -> Vec<ast_map::PathElem> {
301 let path_doc = reader::get_doc(item_doc, tag_path);
303 let len_doc = reader::get_doc(path_doc, tag_path_len);
304 let len = reader::doc_as_u32(len_doc) as uint;
306 let mut result = Vec::with_capacity(len);
307 reader::docs(path_doc, |tag, elt_doc| {
308 if tag == tag_path_elem_mod {
309 let s = elt_doc.as_str_slice();
310 result.push(ast_map::PathMod(token::intern(s)));
311 } else if tag == tag_path_elem_name {
312 let s = elt_doc.as_str_slice();
313 result.push(ast_map::PathName(token::intern(s)));
315 // ignore tag_path_len element
323 fn item_name(intr: &IdentInterner, item: ebml::Doc) -> ast::Ident {
324 let name = reader::get_doc(item, tag_paths_data_name);
325 let string = name.as_str_slice();
326 match intr.find_equiv(&string) {
327 None => token::str_to_ident(string),
328 Some(val) => ast::Ident::new(val as ast::Name),
332 fn item_to_def_like(item: ebml::Doc, did: ast::DefId, cnum: ast::CrateNum)
334 let fam = item_family(item);
336 ImmStatic => DlDef(ast::DefStatic(did, false)),
337 MutStatic => DlDef(ast::DefStatic(did, true)),
338 Struct => DlDef(ast::DefStruct(did)),
339 UnsafeFn => DlDef(ast::DefFn(did, ast::UnsafeFn)),
340 Fn => DlDef(ast::DefFn(did, ast::NormalFn)),
341 StaticMethod | UnsafeStaticMethod => {
342 let fn_style = if fam == UnsafeStaticMethod { ast::UnsafeFn } else
344 // def_static_method carries an optional field of its enclosing
345 // trait or enclosing impl (if this is an inherent static method).
346 // So we need to detect whether this is in a trait or not, which
347 // we do through the mildly hacky way of checking whether there is
348 // a trait_method_sort.
349 let provenance = if reader::maybe_get_doc(
350 item, tag_item_trait_method_sort).is_some() {
351 ast::FromTrait(item_reqd_and_translated_parent_item(cnum,
354 ast::FromImpl(item_reqd_and_translated_parent_item(cnum,
357 DlDef(ast::DefStaticMethod(did, provenance, fn_style))
359 Type | ForeignType => DlDef(ast::DefTy(did)),
360 Mod => DlDef(ast::DefMod(did)),
361 ForeignMod => DlDef(ast::DefForeignMod(did)),
363 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
364 DlDef(ast::DefVariant(enum_did, did, true))
367 let enum_did = item_reqd_and_translated_parent_item(cnum, item);
368 DlDef(ast::DefVariant(enum_did, did, false))
370 Trait => DlDef(ast::DefTrait(did)),
371 Enum => DlDef(ast::DefTy(did)),
373 PublicField | InheritedField => DlField,
377 pub fn get_trait_def(cdata: Cmd,
378 item_id: ast::NodeId,
379 tcx: &ty::ctxt) -> ty::TraitDef
381 let item_doc = lookup_item(item_id, cdata.data());
382 let tp_defs = item_ty_param_defs(item_doc, tcx, cdata,
383 tag_items_data_item_ty_param_bounds);
384 let rp_defs = item_region_param_defs(item_doc, cdata);
385 let sized = item_sized(item_doc);
386 let mut bounds = ty::EmptyBuiltinBounds();
387 // Collect the builtin bounds from the encoded supertraits.
388 // FIXME(#8559): They should be encoded directly.
389 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
390 // NB. Bypasses real supertraits. See get_supertraits() if you wanted them.
391 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
392 tcx.lang_items.to_builtin_kind(trait_ref.def_id).map(|bound| {
397 // Turn sized into a bound, FIXME(#8559).
398 if sized == ast::StaticSize {
399 tcx.lang_items.to_builtin_kind(tcx.lang_items.sized_trait().unwrap()).map(|bound| {
405 generics: ty::Generics {type_param_defs: tp_defs,
406 region_param_defs: rp_defs},
408 trait_ref: Rc::new(item_trait_ref(item_doc, tcx, cdata))
412 pub fn get_type(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
413 -> ty::ty_param_bounds_and_ty {
415 let item = lookup_item(id, cdata.data());
417 let t = item_type(ast::DefId { krate: cdata.cnum, node: id }, item, tcx,
420 let tp_defs = item_ty_param_defs(item, tcx, cdata, tag_items_data_item_ty_param_bounds);
421 let rp_defs = item_region_param_defs(item, cdata);
423 ty::ty_param_bounds_and_ty {
424 generics: ty::Generics {type_param_defs: tp_defs,
425 region_param_defs: rp_defs},
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,
442 tcx: &ty::ctxt) -> typeck::impl_res
444 let item_doc = lookup_item(id, cdata.data());
445 let vtables_doc = reader::get_doc(item_doc, tag_item_impl_vtables);
446 let mut decoder = reader::Decoder(vtables_doc);
449 trait_vtables: decoder.read_vtable_res(tcx, cdata),
450 self_vtables: decoder.read_vtable_param_res(tcx, cdata)
455 pub fn get_symbol(data: &[u8], id: ast::NodeId) -> String {
456 return item_symbol(lookup_item(id, data));
459 // Something that a name can resolve to.
467 /// Iterates over the language items in the given crate.
468 pub fn each_lang_item(cdata: Cmd, f: |ast::NodeId, uint| -> bool) -> bool {
469 let root = reader::Doc(cdata.data());
470 let lang_items = reader::get_doc(root, tag_lang_items);
471 reader::tagged_docs(lang_items, tag_lang_items_item, |item_doc| {
472 let id_doc = reader::get_doc(item_doc, tag_lang_items_item_id);
473 let id = reader::doc_as_u32(id_doc) as uint;
474 let node_id_doc = reader::get_doc(item_doc,
475 tag_lang_items_item_node_id);
476 let node_id = reader::doc_as_u32(node_id_doc) as ast::NodeId;
482 pub type GetCrateDataCb<'a> = |ast::CrateNum|: 'a -> Rc<crate_metadata>;
484 fn each_child_of_item_or_crate(intr: Rc<IdentInterner>,
487 get_crate_data: GetCrateDataCb,
491 // Iterate over all children.
492 let _ = reader::tagged_docs(item_doc, tag_mod_child, |child_info_doc| {
493 let child_def_id = reader::with_doc_data(child_info_doc,
495 let child_def_id = translate_def_id(cdata, child_def_id);
497 // This item may be in yet another crate if it was the child of a
499 let crate_data = if child_def_id.krate == cdata.cnum {
502 Some(get_crate_data(child_def_id.krate))
504 let crate_data = match crate_data {
505 Some(ref cdata) => &**cdata,
509 let other_crates_items = reader::get_doc(reader::Doc(crate_data.data()), tag_items);
512 match maybe_find_item(child_def_id.node, other_crates_items) {
514 Some(child_item_doc) => {
515 // Hand off the item to the callback.
516 let child_name = item_name(&*intr, child_item_doc);
517 let def_like = item_to_def_like(child_item_doc,
520 let visibility = item_visibility(child_item_doc);
521 callback(def_like, child_name, visibility);
529 // As a special case, iterate over all static methods of
530 // associated implementations too. This is a bit of a botch.
532 let _ = reader::tagged_docs(item_doc,
533 tag_items_data_item_inherent_impl,
534 |inherent_impl_def_id_doc| {
535 let inherent_impl_def_id = item_def_id(inherent_impl_def_id_doc,
537 let items = reader::get_doc(reader::Doc(cdata.data()), tag_items);
538 match maybe_find_item(inherent_impl_def_id.node, items) {
540 Some(inherent_impl_doc) => {
541 let _ = reader::tagged_docs(inherent_impl_doc,
542 tag_item_impl_method,
543 |impl_method_def_id_doc| {
544 let impl_method_def_id =
545 reader::with_doc_data(impl_method_def_id_doc,
547 let impl_method_def_id =
548 translate_def_id(cdata, impl_method_def_id);
549 match maybe_find_item(impl_method_def_id.node, items) {
551 Some(impl_method_doc) => {
552 match item_family(impl_method_doc) {
553 StaticMethod | UnsafeStaticMethod => {
554 // Hand off the static method
556 let static_method_name =
557 item_name(&*intr, impl_method_doc);
558 let static_method_def_like =
559 item_to_def_like(impl_method_doc,
562 callback(static_method_def_like,
564 item_visibility(impl_method_doc));
579 // Iterate over all reexports.
580 let _ = each_reexport(item_doc, |reexport_doc| {
581 let def_id_doc = reader::get_doc(reexport_doc,
582 tag_items_data_item_reexport_def_id);
583 let child_def_id = reader::with_doc_data(def_id_doc,
585 let child_def_id = translate_def_id(cdata, child_def_id);
587 let name_doc = reader::get_doc(reexport_doc,
588 tag_items_data_item_reexport_name);
589 let name = name_doc.as_str_slice();
591 // This reexport may be in yet another crate.
592 let crate_data = if child_def_id.krate == cdata.cnum {
595 Some(get_crate_data(child_def_id.krate))
597 let crate_data = match crate_data {
598 Some(ref cdata) => &**cdata,
602 let other_crates_items = reader::get_doc(reader::Doc(crate_data.data()), tag_items);
605 match maybe_find_item(child_def_id.node, other_crates_items) {
607 Some(child_item_doc) => {
608 // Hand off the item to the callback.
609 let def_like = item_to_def_like(child_item_doc,
612 // These items have a public visibility because they're part of
613 // a public re-export.
614 callback(def_like, token::str_to_ident(name), ast::Public);
622 /// Iterates over each child of the given item.
623 pub fn each_child_of_item(intr: Rc<IdentInterner>,
626 get_crate_data: GetCrateDataCb,
627 callback: |DefLike, ast::Ident, ast::Visibility|) {
629 let root_doc = reader::Doc(cdata.data());
630 let items = reader::get_doc(root_doc, tag_items);
631 let item_doc = match maybe_find_item(id, items) {
633 Some(item_doc) => item_doc,
636 each_child_of_item_or_crate(intr,
643 /// Iterates over all the top-level crate items.
644 pub fn each_top_level_item_of_crate(intr: Rc<IdentInterner>,
646 get_crate_data: GetCrateDataCb,
650 let root_doc = reader::Doc(cdata.data());
651 let misc_info_doc = reader::get_doc(root_doc, tag_misc_info);
652 let crate_items_doc = reader::get_doc(misc_info_doc,
653 tag_misc_info_crate_items);
655 each_child_of_item_or_crate(intr,
662 pub fn get_item_path(cdata: Cmd, id: ast::NodeId) -> Vec<ast_map::PathElem> {
663 item_path(lookup_item(id, cdata.data()))
666 pub type DecodeInlinedItem<'a> = |cdata: Cmd,
668 path: Vec<ast_map::PathElem>,
669 par_doc: ebml::Doc|: 'a
670 -> Result<ast::InlinedItem, Vec<ast_map::PathElem> >;
672 pub fn maybe_get_item_ast(cdata: Cmd, tcx: &ty::ctxt, id: ast::NodeId,
673 decode_inlined_item: DecodeInlinedItem)
674 -> csearch::found_ast {
675 debug!("Looking up item: {}", id);
676 let item_doc = lookup_item(id, cdata.data());
677 let path = Vec::from_slice(item_path(item_doc).init());
678 match decode_inlined_item(cdata, tcx, path, item_doc) {
679 Ok(ref ii) => csearch::found(*ii),
681 match item_parent_item(item_doc) {
683 let did = translate_def_id(cdata, did);
684 let parent_item = lookup_item(did.node, cdata.data());
685 match decode_inlined_item(cdata, tcx, path, parent_item) {
686 Ok(ref ii) => csearch::found_parent(did, *ii),
687 Err(_) => csearch::not_found
690 None => csearch::not_found
696 pub fn get_enum_variants(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
697 tcx: &ty::ctxt) -> Vec<Rc<ty::VariantInfo>> {
698 let data = cdata.data();
699 let items = reader::get_doc(reader::Doc(data), tag_items);
700 let item = find_item(id, items);
701 let mut disr_val = 0;
702 enum_variant_ids(item, cdata).iter().map(|did| {
703 let item = find_item(did.node, items);
704 let ctor_ty = item_type(ast::DefId { krate: cdata.cnum, node: id},
706 let name = item_name(&*intr, item);
707 let arg_tys = match ty::get(ctor_ty).sty {
708 ty::ty_bare_fn(ref f) => f.sig.inputs.clone(),
709 _ => Vec::new(), // Nullary enum variant.
711 match variant_disr_val(item) {
712 Some(val) => { disr_val = val; }
715 let old_disr_val = disr_val;
717 Rc::new(ty::VariantInfo {
722 // I'm not even sure if we encode visibility
723 // for variants -- TEST -- tjc
725 disr_val: old_disr_val,
731 fn get_explicit_self(item: ebml::Doc) -> ast::ExplicitSelf_ {
732 fn get_mutability(ch: u8) -> ast::Mutability {
734 'i' => ast::MutImmutable,
735 'm' => ast::MutMutable,
736 _ => fail!("unknown mutability character: `{}`", ch as char),
740 let explicit_self_doc = reader::get_doc(item, tag_item_trait_method_explicit_self);
741 let string = explicit_self_doc.as_str_slice();
743 let explicit_self_kind = string[0];
744 match explicit_self_kind as char {
745 's' => ast::SelfStatic,
746 'v' => ast::SelfValue,
747 '~' => ast::SelfUniq,
748 // FIXME(#4846) expl. region
749 '&' => ast::SelfRegion(None, get_mutability(string[1])),
750 _ => fail!("unknown self type code: `{}`", explicit_self_kind as char)
754 /// Returns information about the given implementation.
755 pub fn get_impl_methods(cdata: Cmd, impl_id: ast::NodeId) -> Vec<ast::DefId> {
756 let mut methods = Vec::new();
757 reader::tagged_docs(lookup_item(impl_id, cdata.data()),
758 tag_item_impl_method, |doc| {
759 let m_did = reader::with_doc_data(doc, parse_def_id);
760 methods.push(translate_def_id(cdata, m_did));
767 pub fn get_method_name_and_explicit_self(
768 intr: Rc<IdentInterner>,
770 id: ast::NodeId) -> (ast::Ident, ast::ExplicitSelf_)
772 let method_doc = lookup_item(id, cdata.data());
773 let name = item_name(&*intr, method_doc);
774 let explicit_self = get_explicit_self(method_doc);
775 (name, explicit_self)
778 pub fn get_method(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId,
779 tcx: &ty::ctxt) -> ty::Method
781 let method_doc = lookup_item(id, cdata.data());
782 let def_id = item_def_id(method_doc, cdata);
784 let container_id = item_reqd_and_translated_parent_item(cdata.cnum,
786 let container_doc = lookup_item(container_id.node, cdata.data());
787 let container = match item_family(container_doc) {
788 Trait => TraitContainer(container_id),
789 _ => ImplContainer(container_id),
792 let name = item_name(&*intr, method_doc);
793 let type_param_defs = item_ty_param_defs(method_doc, tcx, cdata,
794 tag_item_method_tps);
795 let rp_defs = item_region_param_defs(method_doc, cdata);
796 let fty = doc_method_fty(method_doc, tcx, cdata);
797 let vis = item_visibility(method_doc);
798 let explicit_self = get_explicit_self(method_doc);
799 let provided_source = get_provided_source(method_doc, cdata);
804 type_param_defs: type_param_defs,
805 region_param_defs: rp_defs,
816 pub fn get_trait_method_def_ids(cdata: Cmd,
817 id: ast::NodeId) -> Vec<ast::DefId> {
818 let data = cdata.data();
819 let item = lookup_item(id, data);
820 let mut result = Vec::new();
821 reader::tagged_docs(item, tag_item_trait_method, |mth| {
822 result.push(item_def_id(mth, cdata));
828 pub fn get_item_variances(cdata: Cmd, id: ast::NodeId) -> ty::ItemVariances {
829 let data = cdata.data();
830 let item_doc = lookup_item(id, data);
831 let variance_doc = reader::get_doc(item_doc, tag_item_variances);
832 let mut decoder = reader::Decoder(variance_doc);
833 Decodable::decode(&mut decoder).unwrap()
836 pub fn get_provided_trait_methods(intr: Rc<IdentInterner>, cdata: Cmd,
837 id: ast::NodeId, tcx: &ty::ctxt)
838 -> Vec<Rc<ty::Method>> {
839 let data = cdata.data();
840 let item = lookup_item(id, data);
841 let mut result = Vec::new();
843 reader::tagged_docs(item, tag_item_trait_method, |mth_id| {
844 let did = item_def_id(mth_id, cdata);
845 let mth = lookup_item(did.node, data);
847 if item_method_sort(mth) == 'p' {
848 result.push(Rc::new(get_method(intr.clone(), cdata, did.node, tcx)));
856 /// Returns the supertraits of the given trait.
857 pub fn get_supertraits(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
858 -> Vec<Rc<ty::TraitRef>> {
859 let mut results = Vec::new();
860 let item_doc = lookup_item(id, cdata.data());
861 reader::tagged_docs(item_doc, tag_item_super_trait_ref, |trait_doc| {
862 // NB. Only reads the ones that *aren't* builtin-bounds. See also
863 // get_trait_def() for collecting the builtin bounds.
864 // FIXME(#8559): The builtin bounds shouldn't be encoded in the first place.
865 let trait_ref = doc_trait_ref(trait_doc, tcx, cdata);
866 if tcx.lang_items.to_builtin_kind(trait_ref.def_id).is_none() {
867 results.push(Rc::new(trait_ref));
874 pub fn get_type_name_if_impl(cdata: Cmd,
875 node_id: ast::NodeId) -> Option<ast::Ident> {
876 let item = lookup_item(node_id, cdata.data());
877 if item_family(item) != Impl {
882 reader::tagged_docs(item, tag_item_impl_type_basename, |doc| {
883 ret = Some(token::str_to_ident(doc.as_str_slice()));
890 pub fn get_static_methods_if_impl(intr: Rc<IdentInterner>,
892 node_id: ast::NodeId)
893 -> Option<Vec<StaticMethodInfo> > {
894 let item = lookup_item(node_id, cdata.data());
895 if item_family(item) != Impl {
899 // If this impl implements a trait, don't consider it.
900 let ret = reader::tagged_docs(item, tag_item_trait_ref, |_doc| {
904 if !ret { return None }
906 let mut impl_method_ids = Vec::new();
907 reader::tagged_docs(item, tag_item_impl_method, |impl_method_doc| {
908 impl_method_ids.push(reader::with_doc_data(impl_method_doc, parse_def_id));
912 let mut static_impl_methods = Vec::new();
913 for impl_method_id in impl_method_ids.iter() {
914 let impl_method_doc = lookup_item(impl_method_id.node, cdata.data());
915 let family = item_family(impl_method_doc);
917 StaticMethod | UnsafeStaticMethod => {
919 match item_family(impl_method_doc) {
920 StaticMethod => fn_style = ast::NormalFn,
921 UnsafeStaticMethod => fn_style = ast::UnsafeFn,
925 static_impl_methods.push(StaticMethodInfo {
926 ident: item_name(&*intr, impl_method_doc),
927 def_id: item_def_id(impl_method_doc, cdata),
929 vis: item_visibility(impl_method_doc),
936 return Some(static_impl_methods);
939 /// If node_id is the constructor of a tuple struct, retrieve the NodeId of
940 /// the actual type definition, otherwise, return None
941 pub fn get_tuple_struct_definition_if_ctor(cdata: Cmd,
942 node_id: ast::NodeId)
943 -> Option<ast::DefId>
945 let item = lookup_item(node_id, cdata.data());
947 reader::tagged_docs(item, tag_items_data_item_is_tuple_struct_ctor, |_| {
948 ret = Some(item_reqd_and_translated_parent_item(cdata.cnum, item));
954 pub fn get_item_attrs(cdata: Cmd,
955 orig_node_id: ast::NodeId,
956 f: |Vec<ast::Attribute>|) {
957 // The attributes for a tuple struct are attached to the definition, not the ctor;
958 // we assume that someone passing in a tuple struct ctor is actually wanting to
959 // look at the definition
960 let node_id = get_tuple_struct_definition_if_ctor(cdata, orig_node_id);
961 let node_id = node_id.map(|x| x.node).unwrap_or(orig_node_id);
962 let item = lookup_item(node_id, cdata.data());
963 f(get_attributes(item));
966 fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
968 PublicField => ast::Public,
969 InheritedField => ast::Inherited,
974 pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
975 -> Vec<ty::field_ty> {
976 let data = cdata.data();
977 let item = lookup_item(id, data);
978 let mut result = Vec::new();
979 reader::tagged_docs(item, tag_item_field, |an_item| {
980 let f = item_family(an_item);
981 if f == PublicField || f == InheritedField {
982 // FIXME #6993: name should be of type Name, not Ident
983 let name = item_name(&*intr, an_item);
984 let did = item_def_id(an_item, cdata);
985 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
986 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
987 result.push(ty::field_ty {
990 vis: struct_field_family_to_visibility(f),
996 reader::tagged_docs(item, tag_item_unnamed_field, |an_item| {
997 let did = item_def_id(an_item, cdata);
998 let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
999 let f = item_family(an_item);
1000 let origin_id = translate_def_id(cdata, reader::with_doc_data(tagdoc, parse_def_id));
1001 result.push(ty::field_ty {
1002 name: special_idents::unnamed_field.name,
1004 vis: struct_field_family_to_visibility(f),
1012 fn get_meta_items(md: ebml::Doc) -> Vec<@ast::MetaItem> {
1013 let mut items: Vec<@ast::MetaItem> = Vec::new();
1014 reader::tagged_docs(md, tag_meta_item_word, |meta_item_doc| {
1015 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1016 let n = token::intern_and_get_ident(nd.as_str_slice());
1017 items.push(attr::mk_word_item(n));
1020 reader::tagged_docs(md, tag_meta_item_name_value, |meta_item_doc| {
1021 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1022 let vd = reader::get_doc(meta_item_doc, tag_meta_item_value);
1023 let n = token::intern_and_get_ident(nd.as_str_slice());
1024 let v = token::intern_and_get_ident(vd.as_str_slice());
1025 // FIXME (#623): Should be able to decode MetaNameValue variants,
1026 // but currently the encoder just drops them
1027 items.push(attr::mk_name_value_item_str(n, v));
1030 reader::tagged_docs(md, tag_meta_item_list, |meta_item_doc| {
1031 let nd = reader::get_doc(meta_item_doc, tag_meta_item_name);
1032 let n = token::intern_and_get_ident(nd.as_str_slice());
1033 let subitems = get_meta_items(meta_item_doc);
1034 items.push(attr::mk_list_item(n, subitems.move_iter().collect()));
1040 fn get_attributes(md: ebml::Doc) -> Vec<ast::Attribute> {
1041 let mut attrs: Vec<ast::Attribute> = Vec::new();
1042 match reader::maybe_get_doc(md, tag_attributes) {
1043 option::Some(attrs_d) => {
1044 reader::tagged_docs(attrs_d, tag_attribute, |attr_doc| {
1045 let meta_items = get_meta_items(attr_doc);
1046 // Currently it's only possible to have a single meta item on
1048 assert_eq!(meta_items.len(), 1u);
1049 let meta_item = *meta_items.get(0);
1052 node: ast::Attribute_ {
1053 id: attr::mk_attr_id(),
1054 style: ast::AttrOuter,
1056 is_sugared_doc: false,
1058 span: codemap::DUMMY_SP
1068 fn list_crate_attributes(md: ebml::Doc, hash: &Svh,
1069 out: &mut io::Writer) -> io::IoResult<()> {
1070 try!(write!(out, "=Crate Attributes ({})=\n", *hash));
1072 let r = get_attributes(md);
1073 for attr in r.iter() {
1074 try!(write!(out, "{}\n", pprust::attribute_to_str(attr)));
1080 pub fn get_crate_attributes(data: &[u8]) -> Vec<ast::Attribute> {
1081 get_attributes(reader::Doc(data))
1085 pub struct CrateDep {
1086 pub cnum: ast::CrateNum,
1087 pub crate_id: CrateId,
1091 pub fn get_crate_deps(data: &[u8]) -> Vec<CrateDep> {
1092 let mut deps: Vec<CrateDep> = Vec::new();
1093 let cratedoc = reader::Doc(data);
1094 let depsdoc = reader::get_doc(cratedoc, tag_crate_deps);
1095 let mut crate_num = 1;
1096 fn docstr(doc: ebml::Doc, tag_: uint) -> String {
1097 let d = reader::get_doc(doc, tag_);
1098 d.as_str_slice().to_strbuf()
1100 reader::tagged_docs(depsdoc, tag_crate_dep, |depdoc| {
1102 from_str(docstr(depdoc,
1103 tag_crate_dep_crateid).as_slice()).unwrap();
1104 let hash = Svh::new(docstr(depdoc, tag_crate_dep_hash).as_slice());
1105 deps.push(CrateDep {
1116 fn list_crate_deps(data: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1117 try!(write!(out, "=External Dependencies=\n"));
1118 for dep in get_crate_deps(data).iter() {
1119 try!(write!(out, "{} {}-{}\n", dep.cnum, dep.crate_id, dep.hash));
1121 try!(write!(out, "\n"));
1125 pub fn maybe_get_crate_hash(data: &[u8]) -> Option<Svh> {
1126 let cratedoc = reader::Doc(data);
1127 reader::maybe_get_doc(cratedoc, tag_crate_hash).map(|doc| {
1128 Svh::new(doc.as_str_slice())
1132 pub fn get_crate_hash(data: &[u8]) -> Svh {
1133 let cratedoc = reader::Doc(data);
1134 let hashdoc = reader::get_doc(cratedoc, tag_crate_hash);
1135 Svh::new(hashdoc.as_str_slice())
1138 pub fn maybe_get_crate_id(data: &[u8]) -> Option<CrateId> {
1139 let cratedoc = reader::Doc(data);
1140 reader::maybe_get_doc(cratedoc, tag_crate_crateid).map(|doc| {
1141 from_str(doc.as_str_slice()).unwrap()
1145 pub fn get_crate_triple(data: &[u8]) -> String {
1146 let cratedoc = reader::Doc(data);
1147 let triple_doc = reader::maybe_get_doc(cratedoc, tag_crate_triple);
1148 triple_doc.expect("No triple in crate").as_str().to_strbuf()
1151 pub fn get_crate_id(data: &[u8]) -> CrateId {
1152 let cratedoc = reader::Doc(data);
1153 let hashdoc = reader::get_doc(cratedoc, tag_crate_crateid);
1154 from_str(hashdoc.as_str_slice()).unwrap()
1157 pub fn list_crate_metadata(bytes: &[u8], out: &mut io::Writer) -> io::IoResult<()> {
1158 let hash = get_crate_hash(bytes);
1159 let md = reader::Doc(bytes);
1160 try!(list_crate_attributes(md, &hash, out));
1161 list_crate_deps(bytes, out)
1164 // Translates a def_id from an external crate to a def_id for the current
1165 // compilation environment. We use this when trying to load types from
1166 // external crates - if those types further refer to types in other crates
1167 // then we must translate the crate number from that encoded in the external
1168 // crate to the correct local crate number.
1169 pub fn translate_def_id(cdata: Cmd, did: ast::DefId) -> ast::DefId {
1170 if did.krate == ast::LOCAL_CRATE {
1171 return ast::DefId { krate: cdata.cnum, node: did.node };
1174 match cdata.cnum_map.find(&did.krate) {
1181 None => fail!("didn't find a crate in the cnum_map")
1185 pub fn each_impl(cdata: Cmd, callback: |ast::DefId|) {
1186 let impls_doc = reader::get_doc(reader::Doc(cdata.data()), tag_impls);
1187 let _ = reader::tagged_docs(impls_doc, tag_impls_impl, |impl_doc| {
1188 callback(item_def_id(impl_doc, cdata));
1193 pub fn each_implementation_for_type(cdata: Cmd,
1195 callback: |ast::DefId|) {
1196 let item_doc = lookup_item(id, cdata.data());
1197 reader::tagged_docs(item_doc,
1198 tag_items_data_item_inherent_impl,
1200 let implementation_def_id = item_def_id(impl_doc, cdata);
1201 callback(implementation_def_id);
1206 pub fn each_implementation_for_trait(cdata: Cmd,
1208 callback: |ast::DefId|) {
1209 let item_doc = lookup_item(id, cdata.data());
1211 let _ = reader::tagged_docs(item_doc,
1212 tag_items_data_item_extension_impl,
1214 let implementation_def_id = item_def_id(impl_doc, cdata);
1215 callback(implementation_def_id);
1220 pub fn get_trait_of_method(cdata: Cmd, id: ast::NodeId, tcx: &ty::ctxt)
1221 -> Option<ast::DefId> {
1222 let item_doc = lookup_item(id, cdata.data());
1223 let parent_item_id = match item_parent_item(item_doc) {
1224 None => return None,
1225 Some(item_id) => item_id,
1227 let parent_item_id = translate_def_id(cdata, parent_item_id);
1228 let parent_item_doc = lookup_item(parent_item_id.node, cdata.data());
1229 match item_family(parent_item_doc) {
1230 Trait => Some(item_def_id(parent_item_doc, cdata)),
1232 reader::maybe_get_doc(parent_item_doc, tag_item_trait_ref)
1233 .map(|_| item_trait_ref(parent_item_doc, tcx, cdata).def_id)
1240 pub fn get_native_libraries(cdata: Cmd)
1241 -> Vec<(cstore::NativeLibaryKind, String)> {
1242 let libraries = reader::get_doc(reader::Doc(cdata.data()),
1243 tag_native_libraries);
1244 let mut result = Vec::new();
1245 reader::tagged_docs(libraries, tag_native_libraries_lib, |lib_doc| {
1246 let kind_doc = reader::get_doc(lib_doc, tag_native_libraries_kind);
1247 let name_doc = reader::get_doc(lib_doc, tag_native_libraries_name);
1248 let kind: cstore::NativeLibaryKind =
1249 FromPrimitive::from_u32(reader::doc_as_u32(kind_doc)).unwrap();
1250 let name = name_doc.as_str().to_strbuf();
1251 result.push((kind, name));
1257 pub fn get_macro_registrar_fn(data: &[u8]) -> Option<ast::NodeId> {
1258 reader::maybe_get_doc(reader::Doc(data), tag_macro_registrar_fn)
1259 .map(|doc| FromPrimitive::from_u32(reader::doc_as_u32(doc)).unwrap())
1262 pub fn get_exported_macros(data: &[u8]) -> Vec<String> {
1263 let macros = reader::get_doc(reader::Doc(data),
1264 tag_exported_macros);
1265 let mut result = Vec::new();
1266 reader::tagged_docs(macros, tag_macro_def, |macro_doc| {
1267 result.push(macro_doc.as_str().to_strbuf());
1273 pub fn get_dylib_dependency_formats(cdata: Cmd)
1274 -> Vec<(ast::CrateNum, cstore::LinkagePreference)>
1276 let formats = reader::get_doc(reader::Doc(cdata.data()),
1277 tag_dylib_dependency_formats);
1278 let mut result = Vec::new();
1280 debug!("found dylib deps: {}", formats.as_str_slice());
1281 for spec in formats.as_str_slice().split(',') {
1282 if spec.len() == 0 { continue }
1283 let cnum = spec.split(':').nth(0).unwrap();
1284 let link = spec.split(':').nth(1).unwrap();
1285 let cnum = from_str(cnum).unwrap();
1286 let cnum = match cdata.cnum_map.find(&cnum) {
1288 None => fail!("didn't find a crate in the cnum_map")
1290 result.push((cnum, if link == "d" {
1291 cstore::RequireDynamic
1293 cstore::RequireStatic
1299 pub fn get_missing_lang_items(cdata: Cmd)
1300 -> Vec<lang_items::LangItem>
1302 let items = reader::get_doc(reader::Doc(cdata.data()), tag_lang_items);
1303 let mut result = Vec::new();
1304 reader::tagged_docs(items, tag_lang_items_missing, |missing_doc| {
1305 let item: lang_items::LangItem =
1306 FromPrimitive::from_u32(reader::doc_as_u32(missing_doc)).unwrap();
1313 pub fn get_method_arg_names(cdata: Cmd, id: ast::NodeId) -> Vec<String> {
1314 let mut ret = Vec::new();
1315 let method_doc = lookup_item(id, cdata.data());
1316 match reader::maybe_get_doc(method_doc, tag_method_argument_names) {
1318 reader::tagged_docs(args_doc, tag_method_argument_name, |name_doc| {
1319 ret.push(name_doc.as_str_slice().to_strbuf());