Skip to content

Commit

Permalink
core: split into fmt::Show and fmt::String
Browse files Browse the repository at this point in the history
fmt::Show is for debugging, and can and should be implemented for
all public types. This trait is used with `{:?}` syntax. There still
exists #[derive(Show)].

fmt::String is for types that faithfully be represented as a String.
Because of this, there is no way to derive fmt::String, all
implementations must be purposeful. It is used by the default format
syntax, `{}`.

This will break most instances of `{}`, since that now requires the type
to impl fmt::String. In most cases, replacing `{}` with `{:?}` is the
correct fix. Types that were being printed specifically for users should
receive a fmt::String implementation to fix this.

Part of #20013

[breaking-change]
  • Loading branch information
seanmonstar committed Jan 6, 2015
1 parent 8efd990 commit 44440e5
Show file tree
Hide file tree
Showing 252 changed files with 2,005 additions and 1,375 deletions.
13 changes: 9 additions & 4 deletions src/compiletest/common.rs
Expand Up @@ -43,9 +43,9 @@ impl FromStr for Mode {
}
}

impl fmt::Show for Mode {
impl fmt::String for Mode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = match *self {
fmt::String::fmt(match *self {
CompileFail => "compile-fail",
RunFail => "run-fail",
RunPass => "run-pass",
Expand All @@ -54,8 +54,13 @@ impl fmt::Show for Mode {
DebugInfoGdb => "debuginfo-gdb",
DebugInfoLldb => "debuginfo-lldb",
Codegen => "codegen",
};
msg.fmt(f)
}, f)
}
}

impl fmt::Show for Mode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(self, f)
}
}

Expand Down
26 changes: 13 additions & 13 deletions src/compiletest/compiletest.rs
Expand Up @@ -108,7 +108,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
let matches =
&match getopts::getopts(args_.as_slice(), groups.as_slice()) {
Ok(m) => m,
Err(f) => panic!("{}", f)
Err(f) => panic!("{:?}", f)
};

