about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2015-01-06 15:22:24 -0800
committerAlex Crichton <alex@alexcrichton.com>2015-01-06 15:22:24 -0800
commit5c3ddcb15dc8b40fa780a38fd7494b9b5b991d09 (patch)
tree9ad6d0c242e45a785dae4b22f1e4ddd9d4f9c55a /src/libcore
parent5f27b500800fc2720c5caa4a0cd5dcc46c0b911f (diff)
parent44440e5c18a1dbcc9685866ffffe00c508929079 (diff)
downloadrust-5c3ddcb15dc8b40fa780a38fd7494b9b5b991d09.tar.gz
rust-5c3ddcb15dc8b40fa780a38fd7494b9b5b991d09.zip
rollup merge of #20481: seanmonstar/fmt-show-string
Conflicts:
	src/compiletest/runtest.rs
	src/libcore/fmt/mod.rs
	src/libfmt_macros/lib.rs
	src/libregex/parse.rs
	src/librustc/middle/cfg/construct.rs
	src/librustc/middle/dataflow.rs
	src/librustc/middle/infer/higher_ranked/mod.rs
	src/librustc/middle/ty.rs
	src/librustc_back/archive.rs
	src/librustc_borrowck/borrowck/fragments.rs
	src/librustc_borrowck/borrowck/gather_loans/mod.rs
	src/librustc_resolve/lib.rs
	src/librustc_trans/back/link.rs
	src/librustc_trans/save/mod.rs
	src/librustc_trans/trans/base.rs
	src/librustc_trans/trans/callee.rs
	src/librustc_trans/trans/common.rs
	src/librustc_trans/trans/consts.rs
	src/librustc_trans/trans/controlflow.rs
	src/librustc_trans/trans/debuginfo.rs
	src/librustc_trans/trans/expr.rs
	src/librustc_trans/trans/monomorphize.rs
	src/librustc_typeck/astconv.rs
	src/librustc_typeck/check/method/mod.rs
	src/librustc_typeck/check/mod.rs
	src/librustc_typeck/check/regionck.rs
	src/librustc_typeck/collect.rs
	src/libsyntax/ext/format.rs
	src/libsyntax/ext/source_util.rs
	src/libsyntax/ext/tt/transcribe.rs
	src/libsyntax/parse/mod.rs
	src/libsyntax/parse/token.rs
	src/test/run-pass/issue-8898.rs
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/any.rs2
-rw-r--r--src/libcore/borrow.rs20
-rw-r--r--src/libcore/cell.rs11
-rw-r--r--src/libcore/fmt/mod.rs139
-rw-r--r--src/libcore/fmt/num.rs50
-rw-r--r--src/libcore/macros.rs2
-rw-r--r--src/libcore/result.rs8
-rw-r--r--src/libcore/str/mod.rs2
8 files changed, 189 insertions, 45 deletions
diff --git a/src/libcore/any.rs b/src/libcore/any.rs
index 33cb335d756..2c74ad23925 100644
--- a/src/libcore/any.rs
+++ b/src/libcore/any.rs
@@ -46,7 +46,7 @@
 //!     // different type: just print it out unadorned.
 //!     match value_any.downcast_ref::<String>() {
 //!         Some(as_string) => {
-//!             println!("String ({}): {}", as_string.len(), as_string);
+//!             println!("String ({}): {:?}", as_string.len(), as_string);
 //!         }
 //!         None => {
 //!             println!("{}", value);
