auto merge of #14310 : pcwalton/rust/detildestr-alllibs, r=brson

r? @brson
This commit is contained in:
bors 2014-05-22 15:16:31 -07:00
commit 87ad19eb78
297 changed files with 3198 additions and 2604 deletions

View File

@ -96,7 +96,7 @@ pub fn parse_config(args: Vec<StrBuf> ) -> Config {
let args_ = args.tail();
if args.get(1).as_slice() == "-h" || args.get(1).as_slice() == "--help" {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message, groups.as_slice()));
println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!("");
fail!()
}
@ -109,7 +109,7 @@ pub fn parse_config(args: Vec<StrBuf> ) -> Config {
if matches.opt_present("h") || matches.opt_present("help") {
let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
println!("{}", getopts::usage(message, groups.as_slice()));
println!("{}", getopts::usage(message.as_slice(), groups.as_slice()));
println!("");
fail!()
}
@ -323,11 +323,15 @@ pub fn is_test(config: &Config, testfile: &Path) -> bool {
let mut valid = false;
for ext in valid_extensions.iter() {
if name.ends_with(*ext) { valid = true; }
if name.ends_with(ext.as_slice()) {
valid = true;
}
}
for pre in invalid_prefixes.iter() {
if name.starts_with(*pre) { valid = false; }
if name.starts_with(pre.as_slice()) {
valid = false;
}
}
return valid;

View File

@ -24,7 +24,7 @@ pub fn load_errors(re: &Regex, testfile: &Path) -> Vec<ExpectedError> {
let mut rdr = BufferedReader::new(File::open(testfile).unwrap());
rdr.lines().enumerate().filter_map(|(line_no, ln)| {
parse_expected(line_no + 1, ln.unwrap(), re)
parse_expected(line_no + 1, ln.unwrap().as_slice(), re)
}).collect()
}

View File

@ -157,9 +157,14 @@ fn iter_header(testfile: &Path, it: |&str| -> bool) -> bool {
// module or function. This doesn't seem to be an optimization
// with a warm page cache. Maybe with a cold one.
let ln = ln.unwrap();
if ln.starts_with("fn") || ln.starts_with("mod") {
if ln.as_slice().starts_with("fn") ||
ln.as_slice().starts_with("mod") {
return true;
} else { if !(it(ln.trim())) { return false; } }
} else {
if !(it(ln.as_slice().trim())) {
return false;
}
}
}
return true;
}

View File

@ -15,7 +15,8 @@ use std::unstable::dynamic_lib::DynamicLibrary;
fn target_env(lib_path: &str, prog: &str) -> Vec<(StrBuf, StrBuf)> {
let prog = if cfg!(windows) {prog.slice_to(prog.len() - 4)} else {prog};
let aux_path = prog + ".libaux";
let mut aux_path = prog.to_strbuf();
aux_path.push_str(".libaux");
// Need to be sure to put both the lib_path and the aux path in the dylib
// search path for the child.

View File

@ -351,7 +351,10 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
cmds,
"quit".to_strbuf()].connect("\n");
debug!("script_str = {}", script_str);
dump_output_file(config, testfile, script_str, "debugger.script");
dump_output_file(config,
testfile,
script_str.as_slice(),
"debugger.script");
procsrv::run("",
@ -459,7 +462,10 @@ fn run_debuginfo_gdb_test(config: &Config, props: &TestProps, testfile: &Path) {
"quit\n".to_strbuf()
].connect("\n");
debug!("script_str = {}", script_str);
dump_output_file(config, testfile, script_str, "debugger.script");
dump_output_file(config,
testfile,
script_str.as_slice(),
"debugger.script");
// run debugger script with gdb
#[cfg(windows)]
@ -538,7 +544,8 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
// Set breakpoints on every line that contains the string "#break"
for line in breakpoint_lines.iter() {
script_str.push_str(format!("breakpoint set --line {}\n", line));
script_str.push_str(format!("breakpoint set --line {}\n",
line).as_slice());
}
// Append the other commands
@ -552,7 +559,10 @@ fn run_debuginfo_lldb_test(config: &Config, props: &TestProps, testfile: &Path)
// Write the script into a file
debug!("script_str = {}", script_str);
dump_output_file(config, testfile, script_str.into_owned(), "debugger.script");
dump_output_file(config,
testfile,
script_str.as_slice(),
"debugger.script");
let debugger_script = make_out_name(config, testfile, "debugger.script");
// Let LLDB execute the script via lldb_batchmode.py
@ -609,8 +619,8 @@ fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
-> DebuggerCommands {
use std::io::{BufferedReader, File};
let command_directive = debugger_prefix + "-command";
let check_directive = debugger_prefix + "-check";
let command_directive = format!("{}-command", debugger_prefix);
let check_directive = format!("{}-check", debugger_prefix);
let mut breakpoint_lines = vec!();
let mut commands = vec!();
@ -620,18 +630,18 @@ fn parse_debugger_commands(file_path: &Path, debugger_prefix: &str)
for line in reader.lines() {
match line {
Ok(line) => {
if line.contains("#break") {
if line.as_slice().contains("#break") {
breakpoint_lines.push(counter);
}
header::parse_name_value_directive(
line,
line.as_slice(),
command_directive.to_strbuf()).map(|cmd| {
commands.push(cmd)
});
header::parse_name_value_directive(
line,
line.as_slice(),
check_directive.to_strbuf()).map(|cmd| {
check_lines.push(cmd)
});

View File

@ -60,8 +60,8 @@ To return an Owned String (StrBuf) use the str helper function [`from_utf8_owned
~~~
use std::str;
let x: Result<StrBuf,~[u8]> =
str::from_utf8_owned(~[104u8,105u8]).map(|x| x.to_strbuf());
let x: Option<StrBuf> =
str::from_utf8([ 104u8, 105u8 ]).map(|x| x.to_strbuf());
let y: StrBuf = x.unwrap();
~~~

View File

@ -116,18 +116,18 @@ pub fn stats_print() {
}
}
// The compiler never calls `exchange_free` on ~ZeroSizeType, so zero-size
// allocations can point to this `static`. It would be incorrect to use a null
// pointer, due to enums assuming types like unique pointers are never null.
pub static mut EMPTY: uint = 12345;
/// The allocator for unique pointers.
#[cfg(not(test))]
#[lang="exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: uint, align: uint) -> *mut u8 {
// The compiler never calls `exchange_free` on ~ZeroSizeType, so zero-size
// allocations can point to this `static`. It would be incorrect to use a null
// pointer, due to enums assuming types like unique pointers are never null.
static EMPTY: () = ();
if size == 0 {
&EMPTY as *() as *mut u8
&EMPTY as *uint as *mut u8
} else {
allocate(size, align)
}

View File

@ -28,3 +28,20 @@ fn align_to(size: uint, align: uint) -> uint {
assert!(align != 0);
(size + align - 1) & !(align - 1)
}
// FIXME(#14344): When linking liballoc with libstd, this library will be linked
// as an rlib (it only exists as an rlib). It turns out that an
// optimized standard library doesn't actually use *any* symbols
// from this library. Everything is inlined and optimized away.
// This means that linkers will actually omit the object for this
// file, even though it may be needed in the future.
//
// To get around this for now, we define a dummy symbol which
// will never get inlined so the stdlib can call it. The stdlib's
// reference to this symbol will cause this library's object file
// to get linked in to libstd successfully (the linker won't
// optimize it out).
#[deprecated]
#[doc(hidden)]
pub fn make_stdlib_link_work() {}

View File

@ -538,7 +538,7 @@ impl Bitv {
* The resulting string has the same length as `self`, and each
* character is either '0' or '1'.
*/
pub fn to_str(&self) -> ~str {
pub fn to_str(&self) -> StrBuf {
let mut rs = StrBuf::new();
for i in self.iter() {
if i {
@ -547,7 +547,7 @@ impl Bitv {
rs.push_char('0');
}
};
rs.into_owned()
rs
}
@ -1330,7 +1330,7 @@ mod tests {
#[test]
fn test_from_bytes() {
let bitv = from_bytes([0b10110110, 0b00000000, 0b11111111]);
let str = "10110110".to_owned() + "00000000" + "11111111";
let str = format!("{}{}{}", "10110110", "00000000", "11111111");
assert_eq!(bitv.to_str(), str);
}

View File

@ -119,7 +119,7 @@ mod tests {
use prelude::*;
use super::*;
use realstd::owned::{Box, AnyOwnExt};
use realstd::str::StrAllocating;
use realstd::str::{Str, StrAllocating};
#[deriving(Eq, Show)]
struct Test;
@ -249,13 +249,17 @@ mod tests {
use realstd::to_str::ToStr;
let a = box 8u as Box<::realstd::any::Any>;
let b = box Test as Box<::realstd::any::Any>;
assert_eq!(a.to_str(), "Box<Any>".to_owned());
assert_eq!(b.to_str(), "Box<Any>".to_owned());
let a_str = a.to_str();
let b_str = b.to_str();
assert_eq!(a_str.as_slice(), "Box<Any>");
assert_eq!(b_str.as_slice(), "Box<Any>");
let a = &8u as &Any;
let b = &Test as &Any;
assert_eq!(format!("{}", a), "&Any".to_owned());
assert_eq!(format!("{}", b), "&Any".to_owned());
let s = format!("{}", a);
assert_eq!(s.as_slice(), "&Any");
let s = format!("{}", b);
assert_eq!(s.as_slice(), "&Any");
}
}

View File

@ -242,8 +242,10 @@ mod tests {
#[test]
fn test_to_str() {
assert_eq!(false.to_str(), "false".to_owned());
assert_eq!(true.to_str(), "true".to_owned());
let s = false.to_str();
assert_eq!(s.as_slice(), "false");
let s = true.to_str();
assert_eq!(s.as_slice(), "true");
}
#[test]

View File

@ -404,12 +404,13 @@ mod test {
#[test]
fn cell_has_sensible_show() {
use str::StrSlice;
use realstd::str::Str;
let x = Cell::new("foo bar");
assert!(format!("{}", x).contains(x.get()));
assert!(format!("{}", x).as_slice().contains(x.get()));
x.set("baz qux");
assert!(format!("{}", x).contains(x.get()));
assert!(format!("{}", x).as_slice().contains(x.get()));
}
#[test]

View File

@ -637,7 +637,7 @@ mod test {
use slice::ImmutableVector;
use option::{Some, None};
use realstd::strbuf::StrBuf;
use realstd::str::StrAllocating;
use realstd::str::{Str, StrAllocating};
#[test]
fn test_is_lowercase() {
@ -742,46 +742,65 @@ mod test {
#[test]
fn test_escape_default() {
fn string(c: char) -> ~str {
fn string(c: char) -> StrBuf {
let mut result = StrBuf::new();
escape_default(c, |c| { result.push_char(c); });
return result.into_owned();
return result;
}
assert_eq!(string('\n'), "\\n".to_owned());
assert_eq!(string('\r'), "\\r".to_owned());
assert_eq!(string('\''), "\\'".to_owned());
assert_eq!(string('"'), "\\\"".to_owned());
assert_eq!(string(' '), " ".to_owned());
assert_eq!(string('a'), "a".to_owned());
assert_eq!(string('~'), "~".to_owned());
assert_eq!(string('\x00'), "\\x00".to_owned());
assert_eq!(string('\x1f'), "\\x1f".to_owned());
assert_eq!(string('\x7f'), "\\x7f".to_owned());
assert_eq!(string('\xff'), "\\xff".to_owned());
assert_eq!(string('\u011b'), "\\u011b".to_owned());
assert_eq!(string('\U0001d4b6'), "\\U0001d4b6".to_owned());
let s = string('\n');
assert_eq!(s.as_slice(), "\\n");
let s = string('\r');
assert_eq!(s.as_slice(), "\\r");
let s = string('\'');
assert_eq!(s.as_slice(), "\\'");
let s = string('"');
assert_eq!(s.as_slice(), "\\\"");
let s = string(' ');
assert_eq!(s.as_slice(), " ");
let s = string('a');
assert_eq!(s.as_slice(), "a");
let s = string('~');
assert_eq!(s.as_slice(), "~");
let s = string('\x00');
assert_eq!(s.as_slice(), "\\x00");
let s = string('\x1f');
assert_eq!(s.as_slice(), "\\x1f");
let s = string('\x7f');
assert_eq!(s.as_slice(), "\\x7f");
let s = string('\xff');
assert_eq!(s.as_slice(), "\\xff");
let s = string('\u011b');
assert_eq!(s.as_slice(), "\\u011b");
let s = string('\U0001d4b6');
assert_eq!(s.as_slice(), "\\U0001d4b6");
}
#[test]
fn test_escape_unicode() {
fn string(c: char) -> ~str {
fn string(c: char) -> StrBuf {
let mut result = StrBuf::new();
escape_unicode(c, |c| { result.push_char(c); });
return result.into_owned();
return result;
}
assert_eq!(string('\x00'), "\\x00".to_owned());
assert_eq!(string('\n'), "\\x0a".to_owned());
assert_eq!(string(' '), "\\x20".to_owned());
assert_eq!(string('a'), "\\x61".to_owned());
assert_eq!(string('\u011b'), "\\u011b".to_owned());
assert_eq!(string('\U0001d4b6'), "\\U0001d4b6".to_owned());
let s = string('\x00');
assert_eq!(s.as_slice(), "\\x00");
let s = string('\n');
assert_eq!(s.as_slice(), "\\x0a");
let s = string(' ');
assert_eq!(s.as_slice(), "\\x20");
let s = string('a');
assert_eq!(s.as_slice(), "\\x61");
let s = string('\u011b');
assert_eq!(s.as_slice(), "\\u011b");
let s = string('\U0001d4b6');
assert_eq!(s.as_slice(), "\\U0001d4b6");
}
#[test]
fn test_to_str() {
use realstd::to_str::ToStr;
let s = 't'.to_str();
assert_eq!(s, "t".to_owned());
assert_eq!(s.as_slice(), "t");
}
#[test]

View File

@ -171,7 +171,7 @@ pub trait Ord: Eq {
/// The equivalence relation. Two values may be equivalent even if they are
/// of different types. The most common use case for this relation is
/// container types; e.g. it is often desirable to be able to use `&str`
/// values to look up entries in a container with `~str` keys.
/// values to look up entries in a container with `StrBuf` keys.
pub trait Equiv<T> {
/// Implement this function to decide equivalent values.
fn equiv(&self, other: &T) -> bool;

View File

@ -594,7 +594,7 @@ pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
}
#[cfg(test)]
pub fn format(args: &Arguments) -> ~str {
pub fn format(args: &Arguments) -> ::realstd::strbuf::StrBuf {
use str;
use realstd::str::StrAllocating;
use realstd::io::MemWriter;
@ -613,7 +613,10 @@ pub fn format(args: &Arguments) -> ~str {
let mut i = MemWriter::new();
let _ = write(&mut i, args);
str::from_utf8(i.get_ref()).unwrap().to_owned()
let mut result = ::realstd::strbuf::StrBuf::new();
result.push_str(str::from_utf8(i.get_ref()).unwrap());
result
}
/// When the compiler determines that the type of an argument *must* be a string
@ -761,7 +764,6 @@ macro_rules! delegate(($ty:ty to $other:ident) => {
}
}
})
delegate!(~str to string)
delegate!(&'a str to string)
delegate!(bool to bool)
delegate!(char to char)

View File

@ -194,7 +194,7 @@ mod tests {
use fmt::radix;
use super::{Binary, Octal, Decimal, LowerHex, UpperHex};
use super::{GenericRadix, Radix};
use realstd::str::StrAllocating;
use realstd::str::{Str, StrAllocating};
#[test]
fn test_radix_base() {
@ -246,143 +246,143 @@ mod tests {
// Formatting integers should select the right implementation based off
// the type of the argument. Also, hex/octal/binary should be defined
// for integers, but they shouldn't emit the negative sign.
assert_eq!(format!("{}", 1i), "1".to_owned());
assert_eq!(format!("{}", 1i8), "1".to_owned());
assert_eq!(format!("{}", 1i16), "1".to_owned());
assert_eq!(format!("{}", 1i32), "1".to_owned());
assert_eq!(format!("{}", 1i64), "1".to_owned());
assert_eq!(format!("{:d}", -1i), "-1".to_owned());
assert_eq!(format!("{:d}", -1i8), "-1".to_owned());
assert_eq!(format!("{:d}", -1i16), "-1".to_owned());
assert_eq!(format!("{:d}", -1i32), "-1".to_owned());
assert_eq!(format!("{:d}", -1i64), "-1".to_owned());
assert_eq!(format!("{:t}", 1i), "1".to_owned());
assert_eq!(format!("{:t}", 1i8), "1".to_owned());
assert_eq!(format!("{:t}", 1i16), "1".to_owned());
assert_eq!(format!("{:t}", 1i32), "1".to_owned());
assert_eq!(format!("{:t}", 1i64), "1".to_owned());
assert_eq!(format!("{:x}", 1i), "1".to_owned());
assert_eq!(format!("{:x}", 1i8), "1".to_owned());
assert_eq!(format!("{:x}", 1i16), "1".to_owned());
assert_eq!(format!("{:x}", 1i32), "1".to_owned());
assert_eq!(format!("{:x}", 1i64), "1".to_owned());
assert_eq!(format!("{:X}", 1i), "1".to_owned());
assert_eq!(format!("{:X}", 1i8), "1".to_owned());
assert_eq!(format!("{:X}", 1i16), "1".to_owned());
assert_eq!(format!("{:X}", 1i32), "1".to_owned());
assert_eq!(format!("{:X}", 1i64), "1".to_owned());
assert_eq!(format!("{:o}", 1i), "1".to_owned());
assert_eq!(format!("{:o}", 1i8), "1".to_owned());
assert_eq!(format!("{:o}", 1i16), "1".to_owned());
assert_eq!(format!("{:o}", 1i32), "1".to_owned());
assert_eq!(format!("{:o}", 1i64), "1".to_owned());
assert!(format!("{}", 1i).as_slice() == "1");
assert!(format!("{}", 1i8).as_slice() == "1");
assert!(format!("{}", 1i16).as_slice() == "1");
assert!(format!("{}", 1i32).as_slice() == "1");
assert!(format!("{}", 1i64).as_slice() == "1");
assert!(format!("{:d}", -1i).as_slice() == "-1");
assert!(format!("{:d}", -1i8).as_slice() == "-1");
assert!(format!("{:d}", -1i16).as_slice() == "-1");
assert!(format!("{:d}", -1i32).as_slice() == "-1");
assert!(format!("{:d}", -1i64).as_slice() == "-1");
assert!(format!("{:t}", 1i).as_slice() == "1");
assert!(format!("{:t}", 1i8).as_slice() == "1");
assert!(format!("{:t}", 1i16).as_slice() == "1");
assert!(format!("{:t}", 1i32).as_slice() == "1");
assert!(format!("{:t}", 1i64).as_slice() == "1");
assert!(format!("{:x}", 1i).as_slice() == "1");
assert!(format!("{:x}", 1i8).as_slice() == "1");
assert!(format!("{:x}", 1i16).as_slice() == "1");
assert!(format!("{:x}", 1i32).as_slice() == "1");
assert!(format!("{:x}", 1i64).as_slice() == "1");
assert!(format!("{:X}", 1i).as_slice() == "1");
assert!(format!("{:X}", 1i8).as_slice() == "1");
assert!(format!("{:X}", 1i16).as_slice() == "1");
assert!(format!("{:X}", 1i32).as_slice() == "1");
assert!(format!("{:X}", 1i64).as_slice() == "1");
assert!(format!("{:o}", 1i).as_slice() == "1");
assert!(format!("{:o}", 1i8).as_slice() == "1");
assert!(format!("{:o}", 1i16).as_slice() == "1");
assert!(format!("{:o}", 1i32).as_slice() == "1");
assert!(format!("{:o}", 1i64).as_slice() == "1");
assert_eq!(format!("{}", 1u), "1".to_owned());
assert_eq!(format!("{}", 1u8), "1".to_owned());
assert_eq!(format!("{}", 1u16), "1".to_owned());
assert_eq!(format!("{}", 1u32), "1".to_owned());
assert_eq!(format!("{}", 1u64), "1".to_owned());
assert_eq!(format!("{:u}", 1u), "1".to_owned());
assert_eq!(format!("{:u}", 1u8), "1".to_owned());
assert_eq!(format!("{:u}", 1u16), "1".to_owned());
assert_eq!(format!("{:u}", 1u32), "1".to_owned());
assert_eq!(format!("{:u}", 1u64), "1".to_owned());
assert_eq!(format!("{:t}", 1u), "1".to_owned());
assert_eq!(format!("{:t}", 1u8), "1".to_owned());
assert_eq!(format!("{:t}", 1u16), "1".to_owned());
assert_eq!(format!("{:t}", 1u32), "1".to_owned());
assert_eq!(format!("{:t}", 1u64), "1".to_owned());
assert_eq!(format!("{:x}", 1u), "1".to_owned());
assert_eq!(format!("{:x}", 1u8), "1".to_owned());
assert_eq!(format!("{:x}", 1u16), "1".to_owned());
assert_eq!(format!("{:x}", 1u32), "1".to_owned());
assert_eq!(format!("{:x}", 1u64), "1".to_owned());
assert_eq!(format!("{:X}", 1u), "1".to_owned());
assert_eq!(format!("{:X}", 1u8), "1".to_owned());
assert_eq!(format!("{:X}", 1u16), "1".to_owned());
assert_eq!(format!("{:X}", 1u32), "1".to_owned());
assert_eq!(format!("{:X}", 1u64), "1".to_owned());
assert_eq!(format!("{:o}", 1u), "1".to_owned());
assert_eq!(format!("{:o}", 1u8), "1".to_owned());
assert_eq!(format!("{:o}", 1u16), "1".to_owned());
assert_eq!(format!("{:o}", 1u32), "1".to_owned());
assert_eq!(format!("{:o}", 1u64), "1".to_owned());
assert!(format!("{}", 1u).as_slice() == "1");
assert!(format!("{}", 1u8).as_slice() == "1");
assert!(format!("{}", 1u16).as_slice() == "1");
assert!(format!("{}", 1u32).as_slice() == "1");
assert!(format!("{}", 1u64).as_slice() == "1");
assert!(format!("{:u}", 1u).as_slice() == "1");
assert!(format!("{:u}", 1u8).as_slice() == "1");
assert!(format!("{:u}", 1u16).as_slice() == "1");
assert!(format!("{:u}", 1u32).as_slice() == "1");
assert!(format!("{:u}", 1u64).as_slice() == "1");
assert!(format!("{:t}", 1u).as_slice() == "1");
assert!(format!("{:t}", 1u8).as_slice() == "1");
assert!(format!("{:t}", 1u16).as_slice() == "1");
assert!(format!("{:t}", 1u32).as_slice() == "1");
assert!(format!("{:t}", 1u64).as_slice() == "1");
assert!(format!("{:x}", 1u).as_slice() == "1");
assert!(format!("{:x}", 1u8).as_slice() == "1");
assert!(format!("{:x}", 1u16).as_slice() == "1");
assert!(format!("{:x}", 1u32).as_slice() == "1");
assert!(format!("{:x}", 1u64).as_slice() == "1");
assert!(format!("{:X}", 1u).as_slice() == "1");
assert!(format!("{:X}", 1u8).as_slice() == "1");
assert!(format!("{:X}", 1u16).as_slice() == "1");
assert!(format!("{:X}", 1u32).as_slice() == "1");
assert!(format!("{:X}", 1u64).as_slice() == "1");
assert!(format!("{:o}", 1u).as_slice() == "1");
assert!(format!("{:o}", 1u8).as_slice() == "1");
assert!(format!("{:o}", 1u16).as_slice() == "1");
assert!(format!("{:o}", 1u32).as_slice() == "1");
assert!(format!("{:o}", 1u64).as_slice() == "1");
// Test a larger number
assert_eq!(format!("{:t}", 55), "110111".to_owned());
assert_eq!(format!("{:o}", 55), "67".to_owned());
assert_eq!(format!("{:d}", 55), "55".to_owned());
assert_eq!(format!("{:x}", 55), "37".to_owned());
assert_eq!(format!("{:X}", 55), "37".to_owned());
assert!(format!("{:t}", 55).as_slice() == "110111");
assert!(format!("{:o}", 55).as_slice() == "67");
assert!(format!("{:d}", 55).as_slice() == "55");
assert!(format!("{:x}", 55).as_slice() == "37");
assert!(format!("{:X}", 55).as_slice() == "37");
}
#[test]
fn test_format_int_zero() {
assert_eq!(format!("{}", 0i), "0".to_owned());
assert_eq!(format!("{:d}", 0i), "0".to_owned());
assert_eq!(format!("{:t}", 0i), "0".to_owned());
assert_eq!(format!("{:o}", 0i), "0".to_owned());
assert_eq!(format!("{:x}", 0i), "0".to_owned());
assert_eq!(format!("{:X}", 0i), "0".to_owned());
assert!(format!("{}", 0i).as_slice() == "0");
assert!(format!("{:d}", 0i).as_slice() == "0");
assert!(format!("{:t}", 0i).as_slice() == "0");
assert!(format!("{:o}", 0i).as_slice() == "0");
assert!(format!("{:x}", 0i).as_slice() == "0");
assert!(format!("{:X}", 0i).as_slice() == "0");
assert_eq!(format!("{}", 0u), "0".to_owned());
assert_eq!(format!("{:u}", 0u), "0".to_owned());
assert_eq!(format!("{:t}", 0u), "0".to_owned());
assert_eq!(format!("{:o}", 0u), "0".to_owned());
assert_eq!(format!("{:x}", 0u), "0".to_owned());
assert_eq!(format!("{:X}", 0u), "0".to_owned());
assert!(format!("{}", 0u).as_slice() == "0");
assert!(format!("{:u}", 0u).as_slice() == "0");
assert!(format!("{:t}", 0u).as_slice() == "0");
assert!(format!("{:o}", 0u).as_slice() == "0");
assert!(format!("{:x}", 0u).as_slice() == "0");
assert!(format!("{:X}", 0u).as_slice() == "0");
}
#[test]
fn test_format_int_flags() {
assert_eq!(format!("{:3d}", 1), " 1".to_owned());
assert_eq!(format!("{:>3d}", 1), " 1".to_owned());
assert_eq!(format!("{:>+3d}", 1), " +1".to_owned());
assert_eq!(format!("{:<3d}", 1), "1 ".to_owned());
assert_eq!(format!("{:#d}", 1), "1".to_owned());
assert_eq!(format!("{:#x}", 10), "0xa".to_owned());
assert_eq!(format!("{:#X}", 10), "0xA".to_owned());
assert_eq!(format!("{:#5x}", 10), " 0xa".to_owned());
assert_eq!(format!("{:#o}", 10), "0o12".to_owned());
assert_eq!(format!("{:08x}", 10), "0000000a".to_owned());
assert_eq!(format!("{:8x}", 10), " a".to_owned());
assert_eq!(format!("{:<8x}", 10), "a ".to_owned());
assert_eq!(format!("{:>8x}", 10), " a".to_owned());
assert_eq!(format!("{:#08x}", 10), "0x00000a".to_owned());
assert_eq!(format!("{:08d}", -10), "-0000010".to_owned());
assert_eq!(format!("{:x}", -1u8), "ff".to_owned());
assert_eq!(format!("{:X}", -1u8), "FF".to_owned());
assert_eq!(format!("{:t}", -1u8), "11111111".to_owned());
assert_eq!(format!("{:o}", -1u8), "377".to_owned());
assert_eq!(format!("{:#x}", -1u8), "0xff".to_owned());
assert_eq!(format!("{:#X}", -1u8), "0xFF".to_owned());
assert_eq!(format!("{:#t}", -1u8), "0b11111111".to_owned());
assert_eq!(format!("{:#o}", -1u8), "0o377".to_owned());
assert!(format!("{:3d}", 1).as_slice() == " 1");
assert!(format!("{:>3d}", 1).as_slice() == " 1");
assert!(format!("{:>+3d}", 1).as_slice() == " +1");
assert!(format!("{:<3d}", 1).as_slice() == "1 ");
assert!(format!("{:#d}", 1).as_slice() == "1");
assert!(format!("{:#x}", 10).as_slice() == "0xa");
assert!(format!("{:#X}", 10).as_slice() == "0xA");
assert!(format!("{:#5x}", 10).as_slice() == " 0xa");
assert!(format!("{:#o}", 10).as_slice() == "0o12");
assert!(format!("{:08x}", 10).as_slice() == "0000000a");
assert!(format!("{:8x}", 10).as_slice() == " a");
assert!(format!("{:<8x}", 10).as_slice() == "a ");
assert!(format!("{:>8x}", 10).as_slice() == " a");
assert!(format!("{:#08x}", 10).as_slice() == "0x00000a");
assert!(format!("{:08d}", -10).as_slice() == "-0000010");
assert!(format!("{:x}", -1u8).as_slice() == "ff");
assert!(format!("{:X}", -1u8).as_slice() == "FF");
assert!(format!("{:t}", -1u8).as_slice() == "11111111");
assert!(format!("{:o}", -1u8).as_slice() == "377");
assert!(format!("{:#x}", -1u8).as_slice() == "0xff");
assert!(format!("{:#X}", -1u8).as_slice() == "0xFF");
assert!(format!("{:#t}", -1u8).as_slice() == "0b11111111");
assert!(format!("{:#o}", -1u8).as_slice() == "0o377");
}
#[test]
fn test_format_int_sign_padding() {
assert_eq!(format!("{:+5d}", 1), " +1".to_owned());
assert_eq!(format!("{:+5d}", -1), " -1".to_owned());
assert_eq!(format!("{:05d}", 1), "00001".to_owned());
assert_eq!(format!("{:05d}", -1), "-0001".to_owned());
assert_eq!(format!("{:+05d}", 1), "+0001".to_owned());
assert_eq!(format!("{:+05d}", -1), "-0001".to_owned());
assert!(format!("{:+5d}", 1).as_slice() == " +1");
assert!(format!("{:+5d}", -1).as_slice() == " -1");
assert!(format!("{:05d}", 1).as_slice() == "00001");
assert!(format!("{:05d}", -1).as_slice() == "-0001");
assert!(format!("{:+05d}", 1).as_slice() == "+0001");
assert!(format!("{:+05d}", -1).as_slice() == "-0001");
}
#[test]
fn test_format_int_twos_complement() {
use {i8, i16, i32, i64};
assert_eq!(format!("{}", i8::MIN), "-128".to_owned());
assert_eq!(format!("{}", i16::MIN), "-32768".to_owned());
assert_eq!(format!("{}", i32::MIN), "-2147483648".to_owned());
assert_eq!(format!("{}", i64::MIN), "-9223372036854775808".to_owned());
assert!(format!("{}", i8::MIN).as_slice() == "-128");
assert!(format!("{}", i16::MIN).as_slice() == "-32768");
assert!(format!("{}", i32::MIN).as_slice() == "-2147483648");
assert!(format!("{}", i64::MIN).as_slice() == "-9223372036854775808");
}
#[test]
fn test_format_radix() {
assert_eq!(format!("{:04}", radix(3, 2)), "0011".to_owned());
assert_eq!(format!("{}", radix(55, 36)), "1j".to_owned());
assert!(format!("{:04}", radix(3, 2)).as_slice() == "0011");
assert!(format!("{}", radix(55, 36)).as_slice() == "1j");
}
#[test]

View File

@ -469,6 +469,7 @@ mod tests {
use option::{Some,None};
use realstd::str::StrAllocating;
use realstd::owned::Box;
use realstd::vec::Vec;
use raw;
#[test]
@ -568,7 +569,7 @@ mod tests {
}
unsafe {
assert_eq!(box [76u8], transmute("L".to_owned()));
assert!(Vec::from_slice([76u8]) == transmute("L".to_owned()));
}
}
}

View File

@ -188,14 +188,14 @@ impl<T> Option<T> {
///
/// # Example
///
/// Convert an `Option<~str>` into an `Option<int>`, preserving the original.
/// Convert an `Option<StrBuf>` into an `Option<int>`, preserving the original.
/// The `map` method takes the `self` argument by value, consuming the original,
/// so this technique uses `as_ref` to first take an `Option` to a reference
/// to the value inside the original.
///
/// ```
/// let num_as_str: Option<~str> = Some("10".to_owned());
/// // First, cast `Option<~str>` to `Option<&~str>` with `as_ref`,
/// let num_as_str: Option<StrBuf> = Some("10".to_strbuf());
/// // First, cast `Option<StrBuf>` to `Option<&StrBuf>` with `as_ref`,
/// // then consume *that* with `map`, leaving `num_as_str` on the stack.
/// let num_as_int: Option<uint> = num_as_str.as_ref().map(|n| n.len());
/// println!("still can print num_as_str: {}", num_as_str);
@ -278,10 +278,10 @@ impl<T> Option<T> {
///
/// # Example
///
/// Convert an `Option<~str>` into an `Option<uint>`, consuming the original:
/// Convert an `Option<StrBuf>` into an `Option<uint>`, consuming the original:
///
/// ```
/// let num_as_str: Option<~str> = Some("10".to_owned());
/// let num_as_str: Option<StrBuf> = Some("10".to_strbuf());
/// // `Option::map` takes self *by value*, consuming `num_as_str`
/// let num_as_int: Option<uint> = num_as_str.map(|n| n.len());
/// ```
@ -596,9 +596,10 @@ pub fn collect<T, Iter: Iterator<Option<T>>, V: FromIterator<T>>(iter: Iter) ->
#[cfg(test)]
mod tests {
use realstd::vec::Vec;
use realstd::str::StrAllocating;
use realstd::strbuf::StrBuf;
use option::collect;
use prelude::*;
use realstd::str::{Str, StrAllocating};
use iter::range;
use str::StrSlice;
@ -619,11 +620,11 @@ mod tests {
#[test]
fn test_get_str() {
let x = "test".to_owned();
let addr_x = x.as_ptr();
let x = "test".to_strbuf();
let addr_x = x.as_slice().as_ptr();
let opt = Some(x);
let y = opt.unwrap();
let addr_y = y.as_ptr();
let addr_y = y.as_slice().as_ptr();
assert_eq!(addr_x, addr_y);
}
@ -745,7 +746,8 @@ mod tests {
#[test]
fn test_unwrap() {
assert_eq!(Some(1).unwrap(), 1);
assert_eq!(Some("hello".to_owned()).unwrap(), "hello".to_owned());
let s = Some("hello".to_strbuf()).unwrap();
assert_eq!(s.as_slice(), "hello");
}
#[test]
@ -758,7 +760,7 @@ mod tests {
#[test]
#[should_fail]
fn test_unwrap_fail2() {
let x: Option<~str> = None;
let x: Option<StrBuf> = None;
x.unwrap();
}

View File

@ -486,6 +486,7 @@ pub mod ptr_tests {
use mem;
use libc;
use realstd::str;
use realstd::str::Str;
use slice::{ImmutableVector, MutableVector};
#[test]
@ -660,7 +661,7 @@ pub mod ptr_tests {
let expected = expected_arr[ctr].with_ref(|buf| {
str::raw::from_c_str(buf)
});
assert_eq!(actual, expected);
assert_eq!(actual.as_slice(), expected.as_slice());
ctr += 1;
iteration_count += 1;
});
@ -693,7 +694,7 @@ pub mod ptr_tests {
let expected = expected_arr[ctr].with_ref(|buf| {
str::raw::from_c_str(buf)
});
assert_eq!(actual, expected);
assert_eq!(actual.as_slice(), expected.as_slice());
ctr += 1;
iteration_count += 1;
});

View File

@ -81,7 +81,6 @@ impl<'a, T> Repr<Slice<T>> for &'a [T] {}
impl<'a> Repr<Slice<u8>> for &'a str {}
impl<T> Repr<*Box<T>> for @T {}
impl<T> Repr<*Vec<T>> for ~[T] {}
impl Repr<*String> for ~str {}
#[cfg(test)]
mod tests {

View File

@ -169,20 +169,24 @@
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info { name: ~str, age: int, rating: int }
//! struct Info {
//! name: StrBuf,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! match file.write_line(format!("name: {}", info.name)) {
//! match file.write_line(format!("name: {}", info.name).as_slice()) {
//! Ok(_) => (),
//! Err(e) => return Err(e)
//! }
//! match file.write_line(format!("age: {}", info.age)) {
//! match file.write_line(format!("age: {}", info.age).as_slice()) {
//! Ok(_) => (),
//! Err(e) => return Err(e)
//! }
//! return file.write_line(format!("rating: {}", info.rating));
//! return file.write_line(format!("rating: {}", info.rating).as_slice());
//! }
//! ~~~
//!
@ -191,14 +195,18 @@
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info { name: ~str, age: int, rating: int }
//! struct Info {
//! name: StrBuf,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! try!(file.write_line(format!("name: {}", info.name)));
//! try!(file.write_line(format!("age: {}", info.age)));
//! try!(file.write_line(format!("rating: {}", info.rating)));
//! try!(file.write_line(format!("name: {}", info.name).as_slice()));
//! try!(file.write_line(format!("age: {}", info.age).as_slice()));
//! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
//! return Ok(());
//! }
//! ~~~
@ -421,10 +429,10 @@ impl<T, E> Result<T, E> {
/// let mut sum = 0;
///
/// while !reader.eof() {
/// let line: IoResult<~str> = reader.read_line();
/// let line: IoResult<StrBuf> = reader.read_line();
/// // Convert the string line to a number using `map` and `from_str`
/// let val: IoResult<int> = line.map(|line| {
/// from_str::<int>(line).unwrap_or(0)
/// from_str::<int>(line.as_slice()).unwrap_or(0)
/// });
/// // Add the value if there were no errors, otherwise add 0
/// sum += val.ok().unwrap_or(0);
@ -629,69 +637,68 @@ pub fn fold_<T,E,Iter:Iterator<Result<T,E>>>(iterator: Iter) -> Result<(),E> {
#[cfg(test)]
mod tests {
use realstd::vec::Vec;
use realstd::str::StrAllocating;
use realstd::strbuf::StrBuf;
use result::{collect, fold, fold_};
use prelude::*;
use realstd::str::{Str, StrAllocating};
use iter::range;
pub fn op1() -> Result<int, ~str> { Ok(666) }
pub fn op2() -> Result<int, ~str> { Err("sadface".to_owned()) }
pub fn op1() -> Result<int, &'static str> { Ok(666) }
pub fn op2() -> Result<int, &'static str> { Err("sadface") }
#[test]
pub fn test_and() {
assert_eq!(op1().and(Ok(667)).unwrap(), 667);
assert_eq!(op1().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "bad".to_owned());
assert_eq!(op1().and(Err::<(), &'static str>("bad")).unwrap_err(),
"bad");
assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface".to_owned());
assert_eq!(op2().and(Err::<(), ~str>("bad".to_owned())).unwrap_err(), "sadface".to_owned());
assert_eq!(op2().and(Ok(667)).unwrap_err(), "sadface");
assert_eq!(op2().and(Err::<(),&'static str>("bad")).unwrap_err(),
"sadface");
}
#[test]
pub fn test_and_then() {
assert_eq!(op1().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap(), 667);
assert_eq!(op1().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
"bad".to_owned());
assert_eq!(op1().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap(), 667);
assert_eq!(op1().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(),
"bad");
assert_eq!(op2().and_then(|i| Ok::<int, ~str>(i + 1)).unwrap_err(),
"sadface".to_owned());
assert_eq!(op2().and_then(|_| Err::<int, ~str>("bad".to_owned())).unwrap_err(),
"sadface".to_owned());
assert_eq!(op2().and_then(|i| Ok::<int, &'static str>(i + 1)).unwrap_err(),
"sadface");
assert_eq!(op2().and_then(|_| Err::<int, &'static str>("bad")).unwrap_err(),
"sadface");
}
#[test]
pub fn test_or() {
assert_eq!(op1().or(Ok(667)).unwrap(), 666);
assert_eq!(op1().or(Err("bad".to_owned())).unwrap(), 666);
assert_eq!(op1().or(Err("bad")).unwrap(), 666);
assert_eq!(op2().or(Ok(667)).unwrap(), 667);
assert_eq!(op2().or(Err("bad".to_owned())).unwrap_err(), "bad".to_owned());
assert_eq!(op2().or(Err("bad")).unwrap_err(), "bad");
}
#[test]
pub fn test_or_else() {
assert_eq!(op1().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 666);
assert_eq!(op1().or_else(|e| Err::<int, ~str>(e + "!")).unwrap(), 666);
assert_eq!(op1().or_else(|_| Ok::<int, &'static str>(667)).unwrap(), 666);
assert_eq!(op1().or_else(|e| Err::<int, &'static str>(e)).unwrap(), 666);
assert_eq!(op2().or_else(|_| Ok::<int, ~str>(667)).unwrap(), 667);
assert_eq!(op2().or_else(|e| Err::<int, ~str>(e + "!")).unwrap_err(),
"sadface!".to_owned());
assert_eq!(op2().or_else(|_| Ok::<int, &'static str>(667)).unwrap(), 667);
assert_eq!(op2().or_else(|e| Err::<int, &'static str>(e)).unwrap_err(),
"sadface");
}
#[test]
pub fn test_impl_map() {
assert_eq!(Ok::<~str, ~str>("a".to_owned()).map(|x| x + "b"),
Ok("ab".to_owned()));
assert_eq!(Err::<~str, ~str>("a".to_owned()).map(|x| x + "b"),
Err("a".to_owned()));
assert!(Ok::<int, int>(1).map(|x| x + 1) == Ok(2));
assert!(Err::<int, int>(1).map(|x| x + 1) == Err(1));
}
#[test]
pub fn test_impl_map_err() {
assert_eq!(Ok::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"),
Ok("a".to_owned()));
assert_eq!(Err::<~str, ~str>("a".to_owned()).map_err(|x| x + "b"),
Err("ab".to_owned()));
assert!(Ok::<int, int>(1).map_err(|x| x + 1) == Ok(1));
assert!(Err::<int, int>(1).map_err(|x| x + 1) == Err(2));
}
#[test]
@ -736,17 +743,19 @@ mod tests {
#[test]
pub fn test_fmt_default() {
let ok: Result<int, ~str> = Ok(100);
let err: Result<int, ~str> = Err("Err".to_owned());
let ok: Result<int, &'static str> = Ok(100);
let err: Result<int, &'static str> = Err("Err");
assert_eq!(format!("{}", ok), "Ok(100)".to_owned());
assert_eq!(format!("{}", err), "Err(Err)".to_owned());
let s = format!("{}", ok);
assert_eq!(s.as_slice(), "Ok(100)");
let s = format!("{}", err);
assert_eq!(s.as_slice(), "Err(Err)");
}
#[test]
pub fn test_unwrap_or() {
let ok: Result<int, ~str> = Ok(100);
let ok_err: Result<int, ~str> = Err("Err".to_owned());
let ok: Result<int, &'static str> = Ok(100);
let ok_err: Result<int, &'static str> = Err("Err");
assert_eq!(ok.unwrap_or(50), 100);
assert_eq!(ok_err.unwrap_or(50), 50);
@ -754,16 +763,16 @@ mod tests {
#[test]
pub fn test_unwrap_or_else() {
fn handler(msg: ~str) -> int {
if msg == "I got this.".to_owned() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50
} else {
fail!("BadBad")
}
}
let ok: Result<int, ~str> = Ok(100);
let ok_err: Result<int, ~str> = Err("I got this.".to_owned());
let ok: Result<int, &'static str> = Ok(100);
let ok_err: Result<int, &'static str> = Err("I got this.");
assert_eq!(ok.unwrap_or_else(handler), 100);
assert_eq!(ok_err.unwrap_or_else(handler), 50);
@ -772,15 +781,15 @@ mod tests {
#[test]
#[should_fail]
pub fn test_unwrap_or_else_failure() {
fn handler(msg: ~str) -> int {
if msg == "I got this.".to_owned() {
fn handler(msg: &'static str) -> int {
if msg == "I got this." {
50
} else {
fail!("BadBad")
}
}
let bad_err: Result<int, ~str> = Err("Unrecoverable mess.".to_owned());
let bad_err: Result<int, &'static str> = Err("Unrecoverable mess.");
let _ : int = bad_err.unwrap_or_else(handler);
}
}

View File

@ -10,9 +10,9 @@
// As noted by this file name, this file should not exist. This file should not
// exist because it performs allocations which libcore is not allowed to do. The
// reason for this file's existence is that the `~[T]` and `~str` types are
// language-defined types. Traits are defined in libcore, such as `Clone`, which
// these types need to implement, but the implementation can only be found in
// reason for this file's existence is that the `~[T]` type is a language-
// defined type. Traits are defined in libcore, such as `Clone`, which these
// types need to implement, but the implementation can only be found in
// libcore.
//
// Plan of attack for solving this problem:
@ -24,13 +24,11 @@
//
// Currently, no progress has been made on this list.
use char::Char;
use clone::Clone;
use container::Container;
use default::Default;
use finally::try_finally;
use intrinsics;
use iter::{range, Iterator, FromIterator};
use iter::{range, Iterator};
use mem;
use num::{CheckedMul, CheckedAdd};
use option::{Some, None};
@ -38,9 +36,6 @@ use ptr::RawPtr;
use ptr;
use raw::Vec;
use slice::ImmutableVector;
use str::StrSlice;
#[cfg(not(test))] use ops::Add;
#[allow(ctypes)]
extern {
@ -60,105 +55,6 @@ unsafe fn alloc(cap: uint) -> *mut Vec<()> {
ret
}
// Strings
impl Default for ~str {
fn default() -> ~str {
unsafe {
// Get some memory
let ptr = alloc(0);
// Initialize the memory
(*ptr).fill = 0;
(*ptr).alloc = 0;
mem::transmute(ptr)
}
}
}
impl Clone for ~str {
fn clone(&self) -> ~str {
// Don't use the clone() implementation above because it'll start
// requiring the eh_personality lang item (no fun)
unsafe {
let bytes = self.as_bytes().as_ptr();
let len = self.len();
let ptr = alloc(len) as *mut Vec<u8>;
ptr::copy_nonoverlapping_memory(&mut (*ptr).data, bytes, len);
(*ptr).fill = len;
(*ptr).alloc = len;
mem::transmute(ptr)
}
}
}
impl FromIterator<char> for ~str {
#[inline]
fn from_iter<T: Iterator<char>>(mut iterator: T) -> ~str {
let (lower, _) = iterator.size_hint();
let mut cap = if lower == 0 {16} else {lower};
let mut len = 0;
let mut tmp = [0u8, ..4];
unsafe {
let mut ptr = alloc(cap) as *mut Vec<u8>;
let mut ret = mem::transmute(ptr);
for ch in iterator {
let amt = ch.encode_utf8(tmp);
if len + amt > cap {
cap = cap.checked_mul(&2).unwrap();
if cap < len + amt {
cap = len + amt;
}
let ptr2 = alloc(cap) as *mut Vec<u8>;
ptr::copy_nonoverlapping_memory(&mut (*ptr2).data,
&(*ptr).data,
len);
// FIXME: #13994: port to the sized deallocation API when available
rust_deallocate(ptr as *u8, 0, 8);
mem::forget(ret);
ret = mem::transmute(ptr2);
ptr = ptr2;
}
let base = &mut (*ptr).data as *mut u8;
for byte in tmp.slice_to(amt).iter() {
*base.offset(len as int) = *byte;
len += 1;
}
(*ptr).fill = len;
}
ret
}
}
}
#[cfg(not(test))]
impl<'a> Add<&'a str,~str> for &'a str {
#[inline]
fn add(&self, rhs: & &'a str) -> ~str {
let amt = self.len().checked_add(&rhs.len()).unwrap();
unsafe {
let ptr = alloc(amt) as *mut Vec<u8>;
let base = &mut (*ptr).data as *mut _;
ptr::copy_nonoverlapping_memory(base,
self.as_bytes().as_ptr(),
self.len());
let base = base.offset(self.len() as int);
ptr::copy_nonoverlapping_memory(base,
rhs.as_bytes().as_ptr(),
rhs.len());
(*ptr).fill = amt;
(*ptr).alloc = amt;
mem::transmute(ptr)
}
}
}
// Arrays
impl<A: Clone> Clone for ~[A] {

View File

@ -25,7 +25,7 @@ use iter::range;
use num::Saturating;
use option::{None, Option, Some};
use raw::Repr;
use slice::{ImmutableVector, Vector};
use slice::ImmutableVector;
use slice;
use uint;
@ -596,20 +596,6 @@ pub fn eq_slice(a: &str, b: &str) -> bool {
eq_slice_(a, b)
}
/// Bytewise string equality
#[cfg(not(test))]
#[lang="uniq_str_eq"]
#[inline]
pub fn eq(a: &~str, b: &~str) -> bool {
eq_slice(*a, *b)
}
#[cfg(test)]
#[inline]
pub fn eq(a: &~str, b: &~str) -> bool {
eq_slice(*a, *b)
}
/*
Section: Misc
*/
@ -976,11 +962,6 @@ pub mod traits {
}
}
impl TotalOrd for ~str {
#[inline]
fn cmp(&self, other: &~str) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
}
impl<'a> Eq for &'a str {
#[inline]
fn eq(&self, other: & &'a str) -> bool {
@ -990,36 +971,17 @@ pub mod traits {
fn ne(&self, other: & &'a str) -> bool { !(*self).eq(other) }
}
impl Eq for ~str {
#[inline]
fn eq(&self, other: &~str) -> bool {
eq_slice((*self), (*other))
}
}
impl<'a> TotalEq for &'a str {}
impl TotalEq for ~str {}
impl<'a> Ord for &'a str {
#[inline]
fn lt(&self, other: & &'a str) -> bool { self.cmp(other) == Less }
}
impl Ord for ~str {
#[inline]
fn lt(&self, other: &~str) -> bool { self.cmp(other) == Less }
}
impl<'a, S: Str> Equiv<S> for &'a str {
#[inline]
fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) }
}
impl<'a, S: Str> Equiv<S> for ~str {
#[inline]
fn equiv(&self, other: &S) -> bool { eq_slice(*self, other.as_slice()) }
}
}
#[cfg(test)]
@ -1036,11 +998,6 @@ impl<'a> Str for &'a str {
fn as_slice<'a>(&'a self) -> &'a str { *self }
}
impl<'a> Str for ~str {
#[inline]
fn as_slice<'a>(&'a self) -> &'a str { let s: &'a str = *self; s }
}
impl<'a> Container for &'a str {
#[inline]
fn len(&self) -> uint {
@ -1048,11 +1005,6 @@ impl<'a> Container for &'a str {
}
}
impl Container for ~str {
#[inline]
fn len(&self) -> uint { self.as_slice().len() }
}
/// Methods for string slices
pub trait StrSlice<'a> {
/// Returns true if one string contains another

View File

@ -246,11 +246,11 @@ mod tests {
use super::*;
use clone::Clone;
use cmp::*;
use realstd::str::StrAllocating;
use realstd::str::{Str, StrAllocating};
#[test]
fn test_clone() {
let a = (1, "2".to_owned());
let a = (1, "2");
let b = a.clone();
assert_eq!(a, b);
}
@ -323,8 +323,11 @@ mod tests {
#[test]
fn test_show() {
assert_eq!(format!("{}", (1,)), "(1,)".to_owned());
assert_eq!(format!("{}", (1, true)), "(1, true)".to_owned());
assert_eq!(format!("{}", (1, "hi".to_owned(), true)), "(1, hi, true)".to_owned());
let s = format!("{}", (1,));
assert_eq!(s.as_slice(), "(1,)");
let s = format!("{}", (1, true));
assert_eq!(s.as_slice(), "(1, true)");
let s = format!("{}", (1, "hi", true));
assert_eq!(s.as_slice(), "(1, hi, true)");
}
}

View File

@ -274,12 +274,13 @@ impl<'a> Parser<'a> {
self.cur.next();
}
Some((_, other)) => {
self.err(
format!("expected `{}` but found `{}`", c, other));
self.err(format!("expected `{}` but found `{}`",
c,
other).as_slice());
}
None => {
self.err(
format!("expected `{}` but string was terminated", c));
self.err(format!("expected `{}` but string was terminated",
c).as_slice());
}
}
}
@ -307,7 +308,8 @@ impl<'a> Parser<'a> {
Some((_, c @ '#')) | Some((_, c @ '{')) |
Some((_, c @ '\\')) | Some((_, c @ '}')) => { c }
Some((_, c)) => {
self.err(format!("invalid escape character `{}`", c));
self.err(format!("invalid escape character `{}`",
c).as_slice());
c
}
None => {
@ -459,7 +461,7 @@ impl<'a> Parser<'a> {
return None;
}
method => {
self.err(format!("unknown method: `{}`", method));
self.err(format!("unknown method: `{}`", method).as_slice());
return None;
}
}
@ -526,7 +528,7 @@ impl<'a> Parser<'a> {
let word = self.word();
if word != "offset" {
self.err(format!("expected `offset`, found `{}`",
word));
word).as_slice());
} else {
self.must_consume(':');
match self.integer() {
@ -566,7 +568,7 @@ impl<'a> Parser<'a> {
"many" => Keyword(Many),
word => {
self.err(format!("unexpected plural selector `{}`",
word));
word).as_slice());
if word == "" {
break
} else {

View File

@ -661,7 +661,7 @@ pub fn getopts(args: &[StrBuf], optgrps: &[OptGroup]) -> Result {
/// Derive a usage message from a set of long options.
pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf {
let desc_sep = "\n" + " ".repeat(24);
let desc_sep = format!("\n{}", " ".repeat(24));
let mut rows = opts.iter().map(|optref| {
let OptGroup{short_name: short_name,
@ -713,7 +713,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf {
row.push_char(' ');
}
} else {
row.push_str(desc_sep)
row.push_str(desc_sep.as_slice())
}
// Normalize desc to contain words separated by one space character
@ -734,7 +734,7 @@ pub fn usage(brief: &str, opts: &[OptGroup]) -> StrBuf {
// FIXME: #5516 should be graphemes not codepoints
// wrapped description
row.push_str(desc_rows.connect(desc_sep));
row.push_str(desc_rows.connect(desc_sep.as_slice()).as_slice());
row
});
@ -784,7 +784,11 @@ fn format_option(opt: &OptGroup) -> StrBuf {
/// Derive a short one-line usage summary from a set of long options.
pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> StrBuf {
let mut line = format_strbuf!("Usage: {} ", program_name);
line.push_str(opts.iter().map(format_option).collect::<Vec<StrBuf>>().connect(" "));
line.push_str(opts.iter()
.map(format_option)
.collect::<Vec<StrBuf>>()
.connect(" ")
.as_slice());
line
}

View File

@ -690,13 +690,13 @@ mod test {
let pat = Pattern::new("a[0-9]b");
for i in range(0, 10) {
assert!(pat.matches(format!("a{}b", i)));
assert!(pat.matches(format!("a{}b", i).as_slice()));
}
assert!(!pat.matches("a_b"));
let pat = Pattern::new("a[!0-9]b");
for i in range(0, 10) {
assert!(!pat.matches(format!("a{}b", i)));
assert!(!pat.matches(format!("a{}b", i).as_slice()));
}
assert!(pat.matches("a_b"));
@ -704,11 +704,11 @@ mod test {
for &p in pats.iter() {
let pat = Pattern::new(p);
for c in "abcdefghijklmnopqrstuvwxyz".chars() {
assert!(pat.matches(c.to_str()));
assert!(pat.matches(c.to_str().as_slice()));
}
for c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ".chars() {
let options = MatchOptions {case_sensitive: false, .. MatchOptions::new()};
assert!(pat.matches_with(c.to_str(), options));
assert!(pat.matches_with(c.to_str().as_slice(), options));
}
assert!(pat.matches("1"));
assert!(pat.matches("2"));

View File

@ -46,7 +46,7 @@ macro_rules! rtassert (
macro_rules! rtabort (
($($arg:tt)*) => ( {
::macros::abort(format!($($arg)*));
::macros::abort(format!($($arg)*).as_slice());
} )
)

View File

@ -147,7 +147,10 @@ pub fn expand_syntax_ext(cx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
Some((err_pos, err_str)) => {
let pos = expr.span.lo + syntax::codemap::Pos::from_uint(err_pos + 1);
let span = syntax::codemap::mk_sp(pos,pos);
cx.span_err(span, format!("invalid hex float literal in hexfloat!: {}", err_str));
cx.span_err(span,
format!("invalid hex float literal in hexfloat!: \
{}",
err_str).as_slice());
return base::DummyResult::expr(sp);
}
_ => ()

View File

@ -302,8 +302,10 @@ pub fn mod_enabled(level: u32, module: &str) -> bool {
enabled(level, module, unsafe { (*DIRECTIVES).iter() })
}
fn enabled(level: u32, module: &str,
iter: slice::Items<directive::LogDirective>) -> bool {
fn enabled(level: u32,
module: &str,
iter: slice::Items<directive::LogDirective>)
-> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in iter.rev() {
match directive.name {
@ -322,7 +324,7 @@ fn enabled(level: u32, module: &str,
/// `Once` primitive (and this function is called from that primitive).
fn init() {
let mut directives = match os::getenv("RUST_LOG") {
Some(spec) => directive::parse_logging_spec(spec),
Some(spec) => directive::parse_logging_spec(spec.as_slice()),
None => Vec::new(),
};

View File

@ -104,9 +104,10 @@ fn get_error(_: c_int) -> IoError {
#[cfg(not(windows))]
fn get_error(s: c_int) -> IoError {
use std::io;
use std::str::raw::from_c_str;
let err_str = unsafe { from_c_str(gai_strerror(s)) };
let err_str = unsafe {
CString::new(gai_strerror(s), false).as_str().unwrap().to_strbuf()
};
IoError {
kind: io::OtherIoError,
desc: "unable to resolve host",

View File

@ -450,7 +450,9 @@ pub fn readlink(p: &CString) -> IoResult<Path> {
libc::VOLUME_NAME_DOS)
});
let ret = match ret {
Some(ref s) if s.starts_with(r"\\?\") => Ok(Path::new(s.slice_from(4))),
Some(ref s) if s.as_slice().starts_with(r"\\?\") => {
Ok(Path::new(s.as_slice().slice_from(4)))
}
Some(s) => Ok(Path::new(s)),
None => Err(super::last_error()),
};

View File

@ -323,7 +323,7 @@ fn spawn_process_os(cfg: ProcessConfig, in_fd: c_int, out_fd: c_int, err_fd: c_i
with_envp(cfg.env, |envp| {
with_dirp(cfg.cwd, |dirp| {
os::win32::as_mut_utf16_p(cmd_str, |cmdp| {
os::win32::as_mut_utf16_p(cmd_str.as_slice(), |cmdp| {
let created = CreateProcessW(ptr::null(),
cmdp,
ptr::mut_null(),
@ -396,7 +396,7 @@ fn zeroed_process_information() -> libc::types::os::arch::extra::PROCESS_INFORMA
}
#[cfg(windows)]
fn make_command_line(prog: &CString, args: &[CString]) -> ~str {
fn make_command_line(prog: &CString, args: &[CString]) -> StrBuf {
let mut cmd = StrBuf::new();
append_arg(&mut cmd, prog.as_str()
.expect("expected program name to be utf-8 encoded"));
@ -405,7 +405,7 @@ fn make_command_line(prog: &CString, args: &[CString]) -> ~str {
append_arg(&mut cmd, arg.as_str()
.expect("expected argument to be utf-8 encoded"));
}
return cmd.into_owned();
return cmd;
fn append_arg(cmd: &mut StrBuf, arg: &str) {
let quote = arg.chars().any(|c| c == ' ' || c == '\t');
@ -1093,7 +1093,7 @@ mod tests {
use std::c_str::CString;
use super::make_command_line;
fn test_wrapper(prog: &str, args: &[&str]) -> ~str {
fn test_wrapper(prog: &str, args: &[&str]) -> StrBuf {
make_command_line(&prog.to_c_str(),
args.iter()
.map(|a| a.to_c_str())

View File

@ -604,7 +604,7 @@ impl_to_biguint!(u32, FromPrimitive::from_u32)
impl_to_biguint!(u64, FromPrimitive::from_u64)
impl ToStrRadix for BigUint {
fn to_str_radix(&self, radix: uint) -> ~str {
fn to_str_radix(&self, radix: uint) -> StrBuf {
assert!(1 < radix && radix <= 16);
let (base, max_len) = get_radix_base(radix);
if base == BigDigit::base {
@ -627,15 +627,17 @@ impl ToStrRadix for BigUint {
return result;
}
fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> ~str {
if v.is_empty() { return "0".to_owned() }
fn fill_concat(v: &[BigDigit], radix: uint, l: uint) -> StrBuf {
if v.is_empty() {
return "0".to_strbuf()
}
let mut s = StrBuf::with_capacity(v.len() * l);
for n in v.iter().rev() {
let ss = (*n as uint).to_str_radix(radix);
s.push_str("0".repeat(l - ss.len()));
s.push_str(ss);
s.push_str("0".repeat(l - ss.len()).as_slice());
s.push_str(ss.as_slice());
}
s.as_slice().trim_left_chars('0').to_owned()
s.as_slice().trim_left_chars('0').to_strbuf()
}
}
}
@ -1209,11 +1211,11 @@ impl_to_bigint!(u64, FromPrimitive::from_u64)
impl ToStrRadix for BigInt {
#[inline]
fn to_str_radix(&self, radix: uint) -> ~str {
fn to_str_radix(&self, radix: uint) -> StrBuf {
match self.sign {
Plus => self.data.to_str_radix(radix),
Zero => "0".to_owned(),
Minus => "-".to_owned() + self.data.to_str_radix(radix)
Zero => "0".to_strbuf(),
Minus => format_strbuf!("-{}", self.data.to_str_radix(radix)),
}
}
}
@ -1476,29 +1478,112 @@ mod biguint_tests {
check("0", 3, "0");
check("1", 3, "8");
check("1" + "0000" + "0000" + "0000" + "0001" + "0000" + "0000" + "0000" + "0001", 3,
"8" + "0000" + "0000" + "0000" + "0008" + "0000" + "0000" + "0000" + "0008");
check("1" + "0000" + "0001" + "0000" + "0001", 2,
"4" + "0000" + "0004" + "0000" + "0004");
check("1" + "0001" + "0001", 1,
"2" + "0002" + "0002");
check("1\
0000\
0000\
0000\
0001\
0000\
0000\
0000\
0001",
3,
"8\
0000\
0000\
0000\
0008\
0000\
0000\
0000\
0008");
check("1\
0000\
0001\
0000\
0001",
2,
"4\
0000\
0004\
0000\
0004");
check("1\
0001\
0001",
1,
"2\
0002\
0002");
check("" + "4000" + "0000" + "0000" + "0000", 3,
"2" + "0000" + "0000" + "0000" + "0000");
check("" + "4000" + "0000", 2,
"1" + "0000" + "0000");
check("" + "4000", 2,
"1" + "0000");
check("\
4000\
0000\
0000\
0000",
3,
"2\
0000\
0000\
0000\
0000");
check("4000\
0000",
2,
"1\
0000\
0000");
check("4000",
2,
"1\
0000");
check("" + "4000" + "0000" + "0000" + "0000", 67,
"2" + "0000" + "0000" + "0000" + "0000" + "0000" + "0000" + "0000" + "0000");
check("" + "4000" + "0000", 35,
"2" + "0000" + "0000" + "0000" + "0000");
check("" + "4000", 19,
"2" + "0000" + "0000");
check("4000\
0000\
0000\
0000",
67,
"2\
0000\
0000\
0000\
0000\
0000\
0000\
0000\
0000");
check("4000\
0000",
35,
"2\
0000\
0000\
0000\
0000");
check("4000",
19,
"2\
0000\
0000");
check("" + "fedc" + "ba98" + "7654" + "3210" + "fedc" + "ba98" + "7654" + "3210", 4,
"f" + "edcb" + "a987" + "6543" + "210f" + "edcb" + "a987" + "6543" + "2100");
check("fedc\
ba98\
7654\
3210\
fedc\
ba98\
7654\
3210",
4,
"f\
edcb\
a987\
6543\
210f\
edcb\
a987\
6543\
2100");
check("88887777666655554444333322221111", 16,
"888877776666555544443333222211110000");
}
@ -1515,28 +1600,107 @@ mod biguint_tests {
check("0", 3, "0");
check("f", 3, "1");
check("1" + "0000" + "0000" + "0000" + "0001" + "0000" + "0000" + "0000" + "0001", 3,
"" + "2000" + "0000" + "0000" + "0000" + "2000" + "0000" + "0000" + "0000");
check("1" + "0000" + "0001" + "0000" + "0001", 2,
"" + "4000" + "0000" + "4000" + "0000");
check("1" + "0001" + "0001", 1,
"" + "8000" + "8000");
check("1\
0000\
0000\
0000\
0001\
0000\
0000\
0000\
0001",
3,
"2000\
0000\
0000\
0000\
2000\
0000\
0000\
0000");
check("1\
0000\
0001\
0000\
0001",
2,
"4000\
0000\
4000\
0000");
check("1\
0001\
0001",
1,
"8000\
8000");
check("2" + "0000" + "0000" + "0000" + "0001" + "0000" + "0000" + "0000" + "0001", 67,
"" + "4000" + "0000" + "0000" + "0000");
check("2" + "0000" + "0001" + "0000" + "0001", 35,
"" + "4000" + "0000");
check("2" + "0001" + "0001", 19,
"" + "4000");
check("2\
0000\
0000\
0000\
0001\
0000\
0000\
0000\
0001",
67,
"4000\
0000\
0000\
0000");
check("2\
0000\
0001\
0000\
0001",
35,
"4000\
0000");
check("2\
0001\
0001",
19,
"4000");
check("1" + "0000" + "0000" + "0000" + "0000", 1,
"" + "8000" + "0000" + "0000" + "0000");
check("1" + "0000" + "0000", 1,
"" + "8000" + "0000");
check("1" + "0000", 1,
"" + "8000");
check("f" + "edcb" + "a987" + "6543" + "210f" + "edcb" + "a987" + "6543" + "2100", 4,
"" + "fedc" + "ba98" + "7654" + "3210" + "fedc" + "ba98" + "7654" + "3210");
check("1\
0000\
0000\
0000\
0000",
1,
"8000\
0000\
0000\
0000");
check("1\
0000\
0000",
1,
"8000\
0000");
check("1\
0000",
1,
"8000");
check("f\
edcb\
a987\
6543\
210f\
edcb\
a987\
6543\
2100",
4,
"fedc\
ba98\
7654\
3210\
fedc\
ba98\
7654\
3210");
check("888877776666555544443333222211110000", 16,
"88887777666655554444333322221111");
@ -2543,7 +2707,7 @@ mod bigint_tests {
fn test_to_str_radix() {
fn check(n: int, ans: &str) {
let n: BigInt = FromPrimitive::from_int(n).unwrap();
assert!(ans == n.to_str_radix(10));
assert!(ans == n.to_str_radix(10).as_slice());
}
check(10, "10");
check(1, "1");
@ -2572,7 +2736,8 @@ mod bigint_tests {
// issue 10522, this hit an edge case that caused it to
// attempt to allocate a vector of size (-1u) == huge.
let x: BigInt = from_str("1" + "0".repeat(36)).unwrap();
let x: BigInt =
from_str(format!("1{}", "0".repeat(36)).as_slice()).unwrap();
let _y = x.to_str();
}

View File

@ -175,11 +175,15 @@ impl<T: fmt::Show + Num + Ord> fmt::Show for Complex<T> {
}
impl<T: ToStrRadix + Num + Ord> ToStrRadix for Complex<T> {
fn to_str_radix(&self, radix: uint) -> ~str {
fn to_str_radix(&self, radix: uint) -> StrBuf {
if self.im < Zero::zero() {
format!("{}-{}i", self.re.to_str_radix(radix), (-self.im).to_str_radix(radix))
format_strbuf!("{}-{}i",
self.re.to_str_radix(radix),
(-self.im).to_str_radix(radix))
} else {
format!("{}+{}i", self.re.to_str_radix(radix), self.im.to_str_radix(radix))
format_strbuf!("{}+{}i",
self.re.to_str_radix(radix),
self.im.to_str_radix(radix))
}
}
}

View File

@ -281,8 +281,10 @@ impl<T: fmt::Show> fmt::Show for Ratio<T> {
}
impl<T: ToStrRadix> ToStrRadix for Ratio<T> {
/// Renders as `numer/denom` where the numbers are in base `radix`.
fn to_str_radix(&self, radix: uint) -> ~str {
format!("{}/{}", self.numer.to_str_radix(radix), self.denom.to_str_radix(radix))
fn to_str_radix(&self, radix: uint) -> StrBuf {
format_strbuf!("{}/{}",
self.numer.to_str_radix(radix),
self.denom.to_str_radix(radix))
}
}
@ -582,7 +584,7 @@ mod test {
#[test]
fn test_to_from_str_radix() {
fn test(r: Rational, s: StrBuf, n: uint) {
assert_eq!(FromStrRadix::from_str_radix(s.to_owned(), n),
assert_eq!(FromStrRadix::from_str_radix(s.as_slice(), n),
Some(r));
assert_eq!(r.to_str_radix(n).to_strbuf(), s);
}

View File

@ -278,7 +278,10 @@ impl<'a> Parser<'a> {
fn noteof(&mut self, expected: &str) -> Result<(), Error> {
match self.next_char() {
true => Ok(()),
false => self.err(format!("Expected {} but got EOF.", expected)),
false => {
self.err(format!("Expected {} but got EOF.",
expected).as_slice())
}
}
}
@ -286,8 +289,11 @@ impl<'a> Parser<'a> {
match self.next_char() {
true if self.cur() == expected => Ok(()),
true => self.err(format!("Expected '{}' but got '{}'.",
expected, self.cur())),
false => self.err(format!("Expected '{}' but got EOF.", expected)),
expected, self.cur()).as_slice()),
false => {
self.err(format!("Expected '{}' but got EOF.",
expected).as_slice())
}
}
}
@ -429,8 +435,10 @@ impl<'a> Parser<'a> {
try!(self.noteof("not a ']'"))
let c2 = self.cur();
if c2 < c {
return self.err(format!(
"Invalid character class range '{}-{}'", c, c2))
return self.err(format!("Invalid character class \
range '{}-{}'",
c,
c2).as_slice())
}
ranges.push((c, self.cur()))
} else {
@ -491,9 +499,12 @@ impl<'a> Parser<'a> {
let closer =
match self.pos('}') {
Some(i) => i,
None => return self.err(format!(
"No closing brace for counted repetition starting at \
position {}.", start)),
None => {
return self.err(format!("No closing brace for counted \
repetition starting at position \
{}.",
start).as_slice())
}
};
self.chari = closer;
let greed = try!(self.get_next_greedy());
@ -502,11 +513,11 @@ impl<'a> Parser<'a> {
// Parse the min and max values from the regex.
let (mut min, mut max): (uint, Option<uint>);
if !inner.contains(",") {
min = try!(self.parse_uint(inner));
if !inner.as_slice().contains(",") {
min = try!(self.parse_uint(inner.as_slice()));
max = Some(min);
} else {
let pieces: Vec<&str> = inner.splitn(',', 1).collect();
let pieces: Vec<&str> = inner.as_slice().splitn(',', 1).collect();
let (smin, smax) = (*pieces.get(0), *pieces.get(1));
if smin.len() == 0 {
return self.err("Max repetitions cannot be specified \
@ -525,19 +536,19 @@ impl<'a> Parser<'a> {
if min > MAX_REPEAT {
return self.err(format!(
"{} exceeds maximum allowed repetitions ({})",
min, MAX_REPEAT));
min, MAX_REPEAT).as_slice());
}
if max.is_some() {
let m = max.unwrap();
if m > MAX_REPEAT {
return self.err(format!(
"{} exceeds maximum allowed repetitions ({})",
m, MAX_REPEAT));
m, MAX_REPEAT).as_slice());
}
if m < min {
return self.err(format!(
"Max repetitions ({}) cannot be smaller than min \
repetitions ({}).", m, min));
repetitions ({}).", m, min).as_slice());
}
}
@ -600,7 +611,10 @@ impl<'a> Parser<'a> {
if c.is_uppercase() { flags |= FLAG_NEGATED }
Ok(Class(ranges, flags))
}
_ => self.err(format!("Invalid escape sequence '\\\\{}'", c)),
_ => {
self.err(format!("Invalid escape sequence '\\\\{}'",
c).as_slice())
}
}
}
@ -619,7 +633,7 @@ impl<'a> Parser<'a> {
Some(i) => i,
None => return self.err(format!(
"Missing '\\}' for unclosed '\\{' at position {}",
self.chari)),
self.chari).as_slice()),
};
if closer - self.chari + 1 == 0 {
return self.err("No Unicode class name found.")
@ -634,8 +648,10 @@ impl<'a> Parser<'a> {
self.chari += 1;
}
match find_class(UNICODE_CLASSES, name.as_slice()) {
None => return self.err(format!(
"Could not find Unicode class '{}'", name)),
None => {
return self.err(format!("Could not find Unicode class '{}'",
name).as_slice())
}
Some(ranges) => {
Ok(Class(ranges, negated | (self.flags & FLAG_NOCASE)))
}
@ -659,8 +675,10 @@ impl<'a> Parser<'a> {
let s = self.slice(start, end);
match num::from_str_radix::<u32>(s.as_slice(), 8) {
Some(n) => Ok(Literal(try!(self.char_from_u32(n)), FLAG_EMPTY)),
None => self.err(format!(
"Could not parse '{}' as octal number.", s)),
None => {
self.err(format!("Could not parse '{}' as octal number.",
s).as_slice())
}
}
}
@ -674,8 +692,11 @@ impl<'a> Parser<'a> {
let start = self.chari + 2;
let closer =
match self.pos('}') {
None => return self.err(format!(
"Missing '\\}' for unclosed '\\{' at position {}", start)),
None => {
return self.err(format!("Missing '\\}' for unclosed \
'\\{' at position {}",
start).as_slice())
}
Some(i) => i,
};
self.chari = closer;
@ -689,7 +710,8 @@ impl<'a> Parser<'a> {
fn parse_hex_two(&mut self) -> Result<Ast, Error> {
let (start, end) = (self.chari, self.chari + 2);
let bad = self.slice(start - 2, self.chars.len());
try!(self.noteof(format!("Invalid hex escape sequence '{}'", bad)))
try!(self.noteof(format!("Invalid hex escape sequence '{}'",
bad).as_slice()))
self.parse_hex_digits(self.slice(start, end).as_slice())
}
@ -697,8 +719,10 @@ impl<'a> Parser<'a> {
fn parse_hex_digits(&self, s: &str) -> Result<Ast, Error> {
match num::from_str_radix::<u32>(s, 16) {
Some(n) => Ok(Literal(try!(self.char_from_u32(n)), FLAG_EMPTY)),
None => self.err(format!(
"Could not parse '{}' as hex number.", s)),
None => {
self.err(format!("Could not parse '{}' as hex number.",
s).as_slice())
}
}
}
@ -722,7 +746,8 @@ impl<'a> Parser<'a> {
"Capture names can only have underscores, letters and digits.")
}
if self.names.contains(&name) {
return self.err(format!("Duplicate capture group name '{}'.", name))
return self.err(format!("Duplicate capture group name '{}'.",
name).as_slice())
}
self.names.push(name.clone());
self.chari = closer;
@ -754,7 +779,7 @@ impl<'a> Parser<'a> {
if sign < 0 {
return self.err(format!(
"Cannot negate flags twice in '{}'.",
self.slice(start, self.chari + 1)))
self.slice(start, self.chari + 1)).as_slice())
}
sign = -1;
saw_flag = false;
@ -765,7 +790,7 @@ impl<'a> Parser<'a> {
if !saw_flag {
return self.err(format!(
"A valid flag does not follow negation in '{}'",
self.slice(start, self.chari + 1)))
self.slice(start, self.chari + 1)).as_slice())
}
flags = flags ^ flags;
}
@ -777,7 +802,7 @@ impl<'a> Parser<'a> {
return Ok(())
}
_ => return self.err(format!(
"Unrecognized flag '{}'.", self.cur())),
"Unrecognized flag '{}'.", self.cur()).as_slice()),
}
}
}
@ -871,16 +896,21 @@ impl<'a> Parser<'a> {
fn parse_uint(&self, s: &str) -> Result<uint, Error> {
match from_str::<uint>(s) {
Some(i) => Ok(i),
None => self.err(format!(
"Expected an unsigned integer but got '{}'.", s)),
None => {
self.err(format!("Expected an unsigned integer but got '{}'.",
s).as_slice())
}
}
}
fn char_from_u32(&self, n: u32) -> Result<char, Error> {
match char::from_u32(n) {
Some(c) => Ok(c),
None => self.err(format!(
"Could not decode '{}' to unicode character.", n)),
None => {
self.err(format!("Could not decode '{}' to unicode \
character.",
n).as_slice())
}
}
}

View File

@ -20,38 +20,40 @@ fn bench_assert_match(b: &mut Bencher, re: Regex, text: &str) {
#[bench]
fn no_exponential(b: &mut Bencher) {
let n = 100;
let re = Regex::new("a?".repeat(n) + "a".repeat(n)).unwrap();
let re = Regex::new(format!("{}{}",
"a?".repeat(n),
"a".repeat(n)).as_slice()).unwrap();
let text = "a".repeat(n);
bench_assert_match(b, re, text);
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn literal(b: &mut Bencher) {
let re = regex!("y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
let text = format!("{}y", "x".repeat(50));
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn not_literal(b: &mut Bencher) {
let re = regex!(".y");
let text = "x".repeat(50) + "y";
bench_assert_match(b, re, text);
let text = format!("{}y", "x".repeat(50));
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn match_class(b: &mut Bencher) {
let re = regex!("[abcdw]");
let text = "xxxx".repeat(20) + "w";
bench_assert_match(b, re, text);
let text = format!("{}w", "xxxx".repeat(20));
bench_assert_match(b, re, text.as_slice());
}
#[bench]
fn match_class_in_range(b: &mut Bencher) {
// 'b' is between 'a' and 'c', so the class range checking doesn't help.
let re = regex!("[ac]");
let text = "bbbb".repeat(20) + "c";
bench_assert_match(b, re, text);
let text = format!("{}c", "bbbb".repeat(20));
bench_assert_match(b, re, text.as_slice());
}
#[bench]
@ -75,7 +77,7 @@ fn anchored_literal_short_non_match(b: &mut Bencher) {
fn anchored_literal_long_non_match(b: &mut Bencher) {
let re = regex!("^zbc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
b.iter(|| re.is_match(text.as_slice()));
}
#[bench]
@ -89,7 +91,7 @@ fn anchored_literal_short_match(b: &mut Bencher) {
fn anchored_literal_long_match(b: &mut Bencher) {
let re = regex!("^.bc(d|e)");
let text = "abcdefghijklmnopqrstuvwxyz".repeat(15);
b.iter(|| re.is_match(text));
b.iter(|| re.is_match(text.as_slice()));
}
#[bench]

View File

@ -82,10 +82,10 @@ fn native(cx: &mut ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree])
// error is logged in 'parse' with cx.span_err
None => return DummyResult::any(sp),
};
let re = match Regex::new(regex.to_owned()) {
let re = match Regex::new(regex.as_slice()) {
Ok(re) => re,
Err(err) => {
cx.span_err(sp, err.to_str());
cx.span_err(sp, err.to_str().as_slice());
return DummyResult::any(sp)
}
};
@ -612,7 +612,7 @@ fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<StrBuf> {
_ => {
cx.span_err(entry.span, format!(
"expected string literal but got `{}`",
pprust::lit_to_str(lit)));
pprust::lit_to_str(lit)).as_slice());
return None
}
}
@ -620,7 +620,7 @@ fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<StrBuf> {
_ => {
cx.span_err(entry.span, format!(
"expected string literal but got `{}`",
pprust::expr_to_str(entry)));
pprust::expr_to_str(entry)).as_slice());
return None
}
};

View File

@ -56,17 +56,24 @@ fn run_ar(sess: &Session, args: &str, cwd: Option<&Path>,
Ok(prog) => {
let o = prog.wait_with_output().unwrap();
if !o.status.success() {
sess.err(format!("{} failed with: {}", cmd, o.status));
sess.err(format!("{} failed with: {}",
cmd,
o.status).as_slice());
sess.note(format!("stdout ---\n{}",
str::from_utf8(o.output.as_slice()).unwrap()));
str::from_utf8(o.output
.as_slice()).unwrap())
.as_slice());
sess.note(format!("stderr ---\n{}",
str::from_utf8(o.error.as_slice()).unwrap()));
str::from_utf8(o.error
.as_slice()).unwrap())
.as_slice());
sess.abort_if_errors();
}
o
},
Err(e) => {
sess.err(format!("could not exec `{}`: {}", ar.as_slice(), e));
sess.err(format!("could not exec `{}`: {}", ar.as_slice(),
e).as_slice());
sess.abort_if_errors();
fail!("rustc::back::archive::run_ar() should not reach this point");
}
@ -158,7 +165,7 @@ impl<'a> Archive<'a> {
if skip.iter().any(|s| *s == filename) { continue }
if filename.contains(".SYMDEF") { continue }
let filename = format!("r-{}-{}", name, filename);
let filename = format_strbuf!("r-{}-{}", name, filename);
let new_filename = file.with_filename(filename);
try!(fs::rename(file, &new_filename));
inputs.push(new_filename);
@ -178,8 +185,8 @@ impl<'a> Archive<'a> {
};
// On Windows, static libraries sometimes show up as libfoo.a and other
// times show up as foo.lib
let oslibname = format!("{}{}.{}", osprefix, name, osext);
let unixlibname = format!("lib{}.a", name);
let oslibname = format_strbuf!("{}{}.{}", osprefix, name, osext);
let unixlibname = format_strbuf!("lib{}.a", name);
let mut rustpath = filesearch::rust_path();
rustpath.push(self.sess.target_filesearch().get_lib_path());
@ -194,7 +201,8 @@ impl<'a> Archive<'a> {
}
}
self.sess.fatal(format!("could not find native static library `{}`, \
perhaps an -L flag is missing?", name));
perhaps an -L flag is missing?",
name).as_slice());
}
}

View File

@ -62,7 +62,9 @@ pub fn llvm_err(sess: &Session, msg: StrBuf) -> ! {
} else {
let err = CString::new(cstr, true);
let err = str::from_utf8_lossy(err.as_bytes());
sess.fatal((msg.as_slice() + ": " + err.as_slice()));
sess.fatal(format!("{}: {}",
msg.as_slice(),
err.as_slice()).as_slice());
}
}
}
@ -167,7 +169,9 @@ pub mod write {
"dynamic-no-pic" => lib::llvm::RelocDynamicNoPic,
_ => {
sess.err(format!("{} is not a valid relocation mode",
sess.opts.cg.relocation_model));
sess.opts
.cg
.relocation_model).as_slice());
sess.abort_if_errors();
return;
}
@ -219,7 +223,8 @@ pub mod write {
for pass in sess.opts.cg.passes.iter() {
pass.as_slice().with_c_str(|s| {
if !llvm::LLVMRustAddPass(mpm, s) {
sess.warn(format!("unknown pass {}, ignoring", *pass));
sess.warn(format!("unknown pass {}, ignoring",
*pass).as_slice());
}
})
}
@ -360,16 +365,21 @@ pub mod write {
match cmd.output() {
Ok(prog) => {
if !prog.status.success() {
sess.err(format!("linking with `{}` failed: {}", pname, prog.status));
sess.note(format!("{}", &cmd));
sess.err(format!("linking with `{}` failed: {}",
pname,
prog.status).as_slice());
sess.note(format!("{}", &cmd).as_slice());
let mut note = prog.error.clone();
note.push_all(prog.output.as_slice());
sess.note(str::from_utf8(note.as_slice()).unwrap().to_owned());
sess.note(str::from_utf8(note.as_slice()).unwrap()
.as_slice());
sess.abort_if_errors();
}
},
Err(e) => {
sess.err(format!("could not exec the linker `{}`: {}", pname, e));
sess.err(format!("could not exec the linker `{}`: {}",
pname,
e).as_slice());
sess.abort_if_errors();
}
}
@ -531,8 +541,8 @@ pub fn find_crate_id(attrs: &[ast::Attribute], out_filestem: &str) -> CrateId {
match attr::find_crateid(attrs) {
None => from_str(out_filestem).unwrap_or_else(|| {
let mut s = out_filestem.chars().filter(|c| c.is_XID_continue());
from_str(s.collect::<StrBuf>()
.to_owned()).or(from_str("rust-out")).unwrap()
from_str(s.collect::<StrBuf>().as_slice())
.or(from_str("rust-out")).unwrap()
}),
Some(s) => s,
}
@ -639,7 +649,7 @@ pub fn sanitize(s: &str) -> StrBuf {
if result.len() > 0u &&
result.as_slice()[0] != '_' as u8 &&
! char::is_XID_start(result.as_slice()[0] as char) {
return ("_" + result.as_slice()).to_strbuf();
return format!("_{}", result.as_slice()).to_strbuf();
}
return result;
@ -666,7 +676,7 @@ pub fn mangle<PI: Iterator<PathElem>>(mut path: PI,
fn push(n: &mut StrBuf, s: &str) {
let sani = sanitize(s);
n.push_str(format!("{}{}", sani.len(), sani));
n.push_str(format!("{}{}", sani.len(), sani).as_slice());
}
// First, connect each component with <len, name> pairs.
@ -691,7 +701,7 @@ pub fn exported_name(path: PathElems, hash: &str, vers: &str) -> StrBuf {
// The version will get mangled to have a leading '_', but it makes more
// sense to lead with a 'v' b/c this is a version...
let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
"v" + vers
format!("v{}", vers)
} else {
vers.to_owned()
};
@ -774,7 +784,9 @@ fn remove(sess: &Session, path: &Path) {
match fs::unlink(path) {
Ok(..) => {}
Err(e) => {
sess.err(format!("failed to remove {}: {}", path.display(), e));
sess.err(format!("failed to remove {}: {}",
path.display(),
e).as_slice());
}
}
}
@ -815,7 +827,7 @@ pub fn filename_for_input(sess: &Session, crate_type: config::CrateType,
let libname = output_lib_filename(id);
match crate_type {
config::CrateTypeRlib => {
out_filename.with_filename(format!("lib{}.rlib", libname))
out_filename.with_filename(format_strbuf!("lib{}.rlib", libname))
}
config::CrateTypeDylib => {
let (prefix, suffix) = match sess.targ_cfg.os {
@ -825,10 +837,13 @@ pub fn filename_for_input(sess: &Session, crate_type: config::CrateType,
abi::OsAndroid => (loader::ANDROID_DLL_PREFIX, loader::ANDROID_DLL_SUFFIX),
abi::OsFreebsd => (loader::FREEBSD_DLL_PREFIX, loader::FREEBSD_DLL_SUFFIX),
};
out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
out_filename.with_filename(format_strbuf!("{}{}{}",
prefix,
libname,
suffix))
}
config::CrateTypeStaticlib => {
out_filename.with_filename(format!("lib{}.a", libname))
out_filename.with_filename(format_strbuf!("lib{}.a", libname))
}
config::CrateTypeExecutable => out_filename.clone(),
}
@ -855,12 +870,14 @@ fn link_binary_output(sess: &Session,
let obj_is_writeable = is_writeable(&obj_filename);
let out_is_writeable = is_writeable(&out_filename);
if !out_is_writeable {
sess.fatal(format!("output file {} is not writeable -- check its permissions.",
out_filename.display()));
sess.fatal(format!("output file {} is not writeable -- check its \
permissions.",
out_filename.display()).as_slice());
}
else if !obj_is_writeable {
sess.fatal(format!("object file {} is not writeable -- check its permissions.",
obj_filename.display()));
sess.fatal(format!("object file {} is not writeable -- check its \
permissions.",
obj_filename.display()).as_slice());
}
match crate_type {
@ -936,7 +953,8 @@ fn link_rlib<'a>(sess: &'a Session,
Ok(..) => {}
Err(e) => {
sess.err(format!("failed to write {}: {}",
metadata.display(), e));
metadata.display(),
e).as_slice());
sess.abort_if_errors();
}
}
@ -956,7 +974,9 @@ fn link_rlib<'a>(sess: &'a Session,
}) {
Ok(()) => {}
Err(e) => {
sess.err(format!("failed to write compressed bytecode: {}", e));
sess.err(format!("failed to write compressed bytecode: \
{}",
e).as_slice());
sess.abort_if_errors()
}
}
@ -1003,7 +1023,8 @@ fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
let name = sess.cstore.get_crate_data(cnum).name.clone();
let p = match *path {
Some(ref p) => p.clone(), None => {
sess.err(format!("could not find rlib for: `{}`", name));
sess.err(format!("could not find rlib for: `{}`",
name).as_slice());
continue
}
};
@ -1015,7 +1036,9 @@ fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
cstore::NativeUnknown => "library",
cstore::NativeFramework => "framework",
};
sess.warn(format!("unlinked native {}: {}", name, *lib));
sess.warn(format!("unlinked native {}: {}",
name,
*lib).as_slice());
}
}
}
@ -1049,16 +1072,21 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
match prog {
Ok(prog) => {
if !prog.status.success() {
sess.err(format!("linking with `{}` failed: {}", pname, prog.status));
sess.note(format!("{}", &cmd));
sess.err(format!("linking with `{}` failed: {}",
pname,
prog.status).as_slice());
sess.note(format!("{}", &cmd).as_slice());
let mut output = prog.error.clone();
output.push_all(prog.output.as_slice());
sess.note(str::from_utf8(output.as_slice()).unwrap().to_owned());
sess.note(str::from_utf8(output.as_slice()).unwrap()
.as_slice());
sess.abort_if_errors();
}
},
Err(e) => {
sess.err(format!("could not exec the linker `{}`: {}", pname, e));
sess.err(format!("could not exec the linker `{}`: {}",
pname,
e).as_slice());
sess.abort_if_errors();
}
}
@ -1070,7 +1098,7 @@ fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
match Command::new("dsymutil").arg(out_filename).status() {
Ok(..) => {}
Err(e) => {
sess.err(format!("failed to run dsymutil: {}", e));
sess.err(format!("failed to run dsymutil: {}", e).as_slice());
sess.abort_if_errors();
}
}
@ -1409,7 +1437,8 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
// against the archive.
if sess.lto() {
let name = sess.cstore.get_crate_data(cnum).name.clone();
time(sess.time_passes(), format!("altering {}.rlib", name),
time(sess.time_passes(),
format!("altering {}.rlib", name).as_slice(),
(), |()| {
let dst = tmpdir.join(cratepath.filename().unwrap());
match fs::copy(&cratepath, &dst) {
@ -1418,12 +1447,12 @@ fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
sess.err(format!("failed to copy {} to {}: {}",
cratepath.display(),
dst.display(),
e));
e).as_slice());
sess.abort_if_errors();
}
}
let mut archive = Archive::open(sess, dst.clone());
archive.remove_file(format!("{}.o", name));
archive.remove_file(format!("{}.o", name).as_slice());
let files = archive.files();
if files.iter().any(|s| s.as_slice().ends_with(".o")) {
cmd.arg(dst);

View File

@ -47,29 +47,46 @@ pub fn run(sess: &session::Session, llmod: ModuleRef,
let path = match path {
Some(p) => p,
None => {
sess.fatal(format!("could not find rlib for: `{}`", name));
sess.fatal(format!("could not find rlib for: `{}`",
name).as_slice());
}
};
let archive = ArchiveRO::open(&path).expect("wanted an rlib");
debug!("reading {}", name);
let bc = time(sess.time_passes(), format!("read {}.bc.deflate", name), (), |_|
archive.read(format!("{}.bc.deflate", name)));
let bc = time(sess.time_passes(),
format!("read {}.bc.deflate", name).as_slice(),
(),
|_| {
archive.read(format!("{}.bc.deflate",
name).as_slice())
});
let bc = bc.expect("missing compressed bytecode in archive!");
let bc = time(sess.time_passes(), format!("inflate {}.bc", name), (), |_|
match flate::inflate_bytes(bc) {
Some(bc) => bc,
None => sess.fatal(format!("failed to decompress bc of `{}`", name))
let bc = time(sess.time_passes(),
format!("inflate {}.bc", name).as_slice(),
(),
|_| {
match flate::inflate_bytes(bc) {
Some(bc) => bc,
None => {
sess.fatal(format!("failed to decompress \
bc of `{}`",
name).as_slice())
}
}
});
let ptr = bc.as_slice().as_ptr();
debug!("linking {}", name);
time(sess.time_passes(), format!("ll link {}", name), (), |()| unsafe {
time(sess.time_passes(),
format!("ll link {}", name).as_slice(),
(),
|()| unsafe {
if !llvm::LLVMRustLinkInExternalBitcode(llmod,
ptr as *libc::c_char,
bc.len() as libc::size_t) {
link::llvm_err(sess,
(format_strbuf!("failed to load bc of `{}`",
name)));
format_strbuf!("failed to load bc of `{}`",
name.as_slice()));
}
});
}

View File

@ -59,7 +59,7 @@ pub fn get_rpath_flags(sess: &Session, out_filename: &Path) -> Vec<StrBuf> {
pub fn rpaths_to_flags(rpaths: &[StrBuf]) -> Vec<StrBuf> {
let mut ret = Vec::new();
for rpath in rpaths.iter() {
ret.push(("-Wl,-rpath," + (*rpath).as_slice()).to_strbuf());
ret.push(format!("-Wl,-rpath,{}", (*rpath).as_slice()));
}
return ret;
}
@ -132,8 +132,9 @@ pub fn get_rpath_relative_to_output(os: abi::Os,
let relative = lib.path_relative_from(&output);
let relative = relative.expect("could not create rpath relative to output");
// FIXME (#9639): This needs to handle non-utf8 paths
(prefix + "/" + relative.as_str()
.expect("non-utf8 component in path")).to_strbuf()
format!("{}/{}",
prefix,
relative.as_str().expect("non-utf8 component in path"))
}
pub fn get_install_prefix_rpath(sysroot: &Path, target_triple: &str) -> StrBuf {

View File

@ -328,18 +328,23 @@ pub fn build_codegen_options(matches: &getopts::Matches) -> CodegenOptions
if option_to_lookup.as_slice() != candidate { continue }
if !setter(&mut cg, value) {
match value {
Some(..) => early_error(format!("codegen option `{}` takes \
no value", key)),
None => early_error(format!("codegen option `{0}` requires \
a value (-C {0}=<value>)",
key))
Some(..) => {
early_error(format!("codegen option `{}` takes no \
value", key).as_slice())
}
None => {
early_error(format!("codegen option `{0}` requires \
a value (-C {0}=<value>)",
key).as_slice())
}
}
}
found = true;
break;
}
if !found {
early_error(format!("unknown codegen option: `{}`", key));
early_error(format!("unknown codegen option: `{}`",
key).as_slice());
}
}
return cg;
@ -464,8 +469,8 @@ pub fn build_target_config(sopts: &Options) -> Config {
let arch = match get_arch(sopts.target_triple.as_slice()) {
Some(arch) => arch,
None => {
early_error("unknown architecture: " +
sopts.target_triple.as_slice())
early_error(format!("unknown architecture: {}",
sopts.target_triple.as_slice()).as_slice())
}
};
let (int_type, uint_type) = match arch {
@ -570,7 +575,10 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
"staticlib" => CrateTypeStaticlib,
"dylib" => CrateTypeDylib,
"bin" => CrateTypeExecutable,
_ => early_error(format!("unknown crate type: `{}`", part))
_ => {
early_error(format!("unknown crate type: `{}`",
part).as_slice())
}
};
crate_types.push(new_part)
}
@ -589,14 +597,17 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
let level_short = level_name.slice_chars(0, 1);
let level_short = level_short.to_ascii().to_upper().into_str();
let flags = matches.opt_strs(level_short).move_iter().collect::<Vec<_>>().append(
matches.opt_strs(level_name).as_slice());
let flags = matches.opt_strs(level_short.as_slice())
.move_iter()
.collect::<Vec<_>>()
.append(matches.opt_strs(level_name).as_slice());
for lint_name in flags.iter() {
let lint_name = lint_name.replace("-", "_");
let lint_name = lint_name.replace("-", "_").into_strbuf();
match lint_dict.find_equiv(&lint_name) {
None => {
early_error(format!("unknown {} flag: {}",
level_name, lint_name));
level_name,
lint_name).as_slice());
}
Some(lint) => {
lint_opts.push((lint.lint, *level));
@ -618,7 +629,8 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
}
}
if this_bit == 0 {
early_error(format!("unknown debug flag: {}", *debug_flag))
early_error(format!("unknown debug flag: {}",
*debug_flag).as_slice())
}
debugging_opts |= this_bit;
}
@ -638,7 +650,10 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
"bc" => link::OutputTypeBitcode,
"obj" => link::OutputTypeObject,
"link" => link::OutputTypeExe,
_ => early_error(format!("unknown emission type: `{}`", part))
_ => {
early_error(format!("unknown emission type: `{}`",
part).as_slice())
}
};
output_types.push(output_type)
}
@ -671,8 +686,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
Some("2") => Default,
Some("3") => Aggressive,
Some(arg) => {
early_error(format!("optimization level needs to be between 0-3 \
(instead was `{}`)", arg));
early_error(format!("optimization level needs to be \
between 0-3 (instead was `{}`)",
arg).as_slice());
}
}
} else {
@ -692,8 +708,9 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
None |
Some("2") => FullDebugInfo,
Some(arg) => {
early_error(format!("optimization level needs to be between 0-3 \
(instead was `{}`)", arg));
early_error(format!("optimization level needs to be between \
0-3 (instead was `{}`)",
arg).as_slice());
}
}
} else {
@ -725,9 +742,11 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
None => Auto,
Some(arg) => early_error(format!(
"argument for --color must be auto, always or never (instead was `{}`)",
arg))
Some(arg) => {
early_error(format!("argument for --color must be auto, always \
or never (instead was `{}`)",
arg).as_slice())
}
};
Options {

View File

@ -511,7 +511,7 @@ fn write_out_deps(sess: &Session,
Ok(()) => {}
Err(e) => {
sess.fatal(format!("error writing dependencies to `{}`: {}",
deps_filename.display(), e));
deps_filename.display(), e).as_slice());
}
}
}
@ -705,7 +705,8 @@ fn print_flowgraph<W:io::Writer>(analysis: CrateAnalysis,
let m = "graphviz::render failed";
io::IoError {
detail: Some(match orig_detail {
None => m.into_owned(), Some(d) => format!("{}: {}", m, d)
None => m.into_strbuf(),
Some(d) => format_strbuf!("{}: {}", m, d)
}),
..ioerr
}

View File

@ -120,7 +120,8 @@ Additional help:
-C help Print codegen options
-W help Print 'lint' options and default settings
-Z help Print internal options for debugging rustc\n",
getopts::usage(message, config::optgroups().as_slice()));
getopts::usage(message.as_slice(),
config::optgroups().as_slice()));
}
fn describe_warnings() {
@ -142,8 +143,8 @@ Available lint options:
for &(_, name) in lint_dict.iter() {
max_key = cmp::max(name.len(), max_key);
}
fn padded(max: uint, s: &str) -> ~str {
" ".repeat(max - s.len()) + s
fn padded(max: uint, s: &str) -> StrBuf {
format!("{}{}", " ".repeat(max - s.len()), s)
}
println!("\nAvailable lint checks:\n");
println!(" {} {:7.7s} {}",
@ -153,7 +154,7 @@ Available lint options:
for (spec, name) in lint_dict.move_iter() {
let name = name.replace("_", "-");
println!(" {} {:7.7s} {}",
padded(max_key, name),
padded(max_key, name.as_slice()),
lint::level_to_str(spec.default),
spec.desc);
}
@ -305,16 +306,18 @@ pub fn parse_pretty(sess: &Session, name: &str) -> PpMode {
(arg, "flowgraph") => {
match arg.and_then(from_str) {
Some(id) => PpmFlowGraph(id),
None => sess.fatal(format_strbuf!("`pretty flowgraph=<nodeid>` needs \
an integer <nodeid>; got {}",
arg.unwrap_or("nothing")).as_slice())
None => {
sess.fatal(format!("`pretty flowgraph=<nodeid>` needs \
an integer <nodeid>; got {}",
arg.unwrap_or("nothing")).as_slice())
}
}
}
_ => {
sess.fatal(format!(
"argument to `pretty` must be one of `normal`, \
`expanded`, `flowgraph=<nodeid>`, `typed`, `identified`, \
or `expanded,identified`; got {}", name));
or `expanded,identified`; got {}", name).as_slice());
}
}
}
@ -397,18 +400,23 @@ fn monitor(f: proc():Send) {
let xs = [
"the compiler hit an unexpected failure path. this is a bug.".to_owned(),
"we would appreciate a bug report: " + BUG_REPORT_URL,
format!("we would appreciate a bug report: {}",
BUG_REPORT_URL),
"run with `RUST_BACKTRACE=1` for a backtrace".to_owned(),
];
for note in xs.iter() {
emitter.emit(None, *note, diagnostic::Note)
emitter.emit(None, note.as_slice(), diagnostic::Note)
}
match r.read_to_str() {
Ok(s) => println!("{}", s),
Err(e) => emitter.emit(None,
format!("failed to read internal stderr: {}", e),
diagnostic::Error),
Err(e) => {
emitter.emit(None,
format!("failed to read internal \
stderr: {}",
e).as_slice(),
diagnostic::Error)
}
}
}

View File

@ -141,7 +141,8 @@ impl Session {
// This exists to help with refactoring to eliminate impossible
// cases later on
pub fn impossible_case(&self, sp: Span, msg: &str) -> ! {
self.span_bug(sp, format!("impossible case reached: {}", msg));
self.span_bug(sp,
format!("impossible case reached: {}", msg).as_slice());
}
pub fn verbose(&self) -> bool { self.debugging_opt(config::VERBOSE) }
pub fn time_passes(&self) -> bool { self.debugging_opt(config::TIME_PASSES) }

View File

@ -109,7 +109,7 @@ impl<'a> Context<'a> {
self.sess.span_err(span, explain);
self.sess.span_note(span, format!("add \\#![feature({})] to the \
crate attributes to enable",
feature));
feature).as_slice());
}
}
@ -259,7 +259,9 @@ impl<'a> Visitor<()> for Context<'a> {
else {
for &quote in quotes.iter() {
if id == token::str_to_ident(quote) {
self.gate_feature("quote", path.span, quote + msg);
self.gate_feature("quote",
path.span,
format!("{}{}", quote, msg).as_slice());
}
}
}

View File

@ -65,7 +65,7 @@ pub fn with_version(krate: &str) -> Option<(InternedString, ast::StrStyle)> {
_ => {
Some((token::intern_and_get_ident(format!("{}\\#{}",
krate,
VERSION)),
VERSION).as_slice()),
ast::CookedStr))
}
}

View File

@ -327,7 +327,7 @@ fn mk_test_module(cx: &TestCtxt) -> @ast::Item {
pub fn main() {
#![main]
use std::slice::Vector;
test::test_main_static_x(::std::os::args().as_slice(), TESTS);
test::test_main_static(::std::os::args().as_slice(), TESTS);
}
)).unwrap();

View File

@ -91,7 +91,8 @@ fn warn_if_multiple_versions(diag: &SpanHandler, cstore: &CStore) {
for ((name, _), dupes) in map.move_iter() {
if dupes.len() == 1 { continue }
diag.handler().warn(
format!("using multiple versions of crate `{}`", name));
format!("using multiple versions of crate `{}`",
name).as_slice());
for dupe in dupes.move_iter() {
let data = cstore.get_crate_data(dupe);
diag.span_note(data.span, "used here");
@ -161,7 +162,7 @@ fn extract_crate_info(e: &Env, i: &ast::ViewItem) -> Option<CrateInfo> {
Some(id) => id
}
}
None => from_str(ident.get().to_str()).unwrap()
None => from_str(ident.get().to_str().as_slice()).unwrap()
};
Some(CrateInfo {
ident: ident.get().to_strbuf(),
@ -224,7 +225,8 @@ fn visit_item(e: &Env, i: &ast::Item) {
cstore::NativeUnknown
} else {
e.sess.span_err(m.span,
format!("unknown kind: `{}`", k));
format!("unknown kind: `{}`",
k).as_slice());
cstore::NativeUnknown
}
}
@ -243,7 +245,9 @@ fn visit_item(e: &Env, i: &ast::Item) {
}
};
if n.get().is_empty() {
e.sess.span_err(m.span, "#[link(name = \"\")] given with empty name");
e.sess.span_err(m.span,
"#[link(name = \"\")] given with \
empty name");
} else {
e.sess
.cstore
@ -425,7 +429,7 @@ impl<'a> CrateLoader for Loader<'a> {
let message = format!("crate `{}` contains a macro_registrar fn but \
only a version for triple `{}` could be found (need {})",
info.ident, target_triple, driver::host_triple());
self.env.sess.span_err(krate.span, message);
self.env.sess.span_err(krate.span, message.as_slice());
// need to abort now because the syntax expansion
// code will shortly attempt to load and execute
// code from the found library.

View File

@ -248,7 +248,7 @@ fn encode_symbol(ecx: &EncodeContext,
}
None => {
ecx.diag.handler().bug(
format!("encode_symbol: id not found {}", id));
format!("encode_symbol: id not found {}", id).as_slice());
}
}
ebml_w.end_tag();
@ -375,7 +375,7 @@ fn encode_reexported_static_method(ebml_w: &mut Encoder,
ebml_w.start_tag(tag_items_data_item_reexport_name);
ebml_w.wr_str(format!("{}::{}",
exp.name,
token::get_ident(method_ident)));
token::get_ident(method_ident)).as_slice());
ebml_w.end_tag();
ebml_w.end_tag();
}
@ -602,7 +602,7 @@ fn encode_visibility(ebml_w: &mut Encoder, visibility: Visibility) {
Public => 'y',
Inherited => 'i',
};
ebml_w.wr_str(str::from_char(ch));
ebml_w.wr_str(str::from_char(ch).as_slice());
ebml_w.end_tag();
}
@ -848,7 +848,7 @@ fn encode_sized(ebml_w: &mut Encoder, sized: Sized) {
DynSize => 'd',
StaticSize => 's',
};
ebml_w.wr_str(str::from_char(ch));
ebml_w.wr_str(str::from_char(ch).as_slice());
ebml_w.end_tag();
}
@ -1439,7 +1439,10 @@ fn synthesize_crate_attrs(ecx: &EncodeContext,
attr::mk_attr_inner(
attr::mk_name_value_item_str(
InternedString::new("crate_id"),
token::intern_and_get_ident(ecx.link_meta.crateid.to_str())))
token::intern_and_get_ident(ecx.link_meta
.crateid
.to_str()
.as_slice())))
}
let mut attrs = Vec::new();
@ -1882,5 +1885,5 @@ pub fn encoded_ty(tcx: &ty::ctxt, t: ty::t) -> StrBuf {
tcx: tcx,
abbrevs: &RefCell::new(HashMap::new())
}, t);
str::from_utf8_owned(wr.get_ref().to_owned()).unwrap().to_strbuf()
str::from_utf8_owned(Vec::from_slice(wr.get_ref())).unwrap().to_strbuf()
}

View File

@ -137,15 +137,17 @@ impl<'a> Context<'a> {
&Some(ref r) => format!("{} which `{}` depends on",
message, r.ident)
};
self.sess.span_err(self.span, message);
self.sess.span_err(self.span, message.as_slice());
let mismatches = self.rejected_via_triple.iter();
if self.rejected_via_triple.len() > 0 {
self.sess.span_note(self.span, format!("expected triple of {}", self.triple));
self.sess.span_note(self.span,
format!("expected triple of {}",
self.triple).as_slice());
for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() {
self.sess.fileline_note(self.span,
format!("crate `{}` path \\#{}, triple {}: {}",
self.ident, i+1, got, path.display()));
self.ident, i+1, got, path.display()).as_slice());
}
}
if self.rejected_via_hash.len() > 0 {
@ -155,7 +157,7 @@ impl<'a> Context<'a> {
for (i, &CrateMismatch{ ref path, .. }) in mismatches.enumerate() {
self.sess.fileline_note(self.span,
format!("crate `{}` path \\#{}: {}",
self.ident, i+1, path.display()));
self.ident, i+1, path.display()).as_slice());
}
match self.root {
&None => {}
@ -163,7 +165,7 @@ impl<'a> Context<'a> {
for (i, path) in r.paths().iter().enumerate() {
self.sess.fileline_note(self.span,
format!("crate `{}` path \\#{}: {}",
r.ident, i+1, path.display()));
r.ident, i+1, path.display()).as_slice());
}
}
}
@ -198,9 +200,10 @@ impl<'a> Context<'a> {
None => return FileDoesntMatch,
Some(file) => file,
};
if file.starts_with(rlib_prefix) && file.ends_with(".rlib") {
if file.starts_with(rlib_prefix.as_slice()) &&
file.ends_with(".rlib") {
info!("rlib candidate: {}", path.display());
match self.try_match(file, rlib_prefix, ".rlib") {
match self.try_match(file, rlib_prefix.as_slice(), ".rlib") {
Some(hash) => {
info!("rlib accepted, hash: {}", hash);
let slot = candidates.find_or_insert_with(hash, |_| {
@ -215,9 +218,12 @@ impl<'a> Context<'a> {
FileDoesntMatch
}
}
} else if file.starts_with(dylib_prefix) && file.ends_with(dysuffix){
} else if file.starts_with(dylib_prefix.as_slice()) &&
file.ends_with(dysuffix){
info!("dylib candidate: {}", path.display());
match self.try_match(file, dylib_prefix, dysuffix) {
match self.try_match(file,
dylib_prefix.as_slice(),
dysuffix) {
Some(hash) => {
info!("dylib accepted, hash: {}", hash);
let slot = candidates.find_or_insert_with(hash, |_| {
@ -271,18 +277,20 @@ impl<'a> Context<'a> {
_ => {
self.sess.span_err(self.span,
format!("multiple matching crates for `{}`",
self.crate_id.name));
self.crate_id.name).as_slice());
self.sess.note("candidates:");
for lib in libraries.iter() {
match lib.dylib {
Some(ref p) => {
self.sess.note(format!("path: {}", p.display()));
self.sess.note(format!("path: {}",
p.display()).as_slice());
}
None => {}
}
match lib.rlib {
Some(ref p) => {
self.sess.note(format!("path: {}", p.display()));
self.sess.note(format!("path: {}",
p.display()).as_slice());
}
None => {}
}
@ -375,10 +383,13 @@ impl<'a> Context<'a> {
if ret.is_some() {
self.sess.span_err(self.span,
format!("multiple {} candidates for `{}` \
found", flavor, self.crate_id.name));
found",
flavor,
self.crate_id.name).as_slice());
self.sess.span_note(self.span,
format!(r"candidate \#1: {}",
ret.get_ref().display()));
ret.get_ref()
.display()).as_slice());
error = 1;
ret = None;
}
@ -386,7 +397,7 @@ impl<'a> Context<'a> {
error += 1;
self.sess.span_note(self.span,
format!(r"candidate \#{}: {}", error,
lib.display()));
lib.display()).as_slice());
continue
}
*slot = Some(metadata);
@ -450,7 +461,7 @@ impl<'a> Context<'a> {
}
pub fn note_crateid_attr(diag: &SpanHandler, crateid: &CrateId) {
diag.handler().note(format!("crate_id: {}", crateid.to_str()));
diag.handler().note(format!("crate_id: {}", crateid.to_str()).as_slice());
}
impl ArchiveMetadata {
@ -541,7 +552,7 @@ fn get_metadata_section_imp(os: Os, filename: &Path) -> Result<MetadataBlob, Str
let name_len = llvm::LLVMRustGetSectionName(si.llsi, &mut name_buf);
let name = str::raw::from_buf_len(name_buf as *u8, name_len as uint);
debug!("get_metadata_section: name {}", name);
if read_meta_section_name(os) == name {
if read_meta_section_name(os).as_slice() == name.as_slice() {
let cbuf = llvm::LLVMGetSectionContents(si.llsi);
let csz = llvm::LLVMGetSectionSize(si.llsi) as uint;
let mut found =

View File

@ -155,7 +155,10 @@ fn parse_trait_store(st: &mut PState, conv: conv_did) -> ty::TraitStore {
match next(st) {
'~' => ty::UniqTraitStore,
'&' => ty::RegionTraitStore(parse_region(st, conv), parse_mutability(st)),
c => st.tcx.sess.bug(format!("parse_trait_store(): bad input '{}'", c))
c => {
st.tcx.sess.bug(format!("parse_trait_store(): bad input '{}'",
c).as_slice())
}
}
}
@ -449,7 +452,7 @@ fn parse_abi_set(st: &mut PState) -> abi::Abi {
assert_eq!(next(st), '[');
scan(st, |c| c == ']', |bytes| {
let abi_str = str::from_utf8(bytes).unwrap().to_owned();
abi::lookup(abi_str).expect(abi_str)
abi::lookup(abi_str.as_slice()).expect(abi_str)
})
}

View File

@ -1312,7 +1312,8 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext,
match c::astencode_tag::from_uint(tag) {
None => {
xcx.dcx.tcx.sess.bug(
format!("unknown tag found in side tables: {:x}", tag));
format!("unknown tag found in side tables: {:x}",
tag).as_slice());
}
Some(value) => {
let val_doc = entry_doc.get(c::tag_table_val as uint);
@ -1376,7 +1377,8 @@ fn decode_side_tables(xcx: &ExtendedDecodeContext,
}
_ => {
xcx.dcx.tcx.sess.bug(
format!("unknown tag found in side tables: {:x}", tag));
format!("unknown tag found in side tables: {:x}",
tag).as_slice());
}
}
}

View File

@ -243,7 +243,7 @@ impl<'a> CheckLoanCtxt<'a> {
if restr.loan_path != loan2.loan_path { continue; }
let old_pronoun = if new_loan.loan_path == old_loan.loan_path {
"it".to_owned()
"it".to_strbuf()
} else {
format!("`{}`",
self.bccx.loan_path_to_str(&*old_loan.loan_path))
@ -255,7 +255,8 @@ impl<'a> CheckLoanCtxt<'a> {
new_loan.span,
format!("cannot borrow `{}` as mutable \
more than once at a time",
self.bccx.loan_path_to_str(&*new_loan.loan_path)));
self.bccx.loan_path_to_str(
&*new_loan.loan_path)).as_slice());
}
(ty::UniqueImmBorrow, _) => {
@ -264,7 +265,7 @@ impl<'a> CheckLoanCtxt<'a> {
format!("closure requires unique access to `{}` \
but {} is already borrowed",
self.bccx.loan_path_to_str(&*new_loan.loan_path),
old_pronoun));
old_pronoun).as_slice());
}
(_, ty::UniqueImmBorrow) => {
@ -273,7 +274,7 @@ impl<'a> CheckLoanCtxt<'a> {
format!("cannot borrow `{}` as {} because \
previous closure requires unique access",
self.bccx.loan_path_to_str(&*new_loan.loan_path),
new_loan.kind.to_user_str()));
new_loan.kind.to_user_str()).as_slice());
}
(_, _) => {
@ -284,7 +285,7 @@ impl<'a> CheckLoanCtxt<'a> {
self.bccx.loan_path_to_str(&*new_loan.loan_path),
new_loan.kind.to_user_str(),
old_pronoun,
old_loan.kind.to_user_str()));
old_loan.kind.to_user_str()).as_slice());
}
}
@ -293,7 +294,8 @@ impl<'a> CheckLoanCtxt<'a> {
self.bccx.span_note(
span,
format!("borrow occurs due to use of `{}` in closure",
self.bccx.loan_path_to_str(&*new_loan.loan_path)));
self.bccx.loan_path_to_str(
&*new_loan.loan_path)).as_slice());
}
_ => { }
}
@ -303,7 +305,8 @@ impl<'a> CheckLoanCtxt<'a> {
format!("the mutable borrow prevents subsequent \
moves, borrows, or modification of `{0}` \
until the borrow ends",
self.bccx.loan_path_to_str(&*old_loan.loan_path))
self.bccx.loan_path_to_str(
&*old_loan.loan_path))
}
ty::ImmBorrow => {
@ -340,7 +343,7 @@ impl<'a> CheckLoanCtxt<'a> {
self.bccx.span_note(
old_loan.span,
format!("{}; {}", borrow_summary, rule_summary));
format!("{}; {}", borrow_summary, rule_summary).as_slice());
let old_loan_span = self.tcx().map.span(old_loan.kill_scope);
self.bccx.span_end_note(old_loan_span,
@ -428,14 +431,14 @@ impl<'a> CheckLoanCtxt<'a> {
format!("cannot assign to {} {} `{}`",
cmt.mutbl.to_user_str(),
self.bccx.cmt_to_str(&*cmt),
self.bccx.loan_path_to_str(&*lp)));
self.bccx.loan_path_to_str(&*lp)).as_slice());
}
None => {
self.bccx.span_err(
expr.span,
format!("cannot assign to {} {}",
cmt.mutbl.to_user_str(),
self.bccx.cmt_to_str(&*cmt)));
self.bccx.cmt_to_str(&*cmt)).as_slice());
}
}
return;
@ -672,11 +675,11 @@ impl<'a> CheckLoanCtxt<'a> {
self.bccx.span_err(
expr.span,
format!("cannot assign to `{}` because it is borrowed",
self.bccx.loan_path_to_str(loan_path)));
self.bccx.loan_path_to_str(loan_path)).as_slice());
self.bccx.span_note(
loan.span,
format!("borrow of `{}` occurs here",
self.bccx.loan_path_to_str(loan_path)));
self.bccx.loan_path_to_str(loan_path)).as_slice());
}
fn check_move_out_from_expr(&self, expr: &ast::Expr) {
@ -702,11 +705,13 @@ impl<'a> CheckLoanCtxt<'a> {
span,
format!("cannot move out of `{}` \
because it is borrowed",
self.bccx.loan_path_to_str(move_path)));
self.bccx.loan_path_to_str(
move_path)).as_slice());
self.bccx.span_note(
loan_span,
format!("borrow of `{}` occurs here",
self.bccx.loan_path_to_str(&*loan_path)));
self.bccx.loan_path_to_str(
&*loan_path)).as_slice());
}
}
true
@ -745,11 +750,13 @@ impl<'a> CheckLoanCtxt<'a> {
freevar.span,
format!("cannot move `{}` into closure \
because it is borrowed",
this.bccx.loan_path_to_str(move_path)));
this.bccx.loan_path_to_str(
move_path)).as_slice());
this.bccx.span_note(
loan_span,
format!("borrow of `{}` occurs here",
this.bccx.loan_path_to_str(&*loan_path)));
this.bccx.loan_path_to_str(
&*loan_path)).as_slice());
}
}
}

View File

@ -174,8 +174,9 @@ fn check_aliasability(bccx: &BorrowckCtxt,
// static item resides in immutable memory and mutating it would
// cause segfaults.
bccx.tcx.sess.span_err(borrow_span,
format!("borrow of immutable static items with \
unsafe interior is not allowed"));
"borrow of immutable static items \
with unsafe interior is not \
allowed");
Err(())
}
mc::InteriorSafe => {
@ -290,7 +291,8 @@ impl<'a> GatherLoanCtxt<'a> {
ty::ReInfer(..) => {
self.tcx().sess.span_bug(
cmt.span,
format!("invalid borrow lifetime: {:?}", loan_region));
format!("invalid borrow lifetime: {:?}",
loan_region).as_slice());
}
};
debug!("loan_scope = {:?}", loan_scope);

View File

@ -131,7 +131,7 @@ fn report_cannot_move_out_of(bccx: &BorrowckCtxt, move_from: mc::cmt) {
bccx.span_err(
move_from.span,
format!("cannot move out of {}",
bccx.cmt_to_str(&*move_from)));
bccx.cmt_to_str(&*move_from)).as_slice());
}
mc::cat_downcast(ref b) |
@ -143,7 +143,7 @@ fn report_cannot_move_out_of(bccx: &BorrowckCtxt, move_from: mc::cmt) {
move_from.span,
format!("cannot move out of type `{}`, \
which defines the `Drop` trait",
b.ty.user_string(bccx.tcx)));
b.ty.user_string(bccx.tcx)).as_slice());
},
_ => fail!("this path should not cause illegal move")
}
@ -163,10 +163,10 @@ fn note_move_destination(bccx: &BorrowckCtxt,
format!("attempting to move value to here (to prevent the move, \
use `ref {0}` or `ref mut {0}` to capture value by \
reference)",
pat_name));
pat_name).as_slice());
} else {
bccx.span_note(move_to_span,
format!("and here (use `ref {0}` or `ref mut {0}`)",
pat_name));
pat_name).as_slice());
}
}

View File

@ -460,17 +460,17 @@ impl<'a> BorrowckCtxt<'a> {
self.tcx.sess.span_err(
use_span,
format!("{} of possibly uninitialized variable: `{}`",
verb,
self.loan_path_to_str(lp)));
verb,
self.loan_path_to_str(lp)).as_slice());
}
_ => {
let partially = if lp == moved_lp {""} else {"partially "};
self.tcx.sess.span_err(
use_span,
format!("{} of {}moved value: `{}`",
verb,
partially,
self.loan_path_to_str(lp)));
verb,
partially,
self.loan_path_to_str(lp)).as_slice());
}
}
@ -482,25 +482,31 @@ impl<'a> BorrowckCtxt<'a> {
Some(ast_map::NodeExpr(expr)) => {
(ty::expr_ty_adjusted(self.tcx, expr), expr.span)
}
r => self.tcx.sess.bug(format!("MoveExpr({:?}) maps to {:?}, not Expr",
move.id, r))
r => {
self.tcx.sess.bug(format!("MoveExpr({:?}) maps to \
{:?}, not Expr",
move.id,
r).as_slice())
}
};
let suggestion = move_suggestion(self.tcx, expr_ty,
"moved by default (use `copy` to override)");
self.tcx.sess.span_note(
expr_span,
format!("`{}` moved here because it has type `{}`, which is {}",
self.loan_path_to_str(moved_lp),
expr_ty.user_string(self.tcx), suggestion));
self.loan_path_to_str(moved_lp),
expr_ty.user_string(self.tcx),
suggestion).as_slice());
}
move_data::MovePat => {
let pat_ty = ty::node_id_to_type(self.tcx, move.id);
self.tcx.sess.span_note(self.tcx.map.span(move.id),
format!("`{}` moved here because it has type `{}`, \
which is moved by default (use `ref` to override)",
self.loan_path_to_str(moved_lp),
pat_ty.user_string(self.tcx)));
which is moved by default (use `ref` to \
override)",
self.loan_path_to_str(moved_lp),
pat_ty.user_string(self.tcx)).as_slice());
}
move_data::Captured => {
@ -508,8 +514,12 @@ impl<'a> BorrowckCtxt<'a> {
Some(ast_map::NodeExpr(expr)) => {
(ty::expr_ty_adjusted(self.tcx, expr), expr.span)
}
r => self.tcx.sess.bug(format!("Captured({:?}) maps to {:?}, not Expr",
move.id, r))
r => {
self.tcx.sess.bug(format!("Captured({:?}) maps to \
{:?}, not Expr",
move.id,
r).as_slice())
}
};
let suggestion = move_suggestion(self.tcx, expr_ty,
"moved by default (make a copy and \
@ -517,9 +527,10 @@ impl<'a> BorrowckCtxt<'a> {
self.tcx.sess.span_note(
expr_span,
format!("`{}` moved into closure environment here because it \
has type `{}`, which is {}",
self.loan_path_to_str(moved_lp),
expr_ty.user_string(self.tcx), suggestion));
has type `{}`, which is {}",
self.loan_path_to_str(moved_lp),
expr_ty.user_string(self.tcx),
suggestion).as_slice());
}
}
@ -547,10 +558,8 @@ impl<'a> BorrowckCtxt<'a> {
self.tcx.sess.span_err(
span,
format!("re-assignment of immutable variable `{}`",
self.loan_path_to_str(lp)));
self.tcx.sess.span_note(
assign.span,
format!("prior assignment occurs here"));
self.loan_path_to_str(lp)).as_slice());
self.tcx.sess.span_note(assign.span, "prior assignment occurs here");
}
pub fn span_err(&self, s: Span, m: &str) {
@ -657,23 +666,23 @@ impl<'a> BorrowckCtxt<'a> {
self.tcx.sess.span_err(
span,
format!("{} in an aliasable location",
prefix));
prefix).as_slice());
}
mc::AliasableStatic(..) |
mc::AliasableStaticMut(..) => {
self.tcx.sess.span_err(
span,
format!("{} in a static location", prefix));
format!("{} in a static location", prefix).as_slice());
}
mc::AliasableManaged => {
self.tcx.sess.span_err(
span,
format!("{} in a `@` pointer", prefix));
format!("{} in a `@` pointer", prefix).as_slice());
}
mc::AliasableBorrowed => {
self.tcx.sess.span_err(
span,
format!("{} in a `&` reference", prefix));
format!("{} in a `&` reference", prefix).as_slice());
}
}
}
@ -710,12 +719,13 @@ impl<'a> BorrowckCtxt<'a> {
};
note_and_explain_region(
self.tcx,
format!("{} would have to be valid for ", descr),
format!("{} would have to be valid for ",
descr).as_slice(),
loan_scope,
"...");
note_and_explain_region(
self.tcx,
format!("...but {} is only valid for ", descr),
format!("...but {} is only valid for ", descr).as_slice(),
ptr_scope,
"");
}
@ -739,7 +749,7 @@ impl<'a> BorrowckCtxt<'a> {
}
mc::PositionalField(idx) => {
out.push_char('#'); // invent a notation here
out.push_str(idx.to_str());
out.push_str(idx.to_str().as_slice());
}
}
}