if matches.opt_present("h") || matches.opt_present("help") {
Expand All @@ -127,7 +127,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
match regex::Regex::new(s) {
Ok(re) => Some(re),
Err(e) => {
println!("failed to parse filter /{}/: {}", s, e);
println!("failed to parse filter /{}/: {:?}", s, e);
panic!()
}
}
Expand Down Expand Up @@ -186,11 +186,11 @@ pub fn parse_config(args: Vec<String> ) -> Config {
pub fn log_config(config: &Config) {
let c = config;
logv(c, format!("configuration:"));
logv(c, format!("compile_lib_path: {}", config.compile_lib_path));
logv(c, format!("run_lib_path: {}", config.run_lib_path));
logv(c, format!("rustc_path: {}", config.rustc_path.display()));
logv(c, format!("src_base: {}", config.src_base.display()));
logv(c, format!("build_base: {}", config.build_base.display()));
logv(c, format!("compile_lib_path: {:?}", config.compile_lib_path));
logv(c, format!("run_lib_path: {:?}", config.run_lib_path));
logv(c, format!("rustc_path: {:?}", config.rustc_path.display()));
logv(c, format!("src_base: {:?}", config.src_base.display()));
logv(c, format!("build_base: {:?}", config.build_base.display()));
logv(c, format!("stage_id: {}", config.stage_id));
logv(c, format!("mode: {}", config.mode));
logv(c, format!("run_ignored: {}", config.run_ignored));
Expand All @@ -206,10 +206,10 @@ pub fn log_config(config: &Config) {
logv(c, format!("jit: {}", config.jit));
logv(c, format!("target: {}", config.target));
logv(c, format!("host: {}", config.host));
logv(c, format!("android-cross-path: {}",
logv(c, format!("android-cross-path: {:?}",
config.android_cross_path.display()));
logv(c, format!("adb_path: {}", config.adb_path));
logv(c, format!("adb_test_dir: {}", config.adb_test_dir));
logv(c, format!("adb_path: {:?}", config.adb_path));
logv(c, format!("adb_test_dir: {:?}", config.adb_test_dir));
logv(c, format!("adb_device_status: {}",
config.adb_device_status));
match config.test_shard {
Expand Down Expand Up @@ -271,7 +271,7 @@ pub fn run_tests(config: &Config) {
Ok(true) => {}
Ok(false) => panic!("Some tests failed"),
Err(e) => {
println!("I/O failure during tests: {}", e);
println!("I/O failure during tests: {:?}", e);
}
}
}
Expand Down Expand Up @@ -299,13 +299,13 @@ pub fn test_opts(config: &Config) -> test::TestOpts {
}

pub fn make_tests(config: &Config) -> Vec<test::TestDescAndFn> {
debug!("making tests from {}",
debug!("making tests from {:?}",
config.src_base.display());
let mut tests = Vec::new();
let dirs = fs::readdir(&config.src_base).unwrap();
for file in dirs.iter() {
let file = file.clone();
debug!("inspecting file {}", file.display());
debug!("inspecting file {:?}", file.display());
if is_test(config, &file) {
let t = make_test(config, &file, || {
match config.mode {
Expand Down
2 changes: 1 addition & 1 deletion src/compiletest/errors.rs
Expand Up @@ -84,7 +84,7 @@ fn parse_expected(last_nonfollow_error: Option<uint>,
(which, line)
};

debug!("line={} which={} kind={} msg={}", line_num, which, kind, msg);
debug!("line={} which={:?} kind={:?} msg={:?}", line_num, which, kind, msg);
Some((which, ExpectedError { line: line,
kind: kind,
msg: msg, }))
Expand Down
22 changes: 11 additions & 11 deletions src/compiletest/runtest.rs
Expand Up @@ -61,7 +61,7 @@ pub fn run_metrics(config: Config, testfile: String, mm: &mut MetricMap) {
print!("\n\n");
}
let testfile = Path::new(testfile);
debug!("running {}", testfile.display());
debug!("running {:?}", testfile.display());
let props = header::load_props(&testfile);
debug!("loaded props");
match config.mode {
Expand Down Expand Up @@ -141,7 +141,7 @@ fn check_correct_failure_status(proc_res: &ProcRes) {
static RUST_ERR: int = 101;
if !proc_res.status.matches_exit_status(RUST_ERR) {
fatal_proc_rec(
format!("failure produced the wrong error: {}",
format!("failure produced the wrong error: {:?}",
proc_res.status).as_slice(),
proc_res);
}
Expand Down Expand Up @@ -410,7 +410,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
],
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
.expect(format!("failed to exec `{}`", config.adb_path).as_slice());
.expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());

procsrv::run("",
config.adb_path.as_slice(),
Expand All @@ -422,7 +422,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
],
vec!(("".to_string(), "".to_string())),
Some("".to_string()))
.expect(format!("failed to exec `{}`", config.adb_path).as_slice());
.expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());

let adb_arg = format!("export LD_LIBRARY_PATH={}; \
gdbserver :5039 {}/{}",
Expand All @@ -443,7 +443,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
vec!(("".to_string(),
"".to_string())),
Some("".to_string()))
.expect(format!("failed to exec `{}`", config.adb_path).as_slice());
.expect(format!("failed to exec `{:?}`", config.adb_path).as_slice());
loop {
//waiting 1 second for gdbserver start
timer::sleep(Duration::milliseconds(1000));
Expand Down Expand Up @@ -481,7 +481,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
debugger_opts.as_slice(),
vec!(("".to_string(), "".to_string())),
None)
.expect(format!("failed to exec `{}`", gdb_path).as_slice());
.expect(format!("failed to exec `{:?}`", gdb_path).as_slice());
let cmdline = {
let cmdline = make_cmdline("",
"arm-linux-androideabi-gdb",
Expand Down Expand Up @@ -548,7 +548,7 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {

// Add line breakpoints
for line in breakpoint_lines.iter() {
script_str.push_str(format!("break '{}':{}\n",
script_str.push_str(format!("break '{:?}':{}\n",
testfile.filename_display(),
*line)[]);
}
Expand Down Expand Up @@ -889,7 +889,7 @@ fn check_error_patterns(props: &TestProps,
output_to_check: &str,
proc_res: &ProcRes) {
if props.error_patterns.is_empty() {
fatal(format!("no error pattern specified in {}",
fatal(format!("no error pattern specified in {:?}",
testfile.display()).as_slice());
}
let mut next_err_idx = 0u;
Expand Down Expand Up @@ -955,7 +955,7 @@ fn check_expected_errors(expected_errors: Vec<errors::ExpectedError> ,
}

let prefixes = expected_errors.iter().map(|ee| {
format!("{}:{}:", testfile.display(), ee.line)
format!("{:?}:{}:", testfile.display(), ee.line)
}).collect::<Vec<String> >();

#[cfg(windows)]
Expand Down Expand Up @@ -1191,7 +1191,7 @@ fn compose_and_run_compiler(
None);
if !auxres.status.success() {
fatal_proc_rec(
format!("auxiliary build of {} failed to compile: ",
format!("auxiliary build of {:?} failed to compile: ",
abs_ab.display()).as_slice(),
&auxres);
}
Expand Down Expand Up @@ -1601,7 +1601,7 @@ fn _arm_push_aux_shared_library(config: &Config, testfile: &Path) {
.expect(format!("failed to exec `{}`", config.adb_path).as_slice());

if config.verbose {
println!("push ({}) {} {} {}",
println!("push ({}) {:?} {} {}",
config.target, file.display(),
copy_result.out, copy_result.err);
}
Expand Down
4 changes: 2 additions & 2 deletions src/liballoc/arc.rs
Expand Up @@ -581,7 +581,7 @@ impl<T: Eq> Eq for Arc<T> {}

impl<T: fmt::Show> fmt::Show for Arc<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
write!(f, "Arc({:?})", (**self))
}
}

Expand Down Expand Up @@ -794,7 +794,7 @@ mod tests {
#[test]
fn show_arc() {
let a = Arc::new(5u32);
assert!(format!("{}", a) == "5")
assert!(format!("{:?}", a) == "Arc(5u32)")
}

// Make sure deriving works with Arc<T>
Expand Down
8 changes: 7 additions & 1 deletion src/liballoc/boxed.rs
Expand Up @@ -145,7 +145,13 @@ impl BoxAny for Box<Any> {

impl<T: ?Sized + fmt::Show> fmt::Show for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
write!(f, "Box({:?})", &**self)
}
}

impl<Sized? T: fmt::String> fmt::String for Box<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::String::fmt(&**self, f)
}
}

Expand Down
8 changes: 7 additions & 1 deletion src/liballoc/rc.rs
Expand Up @@ -607,7 +607,7 @@ impl<S: hash::Writer, T: Hash<S>> Hash<S> for Rc<T> {
#[experimental = "Show is experimental."]
impl<T: fmt::Show> fmt::Show for Rc<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
write!(f, "Rc({:?})", **self)
}
}

Expand Down Expand Up @@ -962,4 +962,10 @@ mod tests {
assert!(cow1_weak.upgrade().is_none());
}

#[test]
fn test_show() {
let foo = Rc::new(75u);
assert!(format!("{:?}", foo) == "Rc(75u)")
}

}
4 changes: 2 additions & 2 deletions src/libcollections/bit.rs
Expand Up @@ -1729,13 +1729,13 @@ impl BitvSet {

impl fmt::Show for BitvSet {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{{"));
try!(write!(fmt, "BitvSet {{"));
let mut first = true;
for n in self.iter() {
if !first {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", n));
try!(write!(fmt, "{:?}", n));
first = false;
}
write!(fmt, "}}")
Expand Down
4 changes: 2 additions & 2 deletions src/libcollections/btree/map.rs
Expand Up @@ -866,11 +866,11 @@ impl<K: Ord, V: Ord> Ord for BTreeMap<K, V> {
#[stable]
impl<K: Show, V: Show> Show for BTreeMap<K, V> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{{"));
try!(write!(f, "BTreeMap {{"));

for (i, (k, v)) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}: {}", *k, *v));
try!(write!(f, "{:?}: {:?}", *k, *v));
}

write!(f, "}}")
Expand Down
2 changes: 1 addition & 1 deletion src/libcollections/btree/node.rs
Expand Up @@ -493,7 +493,7 @@ impl<K: Clone, V: Clone> Clone for Node<K, V> {
/// // Now the handle still points at index 75, but on the small node, which has no index 75.
/// flag.set(true);
///
/// println!("Uninitialized memory: {}", handle.into_kv());
/// println!("Uninitialized memory: {:?}", handle.into_kv());
/// }
/// ```
#[derive(Copy)]
Expand Down
4 changes: 2 additions & 2 deletions src/libcollections/btree/set.rs
Expand Up @@ -556,11 +556,11 @@ impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet<T>> for &'a BTreeSet<T> {
#[stable]
impl<T: Show> Show for BTreeSet<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{{"));
try!(write!(f, "BTreeSet {{"));

for (i, x) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", *x));
try!(write!(f, "{:?}", *x));
}

write!(f, "}}")
Expand Down
4 changes: 2 additions & 2 deletions src/libcollections/dlist.rs
Expand Up @@ -663,11 +663,11 @@ impl<A: Clone> Clone for DList<A> {
#[stable]
impl<A: fmt::Show> fmt::Show for DList<A> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "["));
try!(write!(f, "DList ["));

for (i, e) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", *e));
try!(write!(f, "{:?}", *e));
}

write!(f, "]")
Expand Down
10 changes: 5 additions & 5 deletions src/libcollections/enum_set.rs
Expand Up @@ -33,13 +33,13 @@ impl<E> Copy for EnumSet<E> {}

impl<E:CLike+fmt::Show> fmt::Show for EnumSet<E> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
try!(write!(fmt, "{{"));
try!(write!(fmt, "EnumSet {{"));
let mut first = true;
for e in self.iter() {
if !first {
try!(write!(fmt, ", "));
}
try!(write!(fmt, "{}", e));
try!(write!(fmt, "{:?}", e));
first = false;
}
write!(fmt, "}}")
Expand Down Expand Up @@ -287,11 +287,11 @@ mod test {
#[test]
fn test_show() {
let mut e = EnumSet::new();
assert_eq!("{}", e.to_string());
assert!(format!("{:?}", e) == "EnumSet {}");
e.insert(A);
assert_eq!("{A}", e.to_string());
assert!(format!("{:?}", e) == "EnumSet {A}");
e.insert(C);
assert_eq!("{A, C}", e.to_string());
assert!(format!("{:?}", e) == "EnumSet {A, C}");
}

#[test]
Expand Down
4 changes: 2 additions & 2 deletions src/libcollections/ring_buf.rs
Expand Up @@ -1613,11 +1613,11 @@ impl<A> Extend<A> for RingBuf<A> {
#[stable]
impl<T: fmt::Show> fmt::Show for RingBuf<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "["));
try!(write!(f, "RingBuf ["));

for (i, e) in self.iter().enumerate() {
if i != 0 { try!(write!(f, ", ")); }
try!(write!(f, "{}", *e));
try!(write!(f, "{:?}", *e));
}

write!(f, "]")
Expand Down

0 comments on commit 44440e5

Please sign in to comment.