diff --git a/src/libcore/borrow.rs b/src/libcore/borrow.rs
index 2c08b976355..8cde33c9408 100644
--- a/src/libcore/borrow.rs
+++ b/src/libcore/borrow.rs
@@ -133,6 +133,7 @@ impl<T> ToOwned<T> for T where T: Clone {
 ///     }
 /// }
 /// ```
+//#[deriving(Show)] NOTE(stage0): uncomment after snapshot
 pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> {
     /// Borrowed data.
     Borrowed(&'a B),
@@ -141,6 +142,16 @@ pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned<T> {
     Owned(T)
 }
 
+//NOTE(stage0): replace with deriving(Show) after snapshot
+impl<'a, T, B: ?Sized> fmt::Show for Cow<'a, T, B> where
+    B: fmt::String + ToOwned<T>,
+    T: fmt::String
+{
+    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+        fmt::String::fmt(self, f)
+    }
+}
+
 #[stable]
 impl<'a, T, B: ?Sized> Clone for Cow<'a, T, B> where B: ToOwned<T> {
     fn clone(&self) -> Cow<'a, T, B> {
@@ -237,11 +248,14 @@ impl<'a, T, B: ?Sized> PartialOrd for Cow<'a, T, B> where B: PartialOrd + ToOwne
     }
 }
 
-impl<'a, T, B: ?Sized> fmt::Show for Cow<'a, T, B> where B: fmt::Show + ToOwned<T>, T: fmt::Show {
+impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where
+    B: fmt::String + ToOwned<T>,
+    T: fmt::String,
+{
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         match *self {
-            Borrowed(ref b) => fmt::Show::fmt(b, f),
-            Owned(ref o) => fmt::Show::fmt(o, f),
+            Borrowed(ref b) => fmt::String::fmt(b, f),
+            Owned(ref o) => fmt::String::fmt(o, f),
         }
     }
 }
diff --git a/src/libcore/cell.rs b/src/libcore/cell.rs
index fd18d6ac3f3..3cc197c323c 100644
--- a/src/libcore/cell.rs
+++ b/src/libcore/cell.rs
@@ -160,7 +160,6 @@
 use clone::Clone;
 use cmp::PartialEq;
 use default::Default;
-use fmt;
 use kinds::{Copy, Send};
 use ops::{Deref, DerefMut, Drop};
 use option::Option;
@@ -364,16 +363,6 @@ impl<T: PartialEq> PartialEq for RefCell<T> {
     }
 }
 
-#[unstable]
-impl<T:fmt::Show> fmt::Show for RefCell<T> {
-    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
-        match self.try_borrow() {
-            Some(val) => write!(f, "{}", val),
-            None => write!(f, "<borrowed RefCell>")
-        }
-    }
-}
-
 struct BorrowRef<'b> {
     _borrow: &'b Cell<BorrowFlag>,
 }
diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs
index 76c2671cfd0..fe2511d1f7f 100644
--- a/src/libcore/fmt/mod.rs
+++ b/src/libcore/fmt/mod.rs
@@ -13,7 +13,8 @@
 #![allow(unused_variables)]
 
 use any;
-use cell::{Cell, Ref, RefMut};
+use cell::{Cell, RefCell, Ref, RefMut};
+use char::CharExt;
 use iter::{Iterator, IteratorExt, range};
 use kinds::{Copy, Sized};
 use mem;
@@ -215,21 +216,37 @@ pub struct Arguments<'a> {
     args: &'a [Argument<'a>],
 }
 
+#[cfg(stage0)]
+//FIXME: remove after stage0 snapshot
 impl<'a> Show for Arguments<'a> {
     fn fmt(&self, fmt: &mut Formatter) -> Result {
         write(fmt.buf, *self)
     }
 }
 
-/// When a format is not otherwise specified, types are formatted by ascribing
-/// to this trait. There is not an explicit way of selecting this trait to be
-/// used for formatting, it is only if no other format is specified.
+#[cfg(not(stage0))]
+impl<'a> String for Arguments<'a> {
+    fn fmt(&self, fmt: &mut Formatter) -> Result {
+        write(fmt.buf, *self)
+    }
+}
+
+/// Format trait for the `:?` format. Useful for debugging, most all types
+/// should implement this.
 #[unstable = "I/O and core have yet to be reconciled"]
 pub trait Show {
     /// Formats the value using the given formatter.
     fn fmt(&self, &mut Formatter) -> Result;
 }
 
