]> git.lizzy.rs Git - rust.git/commitdiff
Auto merge of #26957 - wesleywiser:rename_connect_to_join, r=alexcrichton
authorbors <bors@rust-lang.org>
Sun, 12 Jul 2015 22:05:59 +0000 (22:05 +0000)
committerbors <bors@rust-lang.org>
Sun, 12 Jul 2015 22:05:59 +0000 (22:05 +0000)
Fixes #26900

94 files changed:
mk/cfg/i686-unknown-freebsd.mk [new file with mode: 0644]
src/compiletest/compiletest.rs
src/liballoc/boxed.rs
src/libcollections/slice.rs
src/libcollections/str.rs
src/libcollections/string.rs
src/libcollections/vec_deque.rs
src/libcollectionstest/lib.rs
src/libcollectionstest/slice.rs
src/libcollectionstest/str.rs
src/libcollectionstest/string.rs
src/libcore/fmt/builders.rs
src/libcore/fmt/mod.rs
src/libcore/num/mod.rs
src/libcore/option.rs
src/libcore/slice.rs
src/libgetopts/lib.rs
src/liblibc/lib.rs
src/librustc/diagnostics.rs
src/librustc/lib.rs
src/librustc/metadata/csearch.rs
src/librustc/metadata/decoder.rs
src/librustc/metadata/encoder.rs
src/librustc/metadata/tydecode.rs
src/librustc/metadata/tyencode.rs
src/librustc/middle/cast.rs
src/librustc/middle/check_match.rs
src/librustc/middle/expr_use_visitor.rs
src/librustc/middle/implicator.rs
src/librustc/middle/infer/combine.rs
src/librustc/middle/infer/error_reporting.rs
src/librustc/middle/infer/higher_ranked/mod.rs
src/librustc/middle/infer/mod.rs
src/librustc/middle/infer/region_inference/mod.rs
src/librustc/middle/infer/resolve.rs
src/librustc/middle/mem_categorization.rs
src/librustc/middle/traits/mod.rs
src/librustc/middle/traits/project.rs
src/librustc/middle/traits/select.rs
src/librustc/middle/ty.rs
src/librustc/middle/ty_fold.rs
src/librustc/middle/ty_match.rs
src/librustc/middle/ty_relate/mod.rs
src/librustc/util/ppaux.rs
src/librustc_back/target/i686_unknown_freebsd.rs [new file with mode: 0644]
src/librustc_back/target/mod.rs
src/librustc_resolve/build_reduced_graph.rs
src/librustc_resolve/lib.rs
src/librustc_trans/trans/adt.rs
src/librustc_trans/trans/attributes.rs
src/librustc_trans/trans/common.rs
src/librustc_trans/trans/consts.rs
src/librustc_trans/trans/debuginfo/metadata.rs
src/librustc_trans/trans/debuginfo/type_names.rs
src/librustc_trans/trans/expr.rs
src/librustc_trans/trans/tvec.rs
src/librustc_trans/trans/type_of.rs
src/librustc_typeck/astconv.rs
src/librustc_typeck/check/_match.rs
src/librustc_typeck/check/cast.rs
src/librustc_typeck/check/coercion.rs
src/librustc_typeck/check/demand.rs
src/librustc_typeck/check/method/confirm.rs
src/librustc_typeck/check/method/mod.rs
src/librustc_typeck/check/method/probe.rs
src/librustc_typeck/check/mod.rs
src/librustc_typeck/check/wf.rs
src/librustc_typeck/check/writeback.rs
src/librustc_typeck/coherence/mod.rs
src/librustc_typeck/coherence/orphan.rs
src/librustc_typeck/collect.rs
src/librustc_typeck/lib.rs
src/librustc_typeck/variance.rs
src/librustdoc/clean/mod.rs
src/librustdoc/html/layout.rs
src/librustdoc/html/static/main.css
src/librustdoc/html/static/main.js
src/librustdoc/html/static/playpen.js
src/librustdoc/lib.rs
src/librustdoc/passes.rs
src/libstd/array.rs
src/libstd/ffi/c_str.rs
src/libstd/fs.rs
src/libstd/io/buffered.rs
src/libstd/io/error.rs
src/libstd/io/prelude.rs
src/libstd/io/stdio.rs
src/libstd/io/util.rs
src/libstd/sys/common/stack.rs
src/libstd/sys/unix/fs.rs
src/libstd/sys/windows/c.rs
src/libstd/sys/windows/fs.rs
src/libtest/lib.rs
src/rust-installer

diff --git a/mk/cfg/i686-unknown-freebsd.mk b/mk/cfg/i686-unknown-freebsd.mk
new file mode 100644 (file)
index 0000000..0ac0ca9
--- /dev/null
@@ -0,0 +1,22 @@
+# i686-unknown-freebsd configuration
+CC_i686-unknown-freebsd=$(CC)
+CXX_i686-unknown-freebsd=$(CXX)
+CPP_i686-unknown-freebsd=$(CPP)
+AR_i686-unknown-freebsd=$(AR)
+CFG_LIB_NAME_i686-unknown-freebsd=lib$(1).so
+CFG_STATIC_LIB_NAME_i686-unknown-freebsd=lib$(1).a
+CFG_LIB_GLOB_i686-unknown-freebsd=lib$(1)-*.so
+CFG_LIB_DSYM_GLOB_i686-unknown-freebsd=$(1)-*.dylib.dSYM
+CFG_JEMALLOC_CFLAGS_i686-unknown-freebsd := -m32 -arch i386 -I/usr/local/include $(CFLAGS)
+CFG_GCCISH_CFLAGS_i686-unknown-freebsd := -Wall -Werror -g -fPIC -m32 -arch i386 -I/usr/local/include $(CFLAGS)
+CFG_GCCISH_LINK_FLAGS_i686-unknown-freebsd := -m32 -shared -fPIC -g -pthread -lrt
+CFG_GCCISH_DEF_FLAG_i686-unknown-freebsd := -Wl,--export-dynamic,--dynamic-list=
+CFG_LLC_FLAGS_i686-unknown-freebsd :=
+CFG_INSTALL_NAME_i686-unknown-freebsd =
+CFG_EXE_SUFFIX_i686-unknown-freebsd :=
+CFG_WINDOWSY_i686-unknown-freebsd :=
+CFG_UNIXY_i686-unknown-freebsd := 1
+CFG_LDPATH_i686-unknown-freebsd :=
+CFG_RUN_i686-unknown-freebsd=$(2)
+CFG_RUN_TARG_i686-unknown-freebsd=$(call CFG_RUN_i686-unknown-freebsd,,$(2))
+CFG_GNU_TRIPLE_i686-unknown-freebsd := i686-unknown-freebsd
index 92a94d23f0842afe1412f48626b7f3f4da18e642..36c676391019bd1ad44a078aede726784cf786ee 100644 (file)
@@ -15,7 +15,7 @@
 #![feature(libc)]
 #![feature(path_ext)]
 #![feature(rustc_private)]
-#![feature(slice_extras)]
+#![feature(slice_splits)]
 #![feature(str_char)]
 #![feature(test)]
 #![feature(vec_push_all)]
@@ -90,9 +90,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
           optopt("", "lldb-python-dir", "directory containing LLDB's python module", "PATH"),
           optflag("h", "help", "show this message"));
 
-    assert!(!args.is_empty());
-    let argv0 = args[0].clone();
-    let args_ = args.tail();
+    let (argv0, args_) = args.split_first().unwrap();
     if args[1] == "-h" || args[1] == "--help" {
         let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
         println!("{}", getopts::usage(&message, &groups));
index c941629b871ef418566ee87c4dda4ef4ba3bac7d..3dfd10f09167be7b6c3a26d6841284c74e986471 100644 (file)
@@ -71,7 +71,7 @@
 /// The following two examples are equivalent:
 ///
 /// ```
-/// # #![feature(box_heap)]
+/// #![feature(box_heap)]
 /// #![feature(box_syntax)]
 /// use std::boxed::HEAP;
 ///
@@ -162,7 +162,7 @@ pub fn into_raw(b: Box<T>) -> *mut T {
 ///
 /// # Examples
 /// ```
-/// # #![feature(box_raw)]
+/// #![feature(box_raw)]
 /// use std::boxed;
 ///
 /// let seventeen = Box::new(17u32);
index 85a4d6f192ee7c0bf13d7a86af2f954609f52889..f5a27565ef7dec67a8ddb7a1e750478470d96122 100644 (file)
@@ -282,34 +282,65 @@ pub fn first_mut(&mut self) -> Option<&mut T> {
 
     /// Returns all but the first element of a slice.
     #[unstable(feature = "slice_extras", reason = "likely to be renamed")]
+    #[deprecated(since = "1.3.0", reason = "superseded by split_first")]
     #[inline]
     pub fn tail(&self) -> &[T] {
         core_slice::SliceExt::tail(self)
     }
 
+    /// Returns the first and all the rest of the elements of a slice.
+    #[unstable(feature = "slice_splits", reason = "new API")]
+    #[inline]
+    pub fn split_first(&self) -> Option<(&T, &[T])> {
+        core_slice::SliceExt::split_first(self)
+    }
+
     /// Returns all but the first element of a mutable slice
-    #[unstable(feature = "slice_extras",
-               reason = "likely to be renamed or removed")]
+    #[unstable(feature = "slice_extras", reason = "likely to be renamed or removed")]
+    #[deprecated(since = "1.3.0", reason = "superseded by split_first_mut")]
     #[inline]
     pub fn tail_mut(&mut self) -> &mut [T] {
         core_slice::SliceExt::tail_mut(self)
     }
 
+    /// Returns the first and all the rest of the elements of a slice.
+    #[unstable(feature = "slice_splits", reason = "new API")]
+    #[inline]
+    pub fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
+        core_slice::SliceExt::split_first_mut(self)
+    }
+
     /// Returns all but the last element of a slice.
     #[unstable(feature = "slice_extras", reason = "likely to be renamed")]
+    #[deprecated(since = "1.3.0", reason = "superseded by split_last")]
     #[inline]
     pub fn init(&self) -> &[T] {
         core_slice::SliceExt::init(self)
     }
 
+    /// Returns the last and all the rest of the elements of a slice.
+    #[unstable(feature = "slice_splits", reason = "new API")]
+    #[inline]
+    pub fn split_last(&self) -> Option<(&T, &[T])> {
+        core_slice::SliceExt::split_last(self)
+
+    }
+
     /// Returns all but the last element of a mutable slice
-    #[unstable(feature = "slice_extras",
-               reason = "likely to be renamed or removed")]
+    #[unstable(feature = "slice_extras", reason = "likely to be renamed or removed")]
+    #[deprecated(since = "1.3.0", reason = "superseded by split_last_mut")]
     #[inline]
     pub fn init_mut(&mut self) -> &mut [T] {
         core_slice::SliceExt::init_mut(self)
     }
 
+    /// Returns the last and all the rest of the elements of a slice.
+    #[unstable(feature = "slice_splits", since = "1.3.0")]
+    #[inline]
+    pub fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
+        core_slice::SliceExt::split_last_mut(self)
+    }
+
     /// Returns the last element of a slice, or `None` if it is empty.
     ///
     /// # Examples
index 7e4a219fc422f4f06917a412458941918eb53eb5..f92db5353b39ebb997d8799f726c70983d2d7855 100644 (file)
@@ -61,6 +61,7 @@
 use core::str as core_str;
 use core::str::pattern::Pattern;
 use core::str::pattern::{Searcher, ReverseSearcher, DoubleEndedSearcher};
+use core::mem;
 use rustc_unicode::str::{UnicodeStr, Utf16Encoder};
 
 use vec_deque::VecDeque;
@@ -69,6 +70,7 @@
 use rustc_unicode;
 use vec::Vec;
 use slice::SliceConcatExt;
+use boxed::Box;
 
 pub use core::str::{FromStr, Utf8Error};
 pub use core::str::{Lines, LinesAny, CharRange};
 pub use rustc_unicode::str::{SplitWhitespace, Words, Graphemes, GraphemeIndices};
 pub use core::str::pattern;
 
-/*
-Section: Creating a string
-*/
-
 impl<S: Borrow<str>> SliceConcatExt<str> for [S] {
     type Output = String;
 
@@ -138,10 +136,6 @@ fn connect(&self, sep: &str) -> String {
     }
 }
 
-/*
-Section: Iterators
-*/
-
 // Helper functions used for Unicode normalization
 fn canonical_sort(comb: &mut [(char, u8)]) {
     let len = comb.len();
@@ -386,10 +380,6 @@ fn next(&mut self) -> Option<u16> { self.encoder.next() }
     fn size_hint(&self) -> (usize, Option<usize>) { self.encoder.size_hint() }
 }
 
-/*
-Section: Misc
-*/
-
 // Return the initial codepoint accumulator for the first byte.
 // The first byte is special, only want bottom 5 bits for width 2, 4 bits
 // for width 3, and 3 bits for width 4
@@ -418,15 +408,6 @@ fn to_owned(&self) -> String {
     }
 }
 
-/*
-Section: CowString
-*/
-
-/*
-Section: Trait implementations
-*/
-
-
 /// Any string that can be represented as a slice.
 #[lang = "str"]
 #[cfg(not(test))]
@@ -1928,4 +1909,14 @@ pub fn escape_default(&self) -> String {
     pub fn escape_unicode(&self) -> String {
         self.chars().flat_map(|c| c.escape_unicode()).collect()
     }
+
+    /// Converts the `Box<str>` into a `String` without copying or allocating.
+    #[unstable(feature = "box_str",
+               reason = "recently added, matches RFC")]
+    pub fn into_string(self: Box<str>) -> String {
+        unsafe {
+            let slice = mem::transmute::<Box<str>, Box<[u8]>>(self);
+            String::from_utf8_unchecked(slice.into_vec())
+        }
+    }
 }
index 6b20d6e2a3f9b99587acdae98ef3ae69a8165439..ef1d9b08b4a9a6d4b5b5328c5529f9c71bd4db62 100644 (file)
@@ -29,6 +29,7 @@
 use range::RangeArgument;
 use str::{self, FromStr, Utf8Error, Chars};
 use vec::{DerefVec, Vec, as_vec};
+use boxed::Box;
 
 /// A growable string stored as a UTF-8 encoded buffer.
 #[derive(Clone, PartialOrd, Eq, Ord)]
@@ -741,6 +742,16 @@ pub fn drain<R>(&mut self, range: R) -> Drain where R: RangeArgument<usize> {
             string: self_ptr,
         }
     }