View File

@ -508,7 +508,9 @@ impl<'a> CFGBuilder<'a> {
fn add_returning_edge(&mut self,
_from_expr: @ast::Expr,
from_index: CFGIndex) {
let mut data = CFGEdgeData {exiting_scopes: vec!() };
let mut data = CFGEdgeData {
exiting_scopes: vec!(),
};
for &LoopScope { loop_id: id, .. } in self.loop_scopes.iter().rev() {
data.exiting_scopes.push(id);
}
@ -533,13 +535,15 @@ impl<'a> CFGBuilder<'a> {
}
self.tcx.sess.span_bug(
expr.span,
format!("no loop scope for id {:?}", loop_id));
format!("no loop scope for id {:?}",
loop_id).as_slice());
}
r => {
self.tcx.sess.span_bug(
expr.span,
format!("bad entry `{:?}` in def_map for label", r));
format!("bad entry `{:?}` in def_map for label",
r).as_slice());
}
}
}

View File

@ -37,7 +37,8 @@ fn replace_newline_with_backslash_l(s: StrBuf) -> StrBuf {
// \l, not the line that follows; so, add \l at end of string
// if not already present, ensuring last line gets left-aligned
// as well.
let mut last_two : Vec<_> = s.chars().rev().take(2).collect();
let mut last_two: Vec<_> =
s.as_slice().chars().rev().take(2).collect();
last_two.reverse();
if last_two.as_slice() != ['\\', 'l'] {
s = s.append("\\l");
@ -82,7 +83,9 @@ impl<'a> dot::Labeller<'a, Node<'a>, Edge<'a>> for LabelledCFG<'a> {
let s = self.ast_map.node_to_str(node_id);
// left-aligns the lines
let s = replace_newline_with_backslash_l(s);
label = label.append(format!("exiting scope_{} {}", i, s.as_slice()));
label = label.append(format!("exiting scope_{} {}",
i,
s.as_slice()).as_slice());
}
dot::EscStr(label.into_maybe_owned())
}

