1
Fork 0
This commit is contained in:
Nick Cameron 2015-01-04 17:43:24 +13:00
parent 791f545685
commit 0c7f7a5fb8
89 changed files with 543 additions and 468 deletions

View file

@ -539,18 +539,17 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
script_str.push_str("set print pretty off\n"); script_str.push_str("set print pretty off\n");
// Add the pretty printer directory to GDB's source-file search path // 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 // Load the target executable
script_str.push_str(format!("file {}\n", script_str.push_str(&format!("file {}\n",
exe_file.as_str().unwrap().replace("\\", "\\\\")) exe_file.as_str().unwrap().replace("\\", "\\\\"))[]);
.as_slice());
// Add line breakpoints // Add line breakpoints
for line in breakpoint_lines.iter() { for line in breakpoint_lines.iter() {
script_str.push_str(format!("break '{}':{}\n", script_str.push_str(&format!("break '{}':{}\n",
testfile.filename_display(), testfile.filename_display(),
*line)[]); *line)[]);
} }
script_str.push_str(cmds.as_slice()); script_str.push_str(cmds.as_slice());
@ -676,7 +675,7 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
.unwrap() .unwrap()
.to_string(); .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("type summary add --no-value ");
script_str.push_str("--python-function lldb_rust_formatters.print_val "); script_str.push_str("--python-function lldb_rust_formatters.print_val ");
script_str.push_str("-x \".*\" --category Rust\n"); script_str.push_str("-x \".*\" --category Rust\n");

View file

