From bc1dde468c1613743c919cb9f33923cc9916c5b4 Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Sat, 21 Mar 2015 19:30:06 -0400 Subject: [PATCH 1/4] Compiler and trait changes to make indexing by value. --- src/libcollections/bit.rs | 12 ++++++++++++ src/libcore/ops.rs | 12 ++++++++++++ src/librustc/middle/expr_use_visitor.rs | 2 +- src/librustc_trans/trans/expr.rs | 2 +- 4 files changed, 26 insertions(+), 2 deletions(-) diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index 90fbe04d3482f..e494527b6a67c 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -169,6 +169,8 @@ pub struct BitVec { impl Index for BitVec { type Output = bool; + + #[cfg(stage0)] #[inline] fn index(&self, i: &usize) -> &bool { if self.get(*i).expect("index out of bounds") { @@ -177,6 +179,16 @@ impl Index for BitVec { &FALSE } } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, i: usize) -> &bool { + if self.get(i).expect("index out of bounds") { + &TRUE + } else { + &FALSE + } + } } /// Computes how many blocks are needed to store that many bits diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index 6324e8fa87443..e1e352b5b640c 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -917,8 +917,14 @@ pub trait Index { type Output: ?Sized; /// The method for the indexing (`Foo[Bar]`) operation + #[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] fn index<'a>(&'a self, index: &Idx) -> &'a Self::Output; + + /// The method for the indexing (`Foo[Bar]`) operation + #[cfg(not(stage0))] + #[stable(feature = "rust1", since = "1.0.0")] + fn index<'a>(&'a self, index: Idx) -> &'a Self::Output; } /// The `IndexMut` trait is used to specify the functionality of indexing @@ -960,8 +966,14 @@ pub trait Index { #[stable(feature = "rust1", since = "1.0.0")] pub trait IndexMut: Index { /// The method for the indexing (`Foo[Bar]`) operation + #[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] fn index_mut<'a>(&'a mut self, index: &Idx) -> &'a mut Self::Output; + + /// The method for the indexing (`Foo[Bar]`) operation + #[cfg(not(stage0))] + #[stable(feature = "rust1", since = "1.0.0")] + fn index_mut<'a>(&'a mut self, index: Idx) -> &'a mut Self::Output; } /// An unbounded range. diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 6d2392054f9d5..975bf01fdef6f 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -442,7 +442,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { if !self.walk_overloaded_operator(expr, &**lhs, vec![&**rhs], - PassArgs::ByRef) { + PassArgs::ByValue) { self.select_from_expr(&**lhs); self.consume_expr(&**rhs); } diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 4653ef2980a78..4aff28122bbb3 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -843,7 +843,7 @@ fn trans_index<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, base_datum, vec![(ix_datum, idx.id)], Some(SaveIn(scratch.val)), - true)); + false)); let datum = scratch.to_expr_datum(); if type_is_sized(bcx.tcx(), elt_ty) { Datum::new(datum.to_llscalarish(bcx), elt_ty, LvalueExpr) From b4d4daf007753dfb04d87b1ffe1c2ad2d8811d5a Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Sat, 21 Mar 2015 19:33:27 -0400 Subject: [PATCH 2/4] Adjust Index/IndexMut impls. For generic collections, we take references. For collections whose keys are integers, we take both references and by-value. --- src/libcollections/btree/map.rs | 15 +++ src/libcollections/string.rs | 32 +++++ src/libcollections/vec.rs | 82 ++++++++++++ src/libcollections/vec_deque.rs | 14 ++ src/libcollections/vec_map.rs | 42 +++++- src/libcore/ops.rs | 6 +- src/libcore/slice.rs | 201 +++++++++++++++++++++++++++++ src/libcore/str/mod.rs | 78 +++++++++++ src/libserialize/json.rs | 23 ++++ src/libstd/collections/hash/map.rs | 24 +++- src/libstd/ffi/os_str.rs | 12 ++ src/libstd/sys/common/wtf8.rs | 79 ++++++++++++ 12 files changed, 600 insertions(+), 8 deletions(-) diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index a9e1ce8d7ce50..0a72f24b43740 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -914,12 +914,27 @@ impl Debug for BTreeMap { } } +#[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] impl Index for BTreeMap where K: Borrow, Q: Ord { type Output = V; + #[inline] + fn index(&self, key: &Q) -> &V { + self.get(key).expect("no entry found for key") + } +} + +#[cfg(not(stage0))] +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, K: Ord, Q: ?Sized, V> Index<&'a Q> for BTreeMap + where K: Borrow, Q: Ord +{ + type Output = V; + + #[inline] fn index(&self, key: &Q) -> &V { self.get(key).expect("no entry found for key") } diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index cd6f27bf65f6e..3f869d0b8ae45 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -870,34 +870,66 @@ impl<'a> Add<&'a str> for String { #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for String { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::Range) -> &str { &self[..][*index] } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::Range) -> &str { + &self[..][index] + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for String { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeTo) -> &str { &self[..][*index] } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeTo) -> &str { + &self[..][index] + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for String { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeFrom) -> &str { &self[..][*index] } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeFrom) -> &str { + &self[..][index] + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for String { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, _index: &ops::RangeFull) -> &str { unsafe { mem::transmute(&*self.vec) } } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, _index: ops::RangeFull) -> &str { + unsafe { mem::transmute(&*self.vec) } + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index b0e8dc7d0b622..3e46ebfc44634 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1323,83 +1323,165 @@ impl Hash for Vec { impl Index for Vec { type Output = T; + + #[cfg(stage0)] #[inline] fn index(&self, index: &usize) -> &T { // NB built-in indexing via `&[T]` &(**self)[*index] } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: usize) -> &T { + // NB built-in indexing via `&[T]` + &(**self)[index] + } } #[stable(feature = "rust1", since = "1.0.0")] impl IndexMut for Vec { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &usize) -> &mut T { // NB built-in indexing via `&mut [T]` &mut (**self)[*index] } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: usize) -> &mut T { + // NB built-in indexing via `&mut [T]` + &mut (**self)[index] + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for Vec { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::Range) -> &[T] { Index::index(&**self, index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::Range) -> &[T] { + Index::index(&**self, index) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for Vec { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { Index::index(&**self, index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeTo) -> &[T] { + Index::index(&**self, index) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for Vec { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { Index::index(&**self, index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeFrom) -> &[T] { + Index::index(&**self, index) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for Vec { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, _index: &ops::RangeFull) -> &[T] { self.as_slice() } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, _index: ops::RangeFull) -> &[T] { + self.as_slice() + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for Vec { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { IndexMut::index_mut(&mut **self, index) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::Range) -> &mut [T] { + IndexMut::index_mut(&mut **self, index) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for Vec { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { IndexMut::index_mut(&mut **self, index) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::RangeTo) -> &mut [T] { + IndexMut::index_mut(&mut **self, index) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for Vec { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { IndexMut::index_mut(&mut **self, index) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::RangeFrom) -> &mut [T] { + IndexMut::index_mut(&mut **self, index) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut for Vec { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] { self.as_mut_slice() } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] { + self.as_mut_slice() + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcollections/vec_deque.rs b/src/libcollections/vec_deque.rs index 56ca74dab1f0f..591ad48f57912 100644 --- a/src/libcollections/vec_deque.rs +++ b/src/libcollections/vec_deque.rs @@ -1689,18 +1689,32 @@ impl Hash for VecDeque { impl Index for VecDeque { type Output = A; + #[cfg(stage0)] #[inline] fn index(&self, i: &usize) -> &A { self.get(*i).expect("Out of bounds access") } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, i: usize) -> &A { + self.get(i).expect("Out of bounds access") + } } #[stable(feature = "rust1", since = "1.0.0")] impl IndexMut for VecDeque { + #[cfg(stage0)] #[inline] fn index_mut(&mut self, i: &usize) -> &mut A { self.get_mut(*i).expect("Out of bounds access") } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, i: usize) -> &mut A { + self.get_mut(i).expect("Out of bounds access") + } } #[stable(feature = "rust1", since = "1.0.0")] diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index 6e67d8763273d..05693ec52756a 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -798,6 +798,7 @@ impl Extend<(usize, V)> for VecMap { } } +#[cfg(stage0)] impl Index for VecMap { type Output = V; @@ -807,10 +808,49 @@ impl Index for VecMap { } } +#[cfg(not(stage0))] +impl Index for VecMap { + type Output = V; + + #[inline] + fn index<'a>(&'a self, i: usize) -> &'a V { + self.get(&i).expect("key not present") + } +} + +#[cfg(not(stage0))] +impl<'a,V> Index<&'a usize> for VecMap { + type Output = V; + + #[inline] + fn index(&self, i: &usize) -> &V { + self.get(i).expect("key not present") + } +} + +#[cfg(stage0)] +#[stable(feature = "rust1", since = "1.0.0")] +impl IndexMut for VecMap { + #[inline] + fn index_mut(&mut self, i: &usize) -> &mut V { + self.get_mut(&i).expect("key not present") + } +} + +#[cfg(not(stage0))] #[stable(feature = "rust1", since = "1.0.0")] impl IndexMut for VecMap { #[inline] - fn index_mut<'a>(&'a mut self, i: &usize) -> &'a mut V { + fn index_mut(&mut self, i: usize) -> &mut V { + self.get_mut(&i).expect("key not present") + } +} + +#[cfg(not(stage0))] +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, V> IndexMut<&'a usize> for VecMap { + #[inline] + fn index_mut(&mut self, i: &usize) -> &mut V { self.get_mut(i).expect("key not present") } } diff --git a/src/libcore/ops.rs b/src/libcore/ops.rs index e1e352b5b640c..6e6f97a7af7d9 100644 --- a/src/libcore/ops.rs +++ b/src/libcore/ops.rs @@ -898,7 +898,7 @@ shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize } /// impl Index for Foo { /// type Output = Foo; /// -/// fn index<'a>(&'a self, _index: &Bar) -> &'a Foo { +/// fn index<'a>(&'a self, _index: Bar) -> &'a Foo { /// println!("Indexing!"); /// self /// } @@ -945,13 +945,13 @@ pub trait Index { /// impl Index for Foo { /// type Output = Foo; /// -/// fn index<'a>(&'a self, _index: &Bar) -> &'a Foo { +/// fn index<'a>(&'a self, _index: Bar) -> &'a Foo { /// self /// } /// } /// /// impl IndexMut for Foo { -/// fn index_mut<'a>(&'a mut self, _index: &Bar) -> &'a mut Foo { +/// fn index_mut<'a>(&'a mut self, _index: Bar) -> &'a mut Foo { /// println!("Indexing!"); /// self /// } diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index 907b2eba80c5b..04b425416f3af 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -263,6 +263,7 @@ impl SliceExt for [T] { #[inline] fn as_mut_slice(&mut self) -> &mut [T] { self } + #[cfg(stage0)] #[inline] fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { unsafe { @@ -273,6 +274,17 @@ impl SliceExt for [T] { } } + #[cfg(not(stage0))] + #[inline] + fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { + unsafe { + let self2: &mut [T] = mem::transmute_copy(&self); + + (ops::IndexMut::index_mut(self, ops::RangeTo { end: mid } ), + ops::IndexMut::index_mut(self2, ops::RangeFrom { start: mid } )) + } + } + #[inline] fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { unsafe { @@ -495,25 +507,45 @@ impl SliceExt for [T] { impl ops::Index for [T] { type Output = T; + #[cfg(stage0)] fn index(&self, &index: &usize) -> &T { assert!(index < self.len()); unsafe { mem::transmute(self.repr().data.offset(index as isize)) } } + + #[cfg(not(stage0))] + fn index(&self, index: usize) -> &T { + assert!(index < self.len()); + + unsafe { mem::transmute(self.repr().data.offset(index as isize)) } + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut for [T] { + #[cfg(stage0)] + #[inline] fn index_mut(&mut self, &index: &usize) -> &mut T { assert!(index < self.len()); unsafe { mem::transmute(self.repr().data.offset(index as isize)) } } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: usize) -> &mut T { + assert!(index < self.len()); + + unsafe { mem::transmute(self.repr().data.offset(index as isize)) } + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for [T] { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::Range) -> &[T] { assert!(index.start <= index.end); @@ -525,34 +557,72 @@ impl ops::Index> for [T] { ) } } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::Range) -> &[T] { + assert!(index.start <= index.end); + assert!(index.end <= self.len()); + unsafe { + from_raw_parts ( + self.as_ptr().offset(index.start as isize), + index.end - index.start + ) + } + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for [T] { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.index(&ops::Range{ start: 0, end: index.end }) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeTo) -> &[T] { + self.index(ops::Range{ start: 0, end: index.end }) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for [T] { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.index(&ops::Range{ start: index.start, end: self.len() }) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeFrom) -> &[T] { + self.index(ops::Range{ start: index.start, end: self.len() }) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for [T] { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, _index: &RangeFull) -> &[T] { self } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, _index: RangeFull) -> &[T] { + self + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for [T] { + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { assert!(index.start <= index.end); @@ -564,28 +634,64 @@ impl ops::IndexMut> for [T] { ) } } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::Range) -> &mut [T] { + assert!(index.start <= index.end); + assert!(index.end <= self.len()); + unsafe { + from_raw_parts_mut( + self.as_mut_ptr().offset(index.start as isize), + index.end - index.start + ) + } + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for [T] { + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.index_mut(&ops::Range{ start: 0, end: index.end }) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::RangeTo) -> &mut [T] { + self.index_mut(ops::Range{ start: 0, end: index.end }) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut> for [T] { + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { let len = self.len(); self.index_mut(&ops::Range{ start: index.start, end: len }) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::RangeFrom) -> &mut [T] { + let len = self.len(); + self.index_mut(ops::Range{ start: index.start, end: len }) + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::IndexMut for [T] { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] { self } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, _index: RangeFull) -> &mut [T] { + self + } } @@ -763,37 +869,69 @@ unsafe impl<'a, T: Sync> Send for Iter<'a, T> {} #[unstable(feature = "core")] impl<'a, T> ops::Index> for Iter<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.as_slice().index(index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::Range) -> &[T] { + self.as_slice().index(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::Index> for Iter<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.as_slice().index(index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeTo) -> &[T] { + self.as_slice().index(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::Index> for Iter<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.as_slice().index(index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeFrom) -> &[T] { + self.as_slice().index(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::Index for Iter<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, _index: &RangeFull) -> &[T] { self.as_slice() } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, _index: RangeFull) -> &[T] { + self.as_slice() + } } impl<'a, T> Iter<'a, T> { @@ -856,63 +994,126 @@ unsafe impl<'a, T: Send> Send for IterMut<'a, T> {} #[unstable(feature = "core")] impl<'a, T> ops::Index> for IterMut<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.index(&RangeFull).index(index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::Range) -> &[T] { + self.index(RangeFull).index(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::Index> for IterMut<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.index(&RangeFull).index(index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeTo) -> &[T] { + self.index(RangeFull).index(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::Index> for IterMut<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.index(&RangeFull).index(index) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeFrom) -> &[T] { + self.index(RangeFull).index(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::Index for IterMut<'a, T> { type Output = [T]; + + #[cfg(stage0)] #[inline] fn index(&self, _index: &RangeFull) -> &[T] { make_slice!(T => &[T]: self.ptr, self.end) } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, _index: RangeFull) -> &[T] { + make_slice!(T => &[T]: self.ptr, self.end) + } } #[unstable(feature = "core")] impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { self.index_mut(&RangeFull).index_mut(index) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::Range) -> &mut [T] { + self.index_mut(RangeFull).index_mut(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.index_mut(&RangeFull).index_mut(index) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::RangeTo) -> &mut [T] { + self.index_mut(RangeFull).index_mut(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { self.index_mut(&RangeFull).index_mut(index) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, index: ops::RangeFrom) -> &mut [T] { + self.index_mut(RangeFull).index_mut(index) + } } #[unstable(feature = "core")] impl<'a, T> ops::IndexMut for IterMut<'a, T> { + + #[cfg(stage0)] #[inline] fn index_mut(&mut self, _index: &RangeFull) -> &mut [T] { make_mut_slice!(T => &mut [T]: self.ptr, self.end) } + + #[cfg(not(stage0))] + #[inline] + fn index_mut(&mut self, _index: RangeFull) -> &mut [T] { + make_mut_slice!(T => &mut [T]: self.ptr, self.end) + } } diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index e8181395b5c1e..b9a655c6d4e28 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1203,6 +1203,7 @@ mod traits { /// // byte 100 is outside the string /// // &s[3 .. 100]; /// ``` + #[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for str { type Output = str; @@ -1219,6 +1220,49 @@ mod traits { } } + /// Returns a slice of the given string from the byte range + /// [`begin`..`end`). + /// + /// This operation is `O(1)`. + /// + /// Panics when `begin` and `end` do not point to valid characters + /// or point beyond the last character of the string. + /// + /// # Examples + /// + /// ``` + /// let s = "Löwe 老虎 Léopard"; + /// assert_eq!(&s[0 .. 1], "L"); + /// + /// assert_eq!(&s[1 .. 9], "öwe 老"); + /// + /// // these will panic: + /// // byte 2 lies within `ö`: + /// // &s[2 ..3]; + /// + /// // byte 8 lies within `老` + /// // &s[1 .. 8]; + /// + /// // byte 100 is outside the string + /// // &s[3 .. 100]; + /// ``` + #[cfg(not(stage0))] + #[stable(feature = "rust1", since = "1.0.0")] + impl ops::Index> for str { + type Output = str; + #[inline] + fn index(&self, index: ops::Range) -> &str { + // is_char_boundary checks that the index is in [0, .len()] + if index.start <= index.end && + self.is_char_boundary(index.start) && + self.is_char_boundary(index.end) { + unsafe { self.slice_unchecked(index.start, index.end) } + } else { + super::slice_error_fail(self, index.start, index.end) + } + } + } + /// Returns a slice of the string from the beginning to byte /// `end`. /// @@ -1229,6 +1273,8 @@ mod traits { #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for str { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeTo) -> &str { // is_char_boundary checks that the index is in [0, .len()] @@ -1238,6 +1284,17 @@ mod traits { super::slice_error_fail(self, 0, index.end) } } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeTo) -> &str { + // is_char_boundary checks that the index is in [0, .len()] + if self.is_char_boundary(index.end) { + unsafe { self.slice_unchecked(0, index.end) } + } else { + super::slice_error_fail(self, 0, index.end) + } + } } /// Returns a slice of the string from `begin` to its end. @@ -1249,6 +1306,8 @@ mod traits { #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index> for str { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, index: &ops::RangeFrom) -> &str { // is_char_boundary checks that the index is in [0, .len()] @@ -1258,15 +1317,34 @@ mod traits { super::slice_error_fail(self, index.start, self.len()) } } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, index: ops::RangeFrom) -> &str { + // is_char_boundary checks that the index is in [0, .len()] + if self.is_char_boundary(index.start) { + unsafe { self.slice_unchecked(index.start, self.len()) } + } else { + super::slice_error_fail(self, index.start, self.len()) + } + } } #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for str { type Output = str; + + #[cfg(stage0)] #[inline] fn index(&self, _index: &ops::RangeFull) -> &str { self } + + #[cfg(not(stage0))] + #[inline] + fn index(&self, _index: ops::RangeFull) -> &str { + self + } } } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 096c72e6af2db..abbfc82319f5b 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1218,6 +1218,7 @@ impl Json { } } +#[cfg(stage0)] impl<'a> Index<&'a str> for Json { type Output = Json; @@ -1226,6 +1227,16 @@ impl<'a> Index<&'a str> for Json { } } +#[cfg(not(stage0))] +impl<'a> Index<&'a str> for Json { + type Output = Json; + + fn index(&self, idx: &'a str) -> &Json { + self.find(idx).unwrap() + } +} + +#[cfg(stage0)] impl Index for Json { type Output = Json; @@ -1237,6 +1248,18 @@ impl Index for Json { } } +#[cfg(not(stage0))] +impl Index for Json { + type Output = Json; + + fn index<'a>(&'a self, idx: uint) -> &'a Json { + match self { + &Json::Array(ref v) => &v[idx], + _ => panic!("can only index Json with uint if it is an array") + } + } +} + /// The output of the streaming parser. #[derive(PartialEq, Clone, Debug)] pub enum JsonEvent { diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 9139e182ce479..86664d7eb0cf1 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -1088,7 +1088,7 @@ impl HashMap /// Some(x) => *x = "b", /// None => (), /// } - /// assert_eq!(map[1], "b"); + /// assert_eq!(map[&1], "b"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> @@ -1111,7 +1111,7 @@ impl HashMap /// /// map.insert(37, "b"); /// assert_eq!(map.insert(37, "c"), Some("b")); - /// assert_eq!(map[37], "c"); + /// assert_eq!(map[&37], "c"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn insert(&mut self, k: K, v: V) -> Option { @@ -1244,6 +1244,7 @@ impl Default for HashMap } } +#[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] impl Index for HashMap where K: Eq + Hash + Borrow, @@ -1258,6 +1259,21 @@ impl Index for HashMap } } +#[cfg(not(stage0))] +#[stable(feature = "rust1", since = "1.0.0")] +impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap + where K: Eq + Hash + Borrow, + Q: Eq + Hash, + S: HashState, +{ + type Output = V; + + #[inline] + fn index(&self, index: &Q) -> &V { + self.get(index).expect("no entry found for key") + } +} + /// HashMap iterator. #[stable(feature = "rust1", since = "1.0.0")] pub struct Iter<'a, K: 'a, V: 'a> { @@ -2185,7 +2201,7 @@ mod test_map { map.insert(2, 1); map.insert(3, 4); - assert_eq!(map[2], 1); + assert_eq!(map[&2], 1); } #[test] @@ -2197,7 +2213,7 @@ mod test_map { map.insert(2, 1); map.insert(3, 4); - map[4]; + map[&4]; } #[test] diff --git a/src/libstd/ffi/os_str.rs b/src/libstd/ffi/os_str.rs index feacbf1e98b81..290c48b1310d5 100644 --- a/src/libstd/ffi/os_str.rs +++ b/src/libstd/ffi/os_str.rs @@ -103,6 +103,7 @@ impl OsString { } } +#[cfg(stage0)] #[stable(feature = "rust1", since = "1.0.0")] impl ops::Index for OsString { type Output = OsStr; @@ -113,6 +114,17 @@ impl ops::Index for OsString { } } +#[cfg(not(stage0))] +#[stable(feature = "rust1", since = "1.0.0")] +impl ops::Index for OsString { + type Output = OsStr; + + #[inline] + fn index(&self, _index: ops::RangeFull) -> &OsStr { + unsafe { mem::transmute(self.inner.as_slice()) } + } +} + #[stable(feature = "rust1", since = "1.0.0")] impl ops::Deref for OsString { type Target = OsStr; diff --git a/src/libstd/sys/common/wtf8.rs b/src/libstd/sys/common/wtf8.rs index 3cc91bf54b4d9..9f3dae34c7a4b 100644 --- a/src/libstd/sys/common/wtf8.rs +++ b/src/libstd/sys/common/wtf8.rs @@ -634,6 +634,7 @@ impl Wtf8 { /// /// Panics when `begin` and `end` do not point to code point boundaries, /// or point beyond the end of the string. +#[cfg(stage0)] impl ops::Index> for Wtf8 { type Output = Wtf8; @@ -650,12 +651,36 @@ impl ops::Index> for Wtf8 { } } +/// Return a slice of the given string for the byte range [`begin`..`end`). +/// +/// # Panics +/// +/// Panics when `begin` and `end` do not point to code point boundaries, +/// or point beyond the end of the string. +#[cfg(not(stage0))] +impl ops::Index> for Wtf8 { + type Output = Wtf8; + + #[inline] + fn index(&self, range: ops::Range) -> &Wtf8 { + // is_code_point_boundary checks that the index is in [0, .len()] + if range.start <= range.end && + is_code_point_boundary(self, range.start) && + is_code_point_boundary(self, range.end) { + unsafe { slice_unchecked(self, range.start, range.end) } + } else { + slice_error_fail(self, range.start, range.end) + } + } +} + /// Return a slice of the given string from byte `begin` to its end. /// /// # Panics /// /// Panics when `begin` is not at a code point boundary, /// or is beyond the end of the string. +#[cfg(stage0)] impl ops::Index> for Wtf8 { type Output = Wtf8; @@ -670,12 +695,34 @@ impl ops::Index> for Wtf8 { } } +/// Return a slice of the given string from byte `begin` to its end. +/// +/// # Panics +/// +/// Panics when `begin` is not at a code point boundary, +/// or is beyond the end of the string. +#[cfg(not(stage0))] +impl ops::Index> for Wtf8 { + type Output = Wtf8; + + #[inline] + fn index(&self, range: ops::RangeFrom) -> &Wtf8 { + // is_code_point_boundary checks that the index is in [0, .len()] + if is_code_point_boundary(self, range.start) { + unsafe { slice_unchecked(self, range.start, self.len()) } + } else { + slice_error_fail(self, range.start, self.len()) + } + } +} + /// Return a slice of the given string from its beginning to byte `end`. /// /// # Panics /// /// Panics when `end` is not at a code point boundary, /// or is beyond the end of the string. +#[cfg(stage0)] impl ops::Index> for Wtf8 { type Output = Wtf8; @@ -690,6 +737,28 @@ impl ops::Index> for Wtf8 { } } +/// Return a slice of the given string from its beginning to byte `end`. +/// +/// # Panics +/// +/// Panics when `end` is not at a code point boundary, +/// or is beyond the end of the string. +#[cfg(not(stage0))] +impl ops::Index> for Wtf8 { + type Output = Wtf8; + + #[inline] + fn index(&self, range: ops::RangeTo) -> &Wtf8 { + // is_code_point_boundary checks that the index is in [0, .len()] + if is_code_point_boundary(self, range.end) { + unsafe { slice_unchecked(self, 0, range.end) } + } else { + slice_error_fail(self, 0, range.end) + } + } +} + +#[cfg(stage0)] impl ops::Index for Wtf8 { type Output = Wtf8; @@ -699,6 +768,16 @@ impl ops::Index for Wtf8 { } } +#[cfg(not(stage0))] +impl ops::Index for Wtf8 { + type Output = Wtf8; + + #[inline] + fn index(&self, _range: ops::RangeFull) -> &Wtf8 { + self + } +} + #[inline] fn decode_surrogate(second_byte: u8, third_byte: u8) -> u16 { // The first byte is assumed to be 0xED From 8e58af40044a69a9a88de86e222c287eb79a4dcc Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Sat, 21 Mar 2015 21:15:47 -0400 Subject: [PATCH 3/4] Fallout in stdlib, rustdoc, rustc, etc. For most maps, converted uses of `[]` on maps to `get` in rustc, since stage0 and stage1+ disagree about how to use `[]`. --- src/libcollections/btree/map.rs | 4 +- src/libcollections/btree/node.rs | 61 +++++++++++++++++++ src/librustc/metadata/cstore.rs | 2 +- src/librustc/metadata/encoder.rs | 6 +- src/librustc/middle/astencode.rs | 2 +- src/librustc/middle/check_match.rs | 4 +- src/librustc/middle/const_eval.rs | 2 +- src/librustc/middle/dead.rs | 4 +- src/librustc/middle/effect.rs | 2 +- src/librustc/middle/expr_use_visitor.rs | 2 +- .../middle/infer/region_inference/mod.rs | 2 +- src/librustc/middle/liveness.rs | 8 ++- src/librustc/middle/mem_categorization.rs | 2 +- src/librustc/middle/reachable.rs | 2 +- src/librustc/middle/stability.rs | 2 +- src/librustc/middle/traits/project.rs | 4 +- src/librustc/middle/ty.rs | 8 +-- src/librustc_borrowck/borrowck/move_data.rs | 2 +- src/librustc_lint/builtin.rs | 2 +- src/librustc_privacy/lib.rs | 18 +++--- src/librustc_trans/back/link.rs | 4 +- src/librustc_trans/save/mod.rs | 31 ++++++---- src/librustc_trans/trans/_match.rs | 2 +- src/librustc_trans/trans/base.rs | 4 +- src/librustc_trans/trans/callee.rs | 2 +- src/librustc_trans/trans/common.rs | 4 +- src/librustc_trans/trans/consts.rs | 6 +- src/librustc_trans/trans/expr.rs | 18 +++--- src/librustc_typeck/astconv.rs | 2 +- src/librustc_typeck/check/_match.rs | 8 +-- src/librustc_typeck/check/mod.rs | 10 +-- src/librustc_typeck/check/upvar.rs | 2 +- src/librustc_typeck/coherence/mod.rs | 4 +- src/librustc_typeck/collect.rs | 14 +++-- src/librustdoc/html/format.rs | 6 +- src/librustdoc/html/render.rs | 6 +- src/librustdoc/visit_ast.rs | 2 +- src/libstd/thread_local/mod.rs | 2 +- src/libsyntax/ext/format.rs | 2 +- src/libsyntax/ext/tt/macro_rules.rs | 4 +- src/test/auxiliary/issue-2631-a.rs | 2 +- src/test/auxiliary/procedural_mbe_matching.rs | 2 +- ...k-overloaded-index-and-overloaded-deref.rs | 2 +- .../borrowck-overloaded-index-autoderef.rs | 45 +++++++++----- src/test/compile-fail/dst-index.rs | 4 +- src/test/run-pass/dst-index.rs | 4 +- src/test/run-pass/issue-15734.rs | 10 +-- src/test/run-pass/issue-2804-2.rs | 2 +- src/test/run-pass/issue-2804.rs | 5 +- src/test/run-pass/issue-5521.rs | 2 +- src/test/run-pass/issue-7660.rs | 4 +- src/test/run-pass/operator-overloading.rs | 4 +- .../run-pass/overloaded-index-assoc-list.rs | 10 +-- .../run-pass/overloaded-index-autoderef.rs | 8 +-- .../run-pass/overloaded-index-in-field.rs | 4 +- src/test/run-pass/overloaded-index.rs | 8 +-- src/test/run-pass/slice.rs | 16 ++--- 57 files changed, 245 insertions(+), 159 deletions(-) diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index 0a72f24b43740..755f564621a0f 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -264,7 +264,7 @@ impl BTreeMap { /// Some(x) => *x = "b", /// None => (), /// } - /// assert_eq!(map[1], "b"); + /// assert_eq!(map[&1], "b"); /// ``` // See `get` for implementation notes, this is basically a copy-paste with mut's added #[stable(feature = "rust1", since = "1.0.0")] @@ -326,7 +326,7 @@ impl BTreeMap { /// /// map.insert(37, "b"); /// assert_eq!(map.insert(37, "c"), Some("b")); - /// assert_eq!(map[37], "c"); + /// assert_eq!(map[&37], "c"); /// ``` #[stable(feature = "rust1", since = "1.0.0")] pub fn insert(&mut self, mut key: K, mut value: V) -> Option { diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index bfac3b2df5a5c..5b8a5f029762e 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -1522,6 +1522,7 @@ macro_rules! node_slice_impl { } /// Returns a sub-slice with elements starting with `min_key`. + #[cfg(stage0)] pub fn slice_from(self, min_key: &K) -> $NodeSlice<'a, K, V> { // _______________ // |_1_|_3_|_5_|_7_| @@ -1549,7 +1550,37 @@ macro_rules! node_slice_impl { } } + /// Returns a sub-slice with elements starting with `min_key`. + #[cfg(not(stage0))] + pub fn slice_from(self, min_key: &K) -> $NodeSlice<'a, K, V> { + // _______________ + // |_1_|_3_|_5_|_7_| + // | | | | | + // 0 0 1 1 2 2 3 3 4 index + // | | | | | + // \___|___|___|___/ slice_from(&0); pos = 0 + // \___|___|___/ slice_from(&2); pos = 1 + // |___|___|___/ slice_from(&3); pos = 1; result.head_is_edge = false + // \___|___/ slice_from(&4); pos = 2 + // \___/ slice_from(&6); pos = 3 + // \|/ slice_from(&999); pos = 4 + let (pos, pos_is_kv) = self.search_linear(min_key); + $NodeSlice { + has_edges: self.has_edges, + edges: if !self.has_edges { + self.edges + } else { + self.edges.$index(pos ..) + }, + keys: &self.keys[pos ..], + vals: self.vals.$index(pos ..), + head_is_edge: !pos_is_kv, + tail_is_edge: self.tail_is_edge, + } + } + /// Returns a sub-slice with elements up to and including `max_key`. + #[cfg(stage0)] pub fn slice_to(self, max_key: &K) -> $NodeSlice<'a, K, V> { // _______________ // |_1_|_3_|_5_|_7_| @@ -1577,6 +1608,36 @@ macro_rules! node_slice_impl { tail_is_edge: !pos_is_kv, } } + + /// Returns a sub-slice with elements up to and including `max_key`. + #[cfg(not(stage0))] + pub fn slice_to(self, max_key: &K) -> $NodeSlice<'a, K, V> { + // _______________ + // |_1_|_3_|_5_|_7_| + // | | | | | + // 0 0 1 1 2 2 3 3 4 index + // | | | | | + //\|/ | | | | slice_to(&0); pos = 0 + // \___/ | | | slice_to(&2); pos = 1 + // \___|___| | | slice_to(&3); pos = 1; result.tail_is_edge = false + // \___|___/ | | slice_to(&4); pos = 2 + // \___|___|___/ | slice_to(&6); pos = 3 + // \___|___|___|___/ slice_to(&999); pos = 4 + let (pos, pos_is_kv) = self.search_linear(max_key); + let pos = pos + if pos_is_kv { 1 } else { 0 }; + $NodeSlice { + has_edges: self.has_edges, + edges: if !self.has_edges { + self.edges + } else { + self.edges.$index(.. (pos + 1)) + }, + keys: &self.keys[..pos], + vals: self.vals.$index(.. pos), + head_is_edge: self.head_is_edge, + tail_is_edge: !pos_is_kv, + } + } } impl<'a, K: 'a, V: 'a> $NodeSlice<'a, K, V> { diff --git a/src/librustc/metadata/cstore.rs b/src/librustc/metadata/cstore.rs index 47ec31c0f1ab7..2499853ace1e3 100644 --- a/src/librustc/metadata/cstore.rs +++ b/src/librustc/metadata/cstore.rs @@ -111,7 +111,7 @@ impl CStore { } pub fn get_crate_data(&self, cnum: ast::CrateNum) -> Rc { - (*self.metas.borrow())[cnum].clone() + self.metas.borrow().get(&cnum).unwrap().clone() } pub fn get_crate_hash(&self, cnum: ast::CrateNum) -> Svh { diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 10461e3d2aedf..fa8d0b2a56e4e 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -375,7 +375,7 @@ fn encode_reexported_static_base_methods(ecx: &EncodeContext, match ecx.tcx.inherent_impls.borrow().get(&exp.def_id) { Some(implementations) => { for base_impl_did in &**implementations { - for &method_did in &*(*impl_items)[*base_impl_did] { + for &method_did in impl_items.get(base_impl_did).unwrap() { let impl_item = ty::impl_or_trait_item( ecx.tcx, method_did.def_id()); @@ -1175,7 +1175,7 @@ fn encode_info_for_item(ecx: &EncodeContext, // We need to encode information about the default methods we // have inherited, so we drive this based on the impl structure. let impl_items = tcx.impl_items.borrow(); - let items = &(*impl_items)[def_id]; + let items = impl_items.get(&def_id).unwrap(); add_to_index(item, rbml_w, index); rbml_w.start_tag(tag_items_data_item); @@ -1816,7 +1816,7 @@ struct ImplVisitor<'a, 'b:'a, 'c:'a, 'tcx:'b> { impl<'a, 'b, 'c, 'tcx, 'v> Visitor<'v> for ImplVisitor<'a, 'b, 'c, 'tcx> { fn visit_item(&mut self, item: &ast::Item) { if let ast::ItemImpl(_, _, _, Some(ref trait_ref), _, _) = item.node { - let def_id = self.ecx.tcx.def_map.borrow()[trait_ref.ref_id].def_id(); + let def_id = self.ecx.tcx.def_map.borrow().get(&trait_ref.ref_id).unwrap().def_id(); // Load eagerly if this is an implementation of the Drop trait // or if the trait is not defined in this crate. diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index bffcb93bc6d06..801350e8a1e9c 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -1228,7 +1228,7 @@ fn encode_side_tables_for_id(ecx: &e::EncodeContext, var_id: var_id, closure_expr_id: id }; - let upvar_capture = tcx.upvar_capture_map.borrow()[upvar_id].clone(); + let upvar_capture = tcx.upvar_capture_map.borrow().get(&upvar_id).unwrap().clone(); var_id.encode(rbml_w); upvar_capture.encode(rbml_w); }) diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 496c96c7c8adc..97cd9456098b1 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -874,7 +874,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], } ast::PatEnum(_, ref args) => { - let def = cx.tcx.def_map.borrow()[pat_id].full_def(); + let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def(); match def { DefConst(..) => cx.tcx.sess.span_bug(pat_span, "const pattern should've \ @@ -892,7 +892,7 @@ pub fn specialize<'a>(cx: &MatchCheckCtxt, r: &[&'a Pat], ast::PatStruct(_, ref pattern_fields, _) => { // Is this a struct or an enum variant? - let def = cx.tcx.def_map.borrow()[pat_id].full_def(); + let def = cx.tcx.def_map.borrow().get(&pat_id).unwrap().full_def(); let class_id = match def { DefConst(..) => cx.tcx.sess.span_bug(pat_span, "const pattern should've \ diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 96433729a9b96..f9598237ff460 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -150,7 +150,7 @@ pub fn const_expr_to_pat(tcx: &ty::ctxt, expr: &Expr, span: Span) -> P ast::PatTup(exprs.iter().map(|expr| const_expr_to_pat(tcx, &**expr, span)).collect()), ast::ExprCall(ref callee, ref args) => { - let def = tcx.def_map.borrow()[callee.id]; + let def = *tcx.def_map.borrow().get(&callee.id).unwrap(); if let Vacant(entry) = tcx.def_map.borrow_mut().entry(expr.id) { entry.insert(def); } diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 5efea66ab0c6c..6d4d759476ed5 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -158,7 +158,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { fn handle_field_pattern_match(&mut self, lhs: &ast::Pat, pats: &[codemap::Spanned]) { - let id = match self.tcx.def_map.borrow()[lhs.id].full_def() { + let id = match self.tcx.def_map.borrow().get(&lhs.id).unwrap().full_def() { def::DefVariant(_, id, _) => id, _ => { match ty::ty_to_def_id(ty::node_id_to_type(self.tcx, @@ -496,7 +496,7 @@ impl<'a, 'tcx> DeadVisitor<'a, 'tcx> { None => (), Some(impl_list) => { for impl_did in &**impl_list { - for item_did in &(*impl_items)[*impl_did] { + for item_did in &*impl_items.get(impl_did).unwrap() { if self.live_symbols.contains(&item_did.def_id() .node) { return true; diff --git a/src/librustc/middle/effect.rs b/src/librustc/middle/effect.rs index 378f3db082339..5d970c59f639b 100644 --- a/src/librustc/middle/effect.rs +++ b/src/librustc/middle/effect.rs @@ -141,7 +141,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EffectCheckVisitor<'a, 'tcx> { match expr.node { ast::ExprMethodCall(_, _, _) => { let method_call = MethodCall::expr(expr.id); - let base_type = (*self.tcx.method_map.borrow())[method_call].ty; + let base_type = self.tcx.method_map.borrow().get(&method_call).unwrap().ty; debug!("effect: method call case, base type is {}", ppaux::ty_to_string(self.tcx, base_type)); if type_is_unsafe_function(base_type) { diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 975bf01fdef6f..97314b57ef656 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -1012,7 +1012,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { // Each match binding is effectively an assignment to the // binding being produced. - let def = def_map.borrow()[pat.id].full_def(); + let def = def_map.borrow().get(&pat.id).unwrap().full_def(); match mc.cat_def(pat.id, pat.span, pat_ty, def) { Ok(binding_cmt) => { delegate.mutate(pat.id, pat.span, binding_cmt, Init); diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index 759d7357df193..553e360180667 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -1533,7 +1533,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { ConstrainVarSubReg(_, region) => { state.result.push(RegionAndOrigin { region: region, - origin: this.constraints.borrow()[edge.data].clone() + origin: this.constraints.borrow().get(&edge.data).unwrap().clone() }); } } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 932c9c61ef1fb..705f20559afde 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -448,7 +448,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { match expr.node { // live nodes required for uses or definitions of variables: ast::ExprPath(..) => { - let def = ir.tcx.def_map.borrow()[expr.id].full_def(); + let def = ir.tcx.def_map.borrow().get(&expr.id).unwrap().full_def(); debug!("expr {}: path that leads to {:?}", expr.id, def); if let DefLocal(..) = def { ir.add_live_node_for_node(expr.id, ExprNode(expr.span)); @@ -1302,7 +1302,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { fn access_path(&mut self, expr: &Expr, succ: LiveNode, acc: u32) -> LiveNode { - match self.ir.tcx.def_map.borrow()[expr.id].full_def() { + match self.ir.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() { DefLocal(nid) => { let ln = self.live_node(expr.id, expr.span); if acc != 0 { @@ -1564,7 +1564,9 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { fn check_lvalue(&mut self, expr: &Expr) { match expr.node { ast::ExprPath(..) => { - if let DefLocal(nid) = self.ir.tcx.def_map.borrow()[expr.id].full_def() { + if let DefLocal(nid) = self.ir.tcx.def_map.borrow().get(&expr.id) + .unwrap() + .full_def() { // Assignment to an immutable variable or argument: only legal // if there is no later assignment. If this local is actually // mutable, then check for a reassignment to flag the mutability diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 5237a86ebb630..bdcfc67f92b99 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -531,7 +531,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { } ast::ExprPath(..) => { - let def = self.tcx().def_map.borrow()[expr.id].full_def(); + let def = self.tcx().def_map.borrow().get(&expr.id).unwrap().full_def(); self.cat_def(expr.id, expr.span, expr_ty, def) } diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index 7ded344414ce6..1bd45b5fc8601 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -128,7 +128,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for ReachableContext<'a, 'tcx> { } ast::ExprMethodCall(..) => { let method_call = ty::MethodCall::expr(expr.id); - match (*self.tcx.method_map.borrow())[method_call].origin { + match (*self.tcx.method_map.borrow()).get(&method_call).unwrap().origin { ty::MethodStatic(def_id) => { if is_local(def_id) { if self.def_id_represents_local_inlined_item(def_id) { diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index 01766b0de085f..d12b737619c8d 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -319,7 +319,7 @@ pub fn check_item(tcx: &ty::ctxt, item: &ast::Item, warn_about_defns: bool, // individually as it's possible to have a stable trait with unstable // items. ast::ItemImpl(_, _, _, Some(ref t), _, ref impl_items) => { - let trait_did = tcx.def_map.borrow()[t.ref_id].def_id(); + let trait_did = tcx.def_map.borrow().get(&t.ref_id).unwrap().def_id(); let trait_items = ty::trait_items(tcx, trait_did); for impl_item in impl_items { diff --git a/src/librustc/middle/traits/project.rs b/src/librustc/middle/traits/project.rs index 6b66d7227d300..a9504910ac162 100644 --- a/src/librustc/middle/traits/project.rs +++ b/src/librustc/middle/traits/project.rs @@ -854,10 +854,10 @@ fn confirm_impl_candidate<'cx,'tcx>( let impl_items_map = selcx.tcx().impl_items.borrow(); let impl_or_trait_items_map = selcx.tcx().impl_or_trait_items.borrow(); - let impl_items = &impl_items_map[impl_vtable.impl_def_id]; + let impl_items = impl_items_map.get(&impl_vtable.impl_def_id).unwrap(); let mut impl_ty = None; for impl_item in impl_items { - let assoc_type = match impl_or_trait_items_map[impl_item.def_id()] { + let assoc_type = match *impl_or_trait_items_map.get(&impl_item.def_id()).unwrap() { ty::TypeTraitItem(ref assoc_type) => assoc_type.clone(), ty::MethodTraitItem(..) => { continue; } }; diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 99c35c6e54258..5088b733c4abb 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -2667,7 +2667,7 @@ impl<'tcx> ctxt<'tcx> { } pub fn closure_kind(&self, def_id: ast::DefId) -> ty::ClosureKind { - self.closure_kinds.borrow()[def_id] + *self.closure_kinds.borrow().get(&def_id).unwrap() } pub fn closure_type(&self, @@ -2675,14 +2675,14 @@ impl<'tcx> ctxt<'tcx> { substs: &subst::Substs<'tcx>) -> ty::ClosureTy<'tcx> { - self.closure_tys.borrow()[def_id].subst(self, substs) + self.closure_tys.borrow().get(&def_id).unwrap().subst(self, substs) } pub fn type_parameter_def(&self, node_id: ast::NodeId) -> TypeParameterDef<'tcx> { - self.ty_param_defs.borrow()[node_id].clone() + self.ty_param_defs.borrow().get(&node_id).unwrap().clone() } } @@ -6540,7 +6540,7 @@ impl<'tcx> ctxt<'tcx> { } pub fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option { - Some(self.upvar_capture_map.borrow()[upvar_id].clone()) + Some(self.upvar_capture_map.borrow().get(&upvar_id).unwrap().clone()) } } diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index 8846f70fbd335..2834fce5278c8 100644 --- a/src/librustc_borrowck/borrowck/move_data.rs +++ b/src/librustc_borrowck/borrowck/move_data.rs @@ -486,7 +486,7 @@ impl<'tcx> MoveData<'tcx> { match path.loan_path.kind { LpVar(..) | LpUpvar(..) | LpDowncast(..) => { let kill_scope = path.loan_path.kill_scope(tcx); - let path = self.path_map.borrow()[path.loan_path]; + let path = *self.path_map.borrow().get(&path.loan_path).unwrap(); self.kill_moves(path, kill_scope.node_id(), dfcx_moves); } LpExtend(..) => {} diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index f6f82c65374bd..f788a02adc4c0 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -418,7 +418,7 @@ struct ImproperCTypesVisitor<'a, 'tcx: 'a> { impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { fn check_def(&mut self, sp: Span, id: ast::NodeId) { - match self.cx.tcx.def_map.borrow()[id].full_def() { + match self.cx.tcx.def_map.borrow().get(&id).unwrap().full_def() { def::DefPrimTy(ast::TyInt(ast::TyIs(_))) => { self.cx.span_lint(IMPROPER_CTYPES, sp, "found rust type `isize` in foreign module, while \ diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index bfce2f0062de4..2e7fe91365a13 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -253,7 +253,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { ast::ItemImpl(_, _, _, _, ref ty, ref impl_items) => { let public_ty = match ty.node { ast::TyPath(..) => { - match self.tcx.def_map.borrow()[ty.id].full_def() { + match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() { def::DefPrimTy(..) => true, def => { let did = def.def_id(); @@ -317,7 +317,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { ast::ItemTy(ref ty, _) if public_first => { if let ast::TyPath(..) = ty.node { - match self.tcx.def_map.borrow()[ty.id].full_def() { + match self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def() { def::DefPrimTy(..) | def::DefTyParam(..) => {}, def => { let did = def.def_id(); @@ -349,7 +349,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for EmbargoVisitor<'a, 'tcx> { // crate module gets processed as well. if self.prev_exported { assert!(self.export_map.contains_key(&id), "wut {}", id); - for export in &self.export_map[id] { + for export in self.export_map.get(&id).unwrap() { if is_local(export.def_id) { self.reexports.insert(export.def_id.node); } @@ -525,7 +525,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { // if we've reached the root, then everything was allowable and this // access is public. if closest_private_id == ast::CRATE_NODE_ID { return Allowable } - closest_private_id = self.parents[closest_private_id]; + closest_private_id = *self.parents.get(&closest_private_id).unwrap(); // If we reached the top, then we were public all the way down and // we can allow this access. @@ -543,7 +543,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { /// whether the node is accessible by the current module that iteration is /// inside. fn private_accessible(&self, id: ast::NodeId) -> bool { - let parent = self.parents[id]; + let parent = *self.parents.get(&id).unwrap(); debug!("privacy - accessible parent {}", self.nodestr(parent)); // After finding `did`'s closest private member, we roll ourselves back @@ -567,7 +567,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { _ => {} } - cur = self.parents[cur]; + cur = *self.parents.get(&cur).unwrap(); } } @@ -622,7 +622,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { ast::TyPath(..) => {} _ => return Some((err_span, err_msg, None)), }; - let def = self.tcx.def_map.borrow()[ty.id].full_def(); + let def = self.tcx.def_map.borrow().get(&ty.id).unwrap().full_def(); let did = def.def_id(); assert!(is_local(did)); match self.tcx.map.get(did.node) { @@ -708,7 +708,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { // Checks that a path is in scope. fn check_path(&mut self, span: Span, path_id: ast::NodeId, last: ast::Ident) { debug!("privacy - path {}", self.nodestr(path_id)); - let path_res = self.tcx.def_map.borrow()[path_id]; + let path_res = *self.tcx.def_map.borrow().get(&path_id).unwrap(); let ck = |tyname: &str| { let ck_public = |def: ast::DefId| { debug!("privacy - ck_public {:?}", def); @@ -881,7 +881,7 @@ impl<'a, 'tcx, 'v> Visitor<'v> for PrivacyVisitor<'a, 'tcx> { } } ty::ty_enum(_, _) => { - match self.tcx.def_map.borrow()[expr.id].full_def() { + match self.tcx.def_map.borrow().get(&expr.id).unwrap().full_def() { def::DefVariant(_, variant_id, _) => { for field in fields { self.check_field(expr.span, variant_id, diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index 34a23f3efac42..679f1ce79b28c 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -1141,9 +1141,9 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session, // involves just passing the right -l flag. let data = if dylib { - &trans.crate_formats[config::CrateTypeDylib] + trans.crate_formats.get(&config::CrateTypeDylib).unwrap() } else { - &trans.crate_formats[config::CrateTypeExecutable] + trans.crate_formats.get(&config::CrateTypeExecutable).unwrap() }; // Invoke get_used_crates to ensure that we get a topological sorting of diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 83bb5efb425d2..6a55d6d4adfe3 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -219,7 +219,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.sess.bug(&format!("def_map has no key for {} in lookup_type_ref", ref_id)); } - let def = self.analysis.ty_cx.def_map.borrow()[ref_id].full_def(); + let def = self.analysis.ty_cx.def_map.borrow().get(&ref_id).unwrap().full_def(); match def { def::DefPrimTy(_) => None, _ => Some(def.def_id()), @@ -232,7 +232,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.sess.span_bug(span, &format!("def_map has no key for {} in lookup_def_kind", ref_id)); } - let def = def_map[ref_id].full_def(); + let def = def_map.get(&ref_id).unwrap().full_def(); match def { def::DefMod(_) | def::DefForeignMod(_) => Some(recorder::ModRef), @@ -269,8 +269,10 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.collecting = false; let span_utils = self.span.clone(); for &(id, ref p, _, _) in &self.collected_paths { - let typ = ppaux::ty_to_string(&self.analysis.ty_cx, - (*self.analysis.ty_cx.node_types.borrow())[id]); + let typ = + ppaux::ty_to_string( + &self.analysis.ty_cx, + *self.analysis.ty_cx.node_types.borrow().get(&id).unwrap()); // get the span only for the name of the variable (I hope the path is only ever a // variable name, but who knows?) self.fmt.formal_str(p.span, @@ -431,8 +433,10 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { ast::NamedField(ident, _) => { let name = get_ident(ident); let qualname = format!("{}::{}", qualname, name); - let typ = ppaux::ty_to_string(&self.analysis.ty_cx, - (*self.analysis.ty_cx.node_types.borrow())[field.node.id]); + let typ = + ppaux::ty_to_string( + &self.analysis.ty_cx, + *self.analysis.ty_cx.node_types.borrow().get(&field.node.id).unwrap()); match self.span.sub_span_before_token(field.span, token::Colon) { Some(sub_span) => self.fmt.field_str(field.span, Some(sub_span), @@ -789,7 +793,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.sess.span_bug(span, &format!("def_map has no key for {} in visit_expr", id)); } - let def = def_map[id].full_def(); + let def = def_map.get(&id).unwrap().full_def(); let sub_span = self.span.span_for_last_ident(span); match def { def::DefUpvar(..) | @@ -832,7 +836,8 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { .ty_cx .impl_items .borrow(); - Some((*impl_items)[def_id] + Some(impl_items.get(&def_id) + .unwrap() .iter() .find(|mr| { ty::impl_or_trait_item( @@ -941,7 +946,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { ex: &ast::Expr, args: &Vec>) { let method_map = self.analysis.ty_cx.method_map.borrow(); - let method_callee = &(*method_map)[ty::MethodCall::expr(ex.id)]; + let method_callee = method_map.get(&ty::MethodCall::expr(ex.id)).unwrap(); let (def_id, decl_id) = match method_callee.origin { ty::MethodStatic(def_id) | ty::MethodStaticClosure(def_id) => { @@ -1001,7 +1006,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { self.collected_paths.push((p.id, path.clone(), false, recorder::StructRef)); visit::walk_path(self, path); - let def = self.analysis.ty_cx.def_map.borrow()[p.id].full_def(); + let def = self.analysis.ty_cx.def_map.borrow().get(&p.id).unwrap().full_def(); let struct_def = match def { def::DefConst(..) => None, def::DefVariant(_, variant_id, _) => Some(variant_id), @@ -1113,7 +1118,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let glob_map = &self.analysis.glob_map; let glob_map = glob_map.as_ref().unwrap(); if glob_map.contains_key(&item.id) { - for n in &glob_map[item.id] { + for n in glob_map.get(&item.id).unwrap() { if name_string.len() > 0 { name_string.push_str(", "); } @@ -1406,7 +1411,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { &format!("def_map has no key for {} in visit_arm", id)); } - let def = def_map[id].full_def(); + let def = def_map.get(&id).unwrap().full_def(); match def { def::DefLocal(id) => { let value = if *immut { @@ -1467,7 +1472,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { for &(id, ref p, ref immut, _) in &self.collected_paths { let value = if *immut { value.to_string() } else { "".to_string() }; let types = self.analysis.ty_cx.node_types.borrow(); - let typ = ppaux::ty_to_string(&self.analysis.ty_cx, (*types)[id]); + let typ = ppaux::ty_to_string(&self.analysis.ty_cx, *types.get(&id).unwrap()); // Get the span only for the name of the variable (I hope the path // is only ever a variable name, but who knows?). let sub_span = self.span.span_for_last_ident(p.span); diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index c08d3b2be53dd..eb759393ac6ec 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -1017,7 +1017,7 @@ fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>, None => { let data = &m[0].data; for &(ref ident, ref value_ptr) in &m[0].bound_ptrs { - let binfo = data.bindings_map[*ident]; + let binfo = *data.bindings_map.get(ident).unwrap(); call_lifetime_start(bcx, binfo.llmatch); if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) { expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch); diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index ebd92faaf0f53..bdc810bd83746 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -269,7 +269,7 @@ pub fn self_type_for_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, } pub fn kind_for_closure(ccx: &CrateContext, closure_id: ast::DefId) -> ty::ClosureKind { - ccx.tcx().closure_kinds.borrow()[closure_id] + *ccx.tcx().closure_kinds.borrow().get(&closure_id).unwrap() } pub fn decl_rust_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, @@ -2322,7 +2322,7 @@ pub fn trans_item(ccx: &CrateContext, item: &ast::Item) { static"); } - let v = ccx.static_values().borrow()[item.id].clone(); + let v = ccx.static_values().borrow().get(&item.id).unwrap().clone(); unsafe { if !(llvm::LLVMConstIntGetZExtValue(v) != 0) { ccx.sess().span_fatal(expr.span, "static assertion failed"); diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index cf36ec1f3ed96..088a34857e753 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -511,7 +511,7 @@ pub fn trans_fn_ref_with_substs<'a, 'tcx>( let ref_ty = match node { ExprId(id) => ty::node_id_to_type(tcx, id), MethodCallKey(method_call) => { - (*tcx.method_map.borrow())[method_call].ty + tcx.method_map.borrow().get(&method_call).unwrap().ty } }; let ref_ty = monomorphize::apply_param_substs(tcx, diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 8f5dbfe2ec000..8754d50597bd0 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -709,7 +709,7 @@ impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> { } fn upvar_capture(&self, upvar_id: ty::UpvarId) -> Option { - Some(self.tcx().upvar_capture_map.borrow()[upvar_id].clone()) + Some(self.tcx().upvar_capture_map.borrow().get(&upvar_id).unwrap().clone()) } fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool { @@ -1213,7 +1213,7 @@ pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty::node_id_item_substs(tcx, id).substs } MethodCallKey(method_call) => { - (*tcx.method_map.borrow())[method_call].substs.clone() + tcx.method_map.borrow().get(&method_call).unwrap().substs.clone() } }; diff --git a/src/librustc_trans/trans/consts.rs b/src/librustc_trans/trans/consts.rs index 2a3fcd66195b3..f0947cd471242 100644 --- a/src/librustc_trans/trans/consts.rs +++ b/src/librustc_trans/trans/consts.rs @@ -187,7 +187,7 @@ pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, // Special-case constants to cache a common global for all uses. match expr.node { ast::ExprPath(..) => { - let def = ccx.tcx().def_map.borrow()[expr.id].full_def(); + let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def(); match def { def::DefConst(def_id) => { if !ccx.tcx().adjustments.borrow().contains_key(&expr.id) { @@ -665,7 +665,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } } ast::ExprPath(..) => { - let def = cx.tcx().def_map.borrow()[e.id].full_def(); + let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def(); match def { def::DefFn(..) | def::DefMethod(..) => { expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val @@ -751,7 +751,7 @@ pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) { let g = base::get_item_val(ccx, id); // At this point, get_item_val has already translated the // constant's initializer to determine its LLVM type. - let v = ccx.static_values().borrow()[id].clone(); + let v = ccx.static_values().borrow().get(&id).unwrap().clone(); // boolean SSA values are i1, but they have to be stored in i8 slots, // otherwise some LLVM optimization passes don't work as expected let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() { diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 4aff28122bbb3..28ac7da3cfce8 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -126,7 +126,7 @@ pub fn trans_into<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, return datum.store_to_dest(bcx, dest, expr.id); } - let qualif = bcx.tcx().const_qualif_map.borrow()[expr.id]; + let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap(); if !qualif.intersects(check_const::NOT_CONST | check_const::NEEDS_DROP) { if !qualif.intersects(check_const::PREFER_IN_PLACE) { if let SaveIn(lldest) = dest { @@ -209,7 +209,7 @@ pub fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let mut bcx = bcx; let fcx = bcx.fcx; - let qualif = bcx.tcx().const_qualif_map.borrow()[expr.id]; + let qualif = *bcx.tcx().const_qualif_map.borrow().get(&expr.id).unwrap(); let adjusted_global = !qualif.intersects(check_const::NON_STATIC_BORROWS); let global = if !qualif.intersects(check_const::NOT_CONST | check_const::NEEDS_DROP) { let global = consts::get_const_expr_as_global(bcx.ccx(), expr, qualif, @@ -1405,7 +1405,7 @@ pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>, ty.repr(tcx))); } Some(node_id) => { - let def = tcx.def_map.borrow()[node_id].full_def(); + let def = tcx.def_map.borrow().get(&node_id).unwrap().full_def(); match def { def::DefVariant(enum_id, variant_id, _) => { let variant_info = ty::enum_variant_with_id(tcx, enum_id, variant_id); @@ -1961,7 +1961,7 @@ fn trans_overloaded_op<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, dest: Option, autoref: bool) -> Result<'blk, 'tcx> { - let method_ty = (*bcx.tcx().method_map.borrow())[method_call].ty; + let method_ty = bcx.tcx().method_map.borrow().get(&method_call).unwrap().ty; callee::trans_call_inner(bcx, expr.debug_loc(), monomorphize_type(bcx, method_ty), @@ -1982,10 +1982,12 @@ fn trans_overloaded_call<'a, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, dest: Option) -> Block<'blk, 'tcx> { let method_call = MethodCall::expr(expr.id); - let method_type = (*bcx.tcx() - .method_map - .borrow())[method_call] - .ty; + let method_type = bcx.tcx() + .method_map + .borrow() + .get(&method_call) + .unwrap() + .ty; let mut all_args = vec!(callee); all_args.extend(args.iter().map(|e| &**e)); unpack_result!(bcx, diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 28e7027b2124a..71900855266e9 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1046,7 +1046,7 @@ fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>, return (tcx.types.err, ty_path_def); }; - let ty_param_name = tcx.ty_param_defs.borrow()[ty_param_node_id].name; + let ty_param_name = tcx.ty_param_defs.borrow().get(&ty_param_node_id).unwrap().name; let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) { Ok(v) => v, diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index 8e2f4dcefa022..e71386a9b42b1 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -119,7 +119,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, demand::eqtype(fcx, pat.span, expected, lhs_ty); } ast::PatEnum(..) | ast::PatIdent(..) if pat_is_const(&tcx.def_map, pat) => { - let const_did = tcx.def_map.borrow()[pat.id].def_id(); + let const_did = tcx.def_map.borrow().get(&pat.id).unwrap().def_id(); let const_scheme = ty::lookup_item_type(tcx, const_did); assert!(const_scheme.generics.is_empty()); let const_ty = pcx.fcx.instantiate_type_scheme(pat.span, @@ -163,7 +163,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, // if there are multiple arms, make sure they all agree on // what the type of the binding `x` ought to be - let canon_id = pcx.map[path.node]; + let canon_id = *pcx.map.get(&path.node).unwrap(); if canon_id != pat.id { let ct = fcx.local_ty(pat.span, canon_id); demand::eqtype(fcx, pat.span, ct, typ); @@ -449,7 +449,7 @@ pub fn check_pat_struct<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, pat: &'tcx ast::Pat, let fcx = pcx.fcx; let tcx = pcx.fcx.ccx.tcx; - let def = tcx.def_map.borrow()[pat.id].full_def(); + let def = tcx.def_map.borrow().get(&pat.id).unwrap().full_def(); let (enum_def_id, variant_def_id) = match def { def::DefTrait(_) => { let name = pprust::path_to_string(path); @@ -518,7 +518,7 @@ pub fn check_pat_enum<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>, let fcx = pcx.fcx; let tcx = pcx.fcx.ccx.tcx; - let def = tcx.def_map.borrow()[pat.id].full_def(); + let def = tcx.def_map.borrow().get(&pat.id).unwrap().full_def(); let enum_def = def.variant_def_ids() .map_or_else(|| def.def_id(), |(enum_def, _)| enum_def); diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 45d4a1edc6b24..f319adac1a16e 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -368,7 +368,7 @@ impl<'a, 'tcx> ty::ClosureTyper<'tcx> for FnCtxt<'a, 'tcx> { substs: &subst::Substs<'tcx>) -> ty::ClosureTy<'tcx> { - self.inh.closure_tys.borrow()[def_id].subst(self.tcx(), substs) + self.inh.closure_tys.borrow().get(&def_id).unwrap().subst(self.tcx(), substs) } fn closure_upvars(&self, @@ -549,7 +549,7 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { debug!("Local variable {} is assigned type {}", self.fcx.pat_to_string(&*local.pat), self.fcx.infcx().ty_to_string( - self.fcx.inh.locals.borrow()[local.id].clone())); + self.fcx.inh.locals.borrow().get(&local.id).unwrap().clone())); visit::walk_local(self, local); } @@ -565,7 +565,7 @@ impl<'a, 'tcx> Visitor<'tcx> for GatherLocalsVisitor<'a, 'tcx> { debug!("Pattern binding {} is assigned to {} with type {}", token::get_ident(path1.node), self.fcx.infcx().ty_to_string( - self.fcx.inh.locals.borrow()[p.id].clone()), + self.fcx.inh.locals.borrow().get(&p.id).unwrap().clone()), var_ty.repr(self.fcx.tcx())); } } @@ -3327,7 +3327,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, let mut missing_fields = Vec::new(); for class_field in field_types { let name = class_field.name; - let (_, seen) = class_field_map[name]; + let (_, seen) = *class_field_map.get(&name).unwrap(); if !seen { missing_fields.push( format!("`{}`", &token::get_name(name))) @@ -4428,7 +4428,7 @@ fn check_const<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, let inh = static_inherited_fields(ccx); let rty = ty::node_id_to_type(ccx.tcx, id); let fcx = blank_fn_ctxt(ccx, &inh, ty::FnConverging(rty), e.id); - let declty = (*fcx.ccx.tcx.tcache.borrow())[local_def(id)].ty; + let declty = fcx.ccx.tcx.tcache.borrow().get(&local_def(id)).unwrap().ty; check_const_with_ty(&fcx, sp, e, declty); } diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index ce4bb4465517b..340cca7d47e7a 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -448,7 +448,7 @@ impl<'a,'tcx> AdjustBorrowKind<'a,'tcx> { let closure_def_id = ast_util::local_def(closure_id); let mut closure_kinds = self.fcx.inh.closure_kinds.borrow_mut(); - let existing_kind = closure_kinds[closure_def_id]; + let existing_kind = *closure_kinds.get(&closure_def_id).unwrap(); debug!("adjust_closure_kind: closure_id={}, existing_kind={:?}, new_kind={:?}", closure_id, existing_kind, new_kind); diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 6b0fb8ac71af0..ffd99ff2eece0 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -269,7 +269,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { fn get_self_type_for_implementation(&self, impl_did: DefId) -> TypeScheme<'tcx> { - self.crate_context.tcx.tcache.borrow()[impl_did].clone() + self.crate_context.tcx.tcache.borrow().get(&impl_did).unwrap().clone() } // Converts an implementation in the AST to a vector of items. @@ -387,7 +387,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { }; for &impl_did in &*trait_impls.borrow() { - let items = &(*impl_items)[impl_did]; + let items = impl_items.get(&impl_did).unwrap(); if items.len() < 1 { // We'll error out later. For now, just don't ICE. continue; diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 97cc3ac7c48a7..6be45b26751de 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -194,7 +194,7 @@ impl<'a,'tcx> CrateCtxt<'a,'tcx> { fn method_ty(&self, method_id: ast::NodeId) -> Rc> { let def_id = local_def(method_id); - match self.tcx.impl_or_trait_items.borrow()[def_id] { + match *self.tcx.impl_or_trait_items.borrow().get(&def_id).unwrap() { ty::MethodTraitItem(ref mty) => mty.clone(), ty::TypeTraitItem(..) => { self.tcx.sess.bug(&format!("method with id {} has the wrong type", method_id)); @@ -545,7 +545,7 @@ fn is_param<'tcx>(tcx: &ty::ctxt<'tcx>, -> bool { if let ast::TyPath(None, _) = ast_ty.node { - let path_res = tcx.def_map.borrow()[ast_ty.id]; + let path_res = *tcx.def_map.borrow().get(&ast_ty.id).unwrap(); match path_res.base_def { def::DefSelfTy(node_id) => path_res.depth == 0 && node_id == param_id, @@ -1040,9 +1040,13 @@ fn convert_struct<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, tcx.predicates.borrow_mut().insert(local_def(ctor_id), predicates); } else if struct_def.fields[0].node.kind.is_unnamed() { // Tuple-like. - let inputs: Vec<_> = struct_def.fields.iter().map( - |field| (*tcx.tcache.borrow())[ - local_def(field.node.id)].ty).collect(); + let inputs: Vec<_> = + struct_def.fields + .iter() + .map(|field| tcx.tcache.borrow().get(&local_def(field.node.id)) + .unwrap() + .ty) + .collect(); let ctor_fn_ty = ty::mk_ctor_fn(tcx, local_def(ctor_id), &inputs[..], diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 03a2d708ee43a..4d15abb91dc14 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -290,7 +290,7 @@ fn resolved_path(w: &mut fmt::Formatter, did: ast::DefId, p: &clean::Path, if ast_util::is_local(did) || cache.inlined.contains(&did) { Some(repeat("../").take(loc.len()).collect::()) } else { - match cache.extern_locations[did.krate] { + match cache.extern_locations[&did.krate] { render::Remote(ref s) => Some(s.to_string()), render::Local => { Some(repeat("../").take(loc.len()).collect::()) @@ -404,11 +404,11 @@ fn primitive_link(f: &mut fmt::Formatter, needs_termination = true; } Some(&cnum) => { - let path = &m.paths[ast::DefId { + let path = &m.paths[&ast::DefId { krate: cnum, node: ast::CRATE_NODE_ID, }]; - let loc = match m.extern_locations[cnum] { + let loc = match m.extern_locations[&cnum] { render::Remote(ref s) => Some(s.to_string()), render::Local => { let len = CURRENT_LOCATION_KEY.with(|s| s.borrow().len()); diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index 81daac7b90f0d..5ceb0238aa081 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1404,8 +1404,8 @@ impl<'a> Item<'a> { // located, then we return `None`. } else { let cache = cache(); - let path = &cache.external_paths[self.item.def_id]; - let root = match cache.extern_locations[self.item.def_id.krate] { + let path = &cache.external_paths[&self.item.def_id]; + let root = match cache.extern_locations[&self.item.def_id.krate] { Remote(ref s) => s.to_string(), Local => self.cx.root_path.clone(), Unknown => return None, @@ -1863,7 +1863,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, path = if ast_util::is_local(it.def_id) { cx.current.connect("/") } else { - let path = &cache.external_paths[it.def_id]; + let path = &cache.external_paths[&it.def_id]; path[..path.len() - 1].connect("/") }, ty = shortty(it).to_static_str(), diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index d53954b29b585..11e10cc2aa7a1 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -196,7 +196,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { Some(tcx) => tcx, None => return false }; - let def = tcx.def_map.borrow()[id].def_id(); + let def = tcx.def_map.borrow()[&id].def_id(); if !ast_util::is_local(def) { return false } let analysis = match self.analysis { Some(analysis) => analysis, None => return false diff --git a/src/libstd/thread_local/mod.rs b/src/libstd/thread_local/mod.rs index 08780292c88b1..b2fd8a8e6164f 100644 --- a/src/libstd/thread_local/mod.rs +++ b/src/libstd/thread_local/mod.rs @@ -745,7 +745,7 @@ mod dynamic_tests { thread_local!(static FOO: RefCell> = map()); FOO.with(|map| { - assert_eq!(map.borrow()[1], 2); + assert_eq!(map.borrow()[&1], 2); }); } diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 0eaca9af4f08d..2fe77bf7a5411 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -513,7 +513,7 @@ impl<'a, 'b> Context<'a, 'b> { let lname = self.ecx.ident_of(&format!("__arg{}", *name)); pats.push(self.ecx.pat_ident(e.span, lname)); - names[self.name_positions[*name]] = + names[*self.name_positions.get(name).unwrap()] = Some(Context::format_arg(self.ecx, e.span, arg_ty, self.ecx.expr_ident(e.span, lname))); heads.push(self.ecx.expr_addr_of(e.span, e)); diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 7a2ae55e91494..5940b79184379 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -236,7 +236,7 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt, argument_gram); // Extract the arguments: - let lhses = match *argument_map[lhs_nm] { + let lhses = match **argument_map.get(&lhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured lhs") }; @@ -245,7 +245,7 @@ pub fn compile<'cx>(cx: &'cx mut ExtCtxt, check_lhs_nt_follows(cx, &**lhs, def.span); } - let rhses = match *argument_map[rhs_nm] { + let rhses = match **argument_map.get(&rhs_nm).unwrap() { MatchedSeq(ref s, _) => /* FIXME (#2543) */ (*s).clone(), _ => cx.span_bug(def.span, "wrong-structured rhs") }; diff --git a/src/test/auxiliary/issue-2631-a.rs b/src/test/auxiliary/issue-2631-a.rs index dd1ad413a3d27..604a3e69a2176 100644 --- a/src/test/auxiliary/issue-2631-a.rs +++ b/src/test/auxiliary/issue-2631-a.rs @@ -19,6 +19,6 @@ pub type header_map = HashMap>>>>; // the unused ty param is necessary so this gets monomorphized pub fn request(req: &header_map) { - let data = req["METHOD".to_string()].clone(); + let data = req[&"METHOD".to_string()].clone(); let _x = data.borrow().clone()[0].clone(); } diff --git a/src/test/auxiliary/procedural_mbe_matching.rs b/src/test/auxiliary/procedural_mbe_matching.rs index d9a2b06e0393f..18db50a831ca8 100644 --- a/src/test/auxiliary/procedural_mbe_matching.rs +++ b/src/test/auxiliary/procedural_mbe_matching.rs @@ -33,7 +33,7 @@ fn expand_mbe_matches(cx: &mut ExtCtxt, sp: Span, args: &[TokenTree]) let mac_expr = match TokenTree::parse(cx, &mbe_matcher[..], args) { Success(map) => { - match (&*map[str_to_ident("matched")], &*map[str_to_ident("pat")]) { + match (&*map[&str_to_ident("matched")], &*map[&str_to_ident("pat")]) { (&MatchedNonterminal(NtExpr(ref matched_expr)), &MatchedSeq(ref pats, seq_sp)) => { let pats: Vec> = pats.iter().map(|pat_nt| diff --git a/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs b/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs index 430f2fcc13a73..bee56c9bf390b 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-and-overloaded-deref.rs @@ -19,7 +19,7 @@ struct MyVec { x: T } impl Index for MyVec { type Output = T; - fn index(&self, _: &usize) -> &T { + fn index(&self, _: usize) -> &T { &self.x } } diff --git a/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs b/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs index 99f396ef81432..55a6e2ac7b8d6 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-autoderef.rs @@ -18,6 +18,7 @@ struct Foo { y: isize, } +#[cfg(stage0)] impl Index for Foo { type Output = isize; @@ -30,8 +31,20 @@ impl Index for Foo { } } -impl IndexMut for Foo { - fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize { +impl<'a> Index<&'a String> for Foo { + type Output = isize; + + fn index(&self, z: &String) -> &isize { + if *z == "x" { + &self.x + } else { + &self.y + } + } +} + +impl<'a> IndexMut<&'a String> for Foo { + fn index_mut(&mut self, z: &String) -> &mut isize { if *z == "x" { &mut self.x } else { @@ -41,13 +54,13 @@ impl IndexMut for Foo { } fn test1(mut f: Box, s: String) { - let _p = &mut f[s]; - let _q = &f[s]; //~ ERROR cannot borrow + let _p = &mut f[&s]; + let _q = &f[&s]; //~ ERROR cannot borrow } fn test2(mut f: Box, s: String) { - let _p = &mut f[s]; - let _q = &mut f[s]; //~ ERROR cannot borrow + let _p = &mut f[&s]; + let _q = &mut f[&s]; //~ ERROR cannot borrow } struct Bar { @@ -55,37 +68,37 @@ struct Bar { } fn test3(mut f: Box, s: String) { - let _p = &mut f.foo[s]; - let _q = &mut f.foo[s]; //~ ERROR cannot borrow + let _p = &mut f.foo[&s]; + let _q = &mut f.foo[&s]; //~ ERROR cannot borrow } fn test4(mut f: Box, s: String) { - let _p = &f.foo[s]; - let _q = &f.foo[s]; + let _p = &f.foo[&s]; + let _q = &f.foo[&s]; } fn test5(mut f: Box, s: String) { - let _p = &f.foo[s]; - let _q = &mut f.foo[s]; //~ ERROR cannot borrow + let _p = &f.foo[&s]; + let _q = &mut f.foo[&s]; //~ ERROR cannot borrow } fn test6(mut f: Box, g: Foo, s: String) { - let _p = &f.foo[s]; + let _p = &f.foo[&s]; f.foo = g; //~ ERROR cannot assign } fn test7(mut f: Box, g: Bar, s: String) { - let _p = &f.foo[s]; + let _p = &f.foo[&s]; *f = g; //~ ERROR cannot assign } fn test8(mut f: Box, g: Foo, s: String) { - let _p = &mut f.foo[s]; + let _p = &mut f.foo[&s]; f.foo = g; //~ ERROR cannot assign } fn test9(mut f: Box, g: Bar, s: String) { - let _p = &mut f.foo[s]; + let _p = &mut f.foo[&s]; *f = g; //~ ERROR cannot assign } diff --git a/src/test/compile-fail/dst-index.rs b/src/test/compile-fail/dst-index.rs index 91f3432048256..021ef7343cbb4 100644 --- a/src/test/compile-fail/dst-index.rs +++ b/src/test/compile-fail/dst-index.rs @@ -20,7 +20,7 @@ struct S; impl Index for S { type Output = str; - fn index<'a>(&'a self, _: &usize) -> &'a str { + fn index(&self, _: usize) -> &str { "hello" } } @@ -31,7 +31,7 @@ struct T; impl Index for T { type Output = Debug + 'static; - fn index<'a>(&'a self, idx: &usize) -> &'a (Debug + 'static) { + fn index<'a>(&'a self, idx: usize) -> &'a (Debug + 'static) { static x: usize = 42; &x } diff --git a/src/test/run-pass/dst-index.rs b/src/test/run-pass/dst-index.rs index 0c7ecfcefff34..9539486118b81 100644 --- a/src/test/run-pass/dst-index.rs +++ b/src/test/run-pass/dst-index.rs @@ -19,7 +19,7 @@ struct S; impl Index for S { type Output = str; - fn index<'a>(&'a self, _: &uint) -> &'a str { + fn index<'a>(&'a self, _: uint) -> &'a str { "hello" } } @@ -29,7 +29,7 @@ struct T; impl Index for T { type Output = Debug + 'static; - fn index<'a>(&'a self, idx: &uint) -> &'a (Debug + 'static) { + fn index<'a>(&'a self, idx: uint) -> &'a (Debug + 'static) { static X: uint = 42; &X as &(Debug + 'static) } diff --git a/src/test/run-pass/issue-15734.rs b/src/test/run-pass/issue-15734.rs index 18e4190ee459f..76a5b6488b5a3 100644 --- a/src/test/run-pass/issue-15734.rs +++ b/src/test/run-pass/issue-15734.rs @@ -29,7 +29,7 @@ impl Mat { impl Index<(uint, uint)> for Mat { type Output = T; - fn index<'a>(&'a self, &(row, col): &(uint, uint)) -> &'a T { + fn index<'a>(&'a self, (row, col): (uint, uint)) -> &'a T { &self.data[row * self.cols + col] } } @@ -37,7 +37,7 @@ impl Index<(uint, uint)> for Mat { impl<'a, T> Index<(uint, uint)> for &'a Mat { type Output = T; - fn index<'b>(&'b self, index: &(uint, uint)) -> &'b T { + fn index<'b>(&'b self, index: (uint, uint)) -> &'b T { (*self).index(index) } } @@ -47,8 +47,8 @@ struct Row { mat: M, row: uint, } impl> Index for Row { type Output = T; - fn index<'a>(&'a self, col: &uint) -> &'a T { - &self.mat[(self.row, *col)] + fn index<'a>(&'a self, col: uint) -> &'a T { + &self.mat[(self.row, col)] } } @@ -56,7 +56,7 @@ fn main() { let m = Mat::new(vec!(1, 2, 3, 4, 5, 6), 3); let r = m.row(1); - assert!(r.index(&2) == &6); + assert!(r.index(2) == &6); assert!(r[2] == 6); assert!(r[2] == 6); assert!(6 == r[2]); diff --git a/src/test/run-pass/issue-2804-2.rs b/src/test/run-pass/issue-2804-2.rs index 4f89d28332a23..b04ae0edbed87 100644 --- a/src/test/run-pass/issue-2804-2.rs +++ b/src/test/run-pass/issue-2804-2.rs @@ -16,7 +16,7 @@ extern crate collections; use std::collections::HashMap; fn add_interfaces(managed_ip: String, device: HashMap) { - println!("{}, {}", managed_ip, device["interfaces".to_string()]); + println!("{}, {}", managed_ip, device["interfaces"]); } pub fn main() {} diff --git a/src/test/run-pass/issue-2804.rs b/src/test/run-pass/issue-2804.rs index b9b5aec62fcda..619bd08141fb6 100644 --- a/src/test/run-pass/issue-2804.rs +++ b/src/test/run-pass/issue-2804.rs @@ -56,8 +56,7 @@ fn add_interface(_store: int, managed_ip: String, data: json::Json) -> (String, fn add_interfaces(store: int, managed_ip: String, device: HashMap) -> Vec<(String, object)> { - match device["interfaces".to_string()] - { + match device["interfaces"] { Json::Array(ref interfaces) => { interfaces.iter().map(|interface| { @@ -67,7 +66,7 @@ fn add_interfaces(store: int, managed_ip: String, device: HashMap { println!("Expected list for {} interfaces, found {}", managed_ip, - device["interfaces".to_string()]); + device["interfaces"]); Vec::new() } } diff --git a/src/test/run-pass/issue-5521.rs b/src/test/run-pass/issue-5521.rs index fb0e8e599eb2a..7016e28f2ee02 100644 --- a/src/test/run-pass/issue-5521.rs +++ b/src/test/run-pass/issue-5521.rs @@ -17,7 +17,7 @@ fn bar(a: foo::map) { if false { panic!(); } else { - let _b = &(*a)[2]; + let _b = &(*a)[&2]; } } diff --git a/src/test/run-pass/issue-7660.rs b/src/test/run-pass/issue-7660.rs index 9e36b1f5082d0..78318e083ba40 100644 --- a/src/test/run-pass/issue-7660.rs +++ b/src/test/run-pass/issue-7660.rs @@ -21,6 +21,6 @@ pub fn main() { let mut m: HashMap = HashMap::new(); m.insert(1, A(0, 0)); - let A(ref _a, ref _b) = m[1]; - let (a, b) = match m[1] { A(ref _a, ref _b) => (_a, _b) }; + let A(ref _a, ref _b) = m[&1]; + let (a, b) = match m[&1] { A(ref _a, ref _b) => (_a, _b) }; } diff --git a/src/test/run-pass/operator-overloading.rs b/src/test/run-pass/operator-overloading.rs index 3ddc666cd384c..801e71b303862 100644 --- a/src/test/run-pass/operator-overloading.rs +++ b/src/test/run-pass/operator-overloading.rs @@ -52,8 +52,8 @@ impl ops::Not for Point { impl ops::Index for Point { type Output = int; - fn index(&self, x: &bool) -> &int { - if *x { + fn index(&self, x: bool) -> &int { + if x { &self.x } else { &self.y diff --git a/src/test/run-pass/overloaded-index-assoc-list.rs b/src/test/run-pass/overloaded-index-assoc-list.rs index 0064748e88369..b5c9962fe9c3f 100644 --- a/src/test/run-pass/overloaded-index-assoc-list.rs +++ b/src/test/run-pass/overloaded-index-assoc-list.rs @@ -28,7 +28,7 @@ impl AssociationList { } } -impl Index for AssociationList { +impl<'a, K: PartialEq + std::fmt::Debug, V:Clone> Index<&'a K> for AssociationList { type Output = V; fn index<'a>(&'a self, index: &K) -> &'a V { @@ -49,9 +49,9 @@ pub fn main() { list.push(foo.clone(), 22); list.push(bar.clone(), 44); - assert!(list[foo] == 22); - assert!(list[bar] == 44); + assert!(list[&foo] == 22); + assert!(list[&bar] == 44); - assert!(list[foo] == 22); - assert!(list[bar] == 44); + assert!(list[&foo] == 22); + assert!(list[&bar] == 44); } diff --git a/src/test/run-pass/overloaded-index-autoderef.rs b/src/test/run-pass/overloaded-index-autoderef.rs index 8f655f0517ddf..107f0fbc20904 100644 --- a/src/test/run-pass/overloaded-index-autoderef.rs +++ b/src/test/run-pass/overloaded-index-autoderef.rs @@ -23,8 +23,8 @@ struct Foo { impl Index for Foo { type Output = int; - fn index(&self, z: &int) -> &int { - if *z == 0 { + fn index(&self, z: int) -> &int { + if z == 0 { &self.x } else { &self.y @@ -33,8 +33,8 @@ impl Index for Foo { } impl IndexMut for Foo { - fn index_mut(&mut self, z: &int) -> &mut int { - if *z == 0 { + fn index_mut(&mut self, z: int) -> &mut int { + if z == 0 { &mut self.x } else { &mut self.y diff --git a/src/test/run-pass/overloaded-index-in-field.rs b/src/test/run-pass/overloaded-index-in-field.rs index 487fb93c9fee8..f01e5541c423b 100644 --- a/src/test/run-pass/overloaded-index-in-field.rs +++ b/src/test/run-pass/overloaded-index-in-field.rs @@ -25,8 +25,8 @@ struct Bar { impl Index for Foo { type Output = int; - fn index(&self, z: &int) -> &int { - if *z == 0 { + fn index(&self, z: int) -> &int { + if z == 0 { &self.x } else { &self.y diff --git a/src/test/run-pass/overloaded-index.rs b/src/test/run-pass/overloaded-index.rs index 10ca3804eaedb..60e0ed9bfdd0f 100644 --- a/src/test/run-pass/overloaded-index.rs +++ b/src/test/run-pass/overloaded-index.rs @@ -18,8 +18,8 @@ struct Foo { impl Index for Foo { type Output = int; - fn index(&self, z: &int) -> &int { - if *z == 0 { + fn index(&self, z: int) -> &int { + if z == 0 { &self.x } else { &self.y @@ -28,8 +28,8 @@ impl Index for Foo { } impl IndexMut for Foo { - fn index_mut(&mut self, z: &int) -> &mut int { - if *z == 0 { + fn index_mut(&mut self, z: int) -> &mut int { + if z == 0 { &mut self.x } else { &mut self.y diff --git a/src/test/run-pass/slice.rs b/src/test/run-pass/slice.rs index 30b53dbb0ad5b..ee9bb80356164 100644 --- a/src/test/run-pass/slice.rs +++ b/src/test/run-pass/slice.rs @@ -21,53 +21,53 @@ struct Foo; impl Index> for Foo { type Output = Foo; - fn index(&self, index: &Range) -> &Foo { + fn index(&self, index: Range) -> &Foo { unsafe { COUNT += 1; } self } } impl Index> for Foo { type Output = Foo; - fn index(&self, index: &RangeTo) -> &Foo { + fn index(&self, index: RangeTo) -> &Foo { unsafe { COUNT += 1; } self } } impl Index> for Foo { type Output = Foo; - fn index(&self, index: &RangeFrom) -> &Foo { + fn index(&self, index: RangeFrom) -> &Foo { unsafe { COUNT += 1; } self } } impl Index for Foo { type Output = Foo; - fn index(&self, _index: &RangeFull) -> &Foo { + fn index(&self, _index: RangeFull) -> &Foo { unsafe { COUNT += 1; } self } } impl IndexMut> for Foo { - fn index_mut(&mut self, index: &Range) -> &mut Foo { + fn index_mut(&mut self, index: Range) -> &mut Foo { unsafe { COUNT += 1; } self } } impl IndexMut> for Foo { - fn index_mut(&mut self, index: &RangeTo) -> &mut Foo { + fn index_mut(&mut self, index: RangeTo) -> &mut Foo { unsafe { COUNT += 1; } self } } impl IndexMut> for Foo { - fn index_mut(&mut self, index: &RangeFrom) -> &mut Foo { + fn index_mut(&mut self, index: RangeFrom) -> &mut Foo { unsafe { COUNT += 1; } self } } impl IndexMut for Foo { - fn index_mut(&mut self, _index: &RangeFull) -> &mut Foo { + fn index_mut(&mut self, _index: RangeFull) -> &mut Foo { unsafe { COUNT += 1; } self } From 57cf2decf755c6eea3275e2a87862756eb8c62ca Mon Sep 17 00:00:00 2001 From: Niko Matsakis Date: Sat, 21 Mar 2015 21:16:57 -0400 Subject: [PATCH 4/4] Update borrowck tests to test that index is by-move now --- ...orrowck-overloaded-index-move-from-vec.rs} | 2 +- .../borrowck-overloaded-index-move-index.rs | 74 +++++++++++++++++++ ...=> borrowck-overloaded-index-ref-index.rs} | 14 ++-- 3 files changed, 82 insertions(+), 8 deletions(-) rename src/test/compile-fail/{borrowck-overloaded-index-2.rs => borrowck-overloaded-index-move-from-vec.rs} (95%) create mode 100644 src/test/compile-fail/borrowck-overloaded-index-move-index.rs rename src/test/compile-fail/{borrowck-overloaded-index.rs => borrowck-overloaded-index-ref-index.rs} (82%) diff --git a/src/test/compile-fail/borrowck-overloaded-index-2.rs b/src/test/compile-fail/borrowck-overloaded-index-move-from-vec.rs similarity index 95% rename from src/test/compile-fail/borrowck-overloaded-index-2.rs rename to src/test/compile-fail/borrowck-overloaded-index-move-from-vec.rs index 58668b73cbffb..1b62d9c326d77 100644 --- a/src/test/compile-fail/borrowck-overloaded-index-2.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-move-from-vec.rs @@ -19,7 +19,7 @@ struct MyVec { impl Index for MyVec { type Output = T; - fn index(&self, &i: &usize) -> &T { + fn index(&self, i: usize) -> &T { &self.data[i] } } diff --git a/src/test/compile-fail/borrowck-overloaded-index-move-index.rs b/src/test/compile-fail/borrowck-overloaded-index-move-index.rs new file mode 100644 index 0000000000000..d8615d1905338 --- /dev/null +++ b/src/test/compile-fail/borrowck-overloaded-index-move-index.rs @@ -0,0 +1,74 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +use std::ops::{Index, IndexMut}; + +struct Foo { + x: isize, + y: isize, +} + +impl Index for Foo { + type Output = isize; + + fn index(&self, z: String) -> &isize { + if z == "x" { + &self.x + } else { + &self.y + } + } +} + +impl IndexMut for Foo { + fn index_mut(&mut self, z: String) -> &mut isize { + if z == "x" { + &mut self.x + } else { + &mut self.y + } + } +} + +struct Bar { + x: isize, +} + +impl Index for Bar { + type Output = isize; + + fn index<'a>(&'a self, z: isize) -> &'a isize { + &self.x + } +} + +fn main() { + let mut f = Foo { + x: 1, + y: 2, + }; + let mut s = "hello".to_string(); + let rs = &mut s; + + println!("{}", f[s]); + //~^ ERROR cannot move out of `s` because it is borrowed + + f[s] = 10; + //~^ ERROR cannot move out of `s` because it is borrowed + //~| ERROR use of moved value: `s` + + let s = Bar { + x: 1, + }; + let i = 2; + let _j = &i; + println!("{}", s[i]); // no error, i is copy + println!("{}", s[i]); +} diff --git a/src/test/compile-fail/borrowck-overloaded-index.rs b/src/test/compile-fail/borrowck-overloaded-index-ref-index.rs similarity index 82% rename from src/test/compile-fail/borrowck-overloaded-index.rs rename to src/test/compile-fail/borrowck-overloaded-index-ref-index.rs index 2d752abe7e3c2..4c50caf49768d 100644 --- a/src/test/compile-fail/borrowck-overloaded-index.rs +++ b/src/test/compile-fail/borrowck-overloaded-index-ref-index.rs @@ -15,10 +15,10 @@ struct Foo { y: isize, } -impl Index for Foo { +impl<'a> Index<&'a String> for Foo { type Output = isize; - fn index<'a>(&'a self, z: &String) -> &'a isize { + fn index(&self, z: &String) -> &isize { if *z == "x" { &self.x } else { @@ -27,8 +27,8 @@ impl Index for Foo { } } -impl IndexMut for Foo { - fn index_mut<'a>(&'a mut self, z: &String) -> &'a mut isize { +impl<'a> IndexMut<&'a String> for Foo { + fn index_mut(&mut self, z: &String) -> &mut isize { if *z == "x" { &mut self.x } else { @@ -44,7 +44,7 @@ struct Bar { impl Index for Bar { type Output = isize; - fn index<'a>(&'a self, z: &isize) -> &'a isize { + fn index<'a>(&'a self, z: isize) -> &'a isize { &self.x } } @@ -56,9 +56,9 @@ fn main() { }; let mut s = "hello".to_string(); let rs = &mut s; - println!("{}", f[s]); + println!("{}", f[&s]); //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable - f[s] = 10; + f[&s] = 10; //~^ ERROR cannot borrow `s` as immutable because it is also borrowed as mutable let s = Bar { x: 1,