View File

@ -107,7 +107,7 @@ fn check_expr(v: &mut CheckCrateVisitor, e: &Expr, is_const: bool) {
.span_err(e.span,
format!("can not cast to `{}` in a constant \
expression",
ppaux::ty_to_str(v.tcx, ety).as_slice()))
ppaux::ty_to_str(v.tcx, ety)).as_slice())
}
}
ExprPath(ref pth) => {

View File

@ -57,10 +57,14 @@ impl<'a> CheckLoopVisitor<'a> {
match cx {
Loop => {}
Closure => {
self.sess.span_err(span, format!("`{}` inside of a closure", name));
self.sess.span_err(span,
format!("`{}` inside of a closure",
name).as_slice());
}
Normal => {
self.sess.span_err(span, format!("`{}` outside of loop", name));
self.sess.span_err(span,
format!("`{}` outside of loop",
name).as_slice());
}
}
}

View File

@ -74,7 +74,7 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &Expr) {
// We know the type is inhabited, so this must be wrong
cx.tcx.sess.span_err(ex.span, format!("non-exhaustive patterns: \
type {} is non-empty",
ty_to_str(cx.tcx, pat_ty)));
ty_to_str(cx.tcx, pat_ty)).as_slice());
}
// If the type *is* empty, it's vacuously exhaustive
return;
@ -164,8 +164,8 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: Vec<@Pat> ) {
match ty::get(ty).sty {
ty::ty_bool => {
match *ctor {
val(const_bool(true)) => Some("true".to_owned()),
val(const_bool(false)) => Some("false".to_owned()),
val(const_bool(true)) => Some("true".to_strbuf()),
val(const_bool(false)) => Some("false".to_strbuf()),
_ => None
}
}
@ -177,7 +177,11 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: Vec<@Pat> ) {
let variants = ty::enum_variants(cx.tcx, id);
match variants.iter().find(|v| v.id == vid) {
Some(v) => Some(token::get_ident(v.name).get().to_str()),
Some(v) => {
Some(token::get_ident(v.name).get()
.to_str()
.into_strbuf())
}
None => {
fail!("check_exhaustive: bad variant in ctor")
}
@ -185,7 +189,9 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: Vec<@Pat> ) {
}
ty::ty_vec(..) | ty::ty_rptr(..) => {
match *ctor {
vec(n) => Some(format!("vectors of length {}", n)),
vec(n) => {
Some(format_strbuf!("vectors of length {}", n))
}
_ => None
}
}
@ -193,11 +199,11 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: Vec<@Pat> ) {
}
}
};
let msg = "non-exhaustive patterns".to_owned() + match ext {
Some(ref s) => format!(": {} not covered", *s),
None => "".to_owned()
};
cx.tcx.sess.span_err(sp, msg);
let msg = format_strbuf!("non-exhaustive patterns{}", match ext {
Some(ref s) => format_strbuf!(": {} not covered", *s),
None => "".to_strbuf()
});
cx.tcx.sess.span_err(sp, msg.as_slice());
}
type matrix = Vec<Vec<@Pat> > ;
@ -739,7 +745,8 @@ fn specialize(cx: &MatchCheckCtxt,
pat_span,
format!("struct pattern resolved to {}, \
not a struct",
ty_to_str(cx.tcx, left_ty)));
ty_to_str(cx.tcx,
left_ty)).as_slice());
}
}
let args = class_fields.iter().map(|class_field| {
@ -980,9 +987,10 @@ fn check_legality_of_move_bindings(cx: &MatchCheckCtxt,
_ => {
cx.tcx.sess.span_bug(
p.span,
format!("binding pattern {} is \
not an identifier: {:?}",
p.id, p.node));
format!("binding pattern {} is not an \
identifier: {:?}",
p.id,
p.node).as_slice());
}
}
}