@ -525,7 +525,7 @@ impl<T> RingBuf<T> {
/// *num = *num - 2; /// *num = *num - 2;
/// } /// }
/// let b: &[_] = &[&mut 3, &mut 1, &mut 2]; /// let b: &[_] = &[&mut 3, &mut 1, &mut 2];
/// assert_eq!(buf.iter_mut().collect::<Vec<&mut int>>()[], b); /// assert_eq!(&buf.iter_mut().collect::<Vec<&mut int>>()[], b);
/// ``` /// ```
#[stable] #[stable]
pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> { pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {

View file

@ -1393,15 +1393,20 @@ fn merge_sort<T, F>(v: &mut [T], mut compare: F) where F: FnMut(&T, &T) -> Order
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use prelude::{Some, None, range, Vec, ToString, Clone, Greater, Less, Equal}; use core::cmp::Ordering::{Greater, Less, Equal};
use prelude::{SliceExt, Iterator, IteratorExt}; use core::prelude::{Some, None, range, Clone};
use prelude::AsSlice; use core::prelude::{Iterator, IteratorExt};
use prelude::{RandomAccessIterator, Ord, SliceConcatExt}; use core::prelude::{AsSlice};
use core::prelude::{Ord, FullRange};
use core::default::Default; use core::default::Default;
use core::mem; use core::mem;
use core::ops::Index;
use std::iter::RandomAccessIterator;
use std::rand::{Rng, thread_rng}; use std::rand::{Rng, thread_rng};
use std::rc::Rc; 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 } fn square(n: uint) -> uint { n * n }

View file

@ -60,7 +60,7 @@ use core::char::CharExt;
use core::clone::Clone; use core::clone::Clone;
use core::iter::AdditiveIterator; use core::iter::AdditiveIterator;
use core::iter::{range, Iterator, IteratorExt}; 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::option::Option::{self, Some, None};
use core::slice::AsSlice; use core::slice::AsSlice;
use core::str as core_str; use core::str as core_str;
@ -408,7 +408,7 @@ Section: Trait implementations
/// Any string that can be represented as a slice. /// Any string that can be represented as a slice.
#[stable] #[stable]
pub trait StrExt: Index<FullRange, str> { pub trait StrExt: Index<FullRange, Output = str> {
/// Escapes each char in `s` with `char::escape_default`. /// Escapes each char in `s` with `char::escape_default`.
#[unstable = "return type may change to be an iterator"] #[unstable = "return type may change to be an iterator"]
fn escape_default(&self) -> String { fn escape_default(&self) -> String {
@ -1339,12 +1339,6 @@ pub trait StrExt: Index<FullRange, str> {
fn trim_left(&self) -> &str { fn trim_left(&self) -> &str {
UnicodeStr::trim_left(self.index(&FullRange)) 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] #[stable]
@ -2133,7 +2127,7 @@ mod tests {
let mut bytes = [0u8; 4]; let mut bytes = [0u8; 4];
for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { 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 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() { if Some(c) != s.chars().next() {
panic!("character {:x}={} does not decode correctly", c as u32, c); panic!("character {:x}={} does not decode correctly", c as u32, c);
} }
@ -2145,7 +2139,7 @@ mod tests {
let mut bytes = [0u8; 4]; let mut bytes = [0u8; 4];
for c in range(0u32, 0x110000).filter_map(|c| ::core::char::from_u32(c)) { 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 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() { if Some(c) != s.chars().rev().next() {
panic!("character {:x}={} does not decode correctly", c as u32, c); panic!("character {:x}={} does not decode correctly", c as u32, c);
} }

View file

@ -22,7 +22,7 @@ use core::fmt;
use core::hash; use core::hash;
use core::iter::FromIterator; use core::iter::FromIterator;
use core::mem; use core::mem;
use core::ops::{self, Deref, Add}; use core::ops::{self, Deref, Add, Index};
use core::ptr; use core::ptr;
use core::raw::Slice as RawSlice; use core::raw::Slice as RawSlice;
use unicode::str as unicode_str; use unicode::str as unicode_str;
@ -818,28 +818,29 @@ impl<'a> Add<&'a str> for String {
} }
} }
impl ops::Index<ops::Range<uint>, str> for String { impl ops::Index<ops::Range<uint>> for String {
type Output = str;
#[inline] #[inline]
fn index(&self, index: &ops::Range<uint>) -> &str { fn index(&self, index: &ops::Range<uint>) -> &str {
&self.index(&FullRange)[*index] &self.index(&FullRange)[*index]
} }
} }
impl ops::Index<ops::RangeTo<uint>> for String {
impl ops::Index<ops::RangeTo<uint>, str> for String { type Output = str;
#[inline] #[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &str { fn index(&self, index: &ops::RangeTo<uint>) -> &str {
&self.index(&FullRange)[*index] &self.index(&FullRange)[*index]
} }
} }
impl ops::Index<ops::RangeFrom<uint>> for String {
impl ops::Index<ops::RangeFrom<uint>, str> for String { type Output = str;
#[inline] #[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &str { fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
&self.index(&FullRange)[*index] &self.index(&FullRange)[*index]
} }
} }
impl ops::Index<ops::FullRange> for String {
impl ops::Index<ops::FullRange, str> for String { type Output = str;
#[inline] #[inline]
fn index(&self, _index: &ops::FullRange) -> &str { fn index(&self, _index: &ops::FullRange) -> &str {
unsafe { mem::transmute(self.vec.as_slice()) } unsafe { mem::transmute(self.vec.as_slice()) }
@ -949,6 +950,7 @@ mod tests {
use str::Utf8Error; use str::Utf8Error;
use core::iter::repeat; use core::iter::repeat;
use super::{as_string, CowString}; use super::{as_string, CowString};
use core::ops::FullRange;
#[test] #[test]
fn test_as_string() { fn test_as_string() {
@ -1230,10 +1232,10 @@ mod tests {
#[test] #[test]
fn test_slicing() { fn test_slicing() {
let s = "foobar".to_string(); let s = "foobar".to_string();
assert_eq!("foobar", s.index(&FullRange)); assert_eq!("foobar", &s[]);
assert_eq!("foo", s.index(&(0..3))); assert_eq!("foo", &s[..3]);
assert_eq!("bar", s.index(&(3..))); assert_eq!("bar", &s[3..]);
assert_eq!("oob", s.index(&(1..4))); assert_eq!("oob", &s[1..4]);
} }
#[test] #[test]

View file

@ -1209,62 +1209,66 @@ impl<T> IndexMut<uint> for Vec<T> {
} }
} }
impl<T> ops::Index<ops::Range<uint>, [T]> for Vec<T> {
impl<T> ops::Index<ops::Range<uint>> for Vec<T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] { fn index(&self, index: &ops::Range<uint>) -> &[T] {
self.as_slice().index(index) self.as_slice().index(index)
} }
} }
impl<T> ops::Index<ops::RangeTo<uint>> for Vec<T> {
impl<T> ops::Index<ops::RangeTo<uint>, [T]> for Vec<T> { type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] { fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.as_slice().index(index) self.as_slice().index(index)
} }
} }
impl<T> ops::Index<ops::RangeFrom<uint>> for Vec<T> {
impl<T> ops::Index<ops::RangeFrom<uint>, [T]> for Vec<T> { type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] { fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.as_slice().index(index) self.as_slice().index(index)
} }
} }
impl<T> ops::Index<ops::FullRange> for Vec<T> {
impl<T> ops::Index<ops::FullRange, [T]> for Vec<T> { type Output = [T];
#[inline] #[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] { fn index(&self, _index: &ops::FullRange) -> &[T] {
self.as_slice() self.as_slice()
} }
} }
impl<T> ops::IndexMut<ops::Range<uint>, [T]> for Vec<T> { impl<T> ops::IndexMut<ops::Range<uint>> for Vec<T> {
type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] { fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
self.as_mut_slice().index_mut(index) self.as_mut_slice().index_mut(index)
} }
} }
impl<T> ops::IndexMut<ops::RangeTo<uint>> for Vec<T> {
impl<T> ops::IndexMut<ops::RangeTo<uint>, [T]> for Vec<T> { type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] { fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
self.as_mut_slice().index_mut(index) self.as_mut_slice().index_mut(index)
} }
} }
impl<T> ops::IndexMut<ops::RangeFrom<uint>> for Vec<T> {
impl<T> ops::IndexMut<ops::RangeFrom<uint>, [T]> for Vec<T> { type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] { fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
self.as_mut_slice().index_mut(index) self.as_mut_slice().index_mut(index)
} }
} }
impl<T> ops::IndexMut<ops::FullRange> for Vec<T> {
impl<T> ops::IndexMut<ops::FullRange, [T]> for Vec<T> { type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
self.as_mut_slice() self.as_mut_slice()
} }
} }
#[stable] #[stable]
impl<T> ops::Deref for Vec<T> { impl<T> ops::Deref for Vec<T> {
type Target = [T]; type Target = [T];
@ -1795,6 +1799,7 @@ mod tests {
use prelude::*; use prelude::*;
use core::mem::size_of; use core::mem::size_of;
use core::iter::repeat; use core::iter::repeat;
use core::ops::FullRange;
use test::Bencher; use test::Bencher;
use super::as_vec; use super::as_vec;
@ -1932,7 +1937,7 @@ mod tests {
let (left, right) = values.split_at_mut(2); let (left, right) = values.split_at_mut(2);
{ {
let left: &[_] = left; let left: &[_] = left;
assert!(left[0..left.len()] == [1, 2][]); assert!(&left[..left.len()] == &[1, 2][]);
} }
for p in left.iter_mut() { for p in left.iter_mut() {
*p += 1; *p += 1;
@ -1940,7 +1945,7 @@ mod tests {
{ {
let right: &[_] = right; let right: &[_] = right;
assert!(right[0..right.len()] == [3, 4, 5][]); assert!(&right[..right.len()] == &[3, 4, 5][]);
} }
for p in right.iter_mut() { for p in right.iter_mut() {
*p += 2; *p += 2;
@ -2111,35 +2116,35 @@ mod tests {
#[should_fail] #[should_fail]
fn test_slice_out_of_bounds_1() { fn test_slice_out_of_bounds_1() {
let x: Vec<int> = vec![1, 2, 3, 4, 5]; let x: Vec<int> = vec![1, 2, 3, 4, 5];
x[-1..]; &x[(-1)..];
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_slice_out_of_bounds_2() { fn test_slice_out_of_bounds_2() {
let x: Vec<int> = vec![1, 2, 3, 4, 5]; let x: Vec<int> = vec![1, 2, 3, 4, 5];
x.index(&(0..6)); &x[..6];
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_slice_out_of_bounds_3() { fn test_slice_out_of_bounds_3() {
let x: Vec<int> = vec![1, 2, 3, 4, 5]; let x: Vec<int> = vec![1, 2, 3, 4, 5];
x[-1..4]; &x[(-1)..4];
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_slice_out_of_bounds_4() { fn test_slice_out_of_bounds_4() {
let x: Vec<int> = vec![1, 2, 3, 4, 5]; let x: Vec<int> = vec![1, 2, 3, 4, 5];
x.index(&(1..6)); &x[1..6];
} }
#[test] #[test]
#[should_fail] #[should_fail]
fn test_slice_out_of_bounds_5() { fn test_slice_out_of_bounds_5() {
let x: Vec<int> = vec![1, 2, 3, 4, 5]; let x: Vec<int> = vec![1, 2, 3, 4, 5];
x.index(&(3..2)); &x[3..2];
} }
#[test] #[test]
@ -2385,7 +2390,7 @@ mod tests {
b.bytes = src_len as u64; b.bytes = src_len as u64;
b.iter(|| { b.iter(|| {
let dst = src.clone().as_slice().to_vec(); let dst = src.clone()[].to_vec();
assert_eq!(dst.len(), src_len); assert_eq!(dst.len(), src_len);
assert!(dst.iter().enumerate().all(|(i, x)| i == *x)); assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
}); });

View file

@ -57,9 +57,13 @@ macro_rules! array_impls {
Rhs: Deref<Target=[B]>, Rhs: Deref<Target=[B]>,
{ {
#[inline(always)] #[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)] #[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] #[stable]
@ -68,9 +72,13 @@ macro_rules! array_impls {
Lhs: Deref<Target=[A]> Lhs: Deref<Target=[A]>
{ {
#[inline(always)] #[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)] #[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] #[stable]

View file

@ -521,7 +521,7 @@ impl<'a> Formatter<'a> {
let mut fill = [0u8; 4]; let mut fill = [0u8; 4];
let len = self.fill.encode_utf8(&mut fill).unwrap_or(0); 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) { for _ in range(0, pre_pad) {
try!(self.buf.write_str(fill)); try!(self.buf.write_str(fill));

View file

@ -551,78 +551,8 @@ impl<T> ops::IndexMut<uint> for [T] {
} }
} }
impl<T> ops::Index<ops::Range<uint>, [T]> for [T] { impl<T> ops::Index<ops::Range<uint>> for [T] {
#[inline] type Output = [T];
fn index(&self, &index: &ops::Range<uint>) -> &[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<T> ops::Index<ops::RangeTo<uint>, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::RangeTo<uint>) -> &[T] {
self.index(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::Index<ops::RangeFrom<uint>, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::RangeFrom<uint>) -> &[T] {
self.index(&ops::Range{ start: index.start, end: self.len() })
}
}
impl<T> ops::Index<ops::FullRange, [T]> for [T] {
#[inline]
fn index(&self, &index: &ops::FullRange) -> &[T] {
self
}
}
impl<T> ops::IndexMut<ops::Range<uint>, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::Range<uint>) -> &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<T> ops::IndexMut<ops::RangeTo<uint>, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::RangeTo<uint>) -> &mut [T] {
self.index_mut(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::IndexMut<ops::RangeFrom<uint>, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::RangeFrom<uint>) -> &mut [T] {
let len = self.len();
self.index_mut(&ops::Range{ start: index.start, end: len })
}
}
impl<T> ops::IndexMut<ops::FullRange, [T]> for [T] {
#[inline]
fn index_mut(&mut self, &index: &ops::FullRange) -> &mut [T] {
self
}
}
impl<T> ops::Index<ops::Range<uint>, [T]> for [T] {
#[inline] #[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] { fn index(&self, index: &ops::Range<uint>) -> &[T] {
assert!(index.start <= index.end); assert!(index.start <= index.end);
@ -635,6 +565,64 @@ impl<T> ops::Index<ops::Range<uint>, [T]> for [T] {
} }
} }
} }
impl<T> ops::Index<ops::RangeTo<uint>> for [T] {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.index(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::Index<ops::RangeFrom<uint>> for [T] {
type Output = [T];
#[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.index(&ops::Range{ start: index.start, end: self.len() })
}
}
impl<T> ops::Index<ops::FullRange> for [T] {
type Output = [T];
#[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] {
self
}
}
impl<T> ops::IndexMut<ops::Range<uint>> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &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<T> ops::IndexMut<ops::RangeTo<uint>> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
self.index_mut(&ops::Range{ start: 0, end: index.end })
}
}
impl<T> ops::IndexMut<ops::RangeFrom<uint>> for [T] {
type Output = [T];
#[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
let len = self.len();
self.index_mut(&ops::Range{ start: index.start, end: len })
}
}
impl<T> ops::IndexMut<ops::FullRange> 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] #[experimental]
impl<'a, T> ops::Index<ops::Range<uint>, [T]> for Iter<'a, T> { impl<'a, T> ops::Index<ops::Range<uint>> for Iter<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] { fn index(&self, index: &ops::Range<uint>) -> &[T] {
self.as_slice().index(index) self.as_slice().index(index)
@ -775,7 +764,8 @@ impl<'a, T> ops::Index<ops::Range<uint>, [T]> for Iter<'a, T> {
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::RangeTo<uint>, [T]> for Iter<'a, T> { impl<'a, T> ops::Index<ops::RangeTo<uint>> for Iter<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] { fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.as_slice().index(index) self.as_slice().index(index)
@ -783,7 +773,8 @@ impl<'a, T> ops::Index<ops::RangeTo<uint>, [T]> for Iter<'a, T> {
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::RangeFrom<uint>, [T]> for Iter<'a, T> { impl<'a, T> ops::Index<ops::RangeFrom<uint>> for Iter<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] { fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.as_slice().index(index) self.as_slice().index(index)
@ -791,14 +782,14 @@ impl<'a, T> ops::Index<ops::RangeFrom<uint>, [T]> for Iter<'a, T> {
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::FullRange, [T]> for Iter<'a, T> { impl<'a, T> ops::Index<ops::FullRange> for Iter<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] { fn index(&self, _index: &ops::FullRange) -> &[T] {
self.as_slice() self.as_slice()
} }
} }
impl<'a, T> Iter<'a, T> { impl<'a, T> Iter<'a, T> {
/// View the underlying data as a subslice of the original data. /// 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>, marker: marker::ContravariantLifetime<'a>,
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::Range<uint>, [T]> for IterMut<'a, T> { impl<'a, T> ops::Index<ops::Range<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::Range<uint>) -> &[T] { fn index(&self, index: &ops::Range<uint>) -> &[T] {
self.index(&ops::FullRange).index(index) self.index(&ops::FullRange).index(index)
} }
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::RangeTo<uint>, [T]> for IterMut<'a, T> { impl<'a, T> ops::Index<ops::RangeTo<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &[T] { fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
self.index(&ops::FullRange).index(index) self.index(&ops::FullRange).index(index)
} }
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::RangeFrom<uint>, [T]> for IterMut<'a, T> { impl<'a, T> ops::Index<ops::RangeFrom<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] { fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
self.index(&ops::FullRange).index(index) self.index(&ops::FullRange).index(index)
} }
} }
#[experimental] #[experimental]
impl<'a, T> ops::Index<ops::FullRange, [T]> for IterMut<'a, T> { impl<'a, T> ops::Index<ops::FullRange> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index(&self, _index: &ops::FullRange) -> &[T] { fn index(&self, _index: &ops::FullRange) -> &[T] {
make_slice!(T -> &[T]: self.ptr, self.end) make_slice!(T -> &[T]: self.ptr, self.end)
@ -888,31 +881,32 @@ impl<'a, T> ops::Index<ops::FullRange, [T]> for IterMut<'a, T> {
} }
#[experimental] #[experimental]
impl<'a, T> ops::IndexMut<ops::Range<uint>, [T]> for IterMut<'a, T> { impl<'a, T> ops::IndexMut<ops::Range<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] { fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
self.index_mut(&ops::FullRange).index_mut(index) self.index_mut(&ops::FullRange).index_mut(index)
} }
} }
#[experimental] #[experimental]
impl<'a, T> ops::IndexMut<ops::RangeTo<uint>, [T]> for IterMut<'a, T> { impl<'a, T> ops::IndexMut<ops::RangeTo<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] { fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
self.index_mut(&ops::FullRange).index_mut(index) self.index_mut(&ops::FullRange).index_mut(index)
} }
} }
#[experimental] #[experimental]
impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>, [T]> for IterMut<'a, T> { impl<'a, T> ops::IndexMut<ops::RangeFrom<uint>> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] { fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
self.index_mut(&ops::FullRange).index_mut(index) self.index_mut(&ops::FullRange).index_mut(index)
} }
} }
#[experimental] #[experimental]
impl<'a, T> ops::IndexMut<ops::FullRange, [T]> for IterMut<'a, T> { impl<'a, T> ops::IndexMut<ops::FullRange> for IterMut<'a, T> {
type Output = [T];
#[inline] #[inline]
fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] { fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
make_slice!(T -> &mut [T]: self.ptr, self.end) make_slice!(T -> &mut [T]: self.ptr, self.end)

View file

@ -1119,28 +1119,29 @@ mod traits {
} }
} }
impl ops::Index<ops::Range<uint>, str> for str { impl ops::Index<ops::Range<uint>> for str {
type Output = str;
#[inline] #[inline]
fn index(&self, index: &ops::Range<uint>) -> &str { fn index(&self, index: &ops::Range<uint>) -> &str {
self.slice(index.start, index.end) self.slice(index.start, index.end)
} }
} }
impl ops::Index<ops::RangeTo<uint>> for str {
impl ops::Index<ops::RangeTo<uint>, str> for str { type Output = str;
#[inline] #[inline]
fn index(&self, index: &ops::RangeTo<uint>) -> &str { fn index(&self, index: &ops::RangeTo<uint>) -> &str {
self.slice_to(index.end) self.slice_to(index.end)
} }
} }
impl ops::Index<ops::RangeFrom<uint>> for str {
impl ops::Index<ops::RangeFrom<uint>, str> for str { type Output = str;
#[inline] #[inline]
fn index(&self, index: &ops::RangeFrom<uint>) -> &str { fn index(&self, index: &ops::RangeFrom<uint>) -> &str {
self.slice_from(index.start) self.slice_from(index.start)
} }
} }
impl ops::Index<ops::FullRange> for str {
impl ops::Index<ops::FullRange, str> for str { type Output = str;
#[inline] #[inline]
fn index(&self, _index: &ops::FullRange) -> &str { fn index(&self, _index: &ops::FullRange) -> &str {
self self

View file

@ -14,7 +14,6 @@ use core::iter::MinMaxResult::*;
use core::num::SignedInt; use core::num::SignedInt;
use core::uint; use core::uint;
use core::cmp; use core::cmp;
use core::ops::Slice;
use test::Bencher; use test::Bencher;
@ -230,7 +229,7 @@ fn test_inspect() {
.collect::<Vec<uint>>(); .collect::<Vec<uint>>();
assert_eq!(n, xs.len()); assert_eq!(n, xs.len());
assert_eq!(xs.index(&FullRange), ys.index(&FullRange)); assert_eq!(&xs[], &ys[]);
} }
#[test] #[test]
@ -281,47 +280,47 @@ fn test_iterator_nth() {
fn test_iterator_last() { fn test_iterator_last() {
let v: &[_] = &[0i, 1, 2, 3, 4]; let v: &[_] = &[0i, 1, 2, 3, 4];
assert_eq!(v.iter().last().unwrap(), &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] #[test]
fn test_iterator_len() { fn test_iterator_len() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 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[..4].iter().count(), 4);
assert_eq!(v.index(&(0..10)).iter().count(), 10); assert_eq!(v[..10].iter().count(), 10);
assert_eq!(v.index(&(0..0)).iter().count(), 0); assert_eq!(v[0..0].iter().count(), 0);
} }
#[test] #[test]
fn test_iterator_sum() { fn test_iterator_sum() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 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.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] #[test]
fn test_iterator_product() { fn test_iterator_product() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 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[0..4].iter().map(|&x| x).product(), 0);
assert_eq!(v.index(&(1..5)).iter().map(|&x| x).product(), 24); assert_eq!(v[1..5].iter().map(|&x| x).product(), 24);
assert_eq!(v.index(&(0..0)).iter().map(|&x| x).product(), 1); assert_eq!(v[0..0].iter().map(|&x| x).product(), 1);
} }
#[test] #[test]
fn test_iterator_max() { fn test_iterator_max() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 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.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] #[test]
fn test_iterator_min() { fn test_iterator_min() {
let v: &[_] = &[0i, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; 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.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] #[test]
@ -374,7 +373,7 @@ fn test_all() {
assert!(v.iter().all(|&x| x < 10)); assert!(v.iter().all(|&x| x < 10));
assert!(!v.iter().all(|&x| x % 2 == 0)); assert!(!v.iter().all(|&x| x % 2 == 0));
assert!(!v.iter().all(|&x| x > 100)); 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] #[test]
@ -383,7 +382,7 @@ fn test_any() {
assert!(v.iter().any(|&x| x < 10)); assert!(v.iter().any(|&x| x < 10));
assert!(v.iter().any(|&x| x % 2 == 0)); assert!(v.iter().any(|&x| x % 2 == 0));
assert!(!v.iter().any(|&x| x > 100)); 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] #[test]
@ -586,7 +585,7 @@ fn check_randacc_iter<A, T>(a: T, len: uint) where
fn test_double_ended_flat_map() { fn test_double_ended_flat_map() {
let u = [0u,1]; let u = [0u,1];
let v = [5u,6,7,8]; 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_back().unwrap(), &8);
assert_eq!(it.next().unwrap(), &5); assert_eq!(it.next().unwrap(), &5);
assert_eq!(it.next_back().unwrap(), &7); assert_eq!(it.next_back().unwrap(), &7);

View file

@ -43,35 +43,35 @@ fn iterator_to_slice() {
{ {
let mut iter = data.iter(); let mut iter = data.iter();
assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); assert_eq!(&iter[], &other_data[]);
iter.next(); iter.next();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); assert_eq!(&iter[], &other_data[1..]);
iter.next_back(); 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(); let s = iter.as_slice();
iter.next(); iter.next();
assert_eq!(s, other_data.index(&(1..2))); assert_eq!(s, &other_data[1..2]);
} }
{ {
let mut iter = data.iter_mut(); let mut iter = data.iter_mut();
assert_eq!(iter.index(&FullRange), other_data.index(&FullRange)); assert_eq!(iter.index(&FullRange), other_data.index(&FullRange));
// mutability: // mutability:
assert!(iter[mut] == other_data); assert!(&mut iter[] == other_data);
iter.next(); iter.next();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..))); 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(); iter.next_back();
assert_eq!(iter.index(&FullRange), other_data.index(&(1..2))); 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(); let s = iter.into_slice();
assert!(s == other_data[mut 1..2]); assert!(s == &mut other_data[1..2]);
} }
}} }}
} }