+/// When a value can be semantically expressed as a String, this trait may be
+/// used. It corresponds to the default format, `{}`.
+#[unstable = "I/O and core have yet to be reconciled"]
+pub trait String {
+    /// Formats the value using the given formatter.
+    fn fmt(&self, &mut Formatter) -> Result;
+}
+
 
 /// Format trait for the `o` character
 #[unstable = "I/O and core have yet to be reconciled"]
@@ -572,7 +589,7 @@ impl<'a> Formatter<'a> {
 
 impl Show for Error {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        "an error occurred when formatting an argument".fmt(f)
+        String::fmt("an error occurred when formatting an argument", f)
     }
 }
 
@@ -595,33 +612,86 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
 
 // Implementations of the core formatting traits
 
-impl<'a, T: ?Sized + Show> Show for &'a T {
-    fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
-}
-impl<'a, T: ?Sized + Show> Show for &'a mut T {
-    fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
+macro_rules! fmt_refs {
+    ($($tr:ident),*) => {
+        $(
+        impl<'a, T: ?Sized + $tr> $tr for &'a T {
+            fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
+        }
+        impl<'a, T: ?Sized + $tr> $tr for &'a mut T {
+            fn fmt(&self, f: &mut Formatter) -> Result { $tr::fmt(&**self, f) }
+        }
+        )*
+    }
 }
 
+fmt_refs! { Show, String, Octal, Binary, LowerHex, UpperHex, LowerExp, UpperExp }
+
 impl Show for bool {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        Show::fmt(if *self { "true" } else { "false" }, f)
+        String::fmt(self, f)
     }
 }
 
+impl String for bool {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        String::fmt(if *self { "true" } else { "false" }, f)
+    }
+}
+
+#[cfg(stage0)]
+//NOTE(stage0): remove impl after snapshot
+impl Show for str {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        String::fmt(self, f)
+    }
+}
+
+#[cfg(not(stage0))]
+//NOTE(stage0): remove cfg after snapshot
 impl Show for str {
     fn fmt(&self, f: &mut Formatter) -> Result {
+        try!(write!(f, "\""));
+        for c in self.chars().flat_map(|c| c.escape_default()) {
+            try!(write!(f, "{}", c));
+        }
+        write!(f, "\"")
+    }
+}
+
+impl String for str {
+    fn fmt(&self, f: &mut Formatter) -> Result {
         f.pad(self)
     }
 }
 
+#[cfg(stage0)]
+//NOTE(stage0): remove impl after snapshot
+impl Show for char {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        String::fmt(self, f)
+    }
+}
+
+#[cfg(not(stage0))]
+//NOTE(stage0): remove cfg after snapshot
 impl Show for char {
     fn fmt(&self, f: &mut Formatter) -> Result {
         use char::CharExt;
+        try!(write!(f, "'"));
+        for c in self.escape_default() {
+            try!(write!(f, "{}", c));
+        }
+        write!(f, "'")
+    }
+}
 
+impl String for char {
+    fn fmt(&self, f: &mut Formatter) -> Result {
         let mut utf8 = [0u8; 4];
         let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
         let s: &str = unsafe { mem::transmute(utf8.index(&(0..amt))) };
-        Show::fmt(s, f)
+        String::fmt(s, f)
     }
 }
 