View File

@ -436,10 +436,11 @@ pub fn eval_const_expr_partial<T: ty::ExprTyProvider>(tcx: &T, e: &Expr)
// (#5900). Fall back to doing a limited lookup to get past it.
let ety = ty::expr_ty_opt(tcx.ty_ctxt(), e)
.or_else(|| astconv::ast_ty_to_prim_ty(tcx.ty_ctxt(), target_ty))
.unwrap_or_else(|| tcx.ty_ctxt().sess.span_fatal(
target_ty.span,
format!("target type not found for const cast")
));
.unwrap_or_else(|| {
tcx.ty_ctxt().sess.span_fatal(target_ty.span,
"target type not found for \
const cast")
});
let base = eval_const_expr_partial(tcx, base);
match base {

View File

@ -102,14 +102,14 @@ impl<'a, O:DataFlowOperator> pprust::PpAnn for DataFlowContext<'a, O> {
let gens_str = if gens.iter().any(|&u| u != 0) {
format!(" gen: {}", bits_to_str(gens))
} else {
"".to_owned()
"".to_strbuf()
};
let kills = self.kills.slice(start, end);
let kills_str = if kills.iter().any(|&u| u != 0) {
format!(" kill: {}", bits_to_str(kills))
} else {
"".to_owned()
"".to_strbuf()
};
try!(ps.synth_comment(format_strbuf!("id {}: {}{}{}",
@ -652,8 +652,9 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> {
tcx.sess.span_bug(
from_expr.span,
format!("pop_scopes(from_expr={}, to_scope={:?}) \
to_scope does not enclose from_expr",
from_expr.repr(tcx), to_scope.loop_id));
to_scope does not enclose from_expr",
from_expr.repr(tcx),
to_scope.loop_id).as_slice());
}
}
}
@ -765,7 +766,8 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> {
None => {
self.tcx().sess.span_bug(
expr.span,
format!("no loop scope for id {:?}", loop_id));
format!("no loop scope for id {:?}",
loop_id).as_slice());
}
}
}
@ -773,7 +775,8 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> {
r => {
self.tcx().sess.span_bug(
expr.span,
format!("bad entry `{:?}` in def_map for label", r));
format!("bad entry `{:?}` in def_map for label",
r).as_slice());
}
}
}
@ -789,7 +792,9 @@ impl<'a, 'b, O:DataFlowOperator> PropagationContext<'a, 'b, O> {
fn reset(&mut self, bits: &mut [uint]) {
let e = if self.dfcx.oper.initial_value() {uint::MAX} else {0};
for b in bits.mut_iter() { *b = e; }
for b in bits.mut_iter() {
*b = e;
}
}
fn add_to_entry_set(&mut self, id: ast::NodeId, pred_bits: &[uint]) {
@ -841,7 +846,7 @@ fn bits_to_str(words: &[uint]) -> StrBuf {
let mut v = word;
for _ in range(0u, uint::BYTES) {
result.push_char(sep);
result.push_str(format!("{:02x}", v & 0xFF));
result.push_str(format!("{:02x}", v & 0xFF).as_slice());
v >>= 8;
sep = '-';
}

View File

@ -118,7 +118,7 @@ fn calculate_type(sess: &session::Session,
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(format!("dependency `{}` not found in rlib format",
data.name));
data.name).as_slice());
});
return Vec::new();
}
@ -187,7 +187,7 @@ fn calculate_type(sess: &session::Session,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}));
}).as_slice());
}
}
}
@ -211,7 +211,8 @@ fn add_library(sess: &session::Session,
if link2 != link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(format!("cannot satisfy dependencies so `{}` only \
shows up once", data.name));
shows up once",
data.name).as_slice());
sess.note("having upstream crates all available in one format \
will likely make this go away");
}

