From b78b749810f4ed53e8287adfb284f9f32f16b73c Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 19 Feb 2014 18:56:33 -0800 Subject: [PATCH 1/2] Remove all ToStr impls, add Show impls This commit changes the ToStr trait to: impl ToStr for T { fn to_str(&self) -> ~str { format!("{}", *self) } } The ToStr trait has been on the chopping block for quite awhile now, and this is the final nail in its coffin. The trait and the corresponding method are not being removed as part of this commit, but rather any implementations of the `ToStr` trait are being forbidden because of the generic impl. The new way to get the `to_str()` method to work is to implement `fmt::Show`. Formatting into a `&mut Writer` (as `format!` does) is much more efficient than `ToStr` when building up large strings. The `ToStr` trait forces many intermediate allocations to be made while the `fmt::Show` trait allows incremental buildup in the same heap allocated buffer. Additionally, the `fmt::Show` trait is much more extensible in terms of interoperation with other `Writer` instances and in more situations. By design the `ToStr` trait requires at least one allocation whereas the `fmt::Show` trait does not require any allocations. Closes #8242 Closes #9806 --- src/doc/tutorial.md | 2 +- src/libcollections/btree.rs | 60 +++---- src/libcollections/enum_set.rs | 2 +- src/libcollections/hashmap.rs | 8 - src/libcollections/lru_cache.rs | 27 ++-- src/libextra/json.rs | 16 +- src/libextra/url.rs | 149 +++++++++--------- src/libgetopts/lib.rs | 2 +- src/libnum/bigint.rs | 20 +-- src/libnum/complex.rs | 9 +- src/libnum/rational.rs | 7 +- src/librustc/middle/liveness.rs | 16 +- src/librustc/middle/mem_categorization.rs | 8 +- src/librustc/middle/ty.rs | 91 ++++++----- src/librustc/middle/typeck/variance.rs | 12 +- src/librustdoc/clean.rs | 2 +- src/librustdoc/doctree.rs | 2 +- src/librustuv/lib.rs | 9 +- src/libsemver/lib.rs | 15 -- src/libserialize/base64.rs | 9 +- src/libserialize/hex.rs | 9 +- src/libstd/any.rs | 9 -- src/libstd/ascii.rs | 10 +- src/libstd/bool.rs | 17 -- src/libstd/char.rs | 10 +- src/libstd/fmt/mod.rs | 10 ++ src/libstd/io/mod.rs | 42 +---- src/libstd/io/net/ip.rs | 27 ++-- src/libstd/num/f32.rs | 6 - src/libstd/num/f64.rs | 6 - src/libstd/num/int_macros.rs | 8 - src/libstd/num/uint_macros.rs | 8 - src/libstd/option.rs | 15 +- src/libstd/path/mod.rs | 11 -- src/libstd/result.rs | 19 +-- src/libstd/str.rs | 16 -- src/libstd/to_str.rs | 48 +----- src/libstd/tuple.rs | 7 - src/libsyntax/abi.rs | 21 ++- src/libsyntax/ast.rs | 55 +++---- src/libsyntax/ast_map.rs | 8 +- src/libsyntax/attr.rs | 2 +- src/libsyntax/crateid.rs | 11 +- src/libsyntax/diagnostic.rs | 15 +- src/libtest/lib.rs | 20 +-- src/libuuid/lib.rs | 41 +++-- src/test/auxiliary/cci_class_cast.rs | 8 +- ...use-after-move-implicity-coerced-object.rs | 8 +- src/test/run-pass/class-separate-impl.rs | 9 +- src/test/run-pass/deriving-global.rs | 6 +- src/test/run-pass/deriving-in-fn.rs | 4 +- ...{deriving-to-str.rs => deriving-show-2.rs} | 32 ++-- src/test/run-pass/issue-2904.rs | 10 +- src/test/run-pass/issue-3563-3.rs | 7 +- src/test/run-pass/new-impl-syntax.rs | 14 +- 55 files changed, 411 insertions(+), 604 deletions(-) rename src/test/run-pass/{deriving-to-str.rs => deriving-show-2.rs} (71%) diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md index 2e6a0ef7e5bcb..c2469e0c171f8 100644 --- a/src/doc/tutorial.md +++ b/src/doc/tutorial.md @@ -2519,7 +2519,7 @@ of type `ABC` can be randomly generated and converted to a string: #[deriving(Eq)] struct Circle { radius: f64 } -#[deriving(Rand, ToStr)] +#[deriving(Rand, Show)] enum ABC { A, B, C } ~~~ diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index 13b39da0756e0..cc6a5eda7594f 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -18,7 +18,8 @@ ///a length (the height of the tree), and lower and upper bounds on the ///number of elements that a given node can contain. -use std::vec::OwnedVector; +use std::fmt; +use std::fmt::Show; #[allow(missing_doc)] pub struct BTree { @@ -106,11 +107,10 @@ impl TotalOrd for BTree { } } -impl ToStr for BTree { +impl fmt::Show for BTree { ///Returns a string representation of the BTree - fn to_str(&self) -> ~str { - let ret = self.root.to_str(); - ret + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.root.fmt(f) } } @@ -235,15 +235,15 @@ impl TotalOrd for Node { } } -impl ToStr for Node { +impl fmt::Show for Node { ///Returns a string representation of a Node. ///Will iterate over the Node and show "Key: x, value: y, child: () // " ///for all elements in the Node. "Child" only exists if the Node contains ///a branch. - fn to_str(&self) -> ~str { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - LeafNode(ref leaf) => leaf.to_str(), - BranchNode(ref branch) => branch.to_str() + LeafNode(ref leaf) => leaf.fmt(f), + BranchNode(ref branch) => branch.fmt(f), } } } @@ -401,10 +401,14 @@ impl TotalOrd for Leaf { } -impl ToStr for Leaf { +impl fmt::Show for Leaf { ///Returns a string representation of a Leaf. - fn to_str(&self) -> ~str { - self.elts.iter().map(|s| s.to_str()).to_owned_vec().connect(" // ") + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + for (i, s) in self.elts.iter().enumerate() { + if i != 0 { if_ok!(write!(f.buf, " // ")) } + if_ok!(write!(f.buf, "{}", *s)) + } + Ok(()) } } @@ -618,13 +622,14 @@ impl TotalOrd for Branch { } } -impl ToStr for Branch { +impl fmt::Show for Branch { ///Returns a string representation of a Branch. - fn to_str(&self) -> ~str { - let mut ret = self.elts.iter().map(|s| s.to_str()).to_owned_vec().connect(" // "); - ret.push_str(" // "); - ret.push_str("rightmost child: ("+ self.rightmost_child.to_str() +") "); - ret + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + for (i, s) in self.elts.iter().enumerate() { + if i != 0 { if_ok!(write!(f.buf, " // ")) } + if_ok!(write!(f.buf, "{}", *s)) + } + write!(f.buf, " // rightmost child: ({}) ", *self.rightmost_child) } } @@ -672,11 +677,10 @@ impl TotalOrd for LeafElt { } } -impl ToStr for LeafElt { +impl fmt::Show for LeafElt { ///Returns a string representation of a LeafElt. - fn to_str(&self) -> ~str { - format!("Key: {}, value: {};", - self.key.to_str(), self.value.to_str()) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "Key: {}, value: {};", self.key, self.value) } } @@ -715,12 +719,12 @@ impl TotalOrd for BranchElt { } } -impl ToStr for BranchElt { - ///Returns string containing key, value, and child (which should recur to a leaf) - ///Consider changing in future to be more readable. - fn to_str(&self) -> ~str { - format!("Key: {}, value: {}, (child: {})", - self.key.to_str(), self.value.to_str(), self.left.to_str()) +impl fmt::Show for BranchElt { + /// Returns string containing key, value, and child (which should recur to a + /// leaf) Consider changing in future to be more readable. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "Key: {}, value: {}, (child: {})", + self.key, self.value, *self.left) } } diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 0de6eaf53dd83..2bd8cbf03e969 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -15,7 +15,7 @@ use std::num::Bitwise; -#[deriving(Clone, Eq, Hash, ToStr, Encodable, Decodable)] +#[deriving(Clone, Eq, Hash, Show, Encodable, Decodable)] /// A specialized Set implementation to use enum types. pub struct EnumSet { // We must maintain the invariant that no bits are set diff --git a/src/libcollections/hashmap.rs b/src/libcollections/hashmap.rs index fe56dbdd2f147..877f2b3000970 100644 --- a/src/libcollections/hashmap.rs +++ b/src/libcollections/hashmap.rs @@ -606,10 +606,6 @@ impl fmt::Show for HashMap { } } -impl ToStr for HashMap { - fn to_str(&self) -> ~str { format!("{}", *self) } -} - /// HashMap iterator #[deriving(Clone)] pub struct Entries<'a, K, V> { @@ -888,10 +884,6 @@ impl fmt::Show for HashSet { } } -impl ToStr for HashSet { - fn to_str(&self) -> ~str { format!("{}", *self) } -} - impl FromIterator for HashSet { fn from_iterator>(iter: &mut T) -> HashSet { let (lower, _) = iter.size_hint(); diff --git a/src/libcollections/lru_cache.rs b/src/libcollections/lru_cache.rs index ec387df7215d3..b5e44cda66587 100644 --- a/src/libcollections/lru_cache.rs +++ b/src/libcollections/lru_cache.rs @@ -37,10 +37,11 @@ //! assert!(cache.get(&2).is_none()); //! ``` +use std::cast; use std::container::Container; use std::hash::{Hash, sip}; +use std::fmt; use std::ptr; -use std::cast; use HashMap; @@ -217,36 +218,32 @@ impl LruCache { } } -impl ToStr for LruCache { +impl fmt::Show for LruCache { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. - #[inline] - fn to_str(&self) -> ~str { - let mut acc = ~"{"; + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { - if i > 0 { - acc.push_str(", "); - } + if i > 0 { if_ok!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; match (*cur).key { // should never print nil - None => acc.push_str("nil"), - Some(ref k) => acc.push_str(k.to_str()) + None => if_ok!(write!(f.buf, "nil")), + Some(ref k) => if_ok!(write!(f.buf, "{}", *k)), } } - acc.push_str(": "); + if_ok!(write!(f.buf, ": ")); unsafe { match (*cur).value { // should never print nil - None => acc.push_str("nil"), - Some(ref value) => acc.push_str(value.to_str()) + None => if_ok!(write!(f.buf, "nil")), + Some(ref value) => if_ok!(write!(f.buf, "{}", *value)), } } } - acc.push_char('}'); - acc + write!(f.buf, r"\}") } } diff --git a/src/libextra/json.rs b/src/libextra/json.rs index 4cc210aaa6c72..d438b00b992de 100644 --- a/src/libextra/json.rs +++ b/src/libextra/json.rs @@ -240,7 +240,7 @@ use std::io; use std::io::MemWriter; use std::num; use std::str; -use std::to_str; +use std::fmt; use serialize::Encodable; use serialize; @@ -1576,18 +1576,16 @@ impl ToJson for Option { } } -impl to_str::ToStr for Json { +impl fmt::Show for Json { /// Encodes a json value into a string - fn to_str(&self) -> ~str { - let mut s = MemWriter::new(); - self.to_writer(&mut s as &mut io::Writer).unwrap(); - str::from_utf8_owned(s.unwrap()).unwrap() + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.to_writer(f.buf) } } -impl to_str::ToStr for Error { - fn to_str(&self) -> ~str { - format!("{}:{}: {}", self.line, self.col, self.msg) +impl fmt::Show for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}:{}: {}", self.line, self.col, self.msg) } } diff --git a/src/libextra/url.rs b/src/libextra/url.rs index 41d6d95c6bb35..6e0cd72e3e7c1 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -12,12 +12,14 @@ #[allow(missing_doc)]; -use std::io::BufReader; use std::cmp::Eq; -use collections::HashMap; +use std::fmt; use std::hash::{Hash, sip}; +use std::io::BufReader; use std::uint; +use collections::HashMap; + /// A Uniform Resource Locator (URL). A URL is a form of URI (Uniform Resource /// Identifier) that includes network location information, such as hostname or /// port number. @@ -407,10 +409,12 @@ fn split_char_first(s: &str, c: char) -> (~str, ~str) { } } -fn userinfo_to_str(userinfo: &UserInfo) -> ~str { - match userinfo.pass { - Some(ref pass) => format!("{}:{}@", userinfo.user, *pass), - None => format!("{}@", userinfo.user), +impl fmt::Show for UserInfo { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self.pass { + Some(ref pass) => write!(f.buf, "{}:{}@", self.user, *pass), + None => write!(f.buf, "{}@", self.user), + } } } @@ -437,19 +441,18 @@ fn query_from_str(rawquery: &str) -> Query { * println!("{}", url::query_to_str(&query)); // title=The%20Village&north=52.91&west=4.10 * ``` */ +#[allow(unused_must_use)] pub fn query_to_str(query: &Query) -> ~str { - let mut strvec = ~[]; - for kv in query.iter() { - match kv { - &(ref k, ref v) => { - strvec.push(format!("{}={}", - encode_component(*k), - encode_component(*v)) - ); - } - } + use std::io::MemWriter; + use std::str; + + let mut writer = MemWriter::new(); + for (i, &(ref k, ref v)) in query.iter().enumerate() { + if i != 0 { write!(&mut writer, "&"); } + write!(&mut writer, "{}={}", encode_component(*k), + encode_component(*v)); } - return strvec.connect("&"); + str::from_utf8_lossy(writer.unwrap()).into_owned() } /** @@ -784,74 +787,64 @@ impl FromStr for Path { } } -/** - * Converts a URL from `Url` to string representation. - * - * # Arguments - * - * `url` - a URL. - * - * # Returns - * - * A string that contains the formatted URL. Note that this will usually - * be an inverse of `from_str` but might strip out unneeded separators; - * for example, "http://somehost.com?", when parsed and formatted, will - * result in just "http://somehost.com". - */ -pub fn to_str(url: &Url) -> ~str { - let user = match url.user { - Some(ref user) => userinfo_to_str(user), - None => ~"", - }; - - let authority = if url.host.is_empty() { - // If port is Some, we're in a nonsensical situation. Too bad. - ~"" - } else { - match url.port { - Some(ref port) => format!("//{}{}:{}", user, url.host, *port), - None => format!("//{}{}", user, url.host), +impl fmt::Show for Url { + /** + * Converts a URL from `Url` to string representation. + * + * # Arguments + * + * `url` - a URL. + * + * # Returns + * + * A string that contains the formatted URL. Note that this will usually + * be an inverse of `from_str` but might strip out unneeded separators; + * for example, "http://somehost.com?", when parsed and formatted, will + * result in just "http://somehost.com". + */ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "{}:", self.scheme)); + + if !self.host.is_empty() { + if_ok!(write!(f.buf, "//")); + match self.user { + Some(ref user) => if_ok!(write!(f.buf, "{}", *user)), + None => {} + } + match self.port { + Some(ref port) => if_ok!(write!(f.buf, "{}:{}", self.host, + *port)), + None => if_ok!(write!(f.buf, "{}", self.host)), + } } - }; - - let query = if url.query.is_empty() { - ~"" - } else { - format!("?{}", query_to_str(&url.query)) - }; - - let fragment = match url.fragment { - Some(ref fragment) => format!("\\#{}", encode_component(*fragment)), - None => ~"", - }; - - format!("{}:{}{}{}{}", url.scheme, authority, url.path, query, fragment) -} - -pub fn path_to_str(path: &Path) -> ~str { - let query = if path.query.is_empty() { - ~"" - } else { - format!("?{}", query_to_str(&path.query)) - }; - let fragment = match path.fragment { - Some(ref fragment) => format!("\\#{}", encode_component(*fragment)), - None => ~"", - }; + if_ok!(write!(f.buf, "{}", self.path)); - format!("{}{}{}", path.path, query, fragment) -} + if !self.query.is_empty() { + if_ok!(write!(f.buf, "?{}", query_to_str(&self.query))); + } -impl ToStr for Url { - fn to_str(&self) -> ~str { - to_str(self) + match self.fragment { + Some(ref fragment) => write!(f.buf, "\\#{}", + encode_component(*fragment)), + None => Ok(()), + } } } -impl ToStr for Path { - fn to_str(&self) -> ~str { - path_to_str(self) +impl fmt::Show for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "{}", self.path)); + if !self.query.is_empty() { + if_ok!(write!(f.buf, "?{}", self.query)) + } + + match self.fragment { + Some(ref fragment) => { + write!(f.buf, "\\#{}", encode_component(*fragment)) + } + None => Ok(()) + } } } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index 537c2d40c66bf..20594105183a7 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -169,7 +169,7 @@ pub struct Matches { /// The type returned when the command line does not conform to the /// expected format. Call the `to_err_msg` method to retrieve the /// error as a string. -#[deriving(Clone, Eq, ToStr)] +#[deriving(Clone, Eq, Show)] #[allow(missing_doc)] pub enum Fail_ { ArgumentMissing(~str), diff --git a/src/libnum/bigint.rs b/src/libnum/bigint.rs index 0418c61d361b4..894b3794581e1 100644 --- a/src/libnum/bigint.rs +++ b/src/libnum/bigint.rs @@ -19,14 +19,14 @@ A `BigInt` is a combination of `BigUint` and `Sign`. use Integer; use std::cmp; -use std::cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Less, Equal, Greater}; -use std::num::{Zero, One, ToStrRadix, FromStrRadix}; +use std::fmt; use std::num::{Bitwise, ToPrimitive, FromPrimitive}; +use std::num::{Zero, One, ToStrRadix, FromStrRadix}; use std::rand::Rng; use std::str; use std::uint; -use std::{i64, u64}; use std::vec; +use std::{i64, u64}; /** A `BigDigit` is a `BigUint`'s composing element. @@ -121,9 +121,10 @@ impl TotalOrd for BigUint { } } -impl ToStr for BigUint { - #[inline] - fn to_str(&self) -> ~str { self.to_str_radix(10) } +impl fmt::Show for BigUint { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.to_str_radix(10)) + } } impl FromStr for BigUint { @@ -904,9 +905,10 @@ impl TotalOrd for BigInt { } } -impl ToStr for BigInt { - #[inline] - fn to_str(&self) -> ~str { self.to_str_radix(10) } +impl fmt::Show for BigInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.to_str_radix(10)) + } } impl FromStr for BigInt { diff --git a/src/libnum/complex.rs b/src/libnum/complex.rs index 3755b2e43af1b..5ffd23aa34621 100644 --- a/src/libnum/complex.rs +++ b/src/libnum/complex.rs @@ -11,6 +11,7 @@ //! Complex numbers. +use std::fmt; use std::num::{Zero,One,ToStrRadix}; // FIXME #1284: handle complex NaN & infinity etc. This @@ -167,12 +168,12 @@ impl One for Cmplx { } /* string conversions */ -impl ToStr for Cmplx { - fn to_str(&self) -> ~str { +impl fmt::Show for Cmplx { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < Zero::zero() { - format!("{}-{}i", self.re.to_str(), (-self.im).to_str()) + write!(f.buf, "{}-{}i", self.re, -self.im) } else { - format!("{}+{}i", self.re.to_str(), self.im.to_str()) + write!(f.buf, "{}+{}i", self.re, self.im) } } } diff --git a/src/libnum/rational.rs b/src/libnum/rational.rs index 5f1868b48c519..44a916c5d4e22 100644 --- a/src/libnum/rational.rs +++ b/src/libnum/rational.rs @@ -13,6 +13,7 @@ use Integer; use std::cmp; +use std::fmt; use std::from_str::FromStr; use std::num::{Zero,One,ToStrRadix,FromStrRadix,Round}; use bigint::{BigInt, BigUint, Sign, Plus, Minus}; @@ -277,10 +278,10 @@ impl } /* String conversions */ -impl ToStr for Ratio { +impl fmt::Show for Ratio { /// Renders as `numer/denom`. - fn to_str(&self) -> ~str { - format!("{}/{}", self.numer.to_str(), self.denom.to_str()) + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}/{}", self.numer, self.denom) } } impl ToStrRadix for Ratio { diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 3b9f81adbac26..7293c3a3cee0a 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -111,12 +111,12 @@ use middle::moves; use std::cast::transmute; use std::cell::{Cell, RefCell}; -use collections::HashMap; +use std::fmt; use std::io; use std::str; -use std::to_str; use std::uint; use std::vec; +use collections::HashMap; use syntax::ast::*; use syntax::codemap::Span; use syntax::parse::token::special_idents; @@ -184,12 +184,16 @@ pub fn check_crate(tcx: ty::ctxt, tcx.sess.abort_if_errors(); } -impl to_str::ToStr for LiveNode { - fn to_str(&self) -> ~str { format!("ln({})", self.get()) } +impl fmt::Show for LiveNode { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "ln({})", self.get()) + } } -impl to_str::ToStr for Variable { - fn to_str(&self) -> ~str { format!("v({})", self.get()) } +impl fmt::Show for Variable { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "v({})", self.get()) + } } // ______________________________________________________________________ diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index c413439cb5359..0882e8eb69268 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -123,7 +123,7 @@ pub enum ElementKind { OtherElement, } -#[deriving(Eq, Hash)] +#[deriving(Eq, Hash, Show)] pub enum MutabilityCategory { McImmutable, // Immutable. McDeclared, // Directly declared as mutable. @@ -273,12 +273,6 @@ pub trait Typer { fn upvar_borrow(&mut self, upvar_id: ty::UpvarId) -> ty::UpvarBorrow; } -impl ToStr for MutabilityCategory { - fn to_str(&self) -> ~str { - format!("{:?}", *self) - } -} - impl MutabilityCategory { pub fn from_mutbl(m: ast::Mutability) -> MutabilityCategory { match m { diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 8d88c084e9995..b351b5c0cb8a1 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -33,10 +33,11 @@ use util::common::{indenter}; use std::cast; use std::cell::{Cell, RefCell}; use std::cmp; +use std::fmt::Show; +use std::fmt; use std::hash::{Hash, sip}; use std::ops; use std::rc::Rc; -use std::to_str::ToStr; use std::vec; use collections::{HashMap, HashSet}; use syntax::ast::*; @@ -128,14 +129,14 @@ pub struct mt { mutbl: ast::Mutability, } -#[deriving(Clone, Eq, Encodable, Decodable, Hash, ToStr)] +#[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)] pub enum vstore { vstore_fixed(uint), vstore_uniq, vstore_slice(Region) } -#[deriving(Clone, Eq, Hash, Encodable, Decodable, ToStr)] +#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] pub enum TraitStore { UniqTraitStore, // ~Trait RegionTraitStore(Region), // &Trait @@ -196,7 +197,7 @@ pub struct ItemVariances { region_params: OptVec } -#[deriving(Clone, Eq, Decodable, Encodable)] +#[deriving(Clone, Eq, Decodable, Encodable, Show)] pub enum Variance { Covariant, // T <: T iff A <: B -- e.g., function return type Invariant, // T <: T iff B == A -- e.g., type of mutable cell @@ -384,11 +385,13 @@ pub struct t_box_ { // ~15%.) This does mean that a t value relies on the ctxt to keep its box // alive, and using ty::get is unsafe when the ctxt is no longer alive. enum t_opaque {} -pub type t = *t_opaque; -impl ToStr for t { - fn to_str(&self) -> ~str { - ~"*t_opaque" +#[deriving(Clone, Eq, Hash)] +pub struct t { priv inner: *t_opaque } + +impl fmt::Show for t { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.buf.write_str("*t_opaque") } } @@ -458,7 +461,7 @@ pub struct param_ty { } /// Representation of regions: -#[deriving(Clone, Eq, Hash, Encodable, Decodable, ToStr, Show)] +#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] pub enum Region { // Region bound in a type or fn declaration which will be // substituted 'early' -- that is, at the same time when type @@ -618,13 +621,13 @@ impl Region { } } -#[deriving(Clone, Eq, TotalOrd, TotalEq, Hash, Encodable, Decodable, ToStr, Show)] +#[deriving(Clone, Eq, TotalOrd, TotalEq, Hash, Encodable, Decodable, Show)] pub struct FreeRegion { scope_id: NodeId, bound_region: BoundRegion } -#[deriving(Clone, Eq, TotalEq, TotalOrd, Hash, Encodable, Decodable, ToStr, Show)] +#[deriving(Clone, Eq, TotalEq, TotalOrd, Hash, Encodable, Decodable, Show)] pub enum BoundRegion { /// An anonymous region parameter for a given fn (&T) BrAnon(uint), @@ -768,7 +771,7 @@ pub enum IntVarValue { UintType(ast::UintTy), } -#[deriving(Clone, ToStr)] +#[deriving(Clone, Show)] pub enum terr_vstore_kind { terr_vec, terr_str, @@ -776,14 +779,14 @@ pub enum terr_vstore_kind { terr_trait } -#[deriving(Clone, ToStr)] +#[deriving(Clone, Show)] pub struct expected_found { expected: T, found: T } // Data structures used in type unification -#[deriving(Clone, ToStr)] +#[deriving(Clone, Show)] pub enum type_err { terr_mismatch, terr_purity_mismatch(expected_found), @@ -826,7 +829,7 @@ pub struct ParamBounds { pub type BuiltinBounds = EnumSet; -#[deriving(Clone, Encodable, Eq, Decodable, Hash, ToStr)] +#[deriving(Clone, Encodable, Eq, Decodable, Hash, Show)] #[repr(uint)] pub enum BuiltinBound { BoundStatic, @@ -867,7 +870,7 @@ pub struct IntVid(uint); #[deriving(Clone, Eq, Hash)] pub struct FloatVid(uint); -#[deriving(Clone, Eq, Encodable, Decodable, Hash, Show)] +#[deriving(Clone, Eq, Encodable, Decodable, Hash)] pub struct RegionVid { id: uint } @@ -879,7 +882,7 @@ pub enum InferTy { FloatVar(FloatVid) } -#[deriving(Clone, Encodable, Decodable, Hash, ToStr, Show)] +#[deriving(Clone, Encodable, Decodable, Hash, Show)] pub enum InferRegion { ReVar(RegionVid), ReSkolemized(uint, BoundRegion) @@ -910,56 +913,64 @@ impl Vid for TyVid { fn to_uint(&self) -> uint { let TyVid(v) = *self; v } } -impl ToStr for TyVid { - fn to_str(&self) -> ~str { format!("", self.to_uint()) } +impl fmt::Show for TyVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result{ + write!(f.buf, "", self.to_uint()) + } } impl Vid for IntVid { fn to_uint(&self) -> uint { let IntVid(v) = *self; v } } -impl ToStr for IntVid { - fn to_str(&self) -> ~str { format!("", self.to_uint()) } +impl fmt::Show for IntVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "", self.to_uint()) + } } impl Vid for FloatVid { fn to_uint(&self) -> uint { let FloatVid(v) = *self; v } } -impl ToStr for FloatVid { - fn to_str(&self) -> ~str { format!("", self.to_uint()) } +impl fmt::Show for FloatVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "", self.to_uint()) + } } impl Vid for RegionVid { fn to_uint(&self) -> uint { self.id } } -impl ToStr for RegionVid { - fn to_str(&self) -> ~str { format!("{:?}", self.id) } +impl fmt::Show for RegionVid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.id.fmt(f) + } } -impl ToStr for FnSig { - fn to_str(&self) -> ~str { +impl fmt::Show for FnSig { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // grr, without tcx not much we can do. - return ~"(...)"; + write!(f.buf, "(...)") } } -impl ToStr for InferTy { - fn to_str(&self) -> ~str { +impl fmt::Show for InferTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - TyVar(ref v) => v.to_str(), - IntVar(ref v) => v.to_str(), - FloatVar(ref v) => v.to_str() + TyVar(ref v) => v.fmt(f), + IntVar(ref v) => v.fmt(f), + FloatVar(ref v) => v.fmt(f), } } } -impl ToStr for IntVarValue { - fn to_str(&self) -> ~str { +impl fmt::Show for IntVarValue { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - IntType(ref v) => v.to_str(), - UintType(ref v) => v.to_str(), + IntType(ref v) => v.fmt(f), + UintType(ref v) => v.fmt(f), } } } @@ -2020,9 +2031,9 @@ impl ops::Sub for TypeContents { } } -impl ToStr for TypeContents { - fn to_str(&self) -> ~str { - format!("TypeContents({:t})", self.bits) +impl fmt::Show for TypeContents { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "TypeContents({:t})", self.bits) } } diff --git a/src/librustc/middle/typeck/variance.rs b/src/librustc/middle/typeck/variance.rs index 47c40514e6cac..bd244b431c20e 100644 --- a/src/librustc/middle/typeck/variance.rs +++ b/src/librustc/middle/typeck/variance.rs @@ -197,6 +197,7 @@ use arena; use arena::Arena; use middle::ty; use std::vec; +use std::fmt; use syntax::ast; use syntax::ast_util; use syntax::opt_vec; @@ -235,13 +236,12 @@ enum VarianceTerm<'a> { InferredTerm(InferredIndex), } -impl<'a> ToStr for VarianceTerm<'a> { - fn to_str(&self) -> ~str { +impl<'a> fmt::Show for VarianceTerm<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ConstantTerm(c1) => format!("{}", c1.to_str()), - TransformTerm(v1, v2) => format!("({} \u00D7 {})", - v1.to_str(), v2.to_str()), - InferredTerm(id) => format!("[{}]", { let InferredIndex(i) = id; i }) + ConstantTerm(c1) => write!(f.buf, "{}", c1), + TransformTerm(v1, v2) => write!(f.buf, "({} \u00D7 {})", v1, v2), + InferredTerm(id) => write!(f.buf, "[{}]", { let InferredIndex(i) = id; i }) } } } diff --git a/src/librustdoc/clean.rs b/src/librustdoc/clean.rs index 6e6276e0457b7..2f6f6726be681 100644 --- a/src/librustdoc/clean.rs +++ b/src/librustdoc/clean.rs @@ -976,7 +976,7 @@ impl Clean for doctree::Static { } } -#[deriving(ToStr, Clone, Encodable, Decodable)] +#[deriving(Show, Clone, Encodable, Decodable)] pub enum Mutability { Mutable, Immutable, diff --git a/src/librustdoc/doctree.rs b/src/librustdoc/doctree.rs index 03186c16733a5..af082544532a7 100644 --- a/src/librustdoc/doctree.rs +++ b/src/librustdoc/doctree.rs @@ -58,7 +58,7 @@ impl Module { } } -#[deriving(ToStr, Clone, Encodable, Decodable)] +#[deriving(Show, Clone, Encodable, Decodable)] pub enum StructType { /// A normal struct Plain, diff --git a/src/librustuv/lib.rs b/src/librustuv/lib.rs index adbe4491886d4..9b327dc4ee412 100644 --- a/src/librustuv/lib.rs +++ b/src/librustuv/lib.rs @@ -45,8 +45,9 @@ via `close` and `delete` methods. #[cfg(test)] extern crate green; use std::cast; -use std::io; +use std::fmt; use std::io::IoError; +use std::io; use std::libc::{c_int, c_void}; use std::ptr::null; use std::ptr; @@ -339,9 +340,9 @@ impl UvError { } } -impl ToStr for UvError { - fn to_str(&self) -> ~str { - format!("{}: {}", self.name(), self.desc()) +impl fmt::Show for UvError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}: {}", self.name(), self.desc()) } } diff --git a/src/libsemver/lib.rs b/src/libsemver/lib.rs index d03d230d8bfd4..4c596b11ad609 100644 --- a/src/libsemver/lib.rs +++ b/src/libsemver/lib.rs @@ -38,7 +38,6 @@ use std::cmp; use std::fmt; use std::fmt::Show; use std::option::{Option, Some, None}; -use std::to_str::ToStr; /// An identifier in the pre-release or build metadata. If the identifier can /// be parsed as a decimal value, it will be represented with `Numeric`. @@ -71,13 +70,6 @@ impl fmt::Show for Identifier { } } -impl ToStr for Identifier { - #[inline] - fn to_str(&self) -> ~str { - format!("{}", *self) - } -} - /// Represents a version number conforming to the semantic versioning scheme. #[deriving(Clone, Eq)] @@ -118,13 +110,6 @@ impl fmt::Show for Version { } } -impl ToStr for Version { - #[inline] - fn to_str(&self) -> ~str { - format!("{}", *self) - } -} - impl cmp::Ord for Version { #[inline] fn lt(&self, other: &Version) -> bool { diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index 839450ce57cc3..f43c62f6ffc7e 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -10,6 +10,7 @@ //! Base64 binary-to-text encoding use std::str; +use std::fmt; /// Available encoding character sets pub enum CharacterSet { @@ -165,12 +166,12 @@ pub enum FromBase64Error { InvalidBase64Length, } -impl ToStr for FromBase64Error { - fn to_str(&self) -> ~str { +impl fmt::Show for FromBase64Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidBase64Character(ch, idx) => - format!("Invalid character '{}' at position {}", ch, idx), - InvalidBase64Length => ~"Invalid length", + write!(f.buf, "Invalid character '{}' at position {}", ch, idx), + InvalidBase64Length => write!(f.buf, "Invalid length"), } } } diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index 223a586a5a0dd..5ec70773c3fcf 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -11,6 +11,7 @@ //! Hex binary-to-text encoding use std::str; use std::vec; +use std::fmt; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { @@ -65,12 +66,12 @@ pub enum FromHexError { InvalidHexLength, } -impl ToStr for FromHexError { - fn to_str(&self) -> ~str { +impl fmt::Show for FromHexError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { InvalidHexCharacter(ch, idx) => - format!("Invalid character '{}' at position {}", ch, idx), - InvalidHexLength => ~"Invalid input length", + write!(f.buf, "Invalid character '{}' at position {}", ch, idx), + InvalidHexLength => write!(f.buf, "Invalid input length"), } } } diff --git a/src/libstd/any.rs b/src/libstd/any.rs index 06ae20d60bce5..551a34fc87fbd 100644 --- a/src/libstd/any.rs +++ b/src/libstd/any.rs @@ -24,7 +24,6 @@ use cast::transmute; use fmt; use option::{Option, Some, None}; use result::{Result, Ok, Err}; -use to_str::ToStr; use intrinsics::TypeId; use intrinsics; @@ -151,14 +150,6 @@ impl AnyOwnExt for ~Any { // Trait implementations /////////////////////////////////////////////////////////////////////////////// -impl ToStr for ~Any { - fn to_str(&self) -> ~str { ~"~Any" } -} - -impl<'a> ToStr for &'a Any { - fn to_str(&self) -> ~str { ~"&Any" } -} - impl fmt::Show for ~Any { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad("~Any") diff --git a/src/libstd/ascii.rs b/src/libstd/ascii.rs index 1ae36ab46aad2..ac24a02c15b26 100644 --- a/src/libstd/ascii.rs +++ b/src/libstd/ascii.rs @@ -10,7 +10,7 @@ //! Operations on ASCII strings and characters -use to_str::{ToStr, IntoStr}; +use to_str::{IntoStr}; use str; use str::Str; use str::StrSlice; @@ -127,14 +127,6 @@ impl Ascii { } } -impl ToStr for Ascii { - #[inline] - fn to_str(&self) -> ~str { - // self.chr is always a valid utf8 byte, no need for the check - unsafe { str::raw::from_byte(self.chr) } - } -} - impl<'a> fmt::Show for Ascii { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (self.chr as char).fmt(f) diff --git a/src/libstd/bool.rs b/src/libstd/bool.rs index af745f94fb519..918d42e1bce46 100644 --- a/src/libstd/bool.rs +++ b/src/libstd/bool.rs @@ -17,7 +17,6 @@ //! Implementations of the following traits: //! //! * `FromStr` -//! * `ToStr` //! * `Not` //! * `Ord` //! * `TotalOrd` @@ -34,7 +33,6 @@ use option::{None, Option, Some}; use from_str::FromStr; -use to_str::ToStr; use num::FromPrimitive; #[cfg(not(test))] use cmp::{Eq, Ord, TotalOrd, Ordering}; @@ -179,21 +177,6 @@ impl FromStr for bool { } } -impl ToStr for bool { - /// Convert a `bool` to a string. - /// - /// # Examples - /// - /// ```rust - /// assert_eq!(true.to_str(), ~"true"); - /// assert_eq!(false.to_str(), ~"false"); - /// ``` - #[inline] - fn to_str(&self) -> ~str { - if *self { ~"true" } else { ~"false" } - } -} - #[cfg(not(test))] impl Not for bool { /// The logical complement of a boolean value. diff --git a/src/libstd/char.rs b/src/libstd/char.rs index 1ec89d1850f0e..ed2a88e644b08 100644 --- a/src/libstd/char.rs +++ b/src/libstd/char.rs @@ -15,8 +15,6 @@ use option::{None, Option, Some}; use iter::{Iterator, range_step}; use str::StrSlice; use unicode::{derived_property, property, general_category, decompose}; -use to_str::ToStr; -use str; #[cfg(test)] use str::OwnedStr; @@ -344,13 +342,6 @@ pub fn len_utf8_bytes(c: char) -> uint { } } -impl ToStr for char { - #[inline] - fn to_str(&self) -> ~str { - str::from_char(*self) - } -} - #[allow(missing_doc)] pub trait Char { fn is_alphabetic(&self) -> bool; @@ -556,6 +547,7 @@ fn test_escape_unicode() { #[test] fn test_to_str() { + use to_str::ToStr; let s = 't'.to_str(); assert_eq!(s, ~"t"); } diff --git a/src/libstd/fmt/mod.rs b/src/libstd/fmt/mod.rs index a55794b08fe36..5c0838fadca46 100644 --- a/src/libstd/fmt/mod.rs +++ b/src/libstd/fmt/mod.rs @@ -1055,6 +1055,16 @@ pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> { // Implementations of the core formatting traits +impl Show for @T { + fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) } +} +impl Show for ~T { + fn fmt(&self, f: &mut Formatter) -> Result { secret_show(&**self, f) } +} +impl<'a, T: Show> Show for &'a T { + fn fmt(&self, f: &mut Formatter) -> Result { secret_show(*self, f) } +} + impl Bool for bool { fn fmt(&self, f: &mut Formatter) -> Result { secret_string(&(if *self {"true"} else {"false"}), f) diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 91a8d59932689..94d32d6d8f391 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -188,7 +188,6 @@ use path::Path; use result::{Ok, Err, Result}; use str::{StrSlice, OwnedStr}; use str; -use to_str::ToStr; use uint; use unstable::finally::try_finally; use vec::{OwnedVector, MutableVector, ImmutableVector, OwnedCloneableVector}; @@ -286,21 +285,7 @@ impl fmt::Show for IoError { } } -// FIXME: #8242 implementing manually because deriving doesn't work for some reason -impl ToStr for IoError { - fn to_str(&self) -> ~str { - let mut s = ~"IoError { kind: "; - s.push_str(self.kind.to_str()); - s.push_str(", desc: "); - s.push_str(self.desc); - s.push_str(", detail: "); - s.push_str(self.detail.to_str()); - s.push_str(" }"); - s - } -} - -#[deriving(Eq, Clone)] +#[deriving(Eq, Clone, Show)] pub enum IoErrorKind { OtherIoError, EndOfFile, @@ -321,31 +306,6 @@ pub enum IoErrorKind { InvalidInput, } -// FIXME: #8242 implementing manually because deriving doesn't work for some reason -impl ToStr for IoErrorKind { - fn to_str(&self) -> ~str { - match *self { - OtherIoError => ~"OtherIoError", - EndOfFile => ~"EndOfFile", - FileNotFound => ~"FileNotFound", - PermissionDenied => ~"PermissionDenied", - ConnectionFailed => ~"ConnectionFailed", - Closed => ~"Closed", - ConnectionRefused => ~"ConnectionRefused", - ConnectionReset => ~"ConnectionReset", - NotConnected => ~"NotConnected", - BrokenPipe => ~"BrokenPipe", - PathAlreadyExists => ~"PathAlreadyExists", - PathDoesntExist => ~"PathDoesntExist", - MismatchedFileTypeForOperation => ~"MismatchedFileTypeForOperation", - IoUnavailable => ~"IoUnavailable", - ResourceUnavailable => ~"ResourceUnavailable", - ConnectionAborted => ~"ConnectionAborted", - InvalidInput => ~"InvalidInput", - } - } -} - pub trait Reader { // Only method which need to get implemented for this trait diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index 13ea552ab3b65..e4f3676432378 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -9,11 +9,11 @@ // except according to those terms. use container::Container; +use fmt; use from_str::FromStr; use iter::Iterator; use option::{Option, None, Some}; use str::StrSlice; -use to_str::ToStr; use vec::{MutableCloneableVector, ImmutableVector, MutableVector}; pub type Port = u16; @@ -24,26 +24,27 @@ pub enum IpAddr { Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16) } -impl ToStr for IpAddr { - fn to_str(&self) -> ~str { +impl fmt::Show for IpAddr { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Ipv4Addr(a, b, c, d) => - format!("{}.{}.{}.{}", a, b, c, d), + write!(fmt.buf, "{}.{}.{}.{}", a, b, c, d), // Ipv4 Compatible address Ipv6Addr(0, 0, 0, 0, 0, 0, g, h) => { - format!("::{}.{}.{}.{}", (g >> 8) as u8, g as u8, - (h >> 8) as u8, h as u8) + write!(fmt.buf, "::{}.{}.{}.{}", (g >> 8) as u8, g as u8, + (h >> 8) as u8, h as u8) } // Ipv4-Mapped address Ipv6Addr(0, 0, 0, 0, 0, 0xFFFF, g, h) => { - format!("::FFFF:{}.{}.{}.{}", (g >> 8) as u8, g as u8, - (h >> 8) as u8, h as u8) + write!(fmt.buf, "::FFFF:{}.{}.{}.{}", (g >> 8) as u8, g as u8, + (h >> 8) as u8, h as u8) } Ipv6Addr(a, b, c, d, e, f, g, h) => - format!("{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", a, b, c, d, e, f, g, h) + write!(fmt.buf, "{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}:{:x}", + a, b, c, d, e, f, g, h) } } } @@ -55,11 +56,11 @@ pub struct SocketAddr { } -impl ToStr for SocketAddr { - fn to_str(&self) -> ~str { +impl fmt::Show for SocketAddr { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.ip { - Ipv4Addr(..) => format!("{}:{}", self.ip.to_str(), self.port), - Ipv6Addr(..) => format!("[{}]:{}", self.ip.to_str(), self.port), + Ipv4Addr(..) => write!(f.buf, "{}:{}", self.ip, self.port), + Ipv6Addr(..) => write!(f.buf, "[{}]:{}", self.ip, self.port), } } } diff --git a/src/libstd/num/f32.rs b/src/libstd/num/f32.rs index 7b1fe949199cd..a4eac564ee692 100644 --- a/src/libstd/num/f32.rs +++ b/src/libstd/num/f32.rs @@ -19,7 +19,6 @@ use libc::{c_float, c_int}; use num::{FPCategory, FPNaN, FPInfinite , FPZero, FPSubnormal, FPNormal}; use num::{Zero, One, Bounded, strconv}; use num; -use to_str; use intrinsics; macro_rules! delegate( @@ -745,11 +744,6 @@ pub fn to_str_exp_digits(num: f32, dig: uint, upper: bool) -> ~str { r } -impl to_str::ToStr for f32 { - #[inline] - fn to_str(&self) -> ~str { to_str_digits(*self, 8) } -} - impl num::ToStrRadix for f32 { /// Converts a float to a string in a given radix /// diff --git a/src/libstd/num/f64.rs b/src/libstd/num/f64.rs index d5a571cdd2371..e6b903cbbdb6e 100644 --- a/src/libstd/num/f64.rs +++ b/src/libstd/num/f64.rs @@ -20,7 +20,6 @@ use libc::{c_double, c_int}; use num::{FPCategory, FPNaN, FPInfinite , FPZero, FPSubnormal, FPNormal}; use num::{Zero, One, Bounded, strconv}; use num; -use to_str; use intrinsics; pub use cmp::{min, max}; @@ -747,11 +746,6 @@ pub fn to_str_exp_digits(num: f64, dig: uint, upper: bool) -> ~str { r } -impl to_str::ToStr for f64 { - #[inline] - fn to_str(&self) -> ~str { to_str_digits(*self, 8) } -} - impl num::ToStrRadix for f64 { /// Converts a float to a string in a given radix /// diff --git a/src/libstd/num/int_macros.rs b/src/libstd/num/int_macros.rs index 43a7019081207..030aa2d81fa24 100644 --- a/src/libstd/num/int_macros.rs +++ b/src/libstd/num/int_macros.rs @@ -273,14 +273,6 @@ pub fn to_str_bytes(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { f(buf.slice(0, cur)) } -impl ToStr for $T { - /// Convert to a string in base 10. - #[inline] - fn to_str(&self) -> ~str { - format!("{:d}", *self) - } -} - impl ToStrRadix for $T { /// Convert to a string in a given base. #[inline] diff --git a/src/libstd/num/uint_macros.rs b/src/libstd/num/uint_macros.rs index d60b523544601..001927e603312 100644 --- a/src/libstd/num/uint_macros.rs +++ b/src/libstd/num/uint_macros.rs @@ -187,14 +187,6 @@ pub fn to_str_bytes(n: $T, radix: uint, f: |v: &[u8]| -> U) -> U { f(buf.slice(0, cur)) } -impl ToStr for $T { - /// Convert to a string in base 10. - #[inline] - fn to_str(&self) -> ~str { - format!("{:u}", *self) - } -} - impl ToStrRadix for $T { /// Convert to a string in a given base. #[inline] diff --git a/src/libstd/option.rs b/src/libstd/option.rs index 44d78be93d624..633d6e92c704c 100644 --- a/src/libstd/option.rs +++ b/src/libstd/option.rs @@ -42,16 +42,13 @@ use clone::Clone; use clone::DeepClone; use cmp::{Eq, TotalEq, TotalOrd}; use default::Default; -use fmt; use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize}; use kinds::Send; use mem; -use str::OwnedStr; -use to_str::ToStr; use vec; /// The option type -#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)] +#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, Show)] pub enum Option { /// No value None, @@ -380,16 +377,6 @@ impl Option { // Trait implementations ///////////////////////////////////////////////////////////////////////////// -impl fmt::Show for Option { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Some(ref t) => write!(f.buf, "Some({})", *t), - None => write!(f.buf, "None") - } - } -} - impl Default for Option { #[inline] fn default() -> Option { None } diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 13496033fd0e5..09124f63361d5 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -71,7 +71,6 @@ use iter::Iterator; use option::{Option, None, Some}; use str; use str::{MaybeOwned, OwnedStr, Str, StrSlice, from_utf8_lossy}; -use to_str::ToStr; use vec; use vec::{CloneableVector, OwnedCloneableVector, OwnedVector, Vector}; use vec::{ImmutableEqVector, ImmutableVector}; @@ -499,16 +498,6 @@ impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { } } -impl<'a, P: GenericPath> ToStr for Display<'a, P> { - /// Returns the path as a string - /// - /// If the path is not UTF-8, invalid sequences with be replaced with the - /// unicode replacement char. This involves allocation. - fn to_str(&self) -> ~str { - self.as_maybe_owned().into_owned() - } -} - impl<'a, P: GenericPath> Display<'a, P> { /// Returns the path as a possibly-owned string. /// diff --git a/src/libstd/result.rs b/src/libstd/result.rs index 39e8b6ad6c1d2..3f09351ead66c 100644 --- a/src/libstd/result.rs +++ b/src/libstd/result.rs @@ -12,14 +12,11 @@ use clone::Clone; use cmp::Eq; -use fmt; use iter::{Iterator, FromIterator}; use option::{None, Option, Some}; -use str::OwnedStr; -use to_str::ToStr; /// `Result` is a type that represents either success (`Ok`) or failure (`Err`). -#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, ToStr)] +#[deriving(Clone, DeepClone, Eq, Ord, TotalEq, TotalOrd, Show)] #[must_use] pub enum Result { /// Contains the success value @@ -202,20 +199,6 @@ impl Result { } } -///////////////////////////////////////////////////////////////////////////// -// Trait implementations -///////////////////////////////////////////////////////////////////////////// - -impl fmt::Show for Result { - #[inline] - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Ok(ref t) => write!(f.buf, "Ok({})", *t), - Err(ref e) => write!(f.buf, "Err({})", *e) - } - } -} - ///////////////////////////////////////////////////////////////////////////// // Free functions ///////////////////////////////////////////////////////////////////////////// diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 3c094cd631d76..daaf46be18767 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -98,7 +98,6 @@ use num::Saturating; use option::{None, Option, Some}; use ptr; use ptr::RawPtr; -use to_str::ToStr; use from_str::FromStr; use vec; use vec::{OwnedVector, OwnedCloneableVector, ImmutableVector, MutableVector}; @@ -132,21 +131,11 @@ pub fn from_utf8<'a>(v: &'a [u8]) -> Option<&'a str> { } else { None } } -impl ToStr for ~str { - #[inline] - fn to_str(&self) -> ~str { self.to_owned() } -} - impl FromStr for ~str { #[inline] fn from_str(s: &str) -> Option<~str> { Some(s.to_owned()) } } -impl<'a> ToStr for &'a str { - #[inline] - fn to_str(&self) -> ~str { self.to_owned() } -} - /// Convert a byte to a UTF-8 string /// /// # Failure @@ -1269,11 +1258,6 @@ impl<'a> IntoMaybeOwned<'a> for MaybeOwned<'a> { fn into_maybe_owned(self) -> MaybeOwned<'a> { self } } -impl<'a> ToStr for MaybeOwned<'a> { - #[inline] - fn to_str(&self) -> ~str { self.as_slice().to_owned() } -} - impl<'a> Eq for MaybeOwned<'a> { #[inline] fn eq(&self, other: &MaybeOwned) -> bool { diff --git a/src/libstd/to_str.rs b/src/libstd/to_str.rs index 46a9e93f41642..ba3c1c0fc4554 100644 --- a/src/libstd/to_str.rs +++ b/src/libstd/to_str.rs @@ -14,10 +14,7 @@ The `ToStr` trait for converting to strings */ -use option::{Some, None}; -use str::OwnedStr; -use iter::Iterator; -use vec::ImmutableVector; +use fmt; /// A generic trait for converting a value to a string pub trait ToStr { @@ -31,47 +28,8 @@ pub trait IntoStr { fn into_str(self) -> ~str; } -impl ToStr for () { - #[inline] - fn to_str(&self) -> ~str { ~"()" } -} - -impl<'a,A:ToStr> ToStr for &'a [A] { - #[inline] - fn to_str(&self) -> ~str { - let mut acc = ~"["; - let mut first = true; - for elt in self.iter() { - if first { - first = false; - } - else { - acc.push_str(", "); - } - acc.push_str(elt.to_str()); - } - acc.push_char(']'); - acc - } -} - -impl ToStr for ~[A] { - #[inline] - fn to_str(&self) -> ~str { - let mut acc = ~"["; - let mut first = true; - for elt in self.iter() { - if first { - first = false; - } - else { - acc.push_str(", "); - } - acc.push_str(elt.to_str()); - } - acc.push_char(']'); - acc - } +impl ToStr for T { + fn to_str(&self) -> ~str { format!("{}", *self) } } #[cfg(test)] diff --git a/src/libstd/tuple.rs b/src/libstd/tuple.rs index b0d51cba103d4..9d50337efabdc 100644 --- a/src/libstd/tuple.rs +++ b/src/libstd/tuple.rs @@ -17,7 +17,6 @@ use clone::Clone; #[cfg(not(test))] use default::Default; use fmt; use result::{Ok, Err}; -use to_str::ToStr; // macro for implementing n-ary tuple functions and operations macro_rules! tuple_impls { @@ -119,12 +118,6 @@ macro_rules! tuple_impls { } } - impl<$($T: fmt::Show),+> ToStr for ($($T,)+) { - fn to_str(&self) -> ~str { - format!("{}", *self) - } - } - impl<$($T: fmt::Show),+> fmt::Show for ($($T,)+) { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write_tuple!(f.buf, $(self.$refN()),+) diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index 13725ef24734f..faf24da74ccfc 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -9,6 +9,8 @@ // except according to those terms. use std::hash::{Hash, sip}; +use std::fmt; +use std::fmt::Show; #[deriving(Eq)] pub enum Os { OsWin32, OsMacos, OsLinux, OsAndroid, OsFreebsd, } @@ -271,20 +273,23 @@ impl Hash for Abi { } } -impl ToStr for Abi { - fn to_str(&self) -> ~str { - self.data().name.to_str() +impl fmt::Show for Abi { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + self.data().name.fmt(f) } } -impl ToStr for AbiSet { - fn to_str(&self) -> ~str { - let mut strs = ~[]; +impl fmt::Show for AbiSet { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "\"")); + let mut first = true; self.each(|abi| { - strs.push(abi.data().name); + if first { first = false; } + else { let _ = write!(f.buf, " "); } + let _ = write!(f.buf, "{}", abi.data().name); true }); - format!("\"{}\"", strs.connect(" ")) + write!(f.buf, "\"") } } diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 4e43592ec5c2f..7561d8cbbae88 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -17,11 +17,12 @@ use opt_vec::OptVec; use parse::token::{InternedString, special_idents, str_to_ident}; use parse::token; +use std::fmt; +use std::fmt::Show; use std::cell::RefCell; use collections::HashMap; use std::option::Option; use std::rc::Rc; -use std::to_str::ToStr; use serialize::{Encodable, Decodable, Encoder, Decoder}; /// A pointer abstraction. FIXME(eddyb) #10676 use Rc in the future. @@ -39,7 +40,7 @@ pub fn P(value: T) -> P { // table) and a SyntaxContext to track renaming and // macro expansion per Flatt et al., "Macros // That Work Together" -#[deriving(Clone, Hash, ToStr, TotalEq, TotalOrd, Show)] +#[deriving(Clone, Hash, TotalEq, TotalOrd, Show)] pub struct Ident { name: Name, ctxt: SyntaxContext } impl Ident { @@ -182,7 +183,7 @@ pub type CrateNum = u32; pub type NodeId = u32; -#[deriving(Clone, TotalEq, TotalOrd, Eq, Encodable, Decodable, Hash, ToStr, Show)] +#[deriving(Clone, TotalEq, TotalOrd, Eq, Encodable, Decodable, Hash, Show)] pub struct DefId { krate: CrateNum, node: NodeId, @@ -277,7 +278,7 @@ pub enum Def { DefMethod(DefId /* method */, Option /* trait */), } -#[deriving(Clone, Eq, Hash, Encodable, Decodable, ToStr)] +#[deriving(Clone, Eq, Hash, Encodable, Decodable, Show)] pub enum DefRegion { DefStaticRegion, DefEarlyBoundRegion(/* index */ uint, /* lifetime decl */ NodeId), @@ -398,12 +399,12 @@ pub enum Sigil { ManagedSigil } -impl ToStr for Sigil { - fn to_str(&self) -> ~str { +impl fmt::Show for Sigil { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - BorrowedSigil => ~"&", - OwnedSigil => ~"~", - ManagedSigil => ~"@" + BorrowedSigil => "&".fmt(f), + OwnedSigil => "~".fmt(f), + ManagedSigil => "@".fmt(f), } } } @@ -768,9 +769,9 @@ pub enum IntTy { TyI64, } -impl ToStr for IntTy { - fn to_str(&self) -> ~str { - ast_util::int_ty_to_str(*self) +impl fmt::Show for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", ast_util::int_ty_to_str(*self)) } } @@ -783,9 +784,9 @@ pub enum UintTy { TyU64, } -impl ToStr for UintTy { - fn to_str(&self) -> ~str { - ast_util::uint_ty_to_str(*self) +impl fmt::Show for UintTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", ast_util::uint_ty_to_str(*self)) } } @@ -795,9 +796,9 @@ pub enum FloatTy { TyF64, } -impl ToStr for FloatTy { - fn to_str(&self) -> ~str { - ast_util::float_ty_to_str(*self) +impl fmt::Show for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", ast_util::float_ty_to_str(*self)) } } @@ -826,11 +827,11 @@ pub enum Onceness { Many } -impl ToStr for Onceness { - fn to_str(&self) -> ~str { +impl fmt::Show for Onceness { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Once => ~"once", - Many => ~"many" + Once => "once".fmt(f), + Many => "many".fmt(f), } } } @@ -939,12 +940,12 @@ pub enum Purity { ExternFn, // declared with "extern fn" } -impl ToStr for Purity { - fn to_str(&self) -> ~str { +impl fmt::Show for Purity { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ImpureFn => ~"impure", - UnsafeFn => ~"unsafe", - ExternFn => ~"extern" + ImpureFn => "impure".fmt(f), + UnsafeFn => "unsafe".fmt(f), + ExternFn => "extern".fmt(f), } } } diff --git a/src/libsyntax/ast_map.rs b/src/libsyntax/ast_map.rs index 26c4b07fc9644..9194cfb0694bb 100644 --- a/src/libsyntax/ast_map.rs +++ b/src/libsyntax/ast_map.rs @@ -22,6 +22,7 @@ use std::logging; use std::cell::RefCell; use std::iter; use std::vec; +use std::fmt; #[deriving(Clone, Eq)] pub enum PathElem { @@ -37,9 +38,10 @@ impl PathElem { } } -impl ToStr for PathElem { - fn to_str(&self) -> ~str { - token::get_name(self.name()).get().to_str() +impl fmt::Show for PathElem { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let slot = token::get_name(self.name()); + write!(f.buf, "{}", slot.get()) } } diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index 93edb552bbe7c..27d1c6fa64915 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -341,7 +341,7 @@ pub struct Stability { } /// The available stability levels. -#[deriving(Eq,Ord,Clone,ToStr)] +#[deriving(Eq,Ord,Clone,Show)] pub enum StabilityLevel { Deprecated, Experimental, diff --git a/src/libsyntax/crateid.rs b/src/libsyntax/crateid.rs index 0831f319ce7b9..d04bedc65b5c5 100644 --- a/src/libsyntax/crateid.rs +++ b/src/libsyntax/crateid.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; + /// CrateIds identify crates and include the crate name and optionally a path /// and version. In the full form, they look like relative URLs. Example: /// `github.com/mozilla/rust#std:1.0` would be a package ID with a path of @@ -26,16 +28,17 @@ pub struct CrateId { version: Option<~str>, } -impl ToStr for CrateId { - fn to_str(&self) -> ~str { +impl fmt::Show for CrateId { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if_ok!(write!(f.buf, "{}", self.path)); let version = match self.version { None => "0.0", Some(ref version) => version.as_slice(), }; if self.path == self.name || self.path.ends_with(format!("/{}", self.name)) { - format!("{}\\#{}", self.path, version) + write!(f.buf, "\\#{}", version) } else { - format!("{}\\#{}:{}", self.path, self.name, version) + write!(f.buf, "\\#{}:{}", self.name, version) } } } diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index 8cf0f128d222d..be45008b92a10 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -12,8 +12,9 @@ use codemap::{Pos, Span}; use codemap; use std::cell::Cell; -use std::io; +use std::fmt; use std::io::stdio::StdWriter; +use std::io; use std::iter::range; use std::local_data; use term; @@ -162,12 +163,14 @@ pub enum Level { Note, } -impl ToStr for Level { - fn to_str(&self) -> ~str { +impl fmt::Show for Level { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + use std::fmt::Show; + match *self { - Fatal | Error => ~"error", - Warning => ~"warning", - Note => ~"note" + Fatal | Error => "error".fmt(f), + Warning => "warning".fmt(f), + Note => "note".fmt(f), } } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index c9bdd49f86c7f..a81fc4f6d69a1 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -40,14 +40,14 @@ use term::Terminal; use term::color::{Color, RED, YELLOW, GREEN, CYAN}; use std::cmp; -use std::io; -use std::io::{File, PortReader, ChanWriter}; +use std::f64; +use std::fmt; use std::io::stdio::StdWriter; +use std::io::{File, PortReader, ChanWriter}; +use std::io; +use std::os; use std::str; use std::task; -use std::to_str::ToStr; -use std::f64; -use std::os; // to be used by rustc to compile tests in libtest pub mod test { @@ -70,11 +70,11 @@ pub enum TestName { StaticTestName(&'static str), DynTestName(~str) } -impl ToStr for TestName { - fn to_str(&self) -> ~str { - match (*self).clone() { - StaticTestName(s) => s.to_str(), - DynTestName(s) => s.to_str() +impl fmt::Show for TestName { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + StaticTestName(s) => f.buf.write_str(s), + DynTestName(ref s) => f.buf.write_str(s.as_slice()), } } } diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index dec27719beb19..7a078e4b571b2 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -64,17 +64,15 @@ Examples of string representations: extern crate test; extern crate serialize; -use std::str; -use std::vec; -use std::num::FromStrRadix; +use std::cast::{transmute,transmute_copy}; +use std::cast::{transmute,transmute_copy}; use std::char::Char; -use std::container::Container; -use std::to_str::ToStr; -use std::rand; -use std::rand::Rng; use std::cmp::Eq; -use std::cast::{transmute,transmute_copy}; +use std::cmp::Eq; +use std::fmt; use std::hash::{Hash, sip}; +use std::num::FromStrRadix; +use std::rand::Rng; use serialize::{Encoder, Encodable, Decoder, Decodable}; @@ -142,22 +140,21 @@ pub enum ParseError { } /// Converts a ParseError to a string -impl ToStr for ParseError { - #[inline] - fn to_str(&self) -> ~str { +impl fmt::Show for ParseError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ErrorInvalidLength(found) => - format!("Invalid length; expecting 32, 36 or 45 chars, found {}", - found), + write!(f.buf, "Invalid length; expecting 32, 36 or 45 chars, \ + found {}", found), ErrorInvalidCharacter(found, pos) => - format!("Invalid character; found `{}` (0x{:02x}) at offset {}", - found, found as uint, pos), + write!(f.buf, "Invalid character; found `{}` (0x{:02x}) at \ + offset {}", found, found as uint, pos), ErrorInvalidGroups(found) => - format!("Malformed; wrong number of groups: expected 1 or 5, found {}", - found), + write!(f.buf, "Malformed; wrong number of groups: expected 1 \ + or 5, found {}", found), ErrorInvalidGroupLength(group, found, expecting) => - format!("Malformed; length of group {} was {}, expecting {}", - group, found, expecting), + write!(f.buf, "Malformed; length of group {} was {}, \ + expecting {}", group, found, expecting), } } } @@ -465,9 +462,9 @@ impl FromStr for Uuid { } /// Convert the UUID to a hexadecimal-based string representation -impl ToStr for Uuid { - fn to_str(&self) -> ~str { - self.to_simple_str() +impl fmt::Show for Uuid { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.to_simple_str()) } } diff --git a/src/test/auxiliary/cci_class_cast.rs b/src/test/auxiliary/cci_class_cast.rs index 8fac4a3f322af..79bb5aef764b3 100644 --- a/src/test/auxiliary/cci_class_cast.rs +++ b/src/test/auxiliary/cci_class_cast.rs @@ -9,14 +9,18 @@ // except according to those terms. pub mod kitty { + use std::fmt; + pub struct cat { priv meows : uint, how_hungry : int, name : ~str, } - impl ToStr for cat { - fn to_str(&self) -> ~str { self.name.clone() } + impl fmt::Show for cat { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.name) + } } impl cat { diff --git a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs index 537da53545783..085ed5db6df09 100644 --- a/src/test/compile-fail/use-after-move-implicity-coerced-object.rs +++ b/src/test/compile-fail/use-after-move-implicity-coerced-object.rs @@ -10,13 +10,15 @@ // ignore-tidy-linelength +use std::fmt; + struct Number { n: i64 } -impl ToStr for Number { - fn to_str(&self) -> ~str { - self.n.to_str() +impl fmt::Show for Number { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.n) } } diff --git a/src/test/run-pass/class-separate-impl.rs b/src/test/run-pass/class-separate-impl.rs index e813210f4f4e3..55fa783391ad9 100644 --- a/src/test/run-pass/class-separate-impl.rs +++ b/src/test/run-pass/class-separate-impl.rs @@ -9,6 +9,9 @@ // except according to those terms. // ignore-fast + +use std::fmt; + struct cat { meows : uint, @@ -50,9 +53,9 @@ fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { } } -impl ToStr for cat { - fn to_str(&self) -> ~str { - self.name.clone() +impl fmt::Show for cat { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.name) } } diff --git a/src/test/run-pass/deriving-global.rs b/src/test/run-pass/deriving-global.rs index ffca06dc628d0..cce3575178e2b 100644 --- a/src/test/run-pass/deriving-global.rs +++ b/src/test/run-pass/deriving-global.rs @@ -28,19 +28,19 @@ mod submod { // cause errors about unrecognised module `std` (or `extra`) #[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, DeepClone, - ToStr, Rand, + Show, Rand, Encodable, Decodable)] enum A { A1(uint), A2(int) } #[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, DeepClone, - ToStr, Rand, + Show, Rand, Encodable, Decodable)] struct B { x: uint, y: int } #[deriving(Eq, Ord, TotalEq, TotalOrd, Clone, DeepClone, - ToStr, Rand, + Show, Rand, Encodable, Decodable)] struct C(uint, int); diff --git a/src/test/run-pass/deriving-in-fn.rs b/src/test/run-pass/deriving-in-fn.rs index 7fb7d601b81b9..baa036ee039e0 100644 --- a/src/test/run-pass/deriving-in-fn.rs +++ b/src/test/run-pass/deriving-in-fn.rs @@ -9,11 +9,11 @@ // except according to those terms. pub fn main() { - #[deriving(ToStr)] + #[deriving(Show)] struct Foo { foo: int, } let f = Foo { foo: 10 }; - let _ = f.to_str(); + format!("{}", f); } diff --git a/src/test/run-pass/deriving-to-str.rs b/src/test/run-pass/deriving-show-2.rs similarity index 71% rename from src/test/run-pass/deriving-to-str.rs rename to src/test/run-pass/deriving-show-2.rs index d9f69bd4a4936..a2451c394002f 100644 --- a/src/test/run-pass/deriving-to-str.rs +++ b/src/test/run-pass/deriving-show-2.rs @@ -10,30 +10,34 @@ #[feature(struct_variant)]; -#[deriving(ToStr)] +use std::fmt; + +#[deriving(Show)] enum A {} -#[deriving(ToStr)] +#[deriving(Show)] enum B { B1, B2, B3 } -#[deriving(ToStr)] +#[deriving(Show)] enum C { C1(int), C2(B), C3(~str) } -#[deriving(ToStr)] +#[deriving(Show)] enum D { D1{ a: int } } -#[deriving(ToStr)] +#[deriving(Show)] struct E; -#[deriving(ToStr)] +#[deriving(Show)] struct F(int); -#[deriving(ToStr)] +#[deriving(Show)] struct G(int, int); -#[deriving(ToStr)] +#[deriving(Show)] struct H { a: int } -#[deriving(ToStr)] +#[deriving(Show)] struct I { a: int, b: int } -#[deriving(ToStr)] +#[deriving(Show)] struct J(Custom); struct Custom; -impl ToStr for Custom { - fn to_str(&self) -> ~str { ~"yay" } +impl fmt::Show for Custom { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "yay") + } } pub fn main() { @@ -41,11 +45,11 @@ pub fn main() { assert_eq!(B2.to_str(), ~"B2"); assert_eq!(C1(3).to_str(), ~"C1(3)"); assert_eq!(C2(B2).to_str(), ~"C2(B2)"); - assert_eq!(D1{ a: 2 }.to_str(), ~"D1{a: 2}"); + assert_eq!(D1{ a: 2 }.to_str(), ~"D1 { a: 2 }"); assert_eq!(E.to_str(), ~"E"); assert_eq!(F(3).to_str(), ~"F(3)"); assert_eq!(G(3, 4).to_str(), ~"G(3, 4)"); assert_eq!(G(3, 4).to_str(), ~"G(3, 4)"); - assert_eq!(I{ a: 2, b: 4 }.to_str(), ~"I{a: 2, b: 4}"); + assert_eq!(I{ a: 2, b: 4 }.to_str(), ~"I { a: 2, b: 4 }"); assert_eq!(J(Custom).to_str(), ~"J(yay)"); } diff --git a/src/test/run-pass/issue-2904.rs b/src/test/run-pass/issue-2904.rs index 2816609ef97dc..45f59fe9cd43d 100644 --- a/src/test/run-pass/issue-2904.rs +++ b/src/test/run-pass/issue-2904.rs @@ -17,7 +17,7 @@ extern crate extra; use std::io; -use std::to_str; +use std::fmt; enum square { bot, @@ -30,9 +30,9 @@ enum square { empty } -impl to_str::ToStr for square { - fn to_str(&self) -> ~str { - match *self { +impl fmt::Show for square { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", match *self { bot => { ~"R" } wall => { ~"#" } rock => { ~"*" } @@ -41,7 +41,7 @@ impl to_str::ToStr for square { open_lift => { ~"O" } earth => { ~"." } empty => { ~" " } - } + }) } } diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index 8e5dd762c630f..ae65c46ce71af 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -22,6 +22,7 @@ extern crate extra; // already linked in. Using WriterUtil allows us to use the write_line method. use std::str; use std::vec; +use std::fmt; // Represents a position on a canvas. struct Point { @@ -94,13 +95,13 @@ impl AsciiArt { // Allows AsciiArt to be converted to a string using the libcore ToStr trait. // Note that the %s fmt! specifier will not call this automatically. -impl ToStr for AsciiArt { - fn to_str(&self) -> ~str { +impl fmt::Show for AsciiArt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.map(|line| str::from_chars(*line)); // Concatenate the lines together using a new-line. - lines.connect("\n") + write!(f.buf, "{}", lines.connect("\n")) } } diff --git a/src/test/run-pass/new-impl-syntax.rs b/src/test/run-pass/new-impl-syntax.rs index 6def21a389a5b..30200d4cb1807 100644 --- a/src/test/run-pass/new-impl-syntax.rs +++ b/src/test/run-pass/new-impl-syntax.rs @@ -8,14 +8,16 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +use std::fmt; + struct Thingy { x: int, y: int } -impl ToStr for Thingy { - fn to_str(&self) -> ~str { - format!("\\{ x: {}, y: {} \\}", self.x, self.y) +impl fmt::Show for Thingy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "\\{ x: {}, y: {} \\}", self.x, self.y) } } @@ -23,9 +25,9 @@ struct PolymorphicThingy { x: T } -impl ToStr for PolymorphicThingy { - fn to_str(&self) -> ~str { - self.x.to_str() +impl fmt::Show for PolymorphicThingy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f.buf, "{}", self.x) } } From 8761f79485f11ef03eb6cb569ccb9f4c73e68f11 Mon Sep 17 00:00:00 2001 From: Alex Crichton Date: Wed, 19 Feb 2014 19:18:33 -0800 Subject: [PATCH 2/2] Remove deriving(ToStr) This has been superseded by deriving(Show). cc #9806 --- src/libcollections/btree.rs | 8 +- src/libcollections/lru_cache.rs | 14 +- src/libextra/url.rs | 18 +-- src/libsyntax/abi.rs | 2 +- src/libsyntax/crateid.rs | 2 +- src/libsyntax/ext/deriving/mod.rs | 2 - src/libsyntax/ext/deriving/to_str.rs | 132 ------------------ src/libuuid/lib.rs | 6 +- src/test/run-pass/super-fast-paren-parsing.rs | 2 + 9 files changed, 27 insertions(+), 159 deletions(-) delete mode 100644 src/libsyntax/ext/deriving/to_str.rs diff --git a/src/libcollections/btree.rs b/src/libcollections/btree.rs index cc6a5eda7594f..171203b00b806 100644 --- a/src/libcollections/btree.rs +++ b/src/libcollections/btree.rs @@ -405,8 +405,8 @@ impl fmt::Show for Leaf { ///Returns a string representation of a Leaf. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, s) in self.elts.iter().enumerate() { - if i != 0 { if_ok!(write!(f.buf, " // ")) } - if_ok!(write!(f.buf, "{}", *s)) + if i != 0 { try!(write!(f.buf, " // ")) } + try!(write!(f.buf, "{}", *s)) } Ok(()) } @@ -626,8 +626,8 @@ impl fmt::Show for Branch { ///Returns a string representation of a Branch. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, s) in self.elts.iter().enumerate() { - if i != 0 { if_ok!(write!(f.buf, " // ")) } - if_ok!(write!(f.buf, "{}", *s)) + if i != 0 { try!(write!(f.buf, " // ")) } + try!(write!(f.buf, "{}", *s)) } write!(f.buf, " // rightmost child: ({}) ", *self.rightmost_child) } diff --git a/src/libcollections/lru_cache.rs b/src/libcollections/lru_cache.rs index b5e44cda66587..68bc5f1b6c4ff 100644 --- a/src/libcollections/lru_cache.rs +++ b/src/libcollections/lru_cache.rs @@ -222,24 +222,24 @@ impl fmt::Show for LruCache { /// Return a string that lists the key-value pairs from most-recently /// used to least-recently used. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if_ok!(write!(f.buf, r"\{")); + try!(write!(f.buf, r"\{")); let mut cur = self.head; for i in range(0, self.len()) { - if i > 0 { if_ok!(write!(f.buf, ", ")) } + if i > 0 { try!(write!(f.buf, ", ")) } unsafe { cur = (*cur).next; match (*cur).key { // should never print nil - None => if_ok!(write!(f.buf, "nil")), - Some(ref k) => if_ok!(write!(f.buf, "{}", *k)), + None => try!(write!(f.buf, "nil")), + Some(ref k) => try!(write!(f.buf, "{}", *k)), } } - if_ok!(write!(f.buf, ": ")); + try!(write!(f.buf, ": ")); unsafe { match (*cur).value { // should never print nil - None => if_ok!(write!(f.buf, "nil")), - Some(ref value) => if_ok!(write!(f.buf, "{}", *value)), + None => try!(write!(f.buf, "nil")), + Some(ref value) => try!(write!(f.buf, "{}", *value)), } } } diff --git a/src/libextra/url.rs b/src/libextra/url.rs index 6e0cd72e3e7c1..0292a18817ccd 100644 --- a/src/libextra/url.rs +++ b/src/libextra/url.rs @@ -803,25 +803,25 @@ impl fmt::Show for Url { * result in just "http://somehost.com". */ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if_ok!(write!(f.buf, "{}:", self.scheme)); + try!(write!(f.buf, "{}:", self.scheme)); if !self.host.is_empty() { - if_ok!(write!(f.buf, "//")); + try!(write!(f.buf, "//")); match self.user { - Some(ref user) => if_ok!(write!(f.buf, "{}", *user)), + Some(ref user) => try!(write!(f.buf, "{}", *user)), None => {} } match self.port { - Some(ref port) => if_ok!(write!(f.buf, "{}:{}", self.host, + Some(ref port) => try!(write!(f.buf, "{}:{}", self.host, *port)), - None => if_ok!(write!(f.buf, "{}", self.host)), + None => try!(write!(f.buf, "{}", self.host)), } } - if_ok!(write!(f.buf, "{}", self.path)); + try!(write!(f.buf, "{}", self.path)); if !self.query.is_empty() { - if_ok!(write!(f.buf, "?{}", query_to_str(&self.query))); + try!(write!(f.buf, "?{}", query_to_str(&self.query))); } match self.fragment { @@ -834,9 +834,9 @@ impl fmt::Show for Url { impl fmt::Show for Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if_ok!(write!(f.buf, "{}", self.path)); + try!(write!(f.buf, "{}", self.path)); if !self.query.is_empty() { - if_ok!(write!(f.buf, "?{}", self.query)) + try!(write!(f.buf, "?{}", self.query)) } match self.fragment { diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index faf24da74ccfc..9349e5c8e98d6 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -281,7 +281,7 @@ impl fmt::Show for Abi { impl fmt::Show for AbiSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if_ok!(write!(f.buf, "\"")); + try!(write!(f.buf, "\"")); let mut first = true; self.each(|abi| { if first { first = false; } diff --git a/src/libsyntax/crateid.rs b/src/libsyntax/crateid.rs index d04bedc65b5c5..2417a6fa1bacf 100644 --- a/src/libsyntax/crateid.rs +++ b/src/libsyntax/crateid.rs @@ -30,7 +30,7 @@ pub struct CrateId { impl fmt::Show for CrateId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if_ok!(write!(f.buf, "{}", self.path)); + try!(write!(f.buf, "{}", self.path)); let version = match self.version { None => "0.0", Some(ref version) => version.as_slice(), diff --git a/src/libsyntax/ext/deriving/mod.rs b/src/libsyntax/ext/deriving/mod.rs index 95b9a45b9fc2d..9c823449d2141 100644 --- a/src/libsyntax/ext/deriving/mod.rs +++ b/src/libsyntax/ext/deriving/mod.rs @@ -27,7 +27,6 @@ pub mod encodable; pub mod decodable; pub mod hash; pub mod rand; -pub mod to_str; pub mod show; pub mod zero; pub mod default; @@ -85,7 +84,6 @@ pub fn expand_meta_deriving(cx: &mut ExtCtxt, "Rand" => expand!(rand::expand_deriving_rand), - "ToStr" => expand!(to_str::expand_deriving_to_str), "Show" => expand!(show::expand_deriving_show), "Zero" => expand!(zero::expand_deriving_zero), diff --git a/src/libsyntax/ext/deriving/to_str.rs b/src/libsyntax/ext/deriving/to_str.rs deleted file mode 100644 index 5cb81d9e762ae..0000000000000 --- a/src/libsyntax/ext/deriving/to_str.rs +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -use ast; -use ast::{MetaItem, Item, Expr}; -use codemap::Span; -use ext::base::ExtCtxt; -use ext::build::AstBuilder; -use ext::deriving::generic::*; -use parse::token::InternedString; -use parse::token; - -pub fn expand_deriving_to_str(cx: &mut ExtCtxt, - span: Span, - mitem: @MetaItem, - item: @Item, - push: |@Item|) { - let trait_def = TraitDef { - span: span, - attributes: ~[], - path: Path::new(~["std", "to_str", "ToStr"]), - additional_bounds: ~[], - generics: LifetimeBounds::empty(), - methods: ~[ - MethodDef { - name: "to_str", - generics: LifetimeBounds::empty(), - explicit_self: borrowed_explicit_self(), - args: ~[], - ret_ty: Ptr(~Literal(Path::new_local("str")), Send), - inline: false, - const_nonmatching: false, - combine_substructure: to_str_substructure - } - ] - }; - trait_def.expand(cx, mitem, item, push) -} - -// It used to be the case that this deriving implementation invoked -// std::repr::repr_to_str, but this isn't sufficient because it -// doesn't invoke the to_str() method on each field. Hence we mirror -// the logic of the repr_to_str() method, but with tweaks to call to_str() -// on sub-fields. -fn to_str_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) - -> @Expr { - let to_str = cx.ident_of("to_str"); - - let doit = |start: &str, - end: InternedString, - name: ast::Ident, - fields: &[FieldInfo]| { - if fields.len() == 0 { - cx.expr_str_uniq(span, token::get_ident(name)) - } else { - let buf = cx.ident_of("buf"); - let interned_str = token::get_ident(name); - let start = - token::intern_and_get_ident(interned_str.get() + start); - let init = cx.expr_str_uniq(span, start); - let mut stmts = ~[cx.stmt_let(span, true, buf, init)]; - let push_str = cx.ident_of("push_str"); - - { - let push = |s: @Expr| { - let ebuf = cx.expr_ident(span, buf); - let call = cx.expr_method_call(span, ebuf, push_str, ~[s]); - stmts.push(cx.stmt_expr(call)); - }; - - for (i, &FieldInfo {name, span, self_, .. }) in fields.iter().enumerate() { - if i > 0 { - push(cx.expr_str(span, InternedString::new(", "))); - } - match name { - None => {} - Some(id) => { - let interned_id = token::get_ident(id); - let name = interned_id.get() + ": "; - push(cx.expr_str(span, - token::intern_and_get_ident(name))); - } - } - push(cx.expr_method_call(span, self_, to_str, ~[])); - } - push(cx.expr_str(span, end)); - } - - cx.expr_block(cx.block(span, stmts, Some(cx.expr_ident(span, buf)))) - } - }; - - return match *substr.fields { - Struct(ref fields) => { - if fields.len() == 0 || fields[0].name.is_none() { - doit("(", - InternedString::new(")"), - substr.type_ident, - *fields) - } else { - doit("{", - InternedString::new("}"), - substr.type_ident, - *fields) - } - } - - EnumMatching(_, variant, ref fields) => { - match variant.node.kind { - ast::TupleVariantKind(..) => - doit("(", - InternedString::new(")"), - variant.node.name, - *fields), - ast::StructVariantKind(..) => - doit("{", - InternedString::new("}"), - variant.node.name, - *fields), - } - } - - _ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)") - }; -} diff --git a/src/libuuid/lib.rs b/src/libuuid/lib.rs index 7a078e4b571b2..7a3ed09a492d7 100644 --- a/src/libuuid/lib.rs +++ b/src/libuuid/lib.rs @@ -64,15 +64,15 @@ Examples of string representations: extern crate test; extern crate serialize; -use std::cast::{transmute,transmute_copy}; use std::cast::{transmute,transmute_copy}; use std::char::Char; -use std::cmp::Eq; -use std::cmp::Eq; use std::fmt; use std::hash::{Hash, sip}; use std::num::FromStrRadix; use std::rand::Rng; +use std::rand; +use std::str; +use std::vec; use serialize::{Encoder, Encodable, Decoder, Decodable}; diff --git a/src/test/run-pass/super-fast-paren-parsing.rs b/src/test/run-pass/super-fast-paren-parsing.rs index 759b066c8dbf5..70c7200bee9ae 100644 --- a/src/test/run-pass/super-fast-paren-parsing.rs +++ b/src/test/run-pass/super-fast-paren-parsing.rs @@ -8,6 +8,8 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. +// ignore-pretty + static a: int = ((((((((((((((((((((((((((((((((((((((((((((((((((( (((((((((((((((((((((((((((((((((((((((((((((((((((