@@ -653,8 +723,16 @@ impl<'a, T> Pointer for &'a mut T {
 }
 
 macro_rules! floating { ($ty:ident) => {
+
     impl Show for $ty {
         fn fmt(&self, fmt: &mut Formatter) -> Result {
+            try!(String::fmt(self, fmt));
+            fmt.write_str(stringify!($ty))
+        }
+    }
+
+    impl String for $ty {
+        fn fmt(&self, fmt: &mut Formatter) -> Result {
             use num::Float;
 
             let digits = match fmt.precision {
@@ -746,7 +824,7 @@ macro_rules! tuple {
                     if n > 0 {
                         try!(write!(f, ", "));
                     }
-                    try!(write!(f, "{}", *$name));
+                    try!(write!(f, "{:?}", *$name));
                     n += 1;
                 )*
                 if n == 1 {
@@ -777,7 +855,7 @@ impl<T: Show> Show for [T] {
             } else {
                 try!(write!(f, ", "));
             }
-            try!(write!(f, "{}", *x))
+            try!(write!(f, "{:?}", *x))
         }
         if f.flags & (1 << (rt::FlagAlternate as uint)) == 0 {
             try!(write!(f, "]"));
@@ -786,6 +864,21 @@ impl<T: Show> Show for [T] {
     }
 }
 
+impl<T: String> String for [T] {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        let mut is_first = true;
+        for x in self.iter() {
+            if is_first {
+                is_first = false;
+            } else {
+                try!(write!(f, ", "));
+            }
+            try!(String::fmt(x, f))
+        }
+        Ok(())
+    }
+}
+
 impl Show for () {
     fn fmt(&self, f: &mut Formatter) -> Result {
         f.pad("()")
@@ -794,23 +887,33 @@ impl Show for () {
 
 impl<T: Copy + Show> Show for Cell<T> {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        write!(f, "Cell {{ value: {} }}", self.get())
+        write!(f, "Cell {{ value: {:?} }}", self.get())
+    }
+}
+
+#[unstable]
+impl<T: Show> Show for RefCell<T> {
+    fn fmt(&self, f: &mut Formatter) -> Result {
+        match self.try_borrow() {
+            Some(val) => write!(f, "RefCell {{ value: {:?} }}", val),
+            None => write!(f, "RefCell {{ <borrowed> }}")
+        }
     }
 }
 
 impl<'b, T: Show> Show for Ref<'b, T> {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        (**self).fmt(f)
+        Show::fmt(&**self, f)
     }
 }
 
 impl<'b, T: Show> Show for RefMut<'b, T> {
     fn fmt(&self, f: &mut Formatter) -> Result {
-        (*(self.deref())).fmt(f)
+        Show::fmt(&*(self.deref()), f)
     }
 }
 
-impl Show for Utf8Error {
+impl String for Utf8Error {
     fn fmt(&self, f: &mut Formatter) -> Result {
         match *self {
             Utf8Error::InvalidByte(n) => {
diff --git a/src/libcore/fmt/num.rs b/src/libcore/fmt/num.rs
index 89337e0584b..17149aed3db 100644
--- a/src/libcore/fmt/num.rs
+++ b/src/libcore/fmt/num.rs
@@ -154,9 +154,23 @@ pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
 }
 
 macro_rules! radix_fmt {
-    ($T:ty as $U:ty, $fmt:ident) => {
+    ($T:ty as $U:ty, $fmt:ident, $S:expr) => {
+        #[cfg(stage0)]
         impl fmt::Show for RadixFmt<$T, Radix> {
             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                fmt::String::fmt(self, f)
+            }
+        }
+
+        #[cfg(not(stage0))]
+        impl fmt::Show for RadixFmt<$T, Radix> {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                try!(fmt::String::fmt(self, f));
+                f.write_str($S)
+            }
+        }
+        impl fmt::String for RadixFmt<$T, Radix> {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                 match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
             }
         }
@@ -171,24 +185,48 @@ macro_rules! int_base {
         }
     }
 }
+
+macro_rules! show {
+    ($T:ident with $S:expr) => {
+        #[cfg(stage0)]
+        impl fmt::Show for $T {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                fmt::String::fmt(self, f)
+            }
+        }
+
+        #[cfg(not(stage0))]
+        impl fmt::Show for $T {
+            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+                try!(fmt::String::fmt(self, f));
+                f.write_str($S)
+            }
+        }
+    }
+}
 macro_rules! integer {
     ($Int:ident, $Uint:ident) => {
-        int_base! { Show     for $Int as $Int   -> Decimal }
+        integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
+    };
+    ($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
+        int_base! { String   for $Int as $Int   -> Decimal }
         int_base! { Binary   for $Int as $Uint  -> Binary }
         int_base! { Octal    for $Int as $Uint  -> Octal }
         int_base! { LowerHex for $Int as $Uint  -> LowerHex }
         int_base! { UpperHex for $Int as $Uint  -> UpperHex }
-        radix_fmt! { $Int as $Int, fmt_int }
+        radix_fmt! { $Int as $Int, fmt_int, $SI }
+        show! { $Int with $SI }
 
-        int_base! { Show     for $Uint as $Uint -> Decimal }
+        int_base! { String   for $Uint as $Uint -> Decimal }
         int_base! { Binary   for $Uint as $Uint -> Binary }
         int_base! { Octal    for $Uint as $Uint -> Octal }
         int_base! { LowerHex for $Uint as $Uint -> LowerHex }
         int_base! { UpperHex for $Uint as $Uint -> UpperHex }
-        radix_fmt! { $Uint as $Uint, fmt_int }
+        radix_fmt! { $Uint as $Uint, fmt_int, $SU }
+        show! { $Uint with $SU }
     }
 }
-integer! { int, uint }
+integer! { int, uint, "i", "u" }
 integer! { i8, u8 }
 integer! { i16, u16 }
 integer! { i32, u32 }
diff --git a/src/libcore/macros.rs b/src/libcore/macros.rs
index a579f9db416..99e49cc21ed 100644
--- a/src/libcore/macros.rs
+++ b/src/libcore/macros.rs
@@ -83,7 +83,7 @@ macro_rules! assert_eq {
                 if !((*left_val == *right_val) &&
                      (*right_val == *left_val)) {
                     panic!("assertion failed: `(left == right) && (right == left)` \
-                           (left: `{}`, right: `{}`)", *left_val, *right_val)
+                           (left: `{:?}`, right: `{:?}`)", *left_val, *right_val)
                 }
             }
         }
diff --git a/src/libcore/result.rs b/src/libcore/result.rs
index 8e9bf5487e3..95ae6ebfb68 100644
--- a/src/libcore/result.rs
+++ b/src/libcore/result.rs
@@ -47,10 +47,10 @@
 //! let version = parse_version(&[1, 2, 3, 4]);
 //! match version {
 //!     Ok(v) => {
-//!         println!("working with version: {}", v);
+//!         println!("working with version: {:?}", v);
 //!     }
 //!     Err(e) => {
-//!         println!("error parsing header: {}", e);
+//!         println!("error parsing header: {:?}", e);
 //!     }
 //! }
 //! ```
@@ -743,7 +743,7 @@ impl<T, E: Show> Result<T, E> {
         match self {
             Ok(t) => t,
             Err(e) =>
-                panic!("called `Result::unwrap()` on an `Err` value: {}", e)
+                panic!("called `Result::unwrap()` on an `Err` value: {:?}", e)
         }
     }
 }
@@ -773,7 +773,7 @@ impl<T: Show, E> Result<T, E> {
     pub fn unwrap_err(self) -> E {
         match self {
             Ok(t) =>
-                panic!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
+                panic!("called `Result::unwrap_err()` on an `Ok` value: {:?}", t),
             Err(e) => e
         }
     }
diff --git a/src/libcore/str/mod.rs b/src/libcore/str/mod.rs
index bc995a2af72..4d160c35577 100644
--- a/src/libcore/str/mod.rs
+++ b/src/libcore/str/mod.rs
@@ -143,7 +143,7 @@ Section: Creating a string
 */
 
 /// Errors which can occur when attempting to interpret a byte slice as a `str`.
-#[derive(Copy, Eq, PartialEq, Clone)]
+#[derive(Copy, Eq, PartialEq, Clone, Show)]
 #[unstable = "error enumeration recently added and definitions may be refined"]
 pub enum Utf8Error {
     /// An invalid byte was detected at the byte offset given.