diff --git a/src/compiletest/common.rs b/src/compiletest/common.rs index 202a87fcdc9..c29f74d7418 100644 --- a/src/compiletest/common.rs +++ b/src/compiletest/common.rs @@ -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", @@ -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) } } diff --git a/src/compiletest/compiletest.rs b/src/compiletest/compiletest.rs index 0ce31a335d8..23674efe968 100644 --- a/src/compiletest/compiletest.rs +++ b/src/compiletest/compiletest.rs @@ -108,7 +108,7 @@ pub fn parse_config(args: Vec ) -> 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") { @@ -127,7 +127,7 @@ pub fn parse_config(args: Vec ) -> 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!() } } @@ -186,11 +186,11 @@ pub fn parse_config(args: Vec ) -> 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)); @@ -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 { @@ -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); } } } @@ -299,13 +299,13 @@ pub fn test_opts(config: &Config) -> test::TestOpts { } pub fn make_tests(config: &Config) -> Vec { - 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 { diff --git a/src/compiletest/errors.rs b/src/compiletest/errors.rs index f330bb3143e..dcfac688c7f 100644 --- a/src/compiletest/errors.rs +++ b/src/compiletest/errors.rs @@ -84,7 +84,7 @@ fn parse_expected(last_nonfollow_error: Option, (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, })) diff --git a/src/compiletest/runtest.rs b/src/compiletest/runtest.rs index afcdcf6439c..8a27903259f 100644 --- a/src/compiletest/runtest.rs +++ b/src/compiletest/runtest.rs @@ -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 { @@ -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); } @@ -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(), @@ -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 {}/{}", @@ -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)); @@ -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", @@ -547,7 +547,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)[]); } @@ -888,7 +888,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; @@ -954,7 +954,7 @@ fn check_expected_errors(expected_errors: Vec , } let prefixes = expected_errors.iter().map(|ee| { - format!("{}:{}:", testfile.display(), ee.line) + format!("{:?}:{}:", testfile.display(), ee.line) }).collect:: >(); #[cfg(windows)] @@ -1190,7 +1190,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); } @@ -1600,7 +1600,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); } diff --git a/src/liballoc/arc.rs b/src/liballoc/arc.rs index 25f80ad11bd..7789620a64f 100644 --- a/src/liballoc/arc.rs +++ b/src/liballoc/arc.rs @@ -581,7 +581,7 @@ impl Eq for Arc {} impl fmt::Show for Arc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (**self).fmt(f) + write!(f, "Arc({:?})", (**self)) } } @@ -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 diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs index 6df8bb5f7aa..37827e6311a 100644 --- a/src/liballoc/boxed.rs +++ b/src/liballoc/boxed.rs @@ -145,7 +145,13 @@ impl BoxAny for Box { impl fmt::Show for Box { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (**self).fmt(f) + write!(f, "Box({:?})", &**self) + } +} + +impl fmt::String for Box { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(&**self, f) } } diff --git a/src/liballoc/rc.rs b/src/liballoc/rc.rs index 175bba4e71d..91566e89a16 100644 --- a/src/liballoc/rc.rs +++ b/src/liballoc/rc.rs @@ -607,7 +607,7 @@ impl> Hash for Rc { #[experimental = "Show is experimental."] impl fmt::Show for Rc { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (**self).fmt(f) + write!(f, "Rc({:?})", **self) } } @@ -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)") + } + } diff --git a/src/libcollections/bit.rs b/src/libcollections/bit.rs index 3d1779445e1..93215c3435e 100644 --- a/src/libcollections/bit.rs +++ b/src/libcollections/bit.rs @@ -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, "}}") diff --git a/src/libcollections/btree/map.rs b/src/libcollections/btree/map.rs index b85ea65f5ce..0dd345110d7 100644 --- a/src/libcollections/btree/map.rs +++ b/src/libcollections/btree/map.rs @@ -866,11 +866,11 @@ impl Ord for BTreeMap { #[stable] impl Show for BTreeMap { 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, "}}") diff --git a/src/libcollections/btree/node.rs b/src/libcollections/btree/node.rs index 0a93bbf89c9..a764264fd1e 100644 --- a/src/libcollections/btree/node.rs +++ b/src/libcollections/btree/node.rs @@ -493,7 +493,7 @@ impl Clone for Node { /// // 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)] diff --git a/src/libcollections/btree/set.rs b/src/libcollections/btree/set.rs index 98f16332170..44140154ae4 100644 --- a/src/libcollections/btree/set.rs +++ b/src/libcollections/btree/set.rs @@ -556,11 +556,11 @@ impl<'a, 'b, T: Ord + Clone> BitOr<&'b BTreeSet> for &'a BTreeSet { #[stable] impl Show for BTreeSet { 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, "}}") diff --git a/src/libcollections/dlist.rs b/src/libcollections/dlist.rs index 5e08f90ce1c..4ebd3dc63b6 100644 --- a/src/libcollections/dlist.rs +++ b/src/libcollections/dlist.rs @@ -663,11 +663,11 @@ impl Clone for DList { #[stable] impl fmt::Show for DList { 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, "]") diff --git a/src/libcollections/enum_set.rs b/src/libcollections/enum_set.rs index 4b94348e87a..1b852d0ba68 100644 --- a/src/libcollections/enum_set.rs +++ b/src/libcollections/enum_set.rs @@ -33,13 +33,13 @@ impl Copy for EnumSet {} impl fmt::Show for EnumSet { 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, "}}") @@ -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] diff --git a/src/libcollections/ring_buf.rs b/src/libcollections/ring_buf.rs index 98e9d6c16b8..9374d42b2c7 100644 --- a/src/libcollections/ring_buf.rs +++ b/src/libcollections/ring_buf.rs @@ -1613,11 +1613,11 @@ impl Extend for RingBuf { #[stable] impl fmt::Show for RingBuf { 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, "]") diff --git a/src/libcollections/slice.rs b/src/libcollections/slice.rs index e57574fdbce..95b0a16d4c5 100644 --- a/src/libcollections/slice.rs +++ b/src/libcollections/slice.rs @@ -2471,25 +2471,25 @@ mod tests { macro_rules! test_show_vec { ($x:expr, $x_str:expr) => ({ let (x, x_str) = ($x, $x_str); - assert_eq!(format!("{}", x), x_str); - assert_eq!(format!("{}", x.as_slice()), x_str); + assert_eq!(format!("{:?}", x), x_str); + assert_eq!(format!("{:?}", x.as_slice()), x_str); }) } let empty: Vec = vec![]; test_show_vec!(empty, "[]"); - test_show_vec!(vec![1i], "[1]"); - test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]"); + test_show_vec!(vec![1i], "[1i]"); + test_show_vec!(vec![1i, 2, 3], "[1i, 2i, 3i]"); test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]], - "[[], [1], [1, 1]]"); + "[[], [1u], [1u, 1u]]"); let empty_mut: &mut [int] = &mut[]; test_show_vec!(empty_mut, "[]"); let v: &mut[int] = &mut[1]; - test_show_vec!(v, "[1]"); + test_show_vec!(v, "[1i]"); let v: &mut[int] = &mut[1, 2, 3]; - test_show_vec!(v, "[1, 2, 3]"); + test_show_vec!(v, "[1i, 2i, 3i]"); let v: &mut [&mut[uint]] = &mut[&mut[], &mut[1u], &mut[1u, 1u]]; - test_show_vec!(v, "[[], [1], [1, 1]]"); + test_show_vec!(v, "[[], [1u], [1u, 1u]]"); } #[test] diff --git a/src/libcollections/string.rs b/src/libcollections/string.rs index 20bc08416dc..938ee73455f 100644 --- a/src/libcollections/string.rs +++ b/src/libcollections/string.rs @@ -677,13 +677,25 @@ impl FromUtf8Error { impl fmt::Show for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.error.fmt(f) + fmt::String::fmt(self, f) + } +} + +impl fmt::String for FromUtf8Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(&self.error, f) } } impl fmt::Show for FromUtf16Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - "invalid utf-16: lone surrogate found".fmt(f) + fmt::String::fmt(self, f) + } +} + +impl fmt::String for FromUtf16Error { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt("invalid utf-16: lone surrogate found", f) } } @@ -793,10 +805,17 @@ impl Default for String { } } -#[experimental = "waiting on Show stabilization"] +#[experimental = "waiting on fmt stabilization"] +impl fmt::String for String { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(&**self, f) + } +} + +#[experimental = "waiting on fmt stabilization"] impl fmt::Show for String { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - (**self).fmt(f) + fmt::Show::fmt(&**self, f) } } @@ -902,6 +921,8 @@ pub trait ToString { fn to_string(&self) -> String; } +#[cfg(stage0)] +//NOTE(stage0): remove after stage0 snapshot impl ToString for T { fn to_string(&self) -> String { use core::fmt::Writer; @@ -912,6 +933,17 @@ impl ToString for T { } } +#[cfg(not(stage0))] +impl ToString for T { + fn to_string(&self) -> String { + use core::fmt::Writer; + let mut buf = String::new(); + let _ = buf.write_fmt(format_args!("{}", self)); + buf.shrink_to_fit(); + buf + } +} + impl IntoCow<'static, String, str> for String { fn into_cow(self) -> CowString<'static> { Cow::Owned(self) diff --git a/src/libcollections/vec.rs b/src/libcollections/vec.rs index 1cfbbdf6cb8..a3f7f6c9157 100644 --- a/src/libcollections/vec.rs +++ b/src/libcollections/vec.rs @@ -1450,7 +1450,14 @@ impl Default for Vec { #[experimental = "waiting on Show stability"] impl fmt::Show for Vec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.as_slice().fmt(f) + fmt::Show::fmt(self.as_slice(), f) + } +} + +#[experimental = "waiting on Show stability"] +impl fmt::String for Vec { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self.as_slice(), f) } } diff --git a/src/libcollections/vec_map.rs b/src/libcollections/vec_map.rs index 68469059fea..4399a6fec22 100644 --- a/src/libcollections/vec_map.rs +++ b/src/libcollections/vec_map.rs @@ -489,11 +489,11 @@ impl Ord for VecMap { #[stable] impl fmt::Show for VecMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{{")); + try!(write!(f, "VecMap {{")); 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, "}}") @@ -929,9 +929,9 @@ mod test_map { map.insert(1, 2i); map.insert(3, 4i); - let map_str = map.to_string(); - assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); - assert_eq!(format!("{}", empty), "{}"); + let map_str = format!("{:?}", map); + assert!(map_str == "VecMap {1: 2i, 3: 4i}" || map_str == "{3: 4i, 1: 2i}"); + assert_eq!(format!("{:?}", empty), "VecMap {}"); } #[test] 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::() { //! 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 ToOwned for T where T: Clone { /// } /// } /// ``` +//#[deriving(Show)] NOTE(stage0): uncomment after snapshot pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned { /// Borrowed data. Borrowed(&'a B), @@ -141,6 +142,16 @@ pub enum Cow<'a, T, B: ?Sized + 'a> where B: ToOwned { 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: 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 { 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: fmt::Show { +impl<'a, T, B: ?Sized> fmt::String for Cow<'a, T, B> where + B: fmt::String + ToOwned, + 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 PartialEq for RefCell { } } -#[unstable] -impl fmt::Show for RefCell { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match self.try_borrow() { - Some(val) => write!(f, "{}", val), - None => write!(f, "") - } - } -} - struct BorrowRef<'b> { _borrow: &'b Cell, } 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) } -} - -impl Show for bool { - fn fmt(&self, f: &mut Formatter) -> Result { - Show::fmt(if *self { "true" } else { "false" }, 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 { + 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,7 +723,15 @@ 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; @@ -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 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 Show for [T] { } } +impl 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 Show for Cell { fn fmt(&self, f: &mut Formatter) -> Result { - write!(f, "Cell {{ value: {} }}", self.get()) + write!(f, "Cell {{ value: {:?} }}", self.get()) + } +} + +#[unstable] +impl Show for RefCell { + fn fmt(&self, f: &mut Formatter) -> Result { + match self.try_borrow() { + Some(val) => write!(f, "RefCell {{ value: {:?} }}", val), + None => write!(f, "RefCell {{ }}") + } } } 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,8 +154,22 @@ pub fn radix(x: T, base: u8) -> RadixFmt { } 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 Result { 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 Result { 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. diff --git a/src/libcoretest/any.rs b/src/libcoretest/any.rs index 9b0471bfad9..c0be3a28794 100644 --- a/src/libcoretest/any.rs +++ b/src/libcoretest/any.rs @@ -56,12 +56,12 @@ fn any_downcast_ref() { match a.downcast_ref::() { Some(&5) => {} - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } match a.downcast_ref::() { None => {} - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } } @@ -79,7 +79,7 @@ fn any_downcast_mut() { assert_eq!(*x, 5u); *x = 612; } - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } match b_r.downcast_mut::() { @@ -87,27 +87,27 @@ fn any_downcast_mut() { assert_eq!(*x, 7u); *x = 413; } - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } match a_r.downcast_mut::() { None => (), - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } match b_r.downcast_mut::() { None => (), - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } match a_r.downcast_mut::() { Some(&612) => {} - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } match b_r.downcast_mut::() { Some(&413) => {} - x => panic!("Unexpected value {}", x) + x => panic!("Unexpected value {:?}", x) } } diff --git a/src/libcoretest/cell.rs b/src/libcoretest/cell.rs index 54da6264bb0..86f34ecd15e 100644 --- a/src/libcoretest/cell.rs +++ b/src/libcoretest/cell.rs @@ -29,10 +29,10 @@ fn smoketest_cell() { #[test] fn cell_has_sensible_show() { let x = Cell::new("foo bar"); - assert!(format!("{}", x).contains(x.get())); + assert!(format!("{:?}", x).contains(x.get())); x.set("baz qux"); - assert!(format!("{}", x).contains(x.get())); + assert!(format!("{:?}", x).contains(x.get())); } #[test] @@ -40,11 +40,11 @@ fn ref_and_refmut_have_sensible_show() { let refcell = RefCell::new("foo"); let refcell_refmut = refcell.borrow_mut(); - assert!(format!("{}", refcell_refmut).contains("foo")); + assert!(format!("{:?}", refcell_refmut).contains("foo")); drop(refcell_refmut); let refcell_ref = refcell.borrow(); - assert!(format!("{}", refcell_ref).contains("foo")); + assert!(format!("{:?}", refcell_ref).contains("foo")); drop(refcell_ref); } diff --git a/src/libcoretest/fmt/num.rs b/src/libcoretest/fmt/num.rs index 1e28933becd..c259e4cbb68 100644 --- a/src/libcoretest/fmt/num.rs +++ b/src/libcoretest/fmt/num.rs @@ -26,6 +26,11 @@ fn test_format_int() { assert!(format!("{}", -1i16) == "-1"); assert!(format!("{}", -1i32) == "-1"); assert!(format!("{}", -1i64) == "-1"); + assert!(format!("{:?}", 1i) == "1i"); + assert!(format!("{:?}", 1i8) == "1i8"); + assert!(format!("{:?}", 1i16) == "1i16"); + assert!(format!("{:?}", 1i32) == "1i32"); + assert!(format!("{:?}", 1i64) == "1i64"); assert!(format!("{:b}", 1i) == "1"); assert!(format!("{:b}", 1i8) == "1"); assert!(format!("{:b}", 1i16) == "1"); @@ -52,6 +57,11 @@ fn test_format_int() { assert!(format!("{}", 1u16) == "1"); assert!(format!("{}", 1u32) == "1"); assert!(format!("{}", 1u64) == "1"); + assert!(format!("{:?}", 1u) == "1u"); + assert!(format!("{:?}", 1u8) == "1u8"); + assert!(format!("{:?}", 1u16) == "1u16"); + assert!(format!("{:?}", 1u32) == "1u32"); + assert!(format!("{:?}", 1u64) == "1u64"); assert!(format!("{:b}", 1u) == "1"); assert!(format!("{:b}", 1u8) == "1"); assert!(format!("{:b}", 1u16) == "1"); @@ -84,12 +94,14 @@ fn test_format_int() { #[test] fn test_format_int_zero() { assert!(format!("{}", 0i) == "0"); + assert!(format!("{:?}", 0i) == "0i"); assert!(format!("{:b}", 0i) == "0"); assert!(format!("{:o}", 0i) == "0"); assert!(format!("{:x}", 0i) == "0"); assert!(format!("{:X}", 0i) == "0"); assert!(format!("{}", 0u) == "0"); + assert!(format!("{:?}", 0u) == "0u"); assert!(format!("{:b}", 0u) == "0"); assert!(format!("{:o}", 0u) == "0"); assert!(format!("{:x}", 0u) == "0"); @@ -183,6 +195,12 @@ mod uint { b.iter(|| { format!("{:x}", rng.gen::()); }) } + #[bench] + fn format_show(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:?}", rng.gen::()); }) + } + #[bench] fn format_base_36(b: &mut Bencher) { let mut rng = weak_rng(); @@ -219,6 +237,12 @@ mod int { b.iter(|| { format!("{:x}", rng.gen::()); }) } + #[bench] + fn format_show(b: &mut Bencher) { + let mut rng = weak_rng(); + b.iter(|| { format!("{:?}", rng.gen::()); }) + } + #[bench] fn format_base_36(b: &mut Bencher) { let mut rng = weak_rng(); diff --git a/src/libcoretest/result.rs b/src/libcoretest/result.rs index 52ea14dd05d..b9403598ec2 100644 --- a/src/libcoretest/result.rs +++ b/src/libcoretest/result.rs @@ -95,10 +95,10 @@ pub fn test_fmt_default() { let ok: Result = Ok(100); let err: Result = Err("Err"); - let s = format!("{}", ok); - assert_eq!(s, "Ok(100)"); - let s = format!("{}", err); - assert_eq!(s, "Err(Err)"); + let s = format!("{:?}", ok); + assert_eq!(s, "Ok(100i)"); + let s = format!("{:?}", err); + assert_eq!(s, "Err(\"Err\")"); } #[test] diff --git a/src/libcoretest/tuple.rs b/src/libcoretest/tuple.rs index c3bc38a6614..62eb9f4ad34 100644 --- a/src/libcoretest/tuple.rs +++ b/src/libcoretest/tuple.rs @@ -59,10 +59,10 @@ fn test_tuple_cmp() { #[test] fn test_show() { - let s = format!("{}", (1i,)); - assert_eq!(s, "(1,)"); - let s = format!("{}", (1i, true)); - assert_eq!(s, "(1, true)"); - let s = format!("{}", (1i, "hi", true)); - assert_eq!(s, "(1, hi, true)"); + let s = format!("{:?}", (1i,)); + assert_eq!(s, "(1i,)"); + let s = format!("{:?}", (1i, true)); + assert_eq!(s, "(1i, true)"); + let s = format!("{:?}", (1i, "hi", true)); + assert_eq!(s, "(1i, \"hi\", true)"); } diff --git a/src/libfmt_macros/lib.rs b/src/libfmt_macros/lib.rs index 3829d98c7a1..19173baf166 100644 --- a/src/libfmt_macros/lib.rs +++ b/src/libfmt_macros/lib.rs @@ -212,10 +212,11 @@ impl<'a> Parser<'a> { self.cur.next(); } Some((_, other)) => { - self.err(format!("expected `{}`, found `{}`", c, other).index(&FullRange)); + self.err(format!("expected `{:?}`, found `{:?}`", c, + other).index(&FullRange)); } None => { - self.err(format!("expected `{}` but string was terminated", + self.err(format!("expected `{:?}` but string was terminated", c).index(&FullRange)); } } diff --git a/src/libgetopts/lib.rs b/src/libgetopts/lib.rs index dd9e5e5a038..64d4de7cc8a 100644 --- a/src/libgetopts/lib.rs +++ b/src/libgetopts/lib.rs @@ -105,7 +105,7 @@ use std::iter::repeat; use std::result; /// Name of an option. Either a string or a single char. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Show)] pub enum Name { /// A string representing the long name of an option. /// For example: "help" @@ -116,7 +116,7 @@ pub enum Name { } /// Describes whether an option has an argument. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Show)] pub enum HasArg { /// The option requires an argument. Yes, @@ -127,7 +127,7 @@ pub enum HasArg { } /// Describes how often an option may occur. -#[derive(Clone, Copy, PartialEq, Eq)] +#[derive(Clone, Copy, PartialEq, Eq, Show)] pub enum Occur { /// The option occurs once. Req, @@ -138,7 +138,7 @@ pub enum Occur { } /// A description of a possible option. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Show)] pub struct Opt { /// Name of the option pub name: Name, @@ -152,7 +152,7 @@ pub struct Opt { /// One group of options, e.g., both `-h` and `--help`, along with /// their shared description and properties. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Show)] pub struct OptGroup { /// Short name of the option, e.g. `h` for a `-h` option pub short_name: String, @@ -169,7 +169,7 @@ pub struct OptGroup { } /// Describes whether an option is given at all or has a value. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Show)] enum Optval { Val(String), Given, @@ -177,7 +177,7 @@ enum Optval { /// The result of checking command line arguments. Contains a vector /// of matches and a vector of free strings. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Show)] pub struct Matches { /// Options that matched opts: Vec, @@ -190,7 +190,7 @@ pub struct Matches { /// The type returned when the command line does not conform to the /// expected format. Use the `Show` implementation to output detailed /// information. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Show)] pub enum Fail { /// The option requires an argument but none was passed. ArgumentMissing(String), @@ -205,7 +205,7 @@ pub enum Fail { } /// The type of failure that occurred. -#[derive(Copy, PartialEq, Eq)] +#[derive(Copy, PartialEq, Eq, Show)] #[allow(missing_docs)] pub enum FailType { ArgumentMissing_, @@ -536,13 +536,13 @@ pub fn opt(short_name: &str, impl Fail { /// Convert a `Fail` enum into an error string. - #[deprecated="use `Show` (`{}` format specifier)"] + #[deprecated="use `fmt::String` (`{}` format specifier)"] pub fn to_err_msg(self) -> String { self.to_string() } } -impl fmt::Show for Fail { +impl fmt::String for Fail { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { ArgumentMissing(ref nm) => { diff --git a/src/liblog/directive.rs b/src/liblog/directive.rs index 8134503019c..d741019aa7b 100644 --- a/src/liblog/directive.rs +++ b/src/liblog/directive.rs @@ -84,7 +84,7 @@ pub fn parse_logging_spec(spec: &str) -> (Vec, Option) { match Regex::new(filter) { Ok(re) => Some(re), Err(e) => { - println!("warning: invalid regex filter - {}", e); + println!("warning: invalid regex filter - {:?}", e); None } } diff --git a/src/liblog/lib.rs b/src/liblog/lib.rs index dd4291d6b51..332dd5e558e 100644 --- a/src/liblog/lib.rs +++ b/src/liblog/lib.rs @@ -16,12 +16,12 @@ //! #[macro_use] extern crate log; //! //! fn main() { -//! debug!("this is a debug {}", "message"); +//! debug!("this is a debug {:?}", "message"); //! error!("this is printed by default"); //! //! if log_enabled!(log::INFO) { //! let x = 3i * 4i; // expensive computation -//! info!("the answer was: {}", x); +//! info!("the answer was: {:?}", x); //! } //! } //! ``` @@ -238,11 +238,17 @@ struct DefaultLogger { pub struct LogLevel(pub u32); impl fmt::Show for LogLevel { + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, fmt) + } +} + +impl fmt::String for LogLevel { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let LogLevel(level) = *self; match LOG_LEVEL_NAMES.get(level as uint - 1) { - Some(name) => name.fmt(fmt), - None => level.fmt(fmt) + Some(ref name) => fmt::String::fmt(name, fmt), + None => fmt::String::fmt(&level, fmt) } } } @@ -254,7 +260,7 @@ impl Logger for DefaultLogger { record.level, record.module_path, record.args) { - Err(e) => panic!("failed to log: {}", e), + Err(e) => panic!("failed to log: {:?}", e), Ok(()) => {} } } @@ -264,7 +270,7 @@ impl Drop for DefaultLogger { fn drop(&mut self) { // FIXME(#12628): is panicking the right thing to do? match self.handle.flush() { - Err(e) => panic!("failed to flush a logger: {}", e), + Err(e) => panic!("failed to flush a logger: {:?}", e), Ok(()) => {} } } diff --git a/src/librbml/lib.rs b/src/librbml/lib.rs index ec070269fe1..80a3a88f70c 100644 --- a/src/librbml/lib.rs +++ b/src/librbml/lib.rs @@ -147,7 +147,7 @@ pub mod reader { match $e { Ok(e) => e, Err(e) => { - debug!("ignored error: {}", e); + debug!("ignored error: {:?}", e); return $r } } @@ -256,7 +256,7 @@ pub mod reader { match maybe_get_doc(d, tg) { Some(d) => d, None => { - error!("failed to find block with tag {}", tg); + error!("failed to find block with tag {:?}", tg); panic!(); } } @@ -351,8 +351,8 @@ pub mod reader { self.pos = r_doc.end; let str = r_doc.as_str_slice(); if lbl != str { - return Err(Expected(format!("Expected label {} but \ - found {}", lbl, str))); + return Err(Expected(format!("Expected label {:?} but \ + found {:?}", lbl, str))); } } } @@ -360,14 +360,14 @@ pub mod reader { } fn next_doc(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult> { - debug!(". next_doc(exp_tag={})", exp_tag); + debug!(". next_doc(exp_tag={:?})", exp_tag); if self.pos >= self.parent.end { return Err(Expected(format!("no more documents in \ current node!"))); } let TaggedDoc { tag: r_tag, doc: r_doc } = try!(doc_at(self.parent.data, self.pos)); - debug!("self.parent={}-{} self.pos={} r_tag={} r_doc={}-{}", + debug!("self.parent={:?}-{:?} self.pos={:?} r_tag={:?} r_doc={:?}-{:?}", self.parent.start, self.parent.end, self.pos, @@ -375,8 +375,8 @@ pub mod reader { r_doc.start, r_doc.end); if r_tag != (exp_tag as uint) { - return Err(Expected(format!("expected EBML doc with tag {} but \ - found tag {}", exp_tag, r_tag))); + return Err(Expected(format!("expected EBML doc with tag {:?} but \ + found tag {:?}", exp_tag, r_tag))); } if r_doc.end > self.parent.end { return Err(Expected(format!("invalid EBML, child extends to \ @@ -403,7 +403,7 @@ pub mod reader { fn _next_uint(&mut self, exp_tag: EbmlEncoderTag) -> DecodeResult { let r = doc_as_u32(try!(self.next_doc(exp_tag))); - debug!("_next_uint exp_tag={} result={}", exp_tag, r); + debug!("_next_uint exp_tag={:?} result={:?}", exp_tag, r); Ok(r as uint) } @@ -486,7 +486,7 @@ pub mod reader { fn read_enum(&mut self, name: &str, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_enum({})", name); + debug!("read_enum({:?})", name); try!(self._check_label(name)); let doc = try!(self.next_doc(EsEnum)); @@ -508,7 +508,7 @@ pub mod reader { { debug!("read_enum_variant()"); let idx = try!(self._next_uint(EsEnumVid)); - debug!(" idx={}", idx); + debug!(" idx={:?}", idx); let doc = try!(self.next_doc(EsEnumBody)); @@ -526,7 +526,7 @@ pub mod reader { fn read_enum_variant_arg(&mut self, idx: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_enum_variant_arg(idx={})", idx); + debug!("read_enum_variant_arg(idx={:?})", idx); f(self) } @@ -536,7 +536,7 @@ pub mod reader { { debug!("read_enum_struct_variant()"); let idx = try!(self._next_uint(EsEnumVid)); - debug!(" idx={}", idx); + debug!(" idx={:?}", idx); let doc = try!(self.next_doc(EsEnumBody)); @@ -558,21 +558,21 @@ pub mod reader { -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_enum_struct_variant_arg(name={}, idx={})", name, idx); + debug!("read_enum_struct_variant_arg(name={:?}, idx={:?})", name, idx); f(self) } fn read_struct(&mut self, name: &str, _: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_struct(name={})", name); + debug!("read_struct(name={:?})", name); f(self) } fn read_struct_field(&mut self, name: &str, idx: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_struct_field(name={}, idx={})", name, idx); + debug!("read_struct_field(name={:?}, idx={:?})", name, idx); try!(self._check_label(name)); f(self) } @@ -594,14 +594,14 @@ pub mod reader { fn read_tuple_arg(&mut self, idx: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_tuple_arg(idx={})", idx); + debug!("read_tuple_arg(idx={:?})", idx); self.read_seq_elt(idx, f) } fn read_tuple_struct(&mut self, name: &str, len: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_tuple_struct(name={})", name); + debug!("read_tuple_struct(name={:?})", name); self.read_tuple(len, f) } @@ -611,7 +611,7 @@ pub mod reader { -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_tuple_struct_arg(idx={})", idx); + debug!("read_tuple_struct_arg(idx={:?})", idx); self.read_tuple_arg(idx, f) } @@ -638,7 +638,7 @@ pub mod reader { debug!("read_seq()"); self.push_doc(EsVec, move |d| { let len = try!(d._next_uint(EsVecLen)); - debug!(" len={}", len); + debug!(" len={:?}", len); f(d, len) }) } @@ -646,7 +646,7 @@ pub mod reader { fn read_seq_elt(&mut self, idx: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_seq_elt(idx={})", idx); + debug!("read_seq_elt(idx={:?})", idx); self.push_doc(EsVecElt, f) } @@ -656,7 +656,7 @@ pub mod reader { debug!("read_map()"); self.push_doc(EsMap, move |d| { let len = try!(d._next_uint(EsMapLen)); - debug!(" len={}", len); + debug!(" len={:?}", len); f(d, len) }) } @@ -664,14 +664,14 @@ pub mod reader { fn read_map_elt_key(&mut self, idx: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_map_elt_key(idx={})", idx); + debug!("read_map_elt_key(idx={:?})", idx); self.push_doc(EsMapKey, f) } fn read_map_elt_val(&mut self, idx: uint, f: F) -> DecodeResult where F: FnOnce(&mut Decoder<'doc>) -> DecodeResult, { - debug!("read_map_elt_val(idx={})", idx); + debug!("read_map_elt_val(idx={:?})", idx); self.push_doc(EsMapVal, f) } @@ -1007,7 +1007,7 @@ pub mod writer { } pub fn start_tag(&mut self, tag_id: uint) -> EncodeResult { - debug!("Start tag {}", tag_id); + debug!("Start tag {:?}", tag_id); // Write the enum ID: try!(write_vuint(self.writer, tag_id)); @@ -1026,7 +1026,7 @@ pub mod writer { try!(write_sized_vuint(self.writer, size, 4u)); let r = try!(self.writer.seek(cur_pos as i64, io::SeekSet)); - debug!("End tag (size = {})", size); + debug!("End tag (size = {:?})", size); Ok(r) } @@ -1093,12 +1093,12 @@ pub mod writer { } pub fn wr_bytes(&mut self, b: &[u8]) -> EncodeResult { - debug!("Write {} bytes", b.len()); + debug!("Write {:?} bytes", b.len()); self.writer.write(b) } pub fn wr_str(&mut self, s: &str) -> EncodeResult { - debug!("Write str: {}", s); + debug!("Write str: {:?}", s); self.writer.write(s.as_bytes()) } } @@ -1608,7 +1608,7 @@ mod tests { #[test] fn test_option_int() { fn test_v(v: Option) { - debug!("v == {}", v); + debug!("v == {:?}", v); let mut wr = SeekableMemWriter::new(); { let mut rbml_w = writer::Encoder::new(&mut wr); @@ -1617,7 +1617,7 @@ mod tests { let rbml_doc = Doc::new(wr.get_ref()); let mut deser = reader::Decoder::new(rbml_doc); let v1 = Decodable::decode(&mut deser).unwrap(); - debug!("v1 == {}", v1); + debug!("v1 == {:?}", v1); assert_eq!(v, v1); } diff --git a/src/libregex/lib.rs b/src/libregex/lib.rs index 0084be49b56..92ed048bae0 100644 --- a/src/libregex/lib.rs +++ b/src/libregex/lib.rs @@ -13,7 +13,6 @@ //! Regular expressions implemented in Rust //! //! For official documentation, see the rust-lang/regex crate - #![crate_name = "regex"] #![crate_type = "rlib"] #![crate_type = "dylib"] diff --git a/src/libregex/parse.rs b/src/libregex/parse.rs index 2d46fa1143e..dd11d42b8aa 100644 --- a/src/libregex/parse.rs +++ b/src/libregex/parse.rs @@ -40,7 +40,7 @@ pub struct Error { impl fmt::Show for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "Regex syntax error near position {}: {}", + write!(f, "Regex syntax error near position {}: {:?}", self.pos, self.msg) } } @@ -122,7 +122,7 @@ impl BuildAst { fn flags(&self) -> Flags { match *self { Paren(flags, _, _) => flags, - _ => panic!("Cannot get flags from {}", self), + _ => panic!("Cannot get flags from {:?}", self), } } @@ -130,7 +130,7 @@ impl BuildAst { match *self { Paren(_, 0, _) => None, Paren(_, c, _) => Some(c), - _ => panic!("Cannot get capture group from {}", self), + _ => panic!("Cannot get capture group from {:?}", self), } } @@ -144,7 +144,7 @@ impl BuildAst { Some(name.clone()) } } - _ => panic!("Cannot get capture name from {}", self), + _ => panic!("Cannot get capture name from {:?}", self), } } @@ -158,7 +158,7 @@ impl BuildAst { fn unwrap(self) -> Result { match self { Expr(x) => Ok(x), - _ => panic!("Tried to unwrap non-AST item: {}", self), + _ => panic!("Tried to unwrap non-AST item: {:?}", self), } } } @@ -285,7 +285,7 @@ impl<'a> Parser<'a> { match self.next_char() { true => Ok(()), false => { - self.err(format!("Expected {} but got EOF.", + self.err(format!("Expected {:?} but got EOF.", expected).index(&FullRange)) } } @@ -294,10 +294,10 @@ impl<'a> Parser<'a> { fn expect(&mut self, expected: char) -> Result<(), Error> { match self.next_char() { true if self.cur() == expected => Ok(()), - true => self.err(format!("Expected '{}' but got '{}'.", + true => self.err(format!("Expected '{:?}' but got '{:?}'.", expected, self.cur()).index(&FullRange)), false => { - self.err(format!("Expected '{}' but got EOF.", + self.err(format!("Expected '{:?}' but got EOF.", expected).index(&FullRange)) } } @@ -395,7 +395,7 @@ impl<'a> Parser<'a> { continue } Some(ast) => - panic!("Expected Class AST but got '{}'", ast), + panic!("Expected Class AST but got '{:?}'", ast), // Just drop down and try to add as a regular character. None => {}, }, @@ -410,7 +410,7 @@ impl<'a> Parser<'a> { return self.err( "\\A, \\z, \\b and \\B are not valid escape \ sequences inside a character class."), - ast => panic!("Unexpected AST item '{}'", ast), + ast => panic!("Unexpected AST item '{:?}'", ast), } } ']' if ranges.len() > 0 || alts.len() > 0 => { @@ -443,7 +443,7 @@ impl<'a> Parser<'a> { match try!(self.parse_escape()) { Literal(c3, _) => c2 = c3, // allow literal escapes below ast => - return self.err(format!("Expected a literal, but got {}.", + return self.err(format!("Expected a literal, but got {:?}.", ast).index(&FullRange)), } } @@ -513,7 +513,7 @@ impl<'a> Parser<'a> { None => { return self.err(format!("No closing brace for counted \ repetition starting at position \ - {}.", + {:?}.", start).index(&FullRange)) } }; @@ -686,7 +686,7 @@ impl<'a> Parser<'a> { match num::from_str_radix::(s.index(&FullRange), 8) { Some(n) => Ok(Literal(try!(self.char_from_u32(n)), FLAG_EMPTY)), None => { - self.err(format!("Could not parse '{}' as octal number.", + self.err(format!("Could not parse '{:?}' as octal number.", s).index(&FullRange)) } } diff --git a/src/libregex/re.rs b/src/libregex/re.rs index cb2690ce80c..37f9869f3bf 100644 --- a/src/libregex/re.rs +++ b/src/libregex/re.rs @@ -90,10 +90,19 @@ impl Clone for ExNative { } } +#[cfg(stage0)] +//FIXME: remove after stage0 snapshot impl fmt::Show for Regex { /// Shows the original regular expression. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.as_str()) + fmt::String::fmt(self.as_str(), f) + } +} + +impl fmt::String for Regex { + /// Shows the original regular expression. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self.as_str(), f) } } diff --git a/src/librustc/lint/builtin.rs b/src/librustc/lint/builtin.rs index e3ab587894b..acf0cc6bd95 100644 --- a/src/librustc/lint/builtin.rs +++ b/src/librustc/lint/builtin.rs @@ -1629,7 +1629,6 @@ declare_lint! { Warn, "detects use of #[deprecated] items" } - // FIXME #6875: Change to Warn after std library stabilization is complete declare_lint! { EXPERIMENTAL, @@ -1848,7 +1847,7 @@ declare_lint! { "detects transmutes of fat pointers" } -declare_lint!{ +declare_lint! { pub MISSING_COPY_IMPLEMENTATIONS, Warn, "detects potentially-forgotten implementations of `Copy`" diff --git a/src/librustc/metadata/csearch.rs b/src/librustc/metadata/csearch.rs index 9249bce276e..72ce61b133a 100644 --- a/src/librustc/metadata/csearch.rs +++ b/src/librustc/metadata/csearch.rs @@ -246,13 +246,13 @@ pub fn get_field_type<'tcx>(tcx: &ty::ctxt<'tcx>, class_id: ast::DefId, let class_doc = expect(tcx.sess.diagnostic(), decoder::maybe_find_item(class_id.node, all_items), || { - (format!("get_field_type: class ID {} not found", + (format!("get_field_type: class ID {:?} not found", class_id)).to_string() }); let the_field = expect(tcx.sess.diagnostic(), decoder::maybe_find_item(def.node, class_doc), || { - (format!("get_field_type: in class {}, field ID {} not found", + (format!("get_field_type: in class {:?}, field ID {:?} not found", class_id, def)).to_string() }); diff --git a/src/librustc/metadata/encoder.rs b/src/librustc/metadata/encoder.rs index b19501229aa..a13df5a220f 100644 --- a/src/librustc/metadata/encoder.rs +++ b/src/librustc/metadata/encoder.rs @@ -845,7 +845,7 @@ fn encode_info_for_method<'a, 'tcx>(ecx: &EncodeContext<'a, 'tcx>, parent_id: NodeId, ast_item_opt: Option<&ast::ImplItem>) { - debug!("encode_info_for_method: {} {}", m.def_id, + debug!("encode_info_for_method: {:?} {:?}", m.def_id, token::get_name(m.name)); rbml_w.start_tag(tag_items_data_item); @@ -887,7 +887,7 @@ fn encode_info_for_associated_type(ecx: &EncodeContext, impl_path: PathElems, parent_id: NodeId, typedef_opt: Option>) { - debug!("encode_info_for_associated_type({},{})", + debug!("encode_info_for_associated_type({:?},{:?})", associated_type.def_id, token::get_name(associated_type.name)); diff --git a/src/librustc/metadata/tydecode.rs b/src/librustc/metadata/tydecode.rs index 01b058b5d1b..a4304bf1e2d 100644 --- a/src/librustc/metadata/tydecode.rs +++ b/src/librustc/metadata/tydecode.rs @@ -738,12 +738,12 @@ pub fn parse_def_id(buf: &[u8]) -> ast::DefId { let crate_num = match str::from_utf8(crate_part).ok().and_then(|s| s.parse::()) { Some(cn) => cn as ast::CrateNum, - None => panic!("internal error: parse_def_id: crate number expected, found {}", + None => panic!("internal error: parse_def_id: crate number expected, found {:?}", crate_part) }; let def_num = match str::from_utf8(def_part).ok().and_then(|s| s.parse::()) { Some(dn) => dn as ast::NodeId, - None => panic!("internal error: parse_def_id: id expected, found {}", + None => panic!("internal error: parse_def_id: id expected, found {:?}", def_part) }; ast::DefId { krate: crate_num, node: def_num } diff --git a/src/librustc/middle/astencode.rs b/src/librustc/middle/astencode.rs index 7f11317a4b9..39e15832bb7 100644 --- a/src/librustc/middle/astencode.rs +++ b/src/librustc/middle/astencode.rs @@ -82,7 +82,7 @@ pub fn encode_inlined_item(ecx: &e::EncodeContext, e::IIImplItemRef(_, &ast::MethodImplItem(ref m)) => m.id, e::IIImplItemRef(_, &ast::TypeImplItem(ref ti)) => ti.id, }; - debug!("> Encoding inlined item: {} ({})", + debug!("> Encoding inlined item: {} ({:?})", ecx.tcx.map.path_to_string(id), rbml_w.writer.tell()); @@ -96,7 +96,7 @@ pub fn encode_inlined_item(ecx: &e::EncodeContext, encode_side_tables_for_ii(ecx, rbml_w, &ii); rbml_w.end_tag(); - debug!("< Encoded inlined fn: {} ({})", + debug!("< Encoded inlined fn: {} ({:?})", ecx.tcx.map.path_to_string(id), rbml_w.writer.tell()); } @@ -127,7 +127,7 @@ pub fn decode_inlined_item<'tcx>(cdata: &cstore::crate_metadata, None => Err(path), Some(ast_doc) => { let mut path_as_str = None; - debug!("> Decoding inlined fn: {}::?", + debug!("> Decoding inlined fn: {:?}::?", { // Do an Option dance to use the path after it is moved below. let s = ast_map::path_to_string(ast_map::Values(path.iter())); @@ -1880,7 +1880,7 @@ impl<'a, 'tcx> rbml_decoder_decoder_helpers<'tcx> for reader::Decoder<'a> { NominalType | TypeWithId | RegionParameter => dcx.tr_def_id(did), TypeParameter | UnboxedClosureSource => dcx.tr_intern_def_id(did) }; - debug!("convert_def_id(source={}, did={})={}", source, did, r); + debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r); return r; } } diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index 2f0e3aeee9b..de3ce9f115e 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -480,12 +480,12 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { let inputs = inline_asm.inputs.iter(); let outputs = inline_asm.outputs.iter(); let post_inputs = self.exprs(inputs.map(|a| { - debug!("cfg::construct InlineAsm id:{} input:{}", expr.id, a); + debug!("cfg::construct InlineAsm id:{} input:{:?}", expr.id, a); let &(_, ref expr) = a; &**expr }), pred); let post_outputs = self.exprs(outputs.map(|a| { - debug!("cfg::construct InlineAsm id:{} output:{}", expr.id, a); + debug!("cfg::construct InlineAsm id:{} output:{:?}", expr.id, a); let &(_, ref expr, _) = a; &**expr }), post_inputs); @@ -622,7 +622,7 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> { r => { self.tcx.sess.span_bug( expr.span, - format!("bad entry `{}` in def_map for label", + format!("bad entry `{:?}` in def_map for label", r).index(&FullRange)); } } diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index ac53bdbefcf..621d7274b3f 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -118,7 +118,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &ast::Expr) { DefStruct(_) | DefVariant(_, _, _) => {} def => { - debug!("(checking const) found bad def: {}", def); + debug!("(checking const) found bad def: {:?}", def); span_err!(v.tcx.sess, e.span, E0014, "paths in constants may only refer to constants \ or functions"); diff --git a/src/librustc/middle/check_match.rs b/src/librustc/middle/check_match.rs index 5712ce3792e..f1edfb37273 100644 --- a/src/librustc/middle/check_match.rs +++ b/src/librustc/middle/check_match.rs @@ -574,7 +574,7 @@ fn is_useful(cx: &MatchCheckCtxt, witness: WitnessPreference) -> Usefulness { let &Matrix(ref rows) = matrix; - debug!("{:}", matrix); + debug!("{:?}", matrix); if rows.len() == 0u { return match witness { ConstructWitness => UsefulWithWitness(vec!()), @@ -1042,7 +1042,7 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt, cx.tcx.sess.span_bug( p.span, format!("binding pattern {} is not an \ - identifier: {}", + identifier: {:?}", p.id, p.node).index(&FullRange)); } diff --git a/src/librustc/middle/check_rvalues.rs b/src/librustc/middle/check_rvalues.rs index c383b1579ef..5ff1f36f0e0 100644 --- a/src/librustc/middle/check_rvalues.rs +++ b/src/librustc/middle/check_rvalues.rs @@ -59,7 +59,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for RvalueContextDelegate<'a, 'tcx> { span: Span, cmt: mc::cmt<'tcx>, _: euv::ConsumeMode) { - debug!("consume; cmt: {}; type: {}", *cmt, ty_to_string(self.tcx, cmt.ty)); + debug!("consume; cmt: {:?}; type: {}", *cmt, ty_to_string(self.tcx, cmt.ty)); if !ty::type_is_sized(self.param_env, span, cmt.ty) { span_err!(self.tcx.sess, span, E0161, "cannot move a value of type {0}: the size of {0} cannot be statically determined", diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index 49ae1bce193..bdd98a94fc3 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -196,7 +196,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let words_per_id = (bits_per_id + uint::BITS - 1) / uint::BITS; let num_nodes = cfg.graph.all_nodes().len(); - debug!("DataFlowContext::new(analysis_name: {}, id_range={}, \ + debug!("DataFlowContext::new(analysis_name: {}, id_range={:?}, \ bits_per_id={}, words_per_id={}) \ num_nodes: {}", analysis_name, id_range, bits_per_id, words_per_id, @@ -251,7 +251,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { fn apply_gen_kill(&self, cfgidx: CFGIndex, bits: &mut [uint]) { //! Applies the gen and kill sets for `cfgidx` to `bits` - debug!("{} apply_gen_kill(cfgidx={}, bits={}) [before]", + debug!("{} apply_gen_kill(cfgidx={:?}, bits={}) [before]", self.analysis_name, cfgidx, mut_bits_to_string(bits)); assert!(self.bits_per_id > 0); @@ -261,7 +261,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { let kills = self.kills.slice(start, end); bitwise(bits, kills, &Subtract); - debug!("{} apply_gen_kill(cfgidx={}, bits={}) [after]", + debug!("{} apply_gen_kill(cfgidx={:?}, bits={}) [after]", self.analysis_name, cfgidx, mut_bits_to_string(bits)); } @@ -315,7 +315,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { temp_bits.index(&FullRange) } }; - debug!("{} each_bit_for_node({}, cfgidx={}) bits={}", + debug!("{} each_bit_for_node({:?}, cfgidx={:?}) bits={}", self.analysis_name, e, cfgidx, bits_to_string(slice)); self.each_bit(slice, f) } @@ -410,7 +410,7 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { } } None => { - debug!("{} add_kills_from_flow_exits flow_exit={} \ + debug!("{} add_kills_from_flow_exits flow_exit={:?} \ no cfg_idx for exiting_scope={}", self.analysis_name, flow_exit, node_id); } @@ -419,10 +419,10 @@ impl<'a, 'tcx, O:DataFlowOperator> DataFlowContext<'a, 'tcx, O> { if changed { let bits = self.kills.slice_mut(start, end); - debug!("{} add_kills_from_flow_exits flow_exit={} bits={} [before]", + debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [before]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); bits.clone_from_slice(orig_kills.index(&FullRange)); - debug!("{} add_kills_from_flow_exits flow_exit={} bits={} [after]", + debug!("{} add_kills_from_flow_exits flow_exit={:?} bits={} [after]", self.analysis_name, flow_exit, mut_bits_to_string(bits)); } true @@ -481,7 +481,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { assert!(self.dfcx.bits_per_id > 0); cfg.graph.each_node(|node_index, node| { - debug!("DataFlowContext::walk_cfg idx={} id={} begin in_out={}", + debug!("DataFlowContext::walk_cfg idx={:?} id={} begin in_out={}", node_index, node.data.id, bits_to_string(in_out)); let (start, end) = self.dfcx.compute_id_range(node_index); @@ -521,7 +521,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { edge: &cfg::CFGEdge) { let source = edge.source(); let cfgidx = edge.target(); - debug!("{} propagate_bits_into_entry_set_for(pred_bits={}, {} to {})", + debug!("{} propagate_bits_into_entry_set_for(pred_bits={}, {:?} to {:?})", self.dfcx.analysis_name, bits_to_string(pred_bits), source, cfgidx); assert!(self.dfcx.bits_per_id > 0); @@ -532,7 +532,7 @@ impl<'a, 'b, 'tcx, O:DataFlowOperator> PropagationContext<'a, 'b, 'tcx, O> { bitwise(on_entry, pred_bits, &self.dfcx.oper) }; if changed { - debug!("{} changed entry set for {} to {}", + debug!("{} changed entry set for {:?} to {}", self.dfcx.analysis_name, cfgidx, bits_to_string(self.dfcx.on_entry.slice(start, end))); self.changed = true; diff --git a/src/librustc/middle/dependency_format.rs b/src/librustc/middle/dependency_format.rs index 8182dec2db0..0bc899a8a62 100644 --- a/src/librustc/middle/dependency_format.rs +++ b/src/librustc/middle/dependency_format.rs @@ -149,7 +149,7 @@ fn calculate_type(sess: &session::Session, add_library(sess, cnum, cstore::RequireDynamic, &mut formats); let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum); for &(depnum, style) in deps.iter() { - debug!("adding {}: {}", style, + debug!("adding {:?}: {}", style, sess.cstore.get_crate_data(depnum).name.clone()); add_library(sess, depnum, style, &mut formats); } diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index 1f89121488e..046271613ca 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -1019,7 +1019,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { if pat_util::pat_is_binding(def_map, pat) { let tcx = typer.tcx(); - debug!("binding cmt_pat={} pat={} match_mode={}", + debug!("binding cmt_pat={} pat={} match_mode={:?}", cmt_pat.repr(tcx), pat.repr(tcx), match_mode); @@ -1155,7 +1155,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { // pattern. if !tcx.sess.has_errors() { - let msg = format!("Pattern has unexpected type: {} and type {}", + let msg = format!("Pattern has unexpected type: {:?} and type {}", def, cmt_pat.ty.repr(tcx)); tcx.sess.span_bug(pat.span, msg.as_slice()) @@ -1172,7 +1172,7 @@ impl<'d,'t,'tcx,TYPER:mc::Typer<'tcx>> ExprUseVisitor<'d,'t,'tcx,TYPER> { // reported. if !tcx.sess.has_errors() { - let msg = format!("Pattern has unexpected def: {} and type {}", + let msg = format!("Pattern has unexpected def: {:?} and type {}", def, cmt_pat.ty.repr(tcx)); tcx.sess.span_bug(pat.span, msg.index(&FullRange)) diff --git a/src/librustc/middle/graph.rs b/src/librustc/middle/graph.rs index 52b6af76081..26cafb3c3d4 100644 --- a/src/librustc/middle/graph.rs +++ b/src/librustc/middle/graph.rs @@ -55,7 +55,7 @@ pub struct Edge { impl Show for Edge { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { - write!(f, "Edge {{ next_edge: [{}, {}], source: {}, target: {}, data: {} }}", + write!(f, "Edge {{ next_edge: [{:?}, {:?}], source: {:?}, target: {:?}, data: {:?} }}", self.next_edge[0], self.next_edge[1], self.source, self.target, self.data) } diff --git a/src/librustc/middle/infer/coercion.rs b/src/librustc/middle/infer/coercion.rs index 65de3a083d2..9f87e73d4af 100644 --- a/src/librustc/middle/infer/coercion.rs +++ b/src/librustc/middle/infer/coercion.rs @@ -265,7 +265,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { ty::mt{ty: ty, mutbl: mt_b.mutbl}); try!(self.get_ref().infcx.try(|_| sub.tys(ty, b))); debug!("Success, coerced with AutoDerefRef(1, \ - AutoPtr(AutoUnsize({})))", kind); + AutoPtr(AutoUnsize({:?})))", kind); Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoPtr(r_borrow, mt_b.mutbl, @@ -288,7 +288,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { ty::mt{ty: ty, mutbl: mt_b.mutbl}); try!(self.get_ref().infcx.try(|_| sub.tys(ty, b))); debug!("Success, coerced with AutoDerefRef(1, \ - AutoPtr(AutoUnsize({})))", kind); + AutoPtr(AutoUnsize({:?})))", kind); Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsafe(mt_b.mutbl, @@ -306,7 +306,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { let ty = ty::mk_uniq(self.tcx(), ty); try!(self.get_ref().infcx.try(|_| sub.tys(ty, b))); debug!("Success, coerced with AutoDerefRef(1, \ - AutoUnsizeUniq({}))", kind); + AutoUnsizeUniq({:?}))", kind); Ok(Some(AdjustDerefRef(AutoDerefRef { autoderefs: 1, autoref: Some(ty::AutoUnsizeUniq(kind)) @@ -328,7 +328,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { a: Ty<'tcx>, ty_b: Ty<'tcx>) -> Option<(Ty<'tcx>, ty::UnsizeKind<'tcx>)> { - debug!("unsize_ty(a={}, ty_b={})", a, ty_b.repr(self.tcx())); + debug!("unsize_ty(a={:?}, ty_b={})", a, ty_b.repr(self.tcx())); let tcx = self.tcx(); @@ -406,7 +406,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { { let tcx = self.tcx(); - debug!("coerce_borrowed_object(a={}, b={}, b_mutbl={})", + debug!("coerce_borrowed_object(a={}, b={}, b_mutbl={:?})", a.repr(tcx), b.repr(tcx), b_mutbl); @@ -426,7 +426,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { { let tcx = self.tcx(); - debug!("coerce_unsafe_object(a={}, b={}, b_mutbl={})", + debug!("coerce_unsafe_object(a={}, b={}, b_mutbl={:?})", a.repr(tcx), b.repr(tcx), b_mutbl); @@ -449,7 +449,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { match a.sty { ty::ty_rptr(_, ty::mt{ty, mutbl}) => match ty.sty { ty::ty_trait(box ty::TyTrait { ref principal, ref bounds }) => { - debug!("mutbl={} b_mutbl={}", mutbl, b_mutbl); + debug!("mutbl={:?} b_mutbl={:?}", mutbl, b_mutbl); let tr = ty::mk_trait(tcx, principal.clone(), bounds.clone()); try!(self.subtype(mk_ty(tr), b)); Ok(Some(AdjustDerefRef(AutoDerefRef { diff --git a/src/librustc/middle/infer/combine.rs b/src/librustc/middle/infer/combine.rs index 9122359bb9e..22975f54a9f 100644 --- a/src/librustc/middle/infer/combine.rs +++ b/src/librustc/middle/infer/combine.rs @@ -361,7 +361,7 @@ pub trait Combine<'tcx> : Sized { a: ty::TraitStore, b: ty::TraitStore) -> cres<'tcx, ty::TraitStore> { - debug!("{}.trait_stores(a={}, b={})", self.tag(), a, b); + debug!("{}.trait_stores(a={:?}, b={:?})", self.tag(), a, b); match (a, b) { (ty::RegionTraitStore(a_r, a_m), @@ -471,7 +471,7 @@ pub fn super_tys<'tcx, C: Combine<'tcx>>(this: &C, let tcx = this.infcx().tcx; let a_sty = &a.sty; let b_sty = &b.sty; - debug!("super_tys: a_sty={} b_sty={}", a_sty, b_sty); + debug!("super_tys: a_sty={:?} b_sty={:?}", a_sty, b_sty); return match (a_sty, b_sty) { // The "subtype" ought to be handling cases involving var: (&ty::ty_infer(TyVar(_)), _) | @@ -550,7 +550,7 @@ pub fn super_tys<'tcx, C: Combine<'tcx>>(this: &C, (&ty::ty_trait(ref a_), &ty::ty_trait(ref b_)) => { - debug!("Trying to match traits {} and {}", a, b); + debug!("Trying to match traits {:?} and {:?}", a, b); let principal = try!(this.binders(&a_.principal, &b_.principal)); let bounds = try!(this.existential_bounds(&a_.bounds, &b_.bounds)); Ok(ty::mk_trait(tcx, principal, bounds)) @@ -724,7 +724,7 @@ impl<'f, 'tcx> CombineFields<'f, 'tcx> { Some(e) => e, }; - debug!("instantiate(a_ty={} dir={} b_vid={})", + debug!("instantiate(a_ty={} dir={:?} b_vid={})", a_ty.repr(tcx), dir, b_vid.repr(tcx)); @@ -745,7 +745,7 @@ impl<'f, 'tcx> CombineFields<'f, 'tcx> { self.generalize(a_ty, b_vid, true) } }); - debug!("instantiate(a_ty={}, dir={}, \ + debug!("instantiate(a_ty={}, dir={:?}, \ b_vid={}, generalized_ty={})", a_ty.repr(tcx), dir, b_vid.repr(tcx), generalized_ty.repr(tcx)); diff --git a/src/librustc/middle/infer/error_reporting.rs b/src/librustc/middle/infer/error_reporting.rs index 1566a7938d3..64b3c14ff69 100644 --- a/src/librustc/middle/infer/error_reporting.rs +++ b/src/librustc/middle/infer/error_reporting.rs @@ -268,7 +268,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { } } let pe = ProcessedErrors(var_origins, trace_origins, same_regions); - debug!("errors processed: {}", pe); + debug!("errors processed: {:?}", pe); processed_errors.push(pe); } return processed_errors; @@ -297,7 +297,7 @@ impl<'a, 'tcx> ErrorReporting<'tcx> for InferCtxt<'a, 'tcx> { sub: Region, sup: Region) -> Option { - debug!("free_regions_from_same_fn(sub={}, sup={})", sub, sup); + debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup); let (scope_id, fr1, fr2) = match (sub, sup) { (ReFree(fr1), ReFree(fr2)) => { if fr1.scope != fr2.scope { diff --git a/src/librustc/middle/infer/higher_ranked/mod.rs b/src/librustc/middle/infer/higher_ranked/mod.rs index cd4705d4fb2..073052dd368 100644 --- a/src/librustc/middle/infer/higher_ranked/mod.rs +++ b/src/librustc/middle/infer/higher_ranked/mod.rs @@ -154,7 +154,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C // Regions that pre-dated the LUB computation stay as they are. if !is_var_in_set(new_vars, r0) { assert!(!r0.is_bound()); - debug!("generalize_region(r0={}): not new variable", r0); + debug!("generalize_region(r0={:?}): not new variable", r0); return r0; } @@ -164,8 +164,8 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C // *related* to regions that pre-date the LUB computation // stay as they are. if !tainted.iter().all(|r| is_var_in_set(new_vars, *r)) { - debug!("generalize_region(r0={}): \ - non-new-variables found in {}", + debug!("generalize_region(r0={:?}): \ + non-new-variables found in {:?}", r0, tainted); assert!(!r0.is_bound()); return r0; @@ -178,8 +178,8 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C // with. for (a_br, a_r) in a_map.iter() { if tainted.iter().any(|x| x == a_r) { - debug!("generalize_region(r0={}): \ - replacing with {}, tainted={}", + debug!("generalize_region(r0={:?}): \ + replacing with {:?}, tainted={:?}", r0, *a_br, tainted); return ty::ReLateBound(debruijn, *a_br); } @@ -187,7 +187,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C infcx.tcx.sess.span_bug( span, - format!("region {} is not associated with \ + format!("region {:?} is not associated with \ any bound region from A!", r0).index(&FullRange)) } @@ -322,7 +322,7 @@ impl<'tcx,C> HigherRankedRelations<'tcx> for C } infcx.tcx.sess.span_bug( span, - format!("could not find original bound region for {}", r).index(&FullRange)); + format!("could not find original bound region for {:?}", r).index(&FullRange)); } fn fresh_bound_variable(infcx: &InferCtxt, debruijn: ty::DebruijnIndex) -> ty::Region { @@ -339,7 +339,7 @@ fn var_ids<'tcx, T: Combine<'tcx>>(combiner: &T, r => { combiner.infcx().tcx.sess.span_bug( combiner.trace().origin.span(), - format!("found non-region-vid: {}", r).index(&FullRange)); + format!("found non-region-vid: {:?}", r).index(&FullRange)); } }).collect() } diff --git a/src/librustc/middle/infer/mod.rs b/src/librustc/middle/infer/mod.rs index a3d94e8b844..3f18af3d768 100644 --- a/src/librustc/middle/infer/mod.rs +++ b/src/librustc/middle/infer/mod.rs @@ -989,7 +989,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> { err: Option<&ty::type_err<'tcx>>) where M: FnOnce(Option, String) -> String, { - debug!("hi! expected_ty = {}, actual_ty = {}", expected_ty, actual_ty); + debug!("hi! expected_ty = {:?}, actual_ty = {}", expected_ty, actual_ty); let resolved_expected = expected_ty.map(|e_ty| self.resolve_type_vars_if_possible(&e_ty)); @@ -1219,7 +1219,7 @@ impl<'tcx> Repr<'tcx> for SubregionOrigin<'tcx> { } Reborrow(a) => format!("Reborrow({})", a.repr(tcx)), ReborrowUpvar(a, b) => { - format!("ReborrowUpvar({},{})", a.repr(tcx), b) + format!("ReborrowUpvar({},{:?})", a.repr(tcx), b) } ReferenceOutlivesReferent(_, a) => { format!("ReferenceOutlivesReferent({})", a.repr(tcx)) @@ -1277,7 +1277,7 @@ impl<'tcx> Repr<'tcx> for RegionVariableOrigin<'tcx> { format!("EarlyBoundRegion({},{})", a.repr(tcx), b.repr(tcx)) } LateBoundRegion(a, b, c) => { - format!("LateBoundRegion({},{},{})", a.repr(tcx), b.repr(tcx), c) + format!("LateBoundRegion({},{},{:?})", a.repr(tcx), b.repr(tcx), c) } BoundRegionInCoherence(a) => { format!("bound_regionInCoherence({})", a.repr(tcx)) diff --git a/src/librustc/middle/infer/region_inference/graphviz.rs b/src/librustc/middle/infer/region_inference/graphviz.rs index 98c69962bc2..16169610b52 100644 --- a/src/librustc/middle/infer/region_inference/graphviz.rs +++ b/src/librustc/middle/infer/region_inference/graphviz.rs @@ -67,7 +67,7 @@ pub fn maybe_print_constraints_for<'a, 'tcx>(region_vars: &RegionVarBindings<'a, } let requested_output = os::getenv("RUST_REGION_GRAPH"); - debug!("requested_output: {} requested_node: {}", + debug!("requested_output: {:?} requested_node: {:?}", requested_output, requested_node); let output_path = { @@ -166,7 +166,7 @@ impl<'a, 'tcx> dot::Labeller<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { fn node_label(&self, n: &Node) -> dot::LabelText { match *n { Node::RegionVid(n_vid) => - dot::LabelText::label(format!("{}", n_vid)), + dot::LabelText::label(format!("{:?}", n_vid)), Node::Region(n_rgn) => dot::LabelText::label(format!("{}", n_rgn.repr(self.tcx))), } @@ -204,12 +204,12 @@ impl<'a, 'tcx> dot::GraphWalk<'a, Node, Edge> for ConstraintGraph<'a, 'tcx> { } fn source(&self, edge: &Edge) -> Node { let (n1, _) = constraint_to_nodes(edge); - debug!("edge {} has source {}", edge, n1); + debug!("edge {:?} has source {:?}", edge, n1); n1 } fn target(&self, edge: &Edge) -> Node { let (_, n2) = constraint_to_nodes(edge); - debug!("edge {} has target {}", edge, n2); + debug!("edge {:?} has target {:?}", edge, n2); n2 } } diff --git a/src/librustc/middle/infer/region_inference/mod.rs b/src/librustc/middle/infer/region_inference/mod.rs index ea5d8456117..bdc787e4d58 100644 --- a/src/librustc/middle/infer/region_inference/mod.rs +++ b/src/librustc/middle/infer/region_inference/mod.rs @@ -273,7 +273,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } pub fn rollback_to(&self, snapshot: RegionSnapshot) { - debug!("RegionVarBindings: rollback_to({})", snapshot); + debug!("RegionVarBindings: rollback_to({:?})", snapshot); let mut undo_log = self.undo_log.borrow_mut(); assert!(undo_log.len() > snapshot.length); assert!((*undo_log)[snapshot.length] == OpenSnapshot); @@ -325,7 +325,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { if self.in_snapshot() { self.undo_log.borrow_mut().push(AddVar(vid)); } - debug!("created new region variable {} with origin {}", + debug!("created new region variable {:?} with origin {}", vid, origin.repr(self.tcx)); return vid; } @@ -427,7 +427,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { let mut givens = self.givens.borrow_mut(); if givens.insert((sub, sup)) { - debug!("add_given({} <= {})", + debug!("add_given({} <= {:?})", sub.repr(self.tcx), sup); @@ -565,7 +565,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } Some(ref values) => { let r = lookup(values, rid); - debug!("resolve_var({}) = {}", rid, r.repr(self.tcx)); + debug!("resolve_var({:?}) = {}", rid, r.repr(self.tcx)); r } } @@ -602,7 +602,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } relate(self, a, ReInfer(ReVar(c))); relate(self, b, ReInfer(ReVar(c))); - debug!("combine_vars() c={}", c); + debug!("combine_vars() c={:?}", c); ReInfer(ReVar(c)) } @@ -623,7 +623,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { /// made---`r0` itself will be the first entry. This is used when checking whether skolemized /// regions are being improperly related to other regions. pub fn tainted(&self, mark: &RegionSnapshot, r0: Region) -> Vec { - debug!("tainted(mark={}, r0={})", mark, r0.repr(self.tcx)); + debug!("tainted(mark={:?}, r0={})", mark, r0.repr(self.tcx)); let _indenter = indenter(); // `result_set` acts as a worklist: we explore all outgoing @@ -634,7 +634,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { while result_index < result_set.len() { // nb: can't use uint::range() here because result_set grows let r = result_set[result_index]; - debug!("result_index={}, r={}", result_index, r); + debug!("result_index={}, r={:?}", result_index, r); for undo_entry in self.undo_log.borrow().slice_from(mark.length).iter() @@ -751,7 +751,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.tcx.sess.span_bug( (*self.var_origins.borrow())[v_id.index as uint].span(), format!("lub_concrete_regions invoked with \ - non-concrete regions: {}, {}", + non-concrete regions: {:?}, {:?}", a, b).index(&FullRange)); } @@ -827,7 +827,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { a: Region, b: Region) -> cres<'tcx, Region> { - debug!("glb_concrete_regions({}, {})", a, b); + debug!("glb_concrete_regions({:?}, {:?})", a, b); match (a, b) { (ReLateBound(..), _) | (_, ReLateBound(..)) | @@ -854,7 +854,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.tcx.sess.span_bug( (*self.var_origins.borrow())[v_id.index as uint].span(), format!("glb_concrete_regions invoked with \ - non-concrete regions: {}, {}", + non-concrete regions: {:?}, {:?}", a, b).index(&FullRange)); } @@ -932,7 +932,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { // scopes or two free regions. So, if one of // these scopes is a subscope of the other, return // it. Otherwise fail. - debug!("intersect_scopes(scope_a={}, scope_b={}, region_a={}, region_b={})", + debug!("intersect_scopes(scope_a={:?}, scope_b={:?}, region_a={:?}, region_b={:?})", scope_a, scope_b, region_a, region_b); match self.tcx.region_maps.nearest_common_ancestor(scope_a, scope_b) { Some(r_id) if scope_a == r_id => Ok(ReScope(scope_b)), @@ -971,7 +971,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { // Dorky hack to cause `dump_constraints` to only get called // if debug mode is enabled: - debug!("----() End constraint listing {}---", self.dump_constraints()); + debug!("----() End constraint listing {:?}---", self.dump_constraints()); graphviz::maybe_print_constraints_for(self, subject); self.expansion(var_data.as_mut_slice()); @@ -1039,7 +1039,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { b_data: &mut VarData) -> bool { - debug!("expand_node({}, {} == {})", + debug!("expand_node({}, {:?} == {})", a_region.repr(self.tcx), b_vid, b_data.value.repr(self.tcx)); @@ -1058,7 +1058,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { b_data.classification = Expanding; match b_data.value { NoValue => { - debug!("Setting initial value of {} to {}", + debug!("Setting initial value of {:?} to {}", b_vid, a_region.repr(self.tcx)); b_data.value = Value(a_region); @@ -1071,7 +1071,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { return false; } - debug!("Expanding value of {} from {} to {}", + debug!("Expanding value of {:?} from {} to {}", b_vid, cur_region.repr(self.tcx), lub.repr(self.tcx)); @@ -1122,7 +1122,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { a_data: &mut VarData, b_region: Region) -> bool { - debug!("contract_node({} == {}/{}, {})", + debug!("contract_node({:?} == {}/{:?}, {})", a_vid, a_data.value.repr(self.tcx), a_data.classification, b_region.repr(self.tcx)); @@ -1156,7 +1156,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { b_region: Region) -> bool { if !this.is_subregion_of(a_region, b_region) { - debug!("Setting {} to ErrorValue: {} not subregion of {}", + debug!("Setting {:?} to ErrorValue: {} not subregion of {}", a_vid, a_region.repr(this.tcx), b_region.repr(this.tcx)); @@ -1176,7 +1176,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { if glb == a_region { false } else { - debug!("Contracting value of {} from {} to {}", + debug!("Contracting value of {:?} from {} to {}", a_vid, a_region.repr(this.tcx), glb.repr(this.tcx)); @@ -1185,7 +1185,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { } } Err(_) => { - debug!("Setting {} to ErrorValue: no glb of {}, {}", + debug!("Setting {:?} to ErrorValue: no glb of {}, {}", a_vid, a_region.repr(this.tcx), b_region.repr(this.tcx)); @@ -1412,7 +1412,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.tcx.sess.span_bug( (*self.var_origins.borrow())[node_idx.index as uint].span(), format!("collect_error_for_expanding_node() could not find error \ - for var {}, lower_bounds={}, upper_bounds={}", + for var {:?}, lower_bounds={}, upper_bounds={}", node_idx, lower_bounds.repr(self.tcx), upper_bounds.repr(self.tcx)).index(&FullRange)); @@ -1457,7 +1457,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { self.tcx.sess.span_bug( (*self.var_origins.borrow())[node_idx.index as uint].span(), format!("collect_error_for_contracting_node() could not find error \ - for var {}, upper_bounds={}", + for var {:?}, upper_bounds={}", node_idx, upper_bounds.repr(self.tcx)).index(&FullRange)); } @@ -1498,8 +1498,8 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { state.dup_found = true; } - debug!("collect_concrete_regions(orig_node_idx={}, node_idx={}, \ - classification={})", + debug!("collect_concrete_regions(orig_node_idx={:?}, node_idx={:?}, \ + classification={:?})", orig_node_idx, node_idx, classification); // figure out the direction from which this node takes its @@ -1520,7 +1520,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> { graph: &RegionGraph, source_vid: RegionVid, dir: Direction) { - debug!("process_edges(source_vid={}, dir={})", source_vid, dir); + debug!("process_edges(source_vid={:?}, dir={:?})", source_vid, dir); let source_node_index = NodeIndex(source_vid.index as uint); graph.each_adjacent_edge(source_node_index, dir, |_, edge| { diff --git a/src/librustc/middle/infer/type_variable.rs b/src/librustc/middle/infer/type_variable.rs index 2aacc863f54..3f3e4c50e70 100644 --- a/src/librustc/middle/infer/type_variable.rs +++ b/src/librustc/middle/infer/type_variable.rs @@ -184,7 +184,7 @@ impl<'tcx> TypeVariableTable<'tcx> { let escaping_type = self.probe(vid).unwrap(); escaping_types.push(escaping_type); } - debug!("SpecifyVar({}) new_elem_threshold={}", vid, new_elem_threshold); + debug!("SpecifyVar({:?}) new_elem_threshold={}", vid, new_elem_threshold); } _ => { } diff --git a/src/librustc/middle/infer/unify.rs b/src/librustc/middle/infer/unify.rs index 73da9644593..2d70e2cdc4d 100644 --- a/src/librustc/middle/infer/unify.rs +++ b/src/librustc/middle/infer/unify.rs @@ -129,7 +129,7 @@ impl<'tcx, V:PartialEq+Clone+Repr<'tcx>, K:UnifyKey<'tcx, V>> UnificationTable K { let index = self.values.push(Root(value, 0)); let k = UnifyKey::from_index(index); - debug!("{}: created new key: {}", + debug!("{}: created new key: {:?}", UnifyKey::tag(None::), k); k diff --git a/src/librustc/middle/intrinsicck.rs b/src/librustc/middle/intrinsicck.rs index a83416667ab..41f293cfca5 100644 --- a/src/librustc/middle/intrinsicck.rs +++ b/src/librustc/middle/intrinsicck.rs @@ -209,7 +209,7 @@ impl<'a, 'tcx> IntrinsicCheckingVisitor<'a, 'tcx> { } Some((space, index, ¶m_ty)) => { - debug!("with_each_combination: space={}, index={}, param_ty={}", + debug!("with_each_combination: space={:?}, index={}, param_ty={}", space, index, param_ty.repr(self.tcx)); if !ty::type_is_sized(param_env, span, param_ty) { diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 24cfe511230..dab8faa3f78 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -289,7 +289,7 @@ impl<'a, 'tcx> IrMaps<'a, 'tcx> { self.lnks.push(lnk); self.num_live_nodes += 1; - debug!("{} is of kind {}", ln.to_string(), + debug!("{:?} is of kind {}", ln, live_node_kind_to_string(lnk, self.tcx)); ln @@ -299,7 +299,7 @@ impl<'a, 'tcx> IrMaps<'a, 'tcx> { let ln = self.add_live_node(lnk); self.live_node_map.insert(node_id, ln); - debug!("{} is node {}", ln.to_string(), node_id); + debug!("{:?} is node {}", ln, node_id); } fn add_variable(&mut self, vk: VarKind) -> Variable { @@ -314,7 +314,7 @@ impl<'a, 'tcx> IrMaps<'a, 'tcx> { ImplicitRet | CleanExit => {} } - debug!("{} is {}", v.to_string(), vk); + debug!("{:?} is {:?}", v, vk); v } @@ -377,7 +377,7 @@ fn visit_fn(ir: &mut IrMaps, // swap in a new set of IR maps for this function body: let mut fn_maps = IrMaps::new(ir.tcx); - debug!("creating fn_maps: {}", &fn_maps as *const IrMaps); + debug!("creating fn_maps: {:?}", &fn_maps as *const IrMaps); for arg in decl.inputs.iter() { pat_util::pat_bindings(&ir.tcx.def_map, @@ -430,7 +430,7 @@ fn visit_local(ir: &mut IrMaps, local: &ast::Local) { fn visit_arm(ir: &mut IrMaps, arm: &ast::Arm) { for pat in arm.pats.iter() { pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| { - debug!("adding local variable {} from match with bm {}", + debug!("adding local variable {} from match with bm {:?}", p_id, bm); let name = path1.node; ir.add_live_node_for_node(p_id, VarDefNode(sp)); @@ -448,7 +448,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { // live nodes required for uses or definitions of variables: ast::ExprPath(_) => { let def = ir.tcx.def_map.borrow()[expr.id].clone(); - debug!("expr {}: path that leads to {}", expr.id, def); + debug!("expr {}: path that leads to {:?}", expr.id, def); if let DefLocal(..) = def { ir.add_live_node_for_node(expr.id, ExprNode(expr.span)); } @@ -491,7 +491,7 @@ fn visit_expr(ir: &mut IrMaps, expr: &Expr) { } ast::ExprForLoop(ref pat, _, _, _) => { pat_util::pat_bindings(&ir.tcx.def_map, &**pat, |bm, p_id, sp, path1| { - debug!("adding local variable {} from for loop with bm {}", + debug!("adding local variable {} from for loop with bm {:?}", p_id, bm); let name = path1.node; ir.add_live_node_for_node(p_id, VarDefNode(sp)); @@ -702,7 +702,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { for var_idx in range(0u, self.ir.num_vars) { let idx = node_base_idx + var_idx; if test(idx).is_valid() { - try!(write!(wr, " {}", Variable(var_idx).to_string())); + try!(write!(wr, " {:?}", Variable(var_idx))); } } Ok(()) @@ -740,11 +740,11 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { let mut wr = Vec::new(); { let wr = &mut wr as &mut io::Writer; - write!(wr, "[ln({}) of kind {} reads", ln.get(), self.ir.lnk(ln)); + write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln)); self.write_vars(wr, ln, |idx| self.users[idx].reader); write!(wr, " writes"); self.write_vars(wr, ln, |idx| self.users[idx].writer); - write!(wr, " precedes {}]", self.successors[ln.get()].to_string()); + write!(wr, " precedes {:?}]", self.successors[ln.get()]); } String::from_utf8(wr).unwrap() } @@ -792,8 +792,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { } }); - debug!("merge_from_succ(ln={}, succ={}, first_merge={}, changed={})", - ln.to_string(), self.ln_str(succ_ln), first_merge, changed); + debug!("merge_from_succ(ln={:?}, succ={}, first_merge={}, changed={})", + ln, self.ln_str(succ_ln), first_merge, changed); return changed; fn copy_if_invalid(src: LiveNode, dst: &mut LiveNode) -> bool { @@ -814,14 +814,14 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { self.users[idx].reader = invalid_node(); self.users[idx].writer = invalid_node(); - debug!("{} defines {} (idx={}): {}", writer.to_string(), var.to_string(), + debug!("{:?} defines {:?} (idx={}): {}", writer, var, idx, self.ln_str(writer)); } // Either read, write, or both depending on the acc bitset fn acc(&mut self, ln: LiveNode, var: Variable, acc: uint) { - debug!("{} accesses[{:x}] {}: {}", - ln.to_string(), acc, var.to_string(), self.ln_str(ln)); + debug!("{:?} accesses[{:x}] {:?}: {}", + ln, acc, var, self.ln_str(ln)); let idx = self.idx(ln, var); let user = &mut self.users[idx]; @@ -857,14 +857,14 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> { |this| this.propagate_through_fn_block(decl, body)); // hack to skip the loop unless debug! is enabled: - debug!("^^ liveness computation results for body {} (entry={})", + debug!("^^ liveness computation results for body {} (entry={:?})", { for ln_idx in range(0u, self.ir.num_live_nodes) { - debug!("{}", self.ln_str(LiveNode(ln_idx))); + debug!("{:?}", self.ln_str(LiveNode(ln_idx))); } body.id }, - entry_ln.to_string()); + entry_ln); entry_ln } diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index 81d4d66a88e..c472ea4a814 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -539,7 +539,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { expr_ty: Ty<'tcx>, def: def::Def) -> McResult> { - debug!("cat_def: id={} expr={} def={}", + debug!("cat_def: id={} expr={} def={:?}", id, expr_ty.repr(self.tcx()), def); match def { @@ -852,7 +852,7 @@ impl<'t,'tcx,TYPER:Typer<'tcx>> MemCategorizationContext<'t,TYPER> { }; let method_ty = self.typer.node_method_ty(method_call); - debug!("cat_deref: method_call={} method_ty={}", + debug!("cat_deref: method_call={:?} method_ty={:?}", method_call, method_ty.map(|ty| ty.repr(self.tcx()))); let base_cmt = match method_ty { @@ -1447,7 +1447,7 @@ impl<'tcx> cmt_<'tcx> { impl<'tcx> Repr<'tcx> for cmt_<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { - format!("{{{} id:{} m:{} ty:{}}}", + format!("{{{} id:{} m:{:?} ty:{}}}", self.cat.repr(tcx), self.id, self.mutbl, @@ -1462,7 +1462,7 @@ impl<'tcx> Repr<'tcx> for categorization<'tcx> { cat_rvalue(..) | cat_local(..) | cat_upvar(..) => { - format!("{}", *self) + format!("{:?}", *self) } cat_deref(ref cmt, derefs, ptr) => { format!("{}-{}{}->", cmt.cat.repr(tcx), ptr_sigil(ptr), derefs) diff --git a/src/librustc/middle/privacy.rs b/src/librustc/middle/privacy.rs index df545c7570a..861c4a2c85e 100644 --- a/src/librustc/middle/privacy.rs +++ b/src/librustc/middle/privacy.rs @@ -435,28 +435,28 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { fn def_privacy(&self, did: ast::DefId) -> PrivacyResult { if !is_local(did) { if self.external_exports.contains(&did) { - debug!("privacy - {} was externally exported", did); + debug!("privacy - {:?} was externally exported", did); return Allowable; } - debug!("privacy - is {} a public method", did); + debug!("privacy - is {:?} a public method", did); return match self.tcx.impl_or_trait_items.borrow().get(&did) { Some(&ty::MethodTraitItem(ref meth)) => { - debug!("privacy - well at least it's a method: {}", + debug!("privacy - well at least it's a method: {:?}", *meth); match meth.container { ty::TraitContainer(id) => { - debug!("privacy - recursing on trait {}", id); + debug!("privacy - recursing on trait {:?}", id); self.def_privacy(id) } ty::ImplContainer(id) => { match ty::impl_trait_ref(self.tcx, id) { Some(t) => { - debug!("privacy - impl of trait {}", id); + debug!("privacy - impl of trait {:?}", id); self.def_privacy(t.def_id) } None => { - debug!("privacy - found a method {}", + debug!("privacy - found a method {:?}", meth.vis); if meth.vis == ast::Public { Allowable @@ -471,17 +471,17 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { Some(&ty::TypeTraitItem(ref typedef)) => { match typedef.container { ty::TraitContainer(id) => { - debug!("privacy - recursing on trait {}", id); + debug!("privacy - recursing on trait {:?}", id); self.def_privacy(id) } ty::ImplContainer(id) => { match ty::impl_trait_ref(self.tcx, id) { Some(t) => { - debug!("privacy - impl of trait {}", id); + debug!("privacy - impl of trait {:?}", id); self.def_privacy(t.def_id) } None => { - debug!("privacy - found a typedef {}", + debug!("privacy - found a typedef {:?}", typedef.vis); if typedef.vis == ast::Public { Allowable @@ -696,7 +696,7 @@ impl<'a, 'tcx> PrivacyVisitor<'a, 'tcx> { let fields = ty::lookup_struct_fields(self.tcx, id); let field = match name { NamedField(ident) => { - debug!("privacy - check named field {} in struct {}", ident.name, id); + debug!("privacy - check named field {} in struct {:?}", ident.name, id); fields.iter().find(|f| f.name == ident.name).unwrap() } UnnamedField(idx) => &fields[idx] diff --git a/src/librustc/middle/region.rs b/src/librustc/middle/region.rs index 5be092eb1bd..5d18843097f 100644 --- a/src/librustc/middle/region.rs +++ b/src/librustc/middle/region.rs @@ -146,24 +146,24 @@ impl RegionMaps { None => {} } - debug!("relate_free_regions(sub={}, sup={})", sub, sup); + debug!("relate_free_regions(sub={:?}, sup={:?})", sub, sup); self.free_region_map.borrow_mut().insert(sub, vec!(sup)); } pub fn record_encl_scope(&self, sub: CodeExtent, sup: CodeExtent) { - debug!("record_encl_scope(sub={}, sup={})", sub, sup); + debug!("record_encl_scope(sub={:?}, sup={:?})", sub, sup); assert!(sub != sup); self.scope_map.borrow_mut().insert(sub, sup); } pub fn record_var_scope(&self, var: ast::NodeId, lifetime: CodeExtent) { - debug!("record_var_scope(sub={}, sup={})", var, lifetime); + debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); assert!(var != lifetime.node_id()); self.var_map.borrow_mut().insert(var, lifetime); } pub fn record_rvalue_scope(&self, var: ast::NodeId, lifetime: CodeExtent) { - debug!("record_rvalue_scope(sub={}, sup={})", var, lifetime); + debug!("record_rvalue_scope(sub={:?}, sup={:?})", var, lifetime); assert!(var != lifetime.node_id()); self.rvalue_scopes.borrow_mut().insert(var, lifetime); } @@ -172,7 +172,7 @@ impl RegionMaps { /// e.g. by an expression like `a().f` -- they will be freed within the innermost terminating /// scope. pub fn mark_as_terminating_scope(&self, scope_id: CodeExtent) { - debug!("record_terminating_scope(scope_id={})", scope_id); + debug!("record_terminating_scope(scope_id={:?})", scope_id); self.terminating_scopes.borrow_mut().insert(scope_id); } @@ -186,7 +186,7 @@ impl RegionMaps { //! Returns the narrowest scope that encloses `id`, if any. match self.scope_map.borrow().get(&id) { Some(&r) => r, - None => { panic!("no enclosing scope for id {}", id); } + None => { panic!("no enclosing scope for id {:?}", id); } } } @@ -194,7 +194,7 @@ impl RegionMaps { pub fn var_scope(&self, var_id: ast::NodeId) -> CodeExtent { match self.var_map.borrow().get(&var_id) { Some(&r) => r, - None => { panic!("no enclosing scope for id {}", var_id); } + None => { panic!("no enclosing scope for id {:?}", var_id); } } } @@ -204,7 +204,7 @@ impl RegionMaps { // check for a designated rvalue scope match self.rvalue_scopes.borrow().get(&expr_id) { Some(&s) => { - debug!("temporary_scope({}) = {} [custom]", expr_id, s); + debug!("temporary_scope({:?}) = {:?} [custom]", expr_id, s); return Some(s); } None => { } @@ -225,12 +225,12 @@ impl RegionMaps { id = p; } None => { - debug!("temporary_scope({}) = None", expr_id); + debug!("temporary_scope({:?}) = None", expr_id); return None; } } } - debug!("temporary_scope({}) = {} [enclosing]", expr_id, id); + debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); return Some(id); } @@ -238,7 +238,7 @@ impl RegionMaps { //! Returns the lifetime of the variable `id`. let scope = ty::ReScope(self.var_scope(id)); - debug!("var_region({}) = {}", id, scope); + debug!("var_region({:?}) = {:?}", id, scope); scope } @@ -258,7 +258,7 @@ impl RegionMaps { while superscope != s { match self.scope_map.borrow().get(&s) { None => { - debug!("is_subscope_of({}, {}, s={})=false", + debug!("is_subscope_of({:?}, {:?}, s={:?})=false", subscope, superscope, s); return false; @@ -267,7 +267,7 @@ impl RegionMaps { } } - debug!("is_subscope_of({}, {})=true", + debug!("is_subscope_of({:?}, {:?})=true", subscope, superscope); return true; @@ -287,7 +287,7 @@ impl RegionMaps { sub_region: ty::Region, super_region: ty::Region) -> bool { - debug!("is_subregion_of(sub_region={}, super_region={})", + debug!("is_subregion_of(sub_region={:?}, super_region={:?})", sub_region, super_region); sub_region == super_region || { @@ -365,7 +365,7 @@ impl RegionMaps { fn ancestors_of(this: &RegionMaps, scope: CodeExtent) -> Vec { - // debug!("ancestors_of(scope={})", scope); + // debug!("ancestors_of(scope={:?})", scope); let mut result = vec!(scope); let mut scope = scope; loop { @@ -376,7 +376,7 @@ impl RegionMaps { scope = superscope; } } - // debug!("ancestors_of_loop(scope={})", scope); + // debug!("ancestors_of_loop(scope={:?})", scope); } } } @@ -414,7 +414,7 @@ fn record_var_lifetime(visitor: &mut RegionResolutionVisitor, } fn resolve_block(visitor: &mut RegionResolutionVisitor, blk: &ast::Block) { - debug!("resolve_block(blk.id={})", blk.id); + debug!("resolve_block(blk.id={:?})", blk.id); // Record the parent of this block. record_superlifetime(visitor, blk.id, blk.span); @@ -466,7 +466,7 @@ fn resolve_pat(visitor: &mut RegionResolutionVisitor, pat: &ast::Pat) { fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { let stmt_id = stmt_id(stmt); - debug!("resolve_stmt(stmt.id={})", stmt_id); + debug!("resolve_stmt(stmt.id={:?})", stmt_id); let stmt_scope = CodeExtent::from_node_id(stmt_id); visitor.region_maps.mark_as_terminating_scope(stmt_scope); @@ -479,7 +479,7 @@ fn resolve_stmt(visitor: &mut RegionResolutionVisitor, stmt: &ast::Stmt) { } fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { - debug!("resolve_expr(expr.id={})", expr.id); + debug!("resolve_expr(expr.id={:?})", expr.id); record_superlifetime(visitor, expr.id, expr.span); @@ -566,7 +566,7 @@ fn resolve_expr(visitor: &mut RegionResolutionVisitor, expr: &ast::Expr) { } fn resolve_local(visitor: &mut RegionResolutionVisitor, local: &ast::Local) { - debug!("resolve_local(local.id={},local.init={})", + debug!("resolve_local(local.id={:?},local.init={:?})", local.id,local.init.is_some()); let blk_id = match visitor.cx.var_parent { @@ -815,10 +815,10 @@ fn resolve_fn(visitor: &mut RegionResolutionVisitor, body: &ast::Block, sp: Span, id: ast::NodeId) { - debug!("region::resolve_fn(id={}, \ - span={}, \ - body.id={}, \ - cx.parent={})", + debug!("region::resolve_fn(id={:?}, \ + span={:?}, \ + body.id={:?}, \ + cx.parent={:?})", id, visitor.sess.codemap().span_to_string(sp), body.id, diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 6cdbd9872bc..8e03d774b81 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -223,7 +223,7 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> { fn visit_poly_trait_ref(&mut self, trait_ref: &ast::PolyTraitRef, _modifier: &ast::TraitBoundModifier) { - debug!("visit_poly_trait_ref trait_ref={}", trait_ref); + debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref); self.with(LateScope(&trait_ref.bound_lifetimes, self.scope), |old_scope, this| { this.check_lifetime_defs(old_scope, &trait_ref.bound_lifetimes); @@ -250,9 +250,9 @@ impl<'a> LifetimeContext<'a> { scope: &wrap_scope, def_map: self.def_map, }; - debug!("entering scope {}", this.scope); + debug!("entering scope {:?}", this.scope); f(self.scope, &mut this); - debug!("exiting scope {}", this.scope); + debug!("exiting scope {:?}", this.scope); } /// Visits self by adding a scope and handling recursive walk over the contents with `walk`. @@ -281,7 +281,7 @@ impl<'a> LifetimeContext<'a> { { let referenced_idents = early_bound_lifetime_names(generics); - debug!("visit_early_late: referenced_idents={}", + debug!("visit_early_late: referenced_idents={:?}", referenced_idents); let (early, late): (Vec<_>, _) = generics.lifetimes.iter().cloned().partition( @@ -488,7 +488,7 @@ impl<'a> LifetimeContext<'a> { probably a bug in syntax::fold"); } - debug!("lifetime_ref={} id={} resolved to {}", + debug!("lifetime_ref={:?} id={:?} resolved to {:?}", lifetime_to_string(lifetime_ref), lifetime_ref.id, def); @@ -605,9 +605,9 @@ fn early_bound_lifetime_names(generics: &ast::Generics) -> Vec { impl<'a> fmt::Show for ScopeChain<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { - EarlyScope(space, defs, _) => write!(fmt, "EarlyScope({}, {})", space, defs), - LateScope(defs, _) => write!(fmt, "LateScope({})", defs), - BlockScope(id, _) => write!(fmt, "BlockScope({})", id), + EarlyScope(space, defs, _) => write!(fmt, "EarlyScope({:?}, {:?})", space, defs), + LateScope(defs, _) => write!(fmt, "LateScope({:?})", defs), + BlockScope(id, _) => write!(fmt, "BlockScope({:?})", id), RootScope => write!(fmt, "RootScope"), } } diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index 362d5fedaa3..359ad8d3941 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -161,7 +161,7 @@ pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option { // is this definition the implementation of a trait method? match ty::trait_item_of_item(tcx, id) { Some(ty::MethodTraitItemId(trait_method_id)) if trait_method_id != id => { - debug!("lookup: trait_method_id={}", trait_method_id); + debug!("lookup: trait_method_id={:?}", trait_method_id); return lookup(tcx, trait_method_id) } _ => {} @@ -182,7 +182,7 @@ pub fn lookup(tcx: &ty::ctxt, id: DefId) -> Option { // stability of the trait to determine the stability of any // unmarked impls for it. See FIXME above for more details. - debug!("lookup: trait_id={}", trait_id); + debug!("lookup: trait_id={:?}", trait_id); lookup(tcx, trait_id) } else { None diff --git a/src/librustc/middle/subst.rs b/src/librustc/middle/subst.rs index a3973d58542..98bb0645bef 100644 --- a/src/librustc/middle/subst.rs +++ b/src/librustc/middle/subst.rs @@ -242,7 +242,7 @@ impl fmt::Show for VecPerParamSpace { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "VecPerParamSpace {{")); for space in ParamSpace::all().iter() { - try!(write!(fmt, "{}: {}, ", *space, self.get_slice(*space))); + try!(write!(fmt, "{:?}: {:?}, ", *space, self.get_slice(*space))); } try!(write!(fmt, "}}")); Ok(()) @@ -601,7 +601,7 @@ impl<'a, 'tcx> TypeFolder<'tcx> for SubstFolder<'a, 'tcx> { span, format!("Type parameter out of range \ when substituting in region {} (root type={}) \ - (space={}, index={})", + (space={:?}, index={})", region_name.as_str(), self.root_ty.repr(self.tcx()), space, i).index(&FullRange)); @@ -654,7 +654,7 @@ impl<'a,'tcx> SubstFolder<'a,'tcx> { let span = self.span.unwrap_or(DUMMY_SP); self.tcx().sess.span_bug( span, - format!("Type parameter `{}` ({}/{}/{}) out of range \ + format!("Type parameter `{}` ({}/{:?}/{}) out of range \ when substituting (root type={}) substs={}", p.repr(self.tcx()), source_ty.repr(self.tcx()), @@ -711,7 +711,7 @@ impl<'a,'tcx> SubstFolder<'a,'tcx> { /// first case we do not increase the Debruijn index and in the second case we do. The reason /// is that only in the second case have we passed through a fn binder. fn shift_regions_through_binders(&self, ty: Ty<'tcx>) -> Ty<'tcx> { - debug!("shift_regions(ty={}, region_binders_passed={}, type_has_escaping_regions={})", + debug!("shift_regions(ty={:?}, region_binders_passed={:?}, type_has_escaping_regions={:?})", ty.repr(self.tcx()), self.region_binders_passed, ty::type_has_escaping_regions(ty)); if self.region_binders_passed == 0 || !ty::type_has_escaping_regions(ty) { @@ -719,7 +719,7 @@ impl<'a,'tcx> SubstFolder<'a,'tcx> { } let result = ty_fold::shift_regions(self.tcx(), self.region_binders_passed, &ty); - debug!("shift_regions: shifted result = {}", result.repr(self.tcx())); + debug!("shift_regions: shifted result = {:?}", result.repr(self.tcx())); result } diff --git a/src/librustc/middle/traits/mod.rs b/src/librustc/middle/traits/mod.rs index 3638d98ae88..3ef6694ce31 100644 --- a/src/librustc/middle/traits/mod.rs +++ b/src/librustc/middle/traits/mod.rs @@ -297,7 +297,7 @@ pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, span: Span) -> SelectionResult<'tcx, ()> { - debug!("type_known_to_meet_builtin_bound(ty={}, bound={})", + debug!("type_known_to_meet_builtin_bound(ty={}, bound={:?})", ty.repr(infcx.tcx), bound); @@ -347,7 +347,7 @@ pub fn evaluate_builtin_bound<'a,'tcx>(infcx: &InferCtxt<'a,'tcx>, } }; - debug!("type_known_to_meet_builtin_bound: ty={} bound={} result={}", + debug!("type_known_to_meet_builtin_bound: ty={} bound={:?} result={:?}", ty.repr(infcx.tcx), bound, result); diff --git a/src/librustc/middle/traits/object_safety.rs b/src/librustc/middle/traits/object_safety.rs index 17792ef78ab..beb3340e3c4 100644 --- a/src/librustc/middle/traits/object_safety.rs +++ b/src/librustc/middle/traits/object_safety.rs @@ -295,7 +295,7 @@ impl<'tcx> Repr<'tcx> for ObjectSafetyViolation<'tcx> { ObjectSafetyViolation::SizedSelf => format!("SizedSelf"), ObjectSafetyViolation::Method(ref m, code) => - format!("Method({},{})", m.repr(tcx), code), + format!("Method({},{:?})", m.repr(tcx), code), } } } diff --git a/src/librustc/middle/traits/select.rs b/src/librustc/middle/traits/select.rs index 4ffae39ea44..25a33de1cc7 100644 --- a/src/librustc/middle/traits/select.rs +++ b/src/librustc/middle/traits/select.rs @@ -368,7 +368,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let result = self.evaluate_stack(&stack); - debug!("result: {}", result); + debug!("result: {:?}", result); result } @@ -944,14 +944,14 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { _ => { return Ok(()); } }; - debug!("assemble_unboxed_candidates: self_ty={} kind={} obligation={}", + debug!("assemble_unboxed_candidates: self_ty={} kind={:?} obligation={}", self_ty.repr(self.tcx()), kind, obligation.repr(self.tcx())); let closure_kind = self.closure_typer.unboxed_closure_kind(closure_def_id); - debug!("closure_kind = {}", closure_kind); + debug!("closure_kind = {:?}", closure_kind); if closure_kind == kind { candidates.vec.push(UnboxedClosureCandidate(closure_def_id, substs.clone())); @@ -1102,7 +1102,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { Err(error) => EvaluatedToErr(error), } }); - debug!("winnow_candidate depth={} result={}", + debug!("winnow_candidate depth={} result={:?}", stack.obligation.recursion_depth, result); result } @@ -1716,7 +1716,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let substs = self.rematch_impl(impl_def_id, obligation, snapshot, &skol_map, skol_obligation_trait_ref.trait_ref); - debug!("confirm_impl_candidate substs={}", substs); + debug!("confirm_impl_candidate substs={:?}", substs); Ok(self.vtable_impl(impl_def_id, substs, obligation.cause.clone(), obligation.recursion_depth + 1, skol_map, snapshot)) }) @@ -2225,7 +2225,7 @@ impl<'tcx> Repr<'tcx> for SelectionCandidate<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { match *self { ErrorCandidate => format!("ErrorCandidate"), - BuiltinCandidate(b) => format!("BuiltinCandidate({})", b), + BuiltinCandidate(b) => format!("BuiltinCandidate({:?})", b), ParamCandidate(ref a) => format!("ParamCandidate({})", a.repr(tcx)), ImplCandidate(a) => format!("ImplCandidate({})", a.repr(tcx)), ProjectionCandidate => format!("ProjectionCandidate"), @@ -2234,7 +2234,7 @@ impl<'tcx> Repr<'tcx> for SelectionCandidate<'tcx> { format!("ObjectCandidate") } UnboxedClosureCandidate(c, ref s) => { - format!("UnboxedClosureCandidate({},{})", c, s.repr(tcx)) + format!("UnboxedClosureCandidate({:?},{})", c, s.repr(tcx)) } } } diff --git a/src/librustc/middle/traits/util.rs b/src/librustc/middle/traits/util.rs index 229d34fe423..272447027af 100644 --- a/src/librustc/middle/traits/util.rs +++ b/src/librustc/middle/traits/util.rs @@ -238,7 +238,7 @@ pub fn fresh_substs_for_impl<'a, 'tcx>(infcx: &InferCtxt<'a, 'tcx>, impl<'tcx, N> fmt::Show for VtableImplData<'tcx, N> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "VtableImpl({})", self.impl_def_id) + write!(f, "VtableImpl({:?})", self.impl_def_id) } } @@ -451,8 +451,8 @@ impl<'tcx> Repr<'tcx> for super::FulfillmentErrorCode<'tcx> { impl<'tcx> fmt::Show for super::FulfillmentErrorCode<'tcx> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - super::CodeSelectionError(ref e) => write!(f, "{}", e), - super::CodeProjectionError(ref e) => write!(f, "{}", e), + super::CodeSelectionError(ref e) => write!(f, "{:?}", e), + super::CodeProjectionError(ref e) => write!(f, "{:?}", e), super::CodeAmbiguity => write!(f, "Ambiguity") } } diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 1b35d019c8a..593c144f888 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -1709,8 +1709,8 @@ impl fmt::Show for InferTy { TyVar(ref v) => v.fmt(f), IntVar(ref v) => v.fmt(f), FloatVar(ref v) => v.fmt(f), - FreshTy(v) => write!(f, "FreshTy({})", v), - FreshIntTy(v) => write!(f, "FreshIntTy({})", v), + FreshTy(v) => write!(f, "FreshTy({:?})", v), + FreshIntTy(v) => write!(f, "FreshIntTy({:?})", v), } } } @@ -2470,7 +2470,7 @@ fn intern_ty<'tcx>(type_arena: &'tcx TypedArena>, region_depth: flags.depth, }); - debug!("Interned type: {} Pointer: {}", + debug!("Interned type: {:?} Pointer: {:?}", ty, ty as *const _); interner.insert(InternedTy { ty: ty }, ty); @@ -3532,7 +3532,7 @@ fn type_impls_bound<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>, match cache.borrow().get(&ty) { None => {} Some(&result) => { - debug!("type_impls_bound({}, {}) = {} (cached)", + debug!("type_impls_bound({}, {:?}) = {:?} (cached)", ty.repr(param_env.tcx), bound, result); @@ -3545,7 +3545,7 @@ fn type_impls_bound<'a,'tcx>(param_env: &ParameterEnvironment<'a,'tcx>, let is_impld = traits::type_known_to_meet_builtin_bound(&infcx, param_env, ty, bound, span); - debug!("type_impls_bound({}, {}) = {}", + debug!("type_impls_bound({}, {:?}) = {:?}", ty.repr(param_env.tcx), bound, is_impld); @@ -3584,13 +3584,13 @@ pub fn is_ffi_safe<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> bool { pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool { fn type_requires<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec, r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool { - debug!("type_requires({}, {})?", + debug!("type_requires({:?}, {:?})?", ::util::ppaux::ty_to_string(cx, r_ty), ::util::ppaux::ty_to_string(cx, ty)); let r = r_ty == ty || subtypes_require(cx, seen, r_ty, ty); - debug!("type_requires({}, {})? {}", + debug!("type_requires({:?}, {:?})? {:?}", ::util::ppaux::ty_to_string(cx, r_ty), ::util::ppaux::ty_to_string(cx, ty), r); @@ -3599,7 +3599,7 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool { fn subtypes_require<'tcx>(cx: &ctxt<'tcx>, seen: &mut Vec, r_ty: Ty<'tcx>, ty: Ty<'tcx>) -> bool { - debug!("subtypes_require({}, {})?", + debug!("subtypes_require({:?}, {:?})?", ::util::ppaux::ty_to_string(cx, r_ty), ::util::ppaux::ty_to_string(cx, ty)); @@ -3654,7 +3654,7 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool { ty_unboxed_closure(..) => { // this check is run on type definitions, so we don't expect to see // inference by-products or unboxed closure types - cx.sess.bug(format!("requires check invoked on inapplicable type: {}", + cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}", ty).as_slice()) } @@ -3680,7 +3680,7 @@ pub fn is_instantiable<'tcx>(cx: &ctxt<'tcx>, r_ty: Ty<'tcx>) -> bool { } }; - debug!("subtypes_require({}, {})? {}", + debug!("subtypes_require({:?}, {:?})? {:?}", ::util::ppaux::ty_to_string(cx, r_ty), ::util::ppaux::ty_to_string(cx, ty), r); @@ -3748,7 +3748,7 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) ty_unboxed_closure(..) => { // this check is run on type definitions, so we don't expect to see // unboxed closure types - cx.sess.bug(format!("requires check invoked on inapplicable type: {}", + cx.sess.bug(format!("requires check invoked on inapplicable type: {:?}", ty).as_slice()) } _ => Representable, @@ -3790,7 +3790,7 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) fn is_type_structurally_recursive<'tcx>(cx: &ctxt<'tcx>, sp: Span, seen: &mut Vec>, ty: Ty<'tcx>) -> Representability { - debug!("is_type_structurally_recursive: {}", + debug!("is_type_structurally_recursive: {:?}", ::util::ppaux::ty_to_string(cx, ty)); match ty.sty { @@ -3810,7 +3810,7 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) match iter.next() { Some(&seen_type) => { if same_struct_or_enum_def_id(seen_type, did) { - debug!("SelfRecursive: {} contains {}", + debug!("SelfRecursive: {:?} contains {:?}", ::util::ppaux::ty_to_string(cx, seen_type), ::util::ppaux::ty_to_string(cx, ty)); return SelfRecursive; @@ -3830,7 +3830,7 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) for &seen_type in iter { if same_type(ty, seen_type) { - debug!("ContainsRecursive: {} contains {}", + debug!("ContainsRecursive: {:?} contains {:?}", ::util::ppaux::ty_to_string(cx, seen_type), ::util::ppaux::ty_to_string(cx, ty)); return ContainsRecursive; @@ -3852,7 +3852,7 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) } } - debug!("is_type_representable: {}", + debug!("is_type_representable: {:?}", ::util::ppaux::ty_to_string(cx, ty)); // To avoid a stack overflow when checking an enum variant or struct that @@ -3860,7 +3860,7 @@ pub fn is_type_representable<'tcx>(cx: &ctxt<'tcx>, sp: Span, ty: Ty<'tcx>) // of seen types and check recursion for each of them (issues #3008, #3779). let mut seen: Vec = Vec::new(); let r = is_type_structurally_recursive(cx, sp, &mut seen, ty); - debug!("is_type_representable: {} is {}", + debug!("is_type_representable: {:?} is {:?}", ::util::ppaux::ty_to_string(cx, ty), r); r } @@ -4123,7 +4123,7 @@ pub fn fn_is_variadic(fty: Ty) -> bool { match fty.sty { ty_bare_fn(_, ref f) => f.sig.0.variadic, ref s => { - panic!("fn_is_variadic() called on non-fn type: {}", s) + panic!("fn_is_variadic() called on non-fn type: {:?}", s) } } } @@ -4132,7 +4132,7 @@ pub fn ty_fn_sig<'tcx>(fty: Ty<'tcx>) -> &'tcx PolyFnSig<'tcx> { match fty.sty { ty_bare_fn(_, ref f) => &f.sig, ref s => { - panic!("ty_fn_sig() called on non-fn type: {}", s) + panic!("ty_fn_sig() called on non-fn type: {:?}", s) } } } @@ -4158,7 +4158,7 @@ pub fn ty_closure_store(fty: Ty) -> TraitStore { UniqTraitStore } ref s => { - panic!("ty_closure_store() called on non-closure type: {}", s) + panic!("ty_closure_store() called on non-closure type: {:?}", s) } } } @@ -4167,7 +4167,7 @@ pub fn ty_fn_ret<'tcx>(fty: Ty<'tcx>) -> FnOutput<'tcx> { match fty.sty { ty_bare_fn(_, ref f) => f.sig.0.output, ref s => { - panic!("ty_fn_ret() called on non-fn type: {}", s) + panic!("ty_fn_ret() called on non-fn type: {:?}", s) } } } @@ -4187,7 +4187,7 @@ pub fn ty_region(tcx: &ctxt, ref s => { tcx.sess.span_bug( span, - format!("ty_region() invoked on an inappropriate ty: {}", + format!("ty_region() invoked on an inappropriate ty: {:?}", s).index(&FullRange)); } } @@ -4247,7 +4247,7 @@ pub fn expr_span(cx: &ctxt, id: NodeId) -> Span { e.span } Some(f) => { - cx.sess.bug(format!("Node id {} is not an expr: {}", + cx.sess.bug(format!("Node id {} is not an expr: {:?}", id, f).index(&FullRange)); } @@ -4267,14 +4267,14 @@ pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString { } _ => { cx.sess.bug( - format!("Variable id {} maps to {}, not local", + format!("Variable id {} maps to {:?}, not local", id, pat).index(&FullRange)); } } } r => { - cx.sess.bug(format!("Variable id {} maps to {}, not local", + cx.sess.bug(format!("Variable id {} maps to {:?}, not local", id, r).index(&FullRange)); } @@ -4298,7 +4298,7 @@ pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>, return match adjustment { Some(adjustment) => { match *adjustment { - AdjustReifyFnPointer(_) => { + AdjustReifyFnPointer(_) => { match unadjusted_ty.sty { ty::ty_bare_fn(Some(_), b) => { ty::mk_bare_fn(cx, None, b) @@ -4306,7 +4306,7 @@ pub fn adjust_ty<'tcx, F>(cx: &ctxt<'tcx>, ref b => { cx.sess.bug( format!("AdjustReifyFnPointer adjustment on non-fn-item: \ - {}", + {:?}", b).index(&FullRange)); } } @@ -4397,7 +4397,7 @@ pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>, mk_vec(cx, ty, None) } _ => cx.sess.span_bug(span, - format!("UnsizeLength with bad sty: {}", + format!("UnsizeLength with bad sty: {:?}", ty_to_string(cx, ty)).index(&FullRange)) }, &UnsizeStruct(box ref k, tp_index) => match ty.sty { @@ -4409,7 +4409,7 @@ pub fn unsize_ty<'tcx>(cx: &ctxt<'tcx>, mk_struct(cx, did, cx.mk_substs(unsized_substs)) } _ => cx.sess.span_bug(span, - format!("UnsizeStruct with bad sty: {}", + format!("UnsizeStruct with bad sty: {:?}", ty_to_string(cx, ty)).index(&FullRange)) }, &UnsizeVtable(TyTrait { ref principal, ref bounds }, _) => { @@ -4516,7 +4516,7 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind { def => { tcx.sess.span_bug( expr.span, - format!("uncategorized def for expr {}: {}", + format!("uncategorized def for expr {}: {:?}", expr.id, def).index(&FullRange)); } @@ -4639,7 +4639,7 @@ pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field]) let mut i = 0u; for f in fields.iter() { if f.name == name { return i; } i += 1u; } tcx.sess.bug(format!( - "no field named `{}` found in the list of fields `{}`", + "no field named `{}` found in the list of fields `{:?}`", token::get_name(name), fields.iter() .map(|f| token::get_name(f.name).get().to_string()) @@ -4716,18 +4716,18 @@ pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String { terr_mismatch => "types differ".to_string(), terr_unsafety_mismatch(values) => { format!("expected {} fn, found {} fn", - values.expected.to_string(), - values.found.to_string()) + values.expected, + values.found) } terr_abi_mismatch(values) => { format!("expected {} fn, found {} fn", - values.expected.to_string(), - values.found.to_string()) + values.expected, + values.found) } terr_onceness_mismatch(values) => { format!("expected {} fn, found {} fn", - values.expected.to_string(), - values.found.to_string()) + values.expected, + values.found) } terr_sigil_mismatch(values) => { format!("expected {}, found {}", @@ -4819,14 +4819,14 @@ pub fn type_err_to_str<'tcx>(cx: &ctxt<'tcx>, err: &type_err<'tcx>) -> String { "expected an integral type, found `char`".to_string() } terr_int_mismatch(ref values) => { - format!("expected `{}`, found `{}`", - values.expected.to_string(), - values.found.to_string()) + format!("expected `{:?}`, found `{:?}`", + values.expected, + values.found) } terr_float_mismatch(ref values) => { - format!("expected `{}`, found `{}`", - values.expected.to_string(), - values.found.to_string()) + format!("expected `{:?}`, found `{:?}`", + values.expected, + values.found) } terr_variadic_mismatch(ref values) => { format!("expected {} fn, found {} function", @@ -4915,14 +4915,14 @@ pub fn provided_trait_methods<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) }).collect() } _ => { - cx.sess.bug(format!("provided_trait_methods: `{}` is \ + cx.sess.bug(format!("provided_trait_methods: `{:?}` is \ not a trait", id).index(&FullRange)) } } } _ => { - cx.sess.bug(format!("provided_trait_methods: `{}` is not a \ + cx.sess.bug(format!("provided_trait_methods: `{:?}` is not a \ trait", id).index(&FullRange)) } @@ -4951,7 +4951,7 @@ fn lookup_locally_or_in_crate_store(descr: &str, } if def_id.krate == ast::LOCAL_CRATE { - panic!("No def'n found for {} in tcx.{}", def_id, descr); + panic!("No def'n found for {:?} in tcx.{}", def_id, descr); } let v = load_external(); map.insert(def_id, v.clone()); @@ -5058,7 +5058,7 @@ pub fn impl_trait_ref<'tcx>(cx: &ctxt<'tcx>, id: ast::DefId) -> Option>> { memoized(&cx.impl_trait_cache, id, |id: ast::DefId| { if id.krate == ast::LOCAL_CRATE { - debug!("(impl_trait_ref) searching for trait impl {}", id); + debug!("(impl_trait_ref) searching for trait impl {:?}", id); match cx.map.find(id.node) { Some(ast_map::NodeItem(item)) => { match item.node { @@ -5378,7 +5378,7 @@ pub fn predicates_for_trait_ref<'tcx>(tcx: &ctxt<'tcx>, { let trait_def = lookup_trait_def(tcx, trait_ref.def_id()); - debug!("bounds_for_trait_ref(trait_def={}, trait_ref={})", + debug!("bounds_for_trait_ref(trait_def={:?}, trait_ref={:?})", trait_def.repr(tcx), trait_ref.repr(tcx)); // The interaction between HRTB and supertraits is not entirely @@ -5930,7 +5930,7 @@ pub fn required_region_bounds<'tcx>(tcx: &ctxt<'tcx>, predicates: Vec>) -> Vec { - debug!("required_region_bounds(erased_self_ty={}, predicates={})", + debug!("required_region_bounds(erased_self_ty={:?}, predicates={:?})", erased_self_ty.repr(tcx), predicates.repr(tcx)); @@ -6008,7 +6008,7 @@ pub fn populate_implementations_for_type_if_necessary(tcx: &ctxt, return } - debug!("populate_implementations_for_type_if_necessary: searching for {}", type_id); + debug!("populate_implementations_for_type_if_necessary: searching for {:?}", type_id); let mut inherent_impls = Vec::new(); csearch::each_implementation_for_type(&tcx.sess.cstore, type_id, @@ -6369,7 +6369,7 @@ pub fn construct_parameter_environment<'a,'tcx>( record_region_bounds(tcx, &bounds); - debug!("construct_parameter_environment: free_id={} free_subst={} bounds={}", + debug!("construct_parameter_environment: free_id={:?} free_subst={:?} bounds={:?}", free_id, free_substs.repr(tcx), bounds.repr(tcx)); @@ -6395,15 +6395,15 @@ pub fn construct_parameter_environment<'a,'tcx>( types: &mut VecPerParamSpace>, defs: &[TypeParameterDef<'tcx>]) { for def in defs.iter() { - debug!("construct_parameter_environment(): push_types_from_defs: def={}", + debug!("construct_parameter_environment(): push_types_from_defs: def={:?}", def.repr(tcx)); let ty = ty::mk_param_from_def(tcx, def); types.push(def.space, ty); - } + } } fn record_region_bounds<'tcx>(tcx: &ty::ctxt<'tcx>, bounds: &GenericBounds<'tcx>) { - debug!("record_region_bounds(bounds={})", bounds.repr(tcx)); + debug!("record_region_bounds(bounds={:?})", bounds.repr(tcx)); for predicate in bounds.predicates.iter() { match *predicate { @@ -6757,7 +6757,7 @@ pub fn replace_late_bound_regions<'tcx, T, F>( } }); - debug!("resulting map: {} value: {}", map, value.repr(tcx)); + debug!("resulting map: {:?} value: {:?}", map, value.repr(tcx)); (value, map) } @@ -6805,7 +6805,7 @@ impl<'tcx> Repr<'tcx> for AutoRef<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { match *self { AutoPtr(a, b, ref c) => { - format!("AutoPtr({},{},{})", a.repr(tcx), b, c.repr(tcx)) + format!("AutoPtr({},{:?},{})", a.repr(tcx), b, c.repr(tcx)) } AutoUnsize(ref a) => { format!("AutoUnsize({})", a.repr(tcx)) @@ -6814,7 +6814,7 @@ impl<'tcx> Repr<'tcx> for AutoRef<'tcx> { format!("AutoUnsizeUniq({})", a.repr(tcx)) } AutoUnsafe(ref a, ref b) => { - format!("AutoUnsafe({},{})", a, b.repr(tcx)) + format!("AutoUnsafe({:?},{})", a, b.repr(tcx)) } } } @@ -6844,7 +6844,7 @@ impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { match *self { vtable_static(def_id, ref tys, ref vtable_res) => { - format!("vtable_static({}:{}, {}, {})", + format!("vtable_static({:?}:{}, {}, {})", def_id, ty::item_path_str(tcx, def_id), tys.repr(tcx), @@ -6852,11 +6852,11 @@ impl<'tcx> Repr<'tcx> for vtable_origin<'tcx> { } vtable_param(x, y) => { - format!("vtable_param({}, {})", x, y) + format!("vtable_param({:?}, {})", x, y) } vtable_unboxed_closure(def_id) => { - format!("vtable_unboxed_closure({})", def_id) + format!("vtable_unboxed_closure({:?})", def_id) } vtable_error => { @@ -7287,7 +7287,7 @@ impl ReferencesError for Region impl<'tcx> Repr<'tcx> for ClosureTy<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { - format!("ClosureTy({},{},{},{},{},{})", + format!("ClosureTy({},{},{:?},{},{},{})", self.unsafety, self.onceness, self.store, diff --git a/src/librustc/middle/ty_walk.rs b/src/librustc/middle/ty_walk.rs index 4953e9a2ce1..28975c73416 100644 --- a/src/librustc/middle/ty_walk.rs +++ b/src/librustc/middle/ty_walk.rs @@ -95,7 +95,7 @@ impl<'tcx> Iterator for TypeWalker<'tcx> { type Item = Ty<'tcx>; fn next(&mut self) -> Option> { - debug!("next(): stack={}", self.stack); + debug!("next(): stack={:?}", self.stack); match self.stack.pop() { None => { return None; @@ -103,7 +103,7 @@ impl<'tcx> Iterator for TypeWalker<'tcx> { Some(ty) => { self.last_subtree = self.stack.len(); self.push_subtypes(ty); - debug!("next: stack={}", self.stack); + debug!("next: stack={:?}", self.stack); Some(ty) } } diff --git a/src/librustc/util/common.rs b/src/librustc/util/common.rs index 7d2a8509cb5..26f98e28a8d 100644 --- a/src/librustc/util/common.rs +++ b/src/librustc/util/common.rs @@ -64,7 +64,7 @@ pub fn indent(op: F) -> R where // to make debug output more readable. debug!(">>"); let r = op(); - debug!("<< (Result = {})", r); + debug!("<< (Result = {:?})", r); r } diff --git a/src/librustc/util/ppaux.rs b/src/librustc/util/ppaux.rs index 55bba3e4215..ded8713079a 100644 --- a/src/librustc/util/ppaux.rs +++ b/src/librustc/util/ppaux.rs @@ -111,7 +111,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) } Some(_) | None => { // this really should not happen - (format!("unknown scope: {}. Please report a bug.", scope), None) + (format!("unknown scope: {:?}. Please report a bug.", scope), None) } } } @@ -140,7 +140,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) } Some(_) | None => { // this really should not happen - (format!("{} unknown free region bounded by scope {}", prefix, fr.scope), None) + (format!("{} unknown free region bounded by scope {:?}", prefix, fr.scope), None) } } } @@ -156,7 +156,7 @@ pub fn explain_region_and_span(cx: &ctxt, region: ty::Region) // I believe these cases should not occur (except when debugging, // perhaps) ty::ReInfer(_) | ty::ReLateBound(..) => { - (format!("lifetime {}", region), None) + (format!("lifetime {:?}", region), None) } }; @@ -653,13 +653,13 @@ impl<'tcx, T:UserString<'tcx>> UserString<'tcx> for Vec { impl<'tcx> Repr<'tcx> for def::Def { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } impl<'tcx> Repr<'tcx> for ty::TypeParameterDef<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { - format!("TypeParameterDef({}, {}, {}/{})", + format!("TypeParameterDef({:?}, {}, {:?}/{})", self.def_id, self.bounds.repr(tcx), self.space, @@ -854,7 +854,7 @@ impl<'tcx> Repr<'tcx> for ty::Region { fn repr(&self, tcx: &ctxt) -> String { match *self { ty::ReEarlyBound(id, space, index, name) => { - format!("ReEarlyBound({}, {}, {}, {})", + format!("ReEarlyBound({}, {:?}, {}, {})", id, space, index, @@ -862,7 +862,7 @@ impl<'tcx> Repr<'tcx> for ty::Region { } ty::ReLateBound(binder_id, ref bound_region) => { - format!("ReLateBound({}, {})", + format!("ReLateBound({:?}, {})", binder_id, bound_region.repr(tcx)) } @@ -870,7 +870,7 @@ impl<'tcx> Repr<'tcx> for ty::Region { ty::ReFree(ref fr) => fr.repr(tcx), ty::ReScope(id) => { - format!("ReScope({})", id) + format!("ReScope({:?})", id) } ty::ReStatic => { @@ -878,7 +878,7 @@ impl<'tcx> Repr<'tcx> for ty::Region { } ty::ReInfer(ReVar(ref vid)) => { - format!("{}", vid) + format!("{:?}", vid) } ty::ReInfer(ReSkolemized(id, ref bound_region)) => { @@ -920,14 +920,14 @@ impl<'tcx> Repr<'tcx> for ast::DefId { Some(ast_map::NodeVariant(..)) | Some(ast_map::NodeStructCtor(..)) => { return format!( - "{}:{}", + "{:?}:{}", *self, ty::item_path_str(tcx, *self)) } _ => {} } } - return format!("{}", *self) + return format!("{:?}", *self) } } @@ -1007,13 +1007,13 @@ impl<'tcx> Repr<'tcx> for ast::Ident { impl<'tcx> Repr<'tcx> for ast::ExplicitSelf_ { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } impl<'tcx> Repr<'tcx> for ast::Visibility { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } @@ -1026,6 +1026,7 @@ impl<'tcx> Repr<'tcx> for ty::BareFnTy<'tcx> { } } + impl<'tcx> Repr<'tcx> for ty::FnSig<'tcx> { fn repr(&self, tcx: &ctxt<'tcx>) -> String { format!("fn{} -> {}", self.inputs.repr(tcx), self.output.repr(tcx)) @@ -1096,7 +1097,7 @@ impl<'tcx> Repr<'tcx> for ty::TraitStore { impl<'tcx> Repr<'tcx> for ty::BuiltinBound { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } @@ -1251,13 +1252,13 @@ impl<'tcx> Repr<'tcx> for ty::UpvarId { impl<'tcx> Repr<'tcx> for ast::Mutability { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } impl<'tcx> Repr<'tcx> for ty::BorrowKind { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } @@ -1271,49 +1272,49 @@ impl<'tcx> Repr<'tcx> for ty::UpvarBorrow { impl<'tcx> Repr<'tcx> for ty::IntVid { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", self) + format!("{:?}", self) } } impl<'tcx> Repr<'tcx> for ty::FloatVid { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", self) + format!("{:?}", self) } } impl<'tcx> Repr<'tcx> for ty::RegionVid { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", self) + format!("{:?}", self) } } impl<'tcx> Repr<'tcx> for ty::TyVid { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", self) + format!("{:?}", self) } } impl<'tcx> Repr<'tcx> for ty::IntVarValue { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } impl<'tcx> Repr<'tcx> for ast::IntTy { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } impl<'tcx> Repr<'tcx> for ast::UintTy { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } impl<'tcx> Repr<'tcx> for ast::FloatTy { fn repr(&self, _tcx: &ctxt) -> String { - format!("{}", *self) + format!("{:?}", *self) } } @@ -1332,7 +1333,7 @@ impl<'tcx> UserString<'tcx> for ParamTy { impl<'tcx> Repr<'tcx> for ParamTy { fn repr(&self, tcx: &ctxt) -> String { let ident = self.user_string(tcx); - format!("{}/{}.{}", ident, self.space, self.idx) + format!("{}/{:?}.{}", ident, self.space, self.idx) } } diff --git a/src/librustc_back/archive.rs b/src/librustc_back/archive.rs index 5a5a310c56d..48004acaac0 100644 --- a/src/librustc_back/archive.rs +++ b/src/librustc_back/archive.rs @@ -64,7 +64,7 @@ fn run_ar(handler: &ErrorHandler, maybe_ar_prog: &Option, match cwd { Some(p) => { cmd.cwd(p); - debug!("inside {}", p.display()); + debug!("inside {:?}", p.display()); } None => {} } @@ -105,7 +105,7 @@ pub fn find_library(name: &str, osprefix: &str, ossuffix: &str, let unixlibname = format!("lib{}.a", name); for path in search_paths.iter() { - debug!("looking for {} inside {}", name, path.display()); + debug!("looking for {} inside {:?}", name, path.display()); let test = path.join(oslibname.index(&FullRange)); if test.exists() { return test } if oslibname != unixlibname { diff --git a/src/librustc_back/rpath.rs b/src/librustc_back/rpath.rs index b6f080094cf..db1dfa6b6ee 100644 --- a/src/librustc_back/rpath.rs +++ b/src/librustc_back/rpath.rs @@ -61,10 +61,10 @@ fn get_rpaths(mut config: RPathConfig, libs: &[Path]) -> Vec F: FnOnce() -> Path, G: FnMut(&Path) -> Result, { - debug!("output: {}", config.out_filename.display()); + debug!("output: {:?}", config.out_filename.display()); debug!("libs:"); for libpath in libs.iter() { - debug!(" {}", libpath.display()); + debug!(" {:?}", libpath.display()); } // Use relative paths to the libraries. Binaries can be moved diff --git a/src/librustc_back/svh.rs b/src/librustc_back/svh.rs index 00f1f2402c7..863c1a7c865 100644 --- a/src/librustc_back/svh.rs +++ b/src/librustc_back/svh.rs @@ -119,6 +119,14 @@ impl Svh { } impl fmt::Show for Svh { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + //NOTE(stage0): uncomment after snapshot + //write!(f, "Svh {{ {} }}", self.as_str()) + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Svh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad(self.as_str()) } diff --git a/src/librustc_back/target/mod.rs b/src/librustc_back/target/mod.rs index 02bb6aa4b0d..23c8fc7de51 100644 --- a/src/librustc_back/target/mod.rs +++ b/src/librustc_back/target/mod.rs @@ -301,8 +301,8 @@ impl Target { use serialize::json; fn load_file(path: &Path) -> Result { - let mut f = try!(File::open(path).map_err(|e| e.to_string())); - let obj = try!(json::from_reader(&mut f).map_err(|e| e.to_string())); + let mut f = try!(File::open(path).map_err(|e| format!("{:?}", e))); + let obj = try!(json::from_reader(&mut f).map_err(|e| format!("{:?}", e))); Ok(Target::from_json(obj)) } @@ -315,7 +315,7 @@ impl Target { $( else if target == stringify!($name) { let t = $name::target(); - debug!("Got builtin target: {}", t); + debug!("Got builtin target: {:?}", t); return Ok(t); } )* @@ -379,6 +379,6 @@ impl Target { } } - Err(format!("Could not find specification for target {}", target)) + Err(format!("Could not find specification for target {:?}", target)) } } diff --git a/src/librustc_borrowck/borrowck/check_loans.rs b/src/librustc_borrowck/borrowck/check_loans.rs index 837630c0d61..d942581ca62 100644 --- a/src/librustc_borrowck/borrowck/check_loans.rs +++ b/src/librustc_borrowck/borrowck/check_loans.rs @@ -96,7 +96,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for CheckLoanCtxt<'a, 'tcx> { consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { - debug!("consume(consume_id={}, cmt={}, mode={})", + debug!("consume(consume_id={}, cmt={}, mode={:?})", consume_id, cmt.repr(self.tcx()), mode); self.consume_common(consume_id, consume_span, cmt, mode); @@ -111,7 +111,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for CheckLoanCtxt<'a, 'tcx> { consume_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { - debug!("consume_pat(consume_pat={}, cmt={}, mode={})", + debug!("consume_pat(consume_pat={}, cmt={}, mode={:?})", consume_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); @@ -127,8 +127,8 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for CheckLoanCtxt<'a, 'tcx> { bk: ty::BorrowKind, loan_cause: euv::LoanCause) { - debug!("borrow(borrow_id={}, cmt={}, loan_region={}, \ - bk={}, loan_cause={})", + debug!("borrow(borrow_id={}, cmt={}, loan_region={:?}, \ + bk={:?}, loan_cause={:?})", borrow_id, cmt.repr(self.tcx()), loan_region, bk, loan_cause); @@ -355,10 +355,10 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { //! (Note that some loans can be *issued* without necessarily //! taking effect yet.) - debug!("check_for_conflicting_loans(scope={})", scope); + debug!("check_for_conflicting_loans(scope={:?})", scope); let new_loan_indices = self.loans_generated_by(scope); - debug!("new_loan_indices = {}", new_loan_indices); + debug!("new_loan_indices = {:?}", new_loan_indices); self.each_issued_loan(scope, |issued_loan| { for &new_loan_index in new_loan_indices.iter() { @@ -696,7 +696,7 @@ impl<'a, 'tcx> CheckLoanCtxt<'a, 'tcx> { span: Span, use_kind: MovedValueUseKind, lp: &Rc>) { - debug!("check_if_path_is_moved(id={}, use_kind={}, lp={})", + debug!("check_if_path_is_moved(id={}, use_kind={:?}, lp={})", id, use_kind, lp.repr(self.bccx.tcx)); let base_lp = owned_ptr_base_path_rc(lp); self.move_data.each_move_of(id, &base_lp, |the_move, moved_lp| { diff --git a/src/librustc_borrowck/borrowck/fragments.rs b/src/librustc_borrowck/borrowck/fragments.rs index 8b4029f30d9..d7527487465 100644 --- a/src/librustc_borrowck/borrowck/fragments.rs +++ b/src/librustc_borrowck/borrowck/fragments.rs @@ -198,11 +198,11 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { // First, filter out duplicates moved.sort(); moved.dedup(); - debug!("fragments 1 moved: {}", path_lps(moved.index(&FullRange))); + debug!("fragments 1 moved: {:?}", path_lps(moved.index(&FullRange))); assigned.sort(); assigned.dedup(); - debug!("fragments 1 assigned: {}", path_lps(assigned.index(&FullRange))); + debug!("fragments 1 assigned: {:?}", path_lps(assigned.index(&FullRange))); // Second, build parents from the moved and assigned. for m in moved.iter() { @@ -222,14 +222,14 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { parents.sort(); parents.dedup(); - debug!("fragments 2 parents: {}", path_lps(parents.index(&FullRange))); + debug!("fragments 2 parents: {:?}", path_lps(parents.index(&FullRange))); // Third, filter the moved and assigned fragments down to just the non-parents moved.retain(|f| non_member(*f, parents.index(&FullRange))); - debug!("fragments 3 moved: {}", path_lps(moved.index(&FullRange))); + debug!("fragments 3 moved: {:?}", path_lps(moved.index(&FullRange))); assigned.retain(|f| non_member(*f, parents.index(&FullRange))); - debug!("fragments 3 assigned: {}", path_lps(assigned.index(&FullRange))); + debug!("fragments 3 assigned: {:?}", path_lps(assigned.index(&FullRange))); // Fourth, build the leftover from the moved, assigned, and parents. for m in moved.iter() { @@ -247,7 +247,7 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { unmoved.sort(); unmoved.dedup(); - debug!("fragments 4 unmoved: {}", frag_lps(unmoved.index(&FullRange))); + debug!("fragments 4 unmoved: {:?}", frag_lps(unmoved.index(&FullRange))); // Fifth, filter the leftover fragments down to its core. unmoved.retain(|f| match *f { @@ -256,7 +256,7 @@ pub fn fixup_fragment_sets<'tcx>(this: &MoveData<'tcx>, tcx: &ty::ctxt<'tcx>) { non_member(mpi, moved.index(&FullRange)) && non_member(mpi, assigned.index(&FullRange)) }); - debug!("fragments 5 unmoved: {}", frag_lps(unmoved.index(&FullRange))); + debug!("fragments 5 unmoved: {:?}", frag_lps(unmoved.index(&FullRange))); // Swap contents back in. fragments.unmoved_fragments = unmoved; @@ -430,7 +430,7 @@ fn add_fragment_siblings_for_extension<'tcx>(this: &MoveData<'tcx>, } ref sty_and_variant_info => { - let msg = format!("type {} ({}) is not fragmentable", + let msg = format!("type {} ({:?}) is not fragmentable", parent_ty.repr(tcx), sty_and_variant_info); let opt_span = origin_id.and_then(|id|tcx.map.opt_span(id)); tcx.sess.opt_span_bug(opt_span, msg.index(&FullRange)) diff --git a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs index 6f02f447a15..ca1fba53de4 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/gather_moves.rs @@ -65,7 +65,7 @@ pub fn gather_match_variant<'a, 'tcx>(bccx: &BorrowckCtxt<'a, 'tcx>, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { let tcx = bccx.tcx; - debug!("gather_match_variant(move_pat={}, cmt={}, mode={})", + debug!("gather_match_variant(move_pat={}, cmt={}, mode={:?})", move_pat.id, cmt.repr(tcx), mode); let opt_lp = opt_loan_path(&cmt); diff --git a/src/librustc_borrowck/borrowck/gather_loans/mod.rs b/src/librustc_borrowck/borrowck/gather_loans/mod.rs index 86498af7d95..2c48e0da01d 100644 --- a/src/librustc_borrowck/borrowck/gather_loans/mod.rs +++ b/src/librustc_borrowck/borrowck/gather_loans/mod.rs @@ -76,7 +76,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { _consume_span: Span, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { - debug!("consume(consume_id={}, cmt={}, mode={})", + debug!("consume(consume_id={}, cmt={}, mode={:?})", consume_id, cmt.repr(self.tcx()), mode); match mode { @@ -93,7 +93,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { matched_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::MatchMode) { - debug!("matched_pat(matched_pat={}, cmt={}, mode={})", + debug!("matched_pat(matched_pat={}, cmt={}, mode={:?})", matched_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); @@ -109,7 +109,7 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { consume_pat: &ast::Pat, cmt: mc::cmt<'tcx>, mode: euv::ConsumeMode) { - debug!("consume_pat(consume_pat={}, cmt={}, mode={})", + debug!("consume_pat(consume_pat={}, cmt={}, mode={:?})", consume_pat.repr(self.tcx()), cmt.repr(self.tcx()), mode); @@ -132,8 +132,8 @@ impl<'a, 'tcx> euv::Delegate<'tcx> for GatherLoanCtxt<'a, 'tcx> { bk: ty::BorrowKind, loan_cause: euv::LoanCause) { - debug!("borrow(borrow_id={}, cmt={}, loan_region={}, \ - bk={}, loan_cause={})", + debug!("borrow(borrow_id={}, cmt={}, loan_region={:?}, \ + bk={:?}, loan_cause={:?})", borrow_id, cmt.repr(self.tcx()), loan_region, bk, loan_cause); @@ -235,7 +235,7 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { loan_region: ty::Region, cause: euv::LoanCause) { debug!("guarantee_valid(borrow_id={}, cmt={}, \ - req_mutbl={}, loan_region={})", + req_mutbl={:?}, loan_region={:?})", borrow_id, cmt.repr(self.tcx()), req_kind, @@ -273,7 +273,7 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { self.bccx, borrow_span, cause, cmt.clone(), loan_region); - debug!("guarantee_valid(): restrictions={}", restr); + debug!("guarantee_valid(): restrictions={:?}", restr); // Create the loan record (if needed). let loan = match restr { @@ -306,18 +306,18 @@ impl<'a, 'tcx> GatherLoanCtxt<'a, 'tcx> { ty::ReInfer(..) => { self.tcx().sess.span_bug( cmt.span, - format!("invalid borrow lifetime: {}", + format!("invalid borrow lifetime: {:?}", loan_region).index(&FullRange)); } }; - debug!("loan_scope = {}", loan_scope); + debug!("loan_scope = {:?}", loan_scope); let borrow_scope = region::CodeExtent::from_node_id(borrow_id); let gen_scope = self.compute_gen_scope(borrow_scope, loan_scope); - debug!("gen_scope = {}", gen_scope); + debug!("gen_scope = {:?}", gen_scope); let kill_scope = self.compute_kill_scope(loan_scope, &*loan_path); - debug!("kill_scope = {}", kill_scope); + debug!("kill_scope = {:?}", kill_scope); if req_kind == ty::MutBorrow { self.mark_loan_path_as_mutated(&*loan_path); diff --git a/src/librustc_borrowck/borrowck/mod.rs b/src/librustc_borrowck/borrowck/mod.rs index 75dee496234..88f56f68622 100644 --- a/src/librustc_borrowck/borrowck/mod.rs +++ b/src/librustc_borrowck/borrowck/mod.rs @@ -586,7 +586,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } r => { self.tcx.sess.bug(format!("MoveExpr({}) maps to \ - {}, not Expr", + {:?}, not Expr", the_move.id, r).index(&FullRange)) } @@ -624,7 +624,7 @@ impl<'a, 'tcx> BorrowckCtxt<'a, 'tcx> { } r => { self.tcx.sess.bug(format!("Captured({}) maps to \ - {}, not Expr", + {:?}, not Expr", the_move.id, r).index(&FullRange)) } @@ -1005,7 +1005,7 @@ impl DataFlowOperator for LoanDataFlowOperator { impl<'tcx> Repr<'tcx> for Loan<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { - format!("Loan_{}({}, {}, {}-{}, {})", + format!("Loan_{}({}, {:?}, {:?}-{:?}, {})", self.index, self.loan_path.repr(tcx), self.kind, diff --git a/src/librustc_borrowck/borrowck/move_data.rs b/src/librustc_borrowck/borrowck/move_data.rs index b49164f0c25..21b3c910d32 100644 --- a/src/librustc_borrowck/borrowck/move_data.rs +++ b/src/librustc_borrowck/borrowck/move_data.rs @@ -311,7 +311,7 @@ impl<'tcx> MoveData<'tcx> { } }; - debug!("move_path(lp={}, index={})", + debug!("move_path(lp={}, index={:?})", lp.repr(tcx), index); @@ -362,7 +362,7 @@ impl<'tcx> MoveData<'tcx> { lp: Rc>, id: ast::NodeId, kind: MoveKind) { - debug!("add_move(lp={}, id={}, kind={})", + debug!("add_move(lp={}, id={}, kind={:?})", lp.repr(tcx), id, kind); @@ -413,12 +413,12 @@ impl<'tcx> MoveData<'tcx> { }; if self.is_var_path(path_index) { - debug!("add_assignment[var](lp={}, assignment={}, path_index={})", + debug!("add_assignment[var](lp={}, assignment={}, path_index={:?})", lp.repr(tcx), self.var_assignments.borrow().len(), path_index); self.var_assignments.borrow_mut().push(assignment); } else { - debug!("add_assignment[path](lp={}, path_index={})", + debug!("add_assignment[path](lp={}, path_index={:?})", lp.repr(tcx), path_index); self.path_assignments.borrow_mut().push(assignment); diff --git a/src/librustc_borrowck/graphviz.rs b/src/librustc_borrowck/graphviz.rs index 648b389414a..647a5dd559c 100644 --- a/src/librustc_borrowck/graphviz.rs +++ b/src/librustc_borrowck/graphviz.rs @@ -53,7 +53,7 @@ pub struct DataflowLabeller<'a, 'tcx: 'a> { impl<'a, 'tcx> DataflowLabeller<'a, 'tcx> { fn dataflow_for(&self, e: EntryOrExit, n: &Node<'a>) -> String { let id = n.1.data.id; - debug!("dataflow_for({}, id={}) {}", e, id, self.variants); + debug!("dataflow_for({:?}, id={}) {:?}", e, id, self.variants); let mut sets = "".to_string(); let mut seen_one = false; for &variant in self.variants.iter() { diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index baeca7c8ffd..52d49924d05 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -726,7 +726,7 @@ pub fn collect_crate_types(session: &Session, let res = !link::invalid_output_for_target(session, *crate_type); if !res { - session.warn(format!("dropping unsupported crate type `{}` \ + session.warn(format!("dropping unsupported crate type `{:?}` \ for target `{}`", *crate_type, session.opts.target_triple).index(&FullRange)); } diff --git a/src/librustc_driver/pretty.rs b/src/librustc_driver/pretty.rs index 06ef06a214f..44a35ef6be7 100644 --- a/src/librustc_driver/pretty.rs +++ b/src/librustc_driver/pretty.rs @@ -548,7 +548,7 @@ pub fn pretty_print_input(sess: Session, (PpmSource(s), None) => s.call_with_pp_support( sess, ast_map, &arenas, id, out, |annotation, out| { - debug!("pretty printing source code {}", s); + debug!("pretty printing source code {:?}", s); let sess = annotation.sess(); pprust::print_crate(sess.codemap(), sess.diagnostic(), @@ -563,7 +563,7 @@ pub fn pretty_print_input(sess: Session, (PpmSource(s), Some(uii)) => s.call_with_pp_support( sess, ast_map, &arenas, id, (out,uii), |annotation, (out,uii)| { - debug!("pretty printing source code {}", s); + debug!("pretty printing source code {:?}", s); let sess = annotation.sess(); let ast_map = annotation.ast_map() .expect("--pretty missing ast_map"); @@ -586,7 +586,7 @@ pub fn pretty_print_input(sess: Session, }), (PpmFlowGraph, opt_uii) => { - debug!("pretty printing flow graph for {}", opt_uii); + debug!("pretty printing flow graph for {:?}", opt_uii); let uii = opt_uii.unwrap_or_else(|| { sess.fatal(format!("`pretty flowgraph=..` needs NodeId (int) or unique path suffix (b::c::d)").index(&FullRange)) @@ -609,7 +609,7 @@ pub fn pretty_print_input(sess: Session, } None => { let message = format!("--pretty=flowgraph needs \ - block, fn, or method; got {}", + block, fn, or method; got {:?}", node); // point to what was found, if there's an diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 0a64404a782..ca6b1469f85 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -845,7 +845,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { name: Name, new_parent: &Rc) { debug!("(building reduced graph for \ - external crate) building external def, priv {}", + external crate) building external def, priv {:?}", vis); let is_public = vis == ast::Public; let modifiers = if is_public { PUBLIC } else { DefModifiers::empty() } | IMPORTABLE; @@ -989,7 +989,7 @@ impl<'a, 'b:'a, 'tcx:'b> GraphBuilder<'a, 'b, 'tcx> { DefLocal(..) | DefPrimTy(..) | DefTyParam(..) | DefUse(..) | DefUpvar(..) | DefRegion(..) | DefTyParamBinder(..) | DefLabel(..) | DefSelfTy(..) => { - panic!("didn't expect `{}`", def); + panic!("didn't expect `{:?}`", def); } } } diff --git a/src/librustc_resolve/check_unused.rs b/src/librustc_resolve/check_unused.rs index 26b1058d183..18066a7b94b 100644 --- a/src/librustc_resolve/check_unused.rs +++ b/src/librustc_resolve/check_unused.rs @@ -58,7 +58,7 @@ impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> { // public or private item, we will check the correct thing, dependent on how the import // is used. fn finalize_import(&mut self, id: ast::NodeId, span: Span) { - debug!("finalizing import uses for {}", + debug!("finalizing import uses for {:?}", self.session.codemap().span_to_snippet(span)); if !self.used_imports.contains(&(id, TypeNS)) && diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 8bb94216b4d..dc13f2e331b 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -548,7 +548,7 @@ impl Module { impl fmt::Show for Module { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}, kind: {}, {}", + write!(f, "{:?}, kind: {:?}, {}", self.def_id, self.kind, if self.is_public { "public" } else { "private" } ) @@ -689,7 +689,7 @@ impl NameBindings { /// Records a type definition. fn define_type(&self, def: Def, sp: Span, modifiers: DefModifiers) { - debug!("defining type for def {} with modifiers {}", def, modifiers); + debug!("defining type for def {:?} with modifiers {:?}", def, modifiers); // Merges the type with the existing type def or creates a new one. let type_def = self.type_def.borrow().clone(); match type_def { @@ -714,7 +714,7 @@ impl NameBindings { /// Records a value definition. fn define_value(&self, def: Def, sp: Span, modifiers: DefModifiers) { - debug!("defining value for def {} with modifiers {}", def, modifiers); + debug!("defining value for def {:?} with modifiers {:?}", def, modifiers); *self.value_def.borrow_mut() = Some(ValueNsDef { def: def, value_span: Some(sp), @@ -1274,7 +1274,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { lp: LastPrivate) -> ResolveResult<()> { debug!("(resolving single import) resolving `{}` = `{}::{}` from \ - `{}` id {}, last private {}", + `{}` id {}, last private {:?}", token::get_name(target), self.module_to_string(&*containing_module), token::get_name(source), @@ -1377,7 +1377,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { shadowable: _ }) => { debug!("(resolving single import) found \ - import in ns {}", namespace); + import in ns {:?}", namespace); let id = import_resolution.id(namespace); // track used imports and extern crates as well this.used_imports.insert((id, namespace)); @@ -1486,7 +1486,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { match *result { BoundResult(ref target_module, ref name_bindings) => { - debug!("(resolving single import) found {} target: {}", + debug!("(resolving single import) found {:?} target: {:?}", namespace_name, name_bindings.def_for_namespace(namespace)); self.check_for_conflicting_import( @@ -1510,7 +1510,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } UnboundResult => { /* Continue. */ } UnknownResult => { - panic!("{} result should be known at this point", namespace_name); + panic!("{:?} result should be known at this point", namespace_name); } } }; @@ -2167,7 +2167,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { namespace: Namespace) -> ResolveResult<(Target, bool)> { debug!("(resolving item in lexical scope) resolving `{}` in \ - namespace {} in `{}`", + namespace {:?} in `{}`", token::get_name(name), namespace, self.module_to_string(&*module_)); @@ -2197,7 +2197,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { None => { // Not found; continue. debug!("(resolving item in lexical scope) found \ - import resolution, but not in namespace {}", + import resolution, but not in namespace {:?}", namespace); } Some(target) => { @@ -2477,7 +2477,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { match import_resolution.target_for_namespace(namespace) { None => { debug!("(resolving name in module) name found, \ - but not in namespace {}", + but not in namespace {:?}", namespace); } Some(target) => { @@ -2622,7 +2622,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { match def_like { DlDef(d @ DefUpvar(..)) => { self.session.span_bug(span, - format!("unexpected {} in bindings", d).index(&FullRange)) + format!("unexpected {:?} in bindings", d).index(&FullRange)) } DlDef(d @ DefLocal(_)) => { let node_id = d.def_id().node; @@ -3189,7 +3189,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Some(def) => { match def { (DefTrait(_), _) => { - debug!("(resolving trait) found trait def: {}", def); + debug!("(resolving trait) found trait def: {:?}", def); self.record_def(trait_reference.ref_id, def); } (def, _) => { @@ -3580,8 +3580,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { None => { match self.resolve_path(ty.id, path, TypeNS, true) { Some(def) => { - debug!("(resolving type) resolved `{}` to \ - type {}", + debug!("(resolving type) resolved `{:?}` to \ + type {:?}", token::get_ident(path.segments.last().unwrap() .identifier), def); result_def = Some(def); @@ -3799,7 +3799,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } result => { debug!("(resolving pattern) didn't find struct \ - def: {}", result); + def: {:?}", result); let msg = format!("`{}` does not name a structure", self.path_names_to_string(path)); self.resolve_error(path.span, msg.index(&FullRange)); @@ -3823,7 +3823,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { ValueNS) { Success((target, _)) => { debug!("(resolve bare identifier pattern) succeeded in \ - finding {} at {}", + finding {} at {:?}", token::get_name(name), target.bindings.value_def.borrow()); match *target.bindings.value_def.borrow() { @@ -4181,7 +4181,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { match search_result { Some(DlDef(def)) => { debug!("(resolving path in local ribs) resolved `{}` to \ - local: {}", + local: {:?}", token::get_ident(ident), def); return Some(def); @@ -4532,7 +4532,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { Some(definition) => self.record_def(expr.id, definition), result => { debug!("(resolving expression) didn't find struct \ - def: {}", result); + def: {:?}", result); let msg = format!("`{}` does not name a structure", self.path_names_to_string(path)); self.resolve_error(path.span, msg.index(&FullRange)); @@ -4719,7 +4719,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } fn record_def(&mut self, node_id: NodeId, (def, lp): (Def, LastPrivate)) { - debug!("(recording def) recording {} for {}, last private {}", + debug!("(recording def) recording {:?} for {}, last private {:?}", def, node_id, lp); assert!(match lp {LastImport{..} => false, _ => true}, "Import should only be used for `use` directives"); @@ -4731,8 +4731,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // the same conclusion! - nmatsakis Occupied(entry) => if def != *entry.get() { self.session - .bug(format!("node_id {} resolved first to {} and \ - then {}", + .bug(format!("node_id {} resolved first to {:?} and \ + then {:?}", node_id, *entry.get(), def).index(&FullRange)); diff --git a/src/librustc_resolve/record_exports.rs b/src/librustc_resolve/record_exports.rs index 84fd3c93671..67bcf152eb7 100644 --- a/src/librustc_resolve/record_exports.rs +++ b/src/librustc_resolve/record_exports.rs @@ -117,7 +117,7 @@ impl<'a, 'b, 'tcx> ExportRecorder<'a, 'b, 'tcx> { ns: Namespace) { match namebindings.def_for_namespace(ns) { Some(d) => { - debug!("(computing exports) YES: export '{}' => {}", + debug!("(computing exports) YES: export '{}' => {:?}", name, d.def_id()); exports.push(Export { name: name, @@ -125,7 +125,7 @@ impl<'a, 'b, 'tcx> ExportRecorder<'a, 'b, 'tcx> { }); } d_opt => { - debug!("(computing exports) NO: {}", d_opt); + debug!("(computing exports) NO: {:?}", d_opt); } } } diff --git a/src/librustc_trans/back/link.rs b/src/librustc_trans/back/link.rs index aff5f00e64e..26241ace76f 100644 --- a/src/librustc_trans/back/link.rs +++ b/src/librustc_trans/back/link.rs @@ -171,7 +171,7 @@ pub fn build_link_meta(sess: &Session, krate: &ast::Crate, crate_name: name, crate_hash: Svh::calculate(&sess.opts.cg.metadata, krate), }; - info!("{}", r); + info!("{:?}", r); return r; } @@ -373,7 +373,7 @@ pub fn link_binary(sess: &Session, let mut out_filenames = Vec::new(); for &crate_type in sess.crate_types.borrow().iter() { if invalid_output_for_target(sess, crate_type) { - sess.bug(format!("invalid output type `{}` for target os `{}`", + sess.bug(format!("invalid output type `{:?}` for target os `{}`", crate_type, sess.opts.target_triple).index(&FullRange)); } let out_file = link_binary_output(sess, trans, crate_type, outputs, diff --git a/src/librustc_trans/back/write.rs b/src/librustc_trans/back/write.rs index 56d7fb09662..452e81e2e0e 100644 --- a/src/librustc_trans/back/write.rs +++ b/src/librustc_trans/back/write.rs @@ -174,7 +174,7 @@ fn create_target_machine(sess: &Session) -> TargetMachineRef { "default" => llvm::RelocDefault, "dynamic-no-pic" => llvm::RelocDynamicNoPic, _ => { - sess.err(format!("{} is not a valid relocation mode", + sess.err(format!("{:?} is not a valid relocation mode", sess.opts .cg .relocation_model).index(&FullRange)); @@ -209,7 +209,7 @@ fn create_target_machine(sess: &Session) -> TargetMachineRef { "medium" => llvm::CodeModelMedium, "large" => llvm::CodeModelLarge, _ => { - sess.err(format!("{} is not a valid code model", + sess.err(format!("{:?} is not a valid code model", sess.opts .cg .code_model).index(&FullRange)); diff --git a/src/librustc_trans/save/mod.rs b/src/librustc_trans/save/mod.rs index 4ac9f1c7c93..35f168f092a 100644 --- a/src/librustc_trans/save/mod.rs +++ b/src/librustc_trans/save/mod.rs @@ -240,7 +240,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { def::DefUse(_) | def::DefMethod(..) | def::DefPrimTy(_) => { - self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {}", + self.sess.span_bug(span, format!("lookup_def_kind for unexpected item: {:?}", def).index(&FullRange)); }, } @@ -308,7 +308,7 @@ impl <'l, 'tcx> DxrVisitor<'l, 'tcx> { }, _ => { self.sess.span_bug(method.span, - format!("Container {} for method {} is not a node item {}", + format!("Container {} for method {} is not a node item {:?}", impl_id.node, method.id, self.analysis.ty_cx.map.get(impl_id.node) @@ -1444,7 +1444,8 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> { // FIXME(nrc) what are these doing here? def::DefStatic(_, _) => {} def::DefConst(..) => {} - _ => error!("unexpected definition kind when processing collected paths: {}", *def) + _ => error!("unexpected definition kind when processing collected paths: {:?}", + *def) } } for &(id, span, ref path, ref_kind) in paths_to_process.iter() { diff --git a/src/librustc_trans/trans/_match.rs b/src/librustc_trans/trans/_match.rs index 438cfe0b6c7..49b9ef5a40a 100644 --- a/src/librustc_trans/trans/_match.rs +++ b/src/librustc_trans/trans/_match.rs @@ -518,7 +518,7 @@ fn enter_opt<'a, 'p, 'blk, 'tcx>( variant_size: uint, val: ValueRef) -> Vec> { - debug!("enter_opt(bcx={}, m={}, opt={}, col={}, val={})", + debug!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})", bcx.to_str(), m.repr(bcx.tcx()), *opt, @@ -1046,7 +1046,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, // Decide what kind of branch we need let opts = get_branches(bcx, m, col); - debug!("options={}", opts); + debug!("options={:?}", opts); let mut kind = NoBranch; let mut test_val = val; debug!("test_val={}", bcx.val_to_string(test_val)); diff --git a/src/librustc_trans/trans/adt.rs b/src/librustc_trans/trans/adt.rs index 60fc29c7c83..231de71848a 100644 --- a/src/librustc_trans/trans/adt.rs +++ b/src/librustc_trans/trans/adt.rs @@ -145,7 +145,7 @@ pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } let repr = Rc::new(represent_type_uncached(cx, t)); - debug!("Represented as: {}", repr); + debug!("Represented as: {:?}", repr); cx.adt_reprs().borrow_mut().insert(t, repr.clone()); repr } @@ -482,7 +482,7 @@ fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntType { - debug!("range_to_inttype: {} {}", hint, bounds); + debug!("range_to_inttype: {:?} {:?}", hint, bounds); // Lists of sizes to try. u64 is always allowed as a fallback. #[allow(non_upper_case_globals)] static choose_shortest: &'static[IntType] = &[ @@ -533,7 +533,7 @@ pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type { } fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool { - debug!("bounds_usable: {} {}", ity, bounds); + debug!("bounds_usable: {:?} {:?}", ity, bounds); match ity { attr::SignedInt(_) => { let lllo = C_integral(ll_inttype(cx, ity), bounds.slo as u64, true); @@ -731,7 +731,7 @@ pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>, -> ValueRef { let signed; let val; - debug!("trans_get_discr r: {}", r); + debug!("trans_get_discr r: {:?}", r); match *r { CEnum(ity, min, max) => { val = load_discr(bcx, ity, scrutinee, min, max); diff --git a/src/librustc_trans/trans/base.rs b/src/librustc_trans/trans/base.rs index 3162f78e215..b0339529fd8 100644 --- a/src/librustc_trans/trans/base.rs +++ b/src/librustc_trans/trans/base.rs @@ -976,7 +976,7 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } if need_invoke(bcx) { - debug!("invoking {} at {}", bcx.val_to_string(llfn), bcx.llbb); + debug!("invoking {} at {:?}", bcx.val_to_string(llfn), bcx.llbb); for &llarg in llargs.iter() { debug!("arg: {}", bcx.val_to_string(llarg)); } @@ -996,7 +996,7 @@ pub fn invoke<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, Some(attributes)); return (llresult, normal_bcx); } else { - debug!("calling {} at {}", bcx.val_to_string(llfn), bcx.llbb); + debug!("calling {} at {:?}", bcx.val_to_string(llfn), bcx.llbb); for &llarg in llargs.iter() { debug!("arg: {}", bcx.val_to_string(llarg)); } @@ -2742,7 +2742,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { } let item = ccx.tcx().map.get(id); - debug!("get_item_val: id={} item={}", id, item); + debug!("get_item_val: id={} item={:?}", id, item); let val = match item { ast_map::NodeItem(i) => { let ty = ty::node_id_to_type(ccx.tcx(), i.id); @@ -2917,7 +2917,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef { } ref variant => { - ccx.sess().bug(format!("get_item_val(): unexpected variant: {}", + ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}", variant).index(&FullRange)) } }; diff --git a/src/librustc_trans/trans/callee.rs b/src/librustc_trans/trans/callee.rs index 498182c17e2..7b38f26913d 100644 --- a/src/librustc_trans/trans/callee.rs +++ b/src/librustc_trans/trans/callee.rs @@ -206,7 +206,7 @@ fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr) def::DefSelfTy(..) | def::DefAssociatedPath(..) => { bcx.tcx().sess.span_bug( ref_expr.span, - format!("cannot translate def {} \ + format!("cannot translate def {:?} \ to a callable thing!", def).index(&FullRange)); } } @@ -223,7 +223,7 @@ pub fn trans_fn_ref<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let _icx = push_ctxt("trans_fn_ref"); let substs = node_id_substs(ccx, node, param_substs); - debug!("trans_fn_ref(def_id={}, node={}, substs={})", + debug!("trans_fn_ref(def_id={}, node={:?}, substs={})", def_id.repr(ccx.tcx()), node, substs.repr(ccx.tcx())); @@ -386,7 +386,7 @@ pub fn trans_fn_ref_with_substs<'a, 'tcx>( let _icx = push_ctxt("trans_fn_ref_with_substs"); let tcx = ccx.tcx(); - debug!("trans_fn_ref_with_substs(def_id={}, node={}, \ + debug!("trans_fn_ref_with_substs(def_id={}, node={:?}, \ param_substs={}, substs={})", def_id.repr(tcx), node, diff --git a/src/librustc_trans/trans/cleanup.rs b/src/librustc_trans/trans/cleanup.rs index 561391400a1..92a96cd02b5 100644 --- a/src/librustc_trans/trans/cleanup.rs +++ b/src/librustc_trans/trans/cleanup.rs @@ -227,7 +227,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { bcx: Block<'blk, 'tcx>, custom_scope: CustomScopeIndex) -> Block<'blk, 'tcx> { - debug!("pop_and_trans_custom_cleanup_scope({})", custom_scope); + debug!("pop_and_trans_custom_cleanup_scope({:?})", custom_scope); assert!(self.is_valid_to_pop_custom_scope(custom_scope)); let scope = self.pop_scope(); @@ -265,7 +265,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { ptr: val, }; - debug!("schedule_lifetime_end({}, val={})", + debug!("schedule_lifetime_end({:?}, val={})", cleanup_scope, self.ccx.tn().val_to_string(val)); @@ -286,7 +286,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { zero: false }; - debug!("schedule_drop_mem({}, val={}, ty={})", + debug!("schedule_drop_mem({:?}, val={}, ty={})", cleanup_scope, self.ccx.tn().val_to_string(val), ty.repr(self.ccx.tcx())); @@ -308,7 +308,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { zero: true }; - debug!("schedule_drop_and_zero_mem({}, val={}, ty={}, zero={})", + debug!("schedule_drop_and_zero_mem({:?}, val={}, ty={}, zero={})", cleanup_scope, self.ccx.tn().val_to_string(val), ty.repr(self.ccx.tcx()), @@ -332,7 +332,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { zero: false }; - debug!("schedule_drop_immediate({}, val={}, ty={})", + debug!("schedule_drop_immediate({:?}, val={}, ty={:?})", cleanup_scope, self.ccx.tn().val_to_string(val), ty.repr(self.ccx.tcx())); @@ -348,7 +348,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { content_ty: Ty<'tcx>) { let drop = box FreeValue { ptr: val, heap: heap, content_ty: content_ty }; - debug!("schedule_free_value({}, val={}, heap={})", + debug!("schedule_free_value({:?}, val={}, heap={:?})", cleanup_scope, self.ccx.tn().val_to_string(val), heap); @@ -365,7 +365,7 @@ impl<'blk, 'tcx> CleanupMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx> { heap: Heap) { let drop = box FreeSlice { ptr: val, size: size, align: align, heap: heap }; - debug!("schedule_free_slice({}, val={}, heap={})", + debug!("schedule_free_slice({:?}, val={}, heap={:?})", cleanup_scope, self.ccx.tn().val_to_string(val), heap); @@ -549,7 +549,7 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx fn trans_cleanups_to_exit_scope(&'blk self, label: EarlyExitLabel) -> BasicBlockRef { - debug!("trans_cleanups_to_exit_scope label={} scopes={}", + debug!("trans_cleanups_to_exit_scope label={:?} scopes={}", label, self.scopes_len()); let orig_scopes_len = self.scopes_len(); @@ -675,7 +675,7 @@ impl<'blk, 'tcx> CleanupHelperMethods<'blk, 'tcx> for FunctionContext<'blk, 'tcx self.push_scope(scope); } - debug!("trans_cleanups_to_exit_scope: prev_llbb={}", prev_llbb); + debug!("trans_cleanups_to_exit_scope: prev_llbb={:?}", prev_llbb); assert_eq!(self.scopes_len(), orig_scopes_len); prev_llbb @@ -1018,7 +1018,7 @@ pub fn temporary_scope(tcx: &ty::ctxt, match tcx.region_maps.temporary_scope(id) { Some(scope) => { let r = AstScope(scope.node_id()); - debug!("temporary_scope({}) = {}", id, r); + debug!("temporary_scope({}) = {:?}", id, r); r } None => { @@ -1032,7 +1032,7 @@ pub fn var_scope(tcx: &ty::ctxt, id: ast::NodeId) -> ScopeId { let r = AstScope(tcx.region_maps.var_scope(id).node_id()); - debug!("var_scope({}) = {}", id, r); + debug!("var_scope({}) = {:?}", id, r); r } diff --git a/src/librustc_trans/trans/closure.rs b/src/librustc_trans/trans/closure.rs index 233cbe8f280..f057d4bcab8 100644 --- a/src/librustc_trans/trans/closure.rs +++ b/src/librustc_trans/trans/closure.rs @@ -108,7 +108,7 @@ pub struct EnvValue<'tcx> { impl<'tcx> EnvValue<'tcx> { pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String { - format!("{}({})", self.action, self.datum.to_string(ccx)) + format!("{:?}({})", self.action, self.datum.to_string(ccx)) } } @@ -495,7 +495,7 @@ pub fn get_or_create_declaration_if_unboxed_closure<'a, 'tcx>(ccx: &CrateContext set_inline_hint(llfn); debug!("get_or_create_declaration_if_unboxed_closure(): inserting new \ - closure {} (type {})", + closure {:?} (type {})", mono_id, ccx.tn().type_to_string(val_ty(llfn))); ccx.unboxed_closure_vals().borrow_mut().insert(mono_id, llfn); diff --git a/src/librustc_trans/trans/common.rs b/src/librustc_trans/trans/common.rs index 8596583d4a5..5d3eeb39e31 100644 --- a/src/librustc_trans/trans/common.rs +++ b/src/librustc_trans/trans/common.rs @@ -60,54 +60,54 @@ pub use trans::context::CrateContext; // Is the type's representation size known at compile time? pub fn type_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { - ty::type_contents(cx, ty).is_sized(cx) +ty::type_contents(cx, ty).is_sized(cx) } pub fn lltype_is_sized<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { - match ty.sty { - ty::ty_open(_) => true, - _ => type_is_sized(cx, ty), - } +match ty.sty { + ty::ty_open(_) => true, + _ => type_is_sized(cx, ty), +} } pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool { - match ty.sty { - ty::ty_ptr(ty::mt{ty, ..}) | - ty::ty_rptr(_, ty::mt{ty, ..}) | - ty::ty_uniq(ty) => { - !type_is_sized(cx, ty) - } - _ => { - false - } +match ty.sty { + ty::ty_ptr(ty::mt{ty, ..}) | + ty::ty_rptr(_, ty::mt{ty, ..}) | + ty::ty_uniq(ty) => { + !type_is_sized(cx, ty) } + _ => { + false + } +} } // Return the smallest part of `ty` which is unsized. Fails if `ty` is sized. // 'Smallest' here means component of the static representation of the type; not // the size of an object at runtime. pub fn unsized_part_of_type<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> { - match ty.sty { - ty::ty_str | ty::ty_trait(..) | ty::ty_vec(..) => ty, - ty::ty_struct(def_id, substs) => { - let unsized_fields: Vec<_> = - ty::struct_fields(cx, def_id, substs) - .iter() - .map(|f| f.mt.ty) - .filter(|ty| !type_is_sized(cx, *ty)) - .collect(); +match ty.sty { + ty::ty_str | ty::ty_trait(..) | ty::ty_vec(..) => ty, + ty::ty_struct(def_id, substs) => { + let unsized_fields: Vec<_> = + ty::struct_fields(cx, def_id, substs) + .iter() + .map(|f| f.mt.ty) + .filter(|ty| !type_is_sized(cx, *ty)) + .collect(); - // Exactly one of the fields must be unsized. - assert!(unsized_fields.len() == 1); + // Exactly one of the fields must be unsized. + assert!(unsized_fields.len() == 1); - unsized_part_of_type(cx, unsized_fields[0]) - } - _ => { - assert!(type_is_sized(cx, ty), - "unsized_part_of_type failed even though ty is unsized"); - panic!("called unsized_part_of_type with sized ty"); - } + unsized_part_of_type(cx, unsized_fields[0]) } + _ => { + assert!(type_is_sized(cx, ty), + "unsized_part_of_type failed even though ty is unsized"); + panic!("called unsized_part_of_type with sized ty"); + } +} } // Some things don't need cleanups during unwinding because the @@ -115,93 +115,93 @@ pub fn unsized_part_of_type<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> // that only contain scalars and shared boxes can avoid unwind // cleanups. pub fn type_needs_unwind_cleanup<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { - return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| { - type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet::new()) - }); +return memoized(ccx.needs_unwind_cleanup_cache(), ty, |ty| { + type_needs_unwind_cleanup_(ccx.tcx(), ty, &mut FnvHashSet::new()) +}); - fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>, - ty: Ty<'tcx>, - tycache: &mut FnvHashSet>) - -> bool - { - // Prevent infinite recursion - if !tycache.insert(ty) { - return false; - } - - let mut needs_unwind_cleanup = false; - ty::maybe_walk_ty(ty, |ty| { - needs_unwind_cleanup |= match ty.sty { - ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) | - ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false, - - ty::ty_enum(did, substs) => - ty::enum_variants(tcx, did).iter().any(|v| - v.args.iter().any(|&aty| { - let t = aty.subst(tcx, substs); - type_needs_unwind_cleanup_(tcx, t, tycache) - }) - ), - - _ => true - }; - !needs_unwind_cleanup - }); - needs_unwind_cleanup +fn type_needs_unwind_cleanup_<'tcx>(tcx: &ty::ctxt<'tcx>, + ty: Ty<'tcx>, + tycache: &mut FnvHashSet>) + -> bool +{ + // Prevent infinite recursion + if !tycache.insert(ty) { + return false; } + + let mut needs_unwind_cleanup = false; + ty::maybe_walk_ty(ty, |ty| { + needs_unwind_cleanup |= match ty.sty { + ty::ty_bool | ty::ty_int(_) | ty::ty_uint(_) | + ty::ty_float(_) | ty::ty_tup(_) | ty::ty_ptr(_) => false, + + ty::ty_enum(did, substs) => + ty::enum_variants(tcx, did).iter().any(|v| + v.args.iter().any(|&aty| { + let t = aty.subst(tcx, substs); + type_needs_unwind_cleanup_(tcx, t, tycache) + }) + ), + + _ => true + }; + !needs_unwind_cleanup + }); + needs_unwind_cleanup +} } pub fn type_needs_drop<'tcx>(cx: &ty::ctxt<'tcx>, - ty: Ty<'tcx>) - -> bool { - ty::type_contents(cx, ty).needs_drop(cx) + ty: Ty<'tcx>) + -> bool { +ty::type_contents(cx, ty).needs_drop(cx) } fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - ty: Ty<'tcx>) -> bool { - match ty.sty { - ty::ty_struct(def_id, substs) => { - let fields = ty::struct_fields(ccx.tcx(), def_id, substs); - fields.len() == 1 && - fields[0].name == - token::special_idents::unnamed_field.name && - type_is_immediate(ccx, fields[0].mt.ty) - } - _ => false + ty: Ty<'tcx>) -> bool { +match ty.sty { + ty::ty_struct(def_id, substs) => { + let fields = ty::struct_fields(ccx.tcx(), def_id, substs); + fields.len() == 1 && + fields[0].name == + token::special_idents::unnamed_field.name && + type_is_immediate(ccx, fields[0].mt.ty) } + _ => false +} } pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { - use trans::machine::llsize_of_alloc; - use trans::type_of::sizing_type_of; +use trans::machine::llsize_of_alloc; +use trans::type_of::sizing_type_of; - let tcx = ccx.tcx(); - let simple = ty::type_is_scalar(ty) || - ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) || - type_is_newtype_immediate(ccx, ty) || - ty::type_is_simd(tcx, ty); - if simple && !type_is_fat_ptr(tcx, ty) { - return true; - } - if !type_is_sized(tcx, ty) { - return false; - } - match ty.sty { - ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) | - ty::ty_unboxed_closure(..) => { - let llty = sizing_type_of(ccx, ty); - llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type()) - } - _ => type_is_zero_size(ccx, ty) +let tcx = ccx.tcx(); +let simple = ty::type_is_scalar(ty) || + ty::type_is_unique(ty) || ty::type_is_region_ptr(ty) || + type_is_newtype_immediate(ccx, ty) || + ty::type_is_simd(tcx, ty); +if simple && !type_is_fat_ptr(tcx, ty) { + return true; +} +if !type_is_sized(tcx, ty) { + return false; +} +match ty.sty { + ty::ty_struct(..) | ty::ty_enum(..) | ty::ty_tup(..) | + ty::ty_unboxed_closure(..) => { + let llty = sizing_type_of(ccx, ty); + llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type()) } + _ => type_is_zero_size(ccx, ty) +} } /// Identify types which have size zero at runtime. pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool { - use trans::machine::llsize_of_alloc; - use trans::type_of::sizing_type_of; - let llty = sizing_type_of(ccx, ty); - llsize_of_alloc(ccx, llty) == 0 +use trans::machine::llsize_of_alloc; +use trans::type_of::sizing_type_of; +let llty = sizing_type_of(ccx, ty); +llsize_of_alloc(ccx, llty) == 0 } /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function @@ -209,85 +209,85 @@ pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) - /// zero-size, but not all zero-size types use a `void` return type (in order to aid with C ABI /// compatibility). pub fn return_type_is_void(ccx: &CrateContext, ty: Ty) -> bool { - ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty) +ty::type_is_nil(ty) || ty::type_is_empty(ccx.tcx(), ty) } /// Generates a unique symbol based off the name given. This is used to create /// unique symbols for things like closures. pub fn gensym_name(name: &str) -> PathElem { - let num = token::gensym(name).uint(); - // use one colon which will get translated to a period by the mangler, and - // we're guaranteed that `num` is globally unique for this crate. - PathName(token::gensym(format!("{}:{}", name, num).index(&FullRange))) +let num = token::gensym(name).uint(); +// use one colon which will get translated to a period by the mangler, and +// we're guaranteed that `num` is globally unique for this crate. +PathName(token::gensym(format!("{}:{}", name, num).index(&FullRange))) } #[derive(Copy)] pub struct tydesc_info<'tcx> { - pub ty: Ty<'tcx>, - pub tydesc: ValueRef, - pub size: ValueRef, - pub align: ValueRef, - pub name: ValueRef, +pub ty: Ty<'tcx>, +pub tydesc: ValueRef, +pub size: ValueRef, +pub align: ValueRef, +pub name: ValueRef, } /* - * A note on nomenclature of linking: "extern", "foreign", and "upcall". - * - * An "extern" is an LLVM symbol we wind up emitting an undefined external - * reference to. This means "we don't have the thing in this compilation unit, - * please make sure you link it in at runtime". This could be a reference to - * C code found in a C library, or rust code found in a rust crate. - * - * Most "externs" are implicitly declared (automatically) as a result of a - * user declaring an extern _module_ dependency; this causes the rust driver - * to locate an extern crate, scan its compilation metadata, and emit extern - * declarations for any symbols used by the declaring crate. - * - * A "foreign" is an extern that references C (or other non-rust ABI) code. - * There is no metadata to scan for extern references so in these cases either - * a header-digester like bindgen, or manual function prototypes, have to - * serve as declarators. So these are usually given explicitly as prototype - * declarations, in rust code, with ABI attributes on them noting which ABI to - * link via. - * - * An "upcall" is a foreign call generated by the compiler (not corresponding - * to any user-written call in the code) into the runtime library, to perform - * some helper task such as bringing a task to life, allocating memory, etc. - * - */ +* A note on nomenclature of linking: "extern", "foreign", and "upcall". +* +* An "extern" is an LLVM symbol we wind up emitting an undefined external +* reference to. This means "we don't have the thing in this compilation unit, +* please make sure you link it in at runtime". This could be a reference to +* C code found in a C library, or rust code found in a rust crate. +* +* Most "externs" are implicitly declared (automatically) as a result of a +* user declaring an extern _module_ dependency; this causes the rust driver +* to locate an extern crate, scan its compilation metadata, and emit extern +* declarations for any symbols used by the declaring crate. +* +* A "foreign" is an extern that references C (or other non-rust ABI) code. +* There is no metadata to scan for extern references so in these cases either +* a header-digester like bindgen, or manual function prototypes, have to +* serve as declarators. So these are usually given explicitly as prototype +* declarations, in rust code, with ABI attributes on them noting which ABI to +* link via. +* +* An "upcall" is a foreign call generated by the compiler (not corresponding +* to any user-written call in the code) into the runtime library, to perform +* some helper task such as bringing a task to life, allocating memory, etc. +* +*/ #[derive(Copy)] pub struct NodeInfo { - pub id: ast::NodeId, - pub span: Span, +pub id: ast::NodeId, +pub span: Span, } pub fn expr_info(expr: &ast::Expr) -> NodeInfo { - NodeInfo { id: expr.id, span: expr.span } +NodeInfo { id: expr.id, span: expr.span } } pub struct BuilderRef_res { - pub b: BuilderRef, +pub b: BuilderRef, } impl Drop for BuilderRef_res { - fn drop(&mut self) { - unsafe { - llvm::LLVMDisposeBuilder(self.b); - } +fn drop(&mut self) { + unsafe { + llvm::LLVMDisposeBuilder(self.b); } } +} pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res { - BuilderRef_res { - b: b - } +BuilderRef_res { + b: b +} } pub type ExternMap = FnvHashMap; pub fn validate_substs(substs: &Substs) { - assert!(substs.types.all(|t| !ty::type_needs_infer(*t))); +assert!(substs.types.all(|t| !ty::type_needs_infer(*t))); } // work around bizarre resolve errors @@ -297,183 +297,183 @@ type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>; // Function context. Every LLVM function we create will have one of // these. pub struct FunctionContext<'a, 'tcx: 'a> { - // The ValueRef returned from a call to llvm::LLVMAddFunction; the - // address of the first instruction in the sequence of - // instructions for this function that will go in the .text - // section of the executable we're generating. - pub llfn: ValueRef, +// The ValueRef returned from a call to llvm::LLVMAddFunction; the +// address of the first instruction in the sequence of +// instructions for this function that will go in the .text +// section of the executable we're generating. +pub llfn: ValueRef, - // always an empty parameter-environment - pub param_env: ty::ParameterEnvironment<'a, 'tcx>, +// always an empty parameter-environment +pub param_env: ty::ParameterEnvironment<'a, 'tcx>, - // The environment argument in a closure. - pub llenv: Option, +// The environment argument in a closure. +pub llenv: Option, - // A pointer to where to store the return value. If the return type is - // immediate, this points to an alloca in the function. Otherwise, it's a - // pointer to the hidden first parameter of the function. After function - // construction, this should always be Some. - pub llretslotptr: Cell>, +// A pointer to where to store the return value. If the return type is +// immediate, this points to an alloca in the function. Otherwise, it's a +// pointer to the hidden first parameter of the function. After function +// construction, this should always be Some. +pub llretslotptr: Cell>, - // These pub elements: "hoisted basic blocks" containing - // administrative activities that have to happen in only one place in - // the function, due to LLVM's quirks. - // A marker for the place where we want to insert the function's static - // allocas, so that LLVM will coalesce them into a single alloca call. - pub alloca_insert_pt: Cell>, - pub llreturn: Cell>, +// These pub elements: "hoisted basic blocks" containing +// administrative activities that have to happen in only one place in +// the function, due to LLVM's quirks. +// A marker for the place where we want to insert the function's static +// allocas, so that LLVM will coalesce them into a single alloca call. +pub alloca_insert_pt: Cell>, +pub llreturn: Cell>, - // If the function has any nested return's, including something like: - // fn foo() -> Option { Some(Foo { x: return None }) }, then - // we use a separate alloca for each return - pub needs_ret_allocas: bool, +// If the function has any nested return's, including something like: +// fn foo() -> Option { Some(Foo { x: return None }) }, then +// we use a separate alloca for each return +pub needs_ret_allocas: bool, - // The a value alloca'd for calls to upcalls.rust_personality. Used when - // outputting the resume instruction. - pub personality: Cell>, +// The a value alloca'd for calls to upcalls.rust_personality. Used when +// outputting the resume instruction. +pub personality: Cell>, - // True if the caller expects this fn to use the out pointer to - // return. Either way, your code should write into the slot llretslotptr - // points to, but if this value is false, that slot will be a local alloca. - pub caller_expects_out_pointer: bool, +// True if the caller expects this fn to use the out pointer to +// return. Either way, your code should write into the slot llretslotptr +// points to, but if this value is false, that slot will be a local alloca. +pub caller_expects_out_pointer: bool, - // Maps the DefId's for local variables to the allocas created for - // them in llallocas. - pub lllocals: RefCell>>, +// Maps the DefId's for local variables to the allocas created for +// them in llallocas. +pub lllocals: RefCell>>, - // Same as above, but for closure upvars - pub llupvars: RefCell>, +// Same as above, but for closure upvars +pub llupvars: RefCell>, - // The NodeId of the function, or -1 if it doesn't correspond to - // a user-defined function. - pub id: ast::NodeId, +// The NodeId of the function, or -1 if it doesn't correspond to +// a user-defined function. +pub id: ast::NodeId, - // If this function is being monomorphized, this contains the type - // substitutions used. - pub param_substs: &'a Substs<'tcx>, +// If this function is being monomorphized, this contains the type +// substitutions used. +pub param_substs: &'a Substs<'tcx>, - // The source span and nesting context where this function comes from, for - // error reporting and symbol generation. - pub span: Option, +// The source span and nesting context where this function comes from, for +// error reporting and symbol generation. +pub span: Option, - // The arena that blocks are allocated from. - pub block_arena: &'a TypedArena>, +// The arena that blocks are allocated from. +pub block_arena: &'a TypedArena>, - // This function's enclosing crate context. - pub ccx: &'a CrateContext<'a, 'tcx>, +// This function's enclosing crate context. +pub ccx: &'a CrateContext<'a, 'tcx>, - // Used and maintained by the debuginfo module. - pub debug_context: debuginfo::FunctionDebugContext, +// Used and maintained by the debuginfo module. +pub debug_context: debuginfo::FunctionDebugContext, - // Cleanup scopes. - pub scopes: RefCell>>, +// Cleanup scopes. +pub scopes: RefCell>>, - pub cfg: Option, +pub cfg: Option, } impl<'a, 'tcx> FunctionContext<'a, 'tcx> { - pub fn arg_pos(&self, arg: uint) -> uint { - let arg = self.env_arg_pos() + arg; - if self.llenv.is_some() { - arg + 1 - } else { - arg +pub fn arg_pos(&self, arg: uint) -> uint { + let arg = self.env_arg_pos() + arg; + if self.llenv.is_some() { + arg + 1 + } else { + arg + } +} + +pub fn env_arg_pos(&self) -> uint { + if self.caller_expects_out_pointer { + 1u + } else { + 0u + } +} + +pub fn cleanup(&self) { + unsafe { + llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt + .get() + .unwrap()); + } +} + +pub fn get_llreturn(&self) -> BasicBlockRef { + if self.llreturn.get().is_none() { + + self.llreturn.set(Some(unsafe { + llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, + "return\0".as_ptr() as *const _) + })) + } + + self.llreturn.get().unwrap() +} + +pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>, + output: ty::FnOutput<'tcx>, + name: &str) -> ValueRef { + if self.needs_ret_allocas { + base::alloca_no_lifetime(bcx, match output { + ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type), + ty::FnDiverging => Type::void(bcx.ccx()) + }, name) + } else { + self.llretslotptr.get().unwrap() + } +} + +pub fn new_block(&'a self, + is_lpad: bool, + name: &str, + opt_node_id: Option) + -> Block<'a, 'tcx> { + unsafe { + let name = CString::from_slice(name.as_bytes()); + let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), + self.llfn, + name.as_ptr()); + BlockS::new(llbb, is_lpad, opt_node_id, self) + } +} + +pub fn new_id_block(&'a self, + name: &str, + node_id: ast::NodeId) + -> Block<'a, 'tcx> { + self.new_block(false, name, Some(node_id)) +} + +pub fn new_temp_block(&'a self, + name: &str) + -> Block<'a, 'tcx> { + self.new_block(false, name, None) +} + +pub fn join_blocks(&'a self, + id: ast::NodeId, + in_cxs: &[Block<'a, 'tcx>]) + -> Block<'a, 'tcx> { + let out = self.new_id_block("join", id); + let mut reachable = false; + for bcx in in_cxs.iter() { + if !bcx.unreachable.get() { + build::Br(*bcx, out.llbb); + reachable = true; } } - - pub fn env_arg_pos(&self) -> uint { - if self.caller_expects_out_pointer { - 1u - } else { - 0u - } + if !reachable { + build::Unreachable(out); } + return out; +} - pub fn cleanup(&self) { - unsafe { - llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt - .get() - .unwrap()); - } - } - - pub fn get_llreturn(&self) -> BasicBlockRef { - if self.llreturn.get().is_none() { - - self.llreturn.set(Some(unsafe { - llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn, - "return\0".as_ptr() as *const _) - })) - } - - self.llreturn.get().unwrap() - } - - pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>, - output: ty::FnOutput<'tcx>, - name: &str) -> ValueRef { - if self.needs_ret_allocas { - base::alloca_no_lifetime(bcx, match output { - ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type), - ty::FnDiverging => Type::void(bcx.ccx()) - }, name) - } else { - self.llretslotptr.get().unwrap() - } - } - - pub fn new_block(&'a self, - is_lpad: bool, - name: &str, - opt_node_id: Option) - -> Block<'a, 'tcx> { - unsafe { - let name = CString::from_slice(name.as_bytes()); - let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), - self.llfn, - name.as_ptr()); - BlockS::new(llbb, is_lpad, opt_node_id, self) - } - } - - pub fn new_id_block(&'a self, - name: &str, - node_id: ast::NodeId) - -> Block<'a, 'tcx> { - self.new_block(false, name, Some(node_id)) - } - - pub fn new_temp_block(&'a self, - name: &str) - -> Block<'a, 'tcx> { - self.new_block(false, name, None) - } - - pub fn join_blocks(&'a self, - id: ast::NodeId, - in_cxs: &[Block<'a, 'tcx>]) - -> Block<'a, 'tcx> { - let out = self.new_id_block("join", id); - let mut reachable = false; - for bcx in in_cxs.iter() { - if !bcx.unreachable.get() { - build::Br(*bcx, out.llbb); - reachable = true; - } - } - if !reachable { - build::Unreachable(out); - } - return out; - } - - pub fn monomorphize(&self, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone - { - monomorphize::apply_param_substs(self.ccx.tcx(), - self.param_substs, - value) - } +pub fn monomorphize(&self, value: &T) -> T + where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone +{ + monomorphize::apply_param_substs(self.ccx.tcx(), + self.param_substs, + value) +} } // Basic block context. We create a block context for each basic block @@ -482,277 +482,277 @@ impl<'a, 'tcx> FunctionContext<'a, 'tcx> { // with many basic blocks per function. All the basic blocks attached to a // function are organized as a directed graph. pub struct BlockS<'blk, 'tcx: 'blk> { - // The BasicBlockRef returned from a call to - // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic - // block to the function pointed to by llfn. We insert - // instructions into that block by way of this block context. - // The block pointing to this one in the function's digraph. - pub llbb: BasicBlockRef, - pub terminated: Cell, - pub unreachable: Cell, +// The BasicBlockRef returned from a call to +// llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic +// block to the function pointed to by llfn. We insert +// instructions into that block by way of this block context. +// The block pointing to this one in the function's digraph. +pub llbb: BasicBlockRef, +pub terminated: Cell, +pub unreachable: Cell, - // Is this block part of a landing pad? - pub is_lpad: bool, +// Is this block part of a landing pad? +pub is_lpad: bool, - // AST node-id associated with this block, if any. Used for - // debugging purposes only. - pub opt_node_id: Option, +// AST node-id associated with this block, if any. Used for +// debugging purposes only. +pub opt_node_id: Option, - // The function context for the function to which this block is - // attached. - pub fcx: &'blk FunctionContext<'blk, 'tcx>, +// The function context for the function to which this block is +// attached. +pub fcx: &'blk FunctionContext<'blk, 'tcx>, } pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>; impl<'blk, 'tcx> BlockS<'blk, 'tcx> { - pub fn new(llbb: BasicBlockRef, - is_lpad: bool, - opt_node_id: Option, - fcx: &'blk FunctionContext<'blk, 'tcx>) - -> Block<'blk, 'tcx> { - fcx.block_arena.alloc(BlockS { - llbb: llbb, - terminated: Cell::new(false), - unreachable: Cell::new(false), - is_lpad: is_lpad, - opt_node_id: opt_node_id, - fcx: fcx - }) - } +pub fn new(llbb: BasicBlockRef, + is_lpad: bool, + opt_node_id: Option, + fcx: &'blk FunctionContext<'blk, 'tcx>) + -> Block<'blk, 'tcx> { + fcx.block_arena.alloc(BlockS { + llbb: llbb, + terminated: Cell::new(false), + unreachable: Cell::new(false), + is_lpad: is_lpad, + opt_node_id: opt_node_id, + fcx: fcx + }) +} - pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> { - self.fcx.ccx - } - pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> { - self.fcx.ccx.tcx() - } - pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() } +pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> { + self.fcx.ccx +} +pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> { + self.fcx.ccx.tcx() +} +pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() } - pub fn ident(&self, ident: Ident) -> String { - token::get_ident(ident).get().to_string() - } +pub fn ident(&self, ident: Ident) -> String { + token::get_ident(ident).get().to_string() +} - pub fn node_id_to_string(&self, id: ast::NodeId) -> String { - self.tcx().map.node_to_string(id).to_string() - } +pub fn node_id_to_string(&self, id: ast::NodeId) -> String { + self.tcx().map.node_to_string(id).to_string() +} - pub fn expr_to_string(&self, e: &ast::Expr) -> String { - e.repr(self.tcx()) - } +pub fn expr_to_string(&self, e: &ast::Expr) -> String { + e.repr(self.tcx()) +} - pub fn def(&self, nid: ast::NodeId) -> def::Def { - match self.tcx().def_map.borrow().get(&nid) { - Some(v) => v.clone(), - None => { - self.tcx().sess.bug(format!( - "no def associated with node id {}", nid).index(&FullRange)); - } +pub fn def(&self, nid: ast::NodeId) -> def::Def { + match self.tcx().def_map.borrow().get(&nid) { + Some(v) => v.clone(), + None => { + self.tcx().sess.bug(format!( + "no def associated with node id {}", nid).index(&FullRange)); } } +} - pub fn val_to_string(&self, val: ValueRef) -> String { - self.ccx().tn().val_to_string(val) - } +pub fn val_to_string(&self, val: ValueRef) -> String { + self.ccx().tn().val_to_string(val) +} - pub fn llty_str(&self, ty: Type) -> String { - self.ccx().tn().type_to_string(ty) - } +pub fn llty_str(&self, ty: Type) -> String { + self.ccx().tn().type_to_string(ty) +} - pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { - t.repr(self.tcx()) - } +pub fn ty_to_string(&self, t: Ty<'tcx>) -> String { + t.repr(self.tcx()) +} - pub fn to_str(&self) -> String { - format!("[block {:p}]", self) - } +pub fn to_str(&self) -> String { + format!("[block {:p}]", self) +} - pub fn monomorphize(&self, value: &T) -> T - where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone - { - monomorphize::apply_param_substs(self.tcx(), - self.fcx.param_substs, - value) - } +pub fn monomorphize(&self, value: &T) -> T + where T : TypeFoldable<'tcx> + Repr<'tcx> + HasProjectionTypes + Clone +{ + monomorphize::apply_param_substs(self.tcx(), + self.fcx.param_substs, + value) +} } impl<'blk, 'tcx> mc::Typer<'tcx> for BlockS<'blk, 'tcx> { - fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { - self.tcx() - } +fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> { + self.tcx() +} - fn node_ty(&self, id: ast::NodeId) -> mc::McResult> { - Ok(node_id_type(self, id)) - } +fn node_ty(&self, id: ast::NodeId) -> mc::McResult> { + Ok(node_id_type(self, id)) +} - fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult> { - Ok(expr_ty_adjusted(self, expr)) - } +fn expr_ty_adjusted(&self, expr: &ast::Expr) -> mc::McResult> { + Ok(expr_ty_adjusted(self, expr)) +} - fn node_method_ty(&self, method_call: ty::MethodCall) -> Option> { - self.tcx() - .method_map - .borrow() - .get(&method_call) - .map(|method| monomorphize_type(self, method.ty)) - } +fn node_method_ty(&self, method_call: ty::MethodCall) -> Option> { + self.tcx() + .method_map + .borrow() + .get(&method_call) + .map(|method| monomorphize_type(self, method.ty)) +} - fn node_method_origin(&self, method_call: ty::MethodCall) - -> Option> - { - self.tcx() - .method_map - .borrow() - .get(&method_call) - .map(|method| method.origin.clone()) - } +fn node_method_origin(&self, method_call: ty::MethodCall) + -> Option> +{ + self.tcx() + .method_map + .borrow() + .get(&method_call) + .map(|method| method.origin.clone()) +} - fn adjustments<'a>(&'a self) -> &'a RefCell>> { - &self.tcx().adjustments - } +fn adjustments<'a>(&'a self) -> &'a RefCell>> { + &self.tcx().adjustments +} - fn is_method_call(&self, id: ast::NodeId) -> bool { - self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id)) - } +fn is_method_call(&self, id: ast::NodeId) -> bool { + self.tcx().method_map.borrow().contains_key(&ty::MethodCall::expr(id)) +} - fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option { - self.tcx().region_maps.temporary_scope(rvalue_id) - } +fn temporary_scope(&self, rvalue_id: ast::NodeId) -> Option { + self.tcx().region_maps.temporary_scope(rvalue_id) +} - fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option { - Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone()) - } +fn upvar_borrow(&self, upvar_id: ty::UpvarId) -> Option { + Some(self.tcx().upvar_borrow_map.borrow()[upvar_id].clone()) +} - fn capture_mode(&self, closure_expr_id: ast::NodeId) - -> ast::CaptureClause { - self.tcx().capture_modes.borrow()[closure_expr_id].clone() - } +fn capture_mode(&self, closure_expr_id: ast::NodeId) + -> ast::CaptureClause { + self.tcx().capture_modes.borrow()[closure_expr_id].clone() +} - fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool { - self.fcx.param_env.type_moves_by_default(span, ty) - } +fn type_moves_by_default(&self, span: Span, ty: Ty<'tcx>) -> bool { + self.fcx.param_env.type_moves_by_default(span, ty) +} } impl<'blk, 'tcx> ty::UnboxedClosureTyper<'tcx> for BlockS<'blk, 'tcx> { - fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> { - &self.fcx.param_env - } +fn param_env<'a>(&'a self) -> &'a ty::ParameterEnvironment<'a, 'tcx> { + &self.fcx.param_env +} - fn unboxed_closure_kind(&self, - def_id: ast::DefId) - -> ty::UnboxedClosureKind - { - let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); - typer.unboxed_closure_kind(def_id) - } +fn unboxed_closure_kind(&self, + def_id: ast::DefId) + -> ty::UnboxedClosureKind +{ + let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); + typer.unboxed_closure_kind(def_id) +} - fn unboxed_closure_type(&self, - def_id: ast::DefId, - substs: &subst::Substs<'tcx>) - -> ty::ClosureTy<'tcx> - { - let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); - typer.unboxed_closure_type(def_id, substs) - } +fn unboxed_closure_type(&self, + def_id: ast::DefId, + substs: &subst::Substs<'tcx>) + -> ty::ClosureTy<'tcx> +{ + let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); + typer.unboxed_closure_type(def_id, substs) +} - fn unboxed_closure_upvars(&self, - def_id: ast::DefId, - substs: &Substs<'tcx>) - -> Option>> - { - let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); - typer.unboxed_closure_upvars(def_id, substs) - } +fn unboxed_closure_upvars(&self, + def_id: ast::DefId, + substs: &Substs<'tcx>) + -> Option>> +{ + let typer = NormalizingUnboxedClosureTyper::new(self.tcx()); + typer.unboxed_closure_upvars(def_id, substs) +} } pub struct Result<'blk, 'tcx: 'blk> { - pub bcx: Block<'blk, 'tcx>, - pub val: ValueRef +pub bcx: Block<'blk, 'tcx>, +pub val: ValueRef } impl<'b, 'tcx> Result<'b, 'tcx> { - pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> { - Result { - bcx: bcx, - val: val, - } +pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> { + Result { + bcx: bcx, + val: val, } } +} pub fn val_ty(v: ValueRef) -> Type { - unsafe { - Type::from_ref(llvm::LLVMTypeOf(v)) - } +unsafe { + Type::from_ref(llvm::LLVMTypeOf(v)) +} } // LLVM constant constructors. pub fn C_null(t: Type) -> ValueRef { - unsafe { - llvm::LLVMConstNull(t.to_ref()) - } +unsafe { + llvm::LLVMConstNull(t.to_ref()) +} } pub fn C_undef(t: Type) -> ValueRef { - unsafe { - llvm::LLVMGetUndef(t.to_ref()) - } +unsafe { + llvm::LLVMGetUndef(t.to_ref()) +} } pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef { - unsafe { - llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool) - } +unsafe { + llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool) +} } pub fn C_floating(s: &str, t: Type) -> ValueRef { - unsafe { - let s = CString::from_slice(s.as_bytes()); - llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr()) - } +unsafe { + let s = CString::from_slice(s.as_bytes()); + llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr()) +} } pub fn C_nil(ccx: &CrateContext) -> ValueRef { - C_struct(ccx, &[], false) +C_struct(ccx, &[], false) } pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef { - C_integral(Type::i1(ccx), val as u64, false) +C_integral(Type::i1(ccx), val as u64, false) } pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef { - C_integral(Type::i32(ccx), i as u64, true) +C_integral(Type::i32(ccx), i as u64, true) } pub fn C_i64(ccx: &CrateContext, i: i64) -> ValueRef { - C_integral(Type::i64(ccx), i as u64, true) +C_integral(Type::i64(ccx), i as u64, true) } pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef { - C_integral(Type::i64(ccx), i, false) +C_integral(Type::i64(ccx), i, false) } pub fn C_int(ccx: &CrateContext, i: I) -> ValueRef { - let v = i.as_i64(); +let v = i.as_i64(); - match machine::llbitsize_of_real(ccx, ccx.int_type()) { - 32 => assert!(v < (1<<31) && v >= -(1<<31)), - 64 => {}, - n => panic!("unsupported target size: {}", n) - } +match machine::llbitsize_of_real(ccx, ccx.int_type()) { + 32 => assert!(v < (1<<31) && v >= -(1<<31)), + 64 => {}, + n => panic!("unsupported target size: {}", n) +} - C_integral(ccx.int_type(), v as u64, true) +C_integral(ccx.int_type(), v as u64, true) } pub fn C_uint(ccx: &CrateContext, i: I) -> ValueRef { - let v = i.as_u64(); +let v = i.as_u64(); - match machine::llbitsize_of_real(ccx, ccx.int_type()) { - 32 => assert!(v < (1<<32)), - 64 => {}, - n => panic!("unsupported target size: {}", n) - } +match machine::llbitsize_of_real(ccx, ccx.int_type()) { + 32 => assert!(v < (1<<32)), + 64 => {}, + n => panic!("unsupported target size: {}", n) +} - C_integral(ccx.int_type(), v, false) +C_integral(ccx.int_type(), v, false) } pub trait AsI64 { fn as_i64(self) -> i64; } @@ -769,346 +769,346 @@ impl AsU64 for u32 { fn as_u64(self) -> u64 { self as u64 }} impl AsU64 for uint { fn as_u64(self) -> u64 { self as u64 }} pub fn C_u8(ccx: &CrateContext, i: uint) -> ValueRef { - C_integral(Type::i8(ccx), i as u64, false) +C_integral(Type::i8(ccx), i as u64, false) } // This is a 'c-like' raw string, which differs from // our boxed-and-length-annotated strings. pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef { - unsafe { - match cx.const_cstr_cache().borrow().get(&s) { - Some(&llval) => return llval, - None => () - } - - let sc = llvm::LLVMConstStringInContext(cx.llcx(), - s.get().as_ptr() as *const c_char, - s.get().len() as c_uint, - !null_terminated as Bool); - - let gsym = token::gensym("str"); - let buf = CString::from_vec(format!("str{}", gsym.uint()).into_bytes()); - let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr()); - llvm::LLVMSetInitializer(g, sc); - llvm::LLVMSetGlobalConstant(g, True); - llvm::SetLinkage(g, llvm::InternalLinkage); - - cx.const_cstr_cache().borrow_mut().insert(s, g); - g +unsafe { + match cx.const_cstr_cache().borrow().get(&s) { + Some(&llval) => return llval, + None => () } + + let sc = llvm::LLVMConstStringInContext(cx.llcx(), + s.get().as_ptr() as *const c_char, + s.get().len() as c_uint, + !null_terminated as Bool); + + let gsym = token::gensym("str"); + let buf = CString::from_vec(format!("str{}", gsym.uint()).into_bytes()); + let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(sc).to_ref(), buf.as_ptr()); + llvm::LLVMSetInitializer(g, sc); + llvm::LLVMSetGlobalConstant(g, True); + llvm::SetLinkage(g, llvm::InternalLinkage); + + cx.const_cstr_cache().borrow_mut().insert(s, g); + g +} } // NB: Do not use `do_spill_noroot` to make this into a constant string, or // you will be kicked off fast isel. See issue #4352 for an example of this. pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef { - let len = s.get().len(); - let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx)); - C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)]) +let len = s.get().len(); +let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx)); +C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)]) } pub fn C_binary_slice(cx: &CrateContext, data: &[u8]) -> ValueRef { - unsafe { - let len = data.len(); - let lldata = C_bytes(cx, data); +unsafe { + let len = data.len(); + let lldata = C_bytes(cx, data); - let gsym = token::gensym("binary"); - let name = format!("binary{}", gsym.uint()); - let name = CString::from_vec(name.into_bytes()); - let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), - name.as_ptr()); - llvm::LLVMSetInitializer(g, lldata); - llvm::LLVMSetGlobalConstant(g, True); - llvm::SetLinkage(g, llvm::InternalLinkage); + let gsym = token::gensym("binary"); + let name = format!("binary{}", gsym.uint()); + let name = CString::from_vec(name.into_bytes()); + let g = llvm::LLVMAddGlobal(cx.llmod(), val_ty(lldata).to_ref(), + name.as_ptr()); + llvm::LLVMSetInitializer(g, lldata); + llvm::LLVMSetGlobalConstant(g, True); + llvm::SetLinkage(g, llvm::InternalLinkage); - let cs = consts::ptrcast(g, Type::i8p(cx)); - C_struct(cx, &[cs, C_uint(cx, len)], false) - } + let cs = consts::ptrcast(g, Type::i8p(cx)); + C_struct(cx, &[cs, C_uint(cx, len)], false) +} } pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef { - C_struct_in_context(cx.llcx(), elts, packed) +C_struct_in_context(cx.llcx(), elts, packed) } pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef { - unsafe { - llvm::LLVMConstStructInContext(llcx, - elts.as_ptr(), elts.len() as c_uint, - packed as Bool) - } +unsafe { + llvm::LLVMConstStructInContext(llcx, + elts.as_ptr(), elts.len() as c_uint, + packed as Bool) +} } pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef { - unsafe { - llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint) - } +unsafe { + llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint) +} } pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef { - unsafe { - return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint); - } +unsafe { + return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint); +} } pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef { - C_bytes_in_context(cx.llcx(), bytes) +C_bytes_in_context(cx.llcx(), bytes) } pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef { - unsafe { - let ptr = bytes.as_ptr() as *const c_char; - return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True); - } +unsafe { + let ptr = bytes.as_ptr() as *const c_char; + return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True); +} } pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint]) - -> ValueRef { - unsafe { - let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint); + -> ValueRef { +unsafe { + let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint); - debug!("const_get_elt(v={}, us={}, r={})", - cx.tn().val_to_string(v), us, cx.tn().val_to_string(r)); + debug!("const_get_elt(v={}, us={:?}, r={})", + cx.tn().val_to_string(v), us, cx.tn().val_to_string(r)); - return r; - } + return r; +} } pub fn is_const(v: ValueRef) -> bool { - unsafe { - llvm::LLVMIsConstant(v) == True - } +unsafe { + llvm::LLVMIsConstant(v) == True +} } pub fn const_to_int(v: ValueRef) -> i64 { - unsafe { - llvm::LLVMConstIntGetSExtValue(v) - } +unsafe { + llvm::LLVMConstIntGetSExtValue(v) +} } pub fn const_to_uint(v: ValueRef) -> u64 { - unsafe { - llvm::LLVMConstIntGetZExtValue(v) - } +unsafe { + llvm::LLVMConstIntGetZExtValue(v) +} } pub fn is_undef(val: ValueRef) -> bool { - unsafe { - llvm::LLVMIsUndef(val) != False - } +unsafe { + llvm::LLVMIsUndef(val) != False +} } #[allow(dead_code)] // potentially useful pub fn is_null(val: ValueRef) -> bool { - unsafe { - llvm::LLVMIsNull(val) != False - } +unsafe { + llvm::LLVMIsNull(val) != False +} } pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> { - bcx.fcx.monomorphize(&t) +bcx.fcx.monomorphize(&t) } pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> { - let tcx = bcx.tcx(); - let t = ty::node_id_to_type(tcx, id); - monomorphize_type(bcx, t) +let tcx = bcx.tcx(); +let t = ty::node_id_to_type(tcx, id); +monomorphize_type(bcx, t) } pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> { - node_id_type(bcx, ex.id) +node_id_type(bcx, ex.id) } pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &ast::Expr) -> Ty<'tcx> { - monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex)) +monomorphize_type(bcx, ty::expr_ty_adjusted(bcx.tcx(), ex)) } /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should /// guarantee to us that all nested obligations *could be* resolved if we wanted to. pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - span: Span, - trait_ref: ty::PolyTraitRef<'tcx>) - -> traits::Vtable<'tcx, ()> + span: Span, + trait_ref: ty::PolyTraitRef<'tcx>) + -> traits::Vtable<'tcx, ()> { - let tcx = ccx.tcx(); +let tcx = ccx.tcx(); - // Remove any references to regions; this helps improve caching. - let trait_ref = ty_fold::erase_regions(tcx, trait_ref); +// Remove any references to regions; this helps improve caching. +let trait_ref = ty_fold::erase_regions(tcx, trait_ref); - // First check the cache. - match ccx.trait_cache().borrow().get(&trait_ref) { - Some(vtable) => { - info!("Cache hit: {}", trait_ref.repr(ccx.tcx())); - return (*vtable).clone(); - } - None => { } +// First check the cache. +match ccx.trait_cache().borrow().get(&trait_ref) { + Some(vtable) => { + info!("Cache hit: {}", trait_ref.repr(ccx.tcx())); + return (*vtable).clone(); } + None => { } +} - debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx())); +debug!("trans fulfill_obligation: trait_ref={}", trait_ref.repr(ccx.tcx())); - ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id()); - let infcx = infer::new_infer_ctxt(tcx); +ty::populate_implementations_for_trait_if_necessary(tcx, trait_ref.def_id()); +let infcx = infer::new_infer_ctxt(tcx); - // Do the initial selection for the obligation. This yields the - // shallow result we are looking for -- that is, what specific impl. - let typer = NormalizingUnboxedClosureTyper::new(tcx); - let mut selcx = traits::SelectionContext::new(&infcx, &typer); - let obligation = traits::Obligation::new(traits::ObligationCause::dummy(), - trait_ref.to_poly_trait_predicate()); - let selection = match selcx.select(&obligation) { - Ok(Some(selection)) => selection, - Ok(None) => { - // Ambiguity can happen when monomorphizing during trans - // expands to some humongo type that never occurred - // statically -- this humongo type can then overflow, - // leading to an ambiguous result. So report this as an - // overflow bug, since I believe this is the only case - // where ambiguity can result. - debug!("Encountered ambiguity selecting `{}` during trans, \ - presuming due to overflow", - trait_ref.repr(tcx)); - ccx.sess().span_fatal( - span, - "reached the recursion limit during monomorphization"); - } - Err(e) => { - tcx.sess.span_bug( - span, - format!("Encountered error `{}` selecting `{}` during trans", - e.repr(tcx), - trait_ref.repr(tcx)).index(&FullRange)) - } - }; +// Do the initial selection for the obligation. This yields the +// shallow result we are looking for -- that is, what specific impl. +let typer = NormalizingUnboxedClosureTyper::new(tcx); +let mut selcx = traits::SelectionContext::new(&infcx, &typer); +let obligation = traits::Obligation::new(traits::ObligationCause::dummy(), + trait_ref.to_poly_trait_predicate()); +let selection = match selcx.select(&obligation) { + Ok(Some(selection)) => selection, + Ok(None) => { + // Ambiguity can happen when monomorphizing during trans + // expands to some humongo type that never occurred + // statically -- this humongo type can then overflow, + // leading to an ambiguous result. So report this as an + // overflow bug, since I believe this is the only case + // where ambiguity can result. + debug!("Encountered ambiguity selecting `{}` during trans, \ + presuming due to overflow", + trait_ref.repr(tcx)); + ccx.sess().span_fatal( + span, + "reached the recursion limit during monomorphization"); + } + Err(e) => { + tcx.sess.span_bug( + span, + format!("Encountered error `{}` selecting `{}` during trans", + e.repr(tcx), + trait_ref.repr(tcx)).index(&FullRange)) + } +}; - // Currently, we use a fulfillment context to completely resolve - // all nested obligations. This is because they can inform the - // inference of the impl's type parameters. - let mut fulfill_cx = traits::FulfillmentContext::new(); - let vtable = selection.map_move_nested(|predicate| { - fulfill_cx.register_predicate_obligation(&infcx, predicate); - }); - let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable); +// Currently, we use a fulfillment context to completely resolve +// all nested obligations. This is because they can inform the +// inference of the impl's type parameters. +let mut fulfill_cx = traits::FulfillmentContext::new(); +let vtable = selection.map_move_nested(|predicate| { + fulfill_cx.register_predicate_obligation(&infcx, predicate); +}); +let vtable = drain_fulfillment_cx(span, &infcx, &mut fulfill_cx, &vtable); - info!("Cache miss: {}", trait_ref.repr(ccx.tcx())); - ccx.trait_cache().borrow_mut().insert(trait_ref, - vtable.clone()); +info!("Cache miss: {}", trait_ref.repr(ccx.tcx())); +ccx.trait_cache().borrow_mut().insert(trait_ref, + vtable.clone()); - vtable +vtable } pub struct NormalizingUnboxedClosureTyper<'a,'tcx:'a> { - param_env: ty::ParameterEnvironment<'a, 'tcx> +param_env: ty::ParameterEnvironment<'a, 'tcx> } impl<'a,'tcx> NormalizingUnboxedClosureTyper<'a,'tcx> { - pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> { - // Parameter environment is used to give details about type parameters, - // but since we are in trans, everything is fully monomorphized. - NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) } - } +pub fn new(tcx: &'a ty::ctxt<'tcx>) -> NormalizingUnboxedClosureTyper<'a,'tcx> { + // Parameter environment is used to give details about type parameters, + // but since we are in trans, everything is fully monomorphized. + NormalizingUnboxedClosureTyper { param_env: ty::empty_parameter_environment(tcx) } +} } impl<'a,'tcx> ty::UnboxedClosureTyper<'tcx> for NormalizingUnboxedClosureTyper<'a,'tcx> { - fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> { - &self.param_env - } +fn param_env<'b>(&'b self) -> &'b ty::ParameterEnvironment<'b,'tcx> { + &self.param_env +} - fn unboxed_closure_kind(&self, - def_id: ast::DefId) - -> ty::UnboxedClosureKind - { - self.param_env.tcx.unboxed_closure_kind(def_id) - } +fn unboxed_closure_kind(&self, + def_id: ast::DefId) + -> ty::UnboxedClosureKind +{ + self.param_env.tcx.unboxed_closure_kind(def_id) +} - fn unboxed_closure_type(&self, - def_id: ast::DefId, - substs: &subst::Substs<'tcx>) - -> ty::ClosureTy<'tcx> - { - // the substitutions in `substs` are already monomorphized, - // but we still must normalize associated types - let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs); - monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty) - } +fn unboxed_closure_type(&self, + def_id: ast::DefId, + substs: &subst::Substs<'tcx>) + -> ty::ClosureTy<'tcx> +{ + // the substitutions in `substs` are already monomorphized, + // but we still must normalize associated types + let closure_ty = self.param_env.tcx.unboxed_closure_type(def_id, substs); + monomorphize::normalize_associated_type(self.param_env.tcx, &closure_ty) +} - fn unboxed_closure_upvars(&self, - def_id: ast::DefId, - substs: &Substs<'tcx>) - -> Option>> - { - // the substitutions in `substs` are already monomorphized, - // but we still must normalize associated types - let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs); - monomorphize::normalize_associated_type(self.param_env.tcx, &result) - } +fn unboxed_closure_upvars(&self, + def_id: ast::DefId, + substs: &Substs<'tcx>) + -> Option>> +{ + // the substitutions in `substs` are already monomorphized, + // but we still must normalize associated types + let result = ty::unboxed_closure_upvars(&self.param_env, def_id, substs); + monomorphize::normalize_associated_type(self.param_env.tcx, &result) +} } pub fn drain_fulfillment_cx<'a,'tcx,T>(span: Span, - infcx: &infer::InferCtxt<'a,'tcx>, - fulfill_cx: &mut traits::FulfillmentContext<'tcx>, - result: &T) - -> T - where T : TypeFoldable<'tcx> + Repr<'tcx> + infcx: &infer::InferCtxt<'a,'tcx>, + fulfill_cx: &mut traits::FulfillmentContext<'tcx>, + result: &T) + -> T +where T : TypeFoldable<'tcx> + Repr<'tcx> { - debug!("drain_fulfillment_cx(result={})", - result.repr(infcx.tcx)); +debug!("drain_fulfillment_cx(result={})", + result.repr(infcx.tcx)); - // In principle, we only need to do this so long as `result` - // contains unbound type parameters. It could be a slight - // optimization to stop iterating early. - let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx); - match fulfill_cx.select_all_or_error(infcx, &typer) { - Ok(()) => { } - Err(errors) => { - if errors.iter().all(|e| e.is_overflow()) { - // See Ok(None) case above. - infcx.tcx.sess.span_fatal( - span, - "reached the recursion limit during monomorphization"); - } else { - infcx.tcx.sess.span_bug( - span, - format!("Encountered errors `{}` fulfilling during trans", - errors.repr(infcx.tcx)).index(&FullRange)); - } +// In principle, we only need to do this so long as `result` +// contains unbound type parameters. It could be a slight +// optimization to stop iterating early. +let typer = NormalizingUnboxedClosureTyper::new(infcx.tcx); +match fulfill_cx.select_all_or_error(infcx, &typer) { + Ok(()) => { } + Err(errors) => { + if errors.iter().all(|e| e.is_overflow()) { + // See Ok(None) case above. + infcx.tcx.sess.span_fatal( + span, + "reached the recursion limit during monomorphization"); + } else { + infcx.tcx.sess.span_bug( + span, + format!("Encountered errors `{}` fulfilling during trans", + errors.repr(infcx.tcx)).index(&FullRange)); } } +} - // Use freshen to simultaneously replace all type variables with - // their bindings and replace all regions with 'static. This is - // sort of overkill because we do not expect there to be any - // unbound type variables, hence no `TyFresh` types should ever be - // inserted. - result.fold_with(&mut infcx.freshener()) +// Use freshen to simultaneously replace all type variables with +// their bindings and replace all regions with 'static. This is +// sort of overkill because we do not expect there to be any +// unbound type variables, hence no `TyFresh` types should ever be +// inserted. +result.fold_with(&mut infcx.freshener()) } // Key used to lookup values supplied for type parameters in an expr. #[derive(Copy, PartialEq, Show)] pub enum ExprOrMethodCall { - // Type parameters for a path like `None::` - ExprId(ast::NodeId), +// Type parameters for a path like `None::` +ExprId(ast::NodeId), - // Type parameters for a method call like `a.foo::()` - MethodCallKey(ty::MethodCall) +// Type parameters for a method call like `a.foo::()` +MethodCallKey(ty::MethodCall) } pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, - node: ExprOrMethodCall, - param_substs: &subst::Substs<'tcx>) - -> subst::Substs<'tcx> { - let tcx = ccx.tcx(); + node: ExprOrMethodCall, + param_substs: &subst::Substs<'tcx>) + -> subst::Substs<'tcx> { +let tcx = ccx.tcx(); - let substs = match node { - ExprId(id) => { - ty::node_id_item_substs(tcx, id).substs - } - MethodCallKey(method_call) => { - (*tcx.method_map.borrow())[method_call].substs.clone() - } - }; +let substs = match node { + ExprId(id) => { + ty::node_id_item_substs(tcx, id).substs + } + MethodCallKey(method_call) => { + (*tcx.method_map.borrow())[method_call].substs.clone() + } +}; - if substs.types.any(|t| ty::type_needs_infer(*t)) { - tcx.sess.bug(format!("type parameters for node {} include inference types: {}", +if substs.types.any(|t| ty::type_needs_infer(*t)) { + tcx.sess.bug(format!("type parameters for node {:?} include inference types: {:?}", node, substs.repr(tcx)).index(&FullRange)); } diff --git a/src/librustc_trans/trans/consts.rs b/src/librustc_trans/trans/consts.rs index f9b14e1de4f..b0474d7e011 100644 --- a/src/librustc_trans/trans/consts.rs +++ b/src/librustc_trans/trans/consts.rs @@ -32,7 +32,7 @@ use syntax::ptr::P; pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit) -> ValueRef { let _icx = push_ctxt("trans_lit"); - debug!("const_lit: {}", lit); + debug!("const_lit: {:?}", lit); match lit.node { ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false), ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false), @@ -187,7 +187,7 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr) None => { } Some(adj) => { match adj { - ty::AdjustReifyFnPointer(_def_id) => { + ty::AdjustReifyFnPointer(_def_id) => { // FIXME(#19925) once fn item types are // zero-sized, we'll need to do something here } @@ -259,7 +259,7 @@ pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr) cx.sess() .span_bug(e.span, format!("unimplemented const \ - autoref {}", + autoref {:?}", autoref).index(&FullRange)) } } diff --git a/src/librustc_trans/trans/controlflow.rs b/src/librustc_trans/trans/controlflow.rs index 67e8b4f686a..86f0cbf7933 100644 --- a/src/librustc_trans/trans/controlflow.rs +++ b/src/librustc_trans/trans/controlflow.rs @@ -436,7 +436,7 @@ pub fn trans_break_cont<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, match bcx.tcx().def_map.borrow().get(&expr_id) { Some(&def::DefLabel(loop_id)) => loop_id, ref r => { - bcx.tcx().sess.bug(format!("{} in def-map for label", + bcx.tcx().sess.bug(format!("{:?} in def-map for label", r).index(&FullRange)) } } diff --git a/src/librustc_trans/trans/datum.rs b/src/librustc_trans/trans/datum.rs index 6a1df82056d..26518d4092f 100644 --- a/src/librustc_trans/trans/datum.rs +++ b/src/librustc_trans/trans/datum.rs @@ -552,7 +552,7 @@ impl<'tcx, K: KindOps + fmt::Show> Datum<'tcx, K> { #[allow(dead_code)] // useful for debugging pub fn to_string<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> String { - format!("Datum({}, {}, {})", + format!("Datum({}, {}, {:?})", ccx.tn().val_to_string(self.val), ty_to_string(ccx.tcx(), self.ty), self.kind) diff --git a/src/librustc_trans/trans/debuginfo.rs b/src/librustc_trans/trans/debuginfo.rs index ec2db9ca9b5..dd612a06bca 100644 --- a/src/librustc_trans/trans/debuginfo.rs +++ b/src/librustc_trans/trans/debuginfo.rs @@ -473,7 +473,7 @@ impl<'tcx> TypeMap<'tcx> { &mut unique_type_id); }, _ => { - cx.sess().bug(format!("get_unique_type_id_of_type() - unexpected type: {}, {}", + cx.sess().bug(format!("get_unique_type_id_of_type() - unexpected type: {}, {:?}", ppaux::ty_to_string(cx.tcx(), type_).index(&FullRange), type_.sty).index(&FullRange)) } @@ -798,14 +798,14 @@ pub fn create_global_var_metadata(cx: &CrateContext, format!("debuginfo::\ create_global_var_metadata() - Captured var-id refers to \ - unexpected ast_item variant: {}", + unexpected ast_item variant: {:?}", var_item).index(&FullRange)) } } }, _ => cx.sess().bug(format!("debuginfo::create_global_var_metadata() \ - Captured var-id refers to unexpected \ - ast_map variant: {}", + ast_map variant: {:?}", var_item).index(&FullRange)) }; @@ -914,7 +914,7 @@ pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, format!( "debuginfo::create_captured_var_metadata() - \ Captured var-id refers to unexpected \ - ast_map variant: {}", + ast_map variant: {:?}", ast_item).index(&FullRange)); } } @@ -924,7 +924,7 @@ pub fn create_captured_var_metadata<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, .span_bug(span, format!("debuginfo::create_captured_var_metadata() - \ Captured var-id refers to unexpected \ - ast_map variant: {}", + ast_map variant: {:?}", ast_item).index(&FullRange)); } }; @@ -1321,7 +1321,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, _ => { cx.sess() .bug(format!("create_function_debug_context: \ - unexpected sort of node: {}", + unexpected sort of node: {:?}", fnitem).index(&FullRange)) } } @@ -1332,7 +1332,7 @@ pub fn create_function_debug_context<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, return FunctionDebugContext::FunctionWithoutDebugInfo; } _ => cx.sess().bug(format!("create_function_debug_context: \ - unexpected sort of node: {}", + unexpected sort of node: {:?}", fnitem).index(&FullRange)) }; @@ -1615,7 +1615,7 @@ fn compile_unit_metadata(cx: &CrateContext) -> DIDescriptor { } }; - debug!("compile_unit_metadata: {}", compile_unit_name); + debug!("compile_unit_metadata: {:?}", compile_unit_name); let producer = format!("rustc version {}", (option_env!("CFG_VERSION")).expect("CFG_VERSION")); @@ -1769,7 +1769,7 @@ fn scope_metadata(fcx: &FunctionContext, let node = fcx.ccx.tcx().map.get(node_id); fcx.ccx.sess().span_bug(error_reporting_span, - format!("debuginfo: Could not find scope info for node {}", + format!("debuginfo: Could not find scope info for node {:?}", node).index(&FullRange)); } } @@ -1789,7 +1789,7 @@ fn diverging_type_metadata(cx: &CrateContext) -> DIType { fn basic_type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> DIType { - debug!("basic_type_metadata: {}", t); + debug!("basic_type_metadata: {:?}", t); let (name, encoding) = match t.sty { ty::ty_tup(ref elements) if elements.is_empty() => @@ -2931,7 +2931,7 @@ fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, } }; - debug!("type_metadata: {}", t); + debug!("type_metadata: {:?}", t); let sty = &t.sty; let MetadataCreationResult { metadata, already_stored_in_typemap } = match *sty { @@ -3011,7 +3011,7 @@ fn type_metadata<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, usage_site_span).finalize(cx) } _ => { - cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {}", + cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {:?}", sty).index(&FullRange)) } }; @@ -4022,7 +4022,7 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc node, None => { cx.sess().bug(format!("debuginfo::namespace_for_item(): \ - path too short for {}", + path too short for {:?}", def_id).index(&FullRange)); } } diff --git a/src/librustc_trans/trans/expr.rs b/src/librustc_trans/trans/expr.rs index da19fc52c8c..c8db661e9c6 100644 --- a/src/librustc_trans/trans/expr.rs +++ b/src/librustc_trans/trans/expr.rs @@ -306,7 +306,7 @@ fn apply_adjustments<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, // FIXME(#19596) workaround: `|t| t` causes monomorphization recursion fn identity(t: T) -> T { t } - debug!("unsized_info(kind={}, id={}, unadjusted_ty={})", + debug!("unsized_info(kind={:?}, id={}, unadjusted_ty={})", kind, id, unadjusted_ty.repr(bcx.tcx())); match kind { &ty::UnsizeLength(len) => C_uint(bcx.ccx(), len), @@ -623,7 +623,7 @@ fn trans_datum_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bcx.tcx().sess.span_bug( expr.span, format!("trans_rvalue_datum_unadjusted reached \ - fall-through case: {}", + fall-through case: {:?}", expr.node).index(&FullRange)); } } @@ -972,7 +972,7 @@ fn trans_rvalue_stmt_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bcx.tcx().sess.span_bug( expr.span, format!("trans_rvalue_stmt_unadjusted reached \ - fall-through case: {}", + fall-through case: {:?}", expr.node).index(&FullRange)); } } @@ -1177,7 +1177,7 @@ fn trans_rvalue_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, bcx.tcx().sess.span_bug( expr.span, format!("trans_rvalue_dps_unadjusted reached fall-through \ - case: {}", + case: {:?}", expr.node).index(&FullRange)); } } @@ -1227,7 +1227,7 @@ fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } _ => { bcx.tcx().sess.span_bug(ref_expr.span, format!( - "Non-DPS def {} referened by {}", + "Non-DPS def {:?} referened by {}", def, bcx.node_id_to_string(ref_expr.id)).index(&FullRange)); } } @@ -1255,7 +1255,7 @@ pub fn trans_def_fn_unadjusted<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, } _ => { ccx.tcx().sess.span_bug(ref_expr.span, format!( - "trans_def_fn_unadjusted invoked on: {} for {}", + "trans_def_fn_unadjusted invoked on: {:?} for {}", def, ref_expr.repr(ccx.tcx())).index(&FullRange)); } @@ -1296,7 +1296,7 @@ pub fn trans_local_var<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } _ => { bcx.sess().unimpl(format!( - "unsupported def type in trans_local_var: {}", + "unsupported def type in trans_local_var: {:?}", def).index(&FullRange)); } } @@ -2042,7 +2042,7 @@ fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out), _ => { ccx.sess().bug(format!("translating unsupported cast: \ - {} ({}) -> {} ({})", + {} ({:?}) -> {} ({:?})", t_in.repr(bcx.tcx()), k_in, t_out.repr(bcx.tcx()), @@ -2051,7 +2051,7 @@ fn trans_imm_cast<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } } _ => ccx.sess().bug(format!("translating unsupported cast: \ - {} ({}) -> {} ({})", + {} ({:?}) -> {} ({:?})", t_in.repr(bcx.tcx()), k_in, t_out.repr(bcx.tcx()), @@ -2137,7 +2137,7 @@ fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, -> DatumBlock<'blk, 'tcx, Expr> { let ccx = bcx.ccx(); - debug!("deref_once(expr={}, datum={}, method_call={})", + debug!("deref_once(expr={}, datum={}, method_call={:?})", expr.repr(bcx.tcx()), datum.to_string(ccx), method_call); @@ -2221,7 +2221,7 @@ fn deref_once<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, } }; - debug!("deref_once(expr={}, method_call={}, result={})", + debug!("deref_once(expr={}, method_call={:?}, result={})", expr.id, method_call, r.datum.to_string(ccx)); return r; diff --git a/src/librustc_trans/trans/meth.rs b/src/librustc_trans/trans/meth.rs index 53ce8dd64b8..1dcdad302d3 100644 --- a/src/librustc_trans/trans/meth.rs +++ b/src/librustc_trans/trans/meth.rs @@ -135,7 +135,7 @@ pub fn trans_method_callee<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, }) => { let trait_ref = ty::Binder(bcx.monomorphize(trait_ref)); let span = bcx.tcx().map.span(method_call.expr_id); - debug!("method_call={} trait_ref={}", + debug!("method_call={:?} trait_ref={}", method_call, trait_ref.repr(bcx.tcx())); let origin = fulfill_obligation(bcx.ccx(), @@ -177,7 +177,7 @@ pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, let _icx = push_ctxt("meth::trans_static_method_callee"); let tcx = ccx.tcx(); - debug!("trans_static_method_callee(method_id={}, trait_id={}, \ + debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \ expr_id={})", method_id, ty::item_path_str(tcx, trait_id), @@ -201,7 +201,7 @@ pub fn trans_static_method_callee<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, } else { csearch::get_item_path(tcx, method_id).last().unwrap().name() }; - debug!("trans_static_method_callee: method_id={}, expr_id={}, \ + debug!("trans_static_method_callee: method_id={:?}, expr_id={}, \ name={}", method_id, expr_id, token::get_name(mname)); // Find the substitutions for the fn itself. This includes diff --git a/src/librustc_trans/trans/monomorphize.rs b/src/librustc_trans/trans/monomorphize.rs index df67866e5b0..e2594765f4f 100644 --- a/src/librustc_trans/trans/monomorphize.rs +++ b/src/librustc_trans/trans/monomorphize.rs @@ -42,7 +42,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, debug!("monomorphic_fn(\ fn_id={}, \ real_substs={}, \ - ref_id={})", + ref_id={:?})", fn_id.repr(ccx.tcx()), psubsts.repr(ccx.tcx()), ref_id); @@ -73,7 +73,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, debug!("monomorphic_fn(\ fn_id={}, \ psubsts={}, \ - hash_id={})", + hash_id={:?})", fn_id.repr(ccx.tcx()), psubsts.repr(ccx.tcx()), hash_id); @@ -83,7 +83,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ccx.sess(), ccx.tcx().map.find(fn_id.node), || { - format!("while monomorphizing {}, couldn't find it in \ + format!("while monomorphizing {:?}, couldn't find it in \ the item map (may have attempted to monomorphize \ an item defined in a different crate?)", fn_id) @@ -249,7 +249,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, d } _ => { - ccx.sess().bug(format!("can't monomorphize a {}", + ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).index(&FullRange)) } } @@ -275,7 +275,7 @@ pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ast_map::NodeBlock(..) | ast_map::NodePat(..) | ast_map::NodeLocal(..) => { - ccx.sess().bug(format!("can't monomorphize a {}", + ccx.sess().bug(format!("can't monomorphize a {:?}", map_node).index(&FullRange)) } }; diff --git a/src/librustc_trans/trans/type_of.rs b/src/librustc_trans/trans/type_of.rs index 34cd0188048..40cf11783ad 100644 --- a/src/librustc_trans/trans/type_of.rs +++ b/src/librustc_trans/trans/type_of.rs @@ -277,7 +277,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { None => () } - debug!("type_of {} {}", t.repr(cx.tcx()), t.sty); + debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty); // Replace any typedef'd types with their equivalent non-typedef // type. This ensures that all LLVM nominal types that contain @@ -288,7 +288,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { if t != t_norm { let llty = type_of(cx, t_norm); - debug!("--> normalized {} {} to {} {} llty={}", + debug!("--> normalized {} {:?} to {} {:?} llty={}", t.repr(cx.tcx()), t, t_norm.repr(cx.tcx()), @@ -407,7 +407,7 @@ pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type { ty::ty_err(..) => cx.sess().bug("type_of with ty_err"), }; - debug!("--> mapped t={} {} to llty={}", + debug!("--> mapped t={} {:?} to llty={}", t.repr(cx.tcx()), t, cx.tn().type_to_string(llty)); @@ -457,7 +457,7 @@ pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, let tstr = if strings.is_empty() { base } else { - format!("{}<{}>", base, strings) + format!("{}<{:?}>", base, strings) }; if did.krate == 0 { diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index a2b1c32f0a5..265ebe00d53 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -571,7 +571,7 @@ fn ast_path_to_trait_ref<'a,'tcx>( mut projections: Option<&mut Vec>>) -> Rc> { - debug!("ast_path_to_trait_ref {}", path); + debug!("ast_path_to_trait_ref {:?}", path); let trait_def = this.get_trait_def(trait_def_id); // the trait reference introduces a binding level here, so @@ -1185,7 +1185,7 @@ pub fn ast_ty_to_ty<'tcx>( _ => { tcx.sess.span_fatal(ast_ty.span, format!("found value name used \ - as a type: {}", + as a type: {:?}", a_def).index(&FullRange)); } } @@ -1631,7 +1631,7 @@ fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>, builtin_bounds: ty::BuiltinBounds) -> Option { - debug!("compute_opt_region_bound(explicit_region_bounds={}, \ + debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \ principal_trait_ref={}, builtin_bounds={})", explicit_region_bounds, principal_trait_ref.repr(tcx), diff --git a/src/librustc_typeck/check/closure.rs b/src/librustc_typeck/check/closure.rs index 9945e264bfc..00791157569 100644 --- a/src/librustc_typeck/check/closure.rs +++ b/src/librustc_typeck/check/closure.rs @@ -82,7 +82,7 @@ fn check_unboxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, expected_sig: Option>) { let expr_def_id = ast_util::local_def(expr.id); - debug!("check_unboxed_closure kind={} expected_sig={}", + debug!("check_unboxed_closure kind={:?} expected_sig={}", kind, expected_sig.repr(fcx.tcx())); @@ -134,7 +134,7 @@ fn check_unboxed_closure<'a,'tcx>(fcx: &FnCtxt<'a,'tcx>, // the `unboxed_closures` table. fn_ty.sig.0.inputs = vec![ty::mk_tup(fcx.tcx(), fn_ty.sig.0.inputs)]; - debug!("unboxed_closure for {} --> sig={} kind={}", + debug!("unboxed_closure for {} --> sig={} kind={:?}", expr_def_id.repr(fcx.tcx()), fn_ty.sig.repr(fcx.tcx()), kind); @@ -186,7 +186,7 @@ fn deduce_unboxed_closure_expectations_from_trait_ref<'a,'tcx>( None => { return None; } }; - debug!("found object type {}", kind); + debug!("found object type {:?}", kind); let arg_param_ty = *trait_ref.substs().types.get(subst::TypeSpace, 0); let arg_param_ty = fcx.infcx().resolve_type_vars_if_possible(&arg_param_ty); diff --git a/src/librustc_typeck/check/method/confirm.rs b/src/librustc_typeck/check/method/confirm.rs index 652540bde70..2471bc85bc9 100644 --- a/src/librustc_typeck/check/method/confirm.rs +++ b/src/librustc_typeck/check/method/confirm.rs @@ -200,7 +200,7 @@ impl<'a,'tcx> ConfirmContext<'a,'tcx> { match pick.kind { probe::InherentImplPick(impl_def_id) => { assert!(ty::impl_trait_ref(self.tcx(), impl_def_id).is_none(), - "impl {} is not an inherent impl", impl_def_id); + "impl {:?} is not an inherent impl", impl_def_id); let impl_polytype = check::impl_self_ty(self.fcx, self.span, impl_def_id); (impl_polytype.substs, MethodStatic(pick.method_ty.def_id)) diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index f495885bd10..87ea082b6b2 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -231,7 +231,7 @@ pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, Some(self_expr) => { debug!("lookup_in_trait_adjusted: inserting adjustment if needed \ - (self-id={}, base adjustment={}, explicit_self={})", + (self-id={}, base adjustment={:?}, explicit_self={:?})", self_expr.id, autoderefref, method_ty.explicit_self); match method_ty.explicit_self { @@ -275,7 +275,7 @@ pub fn lookup_in_trait_adjusted<'a, 'tcx>(fcx: &'a FnCtxt<'a, 'tcx>, fcx.tcx().sess.span_bug( span, format!( - "unexpected explicit self type in operator method: {}", + "unexpected explicit self type in operator method: {:?}", method_ty.explicit_self).index(&FullRange)); } } diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 3bc29bb9ef7..4ba161fa835 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -267,7 +267,7 @@ impl<'a,'tcx> ProbeContext<'a,'tcx> { return; // already visited } - debug!("assemble_inherent_impl_probe {}", impl_def_id); + debug!("assemble_inherent_impl_probe {:?}", impl_def_id); let method = match impl_method(self.tcx(), impl_def_id, self.method_name) { Some(m) => m, @@ -1024,7 +1024,7 @@ fn trait_method<'tcx>(tcx: &ty::ctxt<'tcx>, -> Option<(uint, Rc>)> { let trait_items = ty::trait_items(tcx, trait_def_id); - debug!("trait_method; items: {}", trait_items); + debug!("trait_method; items: {:?}", trait_items); trait_items .iter() .filter(|item| @@ -1126,7 +1126,7 @@ impl<'tcx> Repr<'tcx> for CandidateKind<'tcx> { impl<'tcx> Repr<'tcx> for CandidateStep<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { - format!("CandidateStep({},{})", + format!("CandidateStep({},{:?})", self.self_ty.repr(tcx), self.adjustment) } @@ -1134,19 +1134,19 @@ impl<'tcx> Repr<'tcx> for CandidateStep<'tcx> { impl<'tcx> Repr<'tcx> for PickAdjustment { fn repr(&self, _tcx: &ty::ctxt) -> String { - format!("{}", self) + format!("{:?}", self) } } impl<'tcx> Repr<'tcx> for PickKind<'tcx> { fn repr(&self, _tcx: &ty::ctxt) -> String { - format!("{}", self) + format!("{:?}", self) } } impl<'tcx> Repr<'tcx> for Pick<'tcx> { fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String { - format!("Pick(method_ty={}, adjustment={}, kind={})", + format!("Pick(method_ty={}, adjustment={:?}, kind={:?})", self.method_ty.repr(tcx), self.adjustment, self.kind) diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 1b94d93b8dc..c60851b9228 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -1690,7 +1690,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } pub fn tag(&self) -> String { - format!("{}", self as *const FnCtxt) + format!("{:?}", self as *const FnCtxt) } pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> { @@ -1886,7 +1886,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { fn register_unsize_obligations(&self, span: Span, unsize: &ty::UnsizeKind<'tcx>) { - debug!("register_unsize_obligations: unsize={}", unsize); + debug!("register_unsize_obligations: unsize={:?}", unsize); match *unsize { ty::UnsizeLength(..) => {} @@ -2392,7 +2392,7 @@ fn try_index_step<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)> { let tcx = fcx.tcx(); - debug!("try_index_step(expr={}, base_expr.id={}, adjusted_ty={}, adjustment={}, index_ty={})", + debug!("try_index_step(expr={}, base_expr.id={}, adjusted_ty={}, adjustment={:?}, index_ty={})", expr.repr(tcx), base_expr.repr(tcx), adjusted_ty.repr(tcx), @@ -2651,7 +2651,7 @@ fn check_argument_types<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, err_args(fcx.tcx(), supplied_arg_count) }; - debug!("check_argument_types: formal_tys={}", + debug!("check_argument_types: formal_tys={:?}", formal_tys.iter().map(|t| fcx.infcx().ty_to_string(*t)).collect::>()); // Check the arguments. @@ -3101,7 +3101,7 @@ fn check_expr_with_unifier<'a, 'tcx, F>(fcx: &FnCtxt<'a, 'tcx>, } }; - debug!("adjusted_ty={} adjustment={}", + debug!("adjusted_ty={} adjustment={:?}", adj_ty.repr(fcx.tcx()), adjustment); @@ -5052,7 +5052,7 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, } assert_eq!(segment_spaces.len(), path.segments.len()); - debug!("segment_spaces={}", segment_spaces); + debug!("segment_spaces={:?}", segment_spaces); // Next, examine the definition, and determine how many type // parameters we expect from each space. @@ -5276,7 +5276,7 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>, .take_while(|d| d.default.is_none()) .count(); - debug!("adjust_type_parameters(space={}, \ + debug!("adjust_type_parameters(space={:?}, \ provided_len={}, \ desired_len={}, \ required_len={})", diff --git a/src/librustc_typeck/check/regionck.rs b/src/librustc_typeck/check/regionck.rs index ffb721dd7ac..7974e99c521 100644 --- a/src/librustc_typeck/check/regionck.rs +++ b/src/librustc_typeck/check/regionck.rs @@ -188,7 +188,7 @@ fn region_of_def(fcx: &FnCtxt, def: def::Def) -> ty::Region { } } _ => { - tcx.sess.bug(format!("unexpected def in region_of_def: {}", + tcx.sess.bug(format!("unexpected def in region_of_def: {:?}", def).index(&FullRange)) } } @@ -484,7 +484,7 @@ fn visit_expr(rcx: &mut Rcx, expr: &ast::Expr) { // Check any autoderefs or autorefs that appear. for &adjustment in rcx.fcx.inh.adjustments.borrow().get(&expr.id).iter() { - debug!("adjustment={}", adjustment); + debug!("adjustment={:?}", adjustment); match *adjustment { ty::AdjustDerefRef(ty::AutoDerefRef {autoderefs, autoref: ref opt_autoref}) => { let expr_ty = rcx.resolve_node_type(expr.id); @@ -828,7 +828,7 @@ fn check_expr_fn_block(rcx: &mut Rcx, debug!("constrain_free_variables({}, {})", region_bound.repr(tcx), expr.repr(tcx)); for freevar in freevars.iter() { - debug!("freevar def is {}", freevar.def); + debug!("freevar def is {:?}", freevar.def); // Identify the variable being closed over and its node-id. let def = freevar.def; @@ -1038,7 +1038,7 @@ fn type_of_node_must_outlive<'a, 'tcx>( rcx.fcx.inh.adjustments.borrow().get(&id), |method_call| rcx.resolve_method_type(method_call)); debug!("constrain_regions_in_type_of_node(\ - ty={}, ty0={}, id={}, minimum_lifetime={})", + ty={}, ty0={}, id={}, minimum_lifetime={:?})", ty_to_string(tcx, ty), ty_to_string(tcx, ty0), id, minimum_lifetime); type_must_outlive(rcx, origin, ty, minimum_lifetime); @@ -1090,7 +1090,7 @@ fn link_match(rcx: &Rcx, discr: &ast::Expr, arms: &[ast::Arm]) { /// then ensures that the lifetime of the resulting pointer is /// linked to the lifetime of its guarantor (if any). fn link_fn_args(rcx: &Rcx, body_scope: CodeExtent, args: &[ast::Arg]) { - debug!("regionck::link_fn_args(body_scope={})", body_scope); + debug!("regionck::link_fn_args(body_scope={:?})", body_scope); let mc = mc::MemCategorizationContext::new(rcx.fcx); for arg in args.iter() { let arg_ty = rcx.fcx.node_ty(arg.id); @@ -1144,7 +1144,7 @@ fn link_autoref(rcx: &Rcx, autoderefs: uint, autoref: &ty::AutoRef) { - debug!("link_autoref(autoref={})", autoref); + debug!("link_autoref(autoref={:?})", autoref); let mc = mc::MemCategorizationContext::new(rcx.fcx); let expr_cmt = ignore_err!(mc.cat_expr_autoderefd(expr, autoderefs)); debug!("expr_cmt={}", expr_cmt.repr(rcx.tcx())); @@ -1165,7 +1165,7 @@ fn link_by_ref(rcx: &Rcx, expr: &ast::Expr, callee_scope: CodeExtent) { let tcx = rcx.tcx(); - debug!("link_by_ref(expr={}, callee_scope={})", + debug!("link_by_ref(expr={}, callee_scope={:?})", expr.repr(tcx), callee_scope); let mc = mc::MemCategorizationContext::new(rcx.fcx); let expr_cmt = ignore_err!(mc.cat_expr(expr)); diff --git a/src/librustc_typeck/check/upvar.rs b/src/librustc_typeck/check/upvar.rs index 92fda96595c..ec44d765a8e 100644 --- a/src/librustc_typeck/check/upvar.rs +++ b/src/librustc_typeck/check/upvar.rs @@ -134,7 +134,7 @@ impl<'a,'tcx> SeedBorrowKind<'a,'tcx> { let var_node_id = freevar.def.local_node_id(); let upvar_id = ty::UpvarId { var_id: var_node_id, closure_expr_id: expr.id }; - debug!("seed upvar_id {}", upvar_id); + debug!("seed upvar_id {:?}", upvar_id); let origin = UpvarRegion(upvar_id, expr.span); let freevar_region = self.infcx().next_region_var(origin); let upvar_borrow = ty::UpvarBorrow { kind: ty::ImmBorrow, @@ -269,7 +269,7 @@ impl<'a,'tcx> AdjustBorrowKind<'a,'tcx>{ upvar_id: ty::UpvarId, upvar_borrow: &mut ty::UpvarBorrow, kind: ty::BorrowKind) { - debug!("adjust_upvar_borrow_kind: id={} kind=({} -> {})", + debug!("adjust_upvar_borrow_kind: id={:?} kind=({:?} -> {:?})", upvar_id, upvar_borrow.kind, kind); match (upvar_borrow.kind, kind) { @@ -337,7 +337,7 @@ impl<'a,'tcx> euv::Delegate<'tcx> for AdjustBorrowKind<'a,'tcx> { bk: ty::BorrowKind, _loan_cause: euv::LoanCause) { - debug!("borrow(borrow_id={}, cmt={}, bk={})", + debug!("borrow(borrow_id={}, cmt={}, bk={:?})", borrow_id, cmt.repr(self.tcx()), bk); match bk { diff --git a/src/librustc_typeck/check/writeback.rs b/src/librustc_typeck/check/writeback.rs index 70644b6e7de..82da22eab98 100644 --- a/src/librustc_typeck/check/writeback.rs +++ b/src/librustc_typeck/check/writeback.rs @@ -287,7 +287,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { }) } }; - debug!("Adjustments for node {}: {}", id, resolved_adjustment); + debug!("Adjustments for node {}: {:?}", id, resolved_adjustment); self.tcx().adjustments.borrow_mut().insert( id, resolved_adjustment); } @@ -300,7 +300,7 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { // Resolve any method map entry match self.fcx.inh.method_map.borrow_mut().remove(&method_call) { Some(method) => { - debug!("writeback::resolve_method_map_entry(call={}, entry={})", + debug!("writeback::resolve_method_map_entry(call={:?}, entry={})", method_call, method.repr(self.tcx())); let new_method = MethodCallee { diff --git a/src/librustc_typeck/coherence/mod.rs b/src/librustc_typeck/coherence/mod.rs index 7597a410f62..a0f30788bbd 100644 --- a/src/librustc_typeck/coherence/mod.rs +++ b/src/librustc_typeck/coherence/mod.rs @@ -204,7 +204,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { trait_ref: &ty::TraitRef<'tcx>, all_impl_items: &mut Vec) { let tcx = self.crate_context.tcx; - debug!("instantiate_default_methods(impl_id={}, trait_ref={})", + debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})", impl_id, trait_ref.repr(tcx)); let impl_type_scheme = ty::lookup_item_type(tcx, impl_id); @@ -215,7 +215,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { let new_id = tcx.sess.next_node_id(); let new_did = local_def(new_id); - debug!("new_did={} trait_method={}", new_did, trait_method.repr(tcx)); + debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx)); // Create substitutions for the various trait parameters. let new_method_ty = @@ -268,7 +268,7 @@ impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> { } fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) { - debug!("add_trait_impl: base_def_id={} impl_def_id={}", + debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}", base_def_id, impl_def_id); ty::record_trait_implementation(self.crate_context.tcx, base_def_id, diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 7d52418a9db..7c13696118a 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -169,8 +169,8 @@ impl<'a, 'tcx> AstConv<'tcx> for CollectCtxt<'a, 'tcx> { } x => { self.tcx.sess.bug(format!("unexpected sort of node \ - in get_item_type_scheme(): {}", - x).as_slice()); + in get_item_type_scheme(): {:?}", + x)[]); } } } @@ -475,7 +475,7 @@ fn convert_methods<'a,'tcx,'i,I>(ccx: &CollectCtxt<'a, 'tcx>, write_ty_to_tcx(tcx, m.id, fty); - debug!("writing method type: def_id={} mty={}", + debug!("writing method type: def_id={:?} mty={}", mty.def_id, mty.repr(ccx.tcx)); tcx.impl_or_trait_items @@ -840,7 +840,7 @@ fn trait_def_of_item<'a, 'tcx>(ccx: &CollectCtxt<'a, 'tcx>, ref s => { tcx.sess.span_bug( it.span, - format!("trait_def_of_item invoked on {}", s).index(&FullRange)); + format!("trait_def_of_item invoked on {:?}", s).index(&FullRange)); } }; @@ -1201,7 +1201,7 @@ fn ty_generics<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, index: i as u32, def_id: local_def(l.lifetime.id), bounds: bounds }; - debug!("ty_generics: def for region param: {}", def); + debug!("ty_generics: def for region param: {:?}", def); result.regions.push(space, def); } @@ -1213,7 +1213,7 @@ fn ty_generics<'a,'tcx>(ccx: &CollectCtxt<'a,'tcx>, space, param, i as u32); - debug!("ty_generics: def for type param: {}, {}", + debug!("ty_generics: def for type param: {}, {:?}", def.repr(ccx.tcx), space); result.types.push(space, def); diff --git a/src/librustc_typeck/variance.rs b/src/librustc_typeck/variance.rs index 3ca0e40c51e..14243b8e773 100644 --- a/src/librustc_typeck/variance.rs +++ b/src/librustc_typeck/variance.rs @@ -243,8 +243,8 @@ enum VarianceTerm<'a> { impl<'a> fmt::Show for VarianceTerm<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ConstantTerm(c1) => write!(f, "{}", c1), - TransformTerm(v1, v2) => write!(f, "({} \u{00D7} {})", v1, v2), + ConstantTerm(c1) => write!(f, "{:?}", c1), + TransformTerm(v1, v2) => write!(f, "({:?} \u{00D7} {:?})", v1, v2), InferredTerm(id) => write!(f, "[{}]", { let InferredIndex(i) = id; i }) } } @@ -323,10 +323,10 @@ impl<'a, 'tcx> TermsContext<'a, 'tcx> { assert!(newly_added); debug!("add_inferred(item_id={}, \ - kind={}, \ + kind={:?}, \ index={}, \ param_id={}, - inf_index={})", + inf_index={:?})", item_id, kind, index, param_id, inf_index); } @@ -673,8 +673,8 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { fn add_constraint(&mut self, InferredIndex(index): InferredIndex, variance: VarianceTermPtr<'a>) { - debug!("add_constraint(index={}, variance={})", - index, variance.to_string()); + debug!("add_constraint(index={}, variance={:?})", + index, variance); self.constraints.push(Constraint { inferred: InferredIndex(index), variance: variance }); } @@ -854,7 +854,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { region_param_defs: &[ty::RegionParameterDef], substs: &subst::Substs<'tcx>, variance: VarianceTermPtr<'a>) { - debug!("add_constraints_from_substs(def_id={})", def_id); + debug!("add_constraints_from_substs(def_id={:?})", def_id); for p in type_param_defs.iter() { let variance_decl = @@ -988,14 +988,14 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { let new_value = glb(variance, old_value); if old_value != new_value { debug!("Updating inferred {} (node {}) \ - from {} to {} due to {}", + from {:?} to {:?} due to {:?}", inferred, self.terms_cx .inferred_infos[inferred] .param_id, old_value, new_value, - term.to_string()); + term); self.solutions[inferred] = new_value; changed = true; @@ -1028,7 +1028,7 @@ impl<'a, 'tcx> SolveContext<'a, 'tcx> { inferred_infos[index].item_id == item_id { let info = &inferred_infos[index]; let variance = solutions[index]; - debug!("Index {} Info {} / {} / {} Variance {}", + debug!("Index {} Info {} / {:?} / {:?} Variance {:?}", index, info.index, info.kind, info.space, variance); match info.kind { TypeParam => { diff --git a/src/librustdoc/clean/inline.rs b/src/librustdoc/clean/inline.rs index 3eda39f54a9..3e2474468ad 100644 --- a/src/librustdoc/clean/inline.rs +++ b/src/librustdoc/clean/inline.rs @@ -397,9 +397,9 @@ fn build_const(cx: &DocContext, tcx: &ty::ctxt, use syntax::print::pprust; let expr = const_eval::lookup_const_by_id(tcx, did).unwrap_or_else(|| { - panic!("expected lookup_const_by_id to succeed for {}", did); + panic!("expected lookup_const_by_id to succeed for {:?}", did); }); - debug!("converting constant expr {} to snippet", expr); + debug!("converting constant expr {:?} to snippet", expr); let sn = pprust::expr_to_string(expr); debug!("got snippet {}", sn); diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index e9feb9f1e78..bf2664bba6a 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -397,7 +397,7 @@ impl Clean for doctree::Module { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum Attribute { Word(String), List(String, Vec ), @@ -450,7 +450,7 @@ impl<'a> attr::AttrMetaMethods for &'a Attribute { fn meta_item_list(&self) -> Option<&[P]> { None } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct TyParam { pub name: String, pub did: ast::DefId, @@ -483,7 +483,7 @@ impl<'tcx> Clean for ty::TypeParameterDef<'tcx> { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum TyParamBound { RegionBound(Lifetime), TraitBound(PolyTrait, ast::TraitBoundModifier) @@ -621,7 +621,7 @@ impl<'tcx> Clean for ty::TraitRef<'tcx> { cx.external_paths.borrow_mut().as_mut().unwrap().insert(self.def_id, (fqn, TypeTrait)); - debug!("ty::TraitRef\n substs.types(TypeSpace): {}\n", + debug!("ty::TraitRef\n substs.types(TypeSpace): {:?}\n", self.substs.types.get_slice(ParamSpace::TypeSpace)); // collect any late bound regions @@ -632,7 +632,7 @@ impl<'tcx> Clean for ty::TraitRef<'tcx> { for &ty_s in ts.iter() { if let sty::ty_rptr(ref reg, _) = ty_s.sty { if let &Region::ReLateBound(_, _) = *reg { - debug!(" hit an ReLateBound {}", reg); + debug!(" hit an ReLateBound {:?}", reg); if let Some(lt) = reg.clean(cx) { late_bounds.push(lt) } @@ -674,7 +674,7 @@ impl<'tcx> Clean>> for subst::Substs<'tcx> { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct Lifetime(String); impl Lifetime { @@ -724,7 +724,7 @@ impl Clean> for ty::Region { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum WherePredicate { BoundPredicate { ty: Type, bounds: Vec }, RegionPredicate { lifetime: Lifetime, bounds: Vec}, @@ -757,7 +757,7 @@ impl Clean for ast::WherePredicate { } // maybe use a Generic enum and use ~[Generic]? -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct Generics { pub lifetimes: Vec, pub type_params: Vec, @@ -908,7 +908,7 @@ impl Clean for doctree::Function { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct ClosureDecl { pub lifetimes: Vec, pub decl: FnDecl, @@ -929,14 +929,14 @@ impl Clean for ast::ClosureTy { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct FnDecl { pub inputs: Arguments, pub output: FunctionRetTy, pub attrs: Vec, } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct Arguments { pub values: Vec, } @@ -989,7 +989,7 @@ impl<'a, 'tcx> Clean for (ast::DefId, &'a ty::PolyFnSig<'tcx>) { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct Argument { pub type_: Type, pub name: String, @@ -1006,7 +1006,7 @@ impl Clean for ast::Arg { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum FunctionRetTy { Return(Type), NoReturn @@ -1181,7 +1181,7 @@ impl<'tcx> Clean for ty::ImplOrTraitItem<'tcx> { } /// A trait reference, which may have higher ranked lifetimes. -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct PolyTrait { pub trait_: Type, pub lifetimes: Vec @@ -1190,7 +1190,7 @@ pub struct PolyTrait { /// A representation of a Type suitable for hyperlinking purposes. Ideally one can get the original /// type out of the AST/ty::ctxt given one of these, if more information is needed. Most importantly /// it does not preserve mutability or boxes. -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum Type { /// structs/enums/traits (anything that'd be an ast::TyPath) ResolvedPath { @@ -1236,7 +1236,7 @@ pub enum Type { PolyTraitRef(Vec), } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Eq, Hash, Copy, Show)] pub enum PrimitiveType { Isize, I8, I16, I32, I64, Usize, U8, U16, U32, U64, @@ -1376,7 +1376,7 @@ impl Clean for ast::Ty { Infer }, TyTypeof(..) => { - panic!("Unimplemented type {}", self.node) + panic!("Unimplemented type {:?}", self.node) }, } } @@ -1746,7 +1746,7 @@ impl Clean for syntax::codemap::Span { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct Path { pub global: bool, pub segments: Vec, @@ -1761,7 +1761,7 @@ impl Clean for ast::Path { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub enum PathParameters { AngleBracketed { lifetimes: Vec, @@ -1793,7 +1793,7 @@ impl Clean for ast::PathParameters { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct PathSegment { pub name: String, pub params: PathParameters @@ -1857,7 +1857,7 @@ impl Clean for doctree::Typedef { } } -#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq)] +#[derive(Clone, RustcEncodable, RustcDecodable, PartialEq, Show)] pub struct BareFunctionDecl { pub unsafety: ast::Unsafety, pub generics: Generics, @@ -1892,7 +1892,7 @@ pub struct Static { impl Clean for doctree::Static { fn clean(&self, cx: &DocContext) -> Item { - debug!("claning static {}: {}", self.name.clean(cx), self); + debug!("cleaning static {}: {:?}", self.name.clean(cx), self); Item { name: Some(self.name.clean(cx)), attrs: self.attrs.clean(cx), @@ -2170,7 +2170,7 @@ trait ToSource { impl ToSource for syntax::codemap::Span { fn to_src(&self, cx: &DocContext) -> String { - debug!("converting span {} to snippet", self.clean(cx)); + debug!("converting span {:?} to snippet", self.clean(cx)); let sn = match cx.sess().codemap().span_to_snippet(*self) { Some(x) => x.to_string(), None => "".to_string() @@ -2183,7 +2183,7 @@ impl ToSource for syntax::codemap::Span { fn lit_to_string(lit: &ast::Lit) -> String { match lit.node { ast::LitStr(ref st, _) => st.get().to_string(), - ast::LitBinary(ref data) => format!("{}", data), + ast::LitBinary(ref data) => format!("{:?}", data), ast::LitByte(b) => { let mut res = String::from_str("b'"); for c in (b as char).escape_default() { @@ -2202,7 +2202,7 @@ fn lit_to_string(lit: &ast::Lit) -> String { fn name_from_pat(p: &ast::Pat) -> String { use syntax::ast::*; - debug!("Trying to get a name from pattern: {}", p); + debug!("Trying to get a name from pattern: {:?}", p); match p.node { PatWild(PatWildSingle) => "_".to_string(), diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index a69437f7a66..46c212a9f2d 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -136,7 +136,7 @@ pub fn run_core(search_paths: SearchPaths, cfgs: Vec, externs: Externs, inlined: RefCell::new(Some(HashSet::new())), populated_crate_impls: RefCell::new(HashSet::new()), }; - debug!("crate: {}", ctxt.krate); + debug!("crate: {:?}", ctxt.krate); let analysis = CrateAnalysis { exported_items: exported_items, diff --git a/src/librustdoc/html/escape.rs b/src/librustdoc/html/escape.rs index b4afb67170b..99cd467cdfc 100644 --- a/src/librustdoc/html/escape.rs +++ b/src/librustdoc/html/escape.rs @@ -19,7 +19,15 @@ use std::fmt; /// string when passed to a format string. pub struct Escape<'a>(pub &'a str); +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Escape<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Escape<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Because the internet is always right, turns out there's not that many // characters to escape: http://stackoverflow.com/questions/7381974 diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index abc669729fe..b24e7a7a4cf 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -10,7 +10,7 @@ //! HTML formatting module //! -//! This module contains a large number of `fmt::Show` implementations for +//! This module contains a large number of `fmt::String` implementations for //! various types in `rustdoc::clean`. These implementations all currently //! assume that HTML output is desired, although it may be possible to redesign //! them in the future to instead emit any format desired. @@ -64,7 +64,15 @@ impl UnsafetySpace { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for TyParamBounds<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for TyParamBounds<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &TyParamBounds(bounds) = self; for (i, bound) in bounds.iter().enumerate() { @@ -77,7 +85,15 @@ impl<'a> fmt::Show for TyParamBounds<'a> { } } -impl fmt::Show for clean::Generics { +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] +impl fmt::Show for clean::Generic { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::Generics { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() == 0 && self.type_params.len() == 0 { return Ok(()) } try!(f.write_str("<")); @@ -114,7 +130,15 @@ impl fmt::Show for clean::Generics { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for WhereClause<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for WhereClause<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let &WhereClause(gens) = self; if gens.where_predicates.len() == 0 { @@ -151,14 +175,30 @@ impl<'a> fmt::Show for WhereClause<'a> { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::Lifetime { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::Lifetime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.get_ref())); Ok(()) } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::PolyTrait { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::PolyTrait { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.lifetimes.len() > 0 { try!(f.write_str("for<")); @@ -174,7 +214,15 @@ impl fmt::Show for clean::PolyTrait { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::TyParamBound { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::TyParamBound { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::RegionBound(ref lt) => { @@ -191,7 +239,15 @@ impl fmt::Show for clean::TyParamBound { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::PathParameters { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::PathParameters { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::PathParameters::AngleBracketed { ref lifetimes, ref types } => { @@ -236,14 +292,30 @@ impl fmt::Show for clean::PathParameters { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::PathSegment { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::PathSegment { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str(self.name.as_slice())); write!(f, "{}", self.params) } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::Path { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.global { try!(f.write_str("::")) @@ -429,7 +501,15 @@ fn tybounds(w: &mut fmt::Formatter, } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::Type { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::Type { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::TyParamBinder(id) => { @@ -570,7 +650,16 @@ impl fmt::Show for clean::Type { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::Arguments { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + + +impl fmt::String for clean::Arguments { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, input) in self.values.iter().enumerate() { if i > 0 { try!(write!(f, ", ")); } @@ -583,7 +672,15 @@ impl fmt::Show for clean::Arguments { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::FunctionRetTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::FunctionRetTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::Return(clean::Tuple(ref tys)) if tys.is_empty() => Ok(()), @@ -593,13 +690,29 @@ impl fmt::Show for clean::FunctionRetTy { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::FnDecl { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::FnDecl { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "({args}){arrow}", args = self.inputs, arrow = self.output) } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Method<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Method<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Method(selfty, d) = *self; let mut args = String::new(); @@ -629,7 +742,15 @@ impl<'a> fmt::Show for Method<'a> { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for VisSpace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for VisSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { Some(ast::Public) => write!(f, "pub "), @@ -638,7 +759,15 @@ impl fmt::Show for VisSpace { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for UnsafetySpace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for UnsafetySpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.get() { ast::Unsafety::Unsafe => write!(f, "unsafe "), @@ -647,7 +776,15 @@ impl fmt::Show for UnsafetySpace { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::ViewPath { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::ViewPath { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { clean::SimpleImport(ref name, ref src) => { @@ -674,7 +811,15 @@ impl fmt::Show for clean::ViewPath { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::ImportSource { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::ImportSource { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.did { Some(did) => resolved_path(f, did, &self.path, true), @@ -691,7 +836,15 @@ impl fmt::Show for clean::ImportSource { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for clean::ViewListIdent { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for clean::ViewListIdent { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.source { Some(did) => { @@ -712,7 +865,15 @@ impl fmt::Show for clean::ViewListIdent { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for MutableSpace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for MutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { MutableSpace(clean::Immutable) => Ok(()), @@ -721,7 +882,15 @@ impl fmt::Show for MutableSpace { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for RawMutableSpace { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for RawMutableSpace { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { RawMutableSpace(clean::Immutable) => write!(f, "const "), @@ -730,13 +899,21 @@ impl fmt::Show for RawMutableSpace { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Stability<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Stability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Stability(stab) = *self; match *stab { Some(ref stability) => { write!(f, "{lvl}", - lvl = stability.level.to_string(), + lvl = stability.level, reason = stability.text) } None => Ok(()) @@ -744,13 +921,21 @@ impl<'a> fmt::Show for Stability<'a> { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for ConciseStability<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for ConciseStability<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ConciseStability(stab) = *self; match *stab { Some(ref stability) => { write!(f, "", - lvl = stability.level.to_string(), + lvl = stability.level, colon = if stability.text.len() > 0 { ": " } else { "" }, reason = stability.text) } @@ -761,7 +946,15 @@ impl<'a> fmt::Show for ConciseStability<'a> { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for ModuleSummary { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for ModuleSummary { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt_inner<'a>(f: &mut fmt::Formatter, context: &mut Vec<&'a str>, diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs index 3efaf5d4914..13a06f842a2 100644 --- a/src/librustdoc/html/item_type.rs +++ b/src/librustdoc/html/item_type.rs @@ -103,7 +103,15 @@ impl ItemType { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for ItemType { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for ItemType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.to_static_str().fmt(f) } diff --git a/src/librustdoc/html/layout.rs b/src/librustdoc/html/layout.rs index d47c6010be0..f75ab3f431c 100644 --- a/src/librustdoc/html/layout.rs +++ b/src/librustdoc/html/layout.rs @@ -30,7 +30,7 @@ pub struct Page<'a> { pub keywords: &'a str } -pub fn render( +pub fn render( dst: &mut io::Writer, layout: &Layout, page: &Page, sidebar: &S, t: &T) -> io::IoResult<()> { diff --git a/src/librustdoc/html/markdown.rs b/src/librustdoc/html/markdown.rs index 3b9265cf569..f4660a81be4 100644 --- a/src/librustdoc/html/markdown.rs +++ b/src/librustdoc/html/markdown.rs @@ -14,7 +14,7 @@ //! (bundled into the rust runtime). This module self-contains the C bindings //! and necessary legwork to render markdown, and exposes all of the //! functionality through a unit-struct, `Markdown`, which has an implementation -//! of `fmt::Show`. Example usage: +//! of `fmt::String`. Example usage: //! //! ```rust,ignore //! use rustdoc::html::markdown::Markdown; @@ -41,7 +41,7 @@ use html::highlight; use html::escape::Escape; use test; -/// A unit struct which has the `fmt::Show` trait implemented. When +/// A unit struct which has the `fmt::String` trait implemented. When /// formatted, this struct will emit the HTML corresponding to the rendered /// version of the contained markdown string. pub struct Markdown<'a>(pub &'a str); @@ -172,7 +172,7 @@ pub fn render(w: &mut fmt::Formatter, s: &str, print_toc: bool) -> fmt::Result { let text = slice::from_raw_buf(&(*orig_text).data, (*orig_text).size as uint); let origtext = str::from_utf8(text).unwrap(); - debug!("docblock: ==============\n{}\n=======", text); + debug!("docblock: ==============\n{:?}\n=======", text); let rendered = if lang.is_null() { false } else { @@ -435,7 +435,15 @@ pub fn reset_headers() { TEST_IDX.with(|s| s.set(0)); } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Markdown<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Markdown<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Markdown(md) = *self; // This is actually common enough to special-case @@ -444,7 +452,15 @@ impl<'a> fmt::Show for Markdown<'a> { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for MarkdownWithToc<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for MarkdownWithToc<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let MarkdownWithToc(md) = *self; render(fmt, md.as_slice(), true) diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index a01fcd39952..17b1c09fb17 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1051,7 +1051,7 @@ impl Context { F: FnOnce(&mut Context) -> T, { if s.len() == 0 { - panic!("Unexpected empty destination: {}", self.current); + panic!("Unexpected empty destination: {:?}", self.current); } let prev = self.dst.clone(); self.dst.push(s.as_slice()); @@ -1351,8 +1351,15 @@ impl<'a> Item<'a> { } - +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Item<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Item<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { // Write the breadcrumb trail header for the top try!(write!(fmt, "\n

")); @@ -1542,7 +1549,7 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, indices.sort_by(|&i1, &i2| cmp(&items[i1], &items[i2], i1, i2)); - debug!("{}", indices); + debug!("{:?}", indices); let mut curty = None; for &idx in indices.iter() { let myitem = &items[idx]; @@ -1626,7 +1633,16 @@ fn item_module(w: &mut fmt::Formatter, cx: &Context, } struct Initializer<'a>(&'a str); + +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Initializer<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Initializer<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Initializer(s) = *self; if s.len() == 0 { return Ok(()); } @@ -2127,7 +2143,7 @@ fn render_impl(w: &mut fmt::Formatter, i: &Impl) -> fmt::Result { try!(assoc_type(w, item, typaram)); try!(write!(w, "

\n")); } - _ => panic!("can't make docs for trait item with name {}", item.name) + _ => panic!("can't make docs for trait item with name {:?}", item.name) } match item.doc_value() { Some(s) if dox => { @@ -2188,7 +2204,15 @@ fn item_typedef(w: &mut fmt::Formatter, it: &clean::Item, document(w, it) } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Sidebar<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Sidebar<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let cx = self.cx; let it = self.item; @@ -2243,7 +2267,15 @@ impl<'a> fmt::Show for Sidebar<'a> { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl<'a> fmt::Show for Source<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a> fmt::String for Source<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let Source(s) = *self; let lines = s.lines().count(); diff --git a/src/librustdoc/html/toc.rs b/src/librustdoc/html/toc.rs index 71313ea90b8..17d3f511d09 100644 --- a/src/librustdoc/html/toc.rs +++ b/src/librustdoc/html/toc.rs @@ -176,7 +176,15 @@ impl TocBuilder { } } +//NOTE(stage0): remove impl after snapshot +#[cfg(stage0)] impl fmt::Show for Toc { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Toc { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { try!(write!(fmt, "
    ")); for entry in self.entries.iter() { diff --git a/src/librustdoc/lib.rs b/src/librustdoc/lib.rs index 6e42c50f974..99c5fde47ea 100644 --- a/src/librustdoc/lib.rs +++ b/src/librustdoc/lib.rs @@ -445,7 +445,7 @@ fn json_input(input: &str) -> Result { } }; match json::from_reader(&mut input) { - Err(s) => Err(s.to_string()), + Err(s) => Err(format!("{:?}", s)), Ok(Json::Object(obj)) => { let mut obj = obj; // Make sure the schema is what we expect @@ -505,7 +505,7 @@ fn json_output(krate: clean::Crate, res: Vec , let crate_json_str = format!("{}", json::as_json(&krate)); let crate_json = match json::from_str(crate_json_str.as_slice()) { Ok(j) => j, - Err(e) => panic!("Rust generated JSON is invalid: {}", e) + Err(e) => panic!("Rust generated JSON is invalid: {:?}", e) }; json.insert("crate".to_string(), crate_json); diff --git a/src/librustdoc/test.rs b/src/librustdoc/test.rs index bded371e500..9d39b463bdd 100644 --- a/src/librustdoc/test.rs +++ b/src/librustdoc/test.rs @@ -201,7 +201,7 @@ fn runtest(test: &str, cratename: &str, libs: SearchPaths, if should_fail && out.status.success() { panic!("test executable succeeded when it should have failed"); } else if !should_fail && !out.status.success() { - panic!("test executable failed:\n{}", + panic!("test executable failed:\n{:?}", str::from_utf8(out.error.as_slice())); } } diff --git a/src/librustdoc/visit_ast.rs b/src/librustdoc/visit_ast.rs index ad67672ea6e..428b4e92a68 100644 --- a/src/librustdoc/visit_ast.rs +++ b/src/librustdoc/visit_ast.rs @@ -265,7 +265,7 @@ impl<'a, 'tcx> RustdocVisitor<'a, 'tcx> { pub fn visit_item(&mut self, item: &ast::Item, renamed: Option, om: &mut Module) { - debug!("Visiting item {}", item); + debug!("Visiting item {:?}", item); let name = renamed.unwrap_or(item.ident); match item.node { ast::ItemMod(ref m) => { diff --git a/src/libserialize/base64.rs b/src/libserialize/base64.rs index 11a49cd712f..d13d110320e 100644 --- a/src/libserialize/base64.rs +++ b/src/libserialize/base64.rs @@ -204,7 +204,7 @@ impl error::Error for FromBase64Error { } fn detail(&self) -> Option { - Some(self.to_string()) + Some(format!("{:?}", self)) } } diff --git a/src/libserialize/hex.rs b/src/libserialize/hex.rs index 542d0678526..a11eb3f7898 100644 --- a/src/libserialize/hex.rs +++ b/src/libserialize/hex.rs @@ -88,7 +88,7 @@ impl error::Error for FromHexError { } fn detail(&self) -> Option { - Some(self.to_string()) + Some(format!("{:?}", self)) } } @@ -112,7 +112,7 @@ impl FromHex for str { /// let hello_str = "Hello, World".as_bytes().to_hex(); /// println!("{}", hello_str); /// let bytes = hello_str.as_slice().from_hex().unwrap(); - /// println!("{}", bytes); + /// println!("{:?}", bytes); /// let result_str = String::from_utf8(bytes).unwrap(); /// println!("{}", result_str); /// } diff --git a/src/libserialize/json.rs b/src/libserialize/json.rs index c520b6f4723..2ffcbcccbd4 100644 --- a/src/libserialize/json.rs +++ b/src/libserialize/json.rs @@ -214,7 +214,7 @@ use unicode::str::Utf16Item; use Encodable; /// Represents a json value -#[derive(Clone, PartialEq, PartialOrd)] +#[derive(Clone, PartialEq, PartialOrd, Show)] pub enum Json { I64(i64), U64(u64), @@ -331,7 +331,7 @@ fn io_error_to_error(io: io::IoError) -> ParserError { impl std::error::Error for DecoderError { fn description(&self) -> &str { "decoder error" } - fn detail(&self) -> Option { Some(self.to_string()) } + fn detail(&self) -> Option { Some(format!("{:?}", self)) } } pub type EncodeResult = fmt::Result; @@ -1890,7 +1890,7 @@ impl> Builder { match self.token { None => {} Some(Error(e)) => { return Err(e); } - ref tok => { panic!("unexpected token {}", tok.clone()); } + ref tok => { panic!("unexpected token {:?}", tok.clone()); } } result } @@ -2005,7 +2005,7 @@ macro_rules! expect { match $e { Json::Null => Ok(()), other => Err(ExpectedError("Null".to_string(), - format!("{}", other))) + format!("{:?}", other))) } }); ($e:expr, $t:ident) => ({ @@ -2013,7 +2013,7 @@ macro_rules! expect { Json::$t(v) => Ok(v), other => { Err(ExpectedError(stringify!($t).to_string(), - format!("{}", other))) + format!("{:?}", other))) } } }) @@ -2025,20 +2025,20 @@ macro_rules! read_primitive { match self.pop() { Json::I64(f) => match num::cast(f) { Some(f) => Ok(f), - None => Err(ExpectedError("Number".to_string(), format!("{}", f))), + None => Err(ExpectedError("Number".to_string(), format!("{:?}", f))), }, Json::U64(f) => match num::cast(f) { Some(f) => Ok(f), - None => Err(ExpectedError("Number".to_string(), format!("{}", f))), + None => Err(ExpectedError("Number".to_string(), format!("{:?}", f))), }, - Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{}", f))), + Json::F64(f) => Err(ExpectedError("Integer".to_string(), format!("{:?}", f))), // re: #12967.. a type w/ numeric keys (ie HashMap etc) // is going to have a string here, as per JSON spec. Json::String(s) => match s.parse() { Some(f) => Ok(f), None => Err(ExpectedError("Number".to_string(), s)), }, - value => Err(ExpectedError("Number".to_string(), format!("{}", value))), + value => Err(ExpectedError("Number".to_string(), format!("{:?}", value))), } } } @@ -2078,7 +2078,7 @@ impl ::Decoder for Decoder { } }, Json::Null => Ok(f64::NAN), - value => Err(ExpectedError("Number".to_string(), format!("{}", value))) + value => Err(ExpectedError("Number".to_string(), format!("{:?}", value))) } } @@ -2096,7 +2096,7 @@ impl ::Decoder for Decoder { _ => () } } - Err(ExpectedError("single character string".to_string(), format!("{}", s))) + Err(ExpectedError("single character string".to_string(), format!("{:?}", s))) } fn read_str(&mut self) -> DecodeResult { @@ -2119,7 +2119,7 @@ impl ::Decoder for Decoder { let n = match o.remove(&"variant".to_string()) { Some(Json::String(s)) => s, Some(val) => { - return Err(ExpectedError("String".to_string(), format!("{}", val))) + return Err(ExpectedError("String".to_string(), format!("{:?}", val))) } None => { return Err(MissingFieldError("variant".to_string())) @@ -2132,7 +2132,7 @@ impl ::Decoder for Decoder { } }, Some(val) => { - return Err(ExpectedError("Array".to_string(), format!("{}", val))) + return Err(ExpectedError("Array".to_string(), format!("{:?}", val))) } None => { return Err(MissingFieldError("fields".to_string())) @@ -2141,7 +2141,7 @@ impl ::Decoder for Decoder { n } json => { - return Err(ExpectedError("String or Object".to_string(), format!("{}", json))) + return Err(ExpectedError("String or Object".to_string(), format!("{:?}", json))) } }; let idx = match names.iter().position(|n| *n == name.index(&FullRange)) { @@ -2440,7 +2440,7 @@ impl<'a, 'b> fmt::Writer for FormatShim<'a, 'b> { } } -impl fmt::Show for Json { +impl fmt::String for Json { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -2449,7 +2449,7 @@ impl fmt::Show for Json { } } -impl<'a> fmt::Show for PrettyJson<'a> { +impl<'a> fmt::String for PrettyJson<'a> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -2458,7 +2458,15 @@ impl<'a> fmt::Show for PrettyJson<'a> { } } +#[cfg(stage0)] +//NOTE(stage0): remove impl after snapshot impl<'a, T: Encodable> fmt::Show for AsJson<'a, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a, T: Encodable> fmt::String for AsJson<'a, T> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -2475,7 +2483,7 @@ impl<'a, T> AsPrettyJson<'a, T> { } } -impl<'a, T: Encodable> fmt::Show for AsPrettyJson<'a, T> { +impl<'a, T: Encodable> fmt::String for AsPrettyJson<'a, T> { /// Encodes a json value into a string fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut shim = FormatShim { inner: f }; @@ -3141,9 +3149,9 @@ mod tests { Ok(json) => Decodable::decode(&mut Decoder::new(json)) }; match res { - Ok(_) => panic!("`{}` parsed & decoded ok, expecting error `{}`", + Ok(_) => panic!("`{:?}` parsed & decoded ok, expecting error `{:?}`", to_parse, expected), - Err(ParseError(e)) => panic!("`{}` is not valid json: {}", + Err(ParseError(e)) => panic!("`{:?}` is not valid json: {:?}", to_parse, e), Err(e) => { assert_eq!(e, expected); @@ -3354,7 +3362,7 @@ mod tests { write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap(); match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), + Err(_) => panic!("Unable to parse json_str: {:?}", json_str), _ => {} // it parsed and we are good to go } } @@ -3370,7 +3378,7 @@ mod tests { write!(&mut mem_buf, "{}", super::as_pretty_json(&hm)).unwrap(); let json_str = from_utf8(mem_buf.index(&FullRange)).unwrap(); match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), + Err(_) => panic!("Unable to parse json_str: {:?}", json_str), _ => {} // it parsed and we are good to go } } @@ -3433,7 +3441,7 @@ mod tests { use Decodable; let json_str = "{\"1\":true}"; let json_obj = match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), + Err(_) => panic!("Unable to parse json_str: {:?}", json_str), Ok(o) => o }; let mut decoder = Decoder::new(json_obj); @@ -3446,7 +3454,7 @@ mod tests { use Decodable; let json_str = "{\"a\":true}"; let json_obj = match from_str(json_str) { - Err(_) => panic!("Unable to parse json_str: {}", json_str), + Err(_) => panic!("Unable to parse json_str: {:?}", json_str), Ok(o) => o }; let mut decoder = Decoder::new(json_obj); @@ -3465,7 +3473,7 @@ mod tests { }; let (ref expected_evt, ref expected_stack) = expected[i]; if !parser.stack().is_equal_to(expected_stack.as_slice()) { - panic!("Parser stack is not equal to {}", expected_stack); + panic!("Parser stack is not equal to {:?}", expected_stack); } assert_eq!(&evt, expected_evt); i+=1; diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index a3fc38c34e8..681f2454fa0 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -292,7 +292,7 @@ fn test_resize_policy() { /// /// // Use derived implementation to print the status of the vikings. /// for (viking, health) in vikings.iter() { -/// println!("{} has {} hp", viking, health); +/// println!("{:?} has {} hp", viking, health); /// } /// ``` #[derive(Clone)] @@ -1207,11 +1207,11 @@ impl, V: Eq, S, H: Hasher> Eq for HashMap {} #[stable] impl + Show, V: Show, S, H: Hasher> Show for HashMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{{")); + try!(write!(f, "HashMap {{")); 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, "}}") @@ -1891,10 +1891,10 @@ mod test_map { map.insert(1i, 2i); map.insert(3i, 4i); - let map_str = format!("{}", map); + let map_str = format!("{:?}", map); - assert!(map_str == "{1: 2, 3: 4}" || map_str == "{3: 4, 1: 2}"); - assert_eq!(format!("{}", empty), "{}"); + assert!(map_str == "HashMap {1i: 2i, 3i: 4i}" || map_str == "{3i: 4i, 1i: 2i}"); + assert_eq!(format!("{:?}", empty), "HashMap {}"); } #[test] diff --git a/src/libstd/collections/hash/set.rs b/src/libstd/collections/hash/set.rs index 211bfe2c10e..10e8ca6c622 100644 --- a/src/libstd/collections/hash/set.rs +++ b/src/libstd/collections/hash/set.rs @@ -88,7 +88,7 @@ use super::map::{self, HashMap, Keys, INITIAL_CAPACITY}; /// /// // Use derived implementation to print the vikings. /// for x in vikings.iter() { -/// println!("{}", x); +/// println!("{:?}", x); /// } /// ``` #[derive(Clone)] @@ -585,11 +585,11 @@ impl, S, H: Hasher> Eq for HashSet {} #[stable] impl + fmt::Show, S, H: Hasher> fmt::Show for HashSet { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - try!(write!(f, "{{")); + try!(write!(f, "HashSet {{")); for (i, x) in self.iter().enumerate() { if i != 0 { try!(write!(f, ", ")); } - try!(write!(f, "{}", *x)); + try!(write!(f, "{:?}", *x)); } write!(f, "}}") @@ -1116,10 +1116,10 @@ mod test_set { set.insert(1i); set.insert(2); - let set_str = format!("{}", set); + let set_str = format!("{:?}", set); - assert!(set_str == "{1, 2}" || set_str == "{2, 1}"); - assert_eq!(format!("{}", empty), "{}"); + assert!(set_str == "HashSet {1i, 2i}" || set_str == "{2i, 1i}"); + assert_eq!(format!("{:?}", empty), "HashSet {}"); } #[test] diff --git a/src/libstd/fmt.rs b/src/libstd/fmt.rs index 32f5f2d4536..d014f67172c 100644 --- a/src/libstd/fmt.rs +++ b/src/libstd/fmt.rs @@ -31,7 +31,7 @@ //! format!("Hello"); // => "Hello" //! format!("Hello, {}!", "world"); // => "Hello, world!" //! format!("The number is {}", 1i); // => "The number is 1" -//! format!("{}", (3i, 4i)); // => "(3, 4)" +//! format!("{:?}", (3i, 4i)); // => "(3i, 4i)" //! format!("{value}", value=4i); // => "4" //! format!("{} {}", 1i, 2u); // => "1 2" //! # } @@ -87,7 +87,7 @@ //! # fn main() { //! format!("{argument}", argument = "test"); // => "test" //! format!("{name} {}", 1i, name = 2i); // => "2 1" -//! format!("{a} {c} {b}", a="a", b=(), c=3i); // => "a 3 ()" +//! format!("{a} {c} {b}", a="a", b='b', c=3i); // => "a 3 b" //! # } //! ``` //! @@ -127,7 +127,8 @@ //! This allows multiple actual types to be formatted via `{:x}` (like `i8` as //! well as `int`). The current mapping of types to traits is: //! -//! * *nothing* ⇒ `Show` +//! * *nothing* ⇒ `String` +//! * `?` ⇒ `Show` //! * `o` ⇒ `Octal` //! * `x` ⇒ `LowerHex` //! * `X` ⇒ `UpperHex` @@ -140,8 +141,7 @@ //! `std::fmt::Binary` trait can then be formatted with `{:b}`. Implementations //! are provided for these traits for a number of primitive types by the //! standard library as well. If no format is specified (as in `{}` or `{:6}`), -//! then the format trait used is the `Show` trait. This is one of the more -//! commonly implemented traits when formatting a custom type. +//! then the format trait used is the `String` trait. //! //! When implementing a format trait for your own type, you will have to //! implement a method of the signature: @@ -175,12 +175,13 @@ //! use std::f64; //! use std::num::Float; //! +//! #[deriving(Show)] //! struct Vector2D { //! x: int, //! y: int, //! } //! -//! impl fmt::Show for Vector2D { +//! impl fmt::String for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! // The `f` value implements the `Writer` trait, which is what the //! // write! macro is expecting. Note that this formatting ignores the @@ -209,10 +210,31 @@ //! let myvector = Vector2D { x: 3, y: 4 }; //! //! println!("{}", myvector); // => "(3, 4)" +//! println!("{:?}", myvector); // => "Vector2D {x: 3i, y:4i}" //! println!("{:10.3b}", myvector); // => " 5.000" //! } //! ``` //! +//! #### fmt::String vs fmt::Show +//! +//! These two formatting traits have distinct purposes: +//! +//! - `fmt::String` implementations assert that the type can be faithfully +//! represented as a UTF-8 string at all times. It is **not** expected that +//! all types implement the `String` trait. +//! - `fmt::Show` implementations should be implemented for **all** public types. +//! Output will typically represent the internal state as faithfully as possible. +//! The purpose of the `Show` trait is to facilitate debugging Rust code. In +//! most cases, using `#[deriving(Show)]` is sufficient and recommended. +//! +//! Some examples of the output from both traits: +//! +//! ``` +//! assert_eq(format!("{} {:?}", 3i32, 4i32), "3 4i32"); +//! assert_eq(format!("{} {:?}", 'a', 'b'), "a 'b'"); +//! assert_eq(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); +//! ``` +//! //! ### Related macros //! //! There are a number of related macros in the `format!` family. The ones that @@ -393,7 +415,7 @@ use string; pub use core::fmt::{Formatter, Result, Writer, rt}; -pub use core::fmt::{Show, Octal, Binary}; +pub use core::fmt::{Show, String, Octal, Binary}; pub use core::fmt::{LowerHex, UpperHex, Pointer}; pub use core::fmt::{LowerExp, UpperExp}; pub use core::fmt::Error; diff --git a/src/libstd/io/fs.rs b/src/libstd/io/fs.rs index 0fffb2fafbe..1556ef43eb7 100644 --- a/src/libstd/io/fs.rs +++ b/src/libstd/io/fs.rs @@ -107,7 +107,7 @@ impl File { /// /// let file = match File::open_mode(&p, Open, ReadWrite) { /// Ok(f) => f, - /// Err(e) => panic!("file error: {}", e), + /// Err(e) => panic!("file error: {:?}", e), /// }; /// // do some stuff with that file /// @@ -156,7 +156,7 @@ impl File { }) } }).update_err("couldn't open path as file", |e| { - format!("{}; path={}; mode={}; access={}", e, path.display(), + format!("{:?}; path={:?}; mode={}; access={}", e, path.display(), mode_string(mode), access_string(access)) }) } @@ -211,7 +211,7 @@ impl File { pub fn fsync(&mut self) -> IoResult<()> { self.fd.fsync() .update_err("couldn't fsync file", - |e| format!("{}; path={}", e, self.path.display())) + |e| format!("{:?}; path={:?}", e, self.path.display())) } /// This function is similar to `fsync`, except that it may not synchronize @@ -221,7 +221,7 @@ impl File { pub fn datasync(&mut self) -> IoResult<()> { self.fd.datasync() .update_err("couldn't datasync file", - |e| format!("{}; path={}", e, self.path.display())) + |e| format!("{:?}; path={:?}", e, self.path.display())) } /// Either truncates or extends the underlying file, updating the size of @@ -235,7 +235,7 @@ impl File { pub fn truncate(&mut self, size: i64) -> IoResult<()> { self.fd.truncate(size) .update_err("couldn't truncate file", |e| - format!("{}; path={}; size={}", e, self.path.display(), size)) + format!("{:?}; path={:?}; size={:?}", e, self.path.display(), size)) } /// Returns true if the stream has reached the end of the file. @@ -255,7 +255,7 @@ impl File { pub fn stat(&self) -> IoResult { self.fd.fstat() .update_err("couldn't fstat file", |e| - format!("{}; path={}", e, self.path.display())) + format!("{:?}; path={:?}", e, self.path.display())) } } @@ -283,7 +283,7 @@ impl File { pub fn unlink(path: &Path) -> IoResult<()> { fs_imp::unlink(path) .update_err("couldn't unlink path", |e| - format!("{}; path={}", e, path.display())) + format!("{:?}; path={:?}", e, path.display())) } /// Given a path, query the file system to get information about a file, @@ -310,7 +310,7 @@ pub fn unlink(path: &Path) -> IoResult<()> { pub fn stat(path: &Path) -> IoResult { fs_imp::stat(path) .update_err("couldn't stat path", |e| - format!("{}; path={}", e, path.display())) + format!("{:?}; path={:?}", e, path.display())) } /// Perform the same operation as the `stat` function, except that this @@ -324,7 +324,7 @@ pub fn stat(path: &Path) -> IoResult { pub fn lstat(path: &Path) -> IoResult { fs_imp::lstat(path) .update_err("couldn't lstat path", |e| - format!("{}; path={}", e, path.display())) + format!("{:?}; path={:?}", e, path.display())) } /// Rename a file or directory to a new name. @@ -346,7 +346,7 @@ pub fn lstat(path: &Path) -> IoResult { pub fn rename(from: &Path, to: &Path) -> IoResult<()> { fs_imp::rename(from, to) .update_err("couldn't rename path", |e| - format!("{}; from={}; to={}", e, from.display(), to.display())) + format!("{:?}; from={:?}; to={:?}", e, from.display(), to.display())) } /// Copies the contents of one file to another. This function will also @@ -380,7 +380,7 @@ pub fn rename(from: &Path, to: &Path) -> IoResult<()> { pub fn copy(from: &Path, to: &Path) -> IoResult<()> { fn update_err(result: IoResult, from: &Path, to: &Path) -> IoResult { result.update_err("couldn't copy path", |e| { - format!("{}; from={}; to={}", e, from.display(), to.display()) + format!("{:?}; from={:?}; to={:?}", e, from.display(), to.display()) }) } @@ -424,14 +424,14 @@ pub fn copy(from: &Path, to: &Path) -> IoResult<()> { pub fn chmod(path: &Path, mode: io::FilePermission) -> IoResult<()> { fs_imp::chmod(path, mode.bits() as uint) .update_err("couldn't chmod path", |e| - format!("{}; path={}; mode={}", e, path.display(), mode)) + format!("{:?}; path={:?}; mode={:?}", e, path.display(), mode)) } /// Change the user and group owners of a file at the specified path. pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> { fs_imp::chown(path, uid, gid) .update_err("couldn't chown path", |e| - format!("{}; path={}; uid={}; gid={}", e, path.display(), uid, gid)) + format!("{:?}; path={:?}; uid={:?}; gid={:?}", e, path.display(), uid, gid)) } /// Creates a new hard link on the filesystem. The `dst` path will be a @@ -440,7 +440,7 @@ pub fn chown(path: &Path, uid: int, gid: int) -> IoResult<()> { pub fn link(src: &Path, dst: &Path) -> IoResult<()> { fs_imp::link(src, dst) .update_err("couldn't link path", |e| - format!("{}; src={}; dest={}", e, src.display(), dst.display())) + format!("{:?}; src={:?}; dest={:?}", e, src.display(), dst.display())) } /// Creates a new symbolic link on the filesystem. The `dst` path will be a @@ -448,7 +448,7 @@ pub fn link(src: &Path, dst: &Path) -> IoResult<()> { pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { fs_imp::symlink(src, dst) .update_err("couldn't symlink path", |e| - format!("{}; src={}; dest={}", e, src.display(), dst.display())) + format!("{:?}; src={:?}; dest={:?}", e, src.display(), dst.display())) } /// Reads a symlink, returning the file that the symlink points to. @@ -460,7 +460,7 @@ pub fn symlink(src: &Path, dst: &Path) -> IoResult<()> { pub fn readlink(path: &Path) -> IoResult { fs_imp::readlink(path) .update_err("couldn't resolve symlink for path", |e| - format!("{}; path={}", e, path.display())) + format!("{:?}; path={:?}", e, path.display())) } /// Create a new, empty directory at the provided path @@ -483,7 +483,7 @@ pub fn readlink(path: &Path) -> IoResult { pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { fs_imp::mkdir(path, mode.bits() as uint) .update_err("couldn't create directory", |e| - format!("{}; path={}; mode={}", e, path.display(), mode)) + format!("{:?}; path={:?}; mode={:?}", e, path.display(), mode)) } /// Remove an existing, empty directory @@ -505,7 +505,7 @@ pub fn mkdir(path: &Path, mode: FilePermission) -> IoResult<()> { pub fn rmdir(path: &Path) -> IoResult<()> { fs_imp::rmdir(path) .update_err("couldn't remove directory", |e| - format!("{}; path={}", e, path.display())) + format!("{:?}; path={:?}", e, path.display())) } /// Retrieve a vector containing all entries within a provided directory @@ -545,7 +545,7 @@ pub fn rmdir(path: &Path) -> IoResult<()> { pub fn readdir(path: &Path) -> IoResult> { fs_imp::readdir(path) .update_err("couldn't read directory", - |e| format!("{}; path={}", e, path.display())) + |e| format!("{:?}; path={:?}", e, path.display())) } /// Returns an iterator that will recursively walk the directory structure @@ -555,7 +555,7 @@ pub fn readdir(path: &Path) -> IoResult> { pub fn walk_dir(path: &Path) -> IoResult { Ok(Directories { stack: try!(readdir(path).update_err("couldn't walk directory", - |e| format!("{}; path={}", e, path.display()))) + |e| format!("{:?}; path={:?}", e, path.display()))) }) } @@ -605,7 +605,7 @@ pub fn mkdir_recursive(path: &Path, mode: FilePermission) -> IoResult<()> { let result = mkdir(&curpath, mode) .update_err("couldn't recursively mkdir", - |e| format!("{}; path={}", e, path.display())); + |e| format!("{:?}; path={:?}", e, path.display())); match result { Err(mkdir_err) => { @@ -632,7 +632,7 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { rm_stack.push(path.clone()); fn rmdir_failed(err: &IoError, path: &Path) -> String { - format!("rmdir_recursive failed; path={}; cause={}", + format!("rmdir_recursive failed; path={:?}; cause={:?}", path.display(), err) } @@ -692,14 +692,14 @@ pub fn rmdir_recursive(path: &Path) -> IoResult<()> { pub fn change_file_times(path: &Path, atime: u64, mtime: u64) -> IoResult<()> { fs_imp::utime(path, atime, mtime) .update_err("couldn't change_file_times", |e| - format!("{}; path={}", e, path.display())) + format!("{:?}; path={:?}", e, path.display())) } impl Reader for File { fn read(&mut self, buf: &mut [u8]) -> IoResult { fn update_err(result: IoResult, file: &File) -> IoResult { result.update_err("couldn't read file", - |e| format!("{}; path={}", + |e| format!("{:?}; path={:?}", e, file.path.display())) } @@ -722,7 +722,7 @@ impl Writer for File { fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.fd.write(buf) .update_err("couldn't write to file", - |e| format!("{}; path={}", e, self.path.display())) + |e| format!("{:?}; path={:?}", e, self.path.display())) } } @@ -730,7 +730,7 @@ impl Seek for File { fn tell(&self) -> IoResult { self.fd.tell() .update_err("couldn't retrieve file cursor (`tell`)", - |e| format!("{}; path={}", e, self.path.display())) + |e| format!("{:?}; path={:?}", e, self.path.display())) } fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()> { @@ -743,7 +743,7 @@ impl Seek for File { Err(e) => Err(e), }; err.update_err("couldn't seek in file", - |e| format!("{}; path={}", e, self.path.display())) + |e| format!("{:?}; path={:?}", e, self.path.display())) } } @@ -832,15 +832,15 @@ mod test { macro_rules! check { ($e:expr) => ( match $e { Ok(t) => t, - Err(e) => panic!("{} failed with: {}", stringify!($e), e), + Err(e) => panic!("{} failed with: {:?}", stringify!($e), e), } ) } macro_rules! error { ($e:expr, $s:expr) => ( match $e { - Ok(_) => panic!("Unexpected success. Should've been: {}", $s), + Ok(_) => panic!("Unexpected success. Should've been: {:?}", $s), Err(ref err) => assert!(err.to_string().contains($s.as_slice()), - format!("`{}` did not contain `{}`", err, $s)) + format!("`{:?}` did not contain `{:?}`", err, $s)) } ) } @@ -906,7 +906,7 @@ mod test { if cfg!(unix) { error!(result, "no such file or directory"); } - error!(result, format!("path={}; mode=open; access=read", filename.display())); + error!(result, format!("path={:?}; mode=open; access=read", filename.display())); } #[test] @@ -920,7 +920,7 @@ mod test { if cfg!(unix) { error!(result, "no such file or directory"); } - error!(result, format!("path={}", filename.display())); + error!(result, format!("path={:?}", filename.display())); } #[test] @@ -1188,7 +1188,7 @@ mod test { error!(result, "couldn't recursively mkdir"); error!(result, "couldn't create directory"); error!(result, "mode=0700"); - error!(result, format!("path={}", file.display())); + error!(result, format!("path={:?}", file.display())); } #[test] @@ -1255,7 +1255,7 @@ mod test { error!(copy(&from, &to), format!("couldn't copy path (the source path is not an \ - existing file; from={}; to={})", + existing file; from={:?}; to={:?})", from.display(), to.display())); match copy(&from, &to) { diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 465c4f9c5c7..010cb814732 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -302,7 +302,7 @@ pub type IoResult = Result; /// # FIXME /// /// Is something like this sufficient? It's kind of archaic -#[derive(PartialEq, Eq, Clone)] +#[derive(PartialEq, Eq, Clone, Show)] pub struct IoError { /// An enumeration which can be matched against for determining the flavor /// of error. @@ -339,7 +339,7 @@ impl IoError { } } -impl fmt::Show for IoError { +impl fmt::String for IoError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } => @@ -1656,7 +1656,7 @@ pub fn standard_error(kind: IoErrorKind) -> IoError { /// A mode specifies how a file should be opened or created. These modes are /// passed to `File::open_mode` and are used to control where the file is /// positioned when it is initially opened. -#[derive(Copy, Clone, PartialEq, Eq)] +#[derive(Copy, Clone, PartialEq, Eq, Show)] pub enum FileMode { /// Opens a file positioned at the beginning. Open, @@ -1668,7 +1668,7 @@ pub enum FileMode { /// Access permissions with which the file should be opened. `File`s /// opened with `Read` will return an error if written to. -#[derive(Copy, Clone, PartialEq, Eq)] +#[derive(Copy, Clone, PartialEq, Eq, Show)] pub enum FileAccess { /// Read-only access, requests to write will result in an error Read, @@ -1825,6 +1825,12 @@ impl Default for FilePermission { } impl fmt::Show for FilePermission { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for FilePermission { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:04o}", self.bits) } diff --git a/src/libstd/io/net/addrinfo.rs b/src/libstd/io/net/addrinfo.rs index 24d45dcd652..7825a4e16e1 100644 --- a/src/libstd/io/net/addrinfo.rs +++ b/src/libstd/io/net/addrinfo.rs @@ -29,7 +29,7 @@ use sys; use vec::Vec; /// Hints to the types of sockets that are desired when looking up hosts -#[derive(Copy)] +#[derive(Copy, Show)] pub enum SocketType { Stream, Datagram, Raw } @@ -38,7 +38,7 @@ pub enum SocketType { /// to manipulate how a query is performed. /// /// The meaning of each of these flags can be found with `man -s 3 getaddrinfo` -#[derive(Copy)] +#[derive(Copy, Show)] pub enum Flag { AddrConfig, All, @@ -51,7 +51,7 @@ pub enum Flag { /// A transport protocol associated with either a hint or a return value of /// `lookup` -#[derive(Copy)] +#[derive(Copy, Show)] pub enum Protocol { TCP, UDP } @@ -61,7 +61,7 @@ pub enum Protocol { /// /// For details on these fields, see their corresponding definitions via /// `man -s 3 getaddrinfo` -#[derive(Copy)] +#[derive(Copy, Show)] pub struct Hint { pub family: uint, pub socktype: Option, @@ -69,7 +69,7 @@ pub struct Hint { pub flags: uint, } -#[derive(Copy)] +#[derive(Copy, Show)] pub struct Info { pub address: SocketAddr, pub family: uint, diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index 6cb2463fcbc..b9f653f86c2 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -32,13 +32,13 @@ use vec::Vec; pub type Port = u16; -#[derive(Copy, PartialEq, Eq, Clone, Hash)] +#[derive(Copy, PartialEq, Eq, Clone, Hash, Show)] pub enum IpAddr { Ipv4Addr(u8, u8, u8, u8), Ipv6Addr(u16, u16, u16, u16, u16, u16, u16, u16) } -impl fmt::Show for IpAddr { +impl fmt::String for IpAddr { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { Ipv4Addr(a, b, c, d) => @@ -63,13 +63,13 @@ impl fmt::Show for IpAddr { } } -#[derive(Copy, PartialEq, Eq, Clone, Hash)] +#[derive(Copy, PartialEq, Eq, Clone, Hash, Show)] pub struct SocketAddr { pub ip: IpAddr, pub port: Port, } -impl fmt::Show for SocketAddr { +impl fmt::String for SocketAddr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.ip { Ipv4Addr(..) => write!(f, "{}:{}", self.ip, self.port), diff --git a/src/libstd/io/process.rs b/src/libstd/io/process.rs index 5f77ab38d74..efb57341620 100644 --- a/src/libstd/io/process.rs +++ b/src/libstd/io/process.rs @@ -395,7 +395,14 @@ impl Command { } } +#[cfg(stage0)] impl fmt::Show for Command { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Command { /// Format the program and arguments of a Command for display. Any /// non-utf8 data is lossily converted using the utf8 replacement /// character. @@ -504,6 +511,14 @@ pub enum ProcessExit { } impl fmt::Show for ProcessExit { + /// Format a ProcessExit enum, to nicely present the information. + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + + +impl fmt::String for ProcessExit { /// Format a ProcessExit enum, to nicely present the information. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index f571bed3ba2..d7bc572106e 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -349,7 +349,7 @@ fn with_task_stdout(f: F) where F: FnOnce(&mut Writer) -> IoResult<()> { }); match result { Ok(()) => {} - Err(e) => panic!("failed printing to stdout: {}", e), + Err(e) => panic!("failed printing to stdout: {:?}", e), } } diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index d96441e09a8..be3e49c0b82 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -111,7 +111,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/libstd/os.rs b/src/libstd/os.rs index 72ad16e0a5d..5d23f2a9b93 100644 --- a/src/libstd/os.rs +++ b/src/libstd/os.rs @@ -93,7 +93,7 @@ pub const TMPBUF_SZ : uint = 1000u; /// /// // We assume that we are in a valid directory. /// let current_working_directory = os::getcwd().unwrap(); -/// println!("The current directory is {}", current_working_directory.display()); +/// println!("The current directory is {:?}", current_working_directory.display()); /// ``` pub fn getcwd() -> IoResult { sys::os::getcwd() @@ -934,7 +934,7 @@ impl fmt::Show for MapError { impl Error for MapError { fn description(&self) -> &str { "memory map error" } - fn detail(&self) -> Option { Some(self.to_string()) } + fn detail(&self) -> Option { Some(format!("{:?}", self)) } } impl FromError for Box { diff --git a/src/libstd/path/mod.rs b/src/libstd/path/mod.rs index 87188c0d4a2..0448e6907e3 100644 --- a/src/libstd/path/mod.rs +++ b/src/libstd/path/mod.rs @@ -460,7 +460,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(unix)] fn foo() { /// let mut p = Path::new("abc/def.txt"); /// p.set_extension("csv"); - /// assert!(p == Path::new("abc/def.csv")); + /// assert_eq!(p, Path::new("abc/def.csv")); /// # } /// ``` /// @@ -509,7 +509,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(windows)] fn foo() {} /// # #[cfg(unix)] fn foo() { /// let mut p = Path::new("abc/def.txt"); - /// assert!(p.with_filename("foo.dat") == Path::new("abc/foo.dat")); + /// assert_eq!(p.with_filename("foo.dat"), Path::new("abc/foo.dat")); /// # } /// ``` /// @@ -534,7 +534,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(windows)] fn foo() {} /// # #[cfg(unix)] fn foo() { /// let mut p = Path::new("abc/def.txt"); - /// assert!(p.with_extension("csv") == Path::new("abc/def.csv")); + /// assert_eq!(p.with_extension("csv"), Path::new("abc/def.csv")); /// # } /// ``` /// @@ -558,7 +558,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(windows)] fn foo() {} /// # #[cfg(unix)] fn foo() { /// let p = Path::new("abc/def/ghi"); - /// assert!(p.dir_path() == Path::new("abc/def")); + /// assert_eq!(p.dir_path(), Path::new("abc/def")); /// # } /// ``` fn dir_path(&self) -> Self { @@ -576,8 +576,8 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # foo(); /// # #[cfg(windows)] fn foo() {} /// # #[cfg(unix)] fn foo() { - /// assert!(Path::new("abc/def").root_path() == None); - /// assert!(Path::new("/abc/def").root_path() == Some(Path::new("/"))); + /// assert_eq!(Path::new("abc/def").root_path(), None); + /// assert_eq!(Path::new("/abc/def").root_path(), Some(Path::new("/"))); /// # } /// ``` fn root_path(&self) -> Option; @@ -593,7 +593,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(unix)] fn foo() { /// let mut p = Path::new("foo/bar"); /// p.push("baz.txt"); - /// assert!(p == Path::new("foo/bar/baz.txt")); + /// assert_eq!(p, Path::new("foo/bar/baz.txt")); /// # } /// ``` /// @@ -617,7 +617,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(unix)] fn foo() { /// let mut p = Path::new("foo"); /// p.push_many(&["bar", "baz.txt"]); - /// assert!(p == Path::new("foo/bar/baz.txt")); + /// assert_eq!(p, Path::new("foo/bar/baz.txt")); /// # } /// ``` #[inline] @@ -646,7 +646,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(unix)] fn foo() { /// let mut p = Path::new("foo/bar/baz.txt"); /// p.pop(); - /// assert!(p == Path::new("foo/bar")); + /// assert_eq!(p, Path::new("foo/bar")); /// # } /// ``` fn pop(&mut self) -> bool; @@ -662,7 +662,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(windows)] fn foo() {} /// # #[cfg(unix)] fn foo() { /// let p = Path::new("/foo"); - /// assert!(p.join("bar.txt") == Path::new("/foo/bar.txt")); + /// assert_eq!(p.join("bar.txt"), Path::new("/foo/bar.txt")); /// # } /// ``` /// @@ -688,7 +688,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// # #[cfg(unix)] fn foo() { /// let p = Path::new("foo"); /// let fbbq = Path::new("foo/bar/baz/quux.txt"); - /// assert!(p.join_many(&["bar", "baz", "quux.txt"]) == fbbq); + /// assert_eq!(p.join_many(&["bar", "baz", "quux.txt"]), fbbq); /// # } /// ``` #[inline] @@ -765,7 +765,7 @@ pub trait GenericPath: Clone + GenericPathUnsafe { /// let p = Path::new("foo/bar/baz/quux.txt"); /// let fb = Path::new("foo/bar"); /// let bq = Path::new("baz/quux.txt"); - /// assert!(p.path_relative_from(&fb) == Some(bq)); + /// assert_eq!(p.path_relative_from(&fb), Some(bq)); /// # } /// ``` fn path_relative_from(&self, base: &Self) -> Option; @@ -823,7 +823,14 @@ pub struct Display<'a, P:'a> { filename: bool } +//NOTE(stage0): replace with deriving(Show) after snapshot impl<'a, P: GenericPath> fmt::Show for Display<'a, P> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl<'a, P: GenericPath> fmt::String for Display<'a, P> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.as_cow().fmt(f) } diff --git a/src/libstd/path/posix.rs b/src/libstd/path/posix.rs index 7f37d3b23c8..7c5455ed3fc 100644 --- a/src/libstd/path/posix.rs +++ b/src/libstd/path/posix.rs @@ -12,6 +12,7 @@ use clone::Clone; use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd}; +use fmt; use hash; use io::Writer; use iter::{AdditiveIterator, Extend}; @@ -57,6 +58,12 @@ pub fn is_sep(c: char) -> bool { c == SEP } +impl fmt::Show for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Path {{ {} }}", self.display()) + } +} + impl PartialEq for Path { #[inline] fn eq(&self, other: &Path) -> bool { @@ -439,13 +446,13 @@ mod tests { (s: $path:expr, $exp:expr) => ( { let path = $path; - assert!(path.as_str() == Some($exp)); + assert_eq!(path.as_str(), Some($exp)); } ); (v: $path:expr, $exp:expr) => ( { let path = $path; - assert!(path.as_vec() == $exp); + assert_eq!(path.as_vec(), $exp); } ) } @@ -459,7 +466,7 @@ mod tests { t!(v: Path::new(b"a/b/c\xFF"), b"a/b/c\xFF"); t!(v: Path::new(b"\xFF/../foo\x80"), b"foo\x80"); let p = Path::new(b"a/b/c\xFF"); - assert!(p.as_str() == None); + assert!(p.as_str().is_none()); t!(s: Path::new(""), "."); t!(s: Path::new("/"), "/"); @@ -489,14 +496,14 @@ mod tests { b"/bar"); let p = Path::new(b"foo/bar\x80"); - assert!(p.as_str() == None); + assert!(p.as_str().is_none()); } #[test] fn test_opt_paths() { - assert!(Path::new_opt(b"foo/bar\0") == None); + assert!(Path::new_opt(b"foo/bar\0").is_none()); t!(v: Path::new_opt(b"foo/bar").unwrap(), b"foo/bar"); - assert!(Path::new_opt("foo/bar\0") == None); + assert!(Path::new_opt("foo/bar\0").is_none()); t!(s: Path::new_opt("foo/bar").unwrap(), "foo/bar"); } @@ -525,7 +532,7 @@ mod tests { ($path:expr, $disp:ident, $exp:expr) => ( { let path = Path::new($path); - assert!(path.$disp().to_string() == $exp); + assert_eq!(path.$disp().to_string(), $exp); } ) } @@ -541,14 +548,14 @@ mod tests { { let path = Path::new($path); let mo = path.display().as_cow(); - assert!(mo.as_slice() == $exp); + assert_eq!(mo.as_slice(), $exp); } ); ($path:expr, $exp:expr, filename) => ( { let path = Path::new($path); let mo = path.filename_display().as_cow(); - assert!(mo.as_slice() == $exp); + assert_eq!(mo.as_slice(), $exp); } ) } @@ -568,9 +575,9 @@ mod tests { { let path = Path::new($path); let f = format!("{}", path.display()); - assert!(f == $exp); + assert_eq!(f, $exp); let f = format!("{}", path.filename_display()); - assert!(f == $expf); + assert_eq!(f, $expf); } ) } @@ -590,21 +597,21 @@ mod tests { (s: $path:expr, $op:ident, $exp:expr) => ( { let path = Path::new($path); - assert!(path.$op() == ($exp).as_bytes()); + assert_eq!(path.$op(), ($exp).as_bytes()); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( { let path = Path::new($path); let left = path.$op().map(|x| str::from_utf8(x).unwrap()); - assert!(left == $exp); + assert_eq!(left, $exp); } ); (v: $path:expr, $op:ident, $exp:expr) => ( { let arg = $path; let path = Path::new(arg); - assert!(path.$op() == $exp); + assert_eq!(path.$op(), $exp); } ); } @@ -678,7 +685,7 @@ mod tests { let mut p1 = Path::new(path); let p2 = p1.clone(); p1.push(join); - assert!(p1 == p2.join(join)); + assert_eq!(p1, p2.join(join)); } ) } @@ -697,7 +704,7 @@ mod tests { let mut p = Path::new($path); let push = Path::new($push); p.push(&push); - assert!(p.as_str() == Some($exp)); + assert_eq!(p.as_str(), Some($exp)); } ) } @@ -717,14 +724,14 @@ mod tests { { let mut p = Path::new($path); p.push_many(&$push); - assert!(p.as_str() == Some($exp)); + assert_eq!(p.as_str(), Some($exp)); } ); (v: $path:expr, $push:expr, $exp:expr) => ( { let mut p = Path::new($path); p.push_many(&$push); - assert!(p.as_vec() == $exp); + assert_eq!(p.as_vec(), $exp); } ) } @@ -745,16 +752,16 @@ mod tests { { let mut p = Path::new($path); let result = p.pop(); - assert!(p.as_str() == Some($left)); - assert!(result == $right); + assert_eq!(p.as_str(), Some($left)); + assert_eq!(result, $right); } ); (b: $path:expr, $left:expr, $right:expr) => ( { let mut p = Path::new($path); let result = p.pop(); - assert!(p.as_vec() == $left); - assert!(result == $right); + assert_eq!(p.as_vec(), $left); + assert_eq!(result, $right); } ) } @@ -777,8 +784,8 @@ mod tests { #[test] fn test_root_path() { - assert!(Path::new(b"a/b/c").root_path() == None); - assert!(Path::new(b"/a/b/c").root_path() == Some(Path::new("/"))); + assert_eq!(Path::new(b"a/b/c").root_path(), None); + assert_eq!(Path::new(b"/a/b/c").root_path(), Some(Path::new("/"))); } #[test] @@ -802,7 +809,7 @@ mod tests { let path = Path::new($path); let join = Path::new($join); let res = path.join(&join); - assert!(res.as_str() == Some($exp)); + assert_eq!(res.as_str(), Some($exp)); } ) } @@ -822,14 +829,14 @@ mod tests { { let path = Path::new($path); let res = path.join_many(&$join); - assert!(res.as_str() == Some($exp)); + assert_eq!(res.as_str(), Some($exp)); } ); (v: $path:expr, $join:expr, $exp:expr) => ( { let path = Path::new($path); let res = path.join_many(&$join); - assert!(res.as_vec() == $exp); + assert_eq!(res.as_vec(), $exp); } ) } @@ -903,7 +910,7 @@ mod tests { let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); - assert!(p1 == p2.$with(arg)); + assert_eq!(p1, p2.$with(arg)); } ); (v: $path:expr, $set:ident, $with:ident, $arg:expr) => ( @@ -913,7 +920,7 @@ mod tests { let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); - assert!(p1 == p2.$with(arg)); + assert_eq!(p1, p2.$with(arg)); } ) } @@ -943,31 +950,19 @@ mod tests { (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; - let filename = $filename; - assert!(path.filename_str() == filename, - "{}.filename_str(): Expected `{}`, found {}", - path.as_str().unwrap(), filename, path.filename_str()); - let dirname = $dirname; - assert!(path.dirname_str() == dirname, - "`{}`.dirname_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), dirname, path.dirname_str()); - let filestem = $filestem; - assert!(path.filestem_str() == filestem, - "`{}`.filestem_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), filestem, path.filestem_str()); - let ext = $ext; - assert!(path.extension_str() == ext, - "`{}`.extension_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), ext, path.extension_str()); - } + assert_eq!(path.filename_str(), $filename); + assert_eq!(path.dirname_str(), $dirname); + assert_eq!(path.filestem_str(), $filestem); + assert_eq!(path.extension_str(), $ext); + } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; - assert!(path.filename() == $filename); - assert!(path.dirname() == $dirname); - assert!(path.filestem() == $filestem); - assert!(path.extension() == $ext); + assert_eq!(path.filename(), $filename); + assert_eq!(path.dirname(), $dirname); + assert_eq!(path.filestem(), $filestem); + assert_eq!(path.extension(), $ext); } ) } @@ -1155,12 +1150,10 @@ mod tests { let comps = path.components().collect::>(); let exp: &[&str] = &$exp; let exps = exp.iter().map(|x| x.as_bytes()).collect::>(); - assert!(comps == exps, "components: Expected {}, found {}", - comps, exps); + assert_eq!(comps, exprs); let comps = path.components().rev().collect::>(); let exps = exps.into_iter().rev().collect::>(); - assert!(comps == exps, "rev_components: Expected {}, found {}", - comps, exps); + assert_eq!(comps, exps); } ); (b: $arg:expr, [$($exp:expr),*]) => ( diff --git a/src/libstd/path/windows.rs b/src/libstd/path/windows.rs index 97545bc2022..ff269b73476 100644 --- a/src/libstd/path/windows.rs +++ b/src/libstd/path/windows.rs @@ -18,6 +18,7 @@ use ascii::AsciiExt; use char::CharExt; use clone::Clone; use cmp::{Ordering, Eq, Ord, PartialEq, PartialOrd}; +use fmt; use hash; use io::Writer; use iter::{AdditiveIterator, Extend}; @@ -84,6 +85,12 @@ pub struct Path { sepidx: Option // index of the final separator in the non-prefix portion of repr } +impl fmt::Show for Path { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Path {{ {} }}", self.display()) + } +} + impl PartialEq for Path { #[inline] fn eq(&self, other: &Path) -> bool { @@ -1119,13 +1126,13 @@ mod tests { (s: $path:expr, $exp:expr) => ( { let path = $path; - assert!(path.as_str() == Some($exp)); + assert_eq!(path.as_str(), Some($exp)); } ); (v: $path:expr, $exp:expr) => ( { let path = $path; - assert!(path.as_vec() == $exp); + assert_eq!(path.as_vec(), $exp); } ) } @@ -1138,8 +1145,7 @@ mod tests { let path = $path; let exp = $exp; let res = parse_prefix(path); - assert!(res == exp, - "parse_prefix(\"{}\"): expected {}, found {}", path, exp, res); + assert_eq!(res, exp); } ) } @@ -1355,7 +1361,7 @@ mod tests { { let path = $path; let path = Path::new(path); - assert!(path.$op() == Some($exp)); + assert_eq!(path.$op(), Some($exp)); } ); (s: $path:expr, $op:ident, $exp:expr, opt) => ( @@ -1363,14 +1369,14 @@ mod tests { let path = $path; let path = Path::new(path); let left = path.$op(); - assert!(left == $exp); + assert_eq!(left, $exp); } ); (v: $path:expr, $op:ident, $exp:expr) => ( { let path = $path; let path = Path::new(path); - assert!(path.$op() == $exp); + assert_eq!(path.$op(), $exp); } ) } @@ -1481,7 +1487,7 @@ mod tests { let mut p1 = Path::new(path); let p2 = p1.clone(); p1.push(join); - assert!(p1 == p2.join(join)); + assert_eq!(p1, p2.join(join)); } ) } @@ -1495,9 +1501,9 @@ mod tests { // we do want to check one odd case though to ensure the prefix is re-parsed let mut p = Path::new("\\\\?\\C:"); - assert!(prefix(&p) == Some(VerbatimPrefix(2))); + assert_eq!(prefix(&p), Some(VerbatimPrefix(2))); p.push("foo"); - assert!(prefix(&p) == Some(VerbatimDiskPrefix)); + assert_eq!(prefix(&p), Some(VerbatimDiskPrefix)); assert_eq!(p.as_str(), Some("\\\\?\\C:\\foo")); // and another with verbatim non-normalized paths @@ -1596,10 +1602,8 @@ mod tests { let mut p = Path::new(pstr); let result = p.pop(); let left = $left; - assert!(p.as_str() == Some(left), - "`{}`.pop() failed; expected remainder `{}`, found `{}`", - pstr, left, p.as_str().unwrap()); - assert!(result == $right); + assert_eq!(p.as_str(), Some(left)); + assert_eq!(result, $right); } ); (b: $path:expr, $left:expr, $right:expr) => ( @@ -1607,7 +1611,7 @@ mod tests { let mut p = Path::new($path); let result = p.pop(); assert_eq!(p.as_vec(), $left); - assert!(result == $right); + assert_eq!(result, $right); } ) } @@ -1650,16 +1654,16 @@ mod tests { #[test] fn test_root_path() { - assert!(Path::new("a\\b\\c").root_path() == None); - assert!(Path::new("\\a\\b\\c").root_path() == Some(Path::new("\\"))); - assert!(Path::new("C:a").root_path() == Some(Path::new("C:"))); - assert!(Path::new("C:\\a").root_path() == Some(Path::new("C:\\"))); - assert!(Path::new("\\\\a\\b\\c").root_path() == Some(Path::new("\\\\a\\b"))); - assert!(Path::new("\\\\?\\a\\b").root_path() == Some(Path::new("\\\\?\\a"))); - assert!(Path::new("\\\\?\\C:\\a").root_path() == Some(Path::new("\\\\?\\C:\\"))); - assert!(Path::new("\\\\?\\UNC\\a\\b\\c").root_path() == + assert_eq!(Path::new("a\\b\\c").root_path(), None); + assert_eq!(Path::new("\\a\\b\\c").root_path(), Some(Path::new("\\"))); + assert_eq!(Path::new("C:a").root_path(), Some(Path::new("C:"))); + assert_eq!(Path::new("C:\\a").root_path(), Some(Path::new("C:\\"))); + assert_eq!(Path::new("\\\\a\\b\\c").root_path(), Some(Path::new("\\\\a\\b"))); + assert_eq!(Path::new("\\\\?\\a\\b").root_path(), Some(Path::new("\\\\?\\a"))); + assert_eq!(Path::new("\\\\?\\C:\\a").root_path(), Some(Path::new("\\\\?\\C:\\"))); + assert_eq!(Path::new("\\\\?\\UNC\\a\\b\\c").root_path(), Some(Path::new("\\\\?\\UNC\\a\\b"))); - assert!(Path::new("\\\\.\\a\\b").root_path() == Some(Path::new("\\\\.\\a"))); + assert_eq!(Path::new("\\\\.\\a\\b").root_path(), Some(Path::new("\\\\.\\a"))); } #[test] @@ -1737,9 +1741,7 @@ mod tests { let arg = $arg; let res = path.$op(arg); let exp = $res; - assert!(res.as_str() == Some(exp), - "`{}`.{}(\"{}\"): Expected `{}`, found `{}`", - pstr, stringify!($op), arg, exp, res.as_str().unwrap()); + assert_eq!(Path::new($path).$op($arg), $res); } ) } @@ -1822,7 +1824,7 @@ mod tests { let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); - assert!(p1 == p2.$with(arg)); + assert_eq!(p1, p2.$with(arg)); } ); (v: $path:expr, $set:ident, $with:ident, $arg:expr) => ( @@ -1832,7 +1834,7 @@ mod tests { let mut p1 = Path::new(path); p1.$set(arg); let p2 = Path::new(path); - assert!(p1 == p2.$with(arg)); + assert_eq!(p1, p2.$with(arg)); } ) } @@ -1863,31 +1865,19 @@ mod tests { (s: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; - let filename = $filename; - assert!(path.filename_str() == filename, - "`{}`.filename_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), filename, path.filename_str()); - let dirname = $dirname; - assert!(path.dirname_str() == dirname, - "`{}`.dirname_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), dirname, path.dirname_str()); - let filestem = $filestem; - assert!(path.filestem_str() == filestem, - "`{}`.filestem_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), filestem, path.filestem_str()); - let ext = $ext; - assert!(path.extension_str() == ext, - "`{}`.extension_str(): Expected `{}`, found `{}`", - path.as_str().unwrap(), ext, path.extension_str()); + assert_eq!(path.filename_str(), $filename); + assert_eq!(path.dirname_str(), $dirname); + assert_eq!(path.filestem_str(), $filestem); + assert_eq!(path.extension_str(), $ext); } ); (v: $path:expr, $filename:expr, $dirname:expr, $filestem:expr, $ext:expr) => ( { let path = $path; - assert!(path.filename() == $filename); - assert!(path.dirname() == $dirname); - assert!(path.filestem() == $filestem); - assert!(path.extension() == $ext); + assert_eq!(path.filename(), $filename); + assert_eq!(path.dirname(), $dirname); + assert_eq!(path.filestem(), $filestem); + assert_eq!(path.extension(), $ext); } ) } @@ -1931,17 +1921,10 @@ mod tests { let path = Path::new($path); let (abs, vol, cwd, rel) = ($abs, $vol, $cwd, $rel); let b = path.is_absolute(); - assert!(b == abs, "Path '{}'.is_absolute(): expected {}, found {}", - path.as_str().unwrap(), abs, b); - let b = is_vol_relative(&path); - assert!(b == vol, "is_vol_relative('{}'): expected {}, found {}", - path.as_str().unwrap(), vol, b); - let b = is_cwd_relative(&path); - assert!(b == cwd, "is_cwd_relative('{}'): expected {}, found {}", - path.as_str().unwrap(), cwd, b); - let b = path.is_relative(); - assert!(b == rel, "Path '{}'.is_relativf(): expected {}, found {}", - path.as_str().unwrap(), rel, b); + assert_eq!(path.is_absolute(), asb); + assert_eq!(is_vol_relative(&path), vol); + assert_eq!(is_cwd_relative(&path), cwd); + assert_eq!(path.is_relative(), rel); } ) } @@ -1972,9 +1955,7 @@ mod tests { let dest = Path::new($dest); let exp = $exp; let res = path.is_ancestor_of(&dest); - assert!(res == exp, - "`{}`.is_ancestor_of(`{}`): Expected {}, found {}", - path.as_str().unwrap(), dest.as_str().unwrap(), exp, res); + assert_eq!(Path::new($path).is_ancestor_of(Path::new($dest)), $exp); } ) } @@ -2103,14 +2084,8 @@ mod tests { macro_rules! t { (s: $path:expr, $other:expr, $exp:expr) => ( { - let path = Path::new($path); - let other = Path::new($other); - let res = path.path_relative_from(&other); - let exp = $exp; - assert!(res.as_ref().and_then(|x| x.as_str()) == exp, - "`{}`.path_relative_from(`{}`): Expected {}, got {}", - path.as_str().unwrap(), other.as_str().unwrap(), exp, - res.as_ref().and_then(|x| x.as_str())); + assert_eq!(Path::new($path).path_relative_from(Path::new($other)) + .as_ref().and_then(|x| x.as_str()), $exp); } ) } @@ -2319,7 +2294,7 @@ mod tests { let path = Path::new($path); let exp: Option<&str> = $exp; let exp = exp.map(|s| Path::new(s)); - assert!(make_non_verbatim(&path) == exp); + assert_eq!(make_non_verbatim(&path), exp); } ) } diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs index 8855a7e5293..fc257b12bb6 100644 --- a/src/libstd/rand/mod.rs +++ b/src/libstd/rand/mod.rs @@ -303,7 +303,7 @@ impl<'a> SeedableRng<&'a [uint]> for StdRng { pub fn weak_rng() -> XorShiftRng { match OsRng::new() { Ok(mut r) => r.gen(), - Err(e) => panic!("weak_rng: failed to create seeded RNG: {}", e) + Err(e) => panic!("weak_rng: failed to create seeded RNG: {:?}", e) } } @@ -490,7 +490,7 @@ mod test { let mut r = thread_rng(); let a = r.gen::(); let b = r.gen::(); - debug!("{}", (a, b)); + debug!("{:?}", (a, b)); } #[test] diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs index 48d7f2e7854..177b7380831 100644 --- a/src/libstd/rand/reader.rs +++ b/src/libstd/rand/reader.rs @@ -67,7 +67,7 @@ impl Rng for ReaderRng { if v.len() == 0 { return } match self.reader.read_at_least(v.len(), v) { Ok(_) => {} - Err(e) => panic!("ReaderRng.fill_bytes error: {}", e) + Err(e) => panic!("ReaderRng.fill_bytes error: {:?}", e) } } } diff --git a/src/libstd/sys/unix/backtrace.rs b/src/libstd/sys/unix/backtrace.rs index ca268a8f27f..7164931c55a 100644 --- a/src/libstd/sys/unix/backtrace.rs +++ b/src/libstd/sys/unix/backtrace.rs @@ -370,7 +370,7 @@ fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void) -> IoResult<()> { // Finally, after all that work above, we can emit a symbol. fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void, s: Option<&[u8]>) -> IoResult<()> { - try!(write!(w, " {:2}: {:2$} - ", idx, addr, HEX_WIDTH)); + try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH)); match s.and_then(|s| str::from_utf8(s).ok()) { Some(string) => try!(demangle(w, string)), None => try!(write!(w, "")), diff --git a/src/libstd/sys/unix/fs.rs b/src/libstd/sys/unix/fs.rs index 1ad775517bb..c53f9d22790 100644 --- a/src/libstd/sys/unix/fs.rs +++ b/src/libstd/sys/unix/fs.rs @@ -381,7 +381,7 @@ mod tests { assert_eq!(buf[2], 's' as u8); assert_eq!(buf[3], 't' as u8); } - r => panic!("invalid read: {}", r), + r => panic!("invalid read: {:?}", r), } assert!(writer.read(&mut buf).is_err()); diff --git a/src/libstd/sys/unix/process.rs b/src/libstd/sys/unix/process.rs index 5bc6b0c703b..1357bbdd5a3 100644 --- a/src/libstd/sys/unix/process.rs +++ b/src/libstd/sys/unix/process.rs @@ -125,7 +125,7 @@ impl Process { return match input.read(&mut bytes) { Ok(8) => { assert!(combine(CLOEXEC_MSG_FOOTER) == combine(bytes.slice(4, 8)), - "Validation on the CLOEXEC pipe failed: {}", bytes); + "Validation on the CLOEXEC pipe failed: {:?}", bytes); let errno = combine(bytes.slice(0, 4)); assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); Err(super::decode_error(errno)) @@ -133,7 +133,7 @@ impl Process { Err(ref e) if e.kind == EndOfFile => Ok(p), Err(e) => { assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); - panic!("the CLOEXEC pipe failed: {}", e) + panic!("the CLOEXEC pipe failed: {:?}", e) }, Ok(..) => { // pipe I/O up to PIPE_BUF bytes should be atomic assert!(p.wait(0).is_ok(), "wait(0) should either return Ok or panic"); @@ -285,7 +285,7 @@ impl Process { let mut status = 0 as c_int; if deadline == 0 { return match retry(|| unsafe { c::waitpid(self.pid, &mut status, 0) }) { - -1 => panic!("unknown waitpid error: {}", super::last_error()), + -1 => panic!("unknown waitpid error: {:?}", super::last_error()), _ => Ok(translate_status(status)), } } @@ -410,7 +410,7 @@ impl Process { continue } - n => panic!("error in select {} ({})", os::errno(), n), + n => panic!("error in select {:?} ({:?})", os::errno(), n), } // Process any pending messages @@ -491,7 +491,7 @@ impl Process { n if n > 0 => { ret = true; } 0 => return true, -1 if wouldblock() => return ret, - n => panic!("bad read {} ({})", os::last_os_error(), n), + n => panic!("bad read {:?} ({:?})", os::last_os_error(), n), } } } @@ -514,7 +514,7 @@ impl Process { } { 1 => {} -1 if wouldblock() => {} // see above comments - n => panic!("bad error on write fd: {} {}", n, os::errno()), + n => panic!("bad error on write fd: {:?} {:?}", n, os::errno()), } } } @@ -526,7 +526,7 @@ impl Process { }) { n if n == self.pid => Some(translate_status(status)), 0 => None, - n => panic!("unknown waitpid error `{}`: {}", n, + n => panic!("unknown waitpid error `{:?}`: {:?}", n, super::last_error()), } } diff --git a/src/libstd/time/duration.rs b/src/libstd/time/duration.rs index ac1f0c5d803..9bd6f78300e 100644 --- a/src/libstd/time/duration.rs +++ b/src/libstd/time/duration.rs @@ -48,7 +48,7 @@ macro_rules! try_opt { /// ISO 8601 time duration with nanosecond precision. /// This also allows for the negative duration; see individual methods for details. -#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Show)] pub struct Duration { secs: i64, nanos: i32, // Always 0 <= nanos < NANOS_PER_SEC @@ -337,7 +337,7 @@ impl Div for Duration { } } -impl fmt::Show for Duration { +impl fmt::String for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // technically speaking, negative duration is not valid ISO 8601, // but we need to print it anyway. diff --git a/src/libsyntax/abi.rs b/src/libsyntax/abi.rs index c366ced58b2..09235ee209c 100644 --- a/src/libsyntax/abi.rs +++ b/src/libsyntax/abi.rs @@ -47,7 +47,7 @@ pub enum Abi { } #[allow(non_camel_case_types)] -#[derive(Copy, PartialEq)] +#[derive(Copy, PartialEq, Show)] pub enum Architecture { X86, X86_64, @@ -120,12 +120,24 @@ impl Abi { } impl fmt::Show for Abi { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Abi { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\"{}\"", self.name()) } } impl fmt::Show for Os { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Os { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { OsLinux => "linux".fmt(f), diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 753e60738f6..10cdea791b8 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -100,13 +100,26 @@ impl Ident { } } -impl Show for Ident { +//NOTE(stage0): remove after snapshot +impl fmt::Show for Ident { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Ident { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}#{}", self.name, self.ctxt) } } -impl Show for Name { +impl fmt::Show for Name { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for Name { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let Name(nm) = *self; write!(f, "\"{}\"({})", token::get_name(*self).get(), nm) @@ -1094,7 +1107,14 @@ pub enum IntTy { TyI64, } +//NOTE(stage0): remove after snapshot impl fmt::Show for IntTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for IntTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::int_ty_to_string(*self, None)) } @@ -1129,7 +1149,14 @@ impl UintTy { } } +//NOTE(stage0): remove after snapshot impl fmt::Show for UintTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for UintTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::uint_ty_to_string(*self, None)) } @@ -1141,7 +1168,14 @@ pub enum FloatTy { TyF64, } +//NOTE(stage0): remove after snapshot impl fmt::Show for FloatTy { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for FloatTy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", ast_util::float_ty_to_string(*self)) } @@ -1192,10 +1226,19 @@ pub enum Onceness { impl fmt::Show for Onceness { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Once => "once".fmt(f), - Many => "many".fmt(f), - } + fmt::String::fmt(match *self { + Once => "once", + Many => "many", + }, f) + } +} + +impl fmt::String for Onceness { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(match *self { + Once => "once", + Many => "many", + }, f) } } @@ -1305,18 +1348,18 @@ pub struct FnDecl { pub variadic: bool } -#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Show)] pub enum Unsafety { Unsafe, Normal, } -impl fmt::Show for Unsafety { +impl fmt::String for Unsafety { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - match *self { - Unsafety::Normal => "normal".fmt(f), - Unsafety::Unsafe => "unsafe".fmt(f), - } + fmt::String::fmt(match *self { + Unsafety::Normal => "normal", + Unsafety::Unsafe => "unsafe", + }, f) } } diff --git a/src/libsyntax/ast_map/mod.rs b/src/libsyntax/ast_map/mod.rs index efd35f73d45..7496a0f9f26 100644 --- a/src/libsyntax/ast_map/mod.rs +++ b/src/libsyntax/ast_map/mod.rs @@ -46,7 +46,14 @@ impl PathElem { } } +//NOTE(stage0): replace with deriving(Show) after snapshot impl fmt::Show for PathElem { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for PathElem { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let slot = token::get_name(self.name()); write!(f, "{}", slot) @@ -396,7 +403,7 @@ impl<'ast> Map<'ast> { PathName(ident.name) } MethMac(_) => { - panic!("no path elem for {}", node) + panic!("no path elem for {:?}", node) } } } @@ -410,7 +417,7 @@ impl<'ast> Map<'ast> { MethDecl(ident, _, _, _, _, _, _, _) => { PathName(ident.name) } - MethMac(_) => panic!("no path elem for {}", node), + MethMac(_) => panic!("no path elem for {:?}", node), } } TypeTraitItem(ref m) => { @@ -418,7 +425,7 @@ impl<'ast> Map<'ast> { } }, NodeVariant(v) => PathName(v.node.name.name), - _ => panic!("no path elem for {}", node) + _ => panic!("no path elem for {:?}", node) } } @@ -549,7 +556,7 @@ impl<'ast> Map<'ast> { pub fn span(&self, id: NodeId) -> Span { self.opt_span(id) - .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {}", id)) + .unwrap_or_else(|| panic!("AstMap.span: could not find span for id {:?}", id)) } pub fn def_id_span(&self, def_id: DefId, fallback: Span) -> Span { @@ -729,7 +736,7 @@ struct NodeCollector<'ast> { impl<'ast> NodeCollector<'ast> { fn insert_entry(&mut self, id: NodeId, entry: MapEntry<'ast>) { - debug!("ast_map: {} => {}", id, entry); + debug!("ast_map: {:?} => {:?}", id, entry); let len = self.map.len(); if id as uint >= len { self.map.extend(repeat(NotPresent).take(id as uint - len + 1)); diff --git a/src/libsyntax/attr.rs b/src/libsyntax/attr.rs index c5cffc401a1..416fc8c2278 100644 --- a/src/libsyntax/attr.rs +++ b/src/libsyntax/attr.rs @@ -28,6 +28,7 @@ use ptr::P; use std::cell::{RefCell, Cell}; use std::collections::BitvSet; use std::collections::HashSet; +use std::fmt; thread_local! { static USED_ATTRS: RefCell = RefCell::new(BitvSet::new()) } @@ -357,6 +358,12 @@ pub enum StabilityLevel { Locked } +impl fmt::String for StabilityLevel { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Show::fmt(self, f) + } +} + pub fn find_stability_generic<'a, AM: AttrMetaMethods, I: Iterator> diff --git a/src/libsyntax/codemap.rs b/src/libsyntax/codemap.rs index 6d329fe614c..04753bdf652 100644 --- a/src/libsyntax/codemap.rs +++ b/src/libsyntax/codemap.rs @@ -488,7 +488,7 @@ impl CodeMap { let mut total_extra_bytes = 0; for mbc in map.multibyte_chars.borrow().iter() { - debug!("{}-byte char at {}", mbc.bytes, mbc.pos); + debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); if mbc.pos < bpos { // every character is at least one byte, so we only // count the actual extra bytes. @@ -566,9 +566,9 @@ impl CodeMap { let chpos = self.bytepos_to_file_charpos(pos); let linebpos = (*f.lines.borrow())[a]; let linechpos = self.bytepos_to_file_charpos(linebpos); - debug!("byte pos {} is on the line at byte pos {}", + debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); - debug!("char pos {} is on the line at char pos {}", + debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); debug!("byte is on line: {}", line); assert!(chpos >= linechpos); diff --git a/src/libsyntax/diagnostic.rs b/src/libsyntax/diagnostic.rs index f43a236341e..fde2fdb3c55 100644 --- a/src/libsyntax/diagnostic.rs +++ b/src/libsyntax/diagnostic.rs @@ -222,7 +222,7 @@ pub fn mk_handler(e: Box) -> Handler { } } -#[derive(Copy, PartialEq, Clone)] +#[derive(Copy, PartialEq, Clone, Show)] pub enum Level { Bug, Fatal, @@ -232,9 +232,9 @@ pub enum Level { Help, } -impl fmt::Show for Level { +impl fmt::String for Level { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - use std::fmt::Show; + use std::fmt::String; match *self { Bug => "error: internal compiler error".fmt(f), @@ -374,7 +374,7 @@ impl Emitter for EmitterWriter { match error { Ok(()) => {} - Err(e) => panic!("failed to print diagnostics: {}", e), + Err(e) => panic!("failed to print diagnostics: {:?}", e), } } @@ -382,7 +382,7 @@ impl Emitter for EmitterWriter { sp: RenderSpan, msg: &str, lvl: Level) { match emit(self, cm, sp, msg, None, lvl, true) { Ok(()) => {} - Err(e) => panic!("failed to print diagnostics: {}", e), + Err(e) => panic!("failed to print diagnostics: {:?}", e), } } } diff --git a/src/libsyntax/ext/deriving/show.rs b/src/libsyntax/ext/deriving/show.rs index 70d6da0f88b..fa9a7899a12 100644 --- a/src/libsyntax/ext/deriving/show.rs +++ b/src/libsyntax/ext/deriving/show.rs @@ -90,7 +90,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, for (i, field) in fields.iter().enumerate() { if i != 0 { format_string.push_str(", "); } - format_string.push_str("{}"); + format_string.push_str("{:?}"); exprs.push(field.self_.clone()); } @@ -107,7 +107,7 @@ fn show_substructure(cx: &mut ExtCtxt, span: Span, let name = token::get_ident(field.name.unwrap()); format_string.push_str(" "); format_string.push_str(name.get()); - format_string.push_str(": {}"); + format_string.push_str(": {:?}"); exprs.push(field.self_.clone()); } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index 75aea623de6..3e1bccf394a 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -36,7 +36,7 @@ pub fn expand_type(t: P, fld: &mut MacroExpander, impl_ty: Option>) -> P { - debug!("expanding type {} with impl_ty {}", t, impl_ty); + debug!("expanding type {:?} with impl_ty {:?}", t, impl_ty); let t = match (t.node.clone(), impl_ty) { // Expand uses of `Self` in impls to the concrete type. (ast::Ty_::TyPath(ref path, _), Some(ref impl_ty)) => { diff --git a/src/libsyntax/ext/format.rs b/src/libsyntax/ext/format.rs index 85a3a5ebcae..44a596d2657 100644 --- a/src/libsyntax/ext/format.rs +++ b/src/libsyntax/ext/format.rs @@ -607,7 +607,7 @@ impl<'a, 'b> Context<'a, 'b> { let trait_ = match *ty { Known(ref tyname) => { match tyname.index(&FullRange) { - "" => "Show", + "" => "String", "?" => "Show", "e" => "LowerExp", "E" => "UpperExp", diff --git a/src/libsyntax/ext/mtwt.rs b/src/libsyntax/ext/mtwt.rs index 49d6b255c81..d7d768a007e 100644 --- a/src/libsyntax/ext/mtwt.rs +++ b/src/libsyntax/ext/mtwt.rs @@ -121,7 +121,7 @@ fn new_sctable_internal() -> SCTable { pub fn display_sctable(table: &SCTable) { error!("SC table:"); for (idx,val) in table.table.borrow().iter().enumerate() { - error!("{:4} : {}",idx,val); + error!("{:4} : {:?}",idx,val); } } diff --git a/src/libsyntax/ext/source_util.rs b/src/libsyntax/ext/source_util.rs index 5c966ed9823..1ba91dd371c 100644 --- a/src/libsyntax/ext/source_util.rs +++ b/src/libsyntax/ext/source_util.rs @@ -135,7 +135,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) let bytes = match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {}: {}", + format!("couldn't read {:?}: {}", file.display(), e).index(&FullRange)); return DummyResult::expr(sp); @@ -146,7 +146,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) Ok(src) => { // Add this input file to the code map to make it available as // dependency information - let filename = file.display().to_string(); + let filename = format!("{:?}", file.display()); let interned = token::intern_and_get_ident(src.index(&FullRange)); cx.codemap().new_filemap(filename, src); @@ -154,7 +154,7 @@ pub fn expand_include_str(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) } Err(_) => { cx.span_err(sp, - format!("{} wasn't a utf-8 file", + format!("{:?} wasn't a utf-8 file", file.display()).index(&FullRange)); return DummyResult::expr(sp); } @@ -177,7 +177,7 @@ pub fn expand_include_bytes(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) match File::open(&file).read_to_end() { Err(e) => { cx.span_err(sp, - format!("couldn't read {}: {}", file.display(), e).index(&FullRange)); + format!("couldn't read {:?}: {}", file.display(), e).index(&FullRange)); return DummyResult::expr(sp); } Ok(bytes) => { diff --git a/src/libsyntax/ext/tt/transcribe.rs b/src/libsyntax/ext/tt/transcribe.rs index 7ca920a6196..b3bb5cdd897 100644 --- a/src/libsyntax/ext/tt/transcribe.rs +++ b/src/libsyntax/ext/tt/transcribe.rs @@ -128,7 +128,7 @@ impl Add for LockstepIterSize { let l_n = token::get_ident(l_id.clone()); let r_n = token::get_ident(r_id); LisContradiction(format!("inconsistent lockstep iteration: \ - '{}' has {} items, but '{}' has {}", + '{:?}' has {} items, but '{:?}' has {}", l_n, l_len, r_n, r_len).to_string()) } }, @@ -296,7 +296,7 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan { MatchedSeq(..) => { r.sp_diag.span_fatal( r.cur_span, /* blame the macro writer */ - format!("variable '{}' is still repeating at this depth", + format!("variable '{:?}' is still repeating at this depth", token::get_ident(ident)).index(&FullRange)); } } diff --git a/src/libsyntax/parse/attr.rs b/src/libsyntax/parse/attr.rs index f4810cee5f8..4aad7f911db 100644 --- a/src/libsyntax/parse/attr.rs +++ b/src/libsyntax/parse/attr.rs @@ -32,7 +32,7 @@ impl<'a> ParserAttr for Parser<'a> { fn parse_outer_attributes(&mut self) -> Vec { let mut attrs: Vec = Vec::new(); loop { - debug!("parse_outer_attributes: self.token={}", + debug!("parse_outer_attributes: self.token={:?}", self.token); match self.token { token::Pound => { @@ -62,7 +62,7 @@ impl<'a> ParserAttr for Parser<'a> { /// If permit_inner is true, then a leading `!` indicates an inner /// attribute fn parse_attribute(&mut self, permit_inner: bool) -> ast::Attribute { - debug!("parse_attributes: permit_inner={} self.token={}", + debug!("parse_attributes: permit_inner={:?} self.token={:?}", permit_inner, self.token); let (span, value, mut style) = match self.token { token::Pound => { diff --git a/src/libsyntax/parse/lexer/mod.rs b/src/libsyntax/parse/lexer/mod.rs index 850d527fe39..e6331cc085b 100644 --- a/src/libsyntax/parse/lexer/mod.rs +++ b/src/libsyntax/parse/lexer/mod.rs @@ -111,7 +111,7 @@ impl<'a> Reader for TtReader<'a> { } fn next_token(&mut self) -> TokenAndSpan { let r = tt_next_token(self); - debug!("TtReader: r={}", r); + debug!("TtReader: r={:?}", r); r } fn fatal(&self, m: &str) -> ! { @@ -256,13 +256,13 @@ impl<'a> StringReader<'a> { /// adjusted 1 towards each other (assumes that on either side there is a /// single-byte delimiter). pub fn name_from(&self, start: BytePos) -> ast::Name { - debug!("taking an ident from {} to {}", start, self.last_pos); + debug!("taking an ident from {:?} to {:?}", start, self.last_pos); self.with_str_from(start, token::intern) } /// As name_from, with an explicit endpoint. pub fn name_from_to(&self, start: BytePos, end: BytePos) -> ast::Name { - debug!("taking an ident from {} to {}", start, end); + debug!("taking an ident from {:?} to {:?}", start, end); self.with_str_from_to(start, end, token::intern) } @@ -496,7 +496,7 @@ impl<'a> StringReader<'a> { // for skipping over all "junk" '/' | '#' => { let c = self.scan_comment(); - debug!("scanning a comment {}", c); + debug!("scanning a comment {:?}", c); c }, c if is_whitespace(Some(c)) => { @@ -506,7 +506,7 @@ impl<'a> StringReader<'a> { tok: token::Whitespace, sp: codemap::mk_sp(start_bpos, self.last_pos) }); - debug!("scanning whitespace: {}", c); + debug!("scanning whitespace: {:?}", c); c }, _ => None @@ -592,8 +592,8 @@ impl<'a> StringReader<'a> { whence: &str) { match r.curr { Some(r_c) if r_c == c => r.bump(), - Some(r_c) => panic!("expected {}, hit {}, {}", described_c, r_c, whence), - None => panic!("expected {}, hit EOF, {}", described_c, whence), + Some(r_c) => panic!("expected {:?}, hit {:?}, {}", described_c, r_c, whence), + None => panic!("expected {:?}, hit EOF, {}", described_c, whence), } } @@ -614,7 +614,7 @@ impl<'a> StringReader<'a> { self.scan_digits(base); let encoded_name : u32 = self.with_str_from(start_bpos, |s| { num::from_str_radix(s, 10).unwrap_or_else(|| { - panic!("expected digits representing a name, got `{}`, {}, range [{},{}]", + panic!("expected digits representing a name, got {:?}, {}, range [{:?},{:?}]", s, whence, start_bpos, self.last_pos); }) }); @@ -632,7 +632,7 @@ impl<'a> StringReader<'a> { self.scan_digits(base); let encoded_ctxt : ast::SyntaxContext = self.with_str_from(start_bpos, |s| { num::from_str_radix(s, 10).unwrap_or_else(|| { - panic!("expected digits representing a ctxt, got `{}`, {}", s, whence); + panic!("expected digits representing a ctxt, got {:?}, {}", s, whence); }) }); @@ -652,7 +652,7 @@ impl<'a> StringReader<'a> { if c == Some('_') { debug!("skipping a _"); self.bump(); continue; } match c.and_then(|cc| cc.to_digit(radix)) { Some(_) => { - debug!("{} in scan_digits", c); + debug!("{:?} in scan_digits", c); len += 1; self.bump(); } @@ -728,7 +728,7 @@ impl<'a> StringReader<'a> { delim: char, below_0x7f_only: bool) -> bool { - debug!("scanning {} digits until {}", n_digits, delim); + debug!("scanning {} digits until {:?}", n_digits, delim); let start_bpos = self.last_pos; let mut accum_int = 0; @@ -990,7 +990,7 @@ impl<'a> StringReader<'a> { if is_dec_digit(c) { let num = self.scan_number(c.unwrap()); let suffix = self.scan_optional_raw_name(); - debug!("next_token_inner: scanned number {}, {}", num, suffix); + debug!("next_token_inner: scanned number {:?}, {:?}", num, suffix); return token::Literal(num, suffix) } @@ -1444,14 +1444,14 @@ fn is_dec_digit(c: Option) -> bool { return in_range(c, '0', '9'); } pub fn is_doc_comment(s: &str) -> bool { let res = (s.starts_with("///") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'/') || s.starts_with("//!"); - debug!("is `{}` a doc comment? {}", s, res); + debug!("is {:?} a doc comment? {}", s, res); res } pub fn is_block_doc_comment(s: &str) -> bool { let res = (s.starts_with("/**") && *s.as_bytes().get(3).unwrap_or(&b' ') != b'*') || s.starts_with("/*!"); - debug!("is `{}` a doc comment? {}", s, res); + debug!("is {:?} a doc comment? {}", s, res); res } diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs index b79f59cc0c1..82e2c8136a4 100644 --- a/src/libsyntax/parse/mod.rs +++ b/src/libsyntax/parse/mod.rs @@ -254,7 +254,7 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) let bytes = match File::open(path).read_to_end() { Ok(bytes) => bytes, Err(e) => { - err(format!("couldn't read {}: {}", + err(format!("couldn't read {:?}: {:?}", path.display(), e).index(&FullRange)); unreachable!() @@ -266,7 +266,7 @@ pub fn file_to_filemap(sess: &ParseSess, path: &Path, spanopt: Option) path.as_str().unwrap().to_string()) } None => { - err(format!("{} is not UTF-8 encoded", path.display()).index(&FullRange)) + err(format!("{:?} is not UTF-8 encoded", path.display()).index(&FullRange)) } } unreachable!() @@ -539,7 +539,7 @@ fn looks_like_width_suffix(first_chars: &[char], s: &str) -> bool { fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ { - debug!("filtered_float_lit: {}, {}", data, suffix); + debug!("filtered_float_lit: {}, {:?}", data, suffix); match suffix { Some("f32") => ast::LitFloat(data, ast::TyF32), Some("f64") => ast::LitFloat(data, ast::TyF64), @@ -559,7 +559,7 @@ fn filtered_float_lit(data: token::InternedString, suffix: Option<&str>, } } pub fn float_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> ast::Lit_ { - debug!("float_lit: {}, {}", s, suffix); + debug!("float_lit: {:?}, {:?}", s, suffix); // FIXME #2252: bounds checking float literals is defered until trans let s = s.chars().filter(|&c| c != '_').collect::(); let data = token::intern_and_get_ident(&*s); @@ -664,7 +664,7 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> let s2 = s.chars().filter(|&c| c != '_').collect::(); let mut s = s2.index(&FullRange); - debug!("integer_lit: {}, {}", s, suffix); + debug!("integer_lit: {}, {:?}", s, suffix); let mut base = 10; let orig = s; @@ -729,8 +729,8 @@ pub fn integer_lit(s: &str, suffix: Option<&str>, sd: &SpanHandler, sp: Span) -> } } - debug!("integer_lit: the type is {}, base {}, the new string is {}, the original \ - string was {}, the original suffix was {}", ty, base, s, orig, suffix); + debug!("integer_lit: the type is {:?}, base {:?}, the new string is {:?}, the original \ + string was {:?}, the original suffix was {:?}", ty, base, s, orig, suffix); let res: u64 = match ::std::num::from_str_radix(s, base) { Some(r) => r, diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 0ecd098951f..7d7e10e181e 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -488,7 +488,7 @@ impl<'a> Parser<'a> { /// followed by some token from the set edible + inedible. Recover /// from anticipated input errors, discarding erroneous characters. pub fn commit_expr(&mut self, e: &Expr, edible: &[token::Token], inedible: &[token::Token]) { - debug!("commit_expr {}", e); + debug!("commit_expr {:?}", e); if let ExprPath(..) = e.node { // might be unit-struct construction; check for recoverableinput error. let mut expected = edible.iter().map(|x| x.clone()).collect::>(); @@ -5054,7 +5054,7 @@ impl<'a> Parser<'a> { attrs = tmp; first = false; } - debug!("parse_mod_items: parse_item_or_view_item(attrs={})", + debug!("parse_mod_items: parse_item_or_view_item(attrs={:?})", attrs); match self.parse_item_or_view_item(attrs, true /* macros allowed */) { @@ -5191,7 +5191,7 @@ impl<'a> Parser<'a> { format!("file not found for module `{}`", mod_name).index(&FullRange), format!("name the file either {} or {} inside \ - the directory {}", + the directory {:?}", default_path_str, secondary_path_str, dir_path.display()).index(&FullRange)); diff --git a/src/libsyntax/parse/token.rs b/src/libsyntax/parse/token.rs index f70ce54bb1c..306ab303411 100644 --- a/src/libsyntax/parse/token.rs +++ b/src/libsyntax/parse/token.rs @@ -651,6 +651,12 @@ impl BytesContainer for InternedString { } impl fmt::Show for InternedString { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::String::fmt(self, f) + } +} + +impl fmt::String for InternedString { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.string.index(&FullRange)) } diff --git a/src/libsyntax/test.rs b/src/libsyntax/test.rs index 0b2c45ee3a7..711715355e9 100644 --- a/src/libsyntax/test.rs +++ b/src/libsyntax/test.rs @@ -194,7 +194,7 @@ impl<'a> fold::Folder for TestHarnessGenerator<'a> { if !self.cx.path.is_empty() { self.tested_submods.push((self.cx.path[self.cx.path.len()-1], sym)); } else { - debug!("pushing nothing, sym: {}", sym); + debug!("pushing nothing, sym: {:?}", sym); self.cx.toplevel_reexport = Some(sym); } } diff --git a/src/libterm/terminfo/mod.rs b/src/libterm/terminfo/mod.rs index 71c71017850..f2dcdc6160a 100644 --- a/src/libterm/terminfo/mod.rs +++ b/src/libterm/terminfo/mod.rs @@ -190,14 +190,14 @@ impl TerminfoTerminal { ti: msys_terminfo(), num_colors: 8} as Box+Send>); } - debug!("error finding terminfo entry: {}", entry.err().unwrap()); + debug!("error finding terminfo entry: {:?}", entry.err().unwrap()); return None; } let mut file = entry.unwrap(); let ti = parse(&mut file, false); if ti.is_err() { - debug!("error parsing terminfo entry: {}", ti.unwrap_err()); + debug!("error parsing terminfo entry: {:?}", ti.unwrap_err()); return None; } diff --git a/src/libterm/terminfo/parm.rs b/src/libterm/terminfo/parm.rs index 04238f1c965..b0bce8f3112 100644 --- a/src/libterm/terminfo/parm.rs +++ b/src/libterm/terminfo/parm.rs @@ -290,7 +290,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables) ';' => (), _ => { - return Err(format!("unrecognized format option {}", cur)) + return Err(format!("unrecognized format option {:?}", cur)) } } }, @@ -552,7 +552,7 @@ fn format(val: Param, op: FormatOp, flags: Flags) -> Result ,String> { s } _ => { - return Err(format!("non-string on stack with %{}", + return Err(format!("non-string on stack with %{:?}", op.to_char())) } } @@ -636,7 +636,7 @@ mod test { "Binop {} succeeded incorrectly with 1 stack entry", cap); let res = get_res("%{1}%{2}", cap, &[], vars); assert!(res.is_ok(), - "Binop {} failed with 2 stack entries: {}", cap, res.unwrap_err()); + "Binop {} failed with 2 stack entries: {:?}", cap, res.unwrap_err()); } } diff --git a/src/libterm/terminfo/parser/compiled.rs b/src/libterm/terminfo/parser/compiled.rs index 4617be4f3f6..7a06849abd1 100644 --- a/src/libterm/terminfo/parser/compiled.rs +++ b/src/libterm/terminfo/parser/compiled.rs @@ -163,7 +163,7 @@ pub fn parse(file: &mut io::Reader, longnames: bool) macro_rules! try { ($e:expr) => ( match $e { Ok(e) => e, - Err(e) => return Err(format!("{}", e)) + Err(e) => return Err(format!("{:?}", e)) } ) } diff --git a/src/libterm/terminfo/searcher.rs b/src/libterm/terminfo/searcher.rs index 38be6860079..2651be1ebb8 100644 --- a/src/libterm/terminfo/searcher.rs +++ b/src/libterm/terminfo/searcher.rs @@ -82,11 +82,11 @@ pub fn open(term: &str) -> Result { Some(x) => { match File::open(&*x) { Ok(file) => Ok(file), - Err(e) => Err(format!("error opening file: {}", e)), + Err(e) => Err(format!("error opening file: {:?}", e)), } } None => { - Err(format!("could not find terminfo entry for {}", term)) + Err(format!("could not find terminfo entry for {:?}", term)) } } } diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs index 76df9ea4561..3ee2b1b2224 100644 --- a/src/libtest/lib.rs +++ b/src/libtest/lib.rs @@ -95,7 +95,11 @@ pub mod stats; // colons. This way if some test runner wants to arrange the tests // hierarchically it may. +<<<<<<< HEAD #[derive(Clone, PartialEq, Eq, Hash)] +======= +#[deriving(Clone, PartialEq, Eq, Hash, Show)] +>>>>>>> core: split into fmt::Show and fmt::String pub enum TestName { StaticTestName(&'static str), DynTestName(String) @@ -108,9 +112,9 @@ impl TestName { } } } -impl Show for TestName { +impl fmt::String for TestName { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.as_slice().fmt(f) + fmt::String::fmt(self.as_slice(), f) } } @@ -257,13 +261,13 @@ pub fn test_main(args: &[String], tests: Vec ) { let opts = match parse_opts(args) { Some(Ok(o)) => o, - Some(Err(msg)) => panic!("{}", msg), + Some(Err(msg)) => panic!("{:?}", msg), None => return }; match run_tests_console(&opts, tests) { Ok(true) => {} Ok(false) => panic!("Some tests failed"), - Err(e) => panic!("io error when running tests: {}", e), + Err(e) => panic!("io error when running tests: {:?}", e), } } @@ -410,7 +414,7 @@ pub fn parse_opts(args: &[String]) -> Option { let s = matches.free[0].as_slice(); match Regex::new(s) { Ok(re) => Some(re), - Err(e) => return Some(Err(format!("could not parse /{}/: {}", s, e))) + Err(e) => return Some(Err(format!("could not parse /{}/: {:?}", s, e))) } } else { None @@ -793,7 +797,7 @@ impl ConsoleTestState { let ratchet_success = match *ratchet_metrics { None => true, Some(ref pth) => { - try!(self.write_plain(format!("\nusing metrics ratchet: {}\n", + try!(self.write_plain(format!("\nusing metrics ratchet: {:?}\n", pth.display()).as_slice())); match ratchet_pct { None => (), @@ -912,7 +916,7 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec ) -> io::IoR None => (), Some(ref pth) => { try!(st.metrics.save(pth)); - try!(st.write_plain(format!("\nmetrics saved to: {}", + try!(st.write_plain(format!("\nmetrics saved to: {:?}", pth.display()).as_slice())); } } @@ -1206,7 +1210,7 @@ impl MetricMap { let mut decoder = json::Decoder::new(value); MetricMap(match Decodable::decode(&mut decoder) { Ok(t) => t, - Err(e) => panic!("failure decoding JSON: {}", e) + Err(e) => panic!("failure decoding JSON: {:?}", e) }) } diff --git a/src/libtest/stats.rs b/src/libtest/stats.rs index bdc05a50301..3e7e379cd78 100644 --- a/src/libtest/stats.rs +++ b/src/libtest/stats.rs @@ -13,7 +13,7 @@ use std::cmp::Ordering::{self, Less, Greater, Equal}; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::hash_map; -use std::fmt::Show; +use std::fmt; use std::hash::Hash; use std::io; use std::mem; @@ -333,7 +333,7 @@ pub fn winsorize(samples: &mut [T], pct: T) { } /// Render writes the min, max and quartiles of the provided `Summary` to the provided `Writer`. -pub fn write_5_number_summary(w: &mut W, +pub fn write_5_number_summary(w: &mut W, s: &Summary) -> io::IoResult<()> { let (q1,q2,q3) = s.quartiles; write!(w, "(min={}, q1={}, med={}, q3={}, max={})", @@ -355,7 +355,7 @@ pub fn write_5_number_summary(w: &mut W, /// ```{.ignore} /// 10 | [--****#******----------] | 40 /// ``` -pub fn write_boxplot( +pub fn write_boxplot( w: &mut W, s: &Summary, width_hint: uint) diff --git a/src/llvm b/src/llvm index b820135911e..ec1fdb3b9d3 160000 --- a/src/llvm +++ b/src/llvm @@ -1 +1 @@ -Subproject commit b820135911e17c7a46b901db56baa48e5155bf46 +Subproject commit ec1fdb3b9d3b1fb9e1dae97a65dd3a13db9bfb23 diff --git a/src/rust-installer b/src/rust-installer index b5ac4cd4432..3a37981744a 160000 --- a/src/rust-installer +++ b/src/rust-installer @@ -1 +1 @@ -Subproject commit b5ac4cd44321da10dfd70f070dbc9094ca3f92ff +Subproject commit 3a37981744a5af2433fed551f742465c78c9af7f diff --git a/src/test/auxiliary/cci_class_cast.rs b/src/test/auxiliary/cci_class_cast.rs index 6799b5fa85c..0a888d2bd11 100644 --- a/src/test/auxiliary/cci_class_cast.rs +++ b/src/test/auxiliary/cci_class_cast.rs @@ -17,7 +17,7 @@ pub mod kitty { pub name : String, } - impl fmt::Show for cat { + impl fmt::String for cat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name) } diff --git a/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs b/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs index 047ab93530b..23ef5331b49 100644 --- a/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs +++ b/src/test/compile-fail/borrowck-move-out-of-vec-tail.rs @@ -35,7 +35,7 @@ pub fn main() { } } let z = tail[0].clone(); - println!("{}", z); + println!("{:?}", z); } _ => { unreachable!(); diff --git a/src/test/compile-fail/copy-a-resource.rs b/src/test/compile-fail/copy-a-resource.rs index 98cf7009f0f..01c6970506c 100644 --- a/src/test/compile-fail/copy-a-resource.rs +++ b/src/test/compile-fail/copy-a-resource.rs @@ -27,5 +27,5 @@ fn main() { let x = foo(10); let _y = x.clone(); //~^ ERROR does not implement any method in scope - println!("{}", x); + println!("{:?}", x); } diff --git a/src/test/compile-fail/ifmt-bad-arg.rs b/src/test/compile-fail/ifmt-bad-arg.rs index db7f49272aa..7c929d2db16 100644 --- a/src/test/compile-fail/ifmt-bad-arg.rs +++ b/src/test/compile-fail/ifmt-bad-arg.rs @@ -46,7 +46,7 @@ fn main() { // bad syntax of the format string - format!("{"); //~ ERROR: expected `}` but string was terminated + format!("{"); //~ ERROR: expected `'}'` but string was terminated format!("foo } bar"); //~ ERROR: unmatched `}` found format!("foo }"); //~ ERROR: unmatched `}` found diff --git a/src/test/compile-fail/issue-14853.rs b/src/test/compile-fail/issue-14853.rs index 6515b34d964..3d8ebc1ecdf 100644 --- a/src/test/compile-fail/issue-14853.rs +++ b/src/test/compile-fail/issue-14853.rs @@ -27,5 +27,5 @@ impl Something for X { fn main() { let arr = &["one", "two", "three"]; - println!("{}", Something::yay(None::, arr)); + println!("{:?}", Something::yay(None::, arr)); } diff --git a/src/test/compile-fail/issue-15094.rs b/src/test/compile-fail/issue-15094.rs index dd3c88b8a10..5292848f8ee 100644 --- a/src/test/compile-fail/issue-15094.rs +++ b/src/test/compile-fail/issue-15094.rs @@ -19,7 +19,7 @@ struct Shower { impl ops::Fn<(), ()> for Shower { fn call(&self, _args: ()) { //~^ ERROR `call` has an incompatible type for trait: expected "rust-call" fn, found "Rust" fn - println!("{}", self.x); + println!("{:?}", self.x); } } diff --git a/src/test/compile-fail/issue-17728.rs b/src/test/compile-fail/issue-17728.rs index ac2eb735637..66ef7b807f7 100644 --- a/src/test/compile-fail/issue-17728.rs +++ b/src/test/compile-fail/issue-17728.rs @@ -123,8 +123,8 @@ fn str_to_direction(to_parse: &str) -> RoomDirection { fn main() { let mut player = Player::new("Test player"); let mut room = Room::new("A test room"); - println!("Made a player: {}", player); - println!("Direction parse: {}", str_to_direction("east")); + println!("Made a player: {:?}", player); + println!("Direction parse: {:?}", str_to_direction("east")); match player.attemptTraverse(&room, "west") { Ok(_) => println!("Was able to move west"), Err(msg) => println!("Not able to move west: {}", msg) diff --git a/src/test/compile-fail/issue-5062.rs b/src/test/compile-fail/issue-5062.rs index 5082c3102dd..7bf3449a664 100644 --- a/src/test/compile-fail/issue-5062.rs +++ b/src/test/compile-fail/issue-5062.rs @@ -8,5 +8,5 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -fn main() { format!("{}", None); } +fn main() { format!("{:?}", None); } //~^ ERROR type annotations required diff --git a/src/test/compile-fail/issue-6458-2.rs b/src/test/compile-fail/issue-6458-2.rs index 07c1686a7ac..0143c75bfc6 100644 --- a/src/test/compile-fail/issue-6458-2.rs +++ b/src/test/compile-fail/issue-6458-2.rs @@ -10,6 +10,6 @@ fn main() { // Unconstrained type: - format!("{}", None); + format!("{:?}", None); //~^ ERROR type annotations required } diff --git a/src/test/compile-fail/linkage3.rs b/src/test/compile-fail/linkage3.rs index 6c1b3ef67cc..c75c7002e5e 100644 --- a/src/test/compile-fail/linkage3.rs +++ b/src/test/compile-fail/linkage3.rs @@ -16,6 +16,6 @@ extern { } fn main() { - println!("{}", foo); + println!("{:?}", foo); } diff --git a/src/test/compile-fail/lint-uppercase-variables.rs b/src/test/compile-fail/lint-uppercase-variables.rs index 19373c806f1..b6eda8635c2 100644 --- a/src/test/compile-fail/lint-uppercase-variables.rs +++ b/src/test/compile-fail/lint-uppercase-variables.rs @@ -32,7 +32,7 @@ fn main() { let mut buff = [0u8; 16]; match f.read(&mut buff) { Ok(cnt) => println!("read this many bytes: {}", cnt), - Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {}", EndOfFile.to_string()), + Err(IoError{ kind: EndOfFile, .. }) => println!("Got end of file: {:?}", EndOfFile), //~^ ERROR variable `EndOfFile` should have a snake case name such as `end_of_file` //~^^ WARN `EndOfFile` is named the same as one of the variants of the type `std::io::IoErrorKind` } diff --git a/src/test/compile-fail/liveness-use-after-send.rs b/src/test/compile-fail/liveness-use-after-send.rs index f25d2a9b00c..44d45463f19 100644 --- a/src/test/compile-fail/liveness-use-after-send.rs +++ b/src/test/compile-fail/liveness-use-after-send.rs @@ -9,8 +9,8 @@ // except according to those terms. fn send(ch: _chan, data: T) { - println!("{}", ch); - println!("{}", data); + println!("{:?}", ch); + println!("{:?}", data); panic!(); } diff --git a/src/test/compile-fail/no-send-res-ports.rs b/src/test/compile-fail/no-send-res-ports.rs index 9e56b27a05b..6f5741788ee 100644 --- a/src/test/compile-fail/no-send-res-ports.rs +++ b/src/test/compile-fail/no-send-res-ports.rs @@ -39,6 +39,6 @@ fn main() { //~^ ERROR `core::kinds::Send` is not implemented //~^^ ERROR `core::kinds::Send` is not implemented let y = x; - println!("{}", y); + println!("{:?}", y); }); } diff --git a/src/test/compile-fail/noncopyable-class.rs b/src/test/compile-fail/noncopyable-class.rs index aceec2aafdf..ec8369d6736 100644 --- a/src/test/compile-fail/noncopyable-class.rs +++ b/src/test/compile-fail/noncopyable-class.rs @@ -42,5 +42,5 @@ fn foo(i:int) -> foo { fn main() { let x = foo(10); let _y = x.clone(); //~ ERROR does not implement any method in scope - println!("{}", x); + println!("{:?}", x); } diff --git a/src/test/compile-fail/packed-struct-transmute.rs b/src/test/compile-fail/packed-struct-transmute.rs index 91c6776e52e..200c8a5137a 100644 --- a/src/test/compile-fail/packed-struct-transmute.rs +++ b/src/test/compile-fail/packed-struct-transmute.rs @@ -33,6 +33,6 @@ fn main() { let foo = Foo { bar: 1, baz: 10 }; unsafe { let oof: Oof = mem::transmute(foo); - println!("{}", oof); + println!("{:?}", oof); } } diff --git a/src/test/compile-fail/static-reference-to-fn-2.rs b/src/test/compile-fail/static-reference-to-fn-2.rs index d58e89e7767..460154f25d7 100644 --- a/src/test/compile-fail/static-reference-to-fn-2.rs +++ b/src/test/compile-fail/static-reference-to-fn-2.rs @@ -53,9 +53,9 @@ fn state_iter() -> StateMachineIter<'static> { fn main() { let mut it = state_iter(); - println!("{}",it.next()); - println!("{}",it.next()); - println!("{}",it.next()); - println!("{}",it.next()); - println!("{}",it.next()); + println!("{:?}",it.next()); + println!("{:?}",it.next()); + println!("{:?}",it.next()); + println!("{:?}",it.next()); + println!("{:?}",it.next()); } diff --git a/src/test/compile-fail/unique-pinned-nocopy.rs b/src/test/compile-fail/unique-pinned-nocopy.rs index 704d8c568c4..d306d171ca8 100644 --- a/src/test/compile-fail/unique-pinned-nocopy.rs +++ b/src/test/compile-fail/unique-pinned-nocopy.rs @@ -20,5 +20,5 @@ impl Drop for r { fn main() { let i = box r { b: true }; let _j = i.clone(); //~ ERROR not implement - println!("{}", i); + println!("{:?}", i); } diff --git a/src/test/compile-fail/unique-vec-res.rs b/src/test/compile-fail/unique-vec-res.rs index 8aabc9b042f..4848c988300 100644 --- a/src/test/compile-fail/unique-vec-res.rs +++ b/src/test/compile-fail/unique-vec-res.rs @@ -39,6 +39,6 @@ fn main() { f(clone(&r1), clone(&r2)); //~^ ERROR the trait `core::clone::Clone` is not implemented for the type //~^^ ERROR the trait `core::clone::Clone` is not implemented for the type - println!("{}", (r2, i1.get())); - println!("{}", (r1, i2.get())); + println!("{:?}", (r2, i1.get())); + println!("{:?}", (r1, i2.get())); } 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 3f2f43b0c9b..364bfc42985 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 @@ -16,7 +16,7 @@ struct Number { n: i64 } -impl fmt::Show for Number { +impl fmt::String for Number { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.n) } diff --git a/src/test/compile-fail/vec-res-add.rs b/src/test/compile-fail/vec-res-add.rs index 28a7ceeeaa2..dc166f9fd9d 100644 --- a/src/test/compile-fail/vec-res-add.rs +++ b/src/test/compile-fail/vec-res-add.rs @@ -25,5 +25,5 @@ fn main() { let j = vec!(r(1)); let k = i + j; //~^ ERROR binary operation `+` cannot be applied to type - println!("{}", j); + println!("{:?}", j); } diff --git a/src/test/run-fail/assert-eq-macro-panic.rs b/src/test/run-fail/assert-eq-macro-panic.rs index 69ed025070b..4b1a420cb78 100644 --- a/src/test/run-fail/assert-eq-macro-panic.rs +++ b/src/test/run-fail/assert-eq-macro-panic.rs @@ -8,7 +8,7 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -// error-pattern:assertion failed: `(left == right) && (right == left)` (left: `14`, right: `15`) +// error-pattern:assertion failed: `(left == right) && (right == left)` (left: `14i`, right: `15i`) fn main() { assert_eq!(14i,15i); diff --git a/src/test/run-pass/borrowck-mut-uniq.rs b/src/test/run-pass/borrowck-mut-uniq.rs index dac8945b6e8..c586ff2c93a 100644 --- a/src/test/run-pass/borrowck-mut-uniq.rs +++ b/src/test/run-pass/borrowck-mut-uniq.rs @@ -32,9 +32,9 @@ pub fn main() { add_int(&mut *ints, 44); iter_ints(&*ints, |i| { - println!("int = {}", *i); + println!("int = {:?}", *i); true }); - println!("ints={}", ints); + println!("ints={:?}", ints); } diff --git a/src/test/run-pass/class-separate-impl.rs b/src/test/run-pass/class-separate-impl.rs index 86d7b72f4ff..9c7913dc0b0 100644 --- a/src/test/run-pass/class-separate-impl.rs +++ b/src/test/run-pass/class-separate-impl.rs @@ -51,7 +51,7 @@ fn cat(in_x : uint, in_y : int, in_name: String) -> cat { } } -impl fmt::Show for cat { +impl fmt::String for cat { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.name) } diff --git a/src/test/run-pass/conditional-debug-macro-off.rs b/src/test/run-pass/conditional-debug-macro-off.rs index e3bdbeb1692..b5a5f57d07a 100644 --- a/src/test/run-pass/conditional-debug-macro-off.rs +++ b/src/test/run-pass/conditional-debug-macro-off.rs @@ -16,5 +16,5 @@ extern crate log; pub fn main() { // only panics if println! evaluates its argument. - debug!("{}", { if true { panic!() } }); + debug!("{:?}", { if true { panic!() } }); } diff --git a/src/test/run-pass/conditional-debug-macro-on.rs b/src/test/run-pass/conditional-debug-macro-on.rs index 0591828bb13..b335e20f91d 100644 --- a/src/test/run-pass/conditional-debug-macro-on.rs +++ b/src/test/run-pass/conditional-debug-macro-on.rs @@ -13,7 +13,7 @@ pub fn main() { // exits early if println! evaluates its arguments, otherwise it // will hit the panic. - println!("{}", { if true { return; } }); + println!("{:?}", { if true { return; } }); panic!(); } diff --git a/src/test/run-pass/deriving-in-fn.rs b/src/test/run-pass/deriving-in-fn.rs index d191bad10ea..cd79f84b7cb 100644 --- a/src/test/run-pass/deriving-in-fn.rs +++ b/src/test/run-pass/deriving-in-fn.rs @@ -15,5 +15,5 @@ pub fn main() { } let f = Foo { foo: 10 }; - format!("{}", f); + format!("{:?}", f); } diff --git a/src/test/run-pass/deriving-show-2.rs b/src/test/run-pass/deriving-show-2.rs index 58faab7bfbe..8465f521e43 100644 --- a/src/test/run-pass/deriving-show-2.rs +++ b/src/test/run-pass/deriving-show-2.rs @@ -38,16 +38,25 @@ impl fmt::Show for Custom { } } -pub fn main() { - assert_eq!(B::B1.to_string(), "B1".to_string()); - assert_eq!(B::B2.to_string(), "B2".to_string()); - assert_eq!(C::C1(3).to_string(), "C1(3)".to_string()); - assert_eq!(C::C2(B::B2).to_string(), "C2(B2)".to_string()); - assert_eq!(D::D1{ a: 2 }.to_string(), "D1 { a: 2 }".to_string()); - assert_eq!(E.to_string(), "E".to_string()); - assert_eq!(F(3).to_string(), "F(3)".to_string()); - assert_eq!(G(3, 4).to_string(), "G(3, 4)".to_string()); - assert_eq!(G(3, 4).to_string(), "G(3, 4)".to_string()); - assert_eq!(I{ a: 2, b: 4 }.to_string(), "I { a: 2, b: 4 }".to_string()); - assert_eq!(J(Custom).to_string(), "J(yay)".to_string()); +trait ToShow { + fn to_show(&self) -> String; +} + +impl ToShow for T { + fn to_show(&self) -> String { + format!("{:?}", self) + } +} + +pub fn main() { + assert_eq!(B::B1.to_show(), "B1".to_string()); + assert_eq!(B::B2.to_show(), "B2".to_string()); + assert_eq!(C::C1(3).to_show(), "C1(3i)".to_string()); + assert_eq!(C::C2(B::B2).to_show(), "C2(B2)".to_string()); + assert_eq!(D::D1{ a: 2 }.to_show(), "D1 { a: 2i }".to_string()); + assert_eq!(E.to_show(), "E".to_string()); + assert_eq!(F(3).to_show(), "F(3i)".to_string()); + assert_eq!(G(3, 4).to_show(), "G(3i, 4i)".to_string()); + assert_eq!(I{ a: 2, b: 4 }.to_show(), "I { a: 2i, b: 4i }".to_string()); + assert_eq!(J(Custom).to_show(), "J(yay)".to_string()); } diff --git a/src/test/run-pass/deriving-show.rs b/src/test/run-pass/deriving-show.rs index e8086b8b7c6..99c73dd94a6 100644 --- a/src/test/run-pass/deriving-show.rs +++ b/src/test/run-pass/deriving-show.rs @@ -26,15 +26,15 @@ enum Enum { macro_rules! t { ($x:expr, $expected:expr) => { - assert_eq!(format!("{}", $x), $expected.to_string()) + assert_eq!(format!("{:?}", $x), $expected.to_string()) } } pub fn main() { t!(Unit, "Unit"); - t!(Tuple(1, 2), "Tuple(1, 2)"); - t!(Struct { x: 1, y: 2 }, "Struct { x: 1, y: 2 }"); + t!(Tuple(1, 2), "Tuple(1i, 2u)"); + t!(Struct { x: 1, y: 2 }, "Struct { x: 1i, y: 2u }"); t!(Enum::Nullary, "Nullary"); - t!(Enum::Variant(1, 2), "Variant(1, 2)"); - t!(Enum::StructVariant { x: 1, y: 2 }, "StructVariant { x: 1, y: 2 }"); + t!(Enum::Variant(1, 2), "Variant(1i, 2u)"); + t!(Enum::StructVariant { x: 1, y: 2 }, "StructVariant { x: 1i, y: 2u }"); } diff --git a/src/test/run-pass/dst-index.rs b/src/test/run-pass/dst-index.rs index d1823359af1..6f8574ccfa2 100644 --- a/src/test/run-pass/dst-index.rs +++ b/src/test/run-pass/dst-index.rs @@ -37,5 +37,5 @@ impl Index for T { fn main() { assert_eq!(&S[0], "hello"); - assert_eq!(format!("{}", &T[0]).as_slice(), "42"); + assert_eq!(format!("{:?}", &T[0]), "42u"); } diff --git a/src/test/run-pass/enum-discrim-width-stuff.rs b/src/test/run-pass/enum-discrim-width-stuff.rs index 07941eca224..73559af79de 100644 --- a/src/test/run-pass/enum-discrim-width-stuff.rs +++ b/src/test/run-pass/enum-discrim-width-stuff.rs @@ -23,8 +23,8 @@ macro_rules! check { assert_eq!(size_of::(), size_of::<$t>()); assert_eq!(E::V as $t, $v as $t); assert_eq!(C as $t, $v as $t); - assert_eq!(format!("{}", E::V), "V".to_string()); - assert_eq!(format!("{}", C), "V".to_string()); + assert_eq!(format!("{:?}", E::V), "V".to_string()); + assert_eq!(format!("{:?}", C), "V".to_string()); } } $m::check(); diff --git a/src/test/run-pass/functional-struct-upd.rs b/src/test/run-pass/functional-struct-upd.rs index e2297661d65..5f2ebc6cbed 100644 --- a/src/test/run-pass/functional-struct-upd.rs +++ b/src/test/run-pass/functional-struct-upd.rs @@ -17,5 +17,5 @@ struct Foo { pub fn main() { let a = Foo { x: 1, y: 2 }; let c = Foo { x: 4, .. a}; - println!("{}", c); + println!("{:?}", c); } diff --git a/src/test/run-pass/ifmt.rs b/src/test/run-pass/ifmt.rs index d38b0ea2747..cd438b5e339 100644 --- a/src/test/run-pass/ifmt.rs +++ b/src/test/run-pass/ifmt.rs @@ -30,7 +30,7 @@ impl fmt::UpperHex for B { f.write_str("adios") } } -impl fmt::Show for C { +impl fmt::String for C { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.pad_integral(true, "☃", "123") } @@ -58,9 +58,12 @@ pub fn main() { t!(format!("{}", true), "true"); t!(format!("{}", '☃'), "☃"); t!(format!("{}", 10i), "10"); - t!(format!("{}", 10i), "10"); t!(format!("{}", 10u), "10"); - t!(format!("{:?}", true), "true"); + t!(format!("{:?}", '☃'), "'\\u{2603}'"); + t!(format!("{:?}", 10i), "10i"); + t!(format!("{:?}", 10u), "10u"); + t!(format!("{:?}", "true"), "\"true\""); + t!(format!("{:?}", "foo\nbar"), "\"foo\\nbar\""); t!(format!("{:o}", 10u), "12"); t!(format!("{:x}", 10u), "a"); t!(format!("{:X}", 10u), "A"); @@ -80,7 +83,8 @@ pub fn main() { t!(format!("{:#4}", C), "☃123"); let a: &fmt::Show = &1i; - t!(format!("{}", a), "1"); + t!(format!("{:?}", a), "1i"); + // Formatting strings and their arguments t!(format!("{}", "a"), "a"); diff --git a/src/test/run-pass/issue-10396.rs b/src/test/run-pass/issue-10396.rs index ea311e6e32c..308783f0d4b 100644 --- a/src/test/run-pass/issue-10396.rs +++ b/src/test/run-pass/issue-10396.rs @@ -15,7 +15,7 @@ enum Foo<'s> { fn f(arr: &[&Foo]) { for &f in arr.iter() { - println!("{}", f); + println!("{:?}", f); } } diff --git a/src/test/run-pass/issue-10626.rs b/src/test/run-pass/issue-10626.rs index 8a6e300bd15..b06799444f4 100644 --- a/src/test/run-pass/issue-10626.rs +++ b/src/test/run-pass/issue-10626.rs @@ -30,5 +30,5 @@ pub fn main () { let mut p = process::Command::new(args[0].as_slice()); p.arg("child").stdout(process::Ignored).stderr(process::Ignored); - println!("{}", p.spawn().unwrap().wait()); + println!("{:?}", p.spawn().unwrap().wait()); } diff --git a/src/test/run-pass/issue-11267.rs b/src/test/run-pass/issue-11267.rs index f08805fe49c..6fb2c532e0c 100644 --- a/src/test/run-pass/issue-11267.rs +++ b/src/test/run-pass/issue-11267.rs @@ -20,7 +20,7 @@ impl T for Empty { } fn do_something_with(a : &mut T) { - println!("{}", a.next()) + println!("{:?}", a.next()) } pub fn main() { diff --git a/src/test/run-pass/issue-12744.rs b/src/test/run-pass/issue-12744.rs index 1182cf5b29f..a91dbd2b716 100644 --- a/src/test/run-pass/issue-12744.rs +++ b/src/test/run-pass/issue-12744.rs @@ -10,5 +10,5 @@ fn main() { fn test() -> Box { box 1i } - println!("{}", test()) + println!("{:?}", test()) } diff --git a/src/test/run-pass/issue-13434.rs b/src/test/run-pass/issue-13434.rs index e5fd17e2dfe..35e487539fa 100644 --- a/src/test/run-pass/issue-13434.rs +++ b/src/test/run-pass/issue-13434.rs @@ -26,5 +26,5 @@ fn do_stuff(r: R) -> String { } pub fn main() { - assert_eq!("MyStruct".to_string(), do_stuff(|: s: MyStruct| format!("{}", s))); + assert_eq!("MyStruct".to_string(), do_stuff(|: s: MyStruct| format!("{:?}", s))); } diff --git a/src/test/run-pass/issue-1696.rs b/src/test/run-pass/issue-1696.rs index e69738d4caa..40e112d6fbf 100644 --- a/src/test/run-pass/issue-1696.rs +++ b/src/test/run-pass/issue-1696.rs @@ -15,5 +15,5 @@ use std::collections::HashMap; pub fn main() { let mut m = HashMap::new(); m.insert(b"foo".to_vec(), b"bar".to_vec()); - println!("{}", m); + println!("{:?}", m); } diff --git a/src/test/run-pass/issue-19135.rs b/src/test/run-pass/issue-19135.rs index b9d0a9a2988..c90880ff120 100644 --- a/src/test/run-pass/issue-19135.rs +++ b/src/test/run-pass/issue-19135.rs @@ -14,7 +14,7 @@ struct LifetimeStruct<'a>; fn main() { - takes_hrtb_closure(|&mut: lts| println!("{}", lts)); + takes_hrtb_closure(|&mut: lts| println!("{:?}", lts)); } fn takes_hrtb_closureFnMut(LifetimeStruct<'a>)>(mut f: F) { diff --git a/src/test/run-pass/issue-19358.rs b/src/test/run-pass/issue-19358.rs index 86687fccd61..36093482175 100644 --- a/src/test/run-pass/issue-19358.rs +++ b/src/test/run-pass/issue-19358.rs @@ -25,5 +25,5 @@ impl Trait for int {} fn main() { let a = Foo { foo: 12i }; let b = Bar { bar: 12i }; - println!("{} {}", a, b); + println!("{:?} {:?}", a, b); } diff --git a/src/test/run-pass/issue-3109.rs b/src/test/run-pass/issue-3109.rs index 86913c0e8d4..dc22ebce804 100644 --- a/src/test/run-pass/issue-3109.rs +++ b/src/test/run-pass/issue-3109.rs @@ -9,5 +9,5 @@ // except according to those terms. pub fn main() { - println!("{}", ("hi there!", "you")); + println!("{:?}", ("hi there!", "you")); } diff --git a/src/test/run-pass/issue-3556.rs b/src/test/run-pass/issue-3556.rs index e004c24da13..3448273e144 100644 --- a/src/test/run-pass/issue-3556.rs +++ b/src/test/run-pass/issue-3556.rs @@ -43,6 +43,6 @@ pub fn main() "foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string()); - let v = format!("{}", u); // this is the line that causes the seg fault + let v = format!("{:?}", u); // this is the line that causes the seg fault assert!(v.len() > 0); } diff --git a/src/test/run-pass/issue-3559.rs b/src/test/run-pass/issue-3559.rs index 2568d94fcbf..633832f424c 100644 --- a/src/test/run-pass/issue-3559.rs +++ b/src/test/run-pass/issue-3559.rs @@ -24,6 +24,6 @@ pub fn main() { let mut table = HashMap::new(); table.insert("one".to_string(), 1i); table.insert("two".to_string(), 2i); - assert!(check_strs(table.to_string().as_slice(), "{one: 1, two: 2}") || - check_strs(table.to_string().as_slice(), "{two: 2, one: 1}")); + assert!(check_strs(format!("{:?}", table).as_slice(), "HashMap {\"one\": 1i, \"two\": 2i}") || + check_strs(format!("{:?}", table).as_slice(), "HashMap {\"two\": 2i, \"one\": 1i}")); } diff --git a/src/test/run-pass/issue-3563-3.rs b/src/test/run-pass/issue-3563-3.rs index a3903128b65..3fe6e02dcef 100644 --- a/src/test/run-pass/issue-3563-3.rs +++ b/src/test/run-pass/issue-3563-3.rs @@ -104,7 +104,7 @@ impl AsciiArt { // Allows AsciiArt to be converted to a string using the libcore ToString trait. // Note that the %s fmt! specifier will not call this automatically. -impl fmt::Show for AsciiArt { +impl fmt::String for AsciiArt { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // Convert each line into a string. let lines = self.lines.iter() diff --git a/src/test/run-pass/issue-3794.rs b/src/test/run-pass/issue-3794.rs index 4508bc5771c..926b53cf92c 100644 --- a/src/test/run-pass/issue-3794.rs +++ b/src/test/run-pass/issue-3794.rs @@ -19,7 +19,7 @@ struct S { impl T for S { fn print(&self) { - println!("{}", self); + println!("{:?}", self); } } diff --git a/src/test/run-pass/issue-4252.rs b/src/test/run-pass/issue-4252.rs index 6ed35e6bc23..3606aff05ff 100644 --- a/src/test/run-pass/issue-4252.rs +++ b/src/test/run-pass/issue-4252.rs @@ -13,7 +13,7 @@ trait X { fn call(&self, x: &T); fn default_method(&self, x: &T) { - println!("X::default_method {}", x); + println!("X::default_method {:?}", x); } } @@ -27,7 +27,7 @@ struct Z { impl X for Y { fn call(&self, x: &T) { - println!("X::call {} {}", self, x); + println!("X::call {:?} {:?}", self, x); } } diff --git a/src/test/run-pass/issue-7563.rs b/src/test/run-pass/issue-7563.rs index 4d217fbf335..734d131ffdf 100644 --- a/src/test/run-pass/issue-7563.rs +++ b/src/test/run-pass/issue-7563.rs @@ -31,6 +31,6 @@ pub fn main() { let sa = A { a: 100 }; let sb = B { b: 200, pa: &sa }; - println!("sa is {}", sa); - println!("sb is {}", sb); + println!("sa is {:?}", sa); + println!("sb is {:?}", sb); } diff --git a/src/test/run-pass/issue-8898.rs b/src/test/run-pass/issue-8898.rs index 0c19286921a..0ca63d52bd8 100644 --- a/src/test/run-pass/issue-8898.rs +++ b/src/test/run-pass/issue-8898.rs @@ -11,7 +11,7 @@ #![feature(slicing_syntax)] fn assert_repr_eq(obj : T, expected : String) { - assert_eq!(expected, format!("{}", obj)); + assert_eq!(expected, format!("{:?}", obj)); } pub fn main() { @@ -20,7 +20,7 @@ pub fn main() { let x = [(), ()]; let slice = &x[0..1]; - assert_repr_eq(&abc[], "[1, 2, 3]".to_string()); + assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string()); assert_repr_eq(&tf[], "[true, false]".to_string()); assert_repr_eq(&x[], "[(), ()]".to_string()); assert_repr_eq(slice, "[()]".to_string()); diff --git a/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs b/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs index bffa86a2c62..7fb2390b84b 100644 --- a/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs +++ b/src/test/run-pass/log-knows-the-names-of-variants-in-std.rs @@ -15,19 +15,19 @@ enum foo { } fn check_log(exp: String, v: T) { - assert_eq!(exp, format!("{}", v)); + assert_eq!(exp, format!("{:?}", v)); } pub fn main() { let mut x = Some(foo::a(22u)); - let exp = "Some(a(22))".to_string(); - let act = format!("{}", x); + let exp = "Some(a(22u))".to_string(); + let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); x = None; let exp = "None".to_string(); - let act = format!("{}", x); + let act = format!("{:?}", x); assert_eq!(act, exp); check_log(exp, x); } diff --git a/src/test/run-pass/log-knows-the-names-of-variants.rs b/src/test/run-pass/log-knows-the-names-of-variants.rs index e40723ab1b6..45fd2098dc4 100644 --- a/src/test/run-pass/log-knows-the-names-of-variants.rs +++ b/src/test/run-pass/log-knows-the-names-of-variants.rs @@ -21,7 +21,7 @@ enum bar { } pub fn main() { - assert_eq!("a(22)".to_string(), format!("{}", foo::a(22u))); - assert_eq!("c".to_string(), format!("{}", foo::c)); - assert_eq!("d".to_string(), format!("{}", bar::d)); + assert_eq!("a(22u)".to_string(), format!("{:?}", foo::a(22u))); + assert_eq!("c".to_string(), format!("{:?}", foo::c)); + assert_eq!("d".to_string(), format!("{:?}", bar::d)); } diff --git a/src/test/run-pass/log-poly.rs b/src/test/run-pass/log-poly.rs index 163efcb1a2b..a6a99d6fc92 100644 --- a/src/test/run-pass/log-poly.rs +++ b/src/test/run-pass/log-poly.rs @@ -14,8 +14,8 @@ enum Numbers { } pub fn main() { - println!("{}", 1i); - println!("{}", 2.0f64); - println!("{}", Numbers::Three); - println!("{}", vec!(4i)); + println!("{:?}", 1i); + println!("{:?}", 2.0f64); + println!("{:?}", Numbers::Three); + println!("{:?}", vec!(4i)); } diff --git a/src/test/run-pass/logging-only-prints-once.rs b/src/test/run-pass/logging-only-prints-once.rs index 509afff3d13..787d0e98e2b 100644 --- a/src/test/run-pass/logging-only-prints-once.rs +++ b/src/test/run-pass/logging-only-prints-once.rs @@ -29,7 +29,7 @@ impl fmt::Show for Foo { pub fn main() { Thread::spawn(move|| { let mut f = Foo(Cell::new(0)); - println!("{}", f); + println!("{:?}", f); let Foo(ref mut f) = f; assert!(f.get() == 1); }).join().ok().unwrap(); diff --git a/src/test/run-pass/new-impl-syntax.rs b/src/test/run-pass/new-impl-syntax.rs index 8532b5f51dc..84d2083cedd 100644 --- a/src/test/run-pass/new-impl-syntax.rs +++ b/src/test/run-pass/new-impl-syntax.rs @@ -17,7 +17,7 @@ struct Thingy { impl fmt::Show for Thingy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{{ x: {}, y: {} }}", self.x, self.y) + write!(f, "{{ x: {:?}, y: {:?} }}", self.x, self.y) } } @@ -27,11 +27,11 @@ struct PolymorphicThingy { impl fmt::Show for PolymorphicThingy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.x) + write!(f, "{:?}", self.x) } } pub fn main() { - println!("{}", Thingy { x: 1, y: 2 }.to_string()); - println!("{}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } }.to_string()); + println!("{:?}", Thingy { x: 1, y: 2 }); + println!("{:?}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } }); } diff --git a/src/test/run-pass/overloaded-index-assoc-list.rs b/src/test/run-pass/overloaded-index-assoc-list.rs index aac0b5e06d0..2e044227eb1 100644 --- a/src/test/run-pass/overloaded-index-assoc-list.rs +++ b/src/test/run-pass/overloaded-index-assoc-list.rs @@ -37,7 +37,7 @@ impl Index for AssociationList { return &pair.value } } - panic!("No value found for key: {}", index); + panic!("No value found for key: {:?}", index); } } diff --git a/src/test/run-pass/rec-align-u32.rs b/src/test/run-pass/rec-align-u32.rs index e165b34f680..5b91d5e930f 100644 --- a/src/test/run-pass/rec-align-u32.rs +++ b/src/test/run-pass/rec-align-u32.rs @@ -53,11 +53,11 @@ pub fn main() { let x = Outer {c8: 22u8, t: Inner {c64: 44u32}}; // Send it through the shape code - let y = format!("{}", x); + let y = format!("{:?}", x); - println!("align inner = {}", rusti::min_align_of::()); - println!("size outer = {}", mem::size_of::()); - println!("y = {}", y); + println!("align inner = {:?}", rusti::min_align_of::()); + println!("size outer = {:?}", mem::size_of::()); + println!("y = {:?}", y); // per clang/gcc the alignment of `inner` is 4 on x86. assert_eq!(rusti::min_align_of::(), m::align()); @@ -66,6 +66,6 @@ pub fn main() { // because `inner`s alignment was 4. assert_eq!(mem::size_of::(), m::size()); - assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); + assert_eq!(y, "Outer { c8: 22u8, t: Inner { c64: 44u32 } }".to_string()); } } diff --git a/src/test/run-pass/rec-align-u64.rs b/src/test/run-pass/rec-align-u64.rs index c3cec77a646..27941542d00 100644 --- a/src/test/run-pass/rec-align-u64.rs +++ b/src/test/run-pass/rec-align-u64.rs @@ -82,11 +82,11 @@ pub fn main() { unsafe { let x = Outer {c8: 22u8, t: Inner {c64: 44u64}}; - let y = format!("{}", x); + let y = format!("{:?}", x); - println!("align inner = {}", rusti::min_align_of::()); - println!("size outer = {}", mem::size_of::()); - println!("y = {}", y); + println!("align inner = {:?}", rusti::min_align_of::()); + println!("size outer = {:?}", mem::size_of::()); + println!("y = {:?}", y); // per clang/gcc the alignment of `Inner` is 4 on x86. assert_eq!(rusti::min_align_of::(), m::m::align()); @@ -95,6 +95,6 @@ pub fn main() { // because `Inner`s alignment was 4. assert_eq!(mem::size_of::(), m::m::size()); - assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); + assert_eq!(y, "Outer { c8: 22u8, t: Inner { c64: 44u64 } }".to_string()); } } diff --git a/src/test/run-pass/resource-assign-is-not-copy.rs b/src/test/run-pass/resource-assign-is-not-copy.rs index a67b24f8b1e..57f72b23adf 100644 --- a/src/test/run-pass/resource-assign-is-not-copy.rs +++ b/src/test/run-pass/resource-assign-is-not-copy.rs @@ -37,7 +37,7 @@ pub fn main() { let a = r(i); let b = (a, 10i); let (c, _d) = b; - println!("{}", c); + println!("{:?}", c); } assert_eq!(i.get(), 1); } diff --git a/src/test/run-pass/running-with-no-runtime.rs b/src/test/run-pass/running-with-no-runtime.rs index 6f807fc3499..d6c25672cdb 100644 --- a/src/test/run-pass/running-with-no-runtime.rs +++ b/src/test/run-pass/running-with-no-runtime.rs @@ -57,7 +57,7 @@ fn start(argc: int, argv: *const *const u8) -> int { fn pass(output: ProcessOutput) { if !output.status.success() { - println!("{}", str::from_utf8(output.output.as_slice())); - println!("{}", str::from_utf8(output.error.as_slice())); + println!("{:?}", str::from_utf8(output.output.as_slice())); + println!("{:?}", str::from_utf8(output.error.as_slice())); } } diff --git a/src/test/run-pass/show-boxed-slice.rs b/src/test/run-pass/show-boxed-slice.rs index 2273c399c9a..e0d005a485b 100644 --- a/src/test/run-pass/show-boxed-slice.rs +++ b/src/test/run-pass/show-boxed-slice.rs @@ -12,5 +12,5 @@ struct Foo(Box<[u8]>); pub fn main() { - println!("{}", Foo(box [0, 1, 2])); + println!("{:?}", Foo(box [0, 1, 2])); } diff --git a/src/test/run-pass/small-enums-with-fields.rs b/src/test/run-pass/small-enums-with-fields.rs index 46daa659430..c793deaae2b 100644 --- a/src/test/run-pass/small-enums-with-fields.rs +++ b/src/test/run-pass/small-enums-with-fields.rs @@ -20,8 +20,8 @@ macro_rules! check { static S: $t = $e; let v: $t = $e; assert_eq!(S, v); - assert_eq!(format!("{}", v).as_slice(), $s); - assert_eq!(format!("{}", S).as_slice(), $s); + assert_eq!(format!("{:?}", v).as_slice(), $s); + assert_eq!(format!("{:?}", S).as_slice(), $s); });* }} } @@ -29,14 +29,14 @@ macro_rules! check { pub fn main() { check!(Option, 2, None, "None", - Some(129u8), "Some(129)"); + Some(129u8), "Some(129u8)"); check!(Option, 4, None, "None", - Some(-20000i16), "Some(-20000)"); + Some(-20000i16), "Some(-20000i16)"); check!(Either, 2, - Either::Left(132u8), "Left(132)", - Either::Right(-32i8), "Right(-32)"); + Either::Left(132u8), "Left(132u8)", + Either::Right(-32i8), "Right(-32i8)"); check!(Either, 4, - Either::Left(132u8), "Left(132)", - Either::Right(-20000i16), "Right(-20000)"); + Either::Left(132u8), "Left(132u8)", + Either::Right(-20000i16), "Right(-20000i16)"); } diff --git a/src/test/run-pass/supported-cast.rs b/src/test/run-pass/supported-cast.rs index 2757439828d..7cba4533c7f 100644 --- a/src/test/run-pass/supported-cast.rs +++ b/src/test/run-pass/supported-cast.rs @@ -12,208 +12,208 @@ extern crate libc; pub fn main() { let f = 1u as *const libc::FILE; - println!("{}", f as int); - println!("{}", f as uint); - println!("{}", f as i8); - println!("{}", f as i16); - println!("{}", f as i32); - println!("{}", f as i64); - println!("{}", f as u8); - println!("{}", f as u16); - println!("{}", f as u32); - println!("{}", f as u64); + println!("{:?}", f as int); + println!("{:?}", f as uint); + println!("{:?}", f as i8); + println!("{:?}", f as i16); + println!("{:?}", f as i32); + println!("{:?}", f as i64); + println!("{:?}", f as u8); + println!("{:?}", f as u16); + println!("{:?}", f as u32); + println!("{:?}", f as u64); - println!("{}", 1 as int); - println!("{}", 1 as uint); - println!("{}", 1 as *const libc::FILE); - println!("{}", 1 as i8); - println!("{}", 1 as i16); - println!("{}", 1 as i32); - println!("{}", 1 as i64); - println!("{}", 1 as u8); - println!("{}", 1 as u16); - println!("{}", 1 as u32); - println!("{}", 1 as u64); - println!("{}", 1i as f32); - println!("{}", 1i as f64); + println!("{:?}", 1 as int); + println!("{:?}", 1 as uint); + println!("{:?}", 1 as *const libc::FILE); + println!("{:?}", 1 as i8); + println!("{:?}", 1 as i16); + println!("{:?}", 1 as i32); + println!("{:?}", 1 as i64); + println!("{:?}", 1 as u8); + println!("{:?}", 1 as u16); + println!("{:?}", 1 as u32); + println!("{:?}", 1 as u64); + println!("{:?}", 1i as f32); + println!("{:?}", 1i as f64); - println!("{}", 1u as int); - println!("{}", 1u as uint); - println!("{}", 1u as *const libc::FILE); - println!("{}", 1u as i8); - println!("{}", 1u as i16); - println!("{}", 1u as i32); - println!("{}", 1u as i64); - println!("{}", 1u as u8); - println!("{}", 1u as u16); - println!("{}", 1u as u32); - println!("{}", 1u as u64); - println!("{}", 1u as f32); - println!("{}", 1u as f64); + println!("{:?}", 1u as int); + println!("{:?}", 1u as uint); + println!("{:?}", 1u as *const libc::FILE); + println!("{:?}", 1u as i8); + println!("{:?}", 1u as i16); + println!("{:?}", 1u as i32); + println!("{:?}", 1u as i64); + println!("{:?}", 1u as u8); + println!("{:?}", 1u as u16); + println!("{:?}", 1u as u32); + println!("{:?}", 1u as u64); + println!("{:?}", 1u as f32); + println!("{:?}", 1u as f64); - println!("{}", 1i8 as int); - println!("{}", 1i8 as uint); - println!("{}", 1i8 as *const libc::FILE); - println!("{}", 1i8 as i8); - println!("{}", 1i8 as i16); - println!("{}", 1i8 as i32); - println!("{}", 1i8 as i64); - println!("{}", 1i8 as u8); - println!("{}", 1i8 as u16); - println!("{}", 1i8 as u32); - println!("{}", 1i8 as u64); - println!("{}", 1i8 as f32); - println!("{}", 1i8 as f64); + println!("{:?}", 1i8 as int); + println!("{:?}", 1i8 as uint); + println!("{:?}", 1i8 as *const libc::FILE); + println!("{:?}", 1i8 as i8); + println!("{:?}", 1i8 as i16); + println!("{:?}", 1i8 as i32); + println!("{:?}", 1i8 as i64); + println!("{:?}", 1i8 as u8); + println!("{:?}", 1i8 as u16); + println!("{:?}", 1i8 as u32); + println!("{:?}", 1i8 as u64); + println!("{:?}", 1i8 as f32); + println!("{:?}", 1i8 as f64); - println!("{}", 1u8 as int); - println!("{}", 1u8 as uint); - println!("{}", 1u8 as *const libc::FILE); - println!("{}", 1u8 as i8); - println!("{}", 1u8 as i16); - println!("{}", 1u8 as i32); - println!("{}", 1u8 as i64); - println!("{}", 1u8 as u8); - println!("{}", 1u8 as u16); - println!("{}", 1u8 as u32); - println!("{}", 1u8 as u64); - println!("{}", 1u8 as f32); - println!("{}", 1u8 as f64); + println!("{:?}", 1u8 as int); + println!("{:?}", 1u8 as uint); + println!("{:?}", 1u8 as *const libc::FILE); + println!("{:?}", 1u8 as i8); + println!("{:?}", 1u8 as i16); + println!("{:?}", 1u8 as i32); + println!("{:?}", 1u8 as i64); + println!("{:?}", 1u8 as u8); + println!("{:?}", 1u8 as u16); + println!("{:?}", 1u8 as u32); + println!("{:?}", 1u8 as u64); + println!("{:?}", 1u8 as f32); + println!("{:?}", 1u8 as f64); - println!("{}", 1i16 as int); - println!("{}", 1i16 as uint); - println!("{}", 1i16 as *const libc::FILE); - println!("{}", 1i16 as i8); - println!("{}", 1i16 as i16); - println!("{}", 1i16 as i32); - println!("{}", 1i16 as i64); - println!("{}", 1i16 as u8); - println!("{}", 1i16 as u16); - println!("{}", 1i16 as u32); - println!("{}", 1i16 as u64); - println!("{}", 1i16 as f32); - println!("{}", 1i16 as f64); + println!("{:?}", 1i16 as int); + println!("{:?}", 1i16 as uint); + println!("{:?}", 1i16 as *const libc::FILE); + println!("{:?}", 1i16 as i8); + println!("{:?}", 1i16 as i16); + println!("{:?}", 1i16 as i32); + println!("{:?}", 1i16 as i64); + println!("{:?}", 1i16 as u8); + println!("{:?}", 1i16 as u16); + println!("{:?}", 1i16 as u32); + println!("{:?}", 1i16 as u64); + println!("{:?}", 1i16 as f32); + println!("{:?}", 1i16 as f64); - println!("{}", 1u16 as int); - println!("{}", 1u16 as uint); - println!("{}", 1u16 as *const libc::FILE); - println!("{}", 1u16 as i8); - println!("{}", 1u16 as i16); - println!("{}", 1u16 as i32); - println!("{}", 1u16 as i64); - println!("{}", 1u16 as u8); - println!("{}", 1u16 as u16); - println!("{}", 1u16 as u32); - println!("{}", 1u16 as u64); - println!("{}", 1u16 as f32); - println!("{}", 1u16 as f64); + println!("{:?}", 1u16 as int); + println!("{:?}", 1u16 as uint); + println!("{:?}", 1u16 as *const libc::FILE); + println!("{:?}", 1u16 as i8); + println!("{:?}", 1u16 as i16); + println!("{:?}", 1u16 as i32); + println!("{:?}", 1u16 as i64); + println!("{:?}", 1u16 as u8); + println!("{:?}", 1u16 as u16); + println!("{:?}", 1u16 as u32); + println!("{:?}", 1u16 as u64); + println!("{:?}", 1u16 as f32); + println!("{:?}", 1u16 as f64); - println!("{}", 1i32 as int); - println!("{}", 1i32 as uint); - println!("{}", 1i32 as *const libc::FILE); - println!("{}", 1i32 as i8); - println!("{}", 1i32 as i16); - println!("{}", 1i32 as i32); - println!("{}", 1i32 as i64); - println!("{}", 1i32 as u8); - println!("{}", 1i32 as u16); - println!("{}", 1i32 as u32); - println!("{}", 1i32 as u64); - println!("{}", 1i32 as f32); - println!("{}", 1i32 as f64); + println!("{:?}", 1i32 as int); + println!("{:?}", 1i32 as uint); + println!("{:?}", 1i32 as *const libc::FILE); + println!("{:?}", 1i32 as i8); + println!("{:?}", 1i32 as i16); + println!("{:?}", 1i32 as i32); + println!("{:?}", 1i32 as i64); + println!("{:?}", 1i32 as u8); + println!("{:?}", 1i32 as u16); + println!("{:?}", 1i32 as u32); + println!("{:?}", 1i32 as u64); + println!("{:?}", 1i32 as f32); + println!("{:?}", 1i32 as f64); - println!("{}", 1u32 as int); - println!("{}", 1u32 as uint); - println!("{}", 1u32 as *const libc::FILE); - println!("{}", 1u32 as i8); - println!("{}", 1u32 as i16); - println!("{}", 1u32 as i32); - println!("{}", 1u32 as i64); - println!("{}", 1u32 as u8); - println!("{}", 1u32 as u16); - println!("{}", 1u32 as u32); - println!("{}", 1u32 as u64); - println!("{}", 1u32 as f32); - println!("{}", 1u32 as f64); + println!("{:?}", 1u32 as int); + println!("{:?}", 1u32 as uint); + println!("{:?}", 1u32 as *const libc::FILE); + println!("{:?}", 1u32 as i8); + println!("{:?}", 1u32 as i16); + println!("{:?}", 1u32 as i32); + println!("{:?}", 1u32 as i64); + println!("{:?}", 1u32 as u8); + println!("{:?}", 1u32 as u16); + println!("{:?}", 1u32 as u32); + println!("{:?}", 1u32 as u64); + println!("{:?}", 1u32 as f32); + println!("{:?}", 1u32 as f64); - println!("{}", 1i64 as int); - println!("{}", 1i64 as uint); - println!("{}", 1i64 as *const libc::FILE); - println!("{}", 1i64 as i8); - println!("{}", 1i64 as i16); - println!("{}", 1i64 as i32); - println!("{}", 1i64 as i64); - println!("{}", 1i64 as u8); - println!("{}", 1i64 as u16); - println!("{}", 1i64 as u32); - println!("{}", 1i64 as u64); - println!("{}", 1i64 as f32); - println!("{}", 1i64 as f64); + println!("{:?}", 1i64 as int); + println!("{:?}", 1i64 as uint); + println!("{:?}", 1i64 as *const libc::FILE); + println!("{:?}", 1i64 as i8); + println!("{:?}", 1i64 as i16); + println!("{:?}", 1i64 as i32); + println!("{:?}", 1i64 as i64); + println!("{:?}", 1i64 as u8); + println!("{:?}", 1i64 as u16); + println!("{:?}", 1i64 as u32); + println!("{:?}", 1i64 as u64); + println!("{:?}", 1i64 as f32); + println!("{:?}", 1i64 as f64); - println!("{}", 1u64 as int); - println!("{}", 1u64 as uint); - println!("{}", 1u64 as *const libc::FILE); - println!("{}", 1u64 as i8); - println!("{}", 1u64 as i16); - println!("{}", 1u64 as i32); - println!("{}", 1u64 as i64); - println!("{}", 1u64 as u8); - println!("{}", 1u64 as u16); - println!("{}", 1u64 as u32); - println!("{}", 1u64 as u64); - println!("{}", 1u64 as f32); - println!("{}", 1u64 as f64); + println!("{:?}", 1u64 as int); + println!("{:?}", 1u64 as uint); + println!("{:?}", 1u64 as *const libc::FILE); + println!("{:?}", 1u64 as i8); + println!("{:?}", 1u64 as i16); + println!("{:?}", 1u64 as i32); + println!("{:?}", 1u64 as i64); + println!("{:?}", 1u64 as u8); + println!("{:?}", 1u64 as u16); + println!("{:?}", 1u64 as u32); + println!("{:?}", 1u64 as u64); + println!("{:?}", 1u64 as f32); + println!("{:?}", 1u64 as f64); - println!("{}", 1u64 as int); - println!("{}", 1u64 as uint); - println!("{}", 1u64 as *const libc::FILE); - println!("{}", 1u64 as i8); - println!("{}", 1u64 as i16); - println!("{}", 1u64 as i32); - println!("{}", 1u64 as i64); - println!("{}", 1u64 as u8); - println!("{}", 1u64 as u16); - println!("{}", 1u64 as u32); - println!("{}", 1u64 as u64); - println!("{}", 1u64 as f32); - println!("{}", 1u64 as f64); + println!("{:?}", 1u64 as int); + println!("{:?}", 1u64 as uint); + println!("{:?}", 1u64 as *const libc::FILE); + println!("{:?}", 1u64 as i8); + println!("{:?}", 1u64 as i16); + println!("{:?}", 1u64 as i32); + println!("{:?}", 1u64 as i64); + println!("{:?}", 1u64 as u8); + println!("{:?}", 1u64 as u16); + println!("{:?}", 1u64 as u32); + println!("{:?}", 1u64 as u64); + println!("{:?}", 1u64 as f32); + println!("{:?}", 1u64 as f64); - println!("{}", true as int); - println!("{}", true as uint); - println!("{}", true as *const libc::FILE); - println!("{}", true as i8); - println!("{}", true as i16); - println!("{}", true as i32); - println!("{}", true as i64); - println!("{}", true as u8); - println!("{}", true as u16); - println!("{}", true as u32); - println!("{}", true as u64); - println!("{}", true as f32); - println!("{}", true as f64); + println!("{:?}", true as int); + println!("{:?}", true as uint); + println!("{:?}", true as *const libc::FILE); + println!("{:?}", true as i8); + println!("{:?}", true as i16); + println!("{:?}", true as i32); + println!("{:?}", true as i64); + println!("{:?}", true as u8); + println!("{:?}", true as u16); + println!("{:?}", true as u32); + println!("{:?}", true as u64); + println!("{:?}", true as f32); + println!("{:?}", true as f64); - println!("{}", 1f32 as int); - println!("{}", 1f32 as uint); - println!("{}", 1f32 as i8); - println!("{}", 1f32 as i16); - println!("{}", 1f32 as i32); - println!("{}", 1f32 as i64); - println!("{}", 1f32 as u8); - println!("{}", 1f32 as u16); - println!("{}", 1f32 as u32); - println!("{}", 1f32 as u64); - println!("{}", 1f32 as f32); - println!("{}", 1f32 as f64); + println!("{:?}", 1f32 as int); + println!("{:?}", 1f32 as uint); + println!("{:?}", 1f32 as i8); + println!("{:?}", 1f32 as i16); + println!("{:?}", 1f32 as i32); + println!("{:?}", 1f32 as i64); + println!("{:?}", 1f32 as u8); + println!("{:?}", 1f32 as u16); + println!("{:?}", 1f32 as u32); + println!("{:?}", 1f32 as u64); + println!("{:?}", 1f32 as f32); + println!("{:?}", 1f32 as f64); - println!("{}", 1f64 as int); - println!("{}", 1f64 as uint); - println!("{}", 1f64 as i8); - println!("{}", 1f64 as i16); - println!("{}", 1f64 as i32); - println!("{}", 1f64 as i64); - println!("{}", 1f64 as u8); - println!("{}", 1f64 as u16); - println!("{}", 1f64 as u32); - println!("{}", 1f64 as u64); - println!("{}", 1f64 as f32); - println!("{}", 1f64 as f64); + println!("{:?}", 1f64 as int); + println!("{:?}", 1f64 as uint); + println!("{:?}", 1f64 as i8); + println!("{:?}", 1f64 as i16); + println!("{:?}", 1f64 as i32); + println!("{:?}", 1f64 as i64); + println!("{:?}", 1f64 as u8); + println!("{:?}", 1f64 as u16); + println!("{:?}", 1f64 as u32); + println!("{:?}", 1f64 as u64); + println!("{:?}", 1f64 as f32); + println!("{:?}", 1f64 as f64); } diff --git a/src/test/run-pass/tag-align-shape.rs b/src/test/run-pass/tag-align-shape.rs index 8438a5ff47f..b88357252d8 100644 --- a/src/test/run-pass/tag-align-shape.rs +++ b/src/test/run-pass/tag-align-shape.rs @@ -21,7 +21,7 @@ struct t_rec { pub fn main() { let x = t_rec {c8: 22u8, t: a_tag::a_tag_var(44u64)}; - let y = format!("{}", x); - println!("y = {}", y); - assert_eq!(y, "t_rec { c8: 22, t: a_tag_var(44) }".to_string()); + let y = format!("{:?}", x); + println!("y = {:?}", y); + assert_eq!(y, "t_rec { c8: 22u8, t: a_tag_var(44u64) }".to_string()); } diff --git a/src/test/run-pass/tag-disr-val-shape.rs b/src/test/run-pass/tag-disr-val-shape.rs index 1155a619a60..049e4bb9a38 100644 --- a/src/test/run-pass/tag-disr-val-shape.rs +++ b/src/test/run-pass/tag-disr-val-shape.rs @@ -18,9 +18,9 @@ enum color { } pub fn main() { - let act = format!("{}", color::red); + let act = format!("{:?}", color::red); println!("{}", act); assert_eq!("red".to_string(), act); - assert_eq!("green".to_string(), format!("{}", color::green)); - assert_eq!("white".to_string(), format!("{}", color::white)); + assert_eq!("green".to_string(), format!("{:?}", color::green)); + assert_eq!("white".to_string(), format!("{:?}", color::white)); } diff --git a/src/test/run-pass/trivial-message.rs b/src/test/run-pass/trivial-message.rs index 6bece8265c0..df8efb42e30 100644 --- a/src/test/run-pass/trivial-message.rs +++ b/src/test/run-pass/trivial-message.rs @@ -19,5 +19,5 @@ pub fn main() { let (tx, rx) = channel(); tx.send(42i); let r = rx.recv(); - println!("{}", r); + println!("{:?}", r); } diff --git a/src/test/run-pass/tuple-struct-construct.rs b/src/test/run-pass/tuple-struct-construct.rs index 5bf152f2976..d7a78dbc411 100644 --- a/src/test/run-pass/tuple-struct-construct.rs +++ b/src/test/run-pass/tuple-struct-construct.rs @@ -13,5 +13,5 @@ struct Foo(int, int); pub fn main() { let x = Foo(1, 2); - println!("{}", x); + println!("{:?}", x); } diff --git a/src/test/run-pass/vec-to_str.rs b/src/test/run-pass/vec-to_str.rs index 52e0ba89479..0a65cd3a7ac 100644 --- a/src/test/run-pass/vec-to_str.rs +++ b/src/test/run-pass/vec-to_str.rs @@ -9,11 +9,11 @@ // except according to those terms. pub fn main() { - assert_eq!((vec!(0i, 1)).to_string(), "[0, 1]".to_string()); + assert_eq!((vec!(0i, 1)).to_string(), "0, 1".to_string()); let foo = vec!(3i, 4); let bar: &[int] = &[4, 5]; - assert_eq!(foo.to_string(), "[3, 4]".to_string()); - assert_eq!(bar.to_string(), "[4, 5]".to_string()); + assert_eq!(foo.to_string(), "3, 4".to_string()); + assert_eq!(bar.to_string(), "4, 5".to_string()); }