View File

@ -48,8 +48,9 @@ impl<'a> EffectCheckVisitor<'a> {
SafeContext => {
// Report an error.
self.tcx.sess.span_err(span,
format!("{} requires unsafe function or block",
description))
format!("{} requires unsafe function or \
block",
description).as_slice())
}
UnsafeBlock(block_id) => {
// OK, but record this.

View File

@ -422,7 +422,7 @@ impl<'d,'t,TYPER:mc::Typer> ExprUseVisitor<'d,'t,TYPER> {
self.tcx().sess.span_bug(
callee.span,
format!("unxpected callee type {}",
callee_ty.repr(self.tcx())));
callee_ty.repr(self.tcx())).as_slice());
}
}
}
@ -448,9 +448,7 @@ impl<'d,'t,TYPER:mc::Typer> ExprUseVisitor<'d,'t,TYPER> {
}
ast::StmtMac(..) => {
self.tcx().sess.span_bug(
stmt.span,
format!("unexpanded stmt macro"));
self.tcx().sess.span_bug(stmt.span, "unexpanded stmt macro");
}
}
}
@ -518,7 +516,7 @@ impl<'d,'t,TYPER:mc::Typer> ExprUseVisitor<'d,'t,TYPER> {
_ => {
self.tcx().sess.span_bug(
with_expr.span,
format!("with expression doesn't evaluate to a struct"));
"with expression doesn't evaluate to a struct");
}
};
@ -601,7 +599,7 @@ impl<'d,'t,TYPER:mc::Typer> ExprUseVisitor<'d,'t,TYPER> {
ty::ty_rptr(r, ref m) => (m.mutbl, r),
_ => self.tcx().sess.span_bug(expr.span,
format!("bad overloaded deref type {}",
method_ty.repr(self.tcx())))
method_ty.repr(self.tcx())).as_slice())
};
let bk = ty::BorrowKind::from_mutbl(m);
self.delegate.borrow(expr.id, expr.span, cmt,

View File

@ -127,10 +127,12 @@ fn check_impl_of_trait(cx: &mut Context, it: &Item, trait_ref: &TraitRef, self_t
check_builtin_bounds(cx, self_ty, trait_def.bounds, |missing| {
cx.tcx.sess.span_err(self_type.span,
format!("the type `{}', which does not fulfill `{}`, cannot implement this \
trait", ty_to_str(cx.tcx, self_ty), missing.user_string(cx.tcx)));
trait",
ty_to_str(cx.tcx, self_ty),
missing.user_string(cx.tcx)).as_slice());
cx.tcx.sess.span_note(self_type.span,
format!("types implementing this trait must fulfill `{}`",
trait_def.bounds.user_string(cx.tcx)));
trait_def.bounds.user_string(cx.tcx)).as_slice());
});
// If this is a destructor, check kinds.
@ -210,8 +212,9 @@ fn with_appropriate_checker(cx: &Context,
b(check_for_bare)
}
ref s => {
cx.tcx.sess.bug(
format!("expect fn type in kind checker, not {:?}", s));
cx.tcx.sess.bug(format!("expect fn type in kind checker, not \
{:?}",
s).as_slice());
}
}
}
@ -390,9 +393,9 @@ pub fn check_typaram_bounds(cx: &Context,
cx.tcx.sess.span_err(
sp,
format!("instantiating a type parameter with an incompatible type \
`{}`, which does not fulfill `{}`",
ty_to_str(cx.tcx, ty),
missing.user_string(cx.tcx)));
`{}`, which does not fulfill `{}`",
ty_to_str(cx.tcx, ty),
missing.user_string(cx.tcx)).as_slice());
});
}
@ -403,19 +406,26 @@ pub fn check_freevar_bounds(cx: &Context, sp: Span, ty: ty::t,
// Will be Some if the freevar is implicitly borrowed (stack closure).
// Emit a less mysterious error message in this case.
match referenced_ty {
Some(rty) => cx.tcx.sess.span_err(sp,
format!("cannot implicitly borrow variable of type `{}` in a bounded \
stack closure (implicit reference does not fulfill `{}`)",
ty_to_str(cx.tcx, rty), missing.user_string(cx.tcx))),
None => cx.tcx.sess.span_err(sp,
Some(rty) => {
cx.tcx.sess.span_err(sp,
format!("cannot implicitly borrow variable of type `{}` in a \
bounded stack closure (implicit reference does not \
fulfill `{}`)",
ty_to_str(cx.tcx, rty),
missing.user_string(cx.tcx)).as_slice())
}
None => {
cx.tcx.sess.span_err(sp,
format!("cannot capture variable of type `{}`, which does \
not fulfill `{}`, in a bounded closure",
ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx))),
not fulfill `{}`, in a bounded closure",
ty_to_str(cx.tcx, ty),
missing.user_string(cx.tcx)).as_slice())
}
}
cx.tcx.sess.span_note(
sp,
format!("this closure's environment must satisfy `{}`",
bounds.user_string(cx.tcx)));
bounds.user_string(cx.tcx)).as_slice());
});
}
@ -424,9 +434,9 @@ pub fn check_trait_cast_bounds(cx: &Context, sp: Span, ty: ty::t,
check_builtin_bounds(cx, ty, bounds, |missing| {
cx.tcx.sess.span_err(sp,
format!("cannot pack type `{}`, which does not fulfill \
`{}`, as a trait bounded by {}",
ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx),
bounds.user_string(cx.tcx)));
`{}`, as a trait bounded by {}",
ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx),
bounds.user_string(cx.tcx)).as_slice());
});
}
@ -436,9 +446,10 @@ fn check_copy(cx: &Context, ty: ty::t, sp: Span, reason: &str) {
ty::type_contents(cx.tcx, ty).to_str());
if ty::type_moves_by_default(cx.tcx, ty) {
cx.tcx.sess.span_err(
sp, format!("copying a value of non-copyable type `{}`",
ty_to_str(cx.tcx, ty)));
cx.tcx.sess.span_note(sp, format!("{}", reason));
sp,
format!("copying a value of non-copyable type `{}`",
ty_to_str(cx.tcx, ty)).as_slice());
cx.tcx.sess.span_note(sp, format!("{}", reason).as_slice());
}
}
@ -448,7 +459,8 @@ pub fn check_static(tcx: &ty::ctxt, ty: ty::t, sp: Span) -> bool {
ty::ty_param(..) => {
tcx.sess.span_err(sp,
format!("value may contain references; \
add `'static` bound to `{}`", ty_to_str(tcx, ty)));
add `'static` bound to `{}`",
ty_to_str(tcx, ty)).as_slice());
}
_ => {
tcx.sess.span_err(sp, "value may contain references");
@ -564,8 +576,11 @@ pub fn check_cast_for_escaping_regions(
// Ensure that `ty` has a statically known size (i.e., it has the `Sized` bound).
fn check_sized(tcx: &ty::ctxt, ty: ty::t, name: StrBuf, sp: Span) {
if !ty::type_is_sized(tcx, ty) {
tcx.sess.span_err(sp, format!("variable `{}` has dynamically sized type `{}`",
name, ty_to_str(tcx, ty)));
tcx.sess.span_err(sp,
format!("variable `{}` has dynamically sized type \
`{}`",
name,
ty_to_str(tcx, ty)).as_slice());
}
}

View File

@ -152,7 +152,8 @@ impl<'a> LanguageItemCollector<'a> {
match self.items.items.get(item_index) {
&Some(original_def_id) if original_def_id != item_def_id => {
self.session.err(format!("duplicate entry for `{}`",
LanguageItems::item_name(item_index)));
LanguageItems::item_name(
item_index)).as_slice());
}
&Some(_) | &None => {
// OK.

View File

@ -506,8 +506,10 @@ impl<'a> Context<'a> {
let mut note = None;
let msg = match src {
Default => {
format!("{}, \\#[{}({})] on by default", msg,
level_to_str(level), self.lint_to_str(lint))
format_strbuf!("{}, \\#[{}({})] on by default",
msg,
level_to_str(level),
self.lint_to_str(lint))
},
CommandLine => {
format!("{} [-{} {}]", msg,
@ -522,8 +524,8 @@ impl<'a> Context<'a> {
}
};
match level {
Warn => { self.tcx.sess.span_warn(span, msg); }
Deny | Forbid => { self.tcx.sess.span_err(span, msg); }
Warn => self.tcx.sess.span_warn(span, msg.as_slice()),
Deny | Forbid => self.tcx.sess.span_err(span, msg.as_slice()),
Allow => fail!(),
}
@ -552,7 +554,7 @@ impl<'a> Context<'a> {
UnrecognizedLint,
meta.span,
format!("unknown `{}` attribute: `{}`",
level_to_str(level), lintname));
level_to_str(level), lintname).as_slice());
}
Some(lint) => {
let lint = lint.lint;
@ -560,8 +562,9 @@ impl<'a> Context<'a> {
if now == Forbid && level != Forbid {
self.tcx.sess.span_err(meta.span,
format!("{}({}) overruled by outer forbid({})",
level_to_str(level),
lintname, lintname));
level_to_str(level),
lintname,
lintname).as_slice());
} else if now != level {
let src = self.get_source(lint);
self.lint_stack.push((lint, now, src));
@ -965,13 +968,13 @@ fn check_heap_type(cx: &Context, span: Span, ty: ty::t) {
if n_uniq > 0 && lint != ManagedHeapMemory {
let s = ty_to_str(cx.tcx, ty);
let m = format!("type uses owned (Box type) pointers: {}", s);
cx.span_lint(lint, span, m);
cx.span_lint(lint, span, m.as_slice());
}
if n_box > 0 && lint != OwnedHeapMemory {
let s = ty_to_str(cx.tcx, ty);
let m = format!("type uses managed (@ type) pointers: {}", s);
cx.span_lint(lint, span, m);
cx.span_lint(lint, span, m.as_slice());
}
}
}
@ -1122,7 +1125,8 @@ fn check_attrs_usage(cx: &Context, attrs: &[ast::Attribute]) {
for &(obs_attr, obs_alter) in obsolete_attrs.iter() {
if name.equiv(&obs_attr) {
cx.span_lint(AttributeUsage, attr.span,
format!("obsolete attribute: {:s}", obs_alter));
format!("obsolete attribute: {:s}",
obs_alter).as_slice());
return;
}
}
@ -1233,7 +1237,7 @@ fn check_item_non_camel_case_types(cx: &Context, it: &ast::Item) {
cx.span_lint(
NonCamelCaseTypes, span,
format!("{} `{}` should have a camel case identifier",
sort, token::get_ident(ident)));
sort, token::get_ident(ident)).as_slice());
}
}
@ -1331,7 +1335,8 @@ fn check_unnecessary_parens_core(cx: &Context, value: &ast::Expr, msg: &str) {
match value.node {
ast::ExprParen(_) => {
cx.span_lint(UnnecessaryParens, value.span,
format!("unnecessary parentheses around {}", msg))
format!("unnecessary parentheses around {}",
msg).as_slice())
}
_ => {}
}
@ -1506,8 +1511,10 @@ fn check_missing_doc_attrs(cx: &Context,
}
});
if !has_doc {
cx.span_lint(MissingDoc, sp,
format!("missing documentation for {}", desc));
cx.span_lint(MissingDoc,
sp,
format!("missing documentation for {}",
desc).as_slice());
}
}
@ -1675,7 +1682,7 @@ fn check_stability(cx: &Context, e: &ast::Expr) {
_ => format!("use of {} item", label)
};
cx.span_lint(lint, e.span, msg);
cx.span_lint(lint, e.span, msg.as_slice());
}
impl<'a> Visitor<()> for Context<'a> {
@ -1906,8 +1913,11 @@ pub fn check_crate(tcx: &ty::ctxt,
// in the iteration code.
for (id, v) in tcx.sess.lints.borrow().iter() {
for &(lint, span, ref msg) in v.iter() {
tcx.sess.span_bug(span, format!("unprocessed lint {:?} at {}: {}",
lint, tcx.map.node_to_str(*id), *msg))
tcx.sess.span_bug(span,
format!("unprocessed lint {:?} at {}: {}",
lint,
tcx.map.node_to_str(*id),
*msg).as_slice())
}
}

View File

@ -317,7 +317,7 @@ impl<'a> IrMaps<'a> {
self.tcx
.sess
.span_bug(span, format!("no variable registered for id {}",
node_id));
node_id).as_slice());
}
}
}
@ -606,8 +606,9 @@ impl<'a> Liveness<'a> {
// code have to agree about which AST nodes are worth
// creating liveness nodes for.
self.ir.tcx.sess.span_bug(
span, format!("no live node registered for node {}",
node_id));
span,
format!("no live node registered for node {}",
node_id).as_slice());
}
}
}