+
+    /// Converts the string into `Box<str>`.
+    ///
+    /// Note that this will drop any excess capacity.
+    #[unstable(feature = "box_str",
+               reason = "recently added, matches RFC")]
+    pub fn into_boxed_slice(self) -> Box<str> {
+        let slice = self.vec.into_boxed_slice();
+        unsafe { mem::transmute::<Box<[u8]>, Box<str>>(slice) }
+    }
 }
 
 impl FromUtf8Error {
index 2aeb303068bdf108c474e786ff7e618a04572161..117b3544f0269a68cc6c86fbd24dea7e0986534c 100644 (file)
@@ -108,7 +108,7 @@ unsafe fn buffer_write(&mut self, off: usize, t: T) {
         ptr::write(self.ptr.offset(off as isize), t);
     }
 
-    /// Returns true iff the buffer is at capacity
+    /// Returns true if and only if the buffer is at capacity
     #[inline]
     fn is_full(&self) -> bool { self.cap - self.len() == 1 }
 
index ba1b4964b49a3cc08ba20deba84202e209fd494d..6bf7380fdeb500138cc923157607184a17f7c39d 100644 (file)
@@ -36,7 +36,7 @@
 #![feature(rustc_private)]
 #![feature(slice_bytes)]
 #![feature(slice_chars)]
-#![feature(slice_extras)]
+#![feature(slice_splits)]
 #![feature(slice_position_elem)]
 #![feature(split_off)]
 #![feature(step_by)]
@@ -44,6 +44,7 @@
 #![feature(str_escape)]
 #![feature(str_match_indices)]
 #![feature(str_utf16)]
+#![feature(box_str)]
 #![feature(subslice_offset)]
 #![feature(test)]
 #![feature(unboxed_closures)]
 #![feature(vec_deque_retain)]
 #![feature(vec_from_raw_buf)]
 #![feature(vec_push_all)]
-#![feature(vec_split_off)]
 #![feature(vecmap)]
 
+#![allow(deprecated)]
+
 #[macro_use] extern crate log;
 
 extern crate collections;
index 436e71fd4a0ed1ef6337fa5ccec99585b42379d8..c0ab11380d9f6228d24c480599ddd7621280f261 100644 (file)
@@ -119,71 +119,48 @@ fn test_first_mut() {
 }
 
 #[test]
-fn test_tail() {
+fn test_split_first() {
     let mut a = vec![11];
     let b: &[i32] = &[];
-    assert_eq!(a.tail(), b);
+    assert!(b.split_first().is_none());
+    assert_eq!(a.split_first(), Some((&11, b)));
     a = vec![11, 12];
     let b: &[i32] = &[12];
-    assert_eq!(a.tail(), b);
+    assert_eq!(a.split_first(), Some((&11, b)));
 }
 
 #[test]
-fn test_tail_mut() {
+fn test_split_first_mut() {
     let mut a = vec![11];
     let b: &mut [i32] = &mut [];
-    assert!(a.tail_mut() == b);
+    assert!(b.split_first_mut().is_none());
+    assert!(a.split_first_mut() == Some((&mut 11, b)));
     a = vec![11, 12];
     let b: &mut [_] = &mut [12];
-    assert!(a.tail_mut() == b);
+    assert!(a.split_first_mut() == Some((&mut 11, b)));
 }
 
 #[test]
-#[should_panic]
-fn test_tail_empty() {
-    let a = Vec::<i32>::new();
-    a.tail();
-}
-
-#[test]
-#[should_panic]
-fn test_tail_mut_empty() {
-    let mut a = Vec::<i32>::new();
-    a.tail_mut();
-}
-
-#[test]
-fn test_init() {
+fn test_split_last() {
     let mut a = vec![11];
     let b: &[i32] = &[];
-    assert_eq!(a.init(), b);
+    assert!(b.split_last().is_none());
+    assert_eq!(a.split_last(), Some((&11, b)));
     a = vec![11, 12];
     let b: &[_] = &[11];
-    assert_eq!(a.init(), b);
+    assert_eq!(a.split_last(), Some((&12, b)));
 }
 
 #[test]
-fn test_init_mut() {
+fn test_split_last_mut() {
     let mut a = vec![11];
     let b: &mut [i32] = &mut [];
-    assert!(a.init_mut() == b);
+    assert!(b.split_last_mut().is_none());
+    assert!(a.split_last_mut() == Some((&mut 11, b)));
+
     a = vec![11, 12];
     let b: &mut [_] = &mut [11];
-    assert!(a.init_mut() == b);
-}
-
-#[test]
-#[should_panic]
-fn test_init_empty() {
-    let a = Vec::<i32>::new();
-    a.init();
-}
-
-#[test]
-#[should_panic]
-fn test_init_mut_empty() {
-    let mut a = Vec::<i32>::new();
-    a.init_mut();
+    assert!(a.split_last_mut() == Some((&mut 12, b)));
 }
 
 #[test]
index e92af585c15726bb9ac7204195f18d4545c8ea7c..1c038c29fdfae1b413d4e063c0af21d13a92b4cb 100644 (file)
@@ -1746,6 +1746,14 @@ fn to_uppercase() {
     assert_eq!("aéDžßfiᾀ".to_uppercase(), "AÉDŽSSFIἈΙ");
 }
 
+#[test]
+fn test_into_string() {
+    // The only way to acquire a Box<str> in the first place is through a String, so just
+    // test that we can round-trip between Box<str> and String.
+    let string = String::from("Some text goes here");
+    assert_eq!(string.clone().into_boxed_slice().into_string(), string);
+}
+
 mod pattern {
     use std::str::pattern::Pattern;
     use std::str::pattern::{Searcher, ReverseSearcher};
index 257caca4016df28e8cef0f826544a4d16649bceb..7b69601f010ba4af2435ed40410b4614a637eb2d 100644 (file)
@@ -374,6 +374,13 @@ fn test_extend_ref() {
     assert_eq!(&a, "foobar");
 }
 
+#[test]
+fn test_into_boxed_slice() {
+    let xs = String::from("hello my name is bob");
+    let ys = xs.into_boxed_slice();
+    assert_eq!(&*ys, "hello my name is bob");
+}
+
 #[bench]
 fn bench_with_capacity(b: &mut Bencher) {
     b.iter(|| {
index 32d6aa19c64566e90212673866f8a25d573e23e8..22f0215f0aded53311cf7898c27eb23acedcf681 100644 (file)
@@ -175,6 +175,12 @@ pub fn finish(&mut self) -> fmt::Result {
     fn is_pretty(&self) -> bool {
         self.fmt.flags() & (1 << (FlagV1::Alternate as usize)) != 0
     }
+
+    /// Returns the wrapped `Formatter`.
+    #[unstable(feature = "debug_builder_formatter", reason = "recently added")]
+    pub fn formatter(&mut self) -> &mut fmt::Formatter<'b> {
+        &mut self.fmt
+    }
 }
 
 struct DebugInner<'a, 'b: 'a> {
index 47030bf0fb31efc989952e8f53fcf9b1122eb44a..29a2f76ef290b4dcee37738e1781fd4bb195a412 100644 (file)
@@ -1488,20 +1488,19 @@ macro_rules! tuple {
         impl<$($name:Debug),*> Debug for ($($name,)*) {
             #[allow(non_snake_case, unused_assignments)]
             fn fmt(&self, f: &mut Formatter) -> Result {
-                try!(write!(f, "("));
+                let mut builder = f.debug_tuple("");
                 let ($(ref $name,)*) = *self;
                 let mut n = 0;
                 $(
-                    if n > 0 {
-                        try!(write!(f, ", "));
-                    }
-                    try!(write!(f, "{:?}", *$name));
+                    builder.field($name);
                     n += 1;
                 )*
+
                 if n == 1 {
-                    try!(write!(f, ","));
+                    try!(write!(builder.formatter(), ","));
                 }
-                write!(f, ")")
+
+                builder.finish()
             }
         }
         peel! { $($name,)* }
index fd5ef4b1ccccaab3a384cf2b28e7047621f92776..3fd3d4a42b208adf61a6b997264227cfce5c709f 100644 (file)
@@ -1126,7 +1126,7 @@ pub fn pow(self, mut exp: u32) -> Self {
             acc
         }
 
-        /// Returns `true` iff `self == 2^k` for some `k`.
+        /// Returns `true` if and only if `self == 2^k` for some `k`.
         #[stable(feature = "rust1", since = "1.0.0")]
         #[inline]
         pub fn is_power_of_two(self) -> bool {
index c5203c5111b64ab5e3ab7fa306eca86b12062ccd..9ccba7ad78d45a785278ab64b02e34300812ae23 100644 (file)
@@ -46,7 +46,7 @@
 //!     // The division was valid
 //!     Some(x) => println!("Result: {}", x),
 //!     // The division was invalid
-//!     None    => println!("Cannot divide by 0")
+//!     None    => println!("Cannot divide by 0"),
 //! }
 //! ```
 //!
@@ -75,7 +75,7 @@
 //! fn check_optional(optional: &Option<Box<i32>>) {
 //!     match *optional {
 //!         Some(ref p) => println!("have value {}", p),
-//!         None => println!("have no value")
+//!         None => println!("have no value"),
 //!     }
 //! }
 //! ```
 //! // Take a reference to the contained string
 //! match msg {
 //!     Some(ref m) => println!("{}", *m),
-//!     None => ()
+//!     None => (),
 //! }
 //!
 //! // Remove the contained string, destroying the Option
 //! let unwrapped_msg = match msg {
 //!     Some(m) => m,
-//!     None => "default message"
+//!     None => "default message",
 //! };
 //! ```
 //!
 //!
 //! match name_of_biggest_animal {
 //!     Some(name) => println!("the biggest animal is {}", name),
-//!     None => println!("there are no animals :(")
+//!     None => println!("there are no animals :("),
 //! }
 //! ```
 
@@ -198,7 +198,7 @@ impl<T> Option<T> {
     pub fn is_some(&self) -> bool {
         match *self {
             Some(_) => true,
-            None => false
+            None => false,
         }
     }
 
@@ -244,7 +244,7 @@ pub fn is_none(&self) -> bool {
     pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
         match *self {
             Some(ref x) => Some(x),
-            None => None
+            None => None,
         }
     }
 
@@ -265,7 +265,7 @@ pub fn as_ref<'r>(&'r self) -> Option<&'r T> {
     pub fn as_mut<'r>(&'r mut self) -> Option<&'r mut T> {
         match *self {
             Some(ref mut x) => Some(x),
-            None => None
+            None => None,
         }
     }
 
@@ -376,7 +376,7 @@ pub fn unwrap(self) -> T {
     pub fn unwrap_or(self, def: T) -> T {
         match self {
             Some(x) => x,
-            None => def
+            None => def,
         }
     }
 
@@ -394,7 +394,7 @@ pub fn unwrap_or(self, def: T) -> T {
     pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
         match self {
             Some(x) => x,
-            None => f()
+            None => f(),
         }
     }
 
@@ -420,7 +420,7 @@ pub fn unwrap_or_else<F: FnOnce() -> T>(self, f: F) -> T {
     pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Option<U> {
         match self {
             Some(x) => Some(f(x)),
-            None => None
+            None => None,
         }
     }
 
@@ -464,7 +464,7 @@ pub fn map_or<U, F: FnOnce(T) -> U>(self, default: U, f: F) -> U {
     pub fn map_or_else<U, D: FnOnce() -> U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U {
         match self {
             Some(t) => f(t),
-            None => default()
+            None => default(),
         }
     }
 
@@ -637,7 +637,7 @@ pub fn and_then<U, F: FnOnce(T) -> Option<U>>(self, f: F) -> Option<U> {
     pub fn or(self, optb: Option<T>) -> Option<T> {
         match self {
             Some(_) => self,
-            None => optb
+            None => optb,
         }
     }
 
@@ -659,7 +659,7 @@ pub fn or(self, optb: Option<T>) -> Option<T> {
     pub fn or_else<F: FnOnce() -> Option<T>>(self, f: F) -> Option<T> {
         match self {
             Some(_) => self,
-            None => f()
+            None => f(),
         }
     }
 
@@ -736,7 +736,7 @@ impl<T: Default> Option<T> {
     pub fn unwrap_or_default(self) -> T {
         match self {
             Some(x) => x,
-            None => Default::default()
+            None => Default::default(),
         }
     }
 }
index 00e7ff3c4df823ada27f6340a3df5cde64b4176e..2c6acbf9157de7cccfd574eb7947508bdfdcbe23 100644 (file)
@@ -83,6 +83,8 @@ fn rsplitn<'a, P>(&'a self,  n: usize, pred: P) -> RSplitN<'a, Self::Item, P>
     fn first<'a>(&'a self) -> Option<&'a Self::Item>;
     fn tail<'a>(&'a self) -> &'a [Self::Item];
     fn init<'a>(&'a self) -> &'a [Self::Item];
+    fn split_first<'a>(&'a self) -> Option<(&'a Self::Item, &'a [Self::Item])>;
+    fn split_last<'a>(&'a self) -> Option<(&'a Self::Item, &'a [Self::Item])>;
     fn last<'a>(&'a self) -> Option<&'a Self::Item>;
     unsafe fn get_unchecked<'a>(&'a self, index: usize) -> &'a Self::Item;
     fn as_ptr(&self) -> *const Self::Item;
@@ -95,6 +97,8 @@ fn is_empty(&self) -> bool { self.len() == 0 }
     fn first_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
     fn tail_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
     fn init_mut<'a>(&'a mut self) -> &'a mut [Self::Item];
+    fn split_first_mut<'a>(&'a mut self) -> Option<(&'a mut Self::Item, &'a mut [Self::Item])>;
+    fn split_last_mut<'a>(&'a mut self) -> Option<(&'a mut Self::Item, &'a mut [Self::Item])>;
     fn last_mut<'a>(&'a mut self) -> Option<&'a mut Self::Item>;
     fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, Self::Item, P>
                         where P: FnMut(&Self::Item) -> bool;
@@ -238,8 +242,17 @@ fn first(&self) -> Option<&T> {
     fn tail(&self) -> &[T] { &self[1..] }
 
     #[inline]
-    fn init(&self) -> &[T] {
-        &self[..self.len() - 1]
+    fn split_first(&self) -> Option<(&T, &[T])> {
+        if self.is_empty() { None } else { Some((&self[0], &self[1..])) }
+    }
+
+    #[inline]
+    fn init(&self) -> &[T] { &self[..self.len() - 1] }
+
+    #[inline]
+    fn split_last(&self) -> Option<(&T, &[T])> {
+        let len = self.len();
+        if len == 0 { None } else { Some((&self[len - 1], &self[..(len - 1)])) }
     }
 
     #[inline]
@@ -328,8 +341,14 @@ fn first_mut(&mut self) -> Option<&mut T> {
     }
 
     #[inline]
-    fn tail_mut(&mut self) -> &mut [T] {
-        &mut self[1 ..]
+    fn tail_mut(&mut self) -> &mut [T] { &mut self[1 ..] }
+
+    #[inline]
+    fn split_first_mut(&mut self) -> Option<(&mut T, &mut [T])> {
+        if self.is_empty() { None } else {
+            let split = self.split_at_mut(1);
+            Some((&mut split.0[0], split.1))
+        }
     }
 
     #[inline]
@@ -338,6 +357,15 @@ fn init_mut(&mut self) -> &mut [T] {
         &mut self[.. (len - 1)]
     }
 
+    #[inline]
+    fn split_last_mut(&mut self) -> Option<(&mut T, &mut [T])> {
+        let len = self.len();
+        if len == 0 { None } else {
+            let split = self.split_at_mut(len - 1);
+            Some((&mut split.1[0], split.0))
+        }
+    }
+
     #[inline]
     fn split_mut<'a, P>(&'a mut self, pred: P) -> SplitMut<'a, T, P> where P: FnMut(&T) -> bool {
         SplitMut { v: self, pred: pred, finished: false }
index 65e85b92e0b2c1a1a1c5e65ad62e7f578bfe9730..8953375297db26e5309886d49e9b912a6f2fb9de 100644 (file)
@@ -56,7 +56,7 @@
 //!         optopt("o", "", "set output file name", "NAME"),
 //!         optflag("h", "help", "print this help menu")
 //!     ];
-//!     let matches = match getopts(args.tail(), opts) {
+//!     let matches = match getopts(args[1..], opts) {
 //!         Ok(m) => { m }
 //!         Err(f) => { panic!(f.to_string()) }
 //!     };
index 0a32c73a848d0dccd0f121dab06c441040ec61a3..dfcd08b69907aab6a1fae17e504c7245f6f7c9c7 100644 (file)
@@ -960,6 +960,100 @@ fn clone(&self) -> sockaddr_un { *self }
             }
         }
 
+        #[cfg(target_arch = "x86")]
+        pub mod arch {
+            pub mod c95 {
+                pub type c_char = i8;
+                pub type c_schar = i8;
+                pub type c_uchar = u8;
+                pub type c_short = i16;
+                pub type c_ushort = u16;
+                pub type c_int = i32;
+                pub type c_uint = u32;
+                pub type c_long = i32;
+                pub type c_ulong = u32;
+                pub type c_float = f32;
+                pub type c_double = f64;
+                pub type size_t = u32;
+                pub type ptrdiff_t = i32;
+                pub type clock_t = i32;
+                pub type time_t = i32;
+                pub type suseconds_t = i32;
+                pub type wchar_t = i32;
+            }
+            pub mod c99 {
+                pub type c_longlong = i64;
+                pub type c_ulonglong = u64;
+                pub type intptr_t = i32;
+                pub type uintptr_t = u32;
+                pub type intmax_t = i64;
+                pub type uintmax_t = u64;
+            }
+            pub mod posix88 {
+                pub type off_t = i64;
+                pub type dev_t = u32;
+                pub type ino_t = u32;
+                pub type pid_t = i32;
+                pub type uid_t = u32;
+                pub type gid_t = u32;
+                pub type useconds_t = u32;
+                pub type mode_t = u16;
+                pub type ssize_t = i32;
+            }
+            pub mod posix01 {
+                use types::common::c95::{c_void};
+                use types::common::c99::{uint8_t, uint32_t, int32_t};
+                use types::os::arch::c95::{c_long, time_t};
+                use types::os::arch::posix88::{dev_t, gid_t, ino_t};
+                use types::os::arch::posix88::{mode_t, off_t};
+                use types::os::arch::posix88::{uid_t};
+
+                pub type nlink_t = u16;
+                pub type blksize_t = i32;
+                pub type blkcnt_t = i64;
+                pub type fflags_t = u32;
+                #[repr(C)]
+                #[derive(Copy, Clone)] pub struct stat {
+                    pub st_dev: dev_t,
+                    pub st_ino: ino_t,
+                    pub st_mode: mode_t,
+                    pub st_nlink: nlink_t,
+                    pub st_uid: uid_t,
+                    pub st_gid: gid_t,
+                    pub st_rdev: dev_t,
+                    pub st_atime: time_t,
+                    pub st_atime_nsec: c_long,
+                    pub st_mtime: time_t,
+                    pub st_mtime_nsec: c_long,
+                    pub st_ctime: time_t,
+                    pub st_ctime_nsec: c_long,
+                    pub st_size: off_t,
+                    pub st_blocks: blkcnt_t,
+                    pub st_blksize: blksize_t,
+                    pub st_flags: fflags_t,
+                    pub st_gen: uint32_t,
+                    pub st_lspare: int32_t,
+                    pub st_birthtime: time_t,
+                    pub st_birthtime_nsec: c_long,
+                    pub __unused: [uint8_t; 2],
+                }
+
+                #[repr(C)]
+                #[derive(Copy, Clone)] pub struct utimbuf {
+                    pub actime: time_t,
+                    pub modtime: time_t,
+                }
+
+                pub type pthread_attr_t = *mut c_void;
+            }
+            pub mod posix08 {
+            }
+            pub mod bsd44 {
+            }
+            pub mod extra {
+            }
+        }
+
         #[cfg(target_arch = "x86_64")]
         pub mod arch {
             pub mod c95 {
@@ -4978,6 +5072,8 @@ pub mod posix01 {
             pub const F_GETFL : c_int = 3;
             pub const F_SETFL : c_int = 4;
 
+            pub const O_ACCMODE : c_int = 3;
+
             pub const SIGTRAP : c_int = 5;
             pub const SIG_IGN: size_t = 1;
 
@@ -5130,6 +5226,7 @@ pub mod extra {
             pub const O_DSYNC : c_int = 4194304;
             pub const O_SYNC : c_int = 128;
             pub const O_NONBLOCK : c_int = 4;
+            pub const F_GETPATH : c_int = 50;
             pub const F_FULLFSYNC : c_int = 51;
 
             pub const MAP_COPY : c_int = 0x0002;
@@ -5151,6 +5248,8 @@ pub mod extra {
             pub const SO_DONTTRUNC: c_int = 0x2000;
             pub const SO_WANTMORE: c_int = 0x4000;
             pub const SO_WANTOOBFLAG: c_int = 0x8000;
+
+            pub const PATH_MAX: c_int = 1024;
         }
         pub mod sysconf {
             use types::os::arch::c95::c_int;
index 3dbc80d352d15598adc357cfc16c47c6e2a34a3e..9aa5daa3a0a275aae3742183ac4f3aa69fe1a68e 100644 (file)
@@ -791,8 +791,7 @@ trait Foo {
     fn bar(&self);
 }
 
-// we now declare a function which takes an object with Foo trait implemented
-// as parameter
+// we now declare a function which takes an object implementing the Foo trait
 fn some_func<T: Foo>(foo: T) {
     foo.bar();
 }
@@ -1006,7 +1005,7 @@ fn baz() {
 
 E0308: r##"
 This error occurs when the compiler was unable to infer the concrete type of a
-variable. This error can occur for several cases, the most common of which is a
+variable. It can occur for several cases, the most common of which is a
 mismatch in the expected type that the compiler inferred for a variable's
 initializing expression, and the actual type explicitly assigned to the
 variable.
index 732b77a626e88053381857c200484007e05b64ea..f1984708b663aacb9a4360f9620112b1b4b03886 100644 (file)
@@ -53,7 +53,7 @@
 #![feature(rustc_private)]
 #![feature(scoped_tls)]
 #![feature(slice_bytes)]
-#![feature(slice_extras)]
+#![feature(slice_splits)]
 #![feature(slice_patterns)]
 #![feature(slice_position_elem)]
 #![feature(staged_api)]
index 4e0cf7b0e4cd4e4cdadf5a8cfb495feff188cd74..2a469ed69ef9a5b29b849ffda4b5f3c891c8a583 100644 (file)
@@ -197,7 +197,7 @@ pub fn get_item_attrs(cstore: &cstore::CStore,
 
 pub fn get_struct_fields(cstore: &cstore::CStore,
                          def: ast::DefId)
-                      -> Vec<ty::field_ty> {
+                      -> Vec<ty::FieldTy> {
     let cdata = cstore.get_crate_data(def.krate);
     decoder::get_struct_fields(cstore.intr.clone(), &*cdata, def.node)
 }
index 5a79ef203b4b39162e63d05b7d2bd5f9ea68464e..7415b576f762be8f06ab89f9f6cbc6fbe96c334c 100644 (file)
@@ -688,7 +688,7 @@ pub fn maybe_get_item_ast<'tcx>(cdata: Cmd, tcx: &ty::ctxt<'tcx>, id: ast::NodeI
                                 -> csearch::FoundAst<'tcx> {
     debug!("Looking up item: {}", id);
     let item_doc = lookup_item(id, cdata.data());
-    let path = item_path(item_doc).init().to_vec();
+    let path = item_path(item_doc).split_last().unwrap().1.to_vec();
     match decode_inlined_item(cdata, tcx, path, item_doc) {
         Ok(ii) => csearch::FoundAst::Found(ii),
         Err(path) => {
@@ -1049,7 +1049,7 @@ fn struct_field_family_to_visibility(family: Family) -> ast::Visibility {
 }
 
 pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
-    -> Vec<ty::field_ty> {
+    -> Vec<ty::FieldTy> {
     let data = cdata.data();
     let item = lookup_item(id, data);
     reader::tagged_docs(item, tag_item_field).filter_map(|an_item| {
@@ -1059,7 +1059,7 @@ pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
             let did = item_def_id(an_item, cdata);
             let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
             let origin_id =  translated_def_id(cdata, tagdoc);
-            Some(ty::field_ty {
+            Some(ty::FieldTy {
                 name: name,
                 id: did,
                 vis: struct_field_family_to_visibility(f),
@@ -1073,7 +1073,7 @@ pub fn get_struct_fields(intr: Rc<IdentInterner>, cdata: Cmd, id: ast::NodeId)
         let tagdoc = reader::get_doc(an_item, tag_item_field_origin);
         let f = item_family(an_item);
         let origin_id =  translated_def_id(cdata, tagdoc);
-        ty::field_ty {
+        ty::FieldTy {
             name: special_idents::unnamed_field.name,
             id: did,
             vis: struct_field_family_to_visibility(f),
index f38369e3f4c054910acd0f2d6ac17f3969cb43fa..987b6ad5b729622d6d4080900d3f81c1190ef057 100644 (file)
@@ -267,7 +267,7 @@ fn encode_parent_item(rbml_w: &mut Encoder, id: DefId) {
 }
 
 fn encode_struct_fields(rbml_w: &mut Encoder,
-                        fields: &[ty::field_ty],
+                        fields: &[ty::FieldTy],
                         origin: DefId) {
     for f in fields {
         if f.name == special_idents::unnamed_field.name {
@@ -636,7 +636,7 @@ fn encode_provided_source(rbml_w: &mut Encoder,
 /* Returns an index of items in this class */
 fn encode_info_for_struct(ecx: &EncodeContext,
                           rbml_w: &mut Encoder,
-                          fields: &[ty::field_ty],
+                          fields: &[ty::FieldTy],
                           global_index: &mut Vec<entry<i64>>)
                           -> Vec<entry<i64>> {
     /* Each class has its own index, since different classes
index 61fce699dd555285c6dd5b4235a355deac284fe3..57157560f1fbca91e60a0df0463b9d4b165c5e8d 100644 (file)
@@ -525,7 +525,7 @@ fn parse_ty_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> Ty<'tcx> w
         assert_eq!(next(st), ':');
         let len = parse_hex(st);
         assert_eq!(next(st), '#');
-        let key = ty::creader_cache_key {cnum: st.krate,
+        let key = ty::CReaderCacheKey {cnum: st.krate,
                                          pos: pos,
                                          len: len };
 
@@ -587,11 +587,11 @@ fn parse_mutability(st: &mut PState) -> ast::Mutability {
     }
 }
 
-fn parse_mt_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> ty::mt<'tcx> where
+fn parse_mt_<'a, 'tcx, F>(st: &mut PState<'a, 'tcx>, conv: &mut F) -> ty::TypeAndMut<'tcx> where
     F: FnMut(DefIdSource, ast::DefId) -> ast::DefId,
 {
     let m = parse_mutability(st);
-    ty::mt { ty: parse_ty_(st, conv), mutbl: m }
+    ty::TypeAndMut { ty: parse_ty_(st, conv), mutbl: m }
 }
 
 fn parse_def_<F>(st: &mut PState, source: DefIdSource, conv: &mut F) -> ast::DefId where
index 441f9f102aea911e4fa67b7f1ffcc2f606f68ff5..a932ada61f129723817ce3693ea8c69565a514fc 100644 (file)
@@ -183,7 +183,7 @@ fn enc_mutability(w: &mut Encoder, mt: ast::Mutability) {
 }
 
 fn enc_mt<'a, 'tcx>(w: &mut Encoder, cx: &ctxt<'a, 'tcx>,
-                    mt: ty::mt<'tcx>) {
+                    mt: ty::TypeAndMut<'tcx>) {
     enc_mutability(w, mt.mutbl);
     enc_ty(w, cx, mt.ty);
 }
index ec1fd67616b81eb8cdeb2f797e3273409ab74586..bbd452b35acdf7732a5cb04d7708f11e28fa2828 100644 (file)
@@ -36,9 +36,9 @@ pub enum CastTy<'tcx> {
     /// Function Pointers
     FnPtr,
     /// Raw pointers
-    Ptr(&'tcx ty::mt<'tcx>),
+    Ptr(&'tcx ty::TypeAndMut<'tcx>),
     /// References
-    RPtr(&'tcx ty::mt<'tcx>),
+    RPtr(&'tcx ty::TypeAndMut<'tcx>),
 }
 
 /// Cast Kind. See RFC 401 (or librustc_typeck/check/cast.rs)
index 444192b7913ec0b9e585fec4d23b2933b1755b8e..fc2444ed5b45c4771921b35f099ddc37a9fae79b 100644 (file)
@@ -535,7 +535,7 @@ fn construct_witness(cx: &MatchCheckCtxt, ctor: &Constructor,
             }
         }
 
-        ty::TyRef(_, ty::mt { ty, mutbl }) => {
+        ty::TyRef(_, ty::TypeAndMut { ty, mutbl }) => {
             match ty.sty {
                ty::TyArray(_, n) => match ctor {
                     &Single => {
@@ -600,7 +600,7 @@ fn all_constructors(cx: &MatchCheckCtxt, left_ty: Ty,
         ty::TyBool =>
             [true, false].iter().map(|b| ConstantValue(ConstVal::Bool(*b))).collect(),
 
-        ty::TyRef(_, ty::mt { ty, .. }) => match ty.sty {
+        ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
             ty::TySlice(_) =>
                 range_inclusive(0, max_slice_length).map(|length| Slice(length)).collect(),
             _ => vec!(Single)
@@ -696,12 +696,12 @@ fn is_useful(cx: &MatchCheckCtxt,
             Some(constructor) => {
                 let matrix = rows.iter().filter_map(|r| {
                     if pat_is_binding_or_wild(&cx.tcx.def_map, raw_pat(r[0])) {
-                        Some(r.tail().to_vec())
+                        Some(r[1..].to_vec())
                     } else {
                         None
                     }
                 }).collect();
-                match is_useful(cx, &matrix, v.tail(), witness) {
+                match is_useful(cx, &matrix, &v[1..], witness) {
                     UsefulWithWitness(pats) => {
                         let arity = constructor_arity(cx, &constructor, left_ty);
                         let wild_pats = vec![DUMMY_WILD_PAT; arity];
@@ -808,7 +808,7 @@ pub fn constructor_arity(cx: &MatchCheckCtxt, ctor: &Constructor, ty: Ty) -> usi
     match ty.sty {
         ty::TyTuple(ref fs) => fs.len(),
         ty::TyBox(_) => 1,
-        ty::TyRef(_, ty::mt { ty, .. }) => match ty.sty {
+        ty::TyRef(_, ty::TypeAndMut { ty, .. }) => match ty.sty {
             ty::TySlice(_) => match *ctor {
                 Slice(length) => length,
                 ConstantValue(_) => 0,
index 0d204a823af04d89c60c1b1e98f0d51d914cf488..54fc2daff2b8e55165f147b11e093f9d07669967 100644 (file)
@@ -720,7 +720,7 @@ fn walk_struct_expr(&mut self,
         // are properly handled.
         self.walk_expr(with_expr);
 
-        fn contains_field_named(field: &ty::field,
+        fn contains_field_named(field: &ty::Field,
                                 fields: &Vec<ast::Field>)
                                 -> bool
         {
index 3e097578857e94d4336079f378809762e1322eb2..18059848481e6e557a6f80badb0fafd87788e019 100644 (file)
@@ -115,7 +115,7 @@ fn accumulate_from_ty(&mut self, ty: Ty<'tcx>) {
 
             ty::TyArray(t, _) |
             ty::TySlice(t) |
-            ty::TyRawPtr(ty::mt { ty: t, .. }) |
+            ty::TyRawPtr(ty::TypeAndMut { ty: t, .. }) |
             ty::TyBox(t) => {
                 self.accumulate_from_ty(t)
             }
index 0d081cfeee0410ea7f74065020b79abc94534619..94c76e2399947114245bc87e9ceeff25faa7d797 100644 (file)
@@ -43,7 +43,7 @@
 
 use middle::ty::{TyVar};
 use middle::ty::{IntType, UintType};
-use middle::ty::{self, Ty};
+use middle::ty::{self, Ty, TypeError};
 use middle::ty_fold;
 use middle::ty_fold::{TypeFolder, TypeFoldable};
 use middle::ty_relate::{self, Relate, RelateResult, TypeRelation};
@@ -108,7 +108,7 @@ pub fn super_combine_tys<'a,'tcx:'a,R>(infcx: &InferCtxt<'a, 'tcx>,
         // All other cases of inference are errors
         (&ty::TyInfer(_), _) |
         (_, &ty::TyInfer(_)) => {
-            Err(ty::terr_sorts(ty_relate::expected_found(relation, &a, &b)))
+            Err(TypeError::Sorts(ty_relate::expected_found(relation, &a, &b)))
         }
 
 
@@ -278,7 +278,7 @@ fn generalize(&self,
         };
         let u = ty.fold_with(&mut generalize);
         if generalize.cycle_detected {
-            Err(ty::terr_cyclic_ty)
+            Err(TypeError::CyclicTy)
         } else {
             Ok(u)
         }
@@ -363,12 +363,12 @@ fn fold_region(&mut self, r: ty::Region) -> ty::Region {
 
 pub trait RelateResultCompare<'tcx, T> {
     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
-        F: FnOnce() -> ty::type_err<'tcx>;
+        F: FnOnce() -> ty::TypeError<'tcx>;
 }
 
 impl<'tcx, T:Clone + PartialEq> RelateResultCompare<'tcx, T> for RelateResult<'tcx, T> {
     fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
-        F: FnOnce() -> ty::type_err<'tcx>,
+        F: FnOnce() -> ty::TypeError<'tcx>,
     {
         self.clone().and_then(|s| {
             if s == t {
@@ -381,16 +381,16 @@ fn compare<F>(&self, t: T, f: F) -> RelateResult<'tcx, T> where
 }
 
 fn int_unification_error<'tcx>(a_is_expected: bool, v: (ty::IntVarValue, ty::IntVarValue))
-                               -> ty::type_err<'tcx>
+                               -> ty::TypeError<'tcx>
 {
     let (a, b) = v;
-    ty::terr_int_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b))
+    TypeError::IntMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b))
 }
 
 fn float_unification_error<'tcx>(a_is_expected: bool,
                                  v: (ast::FloatTy, ast::FloatTy))
-                                 -> ty::type_err<'tcx>
+                                 -> ty::TypeError<'tcx>
 {
     let (a, b) = v;
-    ty::terr_float_mismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b))
+    TypeError::FloatMismatch(ty_relate::expected_found_bool(a_is_expected, &a, &b))
 }
index 8d226739e1688cdb4bbf82822a43098900e342b3..1ad7df9cd3a86510bfaa4c3278a109b1a971d2cb 100644 (file)
@@ -77,7 +77,7 @@
 use middle::infer;
 use middle::region;
 use middle::subst;
-use middle::ty::{self, Ty, HasTypeFlags};
+use middle::ty::{self, Ty, TypeError, HasTypeFlags};
 use middle::ty::{Region, ReFree};
 
 use std::cell::{Cell, RefCell};
@@ -220,17 +220,17 @@ fn report_region_errors(&self,
     fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
                       -> Vec<RegionResolutionError<'tcx>>;
 
-    fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::type_err<'tcx>);
+    fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::TypeError<'tcx>);
 
     fn report_and_explain_type_error(&self,
                                      trace: TypeTrace<'tcx>,
-                                     terr: &ty::type_err<'tcx>);
+                                     terr: &ty::TypeError<'tcx>);
 
     fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String>;
 
     fn expected_found_str<T: fmt::Display + Resolvable<'tcx> + HasTypeFlags>(
         &self,
-        exp_found: &ty::expected_found<T>)
+        exp_found: &ty::ExpectedFound<T>)
         -> Option<String>;
 
     fn report_concrete_failure(&self,
@@ -260,7 +260,7 @@ fn report_sup_sup_conflict(&self,
 
     fn report_processed_errors(&self,
                                var_origin: &[RegionVariableOrigin],
-                               trace_origin: &[(TypeTrace<'tcx>, ty::type_err<'tcx>)],
+                               trace_origin: &[(TypeTrace<'tcx>, ty::TypeError<'tcx>)],
                                same_regions: &[SameRegions]);
 
     fn give_suggestion(&self, same_regions: &[SameRegions]);
@@ -351,8 +351,8 @@ fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
                     match free_regions_from_same_fn(self.tcx, sub, sup) {
                         Some(ref same_frs) if trace.is_some() => {
                             let trace = trace.unwrap();
-                            let terr = ty::terr_regions_does_not_outlive(sup,
-                                                                         sub);
+                            let terr = TypeError::RegionsDoesNotOutlive(sup,
+                                                                        sub);
                             trace_origins.push((trace, terr));
                             append_to_same_regions(&mut same_regions, same_frs);
                         }
@@ -467,7 +467,7 @@ fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
         }
     }
 
-    fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::type_err<'tcx>) {
+    fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::TypeError<'tcx>) {
         let expected_found_str = match self.values_str(&trace.values) {
             Some(v) => v,
             None => {
@@ -490,7 +490,7 @@ fn report_type_error(&self, trace: TypeTrace<'tcx>, terr: &ty::type_err<'tcx>) {
 
     fn report_and_explain_type_error(&self,
                                      trace: TypeTrace<'tcx>,
-                                     terr: &ty::type_err<'tcx>) {
+                                     terr: &ty::TypeError<'tcx>) {
         let span = trace.origin.span();
         self.report_type_error(trace, terr);
         self.tcx.note_and_explain_type_err(terr, span);
@@ -508,7 +508,7 @@ fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<String> {
 
     fn expected_found_str<T: fmt::Display + Resolvable<'tcx> + HasTypeFlags>(
         &self,
-        exp_found: &ty::expected_found<T>)
+        exp_found: &ty::ExpectedFound<T>)
         -> Option<String>
     {
         let expected = exp_found.expected.resolve(self);
@@ -595,7 +595,7 @@ fn report_concrete_failure(&self,
         match origin {
             infer::Subtype(trace) |
             infer::DefaultExistentialBound(trace) => {
-                let terr = ty::terr_regions_does_not_outlive(sup, sub);
+                let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
                 self.report_and_explain_type_error(trace, &terr);
             }
             infer::Reborrow(span) => {
@@ -888,7 +888,7 @@ fn report_sup_sup_conflict(&self,
 
     fn report_processed_errors(&self,
                                var_origins: &[RegionVariableOrigin],
-                               trace_origins: &[(TypeTrace<'tcx>, ty::type_err<'tcx>)],
+                               trace_origins: &[(TypeTrace<'tcx>, ty::TypeError<'tcx>)],
                                same_regions: &[SameRegions]) {
         for vo in var_origins {
             self.report_inference_failure(vo.clone());
@@ -1495,7 +1495,7 @@ fn rebuild_path(&self,
             parameters: new_parameters
         };
         let mut new_segs = Vec::new();
-        new_segs.push_all(path.segments.init());
+        new_segs.push_all(path.segments.split_last().unwrap().1);
         new_segs.push(new_seg);
         ast::Path {
             span: path.span,
index 64063623f6776f7a92840bf81086e87267d5556e..1919d8ffd294df7736f01b8cfc19715cceacb7d8 100644 (file)
@@ -15,7 +15,7 @@
 use super::combine::CombineFields;
 
 use middle::subst;
-use middle::ty::{self, Binder};
+use middle::ty::{self, TypeError, Binder};
 use middle::ty_fold::{self, TypeFoldable};
 use middle::ty_relate::{Relate, RelateResult, TypeRelation};
 use syntax::codemap::Span;
@@ -85,11 +85,11 @@ fn higher_ranked_sub<T>(&self, a: &Binder<T>, b: &Binder<T>)
                 Err((skol_br, tainted_region)) => {
                     if self.a_is_expected {
                         debug!("Not as polymorphic!");
-                        return Err(ty::terr_regions_insufficiently_polymorphic(skol_br,
+                        return Err(TypeError::RegionsInsufficientlyPolymorphic(skol_br,
                                                                                tainted_region));
                     } else {
                         debug!("Overly polymorphic!");
-                        return Err(ty::terr_regions_overly_polymorphic(skol_br,
+                        return Err(TypeError::RegionsOverlyPolymorphic(skol_br,
                                                                        tainted_region));
                     }
                 }
index e24fadba6a55e38ef0428f571e32c52fc3398f44..0495209f0d00d5ca7483523498ceb96ecf0b2a3b 100644 (file)
 
 //! See the Book for more information.
 
-#![allow(non_camel_case_types)]
-
 pub use self::LateBoundRegionConversionTime::*;
 pub use self::RegionVariableOrigin::*;
 pub use self::SubregionOrigin::*;
 pub use self::TypeOrigin::*;
 pub use self::ValuePairs::*;
-pub use self::fixup_err::*;
 pub use middle::ty::IntVarValue;
 pub use self::freshen::TypeFreshener;
 pub use self::region_inference::GenericKind;
@@ -32,7 +29,7 @@
 use middle::traits::{self, FulfillmentContext, Normalized,
                      SelectionContext, ObligationCause};
 use middle::ty::{TyVid, IntVid, FloatVid, RegionVid, UnconstrainedNumeric};
-use middle::ty::{self, Ty, HasTypeFlags};
+use middle::ty::{self, Ty, TypeError, HasTypeFlags};
 use middle::ty_fold::{self, TypeFolder, TypeFoldable};
 use middle::ty_relate::{Relate, RelateResult, TypeRelation};
 use rustc_data_structures::unify::{self, UnificationTable};
@@ -65,7 +62,7 @@
 
 pub type Bound<T> = Option<T>;
 pub type UnitResult<'tcx> = RelateResult<'tcx, ()>; // "unify result"
-pub type fres<T> = Result<T, fixup_err>; // "fixup result"
+pub type FixupResult<T> = Result<T, FixupError>; // "fixup result"
 
 pub struct InferCtxt<'a, 'tcx: 'a> {
     pub tcx: &'a ty::ctxt<'tcx>,
@@ -171,9 +168,9 @@ fn fmt(&self, f: &mut fmt::Formatter) -> Result<(),fmt::Error> {
 /// See `error_reporting.rs` for more details
 #[derive(Clone, Debug)]
 pub enum ValuePairs<'tcx> {
-    Types(ty::expected_found<Ty<'tcx>>),
-    TraitRefs(ty::expected_found<ty::TraitRef<'tcx>>),
-    PolyTraitRefs(ty::expected_found<ty::PolyTraitRef<'tcx>>),
+    Types(ty::ExpectedFound<Ty<'tcx>>),
+    TraitRefs(ty::ExpectedFound<ty::TraitRef<'tcx>>),
+    PolyTraitRefs(ty::ExpectedFound<ty::PolyTraitRef<'tcx>>),
 }
 
 /// The trace designates the path through inference that we took to
@@ -313,23 +310,25 @@ pub enum RegionVariableOrigin {
 }
 
 #[derive(Copy, Clone, Debug)]
-pub enum fixup_err {
-    unresolved_int_ty(IntVid),
-    unresolved_float_ty(FloatVid),
-    unresolved_ty(TyVid)
+pub enum FixupError {
+    UnresolvedIntTy(IntVid),
+    UnresolvedFloatTy(FloatVid),
+    UnresolvedTy(TyVid)
 }
 
-pub fn fixup_err_to_string(f: fixup_err) -> String {
+pub fn fixup_err_to_string(f: FixupError) -> String {
+    use self::FixupError::*;
+
     match f {
-      unresolved_int_ty(_) => {
+      UnresolvedIntTy(_) => {
           "cannot determine the type of this integer; add a suffix to \
            specify the type explicitly".to_string()
       }
-      unresolved_float_ty(_) => {
+      UnresolvedFloatTy(_) => {
           "cannot determine the type of this number; add a suffix to specify \
            the type explicitly".to_string()
       }
-      unresolved_ty(_) => "unconstrained type".to_string(),
+      UnresolvedTy(_) => "unconstrained type".to_string(),
     }
 }
 
@@ -460,12 +459,12 @@ pub fn mk_sub_poly_trait_refs<'a, 'tcx>(cx: &InferCtxt<'a, 'tcx>,
 fn expected_found<T>(a_is_expected: bool,
                      a: T,
                      b: T)
-                     -> ty::expected_found<T>
+                     -> ty::ExpectedFound<T>
 {
     if a_is_expected {
-        ty::expected_found {expected: a, found: b}
+        ty::ExpectedFound {expected: a, found: b}
     } else {
-        ty::expected_found {expected: b, found: a}
+        ty::ExpectedFound {expected: b, found: a}
     }
 }
 
@@ -913,7 +912,7 @@ pub fn leak_check(&self,
 
         match higher_ranked::leak_check(self, skol_map, snapshot) {
             Ok(()) => Ok(()),
-            Err((br, r)) => Err(ty::terr_regions_insufficiently_polymorphic(br, r))
+            Err((br, r)) => Err(TypeError::RegionsInsufficientlyPolymorphic(br, r))
         }
     }
 
@@ -1169,7 +1168,7 @@ fn resolve_type_vars_or_error(&self, t: &Ty<'tcx>) -> mc::McResult<Ty<'tcx>> {
         if ty.has_infer_types() || ty.references_error() { Err(()) } else { Ok(ty) }
     }
 
-    pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> fres<T> {
+    pub fn fully_resolve<T:TypeFoldable<'tcx>>(&self, value: &T) -> FixupResult<T> {
         /*!
          * Attempts to resolve all type/region variables in
          * `value`. Region inference must have been run already (e.g.,
@@ -1198,7 +1197,7 @@ pub fn type_error_message_str<M>(&self,
                                      sp: Span,
                                      mk_msg: M,
                                      actual_ty: String,
-                                     err: Option<&ty::type_err<'tcx>>) where
+                                     err: Option<&ty::TypeError<'tcx>>) where
         M: FnOnce(Option<String>, String) -> String,
     {
         self.type_error_message_str_with_expected(sp, mk_msg, None, actual_ty, err)
@@ -1209,7 +1208,7 @@ pub fn type_error_message_str_with_expected<M>(&self,
                                                    mk_msg: M,
                                                    expected_ty: Option<Ty<'tcx>>,
                                                    actual_ty: String,
-                                                   err: Option<&ty::type_err<'tcx>>) where
+                                                   err: Option<&ty::TypeError<'tcx>>) where
         M: FnOnce(Option<String>, String) -> String,
     {
         debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty);
@@ -1235,7 +1234,7 @@ pub fn type_error_message<M>(&self,
                                  sp: Span,
                                  mk_msg: M,
                                  actual_ty: Ty<'tcx>,
-                                 err: Option<&ty::type_err<'tcx>>) where
+                                 err: Option<&ty::TypeError<'tcx>>) where
         M: FnOnce(String) -> String,
     {
         let actual_ty = self.resolve_type_vars_if_possible(&actual_ty);
@@ -1254,10 +1253,10 @@ pub fn report_mismatched_types(&self,
                                    span: Span,
                                    expected: Ty<'tcx>,
                                    actual: Ty<'tcx>,
-                                   err: &ty::type_err<'tcx>) {
+                                   err: &ty::TypeError<'tcx>) {
         let trace = TypeTrace {
             origin: Misc(span),
-            values: Types(ty::expected_found {
+            values: Types(ty::ExpectedFound {
                 expected: expected,
                 found: actual
             })
@@ -1431,7 +1430,7 @@ pub fn types(origin: TypeOrigin,
     pub fn dummy(tcx: &ty::ctxt<'tcx>) -> TypeTrace<'tcx> {
         TypeTrace {
             origin: Misc(codemap::DUMMY_SP),
-            values: Types(ty::expected_found {
+            values: Types(ty::ExpectedFound {
                 expected: tcx.types.err,
                 found: tcx.types.err,
             })
index ba5814167a6179b446f013606bed2f4178839e49..cbd195eee4ae733c3b47c780bc697432b10e8514 100644 (file)
@@ -23,7 +23,7 @@
 use rustc_data_structures::graph::{self, Direction, NodeIndex};
 use middle::free_region::FreeRegionMap;
 use middle::region;
-use middle::ty::{self, Ty};
+use middle::ty::{self, Ty, TypeError};
 use middle::ty::{BoundRegion, FreeRegion, Region, RegionVid};
 use middle::ty::{ReEmpty, ReStatic, ReInfer, ReFree, ReEarlyBound};
 use middle::ty::{ReLateBound, ReScope, ReVar, ReSkolemized, BrFresh};
@@ -132,7 +132,7 @@ pub enum RegionResolutionError<'tcx> {
     /// should put a lifetime. In those cases we process and put those errors
     /// into `ProcessedErrors` before we do any reporting.
     ProcessedErrors(Vec<RegionVariableOrigin>,
-                    Vec<(TypeTrace<'tcx>, ty::type_err<'tcx>)>,
+                    Vec<(TypeTrace<'tcx>, ty::TypeError<'tcx>)>,
                     Vec<SameRegions>),
 }
 
@@ -872,7 +872,7 @@ fn glb_concrete_regions(&self,
                 if self.tcx.region_maps.nearest_common_ancestor(fr_scope, s_id) == fr_scope {
                     Ok(s)
                 } else {
-                    Err(ty::terr_regions_no_overlap(b, a))
+                    Err(TypeError::RegionsNoOverlap(b, a))
                 }
             }
 
@@ -891,7 +891,7 @@ fn glb_concrete_regions(&self,
                 if a == b {
                     Ok(a)
                 } else {
-                    Err(ty::terr_regions_no_overlap(b, a))
+                    Err(TypeError::RegionsNoOverlap(b, a))
                 }
             }
         }
@@ -948,7 +948,7 @@ fn intersect_scopes(&self,
         } else if r_id == scope_b {
             Ok(ReScope(scope_a))
         } else {
-            Err(ty::terr_regions_no_overlap(region_a, region_b))
+            Err(TypeError::RegionsNoOverlap(region_a, region_b))
         }
     }
 }
index 41a0d373fba43da8a8979a135ed658701337df10..39807002b58a167c67785fdf1cb4f9a23ccdff6e 100644 (file)
@@ -8,7 +8,7 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-use super::{InferCtxt, fixup_err, fres, unresolved_ty, unresolved_int_ty, unresolved_float_ty};
+use super::{InferCtxt, FixupError, FixupResult};
 use middle::ty::{self, Ty, HasTypeFlags};
 use middle::ty_fold::{self, TypeFoldable};
 
@@ -51,7 +51,7 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
 /// Full type resolution replaces all type and region variables with
 /// their concrete results. If any variable cannot be replaced (never unified, etc)
 /// then an `Err` result is returned.
-pub fn fully_resolve<'a, 'tcx, T>(infcx: &InferCtxt<'a,'tcx>, value: &T) -> fres<T>
+pub fn fully_resolve<'a, 'tcx, T>(infcx: &InferCtxt<'a,'tcx>, value: &T) -> FixupResult<T>
     where T : TypeFoldable<'tcx>
 {
     let mut full_resolver = FullTypeResolver { infcx: infcx, err: None };
@@ -66,7 +66,7 @@ pub fn fully_resolve<'a, 'tcx, T>(infcx: &InferCtxt<'a,'tcx>, value: &T) -> fres
 // `err` field is not enforcable otherwise.
 struct FullTypeResolver<'a, 'tcx:'a> {
     infcx: &'a InferCtxt<'a, 'tcx>,
-    err: Option<fixup_err>,
+    err: Option<FixupError>,
 }
 
 impl<'a, 'tcx> ty_fold::TypeFolder<'tcx> for FullTypeResolver<'a, 'tcx> {
@@ -81,15 +81,15 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
             let t = self.infcx.shallow_resolve(t);
             match t.sty {
                 ty::TyInfer(ty::TyVar(vid)) => {
-                    self.err = Some(unresolved_ty(vid));
+                    self.err = Some(FixupError::UnresolvedTy(vid));
                     self.tcx().types.err
                 }
                 ty::TyInfer(ty::IntVar(vid)) => {
-                    self.err = Some(unresolved_int_ty(vid));
+                    self.err = Some(FixupError::UnresolvedIntTy(vid));
                     self.tcx().types.err
                 }
                 ty::TyInfer(ty::FloatVar(vid)) => {
-                    self.err = Some(unresolved_float_ty(vid));
+                    self.err = Some(FixupError::UnresolvedFloatTy(vid));
                     self.tcx().types.err
                 }
                 ty::TyInfer(_) => {
index f506de525ff9c644e1761e460ab52c21cd04fc71..bf47396bb9f656afdba931e1e18e178c52099744 100644 (file)
@@ -1614,7 +1614,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
 
 fn element_kind(t: Ty) -> ElementKind {
     match t.sty {
-        ty::TyRef(_, ty::mt{ty, ..}) |
+        ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
         ty::TyBox(ty) => match ty.sty {
             ty::TySlice(_) => VecElement,
             _ => OtherElement
index b5f01ada7e1789d4467eb62ee88c06564c5c9d3d..148b27adf64b241c475e3b84a6223767879c8a8e 100644 (file)
@@ -155,7 +155,7 @@ pub enum SelectionError<'tcx> {
     Unimplemented,
     OutputTypeParameterMismatch(ty::PolyTraitRef<'tcx>,
                                 ty::PolyTraitRef<'tcx>,
-                                ty::type_err<'tcx>),
+                                ty::TypeError<'tcx>),
     TraitNotObjectSafe(ast::DefId),
 }
 
index e29d9646509f9eac17bbe26a44620d8628e6143b..cd38e9d0d31bc529a6559d8b51cb23ae5142b4bf 100644 (file)
@@ -51,7 +51,7 @@ pub enum ProjectionTyError<'tcx> {
 
 #[derive(Clone)]
 pub struct MismatchedProjectionTypes<'tcx> {
-    pub err: ty::type_err<'tcx>
+    pub err: ty::TypeError<'tcx>
 }
 
 #[derive(PartialEq, Eq, Debug)]
index ad91f664af2db6ac7289cb2336be3eab7cefbb9f..e8a2e29b590b8a3d317745707400d68751326ddc 100644 (file)
@@ -1659,7 +1659,7 @@ fn builtin_bound(&mut self,
                 }
             }
 
-            ty::TyRef(_, ty::mt { ty: _, mutbl }) => {
+            ty::TyRef(_, ty::TypeAndMut { ty: _, mutbl }) => {
                 // &mut T or &T
                 match bound {
                     ty::BoundCopy => {
@@ -1851,8 +1851,8 @@ fn constituent_types_for_ty(&self, t: Ty<'tcx>) -> Option<Vec<Ty<'tcx>>> {
                 Some(vec![referent_ty])
             }
 
-            ty::TyRawPtr(ty::mt { ty: element_ty, ..}) |
-            ty::TyRef(_, ty::mt { ty: element_ty, ..}) => {
+            ty::TyRawPtr(ty::TypeAndMut { ty: element_ty, ..}) |
+            ty::TyRef(_, ty::TypeAndMut { ty: element_ty, ..}) => {
                 Some(vec![element_ty])
             },
 
@@ -2571,7 +2571,7 @@ fn confirm_builtin_unsize_candidate(&mut self,
                 for &i in &ty_params {
                     new_substs.types.get_mut_slice(TypeSpace)[i] = tcx.types.err;
                 }
-                for &ty in fields.init() {
+                for &ty in fields.split_last().unwrap().1 {
                     if ty.subst(tcx, &new_substs).references_error() {
                         return Err(Unimplemented);
                     }
index b4b8fbf2064adb5bfce97dcd5488785e66860475..5200ed1eb5b50706037e3acc1b89632af1f62cd2 100644 (file)
@@ -8,10 +8,9 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+// FIXME: (@jroesch) @eddyb should remove this when he renames ctxt
 #![allow(non_camel_case_types)]
 
-pub use self::terr_vstore_kind::*;
-pub use self::type_err::*;
 pub use self::InferTy::*;
 pub use self::InferRegion::*;
 pub use self::ImplOrTraitItemId::*;
@@ -109,9 +108,9 @@ pub struct CrateAnalysis {
 }
 
 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
-pub struct field<'tcx> {
+pub struct Field<'tcx> {
     pub name: ast::Name,
-    pub mt: mt<'tcx>
+    pub mt: TypeAndMut<'tcx>
 }
 
 
@@ -488,13 +487,13 @@ pub struct AssociatedType<'tcx> {
 }
 
 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
-pub struct mt<'tcx> {
+pub struct TypeAndMut<'tcx> {
     pub ty: Ty<'tcx>,
     pub mutbl: ast::Mutability,
 }
 
 #[derive(Clone, Copy, Debug)]
-pub struct field_ty {
+pub struct FieldTy {
     pub name: Name,
     pub id: DefId,
     pub vis: ast::Visibility,
@@ -674,7 +673,7 @@ pub fn autoderef(expr_id: ast::NodeId, autoderef: u32) -> MethodCall {
 // Contains information needed to resolve types and (in the future) look up
 // the types of AST nodes.
 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
-pub struct creader_cache_key {
+pub struct CReaderCacheKey {
     pub cnum: CrateNum,
     pub pos: usize,
     pub len: usize
@@ -864,7 +863,7 @@ pub struct ctxt<'tcx> {
     pub map: ast_map::Map<'tcx>,
     pub freevars: RefCell<FreevarMap>,
     pub tcache: RefCell<DefIdMap<TypeScheme<'tcx>>>,
-    pub rcache: RefCell<FnvHashMap<creader_cache_key, Ty<'tcx>>>,
+    pub rcache: RefCell<FnvHashMap<CReaderCacheKey, Ty<'tcx>>>,
     pub tc_cache: RefCell<FnvHashMap<Ty<'tcx>, TypeContents>>,
     pub ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
     pub enum_var_cache: RefCell<DefIdMap<Rc<Vec<Rc<VariantInfo<'tcx>>>>>>,
@@ -873,7 +872,7 @@ pub struct ctxt<'tcx> {
     pub lang_items: middle::lang_items::LanguageItems,
     /// A mapping of fake provided method def_ids to the default implementation
     pub provided_method_sources: RefCell<DefIdMap<ast::DefId>>,
-    pub struct_fields: RefCell<DefIdMap<Rc<Vec<field_ty>>>>,
+    pub struct_fields: RefCell<DefIdMap<Rc<Vec<FieldTy>>>>,
 
     /// Maps from def-id of a type or region parameter to its
     /// (inferred) variance.
@@ -1747,11 +1746,11 @@ pub enum TypeVariants<'tcx> {
     TySlice(Ty<'tcx>),
 
     /// A raw pointer. Written as `*mut T` or `*const T`
-    TyRawPtr(mt<'tcx>),
+    TyRawPtr(TypeAndMut<'tcx>),
 
     /// A reference; a pointer with an associated lifetime. Written as
     /// `&a mut T` or `&'a T`.
-    TyRef(&'tcx Region, mt<'tcx>),
+    TyRef(&'tcx Region, TypeAndMut<'tcx>),
 
     /// If the def-id is Some(_), then this is the type of a specific
     /// fn item. Otherwise, if None(_), it a fn pointer type.
@@ -1945,50 +1944,42 @@ pub enum IntVarValue {
 }
 
 #[derive(Clone, Copy, Debug)]
-pub enum terr_vstore_kind {
-    terr_vec,
-    terr_str,
-    terr_fn,
-    terr_trait
-}
-
-#[derive(Clone, Copy, Debug)]
-pub struct expected_found<T> {
+pub struct ExpectedFound<T> {
     pub expected: T,
     pub found: T
 }
 
 // Data structures used in type unification
 #[derive(Clone, Copy, Debug)]
-pub enum type_err<'tcx> {
-    terr_mismatch,
-    terr_unsafety_mismatch(expected_found<ast::Unsafety>),
-    terr_abi_mismatch(expected_found<abi::Abi>),
-    terr_mutability,
-    terr_box_mutability,
-    terr_ptr_mutability,
-    terr_ref_mutability,
-    terr_vec_mutability,
-    terr_tuple_size(expected_found<usize>),
-    terr_fixed_array_size(expected_found<usize>),
-    terr_ty_param_size(expected_found<usize>),
-    terr_arg_count,
-    terr_regions_does_not_outlive(Region, Region),
-    terr_regions_not_same(Region, Region),
-    terr_regions_no_overlap(Region, Region),
-    terr_regions_insufficiently_polymorphic(BoundRegion, Region),
-    terr_regions_overly_polymorphic(BoundRegion, Region),
-    terr_sorts(expected_found<Ty<'tcx>>),
-    terr_integer_as_char,
-    terr_int_mismatch(expected_found<IntVarValue>),
-    terr_float_mismatch(expected_found<ast::FloatTy>),
-    terr_traits(expected_found<ast::DefId>),
-    terr_builtin_bounds(expected_found<BuiltinBounds>),
-    terr_variadic_mismatch(expected_found<bool>),
-    terr_cyclic_ty,
-    terr_convergence_mismatch(expected_found<bool>),
-    terr_projection_name_mismatched(expected_found<ast::Name>),
-    terr_projection_bounds_length(expected_found<usize>),
+pub enum TypeError<'tcx> {
+    Mismatch,
+    UnsafetyMismatch(ExpectedFound<ast::Unsafety>),
+    AbiMismatch(ExpectedFound<abi::Abi>),
+    Mutability,
+    BoxMutability,
+    PtrMutability,
+    RefMutability,
+    VecMutability,
+    TupleSize(ExpectedFound<usize>),
+    FixedArraySize(ExpectedFound<usize>),
+    TyParamSize(ExpectedFound<usize>),
+    ArgCount,
+    RegionsDoesNotOutlive(Region, Region),
+    RegionsNotSame(Region, Region),
+    RegionsNoOverlap(Region, Region),
+    RegionsInsufficientlyPolymorphic(BoundRegion, Region),
+    RegionsOverlyPolymorphic(BoundRegion, Region),
+    Sorts(ExpectedFound<Ty<'tcx>>),
+    IntegerAsChar,
+    IntMismatch(ExpectedFound<IntVarValue>),
+    FloatMismatch(ExpectedFound<ast::FloatTy>),
+    Traits(ExpectedFound<ast::DefId>),
+    BuiltinBoundsMismatch(ExpectedFound<BuiltinBounds>),
+    VariadicMismatch(ExpectedFound<bool>),
+    CyclicTy,
+    ConvergenceMismatch(ExpectedFound<bool>),
+    ProjectionNameMismatched(ExpectedFound<ast::Name>),
+    ProjectionBoundsLength(ExpectedFound<usize>),
 }
 
 /// Bounds suitable for an existentially quantified type parameter
@@ -3573,28 +3564,28 @@ pub fn mk_box(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
         self.mk_ty(TyBox(ty))
     }
 
-    pub fn mk_ptr(&self, tm: mt<'tcx>) -> Ty<'tcx> {
+    pub fn mk_ptr(&self, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
         self.mk_ty(TyRawPtr(tm))
     }
 
-    pub fn mk_ref(&self, r: &'tcx Region, tm: mt<'tcx>) -> Ty<'tcx> {
+    pub fn mk_ref(&self, r: &'tcx Region, tm: TypeAndMut<'tcx>) -> Ty<'tcx> {
         self.mk_ty(TyRef(r, tm))
     }
 
     pub fn mk_mut_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
-        self.mk_ref(r, mt {ty: ty, mutbl: ast::MutMutable})
+        self.mk_ref(r, TypeAndMut {ty: ty, mutbl: ast::MutMutable})
     }
 
     pub fn mk_imm_ref(&self, r: &'tcx Region, ty: Ty<'tcx>) -> Ty<'tcx> {
-        self.mk_ref(r, mt {ty: ty, mutbl: ast::MutImmutable})
+        self.mk_ref(r, TypeAndMut {ty: ty, mutbl: ast::MutImmutable})
     }
 
     pub fn mk_mut_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
-        self.mk_ptr(mt {ty: ty, mutbl: ast::MutMutable})
+        self.mk_ptr(TypeAndMut {ty: ty, mutbl: ast::MutMutable})
     }
 
     pub fn mk_imm_ptr(&self, ty: Ty<'tcx>) -> Ty<'tcx> {
-        self.mk_ptr(mt {ty: ty, mutbl: ast::MutImmutable})
+        self.mk_ptr(TypeAndMut {ty: ty, mutbl: ast::MutImmutable})
     }
 
     pub fn mk_nil_ptr(&self) -> Ty<'tcx> {
@@ -4278,7 +4269,7 @@ fn tc_ty<'tcx>(cx: &ctxt<'tcx>,
         }
 
         fn tc_mt<'tcx>(cx: &ctxt<'tcx>,
-                       mt: mt<'tcx>,
+                       mt: TypeAndMut<'tcx>,
                        cache: &mut FnvHashMap<Ty<'tcx>, TypeContents>) -> TypeContents
         {
             let mc = TC::ReachesMutable.when(mt.mutbl == MutMutable);
@@ -4350,11 +4341,11 @@ pub fn moves_by_default<'a>(&'tcx self, param_env: &ParameterEnvironment<'a,'tcx
         // Fast-path for primitive types
         let result = match self.sty {
             TyBool | TyChar | TyInt(..) | TyUint(..) | TyFloat(..) |
-            TyRawPtr(..) | TyBareFn(..) | TyRef(_, mt {
+            TyRawPtr(..) | TyBareFn(..) | TyRef(_, TypeAndMut {
                 mutbl: ast::MutImmutable, ..
             }) => Some(false),
 
-            TyStr | TyBox(..) | TyRef(_, mt {
+            TyStr | TyBox(..) | TyRef(_, TypeAndMut {
                 mutbl: ast::MutMutable, ..
             }) => Some(true),
 
@@ -4789,10 +4780,10 @@ pub fn is_c_like_enum(&self, cx: &ctxt) -> bool {
     //
     // The parameter `explicit` indicates if this is an *explicit* dereference.
     // Some types---notably unsafe ptrs---can only be dereferenced explicitly.
-    pub fn builtin_deref(&self, explicit: bool) -> Option<mt<'tcx>> {
+    pub fn builtin_deref(&self, explicit: bool) -> Option<TypeAndMut<'tcx>> {
         match self.sty {
             TyBox(ty) => {
-                Some(mt {
+                Some(TypeAndMut {
                     ty: ty,
                     mutbl: ast::MutImmutable,
                 })
@@ -4931,15 +4922,16 @@ pub fn adjust_for_autoref(&'tcx self, cx: &ctxt<'tcx>,
         match autoref {
             None => self,
             Some(AutoPtr(r, m)) => {
-                cx.mk_ref(r, mt { ty: self, mutbl: m })
+                cx.mk_ref(r, TypeAndMut { ty: self, mutbl: m })
             }
             Some(AutoUnsafe(m)) => {
-                cx.mk_ptr(mt { ty: self, mutbl: m })
+                cx.mk_ptr(TypeAndMut { ty: self, mutbl: m })
             }
         }
     }
 
     fn sort_string(&self, cx: &ctxt) -> String {
+
         match self.sty {
             TyBool | TyChar | TyInt(_) |
             TyUint(_) | TyFloat(_) | TyStr => self.to_string(),
@@ -4983,67 +4975,69 @@ fn sort_string(&self, cx: &ctxt) -> String {
 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
 /// afterwards to present additional details, particularly when it comes to lifetime-related
 /// errors.
-impl<'tcx> fmt::Display for type_err<'tcx> {
+impl<'tcx> fmt::Display for TypeError<'tcx> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        use self::TypeError::*;
+
         match *self {
-            terr_cyclic_ty => write!(f, "cyclic type of infinite size"),
-            terr_mismatch => write!(f, "types differ"),
-            terr_unsafety_mismatch(values) => {
+            CyclicTy => write!(f, "cyclic type of infinite size"),
+            Mismatch => write!(f, "types differ"),
+            UnsafetyMismatch(values) => {
                 write!(f, "expected {} fn, found {} fn",
                        values.expected,
                        values.found)
             }
-            terr_abi_mismatch(values) => {
+            AbiMismatch(values) => {
                 write!(f, "expected {} fn, found {} fn",
                        values.expected,
                        values.found)
             }
-            terr_mutability => write!(f, "values differ in mutability"),
-            terr_box_mutability => {
+            Mutability => write!(f, "values differ in mutability"),
+            BoxMutability => {
                 write!(f, "boxed values differ in mutability")
             }
-            terr_vec_mutability => write!(f, "vectors differ in mutability"),
-            terr_ptr_mutability => write!(f, "pointers differ in mutability"),
-            terr_ref_mutability => write!(f, "references differ in mutability"),
-            terr_ty_param_size(values) => {
+            VecMutability => write!(f, "vectors differ in mutability"),
+            PtrMutability => write!(f, "pointers differ in mutability"),
+            RefMutability => write!(f, "references differ in mutability"),
+            TyParamSize(values) => {
                 write!(f, "expected a type with {} type params, \
                            found one with {} type params",
                        values.expected,
                        values.found)
             }
-            terr_fixed_array_size(values) => {
+            FixedArraySize(values) => {
                 write!(f, "expected an array with a fixed size of {} elements, \
                            found one with {} elements",
                        values.expected,
                        values.found)
             }
-            terr_tuple_size(values) => {
+            TupleSize(values) => {
                 write!(f, "expected a tuple with {} elements, \
                            found one with {} elements",
                        values.expected,
                        values.found)
             }
-            terr_arg_count => {
+            ArgCount => {
                 write!(f, "incorrect number of function parameters")
             }
-            terr_regions_does_not_outlive(..) => {
+            RegionsDoesNotOutlive(..) => {
                 write!(f, "lifetime mismatch")
             }
-            terr_regions_not_same(..) => {
+            RegionsNotSame(..) => {
                 write!(f, "lifetimes are not the same")
             }
-            terr_regions_no_overlap(..) => {
+            RegionsNoOverlap(..) => {
                 write!(f, "lifetimes do not intersect")
             }
-            terr_regions_insufficiently_polymorphic(br, _) => {
+            RegionsInsufficientlyPolymorphic(br, _) => {
                 write!(f, "expected bound lifetime parameter {}, \
                            found concrete lifetime", br)
             }
-            terr_regions_overly_polymorphic(br, _) => {
+            RegionsOverlyPolymorphic(br, _) => {
                 write!(f, "expected concrete lifetime, \
                            found bound lifetime parameter {}", br)
             }
-            terr_sorts(values) => tls::with(|tcx| {
+            Sorts(values) => tls::with(|tcx| {
                 // A naive approach to making sure that we're not reporting silly errors such as:
                 // (expected closure, found closure).
                 let expected_str = values.expected.sort_string(tcx);
@@ -5054,12 +5048,12 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                     write!(f, "expected {}, found {}", expected_str, found_str)
                 }
             }),
-            terr_traits(values) => tls::with(|tcx| {
+            Traits(values) => tls::with(|tcx| {
                 write!(f, "expected trait `{}`, found trait `{}`",
                        tcx.item_path_str(values.expected),
                        tcx.item_path_str(values.found))
             }),
-            terr_builtin_bounds(values) => {
+            BuiltinBoundsMismatch(values) => {
                 if values.expected.is_empty() {
                     write!(f, "expected no bounds, found `{}`",
                            values.found)
@@ -5072,35 +5066,35 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                            values.found)
                 }
             }
-            terr_integer_as_char => {
+            IntegerAsChar => {
                 write!(f, "expected an integral type, found `char`")
             }
-            terr_int_mismatch(ref values) => {
+            IntMismatch(ref values) => {
                 write!(f, "expected `{:?}`, found `{:?}`",
                        values.expected,
                        values.found)
             }
-            terr_float_mismatch(ref values) => {
+            FloatMismatch(ref values) => {
                 write!(f, "expected `{:?}`, found `{:?}`",
                        values.expected,
                        values.found)
             }
-            terr_variadic_mismatch(ref values) => {
+            VariadicMismatch(ref values) => {
                 write!(f, "expected {} fn, found {} function",
                        if values.expected { "variadic" } else { "non-variadic" },
                        if values.found { "variadic" } else { "non-variadic" })
             }
-            terr_convergence_mismatch(ref values) => {
+            ConvergenceMismatch(ref values) => {
                 write!(f, "expected {} fn, found {} function",
                        if values.expected { "converging" } else { "diverging" },
                        if values.found { "converging" } else { "diverging" })
             }
-            terr_projection_name_mismatched(ref values) => {
+            ProjectionNameMismatched(ref values) => {
                 write!(f, "expected {}, found {}",
                        values.expected,
                        values.found)
             }
-            terr_projection_bounds_length(ref values) => {
+            ProjectionBoundsLength(ref values) => {
                 write!(f, "expected {} associated type bindings, found {}",
                        values.expected,
                        values.found)
@@ -5408,7 +5402,7 @@ pub fn expr_is_lval(&self, expr: &ast::Expr) -> bool {
         }
     }
 
-    pub fn field_idx_strict(&self, name: ast::Name, fields: &[field])
+    pub fn field_idx_strict(&self, name: ast::Name, fields: &[Field<'tcx>])
                             -> usize {
         let mut i = 0;
         for f in fields { if f.name == name { return i; } i += 1; }
@@ -5420,36 +5414,38 @@ pub fn field_idx_strict(&self, name: ast::Name, fields: &[field])
                   .collect::<Vec<String>>()));
     }
 
-    pub fn note_and_explain_type_err(&self, err: &type_err<'tcx>, sp: Span) {
+    pub fn note_and_explain_type_err(&self, err: &TypeError<'tcx>, sp: Span) {
+        use self::TypeError::*;
+
         match *err {
-            terr_regions_does_not_outlive(subregion, superregion) => {
+            RegionsDoesNotOutlive(subregion, superregion) => {
                 self.note_and_explain_region("", subregion, "...");
                 self.note_and_explain_region("...does not necessarily outlive ",
                                            superregion, "");
             }
-            terr_regions_not_same(region1, region2) => {
+            RegionsNotSame(region1, region2) => {
                 self.note_and_explain_region("", region1, "...");
                 self.note_and_explain_region("...is not the same lifetime as ",
                                            region2, "");
             }
-            terr_regions_no_overlap(region1, region2) => {
+            RegionsNoOverlap(region1, region2) => {
                 self.note_and_explain_region("", region1, "...");
                 self.note_and_explain_region("...does not overlap ",
                                            region2, "");
             }
-            terr_regions_insufficiently_polymorphic(_, conc_region) => {
+            RegionsInsufficientlyPolymorphic(_, conc_region) => {
                 self.note_and_explain_region("concrete lifetime that was found is ",
                                            conc_region, "");
             }
-            terr_regions_overly_polymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
+            RegionsOverlyPolymorphic(_, ty::ReInfer(ty::ReVar(_))) => {
                 // don't bother to print out the message below for
                 // inference variables, it's not very illuminating.
             }
-            terr_regions_overly_polymorphic(_, conc_region) => {
+            RegionsOverlyPolymorphic(_, conc_region) => {
                 self.note_and_explain_region("expected concrete lifetime is ",
                                            conc_region, "");
             }
-            terr_sorts(values) => {
+            Sorts(values) => {
                 let expected_str = values.expected.sort_string(self);
                 let found_str = values.found.sort_string(self);
                 if expected_str == found_str && expected_str == "closure" {
@@ -5960,7 +5956,7 @@ pub fn lookup_field_type(&self,
 
     // Look up the list of field names and IDs for a given struct.
     // Panics if the id is not bound to a struct.
-    pub fn lookup_struct_fields(&self, did: ast::DefId) -> Vec<field_ty> {
+    pub fn lookup_struct_fields(&self, did: ast::DefId) -> Vec<FieldTy> {
         if did.krate == ast::LOCAL_CRATE {
             let struct_fields = self.struct_fields.borrow();
             match struct_fields.get(&did) {
@@ -5984,11 +5980,11 @@ pub fn is_tuple_struct(&self, did: ast::DefId) -> bool {
     // Returns a list of fields corresponding to the struct's items. trans uses
     // this. Takes a list of substs with which to instantiate field types.
     pub fn struct_fields(&self, did: ast::DefId, substs: &Substs<'tcx>)
-                         -> Vec<field<'tcx>> {
+                         -> Vec<Field<'tcx>> {
         self.lookup_struct_fields(did).iter().map(|f| {
-           field {
+           Field {
                 name: f.name,
-                mt: mt {
+                mt: TypeAndMut {
                     ty: self.lookup_field_type(did, f.id, substs),
                     mutbl: MutImmutable
                 }
@@ -6074,7 +6070,7 @@ pub fn closure_upvars<'a>(typer: &infer::InferCtxt<'a, 'tcx>,
                                     }
                                     UpvarCapture::ByRef(borrow) => {
                                         tcx.mk_ref(tcx.mk_region(borrow.region),
-                                            ty::mt {
+                                            ty::TypeAndMut {
                                                 ty: freevar_ty,
                                                 mutbl: borrow.kind.to_mutbl_lossy(),
                                             })
@@ -6427,7 +6423,7 @@ macro_rules! hash { ($e:expr) => { $e.hash(state) }  }
                 h.as_str().hash(state);
                 did.node.hash(state);
             };
-            let mt = |state: &mut SipHasher, mt: mt| {
+            let mt = |state: &mut SipHasher, mt: TypeAndMut| {
                 mt.mutbl.hash(state);
             };
             let fn_sig = |state: &mut SipHasher, sig: &Binder<FnSig<'tcx>>| {
@@ -7227,7 +7223,7 @@ fn has_type_flags(&self, flags: TypeFlags) -> bool {
     }
 }
 
-impl<'tcx> HasTypeFlags for field<'tcx> {
+impl<'tcx> HasTypeFlags for Field<'tcx> {
     fn has_type_flags(&self, flags: TypeFlags) -> bool {
         self.mt.ty.has_type_flags(flags)
     }
@@ -7256,7 +7252,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-impl<'tcx> fmt::Debug for field<'tcx> {
+impl<'tcx> fmt::Debug for Field<'tcx> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         write!(f, "field({},{})", self.name, self.mt)
     }
index 7016c1484659b7165da31aa66a5a778434824852..3cf5e6ffa039f0143b7245a48707b73578e3ccf0 100644 (file)
@@ -85,7 +85,7 @@ fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
         super_fold_ty(self, t)
     }
 
-    fn fold_mt(&mut self, t: &ty::mt<'tcx>) -> ty::mt<'tcx> {
+    fn fold_mt(&mut self, t: &ty::TypeAndMut<'tcx>) -> ty::TypeAndMut<'tcx> {
         super_fold_mt(self, t)
     }
 
@@ -251,8 +251,8 @@ fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::ClosureTy<'tcx>
     }
 }
 
-impl<'tcx> TypeFoldable<'tcx> for ty::mt<'tcx> {
-    fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::mt<'tcx> {
+impl<'tcx> TypeFoldable<'tcx> for ty::TypeAndMut<'tcx> {
+    fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TypeAndMut<'tcx> {
         folder.fold_mt(self)
     }
 }
@@ -275,9 +275,9 @@ fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::TraitRef<'tcx> {
     }
 }
 
-impl<'tcx> TypeFoldable<'tcx> for ty::field<'tcx> {
-    fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::field<'tcx> {
-        ty::field {
+impl<'tcx> TypeFoldable<'tcx> for ty::Field<'tcx> {
+    fn fold_with<F: TypeFolder<'tcx>>(&self, folder: &mut F) -> ty::Field<'tcx> {
+        ty::Field {
             name: self.name,
             mt: self.mt.fold_with(folder),
         }
@@ -685,9 +685,9 @@ pub fn super_fold_trait_ref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
 }
 
 pub fn super_fold_mt<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
-                                                mt: &ty::mt<'tcx>)
-                                                -> ty::mt<'tcx> {
-    ty::mt {ty: mt.ty.fold_with(this),
+                                                mt: &ty::TypeAndMut<'tcx>)
+                                                -> ty::TypeAndMut<'tcx> {
+    ty::TypeAndMut {ty: mt.ty.fold_with(this),
             mutbl: mt.mutbl}
 }
 
index 5776235780a3a927b225d5e5d7074f72bb7bb63b..56b90e198a5c5500fb023f081eb0d3d7582f680e 100644 (file)
@@ -78,7 +78,7 @@ fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
 
             (&ty::TyInfer(_), _) |
             (_, &ty::TyInfer(_)) => {
-                Err(ty::terr_sorts(ty_relate::expected_found(self, &a, &b)))
+                Err(ty::TypeError::Sorts(ty_relate::expected_found(self, &a, &b)))
             }
 
             (&ty::TyError, _) | (_, &ty::TyError) => {
index b8b2469b2066737f05abd0a6cfe482352e5d1c41..3a4bb102146703f64872174c277f57502ea09720 100644 (file)
 //! type equality, etc.
 
 use middle::subst::{ErasedRegions, NonerasedRegions, ParamSpace, Substs};
-use middle::ty::{self, Ty};
+use middle::ty::{self, Ty, TypeError};
 use middle::ty_fold::TypeFoldable;
 use std::rc::Rc;
 use syntax::abi;
 use syntax::ast;
 
-pub type RelateResult<'tcx, T> = Result<T, ty::type_err<'tcx>>;
+pub type RelateResult<'tcx, T> = Result<T, ty::TypeError<'tcx>>;
 
 #[derive(Clone, Debug)]
 pub enum Cause {
@@ -89,11 +89,11 @@ fn relate<R:TypeRelation<'a,'tcx>>(relation: &mut R,
 ///////////////////////////////////////////////////////////////////////////
 // Relate impls
 
-impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::mt<'tcx> {
+impl<'a,'tcx:'a> Relate<'a,'tcx> for ty::TypeAndMut<'tcx> {
     fn relate<R>(relation: &mut R,
-                 a: &ty::mt<'tcx>,
-                 b: &ty::mt<'tcx>)
-                 -> RelateResult<'tcx, ty::mt<'tcx>>
+                 a: &ty::TypeAndMut<'tcx>,
+                 b: &ty::TypeAndMut<'tcx>)
+                 -> RelateResult<'tcx, ty::TypeAndMut<'tcx>>
         where R: TypeRelation<'a,'tcx>
     {
         debug!("{}.mts({:?}, {:?})",
@@ -101,7 +101,7 @@ fn relate<R>(relation: &mut R,
                a,
                b);
         if a.mutbl != b.mutbl {
-            Err(ty::terr_mutability)
+            Err(TypeError::Mutability)
         } else {
             let mutbl = a.mutbl;
             let variance = match mutbl {
@@ -109,7 +109,7 @@ fn relate<R>(relation: &mut R,
                 ast::MutMutable => ty::Invariant,
             };
             let ty = try!(relation.relate_with_variance(variance, &a.ty, &b.ty));
-            Ok(ty::mt {ty: ty, mutbl: mutbl})
+            Ok(ty::TypeAndMut {ty: ty, mutbl: mutbl})
         }
     }
 }
@@ -186,7 +186,7 @@ fn relate_type_params<'a,'tcx:'a,R>(relation: &mut R,
     where R: TypeRelation<'a,'tcx>
 {
     if a_tys.len() != b_tys.len() {
-        return Err(ty::terr_ty_param_size(expected_found(relation,
+        return Err(TypeError::TyParamSize(expected_found(relation,
                                                          &a_tys.len(),
                                                          &b_tys.len())));
     }
@@ -256,7 +256,7 @@ fn relate<R>(relation: &mut R,
         where R: TypeRelation<'a,'tcx>
     {
         if a.variadic != b.variadic {
-            return Err(ty::terr_variadic_mismatch(
+            return Err(TypeError::VariadicMismatch(
                 expected_found(relation, &a.variadic, &b.variadic)));
         }
 
@@ -270,7 +270,7 @@ fn relate<R>(relation: &mut R,
             (ty::FnDiverging, ty::FnDiverging) =>
                 Ok(ty::FnDiverging),
             (a, b) =>
-                Err(ty::terr_convergence_mismatch(
+                Err(TypeError::ConvergenceMismatch(
                     expected_found(relation, &(a != ty::FnDiverging), &(b != ty::FnDiverging)))),
         });
 
@@ -287,7 +287,7 @@ fn relate_arg_vecs<'a,'tcx:'a,R>(relation: &mut R,
     where R: TypeRelation<'a,'tcx>
 {
     if a_args.len() != b_args.len() {
-        return Err(ty::terr_arg_count);
+        return Err(TypeError::ArgCount);
     }
 
     a_args.iter().zip(b_args)
@@ -303,7 +303,7 @@ fn relate<R>(relation: &mut R,
         where R: TypeRelation<'a,'tcx>
     {
         if a != b {
-            Err(ty::terr_unsafety_mismatch(expected_found(relation, a, b)))
+            Err(TypeError::UnsafetyMismatch(expected_found(relation, a, b)))
         } else {
             Ok(*a)
         }
@@ -320,7 +320,7 @@ fn relate<R>(relation: &mut R,
         if a == b {
             Ok(*a)
         } else {
-            Err(ty::terr_abi_mismatch(expected_found(relation, a, b)))
+            Err(TypeError::AbiMismatch(expected_found(relation, a, b)))
         }
     }
 }
@@ -333,7 +333,7 @@ fn relate<R>(relation: &mut R,
         where R: TypeRelation<'a,'tcx>
     {
         if a.item_name != b.item_name {
-            Err(ty::terr_projection_name_mismatched(
+            Err(TypeError::ProjectionNameMismatched(
                 expected_found(relation, &a.item_name, &b.item_name)))
         } else {
             let trait_ref = try!(relation.relate(&a.trait_ref, &b.trait_ref));
@@ -368,7 +368,7 @@ fn relate<R>(relation: &mut R,
         // so we can just iterate through the lists pairwise, so long as they are the
         // same length.
         if a.len() != b.len() {
-            Err(ty::terr_projection_bounds_length(expected_found(relation, &a.len(), &b.len())))
+            Err(TypeError::ProjectionBoundsLength(expected_found(relation, &a.len(), &b.len())))
         } else {
             a.iter().zip(b)
                 .map(|(a, b)| relation.relate(a, b))
@@ -412,7 +412,7 @@ fn relate<R>(relation: &mut R,
         // Two sets of builtin bounds are only relatable if they are
         // precisely the same (but see the coercion code).
         if a != b {
-            Err(ty::terr_builtin_bounds(expected_found(relation, a, b)))
+            Err(TypeError::BuiltinBoundsMismatch(expected_found(relation, a, b)))
         } else {
             Ok(*a)
         }
@@ -428,7 +428,7 @@ fn relate<R>(relation: &mut R,
     {
         // Different traits cannot be related
         if a.def_id != b.def_id {
-            Err(ty::terr_traits(expected_found(relation, &a.def_id, &b.def_id)))
+            Err(TypeError::Traits(expected_found(relation, &a.def_id, &b.def_id)))
         } else {
             let substs = try!(relate_item_substs(relation, a.def_id, a.substs, b.substs));
             Ok(ty::TraitRef { def_id: a.def_id, substs: relation.tcx().mk_substs(substs) })
@@ -547,7 +547,7 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
             if sz_a == sz_b {
                 Ok(tcx.mk_array(t, sz_a))
             } else {
-                Err(ty::terr_fixed_array_size(expected_found(relation, &sz_a, &sz_b)))
+                Err(TypeError::FixedArraySize(expected_found(relation, &sz_a, &sz_b)))
             }
         }
 
@@ -565,10 +565,10 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
                                  .collect::<Result<_, _>>());
                 Ok(tcx.mk_tup(ts))
             } else if !(as_.is_empty() || bs.is_empty()) {
-                Err(ty::terr_tuple_size(
+                Err(TypeError::TupleSize(
                     expected_found(relation, &as_.len(), &bs.len())))
             } else {
-                Err(ty::terr_sorts(expected_found(relation, &a, &b)))
+                Err(TypeError::Sorts(expected_found(relation, &a, &b)))
             }
         }
 
@@ -587,7 +587,7 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
 
         _ =>
         {
-            Err(ty::terr_sorts(expected_found(relation, &a, &b)))
+            Err(TypeError::Sorts(expected_found(relation, &a, &b)))
         }
     }
 }
@@ -652,7 +652,7 @@ fn relate<R>(relation: &mut R,
 pub fn expected_found<'a,'tcx:'a,R,T>(relation: &mut R,
                                       a: &T,
                                       b: &T)
-                                      -> ty::expected_found<T>
+                                      -> ty::ExpectedFound<T>
     where R: TypeRelation<'a,'tcx>, T: Clone
 {
     expected_found_bool(relation.a_is_expected(), a, b)
@@ -661,14 +661,14 @@ pub fn expected_found<'a,'tcx:'a,R,T>(relation: &mut R,
 pub fn expected_found_bool<T>(a_is_expected: bool,
                               a: &T,
                               b: &T)
-                              -> ty::expected_found<T>
+                              -> ty::ExpectedFound<T>
     where T: Clone
 {
     let a = a.clone();
     let b = b.clone();
     if a_is_expected {
-        ty::expected_found {expected: a, found: b}
+        ty::ExpectedFound {expected: a, found: b}
     } else {
-        ty::expected_found {expected: b, found: a}
+        ty::ExpectedFound {expected: b, found: a}
     }
 }
index 9d82b0c2aa8a0ef8ab08baa1b4d3c6b4ba2372a0..4d60500ecf6b9d561ad2739a656bcc54eef2a161 100644 (file)
@@ -19,7 +19,7 @@
 use middle::ty::{TyParam, TyRawPtr, TyRef, TyTuple};
 use middle::ty::TyClosure;
 use middle::ty::{TyBox, TyTrait, TyInt, TyUint, TyInfer};
-use middle::ty::{self, mt, Ty, HasTypeFlags};
+use middle::ty::{self, TypeAndMut, Ty, HasTypeFlags};
 use middle::ty_fold::{self, TypeFoldable};
 
 use std::fmt;
@@ -321,7 +321,7 @@ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
     }
 }
 
-impl<'tcx> fmt::Display for ty::mt<'tcx> {
+impl<'tcx> fmt::Display for ty::TypeAndMut<'tcx> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         write!(f, "{}{}",
                if self.mutbl == ast::MutMutable { "mut " } else { "" },
diff --git a/src/librustc_back/target/i686_unknown_freebsd.rs b/src/librustc_back/target/i686_unknown_freebsd.rs
new file mode 100644 (file)
index 0000000..d347740
--- /dev/null
@@ -0,0 +1,29 @@
+// 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 target::Target;
+
+pub fn target() -> Target {
+    let mut base = super::freebsd_base::opts();
+    base.cpu = "pentium4".to_string();
+    base.pre_link_args.push("-m32".to_string());
+    base.morestack = false;
+
+    Target {
+        data_layout: "e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32".to_string(),
+        llvm_target: "i686-unknown-freebsd".to_string(),
+        target_endian: "little".to_string(),
+        target_pointer_width: "32".to_string(),
+        arch: "x86".to_string(),
+        target_os: "freebsd".to_string(),
+        target_env: "".to_string(),
+        options: base,
+    }
+}
index 8ecee61621941a7eb735028f8e234ce8fd0e6e68..185d1c9428e86106f00b37499b9c7632fd6a150c 100644 (file)
@@ -368,6 +368,7 @@ macro_rules! load_specific {
             arm_linux_androideabi,
             aarch64_linux_android,
 
+            i686_unknown_freebsd,
             x86_64_unknown_freebsd,
 
             i686_unknown_dragonfly,
index 30d5a4f111ba43e9b41bdd3636c52e947ae7714d..dd26fd25215a3f27e2d04ff7de6969079a438f86 100644 (file)
@@ -276,7 +276,7 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
                 let module_path = match view_path.node {
                     ViewPathSimple(_, ref full_path) => {
                         full_path.segments
-                            .init()
+                            .split_last().unwrap().1
                             .iter().map(|ident| ident.identifier.name)
                             .collect()
                     }
@@ -347,7 +347,7 @@ fn build_reduced_graph_for_item(&mut self, item: &Item, parent: &Rc<Module>) ->
                                             continue;
                                         }
                                     };
-                                    let module_path = module_path.init();
+                                    let module_path = module_path.split_last().unwrap().1;
                                     (module_path.to_vec(), name)
                                 }
                             };
index 0ec3979ccfb30ab6a1d4a2af100aa79ad9b60ac7..1093d2ef318159cab4b59281ab4786fd521061ec 100644 (file)
@@ -23,7 +23,7 @@
 #![feature(rc_weak)]
 #![feature(rustc_diagnostic_macros)]
 #![feature(rustc_private)]
-#![feature(slice_extras)]
+#![feature(slice_splits)]
 #![feature(staged_api)]
 
 #[macro_use] extern crate log;
@@ -2881,7 +2881,7 @@ fn resolve_module_relative_path(&mut self,
                                     segments: &[ast::PathSegment],
                                     namespace: Namespace)
                                     -> Option<(Def, LastPrivate)> {
-        let module_path = segments.init().iter()
+        let module_path = segments.split_last().unwrap().1.iter()
                                          .map(|ps| ps.identifier.name)
                                          .collect::<Vec<_>>();
 
@@ -2939,7 +2939,7 @@ fn resolve_crate_relative_path(&mut self,
                                    segments: &[ast::PathSegment],
                                    namespace: Namespace)
                                        -> Option<(Def, LastPrivate)> {
-        let module_path = segments.init().iter()
+        let module_path = segments.split_last().unwrap().1.iter()
                                          .map(|ps| ps.identifier.name)
                                          .collect::<Vec<_>>();
 
index eca9891c57cb70e1611caea53efcc2fda3f16718..2b480abe3f1f3fc4c59906ae30f6ccd9bef012e6 100644 (file)
@@ -398,7 +398,7 @@ fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
                                     mut path: DiscrField) -> Option<DiscrField> {
     match ty.sty {
         // Fat &T/&mut T/Box<T> i.e. T is [T], str, or Trait
-        ty::TyRef(_, ty::mt { ty, .. }) | ty::TyBox(ty) if !type_is_sized(tcx, ty) => {
+        ty::TyRef(_, ty::TypeAndMut { ty, .. }) | ty::TyBox(ty) if !type_is_sized(tcx, ty) => {
             path.push(FAT_PTR_ADDR);
             Some(path)
         },
@@ -415,7 +415,7 @@ fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
             assert_eq!(nonzero_fields.len(), 1);
             let nonzero_field = tcx.lookup_field_type(did, nonzero_fields[0].id, substs);
             match nonzero_field.sty {
-                ty::TyRawPtr(ty::mt { ty, .. }) if !type_is_sized(tcx, ty) => {
+                ty::TyRawPtr(ty::TypeAndMut { ty, .. }) if !type_is_sized(tcx, ty) => {
                     path.push_all(&[0, FAT_PTR_ADDR]);
                     Some(path)
                 },
index 25cde149df109502a3d3db6d27fb96c20743e00f..f8daefa87a5ff51aa10130df94ed202b32034c70 100644 (file)
@@ -223,7 +223,7 @@ pub fn from_fn_type<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, fn_type: ty::Ty<'tcx
             // We can also mark the return value as `dereferenceable` in certain cases
             match ret_ty.sty {
                 // These are not really pointers but pairs, (pointer, len)
-                ty::TyRef(_, ty::mt { ty: inner, .. })
+                ty::TyRef(_, ty::TypeAndMut { ty: inner, .. })
                 | ty::TyBox(inner) if common::type_is_sized(ccx.tcx(), inner) => {
                     let llret_sz = machine::llsize_of_real(ccx, type_of::type_of(ccx, inner));
                     attrs.ret(llvm::DereferenceableAttribute(llret_sz));
index a4559708bf4e8144d30ab4e51b2b1ea3a8253847..2f5f5345e64187fe32172ff5ef1ee377d558d86b 100644 (file)
@@ -130,8 +130,8 @@ pub fn type_is_sized<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
 
 pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
     match ty.sty {
-        ty::TyRawPtr(ty::mt{ty, ..}) |
-        ty::TyRef(_, ty::mt{ty, ..}) |
+        ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
+        ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
         ty::TyBox(ty) => {
             !type_is_sized(cx, ty)
         }
index 5b6d939d9e6235fd319d5bd3018d2bb5c09d433a..242eceb8335b2c9b27e35fc2452e33ff48324171 100644 (file)
@@ -620,7 +620,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
 
             let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
             let len = match bt.sty {
-                ty::TyBox(ty) | ty::TyRef(_, ty::mt{ty, ..}) => match ty.sty {
+                ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
                     ty::TyStr => {
                         assert!(len > 0);
                         len - 1
index 45d8fa67db683bdc78f64575d305ac730d75096c..ed494d0765bb0a298b73a702a28c1e4360beb283 100644 (file)
@@ -206,7 +206,7 @@ fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
                 unique_type_id.push_str(&inner_type_id[..]);
             },
-            ty::TyRawPtr(ty::mt { ty: inner_type, mutbl } ) => {
+            ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
                 unique_type_id.push('*');
                 if mutbl == ast::MutMutable {
                     unique_type_id.push_str("mut");
@@ -216,7 +216,7 @@ fn get_unique_type_id_of_type<'a>(&mut self, cx: &CrateContext<'a, 'tcx>,
                 let inner_type_id = self.get_unique_type_id_as_string(inner_type_id);
                 unique_type_id.push_str(&inner_type_id[..]);
             },
-            ty::TyRef(_, ty::mt { ty: inner_type, mutbl }) => {
+            ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
                 unique_type_id.push('&');
                 if mutbl == ast::MutMutable {
                     unique_type_id.push_str("mut");
@@ -561,7 +561,7 @@ fn vec_slice_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                                 unique_type_id: UniqueTypeId,
                                 span: Span)
                                 -> MetadataCreationResult {
-    let data_ptr_type = cx.tcx().mk_ptr(ty::mt {
+    let data_ptr_type = cx.tcx().mk_ptr(ty::TypeAndMut {
         ty: element_type,
         mutbl: ast::MutImmutable
     });
@@ -765,7 +765,9 @@ pub fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
                         trait_pointer_metadata(cx, t, None, unique_type_id),
             false)
         }
-        ty::TyBox(ty) | ty::TyRawPtr(ty::mt{ty, ..}) | ty::TyRef(_, ty::mt{ty, ..}) => {
+        ty::TyBox(ty) |
+        ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
+        ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
             match ty.sty {
                 ty::TySlice(typ) => {
                     vec_slice_metadata(cx, t, typ, unique_type_id, usage_site_span)
@@ -1113,7 +1115,7 @@ fn create_member_descriptions<'a>(&self, cx: &CrateContext<'a, 'tcx>)
 
 // Creates MemberDescriptions for the fields of a struct
 struct StructMemberDescriptionFactory<'tcx> {
-    fields: Vec<ty::field<'tcx>>,
+    fields: Vec<ty::Field<'tcx>>,
     is_simd: bool,
     span: Span,
 }
index f411688319981a72bc551ed8e6c317d8f9f5fb55..b912acb90a2cec32c9a68153073af153558e16ff 100644 (file)
@@ -77,7 +77,7 @@ pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
             push_debuginfo_type_name(cx, inner_type, true, output);
             output.push('>');
         },
-        ty::TyRawPtr(ty::mt { ty: inner_type, mutbl } ) => {
+        ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
             output.push('*');
             match mutbl {
                 ast::MutImmutable => output.push_str("const "),
@@ -86,7 +86,7 @@ pub fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
 
             push_debuginfo_type_name(cx, inner_type, true, output);
         },
-        ty::TyRef(_, ty::mt { ty: inner_type, mutbl }) => {
+        ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
             output.push('&');
             if mutbl == ast::MutMutable {
                 output.push_str("mut ");
index f62e4d43cc6c073bf54d9587b1eb17abf66763ec..f7ace78512013789af3369cb6748cf010e5f26c1 100644 (file)
@@ -438,9 +438,12 @@ fn coerce_unsized<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
 
     match (&source.ty.sty, &target.ty.sty) {
         (&ty::TyBox(a), &ty::TyBox(b)) |
-        (&ty::TyRef(_, ty::mt { ty: a, .. }), &ty::TyRef(_, ty::mt { ty: b, .. })) |
-        (&ty::TyRef(_, ty::mt { ty: a, .. }), &ty::TyRawPtr(ty::mt { ty: b, .. })) |
-        (&ty::TyRawPtr(ty::mt { ty: a, .. }), &ty::TyRawPtr(ty::mt { ty: b, .. })) => {
+        (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
+         &ty::TyRef(_, ty::TypeAndMut { ty: b, .. })) |
+        (&ty::TyRef(_, ty::TypeAndMut { ty: a, .. }),
+         &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) |
+        (&ty::TyRawPtr(ty::TypeAndMut { ty: a, .. }),
+         &ty::TyRawPtr(ty::TypeAndMut { ty: b, .. })) => {
             let (inner_source, inner_target) = (a, b);
 
             let (base, old_info) = if !type_is_sized(bcx.tcx(), inner_source) {
@@ -705,7 +708,7 @@ fn trans_field<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
                               base: &ast::Expr,
                               get_idx: F)
                               -> DatumBlock<'blk, 'tcx, Expr> where
-    F: FnOnce(&'blk ty::ctxt<'tcx>, &[ty::field<'tcx>]) -> usize,
+    F: FnOnce(&'blk ty::ctxt<'tcx>, &[ty::Field<'tcx>]) -> usize,
 {
     let mut bcx = bcx;
     let _icx = push_ctxt("trans_rec_field");
@@ -1331,7 +1334,7 @@ pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>,
                                   node_id_opt: Option<ast::NodeId>,
                                   op: F)
                                   -> R where
-    F: FnOnce(ty::Disr, &[ty::field<'tcx>]) -> R,
+    F: FnOnce(ty::Disr, &[ty::Field<'tcx>]) -> R,
 {
     match ty.sty {
         ty::TyStruct(did, substs) => {
@@ -1342,9 +1345,9 @@ pub fn with_field_tys<'tcx, R, F>(tcx: &ty::ctxt<'tcx>,
 
         ty::TyTuple(ref v) => {
             let fields: Vec<_> = v.iter().enumerate().map(|(i, &f)| {
-                ty::field {
+                ty::Field {
                     name: token::intern(&i.to_string()),
-                    mt: ty::mt {
+                    mt: ty::TypeAndMut {
                         ty: f,
                         mutbl: ast::MutImmutable
                     }
@@ -1990,7 +1993,7 @@ pub fn cast_is_noop<'tcx>(tcx: &ty::ctxt<'tcx>,
     }
 
     match (t_in.builtin_deref(true), t_out.builtin_deref(true)) {
-        (Some(ty::mt{ ty: t_in, .. }), Some(ty::mt{ ty: t_out, .. })) => {
+        (Some(ty::TypeAndMut{ ty: t_in, .. }), Some(ty::TypeAndMut{ ty: t_out, .. })) => {
             t_in == t_out
         }
         _ => {
@@ -2271,8 +2274,8 @@ fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
             }
         }
 
-        ty::TyRawPtr(ty::mt { ty: content_ty, .. }) |
-        ty::TyRef(_, ty::mt { ty: content_ty, .. }) => {
+        ty::TyRawPtr(ty::TypeAndMut { ty: content_ty, .. }) |
+        ty::TyRef(_, ty::TypeAndMut { ty: content_ty, .. }) => {
             if type_is_sized(bcx.tcx(), content_ty) {
                 let ptr = datum.to_llscalarish(bcx);
 
index d94a0e235ee861fd3316451dc22ec7dc75e3b380..0e05ca52959fbc3fa64ade5cface2a3b758e94df 100644 (file)
@@ -315,7 +315,7 @@ pub fn get_base_and_len<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
         }
 
         // Only used for pattern matching.
-        ty::TyBox(ty) | ty::TyRef(_, ty::mt{ty, ..}) => {
+        ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => {
             let inner = if type_is_sized(bcx.tcx(), ty) {
                 Load(bcx, llval)
             } else {
index 36905ffe93b942a320e106c6d9be06559f44715e..c5161a8bc2e7807f142c258929b4152e36a077a8 100644 (file)
@@ -193,7 +193,9 @@ pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Typ
         ty::TyUint(t) => Type::uint_from_ty(cx, t),
         ty::TyFloat(t) => Type::float_from_ty(cx, t),
 
-        ty::TyBox(ty) | ty::TyRef(_, ty::mt{ty, ..}) | ty::TyRawPtr(ty::mt{ty, ..}) => {
+        ty::TyBox(ty) |
+        ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
+        ty::TyRawPtr(ty::TypeAndMut{ty, ..}) => {
             if type_is_sized(cx.tcx(), ty) {
                 Type::i8p(cx)
             } else {
@@ -352,7 +354,9 @@ pub fn in_memory_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) ->
           adt::incomplete_type_of(cx, &*repr, "closure")
       }
 
-      ty::TyBox(ty) | ty::TyRef(_, ty::mt{ty, ..}) | ty::TyRawPtr(ty::mt{ty, ..}) => {
+      ty::TyBox(ty) |
+      ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
+      ty::TyRawPtr(ty::TypeAndMut{ty, ..}) => {
           if !type_is_sized(cx.tcx(), ty) {
               if let ty::TyStr = ty.sty {
                   // This means we get a nicer name in the output (str is always
index ef3c858bed5862b21ec620d3f3b32207b4972732..a57fc60e923462fdd94ad48df03402a6bc596553 100644 (file)
@@ -1402,7 +1402,7 @@ fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
                                                           base_segments.last().unwrap(),
                                                           &mut projection_bounds);
 
-            check_path_args(tcx, base_segments.init(), NO_TPS | NO_REGIONS);
+            check_path_args(tcx, base_segments.split_last().unwrap().1, NO_TPS | NO_REGIONS);
             trait_ref_to_object_type(this,
                                      rscope,
                                      span,
@@ -1411,7 +1411,7 @@ fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
                                      &[])
         }
         def::DefTy(did, _) | def::DefStruct(did) => {
-            check_path_args(tcx, base_segments.init(), NO_TPS | NO_REGIONS);
+            check_path_args(tcx, base_segments.split_last().unwrap().1, NO_TPS | NO_REGIONS);
             ast_path_to_ty(this,
                            rscope,
                            span,
@@ -1555,7 +1555,7 @@ pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
             }
         }
         ast::TyPtr(ref mt) => {
-            tcx.mk_ptr(ty::mt {
+            tcx.mk_ptr(ty::TypeAndMut {
                 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
                 mutbl: mt.mutbl
             })
@@ -1568,7 +1568,7 @@ pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
                     rscope,
                     ty::ObjectLifetimeDefault::Specific(r));
             let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
-            tcx.mk_ref(tcx.mk_region(r), ty::mt {ty: t, mutbl: mt.mutbl})
+            tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
         }
         ast::TyTup(ref fields) => {
             let flds = fields.iter()
@@ -1754,7 +1754,7 @@ fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
                 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
                     (Some(this.tcx().mk_ref(
                                       this.tcx().mk_region(region),
-                                      ty::mt {
+                                      ty::TypeAndMut {
                                         ty: self_info.untransformed_self_ty,
                                         mutbl: mutability
                                       })),
index 87f867d7f90acdfe3347e00070711fa3760ad4fe..a995401cf5c81d9b7bbb1cb5da7a545b376f27fd 100644 (file)
@@ -170,7 +170,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
                     // then `x` is assigned a value of type `&M T` where M is the mutability
                     // and T is the expected type.
                     let region_var = fcx.infcx().next_region_var(infer::PatternRegion(pat.span));
-                    let mt = ty::mt { ty: expected, mutbl: mutbl };
+                    let mt = ty::TypeAndMut { ty: expected, mutbl: mutbl };
                     let region_ty = tcx.mk_ref(tcx.mk_region(region_var), mt);
 
                     // `x` is assigned a value of type `&M T`, hence `&M T <: typeof(x)` is
@@ -272,7 +272,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
         ast::PatRegion(ref inner, mutbl) => {
             let inner_ty = fcx.infcx().next_ty_var();
 
-            let mt = ty::mt { ty: inner_ty, mutbl: mutbl };
+            let mt = ty::TypeAndMut { ty: inner_ty, mutbl: mutbl };
             let region = fcx.infcx().next_region_var(infer::PatternRegion(pat.span));
             let rptr_ty = tcx.mk_ref(tcx.mk_region(region), mt);
 
@@ -301,7 +301,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
                 }),
                 _ => {
                     let region = fcx.infcx().next_region_var(infer::PatternRegion(pat.span));
-                    tcx.mk_ref(tcx.mk_region(region), ty::mt {
+                    tcx.mk_ref(tcx.mk_region(region), ty::TypeAndMut {
                         ty: tcx.mk_slice(inner_ty),
                         mutbl: expected_ty.builtin_deref(true).map(|mt| mt.mutbl)
                                                               .unwrap_or(ast::MutImmutable)
@@ -324,7 +324,7 @@ pub fn check_pat<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
                 let mutbl = expected_ty.builtin_deref(true)
                     .map_or(ast::MutImmutable, |mt| mt.mutbl);
 
-                let slice_ty = tcx.mk_ref(tcx.mk_region(region), ty::mt {
+                let slice_ty = tcx.mk_ref(tcx.mk_region(region), ty::TypeAndMut {
                     ty: tcx.mk_slice(inner_ty),
                     mutbl: mutbl
                 });
@@ -729,7 +729,7 @@ pub fn check_pat_enum<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
 pub fn check_struct_pat_fields<'a, 'tcx>(pcx: &pat_ctxt<'a, 'tcx>,
                                          span: Span,
                                          fields: &'tcx [Spanned<ast::FieldPat>],
-                                         struct_fields: &[ty::field<'tcx>],
+                                         struct_fields: &[ty::Field<'tcx>],
                                          struct_id: ast::DefId,
                                          etc: bool) {
     let tcx = pcx.fcx.ccx.tcx;
index 49b47da517720117139778d969980462eebaf615..37541dee7d9d1c3a82bab8c0897c19bb04b30c9b 100644 (file)
@@ -272,8 +272,8 @@ fn do_check<'a>(&self, fcx: &FnCtxt<'a, 'tcx>) -> Result<CastKind, CastError> {
 
     fn check_ptr_ptr_cast<'a>(&self,
                               fcx: &FnCtxt<'a, 'tcx>,
-                              m_expr: &'tcx ty::mt<'tcx>,
-                              m_cast: &'tcx ty::mt<'tcx>)
+                              m_expr: &'tcx ty::TypeAndMut<'tcx>,
+                              m_cast: &'tcx ty::TypeAndMut<'tcx>)
                               -> Result<CastKind, CastError>
     {
         debug!("check_ptr_ptr_cast m_expr={:?} m_cast={:?}",
@@ -299,7 +299,7 @@ fn check_ptr_ptr_cast<'a>(&self,
 
     fn check_fptr_ptr_cast<'a>(&self,
                                fcx: &FnCtxt<'a, 'tcx>,
-                               m_cast: &'tcx ty::mt<'tcx>)
+                               m_cast: &'tcx ty::TypeAndMut<'tcx>)
                                -> Result<CastKind, CastError>
     {
         // fptr-ptr cast. must be to sized ptr
@@ -313,7 +313,7 @@ fn check_fptr_ptr_cast<'a>(&self,
 
     fn check_ptr_addr_cast<'a>(&self,
                                fcx: &FnCtxt<'a, 'tcx>,
-                               m_expr: &'tcx ty::mt<'tcx>)
+                               m_expr: &'tcx ty::TypeAndMut<'tcx>)
                                -> Result<CastKind, CastError>
     {
         // ptr-addr cast. must be from sized ptr
@@ -327,8 +327,8 @@ fn check_ptr_addr_cast<'a>(&self,
 
     fn check_ref_cast<'a>(&self,
                           fcx: &FnCtxt<'a, 'tcx>,
-                          m_expr: &'tcx ty::mt<'tcx>,
-                          m_cast: &'tcx ty::mt<'tcx>)
+                          m_expr: &'tcx ty::TypeAndMut<'tcx>,
+                          m_cast: &'tcx ty::TypeAndMut<'tcx>)
                           -> Result<CastKind, CastError>
     {
         // array-ptr-cast.
@@ -353,7 +353,7 @@ fn check_ref_cast<'a>(&self,
 
     fn check_addr_ptr_cast<'a>(&self,
                                fcx: &FnCtxt<'a, 'tcx>,
-                               m_cast: &'tcx ty::mt<'tcx>)
+                               m_cast: &'tcx ty::TypeAndMut<'tcx>)
                                -> Result<CastKind, CastError>
     {
         // ptr-addr cast. pointer must be thin.
index a0abef74907037156fb69f7567b939a5e98d0b3a..6963e25cd5b1b27a1418030d9c15b5f35549e031 100644 (file)
@@ -66,7 +66,7 @@
 use middle::traits::{self, ObligationCause};
 use middle::traits::{predicate_for_trait_def, report_selection_error};
 use middle::ty::{AutoDerefRef, AdjustDerefRef};
-use middle::ty::{self, mt, Ty};
+use middle::ty::{self, TypeAndMut, Ty, TypeError};
 use middle::ty_relate::RelateResult;
 use util::common::indent;
 
@@ -202,7 +202,7 @@ fn coerce_borrowed_pointer(&self,
                 return None;
             }
             let ty = self.tcx().mk_ref(r_borrow,
-                                        mt {ty: inner_ty, mutbl: mutbl_b});
+                                        TypeAndMut {ty: inner_ty, mutbl: mutbl_b});
             if let Err(err) = self.subtype(ty, b) {
                 if first_error.is_none() {
                     first_error = Some(err);
@@ -247,7 +247,7 @@ fn coerce_unsized(&self,
             (u, cu)
         } else {
             debug!("Missing Unsize or CoerceUnsized traits");
-            return Err(ty::terr_mismatch);
+            return Err(TypeError::Mismatch);
         };
 
         // Note, we want to avoid unnecessary unsizing. We don't want to coerce to
@@ -307,7 +307,7 @@ fn coerce_unsized(&self,
                 // Uncertain or unimplemented.
                 Ok(None) | Err(traits::Unimplemented) => {
                     debug!("coerce_unsized: early return - can't prove obligation");
-                    return Err(ty::terr_mismatch);
+                    return Err(TypeError::Mismatch);
                 }
 
                 // Object safety violations or miscellaneous.
@@ -411,7 +411,7 @@ fn coerce_unsafe_ptr(&self,
         };
 
         // Check that the types which they point at are compatible.
-        let a_unsafe = self.tcx().mk_ptr(ty::mt{ mutbl: mutbl_b, ty: mt_a.ty });
+        let a_unsafe = self.tcx().mk_ptr(ty::TypeAndMut{ mutbl: mutbl_b, ty: mt_a.ty });
         try!(self.subtype(a_unsafe, b));
         try!(coerce_mutbls(mt_a.mutbl, mutbl_b));
 
@@ -472,6 +472,6 @@ fn coerce_mutbls<'tcx>(from_mutbl: ast::Mutability,
         (ast::MutMutable, ast::MutMutable) |
         (ast::MutImmutable, ast::MutImmutable) |
         (ast::MutMutable, ast::MutImmutable) => Ok(None),
-        (ast::MutImmutable, ast::MutMutable) => Err(ty::terr_mutability)
+        (ast::MutImmutable, ast::MutMutable) => Err(TypeError::Mutability)
     }
 }
index 392515926da0c9b71735ffd7423f62b9e92e8877..e175fd9bcfdc78dfeba787c54aac64c880e88cba 100644 (file)
@@ -32,7 +32,7 @@ pub fn suptype_with_fn<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>,
                                     ty_a: Ty<'tcx>,
                                     ty_b: Ty<'tcx>,
                                     handle_err: F) where
-    F: FnOnce(Span, Ty<'tcx>, Ty<'tcx>, &ty::type_err<'tcx>),
+    F: FnOnce(Span, Ty<'tcx>, Ty<'tcx>, &ty::TypeError<'tcx>),
 {
     // n.b.: order of actual, expected is reversed
     match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp),
index b9c986a512ebddc80dab4d83659b89e90a57d1b4..a8c56b2660ce005958adfcfc2a63ddc6d189a31f 100644 (file)
@@ -432,7 +432,7 @@ fn fixup_derefs_on_method_receiver_if_necessary(&self,
         };
 
         match sig.0.inputs[0].sty {
-            ty::TyRef(_, ty::mt {
+            ty::TyRef(_, ty::TypeAndMut {
                 ty: _,
                 mutbl: ast::MutMutable,
             }) => {}
index 2117cba108730797d483d770c59025bc421dc651..a74c004389b4da4515a7585c9e98694bba0951f6 100644 (file)
@@ -271,7 +271,7 @@ pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                     // Trait method is fn(&self) or fn(&mut self), need an
                     // autoref. Pull the region etc out of the type of first argument.
                     match transformed_self_ty.sty {
-                        ty::TyRef(region, ty::mt { mutbl, ty: _ }) => {
+                        ty::TyRef(region, ty::TypeAndMut { mutbl, ty: _ }) => {
                             fcx.write_adjustment(self_expr.id,
                                 ty::AdjustDerefRef(ty::AutoDerefRef {
                                     autoderefs: autoderefs,
index c43046ba0e71641d61252788fff7e8a48de0a953..a960123efc6b8172045ea9fefa1c0fe7a4ed8e3e 100644 (file)
@@ -311,11 +311,11 @@ fn assemble_probe(&mut self, self_ty: Ty<'tcx>) {
                 let lang_def_id = self.tcx().lang_items.slice_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
-            ty::TyRawPtr(ty::mt { ty: _, mutbl: ast::MutImmutable }) => {
+            ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: ast::MutImmutable }) => {
                 let lang_def_id = self.tcx().lang_items.const_ptr_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
-            ty::TyRawPtr(ty::mt { ty: _, mutbl: ast::MutMutable }) => {
+            ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: ast::MutMutable }) => {
                 let lang_def_id = self.tcx().lang_items.mut_ptr_impl();
                 self.assemble_inherent_impl_for_primitive(lang_def_id);
             }
@@ -951,7 +951,7 @@ fn pick_autorefd_method(&mut self,
 
         // Search through mutabilities in order to find one where pick works:
         [ast::MutImmutable, ast::MutMutable].iter().filter_map(|&m| {
-            let autoref_ty = tcx.mk_ref(region, ty::mt {
+            let autoref_ty = tcx.mk_ref(region, ty::TypeAndMut {
                 ty: step.self_ty,
                 mutbl: m
             });
index 0f9ebf3713c5887212ae3c1c0249f02442342410..5a71d1ed0b5bd0fa8d0cb30aaa1b4be563882847 100644 (file)
@@ -1029,7 +1029,7 @@ fn report_cast_to_unsized_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
         format!("cast to unsized type: `{}` as `{}`", actual, tstr)
     }, t_expr, None);
     match t_expr.sty {
-        ty::TyRef(_, ty::mt { mutbl: mt, .. }) => {
+        ty::TyRef(_, ty::TypeAndMut { mutbl: mt, .. }) => {
             let mtstr = match mt {
                 ast::MutMutable => "mut ",
                 ast::MutImmutable => ""
@@ -1576,7 +1576,7 @@ pub fn mk_subty(&self,
                     origin: infer::TypeOrigin,
                     sub: Ty<'tcx>,
                     sup: Ty<'tcx>)
-                    -> Result<(), ty::type_err<'tcx>> {
+                    -> Result<(), ty::TypeError<'tcx>> {
         infer::mk_subty(self.infcx(), a_is_expected, origin, sub, sup)
     }
 
@@ -1585,7 +1585,7 @@ pub fn mk_eqty(&self,
                    origin: infer::TypeOrigin,
                    sub: Ty<'tcx>,
                    sup: Ty<'tcx>)
-                   -> Result<(), ty::type_err<'tcx>> {
+                   -> Result<(), ty::TypeError<'tcx>> {
         infer::mk_eqty(self.infcx(), a_is_expected, origin, sub, sup)
     }
 
@@ -1600,7 +1600,7 @@ pub fn type_error_message<M>(&self,
                                  sp: Span,
                                  mk_msg: M,
                                  actual_ty: Ty<'tcx>,
-                                 err: Option<&ty::type_err<'tcx>>) where
+                                 err: Option<&ty::TypeError<'tcx>>) where
         M: FnOnce(String) -> String,
     {
         self.infcx().type_error_message(sp, mk_msg, actual_ty, err);
@@ -1610,7 +1610,7 @@ pub fn report_mismatched_types(&self,
                                    sp: Span,
                                    e: Ty<'tcx>,
                                    a: Ty<'tcx>,
-                                   err: &ty::type_err<'tcx>) {
+                                   err: &ty::TypeError<'tcx>) {
         self.infcx().report_mismatched_types(sp, e, a, err)
     }
 
@@ -1674,7 +1674,7 @@ pub fn add_obligations_for_parameters(&self,
     pub fn lookup_field_ty(&self,
                            span: Span,
                            class_id: ast::DefId,
-                           items: &[ty::field_ty],
+                           items: &[ty::FieldTy],
                            fieldname: ast::Name,
                            substs: &subst::Substs<'tcx>)
                            -> Option<Ty<'tcx>>
@@ -1687,7 +1687,7 @@ pub fn lookup_field_ty(&self,
     pub fn lookup_tup_field_ty(&self,
                                span: Span,
                                class_id: ast::DefId,
-                               items: &[ty::field_ty],
+                               items: &[ty::FieldTy],
                                idx: usize,
                                substs: &subst::Substs<'tcx>)
                                -> Option<Ty<'tcx>>
@@ -1894,7 +1894,7 @@ fn try_overloaded_deref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                   base_expr: Option<&ast::Expr>,
                                   base_ty: Ty<'tcx>,
                                   lvalue_pref: LvaluePreference)
-                                  -> Option<ty::mt<'tcx>>
+                                  -> Option<ty::TypeAndMut<'tcx>>
 {
     // Try DerefMut first, if preferred.
     let method = match (lvalue_pref, fcx.tcx().lang_items.deref_mut_trait()) {
@@ -1925,7 +1925,7 @@ fn try_overloaded_deref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
 fn make_overloaded_lvalue_return_type<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                                 method_call: Option<MethodCall>,
                                                 method: Option<MethodCallee<'tcx>>)
-                                                -> Option<ty::mt<'tcx>>
+                                                -> Option<ty::TypeAndMut<'tcx>>
 {
     match method {
         Some(method) => {
@@ -2776,7 +2776,7 @@ fn check_struct_or_variant_fields<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
                                                 class_id: ast::DefId,
                                                 node_id: ast::NodeId,
                                                 substitutions: &'tcx subst::Substs<'tcx>,
-                                                field_types: &[ty::field_ty],
+                                                field_types: &[ty::FieldTy],
                                                 ast_fields: &'tcx [ast::Field],
                                                 check_completeness: bool,
                                                 enum_id_opt: Option<ast::DefId>)  {
@@ -3110,7 +3110,7 @@ fn check_struct_fields_on_error<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>,
                                                     hint,
                                                     lvalue_pref);
 
-        let tm = ty::mt { ty: fcx.expr_ty(&**oprnd), mutbl: mutbl };
+        let tm = ty::TypeAndMut { ty: fcx.expr_ty(&**oprnd), mutbl: mutbl };
         let oprnd_t = if tm.ty.references_error() {
             tcx.types.err
         } else {
@@ -3668,7 +3668,7 @@ fn have_disallowed_generic_consts<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
         Some((opt_self_ty, &path.segments, path_res.base_def))
     } else {
         let mut def = path_res.base_def;
-        let ty_segments = path.segments.init();
+        let ty_segments = path.segments.split_last().unwrap().1;
         let base_ty_end = path.segments.len() - path_res.depth;
         let ty = astconv::finish_resolving_def_to_ty(fcx, fcx, span,
                                                      PathParamMode::Optional,
@@ -4908,13 +4908,13 @@ fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
             "offset" | "arith_offset" => {
               (1,
                vec!(
-                  tcx.mk_ptr(ty::mt {
+                  tcx.mk_ptr(ty::TypeAndMut {
                       ty: param(ccx, 0),
                       mutbl: ast::MutImmutable
                   }),
                   ccx.tcx.types.isize
                ),
-               tcx.mk_ptr(ty::mt {
+               tcx.mk_ptr(ty::TypeAndMut {
                    ty: param(ccx, 0),
                    mutbl: ast::MutImmutable
                }))
@@ -4922,11 +4922,11 @@ fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
             "copy" | "copy_nonoverlapping" => {
               (1,
                vec!(
-                  tcx.mk_ptr(ty::mt {
+                  tcx.mk_ptr(ty::TypeAndMut {
                       ty: param(ccx, 0),
                       mutbl: ast::MutImmutable
                   }),
-                  tcx.mk_ptr(ty::mt {
+                  tcx.mk_ptr(ty::TypeAndMut {
                       ty: param(ccx, 0),
                       mutbl: ast::MutMutable
                   }),
@@ -4937,11 +4937,11 @@ fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
             "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
               (1,
                vec!(
-                  tcx.mk_ptr(ty::mt {
+                  tcx.mk_ptr(ty::TypeAndMut {
                       ty: param(ccx, 0),
                       mutbl: ast::MutMutable
                   }),
-                  tcx.mk_ptr(ty::mt {
+                  tcx.mk_ptr(ty::TypeAndMut {
                       ty: param(ccx, 0),
                       mutbl: ast::MutImmutable
                   }),
@@ -4952,7 +4952,7 @@ fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
             "write_bytes" | "volatile_set_memory" => {
               (1,
                vec!(
-                  tcx.mk_ptr(ty::mt {
+                  tcx.mk_ptr(ty::TypeAndMut {
                       ty: param(ccx, 0),
                       mutbl: ast::MutMutable
                   }),
index 7cf7d73a5668c4e1a81a6b5fc5e84fbb5a7896ca..6083a2735c5684ffc787d92aca7d715f1c258fad 100644 (file)
@@ -170,8 +170,8 @@ fn check_type_defn<F>(&mut self, item: &ast::Item, mut lookup_fields: F) where
                 }
 
                 // For DST, all intermediate types must be sized.
-                if !variant.fields.is_empty() {
-                    for field in variant.fields.init() {
+                if let Some((_, fields)) = variant.fields.split_last() {
+                    for field in fields {
                         fcx.register_builtin_bound(
                             field.ty,
                             ty::BoundSized,
index 419fa9e160a47d34a2ef150d7fc9f4c2ff8d5195..9d7ff3b9613d0ffb9a12796c4dc9dfd0ab99add7 100644 (file)
@@ -390,7 +390,7 @@ fn from_infcx(infcx: &'cx infer::InferCtxt<'cx, 'tcx>,
                    reason: reason }
     }
 
-    fn report_error(&self, e: infer::fixup_err) {
+    fn report_error(&self, e: infer::FixupError) {
         self.writeback_errors.set(true);
         if !self.tcx.sess.has_errors() {
             match self.reason {
index cd904425d6346ef1ab74ce34ac2cf96677776136..2b800bd9a441f738c3ecdbaf93a5d059b4eede9e 100644 (file)
@@ -450,11 +450,11 @@ fn check_implementations_of_coerce_unsized(&self) {
 
             let infcx = new_infer_ctxt(tcx, &tcx.tables, Some(param_env), true);
 
-            let check_mutbl = |mt_a: ty::mt<'tcx>, mt_b: ty::mt<'tcx>,
+            let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>, mt_b: ty::TypeAndMut<'tcx>,
                                mk_ptr: &Fn(Ty<'tcx>) -> Ty<'tcx>| {
                 if (mt_a.mutbl, mt_b.mutbl) == (ast::MutImmutable, ast::MutMutable) {
                     infcx.report_mismatched_types(span, mk_ptr(mt_b.ty),
-                                                  target, &ty::terr_mutability);
+                                                  target, &ty::TypeError::Mutability);
                 }
                 (mt_a.ty, mt_b.ty, unsize_trait, None)
             };
index e585b8cd2bde0fea2076d1d4a7563dc6554d5675..be8fce28b6f6b156091ab8c251f8e00a5637ec8b 100644 (file)
@@ -100,14 +100,14 @@ fn check_item(&self, item: &ast::Item) {
                                                   "[T]",
                                                   item.span);
                     }
-                    ty::TyRawPtr(ty::mt { ty: _, mutbl: ast::MutImmutable }) => {
+                    ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: ast::MutImmutable }) => {
                         self.check_primitive_impl(def_id,
                                                   self.tcx.lang_items.const_ptr_impl(),
                                                   "const_ptr",
                                                   "*const T",
                                                   item.span);
                     }
-                    ty::TyRawPtr(ty::mt { ty: _, mutbl: ast::MutMutable }) => {
+                    ty::TyRawPtr(ty::TypeAndMut { ty: _, mutbl: ast::MutMutable }) => {
                         self.check_primitive_impl(def_id,
                                                   self.tcx.lang_items.mut_ptr_impl(),
                                                   "mut_ptr",
index 5d2e3533efccf0f2c2bd8e97543663eca86f1eb6..8949edb027e952c289d5567ca5e9e65eb4bd5d4f 100644 (file)
@@ -655,7 +655,7 @@ fn convert_field<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
                            struct_predicates: &ty::GenericPredicates<'tcx>,
                            v: &ast::StructField,
                            origin: ast::DefId)
-                           -> ty::field_ty
+                           -> ty::FieldTy
 {
     let tt = ccx.icx(struct_predicates).to_ty(&ExplicitRscope, &*v.node.ty);
     write_ty_to_tcx(ccx.tcx, v.node.id, tt);
@@ -671,7 +671,7 @@ fn convert_field<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
 
     match v.node.kind {
         ast::NamedField(ident, visibility) => {
-            ty::field_ty {
+            ty::FieldTy {
                 name: ident.name,
                 id: local_def(v.node.id),
                 vis: visibility,
@@ -679,7 +679,7 @@ fn convert_field<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
             }
         }
         ast::UnnamedField(visibility) => {
-            ty::field_ty {
+            ty::FieldTy {
                 name: special_idents::unnamed_field.name,
                 id: local_def(v.node.id),
                 vis: visibility,
index 8c3ef4ae631c3ebb53551daa963915f246b0ed3e..4260791e38458ab9aa8a503e917358be710cd5ca 100644 (file)
@@ -85,7 +85,7 @@
 #![feature(ref_slice)]
 #![feature(rustc_diagnostic_macros)]
 #![feature(rustc_private)]
-#![feature(slice_extras)]
+#![feature(slice_splits)]
 #![feature(staged_api)]
 #![feature(vec_push_all)]
 #![feature(cell_extras)]
index c1f9725fc8134191721eb1e0b52a24b50a98a1a0..4af23a27c941c569c458a49d5f571923aad7b105 100644 (file)
@@ -1074,7 +1074,7 @@ fn add_constraints_from_region(&mut self,
     /// appearing in a context with ambient variance `variance`
     fn add_constraints_from_mt(&mut self,
                                generics: &ty::Generics<'tcx>,
-                               mt: &ty::mt<'tcx>,
+                               mt: &ty::TypeAndMut<'tcx>,
                                variance: VarianceTermPtr<'a>) {
         match mt.mutbl {
             ast::MutMutable => {
index daa4e1af3382d011a46168d0825dc086d5795031..3cc24550297cee501245bb7b84b51dd6791d1a44 100644 (file)
@@ -1729,7 +1729,7 @@ fn clean(&self, cx: &DocContext) -> Item {
     }
 }
 
-impl Clean<Item> for ty::field_ty {
+impl Clean<Item> for ty::FieldTy {
     fn clean(&self, cx: &DocContext) -> Item {
         use syntax::parse::token::special_idents::unnamed_field;
         use rustc::metadata::csearch;
index 798cc6a612cde239ce60be7f158839e549bbdaab..2c6f62060b2307f2c96cc1a05a10dc80509efc4e 100644 (file)
@@ -72,7 +72,7 @@ pub fn render<T: fmt::Display, S: fmt::Display>(
             <div class="search-container">
                 <input class="search-input" name="search"
                        autocomplete="off"
-                       placeholder="Click or press 'S' to search, '?' for more options..."
+                       placeholder="Click or press ‘S’ to search, ‘?’ for more options…"
                        type="search">
             </div>
         </form>
@@ -85,7 +85,7 @@ pub fn render<T: fmt::Display, S: fmt::Display>(
 
     <div id="help" class="hidden">
         <div class="shortcuts">
-            <h1>Keyboard shortcuts</h1>
+            <h1>Keyboard Shortcuts</h1>
             <dl>
                 <dt>?</dt>
                 <dd>Show this help dialog</dd>
@@ -100,7 +100,7 @@ pub fn render<T: fmt::Display, S: fmt::Display>(
             </dl>
         </div>
         <div class="infos">
-            <h1>Search tricks</h1>
+            <h1>Search Tricks</h1>
             <p>
                 Prefix searches with a type followed by a colon (e.g.
                 <code>fn:</code>) to restrict the search to a given type.
index aaebdc34cd464729ca782eea957780be535fbbc6..21f1ccc555506ddbb442aafe38c412d5e0bc69e2 100644 (file)
@@ -447,7 +447,6 @@ tr.result span.primitive::after { content: ' (primitive type)'; font-style: ital
 
 #help {
     background: #e9e9e9;
-    border-radius: 4px;
     box-shadow: 0 0 6px rgba(0,0,0,.2);
     position: absolute;
     top: 300px;
@@ -461,7 +460,7 @@ tr.result span.primitive::after { content: ' (primitive type)'; font-style: ital
 
 #help dt {
     float: left;
-    border-radius: 3px;
+    border-radius: 4px;
     border: 1px solid #bfbfbf;
     background: #fff;
     width: 23px;
index 4a033452774666d272202816643a7da7a4f972d4..c77cdd4d021837b645f868253783c939cb5893a9 100644 (file)
     highlightSourceLines(null);
     $(window).on('hashchange', highlightSourceLines);
 
-    // Helper function for Keyboard events,
-    // Get's the char from the keypress event
+    // Gets the human-readable string for the virtual-key code of the
+    // given KeyboardEvent, ev.
     //
-    // This method is used because e.wich === x is not
-    // compatible with non-english keyboard layouts
+    // This function is meant as a polyfill for KeyboardEvent#key,
+    // since it is not supported in Trident.  We also test for
+    // KeyboardEvent#keyCode because the handleShortcut handler is
+    // also registered for the keydown event, because Blink doesn't fire
+    // keypress on hitting the Escape key.
     //
-    // Note: event.type must be keypress !
-    function getChar(event) {
-      if (event.which == null) {
-        return String.fromCharCode(event.keyCode) // IE
-      } else if (event.which!=0 && event.charCode!=0) {
-        return String.fromCharCode(event.which)   // the rest
-      } else {
-        return null // special key
-      }
+    // So I guess you could say things are getting pretty interoperable.
+    function getVirtualKey(ev) {
+        if ("key" in ev && typeof ev.key != "undefined")
+            return ev.key;
+
+        var c = ev.charCode || ev.keyCode;
+        if (c == 27)
+            return "Escape";
+        return String.fromCharCode(c);
     }
 
-    $(document).on('keypress', function handleKeyboardShortcut(e) {
-        if (document.activeElement.tagName === 'INPUT') {
+    function handleShortcut(ev) {
+        if (document.activeElement.tagName == "INPUT")
             return;
-        }
 
-        if (getChar(e) === '?') {
-            if (e.shiftKey && $('#help').hasClass('hidden')) {
-                e.preventDefault();
-                $('#help').removeClass('hidden');
+        switch (getVirtualKey(ev)) {
+        case "Escape":
+            if (!$("#help").hasClass("hidden")) {
+                ev.preventDefault();
+                $("#help").addClass("hidden");
+            } else if (!$("#search").hasClass("hidden")) {
+                ev.preventDefault();
+                $("#search").addClass("hidden");
+                $("#main").removeClass("hidden");
             }
-        } else if (getChar(e) === 's' || getChar(e) === 'S') {
-            e.preventDefault();
-            $('.search-input').focus();
-        }
-    }).on('keydown', function(e) {
-        // The escape key event has to be captured with the keydown event.
-        // Because keypressed has no keycode for the escape key
-        // (and other special keys in general)...
-        if (document.activeElement.tagName === 'INPUT') {
-            return;
-        }
-
-        if (e.keyCode === 27) { // escape key
-            if (!$('#help').hasClass('hidden')) {
-                e.preventDefault();
-                $('#help').addClass('hidden');
-            } else if (!$('#search').hasClass('hidden')) {
-                e.preventDefault();
-                $('#search').addClass('hidden');
-                $('#main').removeClass('hidden');
+            break;
+
+        case "s":
+        case "S":
+            ev.preventDefault();
+            $(".search-input").focus();
+            break;
+
+        case "?":
+            if (ev.shiftKey && $("#help").hasClass("hidden")) {
+                ev.preventDefault();
+                $("#help").removeClass("hidden");
             }
+            break;
         }
-    }).on('click', function(e) {
-        if (!$(e.target).closest('#help').length) {
-            $('#help').addClass('hidden');
+    }
+
+    $(document).on("keypress", handleShortcut);
+    $(document).on("keydown", handleShortcut);
+    $(document).on("click", function(ev) {
+        if (!$(ev.target).closest("#help").length) {
+            $("#help").addClass("hidden");
         }
     });
 
-
     $('.version-selector').on('change', function() {
         var i, match,
             url = document.location.href,
 
         document.location.href = url;
     });
+
     /**
      * A function to compute the Levenshtein distance between two strings
      * Licensed under the Creative Commons Attribution-ShareAlike 3.0 Unported
index ff947d93fca16786e56fff3a4dd5ce22316439b6..ef8bdf5e2ce9738146d429b227f1c8a5b817777d 100644 (file)
@@ -16,7 +16,8 @@ document.addEventListener('DOMContentLoaded', function() {
         return;
     }
 
-    var elements = document.querySelectorAll('pre.rust');
+    var featureRegexp = new RegExp('^\s*#!\\[feature\\(\.*?\\)\\]');
+    var elements = document.querySelectorAll('pre.rust-example-rendered');
 
     Array.prototype.forEach.call(elements, function(el) {
         el.onmouseover = function(e) {
@@ -29,8 +30,14 @@ document.addEventListener('DOMContentLoaded', function() {
             a.setAttribute('class', 'test-arrow');
 
             var code = el.previousElementSibling.textContent;
+
+            var channel = '';
+            if (featureRegexp.test(code)) {
+                channel = '&version=nightly';
+            }
+
             a.setAttribute('href', window.playgroundUrl + '?code=' +
-                           encodeURIComponent(code));
+                           encodeURIComponent(code) + channel);
             a.setAttribute('target', '_blank');
 
             el.appendChild(a);
index 17d912dd4cb333936e16e21a0b0a0305414466e6..9ea22ced927b1aede64f31d56d4490bc57525bd8 100644 (file)
@@ -29,7 +29,6 @@
 #![feature(path_relative_from)]
 #![feature(rustc_private)]
 #![feature(set_stdio)]
-#![feature(slice_extras)]
 #![feature(slice_patterns)]
 #![feature(staged_api)]
 #![feature(subslice_offset)]
@@ -192,7 +191,7 @@ pub fn usage(argv0: &str) {
 }
 
 pub fn main_args(args: &[String]) -> isize {
-    let matches = match getopts::getopts(args.tail(), &opts()) {
+    let matches = match getopts::getopts(&args[1..], &opts()) {
         Ok(m) => m,
         Err(err) => {
             println!("{}", err);
index 6e1c8beb3ada12d8b608112cac4deac35db30c39..0441950efb337fa7e96cdd716c488c9996653791 100644 (file)
@@ -353,7 +353,7 @@ pub fn unindent(s: &str) -> String {
 
     if !lines.is_empty() {
         let mut unindented = vec![ lines[0].trim().to_string() ];
-        unindented.push_all(&lines.tail().iter().map(|&line| {
+        unindented.push_all(&lines[1..].iter().map(|&line| {
             if line.chars().all(|c| c.is_whitespace()) {
                 line.to_string()
             } else {
index e79e5d5a680f60bc3a8b2284adeb59eef252c0a7..0dfcc72e3791025cef9ae217059cbf03d97918f2 100644 (file)
@@ -9,7 +9,7 @@
 // except according to those terms.
 
 //! A fixed-size array is denoted `[T; N]` for the element type `T` and
-//! the compile time constant size `N`. The size should be zero or positive.
+//! the compile time constant size `N`. The size must be zero or positive.
 //!
 //! Arrays values are created either with an explicit expression that lists
 //! each element: `[x, y, z]` or a repeat expression: `[x; N]`. The repeat
@@ -32,7 +32,9 @@
 //!
 //! [slice]: primitive.slice.html
 //!
-//! ## Examples
+//! Rust does not currently support generics over the size of an array type.
+//!
+//! # Examples
 //!
 //! ```
 //! let mut array: [i32; 3] = [0; 3];
@@ -49,7 +51,5 @@
 //!
 //! ```
 //!
-//! Rust does not currently support generics over the size of an array type.
-//!
 
 #![doc(primitive = "array")]
index f13c10156f579acd7b01801ba1f29a0d415d5584..c9fe6e7e0b123d8e35267eb25347f09f9805c927 100644 (file)
@@ -8,13 +8,14 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
+use ascii;
 use borrow::{Cow, ToOwned, Borrow};
 use boxed::Box;
 use clone::Clone;
 use convert::{Into, From};
 use cmp::{PartialEq, Eq, PartialOrd, Ord, Ordering};
 use error::Error;
-use fmt;
+use fmt::{self, Write};
 use io;
 use iter::Iterator;
 use libc;
@@ -268,7 +269,18 @@ fn deref(&self) -> &CStr {
 #[stable(feature = "rust1", since = "1.0.0")]
 impl fmt::Debug for CString {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        fmt::Debug::fmt(&String::from_utf8_lossy(self.as_bytes()), f)
+        fmt::Debug::fmt(&**self, f)
+    }
+}
+
+#[stable(feature = "cstr_debug", since = "1.3.0")]
+impl fmt::Debug for CStr {
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        try!(write!(f, "\""));
+        for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
+            try!(f.write_char(byte as char));
+        }
+        write!(f, "\"")
     }
 }
 
@@ -501,8 +513,8 @@ fn build_with_zero3() {
 
     #[test]
     fn formatted() {
-        let s = CString::new(&b"12"[..]).unwrap();
-        assert_eq!(format!("{:?}", s), "\"12\"");
+        let s = CString::new(&b"abc\x01\x02\n\xE2\x80\xA6\xFF"[..]).unwrap();
+        assert_eq!(format!("{:?}", s), r#""abc\x01\x02\n\xe2\x80\xa6\xff""#);
     }
 
     #[test]
index 2458838bc9d362422eb0bfd43adab65ad541d0f3..7598a1c7a48f0e8b80ede49836e3a4add5edc70e 100644 (file)
@@ -269,14 +269,18 @@ pub fn sync_data(&self) -> io::Result<()> {
     /// will be extended to `size` and have all of the intermediate data filled
     /// in with 0s.
     ///
+    /// # Errors
+    ///
+    /// This function will return an error if the file is not opened for writing.
+    ///
     /// # Examples
     ///
     /// ```no_run
     /// use std::fs::File;
     ///
     /// # fn foo() -> std::io::Result<()> {
-    /// let mut f = try!(File::open("foo.txt"));
-    /// try!(f.set_len(0));
+    /// let mut f = try!(File::create("foo.txt"));
+    /// try!(f.set_len(10));
     /// # Ok(())
     /// # }
     /// ```
index 98d8bc6bdaf723975326cbf22f87e612183914f5..44541b7875423a235fe010717a37368bb32511ae 100644 (file)
@@ -20,7 +20,7 @@
 use io::{self, DEFAULT_BUF_SIZE, Error, ErrorKind, SeekFrom};
 use ptr;
 
-/// Wraps a `Read` and buffers input from it.
+/// The `BufReader` struct adds buffering to any reader.
 ///
 /// It can be excessively inefficient to work directly with a `Read` instance.
 /// For example, every call to `read` on `TcpStream` results in a system call.
@@ -29,7 +29,7 @@
 ///
 /// # Examples
 ///
-/// ```no_run
+/// ```
 /// use std::io::prelude::*;
 /// use std::io::BufReader;
 /// use std::fs::File;
@@ -54,12 +54,40 @@ pub struct BufReader<R> {
 
 impl<R: Read> BufReader<R> {
     /// Creates a new `BufReader` with a default buffer capacity.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::io::BufReader;
+    /// use std::fs::File;
+    ///
+    /// # fn foo() -> std::io::Result<()> {
+    /// let mut f = try!(File::open("log.txt"));
+    /// let mut reader = BufReader::new(f);
+    /// # Ok(())
+    /// # }
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn new(inner: R) -> BufReader<R> {
         BufReader::with_capacity(DEFAULT_BUF_SIZE, inner)
     }
 
     /// Creates a new `BufReader` with the specified buffer capacity.
+    ///
+    /// # Examples
+    ///
+    /// Creating a buffer with ten bytes of capacity:
+    ///
+    /// ```
+    /// use std::io::BufReader;
+    /// use std::fs::File;
+    ///
+    /// # fn foo() -> std::io::Result<()> {
+    /// let mut f = try!(File::open("log.txt"));
+    /// let mut reader = BufReader::with_capacity(10, f);
+    /// # Ok(())
+    /// # }
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn with_capacity(cap: usize, inner: R) -> BufReader<R> {
         BufReader {
@@ -71,20 +99,65 @@ pub fn with_capacity(cap: usize, inner: R) -> BufReader<R> {
     }
 
     /// Gets a reference to the underlying reader.
+    ///
+    /// It is inadvisable to directly read from the underlying reader.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::io::BufReader;
+    /// use std::fs::File;
+    ///
+    /// # fn foo() -> std::io::Result<()> {
+    /// let mut f1 = try!(File::open("log.txt"));
+    /// let mut reader = BufReader::new(f1);
+    ///
+    /// let f2 = reader.get_ref();
+    /// # Ok(())
+    /// # }
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get_ref(&self) -> &R { &self.inner }
 
     /// Gets a mutable reference to the underlying reader.
     ///
-    /// # Warning
-    ///
     /// It is inadvisable to directly read from the underlying reader.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::io::BufReader;
+    /// use std::fs::File;
+    ///
+    /// # fn foo() -> std::io::Result<()> {
+    /// let mut f1 = try!(File::open("log.txt"));
+    /// let mut reader = BufReader::new(f1);
+    ///
+    /// let f2 = reader.get_mut();
+    /// # Ok(())
+    /// # }
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
 
     /// Unwraps this `BufReader`, returning the underlying reader.
     ///
     /// Note that any leftover data in the internal buffer is lost.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use std::io::BufReader;
+    /// use std::fs::File;
+    ///
+    /// # fn foo() -> std::io::Result<()> {
+    /// let mut f1 = try!(File::open("log.txt"));
+    /// let mut reader = BufReader::new(f1);
+    ///
+    /// let f2 = reader.into_inner();
+    /// # Ok(())
+    /// # }
+    /// ```
     #[stable(feature = "rust1", since = "1.0.0")]
     pub fn into_inner(self) -> R { self.inner }
 }
index a66789bf2873dc01b08e86e6ad6fd745a6ceee6e..3b48ff3096043d4dfb58443ba79c760d0571ad4a 100644 (file)
 use result;
 use sys;
 
-/// A type for results generated by I/O related functions where the `Err` type
-/// is hard-wired to `io::Error`.
+/// A specialized [`Result`][result] type for I/O operations.
+///
+/// [result]: ../result/enum.Result.html
+///
+/// This type is broadly used across `std::io` for any operation which may
+/// produce an error.
 ///
 /// This typedef is generally used to avoid writing out `io::Error` directly and
-/// is otherwise a direct mapping to `std::result::Result`.
+/// is otherwise a direct mapping to `Result`.
+///
+/// While usual Rust style is to import types directly, aliases of `Result`
+/// often are not, to make it easier to distinguish between them. `Result` is
+/// generally assumed to be `std::result::Result`, and so users of this alias
+/// will generally use `io::Result` instead of shadowing the prelude's import
+/// of `std::result::Result`.
+///
+/// # Examples
+///
+/// A convenience function that bubbles an `io::Result` to its caller:
+///
+/// ```
+/// use std::io;
+///
+/// fn get_string() -> io::Result<String> {
+///     let mut buffer = String::new();
+///
+///     try!(io::stdin().read_line(&mut buffer));
+///
+///     Ok(buffer)
+/// }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub type Result<T> = result::Result<T, Error>;
 
index 880770eb41485b15f05427f5ebf4a5aa84e2eec5..db5c1da8a42274af24c1560bfa8e17b2b20696f9 100644 (file)
 //! # #![allow(unused_imports)]
 //! use std::io::prelude::*;
 //! ```
-//!
-//! This module contains reexports of many core I/O traits such as `Read`,
-//! `Write` and `BufRead`. Structures and functions are not
-//! contained in this module.
 
 #![stable(feature = "rust1", since = "1.0.0")]
 
index 2a64d0f6e8c19ea8d96faf3f482ff7ada0a9d19f..62bbb939a71f5dcd8aeddb44772e94c444bf1868 100644 (file)
@@ -154,15 +154,42 @@ pub struct StdinLock<'a> {
     inner: MutexGuard<'a, BufReader<Maybe<StdinRaw>>>,
 }
 
-/// Creates a new handle to the global standard input stream of this process.
+/// Constructs a new handle to the standard input of the current process.
 ///
-/// The handle returned refers to a globally shared buffer between all threads.
-/// Access is synchronized and can be explicitly controlled with the `lock()`
-/// method.
+/// Each handle returned is a reference to a shared global buffer whose access
+/// is synchronized via a mutex. If you need more explicit control over
+/// locking, see the [lock() method][lock].
+///
+/// [lock]: struct.Stdin.html#method.lock
+///
+/// # Examples
+///
+/// Using implicit synchronization:
+///
+/// ```
+/// use std::io::{self, Read};
+///
+/// # fn foo() -> io::Result<String> {
+/// let mut buffer = String::new();
+/// try!(io::stdin().read_to_string(&mut buffer));
+/// # Ok(buffer)
+/// # }
+/// ```
+///
+/// Using explicit synchronization:
 ///
-/// The `Read` trait is implemented for the returned value but the `BufRead`
-/// trait is not due to the global nature of the standard input stream. The
-/// locked version, `StdinLock`, implements both `Read` and `BufRead`, however.
+/// ```
+/// use std::io::{self, Read};
+///
+/// # fn foo() -> io::Result<String> {
+/// let mut buffer = String::new();
+/// let stdin = io::stdin();
+/// let mut handle = stdin.lock();
+///
+/// try!(handle.read_to_string(&mut buffer));
+/// # Ok(buffer)
+/// # }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn stdin() -> Stdin {
     static INSTANCE: Lazy<Mutex<BufReader<Maybe<StdinRaw>>>> = Lazy::new(stdin_init);
@@ -298,13 +325,42 @@ pub struct StdoutLock<'a> {
     inner: ReentrantMutexGuard<'a, RefCell<LineWriter<Maybe<StdoutRaw>>>>,
 }
 
-/// Constructs a new reference to the standard output of the current process.
+/// Constructs a new handle to the standard output of the current process.
 ///
 /// Each handle returned is a reference to a shared global buffer whose access
-/// is synchronized via a mutex. Explicit control over synchronization is
-/// provided via the `lock` method.
+/// is synchronized via a mutex. If you need more explicit control over
+/// locking, see the [lock() method][lock].
+///
+/// [lock]: struct.Stdout.html#method.lock
+///
+/// # Examples
+///
+/// Using implicit synchronization:
+///
+/// ```
+/// use std::io::{self, Write};
+///
+/// # fn foo() -> io::Result<()> {
+/// try!(io::stdout().write(b"hello world"));
 ///
-/// The returned handle implements the `Write` trait.
+/// # Ok(())
+/// # }
+/// ```
+///
+/// Using explicit synchronization:
+///
+/// ```
+/// use std::io::{self, Write};
+///
+/// # fn foo() -> io::Result<()> {
+/// let stdout = io::stdout();
+/// let mut handle = stdout.lock();
+///
+/// try!(handle.write(b"hello world"));
+///
+/// # Ok(())
+/// # }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn stdout() -> Stdout {
     static INSTANCE: Lazy<ReentrantMutex<RefCell<LineWriter<Maybe<StdoutRaw>>>>>
@@ -376,12 +432,38 @@ pub struct StderrLock<'a> {
     inner: ReentrantMutexGuard<'a, RefCell<Maybe<StderrRaw>>>,
 }
 
-/// Constructs a new reference to the standard error stream of a process.
+/// Constructs a new handle to the standard error of the current process.
+///
+/// This handle is not buffered.
+///
+/// # Examples
+///
+/// Using implicit synchronization:
+///
+/// ```
+/// use std::io::{self, Write};
+///
+/// # fn foo() -> io::Result<()> {
+/// try!(io::stderr().write(b"hello world"));
+///
+/// # Ok(())
+/// # }
+/// ```
+///
+/// Using explicit synchronization:
+///
+/// ```
+/// use std::io::{self, Write};
+///
+/// # fn foo() -> io::Result<()> {
+/// let stderr = io::stderr();
+/// let mut handle = stderr.lock();
 ///
-/// Each returned handle is synchronized amongst all other handles created from
-/// this function. No handles are buffered, however.
+/// try!(handle.write(b"hello world"));
 ///
-/// The returned handle implements the `Write` trait.
+/// # Ok(())
+/// # }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn stderr() -> Stderr {
     static INSTANCE: Lazy<ReentrantMutex<RefCell<Maybe<StderrRaw>>>> = Lazy::new(stderr_init);
index d8c999f8948379eb9c80c325606bf438a32c1654..c0bced26beffafce9c5c78483aaaa3c2efaf0fe1 100644 (file)
 /// This function will return an error immediately if any call to `read` or
 /// `write` returns an error. All instances of `ErrorKind::Interrupted` are
 /// handled by this function and the underlying operation is retried.
+///
+/// # Examples
+///
+/// ```
+/// use std::io;
+///
+/// # fn foo() -> io::Result<()> {
+/// let mut reader: &[u8] = b"hello";
+/// let mut writer: Vec<u8> = vec![];
+///
+/// try!(io::copy(&mut reader, &mut writer));
+///
+/// assert_eq!(reader, &writer[..]);
+/// # Ok(())
+/// # }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn copy<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> io::Result<u64> {
     let mut buf = [0; super::DEFAULT_BUF_SIZE];
@@ -48,9 +64,24 @@ pub fn copy<R: Read, W: Write>(reader: &mut R, writer: &mut W) -> io::Result<u64
 #[stable(feature = "rust1", since = "1.0.0")]
 pub struct Empty { _priv: () }
 
-/// Creates an instance of an empty reader.
+/// Constructs a new handle to an empty reader.
 ///
 /// All reads from the returned reader will return `Ok(0)`.
+///
+/// # Examples
+///
+/// A slightly sad example of not reading anything into a buffer:
+///
+/// ```
+/// use std::io;
+/// use std::io::Read;
+///
+/// # fn foo() -> io::Result<String> {
+/// let mut buffer = String::new();
+/// try!(io::empty().read_to_string(&mut buffer));
+/// # Ok(buffer)
+/// # }
+/// ```
 #[stable(feature = "rust1", since = "1.0.0")]
 pub fn empty() -> Empty { Empty { _priv: () } }
 
index 002e3b20c354222cff5c7f39eefa0b03ce906790..41c8ac4aed30d1653b74f4acf3bcd9a5d1827022 100644 (file)
@@ -170,8 +170,7 @@ unsafe fn target_record_sp_limit(limit: usize) {
         asm!("movl $$0x48+90*4, %eax
               movl $0, %gs:(%eax)" :: "r"(limit) : "eax" : "volatile")
     }
-    #[cfg(all(target_arch = "x86",
-              any(target_os = "linux", target_os = "freebsd")))]
+    #[cfg(all(target_arch = "x86", target_os = "linux"))]
     #[inline(always)]
     unsafe fn target_record_sp_limit(limit: usize) {
         asm!("movl $0, %gs:48" :: "r"(limit) :: "volatile")
@@ -197,10 +196,12 @@ unsafe fn target_record_sp_limit(limit: usize) {
     // aarch64 - FIXME(AARCH64): missing...
     // powerpc - FIXME(POWERPC): missing...
     // arm-ios - iOS segmented stack is disabled for now, see related notes
-    // openbsd - segmented stack is disabled
+    // openbsd/bitrig/netbsd - no segmented stacks.
+    // x86-freebsd - no segmented stacks.
     #[cfg(any(target_arch = "aarch64",
               target_arch = "powerpc",
               all(target_arch = "arm", target_os = "ios"),
+              all(target_arch = "x86", target_os = "freebsd"),
               target_os = "bitrig",
               target_os = "netbsd",
               target_os = "openbsd"))]
@@ -262,8 +263,7 @@ unsafe fn target_get_sp_limit() -> usize {
               movl %gs:(%eax), $0" : "=r"(limit) :: "eax" : "volatile");
         return limit;
     }
-    #[cfg(all(target_arch = "x86",
-              any(target_os = "linux", target_os = "freebsd")))]
+    #[cfg(all(target_arch = "x86", target_os = "linux"))]
     #[inline(always)]
     unsafe fn target_get_sp_limit() -> usize {
         let limit;
@@ -291,14 +291,16 @@ unsafe fn target_get_sp_limit() -> usize {
 
     // aarch64 - FIXME(AARCH64): missing...
     // powerpc - FIXME(POWERPC): missing...
-    // arm-ios - iOS doesn't support segmented stacks yet.
-    // openbsd - OpenBSD doesn't support segmented stacks.
+    // arm-ios - no segmented stacks.
+    // openbsd/bitrig/netbsd - no segmented stacks.
+    // x86-freebsd - no segmented stacks..
     //
     // This function might be called by runtime though
     // so it is unsafe to unreachable, let's return a fixed constant.
     #[cfg(any(target_arch = "aarch64",
               target_arch = "powerpc",
               all(target_arch = "arm", target_os = "ios"),
+              all(target_arch = "x86", target_os = "freebsd"),
               target_os = "bitrig",
               target_os = "netbsd",
               target_os = "openbsd"))]
index 8113d0ea8479cd98e7e41d301e8cea8719c8eb3d..867cdcbab94cb88750c0453ac1141a718ec3be42 100644 (file)
@@ -370,13 +370,25 @@ fn get_path(fd: c_int) -> Option<PathBuf> {
             readlink(&p).ok()
         }
 
-        #[cfg(not(target_os = "linux"))]
+        #[cfg(target_os = "macos")]
+        fn get_path(fd: c_int) -> Option<PathBuf> {
+            let mut buf = vec![0;libc::PATH_MAX as usize];
+            let n = unsafe { libc::fcntl(fd, libc::F_GETPATH, buf.as_ptr()) };
+            if n == -1 {
+                return None;
+            }
+            let l = buf.iter().position(|&c| c == 0).unwrap();
+            buf.truncate(l as usize);
+            Some(PathBuf::from(OsString::from_vec(buf)))
+        }
+
+        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
         fn get_path(_fd: c_int) -> Option<PathBuf> {
             // FIXME(#24570): implement this for other Unix platforms
             None
         }
 
-        #[cfg(target_os = "linux")]
+        #[cfg(any(target_os = "linux", target_os = "macos"))]
         fn get_mode(fd: c_int) -> Option<(bool, bool)> {
             let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
             if mode == -1 {
@@ -390,7 +402,7 @@ fn get_mode(fd: c_int) -> Option<(bool, bool)> {
             }
         }
 
-        #[cfg(not(target_os = "linux"))]
+        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
         fn get_mode(_fd: c_int) -> Option<(bool, bool)> {
             // FIXME(#24570): implement this for other Unix platforms
             None
index 16563be2cfb79ee1dbb9656bd5e34fe88eb2a121..06c14b39e124a640e9b6f85be6b565f1b6cb5af5 100644 (file)
 pub const ERROR_NO_MORE_FILES: libc::DWORD = 18;
 pub const TOKEN_READ: libc::DWORD = 0x20008;
 pub const FILE_FLAG_OPEN_REPARSE_POINT: libc::DWORD = 0x00200000;
+pub const FILE_FLAG_BACKUP_SEMANTICS: libc::DWORD = 0x02000000;
 pub const MAXIMUM_REPARSE_DATA_BUFFER_SIZE: usize = 16 * 1024;
 pub const FSCTL_GET_REPARSE_POINT: libc::DWORD = 0x900a8;
 pub const IO_REPARSE_TAG_SYMLINK: libc::DWORD = 0xa000000c;
+pub const IO_REPARSE_TAG_MOUNT_POINT: libc::DWORD = 0xa0000003;
+pub const FSCTL_SET_REPARSE_POINT: libc::DWORD = 0x900a4;
+pub const FSCTL_DELETE_REPARSE_POINT: libc::DWORD = 0x900ac;
 
 pub const SYMBOLIC_LINK_FLAG_DIRECTORY: libc::DWORD = 0x1;
 
@@ -71,6 +75,9 @@
 pub const PROGRESS_STOP: libc::DWORD = 2;
 pub const PROGRESS_QUIET: libc::DWORD = 3;
 
+pub const TOKEN_ADJUST_PRIVILEGES: libc::DWORD = 0x0020;
+pub const SE_PRIVILEGE_ENABLED: libc::DWORD = 2;
+
 #[repr(C)]
 #[cfg(target_arch = "x86")]
 pub struct WSADATA {
@@ -287,6 +294,40 @@ pub struct CRITICAL_SECTION {
 };
 pub const SRWLOCK_INIT: SRWLOCK = SRWLOCK { ptr: 0 as *mut _ };
 
+#[repr(C)]
+pub struct LUID {
+    pub LowPart: libc::DWORD,
+    pub HighPart: libc::c_long,
+}
+
+pub type PLUID = *mut LUID;
+
+#[repr(C)]
+pub struct TOKEN_PRIVILEGES {
+    pub PrivilegeCount: libc::DWORD,
+    pub Privileges: [LUID_AND_ATTRIBUTES; 1],
+}
+
+pub type PTOKEN_PRIVILEGES = *mut TOKEN_PRIVILEGES;
+
+#[repr(C)]
+pub struct LUID_AND_ATTRIBUTES {
+    pub Luid: LUID,
+    pub Attributes: libc::DWORD,
+}
+
+#[repr(C)]
+pub struct REPARSE_MOUNTPOINT_DATA_BUFFER {
+    pub ReparseTag: libc::DWORD,
+    pub ReparseDataLength: libc::DWORD,
+    pub Reserved: libc::WORD,
+    pub ReparseTargetLength: libc::WORD,
+    pub ReparseTargetMaximumLength: libc::WORD,
+    pub Reserved1: libc::WORD,
+    pub ReparseTarget: libc::WCHAR,
+}
+
+
 #[link(name = "ws2_32")]
 #[link(name = "userenv")]
 extern "system" {
@@ -437,6 +478,15 @@ pub fn CopyFileExW(lpExistingFileName: libc::LPCWSTR,
                        lpData: libc::LPVOID,
                        pbCancel: LPBOOL,
                        dwCopyFlags: libc::DWORD) -> libc::BOOL;
+    pub fn LookupPrivilegeValueW(lpSystemName: libc::LPCWSTR,
+                                 lpName: libc::LPCWSTR,
+                                 lpLuid: PLUID) -> libc::BOOL;
+    pub fn AdjustTokenPrivileges(TokenHandle: libc::HANDLE,
+                                 DisableAllPrivileges: libc::BOOL,
+                                 NewState: PTOKEN_PRIVILEGES,
+                                 BufferLength: libc::DWORD,
+                                 PreviousState: PTOKEN_PRIVILEGES,
+                                 ReturnLength: *mut libc::DWORD) -> libc::BOOL;
 }
 
 // Functions that aren't available on Windows XP, but we still use them and just
index ae6b20de63910079d53270f749ece6c32bfa446a..890cc455d5df2a2816e3b2eeb9531e337b4a392e 100644 (file)
@@ -30,12 +30,12 @@ pub struct File { handle: Handle }
 
 pub struct FileAttr {
     data: c::WIN32_FILE_ATTRIBUTE_DATA,
-    is_symlink: bool,
+    reparse_tag: libc::DWORD,
 }
 
 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
 pub enum FileType {
-    Dir, File, Symlink, ReparsePoint
+    Dir, File, Symlink, ReparsePoint, MountPoint,
 }
 
 pub struct ReadDir {
@@ -133,7 +133,7 @@ pub fn file_name(&self) -> OsString {
 
     pub fn file_type(&self) -> io::Result<FileType> {
         Ok(FileType::new(self.data.dwFileAttributes,
-                         self.data.dwReserved0 == c::IO_REPARSE_TAG_SYMLINK))
+                         /* reparse_tag = */ self.data.dwReserved0))
     }
 
     pub fn metadata(&self) -> io::Result<FileAttr> {
@@ -146,7 +146,7 @@ pub fn metadata(&self) -> io::Result<FileAttr> {
                 nFileSizeHigh: self.data.nFileSizeHigh,
                 nFileSizeLow: self.data.nFileSizeLow,
             },
-            is_symlink: self.data.dwReserved0 == c::IO_REPARSE_TAG_SYMLINK,
+            reparse_tag: self.data.dwReserved0,
         })
     }
 }
@@ -218,10 +218,12 @@ fn get_flags_and_attributes(&self) -> libc::DWORD {
 }
 
 impl File {
-    fn open_reparse_point(path: &Path) -> io::Result<File> {
+    fn open_reparse_point(path: &Path, write: bool) -> io::Result<File> {
         let mut opts = OpenOptions::new();
-        opts.read(true);
-        opts.flags_and_attributes(c::FILE_FLAG_OPEN_REPARSE_POINT);
+        opts.read(!write);
+        opts.write(write);
+        opts.flags_and_attributes(c::FILE_FLAG_OPEN_REPARSE_POINT |
+                                  c::FILE_FLAG_BACKUP_SEMANTICS);
         File::open(path, &opts)
     }
 
@@ -278,10 +280,13 @@ pub fn file_attr(&self) -> io::Result<FileAttr> {
                     nFileSizeHigh: info.nFileSizeHigh,
                     nFileSizeLow: info.nFileSizeLow,
                 },
-                is_symlink: false,
+                reparse_tag: 0,
             };
             if attr.is_reparse_point() {
-                attr.is_symlink = self.is_symlink();
+                let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+                if let Ok((_, buf)) = self.reparse_point(&mut b) {
+                    attr.reparse_tag = buf.ReparseTag;
+                }
             }
             Ok(attr)
         }
@@ -314,15 +319,11 @@ pub fn seek(&self, pos: SeekFrom) -> io::Result<u64> {
 
     pub fn handle(&self) -> &Handle { &self.handle }
 
-    fn is_symlink(&self) -> bool {
-        self.readlink().is_ok()
-    }
-
-    fn readlink(&self) -> io::Result<PathBuf> {
-        let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
-        let mut bytes = 0;
-
+    fn reparse_point<'a>(&self,
+                         space: &'a mut [u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE])
+                         -> io::Result<(libc::DWORD, &'a c::REPARSE_DATA_BUFFER)> {
         unsafe {
+            let mut bytes = 0;
             try!(cvt({
                 c::DeviceIoControl(self.handle.raw(),
                                    c::FSCTL_GET_REPARSE_POINT,
@@ -333,12 +334,20 @@ fn readlink(&self) -> io::Result<PathBuf> {
                                    &mut bytes,
                                    0 as *mut _)
             }));
-            let buf: *const c::REPARSE_DATA_BUFFER = space.as_ptr() as *const _;
-            if (*buf).ReparseTag != c::IO_REPARSE_TAG_SYMLINK {
-                return Err(io::Error::new(io::ErrorKind::Other, "not a symlink"))
-            }
+            Ok((bytes, &*(space.as_ptr() as *const c::REPARSE_DATA_BUFFER)))
+        }
+    }
+
+    fn readlink(&self) -> io::Result<PathBuf> {
+        let mut space = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+        let (_bytes, buf) = try!(self.reparse_point(&mut space));
+        if buf.ReparseTag != c::IO_REPARSE_TAG_SYMLINK {
+            return Err(io::Error::new(io::ErrorKind::Other, "not a symlink"))
+        }
+
+        unsafe {
             let info: *const c::SYMBOLIC_LINK_REPARSE_BUFFER =
-                    &(*buf).rest as *const _ as *const _;
+                    &buf.rest as *const _ as *const _;
             let path_buffer = &(*info).PathBuffer as *const _ as *const u16;
             let subst_off = (*info).SubstituteNameOffset / 2;
             let subst_ptr = path_buffer.offset(subst_off as isize);
@@ -383,7 +392,7 @@ pub fn perm(&self) -> FilePermissions {
     pub fn attrs(&self) -> u32 { self.data.dwFileAttributes as u32 }
 
     pub fn file_type(&self) -> FileType {
-        FileType::new(self.data.dwFileAttributes, self.is_symlink)
+        FileType::new(self.data.dwFileAttributes, self.reparse_tag)
     }
 
     pub fn created(&self) -> u64 { self.to_u64(&self.data.ftCreationTime) }
@@ -414,12 +423,12 @@ pub fn set_readonly(&mut self, readonly: bool) {
 }
 
 impl FileType {
-    fn new(attrs: libc::DWORD, is_symlink: bool) -> FileType {
+    fn new(attrs: libc::DWORD, reparse_tag: libc::DWORD) -> FileType {
         if attrs & libc::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
-            if is_symlink {
-                FileType::Symlink
-            } else {
-                FileType::ReparsePoint
+            match reparse_tag {
+                c::IO_REPARSE_TAG_SYMLINK => FileType::Symlink,
+                c::IO_REPARSE_TAG_MOUNT_POINT => FileType::MountPoint,
+                _ => FileType::ReparsePoint,
             }
         } else if attrs & c::FILE_ATTRIBUTE_DIRECTORY != 0 {
             FileType::Dir
@@ -430,7 +439,9 @@ fn new(attrs: libc::DWORD, is_symlink: bool) -> FileType {
 
     pub fn is_dir(&self) -> bool { *self == FileType::Dir }
     pub fn is_file(&self) -> bool { *self == FileType::File }
-    pub fn is_symlink(&self) -> bool { *self == FileType::Symlink }
+    pub fn is_symlink(&self) -> bool {
+        *self == FileType::Symlink || *self == FileType::MountPoint
+    }
 }
 
 impl DirBuilder {
@@ -488,7 +499,7 @@ pub fn rmdir(p: &Path) -> io::Result<()> {
 }
 
 pub fn readlink(p: &Path) -> io::Result<PathBuf> {
-    let file = try!(File::open_reparse_point(p));
+    let file = try!(File::open_reparse_point(p, false));
     file.readlink()
 }
 
@@ -517,8 +528,15 @@ pub fn link(src: &Path, dst: &Path) -> io::Result<()> {
 
 pub fn stat(p: &Path) -> io::Result<FileAttr> {
     let attr = try!(lstat(p));
-    if attr.data.dwFileAttributes & libc::FILE_ATTRIBUTE_REPARSE_POINT != 0 {
-        let opts = OpenOptions::new();
+
+    // If this is a reparse point, then we need to reopen the file to get the
+    // actual destination. We also pass the FILE_FLAG_BACKUP_SEMANTICS flag to
+    // ensure that we can open directories (this path may be a directory
+    // junction). Once the file is opened we ask the opened handle what its
+    // metadata information is.
+    if attr.is_reparse_point() {
+        let mut opts = OpenOptions::new();
+        opts.flags_and_attributes(c::FILE_FLAG_BACKUP_SEMANTICS);
         let file = try!(File::open(p, &opts));
         file.file_attr()
     } else {
@@ -534,9 +552,10 @@ pub fn lstat(p: &Path) -> io::Result<FileAttr> {
                                          c::GetFileExInfoStandard,
                                          &mut attr.data as *mut _ as *mut _)));
         if attr.is_reparse_point() {
-            attr.is_symlink = File::open_reparse_point(p).map(|f| {
-                f.is_symlink()
-            }).unwrap_or(false);
+            attr.reparse_tag = File::open_reparse_point(p, false).and_then(|f| {
+                let mut b = [0; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+                f.reparse_point(&mut b).map(|(_, b)| b.ReparseTag)
+            }).unwrap_or(0);
         }
         Ok(attr)
     }
@@ -600,3 +619,124 @@ pub fn copy(from: &Path, to: &Path) -> io::Result<u64> {
     }));
     Ok(size as u64)
 }
+
+#[test]
+fn directory_junctions_are_directories() {
+    use ffi::OsStr;
+    use env;
+    use rand::{self, StdRng, Rng};
+
+    macro_rules! t {
+        ($e:expr) => (match $e {
+            Ok(e) => e,
+            Err(e) => panic!("{} failed with: {}", stringify!($e), e),
+        })
+    }
+
+    let d = DirBuilder::new();
+    let p = env::temp_dir();
+    let mut r = rand::thread_rng();
+    let ret = p.join(&format!("rust-{}", r.next_u32()));
+    let foo = ret.join("foo");
+    let bar = ret.join("bar");
+    t!(d.mkdir(&ret));
+    t!(d.mkdir(&foo));
+    t!(d.mkdir(&bar));
+
+    t!(create_junction(&bar, &foo));
+    let metadata = stat(&bar);
+    t!(delete_junction(&bar));
+
+    t!(rmdir(&foo));
+    t!(rmdir(&bar));
+    t!(rmdir(&ret));
+
+    let metadata = t!(metadata);
+    assert!(metadata.file_type().is_dir());
+
+    // Creating a directory junction on windows involves dealing with reparse
+    // points and the DeviceIoControl function, and this code is a skeleton of
+    // what can be found here:
+    //
+    // http://www.flexhex.com/docs/articles/hard-links.phtml
+    fn create_junction(src: &Path, dst: &Path) -> io::Result<()> {
+        let f = try!(opendir(src, true));
+        let h = f.handle().raw();
+
+        unsafe {
+            let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+            let mut db = data.as_mut_ptr()
+                            as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
+            let mut buf = &mut (*db).ReparseTarget as *mut _;
+            let mut i = 0;
+            let v = br"\??\";
+            let v = v.iter().map(|x| *x as u16);
+            for c in v.chain(dst.as_os_str().encode_wide()) {
+                *buf.offset(i) = c;
+                i += 1;
+            }
+            *buf.offset(i) = 0;
+            i += 1;
+            (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
+            (*db).ReparseTargetMaximumLength = (i * 2) as libc::WORD;
+            (*db).ReparseTargetLength = ((i - 1) * 2) as libc::WORD;
+            (*db).ReparseDataLength =
+                    (*db).ReparseTargetLength as libc::DWORD + 12;
+
+            let mut ret = 0;
+            cvt(c::DeviceIoControl(h as *mut _,
+                                   c::FSCTL_SET_REPARSE_POINT,
+                                   data.as_ptr() as *mut _,
+                                   (*db).ReparseDataLength + 8,
+                                   0 as *mut _, 0,
+                                   &mut ret,
+                                   0 as *mut _)).map(|_| ())
+        }
+    }
+
+    fn opendir(p: &Path, write: bool) -> io::Result<File> {
+        unsafe {
+            let mut token = 0 as *mut _;
+            let mut tp: c::TOKEN_PRIVILEGES = mem::zeroed();
+            try!(cvt(c::OpenProcessToken(c::GetCurrentProcess(),
+                                         c::TOKEN_ADJUST_PRIVILEGES,
+                                         &mut token)));
+            let name: &OsStr = if write {
+                "SeRestorePrivilege".as_ref()
+            } else {
+                "SeBackupPrivilege".as_ref()
+            };
+            let name = name.encode_wide().chain(Some(0)).collect::<Vec<_>>();
+            try!(cvt(c::LookupPrivilegeValueW(0 as *const _,
+                                              name.as_ptr(),
+                                              &mut tp.Privileges[0].Luid)));
+            tp.PrivilegeCount = 1;
+            tp.Privileges[0].Attributes = c::SE_PRIVILEGE_ENABLED;
+            let size = mem::size_of::<c::TOKEN_PRIVILEGES>() as libc::DWORD;
+            try!(cvt(c::AdjustTokenPrivileges(token, libc::FALSE, &mut tp, size,
+                                              0 as *mut _, 0 as *mut _)));
+            try!(cvt(libc::CloseHandle(token)));
+
+            File::open_reparse_point(p, write)
+        }
+    }
+
+    fn delete_junction(p: &Path) -> io::Result<()> {
+        unsafe {
+            let f = try!(opendir(p, true));
+            let h = f.handle().raw();
+            let mut data = [0u8; c::MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+            let mut db = data.as_mut_ptr()
+                            as *mut c::REPARSE_MOUNTPOINT_DATA_BUFFER;
+            (*db).ReparseTag = c::IO_REPARSE_TAG_MOUNT_POINT;
+            let mut bytes = 0;
+            cvt(c::DeviceIoControl(h as *mut _,
+                                   c::FSCTL_DELETE_REPARSE_POINT,
+                                   data.as_ptr() as *mut _,
+                                   (*db).ReparseDataLength + 8,
+                                   0 as *mut _, 0,
+                                   &mut bytes,
+                                   0 as *mut _)).map(|_| ())
+        }
+    }
+}
index 629e3920e1041afc4e741dd81ec76f8955ae743e..22c12fdf3de2bbb77d8dd3db3eeed48cb54b946f 100644 (file)
@@ -44,7 +44,6 @@
 #![feature(rt)]
 #![feature(rustc_private)]
 #![feature(set_stdio)]
-#![feature(slice_extras)]
 #![feature(staged_api)]
 
 extern crate getopts;
@@ -359,7 +358,7 @@ fn usage(binary: &str) {
 
 // Parses command line arguments into test options
 pub fn parse_opts(args: &[String]) -> Option<OptRes> {
-    let args_ = args.tail();
+    let args_ = &args[1..];
     let matches =
         match getopts::getopts(args_, &optgroups()) {
           Ok(m) => m,
index 0da191a30ba385215c5eb1dc97c2b5f076f93b07..c37d3747da75c280237dc2d6b925078e69555499 160000 (submodule)
@@ -1 +1 @@
-Subproject commit 0da191a30ba385215c5eb1dc97c2b5f076f93b07
+Subproject commit c37d3747da75c280237dc2d6b925078e69555499