Rollup merge of #37349 - srinivasreddy:meta_1, r=nikomatsakis

rustfmt on metadata folder
This commit is contained in:
Jonathan Turner 2016-10-24 15:41:29 -07:00 committed by GitHub
commit 59b7ea4c59
3 changed files with 335 additions and 260 deletions

View File

@ -30,7 +30,7 @@ use rustc_serialize::Encodable;
pub struct Ast<'tcx> { pub struct Ast<'tcx> {
id_range: IdRange, id_range: IdRange,
item: Lazy<InlinedItem>, item: Lazy<InlinedItem>,
side_tables: LazySeq<(ast::NodeId, TableEntry<'tcx>)> side_tables: LazySeq<(ast::NodeId, TableEntry<'tcx>)>,
} }
#[derive(RustcEncodable, RustcDecodable)] #[derive(RustcEncodable, RustcDecodable)]
@ -39,7 +39,7 @@ enum TableEntry<'tcx> {
NodeType(Ty<'tcx>), NodeType(Ty<'tcx>),
ItemSubsts(ty::ItemSubsts<'tcx>), ItemSubsts(ty::ItemSubsts<'tcx>),
Adjustment(ty::adjustment::AutoAdjustment<'tcx>), Adjustment(ty::adjustment::AutoAdjustment<'tcx>),
ConstQualif(ConstQualif) ConstQualif(ConstQualif),
} }
impl<'a, 'tcx> EncodeContext<'a, 'tcx> { impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
@ -48,7 +48,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
match ii { match ii {
InlinedItemRef::Item(_, i) => id_visitor.visit_item(i), InlinedItemRef::Item(_, i) => id_visitor.visit_item(i),
InlinedItemRef::TraitItem(_, ti) => id_visitor.visit_trait_item(ti), InlinedItemRef::TraitItem(_, ti) => id_visitor.visit_trait_item(ti),
InlinedItemRef::ImplItem(_, ii) => id_visitor.visit_impl_item(ii) InlinedItemRef::ImplItem(_, ii) => id_visitor.visit_impl_item(ii),
} }
let ii_pos = self.position(); let ii_pos = self.position();
@ -58,12 +58,12 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
let tables_count = { let tables_count = {
let mut visitor = SideTableEncodingIdVisitor { let mut visitor = SideTableEncodingIdVisitor {
ecx: self, ecx: self,
count: 0 count: 0,
}; };
match ii { match ii {
InlinedItemRef::Item(_, i) => visitor.visit_item(i), InlinedItemRef::Item(_, i) => visitor.visit_item(i),
InlinedItemRef::TraitItem(_, ti) => visitor.visit_trait_item(ti), InlinedItemRef::TraitItem(_, ti) => visitor.visit_trait_item(ti),
InlinedItemRef::ImplItem(_, ii) => visitor.visit_impl_item(ii) InlinedItemRef::ImplItem(_, ii) => visitor.visit_impl_item(ii),
} }
visitor.count visitor.count
}; };
@ -71,14 +71,14 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
self.lazy(&Ast { self.lazy(&Ast {
id_range: id_visitor.result(), id_range: id_visitor.result(),
item: Lazy::with_position(ii_pos), item: Lazy::with_position(ii_pos),
side_tables: LazySeq::with_position_and_length(tables_pos, tables_count) side_tables: LazySeq::with_position_and_length(tables_pos, tables_count),
}) })
} }
} }
struct SideTableEncodingIdVisitor<'a, 'b:'a, 'tcx:'b> { struct SideTableEncodingIdVisitor<'a, 'b: 'a, 'tcx: 'b> {
ecx: &'a mut EncodeContext<'b, 'tcx>, ecx: &'a mut EncodeContext<'b, 'tcx>,
count: usize count: usize,
} }
impl<'a, 'b, 'tcx, 'v> Visitor<'v> for SideTableEncodingIdVisitor<'a, 'b, 'tcx> { impl<'a, 'b, 'tcx, 'v> Visitor<'v> for SideTableEncodingIdVisitor<'a, 'b, 'tcx> {
@ -114,10 +114,11 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &CrateMetadata,
let cnt = ast.id_range.max.as_usize() - ast.id_range.min.as_usize(); let cnt = ast.id_range.max.as_usize() - ast.id_range.min.as_usize();
let start = tcx.sess.reserve_node_ids(cnt); let start = tcx.sess.reserve_node_ids(cnt);
let id_ranges = [ast.id_range, IdRange { let id_ranges = [ast.id_range,
min: start, IdRange {
max: ast::NodeId::new(start.as_usize() + cnt) min: start,
}]; max: ast::NodeId::new(start.as_usize() + cnt),
}];
let ii = ast.item.decode((cdata, tcx, id_ranges)); let ii = ast.item.decode((cdata, tcx, id_ranges));
let ii = ast_map::map_decoded_item(&tcx.map, let ii = ast_map::map_decoded_item(&tcx.map,
@ -129,7 +130,7 @@ pub fn decode_inlined_item<'a, 'tcx>(cdata: &CrateMetadata,
let item_node_id = match ii { let item_node_id = match ii {
&InlinedItem::Item(_, ref i) => i.id, &InlinedItem::Item(_, ref i) => i.id,
&InlinedItem::TraitItem(_, ref ti) => ti.id, &InlinedItem::TraitItem(_, ref ti) => ti.id,
&InlinedItem::ImplItem(_, ref ii) => ii.id &InlinedItem::ImplItem(_, ref ii) => ii.id,
}; };
let inlined_did = tcx.map.local_def_id(item_node_id); let inlined_did = tcx.map.local_def_id(item_node_id);
tcx.register_item_type(inlined_did, tcx.lookup_item_type(orig_did)); tcx.register_item_type(inlined_did, tcx.lookup_item_type(orig_did));

View File

@ -54,7 +54,7 @@ pub struct ImportedFileMap {
/// The end of this FileMap within the codemap of its original crate /// The end of this FileMap within the codemap of its original crate
pub original_end_pos: syntax_pos::BytePos, pub original_end_pos: syntax_pos::BytePos,
/// The imported FileMap's representation within the local codemap /// The imported FileMap's representation within the local codemap
pub translated_filemap: Rc<syntax_pos::FileMap> pub translated_filemap: Rc<syntax_pos::FileMap>,
} }
pub struct CrateMetadata { pub struct CrateMetadata {
@ -141,8 +141,8 @@ impl CStore {
self.metas.borrow_mut().insert(cnum, data); self.metas.borrow_mut().insert(cnum, data);
} }
pub fn iter_crate_data<I>(&self, mut i: I) where pub fn iter_crate_data<I>(&self, mut i: I)
I: FnMut(CrateNum, &Rc<CrateMetadata>), where I: FnMut(CrateNum, &Rc<CrateMetadata>)
{ {
for (&k, v) in self.metas.borrow().iter() { for (&k, v) in self.metas.borrow().iter() {
i(k, v); i(k, v);
@ -150,12 +150,14 @@ impl CStore {
} }
/// Like `iter_crate_data`, but passes source paths (if available) as well. /// Like `iter_crate_data`, but passes source paths (if available) as well.
pub fn iter_crate_data_origins<I>(&self, mut i: I) where pub fn iter_crate_data_origins<I>(&self, mut i: I)
I: FnMut(CrateNum, &CrateMetadata, Option<CrateSource>), where I: FnMut(CrateNum, &CrateMetadata, Option<CrateSource>)
{ {
for (&k, v) in self.metas.borrow().iter() { for (&k, v) in self.metas.borrow().iter() {
let origin = self.opt_used_crate_source(k); let origin = self.opt_used_crate_source(k);
origin.as_ref().map(|cs| { assert!(k == cs.cnum); }); origin.as_ref().map(|cs| {
assert!(k == cs.cnum);
});
i(k, &v, origin); i(k, &v, origin);
} }
} }
@ -167,10 +169,12 @@ impl CStore {
} }
} }
pub fn opt_used_crate_source(&self, cnum: CrateNum) pub fn opt_used_crate_source(&self, cnum: CrateNum) -> Option<CrateSource> {
-> Option<CrateSource> { self.used_crate_sources
self.used_crate_sources.borrow_mut() .borrow_mut()
.iter().find(|source| source.cnum == cnum).cloned() .iter()
.find(|source| source.cnum == cnum)
.cloned()
} }
pub fn reset(&self) { pub fn reset(&self) {
@ -182,19 +186,17 @@ impl CStore {
self.statically_included_foreign_items.borrow_mut().clear(); self.statically_included_foreign_items.borrow_mut().clear();
} }
pub fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec<CrateNum> pub fn crate_dependencies_in_rpo(&self, krate: CrateNum) -> Vec<CrateNum> {
{
let mut ordering = Vec::new(); let mut ordering = Vec::new();
self.push_dependencies_in_postorder(&mut ordering, krate); self.push_dependencies_in_postorder(&mut ordering, krate);
ordering.reverse(); ordering.reverse();
ordering ordering
} }
pub fn push_dependencies_in_postorder(&self, pub fn push_dependencies_in_postorder(&self, ordering: &mut Vec<CrateNum>, krate: CrateNum) {
ordering: &mut Vec<CrateNum>, if ordering.contains(&krate) {
krate: CrateNum) return;
{ }
if ordering.contains(&krate) { return }
let data = self.get_crate_data(krate); let data = self.get_crate_data(krate);
for &dep in data.cnum_map.borrow().iter() { for &dep in data.cnum_map.borrow().iter() {
@ -215,7 +217,8 @@ impl CStore {
// In order to get this left-to-right dependency ordering, we perform a // In order to get this left-to-right dependency ordering, we perform a
// topological sort of all crates putting the leaves at the right-most // topological sort of all crates putting the leaves at the right-most
// positions. // positions.
pub fn do_get_used_crates(&self, prefer: LinkagePreference) pub fn do_get_used_crates(&self,
prefer: LinkagePreference)
-> Vec<(CrateNum, Option<PathBuf>)> { -> Vec<(CrateNum, Option<PathBuf>)> {
let mut ordering = Vec::new(); let mut ordering = Vec::new();
for (&num, _) in self.metas.borrow().iter() { for (&num, _) in self.metas.borrow().iter() {
@ -223,12 +226,16 @@ impl CStore {
} }
info!("topological ordering: {:?}", ordering); info!("topological ordering: {:?}", ordering);
ordering.reverse(); ordering.reverse();
let mut libs = self.used_crate_sources.borrow() let mut libs = self.used_crate_sources
.borrow()
.iter() .iter()
.map(|src| (src.cnum, match prefer { .map(|src| {
LinkagePreference::RequireDynamic => src.dylib.clone().map(|p| p.0), (src.cnum,
LinkagePreference::RequireStatic => src.rlib.clone().map(|p| p.0), match prefer {
})) LinkagePreference::RequireDynamic => src.dylib.clone().map(|p| p.0),
LinkagePreference::RequireStatic => src.rlib.clone().map(|p| p.0),
})
})
.collect::<Vec<_>>(); .collect::<Vec<_>>();
libs.sort_by(|&(a, _), &(b, _)| { libs.sort_by(|&(a, _), &(b, _)| {
let a = ordering.iter().position(|x| *x == a); let a = ordering.iter().position(|x| *x == a);
@ -243,9 +250,7 @@ impl CStore {
self.used_libraries.borrow_mut().push((lib, kind)); self.used_libraries.borrow_mut().push((lib, kind));
} }
pub fn get_used_libraries<'a>(&'a self) pub fn get_used_libraries<'a>(&'a self) -> &'a RefCell<Vec<(String, NativeLibraryKind)>> {
-> &'a RefCell<Vec<(String,
NativeLibraryKind)>> {
&self.used_libraries &self.used_libraries
} }
@ -255,13 +260,11 @@ impl CStore {
} }
} }
pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String> > { pub fn get_used_link_args<'a>(&'a self) -> &'a RefCell<Vec<String>> {
&self.used_link_args &self.used_link_args
} }
pub fn add_extern_mod_stmt_cnum(&self, pub fn add_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId, cnum: CrateNum) {
emod_id: ast::NodeId,
cnum: CrateNum) {
self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum); self.extern_mod_crate_map.borrow_mut().insert(emod_id, cnum);
} }
@ -273,8 +276,7 @@ impl CStore {
self.statically_included_foreign_items.borrow().contains(&id) self.statically_included_foreign_items.borrow().contains(&id)
} }
pub fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> pub fn do_extern_mod_stmt_cnum(&self, emod_id: ast::NodeId) -> Option<CrateNum> {
{
self.extern_mod_crate_map.borrow().get(&emod_id).cloned() self.extern_mod_crate_map.borrow().get(&emod_id).cloned()
} }
@ -288,14 +290,20 @@ impl CStore {
} }
impl CrateMetadata { impl CrateMetadata {
pub fn name(&self) -> &str { &self.root.name } pub fn name(&self) -> &str {
pub fn hash(&self) -> Svh { self.root.hash } &self.root.name
pub fn disambiguator(&self) -> &str { &self.root.disambiguator } }
pub fn hash(&self) -> Svh {
self.root.hash
}
pub fn disambiguator(&self) -> &str {
&self.root.disambiguator
}
pub fn is_staged_api(&self) -> bool { pub fn is_staged_api(&self) -> bool {
self.get_item_attrs(CRATE_DEF_INDEX).iter().any(|attr| { self.get_item_attrs(CRATE_DEF_INDEX)
attr.name() == "stable" || attr.name() == "unstable" .iter()
}) .any(|attr| attr.name() == "stable" || attr.name() == "unstable")
} }
pub fn is_allocator(&self) -> bool { pub fn is_allocator(&self) -> bool {

View File

@ -56,19 +56,23 @@ pub struct DecodeContext<'a, 'tcx: 'a> {
// Cache the last used filemap for translating spans as an optimization. // Cache the last used filemap for translating spans as an optimization.
last_filemap_index: usize, last_filemap_index: usize,
lazy_state: LazyState lazy_state: LazyState,
} }
/// Abstract over the various ways one can create metadata decoders. /// Abstract over the various ways one can create metadata decoders.
pub trait Metadata<'a, 'tcx>: Copy { pub trait Metadata<'a, 'tcx>: Copy {
fn raw_bytes(self) -> &'a [u8]; fn raw_bytes(self) -> &'a [u8];
fn cdata(self) -> Option<&'a CrateMetadata> { None } fn cdata(self) -> Option<&'a CrateMetadata> {
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { None } None
}
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
None
}
fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
let id_range = IdRange { let id_range = IdRange {
min: NodeId::from_u32(u32::MIN), min: NodeId::from_u32(u32::MIN),
max: NodeId::from_u32(u32::MAX) max: NodeId::from_u32(u32::MAX),
}; };
DecodeContext { DecodeContext {
opaque: opaque::Decoder::new(self.raw_bytes(), pos), opaque: opaque::Decoder::new(self.raw_bytes(), pos),
@ -77,7 +81,7 @@ pub trait Metadata<'a, 'tcx>: Copy {
from_id_range: id_range, from_id_range: id_range,
to_id_range: id_range, to_id_range: id_range,
last_filemap_index: 0, last_filemap_index: 0,
lazy_state: LazyState::NoNode lazy_state: LazyState::NoNode,
} }
} }
} }
@ -92,21 +96,37 @@ impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a MetadataBlob {
} }
impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata { impl<'a, 'tcx> Metadata<'a, 'tcx> for &'a CrateMetadata {
fn raw_bytes(self) -> &'a [u8] { self.blob.raw_bytes() } fn raw_bytes(self) -> &'a [u8] {
fn cdata(self) -> Option<&'a CrateMetadata> { Some(self) } self.blob.raw_bytes()
}
fn cdata(self) -> Option<&'a CrateMetadata> {
Some(self)
}
} }
impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) { impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>) {
fn raw_bytes(self) -> &'a [u8] { self.0.raw_bytes() } fn raw_bytes(self) -> &'a [u8] {
fn cdata(self) -> Option<&'a CrateMetadata> { Some(self.0) } self.0.raw_bytes()
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { Some(self.1) } }
fn cdata(self) -> Option<&'a CrateMetadata> {
Some(self.0)
}
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
Some(self.1)
}
} }
// HACK(eddyb) Only used by astencode to customize the from/to IdRange's. // HACK(eddyb) Only used by astencode to customize the from/to IdRange's.
impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>, [IdRange; 2]) { impl<'a, 'tcx> Metadata<'a, 'tcx> for (&'a CrateMetadata, TyCtxt<'a, 'tcx, 'tcx>, [IdRange; 2]) {
fn raw_bytes(self) -> &'a [u8] { self.0.raw_bytes() } fn raw_bytes(self) -> &'a [u8] {
fn cdata(self) -> Option<&'a CrateMetadata> { Some(self.0) } self.0.raw_bytes()
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> { Some(self.1) } }
fn cdata(self) -> Option<&'a CrateMetadata> {
Some(self.0)
}
fn tcx(self) -> Option<TyCtxt<'a, 'tcx, 'tcx>> {
Some(self.1)
}
fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> { fn decoder(self, pos: usize) -> DecodeContext<'a, 'tcx> {
let mut dcx = (self.0, self.1).decoder(pos); let mut dcx = (self.0, self.1).decoder(pos);
@ -125,12 +145,10 @@ impl<'a, 'tcx: 'a, T: Decodable> Lazy<T> {
} }
impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> { impl<'a, 'tcx: 'a, T: Decodable> LazySeq<T> {
pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item=T> + 'a { pub fn decode<M: Metadata<'a, 'tcx>>(self, meta: M) -> impl Iterator<Item = T> + 'a {
let mut dcx = meta.decoder(self.position); let mut dcx = meta.decoder(self.position);
dcx.lazy_state = LazyState::NodeStart(self.position); dcx.lazy_state = LazyState::NodeStart(self.position);
(0..self.len).map(move |_| { (0..self.len).map(move |_| T::decode(&mut dcx).unwrap())
T::decode(&mut dcx).unwrap()
})
} }
} }
@ -153,20 +171,15 @@ impl<'a, 'tcx> DecodeContext<'a, 'tcx> {
r r
} }
fn read_lazy_distance(&mut self, min_size: usize) fn read_lazy_distance(&mut self, min_size: usize) -> Result<usize, <Self as Decoder>::Error> {
-> Result<usize, <Self as Decoder>::Error> {
let distance = self.read_usize()?; let distance = self.read_usize()?;
let position = match self.lazy_state { let position = match self.lazy_state {
LazyState::NoNode => { LazyState::NoNode => bug!("read_lazy_distance: outside of a metadata node"),
bug!("read_lazy_distance: outside of a metadata node")
}
LazyState::NodeStart(start) => { LazyState::NodeStart(start) => {
assert!(distance + min_size <= start); assert!(distance + min_size <= start);
start - distance - min_size start - distance - min_size
} }
LazyState::Previous(last_min_end) => { LazyState::Previous(last_min_end) => last_min_end + distance,
last_min_end + distance
}
}; };
self.lazy_state = LazyState::Previous(position + min_size); self.lazy_state = LazyState::Previous(position + min_size);
Ok(position) Ok(position)
@ -239,13 +252,15 @@ impl<'a, 'tcx> SpecializedDecoder<NodeId> for DecodeContext<'a, 'tcx> {
// meaningful result // meaningful result
if !self.from_id_range.contains(NodeId::from_u32(id)) { if !self.from_id_range.contains(NodeId::from_u32(id)) {
bug!("NodeId::decode: {} out of DecodeContext range ({:?} -> {:?})", bug!("NodeId::decode: {} out of DecodeContext range ({:?} -> {:?})",
id, self.from_id_range, self.to_id_range); id,
self.from_id_range,
self.to_id_range);
} }
// Use wrapping arithmetic because otherwise it introduces control flow. // Use wrapping arithmetic because otherwise it introduces control flow.
// Maybe we should just have the control flow? -- aatch // Maybe we should just have the control flow? -- aatch
Ok(NodeId::from_u32(id.wrapping_sub(self.from_id_range.min.as_u32()) Ok(NodeId::from_u32(id.wrapping_sub(self.from_id_range.min.as_u32())
.wrapping_add(self.to_id_range.min.as_u32()))) .wrapping_add(self.to_id_range.min.as_u32())))
} }
} }
@ -290,10 +305,9 @@ impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
// originate from the same filemap. // originate from the same filemap.
let last_filemap = &imported_filemaps[self.last_filemap_index]; let last_filemap = &imported_filemaps[self.last_filemap_index];
if lo >= last_filemap.original_start_pos && if lo >= last_filemap.original_start_pos && lo <= last_filemap.original_end_pos &&
lo <= last_filemap.original_end_pos && hi >= last_filemap.original_start_pos &&
hi >= last_filemap.original_start_pos && hi <= last_filemap.original_end_pos {
hi <= last_filemap.original_end_pos {
last_filemap last_filemap
} else { } else {
let mut a = 0; let mut a = 0;
@ -313,10 +327,8 @@ impl<'a, 'tcx> SpecializedDecoder<Span> for DecodeContext<'a, 'tcx> {
} }
}; };
let lo = (lo - filemap.original_start_pos) + let lo = (lo - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
filemap.translated_filemap.start_pos; let hi = (hi - filemap.original_start_pos) + filemap.translated_filemap.start_pos;
let hi = (hi - filemap.original_start_pos) +
filemap.translated_filemap.start_pos;
Ok(syntax_pos::mk_sp(lo, hi)) Ok(syntax_pos::mk_sp(lo, hi))
} }
@ -336,7 +348,7 @@ impl<'a, 'tcx> SpecializedDecoder<Ty<'tcx>> for DecodeContext<'a, 'tcx> {
assert!(pos >= SHORTHAND_OFFSET); assert!(pos >= SHORTHAND_OFFSET);
let key = ty::CReaderCacheKey { let key = ty::CReaderCacheKey {
cnum: self.cdata().cnum, cnum: self.cdata().cnum,
pos: pos - SHORTHAND_OFFSET pos: pos - SHORTHAND_OFFSET,
}; };
if let Some(ty) = tcx.rcache.borrow().get(&key).cloned() { if let Some(ty) = tcx.rcache.borrow().get(&key).cloned() {
return Ok(ty); return Ok(ty);
@ -357,17 +369,18 @@ impl<'a, 'tcx> SpecializedDecoder<ty::GenericPredicates<'tcx>> for DecodeContext
Ok(ty::GenericPredicates { Ok(ty::GenericPredicates {
parent: Decodable::decode(self)?, parent: Decodable::decode(self)?,
predicates: (0..self.read_usize()?).map(|_| { predicates: (0..self.read_usize()?).map(|_| {
// Handle shorthands first, if we have an usize > 0x80. // Handle shorthands first, if we have an usize > 0x80.
if self.opaque.data[self.opaque.position()] & 0x80 != 0 { if self.opaque.data[self.opaque.position()] & 0x80 != 0 {
let pos = self.read_usize()?; let pos = self.read_usize()?;
assert!(pos >= SHORTHAND_OFFSET); assert!(pos >= SHORTHAND_OFFSET);
let pos = pos - SHORTHAND_OFFSET; let pos = pos - SHORTHAND_OFFSET;
self.with_position(pos, ty::Predicate::decode) self.with_position(pos, ty::Predicate::decode)
} else { } else {
ty::Predicate::decode(self) ty::Predicate::decode(self)
} }
}).collect::<Result<Vec<_>, _>>()? })
.collect::<Result<Vec<_>, _>>()?,
}) })
} }
} }
@ -411,8 +424,7 @@ impl<'a, 'tcx> MetadataBlob {
pub fn get_root(&self) -> CrateRoot { pub fn get_root(&self) -> CrateRoot {
let slice = self.raw_bytes(); let slice = self.raw_bytes();
let offset = METADATA_HEADER.len(); let offset = METADATA_HEADER.len();
let pos = (((slice[offset + 0] as u32) << 24) | let pos = (((slice[offset + 0] as u32) << 24) | ((slice[offset + 1] as u32) << 16) |
((slice[offset + 1] as u32) << 16) |
((slice[offset + 2] as u32) << 8) | ((slice[offset + 2] as u32) << 8) |
((slice[offset + 3] as u32) << 0)) as usize; ((slice[offset + 3] as u32) << 0)) as usize;
Lazy::with_position(pos).decode(self) Lazy::with_position(pos).decode(self)
@ -421,9 +433,9 @@ impl<'a, 'tcx> MetadataBlob {
/// Go through each item in the metadata and create a map from that /// Go through each item in the metadata and create a map from that
/// item's def-key to the item's DefIndex. /// item's def-key to the item's DefIndex.
pub fn load_key_map(&self, index: LazySeq<Index>) -> FnvHashMap<DefKey, DefIndex> { pub fn load_key_map(&self, index: LazySeq<Index>) -> FnvHashMap<DefKey, DefIndex> {
index.iter_enumerated(self.raw_bytes()).map(|(index, item)| { index.iter_enumerated(self.raw_bytes())
(item.decode(self).def_key.decode(self), index) .map(|(index, item)| (item.decode(self).def_key.decode(self), index))
}).collect() .collect()
} }
pub fn list_crate_metadata(&self, out: &mut io::Write) -> io::Result<()> { pub fn list_crate_metadata(&self, out: &mut io::Write) -> io::Result<()> {
@ -440,7 +452,7 @@ impl<'a, 'tcx> MetadataBlob {
impl<'tcx> EntryKind<'tcx> { impl<'tcx> EntryKind<'tcx> {
fn to_def(&self, did: DefId) -> Option<Def> { fn to_def(&self, did: DefId) -> Option<Def> {
Some(match *self { Some(match *self {
EntryKind::Const => Def::Const(did), EntryKind::Const => Def::Const(did),
EntryKind::AssociatedConst(_) => Def::AssociatedConst(did), EntryKind::AssociatedConst(_) => Def::AssociatedConst(did),
EntryKind::ImmStatic | EntryKind::ImmStatic |
EntryKind::ForeignImmStatic => Def::Static(did, false), EntryKind::ForeignImmStatic => Def::Static(did, false),
@ -462,9 +474,7 @@ impl<'tcx> EntryKind<'tcx> {
EntryKind::Impl(_) | EntryKind::Impl(_) |
EntryKind::DefaultImpl(_) | EntryKind::DefaultImpl(_) |
EntryKind::Field | EntryKind::Field |
EntryKind::Closure (_) => { EntryKind::Closure(_) => return None,
return None
}
}) })
} }
} }
@ -476,23 +486,29 @@ impl<'a, 'tcx> CrateMetadata {
fn entry(&self, item_id: DefIndex) -> Entry<'tcx> { fn entry(&self, item_id: DefIndex) -> Entry<'tcx> {
match self.maybe_entry(item_id) { match self.maybe_entry(item_id) {
None => bug!("entry: id not found: {:?} in crate {:?} with number {}", None => {
item_id, bug!("entry: id not found: {:?} in crate {:?} with number {}",
self.name, item_id,
self.cnum), self.name,
Some(d) => d.decode(self) self.cnum)
}
Some(d) => d.decode(self),
} }
} }
fn local_def_id(&self, index: DefIndex) -> DefId { fn local_def_id(&self, index: DefIndex) -> DefId {
DefId { DefId {
krate: self.cnum, krate: self.cnum,
index: index index: index,
} }
} }
fn item_name(&self, item: &Entry<'tcx>) -> ast::Name { fn item_name(&self, item: &Entry<'tcx>) -> ast::Name {
item.def_key.decode(self).disambiguated_data.data.get_opt_name() item.def_key
.decode(self)
.disambiguated_data
.data
.get_opt_name()
.expect("no name in item_name") .expect("no name in item_name")
} }
@ -502,55 +518,66 @@ impl<'a, 'tcx> CrateMetadata {
pub fn get_trait_def(&self, pub fn get_trait_def(&self,
item_id: DefIndex, item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::TraitDef<'tcx> { tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::TraitDef<'tcx> {
let data = match self.entry(item_id).kind { let data = match self.entry(item_id).kind {
EntryKind::Trait(data) => data.decode(self), EntryKind::Trait(data) => data.decode(self),
_ => bug!() _ => bug!(),
}; };
ty::TraitDef::new(data.unsafety, data.paren_sugar, ty::TraitDef::new(data.unsafety,
data.paren_sugar,
tcx.lookup_generics(self.local_def_id(item_id)), tcx.lookup_generics(self.local_def_id(item_id)),
data.trait_ref.decode((self, tcx)), data.trait_ref.decode((self, tcx)),
self.def_path(item_id).unwrap().deterministic_hash(tcx)) self.def_path(item_id).unwrap().deterministic_hash(tcx))
} }
fn get_variant(&self, item: &Entry<'tcx>, index: DefIndex) fn get_variant(&self,
item: &Entry<'tcx>,
index: DefIndex)
-> (ty::VariantDefData<'tcx, 'tcx>, Option<DefIndex>) { -> (ty::VariantDefData<'tcx, 'tcx>, Option<DefIndex>) {
let data = match item.kind { let data = match item.kind {
EntryKind::Variant(data) | EntryKind::Variant(data) |
EntryKind::Struct(data) | EntryKind::Struct(data) |
EntryKind::Union(data) => data.decode(self), EntryKind::Union(data) => data.decode(self),
_ => bug!() _ => bug!(),
}; };
let fields = item.children.decode(self).map(|index| { let fields = item.children
let f = self.entry(index); .decode(self)
ty::FieldDefData::new(self.local_def_id(index), .map(|index| {
self.item_name(&f), let f = self.entry(index);
f.visibility) ty::FieldDefData::new(self.local_def_id(index), self.item_name(&f), f.visibility)
}).collect(); })
.collect();
(ty::VariantDefData { (ty::VariantDefData {
did: self.local_def_id(data.struct_ctor.unwrap_or(index)), did: self.local_def_id(data.struct_ctor.unwrap_or(index)),
name: self.item_name(item), name: self.item_name(item),
fields: fields, fields: fields,
disr_val: ConstInt::Infer(data.disr), disr_val: ConstInt::Infer(data.disr),
ctor_kind: data.ctor_kind, ctor_kind: data.ctor_kind,
}, data.struct_ctor) },
data.struct_ctor)
} }
pub fn get_adt_def(&self, item_id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) pub fn get_adt_def(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::AdtDefMaster<'tcx> { -> ty::AdtDefMaster<'tcx> {
let item = self.entry(item_id); let item = self.entry(item_id);
let did = self.local_def_id(item_id); let did = self.local_def_id(item_id);
let mut ctor_index = None; let mut ctor_index = None;
let variants = if let EntryKind::Enum = item.kind { let variants = if let EntryKind::Enum = item.kind {
item.children.decode(self).map(|index| { item.children
let (variant, struct_ctor) = self.get_variant(&self.entry(index), index); .decode(self)
assert_eq!(struct_ctor, None); .map(|index| {
variant let (variant, struct_ctor) = self.get_variant(&self.entry(index), index);
}).collect() assert_eq!(struct_ctor, None);
} else{ variant
})
.collect()
} else {
let (variant, struct_ctor) = self.get_variant(&item, item_id); let (variant, struct_ctor) = self.get_variant(&item, item_id);
ctor_index = struct_ctor; ctor_index = struct_ctor;
vec![variant] vec![variant]
@ -559,7 +586,7 @@ impl<'a, 'tcx> CrateMetadata {
EntryKind::Enum => ty::AdtKind::Enum, EntryKind::Enum => ty::AdtKind::Enum,
EntryKind::Struct(_) => ty::AdtKind::Struct, EntryKind::Struct(_) => ty::AdtKind::Struct,
EntryKind::Union(_) => ty::AdtKind::Union, EntryKind::Union(_) => ty::AdtKind::Union,
_ => bug!("get_adt_def called on a non-ADT {:?}", did) _ => bug!("get_adt_def called on a non-ADT {:?}", did),
}; };
let adt = tcx.intern_adt_def(did, kind, variants); let adt = tcx.intern_adt_def(did, kind, variants);
@ -572,33 +599,41 @@ impl<'a, 'tcx> CrateMetadata {
// to support recursive structures // to support recursive structures
for variant in &adt.variants { for variant in &adt.variants {
for field in &variant.fields { for field in &variant.fields {
debug!("evaluating the type of {:?}::{:?}", variant.name, field.name); debug!("evaluating the type of {:?}::{:?}",
variant.name,
field.name);
let ty = self.get_type(field.did.index, tcx); let ty = self.get_type(field.did.index, tcx);
field.fulfill_ty(ty); field.fulfill_ty(ty);
debug!("evaluating the type of {:?}::{:?}: {:?}", debug!("evaluating the type of {:?}::{:?}: {:?}",
variant.name, field.name, ty); variant.name,
field.name,
ty);
} }
} }
adt adt
} }
pub fn get_predicates(&self, item_id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) pub fn get_predicates(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::GenericPredicates<'tcx> { -> ty::GenericPredicates<'tcx> {
self.entry(item_id).predicates.unwrap().decode((self, tcx)) self.entry(item_id).predicates.unwrap().decode((self, tcx))
} }
pub fn get_super_predicates(&self, item_id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) pub fn get_super_predicates(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::GenericPredicates<'tcx> { -> ty::GenericPredicates<'tcx> {
match self.entry(item_id).kind { match self.entry(item_id).kind {
EntryKind::Trait(data) => { EntryKind::Trait(data) => data.decode(self).super_predicates.decode((self, tcx)),
data.decode(self).super_predicates.decode((self, tcx)) _ => bug!(),
}
_ => bug!()
} }
} }
pub fn get_generics(&self, item_id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) pub fn get_generics(&self,
item_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::Generics<'tcx> { -> ty::Generics<'tcx> {
self.entry(item_id).generics.unwrap().decode((self, tcx)) self.entry(item_id).generics.unwrap().decode((self, tcx))
} }
@ -622,7 +657,7 @@ impl<'a, 'tcx> CrateMetadata {
fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> { fn get_impl_data(&self, id: DefIndex) -> ImplData<'tcx> {
match self.entry(id).kind { match self.entry(id).kind {
EntryKind::Impl(data) => data.decode(self), EntryKind::Impl(data) => data.decode(self),
_ => bug!() _ => bug!(),
} }
} }
@ -634,7 +669,8 @@ impl<'a, 'tcx> CrateMetadata {
self.get_impl_data(id).polarity self.get_impl_data(id).polarity
} }
pub fn get_custom_coerce_unsized_kind(&self, id: DefIndex) pub fn get_custom_coerce_unsized_kind(&self,
id: DefIndex)
-> Option<ty::adjustment::CustomCoerceUnsized> { -> Option<ty::adjustment::CustomCoerceUnsized> {
self.get_impl_data(id).coerce_unsized_kind self.get_impl_data(id).coerce_unsized_kind
} }
@ -674,21 +710,25 @@ impl<'a, 'tcx> CrateMetadata {
if let Some(def) = self.get_def(child_index) { if let Some(def) = self.get_def(child_index) {
callback(def::Export { callback(def::Export {
def: def, def: def,
name: self.item_name(&self.entry(child_index)) name: self.item_name(&self.entry(child_index)),
}); });
} }
} }
continue; continue;
} }
EntryKind::Impl(_) | EntryKind::DefaultImpl(_) => continue, EntryKind::Impl(_) |
EntryKind::DefaultImpl(_) => continue,
_ => {} _ => {}
} }
let def_key = child.def_key.decode(self); let def_key = child.def_key.decode(self);
if let (Some(def), Some(name)) = (self.get_def(child_index), if let (Some(def), Some(name)) =
def_key.disambiguated_data.data.get_opt_name()) { (self.get_def(child_index), def_key.disambiguated_data.data.get_opt_name()) {
callback(def::Export { def: def, name: name }); callback(def::Export {
def: def,
name: name,
});
// For non-reexport structs and variants add their constructors to children. // For non-reexport structs and variants add their constructors to children.
// Reexport lists automatically contain constructors when necessary. // Reexport lists automatically contain constructors when necessary.
match def { match def {
@ -696,7 +736,10 @@ impl<'a, 'tcx> CrateMetadata {
if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) { if let Some(ctor_def_id) = self.get_struct_ctor_def_id(child_index) {
let ctor_kind = self.get_ctor_kind(child_index); let ctor_kind = self.get_ctor_kind(child_index);
let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind); let ctor_def = Def::StructCtor(ctor_def_id, ctor_kind);
callback(def::Export { def: ctor_def, name: name }); callback(def::Export {
def: ctor_def,
name: name,
});
} }
} }
Def::Variant(def_id) => { Def::Variant(def_id) => {
@ -704,7 +747,10 @@ impl<'a, 'tcx> CrateMetadata {
// value namespace, they are reserved for possible future use. // value namespace, they are reserved for possible future use.
let ctor_kind = self.get_ctor_kind(child_index); let ctor_kind = self.get_ctor_kind(child_index);
let ctor_def = Def::VariantCtor(def_id, ctor_kind); let ctor_def = Def::VariantCtor(def_id, ctor_kind);
callback(def::Export { def: ctor_def, name: name }); callback(def::Export {
def: ctor_def,
name: name,
});
} }
_ => {} _ => {}
} }
@ -719,7 +765,9 @@ impl<'a, 'tcx> CrateMetadata {
} }
} }
pub fn maybe_get_item_ast(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefIndex) pub fn maybe_get_item_ast(&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
id: DefIndex)
-> Option<&'tcx InlinedItem> { -> Option<&'tcx InlinedItem> {
debug!("Looking up item: {:?}", id); debug!("Looking up item: {:?}", id);
let item_doc = self.entry(id); let item_doc = self.entry(id);
@ -737,12 +785,16 @@ impl<'a, 'tcx> CrateMetadata {
self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some() self.maybe_entry(id).and_then(|item| item.decode(self).mir).is_some()
} }
pub fn maybe_get_item_mir(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, id: DefIndex) pub fn maybe_get_item_mir(&self,
tcx: TyCtxt<'a, 'tcx, 'tcx>,
id: DefIndex)
-> Option<Mir<'tcx>> { -> Option<Mir<'tcx>> {
self.entry(id).mir.map(|mir| mir.decode((self, tcx))) self.entry(id).mir.map(|mir| mir.decode((self, tcx)))
} }
pub fn get_impl_or_trait_item(&self, id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) pub fn get_impl_or_trait_item(&self,
id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> Option<ty::ImplOrTraitItem<'tcx>> { -> Option<ty::ImplOrTraitItem<'tcx>> {
let item = self.entry(id); let item = self.entry(id);
let parent_and_name = || { let parent_and_name = || {
@ -769,9 +821,11 @@ impl<'a, 'tcx> CrateMetadata {
let ity = item.ty.unwrap().decode((self, tcx)); let ity = item.ty.unwrap().decode((self, tcx));
let fty = match ity.sty { let fty = match ity.sty {
ty::TyFnDef(.., fty) => fty, ty::TyFnDef(.., fty) => fty,
_ => bug!( _ => {
"the type {:?} of the method {:?} is not a function?", bug!("the type {:?} of the method {:?} is not a function?",
ity, name) ity,
name)
}
}; };
let data = data.decode(self); let data = data.decode(self);
@ -799,7 +853,7 @@ impl<'a, 'tcx> CrateMetadata {
container: container.with_def_id(parent), container: container.with_def_id(parent),
})) }))
} }
_ => return None _ => return None,
}) })
} }
@ -821,7 +875,7 @@ impl<'a, 'tcx> CrateMetadata {
EntryKind::Struct(data) => { EntryKind::Struct(data) => {
data.decode(self).struct_ctor.map(|index| self.local_def_id(index)) data.decode(self).struct_ctor.map(|index| self.local_def_id(index))
} }
_ => None _ => None,
} }
} }
@ -838,17 +892,22 @@ impl<'a, 'tcx> CrateMetadata {
} }
pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> { pub fn get_struct_field_names(&self, id: DefIndex) -> Vec<ast::Name> {
self.entry(id).children.decode(self).map(|index| { self.entry(id)
self.item_name(&self.entry(index)) .children
}).collect() .decode(self)
.map(|index| self.item_name(&self.entry(index)))
.collect()
} }
fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> { fn get_attributes(&self, item: &Entry<'tcx>) -> Vec<ast::Attribute> {
item.attributes.decode(self).map(|mut attr| { item.attributes
// Need new unique IDs: old thread-local IDs won't map to new threads. .decode(self)
attr.node.id = attr::mk_attr_id(); .map(|mut attr| {
attr // Need new unique IDs: old thread-local IDs won't map to new threads.
}).collect() attr.node.id = attr::mk_attr_id();
attr
})
.collect()
} }
// Translate a DefId from the current compilation environment to a DefId // Translate a DefId from the current compilation environment to a DefId
@ -856,7 +915,10 @@ impl<'a, 'tcx> CrateMetadata {
fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> { fn reverse_translate_def_id(&self, did: DefId) -> Option<DefId> {
for (local, &global) in self.cnum_map.borrow().iter_enumerated() { for (local, &global) in self.cnum_map.borrow().iter_enumerated() {
if global == did.krate { if global == did.krate {
return Some(DefId { krate: local, index: did.index }); return Some(DefId {
krate: local,
index: did.index,
});
} }
} }
@ -864,9 +926,11 @@ impl<'a, 'tcx> CrateMetadata {
} }
pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> { pub fn get_inherent_implementations_for_type(&self, id: DefIndex) -> Vec<DefId> {
self.entry(id).inherent_impls.decode(self).map(|index| { self.entry(id)
self.local_def_id(index) .inherent_impls
}).collect() .decode(self)
.map(|index| self.local_def_id(index))
.collect()
} }
pub fn get_implementations_for_trait(&self, filter: Option<DefId>, result: &mut Vec<DefId>) { pub fn get_implementations_for_trait(&self, filter: Option<DefId>, result: &mut Vec<DefId>) {
@ -875,7 +939,7 @@ impl<'a, 'tcx> CrateMetadata {
let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) { let filter = match filter.map(|def_id| self.reverse_translate_def_id(def_id)) {
Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)), Some(Some(def_id)) => Some((def_id.krate.as_u32(), def_id.index)),
Some(None) => return, Some(None) => return,
None => None None => None,
}; };
// FIXME(eddyb) Make this O(1) instead of O(n). // FIXME(eddyb) Make this O(1) instead of O(n).
@ -884,9 +948,7 @@ impl<'a, 'tcx> CrateMetadata {
continue; continue;
} }
result.extend(trait_impls.impls.decode(self).map(|index| { result.extend(trait_impls.impls.decode(self).map(|index| self.local_def_id(index)));
self.local_def_id(index)
}));
if filter.is_some() { if filter.is_some() {
break; break;
@ -898,7 +960,7 @@ impl<'a, 'tcx> CrateMetadata {
self.entry(id).def_key.decode(self).parent.and_then(|parent_index| { self.entry(id).def_key.decode(self).parent.and_then(|parent_index| {
match self.entry(parent_index).kind { match self.entry(parent_index).kind {
EntryKind::Trait(_) => Some(self.local_def_id(parent_index)), EntryKind::Trait(_) => Some(self.local_def_id(parent_index)),
_ => None _ => None,
} }
}) })
} }
@ -909,10 +971,15 @@ impl<'a, 'tcx> CrateMetadata {
} }
pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> { pub fn get_dylib_dependency_formats(&self) -> Vec<(CrateNum, LinkagePreference)> {
self.root.dylib_dependency_formats.decode(self).enumerate().flat_map(|(i, link)| { self.root
let cnum = CrateNum::new(i + 1); .dylib_dependency_formats
link.map(|link| (self.cnum_map.borrow()[cnum], link)) .decode(self)
}).collect() .enumerate()
.flat_map(|(i, link)| {
let cnum = CrateNum::new(i + 1);
link.map(|link| (self.cnum_map.borrow()[cnum], link))
})
.collect()
} }
pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> { pub fn get_missing_lang_items(&self) -> Vec<lang_items::LangItem> {
@ -924,7 +991,7 @@ impl<'a, 'tcx> CrateMetadata {
EntryKind::Fn(data) | EntryKind::Fn(data) |
EntryKind::ForeignFn(data) => data.decode(self).arg_names, EntryKind::ForeignFn(data) => data.decode(self).arg_names,
EntryKind::Method(data) => data.decode(self).fn_data.arg_names, EntryKind::Method(data) => data.decode(self).fn_data.arg_names,
_ => LazySeq::empty() _ => LazySeq::empty(),
}; };
arg_names.decode(self).collect() arg_names.decode(self).collect()
} }
@ -937,7 +1004,7 @@ impl<'a, 'tcx> CrateMetadata {
let constness = match self.entry(id).kind { let constness = match self.entry(id).kind {
EntryKind::Method(data) => data.decode(self).fn_data.constness, EntryKind::Method(data) => data.decode(self).fn_data.constness,
EntryKind::Fn(data) => data.decode(self).constness, EntryKind::Fn(data) => data.decode(self).constness,
_ => hir::Constness::NotConst _ => hir::Constness::NotConst,
}; };
constness == hir::Constness::Const constness == hir::Constness::Const
} }
@ -953,16 +1020,14 @@ impl<'a, 'tcx> CrateMetadata {
EntryKind::ForeignImmStatic | EntryKind::ForeignImmStatic |
EntryKind::ForeignMutStatic => true, EntryKind::ForeignMutStatic => true,
EntryKind::Fn(_) | EntryKind::ForeignFn(_) => { EntryKind::Fn(_) |
self.get_generics(id, tcx).types.is_empty() EntryKind::ForeignFn(_) => self.get_generics(id, tcx).types.is_empty(),
}
_ => false, _ => false,
}; };
if applicable { if applicable {
attr::contains_extern_indicator(tcx.sess.diagnostic(), attr::contains_extern_indicator(tcx.sess.diagnostic(), &self.get_attributes(&item))
&self.get_attributes(&item))
} else { } else {
false false
} }
@ -973,36 +1038,38 @@ impl<'a, 'tcx> CrateMetadata {
EntryKind::ForeignImmStatic | EntryKind::ForeignImmStatic |
EntryKind::ForeignMutStatic | EntryKind::ForeignMutStatic |
EntryKind::ForeignFn(_) => true, EntryKind::ForeignFn(_) => true,
_ => false _ => false,
} }
} }
pub fn is_defaulted_trait(&self, trait_id: DefIndex) -> bool { pub fn is_defaulted_trait(&self, trait_id: DefIndex) -> bool {
match self.entry(trait_id).kind { match self.entry(trait_id).kind {
EntryKind::Trait(data) => data.decode(self).has_default_impl, EntryKind::Trait(data) => data.decode(self).has_default_impl,
_ => bug!() _ => bug!(),
} }
} }
pub fn is_default_impl(&self, impl_id: DefIndex) -> bool { pub fn is_default_impl(&self, impl_id: DefIndex) -> bool {
match self.entry(impl_id).kind { match self.entry(impl_id).kind {
EntryKind::DefaultImpl(_) => true, EntryKind::DefaultImpl(_) => true,
_ => false _ => false,
} }
} }
pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind { pub fn closure_kind(&self, closure_id: DefIndex) -> ty::ClosureKind {
match self.entry(closure_id).kind { match self.entry(closure_id).kind {
EntryKind::Closure(data) => data.decode(self).kind, EntryKind::Closure(data) => data.decode(self).kind,
_ => bug!() _ => bug!(),
} }
} }
pub fn closure_ty(&self, closure_id: DefIndex, tcx: TyCtxt<'a, 'tcx, 'tcx>) pub fn closure_ty(&self,
closure_id: DefIndex,
tcx: TyCtxt<'a, 'tcx, 'tcx>)
-> ty::ClosureTy<'tcx> { -> ty::ClosureTy<'tcx> {
match self.entry(closure_id).kind { match self.entry(closure_id).kind {
EntryKind::Closure(data) => data.decode(self).ty.decode((self, tcx)), EntryKind::Closure(data) => data.decode(self).ty.decode((self, tcx)),
_ => bug!() _ => bug!(),
} }
} }
@ -1045,7 +1112,8 @@ impl<'a, 'tcx> CrateMetadata {
/// file they represent, just information about length, line breaks, and /// file they represent, just information about length, line breaks, and
/// multibyte characters. This information is enough to generate valid debuginfo /// multibyte characters. This information is enough to generate valid debuginfo
/// for items inlined from other crates. /// for items inlined from other crates.
pub fn imported_filemaps(&'a self, local_codemap: &codemap::CodeMap) pub fn imported_filemaps(&'a self,
local_codemap: &codemap::CodeMap)
-> Ref<'a, Vec<cstore::ImportedFileMap>> { -> Ref<'a, Vec<cstore::ImportedFileMap>> {
{ {
let filemaps = self.codemap_import_info.borrow(); let filemaps = self.codemap_import_info.borrow();
@ -1057,67 +1125,66 @@ impl<'a, 'tcx> CrateMetadata {
let external_codemap = self.root.codemap.decode(self); let external_codemap = self.root.codemap.decode(self);
let imported_filemaps = external_codemap.map(|filemap_to_import| { let imported_filemaps = external_codemap.map(|filemap_to_import| {
// Try to find an existing FileMap that can be reused for the filemap to // Try to find an existing FileMap that can be reused for the filemap to
// be imported. A FileMap is reusable if it is exactly the same, just // be imported. A FileMap is reusable if it is exactly the same, just
// positioned at a different offset within the codemap. // positioned at a different offset within the codemap.
let reusable_filemap = { let reusable_filemap = {
local_codemap.files local_codemap.files
.borrow() .borrow()
.iter() .iter()
.find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import)) .find(|fm| are_equal_modulo_startpos(&fm, &filemap_to_import))
.map(|rc| rc.clone()) .map(|rc| rc.clone())
}; };
match reusable_filemap { match reusable_filemap {
Some(fm) => { Some(fm) => {
cstore::ImportedFileMap { cstore::ImportedFileMap {
original_start_pos: filemap_to_import.start_pos, original_start_pos: filemap_to_import.start_pos,
original_end_pos: filemap_to_import.end_pos, original_end_pos: filemap_to_import.end_pos,
translated_filemap: fm translated_filemap: fm,
}
}
None => {
// We can't reuse an existing FileMap, so allocate a new one
// containing the information we need.
let syntax_pos::FileMap { name,
abs_path,
start_pos,
end_pos,
lines,
multibyte_chars,
.. } = filemap_to_import;
let source_length = (end_pos - start_pos).to_usize();
// Translate line-start positions and multibyte character
// position into frame of reference local to file.
// `CodeMap::new_imported_filemap()` will then translate those
// coordinates to their new global frame of reference when the
// offset of the FileMap is known.
let mut lines = lines.into_inner();
for pos in &mut lines {
*pos = *pos - start_pos;
}
let mut multibyte_chars = multibyte_chars.into_inner();
for mbc in &mut multibyte_chars {
mbc.pos = mbc.pos - start_pos;
}
let local_version = local_codemap.new_imported_filemap(name,
abs_path,
source_length,
lines,
multibyte_chars);
cstore::ImportedFileMap {
original_start_pos: start_pos,
original_end_pos: end_pos,
translated_filemap: local_version,
}
} }
} }
None => { })
// We can't reuse an existing FileMap, so allocate a new one .collect();
// containing the information we need.
let syntax_pos::FileMap {
name,
abs_path,
start_pos,
end_pos,
lines,
multibyte_chars,
..
} = filemap_to_import;
let source_length = (end_pos - start_pos).to_usize();
// Translate line-start positions and multibyte character
// position into frame of reference local to file.
// `CodeMap::new_imported_filemap()` will then translate those
// coordinates to their new global frame of reference when the
// offset of the FileMap is known.
let mut lines = lines.into_inner();
for pos in &mut lines {
*pos = *pos - start_pos;
}
let mut multibyte_chars = multibyte_chars.into_inner();
for mbc in &mut multibyte_chars {
mbc.pos = mbc.pos - start_pos;
}
let local_version = local_codemap.new_imported_filemap(name,
abs_path,
source_length,
lines,
multibyte_chars);
cstore::ImportedFileMap {
original_start_pos: start_pos,
original_end_pos: end_pos,
translated_filemap: local_version
}
}
}
}).collect();
// This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref. // This shouldn't borrow twice, but there is no way to downgrade RefMut to Ref.
*self.codemap_import_info.borrow_mut() = imported_filemaps; *self.codemap_import_info.borrow_mut() = imported_filemaps;
@ -1151,8 +1218,7 @@ fn are_equal_modulo_startpos(fm1: &syntax_pos::FileMap, fm2: &syntax_pos::FileMa
} }
for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) { for (mb1, mb2) in multibytes1.iter().zip(multibytes2.iter()) {
if (mb1.bytes != mb2.bytes) || if (mb1.bytes != mb2.bytes) || ((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
((mb1.pos - fm1.start_pos) != (mb2.pos - fm2.start_pos)) {
return false; return false;
} }
} }