View File

@ -224,7 +224,7 @@ pub fn deref_kind(tcx: &ty::ctxt, t: ty::t) -> deref_kind {
None => {
tcx.sess.bug(
format!("deref_cat() invoked on non-derefable type {}",
ty_to_str(tcx, t)));
ty_to_str(tcx, t)).as_slice());
}
}
}
@ -578,7 +578,8 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> {
self.tcx().sess.span_bug(
span,
format!("Upvar of non-closure {} - {}",
fn_node_id, ty.repr(self.tcx())));
fn_node_id,
ty.repr(self.tcx())).as_slice());
}
}
}
@ -727,7 +728,7 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> {
self.tcx().sess.span_bug(
node.span(),
format!("Explicit deref of non-derefable type: {}",
base_cmt.ty.repr(self.tcx())));
base_cmt.ty.repr(self.tcx())).as_slice());
}
}
}
@ -800,7 +801,7 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> {
self.tcx().sess.span_bug(
elt.span(),
format!("Explicit index of non-index type `{}`",
base_cmt.ty.repr(self.tcx())));
base_cmt.ty.repr(self.tcx())).as_slice());
}
};
@ -884,9 +885,8 @@ impl<'t,TYPER:Typer> MemCategorizationContext<'t,TYPER> {
},
_ => {
tcx.sess.span_bug(
pat.span,
format!("Type of slice pattern is not a slice"));
tcx.sess.span_bug(pat.span,
"type of slice pattern is not a slice");
}
}
}

View File

@ -632,7 +632,7 @@ impl<'a> PrivacyVisitor<'a> {
UnnamedField(idx) => format!("field \\#{} of {} is private",
idx + 1, struct_desc),
};
self.tcx.sess.span_err(span, msg);
self.tcx.sess.span_err(span, msg.as_slice());
}
// Given the ID of a method, checks to ensure it's in scope.
@ -647,7 +647,8 @@ impl<'a> PrivacyVisitor<'a> {
self.report_error(self.ensure_public(span,
method_id,
None,
format!("method `{}`", string)));
format!("method `{}`",
string).as_slice()));
}
// Checks that a path is in scope.
@ -661,8 +662,12 @@ impl<'a> PrivacyVisitor<'a> {
.unwrap()
.identifier);
let origdid = def_id_of_def(orig_def);
self.ensure_public(span, def, Some(origdid),
format!("{} `{}`", tyname, name))
self.ensure_public(span,
def,
Some(origdid),
format!("{} `{}`",
tyname,
name).as_slice())
};
match *self.last_private_map.get(&path_id) {

View File

@ -234,7 +234,7 @@ impl<'a> ReachableContext<'a> {
None => {
self.tcx.sess.bug(format!("found unmapped ID in worklist: \
{}",
search_item))
search_item).as_slice())
}
}
}
@ -324,9 +324,12 @@ impl<'a> ReachableContext<'a> {
ast_map::NodeVariant(_) |
ast_map::NodeStructCtor(_) => {}
_ => {
self.tcx.sess.bug(format!("found unexpected thingy in \
worklist: {}",
self.tcx.map.node_to_str(search_item)))
self.tcx
.sess
.bug(format!("found unexpected thingy in worklist: {}",
self.tcx
.map
.node_to_str(search_item)).as_slice())
}
}
}

View File

@ -1085,14 +1085,14 @@ impl<'a> Resolver<'a> {
self.resolve_error(sp,
format!("duplicate definition of {} `{}`",
namespace_error_to_str(duplicate_type),
token::get_ident(name)));
token::get_ident(name)).as_slice());
{
let r = child.span_for_namespace(ns);
for sp in r.iter() {
self.session.span_note(*sp,
format!("first definition of {} `{}` here",
namespace_error_to_str(duplicate_type),
token::get_ident(name)));
token::get_ident(name)).as_slice());
}
}
}
@ -2054,7 +2054,7 @@ impl<'a> Resolver<'a> {
import_directive.module_path
.as_slice(),
import_directive.subclass));
self.resolve_error(import_directive.span, msg);
self.resolve_error(import_directive.span, msg.as_slice());
}
Indeterminate => {
// Bail out. We'll come around next time.
@ -2427,7 +2427,7 @@ impl<'a> Resolver<'a> {
`{}` in `{}`",
token::get_ident(source),
self.module_to_str(&*containing_module));
self.resolve_error(directive.span, msg);
self.resolve_error(directive.span, msg.as_slice());
return Failed;
}
let value_used_public = value_used_reexport || value_used_public;
@ -2651,14 +2651,17 @@ impl<'a> Resolver<'a> {
expn_info: span.expn_info,
};
self.resolve_error(span,
format!("unresolved import. maybe \
format!("unresolved import. maybe \
a missing `extern crate \
{}`?",
segment_name));
segment_name).as_slice());
return Failed;
}
self.resolve_error(span, format!("unresolved import: could not find `{}` in \
`{}`.", segment_name, module_name));
self.resolve_error(span,
format!("unresolved import: could not \
find `{}` in `{}`.",
segment_name,
module_name).as_slice());
return Failed;
}
Indeterminate => {
@ -2675,8 +2678,11 @@ impl<'a> Resolver<'a> {
match type_def.module_def {
None => {
// Not a module.
self.resolve_error(span, format!("not a module `{}`",
token::get_ident(name)));
self.resolve_error(
span,
format!("not a module `{}`",
token::get_ident(name))
.as_slice());
return Failed;
}
Some(ref module_def) => {
@ -2717,9 +2723,10 @@ impl<'a> Resolver<'a> {
}
None => {
// There are no type bindings at all.
self.resolve_error(span,
format!("not a module `{}`",
token::get_ident(name)));
self.resolve_error(
span,
format!("not a module `{}`",
token::get_ident(name)).as_slice());
return Failed;
}
}
@ -2764,16 +2771,15 @@ impl<'a> Resolver<'a> {
let mpath = self.idents_to_str(module_path);
match mpath.as_slice().rfind(':') {
Some(idx) => {
self.resolve_error(span,
format!("unresolved import: could \
not find `{}` in `{}`",
// idx +- 1 to account for
// the colons on either
// side
mpath.as_slice()
.slice_from(idx + 1),
mpath.as_slice()
.slice_to(idx - 1)));
self.resolve_error(
span,
format!("unresolved import: could not find `{}` \
in `{}`",
// idx +- 1 to account for the colons on \
// either side
mpath.as_slice().slice_from(idx + 1),
mpath.as_slice()
.slice_to(idx - 1)).as_slice());
},
None => (),
};
@ -3200,7 +3206,7 @@ impl<'a> Resolver<'a> {
} else {
let err = format!("unresolved import (maybe you meant `{}::*`?)",
sn.as_slice().slice(0, sn.len()));
self.resolve_error(imports.get(index).span, err);
self.resolve_error(imports.get(index).span, err.as_slice());
}
}
@ -3870,7 +3876,7 @@ impl<'a> Resolver<'a> {
};
let msg = format!("attempt to {} a nonexistent trait `{}`", usage_str, path_str);
self.resolve_error(trait_reference.path.span, msg);
self.resolve_error(trait_reference.path.span, msg.as_slice());
}
Some(def) => {
debug!("(resolving trait) found trait def: {:?}", def);
@ -4071,7 +4077,7 @@ impl<'a> Resolver<'a> {
format!("variable `{}` from pattern \\#1 is \
not bound in pattern \\#{}",
token::get_name(key),
i + 1));
i + 1).as_slice());
}
Some(binding_i) => {
if binding_0.binding_mode != binding_i.binding_mode {
@ -4080,7 +4086,7 @@ impl<'a> Resolver<'a> {
format!("variable `{}` is bound with different \
mode in pattern \\#{} than in pattern \\#1",
token::get_name(key),
i + 1));
i + 1).as_slice());
}
}
}
@ -4093,7 +4099,7 @@ impl<'a> Resolver<'a> {
format!("variable `{}` from pattern \\#{} is \
not bound in pattern \\#1",
token::get_name(key),
i + 1));
i + 1).as_slice());
}
}
}
@ -4220,7 +4226,7 @@ impl<'a> Resolver<'a> {
None => {
let msg = format!("use of undeclared type name `{}`",
self.path_idents_to_str(path));
self.resolve_error(ty.span, msg);
self.resolve_error(ty.span, msg.as_slice());
}
}
@ -4285,12 +4291,12 @@ impl<'a> Resolver<'a> {
self.record_def(pattern.id, (def, lp));
}
FoundStructOrEnumVariant(..) => {
self.resolve_error(pattern.span,
format!("declaration of `{}` \
shadows an enum \
variant or unit-like \
struct in scope",
token::get_name(renamed)));
self.resolve_error(
pattern.span,
format!("declaration of `{}` shadows an enum \
variant or unit-like struct in \
scope",
token::get_name(renamed)).as_slice());
}
FoundConst(def, lp) if mode == RefutableMode => {
debug!("(resolving pattern) resolving `{}` to \
@ -4359,9 +4365,10 @@ impl<'a> Resolver<'a> {
// in the same disjunct, which is an
// error
self.resolve_error(pattern.span,
format!("identifier `{}` is bound more \
than once in the same pattern",
path_to_str(path)));
format!("identifier `{}` is bound \
more than once in the same \
pattern",
path_to_str(path)).as_slice());
}
// Not bound in the same pattern: do nothing
}
@ -4406,8 +4413,11 @@ impl<'a> Resolver<'a> {
self.resolve_error(
path.span,
format!("`{}` is not an enum variant or constant",
token::get_ident(
path.segments.last().unwrap().identifier)))
token::get_ident(
path.segments
.last()
.unwrap()
.identifier)).as_slice())
}
None => {
self.resolve_error(path.span,
@ -4435,16 +4445,20 @@ impl<'a> Resolver<'a> {
Some(_) => {
self.resolve_error(path.span,
format!("`{}` is not an enum variant, struct or const",
token::get_ident(path.segments
.last().unwrap()
.identifier)));
token::get_ident(
path.segments
.last()
.unwrap()
.identifier)).as_slice());
}
None => {
self.resolve_error(path.span,
format!("unresolved enum variant, struct or const `{}`",
token::get_ident(path.segments
.last().unwrap()
.identifier)));
token::get_ident(
path.segments
.last()
.unwrap()
.identifier)).as_slice());
}
}
@ -4485,7 +4499,7 @@ impl<'a> Resolver<'a> {
def: {:?}", result);
let msg = format!("`{}` does not name a structure",
self.path_idents_to_str(path));
self.resolve_error(path.span, msg);
self.resolve_error(path.span, msg.as_slice());
}
}
}
@ -4705,7 +4719,7 @@ impl<'a> Resolver<'a> {
Failed => {
let msg = format!("use of undeclared module `{}`",
self.idents_to_str(module_path_idents.as_slice()));
self.resolve_error(path.span, msg);
self.resolve_error(path.span, msg.as_slice());
return None;
}
@ -4776,7 +4790,7 @@ impl<'a> Resolver<'a> {
Failed => {
let msg = format!("use of undeclared module `::{}`",
self.idents_to_str(module_path_idents.as_slice()));
self.resolve_error(path.span, msg);
self.resolve_error(path.span, msg.as_slice());
return None;
}
@ -5096,12 +5110,12 @@ impl<'a> Resolver<'a> {
format!("`{}` is a structure name, but \
this expression \
uses it like a function name",
wrong_name));
wrong_name).as_slice());
self.session.span_note(expr.span,
format!("Did you mean to write: \
`{} \\{ /* fields */ \\}`?",
wrong_name));
wrong_name).as_slice());
}
_ => {
@ -5119,10 +5133,11 @@ impl<'a> Resolver<'a> {
if method_scope && token::get_name(self.self_ident.name).get()
== wrong_name.as_slice() {
self.resolve_error(expr.span,
format!("`self` is not available in a \
static method. Maybe a `self` \
argument is missing?"));
self.resolve_error(
expr.span,
"`self` is not available \
in a static method. Maybe a \
`self` argument is missing?");
} else {
let name = path_to_ident(path).name;
let mut msg = match self.find_fallback_in_self_type(name) {
@ -5130,7 +5145,7 @@ impl<'a> Resolver<'a> {
// limit search to 5 to reduce the number
// of stupid suggestions
self.find_best_match_for_name(wrong_name.as_slice(), 5)
.map_or("".into_owned(),
.map_or("".to_strbuf(),
|x| format!("`{}`", x))
}
Field =>
@ -5147,8 +5162,11 @@ impl<'a> Resolver<'a> {
msg = format!(" Did you mean {}?", msg)
}
self.resolve_error(expr.span, format!("unresolved name `{}`.{}",
wrong_name, msg));
self.resolve_error(
expr.span,
format!("unresolved name `{}`.{}",
wrong_name,
msg).as_slice());
}
}
}
@ -5182,7 +5200,7 @@ impl<'a> Resolver<'a> {
def: {:?}", result);
let msg = format!("`{}` does not name a structure",
self.path_idents_to_str(path));
self.resolve_error(path.span, msg);
self.resolve_error(path.span, msg.as_slice());
}
}
@ -5211,10 +5229,12 @@ impl<'a> Resolver<'a> {
let renamed = mtwt::resolve(label);
match self.search_ribs(self.label_ribs.borrow().as_slice(),
renamed, expr.span) {
None =>
self.resolve_error(expr.span,
format!("use of undeclared label `{}`",
token::get_ident(label))),
None => {
self.resolve_error(
expr.span,
format!("use of undeclared label `{}`",
token::get_ident(label)).as_slice())
}
Some(DlDef(def @ DefLabel(_))) => {
// Since this def is a label, it is never read.
self.record_def(expr.id, (def, LastMod(AllPublic)))
@ -5343,8 +5363,12 @@ impl<'a> Resolver<'a> {
// times, so here is a sanity check it at least comes to
// the same conclusion! - nmatsakis
if def != *old_value {
self.session.bug(format!("node_id {:?} resolved first to {:?} \
and then {:?}", node_id, *old_value, def));
self.session
.bug(format!("node_id {:?} resolved first to {:?} and \
then {:?}",
node_id,
*old_value,
def).as_slice());
}
});
}
@ -5356,10 +5380,10 @@ impl<'a> Resolver<'a> {
match pat_binding_mode {
BindByValue(_) => {}
BindByRef(..) => {
self.resolve_error(
pat.span,
format!("cannot use `ref` binding mode with {}",
descr));
self.resolve_error(pat.span,
format!("cannot use `ref` binding mode \
with {}",
descr).as_slice());
}
}
}

View File

@ -341,7 +341,7 @@ impl<'a> LifetimeContext<'a> {
self.sess.span_err(
lifetime_ref.span,
format!("use of undeclared lifetime name `'{}`",
token::get_name(lifetime_ref.name)));
token::get_name(lifetime_ref.name)).as_slice());
}
fn check_lifetime_names(&self, lifetimes: &Vec<ast::Lifetime>) {
@ -354,7 +354,7 @@ impl<'a> LifetimeContext<'a> {
self.sess.span_err(
lifetime.span,
format!("illegal lifetime parameter name: `{}`",
token::get_name(lifetime.name)));
token::get_name(lifetime.name)).as_slice());
}
}
@ -366,7 +366,7 @@ impl<'a> LifetimeContext<'a> {
lifetime_j.span,
format!("lifetime name `'{}` declared twice in \
the same scope",
token::get_name(lifetime_j.name)));
token::get_name(lifetime_j.name)).as_slice());
}
}
}