View file

@ -1413,7 +1413,7 @@ mod tests {
assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()])); assert!(matches_single.opts_present(&["e".to_string(), "encrypt".to_string()]));
assert!(!matches_single.opts_present(&["encrypt".to_string()])); assert!(!matches_single.opts_present(&["encrypt".to_string()]));
assert!(!matches_single.opts_present(&["thing".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()]).unwrap(), "foo");
assert_eq!(matches_single.opts_str(&["e".to_string(), "encrypt".to_string()]).unwrap(), 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(&["e".to_string(), "encrypt".to_string()]));
assert!(!matches_both.opts_present(&["f".to_string()])); assert!(!matches_both.opts_present(&["f".to_string()]));
assert!(!matches_both.opts_present(&["thing".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(&["e".to_string()]).unwrap(), "foo");
assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo"); assert_eq!(matches_both.opts_str(&["encrypt".to_string()]).unwrap(), "foo");

View file

@ -24,7 +24,7 @@ use core::num::{Float, Int};
use {Rng, Rand}; 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::gamma::{Gamma, ChiSquared, FisherF, StudentT};
pub use self::normal::{Normal, LogNormal}; pub use self::normal::{Normal, LogNormal};
pub use self::exponential::Exp; pub use self::exponential::Exp;
@ -104,7 +104,7 @@ pub struct Weighted<T> {
/// ``` /// ```
pub struct WeightedChoice<'a, T:'a> { pub struct WeightedChoice<'a, T:'a> {
items: &'a mut [Weighted<T>], items: &'a mut [Weighted<T>],
weight_range: RandRange<uint> weight_range: Range<uint>
} }
impl<'a, T: Clone> WeightedChoice<'a, T> { impl<'a, T: Clone> WeightedChoice<'a, T> {
@ -138,7 +138,7 @@ impl<'a, T: Clone> WeightedChoice<'a, T> {
items: items, items: items,
// we're likely to be generating numbers in this range // we're likely to be generating numbers in this range
// relatively often, so might as well cache it // relatively often, so might as well cache it
weight_range: RandRange::new(0, running_total) weight_range: Range::new(0, running_total)
} }
} }
} }

View file

@ -166,7 +166,7 @@ mod tests {
use std::num::Int; use std::num::Int;
use std::prelude::v1::*; use std::prelude::v1::*;
use distributions::{Sample, IndependentSample}; use distributions::{Sample, IndependentSample};
use super::Range; use super::Range as Range;
#[should_fail] #[should_fail]
#[test] #[test]

View file

@ -58,7 +58,7 @@ use core::prelude::*;
pub use isaac::{IsaacRng, Isaac64Rng}; pub use isaac::{IsaacRng, Isaac64Rng};
pub use chacha::ChaChaRng; pub use chacha::ChaChaRng;
use distributions::{RandRange, IndependentSample}; use distributions::{Range, IndependentSample};
use distributions::range::SampleRange; use distributions::range::SampleRange;
#[cfg(test)] #[cfg(test)]
@ -247,7 +247,7 @@ pub trait Rng : Sized {
/// ``` /// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T { fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high"); 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 /// 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 choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = thread_rng(); /// let mut rng = thread_rng();
/// println!("{}", rng.choose(&choices)); /// println!("{}", rng.choose(&choices));
/// # // replace with slicing syntax when it's stable! /// # // uncomment when slicing syntax is stable
/// assert_eq!(rng.choose(choices.index(&(0..0))), None); /// //assert_eq!(rng.choose(choices.index(&(0..0))), None);
/// ``` /// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> { fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() { if values.is_empty() {

View file

@ -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_111, r"a[-b]", r"a-", Some((0, 2))}
mat!{match_basic_112, 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_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_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_116, r"a[^-b]c", r"adc", Some((0, 3))}
mat!{match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))} mat!{match_basic_117, r"a[^]b]c", r"adc", Some((0, 3))}

View file

@ -159,7 +159,7 @@ macro_rules! mat {
// actual capture groups to match test set. // actual capture groups to match test set.
let mut sgot = got.as_slice(); let mut sgot = got.as_slice();
if sgot.len() > expected.len() { if sgot.len() > expected.len() {
sgot = sgot[0..expected.len()] sgot = &sgot[..expected.len()]
} }
if expected != sgot { if expected != sgot {
panic!("For RE '{}' against '{}', expected '{}' but got '{}'", panic!("For RE '{}' against '{}', expected '{}' but got '{}'",

View file

@ -499,7 +499,7 @@ impl<'a, 'tcx> Context<'a, 'tcx> {
None => { None => {
self.span_lint(builtin::UNKNOWN_LINTS, span, self.span_lint(builtin::UNKNOWN_LINTS, span,
format!("unknown `{}` attribute: `{}`", format!("unknown `{}` attribute: `{}`",
level.as_str(), lint_name).index(&FullRange)); level.as_str(), lint_name).as_slice());
continue; continue;
} }
} }
@ -791,7 +791,7 @@ pub fn check_crate(tcx: &ty::ctxt,
for &(lint, span, ref msg) in v.iter() { for &(lint, span, ref msg) in v.iter() {
tcx.sess.span_bug(span, tcx.sess.span_bug(span,
format!("unprocessed lint {} at {}: {}", 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())
} }
} }

View file

@ -209,7 +209,7 @@ impl<'a> CrateReader<'a> {
let name = match *path_opt { let name = match *path_opt {
Some((ref path_str, _)) => { Some((ref path_str, _)) => {
let name = path_str.get().to_string(); 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)); Some(i.span));
name name
} }
@ -276,7 +276,7 @@ impl<'a> CrateReader<'a> {
} else { } else {
self.sess.span_err(m.span, self.sess.span_err(m.span,
format!("unknown kind: `{}`", format!("unknown kind: `{}`",
k)[]); k).index(&FullRange));
cstore::NativeUnknown cstore::NativeUnknown
} }
} }
@ -330,7 +330,7 @@ impl<'a> CrateReader<'a> {
match self.sess.opts.externs.get(name) { match self.sess.opts.externs.get(name) {
Some(locs) => { Some(locs) => {
let found = locs.iter().any(|l| { 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 l == source.dylib || l == source.rlib
}); });
if found { if found {
@ -409,7 +409,7 @@ impl<'a> CrateReader<'a> {
crate_name: name, crate_name: name,
hash: hash.map(|a| &*a), hash: hash.map(|a| &*a),
filesearch: self.sess.target_filesearch(kind), filesearch: self.sess.target_filesearch(kind),
triple: self.sess.opts.target_triple[], triple: self.sess.opts.target_triple.index(&FullRange),
root: root, root: root,
rejected_via_hash: vec!(), rejected_via_hash: vec!(),
rejected_via_triple: vec!(), rejected_via_triple: vec!(),

View file

@ -1826,10 +1826,10 @@ fn encode_macro_defs(rbml_w: &mut Encoder,
rbml_w.start_tag(tag_macro_def); rbml_w.start_tag(tag_macro_def);
encode_name(rbml_w, def.ident.name); 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.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();
rbml_w.end_tag(); rbml_w.end_tag();

View file

@ -624,7 +624,8 @@ impl<'a> Context<'a> {
return true return true
} else { } else {
let (ref prefix, ref suffix) = dylibname; 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 return true
} }
} }

View file

@ -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); let s = self.ast_map.node_to_string(node_id);
// left-aligns the lines // left-aligns the lines
let s = replace_newline_with_backslash_l(s); 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()) dot::LabelText::EscStr(label.into_cow())
} }

View file

@ -165,6 +165,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) {
ast::ExprParen(..) | ast::ExprParen(..) |
ast::ExprField(..) | ast::ExprField(..) |
ast::ExprTupField(..) | ast::ExprTupField(..) |
ast::ExprIndex(..) |
ast::ExprTup(..) | ast::ExprTup(..) |
ast::ExprRepeat(..) | ast::ExprRepeat(..) |
ast::ExprStruct(..) => {} ast::ExprStruct(..) => {}

View file

@ -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 {}", let msg = format!("Pattern has unexpected type: {} and type {}",
def, def,
cmt_pat.ty.repr(tcx)); cmt_pat.ty.repr(tcx));
tcx.sess.span_bug(pat.span, msg[]) tcx.sess.span_bug(pat.span, msg.as_slice())
} }
} }

View file

@ -495,7 +495,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> {
ret_ty), 1, true) ret_ty), 1, true)
} }
None => { 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() token::get_name(fld).get().to_string()
} }
InteriorField(PositionalField(i)) => format!("#{}", i), InteriorField(PositionalField(i)) => format!("#{}", i),
InteriorElement(_) => ".index(&FullRange)".to_string(), InteriorElement(_) => "[]".to_string(),
} }
} }
} }

