From 0c7f7a5fb8919c6a382f9acd1e921c51f807f625 Mon Sep 17 00:00:00 2001 From: Nick Cameron Date: Sun, 4 Jan 2015 17:43:24 +1300 Subject: [PATCH] fallout --- src/compiletest/runtest.rs | 15 +- src/libcollections/ring_buf.rs | 2 +- src/libcollections/slice.rs | 15 +- src/libcollections/str.rs | 14 +- src/libcollections/string.rs | 26 +-- src/libcollections/vec.rs | 49 ++--- src/libcore/array.rs | 16 +- src/libcore/fmt/mod.rs | 2 +- src/libcore/slice.rs | 176 +++++++++--------- src/libcore/str/mod.rs | 15 +- src/libcoretest/iter.rs | 35 ++-- src/libcoretest/slice.rs | 16 +- src/libgetopts/lib.rs | 4 +- src/librand/distributions/mod.rs | 6 +- src/librand/distributions/range.rs | 2 +- src/librand/lib.rs | 8 +- src/libregex/test/matches.rs | 2 +- src/libregex/test/tests.rs | 2 +- src/librustc/lint/context.rs | 4 +- src/librustc/metadata/creader.rs | 8 +- src/librustc/metadata/encoder.rs | 4 +- src/librustc/metadata/loader.rs | 3 +- src/librustc/middle/cfg/graphviz.rs | 4 +- src/librustc/middle/check_const.rs | 1 + src/librustc/middle/expr_use_visitor.rs | 2 +- src/librustc/middle/mem_categorization.rs | 4 +- src/librustc/middle/traits/mod.rs | 2 +- src/librustc/middle/traits/object_safety.rs | 2 +- src/librustc/middle/traits/project.rs | 2 +- src/librustc/middle/ty.rs | 6 +- src/librustc/session/config.rs | 4 +- src/librustc_back/target/mod.rs | 4 +- src/librustc_borrowck/borrowck/doc.rs | 8 +- src/librustc_borrowck/borrowck/mod.rs | 2 +- src/librustc_resolve/lib.rs | 4 +- src/librustc_trans/back/link.rs | 6 +- src/librustc_trans/back/lto.rs | 2 +- src/librustc_trans/back/write.rs | 4 +- src/librustc_trans/save/mod.rs | 11 +- src/librustc_trans/save/recorder.rs | 2 +- src/librustc_trans/trans/_match.rs | 4 +- src/librustc_trans/trans/base.rs | 8 +- src/librustc_trans/trans/debuginfo.rs | 2 +- src/librustc_trans/trans/expr.rs | 11 +- src/librustc_trans/trans/foreign.rs | 4 +- src/librustc_typeck/astconv.rs | 11 +- src/librustc_typeck/check/callee.rs | 2 +- src/librustc_typeck/check/method/confirm.rs | 4 +- src/librustc_typeck/check/mod.rs | 2 +- src/librustc_typeck/collect.rs | 2 +- src/librustdoc/html/format.rs | 6 +- src/librustdoc/html/render.rs | 14 +- src/libserialize/json.rs | 57 ++++-- src/libserialize/json_stage0.rs | 28 +-- src/libserialize/serialize_stage0.rs | 3 +- src/libstd/io/buffered.rs | 36 ++-- src/libstd/io/mem.rs | 8 +- src/libstd/io/process.rs | 8 +- src/libstd/path/mod.rs | 2 +- src/libstd/path/windows.rs | 10 +- src/libstd/prelude/v1.rs | 3 +- src/libstd/sys/windows/backtrace.rs | 3 +- src/libsyntax/ast.rs | 2 +- src/libsyntax/attr.rs | 2 +- src/libsyntax/ext/deriving/bounds.rs | 5 +- src/libsyntax/ext/tt/macro_parser.rs | 2 +- src/libsyntax/feature_gate.rs | 7 +- src/libsyntax/parse/mod.rs | 6 +- src/libsyntax/parse/parser.rs | 38 ++-- src/libsyntax/parse/token.rs | 5 +- src/libsyntax/print/pprust.rs | 53 +++--- src/test/bench/shootout-fannkuch-redux.rs | 2 +- src/test/bench/shootout-fasta.rs | 2 +- src/test/bench/shootout-k-nucleotide-pipes.rs | 4 +- .../compile-fail/borrowck-loan-vec-content.rs | 4 +- .../compile-fail/indexing-requires-a-uint.rs | 3 +- src/test/compile-fail/integral-indexing.rs | 32 ++-- src/test/compile-fail/issue-16709.rs | 25 --- src/test/compile-fail/slice-2.rs | 8 +- src/test/compile-fail/slice-mut-2.rs | 2 +- src/test/compile-fail/slice-mut.rs | 2 +- src/test/compile-fail/str-idx.rs | 3 +- src/test/run-pass/issue-17503.rs | 6 +- src/test/run-pass/issue-3888-2.rs | 2 +- src/test/run-pass/issue-4464.rs | 2 +- src/test/run-pass/issue-8898.rs | 2 +- src/test/run-pass/slice-panic-1.rs | 4 +- src/test/run-pass/slice-panic-2.rs | 4 +- src/test/run-pass/slice.rs | 62 ++++-- 89 files changed, 543 insertions(+), 468 deletions(-) delete mode 100644 src/test/compile-fail/issue-16709.rs diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index 684315de004..afcdcf6439c 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -539,18 +539,17 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) { script_str.push_str("set print pretty off\n"); // Add the pretty printer directory to GDB's source-file search path - script_str.push_str(format!("directory {}\n", rust_pp_module_abs_path)[]); + script_str.push_str(&format!("directory {}\n", rust_pp_module_abs_path)[]); // Load the target executable - script_str.push_str(format!("file {}\n", - exe_file.as_str().unwrap().replace("\\", "\\\\")) - .as_slice()); + script_str.push_str(&format!("file {}\n", + exe_file.as_str().unwrap().replace("\\", "\\\\"))[]); // Add line breakpoints for line in breakpoint_lines.iter() { - script_str.push_str(format!("break '{}':{}\n", - testfile.filename_display(), - *line)[]); + script_str.push_str(&format!("break '{}':{}\n", + testfile.filename_display(), + *line)[]); } script_str.push_str(cmds.as_slice()); @@ -676,7 +675,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path) .unwrap() .to_string(); - script_str.push_str(format!("command script import {}\n", rust_pp_module_abs_path.index(&FullRange))[]); + script_str.push_str(&format!("command script import {}\n", &rust_pp_module_abs_path[])[]); script_str.push_str("type summary add --no-value "); script_str.push_str("--python-function lldb_rust_formatters.print_val "); script_str.push_str("-x \".*\" --category Rust\n"); diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index eff25b6d385..98e9d6c16b8 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -525,7 +525,7 @@ impl RingBuf { /// *num = *num - 2; /// } /// let b: &[_] = &[&mut 3, &mut 1, &mut 2]; - /// assert_eq!(buf.iter_mut().collect::>()[], b); + /// assert_eq!(&buf.iter_mut().collect::>()[], b); /// ``` #[stable] pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index ca1fed0f78f..e57574fdbce 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -1393,15 +1393,20 @@ fn merge_sort(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order #[cfg(test)] mod tests { - use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal}; - use prelude::{SliceExt, Iterator, IteratorExt}; - use prelude::AsSlice; - use prelude::{RandomAccessIterator, Ord, SliceConcatExt}; + use core::cmp::Ordering::{Greater, Less, Equal}; + use core::prelude::{Some, None, range, Clone}; + use core::prelude::{Iterator, IteratorExt}; + use core::prelude::{AsSlice}; + use core::prelude::{Ord, FullRange}; use core::default::Default; use core::mem; + use core::ops::Index; + use std::iter::RandomAccessIterator; use std::rand::{Rng, thread_rng}; use std::rc::Rc; - use super::ElementSwaps; + use string::ToString; + use vec::Vec; + use super::{ElementSwaps, SliceConcatExt, SliceExt}; fn square(n: uint) -> uint { n * n } diff --git a/src/libcollections/str.rs b/src/libcollections/str.rs index cb4264ec34f..aacb6d90d6f 100644 --- a/src/libcollections/str.rs +++ b/src/libcollections/str.rs @@ -60,7 +60,7 @@ use core::char::CharExt; use core::clone::Clone; use core::iter::AdditiveIterator; use core::iter::{range, Iterator, IteratorExt}; -use core::ops::{self, llRange, Index}; +use core::ops::{FullRange, Index}; use core::option::Option::{self, Some, None}; use core::slice::AsSlice; use core::str as core_str; @@ -408,7 +408,7 @@ Section: Trait implementations /// Any string that can be represented as a slice. #[stable] -pub trait StrExt: Index { +pub trait StrExt: Index { /// Escapes each char in `s` with `char::escape_default`. #[unstable = "return type may change to be an iterator"] fn escape_default(&self) -> String { @@ -1339,12 +1339,6 @@ pub trait StrExt: Index { fn trim_left(&self) -> &str { UnicodeStr::trim_left(self.index(&FullRange)) } - - /// Returns a string with trailing whitespace removed. - #[stable] - fn trim_right(&self) -> &str { - UnicodeStr::trim_right(self.index(&FullRange)) - } } #[stable] @@ -2133,7 +2127,7 @@ mod tests { let mut bytes = [0u8; 4]; for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { let len = c.encode_utf8(&mut bytes).unwrap_or(0); - let s = ::core::str::from_utf8(bytes.index(&(0..len))).unwrap(); + let s = ::core::str::from_utf8(&bytes[..len]).unwrap(); if Some(c) != s.chars().next() { panic!("character {:x}={} does not decode correctly", c as u32, c); } @@ -2145,7 +2139,7 @@ mod tests { let mut bytes = [0u8; 4]; for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { let len = c.encode_utf8(&mut bytes).unwrap_or(0); - let s = ::core::str::from_utf8(bytes.index(&(0..len))).unwrap(); + let s = ::core::str::from_utf8(&bytes[..len]).unwrap(); if Some(c) != s.chars().rev().next() { panic!("character {:x}={} does not decode correctly", c as u32, c); } diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 69ff513a85b..20bc08416dc 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -22,7 +22,7 @@ use core::fmt; use core::hash; use core::iter::FromIterator; use core::mem; -use core::ops::{self, Deref, Add}; +use core::ops::{self, Deref, Add, Index}; use core::ptr; use core::raw::Slice as RawSlice; use unicode::str as unicode_str; @@ -818,28 +818,29 @@ impl<'a> Add<&'a str> for String { } } -impl ops::Index, str> for String { +impl ops::Index> for String { + type Output = str; #[inline] fn index(&self, index: &ops::Range) -> &str { &self.index(&FullRange)[*index] } } - -impl ops::Index, str> for String { +impl ops::Index> for String { + type Output = str; #[inline] fn index(&self, index: &ops::RangeTo) -> &str { &self.index(&FullRange)[*index] } } - -impl ops::Index, str> for String { +impl ops::Index> for String { + type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom) -> &str { &self.index(&FullRange)[*index] } } - -impl ops::Index for String { +impl ops::Index for String { + type Output = str; #[inline] fn index(&self, _index: &ops::FullRange) -> &str { unsafe { mem::transmute(self.vec.as_slice()) } @@ -949,6 +950,7 @@ mod tests { use str::Utf8Error; use core::iter::repeat; use super::{as_string, CowString}; + use core::ops::FullRange; #[test] fn test_as_string() { @@ -1230,10 +1232,10 @@ mod tests { #[test] fn test_slicing() { let s = "foobar".to_string(); - assert_eq!("foobar", s.index(&FullRange)); - assert_eq!("foo", s.index(&(0..3))); - assert_eq!("bar", s.index(&(3..))); - assert_eq!("oob", s.index(&(1..4))); + assert_eq!("foobar", &s[]); + assert_eq!("foo", &s[..3]); + assert_eq!("bar", &s[3..]); + assert_eq!("oob", &s[1..4]); } #[test] diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 3f667698bae..1cfbbdf6cb8 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1209,62 +1209,66 @@ impl IndexMut for Vec { } } -impl ops::Index, [T]> for Vec { + +impl ops::Index> for Vec { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.as_slice().index(index) } } - -impl ops::Index, [T]> for Vec { +impl ops::Index> for Vec { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.as_slice().index(index) } } - -impl ops::Index, [T]> for Vec { +impl ops::Index> for Vec { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.as_slice().index(index) } } - -impl ops::Index for Vec { +impl ops::Index for Vec { + type Output = [T]; #[inline] fn index(&self, _index: &ops::FullRange) -> &[T] { self.as_slice() } } -impl ops::IndexMut, [T]> for Vec { +impl ops::IndexMut> for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { self.as_mut_slice().index_mut(index) } } - -impl ops::IndexMut, [T]> for Vec { +impl ops::IndexMut> for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.as_mut_slice().index_mut(index) } } - -impl ops::IndexMut, [T]> for Vec { +impl ops::IndexMut> for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { self.as_mut_slice().index_mut(index) } } - -impl ops::IndexMut for Vec { +impl ops::IndexMut for Vec { + type Output = [T]; #[inline] fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { self.as_mut_slice() } } + #[stable] impl ops::Deref for Vec { type Target = [T]; @@ -1795,6 +1799,7 @@ mod tests { use prelude::*; use core::mem::size_of; use core::iter::repeat; + use core::ops::FullRange; use test::Bencher; use super::as_vec; @@ -1932,7 +1937,7 @@ mod tests { let (left, right) = values.split_at_mut(2); { let left: &[_] = left; - assert!(left[0..left.len()] == [1, 2][]); + assert!(&left[..left.len()] == &[1, 2][]); } for p in left.iter_mut() { *p += 1; @@ -1940,7 +1945,7 @@ mod tests { { let right: &[_] = right; - assert!(right[0..right.len()] == [3, 4, 5][]); + assert!(&right[..right.len()] == &[3, 4, 5][]); } for p in right.iter_mut() { *p += 2; @@ -2111,35 +2116,35 @@ mod tests { #[should_fail] fn test_slice_out_of_bounds_1() { let x: Vec = vec![1, 2, 3, 4, 5]; - x[-1..]; + &x[(-1)..]; } #[test] #[should_fail] fn test_slice_out_of_bounds_2() { let x: Vec = vec![1, 2, 3, 4, 5]; - x.index(&(0..6)); + &x[..6]; } #[test] #[should_fail] fn test_slice_out_of_bounds_3() { let x: Vec = vec![1, 2, 3, 4, 5]; - x[-1..4]; + &x[(-1)..4]; } #[test] #[should_fail] fn test_slice_out_of_bounds_4() { let x: Vec = vec![1, 2, 3, 4, 5]; - x.index(&(1..6)); + &x[1..6]; } #[test] #[should_fail] fn test_slice_out_of_bounds_5() { let x: Vec = vec![1, 2, 3, 4, 5]; - x.index(&(3..2)); + &x[3..2]; } #[test] @@ -2385,7 +2390,7 @@ mod tests { b.bytes = src_len as u64; b.iter(|| { - let dst = src.clone().as_slice().to_vec(); + let dst = src.clone()[].to_vec(); assert_eq!(dst.len(), src_len); assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); }); diff --git a/src/libcore/array.rs b/src/libcore/array.rs index 37a2177b38d..a4b32f2b6a2 100644 --- a/src/libcore/array.rs +++ b/src/libcore/array.rs @@ -57,9 +57,13 @@ macro_rules! array_impls { Rhs: Deref, { #[inline(always)] - fn eq(&self, other: &Rhs) -> bool { PartialEq::eq(self.index(&FullRange), &**other) } + fn eq(&self, other: &Rhs) -> bool { + PartialEq::eq(self.index(&FullRange), &**other) + } #[inline(always)] - fn ne(&self, other: &Rhs) -> bool { PartialEq::ne(self.index(&FullRange), &**other) } + fn ne(&self, other: &Rhs) -> bool { + PartialEq::ne(self.index(&FullRange), &**other) + } } #[stable] @@ -68,9 +72,13 @@ macro_rules! array_impls { Lhs: Deref { #[inline(always)] - fn eq(&self, other: &[B; $N]) -> bool { PartialEq::eq(&**self, other.index(&FullRange)) } + fn eq(&self, other: &[B; $N]) -> bool { + PartialEq::eq(&**self, other.index(&FullRange)) + } #[inline(always)] - fn ne(&self, other: &[B; $N]) -> bool { PartialEq::ne(&**self, other.index(&FullRange)) } + fn ne(&self, other: &[B; $N]) -> bool { + PartialEq::ne(&**self, other.index(&FullRange)) + } } #[stable] diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index 19c6b29417f..76c2671cfd0 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -521,7 +521,7 @@ impl<'a> Formatter<'a> { let mut fill = [0u8; 4]; let len = self.fill.encode_utf8(&mut fill).unwrap_or(0); - let fill = unsafe { str::from_utf8_unchecked(fill[..len]) }; + let fill = unsafe { str::from_utf8_unchecked(fill.index(&(..len))) }; for _ in range(0, pre_pad) { try!(self.buf.write_str(fill)); diff --git a/src/libcore/slice.rs b/src/libcore/slice.rs index a0bb0205c42..8ab927f701a 100644 --- a/src/libcore/slice.rs +++ b/src/libcore/slice.rs @@ -551,78 +551,8 @@ impl ops::IndexMut for [T] { } } -impl ops::Index, [T]> for [T] { - #[inline] - fn index(&self, &index: &ops::Range) -> &[T] { - assert!(index.start <= index.end); - assert!(index.end <= self.len()); - unsafe { - transmute(RawSlice { - data: self.as_ptr().offset(index.start as int), - len: index.end - index.start - }) - } - } -} - -impl ops::Index, [T]> for [T] { - #[inline] - fn index(&self, &index: &ops::RangeTo) -> &[T] { - self.index(&ops::Range{ start: 0, end: index.end }) - } -} - -impl ops::Index, [T]> for [T] { - #[inline] - fn index(&self, &index: &ops::RangeFrom) -> &[T] { - self.index(&ops::Range{ start: index.start, end: self.len() }) - } -} - -impl ops::Index for [T] { - #[inline] - fn index(&self, &index: &ops::FullRange) -> &[T] { - self - } -} - -impl ops::IndexMut, [T]> for [T] { - #[inline] - fn index_mut(&mut self, &index: &ops::Range) -> &mut [T] { - assert!(index.start <= index.end); - assert!(index.end <= self.len()); - unsafe { - transmute(RawSlice { - data: self.as_ptr().offset(index.start as int), - len: index.end - index.start - }) - } - } -} - -impl ops::IndexMut, [T]> for [T] { - #[inline] - fn index_mut(&mut self, &index: &ops::RangeTo) -> &mut [T] { - self.index_mut(&ops::Range{ start: 0, end: index.end }) - } -} - -impl ops::IndexMut, [T]> for [T] { - #[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 }) - } -} - -impl ops::IndexMut for [T] { - #[inline] - fn index_mut(&mut self, &index: &ops::FullRange) -> &mut [T] { - self - } -} - -impl ops::Index, [T]> for [T] { +impl ops::Index> for [T] { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { assert!(index.start <= index.end); @@ -635,6 +565,64 @@ impl ops::Index, [T]> for [T] { } } } +impl ops::Index> for [T] { + type Output = [T]; + #[inline] + fn index(&self, index: &ops::RangeTo) -> &[T] { + self.index(&ops::Range{ start: 0, end: index.end }) + } +} +impl ops::Index> for [T] { + type Output = [T]; + #[inline] + fn index(&self, index: &ops::RangeFrom) -> &[T] { + self.index(&ops::Range{ start: index.start, end: self.len() }) + } +} +impl ops::Index for [T] { + type Output = [T]; + #[inline] + fn index(&self, _index: &ops::FullRange) -> &[T] { + self + } +} + +impl ops::IndexMut> for [T] { + type Output = [T]; + #[inline] + fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { + assert!(index.start <= index.end); + assert!(index.end <= self.len()); + unsafe { + transmute(RawSlice { + data: self.as_ptr().offset(index.start as int), + len: index.end - index.start + }) + } + } +} +impl ops::IndexMut> for [T] { + type Output = [T]; + #[inline] + fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { + self.index_mut(&ops::Range{ start: 0, end: index.end }) + } +} +impl ops::IndexMut> for [T] { + type Output = [T]; + #[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 }) + } +} +impl ops::IndexMut for [T] { + type Output = [T]; + #[inline] + fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { + self + } +} //////////////////////////////////////////////////////////////////////////////// @@ -767,7 +755,8 @@ pub struct Iter<'a, T: 'a> { } #[experimental] -impl<'a, T> ops::Index, [T]> for Iter<'a, T> { +impl<'a, T> ops::Index> for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.as_slice().index(index) @@ -775,7 +764,8 @@ impl<'a, T> ops::Index, [T]> for Iter<'a, T> { } #[experimental] -impl<'a, T> ops::Index, [T]> for Iter<'a, T> { +impl<'a, T> ops::Index> for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.as_slice().index(index) @@ -783,7 +773,8 @@ impl<'a, T> ops::Index, [T]> for Iter<'a, T> { } #[experimental] -impl<'a, T> ops::Index, [T]> for Iter<'a, T> { +impl<'a, T> ops::Index> for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.as_slice().index(index) @@ -791,14 +782,14 @@ impl<'a, T> ops::Index, [T]> for Iter<'a, T> { } #[experimental] -impl<'a, T> ops::Index for Iter<'a, T> { +impl<'a, T> ops::Index for Iter<'a, T> { + type Output = [T]; #[inline] fn index(&self, _index: &ops::FullRange) -> &[T] { self.as_slice() } } - impl<'a, T> Iter<'a, T> { /// View the underlying data as a subslice of the original data. /// @@ -855,32 +846,34 @@ pub struct IterMut<'a, T: 'a> { marker: marker::ContravariantLifetime<'a>, } + #[experimental] -impl<'a, T> ops::Index, [T]> for IterMut<'a, T> { +impl<'a, T> ops::Index> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::Range) -> &[T] { self.index(&ops::FullRange).index(index) } } - #[experimental] -impl<'a, T> ops::Index, [T]> for IterMut<'a, T> { +impl<'a, T> ops::Index> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeTo) -> &[T] { self.index(&ops::FullRange).index(index) } } - #[experimental] -impl<'a, T> ops::Index, [T]> for IterMut<'a, T> { +impl<'a, T> ops::Index> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, index: &ops::RangeFrom) -> &[T] { self.index(&ops::FullRange).index(index) } } - #[experimental] -impl<'a, T> ops::Index for IterMut<'a, T> { +impl<'a, T> ops::Index for IterMut<'a, T> { + type Output = [T]; #[inline] fn index(&self, _index: &ops::FullRange) -> &[T] { make_slice!(T -> &[T]: self.ptr, self.end) @@ -888,31 +881,32 @@ impl<'a, T> ops::Index for IterMut<'a, T> { } #[experimental] -impl<'a, T> ops::IndexMut, [T]> for IterMut<'a, T> { +impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::Range) -> &mut [T] { self.index_mut(&ops::FullRange).index_mut(index) } } - #[experimental] -impl<'a, T> ops::IndexMut, [T]> for IterMut<'a, T> { +impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeTo) -> &mut [T] { self.index_mut(&ops::FullRange).index_mut(index) } } - #[experimental] -impl<'a, T> ops::IndexMut, [T]> for IterMut<'a, T> { +impl<'a, T> ops::IndexMut> for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, index: &ops::RangeFrom) -> &mut [T] { self.index_mut(&ops::FullRange).index_mut(index) } } - #[experimental] -impl<'a, T> ops::IndexMut for IterMut<'a, T> { +impl<'a, T> ops::IndexMut for IterMut<'a, T> { + type Output = [T]; #[inline] fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { make_slice!(T -> &mut [T]: self.ptr, self.end) diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs index c4e97fe3b7f..bc995a2af72 100644 --- a/src/libcore/str/mod.rs +++ b/src/libcore/str/mod.rs @@ -1119,28 +1119,29 @@ mod traits { } } - impl ops::Index, str> for str { + impl ops::Index> for str { + type Output = str; #[inline] fn index(&self, index: &ops::Range) -> &str { self.slice(index.start, index.end) } } - - impl ops::Index, str> for str { + impl ops::Index> for str { + type Output = str; #[inline] fn index(&self, index: &ops::RangeTo) -> &str { self.slice_to(index.end) } } - - impl ops::Index, str> for str { + impl ops::Index> for str { + type Output = str; #[inline] fn index(&self, index: &ops::RangeFrom) -> &str { self.slice_from(index.start) } } - - impl ops::Index for str { + impl ops::Index for str { + type Output = str; #[inline] fn index(&self, _index: &ops::FullRange) -> &str { self diff --git a/src/libcoretest/iter.rs b/src/libcoretest/iter.rs index 19bfbf3df44..61266a92649 100644 --- a/src/libcoretest/iter.rs +++ b/src/libcoretest/iter.rs @@ -14,7 +14,6 @@ use core::iter::MinMaxResult::*; use core::num::SignedInt; use core::uint; use core::cmp; -use core::ops::Slice; use test::Bencher; @@ -230,7 +229,7 @@ fn test_inspect() { .collect::>(); assert_eq!(n, xs.len()); - assert_eq!(xs.index(&FullRange), ys.index(&FullRange)); + assert_eq!(&xs[], &ys[]); } #[test] @@ -281,47 +280,47 @@ fn test_iterator_nth() { fn test_iterator_last() { let v: &[_] = &[0i, 1, 2, 3, 4]; assert_eq!(v.iter().last().unwrap(), &4); - assert_eq!(v.index(&(0..1)).iter().last().unwrap(), &0); + assert_eq!(v[..1].iter().last().unwrap(), &0); } #[test] fn test_iterator_len() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().count(), 4); - assert_eq!(v.index(&(0..10)).iter().count(), 10); - assert_eq!(v.index(&(0..0)).iter().count(), 0); + assert_eq!(v[..4].iter().count(), 4); + assert_eq!(v[..10].iter().count(), 10); + assert_eq!(v[0..0].iter().count(), 0); } #[test] fn test_iterator_sum() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).sum(), 6); + assert_eq!(v[..4].iter().map(|&x| x).sum(), 6); assert_eq!(v.iter().map(|&x| x).sum(), 55); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).sum(), 0); + assert_eq!(v[0..0].iter().map(|&x| x).sum(), 0); } #[test] fn test_iterator_product() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).product(), 0); - assert_eq!(v.index(&(1..5)).iter().map(|&x| x).product(), 24); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).product(), 1); + assert_eq!(v[0..4].iter().map(|&x| x).product(), 0); + assert_eq!(v[1..5].iter().map(|&x| x).product(), 24); + assert_eq!(v[0..0].iter().map(|&x| x).product(), 1); } #[test] fn test_iterator_max() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).max(), Some(3)); + assert_eq!(v[0..4].iter().map(|&x| x).max(), Some(3)); assert_eq!(v.iter().map(|&x| x).max(), Some(10)); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).max(), None); + assert_eq!(v[0..0].iter().map(|&x| x).max(), None); } #[test] fn test_iterator_min() { let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - assert_eq!(v.index(&(0..4)).iter().map(|&x| x).min(), Some(0)); + assert_eq!(v[0..4].iter().map(|&x| x).min(), Some(0)); assert_eq!(v.iter().map(|&x| x).min(), Some(0)); - assert_eq!(v.index(&(0..0)).iter().map(|&x| x).min(), None); + assert_eq!(v[0..0].iter().map(|&x| x).min(), None); } #[test] @@ -374,7 +373,7 @@ fn test_all() { assert!(v.iter().all(|&x| x < 10)); assert!(!v.iter().all(|&x| x % 2 == 0)); assert!(!v.iter().all(|&x| x > 100)); - assert!(v.slice_or_fail(&0, &0).iter().all(|_| panic!())); + assert!(v[0..0].iter().all(|_| panic!())); } #[test] @@ -383,7 +382,7 @@ fn test_any() { assert!(v.iter().any(|&x| x < 10)); assert!(v.iter().any(|&x| x % 2 == 0)); assert!(!v.iter().any(|&x| x > 100)); - assert!(!v.slice_or_fail(&0, &0).iter().any(|_| panic!())); + assert!(!v[0..0].iter().any(|_| panic!())); } #[test] @@ -586,7 +585,7 @@ fn check_randacc_iter(a: T, len: uint) where fn test_double_ended_flat_map() { let u = [0u,1]; let v = [5u,6,7,8]; - let mut it = u.iter().flat_map(|x| v[*x..v.len()].iter()); + let mut it = u.iter().flat_map(|x| v[(*x)..v.len()].iter()); assert_eq!(it.next_back().unwrap(), &8); assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next_back().unwrap(), &7); diff --git a/src/libcoretest/slice.rs b/src/libcoretest/slice.rs index d20def89abb..b714b6a4e41 100644 --- a/src/libcoretest/slice.rs +++ b/src/libcoretest/slice.rs @@ -43,35 +43,35 @@ fn iterator_to_slice() { { let mut iter = data.iter(); - assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); + assert_eq!(&iter[], &other_data[]); iter.next(); - assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); + assert_eq!(&iter[], &other_data[1..]); iter.next_back(); - assert_eq!(iter.index(&FullRange), other_data.index(&(1..2))); + assert_eq!(&iter[], &other_data[1..2]); let s = iter.as_slice(); iter.next(); - assert_eq!(s, other_data.index(&(1..2))); + assert_eq!(s, &other_data[1..2]); } { let mut iter = data.iter_mut(); assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); // mutability: - assert!(iter[mut] == other_data); + assert!(&mut iter[] == other_data); iter.next(); assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); - assert!(iter[mut] == other_data[mut 1..]); + assert!(&mut iter[] == &mut other_data[1..]); iter.next_back(); assert_eq!(iter.index(&FullRange), other_data.index(&(1..2))); - assert!(iter[mut] == other_data[mut 1..2]); + assert!(&mut iter[] == &mut other_data[1..2]); let s = iter.into_slice(); - assert!(s == other_data[mut 1..2]); + assert!(s == &mut other_data[1..2]); } }} } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index a9e4e8d2514..dd9e5e5a038 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -1413,7 +1413,7 @@ mod tests { assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(!matches_single.opts_present(&["encrypt".to_string()])); assert!(!matches_single.opts_present(&["thing".to_string()])); - assert!(!matches_single.opts_present(&.index(&FullRange))); + assert!(!matches_single.opts_present(&[])); assert_eq!(matches_single.opts_str(&["e".to_string()]).unwrap(), "foo"); assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), @@ -1434,7 +1434,7 @@ mod tests { assert!(matches_both.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(!matches_both.opts_present(&["f".to_string()])); assert!(!matches_both.opts_present(&["thing".to_string()])); - assert!(!matches_both.opts_present(&.index(&FullRange))); + assert!(!matches_both.opts_present(&[])); assert_eq!(matches_both.opts_str(&["e".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo"); diff --git a/src/librand/distributions/mod.rs b/src/librand/distributions/mod.rs index 6fe995d1c58..2fdba8a6c4f 100644 --- a/src/librand/distributions/mod.rs +++ b/src/librand/distributions/mod.rs @@ -24,7 +24,7 @@ use core::num::{Float, Int}; use {Rng, Rand}; -pub use self::range::Range as RandRange; +pub use self::range::Range; pub use self::gamma::{Gamma, ChiSquared, FisherF, StudentT}; pub use self::normal::{Normal, LogNormal}; pub use self::exponential::Exp; @@ -104,7 +104,7 @@ pub struct Weighted { /// ``` pub struct WeightedChoice<'a, T:'a> { items: &'a mut [Weighted], - weight_range: RandRange + weight_range: Range } impl<'a, T: Clone> WeightedChoice<'a, T> { @@ -138,7 +138,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> { items: items, // we're likely to be generating numbers in this range // relatively often, so might as well cache it - weight_range: RandRange::new(0, running_total) + weight_range: Range::new(0, running_total) } } } diff --git a/src/librand/distributions/range.rs b/src/librand/distributions/range.rs index 2369c094b9f..1002d9693ba 100644 --- a/src/librand/distributions/range.rs +++ b/src/librand/distributions/range.rs @@ -166,7 +166,7 @@ mod tests { use std::num::Int; use std::prelude::v1::*; use distributions::{Sample, IndependentSample}; - use super::Range; + use super::Range as Range; #[should_fail] #[test] diff --git a/src/librand/lib.rs b/src/librand/lib.rs index 51ae3114cad..aeecd69e205 100644 --- a/src/librand/lib.rs +++ b/src/librand/lib.rs @@ -58,7 +58,7 @@ use core::prelude::*; pub use isaac::{IsaacRng, Isaac64Rng}; pub use chacha::ChaChaRng; -use distributions::{RandRange, IndependentSample}; +use distributions::{Range, IndependentSample}; use distributions::range::SampleRange; #[cfg(test)] @@ -247,7 +247,7 @@ pub trait Rng : Sized { /// ``` fn gen_range(&mut self, low: T, high: T) -> T { assert!(low < high, "Rng.gen_range called with low >= high"); - RandRange::new(low, high).ind_sample(self) + Range::new(low, high).ind_sample(self) } /// Return a bool with a 1 in n chance of true @@ -290,8 +290,8 @@ pub trait Rng : Sized { /// let choices = [1i, 2, 4, 8, 16, 32]; /// let mut rng = thread_rng(); /// println!("{}", rng.choose(&choices)); - /// # // replace with slicing syntax when it's stable! - /// assert_eq!(rng.choose(choices.index(&(0..0))), None); + /// # // uncomment when slicing syntax is stable + /// //assert_eq!(rng.choose(choices.index(&(0..0))), None); /// ``` fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { if values.is_empty() { diff --git a/src/libregex/test/matches.rs b/src/libregex/test/matches.rs index b422ac668ca..7508f4c50a2 100644 --- a/src/libregex/test/matches.rs +++ b/src/libregex/test/matches.rs @@ -121,7 +121,7 @@ mat!{match_basic_110, r"a[b-d]", r"aac", Some((1, 3))} mat!{match_basic_111, r"a[-b]", r"a-", Some((0, 2))} mat!{match_basic_112, r"a[b-]", r"a-", Some((0, 2))} mat!{match_basic_113, r"a]", r"a]", Some((0, 2))} -mat!{match_basic_114, r"a.index(&FullRange)]b", r"a]b", Some((0, 3))} +mat!{match_basic_114, r"a[]]b", r"a]b", Some((0, 3))} mat!{match_basic_115, r"a[^bc]d", r"aed", Some((0, 3))} mat!{match_basic_116, r"a[^-b]c", r"adc", Some((0, 3))} mat!{match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))} diff --git a/src/libregex/test/tests.rs b/src/libregex/test/tests.rs index d087814b7f4..4f38370d7a1 100644 --- a/src/libregex/test/tests.rs +++ b/src/libregex/test/tests.rs @@ -159,7 +159,7 @@ macro_rules! mat { // actual capture groups to match test set. let mut sgot = got.as_slice(); if sgot.len() > expected.len() { - sgot = sgot[0..expected.len()] + sgot = &sgot[..expected.len()] } if expected != sgot { panic!("For RE '{}' against '{}', expected '{}' but got '{}'", diff --git a/src/librustc/lint/context.rs b/src/librustc/lint/context.rs index fa451e03ab9..51998bdbcf2 100644 --- a/src/librustc/lint/context.rs +++ b/src/librustc/lint/context.rs @@ -499,7 +499,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> { None => { self.span_lint(builtin::UNKNOWN_LINTS, span, format!("unknown `{}` attribute: `{}`", - level.as_str(), lint_name).index(&FullRange)); + level.as_str(), lint_name).as_slice()); continue; } } @@ -791,7 +791,7 @@ pub fn check_crate(tcx: &ty::ctxt, for &(lint, span, ref msg) in v.iter() { tcx.sess.span_bug(span, format!("unprocessed lint {} at {}: {}", - lint.as_str(), tcx.map.node_to_string(*id), *msg).index(&FullRange)) + lint.as_str(), tcx.map.node_to_string(*id), *msg).as_slice()) } } diff --git a/src/librustc/metadata/creader.rs b/src/librustc/metadata/creader.rs index 08d19dcb607..8961c3e728c 100644 --- a/src/librustc/metadata/creader.rs +++ b/src/librustc/metadata/creader.rs @@ -209,7 +209,7 @@ impl<'a> CrateReader<'a> { let name = match *path_opt { Some((ref path_str, _)) => { let name = path_str.get().to_string(); - validate_crate_name(Some(self.sess), name[], + validate_crate_name(Some(self.sess), name.index(&FullRange), Some(i.span)); name } @@ -276,7 +276,7 @@ impl<'a> CrateReader<'a> { } else { self.sess.span_err(m.span, format!("unknown kind: `{}`", - k)[]); + k).index(&FullRange)); cstore::NativeUnknown } } @@ -330,7 +330,7 @@ impl<'a> CrateReader<'a> { match self.sess.opts.externs.get(name) { Some(locs) => { let found = locs.iter().any(|l| { - let l = fs::realpath(&Path::new(l[])).ok(); + let l = fs::realpath(&Path::new(l.index(&FullRange))).ok(); l == source.dylib || l == source.rlib }); if found { @@ -409,7 +409,7 @@ impl<'a> CrateReader<'a> { crate_name: name, hash: hash.map(|a| &*a), filesearch: self.sess.target_filesearch(kind), - triple: self.sess.opts.target_triple[], + triple: self.sess.opts.target_triple.index(&FullRange), root: root, rejected_via_hash: vec!(), rejected_via_triple: vec!(), diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index 592fbe4d64e..b19501229aa 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -1826,10 +1826,10 @@ fn encode_macro_defs(rbml_w: &mut Encoder, rbml_w.start_tag(tag_macro_def); encode_name(rbml_w, def.ident.name); - encode_attributes(rbml_w, def.attrs[]); + encode_attributes(rbml_w, def.attrs.index(&FullRange)); rbml_w.start_tag(tag_macro_def_body); - rbml_w.wr_str(pprust::tts_to_string(def.body[])[]); + rbml_w.wr_str(pprust::tts_to_string(def.body.index(&FullRange)).index(&FullRange)); rbml_w.end_tag(); rbml_w.end_tag(); diff --git a/src/librustc/metadata/loader.rs b/src/librustc/metadata/loader.rs index 6f75770bcb8..4106d216bf9 100644 --- a/src/librustc/metadata/loader.rs +++ b/src/librustc/metadata/loader.rs @@ -624,7 +624,8 @@ impl<'a> Context<'a> { return true } else { let (ref prefix, ref suffix) = dylibname; - if file.starts_with(prefix.index(&FullRange)) && file.ends_with(suffix.index(&FullRange)) { + if file.starts_with(prefix.index(&FullRange)) && + file.ends_with(suffix.index(&FullRange)) { return true } } diff --git a/src/librustc/middle/cfg/graphviz.rs b/src/librustc/middle/cfg/graphviz.rs index 34dae07642d..8b9a0d89b38 100644 --- a/src/librustc/middle/cfg/graphviz.rs +++ b/src/librustc/middle/cfg/graphviz.rs @@ -85,7 +85,9 @@ impl<'a, 'ast> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a, 'ast> { let s = self.ast_map.node_to_string(node_id); // left-aligns the lines let s = replace_newline_with_backslash_l(s); - label.push_str(format!("exiting scope_{} {}", i, s.index(&FullRange)).index(&FullRange)); + label.push_str(format!("exiting scope_{} {}", + i, + s.index(&FullRange)).index(&FullRange)); } dot::LabelText::EscStr(label.into_cow()) } diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index d8d7c5afb10..ac53bdbefcf 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -165,6 +165,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) { ast::ExprParen(..) | ast::ExprField(..) | ast::ExprTupField(..) | + ast::ExprIndex(..) | ast::ExprTup(..) | ast::ExprRepeat(..) | ast::ExprStruct(..) => {} diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index f71d020a1b8..1f89121488e 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -1158,7 +1158,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { let msg = format!("Pattern has unexpected type: {} and type {}", def, cmt_pat.ty.repr(tcx)); - tcx.sess.span_bug(pat.span, msg[]) + tcx.sess.span_bug(pat.span, msg.as_slice()) } } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 99c2fad0e50..81d4d66a88e 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -495,7 +495,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { ret_ty), 1, true) } None => { - self.cat_index(expr, self.cat_expr(&**base)) + self.cat_index(expr, try!(self.cat_expr(&**base))) } } } @@ -1497,7 +1497,7 @@ impl<'tcx> Repr<'tcx> for InteriorKind { token::get_name(fld).get().to_string() } InteriorField(PositionalField(i)) => format!("#{}", i), - InteriorElement(_) => ".index(&FullRange)".to_string(), + InteriorElement(_) => "[]".to_string(), } } } diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index ce926fd8d10..3638d98ae88 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -378,7 +378,7 @@ pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, span, format!("overflow evaluating whether `{}` is `{}`", ty.user_string(infcx.tcx), - bound.user_string(infcx.tcx))[]); + bound.user_string(infcx.tcx)).as_slice()); suggest_new_overflow_limit(infcx.tcx, span); false } diff --git a/src/librustc/middle/traits/object_safety.rs b/src/librustc/middle/traits/object_safety.rs index 8880cb7ce73..17792ef78ab 100644 --- a/src/librustc/middle/traits/object_safety.rs +++ b/src/librustc/middle/traits/object_safety.rs @@ -178,7 +178,7 @@ fn object_safety_violations_for_method<'tcx>(tcx: &ty::ctxt<'tcx>, // The `Self` type is erased, so it should not appear in list of // arguments or return type apart from the receiver. let ref sig = method.fty.sig; - for &input_ty in sig.0.inputs[1..].iter() { + for &input_ty in sig.0.inputs.index(&(1..)).iter() { if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) { return Some(MethodViolationCode::ReferencesSelf); } diff --git a/src/librustc/middle/traits/project.rs b/src/librustc/middle/traits/project.rs index 65f7ad296db..67a8508e60d 100644 --- a/src/librustc/middle/traits/project.rs +++ b/src/librustc/middle/traits/project.rs @@ -490,7 +490,7 @@ fn assemble_candidates_from_object_type<'cx,'tcx>( selcx.tcx().sess.span_bug( obligation.cause.span, format!("assemble_candidates_from_object_type called with non-object: {}", - object_ty.repr(selcx.tcx()))[]); + object_ty.repr(selcx.tcx())).as_slice()); } }; let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty); diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index d954495055d..e24fe46b34d 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -3654,7 +3654,8 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool { ty_unboxed_closure(..) => { // this check is run on type definitions, so we don't expect to see // inference by-products or unboxed closure types - cx.sess.bug(format!("requires check invoked on inapplicable type: {}", ty)[]) + cx.sess.bug(format!("requires check invoked on inapplicable type: {}", + ty).as_slice()) } ty_tup(ref ts) => { @@ -3747,7 +3748,8 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) ty_unboxed_closure(..) => { // this check is run on type definitions, so we don't expect to see // unboxed closure types - cx.sess.bug(format!("requires check invoked on inapplicable type: {}", ty)[]) + cx.sess.bug(format!("requires check invoked on inapplicable type: {}", + ty).as_slice()) } _ => Representable, } diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 88a71e53b60..d3f8c8284e0 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -639,7 +639,7 @@ pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config { let target = match Target::search(opts.target_triple.index(&FullRange)) { Ok(t) => t, Err(e) => { - sp.handler().fatal((format!("Error loading target specification: {}", e)).index(&FullRange)); + sp.handler().fatal((format!("Error loading target specification: {}", e)).as_slice()); } }; @@ -1027,7 +1027,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options { s => { early_error(format!("unknown library kind `{}`, expected \ one of dylib, framework, or static", - s)[]); + s).as_slice()); } }; return (name.to_string(), kind) diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 5f5ad7efdf1..02bb6aa4b0d 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -247,7 +247,9 @@ impl Target { } ); ($key_name:ident, bool) => ( { let name = (stringify!($key_name)).replace("_", "-"); - obj.find(name.index(&FullRange)).map(|o| o.as_boolean().map(|s| base.options.$key_name = s)); + obj.find(name.index(&FullRange)) + .map(|o| o.as_boolean() + .map(|s| base.options.$key_name = s)); } ); ($key_name:ident, list) => ( { let name = (stringify!($key_name)).replace("_", "-"); diff --git a/src/librustc_borrowck/borrowck/doc.rs b/src/librustc_borrowck/borrowck/doc.rs index e309ba0a634..2100d5a9bc3 100644 --- a/src/librustc_borrowck/borrowck/doc.rs +++ b/src/librustc_borrowck/borrowck/doc.rs @@ -138,7 +138,7 @@ //! - `FREEZE` means that the `LV` cannot be borrowed immutably; //! //! Finally, it is never possible to move from an lvalue that appears in a -//! restriction. This implies that the "empty restriction" `(LV, .index(&FullRange))`, +//! restriction. This implies that the "empty restriction" `(LV, [])`, //! which contains an empty set of actions, still has a purpose---it //! prevents moves from `LV`. I chose not to make `MOVE` a fourth kind of //! action because that would imply that sometimes moves are permitted @@ -476,7 +476,7 @@ //! ```text //! &mut LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM|FREEZE) //! &LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM) -//! &const LV => RESTRICTIONS(LV, LT, .index(&FullRange)) +//! &const LV => RESTRICTIONS(LV, LT, []) //! ``` //! //! The reasoning here is that a mutable borrow must be the only writer, @@ -542,7 +542,7 @@ //! restricting `MUTATE` and `CLAIM` actions: //! //! ```text -//! RESTRICTIONS(*LV, LT, ACTIONS) = .index(&FullRange) // R-Deref-Imm-Borrowed +//! RESTRICTIONS(*LV, LT, ACTIONS) = [] // R-Deref-Imm-Borrowed //! TYPE(LV) = <' Ty //! LT <= LT' // (1) //! ACTIONS subset of [MUTATE, CLAIM] @@ -660,7 +660,7 @@ //! necessary to add any restrictions at all to the final result. //! //! ```text -//! RESTRICTIONS(*LV, LT, .index(&FullRange)) = .index(&FullRange) // R-Deref-Freeze-Borrowed +//! RESTRICTIONS(*LV, LT, []) = [] // R-Deref-Freeze-Borrowed //! TYPE(LV) = &const Ty //! ``` //! diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 36e1a486112..75dee496234 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -804,7 +804,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { mc::AliasableClosure(id) => { self.tcx.sess.span_err(span, format!("{} in a captured outer \ - variable in an `Fn` closure", prefix).index(&FullRange)); + variable in an `Fn` closure", prefix).as_slice()); span_help!(self.tcx.sess, self.tcx.map.span(id), "consider changing this closure to take self by mutable reference"); } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index d8c7a62e194..debbf2767ac 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -3763,13 +3763,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { self.resolve_error(path.span, format!("`{}` is not an enum variant, struct or const", token::get_ident( - path.segments.last().unwrap().identifier)).index(&FullRange)); + path.segments.last().unwrap().identifier)).as_slice()); } None => { self.resolve_error(path.span, format!("unresolved enum variant, struct or const `{}`", token::get_ident( - path.segments.last().unwrap().identifier)).index(&FullRange)); + path.segments.last().unwrap().identifier)).as_slice()); } } diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index 388bc4a4d30..aff5f00e64e 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -608,7 +608,7 @@ fn link_rlib<'a>(sess: &'a Session, // extension to it. This is to work around a bug in LLDB that // would cause it to crash if the name of a file in an archive // was exactly 16 bytes. - let bc_filename = obj_filename.with_extension(format!("{}.bc", i).index(&FullRange)); + let bc_filename = obj_filename.with_extension(format!("{}.bc", i).as_slice()); let bc_deflated_filename = obj_filename.with_extension( format!("{}.bytecode.deflate", i).index(&FullRange)); @@ -1083,8 +1083,8 @@ fn add_local_native_libraries(cmd: &mut Command, sess: &Session) { // -force_load is the OSX equivalent of --whole-archive, but it // involves passing the full path to the library to link. let lib = archive::find_library(l.index(&FullRange), - sess.target.target.options.staticlib_prefix.index(&FullRange), - sess.target.target.options.staticlib_suffix.index(&FullRange), + sess.target.target.options.staticlib_prefix.as_slice(), + sess.target.target.options.staticlib_suffix.as_slice(), search_path.index(&FullRange), &sess.diagnostic().handler); let mut v = b"-Wl,-force_load,".to_vec(); diff --git a/src/librustc_trans/back/lto.rs b/src/librustc_trans/back/lto.rs index 450b4176b7a..ecf2e9ed724 100644 --- a/src/librustc_trans/back/lto.rs +++ b/src/librustc_trans/back/lto.rs @@ -64,7 +64,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef, debug!("reading {}", file); for i in iter::count(0u, 1) { let bc_encoded = time(sess.time_passes(), - format!("check for {}.{}.bytecode.deflate", name, i).index(&FullRange), + format!("check for {}.{}.bytecode.deflate", name, i).as_slice(), (), |_| { archive.read(format!("{}.{}.bytecode.deflate", diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index f27f7dc5719..56d7fb09662 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -381,8 +381,8 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo cgcx.handler.note(format!("optimization {} for {} at {}: {}", opt.kind.describe(), pass_name, - if loc.is_empty() { "[unknown]" } else { loc.index(&FullRange) }, - llvm::twine_to_string(opt.message)).index(&FullRange)); + if loc.is_empty() { "[unknown]" } else { loc.as_slice() }, + llvm::twine_to_string(opt.message)).as_slice()); } } diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index b27421ea426..4ac9f1c7c93 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -292,7 +292,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { Some(def_id) => { result.push_str(" as "); result.push_str( - ty::item_path_str(&self.analysis.ty_cx, def_id).index(&FullRange)); + ty::item_path_str(&self.analysis.ty_cx, def_id).as_slice()); }, None => {} } @@ -636,7 +636,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { item.id); for field in struct_def.fields.iter() { - self.process_struct_field_def(field, qualname.index(&FullRange), variant.node.id); + self.process_struct_field_def(field, qualname.as_slice(), variant.node.id); self.visit_ty(&*field.node.ty); } } @@ -774,7 +774,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&id) { self.sess.span_bug(span, - format!("def_map has no key for {} in visit_expr", id).index(&FullRange)); + format!("def_map has no key for {} in visit_expr", id).as_slice()); } let def = &(*def_map)[id]; let sub_span = self.span.span_for_last_ident(span); @@ -1065,7 +1065,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { value.index(&FullRange)); self.visit_ty(&**ty); - self.process_generic_params(ty_params, item.span, qualname.index(&FullRange), item.id); + self.process_generic_params(ty_params, item.span, qualname.as_slice(), item.id); }, ast::ItemMac(_) => (), _ => visit::walk_item(self, item), @@ -1418,7 +1418,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { let def_map = self.analysis.ty_cx.def_map.borrow(); if !def_map.contains_key(&id) { self.sess.span_bug(p.span, - format!("def_map has no key for {} in visit_arm", id).index(&FullRange)); + format!("def_map has no key for {} in visit_arm", + id).index(&FullRange)); } let def = &(*def_map)[id]; match *def { diff --git a/src/librustc_trans/save/recorder.rs b/src/librustc_trans/save/recorder.rs index 5352fcc2fed..bb0fb387002 100644 --- a/src/librustc_trans/save/recorder.rs +++ b/src/librustc_trans/save/recorder.rs @@ -237,7 +237,7 @@ impl<'a> FmtStrs<'a> { if !needs_span { self.span.sess.span_bug(span, format!("Called record_with_span for '{}' \ - which does not require a span", label).index(&FullRange)); + which does not require a span", label).as_slice()); } let values_str = match self.make_values_str(label, fields, values, span) { diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index f55076e7484..438cfe0b6c7 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -1037,8 +1037,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, field_vals.len()) ); let mut vals = field_vals; - vals.push_all(vals_left.index(&FullRange)); - compile_submatch(bcx, pats.index(&FullRange), vals.index(&FullRange), chk, has_genuine_default); + vals.push_all(vals_left.as_slice()); + compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default); return; } _ => () diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index e69bfb57670..458c1fa923e 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -2239,7 +2239,7 @@ pub fn update_linkage(ccx: &CrateContext, if let Some(id) = id { let item = ccx.tcx().map.get(id); if let ast_map::NodeItem(i) = item { - if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.index(&FullRange), "linkage") { + if let Some(name) = attr::first_attr_value_str_by_name(i.attrs.as_slice(), "linkage") { if let Some(linkage) = llvm_linkage_by_name(name.get()) { llvm::SetLinkage(llval, linkage); } else { @@ -2597,7 +2597,11 @@ pub fn register_fn_llvmty(ccx: &CrateContext, llfty: Type) -> ValueRef { debug!("register_fn_llvmty id={} sym={}", node_id, sym); - let llfn = decl_fn(ccx, sym.index(&FullRange), cc, llfty, ty::FnConverging(ty::mk_nil(ccx.tcx()))); + let llfn = decl_fn(ccx, + sym.index(&FullRange), + cc, + llfty, + ty::FnConverging(ty::mk_nil(ccx.tcx()))); finish_register_fn(ccx, sp, sym, node_id, llfn); llfn } diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index 5777ee78800..44890407d08 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -414,7 +414,7 @@ impl<'tcx> TypeMap<'tcx> { unique_type_id.push_str(format!("[{}]", len).index(&FullRange)); } None => { - unique_type_id.push_str(".index(&FullRange)"); + unique_type_id.push_str("[]"); } }; diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index 24feb579a06..da19fc52c8c 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -1369,13 +1369,13 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, let tcx = bcx.tcx(); with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| { - let mut need_base: Vec<_> = repeat(true).take(field_tys.len()).collect(); + let mut need_base: Vec = repeat(true).take(field_tys.len()).collect(); let numbered_fields = fields.iter().map(|field| { let opt_pos = field_tys.iter().position(|field_ty| field_ty.name == field.ident.node.name); - match opt_pos { + let result = match opt_pos { Some(i) => { need_base[i] = false; (i, &*field.expr) @@ -1384,14 +1384,15 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, tcx.sess.span_bug(field.span, "Couldn't find field in struct type") } - } + }; + result }).collect::>(); let optbase = match base { Some(base_expr) => { let mut leftovers = Vec::new(); for (i, b) in need_base.iter().enumerate() { if *b { - leftovers.push((i, field_tys[i].mt.ty)) + leftovers.push((i, field_tys[i].mt.ty)); } } Some(StructBaseInfo {expr: base_expr, @@ -1408,7 +1409,7 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, trans_adt(bcx, ty, discr, - numbered_fields.index(&FullRange), + numbered_fields.as_slice(), optbase, dest, Some(NodeInfo { id: expr_id, span: expr_span })) diff --git a/src/librustc_trans/trans/foreign.rs b/src/librustc_trans/trans/foreign.rs index a90f0dbbf15..c8112e03707 100644 --- a/src/librustc_trans/trans/foreign.rs +++ b/src/librustc_trans/trans/foreign.rs @@ -748,7 +748,7 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, debug!("calling llrustfn = {}, t = {}", ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx())); let attributes = base::get_fn_llvm_attributes(ccx, t); - let llrust_ret_val = builder.call(llrustfn, llrust_args.index(&FullRange), Some(attributes)); + let llrust_ret_val = builder.call(llrustfn, llrust_args.as_slice(), Some(attributes)); // Get the return value where the foreign fn expects it. let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast { @@ -869,7 +869,7 @@ fn foreign_types_for_fn_ty<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty.repr(ccx.tcx()), ccx.tn().types_to_str(llsig.llarg_tys.index(&FullRange)), ccx.tn().type_to_string(llsig.llret_ty), - ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::>().index(&FullRange)), + ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::>().as_slice()), ccx.tn().type_to_string(fn_ty.ret_ty.ty), llsig.ret_def); diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 7d36d01cc50..a2b1c32f0a5 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -556,7 +556,8 @@ pub fn instantiate_trait_ref<'tcx>( _ => { this.tcx().sess.span_fatal( ast_trait_ref.path.span, - format!("`{}` is not a trait", ast_trait_ref.path.user_string(this.tcx())).index(&FullRange)); + format!("`{}` is not a trait", + ast_trait_ref.path.user_string(this.tcx())).index(&FullRange)); } } } @@ -1069,8 +1070,12 @@ pub fn ast_ty_to_ty<'tcx>( ast::TyObjectSum(ref ty, ref bounds) => { match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.index(&FullRange)) { Ok((trait_ref, projection_bounds)) => { - trait_ref_to_object_type(this, rscope, ast_ty.span, - trait_ref, projection_bounds, bounds.index(&FullRange)) + trait_ref_to_object_type(this, + rscope, + ast_ty.span, + trait_ref, + projection_bounds, + bounds.index(&FullRange)) } Err(ErrorReported) => { this.tcx().types.err diff --git a/src/librustc_typeck/check/callee.rs b/src/librustc_typeck/check/callee.rs index b1dc033b567..dff216ac293 100644 --- a/src/librustc_typeck/check/callee.rs +++ b/src/librustc_typeck/check/callee.rs @@ -195,7 +195,7 @@ fn confirm_builtin_call<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>]. check_argument_types(fcx, call_expr.span, - fn_sig.inputs[], + fn_sig.inputs.as_slice(), arg_exprs.as_slice(), AutorefArgs::No, fn_sig.variadic, diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index d43850989fe..652540bde70 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -563,7 +563,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { &**base_expr, Some(&ty::AdjustDerefRef(base_adjustment.clone()))); let index_expr_ty = self.fcx.expr_ty(&**index_expr); - + let result = check::try_index_step( self.fcx, MethodCall::expr(expr.id), @@ -640,7 +640,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { self.span, format!("cannot upcast `{}` to `{}`", source_trait_ref.repr(self.tcx()), - target_trait_def_id.repr(self.tcx()))[]); + target_trait_def_id.repr(self.tcx())).as_slice()); } } } diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 50f73312c77..eb85654e68e 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -3976,7 +3976,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, callee::check_call(fcx, expr, &**callee, args.as_slice()); } ast::ExprMethodCall(ident, ref tps, ref args) => { - check_method_call(fcx, expr, ident, args.index(&FullRange), tps.index(&FullRange), lvalue_pref); + check_method_call(fcx, expr, ident, args.as_slice(), tps.as_slice(), lvalue_pref); let arg_tys = args.iter().map(|a| fcx.expr_ty(&**a)); let args_err = arg_tys.fold(false, |rest_err, a| { diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index cc36065656c..7d52418a9db 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -1318,7 +1318,7 @@ fn get_or_create_type_parameter_def<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, let param_ty = ty::ParamTy::new(space, index, param.ident.name); let bounds = compute_bounds(ccx, param_ty.to_ty(ccx.tcx), - param.bounds.index(&FullRange, + param.bounds.index(&FullRange), SizedByDefault::Yes, param.span); let default = match param.default { diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 6c0f6610802..abc669729fe 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -97,7 +97,7 @@ impl fmt::Show for clean::Generics { if i > 0 { try!(f.write_str(", ")) } - try!(f.write_str(tp.name[])); + try!(f.write_str(tp.name.as_slice())); if tp.bounds.len() > 0 { try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice()))); @@ -337,7 +337,7 @@ fn path(w: &mut fmt::Formatter, // This is a documented path, link to it! Some((ref fqp, shortty)) if abs_root.is_some() => { let mut url = String::from_str(abs_root.unwrap().as_slice()); - let to_link = fqp[..fqp.len() - 1]; + let to_link = &fqp[..(fqp.len() - 1)]; for component in to_link.iter() { url.push_str(component.as_slice()); url.push_str("/"); @@ -433,7 +433,7 @@ impl fmt::Show for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::TyParamBinder(id) => { - f.write_str(cache().typarams[ast_util::local_def(id)][]) + f.write_str(cache().typarams[ast_util::local_def(id)].as_slice()) } clean::Generic(ref name) => { f.write_str(name.as_slice()) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index ddb14d6944b..a01fcd39952 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -404,7 +404,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult search_index.push(IndexItem { ty: shortty(item), name: item.name.clone().unwrap(), - path: fqp[..fqp.len() - 1].connect("::"), + path: fqp[..(fqp.len() - 1)].connect("::"), desc: shorter(item.doc_value()).to_string(), parent: Some(did), }); @@ -559,7 +559,7 @@ fn write_shared(cx: &Context, }; let mut mydst = dst.clone(); - for part in remote_path[..remote_path.len() - 1].iter() { + for part in remote_path[..(remote_path.len() - 1)].iter() { mydst.push(part.as_slice()); try!(mkdir(&mydst)); } @@ -842,7 +842,7 @@ impl DocFolder for Cache { clean::StructFieldItem(..) | clean::VariantItem(..) => { ((Some(*self.parent_stack.last().unwrap()), - Some(self.stack[..self.stack.len() - 1])), + Some(&self.stack[..(self.stack.len() - 1)])), false) } clean::MethodItem(..) => { @@ -853,13 +853,13 @@ impl DocFolder for Cache { let did = *last; let path = match self.paths.get(&did) { Some(&(_, ItemType::Trait)) => - Some(self.stack[..self.stack.len() - 1]), + Some(&self.stack[..(self.stack.len() - 1)]), // The current stack not necessarily has correlation for // where the type was defined. On the other hand, // `paths` always has the right information if present. Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Enum)) => - Some(fqp[..fqp.len() - 1]), + Some(&fqp[..(fqp.len() - 1)]), Some(..) => Some(self.stack.as_slice()), None => None }; @@ -1185,7 +1185,7 @@ impl Context { .collect::(); match cache().paths.get(&it.def_id) { Some(&(ref names, _)) => { - for name in names[..names.len() - 1].iter() { + for name in (&names[..(names.len() - 1)]).iter() { url.push_str(name.as_slice()); url.push_str("/"); } @@ -2267,7 +2267,7 @@ fn item_macro(w: &mut fmt::Formatter, it: &clean::Item, t: &clean::Macro) -> fmt::Result { try!(w.write_str(highlight::highlight(t.source.as_slice(), Some("macro"), - None)[])); + None).as_slice())); document(w, it) } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index 18c79fb9c59..c520b6f4723 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -1124,7 +1124,7 @@ impl Json { } } -impl<'a> ops::Index<&'a str> for Json { +impl<'a> Index<&'a str> for Json { type Output = Json; fn index(&self, idx: & &str) -> &Json { @@ -1132,7 +1132,7 @@ impl<'a> ops::Index<&'a str> for Json { } } -impl ops::Index for Json { +impl Index for Json { type Output = Json; fn index<'a>(&'a self, idx: &uint) -> &'a Json { @@ -1186,7 +1186,8 @@ pub struct Stack { } /// StackElements compose a Stack. -/// For example, StackElement::Key("foo"), StackElement::Key("bar"), StackElement::Index(3) and StackElement::Key("x") are the +/// For example, StackElement::Key("foo"), StackElement::Key("bar"), +/// StackElement::Index(3) and StackElement::Key("x") are the /// StackElements compositing the stack that represents foo.bar[3].x #[derive(PartialEq, Clone, Show)] pub enum StackElement<'l> { @@ -2505,12 +2506,12 @@ mod tests { use super::ParserError::*; use super::DecoderError::*; use super::JsonEvent::*; - use super::StackElement::*; use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, StackElement, Stack, Decoder}; - use std::{i64, u64, f32, f64}; + use std::{i64, u64, f32, f64, io}; use std::collections::BTreeMap; use std::num::Float; + use std::ops::Index; use std::string; #[derive(RustcDecodable, Eq, PartialEq, Show)] @@ -3487,9 +3488,12 @@ mod tests { (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]), (ArrayEnd, vec![StackElement::Key("array")]), (ArrayStart, vec![StackElement::Key("idents")]), - (NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]), - (BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]), - (BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]), + (NullValue, vec![StackElement::Key("idents"), + StackElement::Index(0)]), + (BooleanValue(true), vec![StackElement::Key("idents"), + StackElement::Index(1)]), + (BooleanValue(false), vec![StackElement::Key("idents"), + StackElement::Index(2)]), (ArrayEnd, vec![StackElement::Key("idents")]), (ObjectEnd, vec![]), ] @@ -3567,13 +3571,24 @@ mod tests { (ObjectStart, vec![]), (F64Value(1.0), vec![StackElement::Key("a")]), (ArrayStart, vec![StackElement::Key("b")]), - (BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]), - (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), StackElement::Index(1)]), - (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]), - (ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]), - (NullValue, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c"), StackElement::Key("d")]), - (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]), - (ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2)]), + (BooleanValue(true), vec![StackElement::Key("b"), + StackElement::Index(0)]), + (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), + StackElement::Index(1)]), + (ObjectStart, vec![StackElement::Key("b"), + StackElement::Index(2)]), + (ObjectStart, vec![StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c")]), + (NullValue, vec![StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c"), + StackElement::Key("d")]), + (ObjectEnd, vec![StackElement::Key("b"), + StackElement::Index(2), + StackElement::Key("c")]), + (ObjectEnd, vec![StackElement::Key("b"), + StackElement::Index(2)]), (ArrayEnd, vec![StackElement::Key("b")]), (ObjectEnd, vec![]), ] @@ -3716,13 +3731,19 @@ mod tests { stack.push_key("bar".to_string()); assert!(stack.len() == 3); - assert!(stack.is_equal_to(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")])); + assert!(stack.is_equal_to(&[StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar")])); assert!(stack.starts_with(&[StackElement::Index(1)])); assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")])); - assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")])); + assert!(stack.starts_with(&[StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar")])); assert!(stack.ends_with(&[StackElement::Key("bar")])); assert!(stack.ends_with(&[StackElement::Key("foo"), StackElement::Key("bar")])); - assert!(stack.ends_with(&[StackElement::Index(1), StackElement::Key("foo"), StackElement::Key("bar")])); + assert!(stack.ends_with(&[StackElement::Index(1), + StackElement::Key("foo"), + StackElement::Key("bar")])); assert!(!stack.last_is_index()); assert!(stack.get(0) == StackElement::Index(1)); assert!(stack.get(1) == StackElement::Key("foo")); diff --git a/src/libserialize/json_stage0.rs b/src/libserialize/json_stage0.rs index a157d917274..1c2855f6745 100644 --- a/src/libserialize/json_stage0.rs +++ b/src/libserialize/json_stage0.rs @@ -211,6 +211,7 @@ use std::string; use std::ops; use unicode::str as unicode_str; use unicode::str::Utf16Item; +use std::ops::Index as IndexOp; use Encodable; @@ -386,7 +387,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { }; if start < i { - try!(wr.write_str(v[start..i])); + try!(wr.write_str(v.index(&(start..i)))); } try!(wr.write_str(escaped)); @@ -395,7 +396,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { } if start != v.len() { - try!(wr.write_str(v[start..])); + try!(wr.write_str(v.index(&(start..)))); } wr.write_str("\"") @@ -404,7 +405,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result { fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result { let mut buf = [0; 4]; let n = v.encode_utf8(&mut buf).unwrap(); - let buf = unsafe { str::from_utf8_unchecked(buf[0..n]) }; + let buf = unsafe { str::from_utf8_unchecked(buf.index(&(0..n))) }; escape_str(writer, buf) } @@ -417,7 +418,7 @@ fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result { } if n > 0 { - wr.write_str(BUF[..n]) + wr.write_str(BUF.index(&(..n))) } else { Ok(()) } @@ -624,7 +625,7 @@ impl<'a> ::Encoder for Encoder<'a> { let mut check_encoder = Encoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let out = str::from_utf8(buf[]).unwrap(); + let out = str::from_utf8(buf.index(&FullRange)).unwrap(); let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); @@ -893,7 +894,7 @@ impl<'a> ::Encoder for PrettyEncoder<'a> { let mut check_encoder = PrettyEncoder::new(&mut buf); try!(f(transmute(&mut check_encoder))); } - let out = str::from_utf8(buf[]).unwrap(); + let out = str::from_utf8(buf.index(&FullRange)).unwrap(); let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"'; if needs_wrapping { try!(write!(self.writer, "\"")); } try!(f(self)); @@ -1026,7 +1027,7 @@ impl Json { /// Returns None otherwise. pub fn as_string<'a>(&'a self) -> Option<&'a str> { match *self { - Json::String(ref s) => Some(s[]), + Json::String(ref s) => Some(s.index(&FullRange)), _ => None } } @@ -1220,7 +1221,8 @@ impl Stack { InternalIndex(i) => Index(i), InternalKey(start, size) => { Key(str::from_utf8( - self.str_buffer[start as uint .. start as uint + size as uint]).unwrap()) + self.str_buffer.index( + &((start as uint) .. (start as uint + size as uint)))).unwrap()) } } } @@ -1262,7 +1264,7 @@ impl Stack { Some(&InternalIndex(i)) => Some(Index(i)), Some(&InternalKey(start, size)) => { Some(Key(str::from_utf8( - self.str_buffer[start as uint .. (start+size) as uint] + self.str_buffer.index(&(start as uint) .. ((start+size) as uint)) ).unwrap())) } } @@ -2139,7 +2141,7 @@ impl ::Decoder for Decoder { return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) } }; - let idx = match names.iter().position(|n| *n == name[]) { + let idx = match names.iter().position(|n| *n == name.index(&FullRange)) { Some(idx) => idx, None => return Err(UnknownVariantError(name)) }; @@ -3352,7 +3354,7 @@ mod tests { hm.insert(1, true); let mut mem_buf = Vec::new(); write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(mem_buf[]).unwrap(); + let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap(); match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {}", json_str), _ => {} // it parsed and we are good to go @@ -3368,7 +3370,7 @@ mod tests { hm.insert(1, true); let mut mem_buf = Vec::new(); write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); - let json_str = from_utf8(mem_buf[]).unwrap(); + let json_str = from_utf8(&mem_buf.index(&FullRange)).unwrap(); match from_str(json_str) { Err(_) => panic!("Unable to parse json_str: {}", json_str), _ => {} // it parsed and we are good to go @@ -3408,7 +3410,7 @@ mod tests { write!(&mut writer, "{}", super::as_pretty_json(&json).indent(i)).unwrap(); - let printed = from_utf8(writer[]).unwrap(); + let printed = from_utf8(&writer.index(&FullRange)).unwrap(); // Check for indents at each line let lines: Vec<&str> = printed.lines().collect(); diff --git a/src/libserialize/serialize_stage0.rs b/src/libserialize/serialize_stage0.rs index fd37bb63230..87ff5922c1a 100644 --- a/src/libserialize/serialize_stage0.rs +++ b/src/libserialize/serialize_stage0.rs @@ -14,6 +14,7 @@ Core encoding and decoding interfaces. */ +use std::ops::FullRange; use std::path; use std::rc::Rc; use std::cell::{Cell, RefCell}; @@ -308,7 +309,7 @@ impl> Encodable for str { impl> Encodable for String { fn encode(&self, s: &mut S) -> Result<(), E> { - s.emit_str(self[]) + s.emit_str(self.index(&FullRange)) } } diff --git a/src/libstd/io/buffered.rs b/src/libstd/io/buffered.rs index 11d48dff32a..c54a5ffa665 100644 --- a/src/libstd/io/buffered.rs +++ b/src/libstd/io/buffered.rs @@ -472,41 +472,37 @@ mod test { writer.write(&[0, 1]).unwrap(); let b: &[_] = &[]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[2]).unwrap(); let b: &[_] = &[0, 1]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[3]).unwrap(); - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let a: &[_] = &[0, 1, 2, 3]; - assert_eq!(a, writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[4]).unwrap(); writer.write(&[5]).unwrap(); - assert_eq!(a, writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[6]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5]; - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[7, 8]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5, 6]; - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.write(&[9, 10, 11]).unwrap(); let a: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); writer.flush().unwrap(); - assert_eq!(a, - writer.get_ref()[]); + assert_eq!(a, &writer.get_ref()[]); } #[test] @@ -514,7 +510,7 @@ mod test { let mut w = BufferedWriter::with_capacity(3, Vec::new()); w.write(&[0, 1]).unwrap(); let a: &[_] = &[]; - assert_eq!(a, w.get_ref()[]); + assert_eq!(a, &w.get_ref()[]); let w = w.into_inner(); let a: &[_] = &[0, 1]; assert_eq!(a, w.index(&FullRange)); @@ -559,21 +555,21 @@ mod test { let mut writer = LineBufferedWriter::new(Vec::new()); writer.write(&[0]).unwrap(); let b: &[_] = &[]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[1]).unwrap(); - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let b: &[_] = &[0, 1]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[0, b'\n', 1, b'\n', 2]).unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n']; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.flush().unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2]; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); writer.write(&[3, b'\n']).unwrap(); let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n']; - assert_eq!(writer.get_ref()[], b); + assert_eq!(&writer.get_ref()[], b); } #[test] diff --git a/src/libstd/io/mem.rs b/src/libstd/io/mem.rs index 2c2824cbb3b..9e6af86925b 100644 --- a/src/libstd/io/mem.rs +++ b/src/libstd/io/mem.rs @@ -13,7 +13,7 @@ //! Readers and Writers for in-memory buffers use cmp::min; -use prelude::Index; +use prelude::v1::Index; use option::Option::None; use result::Result::{Err, Ok}; use io; @@ -391,9 +391,9 @@ impl<'a> Buffer for BufReader<'a> { #[cfg(test)] mod test { extern crate "test" as test_crate; - use prelude::v1::*; - - use io::{SeekSet, SeekCur, SeekEnd}; + use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek}; + use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt}; + use prelude::v1::{IteratorExt, Index}; use io; use iter::repeat; use self::test_crate::Bencher; diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index ea232ad0c3f..5f77ab38d74 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -752,12 +752,12 @@ impl Drop for Process { #[cfg(test)] mod tests { - use prelude::v1::*; - + use io::{Truncate, Write, TimedOut, timer, process, FileNotFound}; + use prelude::v1::{Ok, Err, range, drop, Some, None, Vec}; + use prelude::v1::{Path, String, Reader, Writer, Clone}; + use prelude::v1::{SliceExt, Str, StrExt, AsSlice, ToString, GenericPath}; use io::fs::PathExtensions; - use io::process; use io::timer::*; - use io::{Truncate, Write, TimedOut, timer, FileNotFound}; use rt::running_on_valgrind; use str; use super::{CreatePipe}; diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 021aae5a601..87188c0d4a2 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -68,7 +68,7 @@ use fmt; use iter::IteratorExt; use option::Option; use option::Option::{None, Some}; -use prelude::{FullRange, Index}; +use prelude::v1::{FullRange, Index}; use str; use str::StrExt; use string::{String, CowString}; diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index d469bb4d767..97545bc2022 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -24,7 +24,7 @@ use iter::{AdditiveIterator, Extend}; use iter::{Iterator, IteratorExt, Map, repeat}; use mem; use option::Option::{self, Some, None}; -use prelude::{FullRange, Index}; +use prelude::v1::{FullRange, Index}; use slice::{SliceExt, SliceConcatExt}; use str::{SplitTerminator, FromStr, StrExt}; use string::{String, ToString}; @@ -337,8 +337,12 @@ impl GenericPath for Path { Some(match self.sepidx_or_prefix_len() { None if ".." == self.repr => self.repr.index(&FullRange), None => ".", - Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => self.repr.index(&FullRange), - Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => self.repr.index(&FullRange), + Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => { + self.repr.index(&FullRange) + } + Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => { + self.repr.index(&FullRange) + } Some((0,idxa,_)) => self.repr.index(&(0..idxa)), Some((idxb,idxa,_)) => { match self.prefix { diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs index 9e9a483e1a5..d0dcf77002f 100644 --- a/src/libstd/prelude/v1.rs +++ b/src/libstd/prelude/v1.rs @@ -14,7 +14,8 @@ // Reexported core operators #[stable] #[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Sync}; -#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce}; +#[stable] #[doc(no_inline)] pub use ops::{Drop, Fn, FnMut, FnOnce, FullRange}; +#[unstable] #[doc(no_inline)] pub use ops::{Index, IndexMut}; // Reexported functions #[stable] #[doc(no_inline)] pub use mem::drop; diff --git a/src/libstd/sys/windows/backtrace.rs b/src/libstd/sys/windows/backtrace.rs index 4ccecfd1f5f..eb76f13afe7 100644 --- a/src/libstd/sys/windows/backtrace.rs +++ b/src/libstd/sys/windows/backtrace.rs @@ -23,6 +23,7 @@ use dynamic_lib::DynamicLibrary; use ffi; +use core::ops::Index; use intrinsics; use io::{IoResult, Writer}; use libc; @@ -361,7 +362,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> { let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; match str::from_utf8(bytes) { Ok(s) => try!(demangle(w, s)), - Err(..) => try!(w.write(bytes[..bytes.len()-1])), + Err(..) => try!(w.write(bytes.index(&(..(bytes.len()-1))))), } } try!(w.write(&['\n' as u8])); diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 54e6a338178..da3744d83f5 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -206,7 +206,7 @@ impl, E> Decodable for Ident { #[cfg(not(stage0))] impl Decodable for Ident { fn decode(d: &mut D) -> Result { - Ok(str_to_ident(try!(d.read_str())[])) + Ok(str_to_ident(try!(d.read_str()).index(&FullRange))) } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 97f70d416db..68bbde35ae6 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -332,7 +332,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P], cfg: &ast::Me !cfg_matches(diagnostic, cfgs, &*mis[0]) } ast::MetaList(ref pred, _) => { - diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).index(&FullRange)); + diagnostic.span_err(cfg.span, format!("invalid predicate `{}`", pred).as_slice()); false }, ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg), diff --git a/src/libsyntax/ext/deriving/bounds.rs b/src/libsyntax/ext/deriving/bounds.rs index 2189f7d83d8..440bdff1471 100644 --- a/src/libsyntax/ext/deriving/bounds.rs +++ b/src/libsyntax/ext/deriving/bounds.rs @@ -29,12 +29,13 @@ pub fn expand_deriving_bound(cx: &mut ExtCtxt, "Send" | "Sync" => { return cx.span_err(span, format!("{} is an unsafe trait and it \ - should be implemented explicitly", *tname).index(&FullRange)) + should be implemented explicitly", + *tname).as_slice()) } ref tname => { cx.span_bug(span, format!("expected built-in trait name but \ - found {}", *tname).index(&FullRange)) + found {}", *tname).as_slice()) } } }, diff --git a/src/libsyntax/ext/tt/macro_parser.rs b/src/libsyntax/ext/tt/macro_parser.rs index 328e302bef3..581c60bdeb9 100644 --- a/src/libsyntax/ext/tt/macro_parser.rs +++ b/src/libsyntax/ext/tt/macro_parser.rs @@ -386,7 +386,7 @@ pub fn parse(sess: &ParseSess, new_ei.idx += 1u; //we specifically matched zero repeats. for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { - (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(Vec::new(), sp))); + (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); } cur_eis.push(new_ei); diff --git a/src/libsyntax/feature_gate.rs b/src/libsyntax/feature_gate.rs index afe149e9d69..2c36a02d44f 100644 --- a/src/libsyntax/feature_gate.rs +++ b/src/libsyntax/feature_gate.rs @@ -278,7 +278,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { _ => {} } - if attr::contains_name(i.attrs[], + if attr::contains_name(i.attrs.as_slice(), "unsafe_destructor") { self.gate_feature("unsafe_destructor", i.span, @@ -287,7 +287,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { removed in the future"); } - if attr::contains_name(i.attrs[], + if attr::contains_name(i.attrs.index(&FullRange), "old_orphan_check") { self.gate_feature( "old_orphan_check", @@ -309,7 +309,8 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> { and not portable across platforms") } - let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs[], "link_name") { + let links_to_llvm = match attr::first_attr_value_str_by_name(i.attrs.as_slice(), + "link_name") { Some(val) => val.get().starts_with("llvm."), _ => false }; diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index 24a909cc5fb..d4650a4bb03 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -1167,10 +1167,10 @@ mod test { for &src in srcs.iter() { let spans = get_spans_of_pat_idents(src); - let Span{lo:lo,hi:hi,..} = spans[0]; - assert!("self" == src[lo.to_uint()..hi.to_uint()], + let Span{ lo, hi, .. } = spans[0]; + assert!("self" == &src[lo.to_uint()..hi.to_uint()], "\"{}\" != \"self\". src=\"{}\"", - src[lo.to_uint()..hi.to_uint()], src) + &src[lo.to_uint()..hi.to_uint()], src) } } diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 7824dacd3a1..0ecd098951f 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1726,7 +1726,7 @@ impl<'a> Parser<'a> { token::Str_(s) => { (true, - LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).index(&FullRange)), + LitStr(token::intern_and_get_ident(parse::str_lit(s.as_str()).as_slice()), ast::CookedStr)) } token::StrRaw(s, n) => { @@ -2538,16 +2538,26 @@ impl<'a> Parser<'a> { token::OpenDelim(token::Bracket) => { let bracket_pos = self.span.lo; self.bump(); - if self.eat(&token::CloseDelim(token::Bracket)) { + + let mut found_dotdot = false; + if self.token == token::DotDot && + self.look_ahead(1, |t| t == &token::CloseDelim(token::Bracket)) { + // Using expr[..], which is a mistake, should be expr[] + self.bump(); + self.bump(); + found_dotdot = true; + } + + if found_dotdot || self.eat(&token::CloseDelim(token::Bracket)) { // No expression, expand to a FullRange - let ix = { - hi = self.last_span.hi; - let range = ExprStruct(ident_to_path(mk_sp(lo, hi), - token::special_idents::FullRange), - vec![], - None); - self.mk_expr(bracket_pos, hi, range) - }; + // FIXME(#20516) It would be better to use a lang item or + // something for FullRange. + hi = self.last_span.hi; + let range = ExprStruct(ident_to_path(mk_sp(lo, hi), + token::special_idents::FullRange), + vec![], + None); + let ix = self.mk_expr(bracket_pos, hi, range); let index = self.mk_index(e, ix); e = self.mk_expr(lo, hi, index) } else { @@ -2557,6 +2567,12 @@ impl<'a> Parser<'a> { let index = self.mk_index(e, ix); e = self.mk_expr(lo, hi, index) } + + if found_dotdot { + self.span_err(e.span, "incorrect slicing expression: `[..]`"); + self.span_note(e.span, + "use `&expr[]` to construct a slice of the whole of expr"); + } } // A range expression, either `expr..expr` or `expr..`. @@ -4881,7 +4897,7 @@ impl<'a> Parser<'a> { let token_str = self.this_token_to_string(); self.fatal(format!("expected `where`, or `{}` after struct \ name, found `{}`", "{", - token_str)[]); + token_str).index(&FullRange)); } fields diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index ada463a40cb..f70ce54bb1c 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -689,8 +689,7 @@ impl, E> Decodable for InternedString { #[cfg(not(stage0))] impl Decodable for InternedString { fn decode(d: &mut D) -> Result { - Ok(get_name(get_ident_interner().intern( - try!(d.read_str())[]))) + Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange)))) } } @@ -704,7 +703,7 @@ impl, E> Encodable for InternedString { #[cfg(not(stage0))] impl Encodable for InternedString { fn encode(&self, s: &mut S) -> Result<(), S::Error> { - s.emit_str(self.string[]) + s.emit_str(self.string.index(&FullRange)) } } diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 721769be7a4..87dcc9e70f4 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1537,35 +1537,34 @@ impl<'a> State<'a> { ast::ExprStruct(ref path, ref fields, ref wth) => { try!(self.print_path(path, true)); - if fields.is_empty() && wth.is_none() { - return; - } - try!(word(&mut self.s, "{")); - try!(self.commasep_cmnt( - Consistent, - fields.index(&FullRange), - |s, field| { - try!(s.ibox(indent_unit)); - try!(s.print_ident(field.ident.node)); - try!(s.word_space(":")); - try!(s.print_expr(&*field.expr)); - s.end() - }, - |f| f.span)); - match *wth { - Some(ref expr) => { - try!(self.ibox(indent_unit)); - if !fields.is_empty() { - try!(word(&mut self.s, ",")); - try!(space(&mut self.s)); + if !(fields.is_empty() && wth.is_none()) { + try!(word(&mut self.s, "{")); + try!(self.commasep_cmnt( + Consistent, + fields.index(&FullRange), + |s, field| { + try!(s.ibox(indent_unit)); + try!(s.print_ident(field.ident.node)); + try!(s.word_space(":")); + try!(s.print_expr(&*field.expr)); + s.end() + }, + |f| f.span)); + match *wth { + Some(ref expr) => { + try!(self.ibox(indent_unit)); + if !fields.is_empty() { + try!(word(&mut self.s, ",")); + try!(space(&mut self.s)); + } + try!(word(&mut self.s, "..")); + try!(self.print_expr(&**expr)); + try!(self.end()); } - try!(word(&mut self.s, "..")); - try!(self.print_expr(&**expr)); - try!(self.end()); + _ => try!(word(&mut self.s, ",")), } - _ => try!(word(&mut self.s, ",")), + try!(word(&mut self.s, "}")); } - try!(word(&mut self.s, "}")); } ast::ExprTup(ref exprs) => { try!(self.popen()); @@ -2781,7 +2780,7 @@ impl<'a> State<'a> { format!("-{}", istr).index(&FullRange)) } ast::UnsignedIntLit(ut) => { - word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).index(&FullRange)) + word(&mut self.s, ast_util::uint_ty_to_string(ut, Some(i)).as_slice()) } ast::UnsuffixedIntLit(ast::Plus) => { word(&mut self.s, format!("{}", i).index(&FullRange)) diff --git a/src/test/bench/shootout-fannkuch-redux.rs b/src/test/bench/shootout-fannkuch-redux.rs index 7dca2b24fc1..8ce365f765d 100644 --- a/src/test/bench/shootout-fannkuch-redux.rs +++ b/src/test/bench/shootout-fannkuch-redux.rs @@ -105,7 +105,7 @@ impl Perm { let d = idx / self.fact[i] as i32; self.cnt[i] = d; idx %= self.fact[i] as i32; - for (place, val) in pp.iter_mut().zip(self.perm.p[..i+1].iter()) { + for (place, val) in pp.iter_mut().zip(self.perm.p[..(i+1)].iter()) { *place = (*val) as u8 } diff --git a/src/test/bench/shootout-fasta.rs b/src/test/bench/shootout-fasta.rs index 9128930651f..29994f45d3a 100644 --- a/src/test/bench/shootout-fasta.rs +++ b/src/test/bench/shootout-fasta.rs @@ -99,7 +99,7 @@ fn make_fasta>( } n -= nb; line[nb] = '\n' as u8; - try!(wr.write(line[..nb+1])); + try!(wr.write(&line[..(nb+1)])); } Ok(()) } diff --git a/src/test/bench/shootout-k-nucleotide-pipes.rs b/src/test/bench/shootout-k-nucleotide-pipes.rs index e6ef6a8c8c9..39c839ba114 100644 --- a/src/test/bench/shootout-k-nucleotide-pipes.rs +++ b/src/test/bench/shootout-k-nucleotide-pipes.rs @@ -101,11 +101,11 @@ fn windows_with_carry(bb: &[u8], nn: uint, mut it: F) -> Vec where let len = bb.len(); while ii < len - (nn - 1u) { - it(bb[ii..ii+nn]); + it(&bb[ii..(ii+nn)]); ii += 1u; } - return bb[len - (nn - 1u)..len].to_vec(); + return bb[(len - (nn - 1u))..len].to_vec(); } fn make_sequence_processor(sz: uint, diff --git a/src/test/compile-fail/borrowck-loan-vec-content.rs b/src/test/compile-fail/borrowck-loan-vec-content.rs index 7849475ec67..efb7a5253ed 100644 --- a/src/test/compile-fail/borrowck-loan-vec-content.rs +++ b/src/test/compile-fail/borrowck-loan-vec-content.rs @@ -17,12 +17,12 @@ fn takes_imm_elt(_v: &int, f: F) where F: FnOnce() { } fn has_mut_vec_and_does_not_try_to_change_it() { - let mut v = vec!(1, 2, 3); + let mut v: Vec = vec!(1, 2, 3); takes_imm_elt(&v[0], || {}) } fn has_mut_vec_but_tries_to_change_it() { - let mut v = vec!(1, 2, 3); + let mut v: Vec = vec!(1, 2, 3); takes_imm_elt( &v[0], || { //~ ERROR cannot borrow `v` as mutable diff --git a/src/test/compile-fail/indexing-requires-a-uint.rs b/src/test/compile-fail/indexing-requires-a-uint.rs index 9ac4bd2566e..e5edb2358f8 100644 --- a/src/test/compile-fail/indexing-requires-a-uint.rs +++ b/src/test/compile-fail/indexing-requires-a-uint.rs @@ -13,7 +13,8 @@ fn main() { fn bar(_: T) {} - [0][0u8]; //~ ERROR: mismatched types + [0][0u8]; //~ ERROR: the trait `core::ops::Index` is not implemented + //~^ ERROR: the trait `core::ops::Index` is not implemented [0][0]; // should infer to be a uint diff --git a/src/test/compile-fail/integral-indexing.rs b/src/test/compile-fail/integral-indexing.rs index 8b1f9eb1986..bbceb00abd3 100644 --- a/src/test/compile-fail/integral-indexing.rs +++ b/src/test/compile-fail/integral-indexing.rs @@ -11,16 +11,24 @@ pub fn main() { let v: Vec = vec!(0, 1, 2, 3, 4, 5); let s: String = "abcdef".to_string(); - assert_eq!(v.as_slice()[3u], 3); - assert_eq!(v.as_slice()[3u8], 3); //~ ERROR: mismatched types - assert_eq!(v.as_slice()[3i8], 3); //~ ERROR: mismatched types - assert_eq!(v.as_slice()[3u32], 3); //~ ERROR: mismatched types - assert_eq!(v.as_slice()[3i32], 3); //~ ERROR: mismatched types - println!("{}", v.as_slice()[3u8]); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3u], 'd' as u8); - assert_eq!(s.as_bytes()[3u8], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3i8], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3u32], 'd' as u8); //~ ERROR: mismatched types - assert_eq!(s.as_bytes()[3i32], 'd' as u8); //~ ERROR: mismatched types - println!("{}", s.as_bytes()[3u8]); //~ ERROR: mismatched types + v.as_slice()[3u]; + v.as_slice()[3]; + v.as_slice()[3u8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + v.as_slice()[3i8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + v.as_slice()[3u32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3u]; + s.as_bytes()[3]; + s.as_bytes()[3u8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3i8]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3u32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented + s.as_bytes()[3i32]; //~ERROR the trait `core::ops::Index` is not implemented + //~^ERROR the trait `core::ops::Index` is not implemented } diff --git a/src/test/compile-fail/issue-16709.rs b/src/test/compile-fail/issue-16709.rs deleted file mode 100644 index 327f50ee059..00000000000 --- a/src/test/compile-fail/issue-16709.rs +++ /dev/null @@ -1,25 +0,0 @@ -// 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::ptr; -use std::raw; - -trait Slice {} - -fn main() { - unsafe { - let nil: *const u8 = ptr::null(); - let slice: raw::Slice = - Slice { //~ ERROR use of trait `Slice` as a struct constructor [E0159] - data: nil, - len: 0, - }; - } -} diff --git a/src/test/compile-fail/slice-2.rs b/src/test/compile-fail/slice-2.rs index 9ee70022545..a03693b5fad 100644 --- a/src/test/compile-fail/slice-2.rs +++ b/src/test/compile-fail/slice-2.rs @@ -16,8 +16,8 @@ struct Foo; fn main() { let x = Foo; - &x[]; //~ ERROR cannot take a slice of a value with type `Foo` - &x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo` - &x[0..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` - &x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` + &x[]; //~ ERROR cannot index a value of type `Foo` + &x[Foo..]; //~ ERROR cannot index a value of type `Foo` + &x[..Foo]; //~ ERROR cannot index a value of type `Foo` + &x[Foo..Foo]; //~ ERROR cannot index a value of type `Foo` } diff --git a/src/test/compile-fail/slice-mut-2.rs b/src/test/compile-fail/slice-mut-2.rs index b34c9a49268..1dedb0cf888 100644 --- a/src/test/compile-fail/slice-mut-2.rs +++ b/src/test/compile-fail/slice-mut-2.rs @@ -16,5 +16,5 @@ fn main() { let x: &[int] = &[1, 2, 3, 4, 5]; // Can't mutably slice an immutable slice let slice: &mut [int] = &mut [0, 1]; - &mut x[2..4] = slice; //~ ERROR cannot borrow + let _ = &mut x[2..4]; //~ERROR cannot borrow immutable dereference of `&`-pointer `*x` as mutabl } diff --git a/src/test/compile-fail/slice-mut.rs b/src/test/compile-fail/slice-mut.rs index e7353dfbcd0..f0f525a5535 100644 --- a/src/test/compile-fail/slice-mut.rs +++ b/src/test/compile-fail/slice-mut.rs @@ -15,5 +15,5 @@ fn main() { let x: &[int] = &[1, 2, 3, 4, 5]; // Immutable slices are not mutable. - let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutabl + let y: &mut[_] = &x[2..4]; //~ ERROR cannot borrow immutable dereference of `&`-pointer as mutab } diff --git a/src/test/compile-fail/str-idx.rs b/src/test/compile-fail/str-idx.rs index 424ffed989b..ddd2a4eeedf 100644 --- a/src/test/compile-fail/str-idx.rs +++ b/src/test/compile-fail/str-idx.rs @@ -10,5 +10,6 @@ pub fn main() { let s: &str = "hello"; - let c: u8 = s[4]; //~ ERROR cannot index a value of type `&str` + let c: u8 = s[4]; //~ ERROR the trait `core::ops::Index<_>` is not implemented + //~^ ERROR the trait `core::ops::Index<_>` is not implemented } diff --git a/src/test/run-pass/issue-17503.rs b/src/test/run-pass/issue-17503.rs index 9d1a51ad79c..8acda175006 100644 --- a/src/test/run-pass/issue-17503.rs +++ b/src/test/run-pass/issue-17503.rs @@ -15,7 +15,7 @@ fn main() { let ss: &&[int] = &s; let sss: &&&[int] = &ss; - println!("{}", s.index(&(0..3))); - println!("{}", ss.index(&(3..))); - println!("{}", sss.index(&(2..4))); + println!("{}", &s[0..3]); + println!("{}", &ss[3..]); + println!("{}", &sss[2..4]); } diff --git a/src/test/run-pass/issue-3888-2.rs b/src/test/run-pass/issue-3888-2.rs index 115a96d5289..5ed9729c142 100644 --- a/src/test/run-pass/issue-3888-2.rs +++ b/src/test/run-pass/issue-3888-2.rs @@ -11,7 +11,7 @@ #![feature(slicing_syntax)] fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] { - v.index(&(1..5)) + &v[1..5] } pub fn main() {} diff --git a/src/test/run-pass/issue-4464.rs b/src/test/run-pass/issue-4464.rs index fa75b5d2583..2581069d29b 100644 --- a/src/test/run-pass/issue-4464.rs +++ b/src/test/run-pass/issue-4464.rs @@ -10,6 +10,6 @@ #![feature(slicing_syntax)] -fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { v.index(&(i..j)) } +fn broken(v: &[u8], i: uint, j: uint) -> &[u8] { &v[i..j] } pub fn main() {} diff --git a/src/test/run-pass/issue-8898.rs b/src/test/run-pass/issue-8898.rs index 5b90878aa28..0c19286921a 100644 --- a/src/test/run-pass/issue-8898.rs +++ b/src/test/run-pass/issue-8898.rs @@ -18,7 +18,7 @@ pub fn main() { let abc = [1i, 2, 3]; let tf = [true, false]; let x = [(), ()]; - let slice = x.index(&(0..1)); + let slice = &x[0..1]; assert_repr_eq(&abc[], "[1, 2, 3]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); diff --git a/src/test/run-pass/slice-panic-1.rs b/src/test/run-pass/slice-panic-1.rs index 87de4246f3e..ebe6e974c26 100644 --- a/src/test/run-pass/slice-panic-1.rs +++ b/src/test/run-pass/slice-panic-1.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Test that is a slicing expr.index(&(..)) fails, the correct cleanups happen. +// Test that if a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] @@ -24,7 +24,7 @@ impl Drop for Foo { fn foo() { let x: &[_] = &[Foo, Foo]; - x.index(&(3..4)); + &x[3..4]; } fn main() { diff --git a/src/test/run-pass/slice-panic-2.rs b/src/test/run-pass/slice-panic-2.rs index afffaba64de..6bbd1ac7b2d 100644 --- a/src/test/run-pass/slice-panic-2.rs +++ b/src/test/run-pass/slice-panic-2.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// Test that is a slicing expr.index(&(..)) fails, the correct cleanups happen. +// Test that if a slicing expr[..] fails, the correct cleanups happen. #![feature(slicing_syntax)] @@ -28,7 +28,7 @@ fn bar() -> uint { fn foo() { let x: &[_] = &[Foo, Foo]; - x[3..bar()]; + &x[3..bar()]; } fn main() { diff --git a/src/test/run-pass/slice.rs b/src/test/run-pass/slice.rs index e039886022c..fca7daeb07d 100644 --- a/src/test/run-pass/slice.rs +++ b/src/test/run-pass/slice.rs @@ -11,6 +11,7 @@ // Test slicing sugar. #![feature(slicing_syntax)] +#![feature(associated_types)] extern crate core; use core::ops::{Index, Range, RangeTo, RangeFrom, FullRange}; @@ -19,49 +20,70 @@ static mut COUNT: uint = 0; struct Foo; -impl Slice for Foo { - fn as_slice_<'a>(&'a self) -> &'a Foo { +impl Index> for Foo { + type Output = Foo; + fn index(&self, index: &Range) -> &Foo { unsafe { COUNT += 1; } self } - fn slice_from_or_fail<'a>(&'a self, _from: &Foo) -> &'a Foo { +} +impl Index> for Foo { + type Output = Foo; + fn index(&self, index: &RangeTo) -> &Foo { unsafe { COUNT += 1; } self } - fn slice_to_or_fail<'a>(&'a self, _to: &Foo) -> &'a Foo { +} +impl Index> for Foo { + type Output = Foo; + fn index(&self, index: &RangeFrom) -> &Foo { unsafe { COUNT += 1; } self } - fn slice_or_fail<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo { +} +impl Index for Foo { + type Output = Foo; + fn index(&self, _index: &FullRange) -> &Foo { unsafe { COUNT += 1; } self } } -impl SliceMut for Foo { - fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo { - unsafe { COUNT += 1; } - self - } - fn slice_from_or_fail_mut<'a>(&'a mut self, _from: &Foo) -> &'a mut Foo { - unsafe { COUNT += 1; } - self - } - fn slice_to_or_fail_mut<'a>(&'a mut self, _to: &Foo) -> &'a mut Foo { - unsafe { COUNT += 1; } - self - } - fn slice_or_fail_mut<'a>(&'a mut self, _from: &Foo, _to: &Foo) -> &'a mut Foo { +impl IndexMut> for Foo { + type Output = Foo; + fn index_mut(&mut self, index: &Range) -> &mut Foo { unsafe { COUNT += 1; } self } } +impl IndexMut> for Foo { + type Output = Foo; + fn index_mut(&mut self, index: &RangeTo) -> &mut Foo { + unsafe { COUNT += 1; } + self + } +} +impl IndexMut> for Foo { + type Output = Foo; + fn index_mut(&mut self, index: &RangeFrom) -> &mut Foo { + unsafe { COUNT += 1; } + self + } +} +impl IndexMut for Foo { + type Output = Foo; + fn index_mut(&mut self, _index: &FullRange) -> &mut Foo { + unsafe { COUNT += 1; } + self + } +} + fn main() { let mut x = Foo; &x[]; &x[Foo..]; - &x[0..Foo]; + &x[..Foo]; &x[Foo..Foo]; &mut x[]; &mut x[Foo..];