View File

@ -112,14 +112,17 @@ impl<'a> TypeFolder for SubstFolder<'a> {
let root_msg = match self.root_ty {
Some(root) => format!(" in the substitution of `{}`",
root.repr(self.tcx)),
None => "".to_owned()
None => "".to_strbuf()
};
let m = format!("can't use type parameters from outer \
function{}; try using a local type \
parameter instead", root_msg);
parameter instead",
root_msg);
match self.span {
Some(span) => self.tcx.sess.span_err(span, m),
None => self.tcx.sess.err(m)
Some(span) => {
self.tcx.sess.span_err(span, m.as_slice())
}
None => self.tcx.sess.err(m.as_slice())
}
ty::mk_err()
}
@ -131,12 +134,15 @@ impl<'a> TypeFolder for SubstFolder<'a> {
let root_msg = match self.root_ty {
Some(root) => format!(" in the substitution of `{}`",
root.repr(self.tcx)),
None => "".to_owned()
None => "".to_strbuf()
};
let m = format!("missing `Self` type param{}", root_msg);
let m = format!("missing `Self` type param{}",
root_msg);
match self.span {
Some(span) => self.tcx.sess.span_err(span, m),
None => self.tcx.sess.err(m)
Some(span) => {
self.tcx.sess.span_err(span, m.as_slice())
}
None => self.tcx.sess.err(m.as_slice())
}
ty::mk_err()
}

View File

@ -462,7 +462,7 @@ fn assert_is_binding_or_wild(bcx: &Block, p: @ast::Pat) {
bcx.sess().span_bug(
p.span,
format!("expected an identifier pattern but found p: {}",
p.repr(bcx.tcx())));
p.repr(bcx.tcx())).as_slice());
}
}
@ -1229,8 +1229,10 @@ fn compare_values<'a>(
rhs: ValueRef,
rhs_t: ty::t)
-> Result<'a> {
let did = langcall(cx, None,
format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
let did = langcall(cx,
None,
format!("comparison of `{}`",
cx.ty_to_str(rhs_t)).as_slice(),
StrEqFnLangItem);
let result = callee::trans_lang_call(cx, did, [lhs, rhs], None);
Result {
@ -1252,8 +1254,10 @@ fn compare_values<'a>(
Store(cx, lhs, scratch_lhs);
let scratch_rhs = alloca(cx, val_ty(rhs), "__rhs");
Store(cx, rhs, scratch_rhs);
let did = langcall(cx, None,
format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
let did = langcall(cx,
None,
format!("comparison of `{}`",
cx.ty_to_str(rhs_t)).as_slice(),
UniqStrEqFnLangItem);
let result = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], None);
Result {
@ -2154,7 +2158,7 @@ fn bind_irrefutable_pat<'a>(
if bcx.sess().asm_comments() {
add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
pat.repr(bcx.tcx())));
pat.repr(bcx.tcx())).as_slice());
}
let _indenter = indenter();
@ -2273,7 +2277,7 @@ fn bind_irrefutable_pat<'a>(
}
ast::PatVec(..) => {
bcx.sess().span_bug(pat.span,
format!("vector patterns are never irrefutable!"));
"vector patterns are never irrefutable!");
}
ast::PatWild | ast::PatWildMulti | ast::PatLit(_) | ast::PatRange(_, _) => ()
}

View File

@ -192,7 +192,8 @@ fn represent_type_uncached(cx: &CrateContext, t: ty::t) -> Repr {
if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
cx.sess().bug(format!("non-C-like enum {} with specified \
discriminants",
ty::item_path_str(cx.tcx(), def_id)))
ty::item_path_str(cx.tcx(),
def_id)).as_slice())
}
if cases.len() == 1 {

View File

@ -67,7 +67,8 @@ pub fn trans_inline_asm<'a>(bcx: &'a Block<'a>, ia: &ast::InlineAsm)
StrBuf::from_str(constraints.iter()
.map(|s| s.get().to_strbuf())
.collect::<Vec<StrBuf>>()
.connect(","));
.connect(",")
.as_slice());
let mut clobbers = getClobbers();
if !ia.clobbers.get().is_empty() && !clobbers.is_empty() {

View File

@ -341,7 +341,8 @@ fn require_alloc_fn(bcx: &Block, info_ty: ty::t, it: LangItem) -> ast::DefId {
Ok(id) => id,
Err(s) => {
bcx.sess().fatal(format!("allocation of `{}` {}",
bcx.ty_to_str(info_ty), s));
bcx.ty_to_str(info_ty),
s).as_slice());
}
}
}
@ -476,7 +477,7 @@ pub fn unset_split_stack(f: ValueRef) {
// silently mangles such symbols, breaking our linkage model.
pub fn note_unique_llvm_symbol(ccx: &CrateContext, sym: StrBuf) {
if ccx.all_llvm_symbols.borrow().contains(&sym) {
ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym));
ccx.sess().bug(format!("duplicate LLVM symbol: {}", sym).as_slice());
}
ccx.all_llvm_symbols.borrow_mut().insert(sym);
}
@ -739,8 +740,11 @@ pub fn iter_structural_ty<'r,
for variant in (*variants).iter() {
let variant_cx =
fcx.new_temp_block("enum-iter-variant-".to_owned() +
variant.disr_val.to_str());
fcx.new_temp_block(
format_strbuf!("enum-iter-variant-{}",
variant.disr_val
.to_str()
.as_slice()).as_slice());
match adt::trans_case(cx, &*repr, variant.disr_val) {
_match::single_result(r) => {
AddCase(llswitch, r.val, variant_cx.llbb)
@ -839,7 +843,7 @@ pub fn fail_if_zero<'a>(
}
_ => {
cx.sess().bug(format!("fail-if-zero on unexpected type: {}",
ty_to_str(cx.tcx(), rhs_t)));
ty_to_str(cx.tcx(), rhs_t)).as_slice());
}
};
with_cond(cx, is_zero, |bcx| {
@ -1503,8 +1507,8 @@ fn trans_enum_variant_or_tuple_like_struct(ccx: &CrateContext,
ty::ty_bare_fn(ref bft) => bft.sig.output,
_ => ccx.sess().bug(
format!("trans_enum_variant_or_tuple_like_struct: \
unexpected ctor return type {}",
ty_to_str(ccx.tcx(), ctor_ty)))
unexpected ctor return type {}",
ty_to_str(ccx.tcx(), ctor_ty)).as_slice())
};
let arena = TypedArena::new();
@ -2052,7 +2056,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
ref variant => {
ccx.sess().bug(format!("get_item_val(): unexpected variant: {:?}",
variant))
variant).as_slice())
}
};
@ -2116,7 +2120,9 @@ pub fn write_metadata(cx: &CrateContext, krate: &ast::Crate) -> Vec<u8> {
let compressed = Vec::from_slice(encoder::metadata_encoding_version)
.append(match flate::deflate_bytes(metadata.as_slice()) {
Some(compressed) => compressed,
None => cx.sess().fatal(format!("failed to compress metadata"))
None => {
cx.sess().fatal("failed to compress metadata")
}
}.as_slice());
let llmeta = C_bytes(cx, compressed.as_slice());
let llconst = C_struct(cx, [llmeta], false);

View File

@ -750,9 +750,11 @@ impl<'a> Builder<'a> {
pub fn add_span_comment(&self, sp: Span, text: &str) {
if self.ccx.sess().asm_comments() {
let s = format!("{} ({})", text, self.ccx.sess().codemap().span_to_str(sp));
debug!("{}", s);
self.add_comment(s);
let s = format!("{} ({})",
text,
self.ccx.sess().codemap().span_to_str(sp));
debug!("{}", s.as_slice());
self.add_comment(s.as_slice());
}
}
@ -761,7 +763,7 @@ impl<'a> Builder<'a> {
let sanitized = text.replace("$", "");
let comment_text = format!("\\# {}", sanitized.replace("\n", "\n\t# "));
self.count_insn("inlineasm");
let asm = comment_text.with_c_str(|c| {
let asm = comment_text.as_slice().with_c_str(|c| {
unsafe {
llvm::LLVMConstInlineAsm(Type::func([], &Type::void(self.ccx)).to_ref(),
c, noname(), False, False)

View File

@ -102,8 +102,9 @@ fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("type of callee is neither bare-fn nor closure: {}",
bcx.ty_to_str(datum.ty)));
format!("type of callee is neither bare-fn nor closure: \
{}",
bcx.ty_to_str(datum.ty)).as_slice());
}
}
}
@ -151,7 +152,7 @@ fn trans<'a>(bcx: &'a Block<'a>, expr: &ast::Expr) -> Callee<'a> {
bcx.tcx().sess.span_bug(
ref_expr.span,
format!("cannot translate def {:?} \
to a callable thing!", def));
to a callable thing!", def).as_slice());
}
}
}

View File

@ -329,7 +329,7 @@ impl<'a> CleanupMethods<'a> for FunctionContext<'a> {
self.ccx.sess().bug(
format!("no cleanup scope {} found",
self.ccx.tcx.map.node_to_str(cleanup_scope)));
self.ccx.tcx.map.node_to_str(cleanup_scope)).as_slice());
}
fn schedule_clean_in_custom_scope(&self,
@ -531,7 +531,7 @@ impl<'a> CleanupHelperMethods<'a> for FunctionContext<'a> {
LoopExit(id, _) => {
self.ccx.sess().bug(format!(
"cannot exit from scope {:?}, \
not in scope", id));
not in scope", id).as_slice());
}
}
}
@ -878,7 +878,8 @@ pub fn temporary_scope(tcx: &ty::ctxt,
r
}
None => {
tcx.sess.bug(format!("no temporary scope available for expr {}", id))
tcx.sess.bug(format!("no temporary scope available for expr {}",
id).as_slice())
}
}
}

View File

@ -205,7 +205,7 @@ pub fn store_environment<'a>(
if ccx.sess().asm_comments() {
add_comment(bcx, format!("Copy {} into closure",
bv.to_str(ccx)));
bv.to_str(ccx)).as_slice());
}
let bound_data = GEPi(bcx, llbox, [0u, abi::box_field_body, i]);
@ -386,8 +386,9 @@ pub fn get_wrapper_for_bare_fn(ccx: &CrateContext,
ast::DefVariant(_, did, _) | ast::DefStruct(did) => did,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a statically resolved fn, got {:?}",
def));
expected a statically resolved fn, got \
{:?}",
def).as_slice());
}
};
@ -405,7 +406,7 @@ pub fn get_wrapper_for_bare_fn(ccx: &CrateContext,
_ => {
ccx.sess().bug(format!("get_wrapper_for_bare_fn: \
expected a closure ty, got {}",
closure_ty.repr(tcx)));
closure_ty.repr(tcx)).as_slice());
}
};

View File

@ -108,7 +108,7 @@ pub fn gensym_name(name: &str) -> PathElem {
let num = token::gensym(name);
// 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)))
PathName(token::gensym(format!("{}:{}", name, num).as_slice()))
}
pub struct tydesc_info {
@ -459,7 +459,7 @@ impl<'a> Block<'a> {
Some(&v) => v,
None => {
self.tcx().sess.bug(format!(
"no def associated with node id {:?}", nid));
"no def associated with node id {:?}", nid).as_slice());
}
}
}
@ -747,9 +747,10 @@ pub fn node_id_substs(bcx: &Block,
if !substs.tps.iter().all(|t| !ty::type_needs_infer(*t)) {
bcx.sess().bug(
format!("type parameters for node {:?} include inference types: {}",
format!("type parameters for node {:?} include inference types: \
{}",
node,
substs.repr(bcx.tcx())));
substs.repr(bcx.tcx())).as_slice());
}
substs.substp(tcx, bcx.fcx.param_substs)
@ -816,7 +817,7 @@ pub fn resolve_vtable_under_param_substs(tcx: &ty::ctxt,
_ => {
tcx.sess.bug(format!(
"resolve_vtable_under_param_substs: asked to lookup \
but no vtables in the fn_ctxt!"))
but no vtables in the fn_ctxt!").as_slice())
}
}
}
@ -870,8 +871,8 @@ pub fn langcall(bcx: &Block,
Err(s) => {
let msg = format!("{} {}", msg, s);
match span {
Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
None => { bcx.tcx().sess.fatal(msg); }
Some(span) => bcx.tcx().sess.span_fatal(span, msg.as_slice()),
None => bcx.tcx().sess.fatal(msg.as_slice()),
}
}
}

View File

@ -55,8 +55,9 @@ pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: ast::Lit)
C_integral(Type::uint_from_ty(cx, t), i as u64, false)
}
_ => cx.sess().span_bug(lit.span,
format!("integer literal has type {} (expected int or uint)",
ty_to_str(cx.tcx(), lit_int_ty)))
format!("integer literal has type {} (expected int \
or uint)",
ty_to_str(cx.tcx(), lit_int_ty)).as_slice())
}
}
ast::LitFloat(ref fs, t) => {
@ -150,14 +151,14 @@ fn const_deref(cx: &CrateContext, v: ValueRef, t: ty::t, explicit: bool)
}
_ => {
cx.sess().bug(format!("unexpected dereferenceable type {}",
ty_to_str(cx.tcx(), t)))
ty_to_str(cx.tcx(), t)).as_slice())
}
};
(dv, mt.ty)
}
None => {
cx.sess().bug(format!("can't dereference const of type {}",
ty_to_str(cx.tcx(), t)))
ty_to_str(cx.tcx(), t)).as_slice())
}
}
}
@ -206,7 +207,7 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
cx.sess()
.span_bug(e.span,
format!("unexpected static function: {:?}",
store))
store).as_slice())
}
ty::AutoObject(..) => {
cx.sess()
@ -256,11 +257,11 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
}
}
_ => {
cx.sess().span_bug(e.span,
format!("unimplemented \
const autoref \
{:?}",
autoref))
cx.sess()
.span_bug(e.span,
format!("unimplemented const \
autoref {:?}",
autoref).as_slice())
}
}
}
@ -281,7 +282,7 @@ pub fn const_expr(cx: &CrateContext, e: &ast::Expr, is_local: bool) -> (ValueRef
}
cx.sess().bug(format!("const {} of type {} has size {} instead of {}",
e.repr(cx.tcx()), ty_to_str(cx.tcx(), ety),
csize, tsize));
csize, tsize).as_slice());
}
(llconst, inlineable)
}

View File

@ -165,7 +165,7 @@ pub fn trans_if<'a>(bcx: &'a Block<'a>,
}
let name = format!("then-block-{}-", thn.id);
let then_bcx_in = bcx.fcx.new_id_block(name, thn.id);
let then_bcx_in = bcx.fcx.new_id_block(name.as_slice(), thn.id);
let then_bcx_out = trans_block(then_bcx_in, thn, dest);
debuginfo::clear_source_location(bcx.fcx);
@ -287,7 +287,8 @@ pub fn trans_break_cont<'a>(bcx: &'a Block<'a>,
match bcx.tcx().def_map.borrow().find(&expr_id) {
Some(&ast::DefLabel(loop_id)) => loop_id,
ref r => {
bcx.tcx().sess.bug(format!("{:?} in def-map for label", r))
bcx.tcx().sess.bug(format!("{:?} in def-map for label",
r).as_slice())
}
}
}

View File

@ -317,16 +317,21 @@ pub fn create_global_var_metadata(cx: &CrateContext,
ast_map::NodeItem(item) => {
match item.node {
ast::ItemStatic(..) => (item.ident, item.span),
_ => cx.sess().span_bug(item.span,
format!("debuginfo::create_global_var_metadata() -
Captured var-id refers to unexpected ast_item
variant: {:?}",
var_item))
_ => {
cx.sess()
.span_bug(item.span,
format!("debuginfo::\
create_global_var_metadata() -
Captured var-id refers to \
unexpected ast_item variant: {:?}",
var_item).as_slice())
}
}
},
_ => cx.sess().bug(format!("debuginfo::create_global_var_metadata() - Captured var-id \
refers to unexpected ast_map variant: {:?}",
var_item))
_ => cx.sess().bug(format!("debuginfo::create_global_var_metadata() \
- Captured var-id refers to unexpected \
ast_map variant: {:?}",
var_item).as_slice())
};
let filename = span_start(cx, span).file.name.clone();
@ -340,7 +345,8 @@ pub fn create_global_var_metadata(cx: &CrateContext,
let namespace_node = namespace_for_item(cx, ast_util::local_def(node_id));
let var_name = token::get_ident(ident).get().to_str();
let linkage_name = namespace_node.mangled_name_of_contained_item(var_name);
let linkage_name =
namespace_node.mangled_name_of_contained_item(var_name.as_slice());
let var_scope = namespace_node.scope;
var_name.as_slice().with_c_str(|var_name| {
@ -380,7 +386,7 @@ pub fn create_local_var_metadata(bcx: &Block, local: &ast::Local) {
None => {
bcx.sess().span_bug(span,
format!("no entry in lllocals table for {:?}",
node_id));
node_id).as_slice());
}
};
@ -430,13 +436,17 @@ pub fn create_captured_var_metadata(bcx: &Block,
"debuginfo::create_captured_var_metadata() - \
Captured var-id refers to unexpected \
ast_map variant: {:?}",
ast_item));
ast_item).as_slice());
}
}
}
_ => {
cx.sess().span_bug(span, format!("debuginfo::create_captured_var_metadata() - \
Captured var-id refers to unexpected ast_map variant: {:?}", ast_item));
cx.sess()
.span_bug(span,
format!("debuginfo::create_captured_var_metadata() - \
Captured var-id refers to unexpected \
ast_map variant: {:?}",
ast_item).as_slice());
}
};
@ -519,7 +529,7 @@ pub fn create_argument_metadata(bcx: &Block, arg: &ast::Arg) {
None => {
bcx.sess().span_bug(span,
format!("no entry in llargs table for {:?}",
node_id));
node_id).as_slice());
}
};
@ -653,7 +663,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
ast::ExprFnBlock(fn_decl, top_level_block) |
ast::ExprProc(fn_decl, top_level_block) => {
let name = format!("fn{}", token::gensym("fn"));
let name = token::str_to_ident(name);
let name = token::str_to_ident(name.as_slice());
(name, fn_decl,
// This is not quite right. It should actually inherit the generics of the
// enclosing function.
@ -681,7 +691,7 @@ pub fn create_function_debug_context(cx: &CrateContext,
cx.sess()
.bug(format!("create_function_debug_context: \
unexpected sort of node: {:?}",
fnitem))
fnitem).as_slice())
}
}
}
@ -691,7 +701,8 @@ pub fn create_function_debug_context(cx: &CrateContext,
return FunctionDebugContext { repr: FunctionWithoutDebugInfo };
}
_ => cx.sess().bug(format!("create_function_debug_context: \
unexpected sort of node: {:?}", fnitem))
unexpected sort of node: {:?}",
fnitem).as_slice())
};
// This can be the case for functions inlined from another crate
@ -1124,7 +1135,8 @@ fn scope_metadata(fcx: &FunctionContext,
let node = fcx.ccx.tcx.map.get(node_id);
fcx.ccx.sess().span_bug(span,
format!("debuginfo: Could not find scope info for node {:?}", node));
format!("debuginfo: Could not find scope info for node {:?}",
node).as_slice());
}
}
}
@ -1499,14 +1511,17 @@ fn describe_enum_variant(cx: &CrateContext,
// Get the argument names from the enum variant info
let mut arg_names: Vec<_> = match variant_info.arg_names {
Some(ref names) => {
names.iter().map(|ident| token::get_ident(*ident).get().to_str()).collect()
names.iter()
.map(|ident| {
token::get_ident(*ident).get().to_str().into_strbuf()
}).collect()
}
None => variant_info.args.iter().map(|_| "".to_owned()).collect()
None => variant_info.args.iter().map(|_| "".to_strbuf()).collect()
};
// If this is not a univariant enum, there is also the (unnamed) discriminant field
if discriminant_type_metadata.is_some() {
arg_names.insert(0, "".to_owned());
arg_names.insert(0, "".to_strbuf());
}
// Build an array of (field name, field type) pairs to be captured in the factory closure.
@ -1861,7 +1876,7 @@ fn boxed_type_metadata(cx: &CrateContext,
-> DICompositeType {
let box_type_name = match content_type_name {
Some(content_type_name) => format!("Boxed<{}>", content_type_name),
None => "BoxedType".to_owned()
None => "BoxedType".to_strbuf()
};
let box_llvm_type = Type::at_box(cx, content_llvm_type);
@ -1913,7 +1928,7 @@ fn boxed_type_metadata(cx: &CrateContext,
return composite_type_metadata(
cx,
box_llvm_type,
box_type_name,
box_type_name.as_slice(),
member_descriptions,
file_metadata,
file_metadata,
@ -1971,7 +1986,9 @@ fn vec_metadata(cx: &CrateContext,
let (element_size, element_align) = size_and_align_of(cx, element_llvm_type);
let vec_llvm_type = Type::vec(cx, &element_llvm_type);
let vec_type_name: &str = format!("[{}]", ppaux::ty_to_str(cx.tcx(), element_type));
let vec_type_name = format!("[{}]",
ppaux::ty_to_str(cx.tcx(), element_type));
let vec_type_name = vec_type_name.as_slice();
let member_llvm_types = vec_llvm_type.field_types();
@ -2254,7 +2271,11 @@ fn type_metadata(cx: &CrateContext,
elements.as_slice(),
usage_site_span).finalize(cx)
}
_ => cx.sess().bug(format!("debuginfo: unexpected type in type_metadata: {:?}", sty))
_ => {
cx.sess().bug(format!("debuginfo: unexpected type in \
type_metadata: {:?}",
sty).as_slice())
}
};
debug_context(cx).created_types.borrow_mut().insert(cache_id, type_metadata);
@ -2852,13 +2873,13 @@ impl NamespaceTreeNode {
None => {}
}
let string = token::get_name(node.name);
output.push_str(format!("{}", string.get().len()));
output.push_str(format!("{}", string.get().len()).as_slice());
output.push_str(string.get());
}
let mut name = StrBuf::from_str("_ZN");
fill_nested(self, &mut name);
name.push_str(format!("{}", item_name.len()));
name.push_str(format!("{}", item_name.len()).as_slice());
name.push_str(item_name);
name.push_char('E');
name
@ -2941,7 +2962,8 @@ fn namespace_for_item(cx: &CrateContext, def_id: ast::DefId) -> Rc<NamespaceTree
Some(node) => node,
None => {
cx.sess().bug(format!("debuginfo::namespace_for_item(): \
path too short for {:?}", def_id));
path too short for {:?}",
def_id).as_slice());
}
}
})