View file

@ -378,7 +378,7 @@ pub fn type_known_to_meet_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>,
span, span,
format!("overflow evaluating whether `{}` is `{}`", format!("overflow evaluating whether `{}` is `{}`",
ty.user_string(infcx.tcx), ty.user_string(infcx.tcx),
bound.user_string(infcx.tcx))[]); bound.user_string(infcx.tcx)).as_slice());
suggest_new_overflow_limit(infcx.tcx, span); suggest_new_overflow_limit(infcx.tcx, span);
false false
} }

View file

@ -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 // The `Self` type is erased, so it should not appear in list of
// arguments or return type apart from the receiver. // arguments or return type apart from the receiver.
let ref sig = method.fty.sig; 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) { if contains_illegal_self_type_reference(tcx, trait_def_id, input_ty) {
return Some(MethodViolationCode::ReferencesSelf); return Some(MethodViolationCode::ReferencesSelf);
} }

View file

@ -490,7 +490,7 @@ fn assemble_candidates_from_object_type<'cx,'tcx>(
selcx.tcx().sess.span_bug( selcx.tcx().sess.span_bug(
obligation.cause.span, obligation.cause.span,
format!("assemble_candidates_from_object_type called with non-object: {}", 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); let projection_bounds = data.projection_bounds_with_self_ty(selcx.tcx(), object_ty);

View file

@ -3654,7 +3654,8 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool {
ty_unboxed_closure(..) => { ty_unboxed_closure(..) => {
// this check is run on type definitions, so we don't expect to see // this check is run on type definitions, so we don't expect to see
// inference by-products or unboxed closure types // 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) => { 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(..) => { ty_unboxed_closure(..) => {
// this check is run on type definitions, so we don't expect to see // this check is run on type definitions, so we don't expect to see
// unboxed closure types // 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, _ => Representable,
} }

View file

@ -639,7 +639,7 @@ pub fn build_target_config(opts: &Options, sp: &SpanHandler) -> Config {
let target = match Target::search(opts.target_triple.index(&FullRange)) { let target = match Target::search(opts.target_triple.index(&FullRange)) {
Ok(t) => t, Ok(t) => t,
Err(e) => { 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 => { s => {
early_error(format!("unknown library kind `{}`, expected \ early_error(format!("unknown library kind `{}`, expected \
one of dylib, framework, or static", one of dylib, framework, or static",
s)[]); s).as_slice());
} }
}; };
return (name.to_string(), kind) return (name.to_string(), kind)

View file

@ -247,7 +247,9 @@ impl Target {
} ); } );
($key_name:ident, bool) => ( { ($key_name:ident, bool) => ( {
let name = (stringify!($key_name)).replace("_", "-"); 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) => ( { ($key_name:ident, list) => ( {
let name = (stringify!($key_name)).replace("_", "-"); let name = (stringify!($key_name)).replace("_", "-");

View file

@ -138,7 +138,7 @@
//! - `FREEZE` means that the `LV` cannot be borrowed immutably; //! - `FREEZE` means that the `LV` cannot be borrowed immutably;
//! //!
//! Finally, it is never possible to move from an lvalue that appears in a //! 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 //! 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 //! prevents moves from `LV`. I chose not to make `MOVE` a fourth kind of
//! action because that would imply that sometimes moves are permitted //! action because that would imply that sometimes moves are permitted
@ -476,7 +476,7 @@
//! ```text //! ```text
//! &mut LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM|FREEZE) //! &mut LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM|FREEZE)
//! &LV => RESTRICTIONS(LV, LT, MUTATE|CLAIM) //! &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, //! The reasoning here is that a mutable borrow must be the only writer,
@ -542,7 +542,7 @@
//! restricting `MUTATE` and `CLAIM` actions: //! restricting `MUTATE` and `CLAIM` actions:
//! //!
//! ```text //! ```text
//! RESTRICTIONS(*LV, LT, ACTIONS) = .index(&FullRange) // R-Deref-Imm-Borrowed //! RESTRICTIONS(*LV, LT, ACTIONS) = [] // R-Deref-Imm-Borrowed
//! TYPE(LV) = &LT' Ty //! TYPE(LV) = &LT' Ty
//! LT <= LT' // (1) //! LT <= LT' // (1)
//! ACTIONS subset of [MUTATE, CLAIM] //! ACTIONS subset of [MUTATE, CLAIM]
@ -660,7 +660,7 @@
//! necessary to add any restrictions at all to the final result. //! necessary to add any restrictions at all to the final result.
//! //!
//! ```text //! ```text
//! RESTRICTIONS(*LV, LT, .index(&FullRange)) = .index(&FullRange) // R-Deref-Freeze-Borrowed //! RESTRICTIONS(*LV, LT, []) = [] // R-Deref-Freeze-Borrowed
//! TYPE(LV) = &const Ty //! TYPE(LV) = &const Ty
//! ``` //! ```
//! //!

View file

@ -804,7 +804,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> {
mc::AliasableClosure(id) => { mc::AliasableClosure(id) => {
self.tcx.sess.span_err(span, self.tcx.sess.span_err(span,
format!("{} in a captured outer \ 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), span_help!(self.tcx.sess, self.tcx.map.span(id),
"consider changing this closure to take self by mutable reference"); "consider changing this closure to take self by mutable reference");
} }

View file

@ -3763,13 +3763,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
self.resolve_error(path.span, self.resolve_error(path.span,
format!("`{}` is not an enum variant, struct or const", format!("`{}` is not an enum variant, struct or const",
token::get_ident( token::get_ident(
path.segments.last().unwrap().identifier)).index(&FullRange)); path.segments.last().unwrap().identifier)).as_slice());
} }
None => { None => {
self.resolve_error(path.span, self.resolve_error(path.span,
format!("unresolved enum variant, struct or const `{}`", format!("unresolved enum variant, struct or const `{}`",
token::get_ident( token::get_ident(
path.segments.last().unwrap().identifier)).index(&FullRange)); path.segments.last().unwrap().identifier)).as_slice());
} }
} }

View file

@ -608,7 +608,7 @@ fn link_rlib<'a>(sess: &'a Session,
// extension to it. This is to work around a bug in LLDB that // 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 // would cause it to crash if the name of a file in an archive
// was exactly 16 bytes. // 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( let bc_deflated_filename = obj_filename.with_extension(
format!("{}.bytecode.deflate", i).index(&FullRange)); 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 // -force_load is the OSX equivalent of --whole-archive, but it
// involves passing the full path to the library to link. // involves passing the full path to the library to link.
let lib = archive::find_library(l.index(&FullRange), let lib = archive::find_library(l.index(&FullRange),
sess.target.target.options.staticlib_prefix.index(&FullRange), sess.target.target.options.staticlib_prefix.as_slice(),
sess.target.target.options.staticlib_suffix.index(&FullRange), sess.target.target.options.staticlib_suffix.as_slice(),
search_path.index(&FullRange), search_path.index(&FullRange),
&sess.diagnostic().handler); &sess.diagnostic().handler);
let mut v = b"-Wl,-force_load,".to_vec(); let mut v = b"-Wl,-force_load,".to_vec();

View file

@ -64,7 +64,7 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
debug!("reading {}", file); debug!("reading {}", file);
for i in iter::count(0u, 1) { for i in iter::count(0u, 1) {
let bc_encoded = time(sess.time_passes(), 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", archive.read(format!("{}.{}.bytecode.deflate",

View file

@ -381,8 +381,8 @@ unsafe extern "C" fn diagnostic_handler(info: DiagnosticInfoRef, user: *mut c_vo
cgcx.handler.note(format!("optimization {} for {} at {}: {}", cgcx.handler.note(format!("optimization {} for {} at {}: {}",
opt.kind.describe(), opt.kind.describe(),
pass_name, pass_name,
if loc.is_empty() { "[unknown]" } else { loc.index(&FullRange) }, if loc.is_empty() { "[unknown]" } else { loc.as_slice() },
llvm::twine_to_string(opt.message)).index(&FullRange)); llvm::twine_to_string(opt.message)).as_slice());
} }
} }

View file

@ -292,7 +292,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
Some(def_id) => { Some(def_id) => {
result.push_str(" as "); result.push_str(" as ");
result.push_str( 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 => {} None => {}
} }
@ -636,7 +636,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> {
item.id); item.id);
for field in struct_def.fields.iter() { 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); 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(); let def_map = self.analysis.ty_cx.def_map.borrow();
if !def_map.contains_key(&id) { if !def_map.contains_key(&id) {
self.sess.span_bug(span, 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 def = &(*def_map)[id];
let sub_span = self.span.span_for_last_ident(span); 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)); value.index(&FullRange));
self.visit_ty(&**ty); 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(_) => (), ast::ItemMac(_) => (),
_ => visit::walk_item(self, item), _ => 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(); let def_map = self.analysis.ty_cx.def_map.borrow();
if !def_map.contains_key(&id) { if !def_map.contains_key(&id) {
self.sess.span_bug(p.span, 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]; let def = &(*def_map)[id];
match *def { match *def {

View file

@ -237,7 +237,7 @@ impl<'a> FmtStrs<'a> {
if !needs_span { if !needs_span {
self.span.sess.span_bug(span, self.span.sess.span_bug(span,
format!("Called record_with_span for '{}' \ 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) { let values_str = match self.make_values_str(label, fields, values, span) {

View file

@ -1037,8 +1037,8 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
field_vals.len()) field_vals.len())
); );
let mut vals = field_vals; let mut vals = field_vals;
vals.push_all(vals_left.index(&FullRange)); vals.push_all(vals_left.as_slice());
compile_submatch(bcx, pats.index(&FullRange), vals.index(&FullRange), chk, has_genuine_default); compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
return; return;
} }
_ => () _ => ()

View file

@ -2239,7 +2239,7 @@ pub fn update_linkage(ccx: &CrateContext,
if let Some(id) = id { if let Some(id) = id {
let item = ccx.tcx().map.get(id); let item = ccx.tcx().map.get(id);
if let ast_map::NodeItem(i) = item { 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()) { if let Some(linkage) = llvm_linkage_by_name(name.get()) {
llvm::SetLinkage(llval, linkage); llvm::SetLinkage(llval, linkage);
} else { } else {
@ -2597,7 +2597,11 @@ pub fn register_fn_llvmty(ccx: &CrateContext,
llfty: Type) -> ValueRef { llfty: Type) -> ValueRef {
debug!("register_fn_llvmty id={} sym={}", node_id, sym); 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); finish_register_fn(ccx, sp, sym, node_id, llfn);
llfn llfn
} }

View file

@ -414,7 +414,7 @@ impl<'tcx> TypeMap<'tcx> {
unique_type_id.push_str(format!("[{}]", len).index(&FullRange)); unique_type_id.push_str(format!("[{}]", len).index(&FullRange));
} }
None => { None => {
unique_type_id.push_str(".index(&FullRange)"); unique_type_id.push_str("[]");
} }
}; };

View file

@ -1369,13 +1369,13 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
let tcx = bcx.tcx(); let tcx = bcx.tcx();
with_field_tys(tcx, ty, Some(expr_id), |discr, field_tys| { 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<bool> = repeat(true).take(field_tys.len()).collect();
let numbered_fields = fields.iter().map(|field| { let numbered_fields = fields.iter().map(|field| {
let opt_pos = let opt_pos =
field_tys.iter().position(|field_ty| field_tys.iter().position(|field_ty|
field_ty.name == field.ident.node.name); field_ty.name == field.ident.node.name);
match opt_pos { let result = match opt_pos {
Some(i) => { Some(i) => {
need_base[i] = false; need_base[i] = false;
(i, &*field.expr) (i, &*field.expr)
@ -1384,14 +1384,15 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
tcx.sess.span_bug(field.span, tcx.sess.span_bug(field.span,
"Couldn't find field in struct type") "Couldn't find field in struct type")
} }
} };
result
}).collect::<Vec<_>>(); }).collect::<Vec<_>>();
let optbase = match base { let optbase = match base {
Some(base_expr) => { Some(base_expr) => {
let mut leftovers = Vec::new(); let mut leftovers = Vec::new();
for (i, b) in need_base.iter().enumerate() { for (i, b) in need_base.iter().enumerate() {
if *b { if *b {
leftovers.push((i, field_tys[i].mt.ty)) leftovers.push((i, field_tys[i].mt.ty));
} }
} }
Some(StructBaseInfo {expr: base_expr, Some(StructBaseInfo {expr: base_expr,
@ -1408,7 +1409,7 @@ fn trans_struct<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
trans_adt(bcx, trans_adt(bcx,
ty, ty,
discr, discr,
numbered_fields.index(&FullRange), numbered_fields.as_slice(),
optbase, optbase,
dest, dest,
Some(NodeInfo { id: expr_id, span: expr_span })) Some(NodeInfo { id: expr_id, span: expr_span }))

View file

@ -748,7 +748,7 @@ pub fn trans_rust_fn_with_foreign_abi<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
debug!("calling llrustfn = {}, t = {}", debug!("calling llrustfn = {}, t = {}",
ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx())); ccx.tn().val_to_string(llrustfn), t.repr(ccx.tcx()));
let attributes = base::get_fn_llvm_attributes(ccx, t); 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. // Get the return value where the foreign fn expects it.
let llforeign_ret_ty = match tys.fn_ty.ret_ty.cast { 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()), ty.repr(ccx.tcx()),
ccx.tn().types_to_str(llsig.llarg_tys.index(&FullRange)), ccx.tn().types_to_str(llsig.llarg_tys.index(&FullRange)),
ccx.tn().type_to_string(llsig.llret_ty), ccx.tn().type_to_string(llsig.llret_ty),
ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().index(&FullRange)), ccx.tn().types_to_str(fn_ty.arg_tys.iter().map(|t| t.ty).collect::<Vec<_>>().as_slice()),
ccx.tn().type_to_string(fn_ty.ret_ty.ty), ccx.tn().type_to_string(fn_ty.ret_ty.ty),
llsig.ret_def); llsig.ret_def);

View file

@ -556,7 +556,8 @@ pub fn instantiate_trait_ref<'tcx>(
_ => { _ => {
this.tcx().sess.span_fatal( this.tcx().sess.span_fatal(
ast_trait_ref.path.span, 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) => { ast::TyObjectSum(ref ty, ref bounds) => {
match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.index(&FullRange)) { match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.index(&FullRange)) {
Ok((trait_ref, projection_bounds)) => { Ok((trait_ref, projection_bounds)) => {
trait_ref_to_object_type(this, rscope, ast_ty.span, trait_ref_to_object_type(this,
trait_ref, projection_bounds, bounds.index(&FullRange)) rscope,
ast_ty.span,
trait_ref,
projection_bounds,
bounds.index(&FullRange))
} }
Err(ErrorReported) => { Err(ErrorReported) => {
this.tcx().types.err this.tcx().types.err

View file

@ -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<...>]. let arg_exprs: Vec<_> = arg_exprs.iter().collect(); // for some weird reason we take &[&P<...>].
check_argument_types(fcx, check_argument_types(fcx,
call_expr.span, call_expr.span,
fn_sig.inputs[], fn_sig.inputs.as_slice(),
arg_exprs.as_slice(), arg_exprs.as_slice(),
AutorefArgs::No, AutorefArgs::No,
fn_sig.variadic, fn_sig.variadic,

View file

@ -563,7 +563,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> {
&**base_expr, &**base_expr,
Some(&ty::AdjustDerefRef(base_adjustment.clone()))); Some(&ty::AdjustDerefRef(base_adjustment.clone())));
let index_expr_ty = self.fcx.expr_ty(&**index_expr); let index_expr_ty = self.fcx.expr_ty(&**index_expr);
let result = check::try_index_step( let result = check::try_index_step(
self.fcx, self.fcx,
MethodCall::expr(expr.id), MethodCall::expr(expr.id),
@ -640,7 +640,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> {
self.span, self.span,
format!("cannot upcast `{}` to `{}`", format!("cannot upcast `{}` to `{}`",
source_trait_ref.repr(self.tcx()), source_trait_ref.repr(self.tcx()),
target_trait_def_id.repr(self.tcx()))[]); target_trait_def_id.repr(self.tcx())).as_slice());
} }
} }
} }

View file

@ -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()); callee::check_call(fcx, expr, &**callee, args.as_slice());
} }
ast::ExprMethodCall(ident, ref tps, ref args) => { 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 arg_tys = args.iter().map(|a| fcx.expr_ty(&**a));
let args_err = arg_tys.fold(false, let args_err = arg_tys.fold(false,
|rest_err, a| { |rest_err, a| {

View file

@ -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 param_ty = ty::ParamTy::new(space, index, param.ident.name);
let bounds = compute_bounds(ccx, let bounds = compute_bounds(ccx,
param_ty.to_ty(ccx.tcx), param_ty.to_ty(ccx.tcx),
param.bounds.index(&FullRange, param.bounds.index(&FullRange),
SizedByDefault::Yes, SizedByDefault::Yes,
param.span); param.span);
let default = match param.default { let default = match param.default {

View file

@ -97,7 +97,7 @@ impl fmt::Show for clean::Generics {
if i > 0 { if i > 0 {
try!(f.write_str(", ")) try!(f.write_str(", "))
} }
try!(f.write_str(tp.name[])); try!(f.write_str(tp.name.as_slice()));
if tp.bounds.len() > 0 { if tp.bounds.len() > 0 {
try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice()))); try!(write!(f, ": {}", TyParamBounds(tp.bounds.as_slice())));
@ -337,7 +337,7 @@ fn path<F, G>(w: &mut fmt::Formatter,
// This is a documented path, link to it! // This is a documented path, link to it!
Some((ref fqp, shortty)) if abs_root.is_some() => { Some((ref fqp, shortty)) if abs_root.is_some() => {
let mut url = String::from_str(abs_root.unwrap().as_slice()); 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() { for component in to_link.iter() {
url.push_str(component.as_slice()); url.push_str(component.as_slice());
url.push_str("/"); url.push_str("/");
@ -433,7 +433,7 @@ impl fmt::Show for clean::Type {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { match *self {
clean::TyParamBinder(id) => { 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) => { clean::Generic(ref name) => {
f.write_str(name.as_slice()) f.write_str(name.as_slice())

View file

@ -404,7 +404,7 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> io::IoResult<String>
search_index.push(IndexItem { search_index.push(IndexItem {
ty: shortty(item), ty: shortty(item),
name: item.name.clone().unwrap(), name: item.name.clone().unwrap(),
path: fqp[..fqp.len() - 1].connect("::"), path: fqp[..(fqp.len() - 1)].connect("::"),
desc: shorter(item.doc_value()).to_string(), desc: shorter(item.doc_value()).to_string(),
parent: Some(did), parent: Some(did),
}); });
@ -559,7 +559,7 @@ fn write_shared(cx: &Context,
}; };
let mut mydst = dst.clone(); 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()); mydst.push(part.as_slice());
try!(mkdir(&mydst)); try!(mkdir(&mydst));
} }
@ -842,7 +842,7 @@ impl DocFolder for Cache {
clean::StructFieldItem(..) | clean::StructFieldItem(..) |
clean::VariantItem(..) => { clean::VariantItem(..) => {
((Some(*self.parent_stack.last().unwrap()), ((Some(*self.parent_stack.last().unwrap()),
Some(self.stack[..self.stack.len() - 1])), Some(&self.stack[..(self.stack.len() - 1)])),
false) false)
} }
clean::MethodItem(..) => { clean::MethodItem(..) => {
@ -853,13 +853,13 @@ impl DocFolder for Cache {
let did = *last; let did = *last;
let path = match self.paths.get(&did) { let path = match self.paths.get(&did) {
Some(&(_, ItemType::Trait)) => 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 // The current stack not necessarily has correlation for
// where the type was defined. On the other hand, // where the type was defined. On the other hand,
// `paths` always has the right information if present. // `paths` always has the right information if present.
Some(&(ref fqp, ItemType::Struct)) | Some(&(ref fqp, ItemType::Struct)) |
Some(&(ref fqp, ItemType::Enum)) => Some(&(ref fqp, ItemType::Enum)) =>
Some(fqp[..fqp.len() - 1]), Some(&fqp[..(fqp.len() - 1)]),
Some(..) => Some(self.stack.as_slice()), Some(..) => Some(self.stack.as_slice()),
None => None None => None
}; };
@ -1185,7 +1185,7 @@ impl Context {
.collect::<String>(); .collect::<String>();
match cache().paths.get(&it.def_id) { match cache().paths.get(&it.def_id) {
Some(&(ref names, _)) => { 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(name.as_slice());
url.push_str("/"); url.push_str("/");
} }
@ -2267,7 +2267,7 @@ fn item_macro(w: &mut fmt::Formatter, it: &clean::Item,
t: &clean::Macro) -> fmt::Result { t: &clean::Macro) -> fmt::Result {
try!(w.write_str(highlight::highlight(t.source.as_slice(), try!(w.write_str(highlight::highlight(t.source.as_slice(),
Some("macro"), Some("macro"),
None)[])); None).as_slice()));
document(w, it) document(w, it)
} }

View file

@ -1124,7 +1124,7 @@ impl Json {
} }
} }
impl<'a> ops::Index<&'a str> for Json { impl<'a> Index<&'a str> for Json {
type Output = Json; type Output = Json;
fn index(&self, idx: & &str) -> &Json { fn index(&self, idx: & &str) -> &Json {
@ -1132,7 +1132,7 @@ impl<'a> ops::Index<&'a str> for Json {
} }
} }
impl ops::Index<uint> for Json { impl Index<uint> for Json {
type Output = Json; type Output = Json;
fn index<'a>(&'a self, idx: &uint) -> &'a Json { fn index<'a>(&'a self, idx: &uint) -> &'a Json {
@ -1186,7 +1186,8 @@ pub struct Stack {
} }
/// StackElements compose a 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 /// StackElements compositing the stack that represents foo.bar[3].x
#[derive(PartialEq, Clone, Show)] #[derive(PartialEq, Clone, Show)]
pub enum StackElement<'l> { pub enum StackElement<'l> {
@ -2505,12 +2506,12 @@ mod tests {
use super::ParserError::*; use super::ParserError::*;
use super::DecoderError::*; use super::DecoderError::*;
use super::JsonEvent::*; use super::JsonEvent::*;
use super::StackElement::*;
use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser, use super::{Json, from_str, DecodeResult, DecoderError, JsonEvent, Parser,
StackElement, Stack, Decoder}; StackElement, Stack, Decoder};
use std::{i64, u64, f32, f64}; use std::{i64, u64, f32, f64, io};
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::num::Float; use std::num::Float;
use std::ops::Index;
use std::string; use std::string;
#[derive(RustcDecodable, Eq, PartialEq, Show)] #[derive(RustcDecodable, Eq, PartialEq, Show)]
@ -3487,9 +3488,12 @@ mod tests {
(U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]), (U64Value(5), vec![StackElement::Key("array"), StackElement::Index(5)]),
(ArrayEnd, vec![StackElement::Key("array")]), (ArrayEnd, vec![StackElement::Key("array")]),
(ArrayStart, vec![StackElement::Key("idents")]), (ArrayStart, vec![StackElement::Key("idents")]),
(NullValue, vec![StackElement::Key("idents"), StackElement::Index(0)]), (NullValue, vec![StackElement::Key("idents"),
(BooleanValue(true), vec![StackElement::Key("idents"), StackElement::Index(1)]), StackElement::Index(0)]),
(BooleanValue(false), vec![StackElement::Key("idents"), StackElement::Index(2)]), (BooleanValue(true), vec![StackElement::Key("idents"),
StackElement::Index(1)]),
(BooleanValue(false), vec![StackElement::Key("idents"),
StackElement::Index(2)]),
(ArrayEnd, vec![StackElement::Key("idents")]), (ArrayEnd, vec![StackElement::Key("idents")]),
(ObjectEnd, vec![]), (ObjectEnd, vec![]),
] ]
@ -3567,13 +3571,24 @@ mod tests {
(ObjectStart, vec![]), (ObjectStart, vec![]),
(F64Value(1.0), vec![StackElement::Key("a")]), (F64Value(1.0), vec![StackElement::Key("a")]),
(ArrayStart, vec![StackElement::Key("b")]), (ArrayStart, vec![StackElement::Key("b")]),
(BooleanValue(true), vec![StackElement::Key("b"), StackElement::Index(0)]), (BooleanValue(true), vec![StackElement::Key("b"),
(StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"), StackElement::Index(1)]), StackElement::Index(0)]),
(ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2)]), (StringValue("foo\nbar".to_string()), vec![StackElement::Key("b"),
(ObjectStart, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]), StackElement::Index(1)]),
(NullValue, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c"), StackElement::Key("d")]), (ObjectStart, vec![StackElement::Key("b"),
(ObjectEnd, vec![StackElement::Key("b"), StackElement::Index(2), StackElement::Key("c")]), StackElement::Index(2)]),
(ObjectEnd, 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")]), (ArrayEnd, vec![StackElement::Key("b")]),
(ObjectEnd, vec![]), (ObjectEnd, vec![]),
] ]
@ -3716,13 +3731,19 @@ mod tests {
stack.push_key("bar".to_string()); stack.push_key("bar".to_string());
assert!(stack.len() == 3); 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)]));
assert!(stack.starts_with(&[StackElement::Index(1), StackElement::Key("foo")])); 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("bar")]));
assert!(stack.ends_with(&[StackElement::Key("foo"), 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.last_is_index());
assert!(stack.get(0) == StackElement::Index(1)); assert!(stack.get(0) == StackElement::Index(1));
assert!(stack.get(1) == StackElement::Key("foo")); assert!(stack.get(1) == StackElement::Key("foo"));

View file

@ -211,6 +211,7 @@ use std::string;
use std::ops; use std::ops;
use unicode::str as unicode_str; use unicode::str as unicode_str;
use unicode::str::Utf16Item; use unicode::str::Utf16Item;
use std::ops::Index as IndexOp;
use Encodable; use Encodable;
@ -386,7 +387,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
}; };
if start < i { if start < i {
try!(wr.write_str(v[start..i])); try!(wr.write_str(v.index(&(start..i))));
} }
try!(wr.write_str(escaped)); try!(wr.write_str(escaped));
@ -395,7 +396,7 @@ fn escape_str(wr: &mut fmt::Writer, v: &str) -> fmt::Result {
} }
if start != v.len() { if start != v.len() {
try!(wr.write_str(v[start..])); try!(wr.write_str(v.index(&(start..))));
} }
wr.write_str("\"") 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 { fn escape_char(writer: &mut fmt::Writer, v: char) -> fmt::Result {
let mut buf = [0; 4]; let mut buf = [0; 4];
let n = v.encode_utf8(&mut buf).unwrap(); 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) escape_str(writer, buf)
} }
@ -417,7 +418,7 @@ fn spaces(wr: &mut fmt::Writer, mut n: uint) -> fmt::Result {
} }
if n > 0 { if n > 0 {
wr.write_str(BUF[..n]) wr.write_str(BUF.index(&(..n)))
} else { } else {
Ok(()) Ok(())
} }
@ -624,7 +625,7 @@ impl<'a> ::Encoder<fmt::Error> for Encoder<'a> {
let mut check_encoder = Encoder::new(&mut buf); let mut check_encoder = Encoder::new(&mut buf);
try!(f(transmute(&mut check_encoder))); 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()) != '"'; let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.writer, "\"")); } if needs_wrapping { try!(write!(self.writer, "\"")); }
try!(f(self)); try!(f(self));
@ -893,7 +894,7 @@ impl<'a> ::Encoder<fmt::Error> for PrettyEncoder<'a> {
let mut check_encoder = PrettyEncoder::new(&mut buf); let mut check_encoder = PrettyEncoder::new(&mut buf);
try!(f(transmute(&mut check_encoder))); 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()) != '"'; let needs_wrapping = out.char_at(0) != '"' && out.char_at_reverse(out.len()) != '"';
if needs_wrapping { try!(write!(self.writer, "\"")); } if needs_wrapping { try!(write!(self.writer, "\"")); }
try!(f(self)); try!(f(self));
@ -1026,7 +1027,7 @@ impl Json {
/// Returns None otherwise. /// Returns None otherwise.
pub fn as_string<'a>(&'a self) -> Option<&'a str> { pub fn as_string<'a>(&'a self) -> Option<&'a str> {
match *self { match *self {
Json::String(ref s) => Some(s[]), Json::String(ref s) => Some(s.index(&FullRange)),
_ => None _ => None
} }
} }
@ -1220,7 +1221,8 @@ impl Stack {
InternalIndex(i) => Index(i), InternalIndex(i) => Index(i),
InternalKey(start, size) => { InternalKey(start, size) => {
Key(str::from_utf8( 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(&InternalIndex(i)) => Some(Index(i)),
Some(&InternalKey(start, size)) => { Some(&InternalKey(start, size)) => {
Some(Key(str::from_utf8( 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())) ).unwrap()))
} }
} }
@ -2139,7 +2141,7 @@ impl ::Decoder<DecoderError> for Decoder {
return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) 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, Some(idx) => idx,
None => return Err(UnknownVariantError(name)) None => return Err(UnknownVariantError(name))
}; };
@ -3352,7 +3354,7 @@ mod tests {
hm.insert(1, true); hm.insert(1, true);
let mut mem_buf = Vec::new(); let mut mem_buf = Vec::new();
write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); 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) { match from_str(json_str) {
Err(_) => panic!("Unable to parse json_str: {}", json_str), Err(_) => panic!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go _ => {} // it parsed and we are good to go
@ -3368,7 +3370,7 @@ mod tests {
hm.insert(1, true); hm.insert(1, true);
let mut mem_buf = Vec::new(); let mut mem_buf = Vec::new();
write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); 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) { match from_str(json_str) {
Err(_) => panic!("Unable to parse json_str: {}", json_str), Err(_) => panic!("Unable to parse json_str: {}", json_str),
_ => {} // it parsed and we are good to go _ => {} // it parsed and we are good to go
@ -3408,7 +3410,7 @@ mod tests {
write!(&mut writer, "{}", write!(&mut writer, "{}",
super::as_pretty_json(&json).indent(i)).unwrap(); 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 // Check for indents at each line
let lines: Vec<&str> = printed.lines().collect(); let lines: Vec<&str> = printed.lines().collect();

View file

@ -14,6 +14,7 @@
Core encoding and decoding interfaces. Core encoding and decoding interfaces.
*/ */
use std::ops::FullRange;
use std::path; use std::path;
use std::rc::Rc; use std::rc::Rc;
use std::cell::{Cell, RefCell}; use std::cell::{Cell, RefCell};
@ -308,7 +309,7 @@ impl<E, S:Encoder<E>> Encodable<S, E> for str {
impl<E, S:Encoder<E>> Encodable<S, E> for String { impl<E, S:Encoder<E>> Encodable<S, E> for String {
fn encode(&self, s: &mut S) -> Result<(), E> { fn encode(&self, s: &mut S) -> Result<(), E> {
s.emit_str(self[]) s.emit_str(self.index(&FullRange))
} }
} }

View file

@ -472,41 +472,37 @@ mod test {
writer.write(&[0, 1]).unwrap(); writer.write(&[0, 1]).unwrap();
let b: &[_] = &[]; let b: &[_] = &[];
assert_eq!(writer.get_ref()[], b); assert_eq!(&writer.get_ref()[], b);
writer.write(&[2]).unwrap(); writer.write(&[2]).unwrap();
let b: &[_] = &[0, 1]; let b: &[_] = &[0, 1];
assert_eq!(writer.get_ref()[], b); assert_eq!(&writer.get_ref()[], b);
writer.write(&[3]).unwrap(); writer.write(&[3]).unwrap();
assert_eq!(writer.get_ref()[], b); assert_eq!(&writer.get_ref()[], b);
writer.flush().unwrap(); writer.flush().unwrap();
let a: &[_] = &[0, 1, 2, 3]; let a: &[_] = &[0, 1, 2, 3];
assert_eq!(a, writer.get_ref()[]); assert_eq!(a, &writer.get_ref()[]);
writer.write(&[4]).unwrap(); writer.write(&[4]).unwrap();
writer.write(&[5]).unwrap(); writer.write(&[5]).unwrap();
assert_eq!(a, writer.get_ref()[]); assert_eq!(a, &writer.get_ref()[]);
writer.write(&[6]).unwrap(); writer.write(&[6]).unwrap();
let a: &[_] = &[0, 1, 2, 3, 4, 5]; let a: &[_] = &[0, 1, 2, 3, 4, 5];
assert_eq!(a, assert_eq!(a, &writer.get_ref()[]);
writer.get_ref()[]);
writer.write(&[7, 8]).unwrap(); writer.write(&[7, 8]).unwrap();
let a: &[_] = &[0, 1, 2, 3, 4, 5, 6]; let a: &[_] = &[0, 1, 2, 3, 4, 5, 6];
assert_eq!(a, assert_eq!(a, &writer.get_ref()[]);
writer.get_ref()[]);
writer.write(&[9, 10, 11]).unwrap(); writer.write(&[9, 10, 11]).unwrap();
let a: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]; let a: &[_] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
assert_eq!(a, assert_eq!(a, &writer.get_ref()[]);
writer.get_ref()[]);
writer.flush().unwrap(); writer.flush().unwrap();
assert_eq!(a, assert_eq!(a, &writer.get_ref()[]);
writer.get_ref()[]);
} }
#[test] #[test]
@ -514,7 +510,7 @@ mod test {
let mut w = BufferedWriter::with_capacity(3, Vec::new()); let mut w = BufferedWriter::with_capacity(3, Vec::new());
w.write(&[0, 1]).unwrap(); w.write(&[0, 1]).unwrap();
let a: &[_] = &[]; let a: &[_] = &[];
assert_eq!(a, w.get_ref()[]); assert_eq!(a, &w.get_ref()[]);
let w = w.into_inner(); let w = w.into_inner();
let a: &[_] = &[0, 1]; let a: &[_] = &[0, 1];
assert_eq!(a, w.index(&FullRange)); assert_eq!(a, w.index(&FullRange));
@ -559,21 +555,21 @@ mod test {
let mut writer = LineBufferedWriter::new(Vec::new()); let mut writer = LineBufferedWriter::new(Vec::new());
writer.write(&[0]).unwrap(); writer.write(&[0]).unwrap();
let b: &[_] = &[]; let b: &[_] = &[];
assert_eq!(writer.get_ref()[], b); assert_eq!(&writer.get_ref()[], b);
writer.write(&[1]).unwrap(); writer.write(&[1]).unwrap();
assert_eq!(writer.get_ref()[], b); assert_eq!(&writer.get_ref()[], b);
writer.flush().unwrap(); writer.flush().unwrap();
let b: &[_] = &[0, 1]; 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(); writer.write(&[0, b'\n', 1, b'\n', 2]).unwrap();
let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n']; 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(); writer.flush().unwrap();
let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2]; 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(); writer.write(&[3, b'\n']).unwrap();
let b: &[_] = &[0, 1, 0, b'\n', 1, b'\n', 2, 3, b'\n']; 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] #[test]

View file

@ -13,7 +13,7 @@
//! Readers and Writers for in-memory buffers //! Readers and Writers for in-memory buffers
use cmp::min; use cmp::min;
use prelude::Index; use prelude::v1::Index;
use option::Option::None; use option::Option::None;
use result::Result::{Err, Ok}; use result::Result::{Err, Ok};
use io; use io;
@ -391,9 +391,9 @@ impl<'a> Buffer for BufReader<'a> {
#[cfg(test)] #[cfg(test)]
mod test { mod test {
extern crate "test" as test_crate; extern crate "test" as test_crate;
use prelude::v1::*; use io::{SeekSet, SeekCur, SeekEnd, Reader, Writer, Seek};
use prelude::v1::{Ok, Err, range, Vec, Buffer, AsSlice, SliceExt};
use io::{SeekSet, SeekCur, SeekEnd}; use prelude::v1::{IteratorExt, Index};
use io; use io;
use iter::repeat; use iter::repeat;
use self::test_crate::Bencher; use self::test_crate::Bencher;

View file

@ -752,12 +752,12 @@ impl Drop for Process {
#[cfg(test)] #[cfg(test)]
mod tests { 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::fs::PathExtensions;
use io::process;
use io::timer::*; use io::timer::*;
use io::{Truncate, Write, TimedOut, timer, FileNotFound};
use rt::running_on_valgrind; use rt::running_on_valgrind;
use str; use str;
use super::{CreatePipe}; use super::{CreatePipe};

View file

@ -68,7 +68,7 @@ use fmt;
use iter::IteratorExt; use iter::IteratorExt;
use option::Option; use option::Option;
use option::Option::{None, Some}; use option::Option::{None, Some};
use prelude::{FullRange, Index}; use prelude::v1::{FullRange, Index};
use str; use str;
use str::StrExt; use str::StrExt;
use string::{String, CowString}; use string::{String, CowString};

View file

@ -24,7 +24,7 @@ use iter::{AdditiveIterator, Extend};
use iter::{Iterator, IteratorExt, Map, repeat}; use iter::{Iterator, IteratorExt, Map, repeat};
use mem; use mem;
use option::Option::{self, Some, None}; use option::Option::{self, Some, None};
use prelude::{FullRange, Index}; use prelude::v1::{FullRange, Index};
use slice::{SliceExt, SliceConcatExt}; use slice::{SliceExt, SliceConcatExt};
use str::{SplitTerminator, FromStr, StrExt}; use str::{SplitTerminator, FromStr, StrExt};
use string::{String, ToString}; use string::{String, ToString};
@ -337,8 +337,12 @@ impl GenericPath for Path {
Some(match self.sepidx_or_prefix_len() { Some(match self.sepidx_or_prefix_len() {
None if ".." == self.repr => self.repr.index(&FullRange), None if ".." == self.repr => self.repr.index(&FullRange),
None => ".", None => ".",
Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => self.repr.index(&FullRange), Some((_,idxa,end)) if self.repr.index(&(idxa..end)) == ".." => {
Some((idxb,_,end)) if self.repr.index(&(idxb..end)) == "\\" => self.repr.index(&FullRange), 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((0,idxa,_)) => self.repr.index(&(0..idxa)),
Some((idxb,idxa,_)) => { Some((idxb,idxa,_)) => {
match self.prefix { match self.prefix {

View file

@ -14,7 +14,8 @@
// Reexported core operators // Reexported core operators
#[stable] #[doc(no_inline)] pub use kinds::{Copy, Send, Sized, Sync}; #[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 // Reexported functions
#[stable] #[doc(no_inline)] pub use mem::drop; #[stable] #[doc(no_inline)] pub use mem::drop;

View file

@ -23,6 +23,7 @@
use dynamic_lib::DynamicLibrary; use dynamic_lib::DynamicLibrary;
use ffi; use ffi;
use core::ops::Index;
use intrinsics; use intrinsics;
use io::{IoResult, Writer}; use io::{IoResult, Writer};
use libc; use libc;
@ -361,7 +362,7 @@ pub fn write(w: &mut Writer) -> IoResult<()> {
let bytes = unsafe { ffi::c_str_to_bytes(&ptr) }; let bytes = unsafe { ffi::c_str_to_bytes(&ptr) };
match str::from_utf8(bytes) { match str::from_utf8(bytes) {
Ok(s) => try!(demangle(w, s)), 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])); try!(w.write(&['\n' as u8]));

View file

@ -206,7 +206,7 @@ impl<D: Decoder<E>, E> Decodable<D, E> for Ident {
#[cfg(not(stage0))] #[cfg(not(stage0))]
impl Decodable for Ident { impl Decodable for Ident {
fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> { fn decode<D: Decoder>(d: &mut D) -> Result<Ident, D::Error> {
Ok(str_to_ident(try!(d.read_str())[])) Ok(str_to_ident(try!(d.read_str()).index(&FullRange)))
} }
} }

View file

@ -332,7 +332,7 @@ pub fn cfg_matches(diagnostic: &SpanHandler, cfgs: &[P<MetaItem>], cfg: &ast::Me
!cfg_matches(diagnostic, cfgs, &*mis[0]) !cfg_matches(diagnostic, cfgs, &*mis[0])
} }
ast::MetaList(ref pred, _) => { 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 false
}, },
ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg), ast::MetaWord(_) | ast::MetaNameValue(..) => contains(cfgs, cfg),

View file

@ -29,12 +29,13 @@ pub fn expand_deriving_bound<F>(cx: &mut ExtCtxt,
"Send" | "Sync" => { "Send" | "Sync" => {
return cx.span_err(span, return cx.span_err(span,
format!("{} is an unsafe trait and it \ format!("{} is an unsafe trait and it \
should be implemented explicitly", *tname).index(&FullRange)) should be implemented explicitly",
*tname).as_slice())
} }
ref tname => { ref tname => {
cx.span_bug(span, cx.span_bug(span,
format!("expected built-in trait name but \ format!("expected built-in trait name but \
found {}", *tname).index(&FullRange)) found {}", *tname).as_slice())
} }
} }
}, },

View file

@ -386,7 +386,7 @@ pub fn parse(sess: &ParseSess,
new_ei.idx += 1u; new_ei.idx += 1u;
//we specifically matched zero repeats. //we specifically matched zero repeats.
for idx in range(ei.match_cur, ei.match_cur + seq.num_captures) { 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); cur_eis.push(new_ei);

View file

@ -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") { "unsafe_destructor") {
self.gate_feature("unsafe_destructor", self.gate_feature("unsafe_destructor",
i.span, i.span,
@ -287,7 +287,7 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
removed in the future"); removed in the future");
} }
if attr::contains_name(i.attrs[], if attr::contains_name(i.attrs.index(&FullRange),
"old_orphan_check") { "old_orphan_check") {
self.gate_feature( self.gate_feature(
"old_orphan_check", "old_orphan_check",
@ -309,7 +309,8 @@ impl<'a, 'v> Visitor<'v> for PostExpansionVisitor<'a> {
and not portable across platforms") 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."), Some(val) => val.get().starts_with("llvm."),
_ => false _ => false
}; };

View file

@ -1167,10 +1167,10 @@ mod test {
for &src in srcs.iter() { for &src in srcs.iter() {
let spans = get_spans_of_pat_idents(src); let spans = get_spans_of_pat_idents(src);
let Span{lo:lo,hi:hi,..} = spans[0]; let Span{ lo, hi, .. } = spans[0];
assert!("self" == src[lo.to_uint()..hi.to_uint()], assert!("self" == &src[lo.to_uint()..hi.to_uint()],
"\"{}\" != \"self\". src=\"{}\"", "\"{}\" != \"self\". src=\"{}\"",
src[lo.to_uint()..hi.to_uint()], src) &src[lo.to_uint()..hi.to_uint()], src)
} }
} }

View file

@ -1726,7 +1726,7 @@ impl<'a> Parser<'a> {
token::Str_(s) => { token::Str_(s) => {
(true, (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)) ast::CookedStr))
} }
token::StrRaw(s, n) => { token::StrRaw(s, n) => {
@ -2538,16 +2538,26 @@ impl<'a> Parser<'a> {
token::OpenDelim(token::Bracket) => { token::OpenDelim(token::Bracket) => {
let bracket_pos = self.span.lo; let bracket_pos = self.span.lo;
self.bump(); 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 // No expression, expand to a FullRange
let ix = { // FIXME(#20516) It would be better to use a lang item or
hi = self.last_span.hi; // something for FullRange.
let range = ExprStruct(ident_to_path(mk_sp(lo, hi), hi = self.last_span.hi;
token::special_idents::FullRange), let range = ExprStruct(ident_to_path(mk_sp(lo, hi),
vec![], token::special_idents::FullRange),
None); vec![],
self.mk_expr(bracket_pos, hi, range) None);
}; let ix = self.mk_expr(bracket_pos, hi, range);
let index = self.mk_index(e, ix); let index = self.mk_index(e, ix);
e = self.mk_expr(lo, hi, index) e = self.mk_expr(lo, hi, index)
} else { } else {
@ -2557,6 +2567,12 @@ impl<'a> Parser<'a> {
let index = self.mk_index(e, ix); let index = self.mk_index(e, ix);
e = self.mk_expr(lo, hi, index) 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..`. // A range expression, either `expr..expr` or `expr..`.
@ -4881,7 +4897,7 @@ impl<'a> Parser<'a> {
let token_str = self.this_token_to_string(); let token_str = self.this_token_to_string();
self.fatal(format!("expected `where`, or `{}` after struct \ self.fatal(format!("expected `where`, or `{}` after struct \
name, found `{}`", "{", name, found `{}`", "{",
token_str)[]); token_str).index(&FullRange));
} }
fields fields

View file

@ -689,8 +689,7 @@ impl<D:Decoder<E>, E> Decodable<D, E> for InternedString {
#[cfg(not(stage0))] #[cfg(not(stage0))]
impl Decodable for InternedString { impl Decodable for InternedString {
fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> { fn decode<D: Decoder>(d: &mut D) -> Result<InternedString, D::Error> {
Ok(get_name(get_ident_interner().intern( Ok(get_name(get_ident_interner().intern(try!(d.read_str()).index(&FullRange))))
try!(d.read_str())[])))
} }
} }
@ -704,7 +703,7 @@ impl<S:Encoder<E>, E> Encodable<S, E> for InternedString {
#[cfg(not(stage0))] #[cfg(not(stage0))]
impl Encodable for InternedString { impl Encodable for InternedString {
fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> { fn encode<S: Encoder>(&self, s: &mut S) -> Result<(), S::Error> {
s.emit_str(self.string[]) s.emit_str(self.string.index(&FullRange))
} }
} }

View file

@ -1537,35 +1537,34 @@ impl<'a> State<'a> {
ast::ExprStruct(ref path, ref fields, ref wth) => { ast::ExprStruct(ref path, ref fields, ref wth) => {
try!(self.print_path(path, true)); try!(self.print_path(path, true));
if fields.is_empty() && wth.is_none() { if !(fields.is_empty() && wth.is_none()) {
return; try!(word(&mut self.s, "{"));
} try!(self.commasep_cmnt(
try!(word(&mut self.s, "{")); Consistent,
try!(self.commasep_cmnt( fields.index(&FullRange),
Consistent, |s, field| {
fields.index(&FullRange), try!(s.ibox(indent_unit));
|s, field| { try!(s.print_ident(field.ident.node));
try!(s.ibox(indent_unit)); try!(s.word_space(":"));
try!(s.print_ident(field.ident.node)); try!(s.print_expr(&*field.expr));
try!(s.word_space(":")); s.end()
try!(s.print_expr(&*field.expr)); },
s.end() |f| f.span));
}, match *wth {
|f| f.span)); Some(ref expr) => {
match *wth { try!(self.ibox(indent_unit));
Some(ref expr) => { if !fields.is_empty() {
try!(self.ibox(indent_unit)); try!(word(&mut self.s, ","));
if !fields.is_empty() { try!(space(&mut self.s));
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!(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, "}"));
} }
ast::ExprTup(ref exprs) => { ast::ExprTup(ref exprs) => {
try!(self.popen()); try!(self.popen());
@ -2781,7 +2780,7 @@ impl<'a> State<'a> {
format!("-{}", istr).index(&FullRange)) format!("-{}", istr).index(&FullRange))
} }
ast::UnsignedIntLit(ut) => { 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) => { ast::UnsuffixedIntLit(ast::Plus) => {
word(&mut self.s, format!("{}", i).index(&FullRange)) word(&mut self.s, format!("{}", i).index(&FullRange))

View file

@ -105,7 +105,7 @@ impl Perm {
let d = idx / self.fact[i] as i32; let d = idx / self.fact[i] as i32;
self.cnt[i] = d; self.cnt[i] = d;
idx %= self.fact[i] as i32; 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 *place = (*val) as u8
} }

View file

@ -99,7 +99,7 @@ fn make_fasta<W: Writer, I: Iterator<Item=u8>>(
} }
n -= nb; n -= nb;
line[nb] = '\n' as u8; line[nb] = '\n' as u8;
try!(wr.write(line[..nb+1])); try!(wr.write(&line[..(nb+1)]));
} }
Ok(()) Ok(())
} }

View file

@ -101,11 +101,11 @@ fn windows_with_carry<F>(bb: &[u8], nn: uint, mut it: F) -> Vec<u8> where
let len = bb.len(); let len = bb.len();
while ii < len - (nn - 1u) { while ii < len - (nn - 1u) {
it(bb[ii..ii+nn]); it(&bb[ii..(ii+nn)]);
ii += 1u; ii += 1u;
} }
return bb[len - (nn - 1u)..len].to_vec(); return bb[(len - (nn - 1u))..len].to_vec();
} }
fn make_sequence_processor(sz: uint, fn make_sequence_processor(sz: uint,

View file

@ -17,12 +17,12 @@ fn takes_imm_elt<F>(_v: &int, f: F) where F: FnOnce() {
} }
fn has_mut_vec_and_does_not_try_to_change_it() { fn has_mut_vec_and_does_not_try_to_change_it() {
let mut v = vec!(1, 2, 3); let mut v: Vec<int> = vec!(1, 2, 3);
takes_imm_elt(&v[0], || {}) takes_imm_elt(&v[0], || {})
} }
fn has_mut_vec_but_tries_to_change_it() { fn has_mut_vec_but_tries_to_change_it() {
let mut v = vec!(1, 2, 3); let mut v: Vec<int> = vec!(1, 2, 3);
takes_imm_elt( takes_imm_elt(
&v[0], &v[0],
|| { //~ ERROR cannot borrow `v` as mutable || { //~ ERROR cannot borrow `v` as mutable

View file

@ -13,7 +13,8 @@
fn main() { fn main() {
fn bar<T>(_: T) {} fn bar<T>(_: T) {}
[0][0u8]; //~ ERROR: mismatched types [0][0u8]; //~ ERROR: the trait `core::ops::Index<u8>` is not implemented
//~^ ERROR: the trait `core::ops::Index<u8>` is not implemented
[0][0]; // should infer to be a uint [0][0]; // should infer to be a uint

View file

@ -11,16 +11,24 @@
pub fn main() { pub fn main() {
let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5); let v: Vec<int> = vec!(0, 1, 2, 3, 4, 5);
let s: String = "abcdef".to_string(); let s: String = "abcdef".to_string();
assert_eq!(v.as_slice()[3u], 3); v.as_slice()[3u];
assert_eq!(v.as_slice()[3u8], 3); //~ ERROR: mismatched types v.as_slice()[3];
assert_eq!(v.as_slice()[3i8], 3); //~ ERROR: mismatched types v.as_slice()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented
assert_eq!(v.as_slice()[3u32], 3); //~ ERROR: mismatched types //~^ ERROR the trait `core::ops::Index<u8>` is not implemented
assert_eq!(v.as_slice()[3i32], 3); //~ ERROR: mismatched types v.as_slice()[3i8]; //~ERROR the trait `core::ops::Index<i8>` is not implemented
println!("{}", v.as_slice()[3u8]); //~ ERROR: mismatched types //~^ ERROR the trait `core::ops::Index<i8>` is not implemented
assert_eq!(s.as_bytes()[3u], 'd' as u8); v.as_slice()[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
assert_eq!(s.as_bytes()[3u8], 'd' as u8); //~ ERROR: mismatched types //~^ ERROR the trait `core::ops::Index<u32>` is not implemented
assert_eq!(s.as_bytes()[3i8], 'd' as u8); //~ ERROR: mismatched types v.as_slice()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
assert_eq!(s.as_bytes()[3u32], 'd' as u8); //~ ERROR: mismatched types //~^ ERROR the trait `core::ops::Index<i32>` is not implemented
assert_eq!(s.as_bytes()[3i32], 'd' as u8); //~ ERROR: mismatched types s.as_bytes()[3u];
println!("{}", s.as_bytes()[3u8]); //~ ERROR: mismatched types s.as_bytes()[3];
s.as_bytes()[3u8]; //~ERROR the trait `core::ops::Index<u8>` is not implemented
//~^ERROR the trait `core::ops::Index<u8>` is not implemented
s.as_bytes()[3i8]; //~ERROR the trait `core::ops::Index<i8>` is not implemented
//~^ERROR the trait `core::ops::Index<i8>` is not implemented
s.as_bytes()[3u32]; //~ERROR the trait `core::ops::Index<u32>` is not implemented
//~^ERROR the trait `core::ops::Index<u32>` is not implemented
s.as_bytes()[3i32]; //~ERROR the trait `core::ops::Index<i32>` is not implemented
//~^ERROR the trait `core::ops::Index<i32>` is not implemented
} }

View file

@ -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 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, 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<u8> =
Slice { //~ ERROR use of trait `Slice` as a struct constructor [E0159]
data: nil,
len: 0,
};
}
}

View file

@ -16,8 +16,8 @@ struct Foo;
fn main() { fn main() {
let x = Foo; let x = Foo;
&x[]; //~ ERROR cannot take a slice of a value with type `Foo` &x[]; //~ ERROR cannot index a value of type `Foo`
&x[Foo..]; //~ ERROR cannot take a slice of a value with type `Foo` &x[Foo..]; //~ ERROR cannot index a value of type `Foo`
&x[0..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` &x[..Foo]; //~ ERROR cannot index a value of type `Foo`
&x[Foo..Foo]; //~ ERROR cannot take a slice of a value with type `Foo` &x[Foo..Foo]; //~ ERROR cannot index a value of type `Foo`
} }

View file

@ -16,5 +16,5 @@ fn main() {
let x: &[int] = &[1, 2, 3, 4, 5]; let x: &[int] = &[1, 2, 3, 4, 5];
// Can't mutably slice an immutable slice // Can't mutably slice an immutable slice
let slice: &mut [int] = &mut [0, 1]; 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
} }

View file

@ -15,5 +15,5 @@
fn main() { fn main() {
let x: &[int] = &[1, 2, 3, 4, 5]; let x: &[int] = &[1, 2, 3, 4, 5];
// Immutable slices are not mutable. // 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
} }

View file

@ -10,5 +10,6 @@
pub fn main() { pub fn main() {
let s: &str = "hello"; 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
} }

View file

@ -15,7 +15,7 @@ fn main() {
let ss: &&[int] = &s; let ss: &&[int] = &s;
let sss: &&&[int] = &ss; let sss: &&&[int] = &ss;
println!("{}", s.index(&(0..3))); println!("{}", &s[0..3]);
println!("{}", ss.index(&(3..))); println!("{}", &ss[3..]);
println!("{}", sss.index(&(2..4))); println!("{}", &sss[2..4]);
} }

View file

@ -11,7 +11,7 @@
#![feature(slicing_syntax)] #![feature(slicing_syntax)]
fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] { fn vec_peek<'r, T>(v: &'r [T]) -> &'r [T] {
v.index(&(1..5)) &v[1..5]
} }
pub fn main() {} pub fn main() {}

View file

@ -10,6 +10,6 @@
#![feature(slicing_syntax)] #![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() {} pub fn main() {}

View file

@ -18,7 +18,7 @@ pub fn main() {
let abc = [1i, 2, 3]; let abc = [1i, 2, 3];
let tf = [true, false]; let tf = [true, false];
let x = [(), ()]; 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(&abc[], "[1, 2, 3]".to_string());
assert_repr_eq(&tf[], "[true, false]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string());

View file

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // 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)] #![feature(slicing_syntax)]
@ -24,7 +24,7 @@ impl Drop for Foo {
fn foo() { fn foo() {
let x: &[_] = &[Foo, Foo]; let x: &[_] = &[Foo, Foo];
x.index(&(3..4)); &x[3..4];
} }
fn main() { fn main() {

View file

@ -8,7 +8,7 @@
// option. This file may not be copied, modified, or distributed // option. This file may not be copied, modified, or distributed
// except according to those terms. // 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)] #![feature(slicing_syntax)]
@ -28,7 +28,7 @@ fn bar() -> uint {
fn foo() { fn foo() {
let x: &[_] = &[Foo, Foo]; let x: &[_] = &[Foo, Foo];
x[3..bar()]; &x[3..bar()];
} }
fn main() { fn main() {

View file

@ -11,6 +11,7 @@
// Test slicing sugar. // Test slicing sugar.
#![feature(slicing_syntax)] #![feature(slicing_syntax)]
#![feature(associated_types)]
extern crate core; extern crate core;
use core::ops::{Index, Range, RangeTo, RangeFrom, FullRange}; use core::ops::{Index, Range, RangeTo, RangeFrom, FullRange};
@ -19,49 +20,70 @@ static mut COUNT: uint = 0;
struct Foo; struct Foo;
impl Slice<Foo, Foo> for Foo { impl Index<Range<Foo>> for Foo {
fn as_slice_<'a>(&'a self) -> &'a Foo { type Output = Foo;
fn index(&self, index: &Range<Foo>) -> &Foo {
unsafe { COUNT += 1; } unsafe { COUNT += 1; }
self self
} }
fn slice_from_or_fail<'a>(&'a self, _from: &Foo) -> &'a Foo { }
impl Index<RangeTo<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: &RangeTo<Foo>) -> &Foo {
unsafe { COUNT += 1; } unsafe { COUNT += 1; }
self self
} }
fn slice_to_or_fail<'a>(&'a self, _to: &Foo) -> &'a Foo { }
impl Index<RangeFrom<Foo>> for Foo {
type Output = Foo;
fn index(&self, index: &RangeFrom<Foo>) -> &Foo {
unsafe { COUNT += 1; } unsafe { COUNT += 1; }
self self
} }
fn slice_or_fail<'a>(&'a self, _from: &Foo, _to: &Foo) -> &'a Foo { }
impl Index<FullRange> for Foo {
type Output = Foo;
fn index(&self, _index: &FullRange) -> &Foo {
unsafe { COUNT += 1; } unsafe { COUNT += 1; }
self self
} }
} }
impl SliceMut<Foo, Foo> for Foo { impl IndexMut<Range<Foo>> for Foo {
fn as_mut_slice_<'a>(&'a mut self) -> &'a mut Foo { type Output = Foo;
unsafe { COUNT += 1; } fn index_mut(&mut self, index: &Range<Foo>) -> &mut Foo {
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 {
unsafe { COUNT += 1; } unsafe { COUNT += 1; }
self self
} }
} }
impl IndexMut<RangeTo<Foo>> for Foo {
type Output = Foo;
fn index_mut(&mut self, index: &RangeTo<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<RangeFrom<Foo>> for Foo {
type Output = Foo;
fn index_mut(&mut self, index: &RangeFrom<Foo>) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
impl IndexMut<FullRange> for Foo {
type Output = Foo;
fn index_mut(&mut self, _index: &FullRange) -> &mut Foo {
unsafe { COUNT += 1; }
self
}
}
fn main() { fn main() {
let mut x = Foo; let mut x = Foo;
&x[]; &x[];
&x[Foo..]; &x[Foo..];
&x[0..Foo]; &x[..Foo];
&x[Foo..Foo]; &x[Foo..Foo];
&mut x[]; &mut x[];
&mut x[Foo..]; &mut x[Foo..];