View File

@ -421,8 +421,8 @@ fn trans_datum_unadjusted<'a>(bcx: &'a Block<'a>,
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_rvalue_datum_unadjusted reached \
fall-through case: {:?}",
expr.node));
fall-through case: {:?}",
expr.node).as_slice());
}
}
}
@ -635,8 +635,8 @@ fn trans_rvalue_stmt_unadjusted<'a>(bcx: &'a Block<'a>,
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_rvalue_stmt_unadjusted reached \
fall-through case: {:?}",
expr.node));
fall-through case: {:?}",
expr.node).as_slice());
}
}
}
@ -765,8 +765,9 @@ fn trans_rvalue_dps_unadjusted<'a>(bcx: &'a Block<'a>,
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_rvalue_dps_unadjusted reached fall-through case: {:?}",
expr.node));
format!("trans_rvalue_dps_unadjusted reached fall-through \
case: {:?}",
expr.node).as_slice());
}
}
}
@ -815,7 +816,7 @@ fn trans_def_dps_unadjusted<'a>(
_ => {
bcx.tcx().sess.span_bug(ref_expr.span, format!(
"Non-DPS def {:?} referened by {}",
def, bcx.node_id_to_str(ref_expr.id)));
def, bcx.node_id_to_str(ref_expr.id)).as_slice());
}
}
}
@ -839,7 +840,7 @@ fn trans_def_fn_unadjusted<'a>(bcx: &'a Block<'a>,
bcx.tcx().sess.span_bug(ref_expr.span, format!(
"trans_def_fn_unadjusted invoked on: {:?} for {}",
def,
ref_expr.repr(bcx.tcx())));
ref_expr.repr(bcx.tcx())).as_slice());
}
};
@ -865,7 +866,8 @@ pub fn trans_local_var<'a>(bcx: &'a Block<'a>,
Some(&val) => Datum(val, local_ty, Lvalue),
None => {
bcx.sess().bug(format!(
"trans_local_var: no llval for upvar {:?} found", nid));
"trans_local_var: no llval for upvar {:?} found",
nid).as_slice());
}
}
}
@ -877,7 +879,8 @@ pub fn trans_local_var<'a>(bcx: &'a Block<'a>,
}
_ => {
bcx.sess().unimpl(format!(
"unsupported def type in trans_local_var: {:?}", def));
"unsupported def type in trans_local_var: {:?}",
def).as_slice());
}
};
@ -889,7 +892,8 @@ pub fn trans_local_var<'a>(bcx: &'a Block<'a>,
Some(&v) => v,
None => {
bcx.sess().bug(format!(
"trans_local_var: no datum for local/arg {:?} found", nid));
"trans_local_var: no datum for local/arg {:?} found",
nid).as_slice());
}
};
debug!("take_local(nid={:?}, v={}, ty={})",
@ -922,7 +926,7 @@ pub fn with_field_tys<R>(tcx: &ty::ctxt,
tcx.sess.bug(format!(
"cannot get field types from the enum type {} \
without a node ID",
ty.repr(tcx)));
ty.repr(tcx)).as_slice());
}
Some(node_id) => {
let def = tcx.def_map.borrow().get_copy(&node_id);
@ -947,7 +951,7 @@ pub fn with_field_tys<R>(tcx: &ty::ctxt,
_ => {
tcx.sess.bug(format!(
"cannot get field types from the type {}",
ty.repr(tcx)));
ty.repr(tcx)).as_slice());
}
}
}
@ -1586,16 +1590,22 @@ fn trans_imm_cast<'a>(bcx: &'a Block<'a>,
val_ty(lldiscrim_a),
lldiscrim_a, true),
cast_float => SIToFP(bcx, lldiscrim_a, ll_t_out),
_ => ccx.sess().bug(format!("translating unsupported cast: \
_ => {
ccx.sess().bug(format!("translating unsupported cast: \
{} ({:?}) -> {} ({:?})",
t_in.repr(bcx.tcx()), k_in,
t_out.repr(bcx.tcx()), k_out))
t_in.repr(bcx.tcx()),
k_in,
t_out.repr(bcx.tcx()),
k_out).as_slice())
}
}
}
_ => ccx.sess().bug(format!("translating unsupported cast: \
{} ({:?}) -> {} ({:?})",
t_in.repr(bcx.tcx()), k_in,
t_out.repr(bcx.tcx()), k_out))
t_in.repr(bcx.tcx()),
k_in,
t_out.repr(bcx.tcx()),
k_out).as_slice())
};
return immediate_rvalue_bcx(bcx, newval, t_out).to_expr_datumblock();
}
@ -1757,7 +1767,7 @@ fn deref_once<'a>(bcx: &'a Block<'a>,
bcx.tcx().sess.span_bug(
expr.span,
format!("deref invoked on expr of illegal type {}",
datum.ty.repr(bcx.tcx())));
datum.ty.repr(bcx.tcx())).as_slice());
}
};

View File

@ -81,13 +81,12 @@ pub fn llvm_calling_convention(ccx: &CrateContext,
match abi {
RustIntrinsic => {
// Intrinsics are emitted by monomorphic fn
ccx.sess().bug(format!("asked to register intrinsic fn"));
ccx.sess().bug("asked to register intrinsic fn");
}
Rust => {
// FIXME(#3678) Implement linking to foreign fns with Rust ABI
ccx.sess().unimpl(
format!("foreign functions with Rust ABI"));
ccx.sess().unimpl("foreign functions with Rust ABI");
}
// It's the ABI's job to select this, not us.
@ -164,7 +163,8 @@ pub fn register_static(ccx: &CrateContext,
});
lib::llvm::SetLinkage(g1, linkage);
let real_name = "_rust_extern_with_linkage_" + ident.get();
let mut real_name = "_rust_extern_with_linkage_".to_strbuf();
real_name.push_str(ident.get());
let g2 = real_name.with_c_str(|buf| {
llvm::LLVMAddGlobal(ccx.llmod, llty.to_ref(), buf)
});
@ -202,14 +202,14 @@ pub fn register_foreign_item_fn(ccx: &CrateContext, abi: Abi, fty: ty::t,
Some(s) => {
ccx.sess().span_fatal(s,
format!("ABI `{}` has no suitable calling convention \
for target architecture",
abi.user_string(ccx.tcx())))
for target architecture",
abi.user_string(ccx.tcx())).as_slice())
}
None => {
ccx.sess().fatal(
format!("ABI `{}` has no suitable calling convention \
for target architecture",
abi.user_string(ccx.tcx())))
for target architecture",
abi.user_string(ccx.tcx())).as_slice())
}
}
}
@ -370,8 +370,8 @@ pub fn trans_native_call<'a>(
// FIXME(#8357) We really ought to report a span here
ccx.sess().fatal(
format!("ABI string `{}` has no suitable ABI \
for target architecture",
fn_abi.user_string(ccx.tcx())));
for target architecture",
fn_abi.user_string(ccx.tcx())).as_slice());
}
};
@ -555,9 +555,9 @@ pub fn trans_rust_fn_with_foreign_abi(ccx: &CrateContext,
}
_ => {
ccx.sess().bug(format!("build_rust_fn: extern fn {} has ty {}, \
expected a bare fn ty",
expected a bare fn ty",
ccx.tcx.map.path_to_str(id),
t.repr(tcx)));
t.repr(tcx)).as_slice());
}
};

View File

@ -454,7 +454,10 @@ pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> tydesc_info {
fn declare_generic_glue(ccx: &CrateContext, t: ty::t, llfnty: Type,
name: &str) -> ValueRef {
let _icx = push_ctxt("declare_generic_glue");
let fn_nm = mangle_internal_name_by_type_and_seq(ccx, t, "glue_".to_owned() + name);
let fn_nm = mangle_internal_name_by_type_and_seq(
ccx,
t,
format!("glue_{}", name).as_slice());
debug!("{} is for type {}", fn_nm, ppaux::ty_to_str(ccx.tcx(), t));
let llfn = decl_cdecl_fn(ccx.llmod,
fn_nm.as_slice(),

View File

@ -396,7 +396,7 @@ pub fn trans_intrinsic(ccx: &CrateContext,
intype = ty_to_str(ccx.tcx(), in_type),
insize = in_type_size as uint,
outtype = ty_to_str(ccx.tcx(), out_type),
outsize = out_type_size as uint));
outsize = out_type_size as uint).as_slice());
}
if !return_type_is_void(ccx, out_type) {

View File

@ -205,7 +205,8 @@ pub fn monomorphic_fn(ccx: &CrateContext,
hash_id.hash(&mut state);
mono_ty.hash(&mut state);
exported_name(path, format!("h{}", state.result()),
exported_name(path,
format!("h{}", state.result()).as_slice(),
ccx.link_meta.crateid.version_or_default())
});
debug!("monomorphize_fn mangled to {}", s);
@ -287,7 +288,7 @@ pub fn monomorphic_fn(ccx: &CrateContext,
}
_ => {
ccx.sess().bug(format!("can't monomorphize a {:?}",
map_node))
map_node).as_slice())
}
}
}
@ -311,7 +312,8 @@ pub fn monomorphic_fn(ccx: &CrateContext,
ast_map::NodeBlock(..) |
ast_map::NodePat(..) |
ast_map::NodeLocal(..) => {
ccx.sess().bug(format!("can't monomorphize a {:?}", map_node))
ccx.sess().bug(format!("can't monomorphize a {:?}",
map_node).as_slice())
}
};

View File

@ -87,7 +87,8 @@ impl<'a, 'b> Reflector<'a, 'b> {
pub fn visit(&mut self, ty_name: &str, args: &[ValueRef]) {
let fcx = self.bcx.fcx;
let tcx = self.bcx.tcx();
let mth_idx = ty::method_idx(token::str_to_ident("visit_".to_owned() + ty_name),
let mth_idx = ty::method_idx(token::str_to_ident(format!(
"visit_{}", ty_name).as_slice()),
self.visitor_methods.as_slice()).expect(
format!("couldn't find visit method for {}", ty_name));
let mth_ty =
@ -116,9 +117,9 @@ impl<'a, 'b> Reflector<'a, 'b> {
bracket_name: &str,
extra: &[ValueRef],
inner: |&mut Reflector|) {
self.visit("enter_" + bracket_name, extra);
self.visit(format!("enter_{}", bracket_name).as_slice(), extra);
inner(self);
self.visit("leave_" + bracket_name, extra);
self.visit(format!("leave_{}", bracket_name).as_slice(), extra);
}
pub fn leaf(&mut self, name: &str) {
@ -154,7 +155,7 @@ impl<'a, 'b> Reflector<'a, 'b> {
ty::ty_vec(ref mt, Some(sz)) => {
let extra = (vec!(self.c_uint(sz))).append(self.c_size_and_align(t).as_slice());
let extra = extra.append(self.c_mt(mt).as_slice());
self.visit("evec_fixed".to_owned(), extra.as_slice())
self.visit("evec_fixed", extra.as_slice())
}
ty::ty_vec(..) | ty::ty_str => fail!("unexpected unsized type"),
// Should remove mt from box and uniq.
@ -170,9 +171,9 @@ impl<'a, 'b> Reflector<'a, 'b> {
ty::ty_vec(ref mt, None) => {
let extra = Vec::new();
let extra = extra.append(self.c_mt(mt).as_slice());
self.visit("evec_uniq".to_owned(), extra.as_slice())
self.visit("evec_uniq", extra.as_slice())
}
ty::ty_str => self.visit("estr_uniq".to_owned(), &[]),
ty::ty_str => self.visit("estr_uniq", &[]),
_ => {
let extra = self.c_mt(&ty::mt {
ty: typ,
@ -191,9 +192,10 @@ impl<'a, 'b> Reflector<'a, 'b> {
ty::ty_vec(ref mt, None) => {
let (name, extra) = ("slice".to_owned(), Vec::new());
let extra = extra.append(self.c_mt(mt).as_slice());
self.visit("evec_".to_owned() + name, extra.as_slice())
self.visit(format!("evec_{}", name).as_slice(),
extra.as_slice())
}
ty::ty_str => self.visit("estr_slice".to_owned(), &[]),
ty::ty_str => self.visit("estr_slice", &[]),
_ => {
let extra = self.c_mt(mt);
self.visit("rptr", extra.as_slice())

View File

@ -155,7 +155,7 @@ pub fn sizing_type_of(cx: &CrateContext, t: ty::t) -> Type {
ty::ty_self(_) | ty::ty_infer(..) | ty::ty_param(..) |
ty::ty_err(..) | ty::ty_vec(_, None) | ty::ty_str => {
cx.sess().bug(format!("fictitious type {:?} in sizing_type_of()",
ty::get(t).sty))
ty::get(t).sty).as_slice())
}
};

View File

@ -2620,7 +2620,7 @@ pub fn node_id_to_trait_ref(cx: &ctxt, id: ast::NodeId) -> Rc<ty::TraitRef> {
Some(t) => t.clone(),
None => cx.sess.bug(
format!("node_id_to_trait_ref: no trait ref for node `{}`",
cx.map.node_to_str(id)))
cx.map.node_to_str(id)).as_slice())
}
}
@ -2633,7 +2633,7 @@ pub fn node_id_to_type(cx: &ctxt, id: ast::NodeId) -> t {
Some(t) => t,
None => cx.sess.bug(
format!("node_id_to_type: no type for node `{}`",
cx.map.node_to_str(id)))
cx.map.node_to_str(id)).as_slice())
}
}
@ -2717,7 +2717,8 @@ pub fn ty_region(tcx: &ctxt,
ref s => {
tcx.sess.span_bug(
span,
format!("ty_region() invoked on in appropriate ty: {:?}", s));
format!("ty_region() invoked on in appropriate ty: {:?}",
s).as_slice());
}
}
}
@ -2774,11 +2775,12 @@ pub fn expr_span(cx: &ctxt, id: NodeId) -> Span {
}
Some(f) => {
cx.sess.bug(format!("Node id {} is not an expr: {:?}",
id, f));
id,
f).as_slice());
}
None => {
cx.sess.bug(format!("Node id {} is not present \
in the node map", id));
in the node map", id).as_slice());
}
}
}
@ -2793,14 +2795,15 @@ pub fn local_var_name_str(cx: &ctxt, id: NodeId) -> InternedString {
_ => {
cx.sess.bug(
format!("Variable id {} maps to {:?}, not local",
id, pat));
id,
pat).as_slice());
}
}
}
r => {
cx.sess.bug(
format!("Variable id {} maps to {:?}, not local",
id, r));
cx.sess.bug(format!("Variable id {} maps to {:?}, not local",
id,
r).as_slice());
}
}
}
@ -2832,7 +2835,7 @@ pub fn adjust_ty(cx: &ctxt,
cx.sess.bug(
format!("add_env adjustment on non-bare-fn: \
{:?}",
b));
b).as_slice());
}
}
}
@ -2857,7 +2860,8 @@ pub fn adjust_ty(cx: &ctxt,
format!("the {}th autoderef failed: \
{}",
i,
ty_to_str(cx, adjusted_ty)));
ty_to_str(cx, adjusted_ty))
.as_slice());
}
}
}
@ -2923,7 +2927,8 @@ pub fn adjust_ty(cx: &ctxt,
_ => {
cx.sess.span_bug(
span,
format!("borrow-vec associated with bad sty: {:?}", get(ty).sty));
format!("borrow-vec associated with bad sty: {:?}",
get(ty).sty).as_slice());
}
},
ty_vec(mt, Some(_)) => ty::mk_slice(cx, r, ty::mt {ty: mt.ty, mutbl: m}),
@ -2931,7 +2936,8 @@ pub fn adjust_ty(cx: &ctxt,
ref s => {
cx.sess.span_bug(
span,
format!("borrow-vec associated with bad sty: {:?}", s));
format!("borrow-vec associated with bad sty: {:?}",
s).as_slice());
}
}
}
@ -2947,7 +2953,7 @@ pub fn adjust_ty(cx: &ctxt,
cx.sess.span_bug(
span,
format!("borrow-trait-obj associated with bad sty: {:?}",
s));
s).as_slice());
}
}
}
@ -2996,7 +3002,7 @@ pub fn resolve_expr(tcx: &ctxt, expr: &ast::Expr) -> ast::Def {
Some(&def) => def,
None => {
tcx.sess.span_bug(expr.span, format!(
"no def-map entry for expr {:?}", expr.id));
"no def-map entry for expr {:?}", expr.id).as_slice());
}
}
}
@ -3070,9 +3076,11 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
ast::DefLocal(..) => LvalueExpr,
def => {
tcx.sess.span_bug(expr.span, format!(
"uncategorized def for expr {:?}: {:?}",
expr.id, def));
tcx.sess.span_bug(
expr.span,
format!("uncategorized def for expr {:?}: {:?}",
expr.id,
def).as_slice());
}
}
}
@ -3193,7 +3201,7 @@ pub fn field_idx_strict(tcx: &ctxt, name: ast::Name, fields: &[field])
token::get_name(name),
fields.iter()
.map(|f| token::get_ident(f.ident).get().to_strbuf())
.collect::<Vec<StrBuf>>()));
.collect::<Vec<StrBuf>>()).as_slice());
}
pub fn method_idx(id: ast::Ident, meths: &[Rc<Method>]) -> Option<uint> {
@ -3444,10 +3452,18 @@ pub fn provided_trait_methods(cx: &ctxt, id: ast::DefId) -> Vec<Rc<Method>> {
let (_, p) = ast_util::split_trait_methods(ms.as_slice());
p.iter().map(|m| method(cx, ast_util::local_def(m.id))).collect()
}
_ => cx.sess.bug(format!("provided_trait_methods: `{}` is not a trait", id))
_ => {
cx.sess.bug(format!("provided_trait_methods: `{}` is \
not a trait",
id).as_slice())
}
}
}
_ => cx.sess.bug(format!("provided_trait_methods: `{}` is not a trait", id))
_ => {
cx.sess.bug(format!("provided_trait_methods: `{}` is not a \
trait",
id).as_slice())
}
}
} else {
csearch::get_provided_trait_methods(cx, id)
@ -3800,7 +3816,7 @@ pub fn enum_variants(cx: &ctxt, id: ast::DefId) -> Rc<Vec<Rc<VariantInfo>>> {
cx.sess
.span_err(e.span,
format!("expected constant: {}",
*err));
*err).as_slice());
}
},
None => {}
@ -3963,7 +3979,7 @@ fn each_super_struct(cx: &ctxt, mut did: ast::DefId, f: |ast::DefId|) {
None => {
cx.sess.bug(
format!("ID not mapped to super-struct: {}",
cx.map.node_to_str(did.node)));
cx.map.node_to_str(did.node)).as_slice());
}
}
}
@ -3985,7 +4001,7 @@ pub fn lookup_struct_fields(cx: &ctxt, did: ast::DefId) -> Vec<field_ty> {
_ => {
cx.sess.bug(
format!("ID not mapped to struct fields: {}",
cx.map.node_to_str(did.node)));
cx.map.node_to_str(did.node)).as_slice());
}
}
});

View File

@ -180,7 +180,7 @@ fn ast_path_substs<AC:AstConv,RS:RegionScope>(
format!("wrong number of lifetime parameters: \
expected {} but found {}",
expected_num_region_params,
supplied_num_region_params));
supplied_num_region_params).as_slice());
}
match anon_regions {
@ -204,7 +204,9 @@ fn ast_path_substs<AC:AstConv,RS:RegionScope>(
};
this.tcx().sess.span_fatal(path.span,
format!("wrong number of type arguments: {} {} but found {}",
expected, required_ty_param_count, supplied_ty_param_count));
expected,
required_ty_param_count,
supplied_ty_param_count).as_slice());
} else if supplied_ty_param_count > formal_ty_param_count {
let expected = if required_ty_param_count < formal_ty_param_count {
"expected at most"
@ -213,7 +215,9 @@ fn ast_path_substs<AC:AstConv,RS:RegionScope>(
};
this.tcx().sess.span_fatal(path.span,
format!("wrong number of type arguments: {} {} but found {}",
expected, formal_ty_param_count, supplied_ty_param_count));
expected,
formal_ty_param_count,
supplied_ty_param_count).as_slice());
}
if supplied_ty_param_count > required_ty_param_count
@ -317,8 +321,11 @@ pub fn ast_ty_to_prim_ty(tcx: &ty::ctxt, ast_ty: &ast::Ty) -> Option<ty::t> {
match ast_ty.node {
ast::TyPath(ref path, _, id) => {
let a_def = match tcx.def_map.borrow().find(&id) {
None => tcx.sess.span_bug(
ast_ty.span, format!("unbound path {}", path_to_str(path))),
None => {
tcx.sess.span_bug(ast_ty.span,
format!("unbound path {}",
path_to_str(path)).as_slice())
}
Some(&d) => d
};
match a_def {
@ -382,8 +389,13 @@ pub fn ast_ty_to_builtin_ty<AC:AstConv,
match ast_ty.node {
ast::TyPath(ref path, _, id) => {
let a_def = match this.tcx().def_map.borrow().find(&id) {
None => this.tcx().sess.span_bug(
ast_ty.span, format!("unbound path {}", path_to_str(path))),
None => {
this.tcx()
.sess
.span_bug(ast_ty.span,
format!("unbound path {}",
path_to_str(path)).as_slice())
}
Some(&d) => d
};
@ -493,8 +505,11 @@ fn mk_pointer<AC:AstConv,
RPtr(r) => {
return ty::mk_str_slice(tcx, r, ast::MutImmutable);
}
_ => tcx.sess.span_err(path.span,
format!("managed strings are not supported")),
_ => {
tcx.sess
.span_err(path.span,
"managed strings are not supported")
}
}
}
Some(&ast::DefTrait(trait_def_id)) => {
@ -635,8 +650,12 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
}
ast::TyPath(ref path, ref bounds, id) => {
let a_def = match tcx.def_map.borrow().find(&id) {
None => tcx.sess.span_bug(
ast_ty.span, format!("unbound path {}", path_to_str(path))),
None => {
tcx.sess
.span_bug(ast_ty.span,
format!("unbound path {}",
path_to_str(path)).as_slice())
}
Some(&d) => d
};
// Kind bounds on path types are only supported for traits.
@ -653,8 +672,10 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
let path_str = path_to_str(path);
tcx.sess.span_err(
ast_ty.span,
format!("reference to trait `{name}` where a type is expected; \
try `Box<{name}>` or `&{name}`", name=path_str));
format!("reference to trait `{name}` where a \
type is expected; try `Box<{name}>` or \
`&{name}`",
name=path_str).as_slice());
ty::mk_err()
}
ast::DefTy(did) | ast::DefStruct(did) => {
@ -675,14 +696,16 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
ast::DefMod(id) => {
tcx.sess.span_fatal(ast_ty.span,
format!("found module name used as a type: {}",
tcx.map.node_to_str(id.node)));
tcx.map.node_to_str(id.node)).as_slice());
}
ast::DefPrimTy(_) => {
fail!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
}
_ => {
tcx.sess.span_fatal(ast_ty.span,
format!("found value name used as a type: {:?}", a_def));
format!("found value name used \
as a type: {:?}",
a_def).as_slice());
}
}
}
@ -705,7 +728,9 @@ pub fn ast_ty_to_ty<AC:AstConv, RS:RegionScope>(
Err(ref r) => {
tcx.sess.span_fatal(
ast_ty.span,
format!("expected constant expr for vector length: {}", *r));
format!("expected constant expr for vector \
length: {}",
*r).as_slice());
}
}
}
@ -897,8 +922,8 @@ fn conv_builtin_bounds(tcx: &ty::ctxt, ast_bounds: &Option<OwnedSlice<ast::TyPar
}
tcx.sess.span_fatal(
b.path.span,
format!("only the builtin traits can be used \
as closure or object bounds"));
"only the builtin traits can be used as closure \
or object bounds");
}
ast::StaticRegionTyParamBound => {
builtin_bounds.add(ty::BoundStatic);
@ -907,8 +932,8 @@ fn conv_builtin_bounds(tcx: &ty::ctxt, ast_bounds: &Option<OwnedSlice<ast::TyPar
if !tcx.sess.features.issue_5723_bootstrap.get() {
tcx.sess.span_err(
span,
format!("only the 'static lifetime is \
accepted here."));
"only the 'static lifetime is accepted \
here.");
}
}
}

Some files were not shown because too many files have changed in this diff Show More